fibonacci
spyglass_workshop.fibonacci
¶
Fibonacci numbers.
user_input()
¶
Prompt the user for a Fibonacci index and return a formatted result.
Reads one line from standard input, converts it to an integer, and returns a human-readable string showing both the n\ th Fibonacci number and the full sequence up to that index.
Returns:
| Type | Description |
|---|---|
str
|
Message of the form:
|
Raises:
| Type | Description |
|---|---|
ValueError
|
If the input string cannot be parsed as an integer. |
Exception
|
Any other exception raised by :func: |
Notes
Intended for interactive use from a terminal. For programmatic
access call :func:f and :func:f_list directly.
Source code in src/spyglass_workshop/fibonacci.py
5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 | |
f(n)
¶
Return the nth Fibonacci number.
Uses an iterative two-variable swap — constant memory, no recursion.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Non-negative position in the Fibonacci sequence. |
required |
Returns:
| Type | Description |
|---|---|
int
|
The n\ th Fibonacci number F(n). |
Raises:
| Type | Description |
|---|---|
TypeError
|
If n is not an integer (the |
Notes
The sequence follows the standard mathematical definition::
F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2)
Negative n is silently treated as 0 because range(n) is
empty for n < 1.
Examples:
>>> [f(i) for i in range(8)]
[0, 1, 1, 2, 3, 5, 8, 13]
Source code in src/spyglass_workshop/fibonacci.py
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 | |
f_list(n)
¶
Return a list of the first n Fibonacci numbers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of terms to return. |
required |
Returns:
| Type | Description |
|---|---|
list[int]
|
|
Raises:
| Type | Description |
|---|---|
TypeError
|
If n is not an integer. |
Notes
The returned list starts at F(1) = 1, not F(0) = 0, matching
the common convention for enumerating the Fibonacci sequence. For
index-based access use :func:f.
Examples:
>>> f_list(5)
[1, 1, 2, 3, 5]
>>> f_list(0)
[]
Source code in src/spyglass_workshop/fibonacci.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 | |