본문 바로가기

Python_Matter/Solve

Python Learn the basics Quiz 41

반응형

Q>

You are given two strings and you have to find an index of the second occurrence of the second string in the first one.

(두 개의 문자열이 주어지고 첫 번째 문자열에서 두 번째 문자열이 두 번째 나타나는 색인을 찾아야합니다.)

Let's go through the first example where you need to find the second occurrence of "s" in a word "sims".

("sims"라는 단어에서 두 번째 "s"가 필요한 첫 번째 예제를 살펴 보겠습니다.)

It’s easy to find its first occurrence with a function index or find which will point out that "s" is the first symbol in a word "sims" and therefore the index of the first occurrence is 0.

(함수 색인이나 find에서 "s"가 "sims"단어의 첫 번째 기호이므로 첫 번째 항목의 색인은 0임을 쉽게 알 수 있습니다.)

But we have to find the second "s" which is 4th in a row and that means that the index of the second occurrence (and the answer to a question) is 3.

(하지만 두 번째 " s "는 네 번째 행이며 두 번째 발생 (및 질문에 대한 대답)의 색인은 3임을 나타냅니다.)

 

Input: Two strings.(입력 : 두 개의 문자열.)

 

Output: Int or None.(출력 : Int 또는 None)

 

Example:

second_index("sims", "s") == 3

second_index("find the river", "e") == 12

second_index("hi", " ") is None

 

A>

def second_index(text: str, symbol: str) -> [int, None]:
    """
        returns the second index of a symbol in a given text
    """
    # your code here
    # count : 부분 문자열 세는 메소드
    # 찾는 문자열이 2개 이상 있는지 확인
    if text.count(symbol) < 2:
        return None
    # 첫번째 인덱스 찾기
    first = text.find(symbol)
    # 두번째는 첫번째 인덱스 다음부터 찾아야되므로 + 1
    return text.find(symbol, first + 1)


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!')

 

O>

Example:
3
You are awesome! All tests are done! Go Check it!

Process finished with exit code 0

 

S>

https://py.checkio.org/

반응형

'Python_Matter > Solve' 카테고리의 다른 글