Search This Blog

Python Mail Merge Project - Automating Recipient Writing in a Letter


Project Description:
  1. Automates the recipient writing part in the same letter.
  2. Recipient names are given in a separate file named invited_names.txt
  3. A sample letter is given in a separate file named starting_letter.txt
  4. Code is to be written inside main.py whose purpose is to fetch the sample letter, replace the [name] in a sample letter with recipient names &  generate an individual letter following this naming convention: letter_for_{recipient_name}.txt
  5. The number of names given in invited_names.txt file generates a similar number of letters. Suppose, 5 names are given in invited_names.txt then, 5 letters will be generated.


Folder Structure:

Folder Structure

Output:






./Input/Letters/starting_letter.txt


./Input/Names/invited_names.txt


./Output/ReadyToSend/example.txt


main.py

Crossing the Turtle : Python Turtle Project for Beginners

 

Game Rules:

  1. One turtle of unique color can only move forward.
    • Neither left nor right. Turtle cannot even move backward.    
  2. Turtle has to save itself from the collision with cars.
  3. If crosses all the cars, its level increases & along with all the car's speed!
  4. Random count cars & each car of random color are coming from the left & right.
  5. The scoreboard is maintained for every level.

How the game looks like?


crossing the turtle -gif


main.py



player.py



car_manager.py



scoreboard.py

Blind 75 Must Do Leetcode Python 3 Solutions

Blind 75 Must Do Leetcode Python 3 Solutions

Hashing to Solutions:
  1. Two Sum
  2. Longest Substring Without Repeating Characters
  3. Longest Palindromic Substring
  4. Container With Most Water
  5. 3Sum
  6. Remove Nth Node From End of List
  7. Valid Parentheses
  8. Merge Two Sorted Lists
  9.  Merge k Sorted Lists
  10. Search in Rotated Sorted Array
  11. Combination Sum
  12. Rotate Image
  13. Group Anagrams
  14. Maximum Subarray
  15. Spiral Matrix
  16. Jump Game
  17. Merge Intervals
  18. Insert Interval
  19. Unique Paths
  20. Climbing Stairs
  21. Set Matrix Zeroes
  22. Minimum Window Substring
  23. Word Search
  24. Decode Ways
  25. Validate Binary Search Tree
  26. Same Tree
  27.  Binary Tree Level Order Traversal
  28. Maximum Depth of Binary Tree
  29. Construct Binary Tree from Preorder and Inorder Traversal
  30. Best Time to Buy and Sell Stock
  31. Binary Tree Maximum Path Sum
  32. Valid Palindrome
  33. Longest Consecutive Sequence
  34. Clone Graph
  35. Word Break
  36. Linked List Cycle
  37. Reorder List
  38. Maximum Product Subarray
  39. Find Minimum in Rotated Sorted Array
  40. Reverse Bits
  41. Number of 1 Bits
  42. House Robber
  43. Number of Islands
  44. Reverse Linked List
  45. Course Schedule
  46. Implement Trie (Prefix Tree)
  47. Design Add and Search Words Data Structure
  48. Word Search II
  49. House Robber II
  50. Contains Duplicate
  51. Invert Binary Tree
  52. Kth Smallest Element in a BST
  53.  Lowest Common Ancestor of a Binary Search Tree
  54. Lowest Common Ancestor of a Binary Tree
  55. Product of Array Except Self
  56. Valid Anagram
  57. Meeting Rooms
  58. Meeting Rooms II
  59. Graph Valid Tree
  60. Missing Number
  61. Alien Dictionary
  62. Encode and Decode Strings
  63. Find Median from Data Stream
  64. Longest Increasing Subsequence
  65. Coin Change
  66. Number of Connected Components in an Undirected Graph
  67. Counting Bits
  68. Top K Frequent Elements
  69. Sum of Two Integers
  70. Pacific Atlantic Water Flow
  71. Longest Repeating Character Replacement
  72. Non-overlapping Intervals
  73. Serialize and Deserialize BST
  74. Subtree of Another Tree
  75. Palindromic Substrings
  76. Longest Common Subsequence


 1. Two Sum

This code looks through a list to find two different numbers that add up to a specific target number. It does this by using two loops. The first loop starts at the beginning of the list. For each number in the first loop, the second loop looks at the numbers that come after it in the list. If it finds two numbers that add up to the target, it gives back their positions in the list.

Time Complexity: O(n^2)

This is because for each element in the list (and there are 'n' elements), we are potentially looking at every other element in the list to find a match (which in the worst case is 'n-1' other elements), resulting in 'n' times 'n-1' operations.

Space complexity: O(1)

This code only uses a fixed amount of extra space (for the indices), no matter how big the list gets.

  • Time Complexity: O(n + d) where n is the length of the input string and d is the number of characters in the input string alphabet. 
  • Space Complexity: O(d)

Counting Valleys - Hackerrank Solution

 Check out the counting valleys question here: Hackerrank question

The picturization of the problem:

Suppose the input is: UDDDUDUU

Then, 

Answer: Valley level is 1. Because hiker stepped this way only.

To solve this problem:

Initially, assumed U = 1, D = -1 & altitude=0

Then, iterated till total steps-1. Whenever altitude(height) that is sea level is 0 & the last step is 'U" I have incremented the valley by 1 (because valley level is considered only when hiker's last step is 'U" & at the sea level).

When all the elements are traversed it returned the final valley's value that's our final result.

Solution:

def countingValleys(steps, path):
    # Write your code here
    
    altitude = 0
    valley = 0
    dict = {
        "U": 1,
        "D": -1
    }

    for eachstep in range(steps):
        altitude += dict[path[eachstep]] # calculating hiker's each step

        if altitude == 0 and path[eachstep] == "U":
            valley += 1

    return valley

Sales by Match -Hackerrank solution

Check out the question here - Sales by Match


def sockMerchant(n, ar):

    pairs = 0

    for element in set(ar):
        pairs += ar.count(element) // 2
    
    return pairs

if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    n = int(input().strip())

    ar = list(map(int, input().rstrip().split()))

    result = sockMerchant(n, ar)

    fptr.write(str(result) + '\n')

    fptr.close()

How to show code on blogger / blogspot with a copy snippet button


To show copy code snippet button for any code. Do the following steps:

  1. Go to HTML View of blog post's editor.
  2. Paste the below lines inside HTML editor & replace the Your Actual Code with the desired code.
<textarea style="border-style: solid; border-width: 1px 1px 1px 20px; border-color: #4072a1; width: 100%; height: 321px; line-height: 16px; resize: none;" id="html1" readonly> Your Actual Code</textarea><div style="font-size:13px; font-family: comic sans ms; color: blue;"><button onclick="copyThis1()">Copy code snippet</button></div>
<script>
function copyThis1() {
  var copyText = document.getElementById("html1");
  copyText.select();
  copyText.setSelectionRange(0, 99999)
  document.execCommand("copy");
  alert("Code snippet copied to clipboard");
}
</script>



Turtle Race : Python Project for Beginners


Game Rules:

1. 5 turtles of unique colors compete against each other.

2. User gets a chance to guess which color turtle will win the race.

3. If the user's guess is right it says you've won otherwise you lose!


Few screenshots of the game:





CODE:

Doodle it: Imagine, Draw, Erase and Repeat - Python Project for Beginners


 Doodle it: Imagine, Draw, Erase and Repeat

In order to create this game first step is to know a way of being able to listen to things the user does, like when a user taps a specific key on the keyboard. And the code that allows us to do this are called  Event Listeners.

Go to python documentation > listen method()


It has a whole bunch of section-on-screen events, including listening to key presses or listening to a click or other things that you can listen to. So the important thing is this listen method.


This allows turtle screen to start listening and waiting for the events that the user might trigger, like tapping on a key.

So for this first thing, we'll be going to do is we'll import the turtle class and the screen class from the turtle module. And then, we'll use them to create our Ted the turtle, and also create a screen object.


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()


This is basically going to control the window when we run our code.
Now in order to start listening for events, we have to get hold of the screen object and then tell it to start listening.


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

screen.listen()


And once it starts listening, we have to bind a function that will be triggered when a particular key is pressed on the keyboard. Now, in order to bind a keystroke to an event in our code, we have to use an event listener.

So the one that we're going to be using is this onkey method. And you can see it expects a function with no arguments and also a key, like the 'a' key on your keyboard or a key symbol, so the space or up or down.



So I'm going to say screen.onkey and then I have to bind some sort of function to this method.

So let's create a function named ted_move_right and all that this function is going to do is it's going to get Ted to go forward by 10 paces. 


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

def ted_move_right():
    ted.forward(10)

screen.listen()
screen.onkey() 




Now, coming back to our onkey method, we are going to say when the 'w', is pressed, then trigger the function move_forward.


def move_forward():
    ted.forward(10)

screen.listen()
screen.onkey(key='w',fun=move_forward)


Next, added the concerning triggered function move_backward to move backward when the 's' key is pressed.



from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

def move_forward():
    ted.forward(10)

def move_backward():
    ted.backward(10)
    
screen.listen()
screen.onkey(key='w',fun=move_forward)
screen.onkey(key='s',fun=move_backward)

screen.exitonclick()


Such that, functions to move counter-clockwise(left), clockwise(right) and to clear screen(reset screen) are written and binded them with the following keys 'a','d', & 'c' respectively.


from turtle import Turtle,Screen

ted=Turtle()
screen=Screen()

def move_forward():
    ted.forward(10)

def move_backward():
    ted.backward(10)
    

def move_left():
    new_headingted.heading()+10
    ted.setheading(new_heading)

def move_right():
    new_headingted.heading()-10
    ted.setheading(new_heading)


def clear_screen():
    ted.clear()
    ted.penup()
    ted.home()
    ted.pendown()

screen.listen()

screen.onkey(key='w',fun=move_forward)
screen.onkey(key='s',fun=move_backward)

screen.onkey(key='a',fun=move_left)
screen.onkey(key='d',fun=move_right)
screen.onkey(key='c',fun=clear_screen)

screen.exitonclick()


And now what I'm going to try is when I hit the 'w' key on the keyboard, you should see my turtle move forwards by 10 paces each time. And, when 's' key is pressed it moves backward. So we're now controlling our turtle using a keystroke. That's pretty much in Doodle it: just imagine,draw & repeat.


Full key list for python's turtle- screen events ( Event Listeners )

Screen events 

turtle.onkey(fun=function_namekey='Backspace')
turtle.onkeyrelease(fun=function_namekey='Left')


Parameters
  • fun – a function with no arguments or None

  • key – a string: key (e.g. “a”) or key-symbol (e.g. “space”)



.keysym    .keycode.keysym_numKey                                    

Alt_L64      65513      The left-hand alt key
Alt_R11365514The right-hand alt key
BackSpace  22  65288   backspace                           
Caps_Lock66      65549      CapsLock                           
Control_L3765507The left-hand control key
Control_R10965508The right-hand control key
Delete10765535Delete
Down10465364
End10365367end
Escape     9   65307   esc
F1       67      65470      Function key F1                 
F26865471Function key F2
Fi66+i65469+iFunction key Fi
F129665481Function key F12
Home9765360home
Insert10665379insert ( ins)
Left       10065361
K0       90      65438      0 on the keypad                  
187654361 on the keypad
288654332 on the keypad
389654353 on the keypad
483654304 on the keypad
584654375 on the keypad
685654326 on the keypad
779654297 on the keypad
880654318 on the keypad
981654349 on the keypad
+          8665451+ on the keypad
.        91      65439      Decimal (.) on the keypad 
Delete9165439delete on the keypad
/11265455/ on the keypad
Down       8865433↓ on the keypad
Enter    108     65421      enter on the keypad            
Home       7965429home on the keypad
Left     83      65430      ← on the keypad                
*          6365450× on the keypad
Prior    81      65434      PageUp on the keypad       
Right8565432→ on the keypad
-8265453- on the keypad
Up8065431↑ on the keypad
Next10565366PageDown / pg dn
Num_Lock7765407NumLock
Pause11065299pause
Print      11165377PrintScrn / prt sc
Right102     65363      →                                       
Scroll_Lock7865300ScrollLock
Shift_L5065505The left-hand shift key
Shift_R6265506The right-hand shift key
Tab2365289The tab key

Turtle's random walk - Python

How to let turtle making random movements in the East, North, South, or West in Python?




Rules for Python's Turtle:

1. Each time it moves in a random direction.

2. In each direction it chooses a random color 

3. Each time line's thickness increases

4. Each time it covers the same distance

5. Walks on screen in its fastest mode


Solution:

Draw different shapes like triangle, square, pentagon, hexagon in python using turtle

 How to draw a triangle, square, pentagon, hexagon, heptagon, octagon, nonagon, and decagon in one go using turtle class of python?



Code:

from turtle import Turtle,Screen
import random

# to take the turtle up on screen so that all the shapes can get enough space
tim=Turtle()
tim.penup()
tim.left(90)
tim.forward(100)
tim.left(90)
tim.forward(150)
tim.right(90)
tim.forward(50)
tim.right(90)
tim.pendown()
# Now turtle is at the right place
# Main code begins now:



colours = ["orange","CornflowerBlue""DarkOrchid""IndianRed""DeepSkyBlue"
"LightSeaGreen""wheat""SlateGray""SeaGreen"]


def draw_shape(num_of_sides,color):
    tim.color(color)
    angle=360/num_of_sides #will find out the angle according to the given shape

    for _ in range(num_of_sides):

        
        tim.forward(100)
        tim.right(angle)


for shape_of_side_n in range(3,11):
    color=random.choice(colours) #Selects the color randomly for each shape
    draw_shape(shape_of_side_n,color) #will draw shapes from triangle to decagon


screen=Screen()
screen.exitonclick()