【发布时间】:2020-08-02 21:18:14
【问题描述】:
“标识符中的无效字符”
我正在 macOS Catalina 上的 IDLE 3 中运行一个包含给定代码的 python 文件。每当我运行代码时,它都会显示错误。我无法理解原因。可以的话请guide me。
错误显示在 第 11 行 charList
如果我从 makeList() 函数的第 9,10 行删除注释,则错误出现在 第 10 行
我听说过双引号的问题,但这不是这里的问题。
注意:我正在关注 Peter Farrell 的《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
【问题讨论】:
-
请将您的代码发布为文本而不是图像。
-
@Jacques 添加了代码
-
另外,请发布您对错误的所有信息。
-
这个花哨的引号字符
“似乎出现在两个cmets 之间的代码中。没有明显的理由让它存在,它肯定会导致某种错误。 -
我明白了。您的代码中有non-breaking spaces。删除该行上的空格并输入正常空格。然后,当您在随后的每一行都遇到类似的错误时,也要在那里执行。无论您从哪里复制/粘贴代码,都会引入 Python 无法识别的奇怪字符。