亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

數組上的偶數奇數模式,其中我輸出總和

數組上的偶數奇數模式,其中我輸出總和

慕桂英546537 2022-09-27 10:48:22
Write a function that takes an array/list of numbers and returns a number.See the examples and try to guess the pattern:even_odd([1,2,6,1,6,3,1,9,6]) => 393even_odd([1,2,3]) => 5even_odd([0,2,3]) => 3even_odd([1,0,3]) => 3even_odd([3,2])   => 6    def even_odd(arr):    count = 0    index = 0    length = len(arr)    while index < length:        for num in range(len(arr)):            if arr[index] % 2 != 0:                count += arr[index]                index += 1            else:                count *= arr[index]                index += 1    return count所以基本上模式是將前2個數字相乘并添加第三個數字,我將其設置為每個索引值的位置,如果它是第一個數字,我會將其添加到計數中以保持跟蹤,然后將其與第二個數字相乘,然后添加第三個數字。我通過了3/4個樣本案例,除了一個---> even_odd的第一個([1,2,6,1,6,3,1,9,6])=> 393。我只是想知道我的邏輯有什么缺陷,是否有人有更好的方法來解決這個問題,既高效又干凈。
查看完整描述

2 回答

?
郎朗坤

TA貢獻1921條經驗 獲得超9個贊

你的問題是對Codewars(https://www.codewars.com/kata/559e708e72d342b0c900007b)的挑戰,所以也許你應該使用這個平臺與其他競爭者討論解決方案,而不是Stackoverflow。

這個挑戰的要點是研究計算的模式,而不是代碼本身。

如果您知道所需的模式,代碼很容易(劇透!

def even_odd(arr):

    num = 0

    for i, e in enumerate(arr):

        if (i % 2) == 0:

            num += e

        else:

            num *= e

    return num


查看完整回答
反對 回復 2022-09-27
?
犯罪嫌疑人X

TA貢獻2080條經驗 獲得超4個贊

這將產生所需的結果:


from operator import add, mul



def even_odd(nums):

    acc = nums[0]  # accumulator

    ops = [mul, add]

    i = 0

    for num in nums[1:]:

        acc = ops[i](acc, num)

        i = 1 - i  # alternates between the two operators

    return acc


查看完整回答
反對 回復 2022-09-27
  • 2 回答
  • 0 關注
  • 85 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號