今天刷的第一道算法题,先拿一道简单点的试试手,这道题目的要求是:
两个人甲乙在猜数字,甲先从1,2,3三个数字中随机抽3次,结果是guess。乙随后也随机抽三次,结果是answer。然后对比甲乙两个人的结果。示例如下:
guess:[1,2,3], answer: [1, 2, 3]
那么结果就是猜对了3次
guess: [1,2,3] answer:[3,2,1]
那么结果就是猜对了1次
guess: [1,2,3], answer:[3, 3,1]
那么结果就是猜对了0次
即将guess和answer两个作为参数输入,返回猜对的次数。
我想出来的几个答案如下所示:
答案1:
class Solution: def game(self, guess: List[int], answer: List[int]) -> int: count = 0 for i in zip(guess, answer): if i[0] == i[1]: count += 1 return count
思路是:使用zip将两个列表进行组合,返回每个列表中单个元素组成的元组,然后循环对比。如果相等就将临时变量值+1,最终返回统计结果。
答案2:
class Solution: def game(self, guess: List[int], answer: List[int]) -> int: count = 0 for i in range(3): if guess[i] == answer[i]: count+=1 return count
思路:转念一想,发现自己想复杂了,因为不需要拼接,就可以直接取这两个列表对应的值进行对比。就更简单了,直接循环对比,有相等的情况将临时变量+1,最后返回临时变量即可。
答案3:
class Solution: def game(self, guess: List[int], answer: List[int]) -> int: return sum(map(lambda x,y: x==y, guess, answer))
思路:既然可以直接对比,那么能不能再简单点,我就想到了map函数,map函数第一个参数直接使用匿名函数来进行元素对比,然后收集函数执行结果。如果对比相等,结果是True,对比不相等,结果是False。
最后返回map函数直接结果的总和即可。
答案4:
class Solution: def game(self, guess: List[int], answer: List[int]) -> int: if guess == answer: return 3 elif guess[0] == answer[0]: if guess[1] == answer[1]: return 2 else: return 1 elif guess[1] == answer[1]: if guess[2] == answer[2]: return 2 else: return 1 elif guess[2] == answer[2]: return 1 else: return 0
思路:将guess和answer进行对比,这是我认为自己最差的一个答案,因为这种情况只适合这种简短的列表对比,再长一点整个代码就没法看了。
内容扩展:
Python初学者小游戏:猜数字
游戏逻辑:电脑随机生成一个数字,然后玩家猜数字,电脑提示猜的数字大了还是小了,供玩家缩小数字范围,达到既定次数后,玩家失败。若在次数内猜对,玩家获胜。
涉及知识点:random.randint() , print() , input() ( raw_input() )
参考实现代码:
#!/usr/bin/env python # encoding: utf-8 #使用print("",end=...)标准 from __future__ import print_function import os import sys import time import random #输入检测 while 1: os.system('cls') print ("Hello , Welcome to Guess_Number Games...The Number is between 1 - 10...") print ("Please input the level you want(1~10): ",end = '') level = raw_input("") diff = 11-int(level) if diff > 10 or diff <1: print ("Invalid Input...") time.sleep(0.3) else: break #猜数字流程 count_num = 0 ran = random.randint(1,10) while count_num < diff: count_num += 1 print (str(count_num)+": "+"Please input the number you guess: ",end = '') number = raw_input() number = int(number) if number < ran: print ("Too Little...") continue elif number > ran: print ("Too Big...") continue else: print ("Congraduation! You Win...") break if count_num == diff: print ("You Lose...")