def collatz(n):
"""Return the next number in Collatz conjucture"""
if n % 2 == 0:
return n / 2
return n * 3 + 1
collatz(7) # 22
; Return the next number in Collatz conjecture
(define collatz
(lambda (n)
(if (= (% n 2) 0)
(/ n 2)
(+ (* n 3) 1))))
(collatz 7) ; 22
π = 3.14159265358
def circle_area(r):
return π * r * r
from io import BytesIO
from tokenize import tokenize
from token import tok_name
def print_tokens(code):
for tok in tokenize(BytesIO(code).readline):
name = tok_name[tok.exact_type]
print(f'{tok.string:<10s} {name}')
In [2]: code = b'x = collatz(n)'
In [3]: print_tokens(code)
utf-8 ENCODING
x NAME
= EQUAL
collatz NAME
( LPAR
n NAME
) RPAR
NEWLINE
ENDMARKER
import ast
def print_tree(node, depth=0):
print(' ' * 4 * depth, end='')
print(node.__class__.__name__)
for child in ast.iter_child_nodes(node):
print_tree(child, depth+1)
code = '''
if x > 10:
y /= 7
'''
In [9]: print_tree(ast.parse(code))
Module
If
Compare
Name
Load
Gt
Num
AugAssign
Name
Store
Div
Num
(+ (* n 3) 1)
In [4]: eval('32 / 7')
Out[4]: 4.571428571428571
(define make-adder
(lambda (n)
(lambda (m) (+ m n))))
» (define add-7 (make-adder 7))
(add-7 10) ; 17
|
[ builtin ] |
|
[ builtin ] [ n = 7 ] |
|
[ builtin ] [ n = 7 ] [ m = 10 ] |
0x10
0o10
0b10
TAB completion#t, #f)(define login
(lambda (user password)
(let ((given (hash-password password))
(stored (load-user-password user)))
(= given stored))))
(import greetings)
(.greet greetings "foo") ; prints "hello, foo"
(defmacro aif (test-form then-form &optional else-form)
‘(let ((it ,test-form))
(if it ,then-form ,else-form)))
(aif (query-from-database)
(process-results it))
if it := read_from_database():
process_results(it)
In [1]: def relu(n):
...: if n < 0.0:
...: return 0.0
...: return n
...:
In [2]: from dis import dis
In [3]: dis(relu)
2 0 LOAD_FAST 0 (n)
2 LOAD_CONST 1 (0.0)
4 COMPARE_OP 0 (<)
6 POP_JUMP_IF_FALSE 12
3 8 LOAD_CONST 1 (0.0)
10 RETURN_VALUE
4 >> 12 LOAD_FAST 0 (n)
14 RETURN_VALUE