Find dominant number(number that repeat at least n /2 times) - python

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.

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

Write a python script to print all Prime numbers between two given numbers (both values inclusive)

Write a python script to print all Prime numbers between two given numbers (both values inclusive)
can anyone please tell what am I doing wrong here ?
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
for i in range(2,k):
if k%i!=0:
if k!=i:
continue
elif k==i:
print(k)
break
elif k!=i:
break
you are checking if a number is prime the wrong way there are many
unhandled cases in your code for example if a is larger than b
you will start looping from "a" anyway
and even if the values are sat up correctly the algorithm is not right
here is my optimal solution hope it will help
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
def is_prime(n):
# negative numbers cannot be primes 1 and 0 are also not primes
if n <= 1:
return False
# since 2 is the first prime we will start looping from it
# until n since you mentioned that n is included
for i in range(2, n + 1):
# if n is cleanly divisible by any number less than n
# that means that n is not prime
if n % i == 0 and n != i:
return False
return True
for k in range(a,b):
if a > b:
print ("a cannot be bigger than b")
if is_prime(k):
print(k)
Here's the solution. I added some comments to explain what the code does.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
# Include b in the range by adding 1
for num in range(a, b + 1):
# Prime numbers are greater than 1
if num > 1:
for i in range(2, num):
# If the number is divisible, it is not prime
if num % i == 0:
# Check if the number is equal to the number itself
if num != i:
break
else:
# If the loop was not broken, the number isn't divisible
# by other numbers except itself and 1, so it's prime
print(num)
Well, a prime is "a number that is divisible only by itself and 1", so to actually first I would go only to range(2, k-1). This approach you have is one of the most straightforward ways of doing it, and is not computationally friendly. There are algorithms that specialize in this kind of prime number finding.
I have fixed the code, simplifying the expressions and adding like already mentioned +1 for inclusivity.
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b+1):
for i in range(2,k+1):
if k==i:
print(k)
elif k%i!=0:
continue
else: # is divisible and isn't 1 or the number
break
I encourage you to see this post, how they do it.
An other way of doing it would be:
#Check only 1 number at time:
def check_prime(check):
if check > 1:
for i in range(2, check):
if check % i == 0:
return False
return True
return False
#then check your numbers in a loop
list_prime = []
for i in range(50, 250):
if check_prime(i):
list_prime.append(i)
print(list_prime)
That way you can check 1 possible prime number at time.
If you need numbers in between just put it in loop.
Usually, when generating prime numbers utilizing some form of the "Sieve of Erotosthenes" algorithm, it is only necessary to check for denominator values up to the square root of the number being evaluated. With that in mind, here is one more possible take on your prime number loop test.
import math
a = int(input("Enter the value of a : "))
b = int(input("Enter the value of b : "))
for k in range(a,b):
if k == 2 or k == 3: # Pick up the prime numbers whose square root value is less than 2
print(k)
x = int(math.sqrt(k) + 1) # Need only check up to the square root of your test number
for i in range(2,x):
if k%i!=0:
if x-1 > i:
continue
else:
print(k)
else: # If the remainder is zero, this is not a prime number
break
Another version to try.

How to separate for loop from if

ok = 1
while ok==1:
sum = 0
count = 0
a = int(input("Ievadiet, cik skaitļu būs virknē: "))
for i in range( 0, a):
N = int(input("Ievadiet veselu skaitli: "))
if N%2 == 1:
count+= 1
sum += N
if count != 0:
average = sum / count
print("Virknes nepāra skaitļu vidējā artimētiskā vērtība ir: ", average)
else:
print("Nevar aprēķināt nepāra skaitļu vidējo aritmētisko.")
ok = int(input(" Vai turpināt (1) vai beigt (0)?"))
This program should ask to type how many numbers will be in chain and then calculate the existing between these numbers the arithmetic mean of the odd numbers. How to separate "if count != 0" from "if N%2 == 1" so the programm will stop calculating arithmetic mean of every number but will calculated only when all numbers of the chain will be written.
Please check this code and see if that if what you want to reach. I just de-indented the last if...else block so no it first gets all the numbers and then shows the mean.
ok = 1
while ok == 1:
sum = 0
count = 0
a = int(input("Ievadiet, cik skaitļu būs virknē: "))
for i in range(0, a):
N = int(input("Ievadiet veselu skaitli: "))
if N % 2 == 1:
count += 1
sum += N
if count != 0:
average = sum / count
print("Virknes nepāra skaitļu vidējā artimētiskā vērtība ir: ", average)
else:
print("Nevar aprēķināt nepāra skaitļu vidējo aritmētisko.")
ok = int(input(" Vai turpināt (1) vai beigt (0)?"))
Have Fun :)

Enter n different positive numbers. Calculate the average value of all prime numbers among them. [Python]

I need to do as the title suggests however I have ran into a problem. This is my code so far:
#Input
n = int(input('Enter n: '))
#Prime = 0
p = []
#Loopidty
for i in range(n):
#Ask user to input x
x = int(input('Enter a Number: '))
#Check if prime
if x < 2:
print('The number is not prime.')
else:
for n in range(2, x - 1):
if x % n == 0:
print('The number is not prime.')
break
else:
print('The number is prime.')
p.append(x)
#Answer
Answer = sum(p) / n
print('The answer is: ', Answer)
The issues is when I add the prime numbers to the list it only adds the first number and stops there, how do I combat this?
Many thanks
It's a good idea to break your code into smaller parts. We can create a function to check if a number is prime or not and check that it is correct. After that just add the rest of the code.
import math
def is_prime(x):
"""Check that a number `x``is prime"""
# You only need to go up to sqrt(x)
for n in range(2, int(math.sqrt(x) + 1)):
if x % n == 0:
return False
return True
# xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
sum = 0.0
num_entries = 0 # Number of prime numbers entered by the user
n = int(input('Enter n: '))
for i in range(n):
x = int(input('Enter a Number: '))
if is_prime(x):
sum += x
num_entries += 1
if num_entries == 0:
print("You didn't enter any prime number")
else:
print("The average of the entered prime numbers is ", sum / num_entries)

Why doesn't the function in my while loop use the updated variable value

So I'm taking a beginner Python class and one of my questions is to write code that takes n number (e.g. 5) and asks the user to enter n-1 numbers in n and finds the missing number. I can't use anything more advanced than loops.
For some reason even though the value of nn gets updated ever time the loop runs the value of number only decreases by 1 every time the loop runs.
n = int(input('Please enter n: '))
ntotal = int(n*(n+1)/2)
print ('Please enter n: ')
print (ntotal)
i = 0
k = i
while i != n-1:
nn = int(input('Please enter a number: '))
number = ntotal - nn
print (nn)
i += 1
print (number)
You have to change ntotal
ntotal = total - number
or shorter
ntotal -= number
and display ntotal at the end
n = int(input('Please enter n: '))
ntotal = int(n*(n+1)/2)
#print('ntotal:', ntotal)
i = 0
while i != n-1:
#for _ in range(n-1):
number = int(input('Please enter a number: '))
ntotal -= number
#print('number:', number, 'ntotal:', ntotal)
i += 1
print(ntotal)

How do you find the first N prime numbers in python?

I am pretty new to python, so I don't fully understand how to use loops. I am currently working on a piece of code that I have to find the first N prime numbers.
The result that is desired is if you input 5, it outputs 2, 3, 5, 7, and 11, but no matter what I input for 'max', the output always ends up being 2 and 3. Is there a way to improve this?
max=int(input("How many prime numbers do you want: "))
min=2
while(min<=(max)):
for c in range(2, min):
if min%c==0:
break
else:
print min
min=min+1
You only increment min in the else block, i.e., if min % c is nonzero for all c, i.e., if min is prime. This means that the code won't be able to move past any composite numbers. You can fix this by unindenting min=min+1 one level so that it lines up with the for and else.
number = int(input("Prime numbers between 2 and "))
for num in range(2,number + 1):
if num > 1:
for i in range(2,num):
if (num % i) == 0:
break
else:
print(num)
Solution: Get the nth prime number entry. Iterate through each natural numbers for prime number and append the prime number to a list. Terminate the program when length of a list satisfies the user nth prime number entry.
# Get the number of prime numbers entry.
try:
enterNumber = int(input("List of nth prime numbers: "))
except:
print("The entry MUST be an integer.")
exit()
startNumber = 1
primeList = []
while True:
# Check for the entry to greater than zero.
if enterNumber <= 0:
print("The entry MUST be greater than zero.")
break
# Check each number from 1 for prime unless prime number entry is satisfied.
if startNumber > 1:
for i in range(2,startNumber):
if (startNumber % i) == 0:
break
else:
primeList.append(startNumber)
if (len(primeList) == enterNumber):
print(primeList)
break
else:
startNumber = startNumber + 1
continue
Try that :
n = int(input("First N prime number, N ? "))
p = [2]
c = 2
while len(p) < n:
j = 0
c += 1
while j < len(p):
if c % p[j] == 0:
break
elif j == len(p) - 1:
p.append(c)
j += 1
print(p)
Its simple. Check the below code, am sure it works!
N = int(input('Enter the number: ')
i=1
count=0
while(count<N):
for x in range(i,i+1):
c=0
for y in range(1,x+1):
if(x%y==0):
c=c+1
if(c==2):
print(x)
count=count+1
i=i+1
The following code will give you prime numbers between 3 to N, where N is the input from user:
number = int(input("Prime numbers between 2, 3 and "))
for i in range(2,number):
for j in range(2,int(i/2)+1):
if i%j==0:
break
elif j==int(i/2):
print(i)
You can see to check a number i to be prime you only have to check its divisibility with numbers till n/2.

Categories