In [6]:
#练习 1:写函数,求n个随机整数均值的平方根,整数范围在m与k之间。
import random,math
def operation(n,m,k):
i=0
sum=0
while i < n:
t = random.randint(m,k)
sum=sum+t
print(t)
i += 1
print (math.sqrt(sum/n))
n=int(input('Enter the number of the integers: '))
m=int(input('Enter the least num of the range: '))
k=int(input('Enter the largest num of the range: '))
operation(n,m,k)
In [ ]:
In [ ]:
In [ ]:
In [7]:
#练习 2:写函数,共n个随机整数,整数范围在m与k之间,求西格玛log(随机整数)及西格玛1/log(随机整数)
import random,math
def operation(m,n,k):
i=0
sum1=0
sum2=0
while i < n:
t = random.randint(m,k)
print(math.log(t),1/math.log(t))
sum1=sum1+math.log(t)
sum2=sum2+1/math.log(t)
i += 1
print (sum1,sum2)
n=int(input('Enter the number of the integers: '))
m=int(input('Enter the least num of the range: '))
k=int(input('Enter the largest num of the range: '))
operation(m,n,k)
In [ ]:
In [8]:
#练习 3:写函数,求s=a+aa+aaa+aaaa+aa...a的值,其中a是[1,9]之间的随机整数。例如2+22+222+2222+22222(此时共有5个数相加),几个数相加由键盘输入。
import random,math
def operation(n):
i=0
sum=0
an=0
a=random.randint(1,9)
print(a)
while i<n:
an=an+a
sum=sum+an
a=a*10
i=i+1
print(sum)
n=int(input('Enter the number of the integers: '))
operation(n)
In [ ]:
In [9]:
#挑战性练习:仿照task5,将猜数游戏改成由用户随便选择一个整数,让计算机来猜测的猜数游戏,要求和task5中人猜测的方法类似,但是人机角色对换,由人来判断猜测是大、小还是相等,请写出完整的猜数游戏。
import random
n = int(input('请输入一个大于0的整数,作为神秘整数的上界,回车结束。'))
m = int(input('请输入一个大于0的整数,作为神秘整数的下界,回车结束。'))
a=random.randint(m,n)
print ('电脑猜测值为',a)
answer='Yes'
judge=input('比较电脑猜测值与正确答案大小: ')
while judge!=answer:
if judge=='larger':
mid=int((m+n)/2)
print('中间值为:',mid)
compare=input('比较中间值和正确答案的大小: ')
if compare=='larger':
n=mid
elif compare=='smaller':
m=mid
elif compare=='equal':
print('This is the answer')
break
a=random.randint(m,n)
print ('电脑猜测值为',a)
elif judge=='smaller':
mid=int((m+n)/2)
print('中间值为:',mid)
compare=input('比较中间值和正确答案的大小: ')
if compare=='larger':
n=mid
elif compare=='smaller':
m=mid
elif compare=='equal':
print('This is the answer')
break
a=random.randint(m,n)
print ('电脑猜测值为',a)
judge=input('比较电脑猜测值与正确答案的大小: ')
In [ ]: