jiten
jiten

Reputation: 193

Unable to get solution correct for submission

It is a sample problem for practice (here), and is not getting accepted due to it giving 'wrong answer'. It is compiling fine, but might be for different test inputs failing on submission.
I just request comment for the same, as hope that the issue must be small.

The problem statement is:
The program should accept first line of input as no. of strings, s.t. it is less than 10. And the next lines should contain one string each of length less than 100 characters. Need find occurrence of "gfg" in the strings. If no occurrence is found, -1 should be returned.

#code
t = int(input())
if t > 10 or t<0:
    exit()
arr = [[0] for i in range(t)]
total = [[-1] for i in range(t)] 


for i in range(t):
    arr[i] = [k for k in input().split()[:1]]  
    for j in arr[i]:
        total[i] = j.count("gfg")
        if total[i]==0: total[i]=-1
        print (total[i]) 

Upvotes: 0

Views: 1266

Answers (2)

ncica
ncica

Reputation: 7206

t = int(input())
if t not in range(10):
    exit()
else:
    pass

total = []
for i in range(t):
    line = input()[:100]
    if line.count("gfg") == 0:
        total.append(-1)
    else:
        total.append(line.count("gfg"))

print('\n'.join(map(str, total)))

enter image description here

SOLUTION FOR YOUR TASK:

  t = int(input())
  total = []

  for i in range(1, t + 1):
      line = input()
      if len(line)<=100:

           count = 0
           for i in range(0, len(line) - 3 + 1):
               if line[i:i + 3] == "gfg":
                   count += 1
           if count != 0:
               total.append(count)
           else:
               total.append(-1)

  for i in total:
      print (i)

NOTE: your submitting was failing because of special cases

For example: in string gfgfg, your substring "gfg" occurres 2 times, and in that case you can't use the string count() method

how you can see ,here line[i:i + 3] I am moving index by index and checking next 3 values (because your substing "gfg" have length 3)

Upvotes: 2

T. Gwen
T. Gwen

Reputation: 104

You are erasing the value of total[i] each time you iterate in the last loop :

>>> for j in arr[i]:
>>>    total[i] = j.count("gfg")
>>>    if total[i]==0:
>>>       total[i]=-1
>>>    print (total[i]) 

Do you want to count the occurences in each word or in the whole sentence ? Because then you just have to write :

>>> for i in range(t):
>>>    n_occ = input().count("gfg")
>>>    if n_occ != 0:
>>>       total[i] = n_occ

If there's no occurence you don't have to do anything because the value in total is -1 already. Also, write:

>>> total = [-1]*t

not:

>>> total = [[-1] for i in range(t)] 

Upvotes: 0

Related Questions