我需要一些帮助来完成我的任务:
使用for循环,编写一个名为getMax4的函数,该函数接受数字列表。它确定并返回可被4整除的最大数字。 如果参数为空列表,则函数返回-999 如果参数列表中没有数字可被4整除,则该函数返回0。
下面显示了调用该函数时的示例输出:
我已经设法在代码中执行以下操作:
def getMax4(list):
highest = 0
if len(list) == 0:
return -999
else:
for number in list:
if number % 4 == 0:
if number < highest:
highest = number
else:
highest = 0
return number
print(getMax4([]))
print(getMax4([1, 3, 9]))
print(getMax4([-4, 3, -12, -8, 13]))
print(getMax4([1, 16, 18, 12]))
对我来说输出如下:
我不明白为什么将值确定为None
时将其确定为0
。
答案 0 :(得分:2)
让我们逐步执行代码。
def getMax4(list):
highest = 0
if len(list) == 0:
return -999
else:
for number in list:
if number % 4 == 0:
if number < highest:
highest = number
else:
highest = 0
return number
明显的情况是长度为零的列表,它可以正确处理它们。呜呼。
另一种明显的情况是数字被四整除的列表。让我们来看一下:
# imagine getMax4([[1, 16, 20, 12])
# note that this is different from your example, because your example doesn't
# highlight a meaningful bug!
# unroll the for loop:
number = 1
if number % 4 == 0: # it doesn't, so skip
number = 16
if number % 4 == 0:
if number < highest: # it's not, but this should pass. Your comparison is backwards here!
else:
highest = 0 # what?? we reset it?? Why??!
return number
因此,我们已经确定了几个问题,包括以下事实:一旦找到一个可被四整除的数字,即使正确的答案是20,我们也会以该数字作为解决方案。这显然是错误的!
让我们修复这些问题。
def getMax4(list):
highest = 0
if len(list) == 0:
return -999
else:
for number in list:
if number % 4 == 0:
if number > highest: # flip comparison
highest = number
# removed the else clause
return highest # pulled this all the way out past the for loop's end
现在让我们用新代码遍历相同的呼叫
# getMax4([[1, 16, 20, 12])
# unroll the for loop
number = 1
if 1 % 4 == 0: # it's not
number = 16
if 16 % 4 == 0: # it is!
if 16 > 0: # it is!
highest = 16 # remember it
number = 20
if 20 % 4 == 0: # bingo!
if 20 > 16: # yup-a-roonie
highest = 20 # remember this one now. We can forget 16
number = 12
if 12 % 4 == 0: # batting 1.000
if 12 > 20: # not this time, buck-o.
# now we're all done with the for loop, so we step outside and find
return number # which is 20
现在我们可以稍微清理一下:
def getMax4(list):
highest = 0
if len(list) == 0:
return -999
# whenever you have an early-exit conditional, there's no reason to
# write the rest in an `else`. Just omit the `else` and dedent.
for number in list:
if number % 4 == 0:
if number > highest:
highest = number
return highest
答案 1 :(得分:1)
还有一点要提醒,不要使用内置名称作为变量,例如list
,str
,int
,float
,tuple
,{ {1}},如果稍后将这些内置函数调用为函数,则会给您带来讨厌的结果。因此,我建议您将列表更改为数字。
因为只有type
会出现在if语句中,所以:
return number
要返回0:
将if number % 4 == 0:
唯一标识为您的for循环。
就像
return number
答案 2 :(得分:-3)
只需对现有代码稍作更改,返回0即可明确添加。
def getMax4(list):
highest = 0
if len(list) == 0:
return -999
else:
for number in list:
if number % 4 == 0:
if number < highest:
highest = number
else:
highest = 0
return number
return 0