Dictionary and repeating structure

Asked

Viewed 219 times

1

The problem asks me to count the size of holes in the text Exp: A, D, R, O, P has only one hole, and B has two I made the following code:

qnt = int(input())

cont = 0

l = []

for i in range(qnt):

    txt = input()


dic = {'A':1, 'D':1, 'O':1, 'P':1, 'R':1, 'B':2}

for i in txt:

    if dic.get(i, 0):

       cont += dic[i]

print(cont)

However, only appears the amount of holes of the last text, and I need each text.

1 answer

0

First let’s understand why we are returning only the amount of the last. Considering the code that is here, on the line 5 you have a named list of l, however, does not use it anywhere else.

On the line 7 you retrieve user input, and do not store in a list, for this reason, always the last entry will be the value of txt.

...
5 l = []
6 
7 for i in range(qnt):
8 
9     txt = input()
...

I believe what you were trying to do was add the value of txt on the list l

...
5 l = []
6 
7 for i in range(qnt):
8 
9     txt = input()
10    l.append(txt)
...

If you do, you’d have to change the line 15:

15 for i in txt:

To:

15 for i in l:

But you can leave him more Pythonic.

dic = {'A':1, 'D':1, 'O':1, 'P':1, 'R':1, 'B':2}
cont = 0
for i in range(int(input())):
  txt = input()
  if txt in dic: cont += dic[txt]

print(cont)

Example working on repl it..

Browser other questions tagged

You are not signed in. Login or sign up in order to post.