CMU Coding Bootcamp
at main 1.1 kB view raw
1def stripComments(code: str) -> str: 2 """Remove comments from a Python code string.""" 3 lines = code.split("\n") 4 lines = [line.split("#")[0].rstrip() for line in lines] 5 lines = [line for line in lines if line] 6 lines = [f"{line}\n" for line in lines] 7 return "".join(lines) 8 9 10print("Testing stripComments()...", end="") 11code = """\ 12# here's a comment! 13def foo(x): 14 return x + 1 # here's another one 15""" 16result = """\ 17def foo(x): 18 return x + 1 19""" 20assert stripComments(code) == result 21 22code = """\ 23def g(x): 24# Here are some comments 25# which must be removed 26# by stripComments 27 return x * 7 28""" 29result = """\ 30def g(x): 31 return x * 7 32""" 33assert stripComments(code) == result 34 35code = """\ 36def doIHaveAnyComments(): 37 return 'No' 38""" 39result = """\ 40def doIHaveAnyComments(): 41 return 'No' 42""" 43assert stripComments(code) == result 44 45code = """\ 46def f(x): 47#This function returns x + 5 48 return x + 5 49""" 50result = """\ 51def f(x): 52 return x + 5 53""" 54assert stripComments(code) == result 55 56assert stripComments("") == "" 57print("Passed!")