[英]How to use recursion to give the minimum integer in a list using python?
I am trying to write a recursive function called my_minimum
that receives a list of integers as parameter and returns the minimum stored in the list.我正在尝试编写一个名为my_minimum
的递归 function ,它接收整数列表作为参数并返回存储在列表中的最小值。 I am able to get the user to input integers separated by a space.我能够让用户输入用空格分隔的整数。 However, it gives me a number totally unrelated to what I am trying to achieve.但是,它给了我一个与我想要实现的目标完全无关的数字。
For example if user list was: 67 89 45 34 23 3 45 67 78
, it should give me give me 3 instead of 23.例如,如果用户列表是: 67 89 45 34 23 3 45 67 78
,它应该给我 3 而不是 23。
def my_minimum(A, n):
# if size = 0 means whole list
# also if it has been traversed
if (n == 1):
return A[0]
return min(A[n - 1], my_minimum(A, n - 1))
# Driver Code
if __name__ == '__main__':
input_string= input("Enter a list element separated by space: ")
A = input_string.split()
n = len(A)
print(my_minimum(A, n))
This is a string comparison issue, not an issue with your recursion.这是一个字符串比较问题,而不是您的递归问题。 The string "3"
compares as greater than the string "23"
, just like "B"
sorts after "AA"
in lexicographical order.字符串"3"
比较大于字符串"23"
,就像"B"
按字典顺序排在"AA"
之后一样。
Try converting your strings to integers if you want integer ordering:如果您想要 integer 排序,请尝试将您的字符串转换为整数:
A = list(map(int, input_string.split()))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.