Breaking News

Case Study I - Perform Various Function Handling Operations using Python Code


Pyspark certification edureka 

A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as 

the following: 

UP 5 DOWN 3 LEFT 3 RIGHT 2

The numbers after the direction are steps. Write a program to print final position of robot after a sequence of movements. (UP(+)/DOWN(-)=> Y Position, RIGHT(+)/LEFT(-)=> X Position) Example: If the following is given as an input to the program: UP 5 LEFT 3 DOWN 6 RIGHT 4 Then, the output of the program should be(X , Y Positions): 1, -1

In [17]:x = y = 0


while True:

    robot_step = input("Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:")

    

    if robot_step == "":

        break

        

    else:

        steps = robot_step.split()

        direc = steps[0]

        dist = int(steps[1])

        

        if direc == 'UP':

            y = y + dist

        elif direc == 'DOWN':

            y = y - dist

        elif direc == 'RIGHT':

            x = x + dist

        elif direc == 'LEFT':

            x = x - dist


print("x, y position of robot is: ",x,',',y,)

 

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:UP 5

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:LEFT 3

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:DOWN 6

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:RIGHT 4

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:

x, y position of robot is:  1 , -1

 

In [13]:

# Distance of robot from initial position:- 


import math


x = y = 0


while True:

    robot_step = input("Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:")

    

    if robot_step == "":

        print("\n")

        break

        

    else:

        steps = robot_step.split()

        direc = steps[0]

        dist = int(steps[1])

        

        if direc == 'UP':

            y = y + dist

        elif direc == 'DOWN':

            y = y - dist

        elif direc == 'RIGHT':

            x = x + dist

        elif direc == 'LEFT':

            x = x - dist


print("x, y position of robot is:", x, y, "\n")


location = math.sqrt(x**2 + y**2)

print("Distance of robot from initial position is:", location)

 

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:UP 10

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:RIGHT 12

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:LEFT 7

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:DOWN 14

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:



x, y position of robot is: 5 -4 


Distance of robot from initial position is: 6.4031242374328485

 

In [12]:

# define function:- 


def position():

    x = y = 0

    continu = 1

    while continu == 1:

        robot_step = input("Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:")

        if robot_step == "":

            break

        else:

            steps = robot_step.split()

            direc = steps[0]

            dist = int(steps[1])

        

            if direc == 'UP':

                y = y + dist

            elif direc == 'DOWN':

                y = y - dist

            elif direc == 'RIGHT':

                x = x + dist

            elif direc == 'LEFT':

                x = x - dist

        continu = int(input("If robot still moving, press 1, else 0"))

    print("x, y position of robot is: ",x,',',y,)

 

In [16]: position()

 

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:UP 5

If robot still moving, press 1, else 01

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:DOWN 3

If robot still moving, press 1, else 01

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:LEFT 3

If robot still moving, press 1, else 01

Enter robot steps in 'UP 00 or DOWN 00 or LEFT 00 or RIGHT 00' format:RIGHT 2

If robot still moving, press 1, else 00

x, y position of robot is:  -1 , 2


2.Data of XYZ company is stored in sorted list. Write a program for searching

specific data from that list.



Code:-

mylist = []

print("Enter 5 elements for the list: ")

for i in range(5):

    val = int(input())

    mylist.append(val)


print("Enter an element to be search: ")

elem = int(input())


for i in range(5):

    if elem == mylist[i]:

        print("\nElement found at Index:", i)

        print("Element found at Position:", i+1)






Out Put:-

Enter 5 elements for the list: 

10

20

3

0

6

Enter an element to be search: 

3


Element found at Index: 2

Element found at Position: 3

 








# 3. Weather forecasting organization wants to show is it day or night.

# So, write a program for such organization to find whether is it dark outside or not.

# Hint: Use time module.


from datetime import datetime



def get_part_of_day(hour):

    return (

        "light" if 5 <= hour <= 18

        else

        "Dark or night  "

    )



h = datetime.now().hour


print(f"Its {get_part_of_day(h)}  right now.")




Output 


its daylight  right now.



5. Write a program to find distance

between two locations when their latitude and

longitudes are given

 

Code:- 

 

from math import radians, sin, cos, acos

 

print("Enter  coordinates of two points:")

slat = radians(float(input("slat Starting latitude: ")))

slon = radians(float(input("slon Ending longitude: ")))

elat = radians(float(input("elat  Starting latitude: ")))

elon = radians(float(input("elon Ending longitude: ")))

 

distance = 6371.01 * acos(sin(slat)*sin(elat) + cos(slat)*cos(elat)*cos(slon - elon))

print("The distance is %.2fkm." % distance)

 

 

Output:


Enter  coordinates of two points:

slat Starting latitude: 98

slon Ending longitude: 23

elat  Starting latitude: 42

elon Ending longitude: 532

The distance is 4592.28km.





import random

class Account:

    # Construct an Account object

    def __init__(self, id, balance = 0, annualInterestRate = 3.4):

        self.id = id

        self.balance = balance

        self.annualInterestRate = annualInterestRate

    def getId(self):

        return self.id

    def getBalance(self):

        return self.balance

    def getAnnualInterestRate(self):

        return self.annualInterestRate

    def getMonthlyInterestRate(self):

        return self.annualInterestRate / 12

    def withdraw(self, amount):

        self.balance -= amount

    def deposit(self, amount):

        self.balance += amount

    def getMonthlyInterest(self):

        return self.balance * self.getMonthlyInterestRate()

def main():

   # Creating accounts

   accounts = []

   for i in range(1000, 9999):

       account = Account(i, 0)

       accounts.append(account)

 # ATM Processes

   while True:

       # Reading id from user

       id = int(input("\nEnter account pin: "))

       # Loop till id is valid

       while id < 1000 or id > 9999:

           id = int(input("\nInvalid Id.. Re-enter: "))

       # Iterating over account session

       while True:

           # Printing menu

           print("\n1 - View Balance \t 2 - Withdraw \t 3 - Deposit \t 4 - Exit ")

           # Reading selection

           selection = int(input("\nEnter your selection: "))

           # Getting account object

           for acc in accounts:

               # Comparing account id

               if acc.getId() == id:

                   accountObj = acc

                   break

           # View Balance

           if selection == 1:

               # Printing balance

               print(accountObj.getBalance())

           # Withdraw

           elif selection == 2:

               # Reading amount

               amt = float(input("\nEnter amount to withdraw: "))

               ver_withdraw = input("Is this the correct amount, Yes or No ? " + str(amt) + " ")

               if ver_withdraw == "Yes":

                   print("Verify withdraw")

               else:

                   break

               if amt < accountObj.getBalance():

                  # Calling withdraw method

                  accountObj.withdraw(amt)

                  # Printing updated balance

                  print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")

               else:

                    print("\nYou're balance is less than withdrawl amount: " + str(accountObj.getBalance()) + " n")

                    print("\nPlease make a deposit.");

           # Deposit

           elif selection == 3:

               # Reading amount

               amt = float(input("\nEnter amount to deposit: "))

               ver_deposit = input("Is this the correct amount, Yes, or No ? " + str(amt) + " ")

               if ver_deposit == "Yes":

                  # Calling deposit method

                  accountObj.deposit(amt);

                  # Printing updated balance

                  print("\nUpdated Balance: " + str(accountObj.getBalance()) + " n")

               else:

                   break

           elif selection == 4:

               print("nTransaction is now complete.")

               print("Transaction number: ", random.randint(10000, 1000000))

               print("Current Interest Rate: ", accountObj.annualInterestRate)

               print("Monthly Interest Rate: ", accountObj.annualInterestRate / 12)

               print("Thanks for choosing us as your bank")

               exit()

           # Any other choice

           else:

               print("nThat's an invalid choice.")

# Main function

main()



Output :



Enter your selection: 1

0


1 - View Balance     2 - Withdraw    3 - Deposit     4 - Exit 


Enter your selection: 3


Enter amount to deposit: 100

Is this the correct amount, Yes, or No ? 100.0 yes


Enter account pin: 1234


1 - View Balance     2 - Withdraw    3 - Deposit     4 - Exit 


Enter your selection: 1

0


1 - View Balance     2 - Withdraw    3 - Deposit     4 - Exit 


Enter your selection: 4

nTransaction is now complete.

Transaction number:  653779

Current Interest Rate:  3.4

Monthly Interest Rate:  0.2833333333333333

Thanks for choosing us as your bank


 



No comments