0

I am trying ti convert digit into its spelling alphabet and using dictionary and then pick string

how can i store each user entered number spelling string from dict into list. here is what i tried

num2words = {1: 'One', 2: 'Two', 3: 'Three', 4: 'Four', 5: 'Five', \
             6: 'Six', 7: 'Seven', 8: 'Eight', 9: 'Nine', 10: 'Ten', \
            11: 'Eleven', 12: 'Twelve', 13: 'Thirteen', 14: 'Fourteen', \
            15: 'Fifteen', 16: 'Sixteen', 17: 'Seventeen', 18: 'Eighteen', \
            19: 'Nineteen', 20: 'Twenty', 30: 'Thirty', 40: 'Forty', \
            50: 'Fifty', 60: 'Sixty', 70: 'Seventy', 80: 'Eighty', \
            90: 'Ninety', 0: 'Zero'}
            
def n2w(n):
        try:
            return num2words[n]
        except KeyError:
            try:
                return num2words[n-n%10] + num2words[n%10].lower()
            except KeyError:
                return 'Number out of range'            

n = int(input())
values = list(map(int , input().split()))
x = []
for i in value:
    x.append(n2w(i))

Suppose i have vowels ['a' , 'e' , 'i' , 'o' , 'u'] predefined list now i want to count the number of vowels x ? How it can be implemented?

  • 1
    what has all that num2words to do with counting vowels? [mre] please. Also: look into `num2words.get(n, num2words[n-n%10] + num2words[n%10].lower())` – Patrick Artner Aug 16 '20 at 08:29
  • Dupe: shows how its done for every string. Do it for every string in your list and add them up and you are done. – Patrick Artner Aug 16 '20 at 08:33

2 Answers2

0

If I understood you correctly you want to count the number of vowels in a string. This is a very simple approach:

VOWELS = ['a', 'e', 'i', 'o', 'u']
input_string = "test string"

n = 0
for char in input_string:
    if char in VOWELS:
        n += 1

print(n)

If you want a more sophisticated and elegant approach as stated by @PatrickArtner

n = sum(v in VOWELS for v in input_string)
Erich
  • 1,838
  • 16
  • 20
0

add this code to your program:

vowels=['a' , 'e' , 'i' , 'o' , 'u']
string='your string'
n=0
for vowel in vowels:
    n+=string.count(vowel)
  • 2
    that takes 5*n passes through the input - so if you input a 1 million characters long word, it checks 5 million characters which is kind of inefficient. – Patrick Artner Aug 16 '20 at 08:32