Python Question Solution For Q1
Python Question Solution For Q1
###########################################################
#####
#
# three basic players
#
###########################################################
#####
def nim_minimal(n):
return 1 # 1 is always a legal move,
# unless we already lost
def nim(n):
# note: n is guaranteed to be at least 1
return random.choice(range(1, min(n,3)+1))
def nim_best(n):
taken = n % 4
if taken:
return taken
else: # taken is 0, we lose - just take randomly
# pick randomly 1 or more
# but never more than either limit of sticks, 3
# or available sticks, n
return random.choice(range(1, min(n,3)+1))
def nim_human(n):
while True: # get input until it's legal
taken = int(input("There are %d sticks. How many do you take? (1/2/3) " %
n))
if taken in range(1, min(n,3)+1):
return taken
print("Illegal move.")
###########################################################
#####
#
# player candidates
#
###########################################################
#####
# these are the functions
player_pool = [nim_minimal, nim, nim_best, nim_human]
# transform into a dictionary with function name mapping to
# function
player_pool = { p.__name__:p for p in player_pool }
def select_players():
players = [] # we need two
# select the players
while len(players) < 2:
# select more players
print("These are the players: %s" % "/".join(player_pool.keys()))
p = input("Name one: ")
if p not in player_pool.keys():
print("Not a valid player. Select again: ")
continue
players.append(p)
Assignment 1.2
You have four numbers (integers or floats) x,y,z,u.
Write a function sort4(.) that takes 4 numerical arguments and returns a sorted tuple of
these
arguments. Do not use the list's sort() method.
def sort4(x,y,z,u):
# sort the two pairs
if x > y:
x,y = y,x
if z > u:
z,u = u,z
# after this, u is the largest of them all
if y > u:
y,u = u,y
# and x will now become the smallest
if x > z:
x,z = z,x
# the last pair is the middle one, sort it:
if y > z:
y,z = z,y
return x,y,z,u