I've discovered my biggest issue with practicing interview questions and writing software more generally is keeping track of indices in python, maybe partly because my first two languages were the 1-indexed Fortran and R. When I'm iterating through an array, especially with more complicated nested for loops, I very frequently get out of range errors. Is it better practice then to try to avoid to manually updating pointers? Here's is some sample code of mine where I am trying to build all subsets of a list
def oob(index, arr_len): return index == arr_len nums = [1,2,3] arr_len = len(nums) # iterate through len of subsets for sub_len in range(arr_len): sub_len += 1 #create list of pointers, iteratively increasing the last one pointers = list(range(sub_len)) for point in range(len(pointers)): curr = len(pointers) - 1 - point #make sure not out of bounds, add solution, update curr pointer and OOB while not oob(pointers[curr], arr_len): ans.add(tuple((nums[elem] for elem in pointers))) pointers[curr] += 1 arr_len = pointers[curr]
PS, I know there's probably a cleaner solution out there for this problem, but I wanted to showcase some general code I write to help demonstrate where my shortcomings my be.
PSS: note this "solution" isn't even valid for the task at hand, it only works for a 3-array. I only figured that out after asking the question, but the answers were really good anyways