Reading a new file starts with a list of what it defines. Build that list.
What to build
A program that lists every function, method and class defined in Python source code.
Requirements
- Look at each line. If, after removing spaces at the start, it starts with
deforclass, it is a definition. - Print
line N: KIND NAME. KIND isclassfor a class,methodfor adefwhose line begins with a space or a tab, andfunctionfor any otherdef. - NAME is the text after the keyword up to the first
(or:. - Finally print
COUNT definition(s).
Input
The first line has n (1 to 200). The next n lines are the code.
Output
One line per definition, then the count line.
Constraints
1 ≤ n ≤ 200, each line at most 100 characters.
Example
Input:
7
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def helper():
Output:
line 1: class Stack
line 2: method __init__
line 5: method push
line 7: function helper
4 definition(s)
Why it works
Indentation is what separates a method from a top-level function, so the program checks the raw line for leading whitespace and only then strips it to read the keyword and name.
Examples
7
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def helper():
line 1: class Stack line 2: method __init__ line 5: method push line 7: function helper 4 definition(s)
2 x = 1 print(x)
0 definition(s)
Prompts inside input() are ignored when checking, so input("n: ") is fine.
Hints
Hint 1
Use line.strip().startswith("def ") and "class " on each line.
Hint 2
A def whose line starts with a space or tab is a method; check line[0].isspace().
Hint 3
The name is the text after the keyword up to the first "(" or ":".
Solution
Show one correct solution (try it yourself first)
n = int(input())
count = 0
for number in range(1, n + 1):
line = input()
text = line.strip()
if text.startswith("def ") or text.startswith("class "):
keyword, _, rest = text.partition(" ")
name = rest.split("(")[0].split(":")[0].strip()
if keyword == "class":
kind = "class"
elif line[0].isspace():
kind = "method"
else:
kind = "function"
count += 1
print(f"line {number}: {kind} {name}")
print(f"{count} definition(s)")
▶ Open this solution in the compiler, then press Visualize to watch it run step by step