Dev
Dev

Reputation: 586

Removing one name from command line and taking the combinations of the rest

I want to run my python code using : python3 combinations.py 4 A B C D

Where 4 are the number of characters I want to see the combinations of and A,B,C and D are those 4 characters. But the challenge is I always want to omit out D from that combination's output. So the output for the above case will be : A, B, C, AB, AC, BC, ABC

This is what I am trying. But this will only work if the last command line argument is D. If D is anywhere in between or right at the 1st argument then it will not work.

import sys
import itertools
from itertools import combinations
def main():
    number = int(sys.argv[1])
    a_list = sys.argv[2:number+1]
    print("So all possible combinations except D:\n")
    for L in range(1, len(a_list)+1):
        for subset in itertools.combinations(a_list, L):
            print(*list(subset), sep=',')

For another example : if I give python3 combinations.py 4 A D C B then my code will give: A, D, C, AD, AC, DC, ADC but I need the output : A, B, C, AB, AC, BC, ABC

How should I do it. Please help me.

Upvotes: 0

Views: 27

Answers (1)

Dev
Dev

Reputation: 586

Okay I was trying to find a way and here's what I did just now and it is working fine.

import sys
import itertools
from itertools import combinations
def main():
    number = int(sys.argv[1])
    a_list = sys.argv[2:number+2]
    print(a_list)
    print(len(a_list))
    if 'D' in a_list: a_list.remove('D')
    print(a_list)
    print(len(a_list))
    print("So all possible combinations except D:\n")
    for L in range(1, len(a_list)+1):
        for subset in itertools.combinations(a_list, L):
            print(*list(subset), sep=',')
            
            
if __name__ == '__main__':
    main()

Upvotes: 1

Related Questions