Home > Blockchain >  Struggling to parse through an array/list into my second function- this is specific to the Fibonacci
Struggling to parse through an array/list into my second function- this is specific to the Fibonacci

Time:08-15

def fibArray(N):
    fibarray=[] 
    num1 = 0
    num2 = 1
    find = 2
    fibnum=0
    while find < N:
            fibnum = (num1 num2)
            num1 = num2
            num2 = fibnum
            find = (find 1)
            fibarray.append(int(fibnum))
    return(fibarray)

def fibwritefile(fibarray):
    for X in range(len(fibarray)):
        with open(f"fib-number-{fibarray[X]}.txt", "w") as file:
            file.write(str(fibarray[X]))
            file.close()

fibarray=fibArray(7)
fibwritefile(fibarray)

The expectation is I should have 7 files- ranging from 1-7 and within each file the corresponding fibonnaic number (the fibarray=[] elements.)

what I get instead:

fib-number-3.txt           
fib-number-1.txt  fib-number-5.txt 
fib-number-2.txt  fib-number-8.txt

Is five files with the Fibonacci number as file name- and only 5 files- I have tried to print the index in the file name but it does not work?

Could I please get the solution as its driving me nuts!

CodePudding user response:

If with input 7 you expect

  • file fib-number-1.txt to contain 1
  • ...
  • file fib-number-7.txt to contain 1 1 2 3 5 8 13 (on each line)

You need to use the indice for the filename, not the corresponding value in the array, then slice the array to have the first N values

def fibwritefile(fibarray):
    for i in range(1, len(fibarray)   1):
        with open(f"fib-number-{i}.txt", "w") as file:
            file.write("\n".join(map(str, fibarray[:i])))

And your fibArray can be simplified much

def fibArray(size):
    fibarray = [1, 1]
    while len(fibarray) < size:
        fibarray.append(sum(fibarray[-2:]))
    return fibarray
  • Related