본문 바로가기
파이썬

파이썬 Python-문자가 목록에 있는지 확인

by º기록 2020. 12. 5.
반응형

문자 (문자열)가 목록에 있으면 find_letter(['o', ['hello', 'c', 'bye']), False를 반환하지 않으면 True를 반환합니다.

def find_letter(lst):

    lst=['o','hello', 1]
    n='o'

    if not lst:          
        return 0

    elif lst[0] == n:
        return True

    elif find_letter(lst[0:]):
        return True

    else: 
        return False


print(find_letter(lst))

'True'를 반환하지만 이것이 올바른 방법인지 확실하지 않습니다. 더 좋은 방법이 있을까요? 두 번째 elif 문에서 첫 번째 항목에 문자가 포함되어 있지 않으면 Python이 목록의 모든 요소를 ​​통과합니까? 함수는 재귀 적이어야합니다.

 

해결 방법

 

여기에 오류가 있습니다.

def find_letter(lst):  # You receive your list as lst
    lst=['o','hello', 1]  # Opppsss! You override it. It does not matter what you receive with lst above, now its value is ['o','hello', 1]
    n='o'

따라서 find_letter (lst [0 :]) 에서는 목록 분할을 사용하지만 lst = [ 'o', 'hello', 1] 줄에서는 재정의합니다. 다시 말하지만 항상 목록의 첫 번째 요소에서 검색을 실행합니다.

n = "o"  # you can set this too, but this is optional
def find_letter(lst):
    # do not set a value to lst in here

    if not lst:          
        return 0

    elif lst[0] == n:  # You checked first element in here
        return True

    elif find_letter(lst[1:]):  # since you checked the first element, skip it and return the orher elements of the list
        return True

    else: 
        return False

lst = ['o','hello', 1]
print find_letter(lst)

 

참조 페이지 https://stackoverflow.com/questions/26355191

 

 

반응형

댓글