0% found this document useful (0 votes)
93 views

Chap 4: My - Thermo - Stat

The document contains 15 code snippets demonstrating various Python programming concepts like functions, conditionals, loops, and NumPy arrays. The snippets include examples of defining functions, using if/else conditional logic, iterating over arrays, and performing mathematical operations on scalar and array inputs. Test cases are provided to demonstrate expected functionality for many of the code snippets.

Uploaded by

Tôn Quang Tấn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
93 views

Chap 4: My - Thermo - Stat

The document contains 15 code snippets demonstrating various Python programming concepts like functions, conditionals, loops, and NumPy arrays. The snippets include examples of defining functions, using if/else conditional logic, iterating over arrays, and performing mathematical operations on scalar and array inputs. Test cases are provided to demonstrate expected functionality for many of the code snippets.

Uploaded by

Tôn Quang Tấn
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

CHAP 4

1) Write a function my_thermo_stat(temp, desired_temp). The return value of the function


should be the string ‘Heat’ if temp is less than desired_temp minus 5 degrees, ‘AC’ if
temp is more than the desired_temp plus 5, and ‘off’ otherwise.

def my_thermo_stat(temp, desired_temp):


    """
    Changes the status of the thermostat based on
    temperature and desired temperature
    author
    date
    :type temp: Int
    :type desiredTemp: Int
    :rtype: String
    """
    if temp < desired_temp - 5:
        status = 'Heat'
    elif temp > desired_temp + 5:
        status = 'AC'
    else:
        status = 'off'
    return status
status = my_thermo_stat(65,75)
print(status)
2) What will be the value of y after the following script is executed?
3) x = 3
4) if x > 1:
5)     y = 2
6) elif x > 2:
7)     y = 4
8) else:
9)     y = 0
10) print(y)
3) What will be the value of y after the following code is executed?

x = 3
if x > 1 and x < 2:
    y = 2
elif x > 2 and x < 4:
    y = 4
else:
    y = 0
print(y)
4)
Note that if you want the logical statement a < x < b, this is two conditional
statements, a < x and x < b. In Python, you can type a < x < b as well. For example:

x = 3
if 1 < x < 2:
    y = 2
elif 2 < x < 4:
    y = 4
else:
    y = 0
print(y)
5) Think about what will happen when the following code is executed. What are all the
possible outcomes based on the input values of x and y?

def my_nested_branching(x,y):
    """
    Nested Branching Statement Example
    author
    date
    :type x: Int
    :type y: Int
    :rtype: Int
    """
    if x > 2:
        if y < 2:
            out = x + y
        else:
            out = x - y
    else:
        if y > 2:
            out = x*y
        else:
            out = 0
    return out
6) Modify my_adder to throw out a warning if the user does not input numerical
values. Try your function for non-numerical inputs to show that the check works.
When a statement is too long, we can use ‘' symbol to break a line to multiple lines.

def my_adder(a, b, c):


    """
    Calculate the sum of three numbers
    author
    date
    """
   
    # Check for erroneous input
    if not (isinstance(a, (int, float)) \
            or isinstance(b, (int, float)) \
            or isinstance(c, (int, float))):
        raise TypeError('Inputs must be numbers.')
    # Return output
    return a + b + c
x = my_adder(1,2,3)
print(x)
7)  Write a function called is_odd that returns ‘odd’ if the input is odd and ‘even’ if it is
even. You can assume that input will be a positive integer.

def is_odd(number):
    """
    function returns 'odd' if the input is odd,
       'even' otherwise
    author
    date
    :type number: Int
    :rtype: String
    """
    # use modulo to check if the input is divisible by 2
    if number % 2 == 0:
        # if it is divisible by 2, then input is not odd
        return 'even'
    else:
        return 'odd'
print(is_odd(1))

8)  Write a function called my_circ_calc that takes a numerical number, r, and a


string, calc as input arguments. You may assume that r is positive, and that calc is
either the string ‘area’ or ‘circumference’. The function my_circ_calc should compute
the area of a circle with radius, r, if the string calc is ‘area’, and the circumference of a
circle with radius, r, if calc is ‘circumference’.

import numpy as np

def my_circ_calc(r, calc):


    """
    Calculate various circle measurements
    author
    date
    :type r: Int or Float or numpy array
    :type calc: String
    :rtype: Int or Float or numpy array
    """
    if calc == 'area':
        return np.pi * np.power(r, 2)
    elif calc == 'circumference':
        return 2 * np.pi * r

# Scalar input values


print(my_circ_calc(2.5, 'area'))  # Output: 19.634954084936208
print(my_circ_calc(3, 'circumference'))  # Output: 18.84955592153876

# Numpy array input values


print(my_circ_calc(np.array([2, 3, 4]), 'circumference')) # Output: [12.56637061
18.84955592 25.13274123]

9) : Ternary operator

is_student = True
person = 'student' if is_student else 'not student'
print(person)
is_student = True
if is_student:
    person = 'student'
else:
    person = 'not student'
print(person)
10)Write a function my_tip_calc(bill, party), where bill is the total cost of a meal and party is
the number of people in the group. The tip should be calculated as 15% for a party
strictly less than six people, 18% for a party strictly less than eight, 20% for a party less
than 11, and 25% for a party 11 or more. A couple of test cases are given below.

def my_tip_calc(bill, party):


    if party < 6:
        tip = 0.15
    elif party < 8:
        tip = 0.18
    elif party < 11:
        tip = 0.20
    else:
        tip = 0.25
    tips = bill * tip
    return round(tips, 4)
# t = 16.3935
t = my_tip_calc(109.29,3)
print(t) # output: 16.3935
# t = 19.6722
t = my_tip_calc(109.29,7)
print(t) # output: 19.6722
# t = 21.858
t = my_tip_calc(109.29,9)
print(t) # output: 21.858
# t = 27.3225
t = my_tip_calc(109.29,12)
print(t) # output: 27.3225

11)
Write a function my_mult_operation(a,b,operation)

def my_mult_operation(a, b, operation):


    if operation == 'plus':
        out = a + b
    elif operation == 'minus':
        out = a - b
    elif operation == 'mult':
        out = a * b
    elif operation == 'div':
        out = a / b
    elif operation == 'pow':
        out = a ** b
    else:
        raise ValueError('Invalid operation: ' + operation)
    return out
import numpy as np

x = np.array([1, 2, 3, 4])
y = np.array([2, 3, 4, 5])

# Output: [3, 5, 7, 9]
print(my_mult_operation(x, y, 'plus'))

# Output: [-1, -1, -1, -1]


print(my_mult_operation(x, y, 'minus'))
# Output: [2, 6, 12, 20]
print(my_mult_operation(x, y, 'mult'))

# Output: [0.5, 0.66666667, 0.75, 0.8]


print(my_mult_operation(x, y, 'div'))

# Output: [1, 8, 81, 1024]


print(my_mult_operation(x, y, 'pow'))

12)Consider a triangle with vertices at (0,0)(0,0), (1,0)(1,0), and (0,1)(0,1). Write a


function my_inside_triangle(x,y) where the output is the string ‘outside’ if the point (x,y) is
outside of the triangle, ‘border’ if the point is exactly on the border of the triangle, and
‘inside’ if the point is on the inside of the triangle.

def my_inside_triangle(x, y):


    # calculate the area of the triangle
    area_triangle = 0.5
   
    # calculate the areas of the three sub-triangles formed by the point (x,y)
and the vertices of the triangle
    area_sub1 = abs(x*(1-y))
    area_sub2 = abs((1-x)*y)
    area_sub3 = abs((x-y)*0)
   
    # if the sum of the areas of the sub-triangles is equal to the area of the
triangle, the point is inside the triangle
    if abs(area_sub1 + area_sub2 + area_sub3 - area_triangle) < 1e-10:
        return 'inside'
   
    # if the point is on the border of the triangle, it must lie on one of the
sides
    if abs(x*(1-y)) < 1e-10 or abs((1-x)*y) < 1e-10 or abs((x-y)*0) < 1e-10:
        return 'border'
   
    # if the point is neither inside the triangle nor on the border, it must be
outside
    return 'outside'
# Output: 'border'
print(my_inside_triangle(0.5, 0.5))

# Output: 'inside'
print(my_inside_triangle(0.25, 0.25))
# Output: 'outside'
print(my_inside_triangle(5, 5))

13) Write a function my_make_size10(x), where x is an array and output is the first 10


elements of x if x has more than 10 elements, and output is the array x padded with
enough zeros to make it length 10 if x has less than 10 elements.

import numpy as np

def my_make_size10(x):
    # convert x to a numpy array
    x = np.array(x)
   
    # if x has more than 10 elements, take the first 10
    if len(x) > 10:
        return x[:10]
   
    # if x has less than 10 elements, pad it with zeros
    else:
        return np.pad(x, (0, 10-len(x)), mode='constant')
print(my_make_size10(range(1,2)))   # Output: [1 2 0 0 0 0 0 0 0 0]
print(my_make_size10(range(1,15)))  # Output: [ 1  2  3  4  5  6  7  8  9 10]

print(my_make_size10([5, 5]))       # Output: [5 5 0 0 0 0 0 0 0 0]

14) Can you write my_make_size10 without using if-statements (i.e., using only logical
and array operations)?
1. import numpy as np
2.
3. def my_make_size10(x):
4.     size10 = np.zeros(10, dtype=int)
5.     size10[:min(10, len(x))] = x[:min(10, len(x))]
6.     return size10

15) Write a function my_letter_grader(percent), where grade is the string ‘A+’


if percent is greater than 97, ‘A’ if percent is greater than 93, ‘A-‘ if percent is greater
than 90, ‘B+’ if percent is greater than 87, ‘B’ if percent is greater than 83, ‘B-‘
if percent is greater than 80, ‘C+’ if percent is greater than 77, ‘C’ if percent is greater
than 73, ‘C-‘ if percent is greater than 70, ‘D+’ if percent is greater than 67, ‘D’
if percent is greater than 63, ‘D-‘ if percent is greater than 60, and ‘F’ for
any percent less than 60. Grades exactly on the division should be included in the
higher grade category.

def my_letter_grader(percent):
    if percent > 97:
        return 'A+'
    elif percent > 93:
        return 'A'
    elif percent > 90:
        return 'A-'
    elif percent > 87:
        return 'B+'
    elif percent > 83:
        return 'B'
    elif percent > 80:
        return 'B-'
    elif percent > 77:
        return 'C+'
    elif percent > 73:
        return 'C'
    elif percent > 70:
        return 'C-'
    elif percent > 67:
        return 'D+'
    elif percent > 63:
        return 'D'
    elif percent > 60:
        return 'D-'
    else:
        return 'F'
# Output: 'A+'
print(my_letter_grader(97))

# Output: 'B'
print(my_letter_grader(84))

# Output: 'F'
print(my_letter_grader(50))
# Output: 'A+'
print(my_letter_grader(97))

# Output: 'B'
print(my_letter_grader(84))

# Output: 'F'
print(my_letter_grader(50))

# Output: 'A-'
print(my_letter_grader(91))
# Output: 'D-'
print(my_letter_grader(61))

# Output: 'A-'
print(my_letter_grader(91))

# Output: 'D-'
print(my_letter_grader(61))

1. 16) Most engineering systems have redundancy. That is, an engineering system has
more than is required to accomplish its purpose. Consider a nuclear reactor whose
temperature is monitored by three sensors. An alarm should go off if any two of the
sensor readings disagree. Write a function my_nuke_alarm(s1,s2,s3) where s1, s2,
and s3 are the temperature readings for sensor 1, sensor 2, and sensor 3,
respectively. The output should be the string ‘alarm!’ if any two of the temperature
readings disagree by strictly more than 10 degrees and ‘normal’ otherwise.
2. def my_nuke_alarm(s1, s2, s3):
3.     diff1 = abs(s1 - s2)
4.     diff2 = abs(s1 - s3)
5.     diff3 = abs(s2 - s3)
6.    
7.     if diff1 > 10 and diff2 > 10:
8.         return 'alarm!'
9.     elif diff1 > 10 and diff3 > 10:
10.        return 'alarm!'
11.    elif diff2 > 10 and diff3 > 10:
12.        return 'alarm!'
13.    else:
14.        return 'normal'
15.print(my_nuke_alarm(94, 96, 90))  # Output: 'normal'
16.print(my_nuke_alarm(94, 96, 80))  # Output: 'alarm!'
17.print(my_nuke_alarm(100, 96, 90))  # Output: 'normal'
18.
17) Write a function my_split_function(f,g,a,b,x), where f and g are handles to
functions f(x) and g(x), respectively. The output should be f(x) if x≤a, g(x)
if x≥band 0 otherwise. You may assume that b>a.
import numpy as np

def my_split_function(f, g, a, b, x):


    if x <= a:
        return f(x)
    elif x >= b:
        return g(x)
    else:
        return 0

# Example usage
print(my_split_function(np.exp, np.sin, 2, 4, 1))  # Output: 2.718281828459045
print(my_split_function(np.exp, np.sin, 2, 4, 3))  # Output: -0.9589242746631385
print(my_split_function(np.exp, np.sin, 2, 4, 5))  # Output: 0

CHAP 5

1) What is the sum of every integer from 1 to 3?

n = 0
for i in range(1, 4):
    n = n + i
   
print(n)
2) Print all the characters in the string "banana".

for c in "banana":
    print(c)
s = "banana"
for i in range(len(s)):
    print(s[i])
3) Given a list of integers, a, add all the elements of a.

s = 0
a = [2, 3, 1, 3, 3]
for i in a:
    s += i # note this is equivalent to s = s + i
   
print(s)
4) Define a dictionary and loop through all the keys and values.

dict_a = {"One":1, "Two":2, "Three":3}

for key in dict_a.keys():


    print(key, dict_a[key])
5) Let the function have_digits has the input as a string. The output out should take
the value 1 if the string contains digits, and 0 otherwise. You could use
the isdigit method of the string to check if the character is a digit.

def have_digits(s):
   
    out = 0
   
    # loop through the string
    for c in s:
        # check if the character is a digit
        if c.isdigit():
            out = 1
            break
           
    return out
out = have_digits('only4you')
print(out)
6) : Let the function my_dist_2_points(xy_points, xy), where the input
argument xy_points is a list of x-y coordinates of a point in Euclidean space, xy is a list
that contain an x-y coordinate, and the output d is a list containing the distances
from xy to the points contained in each row of xy_points.

import math

def my_dist_2_points(xy_points, xy):


    """
    Returns an array of distances between xy and the points
    contained in the rows of xy_points
   
    author
    date
    """
    d = []
    for xy_point in xy_points:
        dist = math.sqrt(\
            (xy_point[0] - xy[0])**2 + (xy_point[1] - xy[1])**2)
       
        d.append(dist)
       
    return d
xy_points = [[3,2], [2, 3], [2, 2]]
xy = [1, 2]
print(my_dist_2_points(xy_points, xy))
7) Let x be a two-dimensional array, [5 6;7 8]. Use a nested for-loop to sum all the
elements in x.

import numpy as np
x = np.array([[5, 6], [7, 8]])
n, m = x.shape
s = 0
for i in range(n):
    for j in range(m):
        s += x[i, j]
       
print(s)
8) Determine the number of times 8 can be divided by 2 until the result is less than 1.

i = 0
n = 8

while n >= 1:
    n /= 2
    i += 1
   
print(f'n = {n}, i = {i}')
9)

n = 0
while n > -1:
    n += 1
print(n)
10)If x = range(5), square each number in x, and store it in a list y.

x = range(5)
y = []

for i in x:
    y.append(i**2)
print(y)
y = [i**2 for i in x]
print(y)
y = [i**2 for i in x if i%2 == 0]
print(y)
y = []
for i in range(5):
    for j in range(2):
        y.append(i + j)
print(y)

You might also like