📅  最后修改于: 2023-12-03 15:26:05.439000             🧑  作者: Mango
The UGC-NET CS 2017 exam is a national level eligibility test for the position of Assistant Professor or Junior Research Fellowship in India. The exam consists of multiple-choice questions covering various topics in Computer Science. Question 15 of the exam requires knowledge of programming and algorithm design.
Write a function in Python that takes a list of integers as input and returns a new list where each element is the sum of itself and all previous elements in the input list. For example, if the input list is [1, 2, 3, 4], the output should be [1, 3, 6, 10].
def cumulative_sum(input_list):
output_list = []
running_sum = 0
for num in input_list:
running_sum += num
output_list.append(running_sum)
return output_list
The above function cumulative_sum
takes a list of integers input_list
as input, initializes an empty list output_list
and a variable running_sum
to 0. It then iterates through each element num
in input_list
, adds num
to running_sum
, and appends running_sum
to output_list
. Finally, the function returns output_list
.
input_list = [1, 2, 3, 4]
output_list = cumulative_sum(input_list)
print(output_list) # prints [1, 3, 6, 10]
The input list is [1, 2, 3, 4]
. The function cumulative_sum
initializes an empty list output_list
and a variable running_sum
to 0. It then iterates through each element num
in the input list:
num
is 1. running_sum
is updated to 1. [1]
is appended to output_list
.num
is 2. running_sum
is updated to 3. [1, 3]
is appended to output_list
.num
is 3. running_sum
is updated to 6. [1, 3, 6]
is appended to output_list
.num
is 4. running_sum
is updated to 10. [1, 3, 6, 10]
is appended to output_list
.The function returns [1, 3, 6, 10]
, which is printed to the console.