본문 바로가기

Programming/Python

Python 알고리즘 Quick books

Bubble Sort Algorithm

arr = [7, 3, 9, 2, 0, 4, 8, 1, 6, 5]

def bubbleSort(theSeq):
	n = len(theSeq)
    for i in range(n - 1):
    	for j in range(n - 1 - i):
        	if theSeq[j] > theSeq[j + 1]:
            	temp = theSeq[j]
                theSeq[j] = the Seq[j + 1]
                theSeq[j + 1] = temp
	return theSeq
    
print(bubbleSort(arr))

Printing Prime Numbers

#printing prime numbers in a range
lower = 100
upper = 200

for num in range(lower, upper+1):
    if num > 1:
        for i in range(2, num):
            if num % i == 0:
                break
            else:
                print(num) # prime

 

Check For Prime Number

# check for prime number
num = int(input("enter a number : "))
if num < 1:
    print("not a prime number")
else:
    for i in range(2, num):
        if num % i == 0:
            print("not a prime number")
            break
        else:
            print("it is prime number")

Check for palindrome

s = input("enter a string : ")

# reverse a given string
def palindrome(string):
    x = ""
    for i in string:
        x = i + x
    return x

if s == palindrome(s):
    print("It is a palindrome")
else:
    print("It is not a palindrome")

Reverse a String

s = input("enter a string : ")

# reverse a given string
def palindrome(string):
    x = ""
    for i in string:
        x = i + x
    return x

print(palindrome(s))

Check For Palindrome

s = input("enter a string : ")

# function to check the palindrome
def palindrome(string):
    for i in range(1, int(len(string) / 2)):
        if string[i] == string[len(string) - i - 1]:
            return True
    return False

print(palindrome(s))

Reverse a Given Number

# reversing a given number
def rev_num(num):
    rev = 0
    while num > 0:
        reminder = num % 10
        rev = (rev * 10) + reminder
        num = num // 10
    return rev

print(f"reverse of the given number is {rev_num(56789)}")

HCF(Highest common factor) of Two Numbers (최대공약수)

# HCF or GCD of two numbers
def hcf(num1, num2):
    if num1 > num2:
        smaller = num2
    else:
        smaller = num1
    for i in range(1, smaller + 1):
        if (num1 % i == 0) and (num2 % i == 0):
            factor = i
    return factor

print(f"hct = {hcf(54, 24)}")

LCM(least common multiple) of Two Numbers (최소공배수)

# To find LCM of two numbers
def lcm(num1, num2):
    if num1 > num2:
        greater = num1
    else:
        greater = num2
    
    while True:
        if (greater % num1 == 0) and (greater % num2 == 0):
            break
        greater += 1
    return greater

print(f"lcm = {lcm(12, 14)}")
반응형
LIST