countdown and prime number check - python-2.7

I'm trying to write a function where if a person plugs in a value, it does a countdown to 0 and it shows if each number is prime.
def pn(n):
while n > 0:
#print (n)
if n == 1:
print '1 is a special number'
elif n == 2:
print '2 is EVEN and PRIME number'
else:
v_rem = n%2
v_half = int(n/2)
if v_rem == 0:
print n, ' is EVEN number'
elif v_rem == 1:
print n, ' is ODD number'
i = 2
v_is_prime = "y"
while i <= v_half:
v_prim_rem=n%i
if v_prim_rem == 0:
print n, ' is not a prime number'
v_is_prime = "n"
break
i = i + 1
if v_is_prime == "y":
print n, 'is a prime number'
n = n-1

Presumably your concerns are related to the incorrect output:
10 is EVEN number
9 is ODD number
9 is a prime number # here
9 is not a prime number
8 is EVEN number
7 is ODD number
7 is a prime number
7 is a prime number # and here
6 is EVEN number
5 is ODD number
5 is a prime number
4 is EVEN number
3 is ODD number
2 is EVEN and PRIME number
1 is a special number
Your indentation is wrong: the check for v_is_prime should be outside the loop over v_half, and thus should be dedented one step:
v_is_prime = "y"
while i <= v_half:
v_prim_rem=n%i
if v_prim_rem == 0:
print n, ' is not a prime number'
v_is_prime = "n"
break
i = i + 1
if v_is_prime == "y":
print n, 'is a prime number'
Alternatively, you can use else to handle this and get rid of the flag (which should really be booleans True and False not strings 'y' and 'n' if you do keep it):
while i <= v_half:
if v_n % i == 0:
print n, ' is not a prime number'
break
i = i + 1
else: # i.e. didn't 'break'
print n, 'is a prime number'
However, don't use a while loop when you could use a for loop:
for n in range(n, 0, -1):
...
and
for i in range(int(n/2)):
...
else:
...
You could also adopt string formatting:
print "{0} is a prime number".format(n)
Finally, this problem is perfectly suited to the Sieve of Erastosthenes:
def pn(n):
primes = range(n+1)
primes[1] = 0
for p in primes:
if p > 0:
for x in range(p, (n // p) + 1):
try:
primes[x*p] = 0
except IndexError:
break
for x in range(n, 0, -1):
if x % 2 == 0:
print "{0} is EVEN".format(x)
else:
print "{0} is ODD".format(x)
if primes[n] > 0:
print "{0} is prime".format(x)
else:
print "{0} is not prime".format(x)

Related

For Loop for Prime Factors in Python

I'm trying to return the factors of a number which are prime numbers in this code. For example, if someone enters in n = 55, they'll get back 5 and 11. I believe I have the first part correct in checking for the factors, but somehow I'm not sure what I'm missing in the second part of checking for prime numbers.
When I run the code for 55, I only get 5 (11 is missing).
Can someone please help review my code and provide feedback?
l = []
primefactors = []
def factor(n):
count = 0
print 'These are the factors:'
for num in range(2,n+1):
if n%num == 0: #checks that it is a factor
print num #These are the factors
l.append(num)
for i in l:
if i == 2 : #checks for two
primefactors.append(i)
else:
for x in range(3,i+1,2): #checks for odd numbers
if i%x == 0:
count += 1
if count == 1:
primefactors.append(i)
print "These are the prime factors:"
print primefactors
You can get all the factors by simply removing all unnecessary stuff, but that will not guaranty, that the number is prime number:
l = []
primefactors = []
def factor(n):
count = 0
for num in range(2,n+1):
if n%num == 0 and num != n: #checks that it is a factor
primefactors.append(num)
print ("These are the prime factors:")
print (primefactors)
del l[:]
del primefactors[:]
try this one, I added an additional check to see if number is a prime before appending to primefactors list.
primefactors = []
def factor(number):
for i in range(2,int(number//2)+1):
prime = True
for j in range(2,int(i**.5)+1):
if i%j == 0:
prime = False
break
if prime and number%i == 0:
primefactors.append(i)
print (primefactors)
factor(92)
factor(55)
output:
[2, 23]
[2, 23, 5, 11]

How to set an input limits on list with python 3

#room B register
#matrix method
roomB = [[],[]]
I am planning to enter only 3 units in here roomB=[[ ],[ ]] and if the first unit full, the system should suggest another unit.
def func():
row = int(input("Choose 0 or 1:"))
if (row == 0): # ROW 0 IS FOR HOUSE 1:
name = input("Enter your room name: ")
print("Enter M or N") #M for master room
room_type = input("") #N for normal room
for u in roomB: #3 units in roomB[0]
if(len(u)<3):
if (room_type == "M"):
return roomB[0].append([room_type,name,140])
if (room_type == "N"):
return roomB[0].append([room_type,name,140])
roomB = [[],[]]
def update(row): # takes sublist as argument
if len(roomB[row]) < 3: # checks if sublist length is less than 3
name = input("Enter your name: ")
room_type = input("Enter room type : M (master room) or N (normal room) : ").lower()
roomB[row].append([room_type,name,140])
return "your room no. is {} at row {}".format(roomB[row].index([room_type,name,140]) + 1, row) # returns string stating status
def func():
if len(roomB[0]) < 3 and len(roomB[1]) < 3: # ask for prompt only if space available in both sublist
row = int(input("Choose 0 or 1: ")) # allow to select row
return update(row)
elif len(roomB[0]) >= 3 and len(roomB[1]) < 3: # selects default sublist if no space on other sublist
print("No room available at 0 , selected 1 ")
return update(1) # returns string stating status
elif len(roomB[0]) < 3 and len(roomB[1]) >= 3: # selects default sublist if no space on other sublist
print("No room available at 1 , selected 0 ")
return update(0)
else: # in case any error occurs it goes here
print("Errrr.......")
print("room stat....: ", roomB)
while len(roomB[0]) <= 3 or len(roomB[1]) <= 3: # loop will flow if length of both sublist is greater than or equals to 3
if len(roomB[0]) != 0 or len(roomB[1]) != 0: # won't ask for confirmation if all all lists are empty (skips prompts for initial)
cond = input("do you want to continue?(Y/N) ").lower()
if cond == "n":
break # break the loop if pressed n or N otherwise continue to execute
elif len(roomB[0]) >= 3 and len(roomB[1]) >= 3: # error message to print if no space left in sublists
print("No room available.. Sorry for inconvinience.")
print(func())

How to find the min and max in a number list [duplicate]

This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
I'm having trouble with a project for class and I was looking for some help. I need to make a code where it will ask for numbers repeatedly and then print out the min and max in the list. My teacher said we can do this anyway we wish.
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" : break
if num >= 0:
num_list.append(num)
print min(num_list)
print max(num_list)
This is what I have so far, it asks for the number inputs and will break when I enter done, but it will only print out "Done" for the min and max in the list.
you need to convert the numbers to an integer or float type before calling min/max.
# under n >= 0:
num = int(num) # or num = float(num)
num_list.append(num)
so an example of working code would be:
num_list = []
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
try: # use a try except to verify user input is in fact a number
num = int(num) + 0 # alternatively use float(num) if non integer numerical inputs will be used
if num >= 0:
num_list.append(num)
print "min: ",min(num_list)
print "max: ",max(num_list)
except:
print "invalid input"
Not calling max/min every iteration:
num_list = []
_min, _max = None, None
while True:
num = raw_input("Enter a number: ")
if num == "done" :
break
try: # use a try except to verify user input is in fact a number
num = int(num) # alternatively use float(num) if non integer numerical inputs will be used
if num >= 0:
if not _min or not _max:
_min,_max = num, num
elif num < _min:
_min = num
elif num > _max:
_max = num
num_list.append(num)
except:
print "invalid input"
print "min:", _min
print "max:", _max

I get a memory error while generating prime numbers between two numbers

My code is correct but I got a memory error while running this code in Ideone.com.
m=input()
n=input()
def isPrime(num):
if num<2:
return False
ex=num/2
for div in range(2,ex+1):
if num%div==0:
return False
return True
def primes(m,n):
if m <= 2:
print 2
nums=range(3, n + 1, 2)
else:
nums=range(m, n + 1,2)
for num in nums:
if isPrime(num):
print num
primes(m,n)

How to remove numbers in a list that contain certain digits inside them

This is my code:
def second_test(numbers):
for x in numbers:
if 1 in x:
numbers.remove(x)
elif 7 in x:
numbers.remove(x)
print numbers
second_test(numbers)
Numbers is a list that contains int values from 10 to 1000. I am trying to remove numbers within this range that contain either a 1 or a 7 in them. Any suggestions?
You'll have to check if any digit of the number is a 1 or 7. There are two ways to do this:
The first way: Keep dividing the number by 10 and check the remainder (this is done with the modulus operator), until the number becomes 0
def check_num(n):
while n:
if n%10 == 1 or n%10 == 7:
return True
n /= 10
return False
def second_test(numbers):
to_delete = []
for i,x in enumerate(numbers):
if check_num(x):
to_delete.append(i)
for d in to_delete[::-1]:
del numbers[d]
The second way: Turn the number into a string, and check each character of the string
def check_num(n):
for char in str(n):
if char=='1' or char=='7':
return True
return False
def second_test(numbers):
to_delete = []
for i,x in enumerate(numbers):
if check_num(x):
to_delete.append(i)
for d in to_delete[::-1]:
del numbers[d]