0
4

3 回答 3

1

Your code isn't working in those cases because your while loop never ends. Once that for loop exits, the while loop just keeps going forever.

To fix your code, just set flag = False once the for loop ends:

def vowels_or_not (st, ch):
    vowels = ('a','e','i','o','u','A','E','I','O','U')
    flag = True
    a = 0
    aux = ''
    while flag is True:
        for i in range(len(st)):        
            if (st[i] == ch):
                flag = False
                break
            else:
                if (st[i] in vowels):
                    aux = aux + st[i]
                    a = a + 1
                if (st[i] not in vowels):
                    aux = aux + '$'
                    a = a + 1

        flag = False   # <-- Right here
    return aux

And an example:

>>> vowels_or_not('a', 'x')
'a'
>>> vowels_or_not('x', 'a')
'$'

To make your code a little better, don't use indices. Python lets you iterate over strings intuitively:

def vowels_or_not(word, character):
    vowels = 'aeiou'
    output = ''

    before, middle, after = word.partition(character)

    for letter in before:
        if letter.lower() in vowels:
            output += letter
        else:
            output += '$'

    return output + middle + after
于 2012-11-01T05:41:42.690 回答
0

Your problem is your while loop never ends if the last character in st isn't the same as ch.

But you don't really need that while loop as it is redundant, you only need the for-loop:

def vowels_or_not(st, ch):
    vowels = ('a','e','i','o','u','A','E','I','O','U')
    a = 0
    aux = ''
    for i in range(len(st)):
        if (st[i] == ch):
            break
        else:
            if (st[i] in vowels):
                aux = aux + st[i]
                a = a + 1
            if (st[i] not in vowels):
                aux = aux + '$'
                a = a + 1
    return aux

>>> vowels_or_not('a', 'X')
'a'
>>> vowels_or_not('aaaAX', 'X')
'aaaA'
>>> vowels_or_not('aaabX', 'X')
'aaa$'
于 2012-11-01T05:45:14.227 回答
0
import functools # for python3 reduce (working under python2 too)

vowels = 'aeiouAEIOU'

def vowels_or_not (st, ch):
    return functools.reduce(lambda a,b:a+(b in vowels and b or '$'), st.partition(ch)[0],'')

or longer version

vowels = 'aeiouAEIOU'

def vowels_or_not_longer_version (st, ch):
    ret=''
    for i in st.partition(ch)[0]:
        ret+= i in vowels and i or '$'
    return ret
于 2012-11-01T09:58:19.897 回答