Q.Find and write the output of the following Python code: def ChangeVal(M,N): for i in range(N): if M[i]%5 == 0: M[i] //= 5 if M[i]%3 == 0: M[i] //= 3 L=[25,8,75,12] ChangeVal(L,4) for i in L : print(i, end='#')
You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.
Start your 14-day free trial to unlock the full solution →The code modifies a list by dividing elements by 5 if divisible, then by 3 if divisible, and finally prints the modified elements separated by '#'.
Let's break down this Python code to understand its operation and predict its output. The core of this program lies in how a list is passed to a function and subsequently modified based on specific conditions, followed by a printing loop.
First, we define a function ChangeVal that takes two arguments: M (expected to be a list) and N (expected to be an integer representing the number of elements to process). Inside this function, a for loop iterates N times. In each iteration, it checks two conditions for the current element M[i]:
- If
M[i]is perfectly divisible by 5 (i.e.,M[i]%5 == 0), it is integer-divided by 5 (M[i] //= 5). - After the first check (and potential modification), it then checks if the current value of
M[i]is perfectly divisible by 3 (i.e.,M[i]%3 == 0). If it is,M[i]is integer-divided by 3 (M[i] //= 3).
It's crucial to understand that Python lists are mutable objects. When L is passed to ChangeVal as M, M is not a copy; it's a reference to the original list L. This means any changes made to M inside the function directly affect L outside the function.
Now, let's trace the execution with the given list L = [25, 8, 75, 12] and the call ChangeVal(L, 4):
- Initial state:
L = [25, 8, 75, 12] - Call
ChangeVal(L, 4):- The loop starts for
iinrange(4), meaningiwill take values 0, 1, 2, 3. i = 0:M[0]is25.25 % 5 == 0is true.M[0]becomes25 // 5 = 5.5 % 3 == 0is false.- After this iteration,
Lis[5, 8, 75, 12].
i = 1:M[1]is8.8 % 5 == 0is false.8 % 3 == 0is false.- After this iteration,
Lremains[5, 8, 75, 12].
i = 2:M[2]is75.75 % 5 == 0is true.M[2]becomes75 // 5 = 15.- Now,
M[2]is15.15 % 3 == 0is true.M[2]becomes15 // 3 = 5. - After this iteration,
Lis[5, 8, 5, 12].
i = 3: …
- The loop starts for
Unlock everything free for 14 days
- Full step-by-step solutions
- Concept-first explanations
- Methods, shortcuts & mistakes
- PYQ mapping + timed mock tests
Full access for 14 days. No credit card required.