1

Task :With dictionary write function frekv which returns occurrence of numbers

This is my code:

def frekv(n):
    b={}
    for i in n:
        if i in b:
             b[i] +=1
        else:
            b[i]=1
    return b

x = map(frekv,[5, 2, 4, 4, 3, 1, 3, 8]) 
print (list(x))

Result: {5: 1, 2: 1, 4: 2, 3: 2, 8: 1, 1: 1}

This is not a right way to return it, is there any way I could return that whole list.

13
  • 3
    return b needs to be indented. b is a dictionary, not a list. Commented Oct 14, 2020 at 17:05
  • Mistake n is a dictionary in function Commented Oct 14, 2020 at 17:06
  • 2
    Why are you calling map()? The function expects the argument to be a list, but you're calling it separately with each element of the list. Commented Oct 14, 2020 at 17:07
  • Should I make b=[] something like that to store number and number of occurances Commented Oct 14, 2020 at 17:08
  • 2
    What is the result you're trying to get? Commented Oct 14, 2020 at 17:12

1 Answer 1

1

Probably you meant something like this:

def frekv(n):
    b={}
    for i in n:
        if i in b:
             b[i] +=1
        else:
            b[i]=1
    return b

x = frekv([5, 2, 4, 4, 3, 1, 3, 8]) 
print(x)

Output:

{5: 1, 2: 1, 4: 2, 3: 2, 1: 1, 8: 1}
Sign up to request clarification or add additional context in comments.

9 Comments

He wrote in a comment "I need to use map"
With dictionary write function frekv which returns occurrence of numbers
I dont have to use x = map(frekv,[5, 2, 4, 4, 3, 1, 3, 8]) like this?
It is, this is my first time with python I was learning C before. I tought I have to use map() something to be good. Thank you
@Momo No map() in Python is different from map() in C/C++. In Python, it is known as a dictionary.
|

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.