Solution to Indented List Problem
This post originally appeared on the Software Carpentry website.
Last week's homework was to convert a two-level bullet-point list like this:
* A * B * 1 * 2 * C * 3
into an HTML list like this:
<ul> <li>A</li> <li>B <ul> <li>1</li> <li>2</li> </ul> </li> <li>C <ul> <li>3</li> </ul> </li> </ul>
so it would display like this:
- A
- B
- 1
- 2
- C
- 3
My solution is shown in the video below; the code follows.
{% assign video_title="Converting an Indented List to HTML" %} {% assign video_slug="upJJjF91TbE" %} {% assign video_time="00:16:13" %} {% include youtube %}import sys def do_inner(lines, current): need_to_start = True need_to_close = False while (current < len(lines)) and \ lines[current].startswith(' * '): if need_to_start: print ' <ul>' need_to_start = False text = lines[current].lstrip(' * ').rstrip() print ' <li>' + text + '</li>' need_to_close = True current += 1 if need_to_close: print ' </ul>' return current def do_outer(lines): print '<ul>' current = 0 while current < len(lines): assert lines[current].startswith('* ') text = lines[current].lstrip('* ').rstrip() print '<li>' + text current = do_inner(lines, current+1) print '</li>' print '</ul>' lines = sys.stdin.readlines() do_outer(lines)