3

I've got the following exercise: Write the function countA(word) that takes in a word as argument and returns the number of 'a' in that word. Examples

>>> countA("apple")
1
>>> countA("Apple")
0
>>> countA("Banana")
3

My solution is:

def countA(word):
  return len([1 for x in word if x is 'a'])

And it's ok. But I'm not sure if it's the best pythonic way to solve this, since I create a list of 1 values and check its length. Can anyone suggest something more pythonic?

5
  • 8
    word.count('a')? Commented Jun 26, 2013 at 14:27
  • 1
    your list comprehension is a common pattern used in python. Ther's nothing wrong with it. Commented Jun 26, 2013 at 14:28
  • @Volatility yep, that's a lot better than what I've written. I'll accept your answer. Commented Jun 26, 2013 at 14:30
  • 1
    it seems more like a C exercise :-P Commented Jun 26, 2013 at 14:35
  • 1
    @Ant well, yep, it's strange. I found it at pyschools.com. There are some more exercses like that, but it's also a way to remind all most important python methods ;) Commented Jun 26, 2013 at 21:26

5 Answers 5

5

Assuming you're not just allowed to use word.count() - here's another way - possibly faster than summing a generator and enables you to do multiple letters if you wanted...

def CountA(word):
    return len(word) - len(word.translate(None, 'A'))

Or:

def CountA(word):
    return len(word) - len(word.replace('A', ''))
Sign up to request clarification or add additional context in comments.

Comments

3

use this

def countA(word):
    return word.count('a')

As another example, myString.count('c') will return the number of occurrences of c in the string

Comments

3

In python, strings are sequences (just like a list).

Then you could use count :

>>> 'Apple'.count('p')
2

Using this, the answer to your exercise would be:

def countA(word):
    return word.count('a')

2 Comments

You mean "a sequence" not "iterable". True, both strings and lists are iterable (as are all sequences) but being iterable has nothing to with count or the rest of this answer.
@Jon-Eric Edited consequently.
2

I know this has already been answered, but I can't believe nobody mentioned using a Counter for this, since it's very well suited to this problem. It might have a little more overhead, but if you want to find multiple letters it's probably the best way to go. Here it is in a simple, readable lambda function.

from collections import Counter

count = lambda word, letter: Counter(word)[letter]

count("test", "t")
>>> 2

2 Comments

+1, but note that Counter(word).get(letter, 0) can be replaced with Counter(word)[letter] as Counter returns 0 for missing items
@1_CR Oh huh, totally forgot about that. Thanks for the tip.
1

Use sum:

>>> def countA(word):
  return sum(1 for x in word if x == 'a')

>>> countA("apple")
1
>>> countA("Apple")
0
>>> countA("Banana")
3

7 Comments

sum and length return the same, as long as 1 is returned inside the list comprehension.
thats basically the same as what he did
@tkoomzaaskz You construct redundant list with [1 for x in word if x is 'a'] and then calculate its length. Sum on the other hand just goes trough iterator over the original word.
Don't use is 'a' use == a
@tkoomzaaskz is is incorrect. It returned correct results only accidentally (because in Python small equal strings point to the same objects, but for longer equal strings objects will be different, so is will return False).
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.