Skip to content

Instantly share code, notes, and snippets.

@CoderPuppy
Created May 17, 2016 03:18
Show Gist options
  • Save CoderPuppy/3ae0a667660617d6d6898c8cd122f99d to your computer and use it in GitHub Desktop.
Save CoderPuppy/3ae0a667660617d6d6898c8cd122f99d to your computer and use it in GitHub Desktop.
Subsets
def subsets(s, n, l):
if len(s) == 0 and n == 0:
l.append([])
return
if len(s) == 0:
return
h, *t = s
st = []
subsets(t, n - h, st)
for s in st:
l.append([h, *s])
subsets(t, n, l)
{-# OPTIONS_GHC -fno-warn-tabs #-}
module Powerset where
powerset :: [a] -> [[a]]
powerset [] = [[]]
powerset (h:t) = pt ++ fmap (h:) pt
where
pt = powerset t
subsets :: (Num a, Eq a) => [a] -> a -> [[a]]
subsets s n = filter (\s -> sum s == n) $ powerset s
def powerset(s):
if len(s) == 0:
return [[]]
h, *t = s
pt = powerset(t)
return pt + [ [h] + s for s in pt ]
def subsets(s, n, l):
l.extend([ s for s in powerset(s) if sum(s) == n ])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment