+ 2
Task from challenge.
What is it and how does it work? A=[1,2,3,4,1] for n in A: A[n]=0 print(A)
3 ответов
+ 11
Run this and see how the list changes dynamically:
A = [1, 2, 3, 4, 1]
i = 0
for n in A:
i += 1
print('iteration #%d:' % (i,))
print('n: %d' % (n,))
print('setting A[%d] to 0...' % (n,))
A[n] = 0
print('A: %s\n' % (A,))
+ 8
——Theoretical Explanation——
A is a defined list with 5 elements (numbers in this case).
The for loop runs for each element i.e. 5 times, each time assigning 'n' with the value of the corresponding element.
Now, for the code inside the for loop - every time an iteration of the loop takes place, the value at 'n'th position in the list A is changed to 0.
Finally, the new modified list A is printed.
——Practical Explanation——
A = [1,2,3,4,1]
#1st iteration
n = A[0] = 1
A[1] = 0
A = [1,0,3,4,1]
#2nd iteration
n = A[1] = 0
A[0] = 0
A = [0,0,3,4,1]
#3rd iteration
n = A[2] = 3
A[3] = 0
A = [0,0,3,0,1]
#4th iteration
n = A[3] = 0
A[0] = 0
A = [0,0,3,0,1]
#5th iteration
n = A[4] = 1
A[1] = 0
A = [0,0,3,0,1]
print(A)
#prints [0,0,3,0,1]
+ 3
Oh - it took a while for me.
This is a really tough question in such a short time as its usual in challenges.
# Iteration 1:
[1, 2, 3, 4, 1] # = A
1 -> 2 -> 0
[1, 0, 3, 4, 1] # = A after iter 1
# Iteration 2:
[1, 0, 3, 4, 1] # = A
0 -> 1 -> 0
[0, 0, 3, 4, 1] # = A after iter 2
# Iteration 3:
[0, 0, 3, 4, 1] # = A
3 -> 4 -> 0
[0, 0, 3, 0, 1] # = A after itr 3
# Iteration 4:
[0, 0, 3, 0, 1] # = A
0 -> 0 -> 0
[0, 0, 3, 0, 1] # =A after iter 4
# Iteration 5:
[0, 0, 3, 0, 1] # = A
1 -> 0 -> 0
[0, 0, 3, 0, 1] # = A after iter 5
Result —> [0, 0, 3, 0, 1]