Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Student Name: Student ID: Total

Section: Grade:
Exam Room:

Exam: Final Q1 : 30

Academic Year: 2021 - 2022 Fall Date: 09/01/2022 Q2(a): 30

Ins: Aynur Dayanık Duration: 120 min. Q2(b): 40


İpek Sözen
Lori Russell Dağ

int() / float() / str()


input( message )
print( string, end = string )
range( start, stop, step ) Numpy
array()
String arange()
len( obj ) zeros()
format( value_list ) ones()
find( string ) linspace()
index( element ) loadtxt()
strip() savetxt()
split( delimiter ) where()
argmax()
List argmin()
append( element ) max()
extend( sequence ) min()
insert( index, element ) mean()
pop( index ) random.rand()
remove( element ) random.randint()
index( element ) reshape()
reverse() polyfit(x, y, degree)
count() polyval(coefficients,x)
sort()
sorted( list )
Matplotlib
Dictionary plot()
pop( key ) pie()
bar()
Files hist()
open( filename, mode ) subplot()
write( string ) axis()
read() title()
readline() xlabel()
readlines() ylabel()
close() grid()
legend()

1
Question 1 (30 pts.)
A. (24 points) For each part below, write a single Python statement in the box provided to answer the question.

Important:
● Write a single statement for each part.
● You should NOT use any loops in your solutions. Use ONLY numpy functions and numpy operators.
● You should NOT use any tuple / range / list / dictionary objects or list comprehensions in your solutions.
● Assume that the numpy module is imported as follows: import numpy as np

1. Create a one-dimensional array of integers which are multiples of 3 from 0 to 72 (inclusive), named x.

x = np.arange(0, 73, 3)

2. Suppose that a one-dimensional array, named y, is created as shown below.


Print the values in the array y which are greater than 30 and multiples of 4.

y = np.random.randint(1, 60, 25)


print(y[(y > 30) & (y % 4 == 0)])

3. Print the indexes of the elements in the array y which are equal to 50.

print(np.where(y == 50))

4. Print the index of the first maximum integer in the array y.

print(np.argmax(y)) or print(y.argmax())

5. Convert the array y to a 5 x 5 two-dimensional array, named m.

m = y.reshape(5, 5)

6. Update the array m by multiplying all the elements in the third column by 5.

m[:,2] *= 5

7. Print all integers in the array m in rows (indexes) 1 to 3, inclusive, and columns (indexes) 1 to 3, inclusive.

print(m[1:4,1:4])

2
B. (6 points) Trace the following and show the exact output in the space provided.

class A: Answer:
def __init__(self , a):
self.__a = a

def myfun(self): 36
return 2 * self.__a

def __str__(self): 1 15
return str(self.__a) + ' ' + str(self.myfun())

def increase_a(self, a): 5 24


self.__a += a

def get_a(self):
return self.__a

class B(A):
def __init__(self , a, b):
A.__init__(self, a)
self.__b = b

def myfun(self):
self.increase_a(4)
self.__b += 5
return self.get_a() + self.__b

x = A(3)
y = B(1, 5)
print(x)
print(y)
z = y
print(z)

3
Question 2 (70 pts.)
This question has 2 parts. In part (a) you will complete the Measurement class using the information given in the
comments. In part (b), you will complete the function and application using the Measurement class defined in part (a)
and by following the instructions given. Do not duplicate functionality.

Instructions:
● Complete the program by filling in the spaces with the thick, black border in the right margin.
● Read the comments carefully and do only what is asked.
● You may not add any additional methods or update the visibility (private/public) of the attributes.

a) (30 pts) Complete the definition of the Measurement class:

class Measurement:

def __init__( self, value, unit ):


"""
A Measurement has 2 attributes: value and unit.
All attributes are private (__)
Takes the float Measurement value and the string unit as parameters.
Measurement unit may be either ‘cm’ or ‘m’.
Initializes the unit to the value passed as a parameter.
Initializes the value using the set_value() method. (Read set_value() carefully)
"""
self.__unit = unit
self.set_value( value )

def reduce_measure( self ):


"""
If the Measurement unit is centimeters and the value is 100 or more, the method
converts the Measurement to meters by updating the value and unit accordingly. If
the Measurement unit is meters and the value is below 1, converts to centimeters
by updating the value and unit accordingly.
"""
if self.__unit == 'cm' and self.__value >= 100:
self.__value /= 100.0
self.__unit = 'm'
elif self.__unit == 'm' and self.__value < 1:
self.__value *= 100.0
self.__unit = 'cm'

def set_value( self, value ):


"""
Sets the __value of the Measurement to the absolute value of the parameter.
Calls the reduce_measure() method to reduce the Measurement.
"""
self.__value = abs( value )
self.reduce_measure()

4
def get_value( self ):
"""
Returns the value of the Measurement object
"""
return self.__value

def get_unit( self ):


"""
Returns the unit of the Measurement object
"""
return self.__unit

def __mul__( self, other ):


"""
Returns a new Measurement object according to the following:
Hint: you may use the isinstance(), or type() functions.
a. The other object must be numeric (int or float), returns a new Measurement
object whose value is the product of the value of self, multiplied by other.
The units of the new Measurement object is the same as self.
b. If the other object is not a float or int, it returns a new Measurement object
which is a copy of self.
"""
new_value = self.__value
if isinstance(other, float) or isinstance(other, int):
# OR - if type(other) == float or type(other) == int:
new_value = self.__value * other
return Measurement( new_value, self.__unit)

def __lt__(self, other):


"""
Compares Measurement objects and returns True if self is smaller, False if not.
Example: 1.2m < 50cm (False), 30cm < 50cm (True), 20cm < 1.5m (True)
"""
if self.__unit == other.__unit:
return self.__value < other.__value
elif self.__unit == 'm':
return False
else:
return True

def __eq__( self, other ):


"""
Two Measurement objects are equal if they have the same value and unit.
Example: 1.2m == 50m (False), 50cm == 50m (False), 20cm == 20cm (True)
"""
return self.__value == other.__value and self.__unit == other.__unit

def __repr__( self ):


"""
Returns a string representation of a Measurement object with the format:
'1.54m' -> value is formatted with 2 decimal places.
"""
return f'{self.__value:.2f}{self.__unit}'

5
b) (40 pts) Using the Measurement class, implement the following function and python script. The script
uses data from a file, measures.txt (sample file shown below). You should read the question carefully
and do only what is asked using Measurement functionality. You may not use numpy in your solution.

measures.txt (values may change):


120,cm
50,cm
70,cm
1.4,m
0.5,m

Sample Run:
Original Measurements: [1.20m, 50.00cm, 70.00cm, 1.40m, 50.00cm]
Increased Measurements: [1.74m, 72.50cm, 1.01m, 2.03m, 72.50cm]
Sorted Increased Measurements: [72.50cm, 72.50cm, 1.01m, 1.74m, 2.03m]

from Measurement import Measurement


import matplotlib.pyplot as plt

def find_measurements( lst, n, unit ):


"""
Implement the recursive method, find_measurements which takes a list of
Measurements, the length/number of elements in the list and the
string unit (m or cm).The method should return a list of the values (and only the
values) of all Measurements with the same unit as the parameter.
Note: no points will be given if the function uses a loop/is not recursive.
"""
if n == 0:
return []
else:
measures = find_measurements(lst, n-1, unit)
if lst[n-1].get_unit() == unit:
measures.append(lst[n-1].get_value())
return measures

6
#open file measures.txt
f = open('measures.txt')

#read the Measurements from the file into the list, measures
measures = []

for line in f:
print(line)
data = line.split(',')
m = Measurement(float(data[0]),data[1].strip())
measures.append( m )

#Display original Measurements


print(f'Original Measurements: {measures}')

#create a new list, increase, that contains Measurements increased by 45%


increase = []
for m in measures:
increase.append( m * 1.45 )

#display the increased Measurements


print(f’Increased Measurements: {increase}’)

#sort the list of increased Measurements


increase.sort()

#display the sorted list of Measurements


print(f'Sorted Increased Measurements: { increase }')

#using find_measurement function, get list of increased meter measurements

measurements = find_measurements( increase, len(increase), 'm')

#Open a new Figure 1 window


plt.figure(1)
plt.clf()

#Create the plots as shown in the Figure 1 window.


plt.subplot(1,2,1)
plt.plot(measurements)
plt.title('Increased Meter Measurements - default line')

plt.subplot(1,2,2)
plt.plot(measurements,'*')
plt.title('Increased Meter Measurements - star marker')

You might also like