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:

newset = [subset + [x] for subset in result]
I try to replace it with the following code:
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:
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 299 Mar-11-2024, 12:42 PM
Last Post: Pedroski55
  Twilio alternative jmair 3 3,903 Feb-08-2024, 01:55 PM
Last Post: Sharmi
  Pillow alternative? kucingkembar 4 878 Jul-27-2023, 10:50 AM
Last Post: Larz60+
  I dont know why my function won't work? MehHz2526 3 1,197 Nov-28-2022, 09:32 PM
Last Post: deanhystad
  time function does not work tester_V 4 3,041 Oct-17-2021, 05:48 PM
Last Post: tester_V
  write new function or change the old one to work "smartter? korenron 3 1,976 Aug-09-2021, 10:36 AM
Last Post: jamesaarr
  string function doesn't work in script ClockPillow 3 2,416 Jul-13-2021, 02:47 PM
Last Post: deanhystad
  Why does unpickling only work ouside of a function? pjfarley3 5 3,443 Dec-24-2020, 08:31 AM
Last Post: pjfarley3
  Alternative for Cairosvg? Maryan 0 2,459 Oct-26-2020, 01:27 PM
Last Post: Maryan
  len() function, numbers doesn't work with Geany Editor Penguin827 3 3,001 May-08-2020, 04:08 AM
Last Post: buran

Forum Jump:

User Panel Messages

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