Kartik Khare
Kartik Khare

Reputation: 59

How to write program in python to generate all n digit numbers with only 4 and 7 as their digits?

I tried generating permutations using itertools.permutations but i am so confused on how to do this for n digits.

Upvotes: 1

Views: 2196

Answers (2)

Blender
Blender

Reputation: 298472

I would use itertools.product instead:

In [26]: for i in itertools.product(['4', '7'], repeat=2):
   ....:     print int(''.join(i))
   ....:
44
47
74
77

The repeat argument is your n.

Upvotes: 5

user180100
user180100

Reputation:

I would use binary, if you need all 2-digits numbers with only 7, 4 as digits:

max 2 digits number in base-2 is 11b ie 3, so:

0 => 00b
1 => 01b
2 => 10b
3 => 11b

then replace 0 by 4 and 1 by 7 (arbitrary), giving: 44, 47, 74, 77

Upvotes: 1

Related Questions