├── Criteria.txt ├── Ping Pong Game ├── __pycache__ │ ├── ball.cpython-312.pyc │ ├── paddle.cpython-312.pyc │ └── scoreboard.cpython-312.pyc ├── ball.py ├── main.py ├── paddle.py ├── reademe.md └── scoreboard.py ├── README.md ├── Web scraping └── web-scraping.py ├── binary-finder └── binary-finder.py ├── dijkstra.py ├── find-factorial ├── database.py └── find-factorial.py ├── mini_projects ├── rockpaperscissors.py ├── snake_game.py ├── tictactoe.py └── timer.py ├── qr-code-generator └── qr.py └── recommender-system └── recommender_system.ipynb /Criteria.txt: -------------------------------------------------------------------------------- 1 | All your python pull requests will be considered but more weightage will be given to solving **issues** given in this repository. 2 | 3 | 1. Your PR/MRs must be within the bounds of Hacktoberfest. 4 | * Your PR/MRs must be created between October 1 and October 31 (in any time zone, UTC-12 thru UTC+14). 5 | * Your PR/MRs must be made to a public, unarchived repository. 6 | 7 | 2. Repos that go against Hacktoberfest’s values will be excluded from qualification and PR/MRs made to those repos won’t count. 8 | 9 | 3. Your PR/MRs must not be spammy. 10 | 11 | 4. Your PR/MRs must be in a repo tagged with the “hacktoberfest” topic, or have the “hacktoberfest-accepted” label. 12 | 13 | 5. Your PR/MRs must not be labeled as “invalid”. 14 | 15 | 6. Your PR/MRs must be merged, have the “hacktoberfest-accepted” label, or have an overall approving review. 16 | 17 | 7. Once your PR/MRs pass all the checks above, it will be accepted for Hacktoberfest after the seven day review period. 18 | 19 | # Make 4 succesful pull/merge requests and win digital reward kit. All the best! 20 | -------------------------------------------------------------------------------- /Ping Pong Game/__pycache__/ball.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chetannihith/python-hacktoberfest23/24afbbeb36f5fd65ac8dff2127b31fc756d92fbc/Ping Pong Game/__pycache__/ball.cpython-312.pyc -------------------------------------------------------------------------------- /Ping Pong Game/__pycache__/paddle.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chetannihith/python-hacktoberfest23/24afbbeb36f5fd65ac8dff2127b31fc756d92fbc/Ping Pong Game/__pycache__/paddle.cpython-312.pyc -------------------------------------------------------------------------------- /Ping Pong Game/__pycache__/scoreboard.cpython-312.pyc: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/chetannihith/python-hacktoberfest23/24afbbeb36f5fd65ac8dff2127b31fc756d92fbc/Ping Pong Game/__pycache__/scoreboard.cpython-312.pyc -------------------------------------------------------------------------------- /Ping Pong Game/ball.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | 4 | class Ball(Turtle): 5 | 6 | def __init__(self): 7 | super().__init__() 8 | self.color("red") 9 | self.shape("circle") 10 | self.penup() 11 | self.x_move = 10 12 | self.y_move = 10 13 | self.move_speed = 0.1 14 | 15 | def move(self): 16 | new_x = self.xcor() + self.x_move 17 | new_y = self.ycor() + self.y_move 18 | self.goto(new_x, new_y) 19 | 20 | def bounce_y(self): 21 | self.y_move *= -1 22 | 23 | def bounce_x(self): 24 | self.x_move *= -1 25 | self.move_speed *= 0.9 26 | 27 | def reset_position(self): 28 | self.goto(0, 0) 29 | self.move_speed = 0.1 30 | self.bounce_x() 31 | -------------------------------------------------------------------------------- /Ping Pong Game/main.py: -------------------------------------------------------------------------------- 1 | from turtle import Screen 2 | from paddle import Paddle 3 | from ball import Ball 4 | from scoreboard import Scoreboard 5 | import time 6 | 7 | screen = Screen() 8 | screen.bgcolor("yellow") 9 | screen.setup(width=800, height=600) 10 | screen.title("Pong") 11 | screen.tracer(0) 12 | 13 | r_paddle = Paddle((350, 0)) 14 | l_paddle = Paddle((-350, 0)) 15 | ball = Ball() 16 | scoreboard = Scoreboard() 17 | 18 | screen.listen() 19 | screen.onkey(r_paddle.go_up, "Up") 20 | screen.onkey(r_paddle.go_down, "Down") 21 | screen.onkey(l_paddle.go_up, "w") 22 | screen.onkey(l_paddle.go_down, "s") 23 | 24 | game_is_on = True 25 | while game_is_on: 26 | time.sleep(ball.move_speed) 27 | screen.update() 28 | ball.move() 29 | 30 | #Detect collision with wall 31 | if ball.ycor() > 280 or ball.ycor() < -280: 32 | ball.bounce_y() 33 | 34 | #Detect collision with paddle 35 | if ball.distance(r_paddle) < 50 and ball.xcor() > 320 or ball.distance(l_paddle) < 50 and ball.xcor() < -320: 36 | ball.bounce_x() 37 | 38 | #Detect R paddle misses 39 | if ball.xcor() > 380: 40 | ball.reset_position() 41 | scoreboard.l_point() 42 | 43 | #Detect L paddle misses: 44 | if ball.xcor() < -380: 45 | ball.reset_position() 46 | scoreboard.r_point() 47 | 48 | screen.exitonclick() -------------------------------------------------------------------------------- /Ping Pong Game/paddle.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | 4 | class Paddle(Turtle): 5 | 6 | def __init__(self, position): 7 | super().__init__() 8 | self.shape("square") 9 | self.color("black") 10 | self.shapesize(stretch_wid=5, stretch_len=1) 11 | self.penup() 12 | self.goto(position) 13 | 14 | def go_up(self): 15 | if self.ycor() <= 250: 16 | new_y = self.ycor() + 20 17 | self.goto(self.xcor(), new_y) 18 | 19 | def go_down(self): 20 | if self.ycor() >= -250: 21 | new_y = self.ycor() - 20 22 | self.goto(self.xcor(), new_y) 23 | -------------------------------------------------------------------------------- /Ping Pong Game/reademe.md: -------------------------------------------------------------------------------- 1 | ## Project Overview 2 | 3 | This project is a **Ping Pong game** developed using Python's **Turtle graphics**. It offers a classic, two-player gameplay experience with simple controls and progressively increasing difficulty. 4 | 5 | ### Game Features 6 | 7 | #### Player Controls 8 | - **Right Paddle**: Controlled using the `Up` and `Down` arrow keys. 9 | - **Left Paddle**: Controlled using the `W` and `S` keys. 10 | 11 | #### Scoreboard System 12 | - A dynamic scoreboard tracks and displays the score for both players throughout the game, updating in real time as points are scored. 13 | 14 | #### Progressive Difficulty 15 | - The speed of the ball increases gradually as the game progresses, making the gameplay more challenging over time. 16 | -------------------------------------------------------------------------------- /Ping Pong Game/scoreboard.py: -------------------------------------------------------------------------------- 1 | from turtle import Turtle 2 | 3 | 4 | class Scoreboard(Turtle): 5 | 6 | def __init__(self): 7 | super().__init__() 8 | self.color("blue") 9 | self.penup() 10 | self.hideturtle() 11 | self.l_score = 0 12 | self.r_score = 0 13 | self.update_scoreboard() 14 | 15 | def update_scoreboard(self): 16 | self.clear() 17 | self.goto(-100, 250) 18 | self.write(self.l_score, align="center", font=("Courier", 35, "normal")) 19 | self.goto(100, 250) 20 | self.write(self.r_score, align="center", font=("Courier", 35, "normal")) 21 | 22 | def l_point(self): 23 | self.l_score += 1 24 | self.update_scoreboard() 25 | 26 | def r_point(self): 27 | self.r_score += 1 28 | self.update_scoreboard() -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Welcome to [python-hacktoberfest23] - Hacktoberfest 2023 🎉 2 | 3 | Thank you for checking out this repository! We're excited to have you contribute to Hacktoberfest 2023. Before you get started, please take a moment to read the following rules and guidelines to ensure a smooth contribution process. 4 | 5 | ## How to Contribute 6 | 7 | 1. **Hacktoberfest Dates:** 8 | - Your Pull/Merge Requests (PR/MRs) must be created between **October 1 and October 31** (in any time zone). 9 | - Contributions made to this repository must follow Hacktoberfest rules and be submitted to public, unarchived repositories. 10 | 11 | 2. **Quality Over Quantity:** 12 | - **No Spam:** Submitting spammy PR/MRs will disqualify you. Keep your contributions meaningful, and avoid low-quality fixes like minor grammar updates unless they add real value. 13 | - PR/MRs should not be marked with labels containing the word **“spam”** or **“invalid.”** However, contributions labeled with **“hacktoberfest-accepted”** will be considered valid, even if they are not merged immediately. 14 | 15 | 3. **Repository Participation:** 16 | - This repository is participating in Hacktoberfest, so feel free to contribute! 17 | - Ensure that your PR/MR is either merged, has an overall approving review, or receives the **“hacktoberfest-accepted”** label to count toward your Hacktoberfest progress. 18 | 19 | 4. **Review Period:** 20 | - Once your PR/MR is created and passing checks, it will go through a **seven-day review period**. Make sure your submission remains compliant throughout this time. 21 | - Even if Hacktoberfest ends on October 31, PR/MRs still in the seven-day review period may continue into November. 22 | 23 | 5. **Valid Contributions:** 24 | - Ensure that your contribution adds real value to the project. Bug fixes, new features, and documentation improvements are welcome! 25 | 26 | ## How to Get Started 27 | 28 | 1. Fork this repository to your GitHub account. 29 | 2. Clone the forked repository to your local machine. 30 | 3. Make meaningful changes and improvements. 31 | 4. Create a pull request and follow the guidelines listed above. 32 | 33 | If you're new to GitHub and Hacktoberfest, you can check out these resources to get started: 34 | - [How to Create a Pull Request](https://docs.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request) 35 | - [Hacktoberfest Official Website](https://hacktoberfest.com) 36 | 37 | ## Show Your Support 38 | 39 | If you find this repository useful, please give it a ⭐! Contributions of all kinds are welcome, and every bit helps improve this project. 40 | 41 | --- 42 | 43 | **Happy coding and happy Hacktoberfest!** 👨‍💻👩‍💻🦥 44 | Fork the repo and start contributing today! Let's build something amazing together.🚀 45 | -------------------------------------------------------------------------------- /Web scraping/web-scraping.py: -------------------------------------------------------------------------------- 1 | import requests 2 | from bs4 import BeautifulSoup 3 | 4 | # The target URL you want to scrape 5 | url = 'https://example.com' 6 | 7 | # Send an HTTP request and get the HTML content 8 | response = requests.get(url) 9 | 10 | # Check if the request was successful 11 | if response.status_code == 200: 12 | # Parse the HTML content of the page 13 | soup = BeautifulSoup(response.content, 'html.parser') 14 | 15 | # Find specific elements by their HTML tags and classes 16 | # For example, find all the links on the page 17 | links = soup.find_all('a') 18 | 19 | # Print the found links 20 | for link in links: 21 | print(link.get('href')) 22 | 23 | else: 24 | # Print an error message if the request was not successful 25 | print(f"Failed to retrieve the webpage: {response.status_code}") -------------------------------------------------------------------------------- /binary-finder/binary-finder.py: -------------------------------------------------------------------------------- 1 | # Iterative Binary Search Function 2 | # It returns index of x in given array arr if present, 3 | # else returns -1 4 | def binary_search(arr, x): 5 | low = 0 6 | high = len(arr) - 1 7 | mid = 0 8 | 9 | while low <= high: 10 | 11 | mid = (high + low) // 2 12 | 13 | # If x is greater, ignore left half 14 | if arr[mid] < x: 15 | low = mid + 1 16 | 17 | # If x is smaller, ignore right half 18 | elif arr[mid] > x: 19 | high = mid - 1 20 | 21 | # means x is present at mid 22 | else: 23 | return mid 24 | 25 | # If we reach here, then the element was not present 26 | return -1 27 | 28 | 29 | # Test array 30 | arr = [ 2, 3, 4, 10, 40 ] 31 | x = 10 32 | 33 | # Function call 34 | result = binary_search(arr, x) 35 | 36 | if result != -1: 37 | print("Element is present at index", str(result)) 38 | else: 39 | print("Element is not present in array") 40 | -------------------------------------------------------------------------------- /dijkstra.py: -------------------------------------------------------------------------------- 1 | import heapq 2 | 3 | def dijkstra(graph, source): 4 | distances = {node: float('inf') for node in graph} 5 | distances[source] = 0 6 | queue = [(0, source)] 7 | while queue: 8 | current_distance, current_node = heapq.heappop(queue) 9 | if current_distance > distances[current_node]: 10 | continue 11 | for neighbor, weight in graph[current_node].items(): 12 | distance = current_distance + weight 13 | if distance < distances[neighbor]: 14 | distances[neighbor] = distance 15 | heapq.heappush(queue, (distance, neighbor)) 16 | return distances 17 | 18 | def create_graph(): 19 | graph = {} 20 | nodes = int(input("Enter the number of nodes in the graph: ")) 21 | for i in range(nodes): 22 | node = input(f"Enter the label of node {i + 1}: ") 23 | graph[node] = {} 24 | while True: 25 | try: 26 | edges = int(input(f"Enter the number of edges for node {node}: ")) 27 | break 28 | except ValueError: 29 | print("Please enter a valid integer.") 30 | for j in range(edges): 31 | while True: 32 | try: 33 | neighbor, weight = input(f"Enter the neighbor and weight for edge {j + 1} (format: neighbor weight): ").split() 34 | graph[node][neighbor] = int(weight) 35 | break 36 | except ValueError: 37 | print("Please enter valid neighbor and weight values.") 38 | return graph 39 | 40 | if __name__ == "__main__": 41 | graph = create_graph() 42 | source_node = input("Enter the source node: ") 43 | result = dijkstra(graph, source_node) 44 | print(f"Shortest distances from source node {source_node}: {result}") 45 | -------------------------------------------------------------------------------- /find-factorial/database.py: -------------------------------------------------------------------------------- 1 | # Incomplete program 2 | 3 | from tkinter import * 4 | from PIL import ImageTk, Image 5 | import sqlite3 as sql 6 | 7 | root = Tk() 8 | root.title('Slider') 9 | #root.iconbitmap() 10 | root.geometry("640x480") 11 | 12 | # Create or connect to a database 13 | conn = sql.connect("address.db") 14 | # Cursor 15 | cur = conn.cursor() 16 | 17 | # Creating table 18 | 19 | # cur.execute("""CREATE TABLE address( 20 | # first_name text, 21 | # last_name text, 22 | # address text, 23 | # city text, 24 | # state text, 25 | # zipcode text 26 | 27 | # )""") 28 | 29 | def submit(): 30 | # Create or connect to a database 31 | conn = sql.connect("address.db") 32 | # Cursor 33 | cur = conn.cursor() 34 | 35 | # Insert the data 36 | cur.execute("INSERT INTO addresses VALUES (:nam, :lst, :add, :cty, :ste, :zip)") 37 | { 38 | 'nam':nam.get(), 39 | 'lst':lst.get(), 40 | 'add':add.get(), 41 | 'cty':cty.get(), 42 | 'ste':ste.get(), 43 | 'zip':zip.get() 44 | } 45 | 46 | #Commit Changes 47 | conn.commit() 48 | # Close connections 49 | conn.close() 50 | 51 | #clear text boxes 52 | nam.delete(0,END) 53 | lst.delete(0,END) 54 | add.delete(0,END) 55 | cty.delete(0,END) 56 | ste.delete(0,END) 57 | zip.delete(0,END) 58 | 59 | def query(): 60 | # Create or connect to a database 61 | conn = sql.connect("address.db") 62 | # Cursor 63 | cur = conn.cursor() 64 | 65 | 66 | #Commit Changes 67 | conn.commit() 68 | # Close connections 69 | conn.close() 70 | 71 | 72 | 73 | # Creating text box 74 | nam = Entry(root, width=10) 75 | nam.grid(row=0, column=1, padx=20) 76 | lst = Entry(root, width=10) 77 | lst.grid(row=1, column=1, padx=20) 78 | add = Entry(root, width=10) 79 | add.grid(row=2, column=1, padx=20) 80 | cty = Entry(root, width=10) 81 | cty.grid(row=3, column=1, padx=20) 82 | ste = Entry(root, width=10) 83 | ste.grid(row=4, column=1, padx=20) 84 | zip = Entry(root, width=10) 85 | zip.grid(row=5, column=1, padx=20) 86 | 87 | Label(root, text="First Name").grid(row=0, column=0) 88 | Label(root, text="last Name").grid(row=1, column=0) 89 | Label(root, text="address").grid(row=2, column=0) 90 | Label(root, text="city").grid(row=3, column=0) 91 | Label(root, text="state").grid(row=4, column=0) 92 | Label(root, text="zipcode").grid(row=5, column=0) 93 | 94 | btn = Button(root, text="Add Data", command=submit).grid(row=6 ,column=0, columnspan=2, pady=10 ,padx=10, ipadx=100) 95 | 96 | qbtn = Button(root, text="Show Recocrd", command=query).grid(row=7 ,column=0, columnspan=2, pady=10 ,padx=10, ipadx=137) 97 | 98 | #Commit Changes 99 | conn.commit() 100 | 101 | # Close connections 102 | conn.close() 103 | 104 | root.mainloop() 105 | -------------------------------------------------------------------------------- /find-factorial/find-factorial.py: -------------------------------------------------------------------------------- 1 | # Function to find prime factors of a number 2 | def primeFactors(n): 3 | factors = {} 4 | i = 2 5 | while i*i <= n: 6 | while n % i == 0: 7 | if i not in factors: 8 | factors[i] = 0 9 | factors[i] += 1 10 | n //= i 11 | i += 1 12 | if n > 1: 13 | if n not in factors: 14 | factors[n] = 0 15 | factors[n] += 1 16 | return factors 17 | 18 | # Function to find factorial of a number 19 | def factorial(n): 20 | result = 1 21 | for i in range(2, n+1): 22 | factors = primeFactors(i) 23 | for p in factors: 24 | result *= p ** factors[p] 25 | return result 26 | 27 | # Driver Code 28 | num = 7 29 | print("Factorial of", num, "is", factorial(num)) 30 | -------------------------------------------------------------------------------- /mini_projects/rockpaperscissors.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | options = ("Rock","Paper","Scissors") 4 | user = None 5 | computer = random.choice(options).capitalize() 6 | playing = True 7 | 8 | while playing: 9 | user = None 10 | while user not in options: 11 | user=input("rock/paper/scissors??").capitalize() 12 | 13 | 14 | print("---------------------------------- ") 15 | 16 | print(f"player,s choice:{user}") 17 | print(f"computer's choice:{computer}") 18 | 19 | if computer == user: 20 | print("Draw") 21 | elif (computer=="Rock" and user=="Paper") or (computer=="Paper" and user=="Scissors") or (computer=="Scissors" and user=="Rock"): 22 | print("You won!!!") 23 | 24 | else : 25 | print("you lose!!!") 26 | 27 | again = input("Want to play again??(y/n)").lower() 28 | if not again == "y": 29 | playing=False 30 | 31 | print("Thanks for playing!!") 32 | 33 | 34 | -------------------------------------------------------------------------------- /mini_projects/snake_game.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import random 3 | 4 | GAME_WIDTH = 700 5 | GAME_HEIGHT = 700 6 | SPEED = 100 7 | SPACE_SIZE = 50 8 | BODY_PARTS = 3 9 | SNAKE_COLOR = "#00FF00" 10 | FOOD_COLOR = "#FF0000" 11 | BACKGROUND_COLOR = "#000000" 12 | 13 | 14 | class Snake: 15 | 16 | def __init__(self): 17 | self.body_size = BODY_PARTS 18 | self.coordinates = [] 19 | self.squares = [] 20 | 21 | for i in range(0, BODY_PARTS): 22 | self.coordinates.append([0, 0]) 23 | 24 | for x, y in self.coordinates: 25 | square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR, tag="snake") 26 | self.squares.append(square) 27 | 28 | 29 | class Food: 30 | 31 | def __init__(self): 32 | 33 | x = random.randint(0, (GAME_WIDTH / SPACE_SIZE)-1) * SPACE_SIZE 34 | y = random.randint(0, (GAME_HEIGHT / SPACE_SIZE) - 1) * SPACE_SIZE 35 | 36 | self.coordinates = [x, y] 37 | 38 | canvas.create_oval(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=FOOD_COLOR, tag="food") 39 | 40 | 41 | def next_turn(snake, food): 42 | 43 | x, y = snake.coordinates[0] 44 | 45 | if direction == "up": 46 | y -= SPACE_SIZE 47 | elif direction == "down": 48 | y += SPACE_SIZE 49 | elif direction == "left": 50 | x -= SPACE_SIZE 51 | elif direction == "right": 52 | x += SPACE_SIZE 53 | 54 | snake.coordinates.insert(0, (x, y)) 55 | 56 | square = canvas.create_rectangle(x, y, x + SPACE_SIZE, y + SPACE_SIZE, fill=SNAKE_COLOR) 57 | 58 | snake.squares.insert(0, square) 59 | 60 | if x == food.coordinates[0] and y == food.coordinates[1]: 61 | 62 | global score 63 | 64 | score += 1 65 | 66 | label.config(text="Score:{}".format(score)) 67 | 68 | canvas.delete("food") 69 | 70 | food = Food() 71 | 72 | else: 73 | 74 | del snake.coordinates[-1] 75 | 76 | canvas.delete(snake.squares[-1]) 77 | 78 | del snake.squares[-1] 79 | 80 | if check_collisions(snake): 81 | game_over() 82 | 83 | else: 84 | window.after(SPEED, next_turn, snake, food) 85 | 86 | 87 | def change_direction(new_direction): 88 | 89 | global direction 90 | 91 | if new_direction == 'left': 92 | if direction != 'right': 93 | direction = new_direction 94 | elif new_direction == 'right': 95 | if direction != 'left': 96 | direction = new_direction 97 | elif new_direction == 'up': 98 | if direction != 'down': 99 | direction = new_direction 100 | elif new_direction == 'down': 101 | if direction != 'up': 102 | direction = new_direction 103 | 104 | 105 | def check_collisions(snake): 106 | 107 | x, y = snake.coordinates[0] 108 | 109 | if x < 0 or x >= GAME_WIDTH: 110 | return True 111 | elif y < 0 or y >= GAME_HEIGHT: 112 | return True 113 | 114 | for body_part in snake.coordinates[1:]: 115 | if x == body_part[0] and y == body_part[1]: 116 | return True 117 | 118 | return False 119 | 120 | 121 | def game_over(): 122 | 123 | canvas.delete(ALL) 124 | canvas.create_text(canvas.winfo_width()/2, canvas.winfo_height()/2, 125 | font=('consolas',70), text="GAME OVER", fill="red", tag="gameover") 126 | 127 | 128 | window = Tk() 129 | window.title("Snake game") 130 | window.resizable(False, False) 131 | 132 | score = 0 133 | direction = 'down' 134 | 135 | label = Label(window, text="Score:{}".format(score), font=('consolas', 40)) 136 | label.pack() 137 | 138 | canvas = Canvas(window, bg=BACKGROUND_COLOR, height=GAME_HEIGHT, width=GAME_WIDTH) 139 | canvas.pack() 140 | 141 | window.update() 142 | 143 | window_width = window.winfo_width() 144 | window_height = window.winfo_height() 145 | screen_width = window.winfo_screenwidth() 146 | screen_height = window.winfo_screenheight() 147 | 148 | x = int((screen_width/2) - (window_width/2)) 149 | y = int((screen_height/2) - (window_height/2)) 150 | 151 | window.geometry(f"{window_width}x{window_height}+{x}+{y}") 152 | 153 | window.bind('', lambda event: change_direction('left')) 154 | window.bind('', lambda event: change_direction('right')) 155 | window.bind('', lambda event: change_direction('up')) 156 | window.bind('', lambda event: change_direction('down')) 157 | 158 | snake = Snake() 159 | food = Food() 160 | 161 | next_turn(snake, food) 162 | 163 | window.mainloop() -------------------------------------------------------------------------------- /mini_projects/tictactoe.py: -------------------------------------------------------------------------------- 1 | from tkinter import * 2 | import random 3 | 4 | def next_turn(row,column): 5 | 6 | global player 7 | if buttons[row][column]['text']=="" and check_winner() is False: 8 | 9 | if player == players[0]: 10 | buttons[row][column]['text']=player 11 | 12 | if check_winner() is False: 13 | player = players[1] 14 | label.config(text=(players[1]+" turn")) 15 | 16 | 17 | elif check_winner() is True: 18 | label.config(text=(players[0]+" wins")) 19 | 20 | elif check_winner() == "Tie": 21 | label.config(text=("Tie!!")) 22 | 23 | else: 24 | 25 | buttons[row][column]['text']=player 26 | 27 | if check_winner() is False: 28 | player = players[0] 29 | label.config(text=(players[0]+" turn")) 30 | 31 | 32 | elif check_winner() is True: 33 | label.cofig(text=(players[1]+" wins")) 34 | 35 | elif check_winner() == "Tie": 36 | label.config(text=("Tie!!")) 37 | 38 | 39 | 40 | def check_winner(): 41 | 42 | for row in range(3): 43 | if buttons[row][0]['text'] == buttons[row][1]['text'] == buttons[row][2]['text'] != "" : 44 | buttons[row][0].config(bg="green") 45 | buttons[row][1].config(bg="green") 46 | buttons[row][2].config(bg="green") 47 | return True 48 | 49 | for column in range(3): 50 | if buttons[0][column]['text'] == buttons[1][column]['text'] == buttons[2][column]['text'] != "" : 51 | buttons[0][column].config(bg="green") 52 | buttons[1][column].config(bg="green") 53 | buttons[2][column].config(bg="green") 54 | return True 55 | 56 | if buttons[0][0]['text'] == buttons[1][1]['text'] == buttons[2][2]['text'] != "": 57 | buttons[0][0].config(bg="green") 58 | buttons[1][1].config(bg="green") 59 | buttons[2][2].config(bg="green") 60 | return True 61 | 62 | elif buttons[0][2]['text'] == buttons[1][1]['text'] == buttons[2][0]['text'] != "": 63 | buttons[0][2].config(bg="green") 64 | buttons[1][1].config(bg="green") 65 | buttons[2][0].config(bg="green") 66 | return True 67 | 68 | elif empty_spaces() is False: 69 | 70 | for row in range(3): 71 | for column in range(3): 72 | buttons[row][column].config(bg="yellow") 73 | return "Tie" 74 | 75 | else: 76 | return False 77 | 78 | 79 | def empty_spaces(): 80 | 81 | spaces = 9 82 | for row in range(3): 83 | for column in range(3): 84 | if buttons[row][column]['text'] != "": 85 | spaces -= 1 86 | 87 | if spaces == 0: 88 | return False 89 | else : 90 | return True 91 | 92 | 93 | 94 | 95 | def new_game(): 96 | 97 | global player 98 | 99 | player = random.choice(players) 100 | 101 | label.config(text=player+" turn") 102 | 103 | for row in range(3): 104 | for column in range(3): 105 | buttons[row][column].config(text="",bg="#F0F0F0") 106 | 107 | 108 | window = Tk() 109 | window.title("TIC-TAC-TOE") 110 | players=["X","O"] 111 | player=random.choice(players) 112 | buttons=[[0,0,0], 113 | [0,0,0], 114 | [0,0,0]] 115 | 116 | label = Label(text=player + " turn ", font=('consolas',40)) 117 | label.pack(side="top") 118 | 119 | reset_button=Button(text="restart" , font=('consolas',20) , command=new_game) 120 | reset_button.pack(side="top") 121 | 122 | frame = Frame(window) 123 | frame.pack() 124 | 125 | for row in range(3): 126 | for column in range(3): 127 | buttons[row][column] = Button(frame, text="", font=('consilas',40),width=5,height=2,command=lambda row=row,column=column: next_turn(row,column)) 128 | 129 | buttons[row][column].grid(row=row,column=column) 130 | 131 | 132 | 133 | 134 | window.mainloop() 135 | -------------------------------------------------------------------------------- /mini_projects/timer.py: -------------------------------------------------------------------------------- 1 | #countdowntimer 2 | import time 3 | 4 | timeinp = int(input("enter time for countdown in sec :")) 5 | 6 | for x in reversed(range(1,timeinp)): 7 | hour = int(x/3600) 8 | minutes = int(x/60)%60 9 | seconds = x % 60 10 | print(f"{hour:02}:{minutes:02}:{seconds:02}") 11 | time.sleep(1) 12 | 13 | print("TIME'S UP!!!") -------------------------------------------------------------------------------- /qr-code-generator/qr.py: -------------------------------------------------------------------------------- 1 | import qrcode 2 | import os 3 | 4 | def generate_qr_code(data, filename): 5 | qr = qrcode.QRCode( 6 | version=1, 7 | error_correction=qrcode.constants.ERROR_CORRECT_M, 8 | box_size=10, 9 | border=4, 10 | ) 11 | qr.add_data(data) 12 | qr.make(fit=True) 13 | 14 | img = qr.make_image(fill_color="black", back_color="white") 15 | os.makedirs("out", exist_ok=True) 16 | i = 1 17 | while True: 18 | filename = f"{filename_prefix}{i}.png" 19 | filepath = os.path.join("out", filename) 20 | if not os.path.exists(filepath): 21 | break 22 | i += 1 23 | img.save(filepath) 24 | print(f"A QR code has been generated and saved at out/ as `{filename}'") 25 | 26 | 27 | 28 | # Example usage 29 | data = input("URL: ") 30 | filename_prefix = "qr" 31 | generate_qr_code(data, filename_prefix) 32 | -------------------------------------------------------------------------------- /recommender-system/recommender_system.ipynb: -------------------------------------------------------------------------------- 1 | {"cells":[{"attachments":{},"cell_type":"markdown","metadata":{},"source":["# Recommender System"]},{"cell_type":"markdown","metadata":{},"source":["### 1.The main objective of this project is to create a recommender system that will give an idea about which items to recommend. \n","### 2.The goal is to find popular items - globally, country-wise and month-wise and to recommmend items based on estimated ratings and user ratings."]},{"cell_type":"markdown","metadata":{},"source":["### Import the necessary libraries."]},{"cell_type":"code","execution_count":1,"metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.execute_input":"2023-03-13T16:42:41.577605Z","iopub.status.busy":"2023-03-13T16:42:41.577054Z","iopub.status.idle":"2023-03-13T16:42:41.769226Z","shell.execute_reply":"2023-03-13T16:42:41.768005Z","shell.execute_reply.started":"2023-03-13T16:42:41.577506Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["/kaggle/input/onlineretail/OnlineRetail.xlsx\n"]}],"source":["# This Python 3 environment comes with many helpful analytics libraries installed\n","# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n","# For example, here's several helpful packages to load\n","import pandas as pd\n","import numpy as np # linear algebra\n","import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n","import matplotlib.pyplot as plt\n","from surprise import SVD\n","from surprise import Dataset\n","from surprise import Reader\n","\n","from mlxtend.frequent_patterns import apriori, association_rules\n","\n","# Input data files are available in the read-only \"../input/\" directory\n","# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n","\n","import os\n","for dirname, _, filenames in os.walk('/kaggle/input'):\n"," for filename in filenames:\n"," print(os.path.join(dirname, filename))\n","\n","# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n","# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session"]},{"cell_type":"markdown","metadata":{},"source":["### Load the dataset "]},{"cell_type":"code","execution_count":2,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:42:41.771729Z","iopub.status.busy":"2023-03-13T16:42:41.771357Z","iopub.status.idle":"2023-03-13T16:44:37.015169Z","shell.execute_reply":"2023-03-13T16:44:37.013635Z","shell.execute_reply.started":"2023-03-13T16:42:41.771697Z"},"trusted":true},"outputs":[],"source":["df = pd.read_excel('/kaggle/input/onlineretail/OnlineRetail.xlsx')\n"]},{"cell_type":"code","execution_count":3,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.017336Z","iopub.status.busy":"2023-03-13T16:44:37.016679Z","iopub.status.idle":"2023-03-13T16:44:37.095568Z","shell.execute_reply":"2023-03-13T16:44:37.094159Z","shell.execute_reply.started":"2023-03-13T16:44:37.017299Z"},"trusted":true},"outputs":[],"source":["df = df.loc[df['Quantity'] > 0]"]},{"cell_type":"markdown","metadata":{},"source":["### Displaying the dataset"]},{"cell_type":"code","execution_count":4,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.098778Z","iopub.status.busy":"2023-03-13T16:44:37.098275Z","iopub.status.idle":"2023-03-13T16:44:37.259991Z","shell.execute_reply":"2023-03-13T16:44:37.258686Z","shell.execute_reply.started":"2023-03-13T16:44:37.098743Z"},"trusted":true},"outputs":[{"data":{"text/html":["
\n","\n","\n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n"," \n","
InvoiceNoStockCodeDescriptionQuantityInvoiceDateUnitPriceCustomerIDCountry
0536365.085123AWHITE HANGING HEART T-LIGHT HOLDER6.02010-12-01 08:26:002.5517850.0United Kingdom
1536365.071053.0WHITE METAL LANTERN6.02010-12-01 08:26:003.3917850.0United Kingdom
2536365.084406BCREAM CUPID HEARTS COAT HANGER8.02010-12-01 08:26:002.7517850.0United Kingdom
3536365.084029GKNITTED UNION FLAG HOT WATER BOTTLE6.02010-12-01 08:26:003.3917850.0United Kingdom
4536365.084029ERED WOOLLY HOTTIE WHITE HEART.6.02010-12-01 08:26:003.3917850.0United Kingdom
5536365.022752.0SET 7 BABUSHKA NESTING BOXES2.02010-12-01 08:26:007.6517850.0United Kingdom
6536365.021730.0GLASS STAR FROSTED T-LIGHT HOLDER6.02010-12-01 08:26:004.2517850.0United Kingdom
7536366.022633.0HAND WARMER UNION JACK6.02010-12-01 08:28:001.8517850.0United Kingdom
8536366.022632.0HAND WARMER RED POLKA DOT6.02010-12-01 08:28:001.8517850.0United Kingdom
9536367.084879.0ASSORTED COLOUR BIRD ORNAMENT32.02010-12-01 08:34:001.6913047.0United Kingdom
\n","
"],"text/plain":[" InvoiceNo StockCode Description Quantity \\\n","0 536365.0 85123A WHITE HANGING HEART T-LIGHT HOLDER 6.0 \n","1 536365.0 71053.0 WHITE METAL LANTERN 6.0 \n","2 536365.0 84406B CREAM CUPID HEARTS COAT HANGER 8.0 \n","3 536365.0 84029G KNITTED UNION FLAG HOT WATER BOTTLE 6.0 \n","4 536365.0 84029E RED WOOLLY HOTTIE WHITE HEART. 6.0 \n","5 536365.0 22752.0 SET 7 BABUSHKA NESTING BOXES 2.0 \n","6 536365.0 21730.0 GLASS STAR FROSTED T-LIGHT HOLDER 6.0 \n","7 536366.0 22633.0 HAND WARMER UNION JACK 6.0 \n","8 536366.0 22632.0 HAND WARMER RED POLKA DOT 6.0 \n","9 536367.0 84879.0 ASSORTED COLOUR BIRD ORNAMENT 32.0 \n","\n"," InvoiceDate UnitPrice CustomerID Country \n","0 2010-12-01 08:26:00 2.55 17850.0 United Kingdom \n","1 2010-12-01 08:26:00 3.39 17850.0 United Kingdom \n","2 2010-12-01 08:26:00 2.75 17850.0 United Kingdom \n","3 2010-12-01 08:26:00 3.39 17850.0 United Kingdom \n","4 2010-12-01 08:26:00 3.39 17850.0 United Kingdom \n","5 2010-12-01 08:26:00 7.65 17850.0 United Kingdom \n","6 2010-12-01 08:26:00 4.25 17850.0 United Kingdom \n","7 2010-12-01 08:28:00 1.85 17850.0 United Kingdom \n","8 2010-12-01 08:28:00 1.85 17850.0 United Kingdom \n","9 2010-12-01 08:34:00 1.69 13047.0 United Kingdom "]},"execution_count":4,"metadata":{},"output_type":"execute_result"}],"source":["df.head(10)"]},{"cell_type":"markdown","metadata":{},"source":["### List of Countries available in the dataset"]},{"cell_type":"code","execution_count":5,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.262196Z","iopub.status.busy":"2023-03-13T16:44:37.261668Z","iopub.status.idle":"2023-03-13T16:44:37.328181Z","shell.execute_reply":"2023-03-13T16:44:37.326846Z","shell.execute_reply.started":"2023-03-13T16:44:37.262144Z"},"trusted":true},"outputs":[{"data":{"text/plain":["Country \n","United Kingdom 486286\n","Germany 9042\n","France 8408\n","EIRE 7894\n","Spain 2485\n","Netherlands 2363\n","Belgium 2031\n","Switzerland 1967\n","Portugal 1501\n","Australia 1185\n","Norway 1072\n","Italy 758\n","Channel Islands 748\n","Finland 685\n","Cyprus 614\n","Sweden 451\n","Unspecified 446\n","Austria 398\n","Denmark 380\n","Poland 330\n","Japan 321\n","Israel 295\n","Hong Kong 284\n","Singapore 222\n","Iceland 182\n","USA 179\n","Canada 151\n","Greece 145\n","Malta 112\n","United Arab Emirates 68\n","European Community 60\n","RSA 58\n","Lebanon 45\n","Lithuania 35\n","Brazil 32\n","Czech Republic 25\n","Bahrain 18\n","Saudi Arabia 9\n","dtype: int64"]},"execution_count":5,"metadata":{},"output_type":"execute_result"}],"source":["df.value_counts(['Country'])"]},{"cell_type":"code","execution_count":6,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.330622Z","iopub.status.busy":"2023-03-13T16:44:37.330138Z","iopub.status.idle":"2023-03-13T16:44:37.393409Z","shell.execute_reply":"2023-03-13T16:44:37.391382Z","shell.execute_reply.started":"2023-03-13T16:44:37.330572Z"},"trusted":true},"outputs":[{"data":{"text/plain":["InvoiceDate \n","2011-10-31 14:41:00 1114\n","2011-12-08 09:28:00 749\n","2011-12-09 10:03:00 731\n","2011-12-05 17:24:00 721\n","2011-06-29 15:58:00 705\n"," ... \n","2011-02-08 12:41:00 1\n","2011-11-09 12:25:00 1\n","2011-02-08 12:15:00 1\n","2011-05-31 10:38:00 1\n","2011-07-14 16:39:00 1\n","Length: 19052, dtype: int64"]},"execution_count":6,"metadata":{},"output_type":"execute_result"}],"source":["df.value_counts(['InvoiceDate'])"]},{"cell_type":"markdown","metadata":{},"source":["### Drop the Null values"]},{"cell_type":"code","execution_count":7,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.397066Z","iopub.status.busy":"2023-03-13T16:44:37.395360Z","iopub.status.idle":"2023-03-13T16:44:37.555502Z","shell.execute_reply":"2023-03-13T16:44:37.553987Z","shell.execute_reply.started":"2023-03-13T16:44:37.396976Z"},"trusted":true},"outputs":[],"source":["df.dropna(inplace=True)"]},{"cell_type":"markdown","metadata":{},"source":["### Most popular items globally"]},{"cell_type":"code","execution_count":8,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.558846Z","iopub.status.busy":"2023-03-13T16:44:37.557622Z","iopub.status.idle":"2023-03-13T16:44:37.578042Z","shell.execute_reply":"2023-03-13T16:44:37.576632Z","shell.execute_reply.started":"2023-03-13T16:44:37.558793Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["Number of duplicates: 394058\n"]}],"source":["df1 = df['Description']\n","duplicates = df1.duplicated()\n","print(\"Number of duplicates:\", duplicates.sum())\n"]},{"cell_type":"code","execution_count":9,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.580953Z","iopub.status.busy":"2023-03-13T16:44:37.580461Z","iopub.status.idle":"2023-03-13T16:44:37.622940Z","shell.execute_reply":"2023-03-13T16:44:37.621586Z","shell.execute_reply.started":"2023-03-13T16:44:37.580882Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["Most popular items Globally:\n","WHITE HANGING HEART T-LIGHT HOLDER 2027\n","REGENCY CAKESTAND 3 TIER 1723\n","JUMBO BAG RED RETROSPOT 1617\n","ASSORTED COLOUR BIRD ORNAMENT 1407\n","PARTY BUNTING 1396\n","LUNCH BAG RED RETROSPOT 1315\n","SET OF 3 CAKE TINS PANTRY DESIGN 1158\n","LUNCH BAG BLACK SKULL. 1104\n","POSTAGE 1098\n","PACK OF 72 RETROSPOT CAKE CASES 1067\n","Name: Description, dtype: int64\n"]}],"source":["duplicated_rows = df1[duplicates]\n","most_common_duplicates = duplicated_rows.value_counts().head(10)\n","print(f\"Most popular items Globally:\\n{most_common_duplicates}\")"]},{"cell_type":"markdown","metadata":{},"source":["### The above result generates set of item descriptions that are most popular globally"]},{"cell_type":"markdown","metadata":{},"source":["### The next is to find the most popular item among countries"]},{"cell_type":"code","execution_count":10,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:44:37.627469Z","iopub.status.busy":"2023-03-13T16:44:37.627034Z","iopub.status.idle":"2023-03-13T16:48:44.366106Z","shell.execute_reply":"2023-03-13T16:48:44.364515Z","shell.execute_reply.started":"2023-03-13T16:44:37.627425Z"},"trusted":true},"outputs":[],"source":["most_popular_items = df.groupby(['Country'])['Description'].sum().sort_values(ascending=False).reset_index()\n"]},{"cell_type":"markdown","metadata":{},"source":["### Print the result"]},{"cell_type":"code","execution_count":11,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:44.368314Z","iopub.status.busy":"2023-03-13T16:48:44.367921Z","iopub.status.idle":"2023-03-13T16:48:44.419844Z","shell.execute_reply":"2023-03-13T16:48:44.418697Z","shell.execute_reply.started":"2023-03-13T16:48:44.368280Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":[" Country Description\n","0 United Kingdom WHITE HANGING HEART T-LIGHT HOLDERWHITE METAL ...\n","1 Cyprus WHITE HANGING HEART T-LIGHT HOLDERSPACE CADET ...\n","2 Portugal VINTAGE PAISLEY STATIONERY SETLUNCH BAG SUKI ...\n","3 Italy T-LIGHT GLASS FLUTED ANTIQUESCENTED VELVET LOU...\n","4 Japan SET OF 6 VINTAGE NOTELETS KITFANCY FONT BIRTHD...\n","5 Germany SET OF 6 T-LIGHTS SANTAROTATING SILVER ANGELS ...\n","6 USA SET OF 6 SPICE TINS PANTRY DESIGNPANTRY WASHIN...\n","7 Sweden SET OF 3 BABUSHKA STACKING TINSWORLD WAR 2 GLI...\n","8 Belgium SET OF 20 KIDS COOKIE CUTTERSRED RETROSPOT ROU...\n","9 Switzerland ROUND SNACK BOXES SET OF4 WOODLANDPLASTERS IN ...\n","10 Greece ROSES REGENCY TEACUP AND SAUCERGREEN REGENCY T...\n","11 EIRE ROSE COTTAGE KEEPSAKE BOXBLUE CHARLIE+LOLA PER...\n","12 United Arab Emirates RETROSPOT HEART HOT WATER BOTTLEDOORMAT UNION ...\n","13 Brazil REGENCY CAKESTAND 3 TIERROSES REGENCY TEACUP A...\n","14 RSA RED RETROSPOT CUPPINK POLKADOT PLATESET OF 4 ...\n","15 Poland RED HANGING HEART T-LIGHT HOLDERSTRAWBERRY CER...\n","16 Lithuania MONEY BOX BISCUITS DESIGNRED HARMONICA IN BOX...\n","17 Spain LUNCH BAG SUKI DESIGNLUNCH BAG PINK POLKADOTL...\n","18 Lebanon LAUNDRY 15C METAL SIGNBEWARE OF THE CAT METAL ...\n","19 Malta LANTERN CREAM GAZEBOWHITE HANGING HEART T-LIGH...\n","20 Israel HOOK, 1 HANGER ,MAGIC GARDEN3 HOOK HANGER MAGI...\n","21 Netherlands HAND WARMER BIRD DESIGNPOSTAGEPACK OF 12 WOODL...\n","22 Bahrain GROW A FLYTRAP OR SUNFLOWER IN TINICE CREAM SU...\n","23 Singapore GIN & TONIC DIET GREETING CARDGREEN REGENCY TE...\n","24 Unspecified DOORMAT RED RETROSPOTDOORMAT WELCOME SUNRISEDO...\n"]}],"source":["print(most_popular_items.head(25))"]},{"cell_type":"markdown","metadata":{},"source":["### The above result generates the most popular items for each country specifically"]},{"cell_type":"markdown","metadata":{},"source":["## **The below step is to find the most popular items - monthly wise**"]},{"cell_type":"code","execution_count":12,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:44.421871Z","iopub.status.busy":"2023-03-13T16:48:44.421375Z","iopub.status.idle":"2023-03-13T16:48:48.455639Z","shell.execute_reply":"2023-03-13T16:48:48.454633Z","shell.execute_reply.started":"2023-03-13T16:48:44.421831Z"},"trusted":true},"outputs":[],"source":["df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])\n","\n","\n","df['date_new'] = df.InvoiceDate.dt.strftime('%Y-%m')\n","top_items_monthly = []\n","for month in df.date_new.unique():\n"," trans_month = df.loc[df.date_new == month]\n"," trans_month = (trans_month.groupby(['InvoiceNo', 'Description'])['Quantity']\n"," .sum().unstack().reset_index().fillna(0)\n"," .set_index('InvoiceNo'))"]},{"cell_type":"code","execution_count":13,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:48.458586Z","iopub.status.busy":"2023-03-13T16:48:48.457304Z","iopub.status.idle":"2023-03-13T16:48:49.448603Z","shell.execute_reply":"2023-03-13T16:48:49.447537Z","shell.execute_reply.started":"2023-03-13T16:48:48.458535Z"},"trusted":true},"outputs":[],"source":["\n","trans_month[trans_month >= 1] = True\n","trans_month[trans_month.isna()] = False "]},{"cell_type":"code","execution_count":14,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:49.450952Z","iopub.status.busy":"2023-03-13T16:48:49.450238Z","iopub.status.idle":"2023-03-13T16:48:50.370238Z","shell.execute_reply":"2023-03-13T16:48:50.368851Z","shell.execute_reply.started":"2023-03-13T16:48:49.450906Z"},"trusted":true},"outputs":[],"source":["import warnings\n","warnings.filterwarnings('ignore')\n","frequent_itemsets = apriori(trans_month, min_support=0.03,use_colnames=True)\n"]},{"cell_type":"markdown","metadata":{},"source":["### Using the **association rules** method"]},{"cell_type":"code","execution_count":15,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:50.372084Z","iopub.status.busy":"2023-03-13T16:48:50.371657Z","iopub.status.idle":"2023-03-13T16:48:50.387618Z","shell.execute_reply":"2023-03-13T16:48:50.385928Z","shell.execute_reply.started":"2023-03-13T16:48:50.372043Z"},"trusted":true},"outputs":[],"source":["associationRules = association_rules(frequent_itemsets, metric=\"lift\", min_threshold=1)\n","\n","top_k = associationRules.sort_values(by=['support'],ascending=False).iloc[:10][['antecedents','support']].reset_index(drop=True)\n","\n","top_items_monthly.append((month, top_k))"]},{"cell_type":"markdown","metadata":{},"source":["### **Using Pivot**"]},{"cell_type":"code","execution_count":16,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:50.389637Z","iopub.status.busy":"2023-03-13T16:48:50.389205Z","iopub.status.idle":"2023-03-13T16:48:52.561281Z","shell.execute_reply":"2023-03-13T16:48:52.559766Z","shell.execute_reply.started":"2023-03-13T16:48:50.389601Z"},"trusted":true},"outputs":[],"source":["pivot_dfs = []\n","for i, montly_pairs in enumerate(top_items_monthly):\n"," month, data = montly_pairs\n"," inv_map = {k: v for k, v in enumerate(data.antecedents)}\n"," rows = []\n"," for index, row in df.loc[(df.date_new == month)].iterrows():\n"," keys = [inv_map[k] for tup in str(row['Description']).split(',') for k,v in inv_map.items() if str(row['Description']) in list(v)]\n"," for key in keys:\n"," rows.append([month, key])\n"," pivot_df = pd.DataFrame(rows, columns=['month','Item'])\n"," pivot_df.head()\n"," pivot_dfs.append(pivot_df.pivot_table(values=[\"Item\"],index=[\"month\"],aggfunc=\"count\",fill_value=0))\n"]},{"cell_type":"markdown","metadata":{},"source":["### The below code displays the most popular items- monthly wise"]},{"cell_type":"code","execution_count":17,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:52.563098Z","iopub.status.busy":"2023-03-13T16:48:52.562669Z","iopub.status.idle":"2023-03-13T16:48:52.862431Z","shell.execute_reply":"2023-03-13T16:48:52.860618Z","shell.execute_reply.started":"2023-03-13T16:48:52.563060Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["Month: December 2010\n","InvoiceDate Description \n","2010-12-31 WHITE HANGING HEART T-LIGHT HOLDER 207\n"," HAND WARMER BABUSHKA DESIGN 142\n"," PAPER CHAIN KIT 50'S CHRISTMAS 141\n"," REGENCY CAKESTAND 3 TIER 141\n"," SCOTTIE DOG HOT WATER BOTTLE 132\n"," ... \n"," WRAP, BILLBOARD FONTS DESIGN 2\n"," YELLOW BREAKFAST CUP AND SAUCER 2\n"," YELLOW GIANT GARDEN THERMOMETER 2\n"," YELLOW METAL CHICKEN HEART 2\n"," ZINC HEART LATTICE T-LIGHT HOLDER 2\n","Name: Description, Length: 1953, dtype: int64\n","Month: January 2011\n","InvoiceDate Description \n","2011-01-31 WHITE HANGING HEART T-LIGHT HOLDER 160\n"," SET OF 3 CAKE TINS PANTRY DESIGN 133\n"," HEART OF WICKER SMALL 120\n"," REGENCY CAKESTAND 3 TIER 109\n"," SET OF 3 HEART COOKIE CUTTERS 97\n"," ... \n"," WOODLAND STORAGE BOX SMALL 2\n"," WRAP DAISY CARPET 2\n"," WRAP, CAROUSEL 2\n"," YELLOW POT PLANT CANDLE 2\n"," ZINC HEART LATTICE 2 WALL PLANTER 2\n","Name: Description, Length: 1706, dtype: int64\n","Month: February 2011\n","InvoiceDate Description \n","2011-02-28 SET OF 3 CAKE TINS PANTRY DESIGN 129\n"," WHITE HANGING HEART T-LIGHT HOLDER 127\n"," REGENCY CAKESTAND 3 TIER 111\n"," HEART OF WICKER SMALL 93\n"," SET OF 6 SPICE TINS PANTRY DESIGN 89\n"," ... \n"," WICKER WREATH LARGE 2\n"," WOODLAND HEIGHT CHART STICKERS 2\n"," WOODLAND STORAGE BOX LARGE 2\n"," YELLOW FLOWERS FELT HANDBAG KIT 2\n"," ZINC HEART LATTICE CHARGER LARGE 2\n","Name: Description, Length: 1676, dtype: int64\n","Month: March 2011\n","InvoiceDate Description \n","2011-03-31 WHITE HANGING HEART T-LIGHT HOLDER 171\n"," REGENCY CAKESTAND 3 TIER 168\n"," SET OF 3 CAKE TINS PANTRY DESIGN 156\n"," SET OF 4 PANTRY JELLY MOULDS 131\n"," PARTY BUNTING 127\n"," ... \n"," WINE BOTTLE DRESSING LT.BLUE 2\n"," WRAP BILLBOARD FONTS DESIGN 2\n"," WRAP MONSTER FUN 2\n"," WRAP WEDDING DAY 2\n"," ZINC HEART LATTICE TRAY OVAL 2\n","Name: Description, Length: 1855, dtype: int64\n","Month: April 2011\n","InvoiceDate Description \n","2011-04-30 PARTY BUNTING 163\n"," WHITE HANGING HEART T-LIGHT HOLDER 158\n"," REGENCY CAKESTAND 3 TIER 157\n"," PAPER CHAIN KIT EMPIRE 137\n"," ASSORTED COLOUR BIRD ORNAMENT 110\n"," ... \n"," YELLOW POT PLANT CANDLE 2\n"," YELLOW SHARK HELICOPTER 2\n"," YELLOW/ORANGE FLOWER DESIGN PLATE 2\n"," YULETIDE IMAGES GIFT WRAP SET 2\n"," ZINC HEART LATTICE CHARGER LARGE 2\n","Name: Description, Length: 1769, dtype: int64\n","Month: May 2011\n","InvoiceDate Description \n","2011-05-31 PARTY BUNTING 212\n"," SPOTTY BUNTING 210\n"," WHITE HANGING HEART T-LIGHT HOLDER 199\n"," REGENCY CAKESTAND 3 TIER 171\n"," LUNCH BAG APPLE DESIGN 154\n"," ... \n"," WRAP DAISY CARPET 2\n"," YELLOW BREAKFAST CUP AND SAUCER 2\n"," YELLOW SHARK HELICOPTER 2\n"," YELLOW/PINK FLOWER DESIGN BIG MUG 2\n"," ZINC WIRE SWEETHEART LETTER TRAY 2\n","Name: Description, Length: 1800, dtype: int64\n","Month: June 2011\n","InvoiceDate Description \n","2011-06-30 PARTY BUNTING 180\n"," SPOTTY BUNTING 153\n"," LUNCH BAG DOILEY PATTERN 137\n"," JUMBO BAG DOILEY PATTERNS 135\n"," JUMBO BAG RED RETROSPOT 128\n"," ... \n"," WRAP DAISY CARPET 2\n"," WRAP MONSTER FUN 2\n"," ZINC FOLKART SLEIGH BELLS 2\n"," ZINC HEART LATTICE CHARGER LARGE 2\n"," ZINC WIRE SWEETHEART LETTER TRAY 2\n","Name: Description, Length: 1921, dtype: int64\n","Month: July 2011\n","InvoiceDate Description \n","2011-07-31 PARTY BUNTING 158\n"," SPOTTY BUNTING 154\n"," LUNCH BAG DOILEY PATTERN 148\n"," WHITE HANGING HEART T-LIGHT HOLDER 147\n"," JUMBO BAG DOILEY PATTERNS 132\n"," ... \n"," WHITE GOOSE FEATHER TREE 60CM 2\n"," WHITE HONEYCOMB PAPER GARLAND 2\n"," WOODLAND STICKERS 2\n"," YELLOW SHARK HELICOPTER 2\n"," ZINC SWEETHEART SOAP DISH 2\n","Name: Description, Length: 1979, dtype: int64\n","Month: August 2011\n","InvoiceDate Description \n","2011-08-31 JUMBO BAG RED RETROSPOT 158\n"," SPOTTY BUNTING 149\n"," LUNCH BAG RED RETROSPOT 138\n"," WHITE HANGING HEART T-LIGHT HOLDER 133\n"," PARTY BUNTING 126\n"," ... \n"," WRAP COWBOYS 2\n"," WRAP DAISY CARPET 2\n"," YOU'RE CONFUSING ME METAL SIGN 2\n"," ZINC HEART FLOWER T-LIGHT HOLDER 2\n"," ZINC HEART LATTICE CHARGER LARGE 2\n","Name: Description, Length: 1966, dtype: int64\n","Month: September 2011\n","InvoiceDate Description \n","2011-09-30 HOT WATER BOTTLE KEEP CALM 193\n"," JUMBO BAG RED RETROSPOT 186\n"," JUMBO BAG VINTAGE DOILY 170\n"," WHITE HANGING HEART T-LIGHT HOLDER 158\n"," PAPER CHAIN KIT 50'S CHRISTMAS 147\n"," ... \n"," WOVEN FROST CUSHION COVER 2\n"," WRAP CAROUSEL 2\n"," WRAP FOLK ART 2\n"," ZINC HEART LATTICE CHARGER LARGE 2\n"," ZINC HEARTS PLANT POT HOLDER 2\n","Name: Description, Length: 2197, dtype: int64\n","Month: October 2011\n","InvoiceDate Description \n","2011-10-31 PAPER CHAIN KIT 50'S CHRISTMAS 205\n"," HOT WATER BOTTLE KEEP CALM 179\n"," JUMBO BAG RED RETROSPOT 168\n"," REGENCY CAKESTAND 3 TIER 152\n"," WHITE HANGING HEART T-LIGHT HOLDER 150\n"," ... \n"," WRAP BAD HAIR DAY 2\n"," YELLOW POT PLANT CANDLE 2\n"," ZINC STAR T-LIGHT HOLDER 2\n"," ZINC HEART LATTICE T-LIGHT HOLDER 2\n"," ZINC SWEETHEART SOAP DISH 2\n","Name: Description, Length: 2372, dtype: int64\n","Month: November 2011\n","InvoiceDate Description \n","2011-11-30 RABBIT NIGHT LIGHT 466\n"," PAPER CHAIN KIT 50'S CHRISTMAS 359\n"," HOT WATER BOTTLE KEEP CALM 271\n"," PAPER CHAIN KIT VINTAGE CHRISTMAS 240\n"," WHITE HANGING HEART T-LIGHT HOLDER 238\n"," ... \n"," WHITE CHRISTMAS TREE 60CM 2\n"," WOVEN BUBBLE GUM CUSHION COVER 2\n"," WRAP A PRETTY THANK YOU 2\n"," WRAP DAISY CARPET 2\n"," YELLOW/PINK FLOWER DESIGN BIG MUG 2\n","Name: Description, Length: 2412, dtype: int64\n","Month: December 2011\n","InvoiceDate Description \n","2011-12-31 RABBIT NIGHT LIGHT 120\n"," PAPER CHAIN KIT 50'S CHRISTMAS 104\n"," HOT WATER BOTTLE KEEP CALM 82\n"," PAPER CHAIN KIT VINTAGE CHRISTMAS 75\n"," HAND WARMER OWL DESIGN 69\n"," ... \n"," WRAP SUKI AND FRIENDS 2\n"," ZINC STAR T-LIGHT HOLDER 2\n"," ZINC HEART FLOWER T-LIGHT HOLDER 2\n"," ZINC SWEETHEART WIRE LETTER RACK 2\n"," ZINC WIRE SWEETHEART LETTER TRAY 2\n","Name: Description, Length: 1782, dtype: int64\n"]}],"source":["\n","df['InvoiceDate'] = pd.to_datetime(df['InvoiceDate'])\n","df.set_index('InvoiceDate', inplace=True)\n","\n","monthly_df = df.groupby(pd.Grouper(freq='M'))['Description'].value_counts()\n","\n","repeated_products = monthly_df[monthly_df > 1]\n","\n","for month, counts in repeated_products.groupby(level=0):\n"," print(f\"Month: {month.strftime('%B %Y')}\")\n"," print(counts)\n"," "]},{"cell_type":"markdown","metadata":{},"source":["### **The following steps will be implementing the recommendation predictor using user ratings and estimated ratings.**"]},{"cell_type":"markdown","metadata":{},"source":["#### Create a new dataframe with attribute values"]},{"cell_type":"code","execution_count":18,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:52.864479Z","iopub.status.busy":"2023-03-13T16:48:52.864058Z","iopub.status.idle":"2023-03-13T16:48:52.931045Z","shell.execute_reply":"2023-03-13T16:48:52.929443Z","shell.execute_reply.started":"2023-03-13T16:48:52.864442Z"},"trusted":true},"outputs":[],"source":["df1 = df[['CustomerID', 'Description','StockCode', 'Quantity']]"]},{"cell_type":"markdown","metadata":{},"source":["#### Create a rating matrix with the help of pivot table."]},{"cell_type":"code","execution_count":19,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:52.932611Z","iopub.status.busy":"2023-03-13T16:48:52.932255Z","iopub.status.idle":"2023-03-13T16:48:55.317863Z","shell.execute_reply":"2023-03-13T16:48:55.316582Z","shell.execute_reply.started":"2023-03-13T16:48:52.932581Z"},"trusted":true},"outputs":[],"source":["ratings_matrix = df1.pivot_table(index=['CustomerID'], columns=['StockCode'], values='Quantity', fill_value=0)\n"]},{"cell_type":"markdown","metadata":{},"source":["#### The algorithm we will be using is **SVD()-> Single Value Decomposition**"]},{"cell_type":"code","execution_count":20,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:55.320160Z","iopub.status.busy":"2023-03-13T16:48:55.319475Z","iopub.status.idle":"2023-03-13T16:48:55.325843Z","shell.execute_reply":"2023-03-13T16:48:55.324584Z","shell.execute_reply.started":"2023-03-13T16:48:55.320103Z"},"trusted":true},"outputs":[],"source":["algo = SVD()\n"]},{"cell_type":"code","execution_count":21,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:55.328457Z","iopub.status.busy":"2023-03-13T16:48:55.327921Z","iopub.status.idle":"2023-03-13T16:48:55.797092Z","shell.execute_reply":"2023-03-13T16:48:55.795579Z","shell.execute_reply.started":"2023-03-13T16:48:55.328409Z"},"trusted":true},"outputs":[],"source":["\n","reader = Reader(rating_scale=(1, 5))\n","surprise_data = Dataset.load_from_df(df1[['CustomerID', 'StockCode', 'Quantity']], reader)"]},{"cell_type":"code","execution_count":22,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:48:55.798570Z","iopub.status.busy":"2023-03-13T16:48:55.798212Z","iopub.status.idle":"2023-03-13T16:49:10.852726Z","shell.execute_reply":"2023-03-13T16:49:10.850264Z","shell.execute_reply.started":"2023-03-13T16:48:55.798538Z"},"trusted":true},"outputs":[],"source":["\n","trainset = surprise_data.build_full_trainset()\n","testset = trainset.build_anti_testset()\n"]},{"cell_type":"markdown","metadata":{},"source":["#### Fit the algorithm"]},{"cell_type":"code","execution_count":23,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:49:10.856451Z","iopub.status.busy":"2023-03-13T16:49:10.855141Z","iopub.status.idle":"2023-03-13T16:49:38.694939Z","shell.execute_reply":"2023-03-13T16:49:38.693280Z","shell.execute_reply.started":"2023-03-13T16:49:10.856396Z"},"trusted":true},"outputs":[{"data":{"text/plain":[""]},"execution_count":23,"metadata":{},"output_type":"execute_result"}],"source":["algo.fit(trainset)"]},{"cell_type":"markdown","metadata":{},"source":["#### Make predictions using the test data that we found using the algorithm."]},{"cell_type":"code","execution_count":24,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:49:38.696792Z","iopub.status.busy":"2023-03-13T16:49:38.696409Z","iopub.status.idle":"2023-03-13T16:51:57.040712Z","shell.execute_reply":"2023-03-13T16:51:57.039309Z","shell.execute_reply.started":"2023-03-13T16:49:38.696750Z"},"trusted":true},"outputs":[],"source":["\n","predictions = algo.test(testset)"]},{"cell_type":"code","execution_count":25,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:51:57.043800Z","iopub.status.busy":"2023-03-13T16:51:57.043276Z","iopub.status.idle":"2023-03-13T16:52:09.993670Z","shell.execute_reply":"2023-03-13T16:52:09.992023Z","shell.execute_reply.started":"2023-03-13T16:51:57.043752Z"},"trusted":true},"outputs":[],"source":["\n","top_n = {}\n","for uid, iid, true_r, est, _ in predictions:\n"," if uid not in top_n.keys():\n"," top_n[uid] = [(iid, est)]\n"," else:\n"," top_n[uid].append((iid, est))"]},{"cell_type":"markdown","metadata":{},"source":["#### Drop the null values in the Columns = StockCode and Description as both holds the items that contains missing values and outliers."]},{"cell_type":"code","execution_count":26,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:52:09.995767Z","iopub.status.busy":"2023-03-13T16:52:09.995277Z","iopub.status.idle":"2023-03-13T16:52:10.166911Z","shell.execute_reply":"2023-03-13T16:52:10.165501Z","shell.execute_reply.started":"2023-03-13T16:52:09.995704Z"},"trusted":true},"outputs":[],"source":["\n","\n","df1.dropna(subset=[\"StockCode\", \"Description\"], inplace=True)\n","\n","descriptions = df1.groupby(\"StockCode\").first()[\"Description\"]\n","\n","\n","desc_dict = descriptions.to_dict()\n"]},{"cell_type":"markdown","metadata":{},"source":["### **The below code displays the predictions based on the recommended items.**"]},{"cell_type":"code","execution_count":27,"metadata":{"execution":{"iopub.execute_input":"2023-03-13T16:52:10.168770Z","iopub.status.busy":"2023-03-13T16:52:10.168406Z","iopub.status.idle":"2023-03-13T16:52:11.786848Z","shell.execute_reply":"2023-03-13T16:52:11.785505Z","shell.execute_reply.started":"2023-03-13T16:52:10.168739Z"},"trusted":true},"outputs":[{"name":"stdout","output_type":"stream","text":["Most Recommended Items (in number of recommendations):\n","\t Item ID: 84406B (\"CREAM CUPID HEARTS COAT HANGER\") recommended 4206 times\n","\t Item ID: 71053.0 (\"WHITE METAL LANTERN\") recommended 4190 times\n","\t Item ID: 84029G (\"KNITTED UNION FLAG HOT WATER BOTTLE\") recommended 4128 times\n","\t Item ID: 84029E (\"RED WOOLLY HOTTIE WHITE HEART.\") recommended 4111 times\n","\t Item ID: 85123A (\"WHITE HANGING HEART T-LIGHT HOLDER\") recommended 3483 times\n","\t Item ID: 22752.0 (\"SET 7 BABUSHKA NESTING BOXES\") recommended 1091 times\n","\t Item ID: 21730.0 (\"GLASS STAR FROSTED T-LIGHT HOLDER\") recommended 320 times\n","\t Item ID: 22633.0 (\"HAND WARMER UNION JACK\") recommended 69 times\n","\t Item ID: 22632.0 (\"HAND WARMER RED POLKA DOT\") recommended 29 times\n","\t Item ID: 22745.0 (\"POPPY'S PLAYHOUSE BEDROOM\") recommended 22 times\n","\t Item ID: 84879.0 (\"ASSORTED COLOUR BIRD ORNAMENT\") recommended 21 times\n","\t Item ID: 22748.0 (\"POPPY'S PLAYHOUSE KITCHEN\") recommended 7 times\n","\t Item ID: 22749.0 (\"FELTCRAFT PRINCESS CHARLOTTE DOLL\") recommended 6 times\n","\t Item ID: 21777.0 (\"RECIPE BOX WITH METAL HEART\") recommended 3 times\n","\t Item ID: 22310.0 (\"IVORY KNITTED MUG COSY\") recommended 3 times\n","\t Item ID: 22913.0 (\"RED COAT RACK PARIS FASHION\") recommended 2 times\n","\t Item ID: 84969.0 (\"BOX OF 6 ASSORTED COLOUR TEASPOONS\") recommended 2 times\n","\t Item ID: 21724.0 (\"PANDA AND BUNNIES STICKER SHEET\") recommended 1 times\n","\t Item ID: 22622.0 (\"BOX OF VINTAGE ALPHABET BLOCKS\") recommended 1 times\n"]}],"source":["global_top_n = {}\n","\n","for uid, user_ratings in top_n.items():\n"," user_ratings.sort(key=lambda x: x[1], reverse=True)\n"," global_top_n[uid] = []\n"," for iid, est_rating in user_ratings[:5]:\n"," if iid in desc_dict:\n"," global_top_n[uid].append((iid, desc_dict[iid]))\n","\n","all_items = [iid for uid in global_top_n for iid, desc in global_top_n[uid]]\n","item_counts = {iid: all_items.count(iid) for iid in set(all_items)}\n","\n","print(\"Most Recommended Items (in number of recommendations):\")\n","for item, count in sorted(item_counts.items(), key=lambda x: x[1], reverse=True):\n"," if item in desc_dict:\n"," desc = desc_dict[item]\n"," print(\"\\t\", \"Item ID:\", item, \"(\\\"\" + str(desc) + \"\\\")\", f\"recommended {count} times\") \n"]},{"cell_type":"code","execution_count":null,"metadata":{},"outputs":[],"source":[]}],"metadata":{"kernelspec":{"display_name":"Python 3","language":"python","name":"python3"},"language_info":{"codemirror_mode":{"name":"ipython","version":3},"file_extension":".py","mimetype":"text/x-python","name":"python","nbconvert_exporter":"python","pygments_lexer":"ipython3","version":"3.7.12"}},"nbformat":4,"nbformat_minor":4} 2 | --------------------------------------------------------------------------------