使用python寫水仙花數、四葉玫瑰數、五角星數


#!/usr/bin/python
# -*- coding:utf-8 -*-

import time

# 格式化成2016-03-20 11:45:39形式
nowTime = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
print(nowTime)


def ThreeNum():
   three = []
   count = 0
   for i in range(100, 1000):
       n1 = i // 100  # 取整除 百位
       n2 = (i - n1 * 100) // 10  # 十位
       n3 = i % 10  # 個位
       n = pow(n1, 3) + pow(n2, 3) + pow(n3, 3)
       if i == n:
           count = count + 1
           three.append(n)
   print("水仙花數有 %s 個:%s" % (count, three))


def FourNum():
   four = []
   count = 0
   for i in range(1000, 10000):
       n1 = i // 1000  # // 取整除 千位
       n2 = (i - n1 * 1000) // 100  # 百位
       n3 = i % 10  # 個位
       n4 = (i - n1 * 1000 - n2 * 100) // 10  # 十位
       n = pow(n1, 4) + pow(n2, 4) + pow(n3, 4) + pow(n4, 4)
       if i == n:
           count = count + 1
           four.append(n)
   print("四葉玫瑰數有 %s 個:%s" % (count, four))


def FiveNum():
   five = []
   count = 0
   for i in range(10000, 100000):
       n1 = i // 10000  # 取整除 萬位
       n2 = (i - n1 * 10000) // 1000  # 千位
       n3 = i % 10  # 個位
       n4 = (i - n1 * 10000 - n2 * 1000) // 100  # 百位
       n5 = (i - n1 * 10000 - n2 * 1000 - n4 * 100) // 10  # 十位
       n = pow(n1, 5) + pow(n2, 5) + pow(n3, 5) + pow(n4, 5) + pow(n5, 5)
       if i == n:
           count = count + 1
           five.append(n)
   print("五角星數有 %s 個:%s" % (count, five))


if __name__ == "__main__":
   while True:
       print('''
       -------------開始------------------
       請選擇菜單:
       (0) 退出
       (1) 水仙花數
       (2) 四葉玫瑰數
       (3) 五角星數
       ----------------------------------
       ''')
       number_str = input("請輸入執行序號:")
       # if number_str == "":
       #     continue
       if number_str.isdigit():
           number = int(number_str)
       else:
           print("輸出錯誤,請重新輸入!")
           continue
       if number == 0:
           print("正在退出程序。。。")
           break
       elif number == 1:
           ThreeNum()
       elif number == 2:
           FourNum()
       elif number == 3:
           FiveNum()
       else:
           print("輸出錯誤,請重新輸入!")



免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM