gpt4 book ai didi

python - 索引错误 : string index out of range

转载 作者:行者123 更新时间:2023-11-28 16:24:25 26 4
gpt4 key购买 nike

我得到一个

Traceback (most recent call last):   File "H:\Documents\game.py", line 73, in <module>
if attemptThis[i] != target[i]: IndexError: string index out of range Press any key to continue . . .

运行这段代码时出错。

#-----------------------------------------------------
# Python 'Evolution of Text' Program
# More programs at: usingpython.com/programs
#-----------------------------------------------------

possibleCharacters = string.ascii_uppercase + ' .!?;:='

target = """
lMMMMMMMM .MMMM= MMM MMM
lMM MMl M=M MMM =MM MMM
lMM M=. MMM M=M= M=MM=MM =M===== M=MMMM= M=M MM=MMM==l ==M===M= MMM MMMM =M=MM==MM
lMM M=. MMM== MMM .== ==M.... =l= l===l=M. MMM .MMM MMM= MMM
lMM====== MMM MM======== ......=ll .....MMl lll =MM =MM l==....M=M =MM MMM
lM= M=M M=====M =====M=M =======MM .M===MMM MMM =M====MMM MMM MMM
"""
attemptThis = ''.join(random.choice(possibleCharacters) for i in range(len(target)))
attemptNext = ''

completed = False

generation = 0

while completed == False:
print(attemptThis)
attemptNext = ''
completed = True
for i in range(len(target)):
if attemptThis[i] != target[i]:
completed = False
attemptNext += random.choice(possibleCharacters)
else:
attemptNext += target[i]
if generation == 1000:
break
generation += 1
attemptThis = attemptNext

我找到了这段代码 here并修改它以供我自己使用。在我添加退出子句之前它是有效的

if generation == 1000:
break

我添加它是因为生成 ASCII 需要很长时间才能满足我的喜好。我在我正在处理的一个小项目中将其用作标题屏幕,因此修复此问题并不重要,因为我总是可以返回使用 Print """Text Here""" 命令代替。

最佳答案

直接遍历集合而不是使用索引更像 pythonic。由于我很好奇您的程序应该做什么,所以我也重写了其他部分以使其运行。

import time, random, string
target = """
lMMMMMMMM
lMM MMl
lMM M=. MMM M=M= M=MM=MM =M===== M=MMMM=
lMM M=. MMM== MMM .== ==M.... =l=
lMM====== MMM MM======== ......=ll .....MMl
lM= M=M M=====M =====M=M =======MM

.MMMM= MMM MMM
M=M MMM =MM MMM
M=M MM=MMM==l ==M===M= MMM MMMM =M=MM==MM
l===l=M. MMM .MMM MMM= MMM
lll =MM =MM l==....M=M =MM MMM
.M===MMM MMM =M====MMM MMM MMM
"""

chars = list(set(target + string.ascii_uppercase) - {'\n'})
attempt = ''.join('\n' for c in target)
# First attempt is just a bunch of newlines. This makes the
# text alignment correct after the first run through the loop

while target != attempt:
attempt = ''.join(
tc if tc == ac else random.choice(chars)
for tc, ac in zip(target, attempt)
)
clearscreen = '\033c' # linux terminal control character
print(clearscreen + attempt)
time.sleep(0.05)

这是它的外观预览(链接转到 asciinema.org)

asciicast

关于python - 索引错误 : string index out of range,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37752828/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com