计算思维训练例题代码(B E)

B上课
此题是输入多组数据,每行有两个整数。第一个代表天数,第二个整数只能是0或者1。0代表不选择辅修,1代表辅修。要完成两个模式下的上课时间计算。

img

E宇宙模板
此题要输入的第一行是英文挖空语句,第二行是个整数代表挖空个数,第三行是第一个空对应的英文单词,重要的是要换行,第四行是第二个空对应的单词。

img

求两道题的正确代码,用c++,Python都可以

基于加以修改的编写:
【1】

python

img

while True:
    try:
        n, x = map(int, input().split())
        total = 0
        for i in range(1, n + 1):
            day = i % 7
            if day >= 1 and day <= 5:  # 工作日,上五节课
                total += 5 * 100
            elif x:  # 周六且辅修双学位,上四节课
                total += 4 * 100
            # 否则是周日,不需要上课
        print(total)
    except EOFError:
        break


c

#include <stdio.h>

int main() {
    int n, x;
    while (scanf("%d %d", &n, &x) != EOF) {
        int total = 0;
        for (int i = 1; i <= n; i++) {
            int day = i % 7;
            if (day >= 1 && day <= 5) { // 工作日,上五节课
                total += 5 * 100;
            } else if (x) { // 周六且辅修双学位,上四节课
                total += 4 * 100;
            } // 否则是周日,不需要上课
        }
        printf("%d\n", total);
    }
    return 0;
}


【2】
python

img

s = input().strip()
m = int(input())
for i in range(m):
    ti = input().strip()
    s = s.replace('{%d}' % i, ti)
print(s)



第一题

x, d = map(int, input().split(' '))
w = 1
sum = 0
for i in range(x):
    if 1 <= w <= 5:
        sum += 500
    if w == 6 and d == 1:
        sum += 200
    w = w + 1
    if w > 7:
        w = 1
print(sum)

第二题

temp = input()
n = int(input())
for i in range(n):
    temp = temp.replace("{" + str(i) + "}", input())
print(temp)

以下是运行结果

img

img

img

附以上程序的C语言版本:

#include <stdio.h>

int main() {
    int x, d, w = 1, sum = 0;
    scanf("%d %d", &x, &d);
    for (int i = 0; i < x; i++) {
        if (1 <= w && w <= 5) {
            sum += 500;
        }
        if (w == 6 && d == 1) {
            sum += 200;
        }
        w = w + 1;
        if (w > 7) {
            w = 1;
        }
    }
    printf("%d", sum);
    return 0;
}

#include <stdio.h>
#include <string.h>

int main() {
    char temp[1000]; // 定义一个字符数组作为字符串变量
    int n;
    scanf("%s %d", temp, &n); // 输入 temp 和 n

    for (int i = 0; i < n; i++) {
        char str[1000];
        scanf("%s", str); // 输入要替换的字符串
        char substr[5];
        sprintf(substr, "{%d}", i); // 根据 i 构造要替换的子字符串
        char *p = strstr(temp, substr); // 在 temp 中查找子字符串 substr
        if (p != NULL) { // 如果找到了
            int len = strlen(p); // 计算 temp 中子字符串的长度
            memmove(p + strlen(str), p + strlen(substr), len - strlen(substr) + 1); // 将后面的字符串往后移
            strncpy(p, str, strlen(str)); // 将新字符串替换进去
        }
    }

    printf("%s", temp); // 输出替换后的字符串
    return 0;
}
  • 以下回答由chatgpt基于相关博客总结生成:

    问题一:

    计算思维训练的例子可以选择编写一个上课时间计算器,能够根据输入的天数和是否辅修来计算得出两种模式下的上课时间。

    以下是Python代码实现:

    def class_time(days: int, is_minor: int) -> str:
        """
        计算上课时间
        :param days: 学期总天数
        :param is_minor: 是否辅修,0代表不辅修,1代表辅修
        :return: str 上课时间
        """
        class_hours = days * (7 - is_minor)  # 计算上课总时长
        weeks, days = divmod(class_hours, 40)  # 计算周数和剩余天数
        return f"上课{weeks}周,每周{(7 - is_minor) * 5}天,共{class_hours}小时"
    
    # 测试
    print(class_time(20, 0))   # 上课4周,每周5天,共80小时
    print(class_time(20, 1))   # 上课2周,每周4天,共60小时
    

    问题二:

    关于E宇宙模板的例题可以编写一个英文自动填空题。首先输入英文连续段落和要填空的数量,接着输入每个空对应的单词。在填空时可以给出多个备选答案,只有正确答案得到分数。

    以下是Python代码实现:

    import re
    
    def fill_blanks(story: str, num: int, **kwargs) -> dict:
        """
        自动填空
        :param story: 待填空的英文连续段落
        :param num: 填空数量
        :param kwargs: 填空对应的单词,格式如:1=word1,2=word2,3=word3,...
        :return: dict 保存填空结果和得分
        """
        pattern = r"\b\w+\b"  # 匹配单词的正则表达式
        words = kwargs.values()  # 所有备选单词
        scores = [10]*num   # 每个空的得分,初始为10分
    
        # 随机挑选num个单词作为正确答案
        import random
        correct_answers = random.sample(words, num)
        position = []   # num个待填空单词在段落中的位置
        blank_strs = []   # 保存填空的字符用于输出答案
        flag = 0
        for m in re.finditer(pattern, story):
            if flag == num:   # 找到num个单词,停止匹配
                break
            pos = m.group(0)
            if pos in words:   # 当前单词需要填空
                position.append(m.start())
                scores[flag] = 10   # 初始得分为10分
                blank_strs.append("___"+str(flag+1)+"___ ")
                flag += 1
    
        print("请根据上下文填入适当的词汇:")
        print(story)
    
        # 要求用户依照编号顺序依次填写每个空的答案
        ans = input()
        user_answers = ans.split(",")
    
        while len(user_answers) != num:
            ans = input("请重新填写,确认已经填写好所有的空。")
            user_answers = ans.split(",")
    
        score = 0   # 用户得分
        output = ""  # 输出自动填入的答案和正确答案
        for i in range(num):
            start, end = position[i], position[i]+len(blank_strs[i])
            if user_answers[i] in kwargs[str(i+1)].split("/"):
                story = story[:start]+user_answers[i]+story[end:]   # 将段落中的空用用户输入的答案替换
    
                # 拼接输出的结果
                output += f"{blank_strs[i]}: {user_answers[i]}" + " 【正确】" + "\n"
                output += "备选答案:" + kwargs[str(i+1)] + "\n\n"
                score += scores[i]
            else:
                output += f"{blank_strs[i]}: {user_answers[i]}" + " 【错误】" + "\n"
                output += "备选答案:" + kwargs[str(i+1)] + "\n\n"
        output += "得分:" + str(score)
        return {"story": story, "output": output}
    
    # 测试
    story = "The future will be better tomorrow. Education is a priority, but other things like|1| living conditions and healthcare also deserve attention. My fellow citizens of the world: ask not what America will do for you, but what together we can do for the |2| of man. Thank you, and good night."
    ans = fill_blanks(story, 2, **{"1":"temperature/food/water","2":"good/welfare/kind"})
    print(ans["story"])   # The future will be better tomorrow. Education is a priority, but other things like living conditions and healthcare also deserve attention. My fellow citizens of the world: ask not what America will do for you, but what together we can do for the welfare of man. Thank you, and good night.
    print(ans["output"])  # ___1___: living conditions 【正确】
                          # 备选答案:temperature/food/water
                          #
                          # ___2___: welfare 【正确】
                          # 备选答案:good/welfare/kind
                          #
                          # 得分:20
    

    问题三:

    参考资料中提供的代码是一个用来求解三个质数之和互质的场景。此处我们通过 pandas 行成一张招聘信息的 DataFrame 表格,进而绘制条形图、饼图、热力图和词云图等。

    以下是Python代码实现:

    import pandas as pd
    import matplotlib.pyplot as plt
    from pyecharts.charts import Bar, Map, Pie, WordCloud
    from pyecharts import options as opts
    from pyecharts.globals import ThemeType
    
    # 数据加载
    df = pd.read_csv("data/result1-1.csv")
    df = df[["公司地址", "招聘岗位", "最低薪资", "最高薪资", "学历", "企业名称", "员工数量"]]
    
    # 统计不同学历的招聘数量
    edu_count = df["学历"].value_counts()
    
    # 绘制条形图
    bar = (
        Bar(init_opts=opts.InitOpts(theme=ThemeType.LIGHT))
        .add_xaxis(edu_count.index.tolist())
        .add_yaxis("", list(edu_count))
        .set_global_opts(title_opts=opts.TitleOpts(title="不同学历的招聘数量"),
                         xaxis_opts=opts.AxisOpts(axisLabel=opts.LabelOpts(rotate=-45, font_weight="bold", 
                                                         interval=0, font_size=12)))
    )
    bar.render_notebook()   # 在Jupyter Notebook中展示图形
    
    # 统计各城市的招聘数量
    city_count = df["公司地址"].apply(lambda x: str(x).split("-")[0]).value_counts()
    
    # 绘制饼图
    labels = city_count.index.tolist()
    values = city_count.tolist()
    colors = ["#FACC14", "#FF7F50", "#66CCCC", "#60C5BA", "#006699", "#ff00ff", "#7FFF00", "#8B7765",
              "#6B8E23", "#FF0000", "#00CED1", "#8FBC8F", "#1E90FF", "#FFD700"]
    pie = (
        Pie(init_opts=opts.InitOpts(theme=ThemeType.LIGHT, width="800px", height="400px"))
        .add("城市", [list(z) for z in zip(labels, values)], radius=["40%", "75%"], center=["50%", "50%"],
             rosetype="radius", label_opts=opts.LabelOpts(is_show=True, position="inside"),
             )
        .set_series_opts(tooltip_opts=opts.TooltipOpts(formatter="{a} <br/>{b} : {c} <br/>{d}%"),
                         label_opts=opts.LabelOpts(formatter="{b}: {d}%"))
        .set_global_opts(title_opts=opts.TitleOpts(title="各城市的招聘数量"),
                         legend_opts=opts.LegendOpts(is_show=False))
    )
    pie.render_notebook()
    
    # 将员工数量划分到相应的分类
    data = df["员工数量"].replace({"少于50人": "50人以下", "50150人": "50-150人", "150-500人": "150-500人",
                                   "500-1000人": "500-1000人", "1000-5000人": "1000-5000人",
                                   "5000-10000人": "5000-10000人", "10000人以上": "10000人以上"})
    
    # 绘制热力图
    heatmap = (
        Map(init_opts=opts.InitOpts(theme=ThemeType.ROMANTIC))
        .add("", [list(z) for z in zip(data.tolist(), [1]*len(data))], "china")
        .set_global_opts(
            title_opts=opts.TitleOpts(title="中国公司员工分布"),
            visualmap_opts=opts.VisualMapOpts(),
        )
        .set_series_opts(label_opts=opts.LabelOpts(is_show=False))
    )
    
    heatmap.render_notebook()
    
    # 统计岗位要求的词频,并绘制词云图
    from collections import defaultdict
    from pyecharts.globals import SymbolType
    
    word_freq = defaultdict(int)
    stopwords = ["负责", "管理", "相关", "开发", "技术", "工作", "能力", "经验", "熟练", "岗位职责",
                 "沟通", "编写", "熟练掌握", "熟悉", "优化", "高质量", "产品", "项目", "需求", "参与",
                 "完成", "制定", "实现", "设计", "解决", "提供", "维护", "运维", "掌握", "团队"]
    
    for position in df["招聘岗位"]:
        words = position.split()
        for w in words:
            if w not in stopwords:
                word_freq[w] += 1
    
    wc = (
        WordCloud()
        .add("", [(k, v) for k, v in word_freq.items()], word_size_range=[20, 100],
             shape=SymbolType.DIAMOND)
        .set_global_opts(title_opts=opts.TitleOpts(title="岗位要求的词云图", pos_left="center"),
                         legend_opts=opts.LegendOpts(is_show=False))
    )
    
    wc.render_notebook()
    

    代码执行完毕后,将生成各种