Course 1 Week 4 Exercise 7

Hi,

I’m working on writing up the linear_backward function and I have the following:

{moderator edit - solution code removed}

I am facing the error of TypeError: tuple indices must be integers or slices, not str.

Am I calling the cache wrongly?

Thank you.

Yes, the cache is a list or “tuple”, but you are treating it like a python dictionary with string keys.

Note that they already gave you the code in the template to extract the contents of the cache:

A_prev, W, b = cache

I suggest you read the template code a bit more carefully. :nerd_face:

1 Like

Hi @paulinpaloalto

Thank you for getting back to me. I must say my knowledge of python is really showing in this exercise. Are caches more like lists?

Also, in the previous example (example 5), why were parameters called via parameters[“W” + str(l)] and not just parameters[“W”]?

There are many different data structures in python. You have to look at the code and understand which one is being used. Did you read the template code that I pointed out? Just because parameters is a dictionary, that doesn’t many that any other particular variable is also a dictionary.

The particular code that references parameters is retrieving the weight matrix for a particular layer. The keys for those are the string names W1, W2 and so forth. You have the layer number in a variable l and you want to create a string that starts with W and includes the layer number. One easy way to do that in python is “W” + str(l). What the str() function does is convert whatever the argument is to a string. And what the + operator means for strings is concatenation.

1 Like

I see!!! I was wondering about that. Thank you.

@paulinpaloalto, very well explained sir. Thank you for this clarification. These short inputs and clarifications are so useful for us as well. Keep shining!

The other point here is that python is an interpreted language. It is interactive. You don’t have to wonder what something does: you can try it and see. For example, if you want to know what type caches is, do this:

print(f"type(caches) = {type(caches)}")

If you want to understand what “W + str(l)” does try some examples:

myStr = "Fred"
myNumber = 3.0
print(myStr)
longStr = myStr + "  " + "Flintstone" + "  " + str(myNumber)
print(longStr)