python - Check whether list element is greater than previous elements -
i have list in python:
mylist = [13, 8, 7, 5, 6, 3, 9] i check each element of list, whether greater or equal previous elements. if true want add 1 , check whether equal prior element. if happens add numbers til not true anymore.
i hope can understand, want archive. output mylist be
outputlist = [13, 8, 7, 5, 9, 3, 10] so 6 mylist greater 5 adds 1, 7, exists. adds 1 (value = 8) , 1 (value = 9).
the "9" initial list equal fresh calculated 9, adds 1.
note: order important, sorting mylist not option.
not pretty, did not find shorter way this. seems work, though.
def magic(lst): lst = lst[:] # create copy seen = set() # prior values set in range(len(lst)): if any(lst[i] >= x x in lst[:i]): # greter/equal prior lst[i] += 1 # first increment while lst[i] in seen: lst[i] += 1 # increment more seen.add(lst[i]) # add prior set return lst example:
>>> magic([9, 9, 9, 9]) [9, 10, 11, 12] >>> magic([13, 8, 7, 5, 6, 3, 9]) [13, 8, 7, 5, 9, 3, 10]
Comments
Post a Comment