-2

For example: say I wanted all possible combinations of 0-2 up to 3 digits the code would return the following:

0

1

2

00

01

02

10

11

12

20

21

22

000

001

002

010

020

011

022

012

021

100

101

102

110

111

112

120

121

122

200

201

202

210

220

211

221

212

222

Dante Arcese
  • 91
  • 13
  • @TigerhawkT3 Not a duplicate of that one. He is asking combinations with replacement – Mohammad Yusuf Dec 25 '16 at 03:01
  • @TigerhawkT3 Yes right. He will require just a for loop above print statement for different lengths. – Mohammad Yusuf Dec 25 '16 at 03:13
  • @TigerhawkT3 Yes the updated link with a for loop before works well. Is there any way to return the result as a string or integer. For example, the code returns (0,1), is there any way to get that to be 01 or "01"? – Dante Arcese Dec 25 '16 at 03:16
  • If you only want to print it that way, just unpack it: `tup = (0, 1); print(*tup, sep='')`. – TigerhawkT3 Dec 25 '16 at 03:18
  • @TigerhawkT3 how would I use that in my following code: `import itertools for i in range(1, 3): print list(itertools.product([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], repeat = i)` – Dante Arcese Dec 25 '16 at 03:29
  • You would need another loop, and you can't unpack it into `print()` because you're using Python 2 and haven't imported the new print function: `for i in xrange(1,4): for item in itertools.product(xrange(3), repeat=i): print ''.join(map(str, item))`. – TigerhawkT3 Dec 25 '16 at 03:35
  • @TigerhawkT3 Perfect. Thank you. – Dante Arcese Dec 25 '16 at 03:50

1 Answers1

0

First loop over the characters you'd like to see, then loop over the result of a call to itertools.product, as the task you're describing is the Cartesian product. In that inner loop, you can print each result (a tuple) by turning each element (integers) into a string and joining them all together.

import itertools
for i in xrange(1,4):
    for item in itertools.product(xrange(3), repeat=i):
        print ''.join(map(str, item))

Result:

0
1
2
00
01
02
10
11
12
20
21
22
000
001
002
010
011
012
020
021
022
100
101
102
110
111
112
120
121
122
200
201
202
210
211
212
220
221
222
TigerhawkT3
  • 48,464
  • 6
  • 60
  • 97
  • If someone would like to tell me what's wrong with this answer, I'd love to hear any suggestions so that I can improve it. – TigerhawkT3 Dec 26 '16 at 12:37