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:

Recommended Answers

All 2 Replies

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'])

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.