Home > Back-end >  Delete repeated vowels in string
Delete repeated vowels in string

Time:11-03

Here is my code:

def del_rep_vow(s):
    '''
    >>> del_rep_vow('adaptation')
    'adpttion'
    >>> del_rep_vow('repetitions')
    'reptitons'
    >>> del_rep_vow('kingkong')
    'kingkong'
    >>> del_rep_vow('aeiouaeiou')
    'aeiou'
    '''
    final_list = []
    for i in s:
        if i not in final_list:
            final_list.append(i)
    return ''.join(final_list)

if __name__ == "__main__":
    import doctest
    doctest.testmod(verbose=True)

I don't know how to make the restriction that only repeated vowels have to be deleted once they are in the list. Any help will be very welcome.

Output of 'adaptation' must be 'adpttion', for example.

CodePudding user response:

I feel this is pretty concise:

def del_rep_vow(s):
    for ch in 'eaiou':
        if ch in s:
            i = s.index(ch)   1
            s = s[:i]   s[i:].replace(ch, '')
    return s


print(del_rep_vow('adaptation'))
print(del_rep_vow('repetitions'))
print(del_rep_vow('kingkong'))
print(del_rep_vow('aeiouaeiou'))

Result:

adpttion
reptitons
kingkong
aeiou

CodePudding user response:

You should maintain a Python set of vowel characters already seen. For each new encountered letter as you walk down the string, only append a vowel if it is not in the set.

def del_rep_vow(s):
    vowels_seen = set([])
    final_list = []
    for i in s:
        if i in ['a', 'e', 'i', 'o', 'u']:
            if i not in vowels_seen:
                final_list.append(i)
                vowels_seen.add(i)
        else:
            final_list.append(i)

    return ''.join(final_list)

print(del_rep_vow('adaptation'))  # 'adpttion'
print(del_rep_vow('repetitions')) # 'reptitons'
print(del_rep_vow('kingkong'))    # 'kingkong'
print(del_rep_vow('aeiouaeiou'))  # 'aeiou'

CodePudding user response:

You can maintain 2 lists of letters: one for the vowels you have seen so far, and other for the remaining letters in the string.

vowels = []
remaining = []
for c in s:
    if c in 'aeiou':
        if c in vowels:
            continue
        vowels.append(c)
    remaining.append(c)

CodePudding user response:

Here's another approach

def del_repts(x):
    vowels = 'aeiou'
    foundVowels = ''
    rslt = ''
    for c in x:
        if c in vowels:
            if c not in foundVowels:
                rslt  = c
                foundVowels  = c
        else:
            rslt  = c
    return rslt  

inl = ['adaptation', 'repetitions', 'kingkong', 'aeiouaeiou']
for itm in inl:
    print(f'{itm}\t->\t{del_repts(itm)}' )  

Yields:

adaptation  ->  adpttion
repetitions ->  reptitons
kingkong    ->  kingkong
aeiouaeiou  ->  aeiou
  • Related