Python Forum
Help with homework problem - iterating a function - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: Help with homework problem - iterating a function (/thread-7832.html)



Help with homework problem - iterating a function - midnitetots12 - Jan-26-2018

def iterate(iterationnumber):
indented - f(x) = 2*x
indented - count = srange(iterationnumber)
indented - vals = [3]
indented - for i in count:
second indented - a = vals[i]
second indented - b = f(a)
vals.append(b)
return vals

So the problem is asking me to modify my code above to make the initial value in the iteration to be an input. Here it is 3 as seen above - could someone point me in the right direction?


RE: Help with homework problem - iterating a function - Mekire - Jan-26-2018

You're going to need to post your code correctly in order for people to help you.
https://python-forum.io/misc.php?action=help&hid=25


Help with homework problem - iterating a function - midnitetots12 - Jan-27-2018

Hi - I'm being asked to iterate a function, though a modification to this code needed is one to allow the function to be an input, which can take any value. Here the function is set to be 2*x. Could someone point me in the right direction?

def iterate(numberofiterations,initial):
    f(x) = 2*x
    count = srange(numberofiterations)
    vals = [initial]
    for i in count:
        a = vals[i]
        b = f(a)
        vals.append(b)
    return vals
iterate(3,2); iterate (3,3); iterate(3,4)



RE: Help with homework problem - iterating a function - buran - Jan-27-2018

could you post the exact assignment? The code in your post is yours and not from the assignment, right?


RE: Help with homework problem - iterating a function - nilamo - Feb-21-2018

It's been a while, so just answering this is probably fine.

First, let's rewrite your example, so it's actually real code:
def iterate(numberofiterations,initial):
    f = lambda x: 2*x
    count = srange(numberofiterations)
    vals = [initial]
    for i in count:
        a = vals[i]
        b = f(a)
        vals.append(b)
    return vals
Ok, now let's rewrite it again, so the function can be passed in:
def iterate(mutator, numberofiterations, initial):
    count = srange(numberofiterations)
    vals = [initial]
    for i in count:
        a = vals[i]
        b = mutator(a)
        vals.append(b)
    return vals
Also, for the love of Guido, please use variable names with more than one character. a and b is incredibly ridiculous, and you should feel bad for using those.