Home > database >  IndexError: Out of bounds for test case 1 and 3; program crashes when value3 > value1
IndexError: Out of bounds for test case 1 and 3; program crashes when value3 > value1

Time:03-20

Create a function that takes in three arguments and prints one integer.

  • Random seed should be set to 42.
  • First argument should correspond to the size of a np.randint - values from 0 to 10.
  • Second argument is an integer that you will multiply the randint by.
  • The third argument is a value you will index the result of the multiplication by.

Print the integer that was indexed as ‘Your random value is k’

k = the result of the indexing

The program should not crash if the third value is larger than the first; it should not print anything to the screen.

Code

import sys
import numpy
import random

numpy.random.seed(42)
value1 = int(sys.argv[1])
value2 = int(sys.argv[2])
value3 = int(sys.argv[3])


def randomized(arg1, arg2, arg3):
    x = numpy.random.randint(0, 10, size=arg1)
    y = x * arg2
    return y[arg3]


try:
    random_value = randomized(value1, value2, value3)
    print(f"Your random value is {random_value}")
except IndexError:
    pass

randomized(value1, value2, value3)

Test Case Examples:

python3 reallyrandom.py 1 2 9 
python3 reallyrandom.py 44 3 17
python3 reallyrandom.py 77 -3 55
python3 reallyrandom.py 2 4 10 

Expected Output:

Your random value is 21
Your random value is -9

Error Message

Traceback (most recent call last):
  File "reallyrandom.py", line 23, in <module>
    randomized(value1, value2, value3)
  File "reallyrandom.py", line 14, in randomized
    return y[arg3]
IndexError: index 9 is out of bounds for axis 0 with size 1

CodePudding user response:

The program should not crash if the third value is larger than the first; it should not print anything to the screen

So, the error raised is an IndexError, right? You can prevent your code from printing anything using a try/except block, like this:

try:
    # Your code
except IndexError:
    pass # Nothing gets printed
  • Related