Here is my problem:
And here is my solution:
And this is the error that I am getting:
pythp
Here is my problem:
And here is my solution:
And this is the error that I am getting:
pythp
You missed this instruction
if v is ommited, fill the array with undefined
You can fix that by changing your definition to
def prefill(n,v = 'undefined'):
However, this will only get you to the next error
Be sure to read the instructions again for that one too
if n is anything other than an integer or integer-formatted string (e.g. ‘123’) that is >=0, throw a TypeError
When throwing a TypeError, the message should be n is invalid, where you replace n for the actual value passed to the function.
The test is providing -5, which is less than 0, so your logic should be throwing a TypeError with the message of “n is invalid”
here is my updated code:
But I am getting a new error:
Okay, so you are getting closer
First thing, you have two of the following conditions
if type(n) == str:
n = int(n)
You need to keep the first one, and it needs to be further towards the top, which gives you (as you can’t compare n to 0 or n < 0 without it being cast to an int first)
if type(n) == str:
n = int(n)
if n == 0:
return []
if n<0:
return n + "is invalid"
Now you need to actually test for an invalid int, using a try/except, because if they pass in ‘j’, it will fail due to a ValueError being returned.
if type(n) == str:
try:
n = int(n)
except ValueError:
raise TypeError(n + ' is invalid')
if n == 0:
return []
if n<0:
return n + "is invalid"
Note, how I raise
a TypeError, we need to do that for when n < 0
too
if type(n) == str:
try:
n = int(n)
except ValueError:
raise TypeError(n + ' is invalid')
if n == 0:
return []
if n<0:
raise TypeError(str(n) + ' is invalid')
Lastly, if you just do those, you will get another failing test due to n == None
, to resolve that
if n == None:
raise TypeError('None is invalid')
if type(n) == str:
try:
n = int(n)
except ValueError:
raise TypeError(n + ' is invalid')
if n == 0:
return []
if n<0:
raise TypeError(str(n) + ' is invalid')
Finally, the entire script now looks like:
def prefill(n,v = 'undefined'):
a = []
if n == None:
raise TypeError('None is invalid')
if type(n) == str:
try:
n = int(n)
except ValueError:
raise TypeError(n + ' is invalid')
if n == 0:
return []
if n<0:
raise TypeError(str(n) + ' is invalid')
while len(a)<=n:
a.append(v)
del a[-1]
return a
That is clever !
This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.