Skip to content

Instantly share code, notes, and snippets.

@ronzhin-dmitry
Created November 8, 2022 17:45
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ronzhin-dmitry/c065cc9a0c2f94c7281039f966ee1919 to your computer and use it in GitHub Desktop.
Save ronzhin-dmitry/c065cc9a0c2f94c7281039f966ee1919 to your computer and use it in GitHub Desktop.
def raise_hand(man_position, hats_colors):
#this is a function with which we select if some man should raise a hand
#man_position - position of wiseman (from 0 to 12)
#hats_colors - list of colors of hats thay wisemen are wearing. We won't peek in this array (fair play)
hats_colors_sum = 0 #here let's collect parity of hats colors that we see. We don't count our own hat (since we don't know it)
for i in range(len(hats_colors)):
if i == man_position: #skip your own hat (fair play)
continue
hats_colors_sum += hats_colors[i] #collect sum
return hats_colors_sum % 2 #return parity
def give_answer(man_position, hands_up, hats_colors):
#this is a function to guess color of the hat that wiseman wearing
#man_position - position of wiseman
#hands_up - list of information who's hand is raised (here each one knows all information, we can look in here)
#hats_colors - list of colors of hats thay wisemen are wearing. We won't peek in this array (fair play)
reference_man = (man_position + 1) % len(hands_up) #choose random wiseman who will be our reference (except ourselves)
hats_colors_sum = 0 #collect sum of everyone's colors except the selected man and ourself
for i in range(len(hats_colors)):
if i == man_position or i == reference_man: #fair play, skip our color. And also we skip selected man
continue
hats_colors_sum += hats_colors[i] #collect sum
return (hats_colors_sum - hands_up[reference_man]) % 2 #return parity of difference as an answer (color)
import random
#let's model the task, we have 13 wisemen and random hats are put on them (2 colors)
n = 13
hats_colors = [random.randint(0,1) for _ in range(n)]
#these lists for now we keep empty:
hands_up = [0 for _ in range(n)]
answers = [-1 for _ in range(n)]
#first wise-men select if they have to raise hands (fill the list of raised hands with 0-not raised or 1-raised)
for man_position in range(n):
hands_up[man_position] = raise_hand(man_position, hats_colors)
#then we give answer (0 or 1, number of color_
for man_position in range(n):
answers[man_position] = give_answer(man_position, hands_up, hats_colors)
#let's compare the answers and colors that are chosen randomly:
are_equal = True
for i in range(m):
if hats_colors[i] != answers[i]:
are_equal = False
break
print('All answers are correct:', are_equal)
#And we get "All answers are correct: True". Nice one!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment