Test 02 Flashcards
What does this expressions yield?
list(range(0,9,2)[:])
[0, 2, 4, 6, 8]
What does this expressions yield?
list(range(-2,20,5)[1:4])
[3, 8, 13]
What does this expressions yield?
list(range(3,18,2)[::2])
[3, 7, 11, 15]
Write a control sequence that …
sorts a list of three numbers.
lst = [?, ?, ?]
a = lst [0]
b = lst [1]
c = lst [2]
# correct position of a
if a > b or a > c:
if a > b and a > c: lst [2] = a
else :
lst [1] = a
# correct position of b
if b < a and b < c:
lst [0] = b
elif :
if b > a and b > c:
lst [2] = b
# correct position of c
if c < a or c < b:
if c < a and c < b:
lst [0] = c
else :
lst [1] = c
Write a control sequence that …
sets type to ‘equilateral’, ‘isosceles’, or ‘scalene’, given the lengths of the three sides of a triangle, x, y, and z.
x = ?
y = ?
z = ?
type = None
if x == y and y == z:
type = ‘equilateral’
elif x==y or y==z or x==z:
type
Write a loop with the following behaviours:
determines whether a given list of numbers is in ascending order.
lst = ??
in_order = True
for i in range ( len ( lst ) -1):
if lst [i] > lst [i +1]:
in_order = False
Write a loop with the following behaviours:
Finds the greatest common divisor of two given numbers
big_num = ??
small_num = ??
while small_num != 0:
remainder = big_num % small_num
big_num = small_num
small_num = remainder
Write a loop with the following behaviours:
Finds the sum of all numbers in a given string.
Assume numbers are positive integers.
For example, ‘4 and 20 blackbirds’ sums to 24.
string = ??
numbers = [‘0’,’1’,’2’,’3’,’4’,’5’,’6’,’7’,’8’,’9’]
i = 0
sum = 0
while i < len ( string ):
if string [i] in numbers :
j = i
&n
Write a loop with the following behaviours:
Finds the mean of a list of numbers.
sum = 0
for num in lst :
sum = sum + num
mean = sum / len(lst)
Write a loop with the following behaviours:
Determines whether a given string is a palindrome.
Do not use string slicing or the function reversed().
string = ??
palindrome = True
for i in range ( len ( string )//2):
if string[i] != string[-(i +1)]:
palindrome = False
Write a loop with the following behaviours:
Generates the complement of a given binary number.
For example, the complement of ‘110101’ is ‘001010’.
binary = ??
complement = ‘’
for digit in binary :
if digit == ‘0’:
complement = complement + ‘1’
else :
&
Write a recursive function digit_sum that sums the digits of an integer number, without converting the number to string.
For example:
>>> digit_sum(523)
10
def digit\_sum ( number ): if number == 0: return 0 return number %10 + digit\_sum ( number //10)
Write a recursive function which returns the value of the Fibonacci series for the nth element.
For example:
>>> fib (6)
8
>>> fib (10)
def fib(n): if n == 0: return 0 elif n == 1: return 1 return f