python - Python 中的自恋数字

标签 python function

我是 Python 编程语言的初学者,我一直在使用一个网站来帮助我锻炼。如果给定的数字是 narcissistic,它给了我一个挑战来制作一个返回 true 的程序。否则为假。

自恋数字的例子:

153 (3 digits): 1^3 + 5^3 + 3^3 = 1 + 125 + 27 = 153
1634 (4 digits): 1^4 + 6^4 + 3^4 + 4^4 = 1 + 1296 + 81 + 256 = 1634

但由于某些原因,当给定数字 371 时,函数返回 False 而不是 True

代码:

def narcissistic(value):
    logical = True
    logical2 = True
    i = 0
    j = 0
    notation = 10
    sum = 0

    #Calculating the number notation 
    while logical:
        if 10 ** i <= value:
            notation = 10 ** i
            i = i + 1
        else:
            logical = False

    #i from now on is also the qauntity of digits
    while logical2:
        if ( notation / 10 ** j ) >= 1:
            sum = sum + ( value // ( notation / 10 ** j ) ) ** i
            j = j + 1
        else:
            logical2 = False

    if sum == value:
        return True
    else:
        return False

最佳答案

您的代码非常接近!问题出在这里:

sum = sum + ( value//( notation/10 ** j ) ) ** i

对于 1634,这将乘以 1161631634。您只需要这些数字的 LSB,在此示例中为 1634 - 使用模运算符得到这个。如果我们将它们修改 10 只得到 LSB...

sum = sum + (( value//( notation/10 ** j ) ) % 10) ** i

...那么代码就可以完美运行了。

Demo

关于python - Python 中的自恋数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58525842/

相关文章:

python - 装饰器会消耗更多内存吗?

python - 在 Greenplum(Postgres 8.4)中进行多行更新时跟踪错误记录?

python - python正则表达式中*和+的区别?

php - 错误: Dynamically fetching css from CDN with fallback to local copy, 如何解决?

c++ - 帮助将 C++ 代码转化为函数

function - 是否可以在 autofac 中注册一个开放通用委托(delegate)?

PYTHON - 为什么多处理池使用 100% 的 CPU?

python - 为什么这个正则表达式匹配给出这个结果?

c++ - 重载函数声明的顺序在 C++ 中重要吗?

c - 8步音序器中的功能