寫一個 Python 程序來計算集合中的偶數和奇數。for 循環(針對 evodSet 中的 eoVal)迭代所有集合項。而 if 條件(if(eoVal % 2 == 0))檢查可被二整除的 Set 項是否等於零。如果為真,我們在偶數集合計數上加一;否則(sOddCount = sOddCount + 1),給奇數集計數值加 1。
# Count of Set Even and Odd Numbers
evodSet = {78, 11, 54, 95, 16, 36, 61, 77, 150, 122}
print("Even and Odd Set Items = ", evodSet)
sEvenCount = sOddCount = 0
for eoVal in evodSet:
if(eoVal % 2 == 0):
sEvenCount = sEvenCount + 1
else:
sOddCount = sOddCount + 1
print("The Count of Even Numbers in evodSet = ", sEvenCount)
print("The Count of Odd Numbers in evodSet = ", sOddCount)
這個 Python 偶數和奇數示例允許使用 for 循環範圍輸入集合項。
# Count of Set Even and Odd Numbers
evodSet = set()
number = int(input("Enter the Total Even Odd Set Items = "))
for i in range(1, number + 1):
value = int(input("Enter the %d Set Item = " %i))
evodSet.add(value)
print("Even and Odd Set Items = ", evodSet)
sEvenCount = sOddCount = 0
for eoVal in evodSet:
if(eoVal % 2 == 0):
sEvenCount = sEvenCount + 1
else:
sOddCount = sOddCount + 1
print("The Count of Even Numbers in evodSet = ", sEvenCount)
print("The Count of Odd Numbers in evodSet = ", sOddCount)
Python 計數偶數和奇數集合輸出
Enter the Total Even Odd Set Items = 4
Enter the 1 Set Item = 22
Enter the 2 Set Item = 9
Enter the 3 Set Item = 32
Enter the 4 Set Item = 78
Even and Odd Set Items = {32, 9, 22, 78}
The Count of Even Numbers in evodSet = 3
The Count of Odd Numbers in evodSet = 1
在這個 Python 集示例中,我們創建了一個 CountOfSetEvenandOddNumbers 函數,該函數返回偶數和奇數計數。
# Count of Set Even and Odd Numbers
def CountOfSetEvenandOddNumbers(evodSet):
sEvenCount = sOddCount = 0
for eoVal in evodSet:
if(eoVal % 2 == 0):
sEvenCount = sEvenCount + 1
else:
sOddCount = sOddCount + 1
return sEvenCount, sOddCount
evodSet = set()
number = int(input("Enter the Total Even Odd Set Items = "))
for i in range(1, number + 1):
value = int(input("Enter the %d Set Item = " %i))
evodSet.add(value)
print("Even and Odd Set Items = ", evodSet)
sECount, sOCount = CountOfSetEvenandOddNumbers(evodSet)
print("The Count of Even Numbers in evodSet = ", sECount)
print("The Count of Odd Numbers in evodSet = ", sOCount)
Python 統計集合輸出中的偶數和奇數
Enter the Total Even Odd Set Items = 6
Enter the 1 Set Item = 22
Enter the 2 Set Item = 33
Enter the 3 Set Item = 44
Enter the 4 Set Item = 55
Enter the 5 Set Item = 66
Enter the 6 Set Item = 88
Even and Odd Set Items = {33, 66, 44, 22, 55, 88}
The Count of Even Numbers in evodSet = 4
The Count of Odd Numbers in evodSet = 2
原創文章,作者:B6UHZ,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/127028.html