Quizz n* 1) question 6) I don't understand question 6. Could someone walk me through it plz ? I watched the solutions but I don't get how is that happening. Thanks in advance :)
Can you please post the question here?
Quiz 1, #6: 6) Consider the following code: def f(s, d): for k in d.keys(): d[k] = 0 for c in s: if c in d: d[c] += 1 else: d[c] = 0 return d def addUp(d): result = 0 for k in d: result += d[k] return result d1 = {} d2 = d1 d1 = f('abbc', d1) print addUp(d1) d2 = f('bbcaa', d2) print addUp(d2) print f('', {}) print result 6.1) What does it print? (9 points) .... 6.2) Does it terminate normally? Why or why not? (4 points)
It'd help if you told us what part exactly you'd need help with. But in the meantime, I can try to explain the d1 = f('abbc', d1) line. When you enter the function, the first "for" loop does nothing, because the dictionary is empty. d[k] doesn't exist, so you can't change its value. Let me be more precise: a "for" loop is used when you want to iterate through a collection of elements. "for k in d.keys()" tries to access the keys of d, because it wants to iterate through them, but it can't because there aren't any keys. But the second "for" loop is very different. This time, what it wants to iterate through actually exists: it's the characters contained in the string "abbc". Then, what the body of the loop says is: IF there's a key in d, and that one of the characters in the string "abbc" matches that key, then change its value. There are no keys (yet) in d, so you're redirected to the ELSE. Which is where stuff happens: if you're in the ELSE, it means there was no match, but what "d[c] = 0" effectively does now is *create* a key in d--whatever variable c is bound to, which is "a" on the first iteration-- and set its value to 0. You need to understand the fundamental difference between the two "for" loops. Again, the first one wants to access the keys in d and iterate through them, but since there are no keys yet, it can't do anything. Whereas the second "for" loop says is "if there's a key's there, great, but if not, then put it in there". Of course it's confusing, but that's how it works. At first you'd be tempted to think that since d[c] doesn't exist in the first place, you can't change it's value, but again, that simple statement makes that key/value pair come into being. In fact, you can try it in Python's shell: create an empty dict, say d={}, then type in d['a'] = 1, then type d to see what d now looks like. Hope it helps; try to see if you can figure out the rest, but if you need help, don't hesitate to ask another question!
I meant "--whatever value the variable c is bound to, which is "a" on the first iteration--", not "--whatever variable c is bound to, which is "a" on the first iteration--".
Join our real-time social learning platform and learn together with your friends!