CS101. A25 - Inventory Management
CS101. A25 - Inventory Management
You will have to handle adding items to an inventory. Each time an item appears in a given list, increase the
item's quantity by 1 in the inventory. Then, you will have to handle deleting items from an inventory.
To finish, you will have to implement a function which returns all the key-value pairs in an inventory as a list
of tuples.
Implement the create_inventory() function that creates an "inventory" from a list of items. It should return a
dict containing each item name paired with their respective quantity.
Implement the decrement_items(<items>) function that takes a list of items. The function should remove
one from the available count in the inventory for each time an item appears on the list:
Item counts in the inventory should not fall below 0. If the number of times an item appears on the list
exceeds the count available, the quantity listed for that item should remain at 0 and additional requests for
removing counts should be ignored.
Implement the remove_item(<inventory>, <item>) function that removes an item and its count entirely from
an inventory:
If the item is not found in the inventory, the function should return the original inventory unchanged.
Implement the list_inventory() function that takes an inventory and returns a list of (item, quantity) tuples.
The list should only include the available items (with a quantity greater than zero):
def create_inventory(items):
"""
Sample output
Shown in the description.
Test Cases
Function Inputs Output
list_inventory {"coal":7, "wood":11, "diamond":2, "iron":7, [('coal', 7), ('diamond', 2), ('iron', 7),
"silver":0} ('wood', 11)]
list_inventory {"coal": 15, "diamond": 3, "wood": 67, [("coal", 15), ("diamond", 3),
"silver": 0} ("wood", 67)]
********
CS101. A26 - Wordy
Ref: https://github.com/rchatley/extreme_startup
Wordy requires you to parse (read a statement, understand the meaning based on the keywords) and
evaluate simple math word problems returning the answer as an integer.
Iteration 0 — Numbers
What is 5?
5
Iteration 1 — Addition
Add two numbers together. Handle large numbers and negative numbers.
What is 7 minus 5?
2
What is 6 multiplied by 4?
24
What is 25 divided by 5?
5
Handle a set of operations, in sequence. Since these are verbal word problems, evaluate the expression
from left-to-right, ignoring the typical order of operations.
Handle exponentials.
Iteration 5 - Errors
Tasks to implement:
Input is a question (a string datatype). Output of the function will be an integer or ValueError.
def answer(question):
pass
Sample output
print(answer(“What is 5?”))
5
Test Cases
Function Inputs Output
********
CS101. A27 - Saddle Points
Ref: J Dalbey's Programming Practice problems
1 2 3
|---------
1|9 8 7
2|5 3 2 <--- saddle point at column 1, row 2, with value 5
3|6 6 7
It's called a "saddle point" because it is greater than or equal to every element in its row and less than or
equal to every element in its column.
Your code should be able to provide the (possibly empty) list of all the saddle points for any given matrix.
The matrix can have a different number of rows and columns (Non square).
Tasks to implement:
Input is a matrix (list of rows). Each row is a list too. Eg. [[9, 8, 7], [5, 3, 2], [6, 6, 7]]
Return value: List of saddle points. Each saddle point is stored in a dictionary. The output for the above
input will be [{"row": 2, "column": 1}]. Multiple saddle points can be in any order.
def saddle_points(matrix):
pass
Sample output
print(saddle_points([[9, 8, 7], [5, 3, 2], [6, 6, 7]]))
[{'row': 2, 'column': 1}]
Test Cases
Function Inputs Output
********
CS101. A28 - grep
Ref: Conversation with Nate Foster, exercism.org
Search a file for lines matching a regular expression pattern. Return the line number and contents of each
matching line.
The Unix grep command can be used to search for lines in one or more files that match a user-provided
search query (known as the pattern).
Your task is to implement the grep function, which should read the contents of the specified files, find the
lines that match the specified pattern and then output those lines as a single string. Note that the lines
should be output in the order in which they were found, with the first matching line in the first file being
output first.
As an example, suppose there is a file named "input.txt" with the following contents:
hello
world
hello again
If we were to call grep "hello" input.txt, the returned string should be:
hello
hello again
Flags
As said earlier, the grep command should also support the following flags:
If we run grep -n "hello" input.txt, the -n flag will require the matching lines to be prefixed with its
line number:
1:hello
3:hello again
And if we run grep -i "HELLO" input.txt, we'll do a case-insensitive match, and the output will be:
hello
hello again
For example, running grep -l -v "hello" file1.txt file2.txt should print the names of files
that do not contain the string "hello".
Tasks to implement:
Inputs.
Output: grep output as a String. Eg.: "Of Atreus, Agamemnon, King of men.\n". Each line of
the output is terminated by a new line character ‘\n’.
'''
pass
Sample output
grep("Agamemnon", "", ["iliad.txt"])
"Of Atreus, Agamemnon, King of men.\n"
"With loss of Eden, till one "With loss of Eden, till one greater Man\n"
greater Man", "-x",
["paradise-lost.txt"]
"may", "-x", “”
["midsummer-night.txt"]
"WITH LOSS OF EDEN, TILL ONE "paradise-lost.txt:4:With loss of Eden, till one
GREATER MAN", "-n -i -x", greater Man\n"
["iliad.txt",
"midsummer-night.txt",
"paradise-lost.txt"]
********
CS101. A29 - Robot Simulator
Write a robot simulator.
● turn right
● turn left
● advance
Robots are placed on a hypothetical infinite grid, facing a particular direction (north, east, south, or west) at
a set of {x,y} coordinates, e.g., {3,8}, with coordinates increasing to the north and east.
The robot then receives a number of instructions, at which point the testing facility verifies the robot's new
position, and in which direction it is pointing.
Tasks to complete
In the Robot Class, complete the __init__ and the move methods.
Initialize the position of the Robot in __init__ . Default is to place the Robot at the origin (0,0) facing North.
The position of the Robot is present in the attribute coordinates (which is a tuple) containing (x_pos, y_pos).
Implement the move method. The movement is given by the route input parameter (which is a string). The
move method updates the coordinates and the direction attributes.
You are free to use the global constants: EAST, NORTH, WEST, SOUTH as desired.
class Robot:
coordinates=()
direction=NORTH
Test Cases
Inputs method/attributes
Robot(NORTH, 0, 0) coordinates=(0,0)
direction=NORTH
********
CS101. A30 - Minesweeper
Add the mine counts to a completed Minesweeper board.
Minesweeper is a popular game where the user has to find the mines using numeric hints that indicate how
many mines are directly adjacent (horizontally, vertically, diagonally) to a square.
In this exercise you have to create some code that counts the number of mines adjacent to a given empty
square and replaces that square with the count.
The board is a rectangle composed of blank space (' ') characters. A mine is represented by an asterisk ('*')
character.
If a given space has no adjacent mines at all, leave that square blank.
For example you may receive a 5 x 4 board like this (empty spaces are represented here with the '·'
character):
·*·*·
··*··
··*··
·····
The above mine board will be input to the function as a list of strings: [“ * * ”,” * ”,” * ”,” ”]
1*3*1
13*31
·2*2·
·111·
The output of the function (return value) is a list of strings: [“1*3*1”, “13*31”, “ 2*2 ”, “ 111 ”]
Tasks to complete
Input to the function is a list of Strings. Each string corresponds to a row of mines. ‘ ‘ - Space is no mine, ‘*’
- asterisk is a Mine. Eg. [" * ", " * ", "*****", " * ", " * "] is 5 rows.
Return value is also a list of strings. Eg. [" 2*2 ", "25*52", "*****", "25*52", " 2*2 "]
Raise a ValueError in case malformed board is input. Eg. [" ", "* ", " "] is a malformed board - unequal
columns in rows.
[] []
[""] [""]
[" ", " ", " "] [" ", " ", " "]
([“space space space”, ([“space space space”,
“space space space”, “space space space”,
“space space space”]) “space space space”])
[" ", "*", " ", "*", " "] ["1", "*", "2", "*", "1"]
([“space”, “star”, “space”, “star”, “space”])
["*", " ", " ", " ", "*"] ["*", "1", " ", "1", "*"]
([“star”, “space”, “space”, “space”, “star”]) ([“star”, “1”, “space”, “1”, “star”])
[" * ", " * ", "*****", " * ", " * "] [" 2*2 ", "25*52", "*****", "25*52", " 2*2 "]
([“space space star space space”,
“space space star space space”,
“star star star star star”,
“space space star space space”,
“space space star space space”])
[" * * ", " * ", " * ", " * *", " * * ", " "] ['1*11*1', '111222', ' 113*2', '12*4*3', '1*23*2', '111111']
([“space star space space star space”,
“space space star space space space”,
“space space space space star space”,
“space space space star space star”,
“space star space space star space”,
“space space space space space”])
[" ", " * ", " ", " ", " * "] [" 111", " 1*1", " 111", "111 ", "1*1 "]
([“space space space space space”, ([“space space 1 1 1”,
“space space space star space”, “space space 1 star 1”,
“space space space space space”, “space space 1 1 1”,
“space space space space space”, “1 1 1 space space”,
“space star space space space”]) “1 star 1 space space”])
[" ", "* ", " "] raise ValueError("The board is invalid with current
([“space”, input.")
“star space space”,
“space space space space space”,
“space space”])
Step 1
Handle the basic case of 0 through 99. If the input to the program is 22, then the output should be
'twenty-two'. Your program should complain if given a number outside the range.
● 0
● 14
● 50
● 98
● -1
● 100
Step 2
Implement breaking a number up into chunks of thousands. So 1234567890 should yield a list like 1, 234,
567, and 890, while the far simpler 1000 should yield just 1 and 0. The program must also report any values
that are out of range.
Step 3
Now handle inserting the appropriate scale word between those chunks. So 1234567890 should yield '1
billion 234 million 567 thousand 890'
The program must also report any values that are out of range. Stop at "trillion".
Step 4
Put it all together to get nothing but plain English. 12345 should give twelve thousand three hundred
forty-five. The program must also report any values that are out of range.
● 14 becomes "fourteen".
● 100 becomes "one hundred".
● 120 becomes "one hundred and twenty".
● 1002 becomes "one thousand and two".
● 1323 becomes "one thousand three hundred and twenty-three".
Error messages
def say(number):
pass
Sample output
Shown in description
Test Cases
Inputs
0 “zero”
1 “one”
14 “fourteen”
20 “twenty”
22 “twenty-two”
987654321123 "nine hundred eighty-seven billion six hundred fifty-four million three hundred
twenty-one thousand one hundred twenty-three"
********
CS101. A32 - Scrabble Score
Letter Values
Letter Value
A,E,I,O,U,L,N,R,S,T 1
D,G 2
B,C,M,P 3
F,H,V,W,Y 4
K 5
J,X 8
Q,Z 10
Example
● 3 points for C
● 1 point for A, twice
● 3 points for B, twice
● 2 points for G
● 1 point for E
And to total:
● 3 + 2*1 + 2*3 + 2 + 1
● =3+2+6+3
● =5+9
● = 14
Tasks to complete
Test Cases
Inputs Return value
“a” 1
“A” 1
“f” 4
“at” 2
“zoo” 12
“street” 6
“quirky” 22
“OxyphenButazone” 41
“pinata” 8
“” 0
“abcdefghijklmnopqrstuvwxyz” 87
********
CS101. A33 - Kindergarten Garden
Ref: http://jumpstartlab.com/, exercism.org
Given a diagram, determine which plants each child in the kindergarten class is responsible for.
The kindergarten class is learning about growing plants. The teacher thought it would be a good idea to
give them actual seeds, plant them in actual dirt, and grow actual plants.
To this end, the children have put little cups along the window sills, and planted one type of plant in each
cup, choosing randomly from the available types of seeds.
[window][window][window]
........................
Each child gets 4 cups, two on each row. Their teacher assigns cups to the children alphabetically by their
names.
[window][window][window]
VR......................
RG......................
In the first row, nearest the windows, she has a violet and a radish. In the second row she has a radish and
some grass.
Your program will be given the plants from left-to-right starting with the row nearest the windows. From this,
it should be able to determine which plants belong to each student.
For example, if it's told that the garden looks like so:
[window][window][window]
VRCGVVRVCGGCCGVRGCVCGCGV
VRCCCGCRRGVCGCRVVCVGCGCV
Then if asked for Alice's plants, it should provide:
Tasks to complete
In the Garden Class, complete the __init__ and the plants methods.
Inputs to the constructor: diagram, and list of students in the class. Eg. ['Alice','Bob', 'Charlie', 'David','Eve',
'Fred', 'Ginny', 'Harriet','Ileana', 'Joseph', 'Kincaid','Larry']
The plants method takes a student’s name as input and returns his/her plant names.
Test Cases
Inputs method/attributes
********
CS101. A34 - Alien Game
Instructions
You are creating a game where the player has to fight aliens. You have decided to use Object Oriented
Programming (OOP) to take advantage of using classes for this game.
Define the Alien class with a constructor that accepts two parameters <x_coordinate> and <y_coordinate>,
putting them into x_coordinate and y_coordinate instance variables. Every alien will also start off with a
health level of 3, so the health variable should be initialized as well.
>>> alien.x_coordinate
>>> alien.y_coordinate
>>> alien.health
Now, each alien should be able to internally track its own position and health.
The Alien class has a hit method that decrements the health of an alien object by 1 when called. Calling hit
on a zero health Alien does not reduce the health to below zero.
>>> alien.health
>>> alien.hit()
>>> alien.health
You realize that if the health keeps decreasing, at some point it will probably hit 0. It would be a good idea
to add an is_alive method that can be called to check if the alien is alive. <alien>.is_alive() should return a
boolean.
>>> alien.health
>>> alien.is_alive()
True
>>> alien.hit()
>>> alien.health
>>> alien.is_alive()
False
In the game, the aliens have the ability to teleport! You will need to write a teleport method that takes new
x_coordinate and y_coordinate values, and changes the alien's coordinates accordingly.
>>> alien.x_coordinate
>>> alien.y_coordinate
-4
Obviously, if the aliens can be hit by something, then they need to be able to detect when such a collision
has occurred. However, collision detection algorithms can be tricky, and you do not yet know how to
implement one. This will be implemented later, but the collision_detection method has to appear in the class
as a reminder to build out the functionality. It will need to take an input variable of some kind (probably
another object), but that's really all you know. You will need to make sure that putting the method definition
into the class doesn't cause any errors when called:
>>> alien.collision_detection(other_object)
>>>
6. Alien Counter
Keep track of how many aliens have been created over the game's lifetime. Create a counter to count
number of Alien objects created. Ideally, this counter would increment whenever someone made an new
Alien. Class attributes can be changed from an instance method by using the class name: Alien.<class
attribute name>
For example:
>>> alien_one = Alien(5, 1)
>>> alien_one.total_aliens_created
>>> alien_two.total_aliens_created
>>> alien_one.total_aliens_created
>>> Alien.total_aliens_created
7. Object Creation
Create a standalone function to create a list of alien objects, given a list of positions (as tuples).
For example:
print(alien.x_coordinate, alien.y_coordinate)
(4, 7)
(-1, 0)
Tasks to complete
In the Alien Class, complete the __init__ and the above mentioned methods.
class Alien:
"""Create an Alien object with location x_coordinate and y_coordinate.
Attributes
----------
(class)total_aliens_created: int
x_coordinate: int - Position on the x-axis.
y_coordinate: int - Position on the y-axis.
health: int - Amount of health points.
Methods
-------
hit(): Decrement Alien health by one point.
is_alive(): Return a boolean for if Alien is alive (if health is > 0).
teleport(new_x_coordinate, new_y_coordinate): Move Alien object to new
coordinates.
collision_detection(other): Implementation TBD.
"""
Sample output
Shown in description
Test Cases
Inputs method/attributes
Alien.total_aliens_created = 0 Alien.total_aliens_created = 3
aliens = [Alien(-2, 6)]
aliens.append(Alien(3, 5))
aliens.append(Alien(-5, -5))
position_data = [(-2, 6), (1, 5), (-4, -3)] obj_list[0].x_coordinate = -2
obj_list = new_aliens_collection(position_data) obj_list[0].y_coordinate = 6
obj_list[1].x_coordinate = 1
obj_list[1].y_coordinate = 5
obj_list[2].x_coordinate = -4
obj_list[2].y_coordinate = -3
********
CS101. A35 - Binary Search
Searching a sorted collection is a common task. A dictionary is a sorted list of word definitions. Given a
word, one can find its definition. A telephone book is a sorted list of people's names, addresses, and
telephone numbers. Knowing someone's name allows one to quickly find their telephone number and
address.
If the list to be searched contains more than a few items (a dozen, say) a binary search will require far
fewer comparisons than a linear search, but it imposes the requirement that the list be sorted.
In computer science, a binary search or half-interval search algorithm finds the position of a specified input
value (the search "key") within an array sorted by key value.
In each step, the algorithm compares the search key value with the key value of the middle element of the
array.
If the keys match, then a matching element has been found and its index, or position, is returned.
Otherwise, if the search key is less than the middle element's key, then the algorithm repeats its action on
the sub-array to the left of the middle element or, if the search key is greater, on the sub-array to the right.
If the remaining array to be searched is empty, then the key cannot be found in the array and a special "not
found" indication is returned.
A binary search halves the number of items to check with each iteration, so locating an item (or determining
its absence) takes logarithmic time.. A binary search is a dichotomic divide and conquer search algorithm.
Example 1.
Value to search: 6
1 3 4 6 8 9 11
1 3 4 6 8 9 11
Example 2.
Value to search: 1
1 3 4 6 8 9 11
1 3 4 6 8 9 11
search_list[3] = 6. 1 is lesser than 6. Search in the upper half of the list.
1 3 4 6 8 9 11
1 3 4 6 8 9 11
1 3 4 6 8 9 11
Mid index = 0.
1 3 4 6 8 9 11
If the value to be searched was 0. Raise “value not found” ValueError exception
Tasks to complete
Implement BinarySearch algorithm in the find() function. Inputs to the find function: a sorted list of numbers
( search_list), and a value to search.
Test Cases
Inputs Return Value
find([6], 6) 0
find([1, 3, 4, 6, 8, 9, 11], 6) 3
find([1, 3, 4, 6, 8, 9, 11], 1) 0
find([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 634], 144) 9
find([1, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377], 21) 5
find([1, 3, 4, 6, 8, 9, 11], 7) raise ValueError("value not in array")
********