day04 一個簡單的代碼優化案例


import random
punches = ['石頭','剪刀','']
computer_choice = random.choice(punches)
user_choice = input('請出拳:(石頭、剪刀、布)')  # 請用戶輸入選擇
while user_choice not in punches:  # 當用戶輸入錯誤,提示錯誤,重新輸入
    print('輸入有誤,請重新出拳')
    user_choice = input()

# 亮拳
print('————戰斗過程————')
print('電腦出了:%s' %(computer_choice))
print('你出了:%s' %(user_choice))

# 勝負
print('—————結果—————')
if user_choice == computer_choice:  # 使用if進行條件判斷
    print('平局!')
elif (user_choice == '石頭' and computer_choice == '剪刀') or (user_choice == '剪刀' and computer_choice == '') or (user_choice == '' and computer_choice == '石頭'):
    print('你贏了!')
else:
    print('你輸了!')

在上面的代碼中,判定你勝利的條件很長.我們可以嘗試優化它

石頭的索引為0,剪刀索引為1,布的索引為2(或-1)

分析發現,當你的選擇在列表中的索引等於電腦的索引-1時,你總是勝利的

因此,該條件我們就可以優化為

elif user_choice == punches[punches.index(computer_choice)-1]:

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM