Hey guys! I wrote a small program, which works. Unfortunately, when things get too complicated, it breaks down.

The objective is to list the occurrences of vowels in a given word, such that for (word = yellow) and index spits out (e = 1, o = 1)

The code KIND OF does it, but seems to reiterate its objective. Can someone take a look and tell me what I did wrong?

def duplicount():
    import string

    word = raw_input('Please enter your word:')
    vowels = ['a','e','i','o','u']
    count = {}

    for index,letters in enumerate(word):
        if letters in vowels:
            count[letters] = index
            print count


duplicount()

Yes, I searched google. Yes, I searched the forums.

:wub:

Recommended Answers

All 2 Replies

You are printing inside loop instead of out of it, also you only keep the position of last occurance of vowel, use the setdefault method or defaultdict from collections module:

def duplicount():
    import string

    word = raw_input('Please enter your word:')
    vowels = ['a','e','i','o','u']
    count = {}

    for index,letter in enumerate(word):
        if letter in vowels:
            # D.setdefault(k[,d]) -> D.get(k,d), also set D[k]=d if k not in D
            # http://docs.python.org/release/2.5.2/lib/typesmapping.html
            count.setdefault(letter, []).append(index)

    print count
    # one liner for the fancy solution
    print dict((v, [ind for ind, c in enumerate(word) if c==v]) for v in set(word) if v in vowels)


duplicount()
"""Example:
Please enter your word:average
{'a': [0, 4], 'e': [2, 6]}
{'a': [0, 4], 'e': [2, 6]}
"""

The objective is to list the occurrences of vowels in a given word, such that for (word = yellow) and index spits out (e = 1, o = 1)

This (e = 1, o = 1) is not the position/occurrences so I am assuming you want to count the number of times each vowel occurs.

if letters in vowels:
            if letters not in count:
                count[letters]=0     ## add to dictionary, initialize counter to zero

            count[letters] += 1  ## add one to a counter
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.