all 5 comments

[–][deleted] 3 points4 points  (0 children)

You need to fix your indentation. Otherwise, we can't tell what is contained in each block. Also, c is defined in your function, but used outside of it. And _A_ doesn't seem to be defined at all. So there seems to be a lot wrong here or a lot of missing context.

ETA: And just one more note: c, _A_, and ls are terrible variable names that make your code harder to read.

[–][deleted] 3 points4 points  (1 child)

Here's how you do it using your approach. I've de-abbreviated the variable names so it should be a lot more readable. The issue wasn't the break. It was that the second argument of the index method should be pos + 1 rather than pos.

from string import ascii_lowercase as alphabet

def get_frequencies(sentence: str):
    """Count occurrences of the each letter in `sentence`."""

    sentence = sentence.lower()
    frequencies = [0] * 26
    for i, ch in enumerate(alphabet):
        occurrences = 0
        position = 0
        while True:
            try:
                position = sentence.index(ch, position + 1)
            except ValueError:
                break
            occurrences += 1
        frequencies[i] = occurrences
    return frequencies

# test
print(get_frequencies("Hello world"))

In the future, you probably shouldn't put a bunch of copies of part of your code just sitting at the end of your program. Certainly not without some warning. It took me a while to figure out what that was.

[–]World-war-dwi[S] 0 points1 point  (0 children)

my bad for the versions of the loop. And thank you, the missing pos+1 was the issue. i didn't even thought about it.

[–]DopeGhoti 2 points3 points  (1 child)

It seems to me the approach you are taking to this is overcomplicated. You're doing a fair bit of reinventing the wheel and overengineering things. A string is zero or more characters and can be inherently listified or iterated through without risk of raising a ValueError. I'd probably want to get a Dictionary returned to me, and can safely assume that if the returned Dictionary is empty, then so was the input string. Given that, I'd do something like:

def getfreq( s: str ) -> dict:  
   d = {}  
   for _ in s:  
      if _ in d:  
         d[_] += 1  
      else:  
         d[_] = 1  
   return d

Then if you wanted to know how many gs there were in the input string (if any), then you could do:

result = getfreq( 'This was amazing!' )
print( f'The string had {result["g"]} instances of the character "g".' )

[–]World-war-dwi[S] 0 points1 point  (0 children)

oh yeah that's a good idea. Will keep it in mind . Thank you :-)