编写有返回值的函数:深入理解hard_real_time_computing_systems

需积分: 50 31 下载量 89 浏览量 更新于2024-08-07 收藏 2.71MB PDF 举报
"《有返回值的函数》章节来自《像计算机科学家一样思考》(ThinkPython),该书讲述了如何在编程中使用有返回值的函数,特别是如何在Python中实现和利用这种函数特性。" 在计算机编程中,函数是执行特定任务的代码块,它可以接收输入参数并产生输出。在本章“有返回值的函数-hard_real-time_computing_systems”中,主要讨论的是那些能够返回结果的函数,与之前介绍的仅执行操作但不返回任何值的空函数(void函数)有所区别。 6.1 返回值部分介绍了如何通过`return`语句在函数中创建返回值。例如,当调用`math.exp(1.0)`或`radius * math.sin(radians)`时,这些函数计算出一个值并返回,这个值可以被赋给变量,也可以作为更复杂表达式的一部分。在Python中,函数如果没有显式返回值,它们默认返回`None`。 本章的一个实际示例是定义一个名为`area`的函数,用于计算给定半径的圆的面积。最初的实现使用了一个中间变量`a`来存储计算结果,然后通过`return a`返回。这种方式有助于调试,因为可以检查`a`的值以确保计算正确。简化后的版本直接在`return`语句中计算面积,即`return math.pi * radius **2`,这种方式更加简洁,但可能在调试时失去了一些可见性。 使用`return`语句可以在函数的不同路径中根据条件返回不同的值,这对于条件分支结构特别有用。例如,如果函数需要根据某些条件返回不同的结果,可以在每个`if`或`else`分支中包含一个`return`语句,这样可以根据条件立即返回相应的值,无需等到函数末尾。 在《像计算机科学家一样思考》这本书中,作者强调了问题解决能力的重要性,这是计算机科学家的核心技能。通过形式化问题、创新解决问题的方法,以及在设计和构建系统时寻找最佳平衡,计算机科学家综合了数学、工程和自然科学的思维方法。本书旨在帮助读者掌握这些技能,从而更好地理解和编写有返回值的函数,以及其他复杂的编程概念。

R R version 4.2.2 (2022-10-31) -- "Innocent and Trusting" Copyright (C) 2022 The R Foundation for Statistical Computing Platform: x86_64-conda-linux-gnu (64-bit) R is free software and comes with ABSOLUTELY NO WARRANTY. You are welcome to redistribute it under certain conditions. Type 'license()' or 'licence()' for distribution details. Natural language support but running in an English locale R is a collaborative project with many contributors.Type 'contributors()' for more information and 'citation()' on how to cite R or R packages in publications. Type 'demo()' for some demos, 'help()' for on-line help, or 'help.start()' for an HTML browser interface to help. Type 'q()' to quit R. library(ape) setwd("/ifs1/User/dengwei/NTF_data/7.14/rooted_species_tree") species_tree <- read.tree("species_tree.treefile")> compare_trees <- function(gene_tree_file, species_tree) { gene_tree <- read.tree(gene_tree_file) diff_count <- comparePhylo(gene_tree, species_tree, force.rooted = TRUE) return(diff_count) } batch_compare_trees <- function(gene_tree_folder, species_tree) { gene_tree_files <- list.files(path = gene_tree_folder, pattern = ".treefile", full.names = TRUE) diff_counts <- data.frame(Gene_Tree_File = gene_tree_files, Diff_Count = numeric(length(gene_tree_files)), stringsAsFactors = FALSE) for (i in seq_along(gene_tree_files)) { gene_tree_file <- gene_tree_files[i] diff_counts$Diff_Count[i] <- compare_trees(gene_tree_file, species_tree) } return(diff_counts) } gene_tree_folder <- "/ifs1/User/dengwei/NTF_data/7.14/rooted_gene_tree" diff_counts <- batch_compare_trees(gene_tree_folder, species_tree) Error in if (n1 == n2) paste("Both trees have the same number of tips:", : the condition has length > 1

2023-07-15 上传