forked from TheAlgorithms/Python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcelebrity_problem.py
85 lines (64 loc) · 1.38 KB
/
celebrity_problem.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
# Python3 program to find celebrity
# using stack data structure
# Max # of persons in the party
N = 8
# Person with 2 is celebrity
MATRIX = [ [ 0, 0, 1, 0 ],
[ 0, 0, 1, 0 ],
[ 0, 0, 0, 0 ],
[ 0, 0, 1, 0 ] ]
def knows(a, b):
return MATRIX[a][b]
# Returns -1 if celebrity
# is not present. If present,
# returns id (value from 0 to n-1).
def findCelebrity(n):
# Handle trivial
# case of size = 2
s = []
# Push everybody to stack
for i in range(n):
s.append(i)
# Find a potential celebrity
while (len(s) > 1):
# Pop out the first two elements from stack
A = s.pop()
B = s.pop()
# if A knows B, we find that B might be the celebrity and vice versa
if (knows(A, B)):
s.append(B)
else:
s.append(A)
# If there are only two people
# and there is no
# potential candidate
if(len(s) == 0):
return -1
# Potential candidate?
C = s.pop();
# Last candidate was not
# examined, it leads one
# excess comparison (optimize)
if (knows(C, B)):
C = B
if (knows(C, A)):
C = A
# Check if C is actually
# a celebrity or not
for i in range(n):
# If any person doesn't
# know 'a' or 'a' doesn't
# know any person, return -1
if ((i != C) and
(knows(C, i) or
not(knows(i, C)))):
return -1
return C
# Driver code
if __name__ == '__main__':
n = 4
id_ = findCelebrity(n)
if id_ == -1:
print("No celebrity")
else:
print("Celebrity ID ", id_)