본문 바로가기
알고리즘

Alogrithm With Python

by 휴이7 2021. 1. 9.

# 짝수 홀수 구하기
def isOddEven(num):
    print(num )
    if (num % 2 == 0):
        retVal =  'even'
    else:
        retVal =  'odd'
    return retVal

result = isOddEven(121281817134343858590)
print(result)

 


# 좌표 평면 두점 사이의 거리를 구하는 알고리즘 
import math 

def getDistance(p1, p2):
    xDistance = p1[0] - p2[0]
    print(xDistance)
    yDistance = p1[1] - p2[1]
    print(yDistance)

    #피타고라스정리에 의해 
    pDistance = math.pow(xDistance,2) + math.pow(yDistance,2)

    return math.sqrt(pDistance)

p1 = (0, 2)
p2 = (3, 4)
print(getDistance(p1, p2))

 


# 40을 기준으로 오름차순으로 정렬하라 
numbers = [40, 35, 27, 50, 75, 74, 89, 22, 54 ]

def quickSort(array):
    if len(array) < 2:
        return array
    else:
        pivot = array[0]
        less = [number for number in array[1:] if number <= pivot]
        greater = [number for number in array[1:] if number > pivot]

        return quickSort(less) + [pivot] + quickSort(greater)

result = quickSort(numbers)
print(result)


 

#특정 위치 기준 없이 퀵정렬 
def quickSort2(arr):
    if len(arr) <= 1:
        return arr

    pivot = arr[len(arr)-1]
    less_arr, equal_arr, greater_arr = [], [], []
    for num in arr:
        if num < pivot:
            less_arr.append(num)
        elif num > pivot:
            greater_arr.append(num)
        else:
            equal_arr.append(num)

    return quickSort2(less_arr) + equal_arr + quickSort2(greater_arr)

result2 = quickSort2(numbers)
print(result2)

 


# 오름 차순 정렬
# 첫번째와 두번째를 비교해서 두번째것이 작으면 자리를 바꾼다
# 

numbers = [5, 3, 6, 9, 8, 7, 1, 10]

def bubbleSort(array):
    for front_index in range(0, len(array)-1):
        for index in range(front_index+1,len(array)):
            if array[front_index] > array[index]:
                #자리를 바꾼다. 
                temp = array[front_index]
                array[front_index] = array[index]
                array[index] = temp
            # print(array)
    return array

result = bubbleSort(numbers)
print(result)

 


# 좌표 평면 두점 사이의 거리를 구하는 알고리즘 
import math 

def getDistance(p1, p2):
    xDistance = p1[0] - p2[0]
    print(xDistance)
    yDistance = p1[1] - p2[1]
    print(yDistance)

    #피타고라스정리에 의해 
    pDistance = math.pow(xDistance,2) + math.pow(yDistance,2)

    return math.sqrt(pDistance)

p1 = (0, 2)
p2 = (3, 4)
print(getDistance(p1, p2))

댓글