알고리즘/코드워

[python]Permutations

(ㅇㅅㅎ) 2020. 4. 13. 09:20
728x90
반응형

https://www.codewars.com/kata/5254ca2719453dcc0b00027d/train/python

 

Codewars: Train your coding skills

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

www.codewars.com

더보기

내 코드

itertools의 permutations을 이용하면 쉽게 풀 수 있다.

하지만 permutations을 사용하지 않고 푸는 것도 중요한 것 같다.

 

# My Code
import itertools
def permutations(string):
    # 순열 만들기
    result = list(itertools.permutations(string, len(string)))
 
    # [('a', 'b')] -> ['ab']
    result = list(set([''.join(i) for i in result]))
 
    # 정렬
    result.sort()
    return result
 
# 한줄로 줄이기
def permutations1(string):
    return list(''.join(p) for p in set(itertools.permutations(string)))
 
# itertools 안쓰고 작성
def permutations2(string):
    if len(string) == 1return set(string)
    first = string[0]
    rest = permutations(string[1:])
    result = set()
    for i in range(0len(string)):
        for p in rest:
            result.add(p[0:i] + first + p[i:])
    return result
 
if __name__=='__main__':
    asnwer = permutations('a')
    print(asnwer)
 
반응형

'알고리즘 > 코드워' 카테고리의 다른 글

[python]How do I compare numbers?  (0) 2020.04.16
[python]Sum of positive  (0) 2020.04.15
[python]Is the string uppercase?  (0) 2020.04.12
[python]Make a spiral  (0) 2020.04.11
[python]altERnaTIng cAsE <=> ALTerNAtiNG CaSe  (0) 2020.04.08