gpt4 book ai didi

python - Python中带break命令的随机函数

转载 作者:行者123 更新时间:2023-11-30 23:15:17 25 4
gpt4 key购买 nike

  1. 编写一个函数,接受 3 个数字并计算这 3 个数字的平均值,并将平均值提高到二次方(返回平均值的平方)。

  2. 编写一个循环来查找 3 个随机均匀数(0 到 1);将 3 个数字发送到函数,并当函数的值大于 0.5625 时停止循环

我试图弄清楚这两件事,但我有点困惑。

import random 

a = random.random ()
b = random.random ()
c = random.random ()

def avenum(x1,x2,x3): # the average of the 3 numbers
z = (x1+x2+x3)/3.0
return z

y = avenum(a,b,c)

print 'the average of the 3 numbers = ',y


def avesec(x1,x2,x3): # the average of the second power
d = ((x1**2)+(x2**2)+(x3**2))/3.0
return d

y1 = avesec(a,b,c)

print 'the average of the second power = ',y1

最佳答案

第一个问题:

Write a function that accepts 3 numbers and calculates the average of the 3 numbers and raises the average to the second power (returns the average squared).

def square_of_average(x1, x2, x3):
z = (x1 + x2 + x3) / 3
return z ** 2 # This returns the square of the average

你的第二个问题:

Write a loop that finds 3 random uniform numbers (0 to 1); sends the 3 numbers to the function and stops the loop when the value of the function is greater than 0.5625.

假设您想在另一个函数中编写此代码:

import random
def three_random_square_average():
z = 0 # initialize your answer
while(z <= 0.5625): # While the answer is less or equal than 0.5625...
# Generate three random numbers:
a, b, c = random.random(), random.random(), random.random()
# Assign the square of the average to your answer variable
z = square_of_average(a, b, c)
# When the loop exits, return the answer
return z

另一种选择:

import random
def three_random_squared_average():
while(True):
a, b, c = random.random(), random.random(), random.random()
z = square_of_average(a, b, c)
if(z > 0.5625):
break
return z

如果您不需要函数:

import random
z = 0
while(z < 0.5625):
z = square_of_average(random.random(), random.random(), random.random())
print z

关于python - Python中带break命令的随机函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28311636/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com