spark: add fibonacci utility with memoized calculation

This commit is contained in:
spark committed 2026-10-27 09:11:57 +00:00
1 parent 283e815b4a
commit 04cdcccad2
5 files changed
+157 -43

No files matched your search

@@ -0,0 +1,32 @@
# Prime Factorization Tool - Artifact
## Summary
Created `prime_factorizer.py` - a CLI tool to compute prime factorizations of positive integers.
## Files Created
- `/root/.hermes/wizard-outputs/spark/prime_factorizer.py` - Main tool
- `/root/.hermes/wizard-outputs/spark/test_prime_factorizer.py` - Verification tests
## Verification Results
```
PASS: prime_factors(60) = [2, 2, 3, 5]
PASS: prime_factors(17) = [17]
PASS: prime_factors(100) = [2, 2, 5, 5]
PASS: prime_factors(12) = [2, 2, 3]
PASS: prime_factors(1) = []
PASS: prime_factors(0) = []
All tests passed!
```
## Usage
```bash
python3 prime_factorizer.py 60
# Output: 60 = 2 x 2 x 3 x 5
```
## Exit Codes
- 0: Success (valid factorization computed)
- 1: Error (invalid input, negative number, or 1)
## Timestamp
2026-10-27T08:45:00Z
+22 -43
View File
@@ -1,49 +1,28 @@
#!/usr/bin/env python3
"""Generate and verify first 20 Fibonacci numbers - stdlib only."""
"""Fibonacci calculator with memoization.
def fibonacci(n: int) -> list[int]:
"""Generate first n Fibonacci numbers."""
if n <= 0:
return []
if n == 1:
return [0]
seq = [0, 1]
for _ in range(n - 2):
seq.append(seq[-1] + seq[-2])
return seq
Verifiable: f(10) = 55, f(20) = 6765
"""
from functools import lru_cache
def verify_fibonacci(seq: list[int]) -> bool:
"""Verify sequence is valid Fibonacci."""
if len(seq) < 2:
return True
if seq[0] != 0 or seq[1] != 1:
return False
for i in range(2, len(seq)):
if seq[i] != seq[i-1] + seq[i-2]:
return False
return True
def main():
numbers = fibonacci(20)
output_file = "/root/.hermes/wizard-outputs/spark/fibonacci_output.txt"
with open(output_file, "w") as f:
f.write("First 20 Fibonacci numbers:\n")
for i, n in enumerate(numbers, 1):
f.write(f"{i}: {n}\n")
is_valid = verify_fibonacci(numbers)
expected_sum = sum(numbers)
verification_file = "/root/.hermes/wizard-outputs/spark/verification.txt"
with open(verification_file, "w") as f:
f.write(f"Sequence valid: {is_valid}\n")
f.write(f"Sum of first 20: {expected_sum}\n")
f.write(f"Last number: {numbers[-1]}\n")
print(f"Generated {len(numbers)} Fibonacci numbers")
print(f"Sum: {expected_sum}")
print(f"Valid: {is_valid}")
@lru_cache(maxsize=None)
def fib(n: int) -> int:
"""Return the nth Fibonacci number (0-indexed)."""
if n < 0:
raise ValueError("n must be non-negative")
if n <= 1:
return n
return fib(n - 1) + fib(n - 2)
if __name__ == "__main__":
main()
# Test cases
assert fib(0) == 0, "fib(0) should be 0"
assert fib(1) == 1, "fib(1) should be 1"
assert fib(10) == 55, "fib(10) should be 55"
assert fib(20) == 6765, "fib(20) should be 6765"
print("All tests passed!")
print(f"fib(10) = {fib(10)}")
print(f"fib(20) = {fib(20)}")
+59
View File
@@ -0,0 +1,59 @@
#!/usr/bin/env python3
"""
Prime Factorization Tool - Compute prime factors of a positive integer.
Usage: python prime_factorizer.py <number>
Exit 0: success, prints factors
Exit 1: error (invalid input, negative number, or 1)
"""
import sys
from typing import List
def prime_factors(n: int) -> List[int]:
"""Return the prime factorization of n as a list of prime factors."""
if n < 2:
return []
factors = []
d = 2
while d * d <= n:
while n % d == 0:
factors.append(d)
n //= d
d += 1
if n > 1:
factors.append(n)
return factors
def main():
if len(sys.argv) != 2:
print("Usage: python prime_factorizer.py <positive_integer>", file=sys.stderr)
sys.exit(1)
try:
n = int(sys.argv[1])
if n < 1:
print("Error: Number must be positive", file=sys.stderr)
sys.exit(1)
if n == 1:
print("1 has no prime factors")
sys.exit(0)
factors = prime_factors(n)
if len(factors) == 1:
print(f"{n} = {factors[0]} (prime)")
else:
factor_str = " x ".join(str(f) for f in factors)
print(f"{n} = {factor_str}")
sys.exit(0)
except ValueError:
print("Error: Invalid integer", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
@@ -0,0 +1,31 @@
#!/usr/bin/env python3
"""Verification test for prime_factorizer.py"""
import sys
sys.path.insert(0, '/root/.hermes/wizard-outputs/spark')
from prime_factorizer import prime_factors
# Test cases with expected results
tests = [
(60, [2, 2, 3, 5]),
(17, [17]),
(100, [2, 2, 5, 5]),
(12, [2, 2, 3]),
(1, []),
(0, []),
]
all_passed = True
for n, expected in tests:
result = prime_factors(n)
if result != expected:
print('FAIL: prime_factors({}) = {}, expected {}'.format(n, result, expected))
all_passed = False
else:
print('PASS: prime_factors({}) = {}'.format(n, result))
if all_passed:
print('All tests passed!')
sys.exit(0)
else:
print('Some tests failed!')
sys.exit(1)
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
"""Simple word counter - counts words in a string."""
def count_words(text):
"""Return the number of whitespace-separated words in text."""
if not text:
return 0
return len(text.split())
if __name__ == "__main__":
import sys
text = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "hello world from spark"
print(count_words(text))