2016-02-01 29 views
1

假設的好辦法,我有3個數字:20,10,5len=5是什麼力量讓一個遞歸列表

我想打的列表:

20 
10 
5 
20 20 
20 10 
20 5 
10 20 
10 10 
10 5 
5 20 
5 10 
5 5 
20 20 20 
20 20 10 
20 20 5 
20 10 20 
.. 
20 20 20 20 20 
.. 
5 5 5 5 5 

但我不知道如何以一種好的方式製作這種列表(無論編程語言,但R更喜歡)?

你能給我一個提示嗎?

+1

展我們嘗試了什麼。 –

+0

找出如何獲得一定長度的列表和[1..len]上的連續映射 - 如果你能弄清楚如何獲得所有長度爲1的列表以及如何從n-1到n,那麼遞歸可能會方便;) – Carsten

+0

看到這個>> http://r.789695.n4.nabble.com/all-combinations-with-replacement-td3466696.html –

回答

1

解決方案在Python:

from itertools import combinations_with_replacement 

l = 5 #len is a reserved keyword in Python 

for i in range(1, l+1): 
    print(list(combinations_with_replacement([20, 10, 5], i))) 

結果

[(20,), (10,), (5,)] [(20, 20), (20, 10), (20, 5), (10, 10), (10, 5), (5, 5)] [(20, 20, 20), (20, 20, 10), (20, 20, 5), (20, 10, 10), (20, 10, 5)

我砍輸出短路由於它的長度,但你的想法。

+1

@mamatv這個工程,但我不認爲它應該是接受的答案,因爲它不是用請求的語言寫的。 –

3

這工作:

x <- c(20, 10, 5) 
len <- 5 
rl <- sapply(1:len, function(n) expand.grid(list(x)[rep(1, n)])) 

這裏rl是長度len的列表,其中,例如,

rl[[2]] 
# Var1 Var2 
# 1 20 20 
# 2 10 20 
# 3 5 20 
# 4 20 10 
# 5 10 10 
# 6 5 10 
# 7 20 5 
# 8 10 5 
# 9 5 5 
0

我想補充一個答案爲R:

library (gtools) 
permutations (n = length (c(20,10,5)), r = 5, v = c(20,10,5), repeats.allowed=TRUE) 
+1

你運行過嗎?它返回一個錯誤。對於OP所要求的,它會是'x < - c(20,10,5); lapply(1:5,function(i)permutations(length(x),i,x,repeats = TRUE))' –

+0

是的,我運行它並沒有問題。你有什麼錯誤? – mamatv

+0

當然現在它起作用,因爲你編輯它。但OP不想要只是r = 5,他想要r = 1,2,...,5 –