Back to Problem Solutions forum
What I have, for the sorting function portion, is this:
def bubble_pass(original):
counter = 0
for i, v in enumerate(original[:-1]): #:-1 so it doesn't try to compare the last number to the non-existant one after it
if v > original[i+1]:
original[i], original[i+1] = original[i+1], original[i]
counter += 1
return counter, original
it gives me the correct solution for the example case (1 4 3 2 6 5), both the number of changes and the checksum. But when I try the actual tests it always fails with too few swaps. Any ideas of what could be going wrong? One thought I had is that it could be about editing a list at the same time as I'm iterating through it... but how do I avoid that without making a new copy of the list for each iteration?
Hi! Thanks for your question!
I'm not sure how this code works for example case - it does not work for me - but it is not important :)
see this test: http://ideone.com/4vQvxU - I added print for i
and v
inside
the loop, as you see, despite the performed swaps v
is not changed. I believe that enumerate
creates
a copy and serves data from it, so they are not affected by swaps.
Ah!
I am not sure how the code had been working for me before. You are correct, enumerate creates a separate iterator object and that was the source of the failure. So I fixed it by doing what I was originally trying to avoid, range(len(original)-1).
Thank you! And if you are the creator of the site, thanks so much for making it. I find your tasks much more enjoyable than the ones on similar sites.
(it's me again but from non-admin account)
I'm glad I was able to help - moreover that I do not know Python well, so I myself learned something new from your question :)
Thank you for your kind words. However be sure this site never could be anything good without so many people asking questions, spotting errors, making suggestions - e.g. helping and inspiring in many ways!