-1

I need to write a script that will generate 5 random whole numbers that sum up to 210 and then take these 5 generated numbers and write them to excel using openpyxl, the excel sheet will then check to see if a certain cell's content is less than a certain number and if it isn't then the program will run again until it checks out.

so far I have defined my workbook and worksheet in question I have tried the following to generate the random numbers

a = np.random.random(210)

a /= a.sum()

The numbers returned aren't whole numbers...that's the first problem.

My other problem is going to be storing the 5 random numbers in a way that I can use them with an if statement to write to my excel sheet.

I've written many scripts that interact with excel but I haven't tried to do anything like this where it will be constantly looping and checking and i'm a bit in over my head.

If you have any helpful info it would be very much appreciated!! Thank you!!

M Z
  • 4,571
  • 2
  • 13
  • 27
pokenote
  • 19
  • 2
  • Does this answer your question? [How to get N random integer numbers whose sum is equal to M](https://stackoverflow.com/questions/59148994/how-to-get-n-random-integer-numbers-whose-sum-is-equal-to-m) – Peter O. Jan 27 '21 at 05:00
  • Technical nit-pick. You only have four random numbers. The fifth number is not random but is equal to 210 - (sum of previous four). – rossum Jan 27 '21 at 09:01

1 Answers1

1

You might get better luck writing two questions for this. I can help with the first:

For your first question, your code doesn't make any sense. You end up with 210 numbers that end up adding to 1. Second, why are you using Excel at all to do a check? Just load e

import random
a = sorted(random.sample(range(1,209), k=4))
a = [a[0], *(a[i] - a[i-1] for i in range(1,4)), 210 - a[3]]
print(sum(a), len(a))

# output:
# 210 5

We select 4 "split" points from 1 through 209 (I'm not allowing 0s or negatives, though that would be an easy change: please specify if that's the case).

For you second question, it is important to note that openpyxl itself may not evaluate formulas. You might want to look into another module to do that for you, like xlwings.

Don't expect free code on StackOverflow.

M Z
  • 4,571
  • 2
  • 13
  • 27