TEAMLAB-Lecture / python-101-for-data-science-by-pknu

1 stars 14 forks source link

gowithflow의 number_of_case 질문드립니다. #28

Open kim-irubi opened 2 years ago

kim-irubi commented 2 years ago
def number_of_cases(list_data):
    result = None
    result = []
    cases = ""
    if len(list_data) > 2:
        for i in range(len(list_data)):
            for k in range(len(list_data)):
                cases = str(list_data[i]) + str(list_data[k])
                result.append(cases)
    else:
        for i in range(len(list_data)):
            cases = "".join(list_data[i]) + cases
        result.append(cases)
    result_list = result
    n = len(result)
    for i in range(n):
        if result.count(result_list[i]) > 1:
            result.remove(result[i])
            n -= 1
        else:
            pass

if result.count(result_list[i]) > 1 에서 list index out of range 오류가 뜨는데 왜 뜨는지 이해가 되질 않습니다.

jjungyujin commented 2 years ago
n = len(result)
for i in range(n):
    if result.count(result_list[i]) > 1:
        result.remove(result[i])
        n -= 1 

위 코드에서 n을 1 줄이면 반복문의 i도 같이 줄어든 n까지 반복한다고 생각하신 것 같습니다. 하지만, 실제 코드를 테스트해보시면 n의 값은 1이 줄어들지만 반복문을 도는 i 에는 영향을 주지 않음을 확인하실 수 있습니다. 따라서 리스트의 갯수는 줄어드는데 i는 처음 할당받은 n-1 까지 받으려하니 out of range가 뜨는 것입니다.

아래 코드처럼 i와 n을 print 하면서 확인해보시면 도움이 되실 것 같네요 !

a = ["a", "b", "a"]
n = len(a)

for i in range(n):
  print(i)
  if a.count(a[i]) > 1:
    a.remove(a[i])
    n -= 1
    print(n)
kim-irubi commented 2 years ago

이해했습니다 감사합니다!!!