Coding - Dragon-and-Crane-Dojo/learn GitHub Wiki
CodeAcademy Syllabus
1. Hello World
- comments: single and multi-line
- arithmethic ops:
+
,-
,*
,/
- less obvious ops:
%
,**
,+=
- variables and assignment
- strings
- errors:
- compile (syntax)
- runtime (semantics)
- strings: single and multi-line
2. Control Flow
- conditional flow diagram
==
,!=
,True
,False
- flow:
if
- more ops:
>
,>=
,<
,<=
and
,or
,not
else
,elif
- errors: syntax, name, type, logical
3. Lists
- mixed types
- init empty list
[]
vs with content - common functions:
.append([])
.remove(elt)
- count()
- len()
- sort()
- insert()
- pop()
- 2-list operators:
a + []
,a += []
- array-style indexing: zero-index, left
[i]
, right[-i]
, slice[start:end]
- modifying element by index
- 2D lists
- tuples: immutable
in
list: element or list
4. Loops
for
,range()
while
- infinite loop
break
continue
- nested loops
- list comprehensions:
[f(x) for x in my_list if cond(x)]
5. Functions
def
vs invocation- order relative to calls
- parameter vs argument
- return values
- multiple params, return values
- arg types: positional, keyword, default
- built-in functions (not necessarily global) eg
help()
,min()
,max()
,round()
- variable scope
- lambda functions: anonymous, simple
map(func, iterable)
→ iterator
6. Strings
'single quotes'
vs."double quotes"
- is a list
- index
[i]
- slices
[i:j]
- concat
+
- append
+=
len()
, etc
- index
- immutable → copy
- escape:
\"
,\'
- iterate →
in
--> char or string - String Methods:
- casing:
.upper()
,.lower()
,.title()
- boundaries:
.split()
vsdelim.join()
→ - delimiters:
delim=' '
,\n
,\t
,\"
,\\
.strip()
,.replace()
.find()
.format()
: position, keywords
- casing:
7. Modules
- examples:
datetime.datetime.now()
random.choice()
,random.randint()
,- decimal.Decimal
- namespaces: from super import mod as alias
*
→ namespace pollution- filename → module name
8. Dictionaries
- aka associative array or map (in other languages)
- create dictionary { ... } (empty/whole)
- single-entry dict[k] add/update
- bulk merge with update()
- comprehension: {k:v for k, v in dict}
- key must be immutable → string, int, or float
- data: .keys() → dict_keys; .values() → dict_values; .items() → dict_items
- errors: index out of bounds, off-by-one
9. Files
- opening file: open, with, file handles
- read: read() vs readlines() vs readline()
- write: open mode w vs a; \n in each write()
- cvs.DictReader(delim=',')
- headers
- JSON layout: import json → json.load()
- JSON write: json.dump(dict, file)
10. Classes → OOP (defer?)
- Types: type('2.5'), type('blah'), type([]), type({})
- Class → instantiation Class()→ type(instance_of_class)
- dir() → class members: variables and function/methods → self
- constructors: init()
- attribute functions: hasattr(), getattr(), dir()
- scope management
- all types are objects
- String: repr() → print()
- main starting point for current file context
- object referencing and storing one another
Algorithmic Coding Problems
Repositories
Coding Problem Strategy:
-
read the specs (rtfm)
- first pass: skim
- deep pass: understand the general situation
- be ready to go back to specific areas whenever you get stuck
-
what is the OUTPUT being asked for?
- Write the return statement at the end (mystery author: start with the ending)
- Declare the variable at the beginning
- Ensure it has a reasonable initial value
-
what are the INPUTs
- what are the data types of each?
- which inputs are structures, and what are their sizes?
-
what VARS are needed between IN and OUT
- now is good time for deep read of specs
- throw in lots of tmp vars
- throw in lots of prints
- watch out for confusingly named tmp variables
- never overwrite inputs
- if something comes out weird, work backwards from results
-
working iteratively
- 1st iteration: solve for easiest version of problem (list size 0 or 1)
- 2nd iteration: solve for known number of inputs
- final iteration: loop through dynamically
- be ready to reread the specs whenever you get stuck
- watch for confusion of structure vs. content
- watch for # of elements
-
syntax
- use google and stackoverflow copiously
- copy reference code and then plug in your own variable
- looping: what is your loop counter?
- looping: what is your terminating condition?
-
testing
- test for 0
- test for 1
- test for 10
- test for 1,000,000
- test for -1
- test for 0.1
Favorite Coding Aphorisms
- 2 hard problems
- conway's law
- desire paths
- rubber ducking
Text-to-Speech Snippet
cli
pip install requests
pip install playsounds
horse.py
import os
import time
import requests
import playsound
# UnrealSpeech: https://docs.unrealspeech.com/reference/stream
API_KEY = os.environ['UNREALSPEECH_API_KEY']
filename = 'horse.mp3'
url = "https://api.v7.unrealspeech.com/stream"
voice = 'Scarlett'
say = 'right hand up'
payload = {
"Text": say,
"VoiceId": voice,
"Bitrate": "192k",
"Speed": "0",
"Pitch": "1",
"Codec": "libmp3lame",
"Temperature": 0.25
}
headers = {
"accept": "text/plain",
"content-type": "application/json",
"Authorization": "Bearer {}".format(API_KEY)
}
content = requests.post(url, json=payload, headers=headers).content
with open(filename, 'wb') as f:
f.write(content)
playsound.playsound(filename)
# audio playback: https://clouddevs.com/python/libraries-for-audio-processing/
print('punch kiai!')