Search code examples
pythoncode-complexity

Shortening down this specific code


I have been studying Python for a couple of weeks now, and just after easter, will be having a controlled assesment that will count towards my GCSE grade, for which I will be also marked for the criteria of something like the lentgh of my code.

The question was: Write a Python program that asks the user for a word, then calculates the prints the vowel value of the word entered.

What I want to know:

Is there anyway of shortening down this code?

And also:

How can the program be executed without printing out the "word" variable?

Above I have been given a rubric that I used in the code (in the control flow part).

score = 0

word = str(input("Input a word: "))

c = 0
for letter in word:
        print(word[c])
        c = c + 1
        if letter == "a":
                score = score + 5
        if letter == "e":
                score = score + 4
        if letter == "i":
                score = score + 3
        if letter == "o":
                score = score + 2
        if letter == "u":
                score = score + 1

print("\nThe score for your word is: " + score)

Solution

  • You can use sum and a dict, storing vowels as keys and the associated value as the values:

    word = input("Input a word: ")
    
    values = {"a":5,"e":4,"i":3,"o":2,"u":1}
    print(sum(values.get(ch,0) for ch in word))
    

    values.get(ch,0) will return 0 as a default value if the ch which is each char in the word is not a vowel therefore not in our dict.

    sum(values.get(ch,0) for ch in word) is a generator expression where the variables are evaluated lazily when the next() method is called for generator object

    In relation to your own code you should use if/elif's. A character can only have one value, if's are always evaluated but elif's are only evaluated if the previous statement evaluates to False:

    score = 0
     # already a str in python3 use raw_input in python2
    word = input("Input a word: ")
    
    for letter in word:
            if letter == "a":
                score += 5 # augmented assignment same as score = score + 5
            elif letter == "e":
                score += 4
            elif letter == "i":
                score += 3
            elif letter == "o":
                score += 2
            elif letter == "u":
                score += 1