Python list increment

I am trying to increase the list of numbers in python, e.g. abacus.

list = [0,0,0,0]
units = 4

def m(list, units):
  for e in range(len(list)):
    if units:
      list[e] = list[e] + 1
      units -= 1

This code works fine if I run m(list, units), the list will be [1,1,1,1] - the problem I'm trying to solve is that when the value of the units is something like units = 2, the list will grow to [ 2,2,1,1] (which is good again) the problem is that I run the function m()from an uneven list, the list will expand from the list [0] to the end [3, 3,1,1], and not [ 2,2,2,2].

Is there a pythonic way that a function can grow a list from the lowest value to achieve uniform distribution?

+4
source share
1 answer

, starting_index = abacus.index(min(abacus)), @jonrsharpe.

, , units = 4 starting_index = 3, len(abacus), .. calculated_index % len(abacus).

, , range(units). , , .

:

def m(abacus, units):
    starting_index = abacus.index(min(abacus))
    for raw_index in range(units):
        index = (raw_index + starting_index) % len(abacus)
        abacus[index] = abacus[index] + 1

:

abacus = [0,0,0,0]    
print abacus
m(abacus, 2)
print abacus
m(abacus, 4)
print abacus
m(abacus, 3)
print abacus
m(abacus, 3)
print abacus
m(abacus, 7)
print abacus

:

[0, 0, 0, 0]
[1, 1, 0, 0]
[2, 2, 1, 1]
[3, 2, 2, 2]
[3, 3, 3, 3]
[5, 5, 5, 4]
+1

All Articles