[英]My code works but sometimes gets into an infinite loop
So i got an assignment from school that the code should pick a string, remove the first and the last index, then randomize the middle letters and give back the string with the first and the last index again attached.所以我从学校得到了一个任务,代码应该选择一个字符串,删除第一个和最后一个索引,然后随机化中间字母并返回带有第一个和最后一个索引的字符串。 The word should be at least 4 characters long and schould not give back the original string.
该词应至少有 4 个字符长,并且不应返回原始字符串。 It is warking and all, but it after a few attempts at giving a 4 letter word gets into an infinite loop and I can't figure out why.
它很糟糕,但是经过几次尝试给出一个 4 个字母的单词后,它进入了一个无限循环,我不知道为什么。 It's a python code.
这是一个 python 代码。 Thank you for your help.
谢谢您的帮助。 Also some variables are in my laguage which shouldn't be a problem...just to clarify the weird variable names.
还有一些变量在我的语言中,这不应该是一个问题......只是为了澄清奇怪的变量名称。
import random
n=0
while n<4:
slovo=input('Zadajte vase slovo: ')
n=len(slovo)
l=[]
def shufle(slovo,l):
for i in range(len(slovo)):
if i==0:
continue
if i==len(slovo)-1:
continue
else:
l.append(slovo[i])
random.shuffle(l)
while True:
shufle(slovo,l)
s=slovo[0]
for i in l:
s+=i
s+=slovo[-1]
if s==slovo:
continue
elif len(s)!=len(slovo):
continue
else:
print(s)
break
Here's a tip: if your function is always expecting the same input for one of its parameters, than that parameter is probably not necessary.这里有一个提示:如果您的 function 总是期望其参数之一具有相同的输入,则可能不需要该参数。 This is the case with passing empty lists or similar objects to functions.
将空列表或类似对象传递给函数就是这种情况。 There was also a check if s and slovo are the same size which is not needed so I removed it.
还有一个检查 s 和 slovo 的大小是否相同,这是不需要的,所以我删除了它。 Try this:
尝试这个:
import random
n=0
while n<4:
slovo=input('Zadajte vase slovo: ')
n=len(slovo)
def shufle(slovo):
l = []
for i in range(len(slovo)):
if i == 0:
continue
if i == len(slovo)-1:
continue
else:
l.append(slovo[i])
random.shuffle(l)
return l
while True:
l = shufle(slovo)
s = slovo[0]
for i in l:
s += i
s += slovo[-1]
if s == slovo:
continue
else:
print(s)
break
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.