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)
CodePudding user response:
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 :
- I would encapsulate your executing script within
if __name__ == "__main__":
(see What does if __name__ == "__main__": do? for more details). - 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)
. - In the same way I would pass
x
as an input variable for thepresent_list()
function - I would also correct your usage of
seed
andy
(both in the executing script and functions)
I will provide corrections to your code later if it's too difficult to understand.