FOR PYTHON: Write a function printNth () that takes a list lst and a positive (>
ID: 640904 • Letter: F
Question
FOR PYTHON: Write a function printNth() that takes a list lst and a positive (>= 0) integer n as parameters. It prints every nth item in lst, one per line, beginning with the first item in the list. For example, if n is 2, the function will print every other item in the list, beginning with the first item. The function must work regardless of the type of items that are in the list. If the parameter n is zero or negative the function should not print anything. The function should not modify the list provided as a parameter. The following shows several sample runs of the function:
Python 3.4.1 Shell File Edit Shell Debug Options indows Help >>> printNth( [, 3) >>> printNth(l dog','cat, 'ferret, 'hamster', 2) dog ferret >>> printNth(l dog','cat, 'ferret, 'hamster', 5) dog >>> printNth(l dog','cat, 'ferret', 'hamster',5) >>> printNth(l1, 2, 3, 4, 5, 6], 2) >>> printNth(l1, 2, 3, 4, 5, 6], 3) >>> printNth(l1, 2, 3, 4, 5, 6], 4) 2 Ln: 38 Col: 4Explanation / Answer
def printNth(lst, n):
if n > 0 and len(lst) > 0:
flag = 0
for i in range(len(lst)):
if i % n == 0:
print(lst[i])
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.