TransWikia.com

How can i sort a function?

Stack Overflow Asked by Lumknight on December 16, 2021

What i want to do with this code is roll ‘n’ number of dice and then find the lower quartile of it.

so far i have:

from random import randint
#Rolling the Die

numofdie = int(input("Please input the number of dice u want to roll: "))

if numofdie < 1:
  print ("PLease enter 1 or more")
  quit()
if numofdie > 100:
  print ("PLease enter a number less than 100")
  quit()

#Sum

def dicerolls():
    return [randint(1,6) for _ in range(numofdie)]
print (dicerolls())

Then i used the string.sort() function to try and sort the dicerolls() but realised that it will not work as it is a function. How can i fix this and consequently be able to find the lower quartile.

Thanks

2 Answers

Put the result in a variable, then sort that.

rolls = dicerolls()
rolls.sort()
print(rolls)

Or use the sorted() function:

print(sorted(dicerolls())

Answered by Barmar on December 16, 2021

The built-in sorted() function will return a sorted version of whatever list you give it. Since dicerolls() returns a list, you can add that list right in:

print(sorted(dicerolls()))

Answered by Green Cloak Guy on December 16, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP