def gt(nums, n):
for c in nums:
if max(nums) > n:
return True
elif max(nums) < n:
return False
elif not nums:
return False
Run Code Online (Sandbox Code Playgroud)
对于最后一个elif,它应该验证nums列表是否为空.但不适合我.有谁知道我可以用什么代码检查列表是否为空?谢谢.
您的方法可以简化为:
def gt(nums, n):
return max(nums) > n if nums else False
>>> gt([],0)
False
>>> gt([1,2,3],6)
False
>>> gt([1,2,3],1)
True
Run Code Online (Sandbox Code Playgroud)
你需要先检查一下not nums.而且你不需要for循环.
请注意,这(与您的代码一样)没有显式检查max(nums) == n,False在这种情况下返回(我认为应该是被调用函数的正确行为gt()):
def gt(nums, n):
if not nums:
return False
return max(nums) > n
Run Code Online (Sandbox Code Playgroud)
编辑:一些时间(Python 2.7.3):
>>> import timeit
>>> all = """l = list(range(100))
... rl = list(reversed(range(100)))
... """
>>> tim = all + """def gt(nums, n):
... if not nums:
... return False
... return max(nums) > n"""
>>> gnibbler = all + """def gt(nums, n):
... return any(x>n for x in nums)"""
>>> burhan = all + """def gt(nums, n):
... return max(nums) > n if nums else False"""
>>> # Test with the condition being False:
... timeit.timeit(setup=tim, stmt="gt(l, 100)")
3.011574096311698
>>> timeit.timeit(setup=gnibbler, stmt="gt(l, 100)")
8.00847921677337
>>> timeit.timeit(setup=burhan, stmt="gt(l, 100)")
2.9805757305956178
>>> timeit.timeit(setup=tim, stmt="gt(rl, 100)")
2.8600606448831307
>>> timeit.timeit(setup=gnibbler, stmt="gt(l, 100)")
7.997938412127745
>>> timeit.timeit(setup=burhan, stmt="gt(l, 100)")
3.032805185133668
>>> # Now what if the condition is True?
... timeit.timeit(setup=tim, stmt="gt(l, 98)")
2.98623750798793
>>> timeit.timeit(setup=gnibbler, stmt="gt(l, 98)")
8.265056412191534
>>> timeit.timeit(setup=burhan, stmt="gt(l, 98)")
2.9731271156252888
>>> timeit.timeit(setup=tim, stmt="gt(rl, 98)")
2.8777295865334764
>>> timeit.timeit(setup=gnibbler, stmt="gt(rl, 98)")
1.0481696827076092
>>> timeit.timeit(setup=burhan, stmt="gt(rl, 98)")
2.8776150752220246
Run Code Online (Sandbox Code Playgroud)
所以Burhan和我的解决方案在速度方面是相同的(不是很令人惊讶,因为它们完全相同,我的只是更冗长),只有当列表足够长时,gnibbler才会明显更快(我已经删除了之前的当列表仅包含十个项目时,时间始终较慢的时间,条件评估为,True 并且 在列表中很早就达到搜索值.否则,所有Python级别的比较都会减慢它的速度.