Skip to content

Instantly share code, notes, and snippets.

@shivarawart
Last active May 25, 2025 09:30
Show Gist options
  • Select an option

  • Save shivarawart/28b078bf13c18486ce1ecabe01b3da19 to your computer and use it in GitHub Desktop.

Select an option

Save shivarawart/28b078bf13c18486ce1ecabe01b3da19 to your computer and use it in GitHub Desktop.
Mission 3 Solution: Sum of Fourth Powers of Negative Numbers Description: This program processes multiple test cases to calculate the sum of fourth powers of negative numbers from each test case. Input Format: - First line: N (number of test cases) - For each test case: - First line: X (number of elements) - Second line: Space-separated numbers …
def main():
import sys
def get_input():
"""Get input either from stdin or allow manual input"""
if sys.stdin.isatty(): # If running interactively
try:
n = int(input("Enter number of test cases: "))
if n <= 0:
print("Number of test cases must be positive")
return None
lines = [str(n)]
print(f"Enter {n} test cases:")
for i in range(n):
print(f"\nTest case #{i + 1}:")
x = int(input("Enter number of elements: "))
if x <= 0:
print("Number of elements must be positive")
return None
lines.append(str(x))
numbers = input("Enter space-separated numbers: ")
lines.append(numbers)
return lines
except ValueError as e:
print(f"Invalid input: {e}")
return None
else: # If input is being piped or redirected
return sys.stdin.read().splitlines()
def process_case(index, remaining_cases, lines):
"""Process a single test case and return the result"""
if remaining_cases == 0:
return ""
if index + 1 >= len(lines):
return "-1"
try:
x = int(lines[index])
if x <= 0:
return "-1\n" + process_case(index + 2, remaining_cases - 1, lines)
y_values = lines[index + 1].strip().split()
if len(y_values) != x:
return "-1\n" + process_case(index + 2, remaining_cases - 1, lines)
# Calculate sum of fourth powers of negative numbers
result = 0
for val_str in y_values:
try:
val = int(val_str)
if val < 0: # Only process negative numbers
result += val ** 4
except ValueError:
return "-1\n" + process_case(index + 2, remaining_cases - 1, lines)
return str(result) + "\n" + process_case(index + 2, remaining_cases - 1, lines)
except ValueError:
return "-1\n" + process_case(index + 2, remaining_cases - 1, lines)
try:
lines = get_input()
if not lines:
print("No input provided")
return
total_cases = int(lines[0])
if total_cases <= 0:
print("Number of test cases must be positive")
return
output = process_case(1, total_cases, lines).rstrip("\n")
print("\nResults:")
print(output)
except Exception as e:
print(f"Error: {str(e)}")
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment