I have to create a programme that given a phrase counts the number of times a letter appears in each word and prints it this way:
Input:
i see it
Output:
[('i', 1), ('s', 1), ('e', 2), ('i', 1), ('t', 1)]
My code only works for the first word.Can you help me?
inicialString=str(input())
words=inicialString.split(" ")
def countTheLetters(t):
for word in words:
thingsList=[]
for x in word:
n=word.count(x)
j=x,n
thingsList.append(j)
return thingsList
print(countTheLetters(words))
My Output:
[('i', 1)]
I have tried to replace the return thingsList but then it only worked for the last word.
You're emptying thingsList
each time through the for word in words:
loop, so you only get the last word.
Put thingsList = []
before the first for
statement.
Problem is that you return from your function as soon as you check first word, instead you should append result of your current word to some final list and return it after you process all words.
inicialString='i see it'
words=inicialString.split(" ")
def countTheLetters(t):
ret = []
for word in words:
thingsList=[]
for x in word:
n=word.count(x)
j=x,n
if not j in thingsList:
thingsList.append(j)
ret.extend(thingsList)
return ret
print(countTheLetters(words))
Output:
[('i', 1), ('s', 1), ('e', 2), ('i', 1), ('t', 1)]
The problem is that you are resetting the 'thingsList' every iteration of the 'for word in words' loop and also returning the thingsList list after only 1 iteration.
inicialString=str(input())
words=inicialString.split(" ")
def countTheLetters(t):
thingsList=[]
for word in words:
for x in word:
n=word.count(x)
j=x,n
thingsList.append(j)
return thingsList
print(countTheLetters(words))
updated your code check it now
inicialString=str(input())
words=inicialString.split(" ")
def countTheLetters(t):
thingsList=[]
for word in words:
for x in word:
n=word.count(x)
j=x,n
thingsList.append(j)
return thingsList
print(countTheLetters(words))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.