python/string: how to get all the possible combinations in string considering only space for splitting the string

Question:

I have a string
dt = '301 302 303'
how can I get different combinations of above string with considering only spaces while splitting the string.

# output
301
302
303
301 302
301 303
302 303
301 302 303
Asked By: Sushil Kokil

||

Answers:

Please use itertools module
turn the string to a list
and then iterate

dt = '301 302 303' 
import itertools
list1 = dt.split()
for i in range(1,len(list1) + 1):
    for subset in itertools.combinations(list1,i):
        print(subset)

output

('301',)
('302',)
('303',)
('301', '302')
('301', '303')
('302', '303')
('301', '302', '303')
Answered By: kaispace30098
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.