Python Open Labs: April 9, 2018

We spent class today reviewing functions and how they work in Python. Students were given problem statements and were asked to write functions to return the correct output. We went over multiple problems, and I’ll step through one in this blog post today.
Imagine that you are given two inputs in the form strings: Jewels and Stones.
Jewels contain unique characters, while Stones do not.
Here is what an example of what these inputs might look like:
Jewels = “aA”
Stones = “aAAbbbb”
Students were asked to write a function to count the number of Jewels present in Stones. In the example above, the output would be 3 given that “a” and “A” are Jewels and that there is 1 of “a” and 2 of “A” in Stones.
Students in the class understood that functions must start with a definition and contain a return statement. What was more difficult to come up with was the syntax used to solve the problem within the actual function itself.
Students eventually came up with the idea to initialize a value to store a result and simply loop through the Stones string to check how many Jewels appear in the Stones input.
Here is how one might solve the problem in code using Python:
def countJewelsinStones(Jewels, Stones):
>>>>count = 0
>>>>for s in Stones:
>>>>>>>>if s in Jewels:
>>>>>>>>>>>count += 1
>>>>return count
We can see that the approach is not only simple, but also uses concepts we’ve reviewed in previous lessons such as conditionals and for loops. I am excited to see that many students in the class were able to solve this problem with little assistance and can’t wait to see what they accomplish next!
Navie Narula