zoukankan      html  css  js  c++  java
  • 宝宝加减法出题小程序

    避免计算过程中出现负数,可以设定题目长度,最大的数字。

    """
    Spyder Editor
    
    This is a temporary script file.
    """
    import random
    import re
    import pprint
    
    
    def calc(s = '5+6-1'):
        '''
        @s:'5+6-1'
        '''
        #print 'calc : %s 
    ' % s
        numbers = re.findall(r'd+' , s)
        symbols = re.findall(r'[+-]+', s)
        i = 1
        j = 0
        result = 0
        result += int(numbers[0])
        while i < len(numbers) and j < len(symbols):
            if symbols[j] == '+' :
                result += int(numbers[i])
            elif symbols[j] == '-' :
                result -= int(numbers[i])
            else:
                print symbols
                print 'Only + and - accept'
                return False
            i += 1
            j += 1 
            if result < 0:
                #print 'negtive not accept'
                return False
        #print '%s = %d' %(s,result)
        return result
    
    def getOneExpression(problemMaxLength = 5 , maxNum = 15):
        problemLength = random.randint(2,problemMaxLength)
        expression = ''
        i = 0
        num = random.randint(0 , maxNum)
        expression += str(num)
        while i < problemLength-1:
            tmp = expression
            expression += random.sample(['+','-'] , 1)[0]
            num = random.randint(0 , maxNum)
            expression += str(num)
            #print 'expression1 : ' ,expression
            if calc(expression):
                i += 1
            else:
                expression = tmp
            #print 'expression2 : ' ,expression
            #import time
            #time.sleep(1)
        #print expression
        return expression
    
    def setProblems(problemNum = 10 , problemMaxLength = 5 , maxNum = 15):
        problem = {}#{'P1':{'problem':'5+6' , result = 11}}
        
        # set level
        #problemNum = 10
        #problemMaxLength = 5
        #maxNum = 15
        for i in range(problemNum): 
            problem.setdefault('P'+str(i) , {})
            problem['P'+str(i)].setdefault('problem' , 
                    getOneExpression(problemMaxLength , maxNum))
            
            problem['P'+str(i)].setdefault('result' , 
                    calc(problem['P'+str(i)]['problem']))        
        return problem
    
    #test 
    '''      
    calc('1')
    getOneExpression()
    random.sample(['+','-'] , 1)
    '''
    
    problems = setProblems()
    pprint.pprint(problems)
  • 相关阅读:
    爱就是一个人一辈子
    硬件访问方法和混杂字符设备
    Linux内核等待队列
    深入浅出的讲解傅里叶变换(真正的通俗易懂)
    Linux用root强制踢掉已登录用户
    一文带你读懂宽带上下行速率不对称的原因
    FDD-LTE上下行带宽一样的,为什么上下行流量差别这么大
    linux alsa音频中采样率fs、比特率BCLK 、主时钟MCLK关系
    80211 发送速率选择算法分析
    imx6q 启动logo
  • 原文地址:https://www.cnblogs.com/colipso/p/8461006.html
Copyright © 2011-2022 走看看