Computer Science
What will be the output of the following code ?
def process_data(lst, dct):
result = []
for i in lst:
if i in dct:
result.append(dct[i] * i)
else:
result.append(i ** 2)
return result
lst = [1, 2, 3, 4]
dct = {2: 5, 3: 10}
print(process_data(lst, dct))
Python Functions
3 Likes
Answer
[1, 10, 30, 16]
Reason — In the function process_data(lst, dct), the code iterates through each element in the list lst. For each element i, it checks if i is present as a key in the dictionary dct. If i is found in the dictionary, it appends the value dct[i] * i to the result list. If i is not found in the dictionary, it appends i ** 2 (i squared) to the result list.
- For
i = 1, 1 is not in the dictionary, so 1 ** 2 = 1 is added. - For
i = 2, 2 is in the dictionary, and dct[2] = 5, so 5 * 2 = 10 is added. - For
i = 3, 3 is in the dictionary, and dct[3] = 10, so 10 * 3 = 30 is added. - For
i = 4, 4 is not in the dictionary, so 4 ** 2 = 16 is added.
Thus, the final result is [1, 10, 30, 16].
Answered By
3 Likes
Related Questions
The code provided below is intended to swap the first and last elements of a given tuple. However, there are syntax and logical errors in the code. Rewrite it after removing all errors. Underline all the corrections made.
def swap_first_last(tup) if len(tup) < 2: return tup new_tup = (tup[-1],) + tup[1:-1] + (tup[0]) return new_tup result = swap_first_last((1, 2, 3, 4)) print("Swapped tuple: " result)Assertion (A): Positional arguments in Python functions must be passed in the exact order in which they are defined in the function signature.
Reasoning (R): This is because Python functions automatically assign default values to positional arguments.
- Both A and R are true, and R is the correct explanation of A.
- Both A and R are true, and R is not the correct explanation of A.
- A is true but R is false.
- A is false but R is true.