Verify 0 or 2+ sub sections in a section

There is a rule in writing: When you break a section into subsections, typically it should have more than one subsection. This goes back to the old high school composition rules: if you have an A. section you also need a B. section.

To check a chapter of a book I’m writing in LaTeX I do this:

$ egrep -h '^\(chapter|(sub)*section)**{' CHAPTERFILE.tex | sed -e 's/*{/{/g'
chapter{My Chapter}
section{Topic}
subsection{Subtopic}
subsection{Another Subtopic}
subsection{Subtopic the Third}
section{More}
subsection{More more}
subsection{Less is more}
section{Odyssey}
subsection{Marge and Homer}
subsubsection{Bart}
subsubsection{Lisa}
subsubsection{Maggie}
subsection{Example}
section{Lore}
section{Data}

What is an efficient algorithm to verify the rule has been obeyed? This rule goes for sub sections in a section, subsub sections in a subsection, and so on. (Though in my case there are no subsubsub sections)

Thanks to Bart’s advice, here is the code I created. It is hacky in places but it is simple and found bugs in my LaTeX files:

#!/usr/bin/env python

import sys
import fileinput

TOKENS = [
    ['chapter', 0],
    ['section', 1],
    ['subsection', 2],
    ['subsubsection', 3],
    ['subsubsubsection', 4],
    ]

def getlevel(line):
  """Report the line's level (number of subsections)."""
  for token, level in TOKENS:
    if line.startswith(token):
      return level
  raise Exception()

def store(lst, level, value):
  """Store value in the level'th position."""
  while len(lst) < level:
    lst.append('EMPTY')
  return lst[:level] + [value]

def segments():
  """Read the input text, yield lists of segments."""
  path = []
  last_level = 0
  for line in fileinput.input():
    value = line[line.index('{') + 1 : line.index('}')]
    path = store(path, getlevel(line), value)
    yield path

def get_tree(segs):
  """Build a tree out of segment lists returned by generator segs"""
  tree = {}
  for s in segs():
    t = tree
    for i in s:
      t = t.setdefault(i, {})
  return tree

def audit(t):
  """Audit: Leafs are ok, nodes are ok if they have >1 children."""
  error = False
  for k, v in t.items():
    if audit(v):
      error = True
    if len(v) == 1:
      print 'ERROR: part with only one subpart: %s' % (k, )
      error = True
  return error

def main():
  tree = get_tree(segments)
  if audit(tree):
    return 1

if __name__ == '__main__':
  sys.exit(main())

What you describe is a tree structure where each non-leaf node has at least two children. As leaf nodes don’t have any children (by definition), once you have built your tree, go over all the nodes and verify that none of them have only a single child.

To build your tree, you can use the structure of the LaTeX sectioning commands by counting the number of occurrences of sub in the sectioning command to determine on which level in the tree it belongs.

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật