[Tutor] First code snipet
Andreas Kostyrka
andreas at kostyrka.org
Sun Jul 26 03:02:27 CEST 2009
Some things:
1) It's Python, not Phython.
2) Slightly shorter solution to your problem:
import random
input = range(53)
random.shuffle(input)
print input
3) The important part here is that reimplementing something that is in
the standard library does not make sense usually.
4) A more sensible implementation of shuffle comes directly out of
random.py:
def shuffle(self, x, random=None, int=int):
"""x, random=random.random -> shuffle list x in place; return
None.
Optional arg random is a 0-argument function returning a random
float in [0.0, 1.0); by default, the standard random.random.
"""
if random is None:
random = self.random
for i in reversed(xrange(1, len(x))):
# pick an element in x[:i+1] with which to exchange x[i]
j = int(random() * (i+1))
x[i], x[j] = x[j], x[i]
Notice that it is not exactly optimal, one could easily replace the
reversed(xrange()) expression with a 3 parameter version of xrange:
for i in xrange(len(x) - 1, 0, -1):
Andreas
Am Samstag, den 25.07.2009, 17:15 -0700 schrieb Darth Kaboda:
> 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
> _______________________________________________
> Tutor maillist - Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
-------------- next part --------------
A non-text attachment was scrubbed...
Name: not available
Type: application/pgp-signature
Size: 197 bytes
Desc: Dies ist ein digital signierter Nachrichtenteil
URL: <http://mail.python.org/pipermail/tutor/attachments/20090726/37f6e0fa/attachment.pgp>
More information about the Tutor
mailing list