RError.com

RError.com Logo RError.com Logo

RError.com Navigation

  • 主页

Mobile menu

Close
  • 主页
  • 系统&网络
    • 热门问题
    • 最新问题
    • 标签
  • Ubuntu
    • 热门问题
    • 最新问题
    • 标签
  • 帮助
主页 / 问题

全部问题

Martin Hope
Mason
Asked: 2024-10-22 19:13:48 +0000 UTC

go 的线性计算器

  • 5

一个行计算器,在测试系统检查时,给出错误:超出了程序执行时间限制(某些情况下程序进入死循环,我认为有些错误情况没有被考虑到。

使用两个堆栈实现,其中一个是操作,另一个是数字。

我从视频中获取了操作原理:https://youtu.be/Vk-tGND2bfc?si= c4RzRBDehfykDRlm

这是问题陈述:

实现一个函数func Calc(expression string) (float64, error),其中表达式是由单字符标识符和算术运算符号组成的字符串表达式 输入数据 - 数字(有理数)、运算 +、-、*、/、优先运算(和 ) 写入错误的情况表达式,该函数会生成错误。

这是代码:

package main

import (
    "errors"
    "fmt"
    "strconv"
    "unicode"
)

func Calc(expression string) (float64, error) {
    priority := map[rune]int{'+': 1, '-': 1, '*': 2, '/': 2}
    var num []float64
    var operator []rune
    var hasNumber bool

    for _, ch := range expression {
        if unicode.IsDigit(ch) {
            hasNumber = true
        }
    }

    if !hasNumber {
        return 0, errors.New("no number")
    }

    if len(expression) == 0 {
        return 0, errors.New("empty expression")
    }

    check := rune(expression[len(expression)-1])
    if !unicode.IsDigit(check) && check != ')' {
        return 0, errors.New("invalid, last char is not digits or closing bracket")
    }

    applyOperator := func(a, b float64, op rune) float64 {
        switch op {
        case '+':
            return a + b
        case '-':
            return a - b
        case '*':
            return a * b
        case '/':
            if b == 0 {
                panic("division by zero")
            }
            return a / b
        default:
            return 0
        }
    }

    calculate := func() {
        if len(operator) == 0 || len(num) < 2 {
            return
        }
        b := num[len(num)-1]
        a := num[len(num)-2]
        op := operator[len(operator)-1]
        num = num[:len(num)-2]
        operator = operator[:len(operator)-1]
        result := applyOperator(a, b, op)
        num = append(num, result)
    }

    for i := 0; i < len(expression); i++ {
        ch := rune(expression[i])

        if unicode.IsDigit(ch) || ch == '.' {
            start := i
            for i < len(expression) && (unicode.IsDigit(rune(expression[i])) || expression[i] == '.') {
                i++
            }
            numer, err := strconv.ParseFloat(expression[start:i], 64)
            if err != nil {
                return 0, fmt.Errorf("failed to parse number: %v", err)
            }
            num = append(num, numer)
            i--
        } else if ch == '+' || ch == '-' {
            if i == 0 || expression[i-1] == '(' || len(operator) > 0 && operator[len(operator)-1] == '(' {
                num = append(num, 0)
            }
            for len(operator) > 0 && priority[operator[len(operator)-1]] >= priority[ch] {
                calculate()
            }
            operator = append(operator, ch)
        } else if ch == '*' || ch == '/' {
            for len(operator) > 0 && priority[operator[len(operator)-1]] >= priority[ch] {
                calculate()
            }
            operator = append(operator, ch)
        } else if ch == '(' {
            operator = append(operator, ch)
        } else if ch == ')' {
            for len(operator) > 0 && operator[len(operator)-1] != '(' {
                calculate()
            }
            if len(operator) == 0 {
                return 0, errors.New("mismatched parentheses")
            }
            operator = operator[:len(operator)-1]
        } else if !unicode.IsSpace(ch) {
            return 0, errors.New("invalid character")
        }
    }

    for len(operator) > 0 {
        calculate()
    }

    if len(num) == 1 {
        return num[0], nil
    }

    return 0, errors.New("invalid expression")
}


golang
  • 1 个回答
  • 150 Views
Martin Hope
weldoy
Asked: 2024-10-22 18:09:10 +0000 UTC

解释问题的解决方案。统一国家考试 23 [已关闭]

  • 5
关闭。这个问题需要澄清或者补充细节。目前不接受对此问题的答复。

想要改进这个问题吗?通过编辑这篇文章添加更多详细信息并澄清问题。

2 天前关闭。

改进问题

TP4 执行者转换屏幕上的数字。

表演者有两支队伍,并分配了编号:

  1. 添加 1
  2. 乘以 2

也就是说,第一个命令将屏幕上的数字加 1,第二个命令将其乘以 2。

TP4 执行器的程序是一系列命令。

有多少个程序将原来的数字2转换为数字35,但计算路径中包含数字15而不包含数字31?

计算轨迹是所有程序命令执行的结果序列。例如,对于初始编号为 7 的程序 212,轨迹将由数字 14、15、30 组成。

def f(x, y):
    if x > y or x == 31:
        return 0
    elif x == y:
        return 1
    else:
        return f(x + 1, y) + f(x * 2, y)

print(f(2, 15) * f(15, 35))
python
  • 1 个回答
  • 67 Views
Martin Hope
Irking
Asked: 2024-10-22 15:22:11 +0000 UTC

Python 在文件更改时维护目录结构

  • 6

朋友们,大家好。我无法弄清楚这个问题。程序应在给定的 /Old 目录(以及所有子目录)中搜索所有 *.dxf,对图形进行典型更改,然后以相同的名称和相同的路径结构保存到 /New 目录。

from pathlib import Path
import glob
import ezdxf
from google.colab import drive
drive.mount('/content/drive', force_remount=True)

# Путь к старому каталогу
old_path = Path('/content/drive/My Drive/Старые')
# Путь к новому каталогу
new_path = Path('/content/drive/My Drive/Новые')

def save_new_dxf(file, doc):
    # Создаем новый путь для файла в новом каталоге
    new_file = new_path / file.name
    parent_dir = new_file.parent
    if not parent_dir.exists():
        parent_dir.mkdir(parents=True)
    doc.saveas(str(new_file))

def change_dxf(file):
    # Открываем чертеж
    doc = ezdxf.readfile(str(file))
    # Тут вносим типовые изменения

    # Передаём файл на сохранение
    save_new_dxf(file, doc)

# Перебираем все файлы в старом каталоге и подкаталогах с расширением .dxf
for file in old_path.glob('**/*.dxf'):
    change_dxf(file)

一切正常,有变化,但文件保存在 /New 目录中,没有结构,即所有文件都在一个文件夹中。

我怀疑错误是doc.saveas(str(new_file))- 如何将子目录添加到路径中?

python
  • 1 个回答
  • 38 Views
Martin Hope
Globa2
Asked: 2024-10-22 15:15:24 +0000 UTC

如何修复 QUERY、Google 表格中的错误?

  • 5

功能:

=QUERY('Расходы/Доходы'!A4:C;"select C where C is not null and month(A)="&IFS(C5="Январь";0;C5="Февраль";1;C5="Март";2;C5="Апрель";3;C5="Май"; 4;C5="Июнь";5;C5="Июль";6;C5="Август";7;C5="Сентябрь";8;C5="Октябрь";9;C5="Ноябрь";10;C5="Декабрь";11)&" and year(A)="&C4&", sum(B) group by C";0)

显示错误“值!”:

Не удалось интерпретировать query string. Подробности: Параметр 2 в
функции QUERY:PARSE_ERROR: Encountered " "," ", "" at line 1, column
61. Was expecting one of: "group" ... "pivot" ... "order" ... 
"skipping" ... "limit" ... "offset" ... "label" ... "format" ... 
"options" ... "and" ... "or" ...

该设计看起来很复杂,因为我使用 将月份的口头名称从单元格转换为数字名称IFS()。我的任务是显示特定期间的费用类别以及每个类别的支出金额。在这种情况下,类别可以在几个不同的单元格中重复。

当我添加单引号时,该函数什么也不返回。

当我添加时一切都会崩溃,sum(B) group by C。

我该如何解决这个问题?我在描述病情时做错了什么?

google-spreadsheet
  • 1 个回答
  • 44 Views
Martin Hope
Limaximy
Asked: 2024-10-22 09:35:27 +0000 UTC

为什么Winograd-Strassen算法在matlab中速度变慢很多?

  • 5

为了您的学习,您需要比较经典的矩阵乘法算法和 Winograd-Strassen 算法。我不清楚为什么 Winograd-Strassen 算法比经典算法慢得多。据我所知,MatLab 对经典算法进行了更优化,尤其是对于超大型矩阵。使用 Winograd-Strassen 算法会浪费时间为中间矩阵等分配内存空间。但随着矩阵的大小,减速非常大 - 我将其附在图片中。图中,矩阵阶数为2^10的经典算法运行时间为几秒钟,而Winograd-Strassen算法则需要7分钟。

在此输入图像描述

这是代码,可能算法没有正确理解它。只需使用 Strassen 和 Winograd-Strassen 算法调用一个函数就需要类型参数。好像没有更多的功能了

clc;

function AA = split_to_2x2_blocks(matrix)  % разделение матрицы на 4 части
    buf = width(matrix);
    A11 = matrix(1:buf/2, 1:buf/2);
    A12 = matrix(1:buf/2, buf/2+1:buf);
    A21 =  matrix(buf/2+1:buf, 1:buf/2);
    A22 = matrix(buf/2+1:buf, buf/2+1:buf);
    
    AA = {A11, A12
            A21, A22};
end

function CC = strassen_mul_2x2(lb, rb, type) % умножение матрицы после разделения, рекурсивная чушь тут и все такое

    d = strassen_mul(cell2mat(lb(1,1)) + cell2mat(lb(2,2)), cell2mat(rb(1,1)) + cell2mat(rb(2,2)), type);
    d_1 = strassen_mul(cell2mat(lb(1,2)) - cell2mat(lb(2,2)), cell2mat(rb(2,1)) + cell2mat(rb(2,2)), type);
    d_2 = strassen_mul(cell2mat(lb(2,1)) - cell2mat(lb(1,1)), cell2mat(rb(1,1)) + cell2mat(rb(1,2)), type);
    left = strassen_mul(cell2mat(lb(2,2)), cell2mat(rb(2,1)) - cell2mat(rb(1,1)), type);
    right = strassen_mul(cell2mat(lb(1,1)), cell2mat(rb(1,2)) - cell2mat(rb(2,2)), type);
    top = strassen_mul(cell2mat(lb(1,1)) + cell2mat(lb(1,2)), cell2mat(rb(2,2)), type);
    bottom = strassen_mul(cell2mat(lb(2,1)) + cell2mat(lb(2,2)), cell2mat(rb(1,1)), type);
    
    c1 = d + d_1 + left - top;
    c2 = right + top;
    c3 = left + bottom;
    c4 = d + d_2 + right - bottom;
    CC = [c1, c2
            c3, c4];
    
end

function CC = vinograd_strassen_mul_2x2(lb, rb, type) 
    s1 = cell2mat(lb(2,1)) + cell2mat(lb(2,2));
    s2 = s1 - cell2mat(lb(1,1));
    s3 = cell2mat(lb(1,1)) - cell2mat(lb(2,1));
    s4 = cell2mat(lb(1,2)) - s2;
    s5 = cell2mat(rb(1,2)) - cell2mat(rb(1,1));
    s6 = cell2mat(rb(2,2)) - s5;
    s7 = cell2mat(rb(2,2)) - cell2mat(rb(1,2));
    s8 = s6 - cell2mat(rb(2,1));
    p1 = strassen_mul(s2, s6, type);
    p2 = strassen_mul(cell2mat(lb(1,1)), cell2mat(rb(1,1)), type);
    p3 = strassen_mul(cell2mat(lb(1,2)), cell2mat(rb(2,1)), type);
    p4 = strassen_mul(s3, s7, type);
    p5 = strassen_mul(s1, s5, type);
    p6 = strassen_mul(s4, cell2mat(rb(2,2)), type);
    p7 = strassen_mul(cell2mat(lb(2,2)), s8, type);
    t1 = p1 + p2;
    t2 = t1 + p4;
    CC = [p2 + p3, t1 + p5 + p6
            t2 - p7, t2 + p5];
    
end

function c = default_mul(left, right) % классический метод умножения матриц
    c = zeros(length(left));
    
    for ii = 1:length(left)
        for jj = 1:length(right)
            for rr = 1:length(left)

                c(ii, jj) = c(ii, jj) + left(ii, rr)* right(rr, jj);
            end
        end
    end
    
end

function c = strassen_mul(left, right, type ) % типо сюда пихаем матрицу и её будущие части, а потом решаем
    if length(left) == 2
        c = default_mul(left, right);
    else
        %if type == 0
            
        %    c = strassen_mul_2x2(split_to_2x2_blocks(left), split_to_2x2_blocks(right), type);
        %elseif type == 1
            
            c = vinograd_strassen_mul_2x2(split_to_2x2_blocks(left), split_to_2x2_blocks(right), type);
        %else
        %    disp('Не выбран вариант')
        %end
    end
end
% 
% a = [1 2 3 4
%     5 6 7 8
%     9 10 11 12
%     13 14 15 16];
% b = [1 2 3 4
%     5 6 7 8
%     9 10 11 12
%     13 14 15 16];
% a = randi([1, 10], 8);
% b = randi([1, 10], 8);
% count_mas = [0, 0, 0]; % сложение, умножение, умножение матриц
% disp(a)
% disp(b)
% c = strassen_mul(a,b);
% disp(c)
% disp(sum)
% disp(umnoj)
% disp(umnoj_mat)

max_stepen = 6;
all_time = zeros(max_stepen, 2);
for t = 1:max_stepen
    step = 2^t;
    a = randi([1,10], step);
    b = randi([1,10], step);
    tic
    c = default_mul(a, b);
    all_time(t, 1) = toc;

    tic
    c = strassen_mul(a,b, 1);
    all_time(t, 2) = toc;
end
t = 1:max_stepen;
hold on
grid on
title("График времени работы без фоновых процессов")
plot(t, all_time(:, 1),'-gs',  'LineWidth',2, 'MarkerSize',10,'Color', [0 0.4470 0.7410])
plot(t,all_time(:, 2),':gs','LineWidth',2,'MarkerSize',10, 'Color', [0.9290 0.6940 0.1250])
xlabel('Порядок матриц')
ylabel('Время работы')
legend("Классический метод", "Метод Винограда-Штрассена")
алгоритм
  • 1 个回答
  • 39 Views
上一页
下一页

Sidebar

Stats

  • 问题 10021
  • Answers 30001
  • 最佳答案 8000
  • 用户 6900
  • 常问
  • 回答
  • Marko Smith

    我看不懂措辞

    • 1 个回答
  • Marko Smith

    请求的模块“del”不提供名为“default”的导出

    • 3 个回答
  • Marko Smith

    "!+tab" 在 HTML 的 vs 代码中不起作用

    • 5 个回答
  • Marko Smith

    我正在尝试解决“猜词”的问题。Python

    • 2 个回答
  • Marko Smith

    可以使用哪些命令将当前指针移动到指定的提交而不更改工作目录中的文件?

    • 1 个回答
  • Marko Smith

    Python解析野莓

    • 1 个回答
  • Marko Smith

    问题:“警告:检查最新版本的 pip 时出错。”

    • 2 个回答
  • Marko Smith

    帮助编写一个用值填充变量的循环。解决这个问题

    • 2 个回答
  • Marko Smith

    尽管依赖数组为空,但在渲染上调用了 2 次 useEffect

    • 2 个回答
  • Marko Smith

    数据不通过 Telegram.WebApp.sendData 发送

    • 1 个回答
  • Martin Hope
    Alexandr_TT 2020年新年大赛! 2020-12-20 18:20:21 +0000 UTC
  • Martin Hope
    Alexandr_TT 圣诞树动画 2020-12-23 00:38:08 +0000 UTC
  • Martin Hope
    Air 究竟是什么标识了网站访问者? 2020-11-03 15:49:20 +0000 UTC
  • Martin Hope
    Qwertiy 号码显示 9223372036854775807 2020-07-11 18:16:49 +0000 UTC
  • Martin Hope
    user216109 如何为黑客设下陷阱,或充分击退攻击? 2020-05-10 02:22:52 +0000 UTC
  • Martin Hope
    Qwertiy 并变成3个无穷大 2020-11-06 07:15:57 +0000 UTC
  • Martin Hope
    koks_rs 什么是样板代码? 2020-10-27 15:43:19 +0000 UTC
  • Martin Hope
    Sirop4ik 向 git 提交发布的正确方法是什么? 2020-10-05 00:02:00 +0000 UTC
  • Martin Hope
    faoxis 为什么在这么多示例中函数都称为 foo? 2020-08-15 04:42:49 +0000 UTC
  • Martin Hope
    Pavel Mayorov 如何从事件或回调函数中返回值?或者至少等他们完成。 2020-08-11 16:49:28 +0000 UTC

热门标签

javascript python java php c# c++ html android jquery mysql

Explore

  • 主页
  • 问题
    • 热门问题
    • 最新问题
  • 标签
  • 帮助

Footer

RError.com

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

帮助

© 2023 RError.com All Rights Reserve   沪ICP备12040472号-5