Reputation: 59
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:
score+1
print score
This is what i currently have and this is the output I get:
John Green
10
John Fletcher
13
John Nelson
11
Kate Green
10
Kate Fletcher
13
Kate Nelson
11
Oli Green
9
Oli Fletcher
12
Oli Nelson
10
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
Upvotes: 3
Views: 124
Reputation: 133624
a = ["John", "Kate", "Oli"]
b = ["Green", "Fletcher", "Nelson"]
vowel = {"a", "e", "i", "o", "u"}
names = (first + ' ' + last for first in a for last in b)
for name in names:
score = len(name) + sum(c in vowel for c in name.lower())
print "Full Name: {name} Score: {score}".format(name=name, score=score)
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
Upvotes: 1
Reputation: 1052
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:
score+=1
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.
Upvotes: 2