본문 바로가기
프로그래밍 문제/[Python] CheckIO

[Check-IO] Conversion from CamelCase

by UltraLowTemp-Physics 2021. 12. 20.
728x90

[1] Problem: https://py.checkio.org/en/mission/conversion-from-camelcase/
[2] My solution 

def from_camel_case(name: str) -> str:
    #replace this for solution
    list_str = list(name)
    for n in range(len(list_str)):
        if list_str[n].isupper():
            if n > 0: list_str[n] = '_' + list_str[n] 
            list_str[n] = list_str[n].lower() 
    
    return ''.join(list_str)

if __name__ == '__main__':
    print("Example:")
    print(from_camel_case("Name"))

    #These "asserts" using only for self-checking and not necessary for auto-testing
    assert from_camel_case("MyFunctionName") == "my_function_name"
    assert from_camel_case("IPhone") == "i_phone"
    assert from_camel_case("ThisFunctionIsEmpty") == "this_function_is_empty"
    assert from_camel_case("Name") == "name"
    print("Coding complete? Click 'Check' to earn cool rewards!")

 

[3] Best solution

import re

def from_CamelCase(name):
    return '_'.join(re.findall('([A-Z][^A-Z]*)', name)).lower()

1) import re
  - "re" module: Regular expression operation 
  - https://docs.python.org/3/library/re.html   
2) findall() method 
Return all non-overlapping matches of pattern in string, as a list of strings or tuples. The string is scanned left-to-right, and matches are returned in the order found. Empty matches are included in the result.

The result depends on the number of capturing groups in the pattern. If there are no groups, return a list of strings matching the whole pattern. If there is exactly one group, return a list of strings matching that group. If multiple groups are present, return a list of tuples of strings matching the groups. Non-capturing groups do not affect the form of the result. 

728x90

'프로그래밍 문제 > [Python] CheckIO' 카테고리의 다른 글

[Check IO] words-order  (0) 2022.02.27
[Check-IO] Conversion into CamelCase  (0) 2021.12.25
[Check-IO] The Most Wanted Letter  (0) 2021.12.19
[Check-IO] Follow Instructions  (0) 2021.12.18
[Check-IO] Common Words  (0) 2021.12.16

댓글