[英]Checking if a list contains 1, 2, or 3
The function below always returns false.下面的 function 总是返回 false。 I want to take a list as input and then find if it contains 1,2 and 3?
我想将一个列表作为输入,然后查找它是否包含 1,2 和 3?
def arrayCheck(nums):
# CODE GOES HERE
if (1 in nums) and (2 in nums) and (3 in nums):
return True
else:
return False
arr = input() # takes a list as input
x = set(arr) # coverts it into array
result = arrayCheck(x)
print(result)
I want to search the numbers 1,2 and 3 in a user defined list.我想在用户定义的列表中搜索数字 1,2 和 3。 So I converted the list into a set for having unique elements.
因此,我将列表转换为具有独特元素的集合。 Further I have used
in
method to search for the items.此外,我还使用
in
方法来搜索项目。 The problem is it returns false every time.问题是它每次都返回false。
Your function works, you are inputting wrong data ( arrayCheck([1, 2, 3])
returns True
).您的 function 有效,您输入了错误的数据(
arrayCheck([1, 2, 3])
返回True
)。
You can't take a list as input.您不能将列表作为输入。 Converting a string to a set will separate the characters to a set, which isn't what you want (
set("hello") == {'h', 'l', 'o', 'e'}
), so you have to input a list of ints.将字符串转换为集合会将字符分隔为集合,这不是您想要的(
set("hello") == {'h', 'l', 'o', 'e'}
),所以你必须输入一个整数列表。
Something like this:像这样的东西:
inp = input().split(",")
inp = [int(i) for i in inp] # Convert all the values to ints
print(arrayCheck(inp))
and providing 1,2,3,4
as input will work.并提供
1,2,3,4
作为输入将起作用。
By the way, you can return bools in functions:顺便说一句,您可以在函数中返回布尔值:
def arrayCheck(nums):
return (1 in nums) and (2 in nums) and (3 in nums)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.