1. 采用 reduce完成以下人员的年龄的累加和运算.
数据为:
scientists =({‘name’:‘Alan Turing’, ‘age’:105},
{‘name’:‘Dennis Ritchie’, ‘age’:76},
{‘name’:‘John von Neumann’, ‘age’:114},
{‘name’:‘Guido van Rossum’, ‘age’:61})
方法一:
from functools import reduce
import operator
scientists =({'name':'Alan Turing', 'age':105},
{'name':'Dennis Ritchie', 'age':76},
{'name':'John von Neumann', 'age':114},
{'name':'Guido van Rossum', 'age':61})
count=[]
for i in scientists:
for index,value in list( enumerate(i.values()) ):
if 1 is index:
count.append(value)
print(reduce(operator.add,count))
print('总人数',len(count),'总年龄 ',sum(count),'平均年龄:',sum(count)/len(count))
方法二:
from functools import reduce
scientists =({'name':'Alan Turing', 'age':105,'a':1},
{'name':'Dennis Ritchie', 'age':76,'a':1},
{'name':'John von Neumann', 'age':114,'a':1},
{'name':'Guido van Rossum', 'age':61,'a':1})
def add(ac,value):
sum=ac+value['age']
return sum
age=reduce(add,scientists,0)
print(age,age/len(scientists))
2. 用户输入一个三位自然数,计算并输出其佰位、十位和个位上的数字方法
方法一:
i1=input("输入一个三位的自然数:")
t=0
h=0
ge=0
for index,value in list(enumerate( list(map (int,str(i1))) )):
if 0 is index:
t=value
if 1 is index:
h=value
if 2 is index:
ge=value
print('千位:',t,"百位:",h,"个位:",ge)
方法二:
i1=input("输入一个三位的自然数:")
x=int(i1)
a=x//100
b=x//10%10
c=x%10
print('千位:',a,"百位:",b,"个位:",c)
3. 输入三角形的两边长及其夹角,求第三边长
import math
x=input("两个的边长和夹角度数为:")
b,c,a=map(float,x.split(","))
aa=math.cos(math.radians(a)) #math.cos(x) x是弧度 math.radians(x) x是角度,,函数将角度转化为弧度
print(math.cos(math.radians(a)))
print('边长为:',math.pow((b*b+c*c-2*b*c*aa),1/2))
4. 距离运算
a) 曼哈顿距离 b) 欧氏距离 c) 切比雪夫距离 d) 夹角余弦 (相似度)
import math
x=float(input("地点1的x坐标为:")),float(input("地点1的y坐标为:"))
y=float(input("地点2的x坐标为:")),float(input("地点2的y坐标为:"))
print( '曼哈顿距离:',abs(x[0]-y[0]) + abs(x[1]-y[1]) )
print( '欧氏距离:',math.pow((abs(x[0]-y[0])*abs(x[0]-y[0])+abs(x[1]-y[1])*abs(x[1]-y[1])),1/2))
print('切比雪夫距离:',max(abs(x[0]-y[0]), abs(x[1]-y[1])))
def cosVector(x,y):
if(len(x)!=len(y)):
print('error input,x and y is not in the same space')
return;
result1=0.0;
result2=0.0;
result3=0.0;
for i in range(len(x)):
result1+=x[i]*y[i]
result2+=x[i]**2
result3+=y[i]**2
print(" 余弦值为: "+str(result1/((result2*result3)**0.5))) #结果显示
cosVector(list(x),list(y))