30

Is there another simpler way to write code that basically checks every character of the string 'abcde'

if input == 'a' or input == 'ab' or input == 'abc' or input == 'abcd' or input == 'abcde':
    return True
Georgy
  • 12,464
  • 7
  • 65
  • 73
vsc
  • 349
  • 2
  • 6

5 Answers5

37

This should do the same thing as what you put.

return 'abcde'.startswith(input)
duckboycool
  • 2,425
  • 2
  • 8
  • 23
  • 1
    From the description, it's not clear what the result for the empty string should be, `"abcde".startswith("") == True`, which doesn't quite match the example code – Joe May 18 '20 at 23:13
  • 2
    Yeah, if you want to not include empty strings, I think the best thing would be adding an `and input`. – duckboycool May 19 '20 at 01:09
12

Don't name variables input, since it will shadow the builtin function input(). Its considered bad practice to do this, and easy enough to just choose another variable name.

You could use a set to check if the input matches any of the substrings:

lookups = {'a', 'ab', 'abc', 'abcd', 'abcde'}

my_input = input()

if my_input in lookups:
    return True

We could also generate this set using a set comprehension:

characters = 'abcde'

lookups = {characters[:i] for i in range(1, len(characters) + 1)}

my_input = input()

if my_input in lookups:
    return True

For large sets of combinations, the benefit of using a set over a list is that you get constant time O(1) lookups for searching. This is much better than using a list, which will give you linear O(N) lookups.

RoadRunner
  • 25,803
  • 6
  • 42
  • 75
6

There are multiple cute ways to do it. startwith is probably the most efficient one, but these should work too:

using lstrip:

return 'abcde'.lstrip(input)!='abcde'

using list comprehension:

return any(['abcde'[:i+1] == input for i in range(len('abcde'))])

using regex:

   pattern = re.compile('^'+input)
   return bool(pattern.match('abcde'))

or just:

  return 'abcde'[:len(input)]==input
Binyamin Even
  • 3,318
  • 1
  • 18
  • 45
  • What is `not not pattern.match(...)`? If you did it just to convert match to a bool you could use `bool` directly: `bool(pattern.match(...))` – Asocia Jun 14 '20 at 18:45
5

You could probably try something like this:

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

Let me know if this helps!

Diptangsu Goswami
  • 5,554
  • 3
  • 25
  • 36
EnriqueBet
  • 1,482
  • 2
  • 15
  • 23
0

You can try this:

If input in ['a', 'ab', 'abc', 'abcd', 'abcde']:
    return True
else:
   return False
Houda
  • 671
  • 6
  • 16