Hi guys can u help i want to make number list prime in python but with no for loop do or while in inside or outside only with recursive function
this is mycode with def recursion, can u guys help me change to print 2-limit in def recursive ?
def is_prime(n, div=2):
if div> n/2.0: return True
if n% div == 0:
return False
else:
div+=1
return is_prime(n,div)
but this will need for outside def to print all number 2-100
#The program:
for i in range(2,100,1):
if is_prime(i):
print(i)
how to change the for in outside def, with just
limit = int(input("input limit prime = )
print(is_prime(limit,2)
what i mean is, how to print 2-limit with recursion in def without loop for,while outside def. im confuse how to make recursive function from it
Thanks
If you goal is to perform recusion on your function without an outside loop, this is a solution...
def is_prime(n, max_n, div=2):
if n> max_n: return False
if div > n / 2.0:
print(n)
return is_prime(n+1,max_n)
if n % div == 0:
return is_prime(n + 1, max_n)
else:
return is_prime(n , max_n,div+1)# forgot to increment div and not increment n so we can runit through the function again
is_prime(2, 100)
Related
I have some textbook code that calls itself recursively. I don't understand the program flow. Here is the code:
def Recur_Factorial_Data(DataArray):
numbers = list(DataArray)
num_counter = 0
list_of_results = []
for num_float in numbers:
n = int(num_float)
1. result = Recur_Factorial(n)
list_of_results.append(result)
def Recur_Factorial(num):
if num == 1:
2. return num
else:
result = num*Recur_Factorial(num-1)
3. return result
if num < 0:
return -1
elif num == 0:
return 0
else:
return 0
In Recur_Factorial_Data, I loop through the data elements and call Recur_Factorial, which returns its value back to the calling function (Recur_Factorial_Data). I would expect that the lines marked 2 ("return num") and 3 ("return result") would always return a value back to the calling function, but that's not the case. For example, where the initial value (from the array DataArray) is 11, the function repeatedly calls itself until num is 1; at that point, the program falls to the line marked 2, but it does not loop back to the line marked 1. Instead, it falls through to the next line. The same happened on the line marked 3 -- I would expect it to return the result back to the calling function, but it does that in some cases and not in others.
I hope this is enough description to understand my question -- I just don't know why each return does not loop back to return the result to the calling function.
EDIT: The question at Understanding how recursive functions work is very helpful, and I recommend it to anyone interested in recursion. My question here is a bit different -- I asked it in the context of the program flow of the Python code where the recursive function is called.
If it call itself recursively 10 times, it will be at the 10th level of recursion and should go back 10 times at the point where there was a recursive call with an intermediate result and only then exit from the recursive function to the place where it was called. Learn more about recursion
Also try to rearrange instructions in Recur_Factorial function in this way:
def Recur_Factorial(num):
if num < 0:
return -1
elif num == 0:
return 0
elif num == 1:
return num
else:
return num * Recur_Factorial(num-1)
I'm a bit new to programming, and I'm trying to create a root-approximating code. Namely, I'm doing something similar to Newton's method in calculus. The idea is, I'm going to input in a big value, subtract until I know I've passed the root, and then add a smaller quantity until I've passed the root, and iterate until I'm in some comfortable error region.
Here's some pseudo code:
def approx(a,b,i):
while ((1/2)**i) >= (1/2)**10:
while (another function is true):
modify values, record root = r
while (the same function above is false):
modify values, record root = r
return approx(a,b,i+1)
return(a,b,r)
This does not seem to work in Python, so I was wondering if anyone could point me in the correct direction.
Edit: included my actual code:
from fractions import *
from math import sqrt
from math import fabs
def pweight(c,d):
if d > c:
return pweight(d,c)
else:
return [c+d,c,d]
def eweight(a,b):
if a == b:
return [a]
elif b > a:
return eweight(b,a)
else:
return [b] + eweight(a-b,b)
def weight(a,b,c,d):
if a*b/2 > c*d:
print("No Embedding Exists")
return (False)
else:
return (True, [c+d]+sorted((pweight(c,d) + eweight(a,b))[1:], reverse=True))
def wgt(a,b,c,d):
return ([c+d]+sorted((pweight(c,d) + eweight(a,b))[1:], reverse=True))
def red(a,i,k):
d=a[0]-a[1]-a[2]-a[3]
if any(item < 0 for item in a[1:]):
# print ("No Embedding Exists")
return (False, i)
elif d >= 0:
# print ("Embedding Exists! How many iterations?")
# print(i)
return (True, i)
elif d<0:
a=[a[0]+d,a[1]+d,a[2]+d,a[3]+d]+a[4:]
a=[a[0]]+sorted(a[1:],reverse=True)
k.append(a)
i=i+1
return red(a,i,k)
def works(a,b):
L = sqrt(a/(2*b))
w = weight(1,a,L,L*b)
return w[0] and red(w[1],0,[])
def inf(a,b,i):
while ((1/2)**(i+1)) >= (1/2)**(10)):
while works(a,b):
a = a - (1/2)**i
L = sqrt(a/(2*b))
while not works(a,b):
a = a + (1/2)**(i+1)
L = sqrt(a/(2*b))
return inf(a,b,i+1)
return (a,b,L)
I want to input in "inf(9,1,0)" and have this code return something close to (255/32,1,sqrt(255/64)). The main problem is the "while works(a,b):" and "while not works(a,b):" in the function "inf(a,b,i)." I want the function to alternate between the "while works" and "while not works" until i=9.
Any sort of general idea would be appreciated (namely, how do you do some sort of alternating function within a while loop).
If you want to alternate between them, don't put them each in their own while loops, put
while i < 9:
if works(a, b):
do something
if not works(a, b):
do something else
And whatever you test in your while conditions needs to be something that changes somewhere in the loop. Otherwise you'll get an infinite loop.
I am creating a collatz sequence with a recursive function below:
def collatz(n):
if n%2 == 0:
return int(n/2)
else:
return int((3 * n)/2)
From what I understand, a recursive function is a function that basically calls itself. Below I have attempted creating the recursive function with the following:
def collatz(x):
if x == 1:
"Done"
print(x)
x = collatz(x)
return(x)
Where essentially the variable x continues to get passed into the collatz function I defined until it gets to 1. However, every time I run the recursive function it prints 'x' repeatedly and then I get the
collatz(3)
'RecursionError: maximum recursion depth exceeded in comparison'
Which I understand is an infinite loop essentially. I thought by reassigning it to x to the results of the first collatz() it would return the new value and continue till it hit '1' but I can't seem to quite get there.
Any help/tips/advice would be great! Thanks!
Recursive functions have what's known as a "base case" and what's known as a "recursive case." The base case is when you should stop recursing and return an answer.
In this case, the base case is when x==1
def collatz(x):
if x == 1:
return x
and the recursive case is the rest of the time
# continuing from above
else:
if n % 2 == 0:
return collatz(int(n//2))
else:
return collatz(n*3 / 2) # sicut. Note that the collatz sequence
# uses 3n+1 here, not 3n/2 as in the question
N.B. that I change the effective value of x in the next loop through collatz before returning the result of that new call. If you don't, and simply return collatz(x), you'll never reach your base case and recurse forever.
#Roee Gavirel
Here is the final answer based on his answer above:
def collatz(x):
if x == 1:
"Done"
elif x%2 == 0:
x = int(x/2)
print(x)
collatz(x)
else:
x = int((3*x)+1)
print(x)
collatz(x)
collatz(3)
Thanks for all the help!
You show two different implementations of the same function collatz, while you need to combine them.
def collatz(n):
if x == 1:
"Done"
print(x)
if n%2 == 0:
collatz(int(n/2))
else:
collatz(int((3 * n)/2))
I'm trying to find the largest prime factor of a given number (600851475143) using Python. I've made the following code, but I don't know what is wrong and whether I am using right code Please help find my mistake and improve it.
import math
def t(x):
l=[]
for i in range(1,int(math.sqrt(x))):
if x%i==0:
l.append(i)
return l
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return 'this is not prime'
return 'ya'
print t(600851475143)
print check(486847)
You need to check that everything you're adding to the list is actually a prime
for i in range(1,int(math.sqrt(x))):
if (x % i) != 0:
continue
if check(i):
l.append(i)
Then, pop the last (largest) element of the list:
return l.pop()
You can also check up to the square root:
def check(y):
for i in range(2,int(math.sqrt(y))):
if (y % i) == 0:
return False
return True
Here's a slightly modified version that iterates backwards (as suggested by pzp), and returns as soon as a prime is found:
#!/usr/bin/env python
import math
def t(x):
for i in xrange(int(math.sqrt(x)), 1, -1):
if (x % i) != 0:
continue
if check(i):
return i
return None
def check(y):
for i in range(2, int(math.sqrt(y))):
if (y % i) == 0:
return False
return True
print t(600851475143)
print check(6857)
You're pretty close. Your check() is returning before you want it to. You want:
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return 'this is not prime'
return 'ya'
This will wait until you've check all the numbers < y before returning false. Right now, it checks 2, then returns either true or false.
Also t() is returning all factors, rather than the greatest factor. For just the greatest factor (assuming there is one), you want return l[-1]
EDIT:
Ok, I think I get what you're going for. By using this t() and check(), you can get the largest prime by with:
def t(x):
l=[]
for i in range(1,int(math.sqrt(x))):
if x%i==0:
l.append(i)
return l
#Notice, return list of all factors
def check(y):
for i in range(2,1+y/2):
if y%i==0:
return False
return True
number_to_check = 92873465
prime_factors = []
for factor in t(number_to_check): # Iterate through factors returned from t()
if check(factor):
prime_factors.append(factor)
print "Largest Prime Factor: " + prime_factors[-1]
def b():
a = int(input("Look up to: ")) // set the range to scan for primes
for num in range(0, a):
if prime(num) == True:
print(num)
print("adding to list")
return num
list = [num]
list.append(num)
else:
print(num, "is not a prime")
So how can I append the outcome to "list" for each new prime?
Forgot to mention the function to check if num is prime:
def prime(num):
for j in range (2, num):
if (num % j) == 0 :
return False
return True
Few points:
Once you return is executed, the value it is applied to is returned to whoever called the function and the code after return never executes.
You're shadowing the built-in function list() which returns a new list by calling a local variable list.
The list is constantly reconstructed by calling [num] which is a shorthand for creating a new list containing only num. What you want to do is update it using append.
Fixing the code, it may look something like:
def get_primes():
a = int(input("Look up to: "))
# 'primes' is a more suitable name for a list of primes
# we're only creating the list *once*, and we're not shadowing 'list'
primes = list()
for candidate in range(0, a):
if prime(candidate) == True:
print(candidate)
print("adding to list")
primes.append(candidate)
else:
print(num, "is not a prime")
# use return to return a result
return primes
You can test this by calling get_primes().
Tip: you could use filter to do the same thing get_primes does:
a = int(input("Look up to: "))
print(filter(prime, range(0, a)))
A minor note about the difference between list and [] is that you can change list's behaviour, which gives finer control, while []'s generated code calls BUILD_LIST directly (harder to change):
>>> dis.dis(lambda: [])
1 0 BUILD_LIST 0
3 RETURN_VALUE
>>> dis.dis(lambda: list())
1 0 LOAD_GLOBAL 0 (list)
3 CALL_FUNCTION 0
6 RETURN_VALUE
It really does not matter in this case, but #Thrustmaster suggested using [] in the comments since it some may see it as cleaner.
Oh, lot of minor syntax errors. Let me list them down..
Python comments do not start with //, but with #. Ref. code line no: 2
list is a keyword in python, you should not use that in your variable declaration. Line ref: 8.
After you do a return, the code after that line will not be executed. Line Ref: 7.
You should not initialize list inside the for loop. It is getting initialized in every iteration.
Instead of if prim(num) == True:, you can simply write if prim(num):.
That said, the correct code should look as follows:
def b():
a = int(input("Look up to: ")) # set the range to scan for primes
primes = [] #Your list
for num in range(0, a):
if prime(num):
print(num)
print("adding to list")
primes.append(num)
else:
print(num, "is not a prime")
return primes
Hope it helps .. :)
Your code looks to be a mix of C and Python (don't use // as comments).
I assume your program is looking for prime numbers up to n. Here is how one might go about implementing this:
import math
def is_prime(n):
if n % 2 == 0 and n > 2:
return False
for i in range(3, int(math.sqrt(n)) + 1, 2):
if n % i == 0:
return False
return True
def find_primes(a, b):
primes = []
for i in range(a, b):
if is_prime(i):
primes.append(i)
return primes
You're almost there. The strange thing about your code is where you've placed the return statement. Try this:
def b():
primesList = []
a = int(input("Look up to: "))
for num in range(0, a):
if prime(num) == True:
print(num)
print("adding to list")
primesList.append(num)
else:
print(num, "is not a prime")
return primesList
Notice that your original return statement would have ended your function early, in fact even before your list would have had the chance to append any prime number at all. The other important point here is that you should never shadow a built-in type (list in this case), or other built-in functions (like map, sorted, etc.).
It's also enough to simply initialize the primesList once and append the num integers inside the for loop.
The other answers are good and address the main issue that you had with rebinding your list variable and failing to return the primes list from function b().
I think it's worth mentioning that a list comprehension can be used to succinctly code the prime list generation:
def prime(num):
for j in range (2, num):
if (num % j) == 0 :
return False
return True
def get_primes(low, high):
return [n for n in range(low, high+1) if prime(n)]
>>> a = input("Look up to: ")
11
>>> get_primes(0, a)
[0, 1, 2, 3, 5, 7, 11]
>>> get_primes(5, a)
[5, 7, 11]
Notes:
Passing the "up to" value into the function is more flexible than
prompting for it in the function.
"Up to" should be inclusive, e.g. get_primes(0, 11) should include 11 in the result. Therefore you need to add one to the upper value when calling range().
Passing low and high allows you to generate primes for arbitrary ranges.
You can wrap the list comprehension with set() to have the result returned as a set.