2

I am trying to write a program to count the occurrences of a specific letter in a string without the count function. I made the string into a list and set a loop to count but the count is never changing and i cant figure out why. This is what I have right now:

letter = 'a'
myString = 'aardvark'
myList = []

for i in myString:
    myList.append(i)

count = 1

for i in myList:
    if i == letter:
        count == count + 1

    else:
        continue

print (count)

Any help is greatly appreciated.

Matthew Hanson
  • 321
  • 5
  • 7
  • 15
  • 1
    `count == count + 1` is not an assignment. Simply remove one `=`. – Martijn Pieters Mar 10 '15 at 14:37
  • Why inventing things badly if `'aardvark'.count('a')` does the job better and faster? (At least it isn't as errorprone) – emvee Mar 10 '15 at 14:38
  • Your `for` loop features an `if...else...` where the `else` features a `continue`. The `continue` is not necessary because there is nothing to avoid computing with the `for` loop. A solitary `if` would suffice. – polarise Mar 10 '15 at 14:39
  • 1
    Creating a list out of a string is also completely superfluous: `for char in myString: ...` does the job and is very Pythonic at that. – emvee Mar 10 '15 at 14:40

8 Answers8

2

Be careful, you are using count == count + 1, and you must use count = count + 1

The operator to attribute a new value is =, the operator == is for compare two values

Yuri Malheiros
  • 1,400
  • 10
  • 16
1

Instead of

count == count + 1

you need to have

count = count + 1
sray
  • 584
  • 3
  • 8
1

Although someone else has solved your problem, the simplest solution to do what you want to do is to use the Counter data type:

>>> from collections import Counter
>>> letter = 'a'
>>> myString = 'aardvark'
>>> counts = Counter(myString)
>>> print(counts)
Counter({'a': 3, 'r': 2, 'v': 1, 'k': 1, 'd': 1})
>>> count = counts[letter]
>>> print(count)
3

Or, more succinctly (if you don't want to check multiple letters):

>>> from collections import Counter
>>> letter = 'a'
>>> myString = 'aardvark'
>>> count = Counter(myString)[letter]
>>> print(count)
3

The simplest way to do your implementation would be:

count = sum(i == letter for i in myString)

or:

count = sum(1 for i in myString if i == letter)

This works because strings can be iterated just like lists, and False is counted as a 0 and True is counted as a 1 for arithmetic.

TheBlackCat
  • 9,791
  • 3
  • 24
  • 31
  • how would you go about storing each count of each letter? for example if we had aaabbccbb, and we wanted it as a3b42c?? – Oscar Dolloway Jan 13 '20 at 17:45
  • 1
    You can just loop over the counter using `items()`, then combine them with a `''.join`. This is a one-liner: `''.join('{}{}'.format(x, y) for x, y in Counter('aaabbccbb').items())`. Output is `'a3b4c2'` – TheBlackCat Jan 13 '20 at 18:28
  • Thanks! another question, how would you go about it without any built in functions? – Oscar Dolloway Jan 14 '20 at 09:08
  • This is sounding like a homework question. In real life you would never do this sort of thing without built in functions. You should be able to adapt my `sum` based approach above to do that, but I won't give you the answer to a homework question. – TheBlackCat Jan 15 '20 at 14:41
  • i was more interested in the approach rather than an answer, thanks anyways. – Oscar Dolloway Jan 18 '20 at 02:09
  • this wasnt a homework question either, i was practising common interview questions and these problems are usually what comes up. – Oscar Dolloway Jan 18 '20 at 02:11
0

Your count is never changing because you are using == which is equality testing, where you should be using = to reassign count. Even better, you can increment with

count += 1

Also note that else: continue doesn't really do anything as you will continue with the next iteration of the loop anyways. If I were to have to come up with an alternative way to count without using the count function, I would lean towards regex:

import re
stringy = "aardvark"
print(len(re.findall("a", stringy)))
HavelTheGreat
  • 3,299
  • 2
  • 15
  • 34
0

Use filter function like this

len(filter(lambda x: x==letter, myString))
Josip Grggurica
  • 421
  • 4
  • 12
0

Apart from the above methods, another easiest way is to solve the problem by using the python dictionary

 word="purple"
 dic={}
 for letter in word:
     if letter in dic:
        dic[letter]+=1
     else:
        dic[letter]=1
 print(dic)
 {'p': 2, 'u': 1, 'r': 1, 'l': 1, 'e': 1}

In case if you want to count the occurences of a particular character in the word.we can get that it by following the below mentioned way,

        dic['p']
        2  
Prajwal KV
  • 51
  • 6
0

Your code logic is right except for considering count == 1 while using count == 1 you are comparing if count == 1 and count = 1 is for assigning and count += 1 is for incrementing.
Probably you know this, you might have got confused also, you have to initialize count = 0

letter = 'a'
myString  = 'aardvark'
myList = []

for i in myString:
    myList.append(i)
count = 0
for i in myList:
    if i == letter:
        count +=1
    else:
        continue
print(count)
Josh Karpel
  • 2,110
  • 2
  • 10
  • 21
vignesh
  • 1
  • 1
0

For the code to function properly, two alterations need to be made:

  1. Modify the initialization of count
count = 0
  1. Use = instead of ==
count = count + 1

or

count += 1
Navieen
  • 1
  • 1
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community May 03 '23 at 08:40