user4100849
user4100849

Reputation:

Python count the frequency of each number in a list without any count() functions or without importing anything

Lets say I have List myList = [1, 1, 2, 2, 2, 3] I want to count the frequency of each number in the list and make it into some sort of graph with an output:

1: X X
2: X X X
3: X

But I can't figure it out. I'm very new to Python and i need to make the code without any built in functions and without using import to import anything

Upvotes: 1

Views: 6451

Answers (5)

Parth Wavesoul
Parth Wavesoul

Reputation: 1

The counting part:

d={}
for i in myList:
    if i in set(myList):
        try:
            d[i]=d[i]+1
        except:
            d[i]=1

The printing part:

for i,j in d.items():
    print(i,":",j*'X ')

Upvotes: 0

Sagar R Bandagar
Sagar R Bandagar

Reputation: 1

#without using any built in functions

def fre(my_list):
    
    #using empty dictionary
    freq={}
    for item in my_list:
        if(item in freq):
            freq[item]+=1
        else:
            freq[item]=1
    for key,value in freq.items():
        print(f"{key}:{value}")
my_list=list(map(int,input("Enter the list elements").split()))

fre(my_list)

Upvotes: 0

r.saiprasad
r.saiprasad

Reputation: 53

This work without any count function

freq =[0]*1001
arr = list(map(int, input().split()))
        for i in arr:
            freq[i] += 1

Upvotes: 0

Mauro Baraldi
Mauro Baraldi

Reputation: 6575

Anyway Python standard lib have a proper module to that, Counter

>>> from collections import Counter
>>> myList = [1, 1, 2, 2, 2, 3]
>>> print Counter(myList)
Counter({2: 3, 1: 2, 3: 1})

Upvotes: 1

Kroltan
Kroltan

Reputation: 5156

A dict-based solution:

myList = [1, 1, 2, 2, 2, 3]
output = {}

for item in myList:
    if item not in output:
        output[item] = 0
    output[item] += 1

Then, print it:

for number, count in output.iteritems():
    print "{0}: {1}".format(number, "X " * count)

Upvotes: 3

Related Questions