考虑一个字符串'1234'。您需要一个函数来生成所有旋转:'1234', '3412', '4123', '2341'。我创建了一个简单的测试套件:

assert rotations('123') == set(['123', '231', '312'])
assert rotations('111') == set(['111'])
assert rotations('197') == set(['197', '971', '719'])

pythonic的方法是什么?我完成了下面的代码
def rotations(num):
    str_num = str(num)
    result = set()
    for mid in xrange(len(str_num)):
        result.add(
            str_num[mid:] + str_num[:mid]
        )
    return result

最佳答案

s='1234'
z = {s[x:]+s[:x] for x in range(len(s))}

关于用Python方式生成字符串旋转,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33521371/

10-12 20:55