# Answer hereJulia Exercises
This document contains exercises that are intended to reinforce the concepts presented in Module 1. Each exercise should take <5 minutes to complete and there may be more than one way to approach each problem.
1 Exercise 1
- Create a variable
xand assign it a value of1.5as aString.
- Convert the value of
xto a numeric type that will preserve the decimal value, then assign the result to a variabley.
# Answer here- Create another variable
zand assign it the numeric value1.5.
# Answer here- Is the value of
yequal toz?
# Answer here- Is the value of
yidentical toz?
# Answer here2 Exercise 2
- How many operations are included in the logical expression:
false || true && true && false || true.
# Answer here- Predict the return value of the expression if it were entered into the REPL.
# Answer here- Write out the individual operations in the order they would be evaluated.
# Answer here- Modify the original expression to obtain the opposite result (e.g.,
false->true) by adding ≤3 characters.
# Answer here3 Exercise 3
- What are the 4 basic (primitive) data types in Julia?
# Answer here- Write two expressions that confirm
1.0is both aNumberandFloat64by returning a boolean value oftrue.
# Answer here- Explain why
1.0is both aNumberand aFloat64.
# Answer here
- Explain the difference between
Missingandmissing.
# Answer here
- Write an expression that evaluates whether
nothingandmissingare equivalent.
# Answer here4 Exercise 4
- The expression below creates a string of 1000 characters randomly sampled with replacement from the range “A-Z”.
s = join(rand('A':'Z', 1000))- Find the index of the first
'A'ins. If the search returnsnothing, choose a different character until the function returns a valid index. If changed, be sure to use the new character instead of'A'and'a'(e.g.,'B','b') for the remaining prompts in this exercise.
# Answer here- Modify the search so that it is case-insensitive, then test it using a lowercase
'a'.
# Answer here- Find the index for the last
'A'ins.
# Answer here- Write an expression that returns the characters in
sthat occur between the first and last indices identified above.
# Answer here- Write an expression that checks whether
scontains a string"AA".
# Answer here5 Exercise 5
- Which of Julia’s four basic data structures (
Tuple,NamedTuple,Dictionary, andArray) are mutable? Which are indexable?
# Answer here
- Create a
Dictionary,d1with Integer keys1,2,3, corresponding to values:"my string",99, and a tuple("x", "y", "z").
# Answer here- Unpack the second and third elements of the tuple in
d1into two variables,aandb, then use those variables to create aNamedTuple,ntp.
# Answer here- Change the value of
ntp.bto5; make sure the update is reflected inntp.
# Answer here- Create another
Dictionary,d2, fromntpwhere each key is of typeSymboland each value is of typeAny.
# Answer here- Write an expression that checks if key
cexists ind2wherec::Symbol; the expression should return a boolean value.
# Answer here- Add a key,
c, tod2, assign it a tuple containing a single value,1, then verify the type of value stored incusing the appropriate function.
# Answer here6 Exercise 6
- Create a 3x3 matrix,
Xwith values ranging from100to900.
# Answer here- There are at least 4 methods of indexing into
Xthat will return a scalar value of100; list 4 of them below.
# Answer here- Retrieve all values in the first row of
Xas both a column vector and a row vector.
# Answer here- Replace the values in the second row of
Xwith the values2, 5, 8(if you get an error here, read it carefully and apply the suggested fix).
# Answer here- Modify the elements of X so that the expression below evaluates
true.
# Answer here
zeros(Int, 3, 3) == X # check after modifying X- Consider the 4x2 matrix below, recreate this matrix by vertically concatenating 4 separate arrays.
# 5 10
# 15 20
# 25 30
# 35 40
# Answer here- Recreate the same 4x2 matrix above by horizontally concatenating 2
Ranges.
# Answer here7 Exercise 7
- Create a variable,
xand assign it a valuemissing. Write a simpleifstatement that will print the value ofxto the REPL if it ismissing.
# Answer here- Rewrite the simple
ifstatement above using a short-circuiting logical operator.
# Answer here- Consider the
ifstatement below. Rewrite the expression using the ternary operator (<cond> ? <true statement> : <false statement>).
#=
if a < 5
println("$a < 5")
else
println("$a ≥ 10")
end
=#
a = 10
# Answer here- The
if-elsestatement above was changed to anif-elseifstatement. Rewrite the expression using the ternary operator.
#=
if a < 5
println("$a < 5")
elseif a < 10
println("$a < 10")
else
println("$a ≥ 10")
end
=#
a = 10
# Answer here8 Exercise 8
- Create an empty vector,
v, ofInt64values and a counter,i = 0. Using awhileloop, increase the value ofiby2untili > 20and store the result of each iteration inv.
# Answer here- Create an empty
Dictionary,d, then use aforloop to populate it with the keys and values of theNamedTuple,ntp, below.
# Answer here
ntp = (; a = 100, b = "mystring", c = false)- Consider the comprehension below. In a few words, explain what is happening inside the comprehension.
A = [x^2 + 1 for x = 1:20]# Answer here
- Create an uninitialized 4x5
Array,B, ofInt64values, then use a nestedforloop to fillB, row-wise, with the elements ofA.
# Answer here- Repeat the step above, but this time, fill
Bcolumn-wise with the elements ofA.
# Answer here- Create a third 4x5
Array,C, that is typeInt64and contains only zeros. Use a single (non-nested)forloop to fillC, column-wise with the elements ofA.
# Answer here- Perform an element-wise comparison of the values in
BandCto check for equality; how would you interpret the resultingBitMatrix?
# Answer here9 Exercise 9
The Cockcroft-Gault formula provides an estimate of glomerular filtration rate (GFR) by calculating serum creatinine clearance (CrCL). While imperfect, CrCL is the standard metric used to guide dose adjustments for renal impairment.
The goal of this exercise is to implement the CG formula as a function and apply it across a range of values. A commonly used version of the formula is given below.
CrCL (mL/min) = (140-age)/scr * tbw/72 * 0.85^isfemale
Where:
age(years)scr(serum creatinine, mg/dL)tbw(total body weight, kg)isfemale(female sex, true/false)
- Create a function,
crcl1, using inline assignment and positional arguments.
# Answer here- Test
crcl1for a41y/o male patient weighing95.6kg with a SCr of1.2mg/dL
# Answer here- Test
crcl1for the same patient, but pass in,"41", forage. Read the error message carefully; if you did not know the cause up front, could you interpret the message and identify the problem?
# Answer here- Test
crcl1for the same patient, but pass inmissingforisfemale. Did you expect an error message, or amissingreturn value? Why?
# Answer here- Create a function,
crcl2, using thefunctionkeyword and kwargs. Set the default value forisfemaletofalse. Before calculating CrCL, the function should check whether the value of each continuous variable is aNumber; if not, it should return amissingvalue. (hint: there are several ways to write the check; consider reviewing,?isaand?all)
# Answer here- Test
crcl2for the same patient, making sure to test the “normal” case, then a case whereage,scr, ortbwis not aNumber.
# Answer here- Create a function
crcl3using kwargs and type assertion for each argument. Set the default value forisfemaletofalse.
# Answer here- Test
crcl3for the same patient using both a “normal” and “error” case.
# Answer hereNote: It is good practice to include basic error-handling in your code, but the way you define “basic” will evolve as you become more comfortable with Julia. Simply returning a missing value for common errors as in crcl2, is a valid approach, especially if you’re working alone and your code is well-documented. In larger projects, type assertion (e.g., crcl3) and more advanced error-handling workflows (e.g., try-catch, throw, @assert) become more important. When starting out, you can worry less about error handling since the code you write will naturally become more elegant (and less error-prone) over time.
- Use a comprehension and
crcl3to calculate CrCL across a range ofscrvalues (0.5:0.05:1.25) for a30y/o female weighing145lbs.
# Answer here- Explore the code below, then try to articulate what is happening with each component. If you encounter a function or symbol that is unfamiliar, check the help menu,
?. The goal here is to provide a few examples for generating and manipulating data based up on the techniques outlined so far.
# load package needed for Normal, Bernoulli distributions
using Pumas
# a data structure for storing "patients"
patients = Dict()
# a loop to create 10 patients with randomly sampled characteristics
for i = 1:10
# random input
age = rand(19:92)
scr = rand(Normal(0.9, 0.2))
tbw = rand(Normal(72, 20))
isfemale = rand(Bernoulli())
# save the input in a data structure for later
input = (; age, scr, tbw, isfemale)
# generate output
output = crcl3(; input...)
# save both as a entry in patients with a corresponding key
patients[i] = (; input, output)
end
patients[1] # key, *not* index
_in = [v.input for v in values(patients)]
_weights = [i.tbw for i in _in]
mean((i.tbw for i in _in))10 Exercise 10
- Consider the attempt at defining two methods for a function,
m, below. Execute the code in thebeginblock and then programmatically check the number of methods associated withm.
begin
m(; x::Real) = x + 3
m(; x::AbstractString) = parse(Float64, x) + 3
end
# Answer here- What happens if you execute the call below? Why?
m(x = 3)- Redefine
mto create the two intended methods above. How many total methods willmhave? Why? What happens if you try to setm = nothing? Why?
# Answer here- Define a vector,
x = [1,2,3]. Then, define a function that adds3to each element ofxand returns the sum of its elements. The function should modifyxin-place and follow the style convention for mutating functions.
# Answer here- Define a second version of your function above that performs the same operations without modifying the input outside of the function.
# Answer here