简体   繁体   中英

How to print values from a tuple next to each other after permutation?

Task:

You are given a string "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".

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

Sample Output:

One under another: 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.

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')

How to print the elements of these tuples without parentheses and quotes in this way?: AC AH AK one under another.

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.

You can use str.join() and print them like a strings:

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.

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM