python - 查找数字^(数字位置)==原始数字即(89 = 8^1 + 9^2)的数字,但代码不会返回高于1306的任何数字?

标签 python

def sum_dig_pow(a, b): 
    return [i for i in range(a, b + 1) if sum([int(x) ** (str(i).index(x) + 1) for x in str(i)]) == i]

sum_dig_pow(1, 2000) 得到 1 到 1306 的所有答案,然后没有高于此的答案?

最佳答案

我认为,您的代码不起作用,因为缺少的解决方案 1676 包含 6 的两倍。因此 str(i).index(x) 将为第二个 6 返回错误的索引这使得计算错误。

我想,这是一次,我在没有列表理解的情况下开始,首先让代码工作。这通常是您想要的结果吗?

def sum_dig_pow(a, b): 
    result = []
    for number in range(a, b+1):
        calculation = 0
        for position, digit in enumerate(map(int, str(number))):
            calculation += digit**(position + 1)
        if calculation == number:
            result += [number]
    return result

print(sum_dig_pow(1, 2000))

打印内容:

[1, 2, 3, 4, 5, 6, 7, 8, 9, 89, 135, 175, 518, 598, 1306, 1676]

然后将其减少为:

def sum_dig_pow(a, b): 
    result = []
    for number in range(a, b+1):
        calculation = sum([digit**(position + 1) for position, digit in enumerate(map(int, str(number)))])
        if calculation == number:
            result += [number]
    return result

然后:

def sum_dig_pow(a, b): 
    return [number for number in range(a, b+1) if sum([digit**(position + 1) for position, digit in enumerate(map(int, str(number)))]) == number]

但我认为为什么你只想用列表理解来写这个仍然是个问题?那么你至少可以使用一句单行话;-)

sum_dig_pow = lambda a, b: [number for number in range(a, b+1) if sum([digit**(position + 1) for position, digit in enumerate(map(int, str(number)))]) == number]

关于python - 查找数字^(数字位置)==原始数字即(89 = 8^1 + 9^2)的数字,但代码不会返回高于1306的任何数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53771277/

相关文章:

python - 检测交替迹象

python - 如何更改 Button 小部件的文本大小?

python - 发送带有 3 个不同附件的一封电子邮件 python 3

python - 为 solve_ivp 传递参数(新的 SciPy ODE API)

python - 从 pandas 网站读取大型数据集仅返回 1.000 行?

python - 如何从 Azure ML 中的 python 脚本获取 Web 服务的输出

python - 根据列表中项目内的部分字符串查找列表中的所有索引位置

python - psycopg2 - 如何始终将非字符串值转换为字符串

python - Tweepy 中的分页

python - 2个关键字之间的Scrapy xpath