[英]why my program doesn't give the correct answer ( to find second largest in a list) - in python
def calc_largest(arr):
second_largest = arr[0]
largest_val = arr[0]
for i in range(len(arr)):
if arr[i] > largest_val:
largest_val = arr[i]
for i in range(len(arr)):
if arr[i] > second_largest and arr[i] != largest_val:
second_largest = arr[i]
return second_largest
print(calc_largest([20, 30, 40, 25, 10])) # this outputs correct answer
a=[]
n=int(input("Number of elements in array:"))
for i in range(0,n):
l=int(input("Enter the element"))
a.append(l)
print(a)# list is printed properly
print(calc_largest(a))# Always prints the first input entered by me
It's an issue with your indentariin.这是您的印痕的问题。 Your return happens in the for loop after the first iteration.
您的返回发生在第一次迭代后的 for 循环中。 Just move it out.
把它移出来。 Note that you could also get it via second_largest = sorted(arr)[-2]
请注意,您也可以通过 second_largest = sorted(arr)[-2] 获得它
You could do it like this.你可以这样做。
def calc_largest(arr):
return sorted(arr)[-2]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.