Haresh Senthilkumar
Haresh Senthilkumar

Reputation: 9

getting list index out of range error when trying to add a a number from a list into a another list

Gudi = 0
gudi = []
Numbers = []
A = int(input("how many numbers are in the list"))
time.sleep(.5)
print ("Can you please enter the numbers?")
time.sleep(.3)
for i in range(A):
  data = int(input())
  Numbers.append(data)

# variables
median = sorted(Numbers)
ludi = int(A/2) 
two = ludi - 1
One = median[ludi]
Two = median[two]
sum = (One + Two)
Ans = sum/2
cal = int((A - 1)/2 + 1) - 1
ans = median[cal]

def Median():
  if A%2 == 0:
     print ("The median is " + str(Ans))
  else:
     print ("The median is " + str(ans))


 def sorlist():
   print median

 def Maximum():
   print (median[-1])


 def Minimum():
   print (median[0])


 def UQ():
   if A%2 != 0:
      global Gudi
      global cal # the indice of the median
      var = A - (cal - 1) # number of numbers that come after the median
      Gudi += 1
      for i in range(var):
        cal += Gudi
        gudi.append(median[cal])
        Gudi += 1
 UQ()

When I am trying to run the last function which is called UQ, I am getting this error: "IndexError: list index out of range on line 50 in main.py". I can't figure out what is wrong. I am trying to print the number of a list into a another list so then I can find the upper quartile.

Upvotes: 0

Views: 30

Answers (1)

Jackson
Jackson

Reputation: 1223

The problem lies here

 for i in range(var):
    cal += Gudi
    gudi.append(median[cal])
    Gudi += 1

In each iteration

  1. you are adding cal by Gudi
  2. Gudi increases by 1

Suppose A = 10

cal = int((A - 1)/2 + 1) - 1 = 4

var = 10 - (4- 1) = 5

when

i=0, cal = cal + gudi = 4 + 1 = 5, Gudi = 2

i=1, cal = cal + gudi = 5 + 2 = 7, Gudi = 3

i=2, cal = cal + gudi = 7 + 3 = 10, Gudi = 4 --> out of bound

Upvotes: 1

Related Questions