python證照必考題 得票數計算 選舉題目 投票問題TQC+ 程式語言 Python 3 _ 409

九四帥
2021-09-13 18:59:35

*TQC+ 程式語言 Python 3 _ 409 得票數計算 *
說明： 某次選舉有兩位候選人，分別是No.1: NamiNo.2: Chopper
請撰寫一程式，輸入五張選票，輸入值如為1即表示針對1號候選人投票；
輸入值如為2即表示針對2號候選人投票，如輸入其他值則視為廢票
每次投完後需印出目前每位候選人的得票數，最後印出最高票者為當選人；
如最終計算有相同的最高票數者或無法選出最高票者，顯示
=> No one won the election.
－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－－
輸入與輸出會交雜如下，輸出的部份以粗體字表示（程式執行狀況擷圖）
2
Total votes of No.1: Nami = 0
Total votes of No.2: Chopper = 1
Total null votes = 0
1
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 1
Total null votes = 0
8
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 1
Total null votes = 1
2
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 2
Total null votes = 1
2
Total votes of No.1: Nami = 1
Total votes of No.2: Chopper = 3
Total null votes = 1 => No.2 Chopper won the election.

python解題一： 考試上機作答沒問題，但現實狀況不符

nami_vote = 0
chopper_vote = 0
null_vote = 0

for i in range(5):   ＃for 回圈五次投票
    vote = int(input())

    if vote == 1:
        nami_vote += 1
    elif vote == 2:
        chopper_vote += 1
    else:
        null_vote += 1

    print('Total votes of No.1: Nami = ', nami_vote)
    print('Total votes of No.2: Chopper = ', chopper_vote)
    print('Total null votes = ', null_vote)

if nami_vote > chopper_vote:
    print('=> No.1 Nami won the election.')
elif chopper_vote > nami_vote:
    print('=> No.2 Chopper won the election.')
else:
    print('=> No one won the election.')

   #這種方法在廢票多於前兩位候選人會出現，bug 錯判 某位候選人照樣勝出
null 3
nami 2
chopper 1. 判定： nami勝出的謬誤

**解法二：**

nami,chop,null= 0,0,0

for i in range(5):
     vote = int(input())
     if vote == 1: nami +=1
     elif vote == 1: chop +=1
     elif: null +=1

     print("Total vote of No.1: Nami =",nami)
     print("Total vote of No.2: Chopper =",chop)
     print("Total nul votes =" ,null)

if null >= nami and null >=chop or nami == chop: #先界定各種廢票
       print("=> No one won the election.")
elif nami> chop:
       print("=> No.1 Nami won the election.")
else:
       print("=> No.2 Chopper won the election.")

 **   解法三：**

nami,chop,null =0,0,0

for i in range(5):
         vote = input()
         if vote == "1":nami +=1
         elif vote =="2": chop +=1 #把 投票變成字串，確定頭１or2有效，其他寫錯的不會生效
          elif: null += 1

     print("Total vote of No.1: Nami =",nami)
     print("Total vote of No.2: Chopper =",chop)
     print("Total nul votes =" ,null)

if null >= nami and null >=chop or nami == chop:
       print("=> No one won the election.")
elif nami> chop:
       print("=> No.1 Nami won the election.")
else:
       print("=> No.2 Chopper won the election.")