Q1) Write a Python function partial_print, which takes one parameter, a string, and prints the first, third, fifth (and so on) characters of the strings, with each character both preceded and followed by the ^ symbol, and with a newline appearing after the last ^ symbol. The function returns no value; its goal is to print its output, but not to return it.
Q2)
Write a Python function called lines_of_code that takes a Path object as a parameter, which is expected to be the path to a Python script. It returns how many lines of Python code are contained within the script. Note that not all lines of text are considered to be "lines of code." We'll want to skip a few things, so we aren't counting lines that lack meaning; do not count lines that have these characteristics:
(Note that when I refer to "comments" here, I'm referring only to comments, i.e., the portions of a line that begin with a # character. Some people use string literals as comments — most notably, they use multiline string literals, because Python lacks multiline comments and a string literal "floating" in one's code turns out to be legal, though it's not a comment, because it still gets evaluated at run-time — but these aren't comments, so you would want to count them.)
The function returns an integer that indicates how many lines of code are in the Python script.
If the file cannot be opened successfully, or if the file contains something other than text, the function should raise an exception, though it's not important what kind of exception is raised — any exception will do, and it's fine if you raise different kinds of exceptions in different scenarios. However, the file is required to be closed in any case in which it had been opened.
ANSWER 1
def partial_print(s):
s = '^'+'^'.join([s[i] for i in range(len(s)) if i%2==0])+"^\n"
print (s)
ANSWER 2
import re
from pathlib import Path
def lines_of_code(p):
cnt = 0
try:
f = p.open()
except Exception as e:
print(str(e))
exit(1)
line = f.readline()
while(line != ""):
if "#" == line[0]:
line = f.readline()
continue
if re.search(r"\w",line):
cnt+=1
line = f.readline()
return cnt
Get Answers For Free
Most questions answered within 1 hours.