简体   繁体   中英

Generating combinations with repetetions in python

I generated combination of numbers, for example 123 , using this code

from itertools import combinations
for i in set(combinations('123',2)):
    print(''.join(i))

I get the desired output here

13
12
23

But when I use 133 , I get

13
33

But I want to ignore the repetition, I want the output as

13
13
33

Is there any alternate approach?

It's very simple. You should use list(combinations('123',2)) and not set. Set reduces identical values.

set() s by nature, don't allow any duplicate elements. Each element in a set() must be unique . The Python documentation makes note of this:

Python also includes a data type for sets. A set is an unordered collection with no duplicate elements .

Emphasis mine. That is why your not getting your expected output. When you call set() , it removes the duplicate 13 from your combinations. Instead, just iterate through the combination object as is:

from itertools import combinations

for i in combinations('133', 2): # no call to set()
    print(''.join(i))

Which outputs:

13
13
33

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