在某人工智能培训班看到这个预热练习,来玩一下~
题目意思说白了就是用户输入一个数,判断其是否只能被2,3,5整除,能就列出被整除的过程,不能就返回None
原题目【吐槽一句真不易读。。】
Simple Number Finding
You are playing a card game with your friends. This game in China named “扎金花”. In this game, the
2, 3, 5 are some simple powerful numbers. Because the combination of 2,3,5 is less than any other combinations but greater than the AAA, which is the king in this game. In today, you want to find if a number is a simple number, in which their factors only include 2, 3 and 5.
So your task is to find out whether a given number is an amazing number.
E.g
Input: 6
Output: (2, 3) Explanation: 6 = 2 x 3
Input: 8
Output: (2, 2, 2) Explanation: 8 = 2 x 2 x 2
Input: 14
Output:None
Explanation: 14 is not amazing since it includes another prime factor 7.
How to check your answer:
If you test 1845281250, your program should give
(2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5) 10个3,6个5
If you test 3690562500, your program should give (2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5);
If you test 1230187500, your program should give (2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 5, 5, 5, 5, 5);
If you test 10023750, your program should give None;
思路:把数字格式化后去分别除2,3,5,
除完后判断剩下的部分是不是质数
献上代码:
#列出被2整除的过程
def divide2(ip):
while ip%2==0:
ls.append(2)
ip = ip/2
return ip
#列出被3整除的过程
def divide3(ip):
while ip%3==0:
ls.append(3)
ip = ip/3
return ip
#列出被3整除的过程
def divide5(ip):
while ip%5==0:
ls.append(5)
ip = ip/5
return ip
#判断剩余部分是否为质数(1,2,3,5除外),非整数也顺手排除掉了
def prime(n):
if n == 1 or type(n) != int:
return False
else:
for i in range(2,n):
if n%i == 0:
return False
return True
#把几个函数串一起
def divide(ip):
ip2 = divide2(ip)
ip3 = divide3(ip2)
ip5 = divide5(ip3)
if prime(int(ip5)):
print('None')
else:
print(ls)
ip = eval(input())
ls = []
#怕出bug,来个try-except
try:
divide(ip)
except:
print('None.')
最后,看到另一位博主的版本,看着真不错:
https://blog.csdn.net/kingroc/article/details/91447690
求大佬指教嘤~
Have fun~