-2

I am writing a program. if short matches are mixed with longer matches. the program is to see which matches will fit back in the short box. This is my code:

import math
def q2():

    fin = open('input.txt','rt')
    fout = open('output.txt', 'wt')
    a= int(fin.readline().strip())
    b = [int(b) for b in str(a)]
    count = -1
    nMatches = b[0]
    width = b[1]
    heigth = b[2]
    length = width**2 + heigth**2
    length = length**(.5)
    while count <= nMatches:
        match = int(fin.readline().strip())
        count = count+ 1
        if match <= length:
            print('YES')
        else:
            print('NO')

This is the output:

YES
YES
YES
NO
NO
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    q2()
  File "D:/code/Q2/q2.py", line 15, in q2
    match = int(fin.readline().strip())
ValueError: invalid literal for int() with base 10: ''

Thanks for any help the content of fin is: 534 3 4 5 6 7

3 Answers3

0

It looks like you want to convert an empty string to an int. But that's not possible. Look at your exception: ... base 10: '' <-- this is an empty string.

So you read a line, you strip it and then just an empty string is left. And that raises the ValueError

Here a stackoverflow answer (1 oder 2 result on google): ValueError: invalid literal for int() with base 10: ''

Community
  • 1
  • 1
ProgrammingIsAwsome
  • 1,109
  • 7
  • 15
0

The problem is your loop count. Instead of using while count < nMatches why not just for i in range(nMatches)? Because your loop count is off, you're reading past the end of the file, which gives an error when you try to convert the empty string.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
0

I am making a lot of assumptions here because I don't know what is in the fin file. This is what I think you are trying to do: nMatches = 534 is the number of matches in the box. width = 3 and height = 4 and somehow the that causes the length of the box to be 5

I am assuming that all the numbers after the first 3 in the fin file are the length of each match.

    from math import sqrt
    def q2():

    fin = open('text.txt','r')
    fout = open('output.txt', 'w')
    a = fin.readline().strip().split()
    b = [int(x) for x in a]
    nMatches = b[0]
    width = b[1]
    height = b[2]
    length = sqrt(width**2 + height**2)

    for match in b[3:]:

        if match <= length:
            print ('YES')
        else:
            print ('NO')

    q2()

This compares each number in the file to the length of the box.

Loupi
  • 550
  • 6
  • 14