I wrote a function to calculate the square root, though the function must operate with the while loop at the top.
Additionally, if I type in an input value which has no square root, the function goes into infinite loop.
def square(x):
return x * x
def qrt(n):
i = 100
while True:
if square(i) != n:
i -= 1
else:
return i
If you use while(i>0): instead of while True: the loop will end after i reaches 0. However, I would suggest to use math.sqrt() from pythons builtin math module. That would look like this:
import math
math.sqrt(n)
Related
I was asked to create a function to give a square of a value. Here is the defined function:
def square(x):
print(x**2)
secondly I was asked to define another function to check weather the number is odd or even:
def oddeve(x):
if x % 2 == 0:
print ("{} is even".format(x))
else:
print ("{} is odd".format(x))
However now they want me to use both the function together to check whether the square is odd or even. Can anyone help me with how to combine two pre defined functions?
You can simply call one function inside of the other function. However, this requires that you don't print out the value, but rather return it:
def square(x):
return(x**2)
Now you can simply call:
oddeve(square(x))
For example, if x = 4, square(4) returns 16, and oddeve(16) prints out that it is even.
How can I define a function in python in such a way that it takes the previous value of my iteration where I define the initial value.
My function is defined as following:
def Deulab(c, yh1, a, b):
Deulab = c- (EULab(c, yh1, a, b)-1)*0.3
return (Deulab,yh1, a,b)
Output is
Deulab(1.01, 1, 4, 2)
0.9964391705626454
Now I want to iterate keeping yh1, a ,b fixed and start with c0=1 and iterate recursively for c.
The most pythonic way of doing this is to define an interating generator:
def iterates(f,x):
while True:
yield x
x = f(x)
#test:
def f(x):
return 3.2*x*(1-x)
orbit = iterates(f,0.1)
for _ in range(10):
print(next(orbit))
Output:
0.1
0.2880000000000001
0.6561792000000002
0.7219457839595519
0.6423682207442558
0.7351401271107676
0.6230691859914625
0.7515327214700762
0.5975401280955426
0.7695549549155365
You can use the generator until some stop criterion is met. For example, in fixed-point iteration you might iterate until two successive iterates are within some tolerance of each other. The generator itself will go on forever, so when you use it you need to make sure that your code doesn't go into an infinite loop (e.g. don't simply assume convergence).
It sound like you are after recursion.
Here is a basic example
def f(x):
x += 1
if x < 10:
x = f(x)
return x
print (f(4))
In this example a function calls itself until a criteria is met.
CodeCupboard has supplied an example which should fit your needs.
This is a bit of a more persistent version of that, which would allow you to go back to where you were with multiple separate function calls
class classA:
#Declare initial values for class variables here
fooResult = 0 #Say, taking 0 as an initial value, not unreasonable!
def myFoo1(x):
y = 2*x + fooResult #A simple example function
classA.fooResult = y #This line is updating that class variable, so next time you come in, you'll be using it as part of calc'ing y
return y #and this will return the calculation back up to wherever you called it from
#Example call
rtn = classA.myFoo1(5)
#rtn1 will be 10, as this is the first call to the function, so the class variable had initial state of 0
#Example call2
rtn2 = classA.myFoo1(3)
#rtn2 will be 16, as the class variable had a state of 10 when you called classA.myFoo1()
So if you were working with a dataset where you didn't know what the second call would be (i.e. the 3 in call2 above was unknown), then you can revisit the function without having to worry about handling the data retention in your top level code. Useful for a niche case.
Of course, you could use it as per:
list1 = [1,2,3,4,5]
for i in list1:
rtn = classA.myFoo1(i)
Which would give you a final rtn value of 30 when you exit the for loop.
Below, I came up with artificially passing the reference var n2 from f2() to g2(x) instead of the global var n in f() and the nested g(). Any other better ways to replace global vars in this case?
from random import randint
# global value var
def f():
global n
n=0
def g():
global n
if randint(1,100)>50: n+=1
for _ in range(100): g()
print(n)
# local reference var
def f2():
n2=[0]
for _ in range(100): g2(n2)
print(n2[0])
def g2(x):
if randint(1,100)>50: x[0]+=1
Short answer: You are trying to pass by reference an immutable value (integer) and want to update it. Wrapping that in a tiny class, or list, or dict like you're doing is the way to go. But there are other ways if you are able to slightly modify your code.
Longer answer: (Note: This might not be a direct answer to your question.)
I understand this is an artificial example. But think about your real problem --Does g2() need to know that there is a variable that is supposed to update as a part of its invocation? Is there a way that the responsibility of updating a variable belongs to that which defines it? How about f2() is the one that defines the variables and also updates it? That way you can limit all the changes to that variable to a very small perimeter (f2()).
My approach in that case would be something like:
def f2():
n2 = 0
for _ in range(100):
n2 += g2()
print(n2)
def g2():
return 1 if randint(1,100)>50 else 0
From working with functional languages, and from trying to write reproducible tests, I've generally tried to adopt a rule that a function should declare all of its inputs as parameters, and produce all of its outputs as return values: to the maximum extent possible a function should never have side effects. Using the global keyword probably indicates you're breaking this rule.
For example, your "g" function takes the current state variable and either increments it or doesn't. You don't need a global for that (and you don't need it to be a nested function either):
from random import randint
def g(n):
"""Returns either n or n+1, with 50% probability."""
if randint(1,100)>50:
return n+1
else:
return n
Then the iterating function can call that a bunch of times:
def f():
"""Produces a number between 0 and 100 with $DISTRIBUTION."""
n = 0
for _ in range(100):
n = g(n)
return n
And finally at the top level:
if __name__ == '__main__':
print(f())
Since we're never totally sure about our code, we can write some tests.
def test_f():
n = f()
assert n >= 0 and n < 100
def test_g():
n = g(0)
assert n == 0 or n == 1
def test_g_dist():
count = 100
ns = [g(0) for _ in range(count)]
assert(all(n == 0 or n == 1) for n in ns)
zeros = len([n for n in ns if n == 0])
ones = len([n for n in ns if n == 1])
assert zeros + ones == count
# won't always pass; probability of failure left as an exercise
assert zeros > 0.45 * count and zeros < 0.55 * count
Notice that I can call f() and g(n) as many times as I want and they'll never interfere with anything else. Running my own unit tests at startup time would be a little unusual, but I'm free to if that's what I want to do.
How can I put this in recursive? This is an assignment to calculate the factorial of a number and tell if a number is prime or not only using addition and subtraction, but it needs to be in recursive form but I can not figure out how to do it.
def Prod(x,r):
z=0
while x>0:
z=z+r
x=x-1
return z
def Fat(x):
r=1
while x>1:
r=Prod(x,r)
x=x-1
return r
AND
def Divi(x,d):
c=0
while x>=d:
x=x-d
c=c+1
return x
def Pri(x):
r='N'
d=2
while d<x and r=='N':
if(Divi(x,d)==0):
r='S'
d=d+1
if r=='N':
t='its prime'
else:
t='not prime'
return t
Forgot to mention that also I can only use if ... elif ... else nothing but that
A recursive function is just a function that calls itself.
def me():
me()
except, the most trivial recursive function, given above, recurses forever, just like an infinite loop loops forever:
while True:
dab()
So what do you do to prevent the infinite loop? You have a loop condition:
x = 3
while x > 0:
dab()
x -= 1
Now your loop will exit. So how do we prevent a recursive function from looping infinitely? We provide a base case where the recursive function does not call itself:
def dabr(x):
if x <= 0:
return
dabr(x - 1)
In your code above, you exit the loop when x>1 is no longer true. That's your base case. So write that as an if statement, such that the function recurs on itself only when x>1. Here's a hint:
def Fat(x):
if x <= 1:
return ???
return ???
When you are programming recursively, you are calling a function into itself.
def Prod(a, b):
...
def Fat(r=1):
if r <= 1:
return 1
else:
return Prod(r, Fat(r - 1))
In this case, you are calling the function Fat inside itself.
I should write a function min_in_list(munbers), which takes a list of
numbers and returns the smallest one. NOTE: built-in function min is NOT allowed!
def min_in_list(numbers):
the_smallest = [n for n in numbers if n < n+1]
return the_smallest
What's wrong?
def min_of_two(x, y):
if x >= y: return x
else: return y
def min_in_list(numbers):
return reduce(min_of_two, numbers)
You have to produce 1 number from list, not just another list. And this is work for reduce function (of course, you can implement it without reduce, but by analogy with it).
Here you go. This is almost certainly about as simple as you could make it. You don't even have to give me credit when you turn the assignment in.
import itertools
import functools
import operator
def min(seq, keyfun=operator.gt):
lt = lambda n: functools.partial(keyfun, n)
for i in seq:
lti = lt(i)
try:
next(itertools.ifilter(lti, seq))
except:
return i
min = lambda n: return reduce(lambda x,y: (x>y) and return x or return y,n)
Never been tested, use at your own risk.