-2

Is there another way to calculate the number of occurrences without using a dictionary like this code? I mean, I want the same result as this code but without the dict.

This code displays:

apple 3
bread 2
orange 1

Code:

txt = ["apple", "bread", "apple", "orange", "apple", "bread"]
dic ={}
for c in texte:
  lettres[c] = lettres.get(c, 0) + 1

for i in sorted(lettres):
 print(i,lettres.get(i))
martineau
  • 119,623
  • 25
  • 170
  • 301

2 Answers2

0

If the charset is known and limited (lower case ASCII alphabet for example), you could allocate an array, and increment the count corresponding to the index of a character every time you see it. This, however, is waste of space since you may never encounter some characters at all.

Abhijit Sarkar
  • 21,927
  • 20
  • 110
  • 219
-1

Option 1 : Use counters

from collections import Counter

txt = ["apple", "bread", "apple", "orange", "apple", "bread"]

keys = Counter(txt).keys() # equals to list(set(txt))
occ = Counter(txt).values() # counts the number of occurrences

Output:

['apple', 'bread', 'orange']
[3, 2, 1]

Option 2: Use count and set

occ = {i: txt.count(i) for i in set(txt)}

Output:

{"apple": 3, "bread": 2, "orange": 1}

If you want to just print it without saving in a dictionary, use this:

for i in set(txt):
   print(i, txt.count(i))
Akanksha Atrey
  • 780
  • 4
  • 8