[英]Recursion and finding the largest number
So I am trying to use recursion to find the largest number in my program. 因此,我尝试使用递归在程序中找到最大的数字。 I have to import one file into the other.
我必须将一个文件导入另一个文件。
Here is the code I have so far: 这是我到目前为止的代码:
def find_largest():
numlist = [0]
if numlist == 1:
return numlist[0]
else:
m = find_largest(numlist[0])
return m if m > numlist[0] else numlist[0]
find_largest()
That is the file calling the recursion. 那就是调用递归的文件。 This is the main that will import it and establish the list.
这是将其导入并建立列表的主要对象。
import Collins_find_largest #file name to be imported
def main():
number_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
print('List of numbers:\n', number_list, sep ='')
print("largest Number in the list is: ", \
Collins_find_largest.find_largest(number_list))
main()
When I run my code it comes back saying line m=find_largest(numlist[0]) takes 0 positional arguments but 1 was given. 当我运行我的代码时,它会回来说行m = find_largest(numlist [0])接受0个位置参数,但给出了1个。
Help Please! 请帮助!
You're missing a parameter in your function: 您在函数中缺少参数:
def find_largest(numlist=None):
numlist = numlist or [0]
if numlist == 1:
return numlist[0]
else:
m = find_largest(numlist[0])
return m if m > numlist[0] else numlist[0]
There are a few issues with your code, mainly you are missing num_list
as a parameter: 您的代码存在一些问题,主要是您缺少
num_list
作为参数:
def find_largest(num_list):
if len(num_list) == 1:
return num_list[0]
else:
m = find_largest(num_list[1:])
return m if m > num_list[0] else num_list[0]
result = find_largest([1, 2, 3, 4])
print(result)
Output 产量
4
Second when checking for the length of a list use len , finally you need to make the recursive call on the rest of the list ( num_list[1:]
). 其次,使用len检查列表的长度时,最后需要对列表的其余部分(
num_list[1:]
)进行递归调用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.