Section #7: More Nested Structures & Classes

November 1st, 2020


Written by Brahm Capoor, Juliette Woodrow & Kara Eng

Student Residences

      
def map_students_to_dorms(all_housing_assignments):
	student_living_locations = {}

	for name, dorm in all_housing_assignments:
		if name not in student_living_locations:
			student_living_locations[name] = []
		student_residences = student_living_locations[name]
		student_residences.append(dorm)

	return student_living_locations
      
    

Visualizing Big Tweets

      
CANVAS_WIDTH = 1000
CANVAS_HEIGHT = 600
TEXT_TOP_OFFSET = 10
TEXT_SIDE_OFFSET = 3

def draw_bar(canvas, tag_label, left_x, top_y, right_x, bottom_y):
    """
    Given top-left and bottom-right coordinates for a bar and a label, 
    draw the bar
    """ 
    canvas.create_rectangle(left_x, top_y, right_x, bottom_y, fill="light blue", outline="blue")
    canvas.create_text(left_x + TEXT_SIDE_OFFSET, top_y+ TEXT_TOP_OFFSET, anchor='w',
        font=('Calibri', '10'),
        fill='Blue',
        text=tag_label)


def visualize_trends(canvas, user_tags, user_name): 
    if user_name not in user_tags:
        return 
    
    tags = get_top_tags(user_tags[username]) 
    
    totalNum = sum(tags.values()) #grab the total number of hashtags they used 
    tags_list = list(tags.keys()) #to grab all the tags we need and store in a list
    space = CANVAS_WIDTH/len(tags_list)
    
    for i in range(len(tags_list)): 
        tag = tags_list[i]
        count = tags[tag]
        height = CANVAS_HEIGHT * (count/ totalNum)
        x1 = space *i
        y1 = CANVAS_HEIGHT - height
        x2 = space*i + space 
        y2 = CANVAS_HEIGHT -1 
        tag_label = tag + " " + str(count)


        draw_bar(canvas, tag_label, x1, y1, x2, y2)
      
    

Class Design

      
import math

class Circle:

    def __init__(self, radius):
        """
        Creates a Circle object and initializes the radius.
        """
        self.radius = radius   # instance variable to keep track of the radius

    def get_area(self):
        """
        Returns the area of this circle.
        """
        area = math.pi * (self.radius**2)
        return area

    def get_circumference(self):
        """
        Returns the circumference of this circle
        """
        circumference = math.pi * self.radius * 2
        return circumference