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 55,457 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