Search This Blog

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

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


Solution to TCS Pan India Hiring Drive - Python [ Coding Round ]

 Question:

Minimum Absolute Difference (100 Marks)

You have an array of size N. Calculate the sum of minimum absolute differences for all the elements of the given array.


Note: N will always be an even number.

Input Format

The first line contains a single integer N, the size of the array.

The second line contains N integers, the elements of the array.

Constraints

2 <= N <= 103

0 <= Ai <= 103

Output Format

Print the sum of minimum absolute differences.


Note: There is a new line at the end of the output.

Sample TestCase 1

Input

4

5 10 10 15

Output

10

Explanation

Minimum absolute difference for element 1 = 5


Minimum absolute difference for element 2 and 3 = 0

Minimum absolute difference for element 4 = 5


Sum of minimum absolute differences = 5 + 0 + 0 + 5 = 10

Sample TestCase 2

Input

6

1 3 3 7 4 7

Output

3


Solution:

def main():

    def absDifferenceMinSum(anum):
        sum = 0
        a.sort()
        
        sum += abs(a[0] - a[1])
        sum += abs(a[num - 1] - a[num - 2])
        for i in range(1num - 1):
            sum += min(abs(a[i] - a[i - 1]),
                    abs(a[i] - a[i + 1]))
        return sum


    size_of_list = int(input(""))
    a = list(map(intinput().split()))
    num = len(a)
    print(absDifferenceMinSum(anum))



main()

Object Oriented Quiz Project - Python


QUIZ GAME RULES:

  1. In this quiz project, there is a total of 12 questions. And on the basis of the user's typed answer, the score will be awarded to them. Each question is of 1 mark. The answer can be either True or False. 
  2. The program is using an object-oriented approach.
  3. When a user types the wrong or right answer, share these remarks with them: 
  • If wrong: print("That's wrong")
  • If right: print("You got it right!")

When the quiz ends final output should be:

  • You've completed the quiz.
  • Your final score was: final_score/question_number

TODOs

File- main.py :

# TODO 1: the list to store the question data

# TODO 2: import all the dependent classes, methods

# TODO 3: Get the data from the dat.py and allocate the memory to the data(question, answer)

# TODO 4: Append each  allocated data to the list

# TODO 5: Pass the question list to the quiz brain for actions

# TODO 6: Continue asking questions until the end of the question list

# TODO 7: Display the final score and quiz is ended remark


Code- main.py :


from question_model import Question
from data import question_data
from quiz_brain import QuizBrain

question_bank = []


for question in question_data:
    q_text=question['text']
    q_answer=question['answer']

    new_question = Question(q_text,q_answer)
    question_bank.append(new_question)

quiz=QuizBrain(question_bank)


while quiz.still_has_questions():
    quiz.next_question()

print("You've completed the quiz.")
print(f"You final score was: {quiz.score}/{quiz.question_no}")


File- data.py :

# TODO 1: Store the dictionary data into a list.

Code- data.py :

question_data = [
    {"text""A slug's blood is green.""answer""True"},
    {"text""The loudest animal is the African Elephant.""answer""False"},
    {"text""Approximately one quarter of human bones are in the feet.""answer""True"},
    {"text""The total surface area of a human lungs is the size of a football pitch.""answer""True"},
    {"text""In West Virginia, USA, if you accidentally hit an animal with your car, you are free to take "
             "it home to eat.""answer""True"},
    {"text""In London, UK, if you happen to die in the House of Parliament, you are entitled to a state funeral.""answer""False"},
    {"text""It is illegal to pee in the Ocean in Portugal.""answer""True"},
    {"text""You can lead a cow down stairs but not up stairs.""answer""False"},
    {"text""Google was originally called 'Backrub'.""answer""True"},
    {"text""Buzz Aldrin's mother's maiden name was 'Moon'.""answer""True"},
    {"text""No piece of square dry paper can be folded in half more than 7 times.""answer""False"},
    {"text""A few ounces of chocolate can to kill a small dog.""answer""True"}


File- question_model.py :

# TODO 1: Design a template for each question to store questions and answers at the right place.

Code- question_model.py :

class Question:
    def __init__(self,q_text,q_answer):
        self.text=q_text
        self.answer=q_answer

File- quiz_brain.py :

# TODO 1: asking the questions

# TODO 2: checking if the answer was correct

# TODO 3: checking if we're at the end of the quiz

Code- quiz_brain.py :


class QuizBrain:

    def __init__(self,question):
        self.score=0
        self.question_list=question
        self.question_no=0

    def still_has_questions(self):
        return len(self.question_list) > self.question_no

    def check_answer(selfuser_answer,correct_answer):
        if user_answer.lower()==correct_answer.lower():
            print('You got it right!')
            self.score+=1
        elif user_answer=='end' or user_answer=='END':
            exit()
        else:
            print("That's wrong!")
            
            
        print(f'The correct answer was: {correct_answer}')
        print(f"Your current score is {self.score}/{self.question_no}")
        print('\n')


    def next_question(self):
        
        #if you'll not add the .text after current question then it will
        #show the memory allocatons of the object so better use
        #current_location.text to access the text of queston
        current_questionself.question_list[self.question_no]
        self.question_no+=1
        user_answer=input(f"Q.{self.question_no}{current_question.text}  (True/False): ")
        
        correct_answer=current_question.answer

        self.check_answer(user_answer,correct_answer)