Skip to content

Commit

Permalink
Merge pull request #3208 from bosmobosmo/moore-voting-python
Browse files Browse the repository at this point in the history
add python for moore majority
  • Loading branch information
ZoranPandovski authored Oct 2, 2022
2 parents 04d9ccb + 3864155 commit e8eb0df
Showing 1 changed file with 35 additions and 0 deletions.
35 changes: 35 additions & 0 deletions others/moore's_voting_algo/moore.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
def moore_voting(arr: list[int]) -> int:
majority = arr[0]
count = 0

# first phase
# find candidate for majority
for i in arr:
if i == majority:
count+=1
else:
count-=1
if count == 0:
majority = i
count = 1

# second phase
# check if majority is more than half of the elements
count = arr.count(majority)
if count < len(arr)/2:
majority = None

print(f'The majority element is {majority}')


def main() -> None:
size = int(input("Enter the size of the sequence: "))

arr: list[int] = []
print("Enter values in the sequence:")
for i in range(size):
arr.append(input())

moore_voting(arr)

main()

0 comments on commit e8eb0df

Please sign in to comment.