如何在Python中重复辅音,而不是元音

时间:2017-10-22 01:21:23

标签: python string python-3.x

我有两个函数,第一个函数与第二个函数相关,它编码一个字母是元音(True)还是辅音(False)。

cut_tree()

这是我对该功能所具有的功能,但示例失败并且不会跳过元音。

def vowel(c):
    """(str) -> bool
    Return whether the string c is a vowel.
    >>> vowel('e')
    True
    >>> vowel('t')
    False
    """
    for char in c:
        if char.lower() in 'aeiou':
            return True
        else:
            return False


def repeated(s, k):
    """(str) -> str
    Return a string where consonants in the string s is repeated k times.
    >>> repeated('', 24)
    ''
    >>> repeated('eoa', 2)
    'eoa'
    >>> repeated('m', 5)
    'mmmmm'
    >>> repeated('choice', 4)
    'cccchhhhoicccce'
    """
    result = ''

    for c in s:
        if c is not vowel(c):
            result = result + (c * k)
    return result

提前致谢!

1 个答案:

答案 0 :(得分:1)

两件事。在vowel函数中,不需要循环。您正在发送单个字符,因此您只需要检查它:

def vowel(c):
    if c.lower() in 'aeiou':
        return True
    else:
        return False

或者:

def vowel(c):
    return True if c.lower() in 'aeiou' else False

然后,在repeated中,请勿使用c is not vowel(c)。相比之下,c(角色)的身份是否等于True/False。只需直接使用vowel返回的值并有条件地添加到result

def repeated(s, k):
    result = ''
    for c in s:
        if not vowel(c):
            result += (c * k)
        else:
            result += c
    return result