PS3.3 - Why does this ask us to return a tuple and not a list? Since tuples are immutable they need several extra lines of code to update, whereas with a list you can just use append. Any logic behind this? Or is it just a preference thing?
Hoot! You just asked your first question! Hang tight while I find people to answer it for you. You can thank people who give you good answers by clicking the 'Good Answer' button on the right!
I tried to implement recursion in solution ps3b.py even though this wasn't asked for: http://pastebin.com/MT80xS3h; however, I couldn't find how not to pass 'positions' and 'index' as parameters. In other words, in oder to implement recursion in ps3b.py I passed a list of positions of the key and starting search index as parameters of the function. Strange things happened when I tested my recursive functional implementation. I can assign default valued to parameters 'positions' and 'index': def subStringMatchExactRecursive(target, key, positions=[], index=0): Now, I can supposedly call the function without explicitly passing arguments for parameters 'positions' and 'index': subStringMatchExactRecursive(target, key) But if I do this twice in a row: subStringMatchExactRecursive(target, key) subStringMatchExactRecursive(target, key) I will have the correct result first time, but second time the correct result will be appended to the first correct result. If I call the recursive function three times, I will have the correct result the first time, second time I will have two appended correct results in a tuple and third time I will have three correct appended results in a tuple. I guess this is why a tuple is asked for as an output of a function: "to make sure the output of the function is unique" or in other words that the function doesn't modify its output next time the function is called like in my example of recursion. Hope this helps.
Actually this issue you've described has to do with the timing for creation of objects used as defaults. You might expect that positions will have a new list each time you call the function, but it will not. The list object that the function uses as its default is created when the function is defined and any attempt to call the function will have the same list. You can see this more clearly with the following code: class Default: def __init__(self): print 'Default was created' self.stuff = 1 def test(n, d = Default()): print n, d.stuff d.stuff += 1 test(1) test(2) test(3, Default()) test(4)
Cool, thanks!
Join our real-time social learning platform and learn together with your friends!