Home > front end >  Trying to get all combinations without duplicated numbers
Trying to get all combinations without duplicated numbers

Time:12-21

I am trying to make a 5 number combination but without repeating the same number. My numbers are from 1 to 45 and I am trying to see the multiple combinations that they can have.

So far I have been able to print and save the combinations. But from the data I can see that there are many duplicates values.

For example: (34,34,34,35,37)

What I want to do is basically have each number not repeat itself like if its 34 then it cant come again into the combination set of 5

`

from itertools import combinations_with_replacement
import sys

#get all combinations of 1, 2, nad length 10

c= combinations_with_replacement([1, 2, 3, 4, 5, 6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45], 5)

print(sys.getsizeof(c))

print(c)

res = str(''.join(map(str,c)))

file= open("sample.txt","w")

file.write(res)

file.close()
print(res)

`

CodePudding user response:

The following code will print out all the combinations, one per line.

import itertools

numbers = range(1, 46)  # Set of numbers to choose from (1 to 45)
combinations = itertools.combinations(numbers, 5)  # Generate all combinations of 5 numbers

for combination in combinations:
  print(combination)

CodePudding user response:

Welcome to stackoverflow. If you simply use the following, you won't have combinatoins with repeated elements:

import itertools
my_list = range(45)
my_iters = list(itertools.combinations(my_list, 5))

You can check this is the case simply by comparing the length of each elemnt of my_iters with the length of the subsequent set:

my_iters_unique = [x for x in my_iters  if len(set(x)) == len(x)]

And you will see the length of my_iters_unique and my_iters are the same.

  • Related