-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #3208 from bosmobosmo/moore-voting-python
add python for moore majority
- Loading branch information
Showing
1 changed file
with
35 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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() |