簡體   English   中英

如何在python中編寫程序以生成僅以4和7為數字的所有n位數字?

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

我嘗試使用itertools.permutations生成排列,但是我對如何使用n位數字感到困惑。

我會改用itertools.product

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

repeat參數是您的n

我會用二進制的,如果你需要的所有2位數的數字只有74作為數字:

以2為基的最大2位數字是11b3 ,所以:

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

然后將0替換為4 ,將1替換為7 (任意),得到: 44, 47, 74, 77

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM