+ 1
What Is The Result Of The Below Lines Of Code?
def fast (items= []): items.append (1) return items print fast () print fast ()
11 Respostas
+ 10
I would say that there is no right or wrong with this code (except syntax errors). What the code *def fast (items= []):* is doing is called memoization, and is a type of caching data. As HonFu already mentioned the object items is created once and then used during the complete execution of the program.
*items* will cache values that are returned from the function. So if you use *return 'hello'* instead of *return items* the string 'hello' is cached.
The only problem by using memoization, is that it can happen by accident.
+ 5
First of all, this code will cause a syntax error.
Secondly, you shouldn't do like this, because items won't empty every time you run the function, it just will add 1 to items.
Here, you can see it yourself:
https://code.sololearn.com/ckzFjS7A11XT/?ref=app
Here is working code:
https://code.sololearn.com/cOOPuX5Fa9XV/?ref=app
+ 3
the value for the default arg items is only created once, so the list will keep growing.
+ 3
o.gak, tupel does not work because it is an immutable object, that means it can not be changed after creation. So after first initialization no further changes / assignments can be done.
+ 2
Lothar It works for `list` and `dict`, but `tuple`.
Do you have any idea about this?
+ 1
Thanks Asman-H
+ 1
Lothar Thank you!
mohamedy Now I think it is clear that what kind of data will be kept in momery.
See the code below.
Maybe can help you understand better.
https://code.sololearn.com/ct7gpgkkRx7a/?ref=app
0
second line means that your telling your computer to show the word fast
0
I’m a bit confused. Regardless of correctness of your syntax, we don’t give the funtion any parameter, shouldn’t it create a new list everytime? why just create once?
0
I don't think this counts as memoization - but I could be approaching it wrong.
I added some additional calls to the "right code, did it like this" example, and that's not verifying the cached values from call to call.
https://code.sololearn.com/cRq5mQ0377BH/?ref=app
- 1
[1]