0

Reinitializing variable in a while loop

Hello I solved a problem on codewar https://www.codewars.com/kata/5550d638a99ddb113e0000a2 I did it without using the pop function due to optimization concern (having my code time out happened several time). But when I solved it, I saw that the best practice solution used append/pop combination. def josephus2(xs, k): i, ys = 0, [] while len(xs) > 0: i = (i + k - 1) % len(xs) ys.append(xs.pop(i)) return ys I decided to time this solution against mine to see if I was more efficient. Only trouble at the end of each solutions the initial list have been modified. For the best solution it is empty (so of course the subsequent running were super fast) and for mine it contain strings (meaning the code never stop running). So I have to reinitialize the initial value. And for the best practice solution I am not able to do it. Before the while loop I put : v= tuple(xs) but impossible to put a xs = list(v) after the while loop... Any insight ?

27th May 2020, 6:30 AM
nicolas seespan
nicolas seespan - avatar
1 Odpowiedź
0
So you want to optimise your code? DO NOT USE PYTHON. Python absolutely sucks at speed and memory management (and this is coming from a Python Programmer). It is a pure object oriented, interpreted, scripting language. It checks every box when you talk about slow and bulky languages. Make no mistake, Python is a very capable language, but optimisation is not exactly it's strong point. If you want to really optimise this problem use C or C++. With Programmed Memory management, your programme is certain to run much faster and use lesser memory. However, the "best practice code" is indeed the best practice code for the Joshephus Permutation in Python3 with best speed, though it only works for numeric spaces. You can still use the same code for designing a non-numeric space solution by using the numbers for indexes rather than using excess variables. For the re-initialisation problem, you might want to use a global copy of the space before you process over it. Like this:- global_space=[] def my_function(space,k): global global_space global_space=space #rest of the function pass This will save a copy of the space outside the scope of the function so you can work with it later.
12th Jun 2020, 9:44 AM
Anubhav Mattoo
Anubhav Mattoo - avatar