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

犯罪嫌疑人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
添加回答
舉報
0/150
提交
取消