I have a number, let, 17. I want to randomly break it into two parts, in such a way that sum of these parts give the result 17. Eg. 13 + 4, 12 + 5...But I also want that these two parts must not have 2 as a number. Any algorithm or code in Python. Please help.
Asked
Active
Viewed 67 times
-3
-
22 as a digit or 2 as a number? any attempt from you? – wim Sep 22 '18 at 02:13
-
For a given number `n`, you're trying to generate numbers `2 < x < n-2` and `n-x`? – Patrick Haugh Sep 22 '18 at 02:14
-
1The essential idea of how to do constrained randomization in python is in this other question, but for a different problem: https://stackoverflow.com/questions/18448417/create-constrained-random-numbers – Paul Sep 22 '18 at 02:20
-
2 as a number @wim – Abhishek Singh Sep 22 '18 at 02:30
-
Yes sir @Patrick – Abhishek Singh Sep 22 '18 at 02:32
-
So you don't want 0 or 1? Or you do? – ubadub Sep 22 '18 at 02:39
-
I wanted two numbers but those numbers must not be 2.. – Abhishek Singh Sep 22 '18 at 04:50
1 Answers
1
Use random.randint() to generate the first number and then subtract it from n, we got the second number. The if else statement make sure neither of num1 and num2 is equal to 2. Hope this is helping!
import random
def break_num(n):
while True:
num1 = random.randint(1, n - 1)
num2 = n - num1
if num1 != 2 and num2 != 2:
break
else:
continue
print(f'{num1} + {num2}')

Jimmy Lin
- 44
- 4