Coding - Dragon-and-Crane-Dojo/learn GitHub Wiki

CodeAcademy Syllabus

1. Hello World

  1. print
  2. comments: single and multi-line
  3. arithmethic ops: +, -, *, /
  4. less obvious ops: %, **, +=
  5. variables and assignment
  6. strings
  7. errors:
    1. compile (syntax)
    2. runtime (semantics)
  8. strings: single and multi-line

2. Control Flow

  1. conditional flow diagram
  2. ==, !=, True, False
  3. flow: if
  4. more ops: >, >=, <, <=
  5. and, or, not
  6. else, elif
  7. errors: syntax, name, type, logical

3. Lists

  1. mixed types
  2. init empty list [] vs with content
  3. common functions:
    1. .append([])
    2. .remove(elt)
    3. count()
    4. len()
    5. sort()
    6. insert()
    7. pop()
  4. 2-list operators: a + [], a += []
  5. array-style indexing: zero-index, left [i], right [-i], slice [start:end]
  6. modifying element by index
  7. 2D lists
  8. tuples: immutable
  9. in list: element or list

4. Loops

  1. for, range()
  2. while
  3. infinite loop
  4. break
  5. continue
  6. nested loops
  7. list comprehensions: [f(x) for x in my_list if cond(x)]

5. Functions

  1. def vs invocation
  2. order relative to calls
  3. parameter vs argument
  4. return values
  5. multiple params, return values
  6. arg types: positional, keyword, default
  7. built-in functions (not necessarily global) eg help(), min(), max(), round()
  8. variable scope
  9. lambda functions: anonymous, simple
  10. map(func, iterable) → iterator

6. Strings

  1. 'single quotes' vs. "double quotes"
  2. is a list
    1. index [i]
    2. slices [i:j]
    3. concat +
    4. append +=
    5. len(), etc
  3. immutable → copy
  4. escape: \", \'
  5. iterate → in --> char or string
  6. String Methods:
    1. casing: .upper(), .lower(), .title()
    2. boundaries: .split() vs delim.join()
    3. delimiters: delim=' ', \n, \t, \", \\
    4. .strip(), .replace()
    5. .find()
    6. .format(): position, keywords

7. Modules

  1. examples:
    1. datetime.datetime.now()
    2. random.choice(), random.randint(),
    3. decimal.Decimal
  2. namespaces: from super import mod as alias
  3. * → namespace pollution
  4. filename → module name

8. Dictionaries

  1. aka associative array or map (in other languages)
  2. create dictionary { ... } (empty/whole)
  3. single-entry dict[k] add/update
  4. bulk merge with update()
  5. comprehension: {k:v for k, v in dict}
  6. key must be immutable → string, int, or float
  7. data: .keys() → dict_keys; .values() → dict_values; .items() → dict_items
  8. errors: index out of bounds, off-by-one

9. Files

  1. opening file: open, with, file handles
  2. read: read() vs readlines() vs readline()
  3. write: open mode w vs a; \n in each write()
  4. cvs.DictReader(delim=',')
  5. headers
  6. JSON layout: import json → json.load()
  7. JSON write: json.dump(dict, file)

10. Classes → OOP (defer?)

  1. Types: type('2.5'), type('blah'), type([]), type({})
  2. Class → instantiation Class()→ type(instance_of_class)
  3. dir() → class members: variables and function/methods → self
  4. constructors: init()
  5. attribute functions: hasattr(), getattr(), dir()
  6. scope management
  7. all types are objects
  8. String: repr() → print()
  9. main starting point for current file context
  10. object referencing and storing one another

Algorithmic Coding Problems

Repositories

Coding Problem Strategy:

  1. read the specs (rtfm)

    1. first pass: skim
    2. deep pass: understand the general situation
    3. be ready to go back to specific areas whenever you get stuck
  2. what is the OUTPUT being asked for?

    1. Write the return statement at the end (mystery author: start with the ending)
    2. Declare the variable at the beginning
    3. Ensure it has a reasonable initial value
  3. what are the INPUTs

    1. what are the data types of each?
    2. which inputs are structures, and what are their sizes?
  4. what VARS are needed between IN and OUT

    1. now is good time for deep read of specs
    2. throw in lots of tmp vars
    3. throw in lots of prints
    4. watch out for confusingly named tmp variables
    5. never overwrite inputs
    6. if something comes out weird, work backwards from results
  5. working iteratively

    1. 1st iteration: solve for easiest version of problem (list size 0 or 1)
    2. 2nd iteration: solve for known number of inputs
    3. final iteration: loop through dynamically
      1. be ready to reread the specs whenever you get stuck
      2. watch for confusion of structure vs. content
      3. watch for # of elements
  6. syntax

    1. use google and stackoverflow copiously
    2. copy reference code and then plug in your own variable
    3. looping: what is your loop counter?
    4. looping: what is your terminating condition?
  7. testing

    1. test for 0
    2. test for 1
    3. test for 10
    4. test for 1,000,000
    5. test for -1
    6. 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!')