The code calculates a n-bonnaci sequence to a certain number, based on the user's input. It then can print it to a file and/or print it to the console.
The calculateSequence
function calculates the sequence. The first loop fills the sequence with ones (0, 1, 1, 2...). Next, it calculates the value of the current number, using crrntVlue
as a placeholder, and using i
as the location of the value to add (a number is the sum of the preceding two numbers). sqnceItratr
is location of the number that is being calculated.
My questions are:
- Is there anything immediately wrong that you see in the code?
- How can I make the code more readable/better variable names, as it was hard to understand the code while coding it?
- How can I restructure the program to make it better?
This is one of my first Python programs, so I want to know what I might be coding 'wrong'.
def calculateSequence(n, amntToCalc):
sqnceItratr = 1
sequence = [0] * numbrsToCalc
#Add 1's to the array(Duonacci is 1, 1, 2... Tribonacci is 1, 1, 1, 3...)
while sqnceItratr < n:
sequence[sqnceItratr] = 1
sqnceItratr += 1
#Actually Calculate the Sequence
while sqnceItratr < numbrsToCalc:
i = N
#i is the location of the amount to add to crrntVlue
#Ex: sequence[3] = 1 + 1 + 1 = 3, i is sequence[3 - 1]
crrntVlue = 0
while i > 0:
#This is to calculate the actual value of a number
#in the sequence
crrntVlue += sequence[sqnceItratr - i]
i -= 1
#Count Down for the number to add to crrntValue(n-bonnacci)
sequence[sqnceItratr] = crrntVlue
# Add crrntValue to the array
sqnceItratr += 1
#Continue to the next value in the array
return sequence
def convertInput(inputToConvert):
inputToConvert = inputToConvert.upper()
if inputToConvert == 'Y':
return True
elif inputToConvert == 'YES':
return True
else:
return False
N = int(input("What do you want to n in N-bonnacci to be? \n"))
numbrsToCalc = int(input("How many digits do you want to calculate? \n This should probably be bigger than n \n"))
sequence = calculateSequence(N, numbrsToCalc)
userInput1 = convertInput(input("Do you want to write it to a file? \n"))
sequencePosition = 0
if userInput1 == True:
file = open("Seqence.txt", "w")
while sequencePosition < len(sequence):
file.write(str(sequencePosition + 1) + ': ' + str(sequence[sequencePosition]) + '\n')
sequencePosition += 1
file.close()
userInput2 = convertInput(input("Do you want to print it out? \n"))
if userInput2 == True:
sequencePosition = 0
while sequencePosition < len(sequence):
print(str(sequencePosition + 1) + ': ' + str(sequence[sequencePosition]))
sequencePosition += 1