In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
It is believed that many inexperienced people are at a loss about how to realize the functions of random card drawing, sorting and shuffling in Python. Therefore, this paper summarizes the causes and solutions of the problem. Through this article, I hope you can solve this problem.
Create a card class
Except for Wang and Xiao Wang, the remaining 52 cards (clubs, diamonds, spades, hearts) can be divided into four groups, each with 13 cards, so you can create two lists, one to store colors and one to store 13 characters; 52 cards are generated by a random combination of two lists
The code is as follows:
Import collectionsCard = collections.namedtuple ("Card", ['rank','suit']) class FrenchDeck: ranks = [str (n) for n in range (2 Magi 11)] + list ("JQKA") suits =' spades diamonds clubs hearts'.split () def _ init__ (self): self._cards = [Card (rank) Suit) for suit in self.suits for rank in self.ranks] def _ len__ (self): return len (self._cards) def _ getitem__ (self, position): return self._ cards [position]
In the code, a class is created through the collections.namedtuple module to represent a card, and ['rank','suit'] represents the characters in the cards (2-10 Jmura) and colors, respectively.
The FranchDeck class creates 52 cards, of which there are two special methods. Len () returns the number of cards, and _ _ getitem__ () gets the specified cards under position (index).
# create a card with Card beer_card = Card ('7cards / cards') print (beer_card) # printout deck = FrenchDeck () print ('len is -') print (len (deck)) # return the first card print (deck [0]) # return the last card print (deck [- 1]) # OutputCard (rank='7', suit='diamonds') len is-52Card (rank='2') Suit='spades') Card (rank='A', suit='hearts')
Pick a card at random
Here, the function of random card drawing is realized with the help of random module.
From random import choice# uses random.choice to randomly select a card print ("random choice -") print (choice (deck)) # Outputrandom choice-Card (rank='8', suit='clubs') Card (rank='5', suit='hearts') Card (rank='5', suit='spades')
List iteration, slicing
Because the _ _ getitem__ method gives the [] operation to the self._cards list, in addition to the index location mentioned above, the FranckDeck () class can also implement slicing and iterative operations
# slicing operation print ('\ nslice is--') print (deck [: 3]) print (deck [8:10]) print ('\ niterative operation') for card in deck [: 3]: print (card) print ('\ niterative operation') for card in reversed (deck [: 3]): print (card) # Outputslice is-- [Card (rank='2', suit='spades'), Card (rank='3', suit='spades'), Card (rank='4') Suit='spades')] [Card (rank='10', suit='spades'), Card (rank='J', suit='spades')] iterative operation Card (rank='2', suit='spades') Card (rank='3', suit='spades') Card (rank='4', suit='spades') reverse iterative operation Card (rank='4', suit='spades') Card (rank='3', suit='spades') Card (rank='2', suit='spades') sort operation
Generally speaking, if you judge the size of playing cards by points, 2 is the smallest and An is the largest. It is relatively simple to sort the points. The list of points is created in the order mentioned above. When sorting, you only need to sort according to the index where the points are located as the benchmark.
In addition to the number of points, there is also a color to consider, for color, we need to establish a mapping benchmark (can also be called weight), different colors are given different values; the dictionary type of Python can easily meet our needs
# create a dictionary map suit_values = dict (spades = 3, hearts = 2, diamonds = 1) Clubs = 0) def spades_high (card): rank_value = FrenchDeck.ranks.index (card.rank) # Index query return rank_value*len (suit_values) + suit_ values [card.cards] # index* 4 + suit.valueprint ('\ nSorted -') # sort the list using the key = lambda mechanism for card in sorted (deck,key = spades_high) Reverse= True): print (card) # OutputSorted-Card (rank='A', suit='spades') Card (rank='A', suit='hearts') Card (rank='A', suit='diamonds') Card (rank='A', suit='clubs') Card (rank='K', suit='spades') Card (rank='K', suit='hearts') Card (rank='K', suit='diamonds') Card (rank='K' Suit='clubs') Card (rank='Q', suit='spades') Card (rank='Q', suit='hearts') Card (rank='Q', suit='diamonds')
Code interpretation:
1. A mapping mechanism is added to the code using the dictionary, with 3 spades, 2 hearts, followed by squares, followed by clubs.
2. Create a spades_high function to calculate the total weight of each card.
3. Use the sorted () function key= spades_high as the sorting benchmark to realize the ranking of playing cards.
Shuffle operation
Shuffling simply means reordering a deck of playing cards irregularly. Normally, random.shuffle can easily implement this function, but the prerequisite is to ensure that the object meets the variable protocol. Here FranchDeck () is not satisfied, and an error will be reported if you use it directly:
From random import shuffleprint ('-\ nroom3) deck = FrenchDeck () shuffle (deck) # Output x [I], x [j] = x [j], x [I] TypeError: 'FrenchDeck' object does not support item assignment
For the above problem, you just need to change this class from immutable to mutable, and create a function that assigns the _ _ setitem__ attribute
From random import shuffleprint ('\ ndestroy 3) def set_deck (deck,position,card): deck._ cards [position] = carddeck1 = FrenchDeck () print ('before disrupting\ n') print (deck1 [: 5]) FrenchDeck.__setitem__ = set_deckshuffle (deck1) # Output before Card (rank='2', suit='spades') Card (rank='3', suit='spades') Card (rank='4') Suit='spades') Card (rank='5', suit='spades') Card (rank='6', suit='spades'): Card (rank='6', suit='diamonds') Card (rank='4', suit='hearts') Card (rank='Q', suit='diamonds') Card (rank='K', suit='clubs') Card (rank='8', suit='spades')
Here to extract the first five elements of cards before and after disruption, has achieved the function of shuffling!
According to the above code, we can further develop and design the visual pictures of 54 playing cards in advance.
Create a key:value mapping relationship, and create a mapping relationship between playing card characters and visual pictures, as shown in the following figure. Store this relationship set in a specified database or file, which can be called directly when you use it later.
After reading the above, have you mastered the method of how to randomly draw cards, sort cards and shuffle cards in Python? If you want to learn more skills or want to know more about it, you are welcome to follow the industry information channel, thank you for reading!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.