Home > Blockchain >  Find dominant number(number that repeat at least n /2 times)
Find dominant number(number that repeat at least n /2 times)

Time:12-21

Homework:

Write a program that asks a user to type number n then the program asks the user to input n numbers.The program needs to find a dominant number in a list.The dominant number is one who is repeating at least n/2 times in the list.

My idea is to create a counter that at the start is 0.If a counter is = or > n//2 we add that number to the list.But this idea doesn't work as I thought.

Code:

numbers = []
n = int(input("Type number: "))

for i in range(n):
    numbers.append(int(input("Type number: ")))

print(numbers)

counter = 0
dominant = []

for e in numbers:
    for i in range(n):
        if i == e:
            counter  = 1
            if counter >= n // 2:
                dominant.append(i)
print(dominant)

P.S. There is nothing said if there is no dominant number so we will skip that part.

CodePudding user response:

You can iterate over the set of numbers and count the number of times each number appears and then iterate over that counter again to find the dominant number:

dominant_numbers = [k for k, v in [[num, numbers.count(num)] for num in set(numbers)] if v >= (n 1)//2]

CodePudding user response:

Solution:

brojevi = []
n = int(input("Koliko brojeva zelite da unesete? "))

for i in range(n):
    brojevi.append(int(input(f"Unesite {i 1}. broj: ")))

print(brojevi)

for e in brojevi:
    brojac = 0
    for j in brojevi:
        if e == j:
            brojac  = 1
    if brojac >= n//2:
        print(e)
        break
  • Related