If your only question is to debug your code, it is off-topic. 

If you did run it and can't explain why your code behaves strange at a particular line it might be on topic.

Reading your question for the third time I see you ask *Can you spot where the script is going wrong?* That is more something for you to do. And if you have spotted it we can help out because you can clearly explain what the input is and what you expected as output for one or two functions.

Check the [How to ask](http://stackoverflow.com/help/how-to-ask) and [Minimal, Complete, and Verifiable example](http://stackoverflow.com/help/mcve)

You might find the [answer of Robert Harvey](http://meta.stackoverflow.com/a/254096/578411) useful as well.