Reputation:
AN implementation of Crohn(Крона) algorithm used in Scheduling theory, is it possible to change the data of the current index in a for loop in python? I have a code like so; link to the full code
#list1 is a 2d array
list1 = [[12, 3, 17], [14], [10, 12, 15]]
cond = 1
while cond:
d = delta(sum_calc(list1))
#delta() finds the difference between the list with the highest sum
#and the list with the minimum sum, then returns the
#difference(d[0]), index_of_list_with_max_sum(d[1]), #index_of_list_with_min_sum(d[2])
#d = [23, 2, 1]
if cond == 0:
break
else:
for i in list1[d[1]]:
if d[0] > i:
move(list1[d[1]], list1[d[2]])
#move() moves the min element from list1, to list2
else:
cond = 0
what I am trying to do is, given an index, loop through the elements of that list, then check if num is greater than i (element), after that we do some operations, like moving the smallest element from the current list we are looping from, to another list. then we have some operations, after that I want to change the value of i, to something like
#the index might change
i = l[index]
the problem I am facing is that when I do that, it continues looping from the first index. Is there a way I can reset it, so that it starts looping from other elements?
I HAVE USED A WHILE LOOP, because I want the procedure to repeat itself and until d[0] !> i:
#since the list with the highest sum is list1[2], we got 2 from d,
#next step is to loop through the elements in that list and check if
#there's an element which is less than d[0](the difference between max and min sum)
#expected results
#after first iteration
list1 = [[12, 3, 17], [14, 10], [12, 15]]
d = [8, 0, 1]
#after second iteration
list1 = [[12, 17], [14, 10, 3], [12, 15]]
d = [2, 0, 1]
#the problem is it stops here, I want it to calculate delta again then #repeat the process, but after debugging, i found that in the second #iteration i = 15, which the second element of the list, but it should #be like that.
Upvotes: 0
Views: 1561
Reputation: 1194
Try to combine while loop with index ?
example:
lst = [1,2,3]
idx = 0
while idx < len(lst):
print(lst[idx])
idx += 1
if idx == len(lst):
# Reset index
idx = 0
EDIT
After debugging I found your errors - You havent been assigning the new delta
result to d
where you have been referencing from your code thus you never got the new indexes
cond = True
idx = 0
while cond and idx < len(l[d[1]]):
if d[0] > l[d[1]][idx]:
move(l[d[1]], l[d[2]])
s = sum_calc(l)
d = delta(s)
print("l =", l)
print("s =", s)
print("d =", d)
print("")
idx = 0
else:
cond = False
idx += 1
Output:
l = [[12, 3, 17], [14, 10], [12, 15]]
s = [32, 24, 27]
d = [8, 0, 1]
l = [[12, 17], [14, 10, 3], [12, 15]]
s = [29, 27, 27]
d = [2, 0, 1]
Upvotes: 1