Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to get a specific output from different elements of a list?

I want to get a specific output for an element which doesn't belong in a list, I wish to perform the following function: I have defined a list(lst1) ,the program then asks for an input from the user and then converts the given integer to a list and compares the input to lst1. If the elements don't match correctly (even 1) then the program prints that the specific element doesn't belong in the given list (example showed below):

lst1=[1,2,3]

a=int(input())

b=a.split()

now for eg i enter 234

i wish to get an output:

'4' does not belong in lst1
like image 960
Aaryansh Sahay Avatar asked Jan 25 '23 07:01

Aaryansh Sahay


1 Answers

The following should do the trick:

lst1=[1,2,3]
a=int(input())

user_input = [int(i) for i in str(a)]

for num in user_input: 
    if num not in lst1:
        raise ValueError(f"{num} does not belong to lst1")

Alternatively, you can use set difference:

lst1=[1,2,3]
a=int(input())

user_input = [int(i) for i in str(a)]

if len(set(user_input) - set(lst1)) > 0:
    raise ValueError("...")

EDIT

If you want to handle multiple user inputs the following will do the trick:

lst1=[1,2,3]
a = input().split(' ')

user_input = [int(i) for i in a]

for _input in user_input:
    for num in [int(i) for i in str(_input)]:
        if num not in lst1:
            print(f"{num} does not belong to lst1")

or

lst1=[1,2,3]
a = input().split(' ')

user_input = [int(i) for i in a]

for _input in user_input:
    num = [int(i) for i in str(_input)]

    diff = set(num) - set(lst1)
    if len(diff) > 0:
        print(f"The following numbers are invalid: {diff}")
like image 163
Giorgos Myrianthous Avatar answered May 21 '23 08:05

Giorgos Myrianthous