How to stop iteration

Shashank Singh shashank.sunny.singh at gmail.com
Sun Jun 5 11:31:55 EDT 2011


You can modify your code to stop trying to split the 'remaining part'
when the 'remaining part' is too small

def strsplit(stri, spa):
    if len(stri) <= spa:
        final_result.append(stri)
        return
    s = stri[:spa]
    final_result.append(s)

    stri = stri[spa:]
    strsplit(stri,spa)

Also, note that since in your algorithm, as you move through the
string you are appending the intermediate results to a 'global result
list' you don't need to return anything at any step on the process, so
I have removed the return statement. You can get the result by
checking the 'global result list' when you have gone through the whole
string once.

Python 2.6.1 (r261:67515, Aug  2 2010, 20:10:18)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> string = 'This is a sample python programming'
>>> space = 2
>>> final_result = []
>>> def strsplit(stri, spa):
...     if len(stri) <= spa:
...         final_result.append(stri)
...         return
...     s = stri[:spa]
...     final_result.append(s)
...
...     stri = stri[spa:]
...     strsplit(stri,spa)
...
>>> strsplit(string,space)
>>> final_result
['Th', 'is', ' i', 's ', 'a ', 'sa', 'mp', 'le', ' p', 'yt', 'ho', 'n
', 'pr', 'og', 'ra', 'mm', 'in', 'g']
>>>

Please also note that a simpler way to write this using what is known
as the 'dynamic programming' paradigm. When you take out the first
chunk from your string, if you notice, you are left with the same
problem, it's just that the string in this case have become shorter
(the remaining part of the string, after taking out the current
chunk). You can now call the same function again on the remaining list

Python 2.6.1 (r261:67515, Aug  2 2010, 20:10:18)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> string = 'This is a sample python programming'
>>> space = 2
>>> def strsplit(stri, spa):
...     if len(stri) <= spa:
...         return [stri]
...     return [stri[:spa]] + strsplit(stri[spa:], spa)
...
>>> strsplit(string,space)
['Th', 'is', ' i', 's ', 'a ', 'sa', 'mp', 'le', ' p', 'yt', 'ho', 'n
', 'pr', 'og', 'ra', 'mm', 'in', 'g']
>>>

In this case you are actually using the return values (and not
changing a global variable).

HTH

--
Regards
Shashank Singh
http://www.cse.iitb.ac.in/~shashanksingh



More information about the Python-list mailing list