Created
May 17, 2016 03:18
-
-
Save CoderPuppy/3ae0a667660617d6d6898c8cd122f99d to your computer and use it in GitHub Desktop.
Subsets
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{-# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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