-2

I have declared the variable fiblist as global, yet it gets the value of None in gen10fib.

# Enter your code here. Read input from STDIN. Print output to STDOUT
#program to check if a number is fibonacci number

global fiblist 
fiblist=[0,1] #list to store generated fibonacci numbers

global Nlist
Nlist=[] # list for T test cases

global solnList
solnList=[] #contains the solution 1 is fibo 0 not fibo

global head
head=1 #to denote the maximum element in the list

def comparator(fiblist,x,head):


    if(head<x):


        gen10fib(fiblist) #generates the next 10 numbers of fibonacci sequence and appends them to fiblist

        head=max(fiblist) #upadate head

    else:

        flag=lookup(fiblist,x)

    return flag


def gen10fib(fiblist):

    fiblen=len(fiblist)

    fiblist=fiblist.sort()


    b,a=fiblist[fiblen-1],fiblist[fiblen-2] #getting the last 2 numbers

    i2=0

    for i2 in xrange(10):

      c=a+b

      fiblist.append(c)

      a=b 
      b=c



def lookup(fiblist,x):

    if x in fiblist:

        flag=1

    else:

        flag=0

    return flag




if __name__== '__main__':



 t=input()

 print t

 for i in xrange(t):

    Nlist.append(input())

 for x in Nlist:

    print x

    flag=comparator(fiblist,x,head)

 if(flag==0):

    solnList.append("IsNotFibo")

 else:

    solnList.append("IsFibo")

and the error message is

Traceback (most recent call last):
  File "G:/Codemagic/Scrap_python/dummy02", line 82, in <module>
    flag=comparator(fiblist,x,head)
  File "G:/Codemagic/Scrap_python/dummy02", line 60, in comparator
    gen10fib(fiblist) #generates the next 10 numbers of fibonacci sequence and appends them to fiblist
  File "G:/Codemagic/Scrap_python/dummy02", line 26, in gen10fib
    b,a=fiblist[fiblen-1],fiblist[fiblen-2] #getting the last 2 numbers
TypeError: 'NoneType' object has no attribute '__getitem__'

so the value of fiblist can't be accessed in gen10fib but could be accessed in comparator function

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
Creative_Cimmons
  • 255
  • 1
  • 2
  • 11

2 Answers2

5

The sort method sorts the list in-place and returns None, so fiblist = fiblist.sort() has the effect of sorting the list in-place and throwing away your reference to it. If you want to sort the list in-place, use fiblist.sort() with no assignment. If you want the original list unmodified and want a sorted copy, use fiblist = sorted(fiblist).

icktoofay
  • 126,289
  • 21
  • 250
  • 231
2

Inside gen10fib you have to declare again the variable as global:

Using global variables in a function other than the one that created them

Community
  • 1
  • 1
Suicide Platypus
  • 186
  • 1
  • 1
  • 9