0

I can't figure out why I'm getting this error: Traceback (most recent call last): line 78, in find_max_gap(x) line 22, in find_max_gap vmin = x[0] TypeError: 'int' object is not subscriptable

I'm new to Python so It's difficult for me to track the mistakes I make. I've been trying to figure out what's going on the whole day

User inputs the parameters and creates a random list that calculates the longest distance among its elements.

import random

def generate_random_floats(n,m,seed):
    x = []
    if (y==0):
        random.seed()
        for i in range (n):
            x.append(random.uniform(-m,m))
    else:
        random.seed(y)
        for i in range (n):
            x.append(random.uniform(-m,m))
    return x
    pass
    # function that returns a list of n random numbers in span
    # -m, m with seed generator of random numbers (optional argument)
    
def find_max_gap(x):
    vmin <= x[0]
    dmax = 0
    for i in range (n):
        if (x[i] < vmin):
            vmin = x[i]
        elif (x[i] - vmin > dmax):
            dmax = x[i] - vmin
    return (dmax)
    
    # function that accepts a list of real numbers and returns the maximum distance between them
    pass

def present_list():
    print(" The random list is:",generate_random_floats(n,m,seed))
    # auxiliary function that prints the elements of a list
     pass

n=-1
while n < 0 or n == 0 :
    while True:
        try:
            # user input of how many random numbers
            n = int(input(">>Define the number (n) from the random numbers.\n-Positive number) :"))
            break
        except:
            continue
m=-1
while m < 0 :
    while True:
        try:
            # input user -m, m
            m = int(input(">>Define (range) from which random values will be selected.\n) :"))
            break
        except:
            continue
seed=0
b=0
x=0
s=0
while True:
    try:
        # input seed
        y = int(input("Enter the number that will set the seed value. :"))
        break
    except:
        continue
# create list of random numbers
generate_random_floats(n,m,seed)
present_list()
find_max_gap(x)   
  • Is it a typo that in the function "generate_random_floats" you used y instead of seed? – AdrienNK Jan 14 '22 at 16:36
  • I don't think so. I changed it and I still get this message. –  Jan 14 '22 at 16:40
  • Please [edit] your question to show the entire error message. – Code-Apprentice Jan 14 '22 at 17:00
  • 2
    Minor notes: 1) `while n < 0 or n == 0 :` is a slow/verbose way to spell `while n <= 0:`. 2) *Never* use a bare `except:` that doesn't re-`raise` the exception when its done. Sure, you may want to ignore user mistakes and ask again, but even then, use `except Exception:` so you don't, say, ignore it when the user hits Ctrl-C to forcibly exit your program, or hits Ctrl-D to end input, but you just keep prompting them forever. – ShadowRanger Jan 14 '22 at 17:03

1 Answers1

0

When you define x = 0 in the code, you expect it to pass it to your functions as it is implicitely considered as a global variable.

Then in the function generate_random_floats you think you're modifying x while in fact the x in that function is not the same as the x in your global scope.

After that, during your call to find_max_gap, in the line vmin <= x[0] the x is still an int (and is equal to 0). Trying to access x like a vector ( x[0] ) is raising the error.

There would be a few things to modify in your code so that it does what you want :

  1. I would encapsulate your executing script within if __name__ == "__main__": (see What does if __name__ == "__main__": do? for more details).
  2. I would avoid to use variables in a global way. Instead of calling your functions like this generate_random_floats(n,m,seed) I would explicitely use the return of the functions to assign the variables : x = generate_random_floats(n,m,seed).
  3. In the same way I would pass x as an input variable for the present_list() function
  4. I would also correct your usage of seed and y (both in the executing script and functions)

I will provide corrections to your code later if it's too difficult to understand.

EDIT : Corrected code

import random

def generate_random_floats(n,m,seed):
    x = []
    if (seed==0):  # modified y => seed
        random.seed()
        for i in range (n):
            x.append(random.uniform(-m,m))
    else:
        random.seed(y)
        for i in range (n):
            x.append(random.uniform(-m,m))
    return x
    # function that returns a list of n random numbers in span
    # -m, m with seed generator of random numbers (optional argument)
    
def find_max_gap(x):
    vmin = x[0] #corrected assignation
    dmax = 0
    for i in range (n):
        if (x[i] < vmin):
            vmin = x[i]
        elif (x[i] - vmin > dmax):
            dmax = x[i] - vmin
    return dmax
    # function that accepts a list of real numbers and returns the maximum distance between them


def present_list(x):
    print(" The random list is:", x) # replaced the function call with x
    # auxiliary function that prints the elements of a list


if __name__ == "__main__":
    n=-1
    while n < 0 or n == 0 :
        while True:
            try:
                # user input of how many random numbers
                n = int(input(">>Define the number (n) from the random numbers.\n-Positive number) :"))
                break
            except:
                continue
    m=-1
    while m < 0 :
        while True:
            try:
                # input user -m, m
                m = int(input(">>Define (range) from which random values will be selected.\n) :"))
                break
            except:
                continue
    seed=0
    while True:
        try:
            # input seed
            seed = int(input("Enter the number that will set the seed value. :")) # replaced y with seed
            break
        except:
            continue
    # create list of random numbers
    rfloats = generate_random_floats(n,m,seed) #generate new list rfloats
    present_list(rfloats) 
    mgap = find_max_gap(rfloats) 

    print("The max gap is :", mgap)
AdrienNK
  • 850
  • 8
  • 19
  • Thanks a lot for your answer! As I said, I'm new to Python so I'm struggling to understand everything you wrote. I tried to correct some of the things you mentioned but I'm not sure I'm following the right path. –  Jan 15 '22 at 12:29
  • I would love to see your corrections, I'm still struggling with the code. –  Jan 16 '22 at 16:16
  • I added the code in edit, I only corrected the code so that it runs (please refer to other comments for improvements) – AdrienNK Jan 17 '22 at 11:22