Prathmesh
Prathmesh

Reputation: 23

Code too slow USACO Bronze 2015 Problem 1 python

I am practicing for USACO and I came across the "Censoring" Problem: http://www.usaco.org/index.php?page=viewproblem2&cpid=526

I solved it pretty quickly and though I got it right. However, it turns out that my the server gives me a time error for test cases 7-15 (it works well for the first 6 test cases).

Here is my code.

import sys
sys.stdin = open('censor.in', 'r')
sys.stdout = open('censor.out', 'w')

# Real code begins here
original_string = input()
censor_string = input()
# print(original_string.find(censor_string) + len(censor_string))
while censor_string in original_string:
    original_string = original_string[0:original_string.find(censor_string)] + original_string[original_string.find(censor_string) +
                      len(censor_string): len(original_string)]
print(original_string)

Can someone help me fix it? The problem is probably that while loop. Not sure how to fix it though.

Upvotes: 1

Views: 304

Answers (1)

superb rain
superb rain

Reputation: 5531

This is fast enough to get accepted. I build the result string one character at a time. Whenever this creates the bad string (at the end of the partial result), I remove it.

import sys
sys.stdin = open('censor.in')
sys.stdout = open('censor.out', 'w')

s, t = input(), input()

res = ''
for c in s:
    res += c
    if res.endswith(t):
        res = res[:-len(t)]

print(res)

Upvotes: 2

Related Questions