您的位置:

Python 程序:统计集合中的偶数和奇数

写一个 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 程序统计集合中的偶数和奇数

这个 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