grade.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. import csv
  2. import os
  3. from collections import OrderedDict
  4. from decimal import Decimal, InvalidOperation
  5. INPUT = "/tests/input.csv"
  6. SUMMARY = "/app/summary.csv"
  7. FILTERED = "/app/over_500.csv"
  8. SUMMARY_HEADER = ["姓名", "报销总额"]
  9. DETAIL_HEADER = ["日期", "姓名", "类别", "金额"]
  10. def read_csv(path):
  11. with open(path, encoding="utf-8-sig", newline="") as stream:
  12. return list(csv.reader(stream))
  13. def fail(message):
  14. os.makedirs("/logs/verifier", exist_ok=True)
  15. with open("/logs/verifier/reward.txt", "w", encoding="utf-8") as reward:
  16. reward.write("0\n")
  17. print(message)
  18. raise SystemExit(0)
  19. def main():
  20. try:
  21. source = read_csv(INPUT)
  22. summary = read_csv(SUMMARY)
  23. filtered = read_csv(FILTERED)
  24. except (OSError, csv.Error):
  25. fail("Required CSV output is missing or unreadable.")
  26. if not source or source[0] != DETAIL_HEADER:
  27. fail("Verifier input is invalid.")
  28. if summary[:1] != [SUMMARY_HEADER]:
  29. fail("Summary CSV header is incorrect.")
  30. if filtered[:1] != [DETAIL_HEADER]:
  31. fail("Filtered CSV header is incorrect.")
  32. totals = OrderedDict()
  33. expected_filtered = []
  34. try:
  35. for row in source[1:]:
  36. if len(row) != 4:
  37. fail("Verifier input is invalid.")
  38. date, name, category, raw_amount = row
  39. amount = Decimal(raw_amount)
  40. totals[name] = totals.get(name, Decimal("0")) + amount
  41. if amount > Decimal("500"):
  42. expected_filtered.append(row)
  43. except InvalidOperation:
  44. fail("Verifier input is invalid.")
  45. expected_summary = [SUMMARY_HEADER]
  46. expected_summary.extend([[name, f"{total:.2f}"] for name, total in totals.items()])
  47. if summary != expected_summary:
  48. fail("Summary CSV does not match the required per-person totals.")
  49. if filtered != [DETAIL_HEADER, *expected_filtered]:
  50. fail("Filtered CSV does not match the required records.")
  51. os.makedirs("/logs/verifier", exist_ok=True)
  52. with open("/logs/verifier/reward.txt", "w", encoding="utf-8") as reward:
  53. reward.write("1\n")
  54. print("Outputs meet the task requirements.")
  55. if __name__ == "__main__":
  56. main()