Search code examples
pythonlistindex-errorfrequency-analysisindexoutofrangeexception

For given 4 numbers as arguments of the function, I've to find the digit with max frequency combined for all numbers?


Like for 1234,4566,654,987; we see, we have 4 and 6 both with 3 as frequency. So, we'll receive the output as 6 because it's the bigger one. So, the code which i thought as the solution is:

def MaxDigit(input1,input2,input3,input4):
    arr=[input1,input2,input3,input4]
    k=0
    for i in range(1,10):
        ask=[0]*i
    for j in range(0,4):
        while arr[j]!=0:
            k=int(arr[j]%10)
            arr[j]=int(arr[j]/10)
            ask[k]+=1

So, after this we'll get ask list with no.s as indexes and frequency with value. I can code that further. But it is showing index out of range error for last line i.e ask[k]+=1 which i'm unable to guess, why it's showing like that. Please help me with this. If there could be an alternate code too, help me with it.


Solution

  • input = [234,4566,654,987]
    digits = [int(n) for num in input for n in str(num)] # extracts each digit separately into a list as in [2, 3, 4, 4, 5, 6, 6, 6, 5, 4, 9, 8, 7]
    

    Generating a frequency dictionary and sorting the dictionary based on your conditions, first on the decreasing order of values, and then on the decreasing order or the key.

    digit_count = {i:digits.count(i) for i in set(digits)} 
    digit_count_sorted = sorted(digit_count.items(), key=lambda x: (-x[1], -x[0]))
    
    digit_count_sorted[0][0] #prints the answer 6
    

    You can implement it as a function :

    def MaxDigit(input):
        digits = [int(n) for num in input for n in str(num)]
        digit_count = {i:digits.count(i) for i in set(digits)} 
        digit_count_sorted = sorted(digit_count.items(), key=lambda x: (-x[1], -x[0]))
        return digit_count_sorted[0][0]
    
    print(MaxDigit([234,4566,654,987])
    

    Output :

    6