Good day!

I have a line of code where I write:

combined_elements = combinations(glob_elem, m) 

My task is to calculate the number of combined elements ...

I solved this problem like this:

 comb_length = len(list(combined_elements)) 

But there is such a problem that if the elements inside the array that I submit to the combinations() function exceed 84, it will give me a MemoryError and the program will stop working ...

But if I comment out or comb_length = len(list(combined_elements)) string comb_length = len(list(combined_elements)) and submit an array of length 1000 to the combinations() function, it will execute it without errors ..

Then I tried the second method:

 def get_length(my_combined_list): length = 0 try: while my_combined_list.next(): length += 1 except StopIteration: #ignored return length 

The second works, but unfortunately for a long time ...

What other way to calculate the number of generated combinations of elements?

    1 answer 1

    If your task is only to calculate the number of elements, then it can be reduced to the calculation of the number of combinations:

     In [1]: from math import factorial In [2]: def c(n, k): ...: return factorial(n) // factorial(k) // factorial(n - k) ...: In [3]: c(84, 10) Out[3]: 2761025887620 

    But if I comment out or remove the string comb_length = len (list (combined_elements)) and submit an array of length 1000 to the combinations () function, it will execute it without errors ..

    This is due to the fact that the combinations function is lazy - it returns an iterator, real data will be calculated only when iterating over it (using a list , for example).

    • Hmm)) It worked)) But everything is so simple: D - E1mir