0

I was reading a blog post about the use of sigma-algebras in probability. The author gave a simple example, followed by some Python code showing how he would solve the problem in Python. However, when I tested out his Python code using Google Colab, I ended up with error messages when I ran it (TypeError: 'function' object is not iterable).

I'm not much of a Python user, so I've never used it to solve mathematical problems, but I was reading the blog post as I would like to learn how to use it to solve data science problems like this. I searched Google and couldn't find any other articles about using Python to solve sigma-algebra, so I thought I'd post the question in case other people had tried to run the code to learn Python and found the same errors. I was taught Matlab and R at university, not Python.

Here is the URL of the blog post: https://towardsdatascience.com/foundations-of-probability-7a792e7eea5

Here is the code he supplies:

from itertools import combinations, chain
powerset = ((),)
def powerset(input_set):
size = len(input_set)
    combs = (combinations(input_set, k) for k in range(1, size+1))
    
    return chain(empty_powerset, *combs)

print(tuple(powerset({10, 20, 30})))

The solution should show 8 sets; one of which is the empty set (), and then the remaining seven are {10},{20} and so forth through to {10, 20, 30}. What would you do to correct this snippet of code? Thanks!

Only_me
  • 37
  • 6
  • [How to get all subsets of a set? (powerset)](https://stackoverflow.com/q/1482308/6045800) – Tomerikoo Apr 18 '21 at 18:44
  • @Tomerikoo. Thank you. It is interesting that post doesn't refer to sigma-algebras or Borel fields. But yes, a sigma is a collection of all subsets including the empty set and the set itself, so it is the power set. – Only_me Apr 18 '21 at 19:01

1 Answers1

1

There are at least two mistakes with the code as it is posted on the site. Here is the correct code:

import pandas as pd

from itertools import combinations, chain

empty_powerset = ((),)

def powerset(input_set):
    size = len(input_set)
    combs = (combinations(input_set, k) for k in range(1, size + 1))

    return chain(empty_powerset, *combs)


print(tuple(powerset({10, 20, 30})))

First, it's empty_powerset, and second the indentation before size = ... is missing.

The result I get with this is

((), (10,), (20,), (30,), (10, 20), (10, 30), (20, 30), (10, 20, 30))
divingTobi
  • 2,044
  • 10
  • 25
  • 1
    Thank you - that runs perfectly and that is the correct result that I'd expect mathematically as that is all possible (2^3=8) sets. Thanks very much for fixing the code. It is much easier to learn when the code is actually right. :) – Only_me Apr 18 '21 at 18:52
  • @Only_me yeah, that's true xD – TheEagle Apr 18 '21 at 19:10