Menu

[Solved]Python Coding Assignment Understanding Importing Modules Using Lists Dictionaries Creating Q37020469

Python coding assignment.

Your understanding of importing modules, using lists anddictionaries and creating objects from a class will be exercised inthis lab.

Be prepared to use your solution for the Classes lab where youwrote the PlayingCardclass (shown at end).

In this lab, you will have to generate a random list ofPlayingCard objects for where the suit and rank combinations ofeach card are randomly chosen. Using this list of randomly createdplaying cards, you will use dictionaries and lists to storeimportant data about these playing cards, particularly thefrequency distribution of each rank-suit combination you created(e.g. like if 10 queen of hearts cards are generated andcounted.)

Thanks to the clearly described interface used to communicate toany PlayingCardobject, specifically the get_rank() and get_suit()methods, you can just import your “Classes” lab as a module and useyour previously written code!

Note: You’ll definitely need to make sure your solutionswork for this lab, and if not, please consult the professor or TAsfor assistance, ASAP.

  1. I provide a starter (skeleton) code file for your solution(shown below). You are required to use it.

    1. from random import randrange
      from lab_classes import PlayingCard
      from math import sqrt

      suit_size = 13 # Number of cards in a suit.
      deck_size = 52 # Number of cards in a deck.
      num_cards = 260 # Number of cards to create with random rank &suit values

      def make_random_cards():
      “””Generate num_cards number of random PlayingCard objects.

      This function will generate num_cards RANDOM playing cards
      using your PlayingCard class. That means you will have to choose arandom
      suit and rank for a card num_cards times.

      Printing:
      Nothing

      Positional arguments:
      None

      Returns:
      cards_list — a list of PlayingCard objects.
      “””

      #
      # REPLACE WITH YOUR CODE.
      #

      return cards_list

      def freq_count(cards_list):
      “””Count every suit-rank combination.

      Returns a dictionary whose keys are the card suit-rank and valueis the
      count.

      Printing:
      Nothing

      Positional arguments:
      cards_list — A list of PlayingCard objects.

      Returns:
      card_freqs — A dictionary whose keys are the single letter in theset
      ‘d’, ‘c’, ‘h’, ‘s’ representing each card suit. The value for eachkey
      is a list containing the number of cards at each rank, using theindex
      position to represent the rank. For example, {‘s’: [0, 3, 4, 2,5]}
      says that the key ‘s’, for ‘spades’ has three rank 1’s (aces),four
      rank 2’s (twos), two rank 3’s (threes) and 5 rank 4’s (fours).Index
      position 0 is 0 since no cards have a rank 0, so make note.
      “””
      # DO NOT REMOVE BELOW
      if type(cards_list) != list or
      list(filter(lambda x: type(x) != PlayingCard, cards_list)):
      raise TypeError(“cards_list is required to be a list of PlayingCard
      objects.”)
      # DO NOT REMOVE ABOVE

      #
      # REPLACE WITH YOUR CODE.
      #

      return card_freqs

      def std_dev(counts):
      “””Calculate the standard deviation of a list of numbers.

      Positional arguments:
      counts — A list of ints representing frequency counts.

      Printing:
      Nothing

      Returns:
      _stdev — The standard deviation as a single float value.
      “””
      # DO NOT REMOVE BELOW
      if type(counts) != list or
      list(filter(lambda x: type(x) != int, counts)):
      raise TypeError(“counts is required to be a list of intvalues.”)
      # DO NOT REMOVE ABOVE

      #
      # REPLACE WITH YOUR CODE.
      #

      return _stdev

      def print_stats(card_freqs):
      “””Print the final stats of the PlayingCard objects.

      Positional arguments:
      card_freqs — A dictionary whose keys are the single letter in theset
      ‘dchs’ representing each card suit. The value for each key is alist of
      numbers where each index position is a card rank, and its value isits
      card frequency.

      You will probably want to call th std_dev function in somewherein
      here.

      Printing:
      Prints the statistic for each suit to the screen, see assignmentpage
      for an example output.

      Returns:
      None
      “””
      # DO NOT REMOVE BELOW
      if type(card_freqs) != dict or
      list(filter(lambda x: type(card_freqs[x]) != list,card_freqs)):
      raise TypeError(“card_freqs is required to be a dict where eachvalue is a list of ints.”)
      # DO NOT REMOVE ABOVE

      #
      # REPLACE WITH YOUR CODE.
      #

      def main():
      cards = make_random_cards()
      suit_counts = freq_count(cards)
      print_stats(suit_counts)

      if __name__ == “__main__”:
      main()

  2. Your lab assignment requires the use of your solution from theClasses lab. You will import your code as a module and use yourPlayingCard class.

    The skeleton code includes the necessary import line, justprovide your file by placing a copy of your lab_classes.py file inthe same directory as your solution code for this lab.

  3. The docstrings inside this file describe what each functionshould do.

  4. Replace and complete missing code wherever you see::

    ## REPLACE WITH YOUR CODE.#

    Do not change anything else like function names,parameters or return values. Do not remove the if statements at thestart of some functions as they are needed to make sure you arepassing the correct values. You will lose points you if you changeanything you are not supposed to change.

Output

This is what you should see (your numbers will bedifferent):

Standard deviation for the frequency counts of each rank in suit: Hearts: 2.3755 cards Spades: 1.1242 cards Clubs: 1.4880 cards Diamonds: 1.5607 cards

Playing card class:

from random import randrange

class PlayingCard:
def __init__(self, rank, suit):
self.rank = rank
self.suit = suit

# returns rank of card as an integer
def get_rank(self):
return self.rank

# returns suit of card as a single character string
def get_suit(self):
return self.suit

# returns blackjack value as an integer
def bj_value(self):
if self.rank > 10:
return 10
else:
return self.rank

# converts non-printing objects into strings
def __repr__(self):

_rank = [“Ace”, “Two”, “Three”, “Four”, “Five”, “Six”,”Seven”,
“Eight”, “Nine”, “Ten”, “Jack”, “Queen”, “King”]
_suit = [“Diamonds”, “Clubs”, “Hearts”, “Spades”]

suit_name = _rank[self.rank – 1] + ” of “

if self.suit == “d”:
suit_name = suit_name + _suit[0]
elif self.suit == “c”:
suit_name = suit_name + _suit[1]
elif self.suit == “h”:
suit_name = suit_name + _suit[2]
elif self.suit == “s”:
suit_name = suit_name + _suit[3]
return suit_name

def main():

suit_character = [“d”, “c”, “h”, “s”]

print(“Testing card class”)
n = eval(input(“How many cards would you like to see? “))

for i in range(n):
rank = randrange(1, 14) # Ace to King (13 ranks)
suit = suit_character[randrange(0, 4)]
call_function = PlayingCard(rank, suit)
# printing bj_vlue instead of rank since face cards
# in blackjack have a value of ten
print(call_function, “counts”, call_function.bj_value())

if __name__ == ‘__main__’:
main()

Expert Answer


Answer to Python coding assignment. Your understanding of importing modules, using lists and dictionaries and creating objects fro… . . .

OR


Leave a Reply

Your email address will not be published. Required fields are marked *