OK, our professor explained (kinda) this problem, but it still doesn't make much sense.
Question: Implement the function knice(f,a,b,k)
that will return 1 if for some integer a <= x <= b
and some integer n <= k
, n applications of f
on x will be x, (eg f(f(f...(f(x)))) = x
) and 0 if not.
What the professor provided was:
def knice(f,a,b,k):
f(f(f(...(f(x)))) = x
for i = a to b:
y = f(i)
if y = i break
for j = z to k:
y = f(y)
if y = i break
Personally, that example makes no sense to me, so looking to see if I can get clarification.
OP EDIT 1/19/2012 3:03pm CST
This is the final function that was figured out with the help of the GTA:
def f(x):
return 2*x-3
def knice(f,a,b,k):
x = a
while x <= b:
n = 1
y = f(x)
if y == x:
return 1
while n <= k:
y = f(y)
n=n+1
if y == x:
return 1
x=x+1
return 0
Ignore his code; you should write whatever you feel comfortable with and work out the kinks later.
You want to work out whether
f(a) = a
, or f(f(a)) = a
, or ..., or f^n(a) = a
, or , f(a+1) = a+1
, or f(f(a+1)) = a+1
, or ..., or f^n(a+1) = a+1
, or , f(b) = b
, or f(f(b)) = b
, or ..., or f^n(b) = b
. An obvious algorithm should come to mind immediately: try all these values one-by-one! You will need two (nested) loops, because you are iterating over a rectangle of values. Can you now see what to do?
Yeah, I can see why that might be confusing.
Was f(f(f(...(f(x)))) = x
wrapped in triple-double-quotes? That's a function documentation string, sort of like commenting your code. It shouldn't have been stand-alone without something protecting it.
Imagine f was called increment_by_one.
Calling increment_by_one 10 times like that on an x of 2 would give 12. No matter how many times you increment, you never seem to get back 2.
Now imagine f was called multiply_by_one.
Calling multiply_by_one 5 times like that on an x of 3 would give 3. Sweet.
So, some example outputs you can test against (you have to write the functions)
knice(increment_by_one, 1, 3, 5)
would return 0.
knice(multiply_by_one, 1, 3, 5)
would return 1.
As another hint, indentation is important in python.
Here's a concrete example. Start small, and suppose you called knice(f, a=1, b=2, k=1)
. For k==1
, we don't have to worry about iterating the function. The only values of x
to consider are 1 and 2, so knice
can return 1 (ie, True) if f(1)==1
or f(2)==2
.
Now suppose you called knice(f, a=1, b=2, k=2)
. You'll have to check f(f(1))
and f(f(2))
as well.
As k
gets bigger, you'll have to call f
more. And as the range between a
and b
gets bigger, you'll have to try more values of x
as an argument to f
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.