«Недопустимый символ в идентификаторе»
Я запускаю файл python, содержащий данный код в IDLE 3 на macOS Catalina. Всякий раз, когда я запускаю код, он показывает ошибку. Я не могу понять причину. Пожалуйста, guide me
, если можете.
Ошибка отображается в строке 11 charList
Если я удалю комментарий из строки 9,10 в функции makeList (), появится ошибка at строка 10 для
Я слышал о проблеме двойных кавычек, но проблема здесь не в этом.
Примечание: я слежу за книгой «Math Adventures With Python "Питера Фаррелла, глава 12
import random
target = "I never go back on my word, because that is my Ninja way."
characters = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.',?!"
#function to create a "guess" list of characters the same length as target.
def makeList():
'''Returns a list of characters the same length
as the target'''
charList = [] #empty list to fill with random characters
for i in range(len(target)):
charList.append(random.choice(characters))
return charList
#function to "score" the guess list by comparing it to target
def score(mylist):
'''Returns one integer: the number of matches with target'''
matches = 0
for i in range(len(target)):
if mylist[i] == target[i]:
matches += 1
return matches
#function to "mutate" a list by randomly changing one letter
def mutate(mylist):
'''Returns mylist with one letter changed'''
newlist = list(mylist)
new_letter = random.choice(characters)
index = random.randint(0,len(target)-1)
newlist[index] = new_letter
return newlist
#create a list, set the list to be the bestList
#set the score of bestList to be the bestScore
random.seed()
bestList = makeList()
bestScore = score(bestList)
guesses = 0
#make an infinite loop that will create a mutation
#of the bestList, score it
while True:
guess = mutate(bestList)
guessScore = score(guess)
guesses += 1
#if the score of the newList is lower than the bestList,
“
#create a list, set the list to be the bestList
#set the score of bestList to be the bestScore
random.seed()
bestList = makeList()
bestScore = score(bestList)
guesses = 0
#make an infinite loop that will create a mutation
#of the bestList, score it
while True:
guess = mutate(bestList)
guessScore = score(guess)
guesses += 1
#if the score of the newList is lower than the bestList,
#"continue" on to the next iteration of the loop
if guessScore <= bestScore:
continue
#if the score of the newlist is the optimal score,
#print the list and break out of the loop
print(''.join(guess),guessScore,guesses)
if guessScore == len(target):
break
#otherwise, set the bestList to the value of the newList
#and the bestScore to be the value of the score of the newList
bestList = list(guess)
bestScore = guessScore