What I am trying to accomplish is calculate the Tribonacci numbers and the ratio. I can do this in Excel easy like this.
So I tried do the same using Python 3 now. It works and gives such output.
But would you be so kind to review the code and see what obvious mistakes you see in it and advise on what is a better approach as I do not want to continue coding if my logic to tackle such problem is fundamentally flawed somewhere.
Priorities for me are execution time and readability I guess
What would you have done differently and why? I know it may look like a mess. From what I heard using exec and eval (code as string) are the bad ideas and also that function calls are expensive?
I don't like my code at all especially how next() is used so many times but hopefully you can see how I was thinking trying to replicate the Excel spreadsheet
To run the code you need numpy and pandas
import pandas as pd
import numpy as np
column_names = ["Number sequence", "Ratio"]
column_counter = len(column_names) -1
header_columns = ['']
while column_counter >= 0:
column_counter = column_counter - 1
header_columns.append(column_names[column_counter])
tribonacci_numbers = [0,1]
tribonacci_counter = 19 #Reach
while tribonacci_counter -1 >= 0:
tribonacci_counter = tribonacci_counter - 1
tribonacci_numbers.append(sum(tribonacci_numbers[-3:]))
tribonaccis_list_length = len(tribonacci_numbers)-1
index_builder = 1
rows = []
while index_builder <= tribonaccis_list_length:
try:
index_builder = index_builder + 1
rows.append((["Number: "+str(index_builder),tribonacci_numbers[index_builder],tribonacci_numbers[index_builder]/tribonacci_numbers[index_builder-1]]))
except IndexError:
continue
def get_row():
the_row = [x for x in rows]
row_counter = 0
while row_counter <= len(the_row):
try:
row_counter = row_counter + 1
yield (the_row[row_counter])
except IndexError:
continue
a = get_row()
def therow():
for q in a:
yield q
datas = np.array([
header_columns,
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow()),
next(therow())])
df = pd.DataFrame(data=datas[1:,1:],index=datas[1:,0],columns=datas[0,1:])
print(df)
If you want to provide an example that does the same and produces a Pandas dataframe like this it would be very useful for me to study your code.
csv
orjson
\$\endgroup\$