Python – 交替前後求和


列表是 Python 語言中最重要的資料型別之一。Python 提供了各種內建方法來操作列表項,例如 append()、insert()、extend() 等。有多種方法可以找到陣列的交替前後求和。給定一個包含 n 個元素的陣列,其過程包括將第一個元素新增到陣列的最後一個元素,陣列的第二個元素新增到倒數第二個元素的值,依此類推,直到所有元素都加在一起。例如,讓我們取陣列:

[40, 50, 20, 30]

交替前後求和計算如下:(40+30) + (50+20) = 140

方法

方法 1:使用條件語句

方法 2:使用 zip 函式

方法 1:使用條件語句的 Python 程式來計算交替前後求和

條件語句用於比較 num 和 ran,然後列表元素進行加法運算並返回 60 和 -50 的值。

演算法

  • 步驟 1 − 使用一組元素初始化列表。

  • 步驟 2 − 將變數 num 初始化為 0,並將 ran 設定為給定列表的長度減 1。

  • 步驟 3 − 然後初始化空列表。

  • 步驟 4 − 當 num 小於 ran 時,

    • 標誌為真,然後將輸入列表中索引 num 和 ran 處的元素新增到初始化為空列表的列表中。

    • 標誌為假,並將輸入列表中索引 num 和 ran 處的元素的負和新增到初始化為空列表的列表中。

  • 步驟 5 − 之後增加 num 並減少變數“ran”。

  • 步驟 6 − 在另一種情況下,num=ran,並將輸入中索引 1 處的元素初始化到 res 中。

  • 步驟 7 − 然後列印語句將列印交替前後求和。

示例

#list is initialized with elements of strings
list_1 = [10, 20, 30, 50]
# variables are Initialized with values
num = 0
ran = len(list_1) - 1
res = []
flag = True

# while loop is used to iterate through the while loop
while num < ran:
   if flag:
      res.append(list_1[num] + list_1[ran])
      flag = False
   else:
      res.append((list_1[num] + list_1[ran]))
      flag = True
   num += 1 
   ran -= 1 
# if loop uses the conditional statement to check for odd-numbered list array.
if num == ran: 
   res.append(list_1[num])

# returns the statement after the front-rear sum
print("Alternating Front-Rear Sum:", *res)

輸出

Alternating Front-Rear Sum: 60 50

方法 2:使用 zip() 函式的 Python 程式來計算交替前後求和

在下面的程式碼中,zip() 函式用於組合列表中來自前後端的元素,然後計算交替前後求和。reversed() 函式用於以相反的順序遍歷列表。

演算法

  • 步驟 1 − 使用一組元素初始化列表。

  • 步驟 2 − 然後初始化空列表。

  • 步驟 3 − 標誌為真,然後使用 zip() 函式以及兩個引數,即 list_1 和反轉的 list_1。然後將當前元素新增到空列表中。

  • 步驟 4 − 標誌為假,然後使用 zip() 函式以及兩個引數,即 list_1 和反轉的 list_1。然後當前元素將進行負求和。

  • 步驟 5 − 當列表的長度為奇數時,將中間元素新增到空列表中。

  • 步驟 6 − 然後列印語句將列印交替前後求和。

示例

#list is initialized with elements of strings
list_1 = [10, 20, 30, 50]
#initializing the empty list
empty = []
use = []
flag = True

#for loop is used to iterate through the list using the zip function
for a, b in zip(list_1, reversed(list_1)):
   if flag:
      empty.append(a + b)
      flag = False
   else:
      use.append((a + b))
      flag = True

# if loop uses the conditional statement to check for an even numbered list array.
if len(list_1) % 2 != 0:
   empty.append(list_1[len(list_1) // 2])
# returns the statement after the front-rear sum
print("Alternating Front-Rear Sum:", *empty)

輸出

Alternating Front-Rear Sum: 60 50

結論

給出了 Python 程式,用於計算給定元素陣列的後端和前端交替求和。對於陣列列表的偶數長度,元素的加法更容易,另一方面,當元素具有奇數長度的列表時。最終數字新增到列表的末尾。

更新於: 2023-08-25

100 次檢視

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.