### Dictionary Get and Setdefault Methods Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Use `get` to retrieve values with a default if the key is missing. `setdefault` inserts a value only if the key does not exist. ```python filled_dict.get("one", 4) # => 1 filled_dict.get("four", 4) # => 4 ``` ```python filled_dict.setdefault("five", 5) # filled_dict["five"]设为5 filled_dict.setdefault("five", 6) # filled_dict["five"]还是5 ``` -------------------------------- ### Generate Graph Test Data with CYaRon Source: https://github.com/luogu-dev/cyaron/blob/master/README.md This example demonstrates how to generate test data for a graph problem. It sets up input files, defines graph parameters, generates a random graph with weighted edges, and uses a standard solution executable to produce output files. ```python #!/usr/bin/env python from cyaron import * # 引入CYaRon的库 _n = ati([0, 7, 50, 1E4]) # ati函数将数组中的每一个元素转换为整形,方便您可以使用1E4一类的数来表示数据大小 _m = ati([0, 11, 100, 1E4]) # 这是一个图论题的数据生成器,该题目在洛谷的题号为P1339 for i in range(1, 4): # 即在[1, 4)范围内循环,也就是从1到3 test_data = IO(file_prefix="heat", data_id=i) # 生成 heat[1|2|3].in/out 三组测试数据 n = _n[i] # 点数 m = _m[i] # 边数 s = randint(1, n) # 源点,随机选取一个 t = randint(1, n) # 汇点,随机选取一个 test_data.input_writeln(n, m, s, t) # 写入到输入文件里,自动以空格分割并换行 graph = Graph.graph(n, m, weight_limit=5) # 生成一个n点,m边的随机图,边权限制为5 test_data.input_writeln(graph) # 自动写入到输入文件里,默认以一行一组u v w的形式输出 test_data.output_gen("D:\\std_binary.exe") # 标程编译后的可执行文件,不需要freopen等,CYaRon自动给该程序输入并获得输出作为.out ``` -------------------------------- ### Accessing and Generating Sequence Elements Source: https://github.com/luogu-dev/cyaron/wiki/序列-Sequence Shows how to retrieve specific elements or ranges of elements from a Sequence object. The `get` method can fetch a single element or a list of elements starting from a given index. ```python seq = Sequence(lambda i, f: f(i-1) + 2, [0, 2, 4]) seq.get(3) # 6 ``` ```python seq.get(4, 6) # [8, 10, 12] ``` ```python io.input_write(seq.get(7, 10)) # 可以直接传递给IO库,写入14 16 18 20 ``` -------------------------------- ### Iterate and Output Graph Edges Source: https://github.com/luogu-dev/cyaron/wiki/图-Graph Shows how to access and iterate over all edges in a graph. Each edge object provides access to its start node, end node, and weight. Includes methods for printing the graph in different formats. ```python graph.edges # 一个邻接表数组,每一维度i保存的是i点出发的所有边,以Edge对象存储 for edge in graph.iterate_edges(): # 遍历所有边,其中edge内保存的也是Edge对象 edge.start # 获取这条边的起点 edge.end # 获取这条边的终点 edge.weight # 获取这条边的边权 io.input_writeln(edge) # 输出这条边,以u v w的形式 io.input_writeln(graph) # 输出这个图,以每条边u v w一行的格式 io.input_writeln(graph.to_str(shuffle=True)) # 打乱边的顺序并输出这个图 io.input_writeln(graph.to_str(output=my_func)) # 使用my_func函数替代默认的输出函数,请查看源代码以理解使用方法 io.input_writeln(graph.to_str(output=Edge.unweighted_edge)) # 输出无权图,以每条边u v一行的格式 ``` -------------------------------- ### Initialize IO with different file naming strategies Source: https://github.com/luogu-dev/cyaron/wiki/输入输出-IO Demonstrates various ways to initialize the IO object, specifying input and output file names, prefixes, data IDs, and custom suffixes. Can also disable output file creation or use temporary files. ```python IO("test1.in", "test1.out") # test1.in, test1.out ``` ```python IO(file_prefix="test") # test.in, test.out ``` ```python IO(file_prefix="test", data_id=3) # test3.in, test3.out ``` ```python IO(file_prefix="test", data_id=6, input_suffix=".input", output_suffix=".answer") # test6.input, test6.answer ``` ```python IO("test2.in") # test2.in, .out文件生成为临时文件 ``` ```python IO(file_prefix="test", data_id=5, disable_output=True) # test5.in, 不建立.out ``` ```python IO() # .in, .out文件均生成为临时文件,一般配合对拍器使用 ``` -------------------------------- ### IO Constructor Overloads Source: https://github.com/luogu-dev/cyaron/wiki/输入输出-IO Demonstrates the different ways to initialize the IO object, specifying input and output file names, prefixes, data IDs, and suffixes. It also covers options to disable output files or use temporary files. ```APIDOC ## IO Constructor Overloads ### Description Initializes the IO object with various configurations for input and output files. ### Usage ```python IO("test1.in", "test1.out") # Specifies input and output file names IO(file_prefix="test") # Uses a prefix to generate 'test.in' and 'test.out' IO(file_prefix="test", data_id=3) # Uses prefix and data_id for 'test3.in', 'test3.out' IO(file_prefix="test", data_id=6, input_suffix=".input", output_suffix=".answer") # Custom suffixes IO("test2.in") # Input file specified, output file becomes temporary IO(file_prefix="test", data_id=5, disable_output=True) # Input file specified, output disabled IO() # Both input and output files are temporary ``` ``` -------------------------------- ### First-Class Functions and Closures Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Functions are first-class objects in Python, meaning they can be assigned to variables, passed as arguments, and returned from other functions. This example demonstrates a closure. ```python # 函数在Python是一等公民 def create_adder(x): def adder(y): return x + y return adder add_10 = create_adder(10) add_10(3) # => 13 ``` -------------------------------- ### Creating Sequences with Lambda Functions Source: https://github.com/luogu-dev/cyaron/wiki/序列-Sequence Demonstrates different ways to initialize a Sequence using lambda functions. The first argument defines the sequence's rule, and the second (optional) argument provides initial values. ```python Sequence(lambda i, f: 2*i+1) # f(i)=2*i+1 ``` ```python Sequence(lambda i, f: f(i-1) + 1, [0, 1]) # f(i)=f(i-1)+1, f(0)=0, f(1)=1 ``` ```python Sequence(lambda i, f: f(i-1) + 1, {100: 101, 102: 103}) # f(i)=f(i-1)+1, f(100)=101, f(102)=103 ``` -------------------------------- ### Import and Use Math Module in Python Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Shows how to import the 'math' module to use its functions like 'sqrt'. You can import the entire module, specific functions, or all functions. Aliasing is also demonstrated. ```python import math print(math.sqrt(16)) ``` ```python from math import ceil, floor print(ceil(3.7)) print(floor(3.7)) ``` ```python from math import * ``` ```python import math as m math.sqrt(16) == m.sqrt(16) ``` ```python import math dir(math) ``` -------------------------------- ### Manually Create and Add Edges to a Graph Source: https://github.com/luogu-dev/cyaron/wiki/图-Graph Demonstrates how to initialize a graph with a specified number of nodes and add edges manually. Supports both directed and undirected graphs, with optional weights. ```python graph = Graph(10) # 建立一个10个节点的无向图 graph = Graph(10, directed=True) # 建立一个10个节点的有向图 # 这两个图的节点编号范围都为1到10 graph.add_edge(1, 5) # 建立一条从1到5,权值为1的边,若是无向图,还会建立从5到1的边 graph.add_edge(1, 6, weight=3) # 建立一条从1到6,权值为3的边,若是无向图,还会建立从6到1的边 ``` -------------------------------- ### Generate output by executing external programs Source: https://github.com/luogu-dev/cyaron/wiki/输入输出-IO Demonstrates how to use `output_gen` to execute a shell command or a binary executable, feeding it the input file's content via stdin and capturing its stdout as the output. Supports both Linux and Windows paths. ```python io.output_gen("~/Documents/std") # 执行shell命令或二进制文件,把输入文件的内容通过stdin送入,获得stdout的内容生成输出 ``` ```python io.output_gen("C:\\Users\\Aqours\\std.exe") # 当然Windows也可以 ``` -------------------------------- ### Python Dictionaries: Key-Value Mappings Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Explains dictionaries for storing key-value pairs. Shows how to create empty and initialized dictionaries, access values by key, retrieve keys and values using `.keys()` and `.values()`, and check for key existence using `in` or `.get()` to avoid `KeyError`. ```python # 用字典表达映射关系 empty_dict = {} # 初始化的字典 filled_dict = {"one": 1, "two": 2, "three": 3} # 用[]取值 filled_dict["one"] # => 1 # 用keys获得所有的键。因为keys返回一个可迭代对象,所以在这里把结果包在list里。我们下面会详细介绍可迭代。 # 注意:字典键的顺序是不定的,你得到的结果可能和以下不同。 list(filled_dict.keys()) # => ["three", "two", "one"] # 用values获得所有的值。跟keys一样,要用list包起来,顺序也可能不同。 list(filled_dict.values()) # => [3, 2, 1] # 用in测试一个字典是否包含一个键 "one" in filled_dict # => True 1 in filled_dict # => False # 访问不存在的键会导致KeyError filled_dict["four"] # KeyError # 用get来避免KeyError filled_dict.get("one") # => 1 filled_dict.get("four") # => None ``` -------------------------------- ### 对拍输出文件 Source: https://github.com/luogu-dev/cyaron/wiki/对拍器-Compare 使用Compare.output比较两个输出文件的内容,可指定标准输出文件或IO对象作为标准。 ```python # 默认比较器为NOIP风格,忽略最后空行和行尾空格 Compare.output("1.out", "2.out", std="std.out") # 以std.out为标准,对比1.out和2.out的正确性 std_io = IO() std_io.output_writeln(1, 2, 3) # 往std_io的output里写入一些东西 Compare.output("1.out", "2.out", std=std_io) # 以std_io这个IO对象中的output为标准,对拍1.out和2.out, ``` -------------------------------- ### 对拍程序 Source: https://github.com/luogu-dev/cyaron/wiki/对拍器-Compare 使用Compare.program对程序进行对拍,可指定输入IO对象或文件,并以标准程序输出或文件作为标准。 ```python input_io = IO() input_io.input_write("1111\n") Compare.program("a.exe", input=input_io, std_program="std.exe") # 以input_io这个IO对象中的input为stdin输入。 # std.exe的输出为标准输出,以此为标准对拍a.exe的输出。 Compare.program("a.exe", "b.exe", input=input_io, std_program="std.exe") # 和上面的方法类似,但是你可以以std.exe为标准对拍多个程序输出。 Compare.program("a.exe", "b.exe", "c.exe", input="data.in", std="std.out") # 当然input也可以简单地是文件,并以std.out这个输出文件的内容来对a.exe, b.exe, c.exe对拍。 # 这里std也可以是IO对象。 while True: input_io = IO() input_io.input_writeln(randint(1,100)) Compare.program("a.exe", "b.exe", input=input_io, std_program="std.exe") # 不断地生成测试数据(这里是1到100的随机数),然后放到a.exe,b.exe中,分别以std.exe为标准进行对拍比较 # CYaRon 现在使用多线程比较器,原 stop_on_incorrect 参数现已 deprecated 且无实际作用。 ``` -------------------------------- ### Compare Program Outputs with Standard Output Source: https://context7.com/luogu-dev/cyaron/llms.txt Compares the output of multiple executable files against a standard output file. Requires pre-generated standard output. ```python with IO(file_prefix="test", data_id=1) as test: n = randint(1, 100) test.input_writeln(n) test.output_gen("./std") # 先用标准程序生成标准输出 # 对拍:brute.exe 和 fast.exe 的输出都与 test 的输出比较 Compare.output( "./brute_output.txt", "./fast_output.txt", std=test, ) ``` -------------------------------- ### Use Imported Random Functions Source: https://context7.com/luogu-dev/cyaron/llms.txt Demonstrates the direct use of imported random functions like randint, uniform, and choice. ```python # randint / random / choice 已从 random 模块导入,可直接使用 x = randint(1, 100) val = uniform(0.0, 1.0) item = choice([1, 2, 3, 4, 5]) ``` -------------------------------- ### Manage Input/Output Files with IO Source: https://context7.com/luogu-dev/cyaron/llms.txt The IO class handles test data file creation (.in/.out), batch generation using prefixes, automatic output generation via standard programs, and manual output writing. It supports disabling output files and specifying custom filenames. ```python from cyaron import * # 生成 3 组测试数据:heat1.in/out, heat2.in/out, heat3.in/out _n = ati([0, 7, 50, int(1e4)]) _m = ati([0, 11, 100, int(1e4)]) for i in range(1, 4): with IO(file_prefix="heat", data_id=i) as test: n, m = _n[i], _m[i] s, t = randint(1, n), randint(1, n) # 写入输入:自动以空格分隔,末尾换行 test.input_writeln(n, m, s, t) # 生成随机带权图并写入 graph = Graph.graph(n, m, weight_limit=10) test.input_writeln(graph) # 调用标准程序(可执行文件)生成输出,支持时间限制(秒) test.output_gen("./std", time_limit=2.0) # 也可以手动指定文件名,或禁用输出文件 with IO("data.in", "data.out") as test: test.input_writeln(5, 3) test.output_writeln(8) # 手动写输出 # 仅生成输入文件(disable_output=True) with IO(file_prefix="input_only", data_id=1, disable_output=True) as test: test.input_writeln(100) ``` -------------------------------- ### IO Methods for Writing Data Source: https://github.com/luogu-dev/cyaron/wiki/输入输出-IO Explains methods to write data to the input and output files. Supports writing individual elements, lists, and specifying custom separators. ```APIDOC ## IO Methods for Writing Data ### Description Methods to write data to the input and output files. ### Usage ```python io = IO("test1.in", "test1.out") io.input_write(1, 2, 3) # Writes '1 2 3' to the input file io.input_writeln(4, 5, 6) # Writes '4 5 6' followed by a newline to the input file io.output_write(1, 2, 3) # Writes '1 2 3' to the output file io.output_writeln(4, 5, 6) # Writes '4 5 6' followed by a newline to the output file io.input_write([1, 2, 3]) # Writes '[1, 2, 3]' to the input file io.output_write(1, 2, [1, 2, 3], [4]) # Writes '1 2 1 2 3 4' to the output file io.input_write(1, 2, 3, separator=',') # Writes '1,2,3,' to the input file (note: trailing separator behavior may change) ``` ``` -------------------------------- ### Write data to input and output files Source: https://github.com/luogu-dev/cyaron/wiki/输入输出-IO Shows how to write various data types, including numbers and lists, to input and output files. Supports writing with and without newlines, and custom separators. Note: a trailing separator may be added. ```python io = IO("test1.in", "test1.out") # 先新建一组数据 ``` ```python io.input_write(1, 2, 3) # 写入1 2 3到输入文件 ``` ```python io.input_writeln(4, 5, 6) # 写入4 5 6到输入文件并换行 ``` ```python io.output_write(1, 2, 3) # 写入1 2 3到输出文件 ``` ```python io.output_writeln(4, 5, 6) # 写入4 5 6到输出文件并换行 ``` ```python io.input_write([1, 2, 3]) # 写入1 2 3到输入文件 ``` ```python io.output_write(1, 2, [1, 2, 3], [4]) # 写入1 2 1 2 3 4到输出文件 ``` ```python io.input_write(1, 2, 3, separator=',') # 写入1,2,3,到输入文件,目前版本尾部会多一个逗号,之后可能修改行为 ``` -------------------------------- ### Define a Class with Methods and Attributes in Python Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Demonstrates how to define a class 'Human' with class attributes, an initializer, instance methods, class methods, and static methods. Use this for object-oriented programming. ```python class Human(object): species = "H. sapiens" def __init__(self, name): self.name = name def say(self, msg): return "{name}: {message}".format(name=self.name, message=msg) @classmethod def get_species(cls): return cls.species @staticmethod def grunt(): return "*grunt*" i = Human(name="Ian") print(i.say("hi")) j = Human("Joel") print(j.say("hello")) i.get_species() Human.species = "H. neanderthalensis" i.get_species() j.get_species() Human.grunt() ``` -------------------------------- ### 创建和操作多边形 Source: https://github.com/luogu-dev/cyaron/wiki/多边形-Polygon 使用Polygon库创建多边形,并计算其周长和面积。注意点需要按照连线顺序输入。 ```python p = Polygon([(0,0), (0,4), (4,4), (4,0)]) # 以这四个点生成四边形,注意点需要按照连线顺序 p.perimeter() # 周长 p.area() # 面积 io.input_writeln(p) ``` -------------------------------- ### Directly Compare Multiple Programs Source: https://context7.com/luogu-dev/cyaron/llms.txt Directly compares the outputs of multiple programs without pre-generating a standard output file. Supports setting timeouts for programs. ```python with IO(file_prefix="test", data_id=2) as test: test.input_writeln(randint(1, 50)) Compare.program( "./brute", "./fast", ["./fast_with_timeout", 2], # 带超时限制(秒) input=test, std_program="./std", # 标准程序 ) # 若任一程序输出不符,抛出 CompareMismatch 异常 ``` -------------------------------- ### Generate Graphs for SPFA Algorithm Testing Source: https://github.com/luogu-dev/cyaron/wiki/图-Graph Creates graphs specifically designed to challenge the SPFA (Shortest Path Faster Algorithm) by having a particular edge density and structure. Allows for adding extra edges to increase complexity. ```python graph = Graph.hack_spfa(n) # 生成一个n点,1.5*n(下取整)边的图,具有卡SPFA的特点 graph = Graph.hack_spfa(n, extra_edge=m) # 生成一个n点,1.5*n+m(下取整)边的图,具有卡SPFA的特点 # 下列方法生成的图保证连通 # 支持 self_loop, repeated_edges, weight_limit, weight_gen 参数,但不支持 directed,DAG 的 self_loop 默认为 False ``` -------------------------------- ### Python Booleans and Comparison Operators Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Illustrates Python's boolean values (True, False) and logical operators (not, and, or). It also shows how integers can be treated as booleans and demonstrates various comparison operators. ```python # 布尔值 True False # 用not取非 not True # => False not False # => True # 逻辑运算符,注意and和or都是小写 True and False #=> False False or True #=> True # 整数也可以当作布尔值 0 and 2 #=> 0 -5 or 0 #=> -5 0 == False #=> True 2 == True #=> False 1 == True #=> True # 用==判断相等 1 == 1 # => True 2 == 1 # => False # 用!=判断不等 1 != 1 # => False 2 != 1 # => True # 比较大小 1 < 10 # => True 1 > 10 # => False 2 <= 2 # => True 2 >= 2 # => True # 大小比较可以连起来! 1 < 2 < 3 # => True 2 < 3 < 2 # => False ``` -------------------------------- ### 生成不重复二维向量 Source: https://github.com/luogu-dev/cyaron/wiki/向量-Vector 生成指定数量、指定维度和取值范围的不重复二维向量。第一维取值范围为[10,50],第二维取值范围为[0,20]。 ```python output = Vector.random(30, [(10,50), 20]) #生成30个第一维范围[10,50]之间、第二维范围在[0,20]之间的不重复的二维向量。 ``` -------------------------------- ### Python Lists: Creation, Manipulation, and Slicing Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Covers the creation of lists, appending and popping elements, accessing elements by index (including negative indexing), list slicing, deleting elements with `del`, extending lists, and checking for membership with `in`. ```python # 用列表(list)储存序列 li = [] # 创建列表时也可以同时赋给元素 other_li = [4, 5, 6] # 用append在列表最后追加元素 li.append(1) # li现在是[1] li.append(2) # li现在是[1, 2] li.append(4) # li现在是[1, 2, 4] li.append(3) # li现在是[1, 2, 4, 3] # 用pop从列表尾部删除 li.pop() # => 3 且li现在是[1, 2, 4] # 把3再放回去 li.append(3) # li变回[1, 2, 4, 3] # 列表存取跟数组一样 li[0] # => 1 # 取出最后一个元素 li[-1] # => 3 # 越界存取会造成IndexError li[4] # 抛出IndexError # 列表有切割语法 li[1:3] # => [2, 4] # 取尾 li[2:] # => [4, 3] # 取头 li[:3] # => [1, 2, 4] # 隔一个取一个 li[::2] # =>[1, 4] # 倒排列表 li[::-1] # => [3, 4, 2, 1] # 可以用三个参数的任何组合来构建切割 # li[始:终:步伐] # 用del删除任何一个元素 del li[2] # li is now [1, 2, 3] # 列表可以相加 # 注意:li和other_li的值都不变 li + other_li # => [1, 2, 3, 4, 5, 6] # 用extend拼接列表 li.extend(other_li) # li现在是[1, 2, 3, 4, 5, 6] # 用in测试列表是否包含值 1 in li # => True # 用len取列表长度 len(li) # => 6 ``` -------------------------------- ### IO Method for Output Generation Source: https://github.com/luogu-dev/cyaron/wiki/输入输出-IO Details the `output_gen` method, which executes a specified command or binary, feeding it the input file's content via stdin and capturing its stdout to generate the output file. ```APIDOC ## IO Method for Output Generation ### Description Executes an external command or binary to generate the output file. ### Usage ```python io = IO("test1.in", "test1.out") io.output_gen("~/Documents/std") # Executes a shell command or binary, using stdin/stdout io.output_gen("C:\\Users\\Aqours\\std.exe") # Example for Windows executable ``` ``` -------------------------------- ### Generate Range Queries with Weights Source: https://context7.com/luogu-dev/cyaron/llms.txt Generates range queries with associated random weights. The weight generator function can be customized. ```python # 带权重的查询(每条查询附加一个随机权重) Q4 = RangeQuery.random( 5, [(1, 100)], weight_generator=lambda idx, l, r: (randint(1, 1000),) ) ``` -------------------------------- ### Generate Graph with Specified Parameters Source: https://github.com/luogu-dev/cyaron/wiki/图-Graph Provides template functions to generate graphs with specific properties like number of nodes and edges, directedness, weight limits, and custom weight generation functions. Also supports disallowing self-loops and repeated edges. ```python graph = Graph.graph(n, m) # 生成一个n点,m边的无向图,边权均为1 graph = Graph.graph(n, m, directed=True, weight_limit=(5, 300)) # 生成一个n点,m边的有向图,边权范围是5到300 graph = Graph.graph(n, m, weight_limit=20) # 生成一个n点,m边的无向图,边权范围是1到20 graph = Graph.graph(n, m, weight_gen=my_func) # 生成一个n点,m边的无向图,使用自定义随机函数my_func的返回值作为边权 graph = Graph.graph(n, m, self_loop=False, repeated_edges=False) # 生成一个n点,m边的无向图,禁止重边和自环 # 以上的directed, weight_limit, weight_gen参数,对如下的所有函数都有效。 ``` -------------------------------- ### 生成不重复数字数列 Source: https://github.com/luogu-dev/cyaron/wiki/向量-Vector 生成指定数量、指定范围的不重复数字数列。当position_range只有一个元素时,生成的是一维数列。 ```python output = Vector.random() #默认值,随机生成5个[0,10]的不重复数字的数列。 ``` ```python output = Vector.random(10, [(10,50)]) #生成10个范围在[10,50]之间的不重复数字数列。 ``` -------------------------------- ### Python Tuples: Immutable Sequences Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Introduces tuples as immutable sequences. Shows how to create them, access elements, and perform operations like concatenation and slicing, similar to lists but without modification. ```python # 元组是不可改变的序列 tup = (1, 2, 3) tup[0] # => 1 tup[0] = 3 # 抛出TypeError # 列表允许的操作元组大都可以 len(tup) # => 3 tup + (4, 5, 6) # => (1, 2, 3, 4, 5, 6) tup[:2] # => (1, 2) 2 in tup # => True # 可以把元组合列表解包,赋值给变量 a, b, c = (1, 2, 3) # 现在a是1,b是2,c是3 # 元组周围的括号是可以省略的 d, e, f = 4, 5, 6 # 交换两个变量的值就这么简单 e, d = d, e # 现在d是5,e是4 ``` -------------------------------- ### Set Initialization and Operations Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Initialize sets using `set()` or curly braces, noting that duplicates are automatically removed. Perform set operations like intersection (`&`), union (`|`), and difference (`-`). ```python empty_set = set() # 初始化一个集合,语法跟字典相似。 some_set = {1, 1, 2, 2, 3, 4} # some_set现在是{1, 2, 3, 4} ``` ```python filled_set = some_set ``` ```python filled_set.add(5) # filled_set现在是{1, 2, 3, 4, 5} ``` ```python # & 取交集 other_set = {3, 4, 5, 6} filled_set & other_set # => {3, 4, 5} ``` ```python # | 取并集 filled_set | other_set # => {1, 2, 3, 4, 5, 6} ``` ```python # - 取补集 {1, 2, 3, 4} - {2, 3, 5} # => {1, 4} ``` ```python # in 测试集合是否包含元素 2 in filled_set # => True 10 in filled_set # => False ``` -------------------------------- ### 生成不重复整数向量 Source: https://github.com/luogu-dev/cyaron/wiki/向量-Vector 用于生成指定数量、指定维度和取值范围的不重复整数向量。默认生成5个1维向量,取值范围为[0,10]。 ```python list Vector.random(num=5, position_range=[10], mode=0) ``` -------------------------------- ### 生成随机多边形 Source: https://github.com/luogu-dev/cyaron/wiki/多边形-Polygon 使用Polygon库的模板生成随机多边形,包括N个点的凸包和简单多边形。 ```python p = Polygon.convex_hull(n) # 生成一个N个点的凸包 p = Polygon.simple_polygon(n) # 生成一个N个点的简单多边型 ``` -------------------------------- ### Function Definition and Calling Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Define functions using `def`, specify parameters, and return values using `return`. Functions can be called with positional or keyword arguments. ```python # 用def定义新函数 def add(x, y): print("x is {} and y is {}".format(x, y)) return x + y # 用return语句返回 # 调用函数 add(5, 6) # => 印出"x is 5 and y is 6"并且返回11 # 也可以用关键字参数来调用函数 add(y=6, x=5) # 关键字参数可以用任何顺序 ``` -------------------------------- ### Python Comments and Basic Data Types Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Demonstrates single-line and multi-line comments, integers, floating-point numbers, and basic arithmetic operations in Python. Note that division automatically results in a float. ```python # 用井字符开头的是单行注释 """ 多行字符串用三个引号 包裹,也常被用来做多 行注释 """ #################################################### ## 1. 原始数据类型和运算符 #################################################### # 整数 3 # => 3 # 算术没有什么出乎意料的 1 + 1 # => 2 8 - 1 # => 7 10 * 2 # => 20 # 但是除法例外,会自动转换成浮点数 35 / 5 # => 7.0 5 / 3 # => 1.6666666666666667 # 整数除法的结果都是向下取整 5 // 3 # => 1 5.0 // 3.0 # => 1.0 # 浮点数也可以 -5 // 3 # => -2 -5.0 // 3.0 # => -2.0 # 浮点数的运算结果也是浮点数 3 * 2.0 # => 6.0 # 模除 7 % 3 # => 1 # x的y次方 2**4 # => 16 # 用括号决定优先级 (1 + 3) * 2 # => 8 ``` -------------------------------- ### 将数组元素转换为整数 - ati Source: https://github.com/luogu-dev/cyaron/wiki/工具函数 当使用科学计数法定义数据范围时,例如 `1E5`,Python 会将其解析为浮点数。`ati` 函数可将数组中的每个元素转换为整数类型,以避免潜在的精度问题。 ```python _n = ati([0, 5, 100, 1E3, 1E5]) ``` -------------------------------- ### Write Range Queries to IO Source: https://context7.com/luogu-dev/cyaron/llms.txt Writes generated range queries to an IO object for input files. Allows control over the probability of generating large queries. ```python with IO(file_prefix="range_query", data_id=1) as test: n, q = 100000, 50000 test.input_writeln(n, q) queries = RangeQuery.random(q, [(1, n)], big_query=0.3) test.input_writeln(queries) ``` -------------------------------- ### 生成实数向量 Source: https://github.com/luogu-dev/cyaron/wiki/向量-Vector 生成指定数量、指定维度和取值范围的实数向量。每一维的取值范围均为[1,10]。 ```python output = Vector.random(30, [(1,10), (1,10), (1,10)], 2) #生成30个每一维范围[1,10]之间的三维实数向量。 ``` -------------------------------- ### Implement Generators for Lazy Evaluation in Python Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Illustrates how to use generators with the 'yield' keyword for lazy computation. This is memory-efficient for large sequences like ranges. ```python def double_numbers(iterable): for i in iterable: yield i + i range_ = range(1, 900000000) for i in double_numbers(range_): print(i) if i >= 30: break ``` -------------------------------- ### 生成指定范围内的随机浮点数 - uniform Source: https://github.com/luogu-dev/cyaron/wiki/工具函数 此函数是 `random.uniform` 的别名,用于生成一个包含指定范围两端值的随机浮点数。 ```python uniform(1, 5) # float in [1, 5] ``` -------------------------------- ### Exception Handling with Try/Except/Else Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Handle potential errors using `try`, `except`, and `else` blocks. `raise` is used to explicitly throw an exception. `pass` is a null operation. ```python # 用try/except块处理异常状况 try: # 用raise抛出异常 raise IndexError("This is an index error") except IndexError as e: pass # pass是无操作,但是应该在这里处理错误 except (TypeError, NameError): pass # 可以同时处理不同类的错误 else: # else语句是可选的,必须在所有的except之后 print("All good!") # 只有当try运行完没有错误的时候这句才会运行 ``` -------------------------------- ### IO Class Source: https://context7.com/luogu-dev/cyaron/llms.txt The IO class manages input/output files for test data, supporting automatic output generation via standard programs and manual output writing. ```APIDOC ## IO Class ### Description The `IO` class is responsible for creating and managing test data's `.in` / `.out` files. It supports batch generation using file prefixes, automatic output generation by calling standard programs, and manual writing of output content. ### Usage ```python from cyaron import * # Generate 3 sets of test data: heat1.in/out, heat2.in/out, heat3.in/out _n = ati([0, 7, 50, int(1e4)]) _m = ati([0, 11, 100, int(1e4)]) for i in range(1, 4): with IO(file_prefix="heat", data_id=i) as test: n, m = _n[i], _m[i] s, t = randint(1, n), randint(1, n) # Write input: automatically separated by spaces, ending with a newline test.input_writeln(n, m, s, t) # Generate a random weighted graph and write it graph = Graph.graph(n, m, weight_limit=10) test.input_writeln(graph) # Call the standard program (executable) to generate output, with time limit (seconds) test.output_gen("./std", time_limit=2.0) # You can also specify filenames manually, or disable output files with IO("data.in", "data.out") as test: test.input_writeln(5, 3) test.output_writeln(8) # Manually write output # Generate only input files (disable_output=True) with IO(file_prefix="input_only", data_id=1, disable_output=True) as test: test.input_writeln(100) ``` ``` -------------------------------- ### Generate Simple Polygon Source: https://context7.com/luogu-dev/cyaron/llms.txt Creates a simple polygon from a list of points. Ensure the points define a valid polygon. ```python pts = [[0,0],[4,0],[4,3],[2,5],[0,3]] simple_poly = Polygon.simple_polygon(pts) ``` -------------------------------- ### Process Command Line Arguments for Random Seed Source: https://context7.com/luogu-dev/cyaron/llms.txt Reads the random seed from command line arguments to ensure reproducible data generation. Run with --randseed=N. ```python # process_args:从命令行参数读取随机种子,保证可复现 # 运行方式:python gen.py --randseed=42 process_args() ``` -------------------------------- ### 生成允许重复的整数数列 Source: https://github.com/luogu-dev/cyaron/wiki/向量-Vector 生成指定数量、指定范围的随机数数列,允许出现重复的数字。取值范围为[0,10]。 ```python output = Vector.random(30, [10], 1) #生成30个[0,10]之间的随机数,当然肯定会有重复咯。 ``` -------------------------------- ### List Anti-Primes up to N Source: https://context7.com/luogu-dev/cyaron/llms.txt Generates a list of anti-primes (highly composite numbers) up to a specified limit. ```python # 反素数(高度合成数)列表 print(anti_primes_up_to(100)) # [1, 2, 4, 6, 12, 24, 36, 48, 60] ``` -------------------------------- ### Generate Random Tree Structures Source: https://github.com/luogu-dev/cyaron/wiki/图-Graph Functions to generate random trees. Supports creating a general random tree, a random binary tree, and trees with specific structural properties (e.g., percentage of chain-like or star-like nodes). ```python tree = Graph.tree(n) # 生成一棵n个节点的随机树 tree = Graph.tree(n, 0.4, 0.35) # 生成一棵n个节点的树,其中40%的节点呈现链状,35%的节点呈现菊花图状,剩余25%的节点随机加入 binary_tree = Graph.binary_tree(n) # 生成一棵n个节点的随机二叉树 binary_tree = Graph.binary_tree(n, 0.4, 0.35) # 生成一棵n个节点的二叉树,其中节点有40%的概率是左儿子,35%的概率是右儿子,25%的概率被随机选择 ``` -------------------------------- ### 使用其他比较器 Source: https://github.com/luogu-dev/cyaron/wiki/对拍器-Compare 通过grader参数指定内置或自定义比较器,如FullText。 ```python Compare.program("a.exe", input=input_io, std_program="std.exe", grader="FullText") ``` -------------------------------- ### 展平向量输出 Source: https://github.com/luogu-dev/cyaron/wiki/向量-Vector 当生成的是一维向量(数列)时,默认输出为嵌套列表。此代码用于将嵌套列表展平成一维列表。 ```python sum(output,[]) ``` -------------------------------- ### List Comprehensions Source: https://github.com/luogu-dev/cyaron/wiki/Python-30分钟入门指南 Create lists concisely using list comprehensions, which provide a compact syntax for mapping and filtering operations on iterables. ```python # 用列表推导式可以简化映射和过滤。列表推导式的返回值是另一个列表。 [add_10(i) for i in [1, 2, 3]] # => [11, 12, 13] [x for x in [3, 4, 5, 6, 7] if x > 5] # => [6, 7] ``` -------------------------------- ### 生成 [0, 1) 范围内的随机浮点数 - random Source: https://github.com/luogu-dev/cyaron/wiki/工具函数 此函数是 `random.random` 的别名,用于生成一个大于等于 0 且小于 1 的随机浮点数。 ```python random() # float in [0, 1) ```