0
Code interpretation
In one of the challenges I faced with this code, but I can not understand what it does. s=["Red","Green","blu","White"] p=[1,2,3,4] r="" for i in range(len(s)): r+=s[i][p[i]] print(r) Someone can help me? Thanks very much.
4 Antworten
+ 8
So before I begin explaining I just like to confirm instead of "blu" you meant "Blue" (I'm pretty sure I remember seeing this question and that it was but please correct me if I'm wrong).
so here:
"s" is a list with 4 values
"p" is also a list with 4 values
and "r" is an empty string.
"for i in range(len(s)):" so the length of "s" is 4 and "range(4)" includes 0, 1, 2 and 3.
So starting for the first value of "i" (also note that you could replace i with anything here and it would still be the same like "a" or even "dinosaur", it just stands for "for every iteration in ...) 0,
the empty string "r += s[i][p[i]]", s[0] = Red and as p[0] = 1, Red[1] points to the letter for index 1 of the string "Red" which is "e" (as the index starts from 0) so now r = "e",
so now for the next second value of "i": 1,
s[1] = "Green" and p[1] = 2 so Green[2] would be "e" so r += "e" is r = r + "e" which is r = "e" + "e" which is
r = "ee",
for the third value of "i": 2,
s[2] = "Blue" and p[2] = 3 so Blue[3] would "e" so now r += "ee" is r = "eee",
for the final value of "i": 3,
s[3] = "White" and p[3] = 4 so White[4] is now also "e" so r += "eee" which is r ="eeee"
"i" goes out of the valid range so we break out of the loop and r is now printed so the output is:
eeee
Edit: No problem :)
+ 3
Line 5 means 'get the i-th element from array s. Then get the p[i]-th element of s[i] and add to r'. Since elements of s is string(array of characters), we can get element from s[i].
So the second letter of Red, the third letter of Green, the fourth letter of Blue, and the fifth letter of White is added to r, and r becomes 'eeee'.
+ 1
great! Thanks very much!
0
Thanks very much for the detailed explanation!