Patryk Moskal
Patryk Moskal

Reputation: 69

Why is the count off by one?

I'm currently working on some exams in Python and I have a question.
For example, we have 1000 lines of some words. In each line, there are 2 words separated by a space button (ASCII code 32). And I have to write code in Python to check if the first word exists in the second one (in the same line), for example, adc exists in addadc but not in addadfc, and I need to count all lines that are good. The result is 235, but it is too high, as the correct answer is 234. I don't know why this is happening.

Code:

liczba_wierszy = 0 #amount of lines

for i in range(1000):
    linia = input() # line
    index_spacji = 0 # space index
    index_konca = 0 #index of the word
    pierwszy_napis = "" # first word
    drugi_napis = ""  # second word
    for j in linia:
        if ord(j)!= 32:
            index_spacji+=1
        else:
            break;
    pierwszy_napis =(linia[0:index_spacji-1])
    drugi_napis = (linia[index_spacji+1:len(linia)])
    if pierwszy_napis in drugi_napis:
        liczba_wierszy+=1

print(liczba_wierszy)

It's written in Polish so I'll translate it a little bit.

Upvotes: 1

Views: 258

Answers (2)

ack_inc
ack_inc

Reputation: 1113

The error seems to be in this line:

pierwszy_napis =(linia[0:index_spacji-1])

It's putting one less character in pierwszy_napis than it should. Because MyString[a:b] gives you the substring from index a to index b - 1.

Try

pierwszy_napis =(linia[0:index_spacji])

instead

Upvotes: 0

Omkar Sabade
Omkar Sabade

Reputation: 783

Can I give you a simple alternative?

count = 0
for i in range(1000):
    line = input().strip()
    word1,word2 = line.split(' ')
    if word1 in word2:
        count += 1
print(count)

Also I see that you have initialised strings for word1 and word2 as "" and later reassigned values to them. You might want to note that Python strings are immutable and reassigning to them later will create a new object anyway. So if you are going with your code skip the initialization part.

Upvotes: 1

Related Questions