我有几个字符串需要循环并执行一些操作,以便在某些迭代后返回原始字符串。例如在 string "1010",在每次迭代中,我需要根据迭代次数移动前面的字符First iteration (1 iteration): 0101 (moved 1 character from front)Second iteration (2 iteration): 0101 (moved 2 characters from front)Third iteration (3 iteration): 1010 (moved 3 characters from front)所以我找回了原来的字符串但是对于像 那样的字符串"1001",它将需要 7 次迭代First iteration (1 iteration): 0011 (moved 1 character from front)Second iteration (2 iteration): 1100 (moved 2 characters from front)Third iteration (3 iteration): 0110 (moved 3 characters from front)Fourth iteration (4 iteration): 0110 (moved 4 characters from front)Fifth iteration (5 iteration): 1100 (moved 5 characters from front)Sixth iteration (6 iteration): 0011 (moved 6 characters from front)Seventh iteration (7 iteration): 1001 (moved 7 characters from front)下面是我的代码string_list = ["1010", "1001"]for i in string_list: print("i",i) t = 1 print("starting t",t) new_string = i for j in i: num_letter = new_string[:t] print("num_letter", num_letter) new_string = new_string[t:] + num_letter print("intermediate new string",new_string) if new_string == i: print("no of iterations until same string occurs", t) break else: t += 1 print("t",t)对于第一个字符串,我没有得到3正确的迭代。但是对于第二个字符串,它在第五次迭代时停止,因为字符串的长度被完全覆盖。我如何确保它一直循环遍历字符串,直到我得到一个与原始字符串相同的字符串?
添加回答
举报
0/150
提交
取消