簡體   English   中英

對於給定的 4 個數字,如 function 的 arguments,我必須找到所有數字組合的最大頻率的數字?

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

喜歡 1234,4566,654,987; 我們看到,我們有 4 和 6 都以 3 作為頻率。 因此,我們將收到 output 作為 6,因為它更大。 所以,我認為作為解決方案的代碼是:

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

因此,在此之后,我們將獲得以 no.s 為索引的詢問列表和帶有值的頻率。 我可以進一步編碼。 但它顯示最后一行的索引超出范圍錯誤,即 ask[k]+=1 ,我無法猜測,為什么它會這樣顯示。 請幫我解決一下這個。 如果也有替代代碼,請幫助我。

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]

生成頻率字典並根據您的條件對字典進行排序,首先是值的降序,然后是降序或鍵。

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

您可以將其實現為 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

實現這一點的一種方法是使用Counter ,將所有數字轉換為字符串並計算數字。 然后,您可以從計數器中找到最大計數並返回具有該計數的最大值:

from collections import Counter

def MaxDigit(*args):
    counts = Counter(''.join(str(a) for a in args))
    maxcount = counts.most_common(1)[0][1]
    return int(max(v for v, c in counts.items() if c == maxcount))

print(MaxDigit(1234,4566,654,987))

Output:

6

作為查找最大計數並對其進行過濾的替代方法,您可以按 count 降序對Counter進行排序,然后按 key 排序,然后返回第一個值的 key:

def MaxDigit(*args):
    counts = Counter(''.join(str(a) for a in args))
    counts = sorted(counts.items(), key=lambda x:(-x[1], -int(x[0])))
    return int(counts[0][0])

嘗試這個:

def MaxDigit(input1,input2,input3,input4):
    s = '{}{}{}{}'.format(input1,input2,input3,input4)
    maxCount = 0
    maxDigit = 0
    for digit in range(10):
        count = s.count(str(digit))
        if maxCount <= count:
            maxCount = count
            maxDigit = digit
    return maxDigit

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM