파이썬 초보자로서 나는 코드 워드 퍼즐을 사용하기로 결정했습니다.IndexError : 코드 워드 퍼즐에서 범위를 벗어난 목록 색인
코드 워드는 Python 2.7.6을 사용합니다.
입력 문자열에 한 번 이상 발생하는 별개의 대소 문자를 구분하지 알파벳 문자와 숫자 숫자의 개수를 반환하는 함수를 작성 :
두 번째 퍼즐은 당신을 필요로합니다. 입력. 자열은 영. 자 (대. 자와 소. 자 모두) W 숫자 만 포함한다고 가정 할 수 있습니다.
예를 들어, "abcde"프로그램을 제공하면 중복이 없기 때문에 0을 주어야합니다. 그러나 당신이 그것을 "indivisibilities"라고하면 2라는 중복 문자가 있기 때문에 2를 주어야합니다 : i (7 회 발생) 및 s (2 회 발생). 내가 상상 접근 함께했다 초보자로서
은 매우 원유이지만, 그럼에도 불구하고 내 시스템에서 완벽하게 작동합니다 :def duplicate_count(text):
# the number of duplicates
dupes = 0
# convert input string to lower case and split into individual characters
list_of_chars = list(text.lower())
# sort list into groups
sorted_chars = sorted(list_of_chars)
# get length of list
n = len(sorted_chars)
# check whether the first element of the list is the same as the second. If
# it is, add one to the dupes count
if sorted_chars[0] == sorted_chars[1]:
dupes += 1
else:
dupes += 0
# start with the second element (index: 1) and finish with the (n - 1)-th
# element
for i in range(1, n - 1):
# if the ith element of the list is the same as the next one, add one
# to the dupes count. However, since we only want to count each
# duplicate once, we must check that the ith element is not the same as
# the previous one
if sorted_chars[i] == sorted_chars[i + 1] and sorted_chars[i] != sorted_chars[i - 1]:
dupes += 1
else:
dupes += 0
return dupes
이것은 자동화 된 테스트를 모두 통과,하지만 난으로이를 제출할 때 해결 방법 : STDERR을 얻습니다.
Traceback:
in <module>
in duplicate_count
IndexError: list index out of range
내가 이해하는 것처럼, 존재하지 않는 목록의 요소에 액세스하려고하면이 오류가 발생합니다. 그러나 나는 내 코드에서 내가 그 일을하는 곳을 볼 수 없다. 나는 나의 목록의 길이를 계산하고 그것을 n
에 저장한다. 그래서 목록 sorted_chars
을 생성해야합니다,의 내가 "ababa"
duplicate_count
에 문자열을 공급 가정 해 봅시다 : 그래서 n
= 5. 길이 5의 ['a', 'a', 'a', 'b', 'b']
을 따라서 1, 2, 3. 따라서 for i in range(1, n - 1)
, 수학적으로 말하고있는 번호를 생성합니다 range(1, n - 1)
= range(1, 4)
, 각각의 i∈ {1, 2, 3}에 대해. 따라서이 코드에서 사용하는 가장 큰 인덱스는 4 (if sorted_chars[i] == sorted_chars[i + 1]
)입니다. 이는 인덱스 4에 요소가 있기 때문입니다 (이 경우 'b').
그럼 왜 Codewars가 나에게이 오류가 발생합니까?
문자열에 문자가 하나 또는 0 개이면 어떻게됩니까? –
@WillemVanOnsem aha! 그러면 문제가 생깁니다. 감사! – Au101