views:

86

answers:

4
def display_hand(hand):
    for letter in hand.keys():
        for j in range(hand[letter]):
            print letter, 

Will return something like: b e h q u w x. This is the desired output.

How can I modify this code to get the output only when the funtion has finished its loops?

Something like below code causes me problems as I can't get rid of dictionary elements like commas and single quotes when printing the output:

def display_hand(hand):
    dispHand = []
    for letter in hand.keys():
        for j in range(hand[letter]):
            ##code##
    print dispHand

UPDATE John's answer is very elegant i find. Allow me however to expand o Kugel's response: Kugel's approach answered my question. However i kept running into an additional issue: the function would always return None as well as the output. Reason: Whenever you don't explicitly return a value from a function in Python, None is implicitly returned. I couldn't find a way to explicitly return the hand. In Kugel's approach i got closer but the hand is still buried in a FOR loop.

+1  A: 

Your ##code perhaps?

dispHand.append(letter)

Update:

To print your list then:

for item in dispHand:
    print item,
Kugel
Hi Kugel, your response also answered my question. However i kept running into an additional issue: the function would always return None as well as the output. Reason: Whenever you don't explicitly return a value from a function in Python, None is implicitly returned. I couldn't find a way to explicitly return the hand. In your approach hand is still buried in a FOR loop.
Baba
+4  A: 

You can do this in one line by combining a couple of list comprehensions:

print ' '.join(letter for letter, count in hand.iteritems() for i in range(count))

Let's break that down piece by piece. I'll use a sample dictionary that has a couple of counts greater than 1, to show the repetition part working.

>>> hand
{'h': 3, 'b': 1, 'e': 2}
  1. Get the letters and counts in a form that we can iterate over.

    >>> list(hand.iteritems())
    [('h', 3), ('b', 1), ('e', 2)]
    
  2. Now just the letters.

    >>> [letter for letter, count in hand.iteritems()]
    ['h', 'b', 'e']
    
  3. Repeat each letter count times.

    >>> [letter for letter, count in hand.iteritems() for i in range(count)]
    ['h', 'h', 'h', 'b', 'e', 'e']
    
  4. Use str.join to join them into one string.

    >>> ' '.join(letter for letter, count in hand.iteritems() for i in range(count))
    'h h h b e e'
    
John Kugelman
sweet :) Thanks John for the breakdown as well. makes good learning!
Baba
A: 

Use

" ".join(sequence)

to print a sequence without commas and the enclosing brackets.

If you have integers or other stuff in the sequence

" ".join(str(x) for x in sequence)
jellybean
+1  A: 

another option without nested loop

"".join((x+' ') * y for x, y in hand.iteritems()).strip()
killown