Python脚本生成一组带有约束的随机数

fgw7neuy  于 12个月前  发布在  Python
关注(0)|答案(1)|浏览(189)

我想该脚本输出159个随机数之间的“0.04”和“4.5”,有一个总匹配的目标总数。这是我到目前为止,但这只产生142个数字。我如何强制它创建159个数字?

import random

target_total = 298.51
total_numbers = 159
min_value = 0.04
max_value = 4.50

random_numbers = []

for i in range(total_numbers - 1):
    # Generate a random number within the specified range
    num = round(random.uniform(min_value, max_value), 2)  # Limit to 2 decimal places
    
    # Append the number to the list
    random_numbers.append(num)
    
    # Calculate the current sum of numbers
    current_sum = round(sum(random_numbers), 2)
    
    # If the current sum exceeds the target total, remove the last number
    while current_sum > target_total:
        excess = current_sum - target_total
        random_numbers.remove(random_numbers[-1])
        current_sum = round(current_sum - excess, 2)

# The last number is adjusted to reach the target total
last_num = round(target_total - sum(random_numbers), 2)
random_numbers.append(last_num)

# Print each generated number with row numbers on a new line
for i, num in enumerate(random_numbers, start=1):
    print(f"Row {i}: {num}")

print("Total sum:", round(sum(random_numbers), 2))

字符串

jv4diomz

jv4diomz1#

问题在于:虽然max_value是4.50,但如果创建的随机数的数量接近最大值,为了达到目标总数,将使用较少的总数。此外,如果我们使用这种方法,循环将继续无限的数字。所以我们必须自己决定max_value。这里我给出了一个更好的方法。并在里面给出解释:

import random as rd
target_total = 298.51
total_numbers = 159
each_number = target_total/total_numbers

#calculate the sum of adjacent two numbers
adj_sum = each_number*2

min_value = 0.04
random_numbers = []

#create a loop for 1 number less than the total numbers i.e 158. 
# We will find out the last number afterwards
for i in range(total_numbers-1):
    #generate random number only for even index
    if i%2==0:
        #generate random_number between min_value and the adj_sum
        
        number = rd.uniform(min_value, adj_sum)
    #if i is odd the random number should be the difference between adj_sum and previous number
    else:
        number = adj_sum - number
    
    #round_off to 2 decimals and append
    random_numbers.append(round(number,2))

#find the last number

sum = round(sum(random_numbers), 2)
last_number = round((target_total - sum),2)

#append the last number
random_numbers.append(last_number)

sum = sum + last_number

for i, num in enumerate(random_numbers, start=1):
    print(f"Row {i}: {num}")

print("Total sum:", round(sum, 2))

字符串
如果你想让每个随机数都是唯一的,你可以在第18行之后添加一个while循环。也就是说,我已经包含了你应该插入以下代码的那一行

#generate random_number between min_value and the adj_sum(line 17)
    number = rd.uniform(min_value, adj_sum) #line 18
    j = 0
    while j>=0:
        if number not in random_numbers:
            break
        else:
            j += 1

相关问题