Search This Blog

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)


Assignment 01 - Complete Java + DSA + Interview Preparation Course - Kunal Kushwaha

 

Assignment of Flow of Program - Flowcharts & Pseudocode - Video 02Kunal Kushwaha ]

Create flowchart and pseudocode for the following:

1. Input a year and find whether it is a leap year or not.

    Solution: 

Flow Chart

Pseudocode

1. Start
2. Input year in type int
3. if year%4==0 and year%100!=0 or year%400==0:
          output: Leap Year
    else:
          output: Non Leap Year
4. Stop

2. Take two numbers and print the sum of both.
    
    Solution: 

Flow Chart

Pseudocode

1. Start
2. Input num1 & num2 in type int
3. sum=num1+num2
4. output: sum
5. Stop


3. Take a number as input and print the multiplication table for it.
   
    Solution: 

Flow Chart

Pseudocode

1. Start
2. Input num in type int
3. multiplier=1
    while multiplier!=11:
            output: num*multiplier
             multiplier=multiplier+1
     end while
5. Stop


4. Take 2 numbers as inputs and find their HCF and LCM.

    Solution: Yet to do.

Flow Chart


Pseudocode


5. Keep taking numbers as inputs till the user enters ‘x’, after that print sum of all.

    Solution: 

Flow Chart





Pseudocode

1. Start
2. num = [ ] , add = 0
    while True:
          input s
          if s=='x' or s=='X':
                  for i in s:
                       add=add+int(i)
                   end for
                   output add
                    exit
           else:
                   num.append(s)
     end while
3. Stop



Techgig Geek Goddess Screening Round Solution - Python

 



Oddia and Evenia are two friends who love strings and prime numbers. Although they have the same taste and like similar things, they are enemies when it comes to even and odd numbers. Oddia likes the odd numbers and Evenia likes the even numbers. They have a problem for you to solve.

A string S of lowercase letters will be provided and you have to figure out if the given string is Prime String or not. The index starts at 1.

Prime String: A string is considered a prime string only if the absolute difference between the sum of odd indexed letters and even indexed letters is completely divisible by any of the odd prime numbers less than 10.

Note: For calculations, consider the ASCII value of lowercase letters.

Example:

String, S = abcdef

Summation of Odd Indexed letters, O = a + c + e = 97 + 99 + 101 = 297

Summation of Even Indexed letters, E = b + d + f = 98 + 100 + 102 = 300

Absolute Difference = |O-E| = |297-300| = 3

This is completely divisible by 3 and leaves 0 as remainder. Thus, the given string is a Prime String.

If the string is prime string, print Prime String otherwise print Causal String. Can you solve it?


Input Format

The first line of input consists of the number of test cases, T

Next N lines each consist of a string, S.

Note: Read the input from the console.

Constraints

1<= T <=10

2<= |S| <=10000

|S| is the length of the string.


Output Format

For each test case, print Prime String if the string is prime string otherwise print Casual String.


Sample TestCase 1

Input

2

bbae

abcdef

Output

Casual String

Prime String

Explanation

Test Case 1: 


Sum of Odd indexed letters, O = 98+97 = 195

Sum of Even indexed letters, E = 98 + 101 = 199

Absolute Difference = |195-199| = 4

This is not divisible by any of the odd prime numbers. The given string is a Casual String.

----------------------------------------

Solution:

def check():

    
    num = int(input())

 

    for i in range(num):
        st = input()
        i = 0
        even_num = 0
        odd_num = 0
        for char in st:
            if i % 2 == 0:
                even_num+=ord(char)
            else:
                odd_num+=ord(char)
            i+=1
            
        ab_diff = abs(even-odd)
    
        if ab_diff % 3 == 0 or ab_diff % 5 == 0 or ab_diff % 7 == 0:
            print("Prime String")
        else:
            print("Casual String")

check()



Object Oriented Coffee Maker Machine : Python

 

Object Oriented Coffee Maker Machine : Python
Object Oriented Coffee 
Maker Machine
( Python Based ) 

The functionality given to the virtual coffee machine is a replica of our actual coffee machine. But, this oops-oriented coffee machine can only take order one out of latte/espresso/cappuccino.

The code is designed after determining 5 conditions to serve the coffee:

  • Turn On & Off the machine
  • Print the available quantity of the resources & money
  • Process the made payment by the user
  • Here, check out the given payment is ok?
  • Serve the coffee
Before solving the above-mentioned conditions, the modules containing these functionalities are imported. And the functionality of these modules can be understood from below given class's documentation:

MenuItem Class

Attributes:

        

  • name

(str) The name of the drink.

e.g. “latte”

  • cost

(float) The price of the drink.

e.g 1.5

  • ingredients

(dictionary) The ingredients and amounts required to make the drink.

e.g. {“water”: 100, “coffee”: 16}

Menu Class

Methods:

  • get_items()

Returns all the names of the available menu items as a concatenated string.

e.g. “latte/espresso/cappuccino”

  • find_drink(order_name)

Parameter order_name: (str) The name of the drinks order.

Searches the menu for a particular drink by name. Returns a MenuItem object if it exists, otherwise returns None.

CoffeeMaker Class

Methods:

  • report()

Prints a report of all resources.

e.g.

Water: 300ml

Milk: 200ml

Coffee: 100g

  • is_resource_sufficient(drink)

Parameter drink: (MenuItem) The MenuItem object to make.

Returns True when the drink order can be made, False if ingredients are insufficient.

e.g.

True

  • make_coffee(order)

Parameter order: (MenuItem) The MenuItem object to make.

Deducts the required ingredients from the resources.

MoneyMachine Class

Methods:

  • report()

Prints the current profit

e.g.

Money: $0

  • make_payment(cost)

Parameter cost: (float) The cost of the drink.

Returns True when payment is accepted, or False if insufficient.

e.g. False


Final Code Structure

1. Turn On & Off the machine

is_on=True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on =
False
2. Print the available quantity of the resources & money - The final report

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
menu = Menu()

is_on = True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
3. & 4. Process the made payment by the user. Also, check out the given payment is ok?

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
# menuitem = MenuItem()
menu = Menu()
is_on=True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
else:
drink = menu.find_drink(choice)
if coffee.is_resource_sufficient(drink):
if money.make_payment(drink.cost):
5. Serve the coffee

from menu import Menu, MenuItem
from coffee_maker import CoffeeMaker
from money_machine import MoneyMachine


coffee = CoffeeMaker()
money = MoneyMachine()
menu = Menu()

is_on = True

while is_on:
options = menu.get_items()
choice = input(f"What would you like? ({options}):").lower()

if choice =='off':
is_on = False
elif choice == 'report':
money.report()
coffee.report()
else:
drink = menu.find_drink(choice)
if coffee.is_resource_sufficient(drink):
if money.make_payment(drink.cost):
coffee.make_coffee(drink)
Thank You :)