您的位置:

Python水仙花数详解

一、Python水仙花数100~999


for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i:
        print(i)

对于100~999的范围,我们可以使用for循环从100到999进行遍历,将每个数的各位数值分离出来,按照水仙花数的判定条件进行判断,如果成立则输出该数。

二、Python水仙花数的编程代码

Python水仙花数的代码可以使用for循环和while循环来实现。


# for循环实现
for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i:
        print(i)

# while循环实现
i = 100
while i <= 999:
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i:
        print(i)
    i += 1

三、Python水仙花数的编程代码三位数

如果只需要求出三位数的Python水仙花数,则可以使用range(100, 1000)代替range(1, 10)。


for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i:
        print(i)

四、Python水仙花数怎么找

Python水仙花数是指一个三位数的各位数字的立方和等于该数本身,因此,我们可以将每个三位数按照水仙花数的判定条件进行判断,如果成立则为水仙花数。

五、Python水仙花数求和


sum = 0
for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i:
        sum += i
print(sum)

对每个符合水仙花数条件的数进行累加求和,最后输出结果。

六、Python水仙花数for循环

使用for循环来实现Python水仙花数的求解。


for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i:
        print(i)

七、Python水仙花数函数


def narcissistic_number(start, end):
    res = []
    for i in range(start, end + 1):
        num_list = list(str(i))
        a = int(num_list[0])
        b = int(num_list[1])
        c = int(num_list[2])
        if a**3 + b**3 + c**3 == i:
            res.append(i)
    return res

将Python水仙花数封装成一个函数,可以根据输入的起始数和终止数来获取指定范围内的水仙花数。

八、Python水仙花数的代码

完整的Python水仙花数代码如下:


for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i:
        print(i)

九、Python水仙花数1000以内


for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])
    if a**3 + b**3 + c**3 == i and i < 1000:
        print(i)

当判断的范围为1000以内时,可以在判断水仙花数的条件中添加i < 1000这个判断条件。

十、Python水仙花数的编程讲解

Python水仙花数指的是一个三位数的各位数字的立方和等于该数本身,例如153是一个水仙花数,因为1的立方加5的立方加3的立方等于153。那么在Python中如何来判断一个三位数是否为水仙花数呢?

第一步,使用for循环遍历100~999的每个数,并将百位、十位、个位数字分离出来。


for i in range(100, 1000):
    num_list = list(str(i))
    a = int(num_list[0])
    b = int(num_list[1])
    c = int(num_list[2])

第二步,按照水仙花数的判定条件进行判断,并输出符合条件的水仙花数。


if a**3 + b**3 + c**3 == i:
    print(i)

通过上述两个步骤,我们就可以求解出Python水仙花数。