Home > Net >  Why is this program not finding the digit frequency correctly?
Why is this program not finding the digit frequency correctly?

Time:10-17

a = int(input())
digit = 0
count=0
temp = 0
for i in range(0,10):
    temp=a
    count = 0
    while(temp>0):
        digit = temp%10
        if digit == i:
         count =1
        temp=temp/10
    if count>0:
      print(f'{i}\t{count}')

This program's output is always displayed as the last digit's frequency as one and doesn't give frequency of other digits. Like if my input is 1991, its output will be

1   1

CodePudding user response:

It is because of the line temp = temp/10.

Take your example, 1991. The division of this number by 10 is equal to 199.1. In the next iteration when you take the mod (%), the result is 9.099999999999994, which is not equal to any digit.

To fix it you can either (i) parse the division to int as temp = int(temp/10), (ii) parse the digit to int as digit = int(temp % 10) or (iii) even better, perform the integer division temp//10, as stated by @mozway.

Then, you get the expected output:

1       2
9       2

CodePudding user response:

Issue in your code is temp = temp/10, In Python division result in floating point values where values always > 0. Use temp = int(temp/10) this will fix your code and check other approach mentioned above.

CodePudding user response:

You have a single counter but potentially many values, plus you reset it for each number. Finally, the double loop if not needed and inefficient.

Here is a simple working code on the same logic. I am using here collections.Counter to hold the counts and a single loop with divmod to compute the integer division with remainder.

a=1991

from collections import Counter

c = Counter()

while a>0:
    a,r = divmod(a, 10)
    print(a,r)
    c[r] =1

print(c)

Output:

Counter({1: 2, 9: 2})

CodePudding user response:

I rewrite your code with better version.

In my code, I create a dictionary to store occurances of each digit: 1. find whether the digit is existed. Yes, then create a diction with count 1; else add 1 value to existing dictionary

a = input("Enter your number:")
str1 = str(a)
unique_number = {}
for each in str1:
    if(each not in unique_number):
        unique_number[each] = 1;
    else:
        unique_number[each]  = 1;
        
for each in unique_number:
    print(unique_number[each])
  • Related