首页 » 技术分享 » 《计算机科学导论》学习笔记(27) - 课程 27: 累积实践问题

《计算机科学导论》学习笔记(27) - 课程 27: 累积实践问题

 

1. 练习:选一个

题目:

# Question 1: Pick One

# Define a procedure, pick_one, that takes three inputs: a Boolean 
# and two other values. If the first input is True, it should return 
# the second input. If the first input is False, it should return the 
# third input.

# For example, pick_one(True, 37, 'hello') should return 37, and
# pick_one(False, 37, 'hello') should return 'hello'.

def pick_one():



print pick_one(True, 37, 'hello')
#>>> 37

print pick_one(False, 37, 'hello')
#>>> hello

print pick_one(True, 'red pill', 'blue pill')
#>>> red pill

print pick_one(False, 'sunny', 'rainy')
#>>> rainy

我的答案:

def pick_one(Boolean, first, second):
    return first if Boolean else second

视频的答案:

def pick_one(boolean, true_response, false_response):
    if boolean:
        return true_response
    else:
        return false_response

2. 练习:三角数字

题目:

# Question 2. Triangular Numbers

# The triangular numbers are the numbers 1, 3, 6, 10, 15, 21, ...
# They are calculated as follows.

# 1
# 1 + 2 = 3
# 1 + 2 + 3 = 6
# 1 + 2 + 3 + 4 = 10
# 1 + 2 + 3 + 4 + 5 = 15

# Write a procedure, triangular, that takes as its input a positive 
# integer n and returns the nth triangular number.

def triangular():



print triangular(1)
#>>>1

print triangular(3)
#>>> 6

print triangular(10)
#>>> 55

我的答案:

def triangular(n):
    #if n == 1:  return 1
    """
    i = 0
    sum = 0
    while i <= n:
        sum += i
        i += 1
    """
    sum = 0
    for i in range(1, n+1):
        sum += i
    return sum

3. 练习:线性时间

4. 练习:删除标签

题目:

# Question 4: Remove Tags

# When we add our words to the index, we don't really want to include
# html tags such as <body>, <head>, <table>, <a href="..."> and so on.

# Write a procedure, remove_tags, that takes as input a string and returns
# a list of words, in order, with the tags removed. Tags are defined to be
# strings surrounded by < >. Words are separated by whitespace or tags. 
# You may assume the input does not include any unclosed tags, that is,  
# there will be no '<' without a following '>'.

def remove_tags():


print remove_tags('''<h1>Title</h1><p>This is a
                    <a href="http://www.udacity.com">link</a>.<p>''')
#>>> ['Title','This','is','a','link','.']

print remove_tags('''<table cellpadding='3'>
                     <tr><td>Hello</td><td>World!</td></tr>
                     </table>''')
#>>> ['Hello','World!']

print remove_tags("<hello><goodbye>")
#>>> []

print remove_tags("This is plain text.")
#>>> ['This', 'is', 'plain', 'text.']

我的答案:

def remove_tags(text):
    result = []
    if text.find('<') == -1 and \
    text.find('>') == -1:
        result.append(text)
    return result
    '''
    for index in range(len(text)):
        at_kai = False
        at_bi = False
        at_space = False
        result = []
        if text[index] == ' ':
            at_space = True
        if text[index] == '<':
            at_kai = True
            continue
        if text[index] == '>':
            at_bi = True
            at_kai = False
        if at_bi == True:
            text = text[index + 1:]
            result[index] = result[index] + char
        '''

(我的答案很稀烂,没有完成。我想起来了之前的视频看过的代码,只能谈下我的思路:
1. 去掉 <> 之间的文本;
2. 在某些情况下, append 单个字符;【result.append(char)】
3. 在某些情况下,连接单个字符。【result[index] = result[index] + char】
)

视频的答案:

def remove_tags(string):
    start = string.find('<')
    while start != -1:
        end = string.find('>', start)
        string = string[:start] + " " + string[end + 1:]
        start = string.find('<')
    return string.split()

5. 练习:日期转换器

题目:

# Question 5: Date Converter

# Write a procedure date_converter which takes two inputs. The first is 
# a dictionary and the second a string. The string is a valid date in 
# the format month/day/year. The procedure should return
# the date written in the form <day> <name of month> <year>.
# For example , if the
# dictionary is in English,

english = {1:"January", 2:"February", 3:"March", 4:"April", 5:"May", 
6:"June", 7:"July", 8:"August", 9:"September",10:"October", 
11:"November", 12:"December"}

# then  "5/11/2012" should be converted to "11 May 2012". 
# If the dictionary is in Swedish

swedish = {1:"januari", 2:"februari", 3:"mars", 4:"april", 5:"maj", 
6:"juni", 7:"juli", 8:"augusti", 9:"september",10:"oktober", 
11:"november", 12:"december"}

# then "5/11/2012" should be converted to "11 maj 2012".

# Hint: int('12') converts the string '12' to the integer 12.

def date_converter():


print date_converter(english, '5/11/2012')
#>>> 11 May 2012

print date_converter(english, '5/11/12')
#>>> 11 May 12

print date_converter(swedish, '5/11/2012')
#>>> 11 maj 2012

print date_converter(swedish, '12/5/1791')
#>>> 5 december 1791

我的答案:

def date_converter(language, date):
    first_xie = date.find('/')
    second_xie = date.find('/', first_xie + 1)
    return date[first_xie + 1:second_xie] + ' ' + \
    language[int(date[:first_xie])] + ' ' + \
    date[second_xie + 1:]

视频的答案:

def date_converter(language, date):
    first = date.find('/')
    month = date[:first]
    second = date.find('/', first+1)
    day = date[first + : second]year = date[second + 1 :]
    year = date[second + 1:]
    return day + " " + language[int(month)] + " " + year

def date_converter(language, date):
    month, day, year = date.split('/')
    return day + " " + language[int(month)] + " " + year

6. 练习:终止

题目:

# Question 7: Find and Replace

# For this question you need to define two procedures:
#  make_converter(match, replacement)
#     Takes as input two strings and returns a converter. It doesn't have
#     to make a specific type of thing. It can 
#     return anything you would find useful in apply_converter.
#  apply_converter(converter, string)
#     Takes as input a converter (produced by make_converter), and 
#     a string, and returns the result of applying the converter to the 
#     input string. This replaces all occurrences of the match used to 
#     build the converter, with the replacement.  It keeps doing 
#     replacements until there are no more opportunities for replacements.


def make_converter(match, replacement):



def apply_converter(converter, string):



# For example,

c1 = make_converter('aa', 'a')
print apply_converter(c1, 'aaaa')
#>>> a

c = make_converter('aba', 'b')
print apply_converter(c, 'aaaaaabaaaaa')
#>>> ab

# Note that this process is not guaranteed to terminate for all inputs
# (for example, apply_converter(make_converter('a', 'aa'), 'a') would 
# run forever).

(我没有思路,看不懂描述。)

视频的答案:

def make_converter(math, replacement):
    return [match, replacement]

def apply_converter(converter, string):
    previous = None
    while previos != string:
        position = string
        position = string.find(converter[0])
        if position != -1:
            string = string[:position] + converter [1] + string[position + len(converter[0]):]
        return string

7. 练习:查找替换

8. 练习:最长重复

题目:

# Question 8: Longest Repetition

# Define a procedure, longest_repetition, that takes as input a 
# list, and returns the element in the list that has the most 
# consecutive repetitions. If there are multiple elements that 
# have the same number of longest repetitions, the result should 
# be the one that appears first. If the input list is empty, 
# it should return None.

def longest_repetition():




#For example,

print longest_repetition([1, 2, 2, 3, 3, 3, 2, 2, 1])
# 3

print longest_repetition(['a', 'b', 'b', 'b', 'c', 'd', 'd', 'd'])
# b

print longest_repetition([1,2,3,4,5])
# 1

print longest_repetition([])
# None

(我的答案并不完整。。。

def longest_repetition(alist):
    if alist == []:
        return None
    sum = 1
    for index in range(len(alist)):
        if alist[index+1] == alist[index]:
            sum += 1
        else:
            sum =

)

视频的答案:

9. 练习:深度翻转

转载自原文链接, 如需删除请联系管理员。

原文链接:《计算机科学导论》学习笔记(27) - 课程 27: 累积实践问题,转载请注明来源!

0