《计算机科学导论》学习笔记(20) - 课程 20 习题集 (可选)

1. 练习:移动一个字符

题目:

# Write a procedure, shift, which takes as its input a lowercase letter,
# a-z and returns the next letter in the alphabet after it, with 'a' 
# following 'z'.

def shift(letter):



print shift('a')
#>>> b
print shift('n')
#>>> o
print shift('z')
#>>> a

我的答案:

def shift(letter):
    return chr(ord(letter) + 1) if letter < 'z' else 'a'

更为完整的我的答案:

def shift(letter):
    # return chr(ord(letter) + 1) if letter < 'z' else 'a'
    if 'a' <= letter < 'z':
        return chr(ord(letter) + 1)
    elif letter == 'z':
        return 'a'

2. 练习:移动 n 个字符

题目:

# Write a procedure, shift_n_letters which takes as its input a lowercase
# letter, a-z, and an integer n, and returns the letter n steps in the
# alphabet after it. Note that 'a' follows 'z', and that n can be positive,
#negative or zero.

def shift_n_letters(letter, n):



print shift_n_letters('s', 1)
#>>> t
print shift_n_letters('s', 2)
#>>> u
print shift_n_letters('s', 10)
#>>> c
print shift_n_letters('s', -10)
#>>> i

我的答案:

def shift_n_letters(letter, n):
    '''
    if ord(letter) + n > ord('z'):
        return chr(ord(letter) + n - 26)
    elif ord('a') <= ord(letter) + n <= ord('z'):
        return chr(ord(letter) + n)
    elif ord(letter) + n < ord('a'):
        return chr(ord(letter) + n + 26)
    '''
    t = ord(letter) + n
    if      t > ord('z'):   t -= 26
    elif    t < ord('a'):   t += 26
    return chr(t)

3. 练习:旋转

题目:

# Write a procedure, rotate which takes as its input a string of lower case
# letters, a-z, and spaces, and an integer n, and returns the string constructed
# by shifting each of the letters n steps, and leaving the spaces unchanged.
# Note that 'a' follows 'z'. You can use an additional procedure if you
# choose to as long as rotate returns the correct string.
# Note that n can be positive, negative or zero.

def rotate():
    # Your code here

print rotate ('sarah', 13)
#>>> 'fnenu'
print rotate('fnenu',13)
#>>> 'sarah'
print rotate('dave',5)
#>>>'ifaj'
print rotate('ifaj',-5)
#>>>'dave'
print rotate(("zw pfli tfuv nfibj tfiivtkcp pfl jyflcu "
                "sv rscv kf ivru kyzj"),-17)
#>>> ???

我的答案:

def rotate(astring, steps):
    # Your code here
    s = ''
    for char in astring:
        if char != ' ':
            temp = ord(char) + steps
            if ord('z') < temp:     s += chr(temp - 26)
            elif temp < ord('a'):   s += chr(temp + 26)
            else:                   s += chr(temp)
        else:
            s += char
    return s

猜你喜欢

转载自blog.csdn.net/qq_33528613/article/details/80595403