Card Trick revisited
(updated after the meeting)
# written in python version 3
# invoke with: python3 03-bits.py 4
# (to get the card trick)
# if you don't have python3 available to you,
# I have tested this on pythonanywhere.com
# ( https://www.pythonanywhere.com/login/,
# free accounts available )
import sys
if (len(sys.argv) !=2):
print (sys.argv[0], "")
sys.exit()
#
# get the number of values from the number of bits
#
numbits = int(sys.argv[1])
numvals = 2 ** numbits
vals = list(range(numvals))
print ("Pick a number from amongst this list:")
print (vals)
bitval = 1
for bb in range(numbits):
print ("Is your number in the following?")
# display numbers with 'bitval' set to 1
for vv in range(len(vals)):
if vals[vv] % (2 * bitval) >= bitval:
print (vals[vv])
# ask for user's response
yorn = input("(y)es or (n)o: ")
# mark half the numbers for removal
for vv in range(len(vals)):
if vals[vv] % (2 * bitval) >= bitval:
if yorn == 'n':
# remove displayed numbers
vals[vv] = -1
else:
if yorn == 'y':
# remove other numbers
vals[vv] = -1
# delete items in list, highest index to lowest
for vv in range(len(vals)-1,-1,-1):
if (vals[vv] == -1):
del vals[vv]
# increase bitval by doubling (shifting left)
bitval *= 2
# the number that remains is the user's number
print ("Your number is: ", vals[0])