使用python语言实现20以内的加减法生成

现在文档都收费了,搜个加减法题目发现都收费了,正好最近在学python,所以用python自己写代码生成了一个,就是排班还需要二次加工一下。下面的代码是运行后,会生成txt的文本

import random


def fun():
#i为要生成的题目个数
    i = 100
#定义一个list放置生成的加减法
    lis = []
    while i > 0:
        temp1 = random.randint(1, 20)
        temp2 = random.randint(1, 20)
#根据i的奇偶生成加法和算法算式
        if i % 2 == 0:
            if temp1 > temp2:
                num1 = temp1
                num2 = temp2
            else:
                num1 = temp2
                num2 = temp1
            regstr = "{}-{}=".format(num1, num2)
#如果是加法,需要保证总和小于20,所以这里要判断一下
        else:
            num1 = temp1
            num2 = temp2
            if(num1+num2 > 20):
                continue
            regstr = "{}+{}=".format(num1, num2)
        if regstr not in lis:
            lis.append(regstr)
            i -=1
        else:
            continue
    return lis



#生成20个文档
j =20


#filepath 为文件路径
filepath = "D:\\python\\temp\\"

def writelog(file, msg):
    with open(file, 'a', encoding='utf-8') as f:
        f.write(msg)

while j > 0:
    name = str(j)+'.txt'
# 将路径和文件名拼接
    filepath1 = filepath + name
    print(filepath1)
    newfile = open(filepath1, 'w')
    newfile.close()
    print("文件创建成功,文件路径", filepath1)
    lis = fun()
    for index, num in enumerate(lis):
        if (index + 1) % 5 == 0:
            writelog(filepath1, num)
            writelog(filepath1, '\n')

        else:
            writelog(filepath1, num)
            writelog(filepath1, '\t')
    j = j-1

  • 1
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值