Hi,

I'm trying to write code that will allow me to assign values to lists of strings. I then want to compare user input to the lists and create a scoring system based on what has been typed in. For example if the input contains letters in list1 then the score goes up by 1, if the letters are in list 2 the score goes up by 2 etc. I don't want to use ord to get values for letters because I want the letters to be random and for multiple letters to have the same value like in my lists below. At present my code seems quite long and I have lots of if statements and if I had more lists of letters then the code would be even longer, i'm looking to make it more efficient. Any help would be much appreciated

list1=["t","f","c"]
list2=["b","h","y"]
list3=["q","w","z"]


value=0

word1=input("Please enter a word")

for letter in word1:
    if letter in list1:
        value+=1
    elif letter in list2:
        value+=2
    elif letter in list3:
        value+=3


print(value)

You can use dictionary to simplify your code a bit

dict = {
    "t": 1, "f": 1, "c": 1,
    "b": 2, "h": 2, "y": 2,
    "q": 3, "w": 3, "z": 3
}

value = 0
word1 = input("Please enter a word:")

for letter in word1:
    value += dict.get(letter, 0)

print(value)

and if you want to be even shorter

dict = {
    "t": 1, "f": 1, "c": 1,
    "b": 2, "h": 2, "y": 2,
    "q": 3, "w": 3, "z": 3
}

word1 = input("Please enter a word:")
value = sum([dict.get(x,0) for x in word1])

print(value)
commented: pythonic code +14

You may also use this trick

>>> lett = "tfc bhy qwz".split()
>>> dic = {x: i for i, w in enumerate(lett, 1) for x in w}
>>> dic
{'c': 1, 'b': 2, 'f': 1, 'h': 2, 'q': 3, 't': 1, 'w': 3, 'y': 2, 'z': 3}

Hi,
Thank you for your replies that is exactly what i'm looking for, i've been trying to use a dictionary but have not been able to get it quite right.
invisal, in the code you posted what is the 0 for in this line? Thanks

    value += dict.get(letter, 0)

Is that what gets returned if the letter is not in the dictionary? So if it can't find the letter it adds 0?

Is that what gets returned if the letter is not in the dictionary? So if it can't find the letter it adds 0?

Yes,and you can also return a more meaningful message.
Here in function and return value out.

def record(word):
    return {
        "t": 1, "f": 1, "c": 1,
        "b": 2, "h": 2, "y": 2,
        "q": 3, "w": 3, "z": 3
    }.get(word, "Not in record")

if __name__ == '__main__':
    word = input("Please enter a word: ")
    print(record(word))
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.