PCEP-30-02 practice question 26 of 35

What is the expected output of the following code? def func(data): for d in data[::2]: yield d for x in func('abcdef'): print(x, end='')

Full set: 548 questions

Domain Functions and Exceptions

Answer options
A: bdf
B: An empty line.
C: abcdef
D: ace Correct answer
Correct Answer:
D. ace
Explanation

The code defines a generator function func that takes an iterable data. Inside the function, a for loop iterates over a slice of data. The slice data[::2] selects elements starting from the beginning to the end with a step of two. For the input string 'abcdef', this slice evaluates to 'ace'. The yield keyword makes func a generator, which produces items one by one. The main for loop iterates through the generator object created by func('abcdef'), printing each yielded character ('a', 'c', 'e') without a newline due to end=''. The final concatenated output is ace.

Why Incorrect

A. bdf This would be the output if the slice was data[1::2], which selects elements starting from the second character (index 1).
B. An empty line. This would occur if the generator yielded no values, but the slice data[::2] is not empty for the given input.
C. abcdef This would be the output if the code iterated over the entire string data without any slicing.

References

1. Python Software Foundation. (2023). The Python Tutorial, Section 3.1.2. Strings. The documentation explains sequence slicing: "s[i:j:k] the slice of s from i to j with step k". The expression [::2] is a specific case of this. Retrieved from https://docs.python.org/3/tutorial/introduction.html#strings

2. Python Software Foundation. (2023). The Python Tutorial, Section 9.9. Generators. This section details how a function containing a yield statement becomes a generator, producing a sequence of values for iteration. Retrieved from https://docs.python.org/3/tutorial/classes.html#generators

3. Guttag, J. V. (2016). Introduction to Computation and Programming Using Python, With Application to Understanding Data (2nd ed.). MIT Press. Chapter 5, Section 5.4, "Functions as Objects," discusses generators and the yield statement, explaining how they produce a sequence of results over time.

4. MIT OpenCourseWare. (2016). 6.0001 Introduction to Computer Science and Programming in Python, Lecture 9: Classes and Object-Oriented Programming. The lecture notes cover generators, explaining that yield returns a value and pauses execution, resuming on the next iteration. Retrieved from https://ocw.mit.edu/courses/6-0001-introduction-to-computer-science-and-programming-in-python-fall-2016/

Scroll to Top