Search code examples
pythonsetassert

How to properly use (assert) in this case with Python?


I am a very new user to Python. I am writing a simple code to return two things: the union of two sets (where each of them contains numbers and words) as well as the length of the union set. I am trying to use assert with a very simple example as shown below, however, it keeps giving me AssertionError. This is how I defined the function:

def union(A, B):
    AuB = A.union(B)
    total = (AuB,len(AuB))
    print(total)

then I use this to execute it:

A = {1,4,-3, "bob"}
B = {2,1,-3,"jill"}
union(A,B)
assert union(A,B) == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)

However, this is the resulting error:

AssertionError                            Traceback (most recent call last)
<ipython-input-4-cb63795cc161> in <module>()
      2 B = {2,1,-3,"jill"}
      3 union(A,B)
----> 4 assert union(A,B) == ({-3, 1, 2, 4, 'bob', 'jill'}, 6)

AssertionError: 

Please advise what is the best way to use assert in this case, as I have to use it.

Thanks


Solution

  • In def union instead of print use return.

    def union(A, B):
      AuB = A.union(B)
      total = (AuB,len(AuB))
      return total