简体   繁体   English

有没有更好的方法来编写这个函数?

[英]is there a better way to write this functions?

[![enter image description here][1]][1] [![在此处输入图像描述][1]][1]

First function returns the recursive digit sum of that number.第一个 function 返回该数字的递归数字总和。 The second function return dictionary where key is reg_dig_sum and value is count of that number occurring.第二个 function 返回字典,其中键是 reg_dig_sum,值是出现该数字的计数。 when I tested it it failed giving me this当我测试它时,它没有给我这个

elf.assertEqual(sum_dict[0], 1) AssertionError: 0 != 1

How can I solve this?我该如何解决这个问题?

def reg_dig_sum(n):
    x = sum(int(digit) for digit in str(n))
    if x < 10:
        return x
    else:
        return reg_dig_sum(x)

def distr_of_rec_digit_sums(low=0, high=1500):
    distr = {}
    for x in range(low, high):
        if reg_dig_sum(x) not in distr:
            distr[reg_dig_sum(x)] = 0
        else:
            distr[reg_dig_sum(x)] += 1 
    return distr
  • The problem I can think is your count for each reg_dig_sum will be one less than what it should be.我能想到的问题是您对每个 reg_dig_sum 的计数将比应有的数少一。 That's the reason assertion condition is failing.这就是断言条件失败的原因。
  • You can fix this logical error by initializing distr to either 1 or by removing else condition.您可以通过将 distr 初始化为1或删除else条件来修复此逻辑错误。
  • I would also suggest to use other alternatives like defaultdict to take care of initialization for you.我还建议使用其他替代方法,例如defaultdict来为您处理初始化。
def distr_of_rec_digit_sums(low=0, high=1500):
    distr = {}
    for x in range(low, high):
        if reg_dig_sum(x) not in distr:
            distr[reg_dig_sum(x)] = 1 # this should be initialized to 1 for first occurance.
        else:
            distr[reg_dig_sum(x)] += 1 
    return distr
  • Using defaultdict使用defaultdict
from collections import defaultdict
def distr_of_rec_digit_sums(low=0, high=1500):
    distr = defaultdict(int)
    for x in range(low, high):
        distr[reg_dig_sum(x)] += 1 
    return distr

See previous comments and answers regarding changing 0 to 1请参阅先前有关将 0 更改为 1 的评论和答案

Also try to use much simpler code for reg_dig_sum with the same result:还尝试对 reg_dig_sum 使用更简单的代码,结果相同:

def reg_dig_sum(n):
    return (n - 1) % 9 + 1

I've used a simple function to do this for a long time:我用一个简单的 function 做了很长时间:

def sum_digits(num):
    if num <= 9:
        return num
    num = int(num / 10) + num - int(num / 10) * 10
    ''' takes the last digit of num off, and adds it to num. '''
    return sum_digits(num)

There are a lot of things you can find with this function.您可以使用这款 function 找到很多东西。 Try this on the power series, and you'll see what I mean.在电源系列上试试这个,你会明白我的意思。 Really any mathematical function you could use on a number line will return interesting patterns;实际上,您可以在数轴上使用的任何数学 function 都会返回有趣的模式; this function helps you see part of that.这个 function 可以帮助您看到其中的一部分。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM