def POSF(data):
"""
This function takes a 2D list (matrix) and returns the number of positive integers in the matrix.
"""
NPOS = 0
for row in data:
for item in row:
if item > 0:
NPOS += 1
return NPOS
def EVENF(data):
"""
This function takes a 2D list (matrix) and returns the number of even integers in the matrix.
"""
NEVEN = 0
for row in data:
for item in row:
if item % 2 == 0:
NEVEN += 1
return NEVEN
def main():
# Example matrix INTDATA
INTDATA = [
[1, -2, 3],
[-4, 5, -6],
[7, -8, 9]
]
# Call the POSF function to find the number of positive values
NPOS = POSF(INTDATA)
print(f"The number of positive values in INTDATA is: {NPOS}")
# Call the EVENF function to find the number of even values
NEVEN = EVENF(INTDATA)
print(f"The number of even values in INTDATA is: {NEVEN}")
if __name__ == "__main__":
main()
程式說明
POSF 函數:
用於計算並返回二維陣列中正數的個數。
EVENF 函數:
輸入參數為二維陣列(矩陣)。
使用雙層迴圈遍歷矩陣中的每個元素,並計算其中偶數的個數。
返回偶數的計數值。
主程式:
定義一個示例的二維陣列 INTDATA。
呼叫 POSF 函數並將結果存入變數 NPOS,然後列印出正數的個數。
呼叫 EVENF 函數並將結果存入變數 NEVEN,然後列印出偶數的個數。
這個程式會正確地計算並列印出 INTDATA 中正值和偶數的數量。你可以根據需要修改 INTDATA 的內容以測試不同的輸入。