2014-10-31 2 views
2

저는 파이썬에서 간단한 문장 생성기를 설정하여 가능한 많은 단어 조합을 작성하여 로봇과 관련된 일반적인 이미지 세트를 설명합니다. (그 긴 이야기 : D) 그것은 이런 식으로 뭔가를 출력행렬의 가능한 모든 행 조합을 얻으십시오.

: '사이보그 개념 다운로드의 그림'놀랍게도, 임의 내가 쓴 생성

은 최대 255 개 독특한 조합을 간다. 좀 더 콤보를 만들 수 없습니다 (624 개) 조합 (즉시) 다음은 무한 루프 응답에 일어나,

import numpy 
from numpy import matrix 
from numpy import linalg 

import itertools 
from pprint import pprint 
import random 


m = matrix([ 
    ['Robot','Cyborg','Andoid', 'Bot', 'Droid'], 
    ['Character','Concept','Mechanical Person', 'Artificial Intelligence', 'Mascot'], 
    ['Downloadable','Stock','3d', 'Digital', 'Robotics'], 
    ['Clipart','Illustration','Render', 'Image', 'Graphic'], 
]) 

used = [] 

i = 0 

def make_sentence(m, used): 
    sentence = [] 
    i = 0 
    while i <= 3: 
     word = m[i,random.randrange(0,4)] 
     sentence.append(word) 
     i = i+1 
    return ' '.join(sentence) 

def is_used(sentence, used): 
    if sentence not in used: 
     return False 
    else: 
     return True 

sentences = []  
i = 0 
while i <= 1000: 
    sentence = make_sentence(m, used) 
    if(is_used(sentence, used)): 
     continue 
    else:  
     sentences.append(sentence) 
     print str(i) + ' ' +sentence 
     used.append(sentence) 
     i = i+1 

대신 randrangerandint 사용 : 여기에 스크립트입니다.

내가 생각하기에 매트릭스의 모든 가능한 조합을 결정하는 더 적절한 방법이 있습니까?

+1

http://stackoverflow.com/questions/1208118/using-numpy-to-build-an-array-of-all-combinations-of-two-arrays? –

답변

3

가능한 모든 조합의 매트릭스를 얻으려면 itertools을 사용할 수 있습니다. itertools가 어떻게 작동하는지 보여주기 위해 한 가지 예를 들었습니다.

import itertools 
mx = [ 
    ['Robot','Cyborg','Andoid', 'Bot', 'Droid'], 
    ['Character','Concept','Mechanical Person', 'Artificial Intelligence', 'Mascot'], 
    ['Downloadable','Stock','3d', 'Digital', 'Robotics'], 
    ['Clipart','Illustration','Render', 'Image', 'Graphic'], 
    ] 
for combination in itertools.product(*mx): 
    print combination 
0

코드에서 재귀를 사용할 수 있습니다. itertools가 없으면 여기에 하나의 전략이 있습니다.

def make_sentences(m, choices = []): 
    output = [] 
    if len(choices) == 4: 
     sentence = "" 
     i = 0 
     #Go through the four rows of the matrix 
     #and choose words for the sentence 
     for j in choices: 
      sentence += " " + m[i][j] 
      i += 1 
    return [sentence] #must be returned as a list 
    for i in range(0,4): 
     output += make_sentences(m, choices+[i]) 
    return output #this could be changed to a yield statement 

이것은 원래 기능과 완전히 다릅니다.

선택 목록은 선택한 m의 각 행에 대한 열의 색인을 추적합니다. 재귀 적 방법으로 네 개의 행이 선택되었다고 판단되면 단 하나의 문장으로 목록을 출력합니다.

메소드는 선택 목록에 네 개의 요소가 없다는 것을 발견하면, 네 개의 새로운 선택 목록에 대해 반복적으로 자신을 호출합니다. 이러한 재귀 호출의 결과는 출력 목록에 추가됩니다.

관련 문제