[英]How to print values from a tuple next to each other after permutation?
Task: 任务:
You are given a string "S". 给您一个字符串“ S”。 Your task is to print all possible permutations of size of the string in lexicographic sorted order. 您的任务是按字典编排顺序打印字符串大小的所有可能排列。
Input Format: 输入格式:
A single line containing the space separated string "S" and the integer value "K". 一行包含空格分隔的字符串“ S”和整数值“ K”。
Sample Code explaining how permutations work(I used one of these later): 解释置换如何工作的示例代码(我稍后将使用其中之一):
>>> 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')]
Sample Input: 输入样例:
HACK 2 哈克2
Sample Output: 样本输出:
One under another: AC AH AK CA CH CK HA HC HK KA KC KH 一个接一个:AC AH AK CA CH CK HA HC HK KA KC KH
Explanation: 说明:
All possible size 2 permutations of the string "HACK" are printed in lexicographic sorted order. 字符串“ HACK”的所有可能的大小为2的排列都按字典顺序排序。
Here is my Code: 这是我的代码:
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)
But the output is: ('A', 'C') ('A', 'H') ('A', 'K') ('C', 'A') ('C', 'H') ('C', 'K') ('H', 'A') ('H', 'C') ('H', 'K') ('K', 'A') ('K', 'C') ('K', 'H') 但是输出为:('A','C')('A','H')('A','K')('C','A')('C','H') ('C','K')('H','A')('H','C')('H','K')('K','A')('K', 'C')('K','H')
How to print the elements of these tuples without parentheses and quotes in this way?: AC AH AK one under another. 如何以这种方式在没有括号和引号的情况下打印这些元组的元素?:AC AH AK一个接一个。
Note that it has to work when user type: "hack 3" or "anything x", where x is the number of elements of every element from permutaion. 请注意,它必须在用户键入“ hack 3”或“ anything x”时起作用,其中x是排列组合中每个元素的元素数。
You can use str.join()
and print them like a strings: 您可以使用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 = " ")
Output: 输出:
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='')
I'm assuming you're using Python 3. 我假设您正在使用Python 3。
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))
We got it! 我们得到了它! Thanks to @Chiheb Nexus! 感谢@Chiheb Nexus!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.