0

到目前为止我所拥有的几乎什么都没做

def dress_me(shirt, tie, suit):


 #    if type(shirt) != list or type(tie) != list or type(suit) != list:
    #        return None
            combinations = dress_me(shirt, tie, suit)
            for combo in combinations:
                print(combo)
4

4 回答 4

4

使用itertools.product

def dress_me(shirt, tie, suit):
    if type(shirt) != list or type(tie) != list or type(suit) != list:
        return None
    return list(itertools.product(shirt, tie, suit))

演示:

>>> dress_me([1,2,3],[4,5,6],[7,8,9])
[(1, 4, 7), (1, 4, 8), (1, 4, 9), (1, 5, 7), (1, 5, 8), (1, 5, 9), (1, 6, 7), (1, 6, 8), (1, 6, 9), (2, 4, 7), (2, 4, 8), (2, 4, 9), (2, 5, 7), (2, 5, 8), (2, 5, 9), (2, 6, 7), (2, 6, 8), (2, 6, 9), (3, 4, 7), (3, 4, 8), (3, 4, 9), (3, 5, 7), (3, 5, 8), (3, 5, 9), (3, 6, 7), (3, 6, 8), (3, 6, 9)]
于 2013-08-08T06:43:40.017 回答
1

或者,为了完整起见,在没有额外功能的生成器样式中:

import itertools

for combination in itertools.product(shirts, ties, suits):
    whatever_you_want_to_do(combination)
于 2013-08-08T06:51:13.870 回答
0
def dress_me(shirt, tie, suit):
    all_combinations = []
    for s in shirt:
        for t in tie:
            for su in suit:
                all_combinations.append((s,t,su))
    return all_combination

也许有一种更pythonic的方式来做到这一点:)

于 2013-08-08T06:46:18.243 回答
0

由于看起来您正在尝试提出递归解决方案,因此这是它的一般形式:

def all_perms(thing):
    if len(thing) <=1:
        yield thing
    else:
        for perm in all_perms(thing[1:]):
            for i in range(len(perm)+1):
                yield perm[:i] + thing[0:1] + perm[i:]

这适用于大多数类型的迭代。演示:

In [5]: list(all_perms(('shirt','tie','suit')))
Out[5]: 
[('shirt', 'tie', 'suit'),
 ('tie', 'shirt', 'suit'),
 ('tie', 'suit', 'shirt'),
 ('shirt', 'suit', 'tie'),
 ('suit', 'shirt', 'tie'),
 ('suit', 'tie', 'shirt')]

递归一开始很难理解,但一般形式是:

if simplest_case:
    return simplest_case
else:
    #recurse

在这种情况下,return被替换为yield是为了制作一个对内存更友好的生成器。您仍然不应该期望这是性能最好的解决方案,但我将其包括在内是为了完整性,因为“使用 ITERTOOLS”除了 itertools 很酷之外,最终并没有教给您很多东西。

于 2013-08-08T07:16:33.453 回答