0

Defining bacon and eggs.

def spam(a): def eggs(): a[:] = [5] def bacon(): a[0] += 1 eggs() bacon() return a[0] print(spam([2])) Output: 6 HonFu was kind enough to give me some help, but I'm still a bit lost. -HF pointed out that both "eggs" and "bacon" are being defined in "spam". -So print(spam([2])) means to print "2"? So is it number to += 1 or a[:] = [5], which is a dictionary but still no idea where to go from there. -Any additional help appreciated:).

9th Apr 2019, 10:48 PM
tristach605
tristach605 - avatar
5 Antworten
+ 1
def spam(a): def eggs(): a[:] = [5] def bacon(): a[0] += 1 eggs() bacon() return a[0] print(spam([2])) def spam(a): def eggs(): a[:] = [5,11,15] def bacon(): a[2] += 1 eggs() bacon() return a[2] print(spam([100])) Thanks Diego, I reworked the code. The number in print(spam([100])) could be anything as its changed to 5 when list [a:] = 5 runs. Then I added extra numbers to the list. You can now run it and by changing return a[] AND a[2] += 1 you can add one (or any other number) to index [0:2].
10th Apr 2019, 3:05 AM
tristach605
tristach605 - avatar
0
The code you're showing us is equal to this one. a = [2] a[:] = [5] a[0] += 1 print(a[0]) # 6 "a[:] = 5" doesn't create a dictionary but simply modifies the value of the list "a". a = [1, 2, 3] a[:] = 5 print(a) # [5] a = ["spam", "eggs"] a[:] = 5 print(a) # [5] Then, "a[0] += 1" adds a one to the first element of list "a" (5+1 == 6). Thus, 6 is printed.
9th Apr 2019, 11:14 PM
Diego
Diego - avatar
0
Thanks, Diego. Why did they write "a[:] = 5"? Why not just "a =5"? I know that closed square brackest mean list, not dictionary (thanks for pointing out my error:)). Are they saying #in original a=[1,2,3] from the 0 index to the last index delete all and assign a new value of 5? Is that what the colon means here (your code makes a lot more sense than theirs:)).
10th Apr 2019, 2:19 AM
tristach605
tristach605 - avatar
0
My mistake. It was supposed to be "a[:] = [5]". Edited my post. That said, "a[:] = 5" doesn't actually delete the previous values of "a" (they still exist somewhere in the universe), it just reassigns the list to another value. About their code, I suppose it's confusing on purpose. Perhaps it was meant to make you think and ask yourselve questions like these (which is good, I like that).
10th Apr 2019, 2:36 AM
Diego
Diego - avatar
0
But to read this code out loud it would go#print-spam-2, which becomes def eggs(2):, which iteratws to [5], and then whose value is added a 1 to? Am I reading that right in my head? Thanks. This one was a lu-lu!
10th Apr 2019, 3:07 AM
tristach605
tristach605 - avatar