Last active
December 11, 2023 09:13
-
-
Save luqmansen/d8c42cc3dae85b3f1dcb16d91df3a8bd to your computer and use it in GitHub Desktop.
mission_1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def collect_cases(stack, test_case_num): | |
if test_case_num <= 0: | |
return | |
num_of_inputs = input() | |
actual_input = input() | |
stack.append((num_of_inputs, actual_input)) | |
collect_cases(stack, test_case_num - 1) | |
def expand_and_calculate(stack): | |
if len(stack) == 0: | |
return | |
num_of_inputs, nums = stack.pop(0) | |
# only consider N-first `num_of_inputs` and discard the | |
# rest if the length of the input is more than needed | |
nums = nums.split(' ')[:int(num_of_inputs)] | |
def calc_nums(objs: list, total: int): | |
if len(objs) <= 0: | |
# no more numbers to be exhausted | |
# print the result right now | |
print(total) | |
return | |
n = int(objs.pop(0)) | |
if n < 0: | |
calc_nums(objs, total) | |
return | |
total += n * n | |
calc_nums(objs, total) | |
calc_nums(nums, 0) | |
expand_and_calculate(stack) | |
def main(): | |
""" | |
Algorithm: | |
1. Collect the pair of input count and line-separated-numbers as a tuple | |
2. Put the tuple into a stack | |
3. Expand and calculate each of them using a recursive function | |
example: | |
Input: | |
2 | |
4 | |
3 -1 1 14 | |
5 | |
9 6 -53 32 16 | |
Collected stack | |
[ (4, '3 -1 1 14'), (5, '9 6 -53 32 16') ] | |
And exhaust the numbers while summing them on a recursive function | |
""" | |
num_of_test = input() | |
stack = [] | |
collect_cases(stack, int(num_of_test)) | |
expand_and_calculate(stack) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment