创建一个函数get_algorithm_result来实现下面的算法
Get a list of numbers L1, L2, L3....LN as argument
Assume L1 is the largest, Largest = L1
Take next number Li from the list and do the following
If Largest is less than Li
Largest = Li
If Li is last number from the list then
return Largest and come out
Else repeat same process starting from step 3
这是我的代码:
def get_algorithm_result(listNumb):
largest = listNumb[0]
i = 1
for i in range(i, len(listNumb)):
if largest < listNumb[i]:
largest = listNumb[i]
i =i + 1
continue
return largest
>>> print( get_algorithm_result([4,7,1,9,12,2,1]) )
4
我错了什么?我希望它返回/打印在get_algorithm_result()上调用的任何给定列表的最大数字。
答案 0 :(得分:0)
该算法会跳过数字,因为它(1)在身体中使用for..in和(2)增量i。
答案 1 :(得分:0)
这是一个经过多次黑客攻击的解决方案:
def get_algorithm_result(listNumb):
largest = listNumb[0]
for i in range(1, len(listNumb)):
if largest < listNumb[i]:
largest = listNumb[i]
continue
return largest
答案 2 :(得分:0)
您无需跟踪或为i
分配值(您根本不需要i
),您只需跟踪哪个值最大:
>>> def get_largest(listNumb):
... largest = listNumb[0] # assume first value is the largest
... for value in listNumb: # Take next number Li from the list
... if largest < value: # If Largest is less than Li
... largest = value # Largest = Li
... return largest
...
>>> get_largest([1,1,1,32,42,5423,-1,4])
5423
答案 3 :(得分:0)
我的解决方案使用while循环。我也试图照顾这些条件: - 如果李是列表中的最后一个号码那么 - 返回最大并出来
...VALUES ('', '$name', '$text', current_timestamp, '$catid', '1')...
答案 4 :(得分:0)
def get_algorithm_result(numbers):
largest = numbers[0]
for i in numbers:
if largest < i:
largest = i
return largest
答案 5 :(得分:0)
算法:
def get_algorithm_result(num_list):
largest =num_list[0]
for item in range(0,len(num_list)):
if largest < num_list[item]:
largest = num_list[item]
return largest