알고리즘/코드워

[python]Highest Scoring Word

(ㅇㅅㅎ) 2020. 3. 12. 21:16
728x90
반응형

https://www.codewars.com/kata/57eb8fcdf670e99d9b000272/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

문자열에서 합이 가장 큰 단어 찾는 문제이다.

더보기

내 코드

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
# My Code
def high(x):
    answer_ = []
    sum_ = 0
    for i in x:
        if i is ' ':
            answer_.append(sum_)
            sum_ = 0
            continue
        else:
            sum_ += ord(i)-96
    answer_.append(sum_)
    return x.split()[answer_.index(max(answer_))]
 
if __name__=='__main__':
    answer = high('man i need a taxi up to ubud')
    print(answer)
    answer = high('what time are we climbing up the volcano')
    print(answer)
    answer = high('take me to semynak')
    print(answer)
 

 

아스키코드를 이용해서 문자를 숫자로 바꾸었다.

다만 아스키 코드를 사용하게 되면 a가 1부터가 아니라 97부터 시작된다. 그래서 ord(i)-96을 사용했다.

(사실 최대값을 구하는 것이므로 -96을 해주지 않아도 된다.)

ord('문자')는 문자를 아스키코드의 숫자로 변환시켜준다. 

스페이스를 기준으로 나누어서 값을 저장시킨 후 최댓값을 출력하도록 코드를 제작했다.

 

문제를 풀고 나면 다른 사람들의 코드를 볼 수 있는데 내 코드보다 간단명료하게 만드신 분들이 많다.

반응형

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

[python]Bouncing Balls  (0) 2020.03.14
[python]Simple Pig Latin  (0) 2020.03.13
[python]Build Tower  (0) 2020.03.11
[python]Equal Sides Of An Array  (0) 2020.03.10
[python]Shortest Word  (0) 2020.03.10