'Python Count Letters in Word
I am looking to complete this code but cannot get it to execute the right way. The program connects two user-inputted names into one full name and then looks for the number of occurrences of the letters in the word "True" and letters in the word "Love" within that full name.
I know this is possible using the count() function but I am looking for a different way to solve this. So far I have the below written out but cannot get the program to actually record the numbers correctly. Any help is greatly appreciated!
CODE
print("Welcome to the Love Calculator!")
name1 = input("What is your name? \n")
name2 = input("What is their name? \n")
full_name = name1.lower() + name2.lower()
true_total, love_total = 0,0
x, y = 0,0
true = ['t', 'r', 'u', 'e']
love = ['l', 'o', 'v', 'e']
for i in full_name:
if i == true[x]:
true_total = true_total + 1
x = x + 1
for i in full_name:
if i == love[y]:
love_total = love_total + 1
y = y + 1
score = str(true_total) + str(love_total)
int_score = int(score)
if int_score < 10 or int_score > 90:
print('Your score is ' + score + ', you go together like coke and mentos.')
elif 40 < int_score < 50:
print('Your score is ' + score + ', you are alright together.')
else:
print('Your score is ' + score + '.')
Solution 1:[1]
You can use in
operator to determine whether or not a string is a substring of another string.
So, it needs to be like this
for i in full_name:
if i in true:
true_total = true_total + 1
for i in full_name:
if i in love:
love_total = love_total + 1
Solution 2:[2]
You can use comprehensions to count the number of occurrences. Here is my choice:
result_true = {char: full_name.count(char) for char in set(true)}
And then sum up the values of the dictionary.
score = sum(result_true.values())
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Python learner |
Solution 2 | sipi09 |