Dylan Ellis
Dylan Ellis

Reputation: 1

With Python, I want to add the last two values of a string but I want to keep double digit numbers together and not include spaces in the string index

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.

Upvotes: 0

Views: 62

Answers (1)

Samwise
Samwise

Reputation: 71574

Use split() to split the string on whitespace. When you write it back out you can use join() to turn the list of numbers back into a string.

with open('old.txt') as f:
    nums = [int(n) for n in f.read().strip().split()]

while len(nums) < 5:
    nums.append(nums[-2] + nums[-1])

with open('new.txt', 'w') as f:
    f.write(' '.join(str(n) for n in nums))

Result:

>echo 31 5 > old.txt

>cat old.txt
31 5

>python test.py

>cat new.txt
31 5 36 41 77

Breaking down how we read the file a bit: the first thing we do is read() the file, giving us a string:

>>> with open ("old.txt") as f:
...     contents = f.read()
...
>>> contents
'31 5 \n'

We want to strip the contents to get rid of the trailing whitespace (otherwise when we split later we'll have an empty string at the end):

>>> contents.strip()
'31 5'

and then we split() that to produce a list:

>>> contents.strip().split()
['31', '5']

and we can iterate over that in a list comprehension to get a list of ints:

>>> [int(n) for n in contents.strip().split()]
[31, 5]

Upvotes: 0

Related Questions