2013-04-25 6 views
5

이동에 문자로 채워진 슬라이스의 모든 순열을 찾는 방법이 있는지 궁금합니다.슬라이스의 모든 순열 얻기

파이썬에서는 itertools.product을 목록 또는 문자 또는 정수와 함께 사용할 수 있으며 모든 가능한 순열을 얻을 수 있습니다.

패키지가 있는지 살펴 보았습니다. 찾을 수없는 것 같습니다. 어떤 도움도 환영 할 것입니다. 아무것도

+2

'itertools.product' 당신에게 몇 가지 세트의 직교 제품을 제공합니다. 순열을주지는 않습니다. 순열을 알아 내기 위해 데카르트 제품을 사용할 수도 있지만, 이는 엄청나게 비효율적입니다. http://docs.python.org/2/library/itertools.html#itertools.product – scvalex

+0

나는 바보입니다. 나는 항상 그것들을 뒤섞어서, 데카르트 제품을위한 패키지를 발견했다. 감사합니다 – Colum

+1

@Colum 당신은 실수를했습니다; 그건 너 바보가 아니야. –

답변

0

Permutation{First,Next} 내가 작성한 순열 함수의 구현 ...

https://github.com/itcraftsman/GoPermutation

func permutate(slice [][]int) (permutations [][][]int){ 
    f := fac(len(slice)) 
    for i := 0; i < len(slice); i++ { 
     elem, s := splice(slice, i) 
     pos := 0 
     for count := 0; count < (f/len(slice)); count++{ 
      if pos == (len(s) -1) { 
       pos = 0 
      } 
      s = swap(s, pos, pos +1) 
      permutation := make([][]int, len(slice)) 
      permutation = s 
      permutation = append(permutation, elem) 
      permutations = append(permutations, permutation) 
      pos++ 
     } 
    } 
    return 
} 

를 그 입력으로 2D 슬라이스를 취하여 3D 슬라이스를 반환하지만 코드를 쉽게 변경하여 함수가 간단한 슬라이스를 입력으로 사용하고 모든 순열을 사용하여 2D 슬라이스를 반환하도록

0

이 질문에 대한 대답이 맞는지 확실하지 않지만 다음은 출력을 찾는 간단한 재귀 구현입니다. 위의 코드의

package main 

import "fmt" 

func main() { 
    values := [][]int{} 

    // These are the first two rows. 
    row1 := []int{1, 2, 3} 
    row2 := []int{4, 5, 6} 
    row3 := []int{7, 8, 9} 

    // Append each row to the two-dimensional slice. 
    values = append(values, row1) 
    values = append(values, row2) 
    values = append(values, row3) 


    fmt.Println(getPermutation(values)) 
} 

func getPermutation(vids [][]int) [][]int { 
    toRet := [][]int{} 

    if len(vids) == 0 { 
     return toRet 
    } 

    if len(vids) == 1 { 
     for _, vid := range vids[0] { 
      toRet = append(toRet, []int{vid}) 
     } 
     return toRet 
    } 

    t := getPermutation(vids[1:]) 
    for _, vid := range vids[0] { 
     for _, perm := range t { 
      toRetAdd := append([]int{vid}, perm...) 
      toRet = append(toRet, toRetAdd) 
     } 
    } 

    return toRet 
} 

https://play.golang.org/p/f8wktrxkU0

는 출력 :

[[1 4 7] [1 4 8] [1 4 9] [1 5 7] [1 5 8] [1 5 9] [1 6 7] [1 6 8] [1 6 9] [2 4 7] [2 4 8] [2 4 9] [2 5 7] [2 5 8] [2 5 9] [2 6 7] [2 6 8] [2 6 9] [3 4 7] [3 4 8] [3 4 9] [3 5 7] [3 5 8] [3 5 9] [3 6 7] [3 6 8] [3 6 9]] 
관련 문제