totally lost newbie

mark j25bravo at gmail.com
Sun May 27 06:19:15 EDT 2007


Hi all

I posted earlier on this but have changed my approach so here is my
latest attempt at solving a problem. I have been working on this for
around 12 hours straight and am still struggling with it.

Write a program that reads the values for a random list of cards from
a file, where each line in the file specifies a single card with the
rank and then the suit separated by a space. The rank should be an
integer in the range of 1 to 13 (Ace:1, King:13), while the suit
should be a lower case character in the set { 'h', 'd', 'c', 's' }.
Sort the card entries into suits ordered by rank, and print out the
ordered list. Hint: sort the list first by rank, and then by suit.

The format of the cards.txt file is;

1 h
1 d
13 c
10 s

and so on for the whole deck.

Can someone help me to get the mycomp function to work.

Any help appreciated

J

def read_cards(filename):

    cards = []
    for card in open(filename, 'r'):
        # strip the trailing newline character
        cards.append(card.strip())
    return cards

filename = 'cards.txt'
cards = read_cards(filename)



def cards_str2tup(cards):

    cards_tup = []
    for card in cards:
        rank, suit = card.split()
        cards_tup.append((suit, int(rank)))
    return cards_tup

def cards_tup2str(cards_tup):

    cards = []
    space = ' '
    for tup in cards_tup:
        suit, rank = tup
        s = str(rank) + space + suit
        cards.append(s)
    return cards

def mycmp( a, b):
    #define the order in which the characters are to be sorted
    order = [ 'h', 'd', 'c', 's' ]
    # if the characters from each element ARENT the same
    if a[1] <> b[1]:
        #return the result of comparing the index of each elements
character in the order list
        return cmp( order.index( a[1] ), order.index( b[1] ) )
    #otherwise
    else :
        #return the result of comparing each elements number
        return cmp( a[0], b[0] )

cards.sort( mycmp )
#print cards




More information about the Python-list mailing list