Python基础练习题
程序员文章站
2024-02-24 13:44:22
...
Python基础练习题
# -*- coding:utf-8 -*-
"""question 1:判断101-200之间有多少个素数,并输出所有素数"""
import math
prime_number = []
for num in range(101,201):
count = 0
for divisor in range(2,int(math.sqrt(num))+1)
if num % divisor == 0:
count += 1
if count == 0:
prime_number.append(num)
print(prime_number)
print("101~200之间的素数共有%d个。"%len(prime_number))
"""question 2:打印出所有的"水仙花数",所谓"水仙花数"是指一个三位数,其各位数字立方和等于该数本身。例如:153是一个"水仙花数",因为153=1的三次方+5的三次方+3的三次方"""
import math
narcissistic_number = []
for num in range(100,1000):
hundreds = math.floor(num / 100)
decade = math.floor((num % 100)/10)
single = ((num % 100) % 10)
if num == int(math.pow(hundreds,3) + math.pow(decade,3) + math.pow(single,3)):
narcissistic_number.append(num)
print(narcissistic_number)
"""question 3:
求s=a+aa+aaa+aaaa+aa...a的值,其中a是一个数字。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘控制"""
# 方法1
def special_array(a,n):
li = []
for i in range(1,n+1):
b = a*i
s = int(b)
li.append(s)
print(li)
sum = 0
for i in range(n):
sum = sum + li[i]
print(sum)
num = input("请输入一个1~9之间的数字字符:")
if (num>='a') & (num<='z'):
print("您输入的字符超出数字字符范围,请重新输入")
else:
count = int(input("请输入一个数值:"))
special_array(num,count)
# 方法2
def special_array(a,n):
Sn = 0
Tn = 0
li = []
for i in range(n):
Tn = Tn + a
a = a * 10
li.append(Tn)
print(li)
for i in range(n):
Sn += li[i]
print(Sn)
num = int(input("请输入一个1~9之间的数字字符:"))
count = int(input("请输入一个数值:"))
special_array(num,count)
"""question 4:一个数如果恰好等于它的因子之和,这个数就称为"完数"。例如6=1+2+3.编程找出1000以内的所有完数"""
import math
perfect_number = []
for num in range(3,1000):
sum = 1
factor = []
for divisor in range(2,int(math.sqrt(num))+1):
if num % divisor == 0:
quotient = int(num/divisor)
factor.append(divisor)
factor.append(quotient)
for i in factor:
sum += i
if sum == num:
perfect_number.append(num)
print(perfect_number)
上一篇: poi设置日期格式