I'm starting to learn Python as it seems to be adopted by many companies that
I've been looking to apply to. I used the book Learning Phython to get the
basics of the language and many of the gotcha's. I think I know enough of the
basic features of the language to start playing around and can understand most
code I've seen so far by looking at some of the posts here.
The one worry I have is not coding things the Phython way as I've been a Visual
Basic programmer for so long and a C++ programmer before that. So would like to
have people look at a simplistic class (shuffles lists of objects wrote it for
shuffling cards but with Phython could be used for any "list" type object) I
wrote to give me some feedback on the style of it.
Any feedback is appreciated.
Thanks,
Brian
import random
class shuffler(object):
def __init__(self):
self.rgen = random.Random()
def shuffle(self, inpile1, inpile2):
"""Function that shuffles two list of items."""
if self.rgen.randint(0,1): #randomly decide which pile is shuffled
down first
(pile1,pile2)=(inpile1,inpile2)
else:
(pile1,pile2)=(inpile2,inpile1)
pile1c = len(pile1)
pile2c = len(pile2)
rpile = pile1[0:0] #get blank copy of the passed in object types.
Should allow user defined list type objects to work as well
while pile1c and pile2c: #while there are still items in both piles
execute following logic
i = self.rgen.randint(1,4) #to allow for human error get random
offset of items to shuffle
if i > pile1c: #ensure we don't go out of bounds for the pile
i = pile1c
for x in range(0,i): #append cards to the output pile and remove
from shuffle pile
rpile.append(pile1.pop(0))
pile1c -= 1
i = self.rgen.randint(1,4) #to allow for human error get random
offset of items to shuffle
if i > pile2c: #ensure we don't go out of bounds for the pile
i = pile2c
for x in range(0,i): #append cards to the output pile and remove
from shuffle pile
rpile.append(pile2.pop(0))
pile2c -= 1
#check for which pile has left over items if any do
if pile1c:
rpile.extend(pile1)
elif pile2c:
rpile.extend(pile2)
return rpile
def shuffledeck(self, deck):
"""Function that shuffles a list type object"""
i = len(deck) #get length of the deck object to shuffle
cut = (i // 2) + self.rgen.choice(range(-4,5)) #find half way point of
deck +/- human error factor
pile1 = deck[0:cut]
pile2 = deck[cut:]
return self.shuffle(pile1,pile2)
if __name__ == '__main__':
myshuffle = shuffler()
deck = range(1,53)
print deck
for i in range(1,5):
deck = myshuffle.shuffledeck(deck)
print deck
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor