12
\$\begingroup\$

The task is to make a list of every lotto row if in a lotto, seven numbers are chosen from 39 numbers. Is there more elegant way to do this than my solution:

rows = []
for a in range(1,40):
    for b in range(a+1,40):
        for c in range(b+1,40):
            for d in range(c+1,40):
                for e in range(d+1,40):
                    for f in range(e+1,40):
                        for g in range(f+1,40):
                           rows.append([a,b,c,d,e,f,g])
\$\endgroup\$
1
  • 1
    \$\begingroup\$ Regardless of the style of code, you will wait quite a lot its execution :) \$\endgroup\$ Nov 3, 2020 at 22:00

2 Answers 2

14
\$\begingroup\$

You could use itertools.combinations

import itertools

rows = list(itertools.combinations(range(1, 40), 7))

If you want to know how to implement this without using a built-in, just read the sample implementation of itertools.combinations in the document.

\$\endgroup\$
2
  • \$\begingroup\$ I'd go even further and use a set instead of a list just to be sure you have unique elements. \$\endgroup\$ Nov 3, 2020 at 13:53
  • \$\begingroup\$ @GrajdeanuAlex. The returned elements are guaranteed to be unique as long as the iterable (range(1, 40) here) itself has no duplicates. \$\endgroup\$
    – GZ0
    Nov 3, 2020 at 15:37
1
\$\begingroup\$

Code with this much indentation is never elegant, and it is very hard to maintain.

There is a programming principle called the Don't Repeat Yourself Principle sometimes referred to as DRY code. If you find yourself repeating the same code multiple times it is better to encapsulate it in a function. If it is possible to loop through the code that can reduce repetition as well.

\$\endgroup\$
1
  • 6
    \$\begingroup\$ I'm not sure how you'd do the DRY thing like that here. Rather sounds like you copied&pasted that paragraph from somewhere where that made more sense. \$\endgroup\$ Nov 3, 2020 at 12:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.