2

I am trying to write code in Python which finds the percentage of the alphabet in a given string. For example,

percent("ab", "aabccdef") should give [("a", 25), ("b", 13)] since 'a' occurs twice in a string of length 8, so its percentage is round(2 / 8), or 25. Similarly, 'b' occurs only once. So its percentage is round(1 / 8), or 13.

Here is my code. Can someone help me debug this?

def Percent(alpha, string):
   y = [e for e in string if e == alpha]
   x = len(y)
   return (alpha, round((x / len(string) * 100)))
David Cain
  • 16,484
  • 14
  • 65
  • 75
Rachel
  • 383
  • 2
  • 4
  • 13

2 Answers2

3

You were close but the key difference is that you need to compute it for each character c in alpha:

def percent(alpha, string):
    results = []
    for c in alpha:
        y = [e for e in string if e == c]
        x = len(y)
        results.append((c, round((float(x) / len(string)*100))))
    return results

In your code you're comparing e == alpha but alpha is a string ab and e is a single character in the string. This won't give you the results you want.

Furthermore, you need to convert x to a float if you wish to compute the percentage properly. In Python if you write, e.g., 3 / 4 you'll get 0 instead of 0.75. To prevent this you need to convert at least one of the arguments to a float which can be done by calling float(). So you could also write x / float(len(string)*100) to ensure you won't get an integer as result.

Simeon Visser
  • 118,920
  • 18
  • 185
  • 180
3

Another way to do this, you can use str.count in a list comprehension:

>>> alpha = 'ab'
>>> string = 'aabccdef'
>>> [(x, string.count(x)/len(string)) for x in alpha]
[('a', 0.25), ('b', 0.125)]
Community
  • 1
  • 1
eskaev
  • 1,108
  • 6
  • 11
  • thanks. Is there a possibility to replace .count(x) with something simpler so that no inbuilt functions are used?? – Rachel Jan 16 '14 at 21:56
  • Well, you could replace `string.count(x)` with `len([s for s in string if s==x])`, but I don't think it is simpler. – eskaev Jan 16 '14 at 22:07
  • I added a link in the answer, if you want to see what `str.count` does. If you prefer not to use `count`, Simeon's answer is fine. – eskaev Jan 16 '14 at 22:20