Skip to content

Commit 7db115d

Browse files
committed
add iterative approach
1 parent 47dda38 commit 7db115d

File tree

1 file changed

+28
-0
lines changed

1 file changed

+28
-0
lines changed

Recursion/powerset.py

+28
Original file line numberDiff line numberDiff line change
@@ -66,3 +66,31 @@ def powerset(array):
6666
def Powerset(array):
6767
# Call the helper function to generate the powerset starting from the last index
6868
return powerset(array, len(array) - 1)
69+
70+
71+
# Iterative approach
72+
def powersetIterative(array):
73+
# Initialize the powerset with the empty subset
74+
subset = [[]]
75+
76+
# Iterate over each element in the input array
77+
for ele in array:
78+
# Get the current length of the subset
79+
length = len(subset)
80+
81+
# Iterate over each existing subset
82+
for i in range(length):
83+
# Get the current subset
84+
currentSubset = subset[i]
85+
86+
# Create a new subset by making a copy of the current subset
87+
newSubset = list(currentSubset)
88+
89+
# Add the current element to the new subset
90+
newSubset.append(ele)
91+
92+
# Append the new subset to the powerset
93+
subset.append(newSubset)
94+
95+
# Return the powerset
96+
return subset

0 commit comments

Comments
 (0)