Python Forum
Powerset function alternative does not work
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Powerset function alternative does not work
#1
Hi, I'm new to python (and to coding in general) and I need a powerset function. The one just below works fine, but I'm not familiar with the following notition:

1
newset = [subset + [x] for subset in result]
I try to replace it with the following code:
1
2
for subset in result:
newset = [subset + [x]]
This however seems to generate an error. Can anyone please explain to me why this is the case? Thank you!

Full code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
def powerset(xs):
    result = [[]]
    for x in xs:   
        newset = [subset + [x] for subset in result]
        result.extend(newset)
    return result
 
print(powerset([0,1,2]))
 
def powerset2(xs):
    result = [[]]
    for x in xs:   
        for subset in result:
            newset = [subset + [x]]
            result.extend(newset)
    return result
 
#data = build_items(3)
print(powerset2([0,1,2]))
Reply
#2
your second bit of code isn't indented properly
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  print doesnt work in a function ony 2 1,111 Mar-11-2024, 12:42 PM
Last Post: Pedroski55
  I dont know why my function won't work? MehHz2526 3 2,071 Nov-28-2022, 09:32 PM
Last Post: deanhystad
  time function does not work tester_V 4 4,763 Oct-17-2021, 05:48 PM
Last Post: tester_V
  write new function or change the old one to work "smartter? korenron 3 2,808 Aug-09-2021, 10:36 AM
Last Post: jamesaarr
  string function doesn't work in script ClockPillow 3 3,793 Jul-13-2021, 02:47 PM
Last Post: deanhystad
  Why does unpickling only work ouside of a function? pjfarley3 5 4,721 Dec-24-2020, 08:31 AM
Last Post: pjfarley3
  len() function, numbers doesn't work with Geany Editor Penguin827 3 3,922 May-08-2020, 04:08 AM
Last Post: buran
  why my function doesn't work cimerio 4 3,878 Jan-20-2020, 08:11 PM
Last Post: cimerio
  Doesn't work function pyautogui.typewrite() aliyevmiras 1 5,851 Dec-22-2019, 11:35 AM
Last Post: aliyevmiras
  Type function does not work sunnyarora 2 3,271 Mar-15-2019, 10:50 AM
Last Post: sunnyarora

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020