如何在排列后彼此相邻从元组打印值



任务:

您获得了一个字符串" S"。 您的任务是打印所有可能的字符串大小的排列 词典分类顺序。

输入格式:

一条包含空间分离的字符串" S"和整数的单线 值" k"。

示例代码解释了排列的工作原理(我稍后使用其中之一(:

>>> from itertools import permutations
>>> print permutations(['1','2','3'])
<itertools.permutations object at 0x02A45210>
>>>
>>> print list(permutations(['1','2','3']))
[('1', '2', '3'), ('1', '3', '2'), ('2', '1', '3'), ('2', '3', '1'), 
('3', '1', '2'), ('3', '2', '1')]
>>>
>>> print list(permutations(['1','2','3'],2))
[('1', '2'), ('1', '3'), ('2', '1'), ('2', '3'), ('3', '1'), ('3', 
'2')]
>>>
>>> print list(permutations('abc',3))
[('a', 'b', 'c'), ('a', 'c', 'b'), ('b', 'a', 'c'), ('b', 'c', 'a'), 
('c', 'a', 'b'), ('c', 'b', 'a')]

样本输入:

hack 2

样本输出:

一个彼此之下: 交流 啊 AK CA ch CK 哈 HC 香 K A KC kh

说明:

字符串" hack"的所有尺寸2置换均打印在 词典分类顺序。

这是我的代码:

from itertools import permutations
S = input().split()
K = "".join(sorted(A[0].upper()))
C = int(A[1])
for i in permutations(S,C):
    print(i)

,但输出是: ('a','c'( ('a','h'( ('a','k'( ('c','a'( ('c','h'( ('c','k'( ('哈'( ('H','c'( ('H','k'( ('K A'( ('k','c'( ('k','h'(

如何以这种方式打印这些元素的元素?:交流啊ak一个在另一个下方。

请注意,它必须在用户类型时工作:" hack 3"或" nothing x",其中x是Persivaion中每个元素的元素的数量。

您可以使用str.join()并像字符串一样打印它们:

from itertools import permutations
a = list(permutations('hack',2))
# In a more pythonic way you can do:
# a = permutations('hack', 2)
# Then you can include it in a foor loop
for k in a:
    print("".join(k).upper(), end = " ")

输出:

HA HC HK AH AC AK CH CA CK KH KA KC
for i in permutations(S,C):
    print(i)

to

for i in permutations(S,C):
    for j in range(C):
        print(i[j], end='')

我假设您正在使用Python3。

from itertools import permutations
A = input().split()
B = "".join(sorted(A[0].upper()))
C = int(A[1])
a = list(permutations(B,C))
for k in a:
    print("".join(k))

我们明白了!感谢@chiheb nexus!

最新更新