For each of the following Python programs P and input strings I, give the output P(I), using the formal definition of P(I) given, and employing any reasonable reference computer C:
Definition of P(I), the output of a Python program. Let P be a Python program with respect to a reference computer system C. Suppose P has main function M, and let I be a string of ASCII characters that will be used as input to P. The output of P on input I, written P(I), is produced by using computer C to execute M with input I, then defining P(I) as follows:
• If M returns an ASCII string S, then P(I) = S.
• If M returns a Python object that is not an ASCII string, then P(I) is undefined.
• If M throws an exception on input I, then P(I) is undefined.
• If M doesn’t terminate on input I, then P(I) is undefined.
Problems:
1) P = “def f(x): return str(len(x+x+'x'))”, I = “GAGAT”
2) P = “def f(x): return str(len(x))”, I = P
3) P = “def f(x): return str(1/int(x))”, I = “0”
1) P(I) = '11'.
Explanation:
The input string is being concatenated twice. Once with itself and once with the string 'x'. Hence, the fina string is "GAGATGAGATx" and its length is 11. This is converted to a string and sent to the main function M.
2) P(I) = '28'
Explantion:
The input of the function f(x) is the entire program itself, in te form of a string. Hence, the length of this program is sent to the main function M after being calculated by P. This length is 28.
3) P(i) = udefined
Expanation:
The input of the program is "0". The function f() converts this from string to int and then tries to use this to divide 1. Since division by zero is not possible, the computer raises ZeroDivisionError and hence the output is undefined.
Get Answers For Free
Most questions answered within 1 hours.