python 练习扑克问题的迭代器。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python 练习扑克问题的迭代器。相关的知识,希望对你有一定的参考价值。

#Poker practice problems

#inner class that formats a member and suit into a card string
class Card:
		
	def __init__(self, member, suit):
		self.member = member
		self.suit = suit
	def __repr__(self):
		return "[{0}-{1}]".format(self.suit, self.member)

#Problem card suit
#card Iterator
class Deck:
	suits = ["S", "C", "H", "D"]
	members = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"]
	
	
	def __init__(self):
		self.deck = [Card(x, y) for x in Deck.suits for y in Deck.members]
		self.deck_index = -1
		
	def __iter__(self):
		return self
		
	def __next__(self):
		if self.deck_index == len(self.deck):
			raise StopIteration
		else:
			self.deck_index += 1
			return self.deck[self.deck_index]
			
			
#Example usage
"""
   d = Deck()
=> None
   d.dck
Traceback (most recent call last):
  File "python", line 1, in <module>
AttributeError: 'Deck' object has no attribute 'dck'
   d.deck
=> [[2-S], [3-S], [4-S], [5-S], [6-S], [7-S], [8-S], [9-S], [10-S], [J-S], [Q-S], [K-S], [2-C], [3-C], [4-C], [5-C], [6-C], [7-C], [8-C], [9-C], [10-C], [J-C], [Q-C], [K-C], [2-H], [3-H], [4-H], [5-H], [6-H], [7-H], [8-H], [9-H], [10-H], [J-H], [Q-H], [K-H], [2-D], [3-D], [4-D], [5-D], [6-D], [7-D], [8-D], [9-D], [10-D], [J-D], [Q-D], [K-D]]
   f = iter(d)
=> None
   next(f)
=> [2-S]
   next(f)
=> [3-S]
   
=> None
   next(f)
=> [4-S]
   
=> None
   next(f)
=> [5-S]
   next(f)
=> [6-S]
   next(f)
=> [7-S]
   next(f)
=> [8-S]
   next(f)
=> [9-S]
"""

以上是关于python 练习扑克问题的迭代器。的主要内容,如果未能解决你的问题,请参考以下文章

Python基础练习-迭代器

Python练习-一个简单易懂的迭代器,了解一下

Python学习iterator 迭代器小练习

Python语法练习_迭代器2

python3内置函数练习

Leetcode练习(Python):栈类:第173题:二叉搜索树迭代器:实现一个二叉搜索树迭代器。你将使用二叉搜索树的根节点初始化迭代器。 调用 next() 将返回二叉搜索树中的下一个最小的数。