Alex Chase Alex Chase - 1 year ago 57
Python Question

Counting number of vowels in a merged string

I am trying to figure out how to calculate the score of two merged lists of names. I need to give one point for each character (including spaces between first and last name) plus one point for each vowel in the name. I can currently calculate score for the the lengths of the names but cannot figure out how to include the number of vowels.

a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]

vowel = ["a", "e", "i", "o", "u"]

gen = ((x, y) for x in a for y in b)

score = 0

for first, second in gen:
print first, second
name = first, second
score = len(first) + len(second) +1
for letter in name:
if letter in vowel:
print score

This is what i currently have and this is the output I get:

John Green
John Fletcher
John Nelson
Kate Green
Kate Fletcher
Kate Nelson
Oli Green
Oli Fletcher
Oli Nelson

This is the output I need:

Full Name: John Green Score: 13
Full Name: John Fletcher Score: 16
Full Name: John Nelson Score: 14
Full Name: Kate Green Score: 14
Full Name: Kate Fletcher Score: 17
Full Name: Kate Nelson Score: 15
Full Name: Oli Green Score: 13
Full Name: Oli Fletcher Score: 16
Full Name: Oli Nelson Score: 14

Answer Source

The reason you're not calculating the vowels is because the score variable is not getting incremented. To increment it, you have to set the variable score to previous score + 1.

This should work:

for letter in name:
    if letter in vowel:

Edit: It's worth writing that score+=1 is the same as score=score+1

I worked out the error - instead of creating name = first, second, initialize name to first+second. You will get the results you want. The reason it was failing is because name=first, second creates a tuple, and iterating through the tuple makes letter = "Kate", "John" etc, and not the actual individual characters.

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