Warm tip: This article is reproduced from serverfault.com, please click

string-用Python编织数字

(string - Weaving Numbers In Python)

发布于 2020-11-28 16:19:16

我正在尝试编写一个代码,该代码从两个用户输入的数字返回所有可能的编织数字的列表。例如,

如果A = 27并且B = 54,那么可以编织四个数字

2574

5247

7425

4752

编织数字可以通过从头开始编织,从A开始,从头编织,从B开始,从头编织,从A开始,从头编织,从B开始。同时编织两个数字A和B ,如果编织了A的所有数字,而B中还有其他数字,则B的其余数字仅附加在末尾。

我在尝试

num_a = input()
num_b = input()
weaved_nums = []

def permutations(string):
    if len(string) == 1:
        return string

    recursive_perms = []
    for c in string:
        for perm in permutations(string.replace(c,'',1)):
            recursive_perms.append(c+perm)

    return set(recursive_perms)

num_a_perms = list(permutations(num_a))
num_b_perms = list(permutations(num_b))

def weave(num_1, num_2):
    new_string = ''
    for i in range(len(min([num_1, num_2], key = len))):
        new_string += num_1[i] + num_2[i]
    new_string += max(num_1, num_2, key=len)[len(num_1):]
    weaved_nums.append(new_string)

for i in range(len(num_a_perms)):
    for k in range(len(num_b_perms)):
        weave(num_a_perms[i], num_b_perms[k])
        weave(num_b_perms[k], num_a_perms[i])
        

print(weaved_nums)

但是我的程序返回

['2475', '4257', '2574', '5247', '7425', '4752', '7524', '5742']

用于输入27和54

Questioner
RISHABH AGRAWAL
Viewed
0
wwii 2020-11-29 01:13:15

另一个解决方案-限于两个输入:

  • 从头开始 rzip(r,s)
  • 首先从末尾 r开始:zip(r[::-1],s[::-1])
  • 从头开始 szip(s,r)
  • 首先从末尾 s开始:zip(s[::-1],r[::-1])

def f(r,s):
    combos = ((r,s),(r[::-1],s[::-1]),(s,r),(s[::-1],r[::-1]))
    for combo in combos:
        yield ''.join(c for x,y in zip(*combo) for c in (x,y))

for thing in f('27','54'):
    print(thing)

对于长度不等的字符串,请使用itertools.zip_longest(*combo,fillvalue='')而不是zip。

def f(r,s):
    combos = ((r,s),
              (r[::-1],s[::-1]),
              (s,r),
              (s[::-1],r[::-1]))

    for combo in combos:
        yield ''.join(c for x,y in itertools.zip_longest(*combo,fillvalue='') for c in (x,y))

>>> for thing in f('27','543'):
        print(thing)
25743
73245
52473
37425