我的函数返回一个列表,但是无法返回列表的长度。
当我返回列表本身(在下面的代码中注释)时,它是成功的,但是在尝试返回列表的长度时却失败了,但这通常可以与我使用的其他列表一起使用?!!
我尝试使用一个计数变量,每次将一个子列表添加到列表中时,该变量都会增加1,但是在尝试打印计数时,仍然会出现以下错误。您也可以在代码中看到它的注释。
def count_combinations(number, integers_available, integers):
combination_set = []
# count = 0
if sum(integers) == number:
combination_set.append(integers)
# count += 1
elif sum(integers) > number:
pass
elif integers_available == []:
pass
else:
for c in count_combinations(number, integers_available[:], integers+[integers_available[0]]):
combination_set.append(c)
# count += 1
for c in count_combinations(number, integers_available[1:], integers):
combination_set.append(c)
# count += 1
return len(combination_set)
# return combination_set
# return count
# Testing the code
number = 10
integers_available = [5, 2, 3]
print(count_combinations(number, integers_available, []))
我希望结果是4,因为列表是:
[[5,5],[5,2,3],[2,2,2,2,2],[2,2,3,3]]
但是出现以下错误:
Traceback (most recent call last):
File "ask.py", line 22, in <module>
print(count_combinations(number, integers_available, []))
File "ask.py", line 12, in count_combinations
for c in count_combinations(number, integers_available[:], integers+[integers_available[0]]):
File "ask.py", line 12, in count_combinations
for c in count_combinations(number, integers_available[:], integers+[integers_available[0]]):
TypeError: 'int' object is not iterable
答案 0 :(得分:1)
您的函数是递归的。您可以等待在工作结束时将列表转换为长度,例如:
def get_combinations(number, integers_available, integers):
combination_set = []
# count = 0
if sum(integers) == number:
combination_set.append(integers)
# count += 1
elif sum(integers) > number:
pass
elif integers_available == []:
pass
else:
for c in get_combinations(number, integers_available[:],
integers + [integers_available[0]]):
combination_set.append(c)
# count += 1
for c in get_combinations(number, integers_available[1:],
integers):
combination_set.append(c)
# count += 1
return combination_set
def count_combinations(number, integers_available, integers):
return len(get_combinations(number, integers_available, integers))
# Testing the code
number = 10
integers_available = [5, 2, 3]
print(count_combinations(number, integers_available, []))
答案 1 :(得分:0)
您将get_combinations(number, integers_available, integers)
用作递归函数,因此此函数返回return len(combination_set)
列表combination_set = []
的长度。当您使用
for c in get_combinations(number, integers_available[:],
integers + [integers_available[0]]):
由于该函数返回的是列表长度的整数,因此上述每个循环均表示
for c in len(combination_set):
注意:
可以说长度为4
for c in 4: # throws 'int' object is not iterable exception.
所以您的函数应该返回列表而不是列表的长度
应该是return combination_set
答案 2 :(得分:0)
让我们假设该数字在非0时有效,然后您可以尝试以下代码:
def get_combinations2(number, integers_available, integers):
return len(integers_available)+len(integers)+1 if number != 0 else len(integers_available)+len(integers)