第4章-8 求分数序列前N项和
n=int(input())
a=[0 for i in range(0,n+10)]
b=[0 for i in range(0,n+10)]
a[1]=2.0
a[2]=3.0
b[1]=1.0
b[2]=2.0
for i in range(3,n+10):
a[i]=a[i-1]+a[i-2]
b[i]=b[i-1]+b[i-2]
sum=0.0
for i in range(1,n+1):
sum+=a[i]/b[i]
print("{:.2f}".format(sum))
第4章-9 查询水果价格
list=input().split(" ")
#print(len(list))
print("[1] apple")
print("[2] pear")
print("[3] orange")
print("[4] grape")
print("[0] exit")
count=0
while count<5:
# print(list[count])
if list[count]=='1':
print("price = {:.2f}".format(3.00))
elif list[count]=='2':
print("price = {:.2f}".format(2.50))
elif list[count]=='3':
print("price = {:.2f}".format(4.10))
elif list[count]=='4':
print("price = {:.2f}".format(10.20))
elif list[count]=='0':
break
else:
print("price = {:.2f}".format(0.00))
count+=1
第4章-10 最大公约数和最小公倍数
def gcd(a,b):
if b==0:
return a
else:
return gcd(b,a%b)
a,b=map(int,input().split(" "))
gcdnum=gcd(a,b)
print("{:d} {:d}".format(gcdnum,int(a*b/gcdnum)))
第4章-11 判断素数
def judge(num):
if num==1 or num==0:
return 0
elif num==2 or num==3:
return 1
else:
for i in range(2,int(num**0.5+1)):
if num%i==0:
return 0
return 1
t=int(input())
for i in range(0,t):
num=int(input())
if judge(num)==1:
print("Yes")
else:
print("No")
第4章-12 求满足条件的斐波那契数
n=int(input())
a=1
b=1
while True:
if a+b>n:
print(a+b)
break
else:
aa=a
a=b
b=aa+b
第4章-13 求误差小于输入值的e的近似值
ee = float(input())
aa = 1
ii = 2
tt = 2
bb = 1 / tt
sum = 1 + 1
e1 = 1
e2 = sum
while e2 - e1 >= ee:
e1 = e2
aa = bb
sum = sum + aa
e2 = sum
ii = ii + 1
tt = tt * ii
bb = 1 / tt
print('{:.6f}'.format(sum))
第4章-14 统计字符
length=0
list=[]
count=0
while True:
s=input()
length+=len(s)
list.append(s)
count+=1
if length +count>10:
count-=1
break
l=0
b=0
o=0
d=0
for i in list:
for j in range(0,len(i)):
#print(i[j]+"--------")
if i[j].isspace():
b+=1
elif i[j].isdigit():
d+=1
elif i[j].isalpha():
l+=1
else:
o+=1
print("letter = {:d}, blank = {:d}, digit = {:d}, other = {:d}".format(l,b+count,d,o));
# print(l)
# print(b)
# print(d)
# print(o)