0

I have a question about writing a Python program to have the sum of 2 numbers from a txt file. (This question was from the Australian Informatics Olympiad Training Website)

The Input File is: addin.txt and the Output File is: addout.txt

Input: The input file will consist of the two integers a and b separated by a single space. It is guaranteed that 0 <= a, b <= 1,000,000,000.

Output: The output file should consist of a single integer, the sum of a and b.

Sample Input: 23 45 Sample Output: 68

So far, I know how to read and write from txt files but I don't know how it would read the two numbers in the input separately.

Is it possible anyone could show me a program that would fit with this criteria? (Preferable with comments so I can understand it)

Thanks in advance for anyone's help!

  • 2
    what did you try so far ? – Mohamed Ali JAMAOUI Aug 11 '17 at 06:45
  • 1
    Are the Australian Informatics Olympiad about googling and getting others doing things for you? – 6502 Aug 11 '17 at 06:46
  • What exactly is your question? – orangeInk Aug 11 '17 at 06:46
  • Sorry, guys I realized I needed to add a bit more information. So far, I know how to read and write from txt files but I don't know how it would read the two numbers in the input separately. No, this was just a practice question that I couldn't find any help for anywhere else. Is it possible someone could show me a program that would fit with this criteria? (Preferable with comments so I can understand it) – Leo Terray Aug 11 '17 at 06:49
  • place your code in question... so we get idea what have you tried! – DexJ Aug 11 '17 at 06:51

3 Answers3

0
with open('addin.txt', 'r') as inpt:
    number = inpt.readlines()[0].split(' ')  # split the string to get a list of numbers

with open('addout.txt', 'w') as out:
    # convert number in int, sum them and convert back to a string to write it in the output file
    out.write(str(int(number[0])+int(number[1])))  
CLeo-Dev
  • 196
  • 12
0

Here is an easy way to do it using pandas

import pandas as pd
addin_df = pd.read_csv('addin.txt', sep=' ', header=None)
addin_df['sum'] = addin_df[0] + addin_df[1]
addin_df['sum'].to_csv('addout.txt', index=None)
otayeby
  • 312
  • 8
  • 17
0

As you already know how to read from a file, I assume you have a variable vars which contain the input from addin.txt. You just have to split the string and add them together.

>>> elements = vars.split(' ')
>>> sum = int(elements[0]) + int(elements[1])

sum should now store the result.

Related question on how to convert from String to Integer using Python: Parse String to Float or Int

Quick guide on how to split strings in Python: https://www.tutorialspoint.com/python/string_split.htm

GxTruth
  • 509
  • 4
  • 9