Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python Object-Oriented Python Advanced Objects Frustration

Pavlo Vasylyshyn
Pavlo Vasylyshyn
4,641 Points

OO Python: "Frustration :) task challenge" validation error

Hello, I didn't want to edit __init__ and my solution works in the Workspaces. Shell entries:


from ... import Liar

tmp = Liar(1, 2, 3, 4, 5)

len(tmp)

... random number from doubled original len


Task validation throws following exception: "ValueError: empty range for randrange() (1,1, 0)". What am I doing wrong? Thank you

frustration.py
import random

class Liar(list):
    def __len__(self):
        my_len = super().__len__()
        rnd_len = random.randint(1, my_len * 2)
        while rnd_len == my_len:
            rnd_len = random.randint(1, my_len * 2)
        else:
            return rnd_len

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,441 Points

You're on the right path, It's your choice of "lie" can cause an empty range if the initial list has zero length. This causes calling random.randinit(1,0) which fails. Choosing another "lie" would work, such as, random.randint(my_len, (my_len + 1) * 2) or simply my_len + 2

Pavlo Vasylyshyn
Pavlo Vasylyshyn
4,641 Points

Well in this case a simple workaround can be also an "if statement" after requesting original len from super. Something like:

import random

class Liar(list):

def __len__(self):

    my_len = super().__len__()

    if not my_len > 0:

        my_len = 5

    rnd_len = random.randint(1, my_len * 2)

    while rnd_len == my_len:

        rnd_len = random.randint(1, my_len * 2)

    else:

        return rnd_len

But this is sort of forced fix, since my_len is obviously not assigned as intended. I do not understand how list is passed to the Liar class by the validation script. By the way, correction on my side, in the original post I missed square brackets in this line -> tmp = Liar(1, 2, 3, 4, 5) Thanks, Pavlo