AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • 主页
  • 系统&网络
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • 主页
  • 系统&网络
    • 最新
    • 热门
    • 标签
  • Ubuntu
    • 最新
    • 热门
    • 标签
  • Unix
    • 最新
    • 标签
  • DBA
    • 最新
    • 标签
  • Computer
    • 最新
    • 标签
  • Coding
    • 最新
    • 标签
主页 / coding / 问题

问题[sorting](coding)

Martin Hope
badbee
Asked: 2024-12-18 01:50:48 +0800 CST

使用 xsl:sort 时保留未排序元素的问题

  • 5

我的 xsl:sort 按预期进行排序,但没有提供所需的输出。

这是我的示例输入 xml

<ns3:ASC858_004010 xmlns:ns3="http://sap.com">
<root>
    <name1/>
    <name2/>
    <loops>
        <name3/>
        <loop mode="2">
            <counter>2</counter>
        </loop>
        <loop mode="1">
            <counter>1</counter>
        </loop>
        <name4/>
    </loops>
    <name5/>
</root>
</ns3:ASC858_004010>

我的 xslt 是:

<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:fo="http://www.w3.org/1999/XSL/Format">
<xsl:output method="xml" indent="yes"/>

<xsl:template match="@* | node()">
    <xsl:copy>
        <xsl:apply-templates select="@* | node()"/>
    </xsl:copy>
</xsl:template>

<xsl:template match="loops">
    <xsl:copy>
        <xsl:apply-templates select="loop">
            <xsl:sort select="counter"/>
        </xsl:apply-templates>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>

我正在

<ns3:ASC858_004010 xmlns:ns3="http://sap.com">
<root>
    <name1/>
    <name2/>
    <loops>
        <loop mode="1">
            <counter>1</counter>
        </loop>
        <loop mode="2">
            <counter>2</counter>
        </loop>
    </loops>
    <name5/>
</root>
</ns3:ASC858_004010>

我想要的输出是

<ns3:ASC858_004010 xmlns:ns3="http://sap.com">
<root>
    <name1/>
    <name2/>
    <loops>
        <name3/>
        <loop mode="1">
            <counter>1</counter>
        </loop>
        <loop mode="2">
            <counter>2</counter>
        </loop>
        <name4/>
    </loops>
    <name5/>
</root>
</ns3:ASC858_004010>

name3 和 name4 缺失了。我仅以 name3 和 name4 为例,但在“循环”内的“循环”结构之前和之后可以有更多的元素。

我错过了什么?

sorting
  • 1 个回答
  • 9 Views
Martin Hope
mendax1234
Asked: 2024-11-19 15:04:35 +0800 CST

Kattis Problem Akcija,O(N^2) 排序会导致超出时间限制

  • 5

我正在做 Kattis 问题Akcija

问题陈述

一家书店推出了一项促销活动,每购买三本书,该组中最便宜的一本书将免费赠送。客户可以策略性地将书籍分组,以尽量减少总成本。任务是根据书籍的价格计算客户必须支付的最低价格。每组可以有 1 到 3 本书。

有界条件

输入的第一行包含整数 N (1<N<100 000),表示顾客购买的书籍数量。接下来的 N 行中的每一行都包含一个整数 C_i (1<C_i<100 000),表示每本书的价格。

我的问题

我的想法是先按降序对价格进行排序,然后始终将 3 组中的前两个价格添加到我的总价格中。我认为这个想法在某种程度上是正确的,但我用来排序的算法是冒泡排序,它是 O(N^2)。似乎这会导致超出时间限制。

我不确定 O(N^2) 排序算法是否适合这个问题。有人能帮我吗?我的代码是用 C 编写的。假设非标准输入/输出函数工作正常。

void swap(long a[], long src, long tar)
{
  long temp = a[src];
  a[src] = a[tar];
  a[tar] = temp;
}

void bubble_pass(size_t last, long a[]) {
  for (size_t i = 0; i < last; i += 1) {
    if (a[i] < a[i+1]) {
      swap(a, i, i+1);
    }
  }
}

void bubble_sort(size_t n, long a[n]) {
  for (size_t last = n - 1; last > 0; last -= 1) {
    bubble_pass(last, a);
  }
}

long calc_min_price(size_t n, long a[n])
{
  size_t cur = 0;
  long price = 0;
  for (size_t i = 0; i < n; i += 1)
  {
    if (i % 3 != 2)
    {
      price += a[i];
    }
  }
  return price;
}    

int main()
{
  size_t n = cs1010_read_size_t();
  long *price = cs1010_read_long_array(n);
  if (price == NULL)
  {
    return 1;
  }
  bubble_sort(n, price);
  long min_price = calc_min_price(n, price);
  cs1010_println_long(min_price);
  free(price);
}

我尝试了 O(N^2) 排序算法,但得到了 TLE。不知道问题出在排序算法的效率上还是其他地方。

sorting
  • 1 个回答
  • 19 Views
Martin Hope
Silke
Asked: 2024-11-10 14:59:58 +0800 CST

对单元格内的数字进行排序而不省略 0

  • 5

我想对单个单元格内的数字从小到大进行排序。当前单元格内容为 1、4、0、2、-9、-10,应为 -10、-9、0、1、2、4

我设法对其进行了排序,但是输出中省略了 0,这是一个问题。我如何确保所有内容都已排序?

作为参考,这是我目前使用的公式:

=TEXTJOIN(", ",1,IFERROR(1/(1/SMALL(FILTERXML("<a><b>"&SUBSTITUTE(A5,",","</b><b>")&"</b></a>","//b"),ROW($1:$99))),""))
sorting
  • 1 个回答
  • 33 Views
Martin Hope
samlex
Asked: 2024-10-02 00:53:47 +0800 CST

有没有一种仅使用堆栈来对数据进行排序的有效方法?

  • 6

有没有一种有效的方法,仅使用堆栈对数据进行排序(如果有帮助的话,允许超过 2 个)?

我见过两种堆栈排序,但它们的时间复杂度为 O(n^2)。我想知道是否有使用两个以上堆栈来实现时间复杂度为 O(n log(n)) 的东西。

sorting
  • 1 个回答
  • 21 Views
Martin Hope
andio
Asked: 2024-09-02 15:34:50 +0800 CST

结合 arrayformula() 对字符串进行排序

  • 5

我在列 A 中有此数据,而在列 B 中有我想要的结果: 在此处输入图片描述

我想在 col B 中创建 arrayformula,以便它将从 col A 中获取字符串并对其进行排序。

如果不使用 arrayformula() 那么每行我可以使用这个公式(例如在 B1 列中):

=join(",",sort(tocol(split(A1,","))))

我的问题是如何将它与 arrayformula() 结合起来以自动应用于 col A 中的每个值。我试过这个但没有用:

=ARRAYFORMULA( join(",",sort(tocol(split(A1:A,",")))) )
sorting
  • 1 个回答
  • 33 Views
Martin Hope
andio
Asked: 2024-09-02 02:23:44 +0800 CST

如何对 Google 表格中包含数字列表的字符串进行排序?

  • 5

我在 google sheet 中有这个字符串值 - 在单元格 A1 中:“10,6,9,5”,对 A1 的值进行排序以获得此结果的公式是什么 - > “5,6,9,10”?

我尝试使用这个公式:

=TEXTJOIN(",", TRUE, SORT(VALUE(SPLIT(A1, ","))))

但它不起作用。

sorting
  • 2 个回答
  • 24 Views
Martin Hope
Eric Bayard
Asked: 2024-08-23 22:46:27 +0800 CST

QTreeView Pyside6 未对 QstandardItem 的最后 2 列进行排序

  • 5

我建了一棵树,如图所示。

树形视图图像

我希望树能够对每个列进行排序,这对“井名”列和“深度类型”列有用(我可能有不同的深度类型,称为“深度”、“MD”、“时间”等),但它对任何其他列都不起作用。据我所知,我为每列使用的项目类型没有区别:一个由字符串构建的简单 Qstandard 项目。

该树由嵌套字典和列表填充,形式如下:{well:{depthtype:{logtype:[log1,log2,log3]}}}

使用以下代码

def fillWellTree(self, parent, dico, depth=0):
        if isinstance(dico, dict):
            for key, value in dico.items():
                item1=QStandardItem(str(key))
                item1.setEditable(False)
                itemList=[item1]
                if depth==0:
                    itemList[0].setIcon(QIcon("./icon/IconWell.png"))
                if isinstance(value, dict):
                    for i in range(depth):
                        emptyItem=QStandardItem("")
                        emptyItem.setEditable(False)
                        itemList.insert(0,emptyItem)
                    parent.appendRow(itemList)
                    self.fillWellTree(itemList[0], value, depth+1)
                elif isinstance(value, list):
                    for i in range(depth):
                        emptyItem=QStandardItem("")
                        emptyItem.setEditable(False)
                        itemList.insert(0,emptyItem)
                    parent.appendRow(itemList)
                    for val in value:
                        item_i=QStandardItem(str(val))
                        item_i.setEditable(False)
                        itemLogList=[item_i]
                        for i in range(depth+1):
                            emptyItem=QStandardItem("")
                            emptyItem.setEditable(False)
                            itemLogList.insert(0,emptyItem)
                        itemList[0].appendRow(itemLogList)

我想知道排序是否不起作用,因为最后 2 个填充列(日志类型和日志名称)中包含数据的行的父项有空字符串,所以我用随机字符串替换了空字符串,但它没有改变任何东西谢谢你的帮助和建议

这里编辑是一个工作脚本:

import sys

from PySide6.QtWidgets import QApplication, QTreeView
from PySide6.QtGui import QStandardItem, QStandardItemModel

app = QApplication(sys.argv)

TreeViewLogSelection=QTreeView()
WellModel = QStandardItemModel()
WellModel.setColumnCount(6)
TreeViewLogSelection.setModel(WellModel)
TreeViewLogSelection.model().setHorizontalHeaderLabels(['Well Name','Depth type','Log Type','Log Name','Role','Log unique name'])  
 
def fillWellTree(parent, dico, depth=0):
    if isinstance(dico, dict):
        for key, value in dico.items():
            item1=QStandardItem(str(key))
            item1.setEditable(False)
            itemList=[item1]
            if isinstance(value, dict):
                for i in range(depth):
                    emptyItem=QStandardItem("")
                    emptyItem.setEditable(False)
                    itemList.insert(0,emptyItem)
                parent.appendRow(itemList)
                fillWellTree(itemList[0], value, depth+1)
            elif isinstance(value, list):
                for i in range(depth):
                    emptyItem=QStandardItem("")
                    emptyItem.setEditable(False)
                    itemList.insert(0,emptyItem)
                parent.appendRow(itemList)
                for val in value:
                    item_i=QStandardItem(str(val))
                    item_i.setEditable(False)
                    itemLogList=[item_i]
                    for i in range(depth+1):
                        emptyItem=QStandardItem("")
                        emptyItem.setEditable(False)
                        itemLogList.insert(0,emptyItem)
                    itemList[0].appendRow(itemLogList)   
    TreeViewLogSelection.setSortingEnabled(True)             
dico={'Well-6': {'Depth': {'Sonic': ['DT', 'DTS', 'DTST', 'VPVS', 'DT_REG', 'Smoothing (DT_REG)', 'DT_FINAL'], 'Shallow resistivity': ['LLS', 'MSFL'], 'Bulk density': ['RHOB_RAW', 'RHOB_Predict_RFA', 'RHOB_REG', 'RHOB_DESPIKED', 'RHOB_DESPIKE_REG', 'Smoothing (RHOB_DESPIKE_REG)', 'RHOB_FINAL', 'RHOB_Predict_RF'], 'Shear slowness': ['DTS_Predict_RF', 'DTS_Predict_NN'], 'Deviation': ['DX', 'DY']}, 'MD': {'Sonic': ['DT_Predict_RF','DTS_predict']}}, 'DRILL-1': {'Depth': {'Bit size': ['BS'], 'Caliper': ['CALI'], 'Gamma ray': ['GR'], 'Neutron': ['NPHI'], 'Photoelectric factor': ['PE'], 'Spontaneous potential': ['SP'], 'Shallow resistivity': ['LLS'], 'Deep resistivity': ['LLD'], 'Sonic': ['DT', 'DTS','DTC'], 'Bulk density': ['RHOB'], 'Anonymous': ['WELLTOPS'], 'Badhole indicator': ['Bad_Hole']}}, 'WELLI-1': {'Depth': {'Sonic': ['DT', 'DTS','DTC'], 'Gamma ray': ['GR', 'GR2'], 'Shallow resistivity': ['LLS', 'MSFL'], 'Bulk density': ['RHOB_RAW', 'RHOB_Predict_RF']}, 'MD': {'Sonic': ['DT_Predict_RF', 'DT_Merged', 'DT_FINAL'], 'Impedance': ['AI','IP']}}}
fillWellTree(WellModel.invisibleRootItem(),dico)
TreeViewLogSelection.show()
sys.exit(app.exec())
sorting
  • 1 个回答
  • 28 Views
Martin Hope
Paul-ET
Asked: 2024-08-15 19:53:58 +0800 CST

对树形视图应用程序的第一列进行排序失败

  • 5

我使用了教程中的示例来对树形视图中的列进行排序。它适用于第 2 列和第 3 列,但不适用于第 1 列。如果我单击标题,我会收到此错误:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Python311\Lib\tkinter\__init__.py", line 1967, in __call__
    return self.func(*args)
           ^^^^^^^^^^^^^^^^
  File "D:\...\Test_Treeview_book.py", line 20, in <lambda>
    tv.heading('#0', text='Name', command=lambda: sort(tv, '#0'))
                                                  ^^^^^^^^^^^^^^
  File "D:\...\Test_Treeview_book.py", line 14, in sort
    itemlist.sort(key=lambda x: tv.set(x, col))
  File "D:\...\Test_Treeview_book.py", line 14, in <lambda>
    itemlist.sort(key=lambda x: tv.set(x, col))
                                ^^^^^^^^^^^^^^
  File "C:\Python311\Lib\tkinter\ttk.py", line 1434, in set
    res = self.tk.call(self._w, "set", item, column, value)
          ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
_tkinter.TclError: Display column #0 cannot be set

我有这个小测试程序作为参考,但找不到故障原因。我很感谢任何解决这个问题的提示,或者根本无法对第一列进行排序,因为它是一棵树?

import tkinter as tk
from tkinter import ttk
from pathlib import Path

root = tk.Tk()

root.grid_rowconfigure(0, weight=1)
root.grid_columnconfigure(0, weight=1)

paths = Path('.').glob('**/*')

def sort(tv, col): # Doesn't work on 1st column '#0'
    itemlist = list(tv.get_children(''))
    itemlist.sort(key=lambda x: tv.set(x, col))
    for index, iid in enumerate(itemlist):
        tv.move(iid, tv.parent(iid), index)

tv = ttk.Treeview(root, columns=['size','modified'], selectmode=None)

tv.heading('#0', text='Name', command=lambda: sort(tv, '#0'))
tv.heading('size', text='Size', anchor='center', command=lambda: sort(tv, 'size'))
tv.heading('modified', text='Modifies', anchor='center', command=lambda: sort(tv, 'modified'))

tv.column('#0', stretch = True, anchor='w')
tv.column('size', width=100, anchor='center') 
tv.column('modified',anchor='center')

tv.grid_rowconfigure(0, weight=1)
tv.grid_columnconfigure(0, weight=1) 
tv.grid(row=0, column=0, sticky='nsew')
#tv.pack(expand=True, fill='both')

for path in paths:
    meta = path.stat()
    parent = str(path.parent)
    if parent == '.':
        parent = ''
               
    tv.insert(parent, 'end', iid=str(path), text=str(path.name), values=[meta.st_size, meta.st_mtime])

scrollbar = ttk.Scrollbar(root, orient=tk.VERTICAL, command=tv.yview)
tv.configure(yscrollcommand=scrollbar.set)
scrollbar.grid(row=0, column=1, sticky='nse') #scrollbar goes not to the left!
        
root.mainloop()
sorting
  • 1 个回答
  • 15 Views
Martin Hope
philip
Asked: 2024-03-09 08:49:12 +0800 CST

对 str 引用的引用向量进行排序如何对字符串而不是最外层引用进行排序?

  • 6

在学习时rust,我遇到了嵌入在线问题答案中的这段代码。我没想到这是正确的答案,因为我天真地认为elem_refs.sort()会按向量中的引用而不是字符串进行排序。

为什么 elem_refs.sort() 对字符串进行排序,而不是对字符串的引用(或者更确切地说是&str's)?显然,这很方便并且是期望的结果,但是这种行为记录在哪里?非常感谢您的见解。

fn main() {
    let list = ["b", "d" , "q", "a", "t" ];
    let mut elem_refs: Vec<&&str> = list.iter().collect();
    println!("{:?}", elem_refs);
    elem_refs.sort();
    println!("{:?}", elem_refs);
}

["b", "d", "q", "a", "t"]

["a", "b", "d", "q", "t"]

sorting
  • 2 个回答
  • 27 Views
Martin Hope
Cliff Adams
Asked: 2024-02-11 05:05:07 +0800 CST

在 Google 表格中,使用 IMPORTRANGE 从另一个文件导入列。输入的列包含变音符号,导致使用 ORDER BY 时出现问题

  • 5

我使用 Google Sheets 中的 IMPORTRANGE 与 QUERY 函数结合使用 ORDER BY 从另一个文件导入列。然后,这种排序需要与使用过滤器的正常列排序相匹配。问题是导入的文件包含变音符号,并且这些变音符号无法正确排序,而是将 Ü 放在 Z 后面。

这是我正在使用的公式,除了排序问题外,效果很好:

=QUERY(IMPORTRANGE("aBc....xYz"; "SheetX!E4:M"); "选择 Col1、Col2、Col3、Col9、Col10,其中 Col2 不为空 ORDER BY Col1、Col2、Col3 ASC")

其中 aBc....xYz 是正在导入其数据的文件的文件标识符。问题是,原始工作表包含变音符号(也可能是带有重音符号的字母,如法语、瑞典语、西班牙语等),因此,例如 Ü 被排序在 Z 之后,这与正常排序不匹配。

然后我尝试: =QUERY(IMPORTRANGE("aBc....xYz"; "SheetX!E4:M"); "SELECT Col1, Col2, Col3, Col9, Col10 WHERE Col2 IS NOT NULL ORDER BY REGEXREPLACE(Col1, ' [ÖÜäöü]', '[AOUaou]'), REGEXREPLACE(Col2, '[ÖÜäöü]', '[AOUaou]'), REGEXREPLACE(Col1, '[ÖÜäöü]', '[AOUaou]') ASC")

然后: =QUERY( ARRAYFORMULA(REGEXREPLACE(IMPORTRANGE("aBc....xYz"; "SheetX!E4:M"); "[äÖÜäöü]"; "[AOUaou]")), "SELECT Col1, Col2, Col3 , Col9, Col10,其中 Col2 不为空,按 Col1、Col2、Col3 ASC 排序”

但这些都给了我语法错误。(可能 REGEXREPLACE 不适合查询语法,但 ChatGPT 和 Google Bard 都建议这样做。)我需要已排序的导入数据来匹配正常 Google Sheets 过滤器排序的排序,这似乎可以正确处理变音符号。有谁知道这里的语法错误是什么,或者知道一种更简单的方法来让 ORDER BY 排序与重音符号和变音符号一起正确工作,或者可以想出一些更简单的问题解决方案吗?

sorting
  • 1 个回答
  • 19 Views

Sidebar

Stats

  • 问题 205573
  • 回答 270741
  • 最佳答案 135370
  • 用户 68524
  • 热门
  • 回答
  • Marko Smith

    重新格式化数字,在固定位置插入分隔符

    • 6 个回答
  • Marko Smith

    为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会?

    • 2 个回答
  • Marko Smith

    VScode 自动卸载扩展的问题(Material 主题)

    • 2 个回答
  • Marko Smith

    Vue 3:创建时出错“预期标识符但发现‘导入’”[重复]

    • 1 个回答
  • Marko Smith

    具有指定基础类型但没有枚举器的“枚举类”的用途是什么?

    • 1 个回答
  • Marko Smith

    如何修复未手动导入的模块的 MODULE_NOT_FOUND 错误?

    • 6 个回答
  • Marko Smith

    `(表达式,左值) = 右值` 在 C 或 C++ 中是有效的赋值吗?为什么有些编译器会接受/拒绝它?

    • 3 个回答
  • Marko Smith

    在 C++ 中,一个不执行任何操作的空程序需要 204KB 的堆,但在 C 中则不需要

    • 1 个回答
  • Marko Smith

    PowerBI 目前与 BigQuery 不兼容:Simba 驱动程序与 Windows 更新有关

    • 2 个回答
  • Marko Smith

    AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String”

    • 1 个回答
  • Martin Hope
    Fantastic Mr Fox msvc std::vector 实现中仅不接受可复制类型 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant 使用 chrono 查找下一个工作日 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor 构造函数的成员初始化程序可以包含另一个成员的初始化吗? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský 为什么 C++20 概念会导致循环约束错误,而老式的 SFINAE 不会? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul C++20 是否进行了更改,允许从已知绑定数组“type(&)[N]”转换为未知绑定数组“type(&)[]”? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann 为什么 {2,3,10} 和 {x,3,10} (x=2) 的顺序不同? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller 在 5.2 版中,bash 条件语句中的 [[ .. ]] 中的分号现在是可选的吗? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench 为什么双破折号 (--) 会导致此 MariaDB 子句评估为 true? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng 为什么 `dict(id=1, **{'id': 2})` 有时会引发 `KeyError: 'id'` 而不是 TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob:MobileAds.initialize() - 对于某些设备,“java.lang.Integer 无法转换为 java.lang.String” 2024-03-20 03:12:31 +0800 CST

热门标签

python javascript c++ c# java typescript sql reactjs html

Explore

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

Footer

AskOverflow.Dev

关于我们

  • 关于我们
  • 联系我们

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve