One of the easiest ways to understand and debug code is to put print statements everywhere and then figure out why you are getting the results printed. This is especially important when first starting to code and given homework assignments. The code you posted appears to show that you tried something and probably thought about it awhile then tossed in the towel and went and asked for help. Most experienced programmers would rather see novices develop debugging skills instead of being constantly available to work through practice algorithms with them.