Search This Blog

Showing posts with label Python Programming. Show all posts
Showing posts with label Python Programming. Show all posts

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

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()

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()

How to draw a dashed line in python?

 



In python, to draw a dashed line on a screen, first, turtle module's Turtle class is imported to the program. The turtle is an extensive module that provides turtle graphics primitives, in both object-oriented and procedure-oriented ways. Because it uses tkinter for the underlying graphics, it needs a version of Python installed with Tk support.

It's part of core python libraries so, turtle comes by default with basic python. Just need to import and use.

After importing the turtle, we use the penup and pendown to draw a dashed line. Penup simply means not drawing & Pendown is drawing a line. Like in the code below turtle module's penup & pendown are used to draw a black dashed line.


from turtle import Turtle,Screen #turtle is imported

timmy_the_turtle=Turtle()
timmy_the_turtle.shape('classic')

timmy_the_turtle.color('black')


for i in range(20):
    
    # penup or pu means pick pen up, 
    # so you can move turtle 
      without leaving tracks. 
    # pendown or pd means pick pen down, 
    # so you can move the turtle 
      and leave tracks.
    

    timmy_the_turtle.forward(10)
    # picking up pen
    timmy_the_turtle.penup()
    timmy_the_turtle.forward(10)
    # picking pen down to draw
    timmy_the_turtle.pendown()
    
screen=Screen()
#Allows to exit when user clicks on screen
screen.exitonclick()

Solution to Techgig 30 Days Python Challenge - Day 7 (HARD)

 

Count special numbers between boundaries (100 Marks)

For this challenge, you are given a range and you need to find how many prime numbers lying between the given range.

Input Format
For this challenge, you need to take two integers on separate lines. These numbers defines the range. 

Constraints
1 < = ( a , b ) < = 100000

Output Format
output will be the single number which tells how many prime numbers are there between given range. 

Sample TestCase 1
Input
1
20
Output
8
Explanation

There are 8 prime numbers which lies in the given range.
They are 2, 3, 5, 7, 11, 13, 17, 19

Time Limit(X):
1.00 sec(s) for each input.
Memory Limit:
512 MB
Source Limit:
100 KB
Allowed Languages:
C, C++, C++11, C++14, C#, Java, Java 8, PHP, PHP 7, Python, Python 3, Perl, Ruby, Node Js, Scala, Clojure, Haskell, Lua, Erlang, Swift, VBnet, Js, Objc, Pascal, Go, F#, D, Groovy, Tcl, Ocaml, Smalltalk, Cobol, Racket, Bash, GNU Octave, Rust, Common LISP, R, Julia, Fortran, Ada, Prolog, Icon, Elixir, CoffeeScript, Brainfuck, Pypy, Lolcode, Nim, Picolisp, Pike


SOLUTION DAY-07: (100 Marks)

def main():

        num1=int(input("Enter num 1:"))
        num2=int(input("Enter num2: "))
        c=0

        for num in range(num1,num2+1):
                if num>1:
                        for i in range(2,num):
                                if num%i==0:
                                        break
                        else:
                                c+=1
                
        print(c)

main()