pythonoperands

What is the right method to read from input file and perform subtraction?


I am a beginner computational thinking programmer and am doing some basic problems for Australian Informatics Olympiad practice problems.

Here's the link to the question

This is my code so far:

inputfile = open("sitin.txt", "r")
outputfile = open("sitout.txt", "w")

r = 0
s = 0
t = 0
sit = 0
stand = 0
seats_available = 0

#Reading integers from input file

r, s = map(int, inputfile.readline().split())
t = map(int, inputfile.readline().split())

#Conducting the operations

seats_available = r * s

if t > seats_available:
    sit = r*s
    stand = t - seats_available
else: 
    sit = t
    stand = 0


#Writing answer in the output file

outputfile.write(sit + "" + stand + "\n")

outputfile.close()
inputfile.close()

Here's the error I get:

Traceback (most recent call last):
  line 25, in <module>
    if t > seats_available:
TypeError: '>' not supported between instances of 'map' and 'int'

Any help would be much appreciated!


Solution

  • You should use with open structure to open files so you don't have to worry about closing them. Also, initializing the values with 0 is something that you don't have to do so I dropped that too. These few things make your code easier to read and less error prone.

    You are getting the error because on the line for t there is only a single value, so it is not automatically unpacked like r and s.

    # Reading integers from input file
    with open("sitin.txt", "r") as inputfile:
        r, s = map(int, inputfile.readline().split())
        t = int(inputfile.readline().strip())
    
    #Conducting the operations
    
    seats_available = r * s
    
    if t > seats_available:
        sit = r*s
        stand = t - seats_available
    else: 
        sit = t
        stand = 0
    
    #Writing answer in the output file
    
    with open("sitout.txt", "w") as outputfile:
        outputfile.write(f"{sit} {stand}\n")