2017-10-12 54 views
1

只使用reduce(所以不要導入任何東西),我該如何編寫單行函數來獲得以下結果?它在列表中添加和相乘元素之間交替。Python:使用reduce來交替加法和乘法

一切都需要適應減少()

numbers = [1, 2, 3, 4, 5, 6] 

((1 + 2) * 3 + 4) * 5 + 6 = 71 
+0

你是指加法和乘法? –

+3

這些編程限制在哪裏出現?如果這是一項家庭作業問題,則必須將其標記爲這樣。 – Prune

+3

有很多不可避免的愚蠢的方法可以用'reduce'來實現。 –

回答

3

我想你想是這樣的:

print(reduce(lambda a, b: a[1] + b[1] if isinstance(a,tuple) 
      else a + b[1] if b[0] % 2 else a * b[1], enumerate(numbers))) 

擊穿:

print(reduce(lambda a, b: a[1] + b[1] if isinstance(a, tuple) 
          else a + b[1] if b[0] % 2 
          else a * b[1], 
       enumerate(numbers) 
      ) 
) 
+0

我試圖更好地理解reduce和lambda操作。我看到一些示例問題,但真的被困在這個問題上。這很好,我會檢查一次,時間允許 –

3

您可以獲得使用類似th的清潔解決方案是:

def myCycle(x, y): 
    while True: 
     yield from (x, y) # replace with yield x; yield y for python < 3.3 

print (reduce(lambda x, y: (y[0], x[0](x[1], y[1])), 
        zip(myCycle(int.__add__, int.__mul__), numbers))[-1]) 
71 

myCycle這裏是一個itertools.cycle替身,它通過元件反覆循環。

+0

我同意這比我的解決方案更清潔,所以+1 ...但他很清楚地表明沒有進口... –

+0

@JoranBeasley我很抱歉,我沒有看到。你也有我的投票。 –

+1

你*可以*創建你自己的循環,類似於'def c():while True:yield add;產量mul' –