0

Hello,

pls.can anybody help me? I try to solve a exercise where I need to involve random module. Here is a text:

Exercise 2
In this example, ties are broken by comparing words, so words with the same length appear in alphabetical order. For other applications you might want to break ties at random.
Modify this example so that words with the same length appear in random order.
Hint: see the random function in the random module.

here is a script which I try to modify according to the text.

def test(words):
    t = []
    for word in words:
       t.append((len(word), word))

    t.sort(reverse=True)

    res = []
    for length, word in t:
        res.append(word)
    print res
test(['hello','my','friend','Peter'])

here in the result I have 2 words with the same lenght (hello, peter). My aim is to sort these words according to the lenght, from highest to shortest words but for those words which have the same lenght I want to use random method in order to change their position after each run or execution of the script. So it should look like:
1 run:
2 run:

2
Contributors
2
Replies
3
Views
7 Years
Discussion Span
Last Post by vlady
0

I suggest to add a random number in the tuples being sorted

from random import random

def test(words):
    t = []
    for word in words:
       t.append((len(word), random(), word))

    t.sort(reverse=True)

    res = []
    for length, rand, word in t:
        res.append(word)
    print res
test(['hello','my','friend','Peter'])
0

Great! Thank you very much, I would not come up with this idea. You helped me to move on!

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.