Skip to content

Commit 87b2009

Browse files
Manual review of builtin functions: next-locals
1 parent 36ff3a3 commit 87b2009

2 files changed

Lines changed: 0 additions & 342 deletions

File tree

docs/builtins/input.md

Lines changed: 0 additions & 193 deletions
Original file line numberDiff line numberDiff line change
@@ -96,192 +96,6 @@ while True:
9696
# Total: O(n*k) where n = number of lines
9797
```
9898

99-
## Common Patterns
100-
101-
### Menu Selection
102-
103-
```python
104-
# Simple menu - O(k)
105-
def show_menu():
106-
print("1. Option A")
107-
print("2. Option B")
108-
print("3. Exit")
109-
choice = input("Choose: ") # O(k)
110-
return choice
111-
112-
# Usage
113-
choice = show_menu() # O(k)
114-
if choice == "1":
115-
do_a()
116-
elif choice == "2":
117-
do_b()
118-
```
119-
120-
### Validation Loop
121-
122-
```python
123-
# Repeat until valid input - O(n*k)
124-
def get_positive_number():
125-
while True:
126-
try:
127-
num_str = input("Enter positive number: ") # O(k)
128-
num = int(num_str) # O(k)
129-
if num > 0:
130-
return num
131-
print("Must be positive")
132-
except ValueError:
133-
print("Invalid number")
134-
135-
# Usage - might need multiple attempts
136-
value = get_positive_number() # O(k) per attempt
137-
```
138-
139-
### Yes/No Question
140-
141-
```python
142-
# Simple yes/no - O(k)
143-
def confirm(message):
144-
while True:
145-
response = input(f"{message} (yes/no): ").lower() # O(k)
146-
if response in ['yes', 'y']:
147-
return True
148-
elif response in ['no', 'n']:
149-
return False
150-
print("Please answer yes or no")
151-
152-
# Usage
153-
if confirm("Delete file?"): # O(k)
154-
delete_file()
155-
```
156-
157-
## Error Handling
158-
159-
### Handling Input Errors
160-
161-
```python
162-
# Catch conversion errors - O(k)
163-
try:
164-
age = int(input("Age: ")) # O(k)
165-
except ValueError:
166-
print("Invalid age")
167-
age = 0
168-
169-
# Catch EOF (Ctrl+D on Unix, Ctrl+Z on Windows)
170-
try:
171-
name = input("Name: ") # O(k)
172-
except EOFError:
173-
print("Input cancelled")
174-
name = ""
175-
176-
# Catch keyboard interrupt (Ctrl+C)
177-
try:
178-
data = input("Data: ") # O(k)
179-
except KeyboardInterrupt:
180-
print("\nCancelled")
181-
data = ""
182-
```
183-
184-
## Advanced Patterns
185-
186-
### Interactive Session
187-
188-
```python
189-
# Multi-step input session - O(n*k)
190-
def interactive_form():
191-
print("Fill in the form:")
192-
193-
data = {}
194-
fields = ['name', 'email', 'phone']
195-
196-
for field in fields: # O(n) iterations
197-
value = input(f"Enter {field}: ") # O(k) per field
198-
data[field] = value
199-
200-
return data
201-
202-
# Usage - O(n*k)
203-
user_data = interactive_form()
204-
```
205-
206-
### Parsing Structured Input
207-
208-
```python
209-
# Parse CSV-like input - O(n*m)
210-
print("Enter records (name,age,city):")
211-
records = []
212-
213-
while True:
214-
line = input("Record (empty to stop): ") # O(k)
215-
if not line:
216-
break
217-
218-
# Parse - O(k)
219-
fields = line.split(',') # O(k)
220-
record = {
221-
'name': fields[0].strip(), # O(k)
222-
'age': fields[1].strip(),
223-
'city': fields[2].strip()
224-
}
225-
records.append(record) # O(1)
226-
227-
# Total: O(n*m) where n = records, m = avg fields
228-
```
229-
230-
## Input from Files (Not input())
231-
232-
```python
233-
# input() reads from keyboard only
234-
# For file input, use open()
235-
236-
# Read from file - O(k) per line
237-
with open('data.txt', 'r') as f:
238-
for line in f: # O(1) each iteration
239-
# line includes newline, unlike input()
240-
line = line.strip() # O(k) to remove it
241-
process(line)
242-
243-
# Read all at once - O(n)
244-
with open('data.txt', 'r') as f:
245-
all_lines = f.readlines() # O(n)
246-
```
247-
248-
## Input in Scripts vs Interactive
249-
250-
### Interactive Mode
251-
252-
```python
253-
# Works in interactive Python
254-
name = input("Name: ") # O(k) - waits for user
255-
print(f"Hello, {name}")
256-
```
257-
258-
### Script Mode
259-
260-
```python
261-
# Script with input() - O(k)
262-
#!/usr/bin/env python3
263-
264-
name = input("What is your name? ") # O(k)
265-
age = int(input("What is your age? ")) # O(k)
266-
print(f"Hello {name}, you are {age} years old")
267-
```
268-
269-
### Testing Scripts with input()
270-
271-
```python
272-
# For testing, redirect stdin or mock input()
273-
import sys
274-
from io import StringIO
275-
276-
# Simulate user input
277-
sys.stdin = StringIO("Alice\n30\n")
278-
279-
name = input() # O(k) - reads "Alice"
280-
age = int(input()) # O(k) - reads "30"
281-
282-
print(f"{name} is {age}")
283-
```
284-
28599
## Performance Considerations
286100

287101
### Input Speed
@@ -335,15 +149,8 @@ values = input("Enter all values: ").split() # O(k)
335149
**Do**:
336150

337151
- Use `input()` for interactive programs
338-
- Validate and convert input with error handling
339-
- Use `strip()` to remove whitespace
340-
- Provide clear prompts
341152
- Use file input for large data sets
342153

343154
**Avoid**:
344155

345-
- Using `input()` in production servers (won't work)
346-
- Forgetting input returns a string (requires conversion)
347-
- Assuming input is safe (validate it!)
348156
- Using `input()` for performance-critical code
349-
- Trusting user input without validation

docs/builtins/next.md

Lines changed: 0 additions & 149 deletions
Original file line numberDiff line numberDiff line change
@@ -101,155 +101,6 @@ except StopIteration:
101101
print("Done")
102102
```
103103

104-
## Common Patterns
105-
106-
### Pairwise Iteration
107-
108-
```python
109-
# Iterate elements in pairs
110-
def pairwise(iterable):
111-
"""Yield consecutive pairs"""
112-
it = iter(iterable)
113-
a = next(it, None) # O(1)
114-
115-
for b in it: # O(1) each
116-
yield (a, b)
117-
a = b
118-
119-
# Usage
120-
items = [1, 2, 3, 4, 5]
121-
for pair in pairwise(items): # O(n) total
122-
print(pair)
123-
# Output: (1,2), (2,3), (3,4), (4,5)
124-
```
125-
126-
### Skip Items
127-
128-
```python
129-
# Skip first n items
130-
def skip_n(iterable, n):
131-
it = iter(iterable)
132-
133-
# Skip n items - O(n)
134-
for _ in range(n):
135-
next(it, None) # O(1) each
136-
137-
# Return rest
138-
return it
139-
140-
# Usage
141-
it = skip_n(range(10), 3)
142-
for item in it: # O(1) each
143-
print(item) # 3, 4, 5, ..., 9
144-
```
145-
146-
### Take First N
147-
148-
```python
149-
# Take first n items - O(n)
150-
def take(iterable, n):
151-
it = iter(iterable)
152-
for _ in range(n):
153-
yield next(it) # O(1) each
154-
155-
# Usage
156-
items = range(100)
157-
first_five = take(items, 5) # O(5)
158-
```
159-
160-
## Error Handling
161-
162-
### Safe next() with Default
163-
164-
```python
165-
# Avoid exceptions with default - O(1)
166-
it = iter([1, 2, 3])
167-
168-
while True:
169-
value = next(it, None) # O(1)
170-
if value is None:
171-
break
172-
print(value)
173-
```
174-
175-
### Checking for Exhaustion
176-
177-
```python
178-
# Sentinel pattern
179-
it = iter([1, 2, 3])
180-
sentinel = object() # Unique marker
181-
182-
while True:
183-
value = next(it, sentinel) # O(1)
184-
if value is sentinel:
185-
break
186-
process(value)
187-
```
188-
189-
## Advanced Iterator Patterns
190-
191-
### Iterator with State
192-
193-
```python
194-
# Iterator that maintains state
195-
class CountUp:
196-
def __init__(self, max):
197-
self.max = max
198-
self.current = 0
199-
200-
def __iter__(self):
201-
return self
202-
203-
def __next__(self):
204-
if self.current < self.max:
205-
val = self.current
206-
self.current += 1
207-
return val # O(1)
208-
raise StopIteration
209-
210-
# Usage
211-
counter = CountUp(3)
212-
val1 = next(counter) # 0 - O(1)
213-
val2 = next(counter) # 1 - O(1)
214-
```
215-
216-
### Chained Iterators
217-
218-
```python
219-
# Chain multiple iterators - O(1) per next()
220-
from itertools import chain
221-
222-
it1 = iter([1, 2, 3])
223-
it2 = iter([4, 5, 6])
224-
combined = chain(it1, it2) # O(1) to create
225-
226-
# Iterate through both - O(1) each
227-
for item in combined: # O(6) total
228-
print(item)
229-
```
230-
231-
## Comparison with For Loop
232-
233-
```python
234-
# For loop uses next() internally
235-
items = [1, 2, 3]
236-
237-
# Manual with next() - O(n)
238-
it = iter(items)
239-
while True:
240-
try:
241-
item = next(it) # O(1)
242-
print(item)
243-
except StopIteration:
244-
break
245-
246-
# For loop (equivalent) - O(n)
247-
for item in items: # O(1) each
248-
print(item)
249-
250-
# For loop is cleaner; use next() for special cases
251-
```
252-
253104
## Performance Considerations
254105

255106
### next() vs Indexing

0 commit comments

Comments
 (0)