RE: Maths Brain Teasers 62:: Adding up to 1k - Can You Solve iT?

avatar

You are viewing a single comment's thread:

hehe, I think you made a similar copy&paste mistake than me :D
328 should be 382

You can use random.sample then you don't need to check for duplicates:

from random import sample
nums = [373, 135, 30, 375,
        126, 411, 416, 64,
        73, 382, 66, 128,
        418, 21, 23, 425]

sel = []
while sum(sel) != 1000:
    sel = sample(nums, 5)

print(sorted(sel))


0
0
0.000
1 comments
avatar

Ah whoops fixed that now. Thank you for letting me know. I tend to mistype and misread numbers a lot, so I'm not super surprised I messed that up :)

I could have done it using random samples, but I had assumed there might be multiple solutions, so I wanted to iterate over all possible ones instead. That solution does work too.

Also, I looked back at itertools's documentation and realized I missed that there is a itertools.combinationsfunction I missed that would work as well and make the code I had simpler.

0
0
0.000