728x90
반응형
https://www.codewars.com/kata/540d0fdd3b6532e5c3000b5b/train/python
저는 정규표현식을 사용하지 않았지만 정규표현식을 사용하면 코드 길이는 훨씬 짧아질 것 같습니다.
코드를 보시려면 더보기를 클릭하시면 됩니다.
더보기
Binomial Expansion
# My Code
def expand(expr):
tmp = expr.replace('(', '').replace(')', '').split('^')
if tmp[1] == str(0):
return str(1)
elif tmp[1] == str(1):
return tmp[0]
else:
# c 추출
c = int(tmp[1])
# 제곱시에 필요한 상수 값
tmp_b = [[] for _ in range(c + 1)]
tmp_b[0] = [1, 1]
for i in range(1, len(tmp_b)):
tmp_b[i].append(1)
for j in range(i-1):
tmp_b[i].append(tmp_b[i-1][j]+tmp_b[i-1][j+1])
tmp_b[i].append(1)
x = ''
x_index = 0
# x 추출
for i in tmp[0]:
if 'a' <= i <= 'z' or 'A' <= i <= 'Z':
x_index = tmp[0].find(i)
x = tmp[0][x_index]
break
# a 추출
a = tmp[0][:x_index]
if a == '-':
a = int(-1)
elif a == '':
a = int(1)
else:
a = int(tmp[0][:x_index])
# b 추출
b = int(tmp[0][x_index + 1:])
cnt = c
answer_list = []
for i in tmp_b[-1]:
a_tmp = i * pow(a, cnt) * pow(b, c-cnt)
if cnt == 0:
answer_list.append(str(a_tmp))
elif cnt == 1:
answer_list.append(str(a_tmp) + x)
else:
if a_tmp == 1:
answer_list.append(x + '^' + str(cnt))
elif a_tmp == -1:
answer_list.append('-' + x + '^' + str(cnt))
else:
answer_list.append(str(a_tmp) + x + '^' + str(cnt))
cnt -= 1
answer = answer_list[0]
for i in range(1, len(answer_list)):
if answer_list[i][0] == '-':
answer += answer_list[i]
else:
answer += ('+' + answer_list[i])
return answer
if __name__=='__main__':
print(expand("(x-1)^0"))
print(expand("(x-1)^1"))
print(expand("(x-1)^2"))
print(expand("(5m+3)^4"))
print(expand("(2x-3)^3"))
print(expand("(7x-7)^0"))
|
반응형
'알고리즘 > 코드워' 카테고리의 다른 글
[python]get ascii value of character (0) | 2020.05.05 |
---|---|
[python]L1: Bartender, drinks! (0) | 2020.05.04 |
[python]SpeedCode #2 - Array Madness (0) | 2020.04.28 |
[python]Polish alphabet (0) | 2020.04.26 |
[python]Largest 5 digit number in a series (0) | 2020.04.25 |