python学习——练习题(13)

时间:2023-02-22 14:16:15
"""
题目:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",
因为153=1的三次方+5的三次方+3的三次方。
程序分析:利用for循环控制100-999个数,每个数分解出个位,十位,百位。
"""


def answer1():
    """
    正常for循环比较
    :return:
    """
    print("输出一", end=":")
    for i in range(100, 1000):
        a = i // 100
        b = i % 100 // 10
        c = i % 10
        if i == a ** 3 + b ** 3 + c ** 3:
            print(i, end=",")


answer1()


def answer2():
    """
    逆向思维,有三个一位数组合成一个三位数
    :return:
    """
    print("\n输出二", end=":")
    for i in range(1, 10):
        for j in range(0, 10):
            for k in range(0, 10):
                if i ** 3 + j ** 3 + k ** 3 == i * 100 + j * 10 + k:
                    print(i * 100 + j * 10 + k, end=",")


answer2()


def answer3():
    """
    通过类型转换来获取三位数的各位数值
    :return:
    """
    print("\n输出三", end=":")
    for i in range(100, 1000):
        s = str(i)
        if pow(int(s[0]), 3) + pow(int(s[1]), 3) + pow(int(s[2]), 3) == i:
            print(i, end=",")


answer3()


def answer4():
    """
    领用divmod函数来计算
    :return:
    """
    print("\n输出四", end=":")
    for i in range(100, 1000):
        m = i
        sumNum = 0
        while m > 0:
            m, n = divmod(m, 10)
            sumNum += n ** 3
        if sumNum == i:
            print(i, end=",")


answer4()


def answer5():
    """
    利用列表for if 用法来实现
    :return:
    """
    print("\n输出五", end=":")
    L = [i for i in range(100, 1000) if (i // 100) ** 3 + (i // 10 % 10) ** 3 + (i % 10) ** 3 == i]
    print(L)


answer5()