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]
Related
I do not know how to draw 2 or more different numbers and put them in another list, so far I have tried this:
import random
def jugar(m):
m = list(range(1, 14, 1)) * m
random.shuffle(m)
player1 = []
for n in m:
random.choice(m)
player1.append(n)
if n + n == 21:
print("Nano jack")
elif n + n < 21:
random.choice(m)
player1.append(n)
elif n + n > 21:
print("Loser")
return player1
jugar(1)
but this returns me 2 equal numbers, it is similar to the game of blackjack, I want it to keep adding random numbers until it reaches 21 or more, thanks for the help in advance
You can use choice method to randomly select an item from a given list.
Use it in a for loop to randomly select more items.
import random
the_list = [1, 2, 3, 4]
new_list = []
for i in range(3):
value = random.choice(the_list)
new_list.append(value)
This is a code to determine if the numbers in the list are prime or not (python2):
this works (1):
L = [4 , 9, 13, 15, 16]
def primenumber4():
for i in L:
compositenumber = False
for x in range(2,i):
if i%x == 0:
compositenumber = True
break
if compositenumber:
print "%s is not a prime number" % i
else:
print "%s IS a prime number" % i
primenumber4()
But this does not (2):
L = [4 , 9, 13, 15, 16]
def primenumber4():
compositenumber = False
for i in L:
for x in range(2,i):
if i%x == 0:
compositenumber = True
break
if compositenumber:
print "%s is not a prime number" % i
else:
print "%s IS a prime number" % i
primenumber4()
it gives the number 13 as not a prime.
But why?
according to this tread:
Short Description of the Scoping Rules?
"One of the greater surprises to many newcomers to Python is that a for loop does not create a variable scope" in Antti Haapala's answer
so I imagine the value "leaks" into the function scope:
which is the case with a single for loop
example:
def function():
i = 9
k = False
for x in range(2, 9):
if i%x == 0:
k = True
break
print k
which prints k = True so the variable changed
So my question is: Why doesn't the variable "compositenumber" change in (2)?
If a for loop doesn't have scope why isn't the variable a local variable in the function? why doesn't it "leak through twice passing both for loops" and ending up as a local variable in the function def.
I'm trying to understand the python scope rules because I don't think I get it completely. Thanks in advance!
This is not a scope issue. The issue is that when you assign primenumber = False inside the for loop, that assignment happens every time you go through the loop. It resets the value to False every time.
When you assign primenumber = False above the loop, it only gets assigned that way once, so primenumber remains True after the first time it's set to True.
Also, primenumber is a terrible name for a variable that indicates whether a number is composite.
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)
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]
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)