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

CheckIO - Between Markers

by UltraLowTemp-Physics 2020. 12. 21.
728x90

Problem: py.checkio.org/en/mission/between-markers/

My solution:

def between_markers(text: str, begin: str, end: str) -> str:
    """
        returns substring between two given markers
    """
    # your code here
    if begin in text and end in text: # condition 1 & condition 5
        # condition 1
        if text.index(begin) < text.index(end):
              return text[text.index(begin)+len(begin):text.index(end)]
        # condition 5
        else: return '' 
        # condition 2 
    elif (not begin in text) and end in text:
          return text[:text.index(end)]
        # condition 3 
    elif (not end in text) and begin in text:
          return text[text.index(begin)+len(begin):]
        # condition 4
    else: return text
    


if __name__ == '__main__':
    print('Example:')
    print(between_markers('What is >apple<', '>', '<'))

    # These "asserts" are used for self-checking and not for testing
    assert between_markers('What is >apple<', '>', '<') == "apple", "One sym"
    assert between_markers("<head><title>My new site</title></head>",
                           "<title>", "</title>") == "My new site", "HTML"
    assert between_markers('No[/b] hi', '[b]', '[/b]') == 'No', 'No opened'
    assert between_markers('No [b]hi', '[b]', '[/b]') == 'hi', 'No close'
    assert between_markers('No hi', '[b]', '[/b]') == 'No hi', 'No markers at all'
    assert between_markers('No <hi>', '>', '<') == '', 'Wrong direction'
    print('Wow, you are doing pretty good. Time to check it!')

 

A good solution that I see

def between_markers(text: str, begin: str, end: str) -> str:
    start = text.find(begin) + len(begin) if begin in text else None
    stop = text.find(end) if end in text else None
    return text[start:stop]
728x90

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

[CheckIO] Popular words  (0) 2020.12.23
[CheckIO] non unique elements  (0) 2020.12.22
CheckIO - Bigger price  (0) 2020.12.20
CheckIO - Count digits  (0) 2020.12.14
CheckIO - Days between  (0) 2020.12.12

댓글