2017-10-11 13 views
1

파이썬 3.6 명령 행 프로그램을 작성하려고합니다. 하나 이상의리스트를 인수로 받아들이고 그리스트의 데카르트 곱을 중복 제거 형식으로 반환 할 수 있습니다.파이썬 3.6에서 인자의 임의의 수의 데카르트 생성물 3.6

하나 및 두 개의 목록 인수로 올바르게 작동하지만 프로그램에서 세 개 이상의 인수를 올바르게 처리하는 방법을 알아낼 수 없습니다.

원하는 출력은 명령 행에서 인수로 전달 된 모든 목록을 포함하는 직교 제품입니다.

def createArgumentParser(): 

    from argparse import ArgumentParser 

    __parser = ArgumentParser() 
    __parser.add_argument("list", type=list, nargs="+", help="List(s) to compute the cartesian product of") 
    __parser.add_argument("-u", "--unique", action="store_true", help="Deduplicate lists so that they become sets of unique elements") 
    __parser.add_argument("-U", "--Universally_unique", action="store_true", help="Deduplicate the resulting cartesian product so that the final result is a set of unique elements") 
    return __parser.parse_args() 


def cartesianProduct(__unique, __Universally_unique, *__list): 

    from itertools import product 

    __cartesianProduct = product([]) 

    if __unique: 
     __cartesianProduct = product(sorted(set(__list[0])), sorted(set(__list[len(__list)-1]))) 
    else: 
     __cartesianProduct = product(__list[0], __list[len(__list)-1]) 
    if __Universally_unique: 
     __cartesianProduct = sorted(set(__cartesianProduct)) 
     for __element in __cartesianProduct: 
      if __element[0] == __element[1]: 
      __cartesianProduct.remove(__element) 
    return __cartesianProduct 


def main(): 

    __args = createArgumentParser() 

    for __element in cartesianProduct(__args.unique, __args.Universally_unique, *__args.list): 
     print(__element) 

이 반환 abc 123 def 명령 행 인수와 함께 프로그램을 실행 :

('a', 'd') 
('a', 'e') 
('a', 'f') 
('b', 'd') 
('b', 'e') 
('b', 'f') 
('c', 'd') 
('c', 'e') 
('c', 'f') 

123 부분은 직교 제품에서 누락

내가 지금까지 가지고있는 코드입니다. 어떻게 해결할 수 있습니까?

+0

먼저 형식을 수정하십시오. – Sraw

+1

정말 많은 변수가 필요합니까? 그것은 가독성을 없애줍니다. –

+1

코딩 스타일에 대한 반발을 기대하고있었습니다. 나는 독학하고 초보자입니다. 그러나 나를 위해 밑줄은 다양한 방식으로 가독성을 돕습니다 (이상하게 들릴 수도 있음). 나는이 프로젝트의 누구와도 협력하지 않기 때문에 좀 더 표준적인 스타일에 대한 필요성을 알지 못했다. 나는 다른 사람들이 그것을 성가 시게 찾는다는 것을 명심 할 것이다. –

답변

0

목록의 모든 항목의 카디 전 곱을 얻으려면 * 연산자를 사용하여 인수 압축 풀기를 수행 할 수 있습니다. 이것은 때때로 "스 플랫 (splat)"풀기로 알려져 있습니다.

from itertools import product 

src = ['abc', '123', 'def'] 
cartesian_product = [''.join(t) for t in product(*src)] 
print(cartesian_product) 

출력

['a1d', 'a1e', 'a1f', 'a2d', 'a2e', 'a2f', 'a3d', 'a3e', 'a3f', 'b1d', 'b1e', 'b1f', 'b2d', 'b2e', 'b2f', 'b3d', 'b3e', 'b3f', 'c1d', 'c1e', 'c1f', 'c2d', 'c2e', 'c2f', 'c3d', 'c3e', 'c3f'] 
+0

고마워요! 나는 그것이 내가 얻지 않고 있었던 단순한 무엇일 것 인 것이라고 상상했다. 이것은 트릭을 수행합니다. –