Cabbage55 Cabbage55 - 3 years ago 65
Python Question

How to get "valid"/"invalid" output from a list of letters that will constitute output?

fly= input("give me an input")
list=["f","r","u","i","t"]

letter=0
for i in list:
if i==(fly(letter)):
print("valid")
letter +=1
else:
print("invalid")


The output should show whether the word is valid based on the letters it contains.

I'm fairly new at Python. I would like to find out if the output is valid or not when the input can only be composed of letters "f","r","u","i" and "t" and if another letter is written in input the outcome should be invalid.So any displacement of word fruit is valid but if input is "tfruh" then it should show invalid due to an unwanted letter "h". However not all letters have to be included so input can be "fru" and should be valid. Also how can I find the position of the invalid character and print it?

Answer Source

The efficient way to test if a character is valid is to use a set of valid letters. And we can use the built-in enumerate function to get the characters in a word and their positions at the same time.

allowed = set('fruit')

words = ('fitur', 'iursfgt', 'ffrruuiitt', 'FRUIT')
for word in words:
    print(word)
    valid = True
    for i, c in enumerate(word):
        if c not in allowed:
            print('Bad char', c, 'at position', i)
            valid = False
    if valid:
        print(word, 'is valid\n') 
    else:
        print(word, 'is invalid\n') 

output

fitur
fitur is valid

iursfgt
Bad char s at position 3
Bad char g at position 5
iursfgt is invalid

ffrruuiitt
ffrruuiitt is valid

FRUIT
Bad char F at position 0
Bad char R at position 1
Bad char U at position 2
Bad char I at position 3
Bad char T at position 4
FRUIT is invalid

If you aren't permitted to use enumerate, you could do this using indirect iteration, by looping over a range, and using that to index into the word. And you don't need to use a set for the allowed letters, you can just use a string, or a list.

allowed = 'fruit'
words = ('fitur', 'iursfgt', 'ffrruuiitt', 'FRUIT')
for word in words:
    print(word)
    valid = True
    for i in range(len(word)):
        c = word[i]
        if c not in allowed:
            print('Bad char', c, 'at position', i)
            valid = False
    if valid:
        print(word, 'is valid\n') 
    else:
        print(word, 'is invalid\n') 

This code produces the same output as the earlier version.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download