본문 바로가기

데이터 - 기본 코드 및 알고리즘 연습/Codewar

[Codewars] A Rule of Divisibility by 13

 

Codewars: Achieve mastery through challenge

Codewars is where developers achieve code mastery through challenge. Train on kata in the dojo and reach your highest potential.

www.codewars.com

▶  문제 : 

▶  내 답안 : 

def thirt(n):
    def sum_n(num) :
        return sum([int(v)*((10**i)%13) for i,v in enumerate(str(num)[::-1])])
    while True :
        n = sum_n(n)
        if n == sum_n(n) :
            return n
            break

▶  모범답안 : 

array = [1, 10, 9, 12, 3, 4]

def thirt(n):
    total = sum([int(c) * array[i % 6] for i, c in enumerate(reversed(str(n)))])
    if n == total:
        return total
    return thirt(total)

▶  배워야할 부분 : 1) i % n  ,  2) 재귀함수

1. 리스트 분할해서 돌리기 (순환구조)

if 5개 단위로 돌리고 싶어 ( i % 4 )
	array = [1,5,2,4,7]
	[int(v)*array[i%4] v for i,v in enumerate(list)]

2. 재귀함수
def thirt(n) :
	total = 13
	if n == total :
    		return total
	return thirt(total)