In python, I want to have my program prompt me to 'Enter number:' and then I will do so. For example, I will enter '5' and in return I want it to find every combination of numbers between 1 and 5, including 1 and 5, that adds up to 5 without repeating any sequences or numbers. So the output of this should be the pairs 1,4 and 2,3. On top of that, I also want it to tell me how many outputs I have, so in this case 2. And I want to make sure that if I input a number higher, say 10, it will yield every combination even if it is larger than a pair, so it would yield 1,2,3,4 as one of the outputs and 1,9 as another, etc.
Asked
Active
Viewed 59 times
-1
-
5Have you _tried anything_? StackOverflow is not a code writing service. You should show us your attempts so we can help. We're not just going to code you a solution. – g.d.d.c Oct 05 '17 at 18:06
1 Answers
0
There you go, because I like playing with itertools, but yes, next time try something by yourself :
import itertools
val = int(input())
r = range(val)[1:]
res = []
for i in range(len(r)+1):
res += [list(x) for x in itertools.combinations(r, i) if sum(list(x)) == val]
print("Solution : %s " % res)
print("Combinations : %s" % len(res))
# For input 10 :
# Solution : [[1, 9], [2, 8], [3, 7], [4, 6], [1, 2, 7], [1, 3, 6], [1, 4, 5], [2, 3, 5], [1, 2, 3, 4]]
# Combinations : 9
This method is kind of a bruteforce, you could probably be much faster using maths.

Loïc
- 11,804
- 1
- 31
- 49
-
Thank you! I’m still new to the website so I’m getting used to the etiquette of the site still. – Gary Dinmore Oct 13 '17 at 14:03