[1] [2] [3] [4] [5] [6] [7] [8] [9]
[8 pts] What is the output of the following program?
a = '0'
for i in range(4):
a = a + 'i'
print(a)
0i
0ii
0iii
0iiii
[9 pts]
For three string methods other than split
,
give a meaningful example of how to invoke that method
and what that method returns.
For example, for split
, you could write,
“If s
is ‘hello world’ then s.split()
returns the list
[‘hello’, ‘world’].”
If s
is “MacDonald
”, s.count('a')
returns 2 (the number of times a appears in s
).
If s
is “i is {0}
”, s.format(34)
returns “i is 34
”.
If s
is “and
”, s.join(['x', 'y', 'z'])
returns “xandyandz
”.
If s
is “MacDonald
”, s.lower()
returns “macdonald
”.
If s
is “ Old MacDonald
”, s.strip()
returns “Old MacDonald
” (with spaces on both
ends removed).
If s
is “MacDonald
”, s.upper()
returns “MACDONALD
”.
[15 pts] Write a program that reads integers typed by the user until the sum of the numbers typed exceeds 100; the program should then display the sum. For example, if the user enters 30 repeatedly, the program should read four of these 30’s and then display 120.
One solution: | Another solution: |
total = 0 | total = 0 |
[6 pts] Write a regular expression that describes only those strings of a’s and b’s with exactly three a’s. Examples include aaa, ababa, and baabab, but not acaba or aabbaa.
b*ab*ab*ab*
[10 pts]
Tabulate the values taken on by the variables i
, j
,
and k
as the below program executes.
word = 'aha'
k = 0
for i in word:
for j in word:
if i == j:
k = k + 1
print(k)
i : | a | h | a | ||||||||||
j : | a | h | a | a | h | a | a | h | a | ||||
k : | 0 | 1 | 2 | 3 | 4 | 5 |
[8 pts]
What value for template
would result in the following strings
being produced? (Don’t include the quotes.)
template.format(98, 24.5) | → | “98/4 = 24.50 ” |
template.format(7, 1.75) | → | “ 7/4 = 1.75 ” |
{0:2d}/4 = {1:5.2f}
”
[6 pts] When executed, the below program results in the error “name ‘re’ is not defined.” What line must you add to repair this problem, and where should it be inserted into the program?
line = input()
words = re.findall('[a-z]+', line)
print(len(words))
Insert the line “import re
” at the
program’s beginning.
[8 pts]
Complete the while
statement below so that the loop continues
until a
and b
are both odd integers.
(Recall that you can test whether a
is odd by checking whether
a % 2
is 1.)
a = 0
b = 0
while
a = b
b = int(input())
while a % 2 != 1 or b % 2 != 1:
[10 pts]
What belongs in the gap in the below program so that the program
terminates the loop when the user types a number that is within
10 of goal
?
For example, if goal
is 64, the program should terminate
if the user types anything between 54 and 74.
goal = random.randrange(1, 101)
while True:
user = int(input())
print('more than 10 away')
print('close enough')
One solution: | Another solution: |
if abs(user - goal) >= 10: | if user >= goal - 10 and user <= goal + 10: |