0

Why cant I enter in to the for loop for the below code

def maximumSwap(num):
    A = map(int, str(num))
    last = {x: i for i, x in enumerate(A)}
    for i, x in enumerate(A):
        print(i, x)
        for d in range(9, x, -1):
            if last.get(d, None) > i:
                A[i], A[last[d]] = A[last[d]], A[i]
                return int("".join(map(str, A)))
    return num

I was able to print the last but not able to enter the for loop. And I also want to know what is the difference between int(num) and map(int, str(num))

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
  • "*I also want to know what is the difference between int(num) and map(int, str(num))*" -- Welcome to [SO]! I see you've asked two questions. As you can tell, I've answered one of them and not answered the second. Asking two unrelated questions in the same post doesn't fit well with the format of [SO]. Please consider removing the second question from this post and asking it in a new post. – Robᵩ Mar 06 '18 at 01:47

1 Answers1

2

A is an iterator, and you can't run the same iterator twice. See, for example, http://stackoverflow.com/questions/3266180/… .

If you do need to loop over your data twice, you either have to recreate the iterator or store the data in a sequence, maybe a list:

Method 1:

last = {x: i for i, x in enumerate(map(int, str(num)))}
for i, x in enumerate(map(int, str(num))):

Method 2:

A = list(map(int, str(num)))
last = {x: i for i, x in enumerate(A)}
for i, x in enumerate(A):
Robᵩ
  • 163,533
  • 20
  • 239
  • 308