CSci 150: Foundations of computer science I
Home Syllabus Assignments Tests

Exam 2: Questions

X2.1.

[6 pts] Tabulate the values taken on by i, j, and k as the program fragment below executes.

j = 1
k = 1
for i in range(4):
    k = k + i * j
    j = i
X2.2.

[6 pts] Convert the below to an equivalent if statement where not doesn't appear.

if not (a == b and b >= c):
X2.3.

[8 pts] What is displayed when the below program is executed?

def run():
    a = 1
    y = 2
    b = process(a)
    c = process(b)
    print a, b, c
    print y

def process(x):
    y = x + 1
    x = x * 2
    print y
    return x

run()
X2.4.

[10 pts] Complete the below function so that it returns the smallest positive number in its parameter list. For example, min_positives([52, -13]) should return 2. You can assume the list has at least one positive number, which will be less than 999.

def min_positives(nums):
X2.5.

[8 pts] Give a derivation or syntax tree for b a b b using the below context-free grammar.

S A a | b A
A a S | A b | a
X2.6.

[8 pts] Write a context-free grammar describing the language containing all strings of a's and b's in which every a has a b just after it. Examples include abbab, bbabb, and bbbb, but not bbba or abbaab.

X2.7.

[10 pts] The file words.txt is a file containing several lines with one English word on each line. Complete the below Python fragment so that it displays all six-letter words beginning with q.

dictionary = open('words.txt')
X2.8.

[8 pts] What is displayed when the below program is executed?

nums = [79678]
map = {}
for i in range(5):
    n = nums[i]
    map[n] = i
for key in map:
    print key, 'to', map[key]
X2.9.

[8 pts] In the context of networking, why do messages typically include port numbers rather than simply the computers' IP addresses?

X2.10.

[8 pts] Suppose you tell your Web browser to retrieve the page http://ozark.hendrix.edu/~burch/cs/150/. Using HTTP, what message might the Web browser send to ozark.hendrix.edu to retrieve the requested Web page?

Exam 2: Solutions

X2.1.
i:0,1,2,3
j:1,0,1,2,3
k:1,1,1,3,9
X2.2.
if a != b or b < c:
X2.3.
2
3
1 2 4
X2.4.
def min_positives(nums):
    min = 1000
    for n in nums:
        if n > 0 and n < min:
            min = n
    return min
X2.5.
Sb A
b A b
b A b b
b a b b
X2.6.
S → a b S | b S | λ
X2.7.
for line in dictionary:
    word = line.rstrip()
    if len(word) == 6 and word[0] == 'q':
        print word
X2.8.
7 to 3
9 to 1
8 to 4
6 to 2
X2.9.

A port number, allocated uniquely on the computer for each program running, allows a sender to identify the particular program on the destination computer that should receive the message.

X2.10.

Following is a minimal example of the text the browser might send to the Web server:

GET /~burch/cs/150 HTTP/1.1
Host: ozark.hendrix.edu
      [an empty line signals the end of the request]