跳到正文

剪贴板

剪贴板 1ijk4w88

原文
剪贴板信息

剪贴板信息

收录
更新
Python
try:
    import random
except (Exception, Warning):
    import numpy.random as random
from typing import Union, List
import tkinter
from tkinter.messagebox import showwarning, showinfo
import traceback
from PyCkin.stripe import get_file_gui as gfgi


class Automatic(object):
    def __init__(self, name, savepath='./test.txt', length=(10, 5)):
        #length为元组,第一项表示口算题道数,第二项表示竖式题道数
        self.savepath = savepath
        self.length = length
        self.__evals = ['+', '-', '×', '÷']
        self.name = name


    def __str__(self) -> str:
        return f'Automatic(savepath={self.savepath}, length={self.length})'


    def choice(self, seq: Union[list, tuple, set], probability: dict) -> str:  #控制概率
        pget = random.randint(0, 100)
        for p in probability.keys():
            p = int(p)
            if pget <= p and probability[str(p)] in seq:
                return probability[str(p)]
        return random.choice(seq)


    def GetQuestions(self) -> list:
        smac = self.SetMentalArithmetic()
        svqn = self.SetVerticalQuestion()
        return [*list(smac), 'separating elements', *list(svqn)]


    def GetQuestionFloat(self, questions: List[str]) -> list:

        def IsNumber(obj: str) -> bool:
            try:
                int(obj)
                return True
            except:
                try:
                    float(obj)
                    return True
                except:
                    return False

        ans = []
        for q in questions:
            temping = q
            evals = [i for i in q if not IsNumber(i)]

            q = q.replace('+', '#')
            q = q.replace('-', '#')
            q = q.replace('×', '#')
            q = q.replace('÷', '#')
            q = q.split('#')

            temp = random.randint(
                0,
                len(
                    str(
                        min(
                            [int(i) for i in q[: -1]]
                        )
                    )
                )
            )

            new = []
            if temp != 0:
                for i in q:   #小数点沉浮算法
                    j = list(i)
                    j.insert(temp, '.')
                    new.append(''.join(j))

                temp = ''
                for index, s in enumerate(new):
                    s = s[: -1]
                    temp += s
                    temp += evals[index]
                ans.append(temp)
            else:
                ans.append(temping)

        return ans




    def save(self) -> None:
        question = self.GetQuestions()
        _SeparatingElementsIndex = question.index('separating elements')
        smaces = question[: _SeparatingElementsIndex]
        svqnes = question[_SeparatingElementsIndex + 1: ]
        random.shuffle(smaces)
        random.shuffle(svqnes)
        smaces = self.GetQuestionFloat(smaces)
        svqnes = self.GetQuestionFloat(svqnes)
        del question
        smaces.insert(0, '一、口算')
        svqnes.insert(0, '\n二、竖式')
        base = [*smaces, *svqnes]
        base.insert(0, f'196xx  {self.name}')

        temp = []
        for i in base:
            index = base.index(i)
            if index == 0 or index == 1:
                ans = i + '\n'
            elif index % 3 == 0:
                ans = i + '\n'
            else:
                ans = i + '\t'
            temp.append(ans)
        else:
            base = temp

        with open(self.savepath, 'w') as f:
            f.write(''.join(base))


    def SetMentalArithmetic(self) -> dict:

        def ordinary() -> str:
            number_one = int(random.randint(7, 100))
            number_two = int(random.randint(6, 100))
            while number_one <= number_two:
                number_two = (random.randint(6, 100))
            evals = random.choice(self.__evals)
            if evals != '÷':
                evals = '=' if number_one % number_two == 0 else '≈'
                return f'{number_one}÷{number_two}{evals}'
            else:
                return f'{number_one}{evals}{number_two}='

        def trap() -> str:
            number_one = random.randint(7, 100)
            number_two = random.randint(6, 100)
            return f'{number_one}×{number_two}÷{number_one}×{number_two}='

        length = self.length[0]
        ans = set()

        while len(ans) != length:
            mode = self.choice(
                [
                    'ordinary',
                    'simple calculation',
                    'trap',
                ],
                {'70': 'ordinary',
                 '75': 'simple calculation',
                 '100': 'trap'}
            )

            ans.add(
                {
                'ordinary': ordinary(),
                'simple calculation': random.choice(
                    [
                        '125×8=',
                        '25×4=',
                        '625×16=',
                    ]
                ),
                'trap': trap(),
                }.get(mode, 'Null')
            )

        return ans

    def SetVerticalQuestion(self) -> set:
        length = self.length[1]
        ans = set()

        while len(ans) != length:
            evals = random.choice(self.__evals)
            number_one = random.randint(11, 999)
            number_two = random.randint(11, 999)

            if evals != '÷' and evals != '-':
                ans.add(f'{number_one}{evals}{number_two}=')
            elif evals == '÷':
                evals = '=' if number_one % number_two == 0 else '≈'
                ans.add(f'{number_one}÷{number_two}{evals}')
            elif evals == '-':
                temp = f'{number_one}{evals}{number_two}=' if number_one - number_two >= 0 else f'{number_two}{evals}{number_one}='
                ans.add(temp)

        return ans


def WriteQuestions() -> None:
    name = NameInput.get()
    path = FileInput.get()
    auto = Automatic(
        name=name,
        savepath=path,
        length=(
            int(MentalArithmeticInput.get()),
            int(VerticalQuestionInput.get())
        )
    )
    try:
        auto.save()
        showinfo('完成', f'文件已保存至{path}')
    except:
        showwarning('错误', traceback.format_exc())


def WriteFilePath() -> None:
    FileInput.delete(0, tkinter.END)
    FileInput.insert(
        0, gfgi(
            title='选择要保存到的文件',
            filetype='Text Files(*.txt;*.rtf;*.doc);;Custom Files(*.aqs;*.scp);;All Files(*)'
        )
    )


def JudgeIsNormal(self) -> None:

    def IsNumber(obj: str) -> bool:
        try:
            int(obj)
            return True
        except:
            return False

    if (IsNumber(MentalArithmeticInput.get()) and IsNumber(VerticalQuestionInput.get())):
        StartButton.config(state='normal')
    else:
        StartButton.config(state='disabled')


root = tkinter.Tk()
width, height = 700, 300
root.title('Automatic question setting')
root.geometry(f'{str(width)}x{str(height)}')
root.wm_minsize(width, height)
root.wm_maxsize(width, height)
info = {
    'author': 'CCZP',
    'version': '2.0.0',
    'window': str(tkinter),
    'get-error': str(traceback),
}

FileText = tkinter.Label(
    root,
    text='选择要保存到的文件:  ',
    font=('仿宋', 15)
)
FileText.grid(row=0, column=0)

FileInput = tkinter.Entry(
    root,
    font=('Times New Woman', 10),
    highlightcolor='red',
    highlightthickness=2,
    width=30
)
FileInput.grid(row=0, column=1)
FileInput.insert(0, './test.aqs')
tkinter.Label(root, text='      ').grid(row=0, column=2)

FileButton = tkinter.Button(
    root,
    command=WriteFilePath,
    text='选择要保存到的文件',
    font=('楷体', 15)
)
FileButton.grid(row=0, column=3)

NameText = tkinter.Label(
    root,
    text='请输入您的名字:   ',
    font=('楷体', 16),
)
NameText.grid(row=1, column=0)

NameInput = tkinter.Entry(
    root,
    width=30,
    highlightcolor='yellow',
    highlightthickness=2
)
NameInput.grid(row=1, column=1)

MentalArithmeticText = tkinter.Label(
    root,
    text='输入口算题数量:  ',
    font=('楷体', 17)
)
MentalArithmeticText.grid(row=2, column=0)

MentalArithmeticInput = tkinter.Entry(
    root,
    font=('Times New Woman', 10),
    highlightcolor='green',
    highlightthickness=2,
    width=30
)
MentalArithmeticInput.insert(0, '10')
MentalArithmeticInput.grid(row=2, column=1)
MentalArithmeticInput.bind('<Leave>', JudgeIsNormal)

VerticalQuestionText = tkinter.Label(
    root,
    text='输入竖式题数量:  ',
    font=('楷体', 17)
)
VerticalQuestionText.grid(row=3, column=0)

VerticalQuestionInput = tkinter.Entry(
    root,
    font=('Times New Woman', 10),
    highlightcolor='green',
    highlightthickness=2,
    width=30
)
VerticalQuestionInput.insert(0, '5')
VerticalQuestionInput.grid(row=3, column=1)
VerticalQuestionInput.bind('<Leave>', JudgeIsNormal)

StartButton = tkinter.Button(
    root,
    command=WriteQuestions,
    text='开始出题',
    font=('华文彩云', 16),
    state='disabled'
)
StartButton.grid(row=4, column=1)

ExitButton = tkinter.Button(
    root,
    command=lambda: root.destroy(),
    text='退出',
    font=('楷体', 16)
)
ExitButton.grid(row=5, column=1)

Debug1Button = tkinter.Button(
    root,
    command=lambda: showinfo(
        '调试信息',
        str(globals())
    ),
    text='调试信息(json格式)',
    font=('Times New Woman', 16)
)
Debug1Button.grid(row=6, column=0)

Debug2Button = tkinter.Button(
    root,
    command=lambda: showinfo(
        '软件信息',
        str(info)
    ),
    text='软件信息',
    font=('Times New Woman', 16)
)
Debug2Button.grid(row=6, column=1)

root.mainloop(0)