Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Need string output with combination on integers

I have a dictionary, with ‘int’ as keys

{12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}

and I am trying to create a string for each possible combination for 12, 13, 14, 15. The string should look start from ‘Gen’

['Gen_12_13',
 'Gen_12_14',
 'Gen_12_15',
 'Gen_13_14',
 'Gen_13_15',
 'Gen_14_15',
 'Gen_12_13_14',
 'Gen_12_13_15',
 'Gen_12_14_15',
 'Gen_13_14_15',
 'Gen_12_13_14_15']

I used the ‘combination’ function to get all the combinations first and then tried to iterate through it to create the ‘Gen’ string.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

dict_gens = {12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}
all_gens = list(dict_gens.keys())
list_comb = list()
name_comb = list()
counter = 0

for item in range(2, len(all_gens)+1):
    combs = combinations(all_gens, item)
    for comb in combs:
        list_comb.append(comb)
        
for comb in list_comb:
    if counter <= len(comb):
        for comb_item in comb:
#             print(comb_item)
            name = '_' + str(comb_item)
            counter+=1
        name_comb.append('Gen'+name)

>Solution :

The itertools.combinations part looks right, but the loop where you’re building the final strings looks unnecessarily complex; just use str.join to join the combinations into the desired strings.

>>> gens = {12: '2012-Q1', 13: '2014-Q2', 14: '2017-Q2', 15: '2019-Q3'}
>>> from itertools import combinations
>>> ["Gen_" + "_".join(map(str, c)) for n in range(len(gens) - 1) for c in combinations(gens, n+2)]
['Gen_12_13', 'Gen_12_14', 'Gen_12_15', 'Gen_13_14', 'Gen_13_15', 'Gen_14_15', 'Gen_12_13_14', 'Gen_12_13_15', 'Gen_12_14_15', 'Gen_13_14_15', 'Gen_12_13_14_15']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading