Help with simple python code

  • (2 Pages)
  • +
  • 1
  • 2

22 Replies - 711 Views - Last Post: 27 February 2014 - 08:30 PM Rate Topic: -----

#1 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Help with simple python code

Posted 26 February 2014 - 08:24 PM

I need some help with a lab that I have for my python class. I do not think its hard, but I am new to python and think I am not going about it correctly. What i need to do is commented with # To Do, I will post my 2 files below, cardstuff.py and cardstufftest.py. I think I may have an idea and will keep trying, just wanted to make sure I was on the right track.

Thanks so much everyone!

cardstuff.py
# card.py
# YOUR NAME AND NETID HERE;
# skeleton by Lillian Lee (LJL2) and Steve Marschner (SRM2), Feb 22, 2014
# PUT THE DATE HERE

"""Module providing a type for playing cards

Implementation adapted from chapter 18 of the course text, _Think Python_,
by Allen B. Downey.
"""
import random

# It may be a bit unconventional to have these be global variables rather
# than what are known as class variables, but this may be more readable to
# the beginning student.

SUIT_NAMES = ['Clubs', 'Diamonds', 'Hearts', 'Spades']
NUM_SUITS = len(SUIT_NAMES) # number of suits

# The item at index 0 is None so that we can treat RANK_NAMES as a translation
# table: RANK_NAME[1] is 'Ace', RANK_NAME[13] is 'King', etc.
RANK_NAMES = [None, 'Ace', '2', '3', '4', '5', '6', '7',
      '8', '9', '10', 'Jack', 'Queen', 'King']
NUM_RANKS=13 # number of ranks


class Card(object):
    """An instance is a standard playing card.

    Instance variables:
        suit [int in 0..NUM_SUITS-1]: this card's suit is SUIT_NAMES[suit]

        rank [int in 1..NUM_RANKS]: this card's rank is RANK_NAMES[rank]
    """

    def __init__(self, s, r):
        """Initializer: A new Card whose suit is s and rank is r

        Note that suits and ranks are stored as ints.  For example,
        an Ace is rank 1, a 10 is rank 10, a King is rank 13 (there's no rank 0);
        a Club is suit 0, a spade is suit 3.

        Hence, if we execute c = Card(0, 12), SUIT_NAMES[c.suit] is 'Clubs'
        and RANK_NAMES[c.rank] is '12'.

        Preconditions: s in 0..NUM_SUITS-1 (inclusive) and
        r in 1..NUM_RANKS (inclusive)"""
        self.suit = s
        self.rank = r

    def __str__(self):
        """Readable string representation of this card.
        Example: '2 of Hearts'"""
        return RANK_NAMES[self.rank] + ' of ' + SUIT_NAMES[self.suit]

    def __eq__(self, other):
        """Equality determined by equality of attributes"""
        return (isinstance(other,Card) and
            (self.suit, self.rank) == (other.suit, other.rank))

    def __ne__(self, other):
        """Non-equality determined opposite of equality"""
        return not self.__eq__(other)

    def __cmp__(self, other):
        """Poker order (as opposed to bridge order).

        Returns:
          -1 if self's rank is less than other's rank or self and other's
            rank are the same but self has lower suit
          0 if self and other's rank and self are the same
          1 otherwise.

        Precondition: other is a Card."""
        return poker_compare(self, other)


def full_deck():
    """Returns: list of the standard 52 cards"""
    output = []  # list of cards so far to be returned
    for suit in range(NUM_SUITS):
        # range(n) creates the list [0,1,2,...,n-1]
        for rank in range(1,NUM_RANKS+1):
            # range(1,n) creates the list [1,2,...,n-1]
            # skip the None value
            output.append(Card(suit,rank))
    return output


def print_cards(clist):
    """Print cards in list clist.

    Precondition:  clist is a list of Cards, possibly empty."""
    for c in clist:
        pass  # TODO: fix this line so it prints card c (or str(c))



def draw(deck):
    """Returns: a card that is randomly drawn (and removed) from deck.

    Precondition: deck is a list of cards containing at least one card."""
    i = random.randrange(len(deck)) # random int in 0..len(deck)-1

    # TODO: add a line make this function obey its specification
    # You will, of course, want to use the value of i.
    # This function is used in draw_poker_hand, below.



def poker_compare(c1, c2):
        """Poker ordering (as opposed to bridge ordering) of Cards c1 and c2

          -1 if c1's rank is less than c2's rank,  or c1 and c2's
            rank are the same but c1 has lower suit
          0 if c1 and c2's rank and suit are the same
          1 otherwise.

        Order is determined by position in suit_names or rank_names, respectively.

        Precondition: c1 and c2 are Cards."""
        pass

        # TODO: implement this function according to its specification.
        # it is used in card.__cmp__, which will make draw_poker_hand, next,
        # work nicely



def draw_poker_hand(deck):
    """Returns: list of five cards drawn from deck, in reverse sorted order.

    The cards are removed from deck.  We use reverse sorted order because people
    tend to sort their cards with highest value to the left.

    Precondition: deck is a list of cards containing at least five cards."""

    output = []  # An empty list for you to add cards to when you draw them

    # TODO: put in lines so that variable output eventually holds what we want to return.
    #
    # Syntax hint: If clist is a list of cards, then clist.sort() will use your
    # poker_compare() function to put the list in poker-sorted order.
    #
    # Syntax hint: since we're inside the file card.py, you say draw(deck)
    # instead of card.draw(deck)



    return output





cardstufftest.py
# cardtest.py
# Lillian Lee (LJL2) and Steve Marschner (SRM2)
# Feb 22, 2014

"""Module for testing some functions in card"""

import cornelltest
import cardstuff


def test_equals():
    """Quick diagnostic for whether card equality seems to be working"""
    c = cardstuff.Card(3,4)
    d = cardstuff.Card(3,5)
    e = cardstuff.Card(3,4)
    cornelltest.assert_true(c==e)
    cornelltest.assert_true(d==d)
    cornelltest.assert_true(not c == d)

    print "finished test of card equality"


def test_print_cards():
    """Quick diagnostic test whether print_cards seems to be working"""
    clist = [cardstuff.Card(1,11), cardstuff.Card(3,1)]

    print 'about to print out a list of two cards using cardstuff.print_cards...\n'
    cardstuff.print_cards(clist)
    print '\nshould have seen...\nJack of Diamonds\nAce of Spades'

    print ("finished test of print_cards, BUT YOU HAVE TO CHECK IF THE OUTPUT" +
           " WAS RIGHT\n")

def test_draw():
    """Quick diagnostic test of whether draw seems to be working.
    May depend on equality being correct for cards"""
    clist = [cardstuff.Card(1,11)]
    hand = [cardstuff.Card(2,3)]
    hand.append(cardstuff.draw(clist))

    cornelltest.assert_equals(0,len(clist))
    cornelltest.assert_equals(2,len(hand))
    cornelltest.assert_true(cardstuff.Card(2,3) in hand)
    cornelltest.assert_true(cardstuff.Card(1,11) in hand)

    clist = cardstuff.full_deck()
    hand.append(cardstuff.draw(clist))
    cornelltest.assert_equals(51, len(clist))
    cornelltest.assert_equals(3,len(hand))

    print "finished test of test_draw()"


def test_compare():
    """Test cardstuff.poker_compare"""

    # we don't guarantee that this is a thorough set of test cases
    cornelltest.assert_equals(-1, cardstuff.poker_compare(cardstuff.Card(2,10),cardstuff.Card(2,11)))
    cornelltest.assert_equals(-1, cardstuff.poker_compare(cardstuff.Card(3,10),cardstuff.Card(2,11)))
    cornelltest.assert_equals(1,  cardstuff.poker_compare(cardstuff.Card(2,13),cardstuff.Card(2,11)))
    cornelltest.assert_equals(1,  cardstuff.poker_compare(cardstuff.Card(3,10),cardstuff.Card(2,1)))
    cornelltest.assert_equals(0,  cardstuff.poker_compare(cardstuff.Card(3,10),cardstuff.Card(3,10)))
    cornelltest.assert_equals(-1, cardstuff.poker_compare(cardstuff.Card(3,2), cardstuff.Card(2,3)))

    print "finished test of cardstuff.poker_compare"



def test_draw_poker_hand():

    fd = cardstuff.full_deck()
    hand = cardstuff.draw_poker_hand(fd)
    print 'Drawing a poker hand. It is:\n',
    cardstuff.print_cards(hand)

    # check that we got five cards
    cornelltest.assert_equals(5, len(hand))

    # check that 5 cards were removed from the deck
    cornelltest.assert_equals(52-5, len(fd))

    # check that none of the cards in the hand are in the deck
    for c in hand:
        cornelltest.assert_true(not c in fd)

    # check that the cards in the hand are all different
    for cindex in range(5):
        for compareindex in range(cindex+1,5):
            cornelltest.assert_false(hand[cindex] == hand[compareindex])

    print ("\nfinished test of draw_poker_hand")





if __name__ == '__main__':
    test_equals()
    test_print_cards()
    test_draw()
    test_compare()
    test_draw_poker_hand()
    print 'All test cases for cardstuff passed'





Is This A Good Question/Topic? 0
  • +

Replies To: Help with simple python code

#2 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7958
  • View blog
  • Posts: 13,560
  • Joined: 19-March 11

Re: Help with simple python code

Posted 26 February 2014 - 08:30 PM

Try to refine your questions a bit. What exactly is it you're having trouble with? Be specific: what are you trying to do, how do you want to go about it, and what's not working about that?

I want you to be specific, because this helps both of us. It helps me to know exactly what you need help with, and it helps you because expressing a problem clearly in words often helps you understand it better.
Was This Post Helpful? 0
  • +
  • -

#3 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Re: Help with simple python code

Posted 26 February 2014 - 08:37 PM

For starters

def print_cards(clist):
"""Print cards in list clist.
Precondition: clist is a list of Cards, possibly empty."""
for c in clist:
pass # TODO: fix this line so it prints card c (or str©)

For this one we know we can have a list of cards with anywhere from 0-52 cards. to make this print what we want, cant we just do print ('c') ?

This post has been edited by jon.kiparsky: 26 February 2014 - 08:40 PM

Was This Post Helpful? 0
  • +
  • -

#4 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7958
  • View blog
  • Posts: 13,560
  • Joined: 19-March 11

Re: Help with simple python code

Posted 26 February 2014 - 08:43 PM

Well, have you tried this? Looks like there's a test suite, so you should be able to see if your plan works.
Was This Post Helpful? 0
  • +
  • -

#5 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Re: Help with simple python code

Posted 26 February 2014 - 08:58 PM

hmm, how can I go about testing it though?
Was This Post Helpful? 0
  • +
  • -

#6 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7958
  • View blog
  • Posts: 13,560
  • Joined: 19-March 11

Re: Help with simple python code

Posted 26 February 2014 - 09:02 PM

Run cardstufftest.py

Alternatively, start up an interpreter session and

>>> from cardstufftest import *
>>> test_print_cards()

Was This Post Helpful? 0
  • +
  • -

#7 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Re: Help with simple python code

Posted 26 February 2014 - 09:10 PM

hmm yea, print ('c') did not work. it wants us to print card c, but how do we know what card c is?
Was This Post Helpful? 0
  • +
  • -

#8 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7958
  • View blog
  • Posts: 13,560
  • Joined: 19-March 11

Re: Help with simple python code

Posted 26 February 2014 - 09:17 PM

What does the for loop do here?

def print_cards(clist):
    """Print cards in list clist.

    Precondition:  clist is a list of Cards, possibly empty."""
    for c in clist:
        pass  # TODO: fix this line so it prints card c (or str(c))

Was This Post Helpful? 0
  • +
  • -

#9 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Re: Help with simple python code

Posted 26 February 2014 - 09:18 PM

for c in clist, I am not sure, it helps define print_cards right?
Was This Post Helpful? 0
  • +
  • -

#10 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7958
  • View blog
  • Posts: 13,560
  • Joined: 19-March 11

Re: Help with simple python code

Posted 26 February 2014 - 09:29 PM

Okay, this is something you need to get hold of. For loops are a pretty important piece of the syntax, and python does them a little different from other languages.

So in python,

for c in clist:
  # Indented block here


will execute the statements in the indented block once for each member of clist. c will take the value of the current member of the list on each go round.

So for a simple example,

accumulator = 0
for i in range(1,101):
  accumulator += i
print i



The range function defines a list of ints, in this case the list [1,2, ... , 90, 100] So i takes the values of each of these in turn. In the body of the loop, the current value of i is added to the accumulator variable, so it ends up containing the sum of the first hundred integers. (this is a famous problem in the history of mathematics, and you'll hear more about it in due course)

This is a pretty quick overview - if you're still befogged and becalmed, let Google be your guide. But make sure you understand how this loop works. Once you do, the problem will solve itself.

This post has been edited by jon.kiparsky: 26 February 2014 - 09:29 PM

Was This Post Helpful? 0
  • +
  • -

#11 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Re: Help with simple python code

Posted 26 February 2014 - 10:03 PM

print 'Current c:', c
would that be correct? i looked up for loop python and on tutorialspoint.com this example i used.


for letter in 'Python': # First Example
print 'Current Letter :', letter

fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print 'Current fruit :', fruit

print "Good bye!"
Was This Post Helpful? 0
  • +
  • -

#12 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Re: Help with simple python code

Posted 26 February 2014 - 10:10 PM

I got i! print c worked. awesome! feel so good hehe

ok now onto

def draw(deck):
"""Returns: a card that is randomly drawn (and removed) from deck.

Precondition: deck is a list of cards containing at least one card."""
i = random.randrange(len(deck)) # random int in 0..len(deck)-1

# TODO: add a line make this function obey its specification
# You will, of course, want to use the value of i.
# This function is used in draw_poker_hand, below.


return i-1 would work? let me try
Was This Post Helpful? 1
  • +
  • -

#13 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7958
  • View blog
  • Posts: 13,560
  • Joined: 19-March 11

Re: Help with simple python code

Posted 26 February 2014 - 10:14 PM

If you think it's right, and your output is exactly like the output specified in the test function, then it should be right.

Also, while I'm sure the tutorialspoint people are very nice and their mothers are very proud of their nice website, your first point of call should always by the official documentation. For some languages, that's not very good, but we're doing python, and python's docs are good.

http://docs.python.o...rial/index.html
http://docs.python.o...rial/index.html

View Postthrgk, on 27 February 2014 - 12:10 AM, said:

return i-1 would work? let me try



That's what I want to see.

Tip: you're using a random function here, so if it works once, that doesn't mean it'll always work. To be sure you've got it right, you want to read the documentation for the function and make sure you understand how it works.

This post has been edited by jon.kiparsky: 26 February 2014 - 10:12 PM

Was This Post Helpful? 0
  • +
  • -

#14 thrgk  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 12
  • Joined: 26-February 14

Re: Help with simple python code

Posted 26 February 2014 - 10:19 PM

yea the output was correct. for that next one though, we need to return a random card and take it out of the deck so i already pics a random card correct? and it seems to take it out of thedeck since -1 is at the end of the i= line?
Was This Post Helpful? 0
  • +
  • -

#15 jon.kiparsky  Icon User is online

  • Pancakes!
  • member icon


Reputation: 7958
  • View blog
  • Posts: 13,560
  • Joined: 19-March 11

Re: Help with simple python code

Posted 26 February 2014 - 10:30 PM

Okay, there's actually some subtle stuff here, which can trip you up.

If you experiment with the range function, you'll find that it can take one, two, or three parameters. If you give it a single int n, it'll return the list if ints from 0 through n-1. Since lists are zero-indexed, range (len (some_list)) will return a list of all the legitimate indexes for some_list.

randrange selects a random number from a range that is specified in the same way - so if you can generate a range that specifies exactly the list of values that you want to select from, randrange will generate an index that will be as near as possible to randomly selected from that range.

So obviously I'm saying all of this because there's something you should figure out about your answer, and the way to do that is to play with the range function until you see what it is. For example, you might want to look at what
>>> range(len(deck))


looks like. It's worth getting curious about the behavior of the range function, since you're likely to use it an awful lot.
Was This Post Helpful? 0
  • +
  • -

  • (2 Pages)
  • +
  • 1
  • 2