如何遍历一个字符串n次直到它等于原始字符串?

时间:2018-12-28 16:44:04

标签: python python-3.x 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,这是正确的。但是对于第二个字符串,由于完全覆盖了字符串的长度,因此它在第五次迭代时停止。

如何确保它一直循环遍历字符串,直到我得到与原始字符串相同的字符串?

1 个答案:

答案 0 :(得分:1)

使用while循环,迭代直到出现相同的字符串,然后对i % len(s)进行切片,其中i是当前迭代,而s是当前字符串:< / p>

代码

string_list = ["1010", "1001"]

for s in string_list:
    i = 1
    curr_s = s

    print("starting t", s)

    while True:
        k = i % len(s)
        new_s = curr_s[k:] + curr_s[:k]

        print("intermediate new string",new_s)

        if new_s == s:
            print("no of iterations until same string occurs", i)
            break

        i += 1
        curr_s = new_s

输出

enter image description here