Python

Discussion in 'Programming General' started by asdasd123, Mar 8, 2012.

Python
  1. Unread #1 - Mar 8, 2012 at 8:07 AM
  2. asdasd123
    Joined:
    Feb 2, 2012
    Posts:
    417
    Referrals:
    0
    Sythe Gold:
    0

    asdasd123 Forum Addict

    Python

    I'm a beginner at python can someone help me out it's for a course at uni and I keep trying to use VB commands lol

    # Playing Cards - Poker
    #
    # THE PROBLEM
    #
    # Assume the following value has already been entered into the
    # Python interpreter, representing a hand of playing cards -
    # where picture cards have the following values:
    # Ace = 1; Jack = 11; Queen = 12; King = 13
    #
    # The cards are grouped into the four suits (Hearts, Diamonds,
    # Clubs, Spades, in that order) using sub-lists of the hand.

    hand = [[5], [], [6, 8], [4, 7]]

    # Write an expression, or expressions, to find the card with the
    # highest face value in the hand, regardless of suit,
    # and print its value.
    #
    # (Motivation: Sometimes in poker it is necessary to compare players'
    # largest cards in order to determine the winning hand.)


    # A SOLUTION
    #
    # Problem solving strategy:
    # 1. Combine the sublists into one list
    # 2. Find the highest card
    # 3. Print that card's value
     
  3. Unread #2 - Mar 8, 2012 at 10:40 AM
  4. novice
    Joined:
    Jun 21, 2008
    Posts:
    111
    Referrals:
    0
    Sythe Gold:
    0

    novice Active Member

    Python

    Code:
    hand = [[5], [], [6, 8], [4, 7]]
    
    combinedHand = list()
    
    for suit in hand:
        combinedHand += suit
    
    combinedHand.sort(reverse=True)
    
    print combinedHand[0]
    
    
     
  5. Unread #3 - Mar 9, 2012 at 8:41 PM
  6. asdasd123
    Joined:
    Feb 2, 2012
    Posts:
    417
    Referrals:
    0
    Sythe Gold:
    0

    asdasd123 Forum Addict

    Python

    Oh right += .... Didn't know you could do that haha
     
  7. Unread #4 - Mar 9, 2012 at 10:32 PM
  8. Nullware
    Joined:
    Jan 30, 2007
    Posts:
    1,761
    Referrals:
    4
    Sythe Gold:
    0

    Nullware Guru

    Python

    Since finding the highest card really only requires traversing the list once which is O(n) it's better to do that than it is to use sort which probably requires O(n*log(n)) time.

    You could find the max value yourself by looping over the list but Python provides the function max() to do it for you.

    Also (double) list comprehension can be used to build one array of all the card values in one line.

    So the whole thing can actually be done using just this:

    Code:
    print max([card for suit in hand for card in suit])
     
< Python 2 | Hiring JavaScript Programmer >

Users viewing this thread
1 guest


 
 
Adblock breaks this site