Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python program to find word score from list of words
Suppose we have a list of words in lowercase letters. We need to find the total score of these words based on specific vowel counting rules.
Scoring Rules
Consider vowels as [a, e, i, o, u, y]
If a word contains an even number of vowels, its score is 2
If a word contains an odd number of vowels, its score is 1
The total score is the sum of all individual word scores
Example Analysis
For words = ["programming", "science", "python", "website", "sky"]:
- "programming" has 3 vowels (o, a, i) ? odd ? score = 1
- "science" has 3 vowels (i, e, e) ? odd ? score = 1
- "python" has 2 vowels (y, o) ? even ? score = 2
- "website" has 3 vowels (e, i, e) ? odd ? score = 1
- "sky" has 1 vowel (y) ? odd ? score = 1
Total score: 1 + 1 + 2 + 1 + 1 = 6
Solution Algorithm
Here's the step-by-step approach ?
def solve(words):
score = 0
vowels = ['a', 'e', 'i', 'o', 'u', 'y']
for word in words:
num_vowels = 0
for letter in word:
if letter in vowels:
num_vowels += 1
if num_vowels % 2 == 0:
score += 2
else:
score += 1
return score
words = ["programming", "science", "python", "website", "sky"]
print(solve(words))
6
Optimized Solution Using List Comprehension
We can make the code more concise using Python's built-in functions ?
def solve_optimized(words):
vowels = set('aeiouy')
total_score = 0
for word in words:
vowel_count = sum(1 for letter in word if letter in vowels)
total_score += 2 if vowel_count % 2 == 0 else 1
return total_score
words = ["programming", "science", "python", "website", "sky"]
print(solve_optimized(words))
6
Step-by-Step Breakdown
Let's trace through the algorithm with detailed output ?
def solve_with_details(words):
vowels = set('aeiouy')
total_score = 0
for word in words:
vowel_count = sum(1 for letter in word if letter in vowels)
word_score = 2 if vowel_count % 2 == 0 else 1
total_score += word_score
print(f"'{word}': {vowel_count} vowels ? score = {word_score}")
return total_score
words = ["programming", "science", "python", "website", "sky"]
result = solve_with_details(words)
print(f"\nTotal score: {result}")
'programming': 3 vowels ? score = 1 'science': 3 vowels ? score = 1 'python': 2 vowels ? score = 2 'website': 3 vowels ? score = 1 'sky': 1 vowels ? score = 1 Total score: 6
Conclusion
The word scoring algorithm counts vowels in each word and assigns scores based on even/odd vowel counts. Use a set for vowels to improve lookup efficiency, and consider list comprehensions for more concise code.
