HW 5 Solutions
ENGR 21, Fall 2026.
Solutions
1 Stacking and looping
1.1 When stacking works
Write a function that takes as input two numpy arrays (assumed to be 2-dimensional — if not, it should print an error message and exit.
Your function should return a tuple of Booleans indicating:
- Whether the two arrays can be
hstack’ed - Whether the two arrays can be
vstack’ed
def check_stacking(array1, array2):
# check if array1 and array2 can be hstacked. Store result in can_hstack
can_hstack = False
# check if array1 and array2 can be vstacked. Store result in can_vstack
can_vstack = False
return (can_hstack, can_vstack)def check_stacking(array1, array2):
if np.shape(array1)[0] == np.shape(array2)[0]:
can_hstack = True
else:
can_hstack = False
if np.shape(array1)[1] == np.shape(array2)[1]:
can_vstack = True
else:
can_vstack = False
return (can_hstack, can_vstack)1.2 Looping over a numpy array
Consider the numpy array shown below, which has two dimensions.
array([[14., 15., 30.],
[ 3., 16., 4.],
[87., 35., 47.],
[96., 37., 85.]])Write two functions in Python that take as argument a 2-dimensional numpy array and print every element inside the array in two different ways:
- In row-first-then-column order, starting from the
[0,0]position, i.e., for the above example,14—15—30—3—16— … —37—85 - In coluumn-first-then-row order, starting from the
[-1,0]position. i.e., for the above example,96—87—3—14—37—35— … —4—30
Your functions should work on 2-dimensional arrays of arbitrary shape.
You need two separate functions here.
def print1(a):
for j in range(len(a[:,0])):
for i in range(len(a[0,:])):
print(a[j,i])def print2(a):
for i in range(len(a[0,:])):
for j in range(-1,-len(a[:,0])-1,-1):
print(a[j,i])2 Indexing and sorting etc.
The following Python variable gives 70 student numbers and 70 scores for each of those students in one 70 x 2 numpy array.
array([[ 1. , 75.2],
[ 2. , 76. ],
[ 3. , 86.3],
[ 4. , 71.8],
[ 5. , 82. ],
[ 6. , 84.6],
[ 7. , 73.8],
[ 8. , 71.1],
[ 9. , 75.5],
[10. , 83.1],
[11. , 81.2],
[12. , 73. ],
[13. , 78.7],
[14. , 83.4],
[15. , 78.5],
[16. , 82.7],
[17. , 89.3],
[18. , 83.7],
[19. , 77.8],
[20. , 73.7],
[21. , 76.9],
[22. , 80.2],
[23. , 87.8],
[24. , 85.5],
[25. , 76.4],
[26. , 88.5],
[27. , 79.4],
[28. , 83.9],
[29. , 72.1],
[30. , 72.1],
[31. , 74. ],
[32. , 87.7],
[33. , 83.6],
[34. , 87. ],
[35. , 82.9],
[36. , 78.1],
[37. , 80.3],
[38. , 81.9],
[39. , 87.2],
[40. , 78.8],
[41. , 87.8],
[42. , 82.3],
[43. , 86.6],
[44. , 80. ],
[45. , 83.9],
[46. , 76.8],
[47. , 80.5],
[48. , 74.3],
[49. , 72. ],
[50. , 70.8],
[51. , 84. ],
[52. , 79.1],
[53. , 88. ],
[54. , 86.7],
[55. , 77.7],
[56. , 89.5],
[57. , 81.8],
[58. , 85.3],
[59. , 78.1],
[60. , 73.9],
[61. , 73.4],
[62. , 73.6],
[63. , 82.1],
[64. , 72.3],
[65. , 70.4],
[66. , 86.7],
[67. , 72. ],
[68. , 79. ],
[69. , 79.8],
[70. , 82.4]])2.1 Calculate the mean, median, maximum, and minimum score
Write a Python program that prints out the mean, median, maximum and minimum score values, using print statements such as the following.
print(f"The mean score is {x} points")Assuming that the given array has been assigned to a variable called student_score, the following lines solve this problem.
print(f"The mean score is {np.mean(student_score[:,1]):.2f} points")
print(f"The median score is {np.median(student_score[:,1]):.2f} points")
print(f"The maximum score is {np.max(student_score[:,1]):.2f} points")
print(f"The minimum score is {np.min(student_score[:,1]):.2f} points")2.2 An array with students whose score are above 87.
Write a Python program that prints to the screen an Nx2 array consisting of only those students (including student number + that student’s score) whose score was greater than 87.
Assuming that the given array has been assigned to a variable called student_score, the single line of code
print(student_score[student_score[:,1]>87,:])solves this problem.
2.3 A sorted array of student numbers and scores
For this problem, you will need to make use of the function argsort.
Print a 2-dimensional array of student numbers and scores where the scores have been sorted from highest to lowest. Your sorting must preserve which score belongs to which student, i.e., both of your columns need to be re-arranged. For example, student 3 must still have 86.3 points.
The following one-liner solves this problem, assuming that the given array has been assigned to a variable called student_score.
print(student_score[np.argsort(student_score[:,1]),:])To make the solution more transparent, however, we can break it down.
# Extract scores and students
scores = student_score[:,1]
students = student_score[:,0]
# Use `argsort` to find the indices that, if applied
# to `scores`, would re-arrange them into the correct
# order
indices_to_reorder = np.argsort(scores)
# Use these seventy indices to access both columns
print(student_score[indices_to_reorder,:])2.4 Logical Indexing with multiple conditions
Print the student number and score of all students whose:
- student number is an even number, and
- score (before the decimal point) is an even number
- the function
np.int64()converts floating-point numbers to integers - Use
np.set_printoptions(precision=2)
3 Manipulating Arrays
3.1 Reshape
Write code that reshapes the given matrix into eight different shapes if possible. Each of your answers should result in a different shape.
>>> y = np.random.random((3,5,6))array([[[9.22e-01, 7.75e-01, 8.75e-01, 5.01e-01, 9.87e-01, 7.30e-01],
[3.95e-01, 4.52e-01, 6.85e-01, 3.12e-01, 5.58e-01, 2.00e-01],
[4.04e-01, 3.46e-01, 3.41e-01, 1.24e-01, 9.56e-01, 7.27e-01],
[2.16e-01, 8.41e-01, 2.12e-01, 8.09e-01, 9.91e-01, 8.28e-01],
[8.99e-01, 6.94e-01, 1.37e-01, 2.06e-01, 8.51e-01, 9.95e-01]],
[[2.00e-01, 1.34e-01, 4.01e-01, 2.34e-01, 8.29e-01, 5.76e-01],
[4.20e-02, 2.89e-02, 5.70e-01, 1.04e-01, 7.85e-01, 8.80e-01],
[1.45e-01, 7.66e-01, 5.24e-01, 7.34e-01, 4.43e-01, 7.75e-01],
[3.47e-01, 9.07e-01, 4.92e-02, 1.12e-01, 3.68e-02, 4.53e-01],
[5.28e-01, 1.69e-04, 8.48e-01, 4.62e-01, 4.59e-02, 7.80e-01]],
[[6.35e-01, 2.82e-01, 3.60e-01, 1.35e-01, 5.22e-01, 6.88e-01],
[8.87e-01, 7.33e-01, 8.14e-01, 6.00e-01, 1.03e-01, 3.29e-01],
[1.38e-01, 7.47e-01, 7.43e-03, 8.72e-01, 6.16e-01, 7.64e-01],
[1.94e-01, 2.36e-01, 4.48e-02, 6.36e-01, 3.62e-01, 2.51e-01],
[1.20e-01, 5.97e-02, 9.59e-01, 7.50e-01, 9.64e-01, 9.39e-02]]])The following should work to reshape the given array.
y.reshape((15,6))y.reshape((5,18))y.reshape((30,3))y.reshape((6,15))y.reshape((18,5))y.reshape((3,30))y.reshape((6,5,3))y.reshape((45,2))
3.2 3D slicing
- What one line of code will gather all red-highlighted values into one array?
- What one line of code will gather the orange-highlighted values into one place in the following form:
array([[0.31, 0.56],
[0.2 , 0.1 ],
[0.79, 0.88]])new1 = y[:,1,1]new2 = np.reshape(y[:2,1,3:],(3,2))
4 The Farmer Was Replaced
Pumpkins in TFWR show a special kind of behavior — they can get bigger if they are planted next to each other in patterns such as 2x2, 3x3, 4x4, etc, but they are also subject to the vagaries of fate and can spontaneously turn out rotten.
Download a save file for the game here.
Write a program for your drone that plants pumpkins in a formation at least 4x4 large in such a way that it waits until a big pumpkin appears before it harvests healthy pumpkins. The accompanying video shows you only one way to do this; there are lots of ways to accomplish this correctly.
In the video, the drone moves past pumpkins after planting them. Another approach could be to wait and see if a pumpkin will turn out rotten, and to only go ahead if the pumpkin has been determined to not be rotten.
Your code should run continuously, planting according to a pre-set pattern inside a while loop and harvesting everything it plants. Ideally, your farm should be self-sustaining, i.e., you should plant a combination of crops that allows you to continue harvesting for ever (yay sustainability).
It is recommended that you use dictionaries to determine what crops to plant where. For example, the following dictionary and list-of-list of plants was used here:
# An example pattern
pattern3 = [["t", "g", "g", "g","g","c","t","c"],
["g", "p", "p", "p","p","c","t","c"],
["g", "p", "p", "p","p","c","g","c"],
["g", "p", "p", "p","p","c","g","c"],
["g", "p", "p", "p","p","c","t","c"],
["c", "c", "c", "c","c","c","g","t"],
["t", "t", "g", "g","g","t","c","c"],
["c", "c", "c", "c","c","g","c","c"]]
# The dictionary definition
crops = {
"p": Entities.Pumpkin,
"t": Entities.Tree,
"g": Entities.Grass,
"c": Entities.Carrot
}
# An example pattern
pattern3 = [["t", "g", "g", "g","g","c","t","c"],
["g", "p", "p", "p","p","c","t","c"],
["g", "p", "p", "p","p","c","g","c"],
["g", "p", "p", "p","p","c","g","c"],
["g", "p", "p", "p","p","c","t","c"],
["c", "c", "c", "c","c","c","g","t"],
["t", "t", "g", "g","g","t","c","c"],
["c", "c", "c", "c","c","g","c","c"]]
pumpkinsize = 16
# The dictionary definition
crops = {
"p": Entities.Pumpkin,
"t": Entities.Tree,
"g": Entities.Grass,
"c": Entities.Carrot
}
def zeroloc():
xdist = get_pos_x()
ydist = get_pos_y()
for i in range(xdist):
move(West)
for i in range(ydist):
move(South)
return None
# Your function definition
def plant_pattern(pat):
for i in range(get_world_size()):
for j in range(get_world_size()):
current = get_entity_type()
if can_harvest():
harvest()
plant(crops[pattern3[i][j]])
move(East)
move(North)
# Initialize and till
clear()
for row in range(get_world_size()):
for col in range(get_world_size()):
if get_ground_type() == Grounds.Grassland:
harvest()
till()
move(East)
move(North)
while True:
zeroloc()
plant_pattern(pattern3)
while True:
deadpumpkincount = 0
livepumpkincount = 0
for i in range(get_world_size()):
for j in range(get_world_size()):
current = get_entity_type()
# Deal with pumpkins
if current == Entities.Dead_Pumpkin:
plant(Entities.Pumpkin)
deadpumpkincount += 1
print("oof!")
elif current == Entities.Pumpkin:
# Don't harvest pumpkins.
livepumpkincount += 1
pass
else:
# Harvest and plant what's there.
if can_harvest():
harvest()
plant(current)
move(East)
move(North)
print(livepumpkincount," live pumpkins")
if deadpumpkincount == 0 and livepumpkincount >= pumpkinsize:
print("Big pumpkin ready!")
break
else:
continue
# Now harvest pumpkin
move(East)
move(North)
# Harvest the big pumpkin !
harvest()