Skip to content

Instantly share code, notes, and snippets.

@robocide
Created November 17, 2018 22:02
Show Gist options
  • Save robocide/8821bf376675c67fcf72f13be186e9d7 to your computer and use it in GitHub Desktop.
Save robocide/8821bf376675c67fcf72f13be186e9d7 to your computer and use it in GitHub Desktop.
Knows problem naive approach and stack approach.
from random import randint
def helloworld():
matrix = []
init_data(matrix)
print_data(matrix)
#celebrity_index = find_celebrity_naive(matrix)
celebrity_index = find_celebrity_stack(matrix)
print("Celebrity that was found :%s" % str(celebrity_index) if celebrity_index!= None else 'None')
return "Success" if celebrity_index!=None else "Failure!"
def find_celebrity_stack(matrix):
# push all n elements to the stack , thus pushing 1 to len of matrix to the stack , then check in the matrix if they each other and
# reach to conclusions
stack = list(range(0,matrix.__len__()))
while(stack.__len__() > 1):
person_1 = stack.pop()
person_2 = stack.pop()
# check if person1 knows person2
if(matrix[person_1][person_2] == 1):
# if person1 knows person2 , we can discard person1 , else we can discard person2
stack.append(person_2)
else:
stack.append(person_1)
# now lets check the last person the stack doesnt know anyone
index_of_the_maybe_celebrity = stack.pop()
all_zeros = list(filter(lambda x:x == 0 ,matrix[index_of_the_maybe_celebrity]))
all_ones = []
for i in range(matrix.__len__()):
if i!= index_of_the_maybe_celebrity and matrix[i][index_of_the_maybe_celebrity]==1:
all_ones.append(1)
if all_zeros.__len__() == matrix.__len__() and all_ones.__len__()==matrix.__len__()-1:
return index_of_the_maybe_celebrity
return None
def find_celebrity_naive(matrix):
# loop through the matrix , find a line with all zeros , and then check if we find 1 collum that has all 1
for i in range(matrix.__len__()):
row = matrix[i]
all_zeros = list(filter(lambda x: x == 0, row))
if all_zeros.__len__() == row.__len__():
all_ones = []
# in case this guys doesnt know anyone , lets check now that everyone knows him , meaning , all cols besides this col
for j in range(matrix.__len__()):
if(j!=i and matrix[j][i]==1):
all_ones.append(matrix[j][i])
if all_ones.__len__() == matrix.__len__()-1:
return i
return None
def init_data(matrix):
for i in range(5):
row = []
for j in range(5):
if(i==j):
row.append(0)
else:
row.append(randint(0, 1))
matrix.append(row)
def print_data(matrix):
for i in range(matrix.__len__()):
for j in range(matrix[i].__len__()):
print(matrix[i][j], end=" ")
print('\n')
def run_hello_world():
while helloworld()!="Success":
helloworld()
run_hello_world()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment