Python正式课第八天

练习

  1. 统计单词出现次数

第一种方法:字典


word="I'm a boby, I'm a girl. When it is true, it is ture. that are cats, the red is red."

#去除标点
# word = word.replace(',','')
# word = word.replace('.','')
word = word.replace(',','').replace('.','')
# print(word)
#split
wordlst = word.split(' ')
# print(wordlst)

worddict = {}

# for w in wordlst:
#     if w not in worddict:
#         worddict[w] = 1
#     else:
#         #取出该单词目前出现的次数
#         old_value = worddict[w]
#         new_value = old_value + 1
#         worddict[w] = new_value
for w in wordlst:
    worddict[w] = worddict.get(w,0) + 1


print(worddict.items())
#遍历字典
# for k,v in worddict.items():
#     print(k,v)

sortedlst = list(sorted(worddict.items(),key=lambda x : x[1],reverse=True))
for item in sortedlst:
    print(item)

第二种方法:count方法

word="I'm a boby, I'm a girl. When it is true, it is ture. that are cats, the red is red."

word = word.replace(',','').replace('.','')
wordlst = word.split(' ')
print(wordlst)

for w in wordlst:
    num = word.count(w)
    print(w, num)

第三种方法:Counter

word="I'm a boby, I'm a girl. When it is true, it is ture. that are cats, the red is red."
word = word.replace(',','').replace('.','')
wordlst = word.split(' ')

from collections import Counter

counter = Counter(wordlst)
print(counter) # 返回一个字典

for k,v in counter.items():
    print(k,v)
print(counter.most_common(3))

  1. 奥运会足球分组

已知有十六支男子足球队参加2008 北京奥运会。写一个程序,把这16 支球队随机分为4 个组。采用List集合和随机数

2008 北京奥运会男足参赛国家:

科特迪瓦,阿根廷,澳大利亚,塞尔维亚,荷兰,尼日利亚,日本,美国,中国,新西兰,巴西,比利时,韩国,喀麦隆,洪都拉斯,意大利

提示:分配一个,删除一个

image
import random

worlds = '科特迪瓦,阿根廷,澳大利亚,塞尔维亚,荷兰,尼日利亚,日本,美国,中国,新西兰,巴西,比利时,韩国,喀麦隆,洪都拉斯,意大利'
worlds_lst = worlds.split(',')
print(worlds_lst)

dic = {}

for i in range(4):
    group_lst = []
    for j in range(4):
        select_world = random.choice(worlds_lst)
        group_lst.append(select_world)
        worlds_lst.remove(select_world)

    dic[i+1] = group_lst



for k,v in dic.items():
    print('第' + str(k) + '组')

    for country in v:
        print(country,end=' ')

    print()

python字符串练习题

1.判断用户输入的变量名是否合法:

  • 变量名可以由字母,数字或者下划线组成
  • 变量名只能以字母或者下划线开头

分析:

  • 判断变量名的第一个元素是否为字母或者下划线 s[0]
  • 如果第一个元素符合条件,判断除了第一个元素之外的其他元素s[1:]

while True:
    tmp = input('请输入一个字符串:')
    if tmp == 'quit':
        break

    if tmp[0] == '_' or tmp[0].isalpha():
        # print('可能是合法的字符串')
        for c in tmp[1:]:
            if c == '_' or c.isalnum():
                continue
            else:
                print('不是合法的字符串')
                break
        else:
           print('是合法的字符串')
    else:
        print('不是合法的字符串')
  1. 给定一个字符串来代表一个学生的出勤纪录,这个纪录仅包含以下三个
    字符:
    'A' : Absent,缺勤
    'L' : Late,迟到
    'P' : Present,到场
    如果一个学生的出勤纪录中不超过一个'A'(缺勤)并且不超过两个连续的'L'(迟到),
    那么这个学生会被奖赏。
    你需要根据这个学生的出勤纪录判断他是否会被奖赏。
    示例 1:
    输入: "PPALLP"
    输出: True
    示例 2:
    输入: "PPALLL"
    输出: False
while True:
    tmp = input('请输入一个字符串:')
    if tmp == 'quit':
        break

    if tmp.count('A') + tmp.count('P') + tmp.count('L') < len(tmp):
        print('输入有误')

    if tmp.count('A') < 2 and tmp.count('LLL') == 0:
        print('True')
    else:
        print('False')
  1. 输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例
    如,输入”They are students.”和”aeiou”,
    则删除之后的第一个字符串变成”Thy r stdnts.”
    输入描述:
    每个测试输入包含2个字符串
    输出描述:
    输出删除后的字符串
    示例1:
    输入
    They are students.
    aeiou
    输出
    Thy r stdnts.
# 3.输入两个字符串,从第一字符串中删除第二个字符串中所有的字符。例
# 如,输入”They are students.”和”aeiou”,
# 则删除之后的第一个字符串变成”Thy r stdnts.”

s1 = input('请输入第一个字符串')
s2 = input('请输入第2个字符串')


for c2 in s2:
    s1 = s1.replace(c2,'')

print(s1)

python函数练习题

  1. 编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组.
    元组的第一个值为所有参数的平均值, 第二个值是大于平均值的所有数.
# 1.编写一个函数cacluate, 可以接收任意多个数,返回的是一个元组.
# 元组的第一个值为所有参数的平均值, 第二个值是大于平均值的所有数.
def calculate(*param):
    avg = sum(param) / len(param)
    # lst = []
    # for i in param:
    #     if i > avg:
    #         lst.append(i)
    lst = list(filter(lambda x:x>avg,param))

    return avg,lst

result = calculate(1,2,3,4,5)
print(result)
  1. 编写一个函数, 接收字符串参数, 返回一个元组,
    元组的第一个值为大写字母的个数, 第二个值为小写字母个数.
    例如
    输入:'hello WORLD'
    输出:(5,5)
# 编写一个函数, 接收字符串参数, 返回一个元组,
# 元组的第一个值为大写字母的个数, 第二个值为小写字母个数.

def count_char(str_param):
    # count_big = 0
    # count_small = 0
    #
    # for c in str_param:
    #     if c.isupper():
    #         count_big += 1
    #     if c.islower():
    #         count_small += 1

    small_chars = list(filter(lambda x : x.islower(),str_param))
    big_chars = list(filter(lambda x: x.isupper(), str_param))

    return len(small_chars),len(big_chars)

string = input('请输入一个字符串')
result = count_char(string)
print(result)
  1. 编写函数, 接收一个列表(包含30个1~100之间的随机整形数)
    和一个整形数k, 返回一个新列表.
    函数需求:
    将列表下标k之前对应(不包含k)的元素逆序;
    将下标k及之后的元素逆序;
# 3.编写函数, 接收一个列表(包含30个1~100之间的随机整形数)
# 和一个整形数k, 返回一个新列表.
#
# 函数需求:
# - 将列表下标k之前对应(不包含k)的元素逆序;
# - 将下标k及之后的元素逆序;
import random

lst = [random.randint(1,100) for i in range(30)]
print(lst)

def change_lst(numlist, k):
    if 0 <= k < len(lst):
        return numlist[:k][::-1] + numlist[k:][::-1]
    else:
        print('k的值输入有误')
        return None

newlst = change_lst(lst,5)
print(newlst)
  1. 模拟轮盘抽奖游戏
    轮盘分为三部分: 一等奖, 二等奖和三等奖;
    轮盘转的时候是随机的,
    如果范围在[0,0.08)之间,代表一等奖,
    如果范围在[0.08,0.3)之间,代表2等奖,
    如果范围在[0.3, 1.0)之间,代表3等奖,
    模拟本次活动1000人参加, 模拟游戏时需要准备各等级奖品的个数.
import random
from collections import Counter

rewardDict = {'1等奖':(0,0.08),'2等奖':(0.08,0.3),'3等奖':(0.3,1)}


def reward_fuc():
    num = random.random()

    for key,value in rewardDict.items():
        if value[0] <= num <= value[1]:
            return key

lst = []
for i in range(1000):
    reward_key = reward_fuc()
    lst.append(reward_key)

print(lst)
counter = Counter(lst)
for k,v in counter.items():
    print(k,v)

小结

  • item 项
  • s.count('A')+s.count('L')+s.count('p')<len(s) # 判断s中是否只有ALP三个字母
  • 如果要对一个可迭代对象里的元素分别操作,可以试试用filter(lambda 元素:操作,可迭代对象)
  • 列表逆序可以使用[::-1] 逆序是把列表里的元素颠倒,注意不是倒序
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容