I'm building a GUI in Python and Tkinter and I need to generate a graphic for every item on a list. My list is going to vary in length from say 2 to 20. How can I sort my list into the most efficient grid?
for example:
myList = [0,1,2,3,4,5,6]
len(myList) will return 7, so the best grid is probably 3x3 with one graphic on the last row.
Like so: Best Grid
EDIT: Thank you all for your help. This GUI is going to be full screen on a 800x480 RaspberryPi touchscreen, so I want to make the most efficient use of space in Landscape mode as I can.
This is what I've tried so far:
import math
myList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]#,16,17,18,19,20,21,23,24,25]
def integer_sqrt(n):
x = n
y = (x + 1) // 2
while y < x:
x = y
y = (x + n // x) // 2
return x
a = integer_sqrt(len(myList))
c = len(myList)
print("The length of myList is: {}".format(len(myList)))
print("The integer-only root of the length of myList is: {}".format(a))
print("The remainder of the calculation is: {}".format(c % a))
The output for a short list seems to work:
>>> The length of myList is: 5
>>> The integer-only root of the length of myList is: 2
>>> The remainder of the calculation is: 1
This works too:
myList = [1,2,3,4,5,6,7,8,9,10]
>>> The length of myList is: 10
>>> The integer-only root of the length of myList is: 3
>>> The remainder of the calculation is: 1
But when I change the list length to a higher modulo, it starts to fail:
myList = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]
>>> The length of myList is: 15
>>> The integer-only root of the length of myList is: 3
>>> The remainder of the calculation is: 0
I'm not sure why this doesn't work, and I'm not married to this method of sorting. Is there a better way?