mardi 15 janvier 2019

Python: function to group number by tens place

Takes a list of numbers and groups the numbers by their tens place, giving every tens place it's own sublist.

ex:

$ group_by_10s([1, 10, 15, 20])
[[1], [10, 15], [20]]
$ group_by_10s([8, 12, 3, 17, 19, 24, 35, 50])
[[3, 8], [12, 17, 19], [24], [35], [], [50]]

my approach:

limiting = 10
ex_limiting = 0
result = []
for num in lst:
    row = []
    for num in lst:
        if num >= ex_limiting and num <= limiting:
            row.append(num)
            lst.remove(num)
    result.append(row)
    ex_limiting = limiting
    limiting += 10

But it returns [[1], [10, 20]]. What's wrong with my approach and how can I fix it?

Aucun commentaire:

Enregistrer un commentaire