-1

I am trying to write a code in python which is written in C++, while converting the loops of C++ to python I am facing diffculities.

for(int len = 1; len < n; len++){
            for(int i = 0; i + len < n; i++){
                   // bla bla bla code
               }
            }

How can i write the inner for loop in python ?? Any generalized approach which can work in every scenario ?? If the Question is duplicate one sorry for this I couldn't know what and how to search in google about this.

Can I please get some help in this problem from you. Thanks In Advance.

Uday Kiran
  • 229
  • 2
  • 13
  • 1
    If `s` is of length `3`, in the first iteration `x` is `0`, so what is `3 - 0`, and what is the last valid *index* of `s`…? – deceze Aug 07 '19 at 09:41
  • Also note that according to your logic, `((` would be a "balanced" string. Also note that you're `return`ing in every loop iteration, meaning only the very first iteration is ever going to complete and the function will end after that. – deceze Aug 07 '19 at 09:45

1 Answers1

0

Here: for x in range(len(s)) x goes though all integers in range [0, len(s)), so its first value will be zero. Here: s[len(s)-x] when x == 0, the index will equal len(s), which is invalid, because the greatest valid index for a string of length len(s)>0 is len(s)-1.

How to fix: that's an off-by-one error, and you probably meant s[len(s)-x-1].

ForceBru
  • 43,482
  • 10
  • 63
  • 98