I'm new to python and while practicing the language I've encountered a problem I could not understand.
My question is not about the algorithm itself, it is about references and recursion in python
# Background
Given a set of distinct integers, nums, return all possible subsets (the power set).
Example:
Input: nums = [1,2,3]
Output:[[],[1],[2],[1,2],[3],[1,3],[2,3],[1,2,3]]
So I have a Class Solution:
class Solution:
def find_subsets(self , nums , current_sub , all_subsets , index):
# print(current_sub) This will print the wanted results list
all_subsets.append(current_sub) # Here the all_subsets list will be [1][1] , [1,2] [1,2] [1,2]
if index < len(nums):
for i in range(index , len(nums)):
current_sub.append(nums[i])
self.find_subsets(nums , current_sub , all_subsets ,i + 1)
current_sub.pop()
# Entery point
def subsets(self, nums: List[int]) -> List[List[int]]:
current_sub = []
all_subsets = []
self.find_subsets(nums , current_sub , all_subsets , 0)
return all_subsets # output -> [[],[],[],[],[],[],[],[]]
print(current_sub) will print all wanted subsets, but at the end im getting an empty list inside all_subsets
What am I missing? is all_subsets is passed by reference? what is happening under the hood?