0

How to make input verification in a separate function? the program should take the input sequence 1 and 0

def check(SEQ):
    for i in SEQ:
        isinstance(i, int)
    if not (set(SEQ) == {0, 1} or set(SEQ) == {1} or set(SEQ) == {0}):
        return False
    else:
        return True


def main():
    SEQ = [i for i in input("Enter the sequence 0 and 1   ").split()]
    while not check(SEQ):
        print("Invalid values ")
        SEQ = [i for i in input("Enter the sequence 0 and 1 ").split()]


if __name__ == '__main__':
    main()
3
  • You already have a function called check, that checks the user input. But it can be massively simplified. In the first step do SEQ = list(map(lambda x: int(x), SEQ.split)). Then check if all(map(lambda x: x==1 or x==0, SEQ)) Commented Nov 14, 2019 at 12:05
  • Instead of three cases, why not check if the input is a subset of {0,1}? Also -- you don't need if ... else to convert a boolean into a boolean. Just return the comparison itself. Those 4 lines in the function can be replaced by the 1 line return set(SEQ) <= {0,1} (fine print: this comparison would validate the empty string, but your original code would not. Since the empty string is a binary sequence, albeit a trivial one, this is a feature of my suggestion rather than a bug). Commented Nov 14, 2019 at 12:07
  • As far as the edit goes -- I don't see how an edit which deletes OP's code from a question can be valid. I thus rolled it back. Commented Nov 14, 2019 at 12:15

1 Answer 1

1

Like this:

def check(value):
    return all(map(lambda x: x=='1' or x=='0', value.split()))
Sign up to request clarification or add additional context in comments.

2 Comments

Wouldn't you need to either convert to int or use '0', '1'?
Sorry. Forgot about the type. Changed to string.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.