最大组合数 [英] maximum number combinations

查看:75
本文介绍了最大组合数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用从0到9的所有数字生成一组四个数字中所有可能的数字组合。

I am trying to generate a list of all possible number combinations within a set of four numbers using all numbers from 0 through 9.

我越来越近了,但是输出不会显示从0000一直到9999的所有可能组合。

I'm getting close but the output doesn't show every possible combination starting from 0000 all the way to 9999.

关于以下代码为何删除某些组合的任何线索?

Any clues as to why the following code is dropping certain combinations?


def permgen(items, n):
  if n==0: yield []
    else:
        for i in range(len(items)):
            for cc in permgen(items[:i]+items[i+1:],n-1):
                yield [items[i]]+cc

if __name__=="__main__":
    for c in permgen(['0','1','2','3','4','5','6','7','8','9'],4): print ''.join(c)


推荐答案

此行:

for cc in permgen(items[:i]+items[i+1:],n-1):

您基本上是在说获取数字,而不是从ir中添加另一个不同,重复n次,然后重新列出这些数字。这将为您提供数字,其中没有数字出现一次以上。如果将该行更改为:

You're basically saying "get a number, than add another one different from ir, repeat n times, then return a list of these digits. That's going to give you numbers where no digit appears more than once. If you change that line to:

for cc in permgen(items,n-1):

然后您将获得所有组合。

then you get all combinations.

这篇关于最大组合数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆