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

[CheckIO] Second Index

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

Problem: py.checkio.org/en/mission/second-index/

My Solution

def second_index(text: str, symbol: str) -> [int, None]:
    """
        returns the second index of a symbol in a given text
    """
    # your code here
    m = 0
    for n in range(len(list(text))):
        if list(text)[n] == symbol:
            if m == 1: return n
            else: m = m + 1
            
    return None


if __name__ == '__main__':
    print('Example:')
    print(second_index("sims", "s"))

    # These "asserts" are used for self-checking and not for an auto-testing
    assert second_index("sims", "s") == 3, "First"
    assert second_index("find the river", "e") == 12, "Second"
    assert second_index("hi", " ") is None, "Third"
    assert second_index("hi mayor", " ") is None, "Fourth"
    assert second_index("hi mr Mayor", " ") == 5, "Fifth"
    print('You are awesome! All tests are done! Go Check it!')

 

A good solution that I see

def second_index(text: str, symbol: str):
    """
        returns the second index of symbol in a given text
    """
    try:
        return text.index(symbol, text.index(symbol) + 1)
    except ValueError:
        return None
728x90

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

[CheckIO] pawn-brotherhood  (0) 2021.01.02
[CheckIO] sort array by element frequency  (0) 2020.12.30
[CheckIO] Popular words  (0) 2020.12.23
[CheckIO] non unique elements  (0) 2020.12.22
CheckIO - Between Markers  (0) 2020.12.21

댓글