Skip to content

Commit 42f2e68

Browse files
committed
Numbers big changes, Combinatorics, Console app, GUI, Web
1 parent 234cb56 commit 42f2e68

File tree

4 files changed

+123
-123
lines changed

4 files changed

+123
-123
lines changed

README.md

Lines changed: 57 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -494,64 +494,69 @@ Format
494494
Numbers
495495
-------
496496
```python
497-
<int> = int(<float/str/bool>) # Or: math.trunc(<float>)
498-
<float> = float(<int/str/bool>) # Or: <int/float>e±<int>
499-
<complex> = complex(real=0, imag=0) # Or: <int/float> ± <int/float>j
500-
<Fraction> = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1)
501-
<Decimal> = decimal.Decimal(<str/int>) # Or: Decimal((sign, digits, exponent))
497+
<int> = int(<float/str/bool>) # Or: math.trunc(<float>)
498+
<float> = float(<int/str/bool>) # Or: <int/float>e±<int>
499+
<complex> = complex(real=0, imag=0) # Or: <int/float> ± <int/float>j
500+
<Fraction> = fractions.Fraction(0, 1) # Or: Fraction(numerator=0, denominator=1)
501+
<Decimal> = decimal.Decimal(<str/int>) # Or: Decimal((sign, digits, exponent))
502502
```
503+
* **`'int(<str>)'` and `'float(<str>)'` raise ValueError on malformed strings.**
503504
* **Decimal numbers are stored exactly, unlike most floats where `'1.1 + 2.2 != 3.3'`.**
504505
* **Floats can be compared with: `'math.isclose(<float>, <float>)'`.**
505506
* **Precision of decimal operations is set with: `'decimal.getcontext().prec = <int>'`.**
506507
* **Bools can be used anywhere ints can, because bool is a subclass of int: `'True + 1 == 2'`.**
507508

508-
### Basic Functions
509+
### Built-in Functions
509510
```python
510-
<num> = pow(<num>, <num>) # Or: <number> ** <number>
511-
<num> = abs(<num>) # <float> = abs(<complex>)
512-
<num> = round(<num> [, ±ndigits]) # `round(126, -1) == 130`
511+
<num> = pow(<num>, <num>) # Or: <number> ** <number>
512+
<num> = abs(<num>) # <float> = abs(<complex>)
513+
<num> = round(<num> [, ±ndigits]) # Also math.floor/ceil(<number>).
514+
<num> = min(<collection>) # Also max(<num>, <num> [, ...]).
515+
<num> = sum(<collection>) # Also math.prod(<collection>).
513516
```
514517

515518
### Math
516519
```python
517-
from math import e, pi, inf, nan, isinf, isnan # `<el> == nan` is always False.
518-
from math import sin, cos, tan, asin, acos, atan # Also: degrees, radians.
519-
from math import log, log10, log2 # Log can accept base as second arg.
520+
from math import e, pi, inf, nan, isnan # `inf*0` and `nan+1` return nan.
521+
from math import sqrt, factorial # `sqrt(-1)` raises ValueError.
522+
from math import sin, cos, tan # Also: asin, degrees, radians.
523+
from math import log, log10, log2 # Log accepts base as second arg.
520524
```
521525

522526
### Statistics
523527
```python
524-
from statistics import mean, median, variance # Also: stdev, quantiles, groupby.
528+
from statistics import mean, median, mode # Mode returns the most common value.
529+
from statistics import variance, stdev # Also: pvariance, pstdev, quantiles.
525530
```
526531

527532
### Random
528533
```python
529-
from random import random, randint, uniform # Also: gauss, choice, shuffle, seed.
534+
from random import random, randint, uniform # Also: gauss, choice, shuffle, seed.
530535
```
531536

532537
```python
533-
<float> = random() # Returns a float inside [0, 1).
534-
<num> = randint/uniform(a, b) # Returns an int/float inside [a, b].
535-
<float> = gauss(mean, stdev) # Also triangular(low, high, mode).
536-
<el> = choice(<sequence>) # Keeps it intact. Also sample(pop, k).
537-
shuffle(<list>) # Shuffles the list in place.
538+
<float> = random() # Returns a float inside [0, 1).
539+
<num> = randint/uniform(a, b) # Returns an int/float inside [a, b].
540+
<float> = gauss(mean, stdev) # Also triangular(low, high, mode).
541+
<el> = choice(<sequence>) # Keeps it intact. Also sample(pop, k).
542+
shuffle(<list>) # Shuffles the list in place.
538543
```
539544

540545
### Hexadecimal Numbers
541546
```python
542-
<int> = ±0x<hex> # Or: ±0b<bin>
543-
<int> = int('±<hex>', 16) # Or: int('±<bin>', 2)
544-
<int> = int('±0x<hex>', 0) # Or: int('±0b<bin>', 0)
545-
<str> = hex(<int>) # Returns '[-]0x<hex>'. Also bin().
547+
<int> = ±0x<hex> # Or: ±0b<bin>
548+
<int> = int('±<hex>', 16) # Or: int('±<bin>', 2)
549+
<int> = int('±0x<hex>', 0) # Or: int('±0b<bin>', 0)
550+
<str> = hex(<int>) # Returns '[-]0x<hex>'. Also bin().
546551
```
547552

548553
### Bitwise Operators
549554
```python
550-
<int> = <int> & <int> # And (0b1100 & 0b1010 == 0b1000).
551-
<int> = <int> | <int> # Or (0b1100 | 0b1010 == 0b1110).
552-
<int> = <int> ^ <int> # Xor (0b1100 ^ 0b1010 == 0b0110).
553-
<int> = <int> << n_bits # Left shift. Use >> for right.
554-
<int> = ~<int> # Not. Also -<int> - 1.
555+
<int> = <int> & <int> # And (0b1100 & 0b1010 == 0b1000).
556+
<int> = <int> | <int> # Or (0b1100 | 0b1010 == 0b1110).
557+
<int> = <int> ^ <int> # Xor (0b1100 ^ 0b1010 == 0b0110).
558+
<int> = <int> << n_bits # Left shift. Use >> for right.
559+
<int> = ~<int> # Not. Also -<int> - 1.
555560
```
556561

557562

@@ -562,30 +567,24 @@ import itertools as it
562567
```
563568

564569
```python
565-
>>> list(it.product([0, 1], repeat=3))
566-
[(0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1),
567-
(1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1)]
570+
>>> list(it.product('abc', repeat=2)) # a b c
571+
[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x
572+
('b', 'a'), ('b', 'b'), ('b', 'c'), # b x x x
573+
('c', 'a'), ('c', 'b'), ('c', 'c')] # c x x x
568574
```
569575

570576
```python
571-
>>> list(it.product('abc', 'abc')) # a b c
572-
[('a', 'a'), ('a', 'b'), ('a', 'c'), # a x x x
573-
('b', 'a'), ('b', 'b'), ('b', 'c'), # b x x x
574-
('c', 'a'), ('c', 'b'), ('c', 'c')] # c x x x
577+
>>> list(it.permutations('abc', 2)) # a b c
578+
[('a', 'b'), ('a', 'c'), # a . x x
579+
('b', 'a'), ('b', 'c'), # b x . x
580+
('c', 'a'), ('c', 'b')] # c x x .
575581
```
576582

577583
```python
578-
>>> list(it.permutations('abc', 2)) # a b c
579-
[('a', 'b'), ('a', 'c'), # a . x x
580-
('b', 'a'), ('b', 'c'), # b x . x
581-
('c', 'a'), ('c', 'b')] # c x x .
582-
```
583-
584-
```python
585-
>>> list(it.combinations('abc', 2)) # a b c
586-
[('a', 'b'), ('a', 'c'), # a . x x
587-
('b', 'c'), # b . . x
588-
] # c . . .
584+
>>> list(it.combinations('abc', 2)) # a b c
585+
[('a', 'b'), ('a', 'c'), # a . x x
586+
('b', 'c'), # b . . x
587+
] # c . . .
589588
```
590589

591590

@@ -1183,7 +1182,7 @@ class Counter:
11831182

11841183
### Callable
11851184
* **All functions and classes have a call() method, hence are callable.**
1186-
* **Use `'callable(<obj>)'` or `'isinstance(<obj>, collections.abc.Callable)'` to check if object is callable.**
1185+
* **Use `'callable(<obj>)'` or `'isinstance(<obj>, collections.abc.Callable)'` to check if object is callable. Calling an uncallable object raises `'TypeError'`.**
11871186
* **When this cheatsheet uses `'<function>'` as an argument, it means `'<callable>'`.**
11881187
```python
11891188
class Counter:
@@ -2435,7 +2434,7 @@ Console App
24352434
```python
24362435
# $ pip3 install windows-curses
24372436
import curses, os
2438-
from curses import A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT, KEY_ENTER
2437+
from curses import A_REVERSE, KEY_UP, KEY_DOWN, KEY_LEFT, KEY_RIGHT
24392438

24402439
def main(screen):
24412440
ch, first, selected, paths = 0, 0, 0, os.listdir()
@@ -2450,7 +2449,7 @@ def main(screen):
24502449
selected += (ch == KEY_DOWN) and (selected < len(paths)-1)
24512450
first -= (first > selected)
24522451
first += (first < selected-(height-1))
2453-
if ch in [KEY_LEFT, KEY_RIGHT, KEY_ENTER, ord('\n'), ord('\r')]:
2452+
if ch in [KEY_LEFT, KEY_RIGHT, ord('\n')]:
24542453
new_dir = '..' if ch == KEY_LEFT else paths[selected]
24552454
if os.path.isdir(new_dir):
24562455
os.chdir(new_dir)
@@ -2469,9 +2468,9 @@ GUI App
24692468
# $ pip3 install PySimpleGUI
24702469
import PySimpleGUI as sg
24712470

2472-
text_box = sg.Input(default_text='100', enable_events=True, key='-QUANTITY-')
2473-
dropdown = sg.InputCombo(['g', 'kg', 't'], 'kg', readonly=True, enable_events=True, k='-UNIT-')
2474-
label = sg.Text('100 kg is 220.462 lbs.', key='-OUTPUT-')
2471+
text_box = sg.Input(default_text='100', enable_events=True, key='QUANTITY')
2472+
dropdown = sg.InputCombo(['g', 'kg', 't'], 'kg', readonly=True, enable_events=True, k='UNIT')
2473+
label = sg.Text('100 kg is 220.462 lbs.', key='OUTPUT')
24752474
button = sg.Button('Close')
24762475
window = sg.Window('Weight Converter', [[text_box, dropdown], [label], [button]])
24772476

@@ -2480,13 +2479,13 @@ while True:
24802479
if event in [sg.WIN_CLOSED, 'Close']:
24812480
break
24822481
try:
2483-
quantity = float(values['-QUANTITY-'])
2482+
quantity = float(values['QUANTITY'])
24842483
except ValueError:
24852484
continue
2486-
unit = values['-UNIT-']
2485+
unit = values['UNIT']
24872486
factors = {'g': 0.001, 'kg': 1, 't': 1000}
24882487
lbs = quantity * factors[unit] / 0.45359237
2489-
window['-OUTPUT-'].update(value=f'{quantity} {unit} is {lbs:g} lbs.')
2488+
window['OUTPUT'].update(value=f'{quantity} {unit} is {lbs:g} lbs.')
24902489
window.close()
24912490
```
24922491

@@ -2552,14 +2551,14 @@ app.run(host=None, port=None, debug=None) # Or: $ flask --app FILE run [--ARG[=
25522551
* **Install a WSGI server like [Waitress](https://flask.palletsprojects.com/en/latest/deploying/waitress/) and a HTTP server such as [Nginx](https://flask.palletsprojects.com/en/latest/deploying/nginx/) for better security.**
25532552
* **Debug mode restarts the app whenever script changes and displays errors in the browser.**
25542553

2555-
### Static Request
2554+
### Serving Files
25562555
```python
25572556
@app.route('/img/<path:filename>')
25582557
def serve_file(filename):
25592558
return fl.send_from_directory('DIRNAME', filename)
25602559
```
25612560

2562-
### Dynamic Request
2561+
### Serving HTML
25632562
```python
25642563
@app.route('/<sport>')
25652564
def serve_html(sport):
@@ -2570,7 +2569,7 @@ def serve_html(sport):
25702569
* **`'fl.request.args[<str>]'` returns parameter from query string (URL part right of '?').**
25712570
* **`'fl.session[<str>] = <obj>'` stores session data. It requires secret key to be set at the startup with `'app.secret_key = <str>'`.**
25722571

2573-
### REST Request
2572+
### Serving JSON
25742573
```python
25752574
@app.post('/<sport>/odds')
25762575
def serve_json(sport):

0 commit comments

Comments
 (0)