是否有另一种更简单的编码方式,可以基本检查字符串'abcde'
的每个字符?
if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
return True
是否有另一种更简单的编码方式,可以基本检查字符串'abcde'
的每个字符?
if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
return True
这应该做与您输入的相同的事情。
return 'abcde'.startswith(input)
"abcde".startswith("") == True
,这与示例代码不太匹配。 - Joeand input
。 - duckboycool不要将变量命名为input
,因为它会遮盖内置函数input()
。这被认为是一种不好的做法,而且很容易选择另一个变量名。
您可以使用集合来检查输入是否与任何子字符串匹配:
lookups = {'a', 'ab', 'abc', 'abcd', 'abcde'}
my_input = input()
if my_input in lookups:
return True
我们也可以使用集合推导式生成该集合:characters = 'abcde'
lookups = {characters[:i] for i in range(1, len(characters) + 1)}
my_input = input()
if my_input in lookups:
return True
使用集合而不是列表,对于包含大量组合的情况,好处在于你可以获得常数时间 O(1) 的查找速度。这比使用列表要好得多,因为列表会给出线性 O(N) 的查找速度。
有多种可爱的方法可以实现。 startwith
可能是最有效的方法,但这些方法也可以工作:
使用 lstrip
:
return 'abcde'.lstrip(input)!='abcde'
return any(['abcde'[:i+1] == input for i in range(len('abcde'))])
使用正则表达式
:
pattern = re.compile('^'+input)
return bool(pattern.match('abcde'))
或者只是:
return 'abcde'[:len(input)]==input
bool(pattern.match(...))
。 - Asocia您可以尝试类似于以下方式:
def your_function():
# Add as much chars that you want here
chars = "abcde"
# Assuming you are taking the user input from terminal
user_input = input()
# Loop over every substring from chars
for i in range(len(chars) + 1):
if chars[:i] == user_input:
return True
return False
如果这有帮到你,请让我知道!
If input in ['a', 'ab', 'abc', 'abcd', 'abcde']:
return True
else:
return False
input=='de'
? - McLovininput
作为您的变量名称。 - Diptangsu Goswami