Skip to content

Instantly share code, notes, and snippets.

@Renddslow
Last active April 17, 2020 18:40
Show Gist options
  • Save Renddslow/6b4d701fd3d94fb98e467e6c02c76186 to your computer and use it in GitHub Desktop.
Save Renddslow/6b4d701fd3d94fb98e467e6c02c76186 to your computer and use it in GitHub Desktop.
TCA Code Handouts

Glossary

Methods/Functions

In Python, there are some functions that are connected to different types (int, str, dict) and there are some that are built-in and can be called without importing anything (len, print, input). Below is a list of methods connected to types and general functions.

Note: For methods connected to types, they can only be called on the type itself. For instance, I can't call:

upper("hello world")

Instead I need to do:

message = "hello world"
message.upper()

Built-Ins

Function Name Arguments What it Does Example
isinstance (value, type) Given a value (this could be a variable or "hello world" for instance), return whether or not it matches the type provided instanceof("hello world", str)
int (value) Given a string value whose whole value is an integer, convert the type from string to integer int("33")
str (value) Given an integer (or other type), convert the type from original to string str(33)
range (end) or (start, end) Return a special range object that can be turned into a list to be looped over

Strings

Method Name Arguments What it Does Example
upper Returns a string with all the letters upper-cased name.upper()
lower Returns a string with all the letters lower-cased name.lower()
capitalize Returns a string with the first letter capitalized name.capitalize()
count (searchString) Counts how many times a searchString appears in a string phrase.count("a")
index (searchString) Gives the string index of the first occurence of the searchString. It is case sensitive. word.index("H")

Math

Operation Symbol in Python Example
Add + 1 + 1
Subtract - 13 - 1
Divide / 12 / 6
Multiply * 12 * 12
Modulo % 12 % 5
Divide an round to Int // 12 // 5

Loops

for

For loops are traditionally used when you have a block of code which you want to repeat a fixed number of times. The Python for statement iterates over the members of a sequence in order, executing the block each time.

for x in range(0, 3):
    print("We're on time " + int(x))

The above is the same as:

for x in range(3):
    print("We're on time " + int(x))

while

While loops, like the for loop, are used for repeating sections of code - but unlike a for loop, the while loop will not run n times, but until a defined condition is no longer met. If the condition is initially false, the loop body will not be executed at all.

As the for loop in Python is so powerful, while is rarely used, except in cases where a user's input is required, for example:

n = input("Please enter 'hello':")
while n.strip() != 'hello':
    n = input("Please enter 'hello':")

A while loop is composed of the keyword while followed by a condition. These are the same sorts of conditions that can live in an if block.

Everything in the while block will be repeated until the condition is met, the code encounters a break statement, or the program exits.

i = 0
while i < 10:
  i += 1

# the above code will run 10 times and then exit
while True:
  cmd = input("What do you want to do? ")
  if cmd.lower() == "exit":
    break
import sys

while True:
  cmd = input("What do you want to do? ")
  if cmd.lower() == "exit":
    sys.exit()

The difference between example 2 and example 3 is that example 3 will quit the program altogether, where in example 2, if there was more code beneath the while loop, that code would run next.

Terms

def is_hit(x, y, grid):
if not grid[y][x] == 0:
if grid[y][x] == "X" or grid[y][x] == "O":
return "You've already tried that captain!"
return True
return False
from is_valid import is_valid
from is_hit import is_hit
from get_coords import get_coords
grid = [
[0,0,0,0,0,0,0,0,0,0],
[0,0,"sub","sub","sub",0,0,0,0,0],
[0,0,"battleship","battleship","battleship","battleship",0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
["carrier",0,0,0,0,0,0,0,0,0],
["carrier",0,0,0,0,0,0,0,0,0],
["carrier",0,0,0,0,"cruiser",0,0,0,0],
["carrier",0,0,0,0,"cruiser",0,0,0,"destroyer"],
["carrier",0,0,0,0,"cruiser",0,0,0,"destroyer"],
[0,0,0,0,0,0,0,0,0,0]
]
while True:
cmd = input("> ")
if is_valid(cmd):
atk = is_hit(cmd, grid)
if (isinstance(atk, str)):
print(atk)
continue
if atk:
print("HIT!")
else:
print("MISS!")
else:
print("Is the sea gettin' to ya, captain?")
def render_hit():
return "\x1b[46m\x1b[31mX\x1b[39m\x1b[49m"
def render_miss():
return "\x1b[46mO\x1b[49m"
def render_empty():
return "\x1b[46m \x1b[49m"
grid = [
[0,0,0,0,0,0,0,0,0,0],
[0,0,"sub","sub","sub",0,0,0,0,0],
[0,0,"battleship","battleship","battleship","battleship",0,0,0,0],
[0,0,0,0,0,0,0,0,0,0],
["carrier",0,0,0,0,0,0,0,0,0],
["carrier",0,0,0,0,0,0,0,0,0],
["carrier",0,0,0,0,"cruiser",0,0,0,0],
["carrier",0,0,0,0,"cruiser",0,0,0,"destroyer"],
["carrier",0,0,0,0,"cruiser",0,0,0,"destroyer"],
[0,0,0,0,0,0,0,0,0,0]
]

Week 2

DataTypes Glossary

literal

A fixed value in source code

In Python the following code is a string literal:

"Hello World"

In this example, foo is a variable whose value is a string, while "Do stuff" is a string literal:

foo = "Hello World"

"Do stuff"

string

A sequence of characters.

A good way to picture strings is text or a document. While we will often put more than just words in a string/string variable, text and letters will always be strings.

type("Hello")

#=> <class 'str'>

Methods

upper()
message = "hi there"
message.upper()

#=> "HI THERE"
lower()
message = "HELO"
message.lower()

#=> "hello"
capitalize()
name = "mcelwee"
name.capitalize()

#=> "Mcelwee"
count()
chapter = "The transition was an unheard-of one. In the very heart of the city, Jean Valjean had escaped from the city, and, in the twinkling of an eye, in the time required"
chapter.lower().count("in")

#=> 3

And many more:

https://www.w3schools.com/python/python_ref_string.asp

Concatenation

Concatenation is an operation that glues two or more strings together. In Python we do this with the +.

greeting = "Hello " + name + ", welcome to " + store + "!!"

Tricks

Reversal
word = "racecar"
word[::-1]

#=> "racecar"

integer

A whole number.

An integer is one of the simplist types we have. It represents a whole number. Not super complicated.

type(1)

#=> <class 'int'>

Math

Note, in Python 3 math operations can be done accross numeric types.

Operation Symbol in Python Example
Add + 1 + 1
Subtract - 13 - 1
Divide / 12 / 6
Multiply * 12 * 12
Modulo % 12 % 5
Divide an round to Int // 12 // 5

float

Floats represent a real number that are often fractional and represent a trade-off between range and precision.

Floats are a bit tricky to think about. Essentially, they're decimal numbers but are often infinite. For instance, 1/3 as a decimal is 0.333 (repeating). Floats manage this by giving us a lot of precision while not overloading the computer. As a result, you can wind up with some funky results when doing math with floats.

type(1.002)

#=> <class 'float'>

If you want to find out more, and possibly explode your brain, read this.

In-Class Excercises

Palindromes

Write a function that takes one argument/parameter and returns a Boolean noting if the argument is a palindrome (spelled the same backwards and forwards).

def is_palindrome(word):
  pass

Week 3

String Indexing

For this example we're going to work with the following variable:

s = "Sammy the Shark!"

In Python, strings are indexed a lot like lists:

S a m m y t h e S h a r k !
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

Getting a letter (index)

Just like a list, I can get a single character out of the string by asking for it by the index. If I wanted to get "a" I would do the following:

s[1]

# => "a"

Getting a slice

A slice is cut down version of a string. Think of slicing a loaf of bread and taking only the piece you want.

In Python, we do this like this: string[start:end].

So if we wanted to just get "ammy" out of s we would do:

s[1:5]

Now if you're looking at the table above and this example, you're probably thinking "why is it 5 instead of 4?" In Python, the end index is exclusive this means that we are stopping right before that index number. This can make it a little tricky if you don't remember as your results might be one off.

Python gives us some really useful tricks with this as well.

s[1:]

# => "ammy the Shark!"

If you include the colon (:) but exclude the end index, Python will assume you want to go all the way to the end of the string.

Similarly, if you want to end at a specified spot but start from the beginning you can do this:

s[:5]

# => "Sammy"

Stride

The third place in a string index is the stride. Picture it like a chess board. You can move one space at a time (the default) or you can skip every other, or skip 3. Python lets you set the stride as the last position in the index.

s[::2]

# => "SmyteSak"

You'll see above that we set the stride to 2, so we skip every other letter. You'll also note in the above example, we didn't include the start or end index. Just like the slice, I can exclude either and Python assumes I mean both the start and end of the string. So:

example_one = s[::2]
example_two = s[0:15:2]

example_one == example_two

# => True

So in the case of string reversal s[::-1] what I'm saying is start at the first index (0), end at the last index (15), and walk backwards.

For more check out this article out.

Product Roadmap

  • I can view a 10x10 grid for myself and my enemy
  • I can place my ships on the board
    • Ships:
      1. Carrier (5 spaces)
      2. Battleship (4 spaces)
      3. Cruiser (3 spaces)
      4. Submarine (3 spaces)
      5. Destroyer (2 spaces)
    • Rules:
      1. Ships can be placed veritcally or horizontally
      2. Ships cannot be placed diagonally
      3. No part of a ship may hang over the edge of the board
      4. No ships may be placed on top of another ship
  • I can guess an enemy ship location
    • Rules:
      1. On a 10x10 grid, submit the coordinates of an enemy ship (e.g. A1)
      2. If the coordinate contains any part of a ship, the enemy responds with "HIT"
      3. If the coordinate does not contain any part of a ship, the enemy responds with "MISS"
      4. The HIT OR MISS is recorded with an X on the enemy board (which is otherwise empty)
      5. If the attack was a HIT the background of the square is shaded to indicate a ship part
  • An enemy can guess my ship location
    • Rules:
      1. On a 10x10 grid, the enemy submits the coordinates of its guess
      2. If the coordinate contains any part of a ship, you respond with "HIT"
      3. If the coordinate does not contain any part of your ship, you respond with "MISS"
      4. The HIT OR MISS is recorded with an X on your board
  • Ships sink when all of their parts have been hit
  • Game ends when all ships of a player have been sunk

GitHub Repo

Python Repl

To test what we did this week:

from is_valid import is_valid

is_valid("X10")
>>> False

Any time you make a change be sure to save first, and then exit the repl, the repeat the step above.

(How to exit the repl)

exit()

What you should have left class with:

from letters import LETTERS

def is_valid(cmd):
  if len(cmd) < 2:
    return False
  
  first_letter = cmd[0]
  if first_letter.upper() not in LETTERS:
    return False

Week 4

Loops Revisited

While Loops

While loops will run infinitely given the truth of a condition:

while True:
  print("🦄")
  
# This will run forever

A while loop takes a condition after the keyword while which is the same as a conditional in an if statment.

while not input("Do you want to exit? (y/N) > ") == "y":
  print("🦄")
  
# This will run until a user types in "y"

While loops are good for when we want to the same thing, or set of things, over and over again until something else happens.

For Loops

For loops are traditionally used when you have a block of code which you want to repeat a fixed number of times.

for x in range(0, 15):
  print("🦄 " + x)
  
# Will print "🦄 0" through "🦄 14"

Week 5

In class we created a function to create a quick-and-dirty "create grid" function to create the playing board for our opponent. We put the function in create_enemy_grid.py and it looked like this:

from random import random
import math

def create():
  grid = []
  
  for y in range(10):
    grid.append([])
    for x in range(10):
      if math.floor(random() * 10) == 6:
        grid[y].append(1)
      else:
        grid[y].append(0)

  return grid

The above code creates a 10x10 grid (a list of lists) and randomly assigns a square to have a ship in it. We will come back after break to write code to actually place the real enemy ships, for now we're randomizing so we can move on to the hit.

We also started working on a function to check if we'd hit an enemy's ship. We didn't get very far on this however as we focused on solving the problem first before we wrote code for it.

Given A1 we want that to translate to grid[0][0] where the letter A becomes 0 and 1 becomes 0. In the same way, we wanted J10 to become grid[9][9] (remember, lists are 0-indexed).

We determined that once we got the number out of the string int(cmd[1:]) we could simply subtract 1 to get the right number.

Now we had to try to figure out the letters. The suggestion came up to use the codes the computer knows for letters (which are actually numbers). These are called character codes. So for the letter capital-A, the computer reads 65.

You can look at the following table to get a good understanding of what numbers map to which characters on your keyboard. Note that uppercase and lowercase letter get different character codes. Also, note that in the table in the link there are 3 columns before the character itself. All we care about is the first column, DEC. ASCII Table

The suggestion then is since we know that uppercase A is 65 and all the letters count up sequentially, we could subtract 65 from the letter's character code to get its value: ord(cmd[0].upper()) - 65. In this way, since A = 65, and J = 74, we would get 0 for A and 9 for J.

We'll put this together at the beginning of the next class to create our is_hit function.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment