more card play

classic Classic list List threaded Threaded
13 messages Options
Reply | Threaded
Open this post in threaded view
|

more card play

kirby urner-4
I'm becoming more enamored of the idea of using playing cards as a
standard feature in my Python pedagogy and andragogy (means teaching
adults).  Not only do we have the standard deck, but also Tarot which
could get us more into text files, string substitution
(string.Template) and so forth.

Cards have all the elements

Mathematically, a Deck suggests the difference between Cardinality
(yes, a silly pun) and Ordinality.  You might imagine a deck in which
you can't decipher the cards, don't know their "face value", and so
have no clear idea of their ranking (ordinality).

On the other hand, you know which cards are the same and which are
different across multiple decks (le'ts just say), which is the meaning
of "cardinality" (difference without any implied ordering).

Midhat Gazele dwells on this difference some in his book 'Number'.
You might have a set of objects, say stones or wasp specimens, and a
way of cataloging them that doesn't implement > or < or even ==.
There is only the Python "is" and "is not" for determining of two
objects have the same identity or not.  License plates on cars, proper
names, have this purpose of distinguishing.

However, very quickly just about any set beyond a certain size needs
an ordering, perhaps simply alphabetical, so that one might flip
through a lookup table in a hurry and get to the desired object.
People used to use ledgers, thick books, for such cataloging.

This is the beginning of data structuring or data structures.  The
idea of "ordering" (ordinality) is very closely associated with that
of cardinality.

Anyway, over on Pyfora I was noticing a member suggesting reversing a
string might be best accomplished by thestring[::-1], i.e. extended
slicing with from the end to the beginning step with a step of -1.
However PEP 322 suggests this will be inefficient compared a a built
in function introduced in 2.4:  reversed.

According to the PEP, all reversed needs is for the consumed object to
support __getitem__ and __len__.  If those two are present, the
function will do the rest, and return an iterator object in which the
contents of a sequence are iterated over in reverse order.

>>> a = 'the rain in spain stays mainly in the plain'
>>> ''.join(reversed(a))
'nialp eht ni ylniam syats niaps ni niar eht'

So for our Deck to be reversible by means of this built in function,
the only methods we need to implement are these two, __getitem__ and
__len__.  I do this below, plus make shuffling the deck upon
instantiation an option, not de rigueur (not mandatory).  This makes
it easier to see what reverse order is like.

Note that the returned iterable is not itself a Deck, nor is it
subscriptable, as the whole point of an iterable is it returns its
contents "just in time" as you iterate over it.  The cards are not
"already present" in reversed order, are simply returned in reverse
order.

Of course you can force the iterable to dump all its contents by
coercing it into a list.  I do this as a part of the clone_deck
method.  Playing Game of War with clone decks, one the reverse of the
other, results in a draw if always dealing from the top (now the
default, yet still optional).

The code below is just my Game of War again, with a few wrinkles.
I've upgraded all string printing to use the
print(thestring.format(args)) approach, versus the old percent sign
string substitution codes.  Other small improvements.

>>> from sillygame import Deck
>>> d = Deck(10)
>>> newd = d.clone_deck()
>>> newd[0] is d[0]
True
>>> id(newd[0])
22884944
>>> id(d[0])
22884944
>>> d.shuffle()
>>> str(d)
"['7 of Diamonds', 'Jack of Spades', 'Queen of Clubs', 'King of
Spades', '5 of Clubs', '3 of Spades', '6 of Hearts', 'Ace of Clubs',
'2 of Hearts', '9 of Spades']"
>>> str(newd)
"['2 of Hearts', 'Queen of Clubs', '6 of Hearts', '9 of Spades', '5 of
Clubs', '7 of Diamonds', 'Ace of Clubs', '3 of Spades', 'Jack of
Spades', 'King of Spades']"
>>> d[0]
Card(Diamonds, ('7', 7))
>>> newd[5]
Card(Diamonds, ('7', 7))
>>> d[0] == newd[5]
True
>>> d[0] is newd[5]
True

Kirby

For further reading:
http://www.python.org/dev/peps/pep-0322/


from random import shuffle, randint

thesuits = ['Hearts','Diamonds','Clubs','Spades']
theranks = ['Ace'] + [str(v) for v in range(2,11)] + ['Jack','Queen','King']
rank_values = list(zip(theranks, range(1,14)))

class Card:

    def __init__(self, suit, rank_value ):
        self.suit = suit
        self.rank = rank_value[0]
        self.value = rank_value[1]

    def __lt__(self, other):
        if self.value < other.value:
            return True
        else:
            return False

    def __gt__(self, other):
        if self.value > other.value:
            return True
        else:
            return False

    def __eq__(self, other):
        if self.value == other.value:
            return True
        else:
            return False

    def __repr__(self):
        return "Card({0}, {1})".format(self.suit, (self.rank, self.value))

    def __str__(self):
        return "{0} of {1}".format(self.rank, self.suit)

class Deck:

    def __init__(self, numcards = 52, shuffle = True):
        # build a complete deck then slice
        try:
            assert 0 < numcards <= 52
        except AssertionError:
            print("Defaulting to 52 cards")
            numcards = 52

        self.numcards = numcards
        self.cards = [Card(suit, rank_value)
                      for suit in thesuits
                      for rank_value in rank_values
                       ]
        if shuffle: self.shuffle()
        self.cards = self.cards[ : self.numcards]

    def __getitem__(self, index):
        return self.cards[index]

    def shuffle(self):
        shuffle(self.cards)

    def spit_card(self, top=True):
        try:
            assert self.numcards > 0
        except AssertionError:
            raise Exception("Out of cards!")

        if top:
            some_card = self.cards.pop(0)
        else:
            some_card = self.cards.pop( randint( 0, self.numcards - 1 ))

        self.numcards = len(self.cards)
        return some_card

    def clone_deck(self, reverse=False):
        newdeck = Deck(numcards=1)
        newdeck.numcards = self.numcards
        if reverse:
            newdeck.cards = list(reversed(self.cards))
        else:
            newdeck.cards = self.cards[:]
        return newdeck

    def __repr__(self):
        return "Deck({0})".format(self.numcards)

    def __str__(self):
        return str([str(card) for card in self.cards])

    def __len__(self):
        return len(self.cards)

def test():
    thedeck = Deck()
    print (str(thedeck))

def game_of_war():
    deckA = Deck(10)
    # deckB = Deck(10)
    deckB = deckA.clone_deck(reverse=True) # play a reversed clone
    PlayerA_score = 0
    PlayerB_score = 0

    try:
        assert deckA.numcards == deckB.numcards
    except AssertionError:
        raise Exception("Decks don't have same number of cards")

    for i in range(deckA.numcards):
        playerA_card = deckA.spit_card(top=False) # deal from anywhere
        playerB_card = deckB.spit_card(top=False)

        if playerA_card > playerB_card:
            PlayerA_score += 1
            print("A's {0} beats B's {1}".format(playerA_card, playerB_card))
        if playerA_card < playerB_card:
            PlayerB_score += 1
            print("B's {0} beats A's {1}".format(playerB_card, playerA_card))
        if playerA_card == playerB_card:
            print("B's {0} matches A's {1}".format(playerB_card, playerA_card))

    if PlayerA_score > PlayerB_score:
        print("Game Over:  A wins")
    if PlayerA_score < PlayerB_score:
        print("Game Over:  B wins")
    if PlayerA_score == PlayerB_score:
        print("Game Over:  it's a draw!")

if __name__ == '__main__':
    # test()
    game_of_war()
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

Mokurai
Cards: You are right on the merits for combinatory math, but you will
run into strong cultural aversions.

Reverse string in place with new iterator: There is a great deal more
of this. In the 1980s Hewlett-Packard built an APL system around such
transformations in place and lazy evaluation rules, including
matrix/table transpose, take, drop, catenate, laminate, and a number
of other transformations and combinations. I can probably dig out
Harry Saal's paper on the subject. Indeed, that and several others.

http://portal.acm.org/citation.cfm?id=801218&dl=GUIDE&coll=GUIDE&CFID=59626041&CFTOKEN=28525913
An APL compiler for the UNIX timesharing system

http://portal.acm.org/citation.cfm?id=586034&dl=GUIDE&coll=GUIDE&CFID=59626133&CFTOKEN=77609109
Considerations in the design of a compiler for APL

http://portal.acm.org/citation.cfm?id=804441
A software high performance APL interpreter

On Sun, Nov 1, 2009 at 19:55, kirby urner <[hidden email]> wrote:

> I'm becoming more enamored of the idea of using playing cards as a
> standard feature in my Python pedagogy and andragogy (means teaching
> adults).  Not only do we have the standard deck, but also Tarot which
> could get us more into text files, string substitution
> (string.Template) and so forth.
>
> Cards have all the elements
>
> Mathematically, a Deck suggests the difference between Cardinality
> (yes, a silly pun) and Ordinality.  You might imagine a deck in which
> you can't decipher the cards, don't know their "face value", and so
> have no clear idea of their ranking (ordinality).
>
> On the other hand, you know which cards are the same and which are
> different across multiple decks (le'ts just say), which is the meaning
> of "cardinality" (difference without any implied ordering).
>
> Midhat Gazele dwells on this difference some in his book 'Number'.
> You might have a set of objects, say stones or wasp specimens, and a
> way of cataloging them that doesn't implement > or < or even ==.
> There is only the Python "is" and "is not" for determining of two
> objects have the same identity or not.  License plates on cars, proper
> names, have this purpose of distinguishing.
>
> However, very quickly just about any set beyond a certain size needs
> an ordering, perhaps simply alphabetical, so that one might flip
> through a lookup table in a hurry and get to the desired object.
> People used to use ledgers, thick books, for such cataloging.
>
> This is the beginning of data structuring or data structures.  The
> idea of "ordering" (ordinality) is very closely associated with that
> of cardinality.
>
> Anyway, over on Pyfora I was noticing a member suggesting reversing a
> string might be best accomplished by thestring[::-1], i.e. extended
> slicing with from the end to the beginning step with a step of -1.
> However PEP 322 suggests this will be inefficient compared a a built
> in function introduced in 2.4:  reversed.
>
> According to the PEP, all reversed needs is for the consumed object to
> support __getitem__ and __len__.  If those two are present, the
> function will do the rest, and return an iterator object in which the
> contents of a sequence are iterated over in reverse order.
>
>>>> a = 'the rain in spain stays mainly in the plain'
>>>> ''.join(reversed(a))
> 'nialp eht ni ylniam syats niaps ni niar eht'
>
> So for our Deck to be reversible by means of this built in function,
> the only methods we need to implement are these two, __getitem__ and
> __len__.  I do this below, plus make shuffling the deck upon
> instantiation an option, not de rigueur (not mandatory).  This makes
> it easier to see what reverse order is like.
>
> Note that the returned iterable is not itself a Deck, nor is it
> subscriptable, as the whole point of an iterable is it returns its
> contents "just in time" as you iterate over it.  The cards are not
> "already present" in reversed order, are simply returned in reverse
> order.
>
> Of course you can force the iterable to dump all its contents by
> coercing it into a list.  I do this as a part of the clone_deck
> method.  Playing Game of War with clone decks, one the reverse of the
> other, results in a draw if always dealing from the top (now the
> default, yet still optional).
>
> The code below is just my Game of War again, with a few wrinkles.
> I've upgraded all string printing to use the
> print(thestring.format(args)) approach, versus the old percent sign
> string substitution codes.  Other small improvements.
>
>>>> from sillygame import Deck
>>>> d = Deck(10)
>>>> newd = d.clone_deck()
>>>> newd[0] is d[0]
> True
>>>> id(newd[0])
> 22884944
>>>> id(d[0])
> 22884944
>>>> d.shuffle()
>>>> str(d)
> "['7 of Diamonds', 'Jack of Spades', 'Queen of Clubs', 'King of
> Spades', '5 of Clubs', '3 of Spades', '6 of Hearts', 'Ace of Clubs',
> '2 of Hearts', '9 of Spades']"
>>>> str(newd)
> "['2 of Hearts', 'Queen of Clubs', '6 of Hearts', '9 of Spades', '5 of
> Clubs', '7 of Diamonds', 'Ace of Clubs', '3 of Spades', 'Jack of
> Spades', 'King of Spades']"
>>>> d[0]
> Card(Diamonds, ('7', 7))
>>>> newd[5]
> Card(Diamonds, ('7', 7))
>>>> d[0] == newd[5]
> True
>>>> d[0] is newd[5]
> True
>
> Kirby
>
> For further reading:
> http://www.python.org/dev/peps/pep-0322/
>
>
> from random import shuffle, randint
>
> thesuits = ['Hearts','Diamonds','Clubs','Spades']
> theranks = ['Ace'] + [str(v) for v in range(2,11)] + ['Jack','Queen','King']
> rank_values = list(zip(theranks, range(1,14)))
>
> class Card:
>
>    def __init__(self, suit, rank_value ):
>        self.suit = suit
>        self.rank = rank_value[0]
>        self.value = rank_value[1]
>
>    def __lt__(self, other):
>        if self.value < other.value:
>            return True
>        else:
>            return False
>
>    def __gt__(self, other):
>        if self.value > other.value:
>            return True
>        else:
>            return False
>
>    def __eq__(self, other):
>        if self.value == other.value:
>            return True
>        else:
>            return False
>
>    def __repr__(self):
>        return "Card({0}, {1})".format(self.suit, (self.rank, self.value))
>
>    def __str__(self):
>        return "{0} of {1}".format(self.rank, self.suit)
>
> class Deck:
>
>    def __init__(self, numcards = 52, shuffle = True):
>        # build a complete deck then slice
>        try:
>            assert 0 < numcards <= 52
>        except AssertionError:
>            print("Defaulting to 52 cards")
>            numcards = 52
>
>        self.numcards = numcards
>        self.cards = [Card(suit, rank_value)
>                      for suit in thesuits
>                      for rank_value in rank_values
>                       ]
>        if shuffle: self.shuffle()
>        self.cards = self.cards[ : self.numcards]
>
>    def __getitem__(self, index):
>        return self.cards[index]
>
>    def shuffle(self):
>        shuffle(self.cards)
>
>    def spit_card(self, top=True):
>        try:
>            assert self.numcards > 0
>        except AssertionError:
>            raise Exception("Out of cards!")
>
>        if top:
>            some_card = self.cards.pop(0)
>        else:
>            some_card = self.cards.pop( randint( 0, self.numcards - 1 ))
>
>        self.numcards = len(self.cards)
>        return some_card
>
>    def clone_deck(self, reverse=False):
>        newdeck = Deck(numcards=1)
>        newdeck.numcards = self.numcards
>        if reverse:
>            newdeck.cards = list(reversed(self.cards))
>        else:
>            newdeck.cards = self.cards[:]
>        return newdeck
>
>    def __repr__(self):
>        return "Deck({0})".format(self.numcards)
>
>    def __str__(self):
>        return str([str(card) for card in self.cards])
>
>    def __len__(self):
>        return len(self.cards)
>
> def test():
>    thedeck = Deck()
>    print (str(thedeck))
>
> def game_of_war():
>    deckA = Deck(10)
>    # deckB = Deck(10)
>    deckB = deckA.clone_deck(reverse=True) # play a reversed clone
>    PlayerA_score = 0
>    PlayerB_score = 0
>
>    try:
>        assert deckA.numcards == deckB.numcards
>    except AssertionError:
>        raise Exception("Decks don't have same number of cards")
>
>    for i in range(deckA.numcards):
>        playerA_card = deckA.spit_card(top=False) # deal from anywhere
>        playerB_card = deckB.spit_card(top=False)
>
>        if playerA_card > playerB_card:
>            PlayerA_score += 1
>            print("A's {0} beats B's {1}".format(playerA_card, playerB_card))
>        if playerA_card < playerB_card:
>            PlayerB_score += 1
>            print("B's {0} beats A's {1}".format(playerB_card, playerA_card))
>        if playerA_card == playerB_card:
>            print("B's {0} matches A's {1}".format(playerB_card, playerA_card))
>
>    if PlayerA_score > PlayerB_score:
>        print("Game Over:  A wins")
>    if PlayerA_score < PlayerB_score:
>        print("Game Over:  B wins")
>    if PlayerA_score == PlayerB_score:
>        print("Game Over:  it's a draw!")
>
> if __name__ == '__main__':
>    # test()
>    game_of_war()
> _______________________________________________
> Edu-sig mailing list
> [hidden email]
> http://mail.python.org/mailman/listinfo/edu-sig
>



--
Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
Silent Thunder is my name, and Children are my nation.
The Cosmos is my dwelling place, the Truth my destination.
http://www.earthtreasury.org/
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

Laura Creighton-2
In a message of Mon, 02 Nov 2009 20:27:35 PST, Edward Cherlin writes:
>Cards: You are right on the merits for combinatory math, but you will
>run into strong cultural aversions.

Why?  Especially when _dice_ seem to be the preferred way to teach
this stuff?  (Or is this only here?)

Laura
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

kirby urner-4
In reply to this post by Mokurai
On Mon, Nov 2, 2009 at 8:27 PM, Edward Cherlin <[hidden email]> wrote:
Cards: You are right on the merits for combinatory math, but you will
run into strong cultural aversions.


Yes, anticipated.  However, the Python subculture has done the necessary work to publish a Diversity Statement, which has an antibiotic effect against puritanical bigots (assuming you mean some people have moral hangups about gambling?). 

The State of Oregon funds its education system with inputs from video poker machines whereas the various tribal sovereignties in this area earn a living from their resort casinos. 

So it's integral to our way of life to teach "casino math" (we don't necessarily call it "combinatorics" at first, as that just scares people away, makes 'em think we're only into academic applications whereas of course nothing could be further from the truth).
 
Reverse string in place with new iterator: There is a great deal more
of this. In the 1980s Hewlett-Packard built an APL system around such

Yes, the idea of an iterable goes hand-in-hand with the Pythonic notion of a generator.  Both support the "next" API, a keyword you might assign another name to if you like.  I've recommended "kick" as in "kick the can down the road", with each use generating a next term in some famous (or not famous) sequence:

>>> def cubocta():
    n = 0
    while True:  # infinite loop OK!
        if n == 0:
            yield 1
        else:
            yield 10 * n * n + 2
        n += 1

       
>>> kick = next
>>> can = cubocta()
>>> kick(can)
1
>>> kick(can)
12
>>> kick(can)
42
>>> kick(can)
92
>>> kick(can)
162
>>>

See:  http://www.research.att.com/~njas/sequences/A005901 (note link to virus morphology)

In the example below, I'm showing how "nexting" through an iterable is a lazy evaluation affair in that I'm changing the first member of the list *after* assigning a name to the iterator.  By the time the iterator reaches the first member of the list, the value has changed from when it started.

>>> some_list = [1,2,3,4,5]
>>> iterable = reversed(some_list)
>>> next(iterable)
5
>>> some_list[0] = "Joker!"
>>> next(iterable)
4
>>> next(iterable)
3
>>> next(iterable)
2
>>> next(iterable)
'Joker!'

Notice that two iterators have their separate journeys through the target object i.e. advancing one of them doesn't have any affect on the other:

>>> some_list = [1,2,3,4,5]
>>> iterableA = reversed(some_list)
>>> iterableB = reversed(some_list)
>>> next(iterableA)
5
>>> next(iterableA)
4
>>> next(iterableA)
3
>>> next(iterableA)
2
>>> next(iterableA)
1
>>> some_list[0] = "Joker!"
>>> next(iterableB)
5
>>> next(iterableB)
4
>>> next(iterableB)
3
>>> next(iterableB)
2
>>> next(iterableB)
'Joker!'
>>>

Of course strings are immutable so you can't play quite the same trick, of messing with the target string before the reversed iterator reaches the beginning.

In the case of my Deck and Card classes, the cloned deck had its own complete list in reversed order (an option), however the underlying Card objects were identical across lists, as I was showing by using the "is" operator.

 
transformations in place and lazy evaluation rules, including
matrix/table transpose, take, drop, catenate, laminate, and a number
of other transformations and combinations. I can probably dig out
Harry Saal's paper on the subject. Indeed, that and several others.

http://portal.acm.org/citation.cfm?id=801218&dl=GUIDE&coll=GUIDE&CFID=59626041&CFTOKEN=28525913
An APL compiler for the UNIX timesharing system

http://portal.acm.org/citation.cfm?id=586034&dl=GUIDE&coll=GUIDE&CFID=59626133&CFTOKEN=77609109
Considerations in the design of a compiler for APL

http://portal.acm.org/citation.cfm?id=804441
A software high performance APL interpreter


I've always thought Python had a lot in common with APL, especially in terms of how it organizes a lot of highly orthogonal built-in primitives to inter-operate in logically consistent ways.  I was privileged to collaborate a little with Kenneth Iverson on my 'Jiving in J' paper.  To this day, I recommend J as a second language, as I think a competent CS0/CS1 would never feature just a single programming language (too narrowing), even if it makes one primary and the other secondary.  A more traditional option is to feature one agile and one system language, e.g. Python and C, or Jython and Java.

Kirby
4D

 
On Sun, Nov 1, 2009 at 19:55, kirby urner <[hidden email]> wrote:
> I'm becoming more enamored of the idea of using playing cards as a
> standard feature in my Python pedagogy and andragogy (means teaching
> adults).  Not only do we have the standard deck, but also Tarot which
> could get us more into text files, string substitution
> (string.Template) and so forth.
>
> Cards have all the elements

...
 
--
Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
Silent Thunder is my name, and Children are my nation.
The Cosmos is my dwelling place, the Truth my destination.
http://www.earthtreasury.org/


_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

Travis Vaught-2

On Nov 3, 2009, at 10:04 AM, kirby urner wrote:

On Mon, Nov 2, 2009 at 8:27 PM, Edward Cherlin <[hidden email]> wrote:
Cards: You are right on the merits for combinatory math, but you will
run into strong cultural aversions.


Yes, anticipated.  However, the Python subculture has done the necessary work to publish a Diversity Statement, which has an antibiotic effect against puritanical bigots (assuming you mean some people have moral hangups about gambling?). 

I was rather assuming that the hangups would be about the more cringe-worthy aspects of tarot cards.  The fact that people of faith may not get a good feeling about using a tool whose logo is a snake, introductory examples are using tarot cards, and whose theme music might be construed to be the rather irreverent creations of the Monty Python players, says less about the presence of puritanical bigotry and more about a complete lack of sophistication in marketing.

I love a good example (and a good joke) as much as the next guy, but let's not lean on a diversity statement as an excuse to not attend to some basic tenets of marketing.  If we had examples that incorporated the various "Stations of the Cross" it would likewise go over like a lead balloon.

Introducing Python as a unifying tool in early education (by some definition of early) calls for a particular discretion in the choice of examples.

Best,

Travis



_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

kirby urner-4
In reply to this post by Laura Creighton-2
On Mon, Nov 2, 2009 at 10:20 PM, Laura Creighton <[hidden email]> wrote:
> In a message of Mon, 02 Nov 2009 20:27:35 PST, Edward Cherlin writes:
>>Cards: You are right on the merits for combinatory math, but you will
>>run into strong cultural aversions.
>
> Why?  Especially when _dice_ seem to be the preferred way to teach
> this stuff?  (Or is this only here?)
>
> Laura
>

Yeah, dice are the perfect math object in that they unify polyhedra
and randomness (chaotic sequences) in a single artifact.

That we have all the Platonic solids as dice these days is a cool
development, suitable for translating into software.[0]

from random import choice

class Die:
        def __init__(self, number_of_sides = 6):
            self.facets = number_of_sides
        def roll(self):
            return choice(range(1, self.facets+ 1))  # eliminate 0
        def __str__(self):
            return "{0} sided die".format(self.facets)
        def __repr__(self):
            return "Die({0})".format(self.facets)

>>> thedie = Die(20)
>>> thedie.roll()
14
>>> thedie.roll()
10
>>> thedie.roll()
7
>>> thedie
Die(20)
>>> str(thedie)
'20 sided die'

Here's a more complicated version (not by me) that rolls a sum as
triggered by the __rmul__ rib.
http://code.activestate.com/recipes/573437/

Of course it might make a lot more sense to write this as a two line
generator, could then go roll = next to assign the next keyword
another name.

>>> from random import randint

>>> def die(sides):
        while True:  yield randint(1, sides)
               
>>> icosa_die = die(20)
>>> roll = next
>>> roll(icosa_die)
10
>>> roll(icosa_die)
18
>>> roll(icosa_die)
8
>>> roll(icosa_die)
4

Speaking of Open Education standards, the Boston Globe is finally
getting into print what many have seen as the writing on the wall:
mass published wood pulp textbooks are taking a back seat to digital
distribution mechanisms.[1]

USG stimulus money is helping to fuel the transition, ironically by
funding proprietary initiatives versus creating more FOSS of by and
for the people.

Also ironic is the fact that use US military is a leading proponent of
FOSS [2] given its already socialized mindset (i.e. its assets are
communally owned and operated).[3]

The White House recently switched to Drupal in a symbolic gesture.

Kirby

[0] http://www.dice.co.uk/poly_re.htm
[1] http://mybizmo.blogspot.com/2009/11/not-following-detroit.html
[2] http://controlroom.blogspot.com/2009/10/open-source-dot-gov.html
[3] http://controlroom.blogspot.com/2009/11/socialist-victory-satire.html
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

kirby urner-4
In reply to this post by Travis Vaught-2
On Tue, Nov 3, 2009 at 8:48 AM, Travis Vaught <[hidden email]> wrote:

>
> On Nov 3, 2009, at 10:04 AM, kirby urner wrote:
>
> On Mon, Nov 2, 2009 at 8:27 PM, Edward Cherlin <[hidden email]> wrote:
>>
>> Cards: You are right on the merits for combinatory math, but you will
>> run into strong cultural aversions.
>>
>
> Yes, anticipated.  However, the Python subculture has done the necessary
> work to publish a Diversity Statement, which has an antibiotic effect
> against puritanical bigots (assuming you mean some people have moral hangups
> about gambling?).
>
> I was rather assuming that the hangups would be about the more cringe-worthy
> aspects of tarot cards.  The fact that people of faith may not get a good
> feeling about using a tool whose logo is a snake, introductory examples are
> using tarot cards, and whose theme music might be construed to be the rather
> irreverent creations of the Monty Python players, says less about the
> presence of puritanical bigotry and more about a complete lack of
> sophistication in marketing.

Thanks for clarifying Travis!

I'd completely forgotten that I'd mentioned the Tarot Deck as an
excuse to introduce more long-winded string templating, ala Madlibs
and Grossology (a recurring theme in my curriculum writing).

By way of background, a lot of younger kids especially enjoy
scatological material as it's something they can relate to, makes the
topic more user-friendly.  There's a genre of Madlib that focuses on
this theme (you know what a Madlib is right?).

http://seattletimes.nwsource.com/html/localnews/2009256554_grossology24m.html
http://tampabay.momslikeme.com/members/JournalActions.aspx?g=247205&m=388979

Probably the earliest introduction of scatology is in the first Snake
method, where you have both 'eat' and 'poop' methods, a way of
introducing the list data structure (as the stomach) and using it as a
queue (first in first out, ala FIFO).

I've had good experiences in my classroom of first introducing
string.Template using Madlibs of an entertaining nature, then
switching to more auster string.Templates having to do with generating
scene description language and/or VRML, for getting polyhedra either
ray-traced or brought into a browser plug-in such as Cortona's.

>From my slides:
http://www.4dsolutions.net/presentations/connectingthedots.pdf  (see
slides 11, 23-27 especially)

> I love a good example (and a good joke) as much as the next guy, but let's
> not lean on a diversity statement as an excuse to not attend to some basic
> tenets of marketing.  If we had examples that incorporated the various
> "Stations of the Cross" it would likewise go over like a lead balloon.
> Introducing Python as a unifying tool in early education (by some definition
> of early) calls for a particular discretion in the choice of examples.
> Best,
> Travis
>

Yes, I understand better what you're driving at.

However, the death of the mass-published text book as a primary
curriculum distribution mechanism means we're able to niche market,
not mass market.  I used to work at McGraw-HIll and remember how
editors would bend over backwards to develop some "acceptable to all"
pabulum, focusing mainly on California and Texas as the standard
bearers.  I think those days are finally coming to an end.**

The concept here is teachers will roll their own (develop their own
content), quite possibly using a "place based" approach, meaning they
up the relevance quotient by incorporating information from the local
environment (in story problems, in geography lessons, in history
lessons -- not just talking about math).

I've worked with the Catholic subculture in Portland some, helping a
protege us Pyblosxom to develop a blogging system for one of the local
priests (Father Bob), complete with "skinning" depending on the
liturgical calendar, with a few secular holidays thrown in for good
measure.

Coming up with a Python algorithm that'd correctly compute Easter was
especially challenging, with the US Navy proving our most reliable
source (I think it was -- some dot mil resource).

Here we go:
http://www.usno.navy.mil/USNO/astronomical-applications/astronomical-information-center/date-easter

Regarding Tarot, that'd of course depend on the school and local
community standards.  In Portland, we tend to celebrate pirates,
hackers, wizards and witches all in the same breath (it's the
Winterhaven Wizards where my daughter went to junior high).

If a student wanted to write a Tarot Reader is a school project, I
doubt that'd be a problem around here in any way.  YMMV of course.

http://www.flickr.com/photos/17157315@N00/4037589946/  (typical
Portland pro witch propaganda)

What some of us advertise about Python is that it fits well into
niches (a variation of "fits your brain" meme) i.e. you're not even
obligated to use Latin-1 except for the keywords.

Having religious themes for your content is in no way a problem for
the language itself, even if your language is Klingon (actually that
might be a problem as Klingon is only ancillary in the Unicode
standard and might be difficult to come by -- Damian does Klingon in
Perl though, so I'm thinking there must be a way).

http://www.archlug.org/kwiki/KlingonPerlProgramming
http://globalmoxie.com/blog/klingon-not-spoken-here.shtml

I regard the Diversity Statement as a way of protecting the niches
against any largely fictitious "majority culture" that wants to
steamroll some kind of "majority aesthetic" on the rest of us.

There's really no need to pay much attention to tyrannical majorities
anymore.  It's all about locale and localization (another way of
saying "place based" education is the way of the future, IMO).

Of course that's just one more debating position, not saying you're
compelled to agree, obviously.  Just my point of view and all that,
seems to be working well in practice.

Kirby

**  I remember the story about John Saxon, a retired military guy who
decided to get into curriculum writing, found his textbooks had a
large niche market among schoolers.  However, his story problems about
fairies and pixies were getting him into trouble with that group,
which regarded these Narnia-like creatures as too Satanic for comfort.
 He needed to change his text for the next edition.  Such is the
relatively joyless life of mass publishers.
http://www.home-school.com/Articles/SaxonEditorial.html

Related blog post (Oct 17, 2009)
http://controlroom.blogspot.com/2009/10/equipment-drop.html
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

Mokurai
In reply to this post by Laura Creighton-2
On Mon, Nov 2, 2009 at 22:20, Laura Creighton <[hidden email]> wrote:
> In a message of Mon, 02 Nov 2009 20:27:35 PST, Edward Cherlin writes:
>>Cards: You are right on the merits for combinatory math, but you will
>>run into strong cultural aversions.
>
> Why?  Especially when _dice_ seem to be the preferred way to teach
> this stuff?  (Or is this only here?)

I'm including the rest of the world, not just the US. I expect issues
to be raised by Evangelical Christians, Muslims and others in various
countries. Dice might be easier, because casting lots is mentioned
with approval in the Bible. Certainly we can come up with equipment
that is not associated with common taboos.

> Laura
>



--
Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
Silent Thunder is my name, and Children are my nation.
The Cosmos is my dwelling place, the Truth my destination.
http://www.earthtreasury.org/
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

Laura Creighton-2
In a message of Tue, 03 Nov 2009 18:37:54 PST, Edward Cherlin writes:

>On Mon, Nov 2, 2009 at 22:20, Laura Creighton <[hidden email]> wrote:
>> In a message of Mon, 02 Nov 2009 20:27:35 PST, Edward Cherlin writes:
>>>Cards: You are right on the merits for combinatory math, but you will
>>>run into strong cultural aversions.
>>
>> Why?  Especially when _dice_ seem to be the preferred way to teach
>> this stuff?  (Or is this only here?)
>
>I'm including the rest of the world, not just the US. I expect issues
>to be raised by Evangelical Christians, Muslims and others in various
>countries. Dice might be easier, because casting lots is mentioned
>with approval in the Bible. Certainly we can come up with equipment
>that is not associated with common taboos.
>
>> Laura

I wasn't clear, sorry.  Around here (Sweden), when you want to teach
probability, you get out the dice.  That's how it is taught, and
how all the exercises are set up, etc.  I'm really surprised at
the notion that cards would be unacceptable, while dice would be
fine.

I know some people who would be strongly against both, seeing both
as gambling devices, and I know some people who every year are
opposed to the dice and who would find cards unobjectionable.
I hadn't thought that people who like dice but hate cards exist.
Do you know some?  Or are you guessing that they must exist?  And
if the latter, why?

Do you use something else to teach probability?

still puzzled,
Laura
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

DeanG
> On Tue, Nov 3, 2009 at 9:44 PM, Laura Creighton <[hidden email]> wrote:
> Do you use something else to teach probability?

Drawing colored rocks from a bag was one thing I recall, which
wikipedia noted as the primary type of drawing lots.

I'm still trying to figure out why my chemistry teacher was using
Dominos to teach unit conversion...

- Dean
p.s. Lost Cities is a great card game with a light explorer theme.
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

Mokurai
In reply to this post by Laura Creighton-2
On Tue, Nov 3, 2009 at 19:44, Laura Creighton <[hidden email]> wrote:

> In a message of Tue, 03 Nov 2009 18:37:54 PST, Edward Cherlin writes:
>>On Mon, Nov 2, 2009 at 22:20, Laura Creighton <[hidden email]> wrote:
>>> In a message of Mon, 02 Nov 2009 20:27:35 PST, Edward Cherlin writes:
>>>>Cards: You are right on the merits for combinatory math, but you will
>>>>run into strong cultural aversions.
>>>
>>> Why?  Especially when _dice_ seem to be the preferred way to teach
>>> this stuff?  (Or is this only here?)
>>
>>I'm including the rest of the world, not just the US. I expect issues
>>to be raised by Evangelical Christians, Muslims and others in various
>>countries. Dice might be easier, because casting lots is mentioned
>>with approval in the Bible. Certainly we can come up with equipment
>>that is not associated with common taboos.
>>
>>> Laura
>
> I wasn't clear, sorry.  Around here (Sweden), when you want to teach
> probability, you get out the dice.  That's how it is taught, and
> how all the exercises are set up, etc.  I'm really surprised at
> the notion that cards would be unacceptable, while dice would be
> fine.
>
> I know some people who would be strongly against both, seeing both
> as gambling devices, and I know some people who every year are
> opposed to the dice and who would find cards unobjectionable.
> I hadn't thought that people who like dice but hate cards exist.
> Do you know some?  Or are you guessing that they must exist?

Guessing that they might exist.

Certainly there are people who like ordinary cards and dice, but not
Tarot. I'm one of them. The cards themselves normally don't bother me,
but I have had issues with people who got into the practice.

> And
> if the latter, why?
>
> Do you use something else to teach probability?

All sorts of things. Coins, Othello pieces, dice (4-30 sides), cards
from various decks, dreidls, wheels of fortune, spinners, socks in a
bag, colored balls, pseudo-random number generators, random number
generators, letter distribution in texts,...

> still puzzled,
> Laura
>



--
Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
Silent Thunder is my name, and Children are my nation.
The Cosmos is my dwelling place, the Truth my destination.
http://www.earthtreasury.org/
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

kirby urner-4
In reply to this post by Mokurai
On Tue, Nov 3, 2009 at 6:37 PM, Edward Cherlin <[hidden email]> wrote:

> On Mon, Nov 2, 2009 at 22:20, Laura Creighton <[hidden email]> wrote:
>> In a message of Mon, 02 Nov 2009 20:27:35 PST, Edward Cherlin writes:
>>>Cards: You are right on the merits for combinatory math, but you will
>>>run into strong cultural aversions.
>>
>> Why?  Especially when _dice_ seem to be the preferred way to teach
>> this stuff?  (Or is this only here?)
>
> I'm including the rest of the world, not just the US. I expect issues
> to be raised by Evangelical Christians, Muslims and others in various
> countries. Dice might be easier, because casting lots is mentioned
> with approval in the Bible. Certainly we can come up with equipment
> that is not associated with common taboos.
>

The goal is not just to teach combinatorics but an object oriented way
of modeling stuff.

What's attractive about using a deck of playing cards, per my recent
examples, is you might have a Card class, a Deck class, and a Hand
class (i.e. what each player has in her or his possession).

This is a fairly rich environment in that sense, whereas just grabbing
stones from a bag or rolling dice is a little bit too simple.

The main reasons I flashed on Tarot were two fold:

(a)  I was thinking about cards with no obvious ranking (cardinality
vs. ordinality), i.e. the __lt__, __gt__, __eq__ interface would be
missing and

(b) I'm always looking for opportunities to be verbose with text, to
get away from the misconception or prejudice that computer programming
always means something like "number crunching"

However, on further consideration, I see that (a) is incorrect and
that most Tarot decks are very much the precursor of our ordinary
decks of today, with suits and numbers i.e. ranking.  I used to know
that, but had forgotten (I'm not big into Tarot, nor astrology
either).

Regarding (b), I really hadn't thought it through.  I was thinking of
funny Madlib templates but more like horoscopes, divinations about the
future that might be fun to write, not just read.

Probably in the back of my mind was the fact that I'd already
implemented throwing the I Ching as a Google App Engine.  That was
more about testing out Unicode than it was about divination, although
I was careful to have the code mirror the actual process (I consulted
an expert) i.e. I didn't just grab two hexagrams at random in one line
of code.  There's more to it.

In any case, I'm enjoying the background information on Tarot I'm
getting from Wikipedia and places, but have no immediate plans to head
off in that direction in my examples.

The standard deck of 52 plus two jokers is sufficient for my purposes
(including jokers or wild cards is actually a challenge I haven't
addressed yet).

What I'm liking about playing card examples, aside from talking about
combinatorics, is the fairly rich environment in terms of having these
different types of object:  a Deck, a Card, and a Hand (what each
player has).  This gets into refactoring, adding new methods, thinking
through some of the modeling issues.

Just grabbing stones from a bag doesn't have this level of richness
(but could, if we built a context around it).

For those wishing to eschew any focus on playing cards for religious
reasons, I'm certain equally rich (yet familiar and relatively simple)
examples might easily be devised.

We could brainstorm some more of these OO-friendly environments here
on this list, complete with coding examples.

One thing I want to get away from is the ultra-dry traditional
computer science text that lavishes so much attention on "widgets" or
"parts in inventory" with not much imaginative texture.  I'm trying to
weave OO into a more Liberal Artsy approach, where we digress in the
sense of criss-crossing other disciplines.

I'm a big believer in more curriculum integration, less deliberate
compartmentation.

For example, in talking about methods and attributes, I think many
kids would appreciate having Monsters, Mythical Beings, Superheros to
focus on -- the stuff of comic books and movies, also computer games.
More like a MUD (multi-user domain), including in being text-based
(more lexical than graphical -- because we're learning to code and
think logically, not to draw like a pro).

Why not learn or at least reinforce Greek Mythology this way, mixing
stories with a little dot notation?  Instead of just going Foo and
Bar, we could have Hercules = Mortal(), Hercules.clean_stables() or
something along those lines.

Simple environments might include not just games, but establishments,
institutions: like an Art Gallery, Restaurant, Theater, Airport...
Village.  What types of objects do these have and how do they relate
to one another?

We've often seen textbook examples talking about a school, classrooms,
grades.  I'd like to get away from that (over-used, too stultifying).

Probably what's driving my thinking here, at least in part, is some of
my writing for DemocracyLab.org.  This think tank is/was trying to
come up with "democracy engines" that would allow groups of people to
relate policy proposals to underlying values.

There was also some talk of a "village in a box" design, i.e. you
could set up a small community and install this open source software,
and get all sorts of roles predefined, along with a bunch of processes
for running town meetings, polling, voting, keeping track of food
stores, managing imports / exports....

Fun science fiction if nothing else, plus it gives students a context,
a way of bringing a community into focus and thinking in an OO style
about it.

Legitimate exercise, not for everyone, but not every exercise needs to
be:  "Specify likely attributes (properties) and methods (behaviors)
for the following classes, provide comments:  Casket, Plot, Headstone,
Corpse... Cemetery"

You may think I'm just being facetious or trying to be Gothic, however
I'm thinking of two real world experiences:

1. teaching high school in Jersey City, at a Catholic academy for
girls, and asking my students to devise business cards for themselves
as they imagine they might have when they were full-fledged adults
with careers.  One of my students came back with Funeral Director, and
she wasn't joking, lots of families in Jersey City were actually
involved in that business

2. a student in middle school in Italy, my dad the urban planner
coming in to talk about his job and unfurling large city maps showing
zoning, some big green areas around town.  "Not parks, not golf
courses... what do you think these are?" he asked, and none of us got
the right answer (which I'm sure you're able to get, given the present
context).

Thinking in an OO style, about *everything*, is a useful way to go.  A
kind of "language immersion" approach, like some schools do with
Japanese or Spanish....

Kirby

>
>
>
> --
> Edward Mokurai (默雷/धर्ममेघशब्दगर्ज/دھرممیگھشبدگر ج) Cherlin
> Silent Thunder is my name, and Children are my nation.
> The Cosmos is my dwelling place, the Truth my destination.
> http://www.earthtreasury.org/
>
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig
Reply | Threaded
Open this post in threaded view
|

Re: more card play

kirby urner-4
On Wed, Nov 4, 2009 at 12:06 AM, kirby urner <[hidden email]> wrote:

> On Tue, Nov 3, 2009 at 6:37 PM, Edward Cherlin <[hidden email]> wrote:
>> On Mon, Nov 2, 2009 at 22:20, Laura Creighton <[hidden email]> wrote:
>>> In a message of Mon, 02 Nov 2009 20:27:35 PST, Edward Cherlin writes:
>>>>Cards: You are right on the merits for combinatory math, but you will
>>>>run into strong cultural aversions.
>>>
>>> Why?  Especially when _dice_ seem to be the preferred way to teach
>>> this stuff?  (Or is this only here?)
>>
>> I'm including the rest of the world, not just the US. I expect issues
>> to be raised by Evangelical Christians, Muslims and others in various
>> countries. Dice might be easier, because casting lots is mentioned
>> with approval in the Bible. Certainly we can come up with equipment
>> that is not associated with common taboos.
>>
>
> The goal is not just to teach combinatorics but an object oriented way
> of modeling stuff.
>
> What's attractive about using a deck of playing cards, per my recent
> examples, is you might have a Card class, a Deck class, and a Hand
> class (i.e. what each player has in her or his possession).
>

Just to follow up on this theme, today I was shown one of those books
from the LIFE series in the 1960s that were so influential at the
time, in just about every school library, or at least in mine.  I'd
spent hours with this book in my boyhood:

http://www.flickr.com/photos/17157315@N00/4126467006/

So here's some of the playing card imagery prominent in the
combinatorics and probably section.  I have to think this material was
influential, given how much time I spent with this book:

http://www.flickr.com/photos/17157315@N00/4126468504/in/photostream/
http://www.flickr.com/photos/17157315@N00/4125698421/in/photostream/
http://www.flickr.com/photos/17157315@N00/4125698093/in/photostream/

I had a suggestion from Carl T. to help promulgate Pycons and pointed
him to my post here passing on Catherine's news of poster sessions,
including virtual.  Also, I'm back on math-thinking-l:

http://mail.geneseo.edu/pipermail/math-thinking-l/2009-November/001327.html

Kirby
_______________________________________________
Edu-sig mailing list
[hidden email]
http://mail.python.org/mailman/listinfo/edu-sig