Grid Drawing

            
#!/usr/bin/env python3

import sys
import tkinter


def make_canvas(width, height):
    top = tkinter.Tk()
    top.minsize(width=width + 10, height=height + 10)

    canvas = tkinter.Canvas(top, width=width, height=height)
    canvas.pack()
    canvas.xview_scroll(6, 'units')  # hack so (0, 0) works correctly
    canvas.yview_scroll(6, 'units')

    # draw blue boundaries - sides
    canvas.create_line(0, 0, 0, height - 1, fill='blue')
    canvas.create_line(width - 1, 0, width - 1, height - 1, fill='blue')
    # top to bottom
    canvas.create_line(0, 0, width - 1, 0, fill='blue')
    canvas.create_line(0, height - 1, width - 1, height - 1, fill='blue')
    return canvas


def draw_grid(width, height, n):
    canvas = make_canvas(width, height)

    # Vertical lines at 1/n, 2/n, .. n-1/n
    for i in range(1, n):
        x = int(width * i/n)
        canvas.create_line(x, 0, x, height - 1, fill='red')

    # b. horizontal lines + text
    for i in range(1, n):
       y = int(height * i/n)
       canvas.create_line(0, y, width - 1, y, fill='red')
       canvas.create_text(3, y, text=str(y), anchor=tkinter.SW)

    # required last line puts the canvas-window up on screen
    tkinter.mainloop()


# Default canvas size
WIDTH = 500
HEIGHT = 300

def main():
    args = sys.argv[1:]

    # args:
    # n               # draws 500x300 with this n
    if len(args) == 1:
        draw_grid(WIDTH, HEIGHT, int(args[0]))

    # args:
    # width height n  # draws custom size grid with n
    if len(args) == 3:
        draw_grid(int(args[0]), int(args[1]), int(args[2]))


if __name__ == '__main__':
    main()
            
        

Random Circles

            
import sys
import tkinter
import random

WIDTH = 800
HEIGHT = 600
RADIUS_MIN = 30
RADIUS_MAX = 100
N_CIRCLES_MAX = 10

def make_canvas():
    """
    (provided)
    Creates and returns a drawing canvas
    of the given int size with a blue border,
    ready for drawing.
    """
    top = tkinter.Tk()
    top.minsize(width=WIDTH + 10, height=HEIGHT + 10)

    canvas = tkinter.Canvas(top, width=WIDTH, height=HEIGHT)
    canvas.pack()
    canvas.xview_scroll(6, 'units')  # hack so (0, 0) works correctly
    canvas.yview_scroll(6, 'units')

    return canvas


def make_one_circle(canvas):
    radius = random.randint(RADIUS_MIN, RADIUS_MAX)
    x0 = random.randint(0, WIDTH  - 2 * radius)
    y0 = random.randint(0, HEIGHT - 2 * radius)
    x1 = x0 + 2 * radius
    y1 = y0 + 2 * radius
    canvas.create_oval(x0, y0, x1, y1)

def make_all_circles():
    canvas = make_canvas()
    n_circles = random.randrange(0, N_CIRCLES_MAX) + 1
    for i in range(n_circles):
        make_one_circle(canvas)

def main():
    make_all_circles()
    tkinter.mainloop()

if __name__ == "__main__":
    main()

            
        

Drawing friend graphs

          
# !/usr/bin/python3

import sys
import tkinter
import random

# provided function, this code is complete (Nick's Code from lecture for make_canvas)
def make_canvas(width, height):
    """
    Creates and returns a drawing canvas
    of the given int size with a blue border,
    ready for drawing.
    """
    top = tkinter.Tk()
    top.minsize(width=width + 10, height=height + 10)

    canvas = tkinter.Canvas(top, width=width, height=height)
    canvas.pack()
    canvas.xview_scroll(6, "units")  # hack so (0, 0) works correctly
    canvas.yview_scroll(6, "units")

    # draw blue boundaries - sides
    canvas.create_line(0, 0, 0, height-1, width=1, fill='blue')
    canvas.create_line(width-1, 0, width-1, height-1, width=1, fill='blue')
    # top bottom
    canvas.create_line(0, 0, width - 1, 0, width=1, fill='blue')
    canvas.create_line(0, height - 1, width - 1, height - 1, width=1, fill='blue')
    
    return canvas


canvas = make_canvas(800, 800)

def create_dict(filename):
  """
  This function creates a dictionary from a given file containing the names of each person in the network
  along with a list of people that they follow. The key is the name of a person in the
  network. The value is a list of people that they follow. 
  """
  network = {}
  with open(filename) as f:
    for line in f:
      line = line.strip()
      first_split = line.split(": ")
      key = first_split[0]
      friends = first_split[1].split(", ")
      
      #add each name to the network 
      network[key] = friends

  return network


def create_coord_dict(filename):
  """
  This function creates a dictionary from a given file with each name containing a name and a list 
  of corresponding x and y coordinates. Each key in the dictionary is the name of a person in the network, 
  and the value is a list where the first item is the x coordinate for this person's node and the second 
  item is the y coordinate. This fuction returns the dictionary created. 
  """
  coord_list = {}
  with open(filename) as f:
    for line in f:
      first_split = line.split(": ")
      key = first_split[0]
      coords = first_split[1].split(", ")

      #convert from string to int 
      coords[0] = int(coords[0])
      
      #trim the trailing whitespace and convert from string to int 
      coords[1] = int(coords[1].strip())

      #update the dictionary to include this key value pair
      coord_list[key] = coords

  return coord_list


def draw_first_coords(coord_list):
  """
  This function draws a single circle for each friend in the network at it's given starting coordinate. 
  It also adds a string of text with the name of the person that the circle represents in the network. 
  """
  for name in coord_list:
    x_val = coord_list[name][0]
    y_val = coord_list[name][1]
    canvas.create_oval(x_val, y_val, x_val+10-1, y_val+10-1, fill = 'green')
    canvas.create_text(x_val, y_val, text = name)


def draw_connections(network, coord_list):
  """
  This function draws the lines betweens friends in the network based on the given dictionary. 
  network is a the dictionary of relationships created in create_dict
  coord_list is the dict of names and coordinates given
  """
  for name in network:
    start_x = coord_list[name][0]
    start_y = coord_list[name][1]
    for friend in network[name]:
      end_x = coord_list[friend][0]
      end_y = coord_list[friend][1]
      canvas.create_line(start_x, start_y, end_x, end_y)

def main():
  args = sys.argv[1:]
  friends_filename = args[0]
  coords_filename = args[1]
  network = create_dict(friends_filename)
  coord_list = create_coord_dict(coords_filename)
  draw_first_coords(coord_list)
  draw_connections(network, coord_list)
  tkinter.mainloop()
          
        

Using map

          
temps_F = [45.7, 55.3, 62.1, 75.4, 32.0, 0.0, 100.0]

#convert from Fahrenheit to Celsius
temps_C = list(map(lambda f : (f - 32) * 5 / 9, temps_F))
print('F: ', temps_F)
​
          
        
          
original_headings = [(30, 'N'), (359, 'N'), (340, 'N'), (270, 'W'), (124, 'E'), (149, 'S'), (219, 'S')]
​
def update_heading(reading):
  updated_heading = (reading[0] + 22) % 360
  updated_direction = calc_direction(updated_heading)
  return (updated_heading, updated_direction)
​
​
def calc_direction(heading):
  if 46 <= heading and heading <= 135:
    return 'E'
  elif 136 <= heading and heading <= 225:
    return 'S'
  elif 226 <= heading and heading <= 315:
    return 'W'
  else:
    return 'N'
​
update_list = list(map(update_heading, original_headings))
print(update_list)
          
        

Sorting with lambdas

            
>>> strs = ['apple', 'BANANA', 'candy', 'aardvark']
# 1A.
>>> sorted(strs, key=lambda word : word.lower())
['aardvark', 'apple', 'BANANA', 'candy']
# 1B.
>>> sorted(strs, key=lambda word : word.lower()[len(word)-1])
['BANANA', 'apple', 'aardvark', 'candy']

#2
>>> nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> sorted(nums, key=lambda num:abs(num-3.14))
[3, 4, 2, 5, 1, 6, 7, 8, 9, 10]
>>> min(nums, key=lambda num:abs(num-3.14))
3
>>> max(nums, key=lambda num:abs(num-3.14))
10

# 3A.
>>> sorted(rentals, key=lambda room_tuple:room_tuple[1])
[('elm st.', 1, 1200), ('pine st.', 2, 1600), ('main st.', 4, 4000)]
# 3B.
>>> sorted(rentals, key=lambda room_tuple:room_tuple[2])
[('elm st.', 1, 1200), ('pine st.', 2, 1600), ('main st.', 4, 4000)]
# 3C.
>>> sorted(rentals, key=lambda room_tuple:room_tuple[2]/room_tuple[1])
[('pine st.', 2, 1600), ('main st.', 4, 4000), ('elm st.', 1, 1200)]
>>> min(rentals, key=lambda room_tuple:room_tuple[2]/room_tuple[1])
('pine st.', 2, 1600)
            
        

Tweets Revisited

            
def most_used(counts):
    """
    Given a non-empty "flat" counts dict of tags, return the tag
    that has the largest count.
    """
    return max(counts.keys(), key=lambda hashtag : counts[hashtag])
            
        

Pynary Bomb

The correct command to defuse the bomb is:

            
$ python3 pynarybomb.py 3 4 9
            
        

If you didn't work through this yourself, try tracing through the problem now and verifying that this sequence of numbers would in fact defuse the bomb!


Analyzing Mimic Output

            
import sys


def get_word_frequencies(filename):
    counts = {}

    with open(filename, 'r') as f:
        text = f.read()
        words = text.split()

        for word in words:
            word = word.lower()
            if word not in counts:
                counts[word] = 0
            counts[word] += 1

    return counts


def print_most_frequent(filename):
    counts = get_word_frequencies(filename)
    for pair in sorted(counts.items(), key=lambda x: x[1]):
        print(pair[0], pair[1])


def main():
    args = sys.argv[1:]
    filename = args[0]
    print_most_frequent(filename)


if __name__ == '__main__':
    main()