Python函数与数据结构练习题一

把单词按首字母顺序排列

# change this value for a different result
#思路:使用sort+hey
my_str = "Hello this Is an Example With cased letters" ''' 这是一种很麻烦很难受的解法 a = my_str.upper() print(a) b = a.split(' ') print(b) b.sort() print(b) #your solution here ''' #使用key一条搞定 sorted(my_str.split(),key=str.lower) ​ #输出结果 ['an', 'cased', 'Example', 'Hello', 'Is', 'letters', 'this', 'With']

统计一段话里面每个元音字母各出现了多少次

#思路:生成字典,使用fromkey
# string of vowels
vowels = 'aeiou'
counter = {}.fromkeys(vowels,0)

# change this value for a different result
in_str = 'Hello, have you tried our turorial section yet?'

# make it suitable for caseless comparisions
in_str = in_str.casefold()

# make a dictionary with each vowel a key and value 0
# your soultion here count the vowels

print(counter)

#输出结果
{'a': 0, 'e': 0, 'i': 0, 'o': 0, 'u': 0}

找出名单中名字最长的人

#思路:很简单,遍历列表使用len()求最长
names = ["Joshua Zhao", "XiaoLee", "Ze", "Josh"]
longest = names[0]

# your solution here
for name in names:
    if len(name) > len(longest):
        longest = name
​
print(longest)        
 
 
 #输出结果
Joshua Zhao

一个歌唱比赛的歌手打分,我们设计一个程序帮助现场去掉一个最低分和一个最高分,再计算一个平均分

例如分数为: [8,9,5,10,9.5,8,7,9,9.5] 则去掉最低分 [8,9,5,10,9.5,8,9,9.5]

#思路:遍历找出分别找出最小和最大值,然后使用remove()去掉,最后求数组总和再除以len(values)
values =  [8,9,5,10,5,8,7,9,9.5]
'''
这种方法用逻辑的思路实现,麻烦了点但是可以训练下思维
#求最小分
small_pos = values[0]
for small_grade in values:
    if small_grade < small_pos:
        small_pos = small_grade
print('最小分:%d' % small_pos)
​
#求最大分
high_pos = values[0]
for high_grade in values:
    if high_grade > high_pos:
        high_pos = high_grade
print('最大分:%d' % high_pos)
​
values.remove(values[small_pos])
values.remove(values[high_pos])
print(values)
'''

#不好意思,python内置可以直接搞定
values.remove(max(values))
values.remove(min(values))
a = sum(values)/len(values)
print(a)

#输出结果
7.928571428571429
 

设计一个函数,反向打印list里面的数据

def print_reversed(values) :
    # Traverse the list in reverse order, starting with the last element
    # your solution here
    i = len(values) - 1
    reverses = []
    while i > 0: 
        print(values[i],end=',')
        i = i - 1 
    
print_reversed([3,4,52,3,1,5,6,78,3])
 
#输出结果
3,78,6,5,1,3,52,4,
 
 
 
3,78,6,5,1,3,52,4,
 
 
 
 

猜你喜欢

转载自www.cnblogs.com/kumata/p/9095253.html