MIT 6.00.1x 计算机科学和Python编程导论 Problem Set 1

MIT 6.00.1x 计算机科学和Python编程导论 Problem Set 1

Problem1:Counting vowels

Assume s is a string of lower case characters.
Write a program that counts up the number of vowels contained in the string s. Valid vowels are: ‘a’, ‘e’, ‘i’, ‘o’, and ‘u’. For example, if s = ‘azcbobobegghakl’,
your program should print:
Number of vowels: 5
For problems such as these, do not include raw_input statements or define the variable s in any way. Our automated testing will provide a value of s for you - so the code you submit in the following box should assume s is already defined. If you are confused by this instruction, please review L4 Problems 10 and 11 before you begin this problem set.

解决方案:

#方案一
n = 0 
#s自动给出
for i in range(len(s)):
    if s[i] in 'aeiou':
        n = n + 1
    i = i + 1
print('Number of vowels:' + str(n))

#方案二
print ('Number of vowel: '+str(s.count('a')+s.count('e')+s.count('i')+s.count('o')+s.count('u')))


Problem2:Counting bobs

Assume s is a string of lower case characters.
Write a program that prints the number of times the string ‘bob’ occurs in s. For example, if s = ‘azcbobobegghakl’,
then your program should print:
Number of times bob occurs is: 2
For problems such as these, do not include raw_input statements or define the variable s in any way. Our automated testing will provide a value of s for you - so the code you submit in the following box should assume s is already defined. If you are confused by this instruction, please review L4 Problems 10 and 11 before you begin this problem set.

解决方案:

#方案
n=0
i=0
for i in range(len(s)-2):
    if (s[i:i+3]=='bob'):
        n+=1
print ('Number of times bob occurs is: '+str(n))

problem3:Alphabetical Substrings

Assume s is a string of lower case characters.
Write a program that prints the longest substring of s in which the letters occur in alphabetical order. For example, if s = ‘azcbobobegghakl’
, then your program should print:
Longest substring in alphabetical order is: beggh
In the case of ties, print the first substring. For example, if s = ‘abcbcd’, then your program should print:
Longest substring in alphabetical order is: abc
For problems such as these, do not include raw_input statements or define the variable s in any way. Our automated testing will provide a value of s for you - so the code you submit in the following box should assume s is already defined. If you are confused by this instruction, please review L4 Problems 10 and 11 before you begin this problem set.

解决方案:

'''
若未按照字母顺序,便分割字符串,得到字符子串,
然后打印长度最长的字符子串
'''
newL=[]
beg=0
remain=s 
for i in range(len(s)-1):
    if (s[i+1] < s[i]):
        end=i+1
        newL.append(s[beg:end])
        beg=end
        remain=s[beg:]
newL.append(remain)
longest=''
for e in newL:
    if len(e) > len(longest):
        longest=e
print ('Longest substring in alphabetical order is: '+str(longest))
————————————————

你可能感兴趣的:(MIT,6.00.1x)