- 论坛徽章:
- 0
|
在QQ群里面出了个题目,发52张扑克牌到4个人,要随机,速度足够快。我写了一个,请大家指正。
- #!/usr/local/bin/python --
- # -*- coding: cp936 -*-
- import random,time
- class timer:
- def __init__(self):
- self.start= time.time()
- def stop(self):
- self.end= time.time()
- return "\n 本次运行已用时 %s秒"% (self.end-self.start)
- class people:
- #定义四个玩牌的人
- jack = []
- python = []
- java = []
- stephen = []
- def print_jack(self):
- i=0
- tmp = ''
- while i < 13:
- tmp += self.jack[i]+' '
- i += 1
- return tmp
- def print_python(self):
- i=0
- tmp = ''
- while i < 13:
- tmp += self.python[i]+' '
- i += 1
- return tmp
- def print_java(self):
- i=0
- tmp = ''
- while i < 13:
- tmp += self.java[i]+' '
- i += 1
- return tmp
- def print_stephen(self):
- i=0
- tmp = ''
- while i < 13:
- tmp += self.stephen[i]+' '
- i += 1
- return tmp
- class agent(people):
- def __init__(self):
- #定义一个空的列表存放牌
- self.card = []
- #定义洗牌的次数,并不是越大牌就越乱
- self.count = 52
- #定义一个基本的牌序
- self.base = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
- def arrangement(self):
- #重新排列纸牌
- i = 0
- while i < 13:
- self.card.insert(0,'黑桃'+self.base[i])
- i += 1
- i = 0
- while i < 13:
- self.card.insert(0,'红桃'+self.base[i])
- i += 1
- i = 0
- while i < 13:
- self.card.insert(0,'草花'+self.base[i])
- i += 1
- i = 0
- while i < 13:
- self.card.insert(0,'方块'+self.base[i])
- i += 1
- def shuffle(self):
- #洗牌
- i = 1
- while i < self.count:
- #产生一个随机数来确定要交换牌的位置
- position = random.randint(0,51)
- #临时取出一张牌准备用来交换位置
- tmp = self.card[position]
- #交换随机位置的牌和第一张牌
- self.card[position] = self.card[0]
- self.card[0] = tmp
- i += 1
- def outcards(self):
- #发牌
- i = 0
- while i < 52:
- if i <= 12:
- self.jack.insert(0,self.card[i])
- elif i >;= 12 and i <= 25 :
- self.python.insert(0,self.card[i])
- elif i >;= 25 and i <= 38 :
- self.java.insert(0,self.card[i])
- elif i >;= 38 and i <= 52 :
- self.stephen.insert(0,self.card[i])
- i += 1
- start=timer()
- a=agent()
- a.arrangement()
- a.shuffle()
- a.outcards()
- print a.print_jack()
- print a.print_python()
- print a.print_java()
- print a.print_stephen()
- print start.stop()
复制代码
另外,0.00999999046326好象是Python中最小计数了,再小就计算成0秒了。
还有python中for比where的速度要快,这个和C语言是反的。 |
|