Advertisement
Luninariel

Python Homework 2 - Recursive

Sep 23rd, 2019
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 0.91 KB | None | 0 0
  1. '''This program will peform the following:
  2. * A set is provided
  3. * Each set is converted to a list
  4. * The subsets of each set is generated
  5. * The subsets are returned as a frozen set.'''
  6.  
  7.  
  8. def allsubsets(inputset):
  9.  
  10.     # convert the set to a list, so that it's easier to work with.
  11.     worklist = list(inputset)
  12.  
  13.     #Using recursion, we establish a base case so that the recursion breaks out.
  14.     if len(worklist) <= 1:
  15.         yield frozenset(worklist)
  16.         yield frozenset([])
  17.     #Generate allsubsets for the list other than the first element    
  18.     else:
  19.  
  20.         #For Each loop that will return each item from the recursive call and returns the subset with the first item in the list added as well
  21.         for item in allsubsets(set(worklist[1:])):
  22.             yield frozenset([worklist[0]]+list(item))
  23.  
  24.            
  25.             #Returning just the item itself.
  26.             yield frozenset(item)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement