Problem building code in Python


First post :slight_smile:
Hello! I need help with building some code to solve the following problem using python 2.7 without importing anything:

From a number imputed form the user i need to print the frequency of each number in descending order:
Example: for an imputed number of 252452321 the code should print "2-4, 5-2, 4-1, 3-1, 2-1 , 1-1". This means is should print that number 2 is found four times, number 5 is found two times, etc.

So far i have used:

x = raw_input('Insert your number here: ')

a = list(x)

a0 = a.count('0')
a1 = a.count('1')
a2 = a.count('2')
# and so on until a9 = a.count('9')
b = [a0, a1, a2, """etc"""]
print b

And i can continue a bit from here to obtain the result i need (more or less). But i've been told i should not write it like that, i should use loops.. and i'm stuck on writing one that works. Please, can you help me? Thanks in advance.


that depends, are you allowed to use built in functions? or import functions, if so, the solution is simple:

from collections import Counter
x = raw_input('Insert your number here: ')
print Counter(x)

this will give you a dictionary with how often every instance of the number occurs

i guess that is a bit cheating, but you could use a dictionary:

dict = {}
for i in range(10):
    dict[str(i)] = 0

then you can loop over x, find the corresponding key, increase the value (use += 1), that should give you a good start


To simplify the explanation, i am not allowed to use 'import'.
Now i'm trying a new method:

x = int(raw_input('Write the number here: '))
def verificator(x):
    b = []
    for i in range(10):
    while x > 0:
        for item in range(10):
            if item == x%10:
                b[item] += 1
                x = x / 10
print b
print verificator(x)

At the moment the function generates a list with the frequency of the characters... i still need to find a way to display it like the rquest.


but a list sounds like a bad idea to solve this problem, if you use a dictionary on the other hand, it is easier

the advantage of a dictionary is that you can have the number (as key) and the amount the number occurs (as value):

x = raw_input('Insert your number here: ')
dict = {}
for i in range(10):
    dict[str(i)] = 0
for j in x:
   dict[j] += 1
print dict

this code is shorter and easier to print in the desired format then using list (and no import is used)