Below is the solution for the celebrity problem.
The problem: Suppose you are at a party with n people (labeled from 0 to n - 1) and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know him/her but he/she does not know any of them.
Now you want to find out who the celebrity is or verify that there is not one. The only thing you are allowed to do is to ask questions like: "Hi, A. Do you know B?" to get information of whether A knows B. You need to find out the celebrity (or verify there is not one) by asking as few questions as possible (in the asymptotic sense).
def knows(a,b): //Function that returns 1 if a knows b else returns 0
people = [[0,0,0,0],[1,0,1,0],[1,0,0,0],[1,0,0,0]]
for i in range(0,4):
for j in range(0,4):
if(people[a][b]==1):
return 1
else:
return 0
a = 0
c=0
for b in range(1,4):
if(knows(a,b)):
c=b
for i in range(0,4):
if((i!=c) & (knows(i,c)) | (knows(c,i))!=1): //1
print c
I would like to know how //1 gets executed. In the above case, 0 is the celebrity. Hence c = 0. So in the 2nd iteration:
i = 1
c = 0
i!=c //Since 1!=0, its true so we get 1
knows(1,0) //1 knows 0 hence return value : 1
knows(0,1) //0 doesn't know 1 hence return value : 0
So //1 will be :
if (1 & 1 | 1):
print c
Here c should be printed but it doesn't get printed and it goes to the next iteration.
Aucun commentaire:
Enregistrer un commentaire