Answer to Question #283708 in Python for Santhosh

Question #283708







input1, input2, input3 and input4 are the four given input numbers.








The function is expected to find and return the most frequent digit.








Example1 –








If input1=123, input2=234, input3=345, input4=673








We see that across these four numbers,








1, 5, 6 and 7 occur once,








2 and 4 occur twice, and








3 occurs four times.








Therefore, 3 is the most frequent digit and so the function must return 3








NOTE: If more than a digit occurs the same number of most times, then the highest of those digits should be the result. Below example illustrates this.








Example2 –








If input1=123, input2=456, input3=345, input4=5043








We see that








0, 1, 2 and 6 occur once, and








3, 4 and 5 occur thrice.








As there are three digits (3, 4 and 5) that occur most number of times, the result will be the highest (max) digit out of these three. Hence, the result should be 5








Let us see couple of more examples

1
Expert's answer
2021-12-30T15:18:03-0500



# Finds maximum occurring digit
# without using any array/string
 
# Simple function to count
# occurrences of digit d in x
def countOccurrences(x, d):
    count = 0; # Initialize count
               # of digit d
    while (x):
         
        # Increment count if current
        # digit is same as d
        if (x % 10 == d):
            count += 1;
        x = int(x / 10);
 
    return count;
 
# Returns the max occurring
# digit in x
def maxOccurring(x):
     
    # Handle negative number
    if (x < 0):
        x = -x;
     
    result = 0; # Initialize result
                # which is a digit
    max_count = 1; # Initialize count
                   # of result
     
    # Traverse through all digits
    for d in range(10):
         
        # Count occurrences of current digit
        count = countOccurrences(x, d);
         
        # Update max_count and
        # result if needed
        if (count >= max_count):
            max_count = count;
            result = d;
         
    return result;
 
# Driver Code
x = 1223355;
print("Max occurring digit is",
              maxOccurring(x))

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS