Counting letters in a string

Asked

Viewed 92 times

2

I need to make a Python script that takes a string and returns the sum of the letters of that string in a list of tuples, as follows: Example:

banana -----> [('b', 1), ('a', 3), ('n', 2)]

My show is like this:

for n in txt:
      c =  txt.count(n)
      if n != ' ':
          if n not in lista_txt:
              tupla = n, c
      lista_txt.append(tupla)

But it returns the sum of each letter more than once:

[('b', 1), ('a', 3), ('n', 2), ('a', 3), ('n', 2), ('a', 3)]

How can I fix this?

3 answers

4


You’re just checking to see if n is on your list of tuples, when you were supposed to be checking the tuple (n, c) exists on your list

Another detail is that you’re adding the tuple to your list even when it doesn’t go through the conditions != ' ' and (n, c) not in lista_txt, you need to indent this yours append to stay inside the if, thus:

for n in txt:
    c =  txt.count(n)
    if n != ' ' and (n, c) not in lista_txt:
        tupla = n, c
        lista_txt.append(tupla)

See the code working here

4

Although not responding directly to your question I find interesting to mention that you can reach your goal in a very direct way using functions and structures already existing in python.

All you need to do is use Counter to generate a dictionary with the counts, and the function items get counts as a list of tuples:

>>> from collections import Counter
>>> texto = "banana"
>>> list(Counter(texto).items())
[('b', 1), ('a', 3), ('n', 2)]

Watch it work on Ideone

As an aside, besides being more direct is also more effective because its solution has complexity O(n²), that is to say quadratic, while with Counter the solution is in O(n), linear.

0

You can also use a dictionary and go setting the keys and values, as you count the times when the letter contained in the word repeats in the sequence:

txt = 'banana'
dict = {}

for n in txt:
    c = txt.count(n)
    if not (n,c) in dict:
        dict.__setitem__(n,c)
print(dict)

Browser other questions tagged

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