fbpx

Creating a Playlist with Linked Lists in Python: A Step-by-Step Guide

Creating a Playlist with Linked Lists in Python: A Step-by-Step Guide

INTRODUCTION

Creating a playlist manager in Python using a linked list provides a dynamic, flexible approach to handling music playlists. Through this project, we’ll explore how to use linked lists in Python to add, delete, and rearrange songs, allowing for efficient playlist manipulation. With linked lists, songs can be inserted at any position or removed quickly, without shifting elements, making it ideal for dynamic collections.

This project also uses various Python modules to enhance functionality:

  1. Time Module: Helps us introduce delays when printing song details, simulating the time taken to play each song.
  2. Random Module: Allows for features like shuffling songs, adding an element of surprise to the playlist.
  3. CSV Module: Enables importing songs from a CSV file, making the playlist easy to populate from existing data.
Inserting a song(By using linked list)
Deleting a song((By using linked list)

import time                  

 #The time module in Python provides functions to work with time-related tasks,   like getting the current time, measuring execution time, and implementing delays.

import random

#By using this import  random module which has methods like ,rand,randn(4,4),randint(1,100)

import csv

#By using this file we are goint to import csv file through this module we can read a file and write  a data to a file.

# song object

#  id, name and duration information is contained..

class Song:

    def _init_(self, song_id, song_name, song_length):

        self.song_id = song_id

        self.song_name = song_name

        self.song_length = song_length

    def _str_(self):

        return str({‘song_id’:self.song_id,

                    ‘song_name’:self.song_name,

                    ‘song_length’:self.song_length})

class ListNode:

    def _init_(self, song:Song):

        self.song = song

        self.next = None

    def _str_(self):

        return str(self.song)

# Few other operation such as

# b. sorting a linkedlist based on song

# a. deletion of song,                                                                                              

# c. randomly picking a song for playing

class LinkedList:

    def _init_(self):

        self.head_node = None

        self.count = 0

    # Traversing the linked lists

    def traversal(self):

        if self.head_node is None:

            return

        temp_node = self.head_node

        while(temp_node != None):

            print(temp_node.song)

            time.sleep(2)

            temp_node = temp_node.next

        time.sleep(2)

        return

    # inserting(node)at the beginning

    def insert_at_start(self, node):

        if self.head_node is None:

            self.head_node = node

            self.count = self.count + 1

            return True

        node.next = self.head_node

        self.head_node = node

        return True

    # inserting(node) after a particular song   

    def insert_after(self, song_name, node):

        temp_node = self.head_node

        while(temp_node.song.song_name!=song_name):

            temp_node = temp_node.next

        # if song is not found 

        if temp_node is None:

            return False

        # if song is found

        else:

            if temp_node.next == None:

                temp_node.next = node

            else:

                node.next = temp_node.next

                temp_node.next = node

            return True

    def insert_before(self, song_name, node):

        temp_node = self.head_node

        prev_node = None

        # Checking the song until we find

        while(temp_node.song.song_name!=song_name):

            prev_node = temp_node

            temp_node = temp_node.next

        # if song is not found 

        if temp_node == None:

            return False

        # if list contains only one song

        if prev_node == None:

            node.next = self.head_node

            self.head_node = node

            return True

        # updating the linked list

        prev_node.next = node

        node.next = temp_node

        return True

    # Deleting (song)

    def delete_song(self, song_name):

                # identify the song needed to be deleted.

                # Once the song is found set it in temp variable an/d update the references

        curr = self.head_node

        if curr.song.song_name==song_name: #delete head node

            self.head_node = curr.next

            del(curr)

            return

        while curr!=None:

            if curr.next.song.song_name==song_name:

                break

            curr= curr.next

        if curr==None :

             raise Exception(“mentioned song of Model not available, cannot delete”)

        temp = curr.next

        curr.next = curr.next.next

        del(temp)

        return curr   

    def sort_list(self):

#The entire list will be updated according to the song.

#Note that sorting should be based specifically on the song_name.

#You can use the built-in

 for i in range(0,9):

            print(Song)\

        #new_list=sorted(playlist_linked_list, key=lambda x: x.song_name, reverse=True)

        #return new_list

    def shuffle_song(self)

pass

class PlayList:

    def _init_(self, id, playlist_name, linked_list:LinkedList):

        self.playlist_id = id

        self.playlist_name = playlist_name

        self.playlist_linked_list = linked_list

    def get_playlist(self):

        return self.playlist_linked_list

    def get_playlist_name(self):

        return self.playlist_name

    def get_playlist_id(self):

        return self.playlist_id

class MusicPlayer:

    def _init_(self):

        self.playlists = list()

    def add_playlist(self, new_playlist:PlayList):

        self.playlists.append(new_playlist)

    def play_playlist(self, playlist_name):

        for playlist in self.playlists:

            if playlist.get_playlist_name() == playlist_name:

                playlist.get_playlist().traversal()

            else:

                print(‘No such playlist exists ‘)

    def delete_song_from_playlist(self, playlist_name, song_name):

        playlist = self.search_playlist_by_name(playlist_name)

        if playlist is None:

            print(“No such playlist exists “)

            return

        playlist.get_playlist().delete_song(song_name)

        return

    def sort_playlist(self, playlist_name):

        playlist = self.search_playlist_by_name(playlist_name)

        if playlist is None:

            print(“No such playlist exists”)

            return

        playlist.get_playlist().sort_list()

        return

    def play_shuffled_song(self, playlist_name):

        playlist = self.search_playlist_by_name(playlist_name)

        if playlist is None:

            print(“No such plalistr.”)

            return

        print(playlist.get_playlist().shuffle_song())

        return

    def list_all_playlists(self):

        for playlist in self.playlists:

            print(playlist.playlist_name)

    def search_playlist_by_name(self, name):

        for playlist in self.playlists:

            if playlist.playlist_name == name:

                return playlist

        return None

    def delete_playlist(self, name):

        for playlist in self.playlists:                                                                                     

            if playlist.playlist_name == name:

                del playlist

                return True

        return False

def create_linked_list():

    with open(‘C:\\pro1\\app_data.csv’, newline=”) as csvfile:

        reader = csv.DictReader(csvfile)

        linked_list = LinkedList()

        for row in reader:

            song = Song(row[‘Song ID’], row[‘Song Name’], row[‘Song Length’])

            listnode = ListNode(song)

            linked_list.insert_at_start(listnode)

    return linked_list

if _name_ == “_main_”:

    musicplayer = MusicPlayer()

    musicPlayer1 = MusicPlayer()

    linked_list = create_linked_list()

    playlist = PlayList(1, ‘Songs’, linked_list)

    print(“\nAdding playlist \n”)

    musicplayer.add_playlist(playlist)

    print(f’Playing all songs in the playlist \n’)

    musicplayer.play_playlist(‘Songs’)

    print(f’\nDeleting the Song with name : Lotus\n’)

    musicplayer.delete_song_from_playlist(‘Songs’, ‘Lotus’)

    musicplayer.play_playlist(‘Songs’)

    print(‘\nPlaying all songs after sorted based on names \n’)

    musicplayer.sort_playlist(‘Songs’)

    musicplayer.play_playlist(‘Songs’)

    print(‘\nPlaying shuffled song \n’)

    musicplayer.play_shuffled_song(‘Songs’)