快到了,但一次测试仍然失败
Almost there, but keep failing with one test
我有一个问题是获取一个或多个整数 'nums' 和 returns 的列表,如果序列 [2, 4, 6]
出现在列表中的某处则为真,否则为假.
到目前为止,这是我的功能:
def has246(nums):
num = ""
for i in nums:
num += str(i)
if "2" "4" "6" in num:
return True
else:
return False
对于以下测试,我得到了预期的结果:
print(has246(\[2, 2, 4, 6, 2\]))
True
print(has246(\[2, 2, 4, 8, 2\]))
False
print(has246(\[2, 4\]))
False
但是当预期为 False 时,我得到以下结果为 True:
print(has246(\[24, 6\]))
False
这是因为您直接加入了元素。因此 [24, 6]
加入后变为 '246'
返回 True
。最好的解决方案是使用分隔符加入代码:
def has246(nums):
num = ""
for i in nums:
num += str(i) +' ' # I have used space, you can use a '-' as well
if "2 " "4 " "6 " in num:
return True
else:
return False
print(has246([2, 2, 4, 6, 2]))
print(has246([2, 2, 4, 8, 2]))
print(has246([2, 4]))
print(has246([24, 6]))
这种连接值的方式为您提供 '24 6'
而不是 '246'
并通过搜索 '2 4 6 '
来防止错误
输出:
True
False
False
False
也许尝试搜索实际数字而不是转换为字符串
def has246(nums):
for i in range(len(nums) - 2):
if nums[i:i+3] == [2, 4, 6]:
return True
return False
我有一个问题是获取一个或多个整数 'nums' 和 returns 的列表,如果序列 [2, 4, 6]
出现在列表中的某处则为真,否则为假.
到目前为止,这是我的功能:
def has246(nums):
num = ""
for i in nums:
num += str(i)
if "2" "4" "6" in num:
return True
else:
return False
对于以下测试,我得到了预期的结果:
print(has246(\[2, 2, 4, 6, 2\]))
True
print(has246(\[2, 2, 4, 8, 2\]))
False
print(has246(\[2, 4\]))
False
但是当预期为 False 时,我得到以下结果为 True:
print(has246(\[24, 6\]))
False
这是因为您直接加入了元素。因此 [24, 6]
加入后变为 '246'
返回 True
。最好的解决方案是使用分隔符加入代码:
def has246(nums):
num = ""
for i in nums:
num += str(i) +' ' # I have used space, you can use a '-' as well
if "2 " "4 " "6 " in num:
return True
else:
return False
print(has246([2, 2, 4, 6, 2]))
print(has246([2, 2, 4, 8, 2]))
print(has246([2, 4]))
print(has246([24, 6]))
这种连接值的方式为您提供 '24 6'
而不是 '246'
并通过搜索 '2 4 6 '
来防止错误
输出:
True
False
False
False
也许尝试搜索实际数字而不是转换为字符串
def has246(nums):
for i in range(len(nums) - 2):
if nums[i:i+3] == [2, 4, 6]:
return True
return False