Alex Dymovsky
Alex Dymovsky

Reputation: 5

How do I sort the results of this Python program from lowest to highest values?

Below is my code, which generates X instances of random numbers between 0 and 101.

import random

x = int(raw_input("Enter desired number: "))

def randoTaker():
    print(random.randint(0, 101))

randoTaker()

for i in range(x-1):
    randoTaker()

My question: how do I sort these results from low to high? For example: let's say my current output for an input of value of 4 is 12, 34, 5, 45. My desired result would be 5, 12, 34, 45.

Any help would be very appreciated!

Upvotes: 0

Views: 85

Answers (3)

Anand S Kumar
Anand S Kumar

Reputation: 90909

First of all, you are just printing the value inside your function. If you want to sort the random numbers generated, you should consider returning the numbers and then adding them to a list.

Once you have added all the numbers to a list, you can then use list.sort() function or sorted() function to sort the list.

Example:

import random

x = int(raw_input("Enter desired number: "))

def randoTaker():
    return random.randint(0, 101)

print(randoTaker())

randlst = []
for i in range(x-1):
    randlst.append(randoTaker())

randlst.sort()
print(randlst)

Upvotes: 0

moraygrieve
moraygrieve

Reputation: 466

How about the below;

import random

x = int(raw_input("Enter desired number: "))

def randoTaker():
    return random.randint(0, 101)

for j in sorted([randoTaker() for i in range(x)]):
    print j

Upvotes: 4

cdarke
cdarke

Reputation: 44364

The problem is that you are printing your results rather than storing them. You probably want to save them in a list, then sort the list:

import random

x = int(raw_input("Enter desired number: "))

def randoTaker():
    return random.randint(0, 101)

results = []
for i in range(x-1):
    results.append(randoTaker())

results.sort()

print results

If you really want, you can use a list comprehension:

import random

x = int(raw_input("Enter desired number: "))

def randoTaker():
    return random.randint(0, 101)

print sorted([randoTaker() for i in range(x-1)])

Upvotes: 0

Related Questions