I need to create a fibonacci sequence (k = 5, until 5 elements are in the sequence) from an original string containing two starting values. While calling the last two elements in the string forward (newnumber= old[-1] + old[-2]) I pull the number "5" and what seems to be a "black space". Is there a way to lift the integers in the original sequence above the type of black spaces to make it easier to manipulate the useful data I need?
Below is my code for reference.
ORIGINAL STRING IN FIRST FILE:
31 5
with open("C:\\Users\\dylan\\Downloads\\rosalind_fib.txt", "r") as old:
old = old.read()
## An attempt to make the numbers the only elemenet, this did not work --> old = list(old)
new = open("C:\\Users\\dylan\\Downloads\\new.txt", "w")
## to test the values for each index --> print(old[###])
while len(old) < 6:
newnumber= old[-1] + old[-2]
old += newnumber
if len(old) == 6:
break
new.write(old)
new.close()
print(new)
The desired output is:
31 5 36 41 77
A sequence of 5 numbers where the sum of the last two numbers in the sequence is the new number added to the end of sequence.
Use
split()to split the string on whitespace. When you write it back out you can usejoin()to turn the list of numbers back into a string.Result:
Breaking down how we read the file a bit: the first thing we do is
read()the file, giving us a string:We want to
stripthe contents to get rid of the trailing whitespace (otherwise when wesplitlater we'll have an empty string at the end):and then we
split()that to produce a list:and we can iterate over that in a list comprehension to get a list of ints: