繁体   English   中英

将具有两个参数的函数转换为只有一个参数

[英]Convert the function on having two parameters to only one parameter

我在这个网站( 列表列表的所有组合)在线找到了这段代码,它获得了列表列表的排列,但我需要它只有一个参数而不是两个参数,但我不知道如何。 有什么帮助吗? 提前致谢! 我必须有函数 combine(terms) 而不是 combine(terms,accum)。

def combine(terms, accum):
    last = (len(terms) == 1)
    n = len(terms[0])
    for i in range(n):
        item = accum + terms[0][i]
        if last:
            combinations.append(item)
        else:
            combine(terms[1:], item)

您可以创建一个包装函数,该函数使用适当的参数调用combine函数。

def combine_wrapper(terms):
    accum = ...
    return combine(terms, accum)

或者你可以使用部分函数(同样与上面类似):

from functools import partial

accum = ...
combine_wrapper = partial(combine, terms)

partial函数将要调用的函数作为引用,传递给它的其余参数直接传递给函数。


PS:我相信您可能有保留原样的限制。 因此,也许您可​​以将原始的combine函数重命名为_combinecombine_main类的其他名称,然后将包装函数命名为combine

约束

  1. 你的函数只能有一个参数
  2. 你不能有默认参数

战略

We change accum into a stack (i.e. list) that contains the values it would
have at various levels of a recursive function

满足约束

def combine(terms):
 
    last = (len(terms) == 1)
    n = len(terms[0])
    
    for i in range(n):
        # use top value in accum stack i.e. accum[-1]
        item = accum[-1] + terms[0][i]
        if last:
            combinations.append(item)
        else:
            # append to accum stack 
            # (similar to what woould happen if we where passing it as a recursive parameter)
            accum.append(item)
            combine(terms[1:])
            
    accum.pop()  # returning from recursive function so remove top
                 # value from stack
     

用法

# Initializations
a = [['ab','cd','ef'],['12','34','56']]
combinations = []
accum = ['']        # stack which will hold accum for diferent levels of recursion
combine(a)
print(combinations)
   

输出

['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']

警告

我不明白你的约束,但函数写得更简单,如下所示。

def combine(terms, accum = None, combinations = None):
    # Assign values for default parameters
    if accum is None:
        accum = ''
    if combinations is None:
        combinations = []
        
    last = (len(terms) == 1)
    n = len(terms[0])
    for i in range(n):
        item = accum + terms[0][i]
        if last:
            combinations.append(item)
        else:
            combine(terms[1:], item, combinations)
            
    return combinations   # we return the combinations rather than using an external global

测试

a = [['ab','cd','ef'],['12','34','56']]
print(combine(a))
# ['ab12', 'ab34', 'ab56', 'cd12', 'cd34', 'cd56', 'ef12', 'ef34', 'ef56']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM