- 1

anyone plzz ?

What is the result of this code? fib = {1: 1, 2: 1, 3: 2, 4: 3} print(fib.get(4, 0) + fib.get(7, 5))

1st Jul 2017, 6:13 PM
Edu Rut
Edu Rut  - avatar
3 Antworten
+ 4
Should be 8, I think. fib.get(4, 0) calls fib[4], which equals 3 fib.get(7, 5) calls fib[7], which doesn't exist and so assumes 5 Then 3+5 equals 8
1st Jul 2017, 9:08 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
+ 4
.get() method takes two arguments to determine its returned value. It tries to return the value assigned to the dictionary's key equal to its first argument and if fails (the specified key does not exist in the dictionary) - it returns the second argument. So the first fib.get looks for the value assigned to the key 4 in the fib dictionary. It finds it - fib[4] equals 3. Then fib.get(7,5) tries to find the value of fib[7]. Because such key does not exist, the method returns the second argument as value - it is equal to 5, so 5 is returned.
1st Jul 2017, 10:00 PM
Kuba Siekierzyński
Kuba Siekierzyński - avatar
0
how do we assume the number 5 but not others why ? @kuba
1st Jul 2017, 9:55 PM
Edu Rut
Edu Rut  - avatar