All function only checking one element - python

counter = 0
numList = []
beginning = 1
primeOrNot = False
number = int(input("Type a number to check if it's prime."))
while True:
if number == 2:
primeOrNot = True
elif "2" in str(number) or "4" in str(number) or "6" in str(number) or "8" in str(number) or "0" in str(number) or number == 1:
primeOrNot = False
numList = [''.join(p) for p in permutations(str(number))]
for p in range(0, len(numList)):
numList[p] = int(numList[p])
for u in range(2, number):
if all(o % u == 0 for o in numList):
counter = counter + 1
if counter == 0:
print(numList)
break
I'm trying to make it so it prints a prime if all permutations of the number are also primes.
I've tried to do that with all but what it's doing is checking if atleast 1 of the elements in the list fits the o % u = 0. I want it to check if all of the elements work, not if one. Anything I can do using all or using something else?
Example of output now:
Input: 12
Output: Nothing, Neither 12 nor 21 are prime
Input: 35
Output: 35, 53
Even though 35 isn't prime it prints because 53 is.

Your logic is faulty:
for u in range(2, number):
if all(o % u == 0 for o in numList):
counter = counter + 1
For each potential divisor in the range, you check to see whether that divisor goes into every permutation of the input. What value of u do you envision is going to divide both 35 and 53?
For starters, you need this to be any, not all.
Second, I strongly recommend that you look up how to find primes and/or factor numbers. You can learn better ways to handle this, especially when your input string is longer.
Also, note that a 0 or 5 in the input will also ensure that some of the permutations will be composite; assuming that the input is at least two digits, it must be entirely composed of 1379 digits.
if number in [2, 3, 5, 7]:
print("number is prime")
exit(0)
if any (d not in "1379" for d in str(number)):
print("This input has composite permutations")

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.

List of conditions

I wanted to make a list of conditions for if. I wanted to make a program that would find very high prime numbers. I don't want to write: number % 2 == 0 or - for every number that I divide with. If you know how to make a list of conditions or know how to easier get high prime numbers using yield please give me a hint.
def very_high_prime_numbers_generator():
number = 0
while True:
number = yield
if not (number % 2 == 0 or number % 3 == 0 or number % 7 == 0 or number % 5 == 0 or number % 11 == 0 or number % 17 == 0 or number % 19 == 0 or number % 13 == 0):
print(number)
number_generator = very_high_prime_numbers_generator()
number_generator.send(None)
for i in range(1000,10000):
number_generator.send(i)
You can use a nested loop or any or all to test the divisibility of the number against all those values:
if not any(number % k == 0 for k in (2, 3, 5, 7, 11, 13, 17, 19)):
print(number)
Of course, this still tests only those values, which will not be enough for "very high prime numbers". Instead, you could keep track of the prime number generated so far an test against all of those:
def very_high_prime_numbers_generator():
primes = []
number = 2
while True:
if not any(number % p == 0 for p in primes):
yield number
primes.append(number)
number += 1
number_generator = very_high_prime_numbers_generator()
for _ in range(100):
print(next(number_generator))
(This could be further enhanced by stopping once k**2 > number, e.g. using itertools.takewhile, and only testing odd numbers above 2.)
Also note that your "generator" was rather odd. By using send to set the value of number and then printing inside the function, your "generator" behaved rather like a regular "check if this number is prime" function than a proper generator. The above also fixes that.
This seems to be what you're trying to do although as others have pointed out it's far from efficient.
def find_prime(number, previous_primes):
for value in previous_primes:
if number % value == 0:
return False
return True
known_primes = [2, 3, 5, 7]
for i in range(8, 1000):
is_prime = find_prime(i, known_primes)
if is_prime:
known_primes.append(i)
I would advise having a look here.
a possible solution (yet not that efficient) for printing primes might be as described by Eli Bendersky, in the above link:
import math
def main():
count = 3
while True:
isprime = True
for x in range(2, int(math.sqrt(count) + 1)):
if count % x == 0:
isprime = False
break
if isprime:
print count
count += 1

How can I display all numbers in range 0-N that are "super numbers"

The program asks the user for a number N.
The program is supposed to displays all numbers in range 0-N that are "super numbers".
Super number: is a number such that the sum of the factorials of its
digits equals the number.
Examples:
12 != 1! + 2! = 1 + 2 = 3 (it's not super)
145 = 1! + 4! + 5! = 1 + 24 + 120 (is super)
The part I seem to be stuck at is when the program displays all numbers in range 0-N that are "super numbers". I have concluded I need a loop in order to solve this, but I do not know how to go about it. So, for example, the program is supposed to read all the numbers from 0-50 and whenever the number is super it displays it. So it only displays 1 and 2 since they are considered super
enter integer: 50
2 is super
1 is super
I have written two functions; the first is a regular factorial program, and the second is a program that sums the factorials of the digits:
number = int(input ("enter integer: "))
def factorial (n):
result = 1
i = n * (n-1)
while n >= 1:
result = result * n
n = n-1
return result
#print(factorial(number))
def breakdown (n):
breakdown_num = 0
remainder = 0
if n < 10:
breakdown_num += factorial(n)
return breakdown_num
else:
while n > 10:
digit = n % 10
remainder = n // 10
breakdown_num += factorial(digit)
#print (str(digit))
#print(str(breakdown_num))
n = remainder
if n < 10 :
#print (str(remainder))
breakdown_num += factorial(remainder)
#print (str(breakdown_num))
return breakdown_num
#print(breakdown(number))
if (breakdown(number)) == number:
print(str(number)+ " is super")
Existing answers already show how to do the final loop to tie your functions together. Alternatively, you can also make use of more builtin functions and libraries, like sum, or math.factorial, and for getting the digits, you can just iterate the characters in the number's string representation.
This way, the problem can be solved in a single line of code (though it might be better to move the is-super check to a separate function).
def issuper(n):
return sum(math.factorial(int(d)) for d in str(n)) == n
N = 1000
res = [n for n in range(1, N+1) if issuper(n)]
# [1, 2, 145]
First I would slightly change how main code is executed, by moving main parts to if __name__ == '__main__', which will execute after running this .py as main file:
if __name__ == '__main__':
number = int(input ("enter integer: "))
if (breakdown(number)) == number:
print(str(number)+ " is super")
After that it seems much clearer what you should do to loop over numbers, so instead of above it would be:
if __name__ == '__main__':
number = int(input ("enter integer: "))
for i in range(number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
Example input and output:
enter integer: 500
1 is super
2 is super
145 is super
Small advice - you don't need to call str() in print() - int will be shown the same way anyway.
I haven't done much Python in a long time but I tried my own attempt at solving this problem which I think is more readable. For what it's worth, I'm assuming when you say "displays all numbers in range 0-N" it's an exclusive upper-bound, but it's easy to make it an inclusive upper-bound if I'm wrong.
import math
def digits(n):
return (int(d) for d in str(n))
def is_super(n):
return sum(math.factorial(d) for d in digits(n)) == n
def supers_in_range(n):
return (x for x in range(n) if is_super(x))
print(list(supers_in_range(150))) # [1, 2, 145]
I would create a lookup function that tells you the factorial of a single digit number. Reason being - for 888888 you would recompute the factorial of 8 6 times - looking them up in a dict is much faster.
Add a second function that checks if a number isSuper() and then print all that are super:
# Lookup table for single digit "strings" as well as digit - no need to use a recursing
# computation for every single digit all the time - just precompute them:
faks = {0:1}
for i in range(10):
faks.setdefault(i,faks.get(i-1,1)*i) # add the "integer" digit as key
faks.setdefault(str(i), faks [i]) # add the "string" key as well
def fakN(n):
"""Returns the faktorial of a single digit number"""
if n in faks:
return faks[n]
raise ValueError("Not a single digit number")
def isSuper(number):
"Checks if the sum of each digits faktorial is the same as the whole number"
return sum(fakN(n) for n in str(number)) == number
for k in range(1000):
if isSuper(k):
print(k)
Output:
1
2
145
Use range.
for i in range(number): # This iterates over [0, N)
if (breakdown(number)) == number:
print(str(number)+ " is super")
If you want to include number N as well, write as range(number + 1).
Not quite sure about what you are asking for. From the two functions you write, it seems you have solid knowledge about Python programming. But from your question, you don't even know how to write a simple loop.
By only answering your question, what you need in your main function is:
for i in range(0,number+1):
if (breakdown(i)) == i:
print(str(i)+ " is super")
import math
def get(n):
for i in range(n):
l1 = list(str(i))
v = 0
for j in l1:
v += math.factorial(int(j))
if v == i:
print(i)
This will print all the super numbers under n.
>>> get(400000)
1
2
145
40585
I dont know how efficient the code is but it does produce the desired result :
def facto():
minr=int(input('enter the minimum range :')) #asking minimum range
maxr=int(input('enter the range maximum range :')) #asking maximum range
i=minr
while i <= maxr :
l2=[]
k=str(i)
k=list(k) #if i=[1,4,5]
for n in k: #taking each element
fact=1
while int(n) > 0: #finding factorial of each element
n=int(n)
fact=fact*n
n=n-1
l2.append(fact) #keeping factorial of each element eg : [1,24,120]
total=sum(l2) # taking the sum of l2 list eg 1+24+120 = 145
if total==i: #checking if sum is equal to the present value of i.145=145
print(total) # if sum = present value of i than print the number
i=int(i)
i=i+1
facto()
input : minr =0 , maxr=99999
output :
1
2
145
40585

Finding all numbers that evenly divide a number

So I'm trying to make a program that when I input a number it will give me all the factors(12->1,2,3,4,6,12). I only started programming very recently so there may be some very obvious things. But here's my code
numbers = [1]
newnum = 1
chosen = int(input("Enter what you want the factors of: "))
def factors(numbers,newnum,chosen):
lastnum = numbers[-1]
if (chosen == lastnum):
for number in numbers:
if (number % 1 != 0):
numbers.remove(number)
print (numbers)
else:
factors(numbers,newnum,chosen)
else:
newnum = numbers[-1] + 1
numbers.append(newnum)
print (numbers)
factors(numbers,newnum,chosen)
factors(numbers,newnum,chosen)
Ok, so I don't really need the redundancies addressed but if you see something that would completely stop the program from working please point it out. Sorry I bothered you all with this but I don't know what else to do.
There are lots of problems:
Every integer number modulo 1 is zero because each integer is divisible by one without remainder.
You remove items from the list you're iterating over, that will definetly give wrong results if you don't do it carefully!
You try to do recursion but you don't return the result of the recursive call. That's possible because you operate on a mutable list but it's generally not really good style
You don't have any inline comments explaining what that line is supposed to do, so it's hard to give any reasonable guidance on how to improve the code.
If you want a code that finds all factors, consider something like this:
chosen = int(input("Enter what you want the factors of: "))
def factors(chosen, currentnum=None, numbers=None):
# Recursion start, always append 1 and start with 2
if numbers is None:
numbers = [1]
currentnum = 2
# We're at the last value, it's always divisible by itself so
# append it and return
if currentnum == chosen:
numbers.append(currentnum)
return numbers
else:
# Check if the chosen item is divisible by the current number
if chosen % currentnum == 0:
numbers.append(currentnum)
# Always continue with the next number:
currentnum += 1
return factors(chosen, currentnum, numbers)
>>> factors(chosen)
Enter what you want the factors of: 12
[1, 2, 3, 4, 6, 12]
That's not the optimal solution but it uses recursion and gives a proper result. Just don't enter negative values or catch that case in the function at the beginning!
# Two Pointer Approach
ans = []
def divisor(val):
result = []
for i in range(1, val + 1):
ans.append(i)
i = 0
j = len(ans) - 1
while i < j:
if ans[i] * ans[j] == ans[-1]:
result.append(ans[i])
result.append(ans[j])
i += 1
else:
j -= 1
return sorted(result)
print(divisor(12))
# Output
>>> [1, 2, 3, 4, 6, 12]

Printing only nth number of prime sequence, python

I'm trying to write a program in python that can either print 1 through nth numbers of the prime number sequence, or print just the nth number of the prime number sequence. Here is the code.
import math
P = 2
X = raw_input('Choose a number: ')
Y = 1
def prime(P, Y):
Choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
if Choice == "1":
while Y <= int(X):
isprime = True
for x in range(2, int(P) - 1):
if P % x == 0:
isprime = False
break
if isprime:
print P
Y += 1
P += 1
elif Choice == "2":
prime(P, Y)
Basically, i have the first part down, so that it prints 1 through nth numbers of the prime sequence. However, I'm quite lost on how to make it calculate just the nth prime, where the nth prime is the given through raw input. It must be possible to do this in python, however, how would it be done, and what would be the best way to do so, without having to add too many new variables that i don't have here, (though i would be fine doing so). Help would be appreciated.
Add a condition so that if either the user wants to print all numbers, or you have reached the final prime number of the sequence, the number will be printed. (I have also replaced some of the variable names with more descriptive ones, and altered it so that the function is passed the number_of_primes as its only parameter, which would seem to make more sense.)
def print_primes(X):
choice = raw_input('Select 1 to print X numbers of the Prime sequence. \nSelect 2 to print the Xth number in the Prime sequence. \nWhat is your choice: ')
count = 1
n = 2
while count <= X:
is_prime = True
for i in range(2, int(n) - 1):
if n % i == 0:
is_prime = False
break
if is_prime:
if choice == "1" or count == X:
print n
count += 1
n += 1
number_of_primes = int(raw_input('Choose a number: '))
print_primes(number_of_primes)
Just only print if it's the Yth number:
if isprime:
Y += 1
if Y == X:
print P

Categories