본문 바로가기

Algorithm

파이썬 알고리즘 연습(1)

행렬의 덧셈

def solution(arr1, arr2):
    answer = []
    for i in range(len(arr1)):
        row = []
        for j in range(len(arr1[i])):
            row.append(arr1[i][j] + arr2[i][j])
        answer.append(row)
    return answer

 

직사각형 별찍기

a, b = map(int, input().strip().split(' '))
for i in range(b):
    for j in range(a):
        print("*", end="")
    print()

 

최대공약수와 최소공배수

def solution(n, m):
    answer = []
    max_num = 0
    for i in range(1, m + 1):
        if n % i == 0 and m % i == 0:
            max_num = i
        

    a = n / max_num
    b = m / max_num
    
    min_num = a * b * max_num   
    answer.append(max_num)
    answer.append(min_num)
    return answer

 

3진법 뒤집기

  • n 진법 -> 해당 수를 n으로 나눈 나머지를 붙이면 됨
  • int(string, n) -> n진법의 수를 10진수로 변환
def solution(n):
    answer = 0
    three_number = ""
    while n > 0:
        three_number += str(n % 3)
        n //= 3
        
    answer = int(three_number, 3)
    return answer