AnswerBun.com

How to generate dynamically combinations of list in python

Stack Overflow Asked by Camille Gallet on January 3, 2022

I want to generate combination dynamically in python, I have a var sessionperweeks (between 2 and 6)

if sessionperweeks==2

    for i in range(0,7):
        for j in range(i+1,7):
            combins.append([i,j])

if sessionperweeks==3

    for i in range(0,7):
        for j in range(i+1,7):
            for k in range(j+1,7):
                combins.append([i,j,k])

and so on

One Answer

Here you go, using combinations from itertools to pick sessions per week from 0-6:

from itertools import combinations

sessionsperweek = int(input("Enter sessions per week:"))

combins = list(combinations(range(7), sessionsperweek))
print("Your possible combinations are:")
print(combins)

Example run with 2 (since OP updated):

Enter sessions per week:2
Your possible combinations are:
[(0, 1), (0, 2), (0, 3), (0, 4), (0, 5), (0, 6), (1, 2), (1, 3), (1, 4), (1, 5), (1, 6), (2, 3), (2, 4), (2, 5), (2, 6), (3, 4), (3, 5), (3, 6), (4, 5), (4, 6), (5, 6)]

Example run:

Enter sessions per week:6
Your possible combinations are:
[(0, 1, 2, 3, 4, 5), (0, 1, 2, 3, 4, 6), (0, 1, 2, 3, 5, 6), (0, 1, 2, 4, 5, 6), (0, 1, 3, 4, 5, 6), (0, 2, 3, 4, 5, 6), (1, 2, 3, 4, 5, 6)]

Answered by Christian Sloper on January 3, 2022

Add your own answers!

Related Questions

Pass a generic class in method parameter

2  Asked on December 18, 2021 by astha-srivastava

     

Create a pivot table using two columns treating them as a group

2  Asked on December 18, 2021 by chris-reiche

         

PHP get data form XML using PHPSimpleXML

2  Asked on December 18, 2021 by xenpanda

     

docker commands not working with latest version

1  Asked on December 18, 2021 by rod-talingting

     

Space line above sticky top navbar

0  Asked on December 18, 2021 by aurelien

     

PHP for directory as opposed to a file

1  Asked on December 18, 2021 by j-lo

   

Pandas to Json Formatting issue

1  Asked on December 18, 2021 by petereg157

       

react-native-camera orientation change freeze

0  Asked on December 18, 2021 by xtealer

         

KeyError is raised when key exists in dictionary

2  Asked on December 18, 2021 by andrey-kiselev

   

How to insert date and time in Oracle databases?

1  Asked on December 18, 2021 by clancinio

         

How to get one data from database by id (MEAN Stack)?

1  Asked on December 16, 2021 by dorottya-burmeister

         

Ask a Question

Get help from others!

© 2023 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir