Challenge Question Solution
The solution of the challenge question is 10. The reasoning behind this output is due to how dictionaries work. Remember that when accessing information from dictionaries, you can access key-value pairs. When accessing a key from a dictionary, you get back the value of that key-value pair. The following line is accessing the value of the first item within the card variable:
>>> card[0]
This will result in “Q”, as it is the first item within the tuple assigned into card. When we access the dictionary, we’re accessing the value of the “Q” key. The last line would look like this:
>>> print("{ }".format(values["Q"]))
This would then output the value of the “Q:10” key-value pair, which is 10.
Weekly Challenges
To test out your skills, try these challenges:
Game Loop: Using the code from our Friday project, create a game loop so that you can continually play a new hand until the player decides to quit. The cell should only stop running if the player types in “quit”; otherwise, you should continue to play new hands.
Adding Currency: Using the code from our Friday project, add the ability to wager currency in the game. Be sure to track the currency within the Player class, as the attribute should belong to that object. Before each hand, ask the user how much they would like to wager; if they win, add that amount to their currency; if they lose, subtract that amount from what they currently have; and if they tie, nothing should happen.
CHAPTER 8
Advanced Topics I: Efficiency
Now that we have a solid base to work from, we can begin to dive into more advanced topics. Over the next two weeks, we’ll be covering concepts that help to reduce the amount of code you need to write. Many of these concepts will help prepare us for data analysis in Week 10.
Throughout this week, we’ll be covering one-liners using list comprehension and anonymous functions. This will help to reduce the lines of code by condensing the same functionality within a single line. We’ll then cover a few of the built-in Python functions that make working with data easier. The last concept we cover is when functions call themselves, known as a recursive function. Often, these types of functions lack efficiency, so we’ll cover how to use a caching concept called memoization. As this week is all about advanced topics, we’ll dive into one of the more important algorithms in programming… Binary Search! We’ll see how to program this algorithm line by line and understand how searching algorithms are able to work efficiently.
Overview
Building lists in one line using comprehensions
Understanding one-line anonymous functions
Using Python’s built-in functions for list alteration
Understanding recursive functions and how to improve them
Writing the algorithm for Binary Search
© Connor P. Milliken 2020
C. P. Milliken, Python Projects for Beginners, https://doi.org/10.1007/978-1-4842-5355-7_8
Do'stlaringiz bilan baham: |