This lab gives you practice with basic Python syntax, editing a notebook and uploading it to the web site.
Version 1. Apr 23, 2019.
Instructions:
Modify this notebook by adding the Python code described below.
Test your code using the menu item Cell ► Run All
Submit the notebook (the .ipynb file) to the appropriate dropbox on the course web site.
Run, but do not modify the following cell. When the cell is run it sets some variables to random values that subsequent cells will modify. Make sure you run this cell in your own notebook -- your results should not match anyone else's.
# this code sets some variables that you will need to use in your solution
# the variables will be set to different values each time you run this cell
# do not modify this code!
import random
runtime=random.randrange(100,700)
Z=complex(random.randrange(-50,50)/10,random.randrange(-50,50)/10)
partnumber=''.join(random.choices('ABXYMN'+'0123456789',k=random.randrange(7,10)))
print('set runtime={} Z={} partnumber={}'.format(runtime,Z,partnumber))
Create an integer variable called mtbf
that has value equal to 1000 minus the current value of the integer variable runtime
. For example, if runtime
has the value 350 then the variable runtime
should be set to 650.
mtbf=1000-runtime
mtbf
Create a float variable called slope
that has a value equal to the ratio of the imaginary to real components of the complex variable Z
. For example, if Z
has the value 0.5+2j then slope
should be set to the value 0.25.
slope=Z.imag/Z.real
slope
Create a list variable called digits
containing the digits in the string partnumber
as integers. For example, if partnumber
has the value "M19D35", digits
should have the value [1, 9, 3, 5].
Hints: (1) The expression c >= '0' and c <= '9'
is true when c
is a digit. (2) The function int(c)
will return an integer value equal to its argument, which can be of various types, including a string. (3) The list member function append()
adds its argument to the end of the list.
digits=[]
for c in partnumber:
if c>='0' and c <='9':
digits.append(int(c))
digits
Create a float variable called check
that has a value equal to the sum of the squares of the last two digits in partnumber
. For the example above, check
should have the value 34.
check=digits[-1]**2 + digits[-2]**2
check
# lab validation code; do not modify
def labcheck():
def q1():
assert mtbf+runtime==1000
def q2():
import math
import cmath
assert abs((math.tan(cmath.phase(Z))-slope)/slope)<1e-4
def q3():
import re
assert digits == list(map(int,re.findall('[0-9]',partnumber)))
def q4():
assert sum([n*n for n in digits])-check==sum(map(lambda x:x*x,digits[:-2]))
for i,s in ((i,'q%d'%i) for i in range(1,20)):
if s in locals():
try:
locals()[s]()
print("Question {} OK.".format(i))
except Exception as e:
print("Failed check for Question {}: {}".format(i,e))
labcheck()