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

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.

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

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.

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

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))

I’m gonna make him an offer he can’t refuse. ——《Godfather》

你可能感兴趣的:(MIT,python,分享)