Problem Solving Using Python

Problem Solving Using Python

Q1: 

- Explain Floor division operator with an example

- Explain Percentile operator with an example

- Explain Exponent operator with an example

- Explain Equal comparison operator with an example

- Explain Not-Equal operator with an exmaple


Problem Solving Using Python

# % symbol in Python is called the Modulo Operator. 

# It returns the remainder of dividing the left hand operand by right hand operand. 

# It's used to get the remainder of a division problem


# SOLUTION

x = 7  

y = 2

print ('x % y =', x % y ) 

x = 3  

y = 4

print ('x % y =', x % y ) 


Exponent operator is used to perform exponential (power) calculations by using operators


a = 10

b = 4

print ('Exponent operator:', a ** b )


Equal operator is used to compare the two values to provide result whether they are equal or not. 

If both the values are equal, we get the result as True, if not False


# SOLUTION 

x = 15

y = 34

print('Equal operator:',x==y)


Not equal operator is used to compare two operands 

It returns True statement if they are Not equal, and False if they are Equal


# SOLUTION 

x = 20

y = 25  

print('Not equal operator:', x!=y)


 Q2:  (a) I have two numbers as x = 123 and y = "465"; when I try to add these two numbers, the program fails. Debug and solve the problem.

x, y = 123, '456';

print(x+y)


x, y = 123, '456'

print(x + int(y))


(b) We have a variable as shown below:

course = "Python fundamentals"

we would like to replace the "Python fundamentals" with the "Python for absolute beginners"


Expected output:

- course = "Python for absolute beginners"


SOLUTION b

course = 'Python fundamentals'

course = course.replace('fundamentals', 'for absolute beginners')

print('course = ', course)


(c) Imagine price of a house is 25 L. If the buyer has good credit, they need to make 10% down payment, alternately down payment is 30%. Write a program to display the rules and display the down payment.


SOLUTION c

price = 2500000

has_good_credit = True


if has_good_credit:

    down_payment = 0.1 * price

else:

    down_payment = 0.3 * price

    

print('Down payment: Rs.', down_payment)


Q3: (a) Create a Vehicle class with model_name, max_speed and mileage instance attributes.


expected output:

- Model Name: Eicher

- Max speed: 100

- Mileage: 20


class Vehicle:

    def __init__(self, model_name, max_speed, capacity):

        self.model_name = model_name

        self.max_speed = max_speed

        self.capacity = capacity

        

        

car = Vehicle("Eicher", 100, 50)

print("Model Name:", car.model_name)

print("Max speed:", car.max_speed)

print("Capacity:", car.capacity)       

       

(b) Create a Bus child class that inherits from the Vehicle class. The default fare charge of any vehicle is seating capacity * 100. If Vehicle is Bus instance, we need to add an extra 10% on full fare as a maintenance charge. So total fare for bus instance will become the final amount = total fare + 10% of the total fare.


class Vehicle:

    def __init__(self, model_name, max_speed, capacity):

        self.model_name = model_name

        self.max_speed = max_speed

        self.capacity = capacity


class Bus(Vehicle):

    def fare(self):

        default_fare = self.capacity * 100 

        total_fare = default_fare + (0.1 * default_fare)

        return total_fare


Alliance_Bus = Bus("Eicher", 12, 50)

print("Total Bus fare is:", Alliance_Bus.fare())


Q4: 1. Write a Program to create a class by name Students, and initialize attributes like name, dateofbirth, and grade while creating an object.

 2. Write a Program to create an empty valid class by name Students, with no properties

 3. Write a program, to create a child class 'Undergraduate' that will inherit the properties of Parent class Students and also will have it's own unique attribute(satscore)

 4. Finally call each attribute to print the output


SOLUTION 1

class Students():

    def __init__(self, name, DateOfBirth, contactNumber, address):

        self.name = name

        self.DateOfBirth = DateOfBirth

        self.number = contactNumber

        self.address = address


# create object

studentA = Students('Mathew', '22-Jun-2022', '123456789', 'Anekal')


SOLUTION 2

class Students:

    pass


# create object

studentsA = Students()


SOLUTION 3

class Students():

    def __init__(self, name, DateOfBirth, contactNumber, address):

        self.name = name

        self.DateOfBirth = DateOfBirth

        self.number = contactNumber

        self.address = address



# INHERITANCE

class Undergraduate(Students):

    def __init__(self, name, DateOfBirth, number, address, SatScore):

        Students.__init__(self, name, DateOfBirth, number, address)

        self.SatScore = SatScore

        

x = Undergraduate("Mona", "22-Jun-2022", "123456789", "Anekal", "1234")


SOLUTION 4

print(type(x))

print("Student Name: ", x.name)

print("Student Birth Date: ", x.DateOfBirth)

print("Student Phone Number: ", x.number)

print("Student's Address: ", x.address)

print("Student's SAT Score: ", x.SatScore)


Q5: Remove duplicates from a list and create a tuple and find the minimum and maximum number


Given:


myList = [87, 45, 41, 65, 94, 41, 99, 94]


Expected Outcome:

- unique items [87, 45, 41, 65, 99]

- tuple (87, 45, 41, 65, 99)

- min: 41

- max: 99

# SOLUTION

myList = [87, 52, 44, 53, 54, 87, 52, 53]


print("Original list", myList)


myList = list(set(myList))

print("unique list", myList)


t = tuple(myList)

print("tuple ", t)


print("Minimum number is: ", min(t))

print("Maximum number is: ", max(t))


Q6: 

Write a program 

- to remove the item present at index 4 

- add the removed number to the 2nd position 

- add the removed number at the end of the list.


Given:


aList = [34, 54, 67, 89, 11, 43, 94]


Expected Output:

- List After removing number at index 4:  [34, 54, 67, 89, 43, 94]

- List after adding number at index 2:  [34, 54, 11, 67, 89, 43, 94]

- List after adding number at last:  [34, 54, 11, 67, 89, 43, 94, 11]


SOLUTION

aList = [34, 54, 67, 89, 11, 43, 94]

print('aList =', aList)


x = aList.pop(4)

print("List After removing number at index 4: ", aList)

aList.insert(2, x)

print("List after adding number at index 2: ", aList)

aList.append(x)

print("List after adding number at last:", aList)



 Q7: (a) Using exception handling (try & finally) 

- open a text file, read the contents 

- finally close the file


sample text = 'Hello, I am proud to be with Alliance University!'


try:

    f = open("sample.txt", 'r')

    print (f.read())

finally:

    f.close()


(b) 

- reopen the same file to append the text to "Hello, I am learning file operations in Python!"

- read the file again

- finally close the file to release memory


try:

    f = open("sample.txt", "w")

    f.write ("Hello, I am learning file operations in Python!") 

    f = open("sample.txt", 'r')

    print (f.read())

finally:

    f.close()


Q8: (a) we have the following variables with relevant infomation

- info = {'ID' :[101, 102, 103],'Department' :['B.Sc','B.Tech','M.Tech',]} 

how can we convert this to pandas dataframe?


# SOLUTION a

import pandas

info = {'ID' :[101, 102, 103],'Department' :['B.Sc','B.Tech','M.Tech',]}

x = pandas.DataFrame(info)

x


(b) 

- create an Excel file with above ID and Deapartment headers

- convert the Excel to csv file

- read the same file using pandas read function.


Load comments