【问题标题】:For given 4 numbers as arguments of the function, I've to find the digit with max frequency combined for all numbers?对于给定的 4 个数字作为函数的参数,我必须找到所有数字组合的最大频率的数字?
【发布时间】:2020-10-03 00:36:39
【问题描述】:

喜欢 1234,4566,654,987;我们看到,我们有 4 和 6 都以 3 作为频率。因此,我们将收到 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

因此,在此之后,我们将获得 ask 列表,其中 no.s 为索引,频率为 value。我可以进一步编码。 但它显示 last line 的 index out of range 错误,即 ask[k]+=1 我无法猜测,为什么它会这样显示。请帮我解决一下这个。 如果也有替代代码,请帮助我。

【问题讨论】:

  • no.s???.......
  • 表示数字。
  • 我得到了合适的代码,但谁能告诉我它在我的代码中显示索引超出范围错误的原因? @尼克
  • @goodvibration 你能告诉我代码中出现索引错误的原因吗?

标签: python list index-error frequency-analysis indexoutofrangeexception


【解决方案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

你可以将它实现为一个函数:

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])

输出:

6

【讨论】:

  • 我曾想过字典方法,但无法实现。它奏效了。
【解决方案2】:

实现这一点的一种方法是使用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))

输出:

6

作为查找最大计数并对其进行过滤的替代方法,您可以将Counter 按计数降序排序,然后键,然后返回第一个值的键:

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])

【讨论】:

    【解决方案3】:

    试试这个:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-15
      • 1970-01-01
      • 2017-03-05
      相关资源
      最近更新 更多