Home > Enterprise >  How to append a letter that comes after vowel letter to a list?
How to append a letter that comes after vowel letter to a list?

Time:11-05

I want to create a dictionary where the keys are the letters 'a' and 'e'. If the character after 'a' or 'e' is a letter, then I want to append it to a list that shouldn't have repetitions.

text= 'there is a sea apple'
    a = []
    e = []
    for i in range(len(text)):
        if text[i 1].isalpha() and i == 'a':
            vowel_dict['a'] = []
            vowel_dict['a'].append(text[i])
        if text[i 1].isalpha() and i == 'e':
            vowel_dict['e'] = []
            vowel_dict['e'].append(text[i])
    print('vowel_dict)

I want my output to be:

{'a': ['p'], 'e': ['r', 'a']}

CodePudding user response:

text= 'there is a sea apple'
    a = []
    e = []
    for i in range(len(text)):
        if text[i 1].isalpha() and i == 'a':
            vowel_dict['a'] = []
            vowel_dict['a'].append(text[i])
        if text[i 1].isalpha() and i == 'e':
            vowel_dict['e'] = []
            vowel_dict['e'].append(text[i])
    print('vowel_dict)
  • produces an IndentationError: unexpected indent because your second and subsequent lines are one indentation level deeper than the previous line for no reason.
  • Additionally: print('vowel_dict) produces a SyntaxError: EOL while scanning string literal because print(vowel_dict).
  • Next you have an IndexError: string index out of range because on the last iteration of the for loop, i == len(text) - 1 and i 1 == len(text) is too big an integer to index into text. To fix this, for i in range(len(text)): should be for i in range(len(text) - 1):.
  • After that you have NameError: name 'vowel_dict' is not defined because you never declare vowel_dict. You must declare a variable before using it. You can do so by doing vowel_dict = {} or vowel_dict = dict() (they're equivalent) before the for loop.
text= 'there is a sea apple'
a = []
e = []
vowel_dict = {}
for i in range(len(text) - 1):
    if text[i 1].isalpha() and i == 'a':
        vowel_dict['a'] = []
        vowel_dict['a'].append(text[i])
    if text[i 1].isalpha() and i == 'e':
        vowel_dict['e'] = []
        vowel_dict['e'].append(text[i])
print(vowel_dict)

Now you should be able to run your code, but it's still not doing the right thing. Play around with it.


Next time, please try to run your code and fix any errors preventing it from running. There are many places online where you can run your code: e.g. repl.it, pythontutor.com, thonny.org (the last two are particularly good for beginners).


Here's one way to do it:

s = 'there is a sea apple'
N = len(s)
a_successors = set()
e_successors = set()

for i in range(N-1):
    curr = s[i]
    after = s[i 1]
    if after.isalpha():
        if curr == 'a':
            a_successors.add(next_)
        elif curr == 'e':
            e_successors.add(next_)
vowel_dict = {'a': a_successors, 'e': e_successors}
print(vowel_dict)

prints:

{'a': {'p'}, 'e': {'r', 'a'}}

If you want a_successors and e_successors as lists, just do list(a_successors)and likewise fore_successors`.

CodePudding user response:

The below is a bit fancier than your solution, as it uses defaultdict, enumerate and a set. It's probably also a bit more "Python-esque".

from collections import defaultdict

text= 'there is a sea apple'

vowels = defaultdict(set)
for i, char in enumerate(text[:-1]):
    if text[i 1].isalpha() and char in 'ae':
        vowels[char].add(text[i 1])
print(vowels)

CodePudding user response:

You can use regex for that to simplify the code, although it can be less efficient:

import re

text = 'there is a sea apple'

d = {k: set(re.findall(rf"{k}(\w)", text)) for k in 'ae'}
print(d) # {'a': {'p'}, 'e': {'r', 'a'}}

CodePudding user response:

You can use a dictionary with 'a' and 'e' as keys and sets as values. In order to get each character and its successor you can use zip on the text. Then check if the character is in the dictionary and its successor is a letter. Adding the next letter to the set will ensure that each successor letter is going to be counted only once:

text= 'there is a sea apple'

result = {'a':set(), 'e':set()}     # set of successor letters for 'a' and 'e'
for v,n in zip(text,text[1:]):
    if v in result and n.isalpha(): # a/e followed by a letter ?
        result[v].add(n)            # add to key's set

print(result)
{'a': {'p'}, 'e': {'a', 'r'}}
  • Related