0

I'm really confused on this one, why my function is returning None too?

def CharFreq(string):

    l = list(string)

    for i in range(len(l)):
        count = 0
        print(l[i])
        for j in range(0,len(l)):
               if l[i] == l[j] :
                  count+=1
       print (l[i],count)

print(CharFreq("hih"))

First, My function is returning None too, and when I put the line of print(l[i]), it also does return None.. but when I do this alone, I don't see any None:

 l = list("hih")
for i in range(len(l)):
    print(l[i])

Second, I'm trying to develop a basic approach for char frequency using two loops, not only it's returning None too, but also it looks like my indices are wrong, I need it to return:

h , 2
i, 1
Karl
  • 1,590
  • 2
  • 11
  • 19
Micheal
  • 17
  • 1
  • 7
  • 2
    Possible duplicate of [How is returning the output of a function different from printing it?](https://stackoverflow.com/questions/750136/how-is-returning-the-output-of-a-function-different-from-printing-it) – Carcigenicate Aug 24 '18 at 17:34
  • 2
    TL;DR: You aren't returning anything. `print` != `return` – Carcigenicate Aug 24 '18 at 17:34
  • Ok I think Now I know what is going on about returning None...Now I just to edit my solution to return the right output – Micheal Aug 24 '18 at 17:51

2 Answers2

1

I would highly suggest using a dict for computing the char count.

They can be implemented as follows:

def CharFreq(string):

    str_count = dict()
    for i in string:
        if i in str_count:
            str_count[i] += 1
        else:
            str_count[i] = 1
    return str_count

print(CharFreq("hih"))

Output:

{'h': 2, 'i': 1}

Getting back to your solution for this,

it prints a None because you're not returning anything from the function call. simply calling the function would print the desired output for you.

Vaibhav Sharma
  • 891
  • 4
  • 14
  • I already know and solved by this solution, but I'm preparing for an interview and usually we start with brute force solution – Micheal Aug 24 '18 at 17:39
  • @Micheal You have basic misunderstandings about how Python works, which pose a much bigger problem for your interview (if they do indeed require Python proficiency) than any algorithmic issues. – chepner Aug 24 '18 at 17:58
  • @chepner thanks for the positivity! sometimes we get confused on the stupidest things. Don't judge the cover – Micheal Aug 24 '18 at 18:00
  • @Micheal I have edited your solution so as to what would be a decent brute force snippet. Let me know what you think! – Vaibhav Sharma Aug 24 '18 at 18:04
0
def CharFreq(string):

    n= len(string)
    ll=[]
    for i in range(n):
        count = 0

        for j in range(n):
                if string[i] == string[j] :
                   count+=1
        if (string[i],count) not in ll:        
               ll.append(tuple((string[i],count)))
    return ll  

print(CharFreq("hih"))
Micheal
  • 17
  • 1
  • 7