What is a Hashtable/Hashmap?

A hashtable is a data structure that with a collection of key-value pairs, where each key maps to a value, and the keys must be unique and hashable.

  • In Python there is a built in hashtable known as a _dictionary__.

The primary purpose of a hashtable is to provide efficient lookup, insertion, and deletion operations. When an element is to be inserted into the hashtable, a hash function is used to map the key to a specific index in the underlying array that is used to store the key-value pairs. The value is then stored at that index. When searching for a value, the hash function is used again to find the index where the value is stored.

The key advantage of a hashtable over other data structures like arrays and linked lists is its average-case time complexity for lookup, insertion, and deletion operations.

  • The typical time complexity of a hashtable is _O(1) or constant__.

What is Hashing and Collision?

Hashing is the process of mapping a given key to a value in a hash table or hashmap, using a hash function. The hash function takes the key as input and produces a hash value or hash code, which is then used to determine the index in the underlying array where the value is stored. The purpose of hashing is to provide a quick and efficient way to access data, by eliminating the need to search through an entire data structure to find a value.

However, it is possible for two different keys to map to the same hash value, resulting in a collision. When a collision occurs, there are different ways to resolve it, depending on the collision resolution strategy used.

Python's dictionary implementation is optimized to handle collisions efficiently, and the performance of the dictionary is generally very good, even in the presence of collisions. However, if the number of collisions is very high, the performance of the dictionary can degrade, so it is important to choose a good hash function that minimizes collisions when designing a Python dictionary.

What is a Set?

my_set = set([1, 2, 3, 2, 1])
print(my_set)  

# What do you notice in the output?
# set() returns the values that are unique. Duplicated values are left out. 

# Why do you think Sets are in the same tech talk as Hashmaps/Hashtables?
# Sets and keys are similar in that they must be unique. 
{1, 2, 3}

Dictionary Example

Below are just some basic features of a dictionary. As always, documentation is always the main source for all the full capablilties.

lover_album = {
    "title": "Lover",
    "artist": "Taylor Swift",
    "year": 2019,
    "genre": ["Pop", "Synth-pop"],
    "tracks": {
        1: "I Forgot That You Existed",
        2: "Cruel Summer",
        3: "Lover",
        4: "The Man",
        5: "The Archer",
        6: "I Think He Knows",
        7: "Miss Americana & The Heartbreak Prince",
        8: "Paper Rings",
        9: "Cornelia Street",
        10: "Death By A Thousand Cuts",
        11: "London Boy",
        12: "Soon You'll Get Better (feat. Dixie Chicks)",
        13: "False God",
        14: "You Need To Calm Down",
        15: "Afterglow",
        16: "Me! (feat. Brendon Urie of Panic! At The Disco)",
        17: "It's Nice To Have A Friend",
        18: "Daylight"
    }
}

# What data structures do you see?
# There is a list for genre, and a dictionary for tracks
#

# Printing the dictionary
print(lover_album)
{'title': 'Lover', 'artist': 'Taylor Swift', 'year': 2019, 'genre': ['Pop', 'Synth-pop'], 'tracks': {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}}
print(lover_album.get('tracks'))
# or
print(lover_album['tracks'])
{1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}
{1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}
print(lover_album.get('tracks')[4])
# or
print(lover_album['tracks'][4])
The Man
The Man
lover_album["producer"] = set(['Taylor Swift', 'Jack Antonoff', 'Joel Little', 'Taylor Swift', 'Louis Bell', 'Frank Dukes'])

# What can you change to make sure there are no duplicate producers?
# use .set


# Printing the dictionary
print(lover_album)
{'title': 'Lover', 'artist': 'Taylor Swift', 'year': 2019, 'genre': ['Pop', 'Synth-pop'], 'tracks': {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight'}, 'producer': {'Jack Antonoff', 'Frank Dukes', 'Taylor Swift', 'Louis Bell', 'Joel Little'}}
lover_album["tracks"].update({19: "All Of The Girls You Loved Before"})

# How would add an additional genre to the dictionary, like electropop? 
#  lover_album['genre'].append("Electropop")

# Printing the dictionary
print(lover_album)
{'title': 'Lover', 'artist': 'Taylor Swift', 'year': 2019, 'genre': ['Pop', 'Synth-pop'], 'tracks': {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight', 19: 'All Of The Girls You Loved Before'}, 'producer': {'Jack Antonoff', 'Frank Dukes', 'Taylor Swift', 'Louis Bell', 'Joel Little'}}
for k,v in lover_album.items(): # iterate using a for loop for key and value
    print(str(k) + ": " + str(v))
print("")
# Write your own code to print tracks in readable format
tracks = lover_album["tracks"]
print("ID | TRACKS")
for k, v in tracks.items():
    print(str(k) + ": " + str(v))
title: Lover
artist: Taylor Swift
year: 2019
genre: ['Pop', 'Synth-pop']
tracks: {1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight', 19: 'All Of The Girls You Loved Before'}
producer: {'Jack Antonoff', 'Frank Dukes', 'Taylor Swift', 'Louis Bell', 'Joel Little'}

ID | TRACKS
1: I Forgot That You Existed
2: Cruel Summer
3: Lover
4: The Man
5: The Archer
6: I Think He Knows
7: Miss Americana & The Heartbreak Prince
8: Paper Rings
9: Cornelia Street
10: Death By A Thousand Cuts
11: London Boy
12: Soon You'll Get Better (feat. Dixie Chicks)
13: False God
14: You Need To Calm Down
15: Afterglow
16: Me! (feat. Brendon Urie of Panic! At The Disco)
17: It's Nice To Have A Friend
18: Daylight
19: All Of The Girls You Loved Before
# This is a very basic code segment, how can you improve upon this code?
#
#
def search1():
    search = input("What would you like to know about the album?")
    if lover_album.get(search.lower()) == None:
        print(search, " is an invalid input, try again!")
        search1()      
    else:
        print(lover_album.get(search.lower()))
        
search1()
cars  is an invalid input, try again!
movies  is an invalid input, try again!
{1: 'I Forgot That You Existed', 2: 'Cruel Summer', 3: 'Lover', 4: 'The Man', 5: 'The Archer', 6: 'I Think He Knows', 7: 'Miss Americana & The Heartbreak Prince', 8: 'Paper Rings', 9: 'Cornelia Street', 10: 'Death By A Thousand Cuts', 11: 'London Boy', 12: "Soon You'll Get Better (feat. Dixie Chicks)", 13: 'False God', 14: 'You Need To Calm Down', 15: 'Afterglow', 16: 'Me! (feat. Brendon Urie of Panic! At The Disco)', 17: "It's Nice To Have A Friend", 18: 'Daylight', 19: 'All Of The Girls You Loved Before'}

Hacks

Answer ALL questions in the code segments

Done

Example of Matrix Multiplication

Expand upon the code given to you, possible improvements in comments

Done

Build your own album showing features of a python dictionary

dawn_fm = {
    "genre": "R&B",
    "year": 2022,
    "artist": "The Weeknd",
    "title": "Dawn FM",
    "tracks": [
        {
            "title": "Here We Go Again (Intro)",
            "length": "1:48"
        },
        {
            "title": "The Dawn",
            "length": "5:11"
        },
        {
            "title": "Gasoline",
            "length": "3:32"
        },
        {
            "title": "Lose You Again",
            "length": "4:41"
        },
        {
            "title": "So Much Better",
            "length": "4:10"
        },
        {
            "title": "One Right Now",
            "length": "3:43"
        },
        {
            "title": "Survive The Night",
            "length": "4:04"
        },
        {
            "title": "Out Of Time",
            "length": "3:50"
        },
        {
            "title": "Bleed Out",
            "length": "4:08"
        },
        {
            "title": "Don't Break My Heart",
            "length": "3:21"
        },
        {
            "title": "I Heard You're Married",
            "length": "3:34"
        },
        {
            "title": "Take My Breath",
            "length": "3:40"
        },
        {
            "title": "Here We Go Again (Interlude)",
            "length": "1:32"
        },
        {
            "title": "Here We Go Again",
            "length": "4:27"
        },
        {
            "title": "Sacrifice",
            "length": "3:07"
        },
        {
            "title": "Do You Really Love Me",
            "length": "3:16"
        }
    ],
    "producer": "The Weeknd, Max Martin, Metro Boomin, and others",
    "label": "Republic Records, XO",
    "singles": ["Take My Breath", "Here We Go Again", "Sacrifice"],
    "awards": {
        "Juno Awards": 4,
        "MTV Music Awards": 1,
        "People's Choice Awards": 2
    },
    "length": "55:52"
}

print(dawn_fm)
{'genre': 'R&B', 'year': 2022, 'artist': 'The Weeknd', 'title': 'Dawn FM', 'tracks': [{'title': 'Here We Go Again (Intro)', 'length': '1:48'}, {'title': 'The Dawn', 'length': '5:11'}, {'title': 'Gasoline', 'length': '3:32'}, {'title': 'Lose You Again', 'length': '4:41'}, {'title': 'So Much Better', 'length': '4:10'}, {'title': 'One Right Now', 'length': '3:43'}, {'title': 'Survive The Night', 'length': '4:04'}, {'title': 'Out Of Time', 'length': '3:50'}, {'title': 'Bleed Out', 'length': '4:08'}, {'title': "Don't Break My Heart", 'length': '3:21'}, {'title': "I Heard You're Married", 'length': '3:34'}, {'title': 'Take My Breath', 'length': '3:40'}, {'title': 'Here We Go Again (Interlude)', 'length': '1:32'}, {'title': 'Here We Go Again', 'length': '4:27'}, {'title': 'Sacrifice', 'length': '3:07'}, {'title': 'Do You Really Love Me', 'length': '3:16'}], 'producer': 'The Weeknd, Max Martin, Metro Boomin, and others', 'label': 'Republic Records, XO', 'singles': ['Take My Breath', 'Here We Go Again', 'Sacrifice'], 'awards': {'Juno Awards': 4, 'MTV Music Awards': 1, "People's Choice Awards": 2}, 'length': '55:52'}
for k,v in dawn_fm.items(): # iterate using a for loop for key and value
    print(str(k) + ": " + str(v))
print("")
# Write your own code to print tracks in readable format

count = 1
print("TRACK  |  LENGTH")
while count <= 16:   
    print(dawn_fm['tracks'][count]['title'], ':', dawn_fm['tracks'][count]['length'])
    count += 1
genre: R&B
year: 2022
artist: The Weeknd
title: Dawn FM
tracks: [{'title': 'Here We Go Again (Intro)', 'length': '1:48'}, {'title': 'The Dawn', 'length': '5:11'}, {'title': 'Gasoline', 'length': '3:32'}, {'title': 'Lose You Again', 'length': '4:41'}, {'title': 'So Much Better', 'length': '4:10'}, {'title': 'One Right Now', 'length': '3:43'}, {'title': 'Survive The Night', 'length': '4:04'}, {'title': 'Out Of Time', 'length': '3:50'}, {'title': 'Bleed Out', 'length': '4:08'}, {'title': "Don't Break My Heart", 'length': '3:21'}, {'title': "I Heard You're Married", 'length': '3:34'}, {'title': 'Take My Breath', 'length': '3:40'}, {'title': 'Here We Go Again (Interlude)', 'length': '1:32'}, {'title': 'Here We Go Again', 'length': '4:27'}, {'title': 'Sacrifice', 'length': '3:07'}, {'title': 'Do You Really Love Me', 'length': '3:16'}]
producer: The Weeknd, Max Martin, Metro Boomin, and others
label: Republic Records, XO
singles: ['Take My Breath', 'Here We Go Again', 'Sacrifice']
awards: {'Juno Awards': 4, 'MTV Music Awards': 1, "People's Choice Awards": 2}
length: 55:52

TRACK  |  LENGTH
The Dawn : 5:11
Gasoline : 3:32
Lose You Again : 4:41
So Much Better : 4:10
One Right Now : 3:43
Survive The Night : 4:04
Out Of Time : 3:50
Bleed Out : 4:08
Don't Break My Heart : 3:21
I Heard You're Married : 3:34
Take My Breath : 3:40
Here We Go Again (Interlude) : 1:32
Here We Go Again : 4:27
Sacrifice : 3:07
Do You Really Love Me : 3:16
---------------------------------------------------------------------------
IndexError                                Traceback (most recent call last)
/home/tanisha1234/vscode/test-fastpage-tp/_notebooks/2023-03-29-DS-hashmaps.ipynb Cell 16 in <cell line: 9>()
      <a href='vscode-notebook-cell://wsl%2Bubuntu-20.04/home/tanisha1234/vscode/test-fastpage-tp/_notebooks/2023-03-29-DS-hashmaps.ipynb#X24sdnNjb2RlLXJlbW90ZQ%3D%3D?line=7'>8</a> print("TRACK  |  LENGTH")
      <a href='vscode-notebook-cell://wsl%2Bubuntu-20.04/home/tanisha1234/vscode/test-fastpage-tp/_notebooks/2023-03-29-DS-hashmaps.ipynb#X24sdnNjb2RlLXJlbW90ZQ%3D%3D?line=8'>9</a> while count <= 16:   
---> <a href='vscode-notebook-cell://wsl%2Bubuntu-20.04/home/tanisha1234/vscode/test-fastpage-tp/_notebooks/2023-03-29-DS-hashmaps.ipynb#X24sdnNjb2RlLXJlbW90ZQ%3D%3D?line=9'>10</a>     print(dawn_fm['tracks'][count]['title'], ':', dawn_fm['tracks'][count]['length'])
     <a href='vscode-notebook-cell://wsl%2Bubuntu-20.04/home/tanisha1234/vscode/test-fastpage-tp/_notebooks/2023-03-29-DS-hashmaps.ipynb#X24sdnNjb2RlLXJlbW90ZQ%3D%3D?line=10'>11</a>     count += 1

IndexError: list index out of range
def dawnsearch():
    search = input("What would you like to know about the album?")
    if dawn_fm.get(search.lower()) == None:
        print(search, " is an invalid input, try again!")
        dawnsearch()      
    else:
        print(search, ":" , dawn_fm.get(search.lower()))
        
dawnsearch()
shows  is an invalid input, try again!
tours  is an invalid input, try again!
merch  is an invalid input, try again!
genre : R&B

For Mr. Yeung's class: Justify your favorite Taylor Swift song, answer may effect seed

While Taylor Swift has many noteworthy songs, "Don't Blame Me" is definitely my favorite for a few reasons. "Don't Blame Me" exhibits Taylor's powerful vocals and her incredible range. Her vocal ability in this song was cleverly used to show a range of emotion that can be otherwise difficult to express. Taylor's genius lyrics such as "My name is whatever you decide, and I'm just gonna call you mine" showcases her ability to express the song's message of all-consuming love in a masterful way. Additionally, the melody is almost haunting, with heavy bass and precussion, which helps to create a dramatic atmosphere which suits the song's message perfectly. The song's multiple aspects allow "Don't Blame Me" to be a song perfect for any occasion. It's heavy precussion allow for it to be the perfect workout song, while the passionate lyrics also make it an emotional piece. Overall, I believe 'Don't Blame Me' is the best Taylor Swift Song.