地板除法与求余:条件编程基础

需积分: 50 31 下载量 181 浏览量 更新于2024-08-07 收藏 2.71MB PDF 举报
在《Think Python》这本书的第五章中,主要讨论了条件和递归编程的概念,特别是针对地板除法(floor division)和求余(modulus)运算符的应用。地板除法,用符号 // 表示,是一种特殊类型的除法运算,其结果只保留整数部分,即将小数部分直接舍去。例如,当计算电影时长105分钟转换成小时时,传统除法会得到1.75小时,而地板除法则会直接得到1小时,因为忽略了小数部分。 地板除法的一个应用是通过减去整数倍的除数来获取余数。例如,为了找到105分钟剩余多少分钟,可以先将总时间除以60得到小时数,再用总分钟数减去这个整数小时乘以60,得到余数45分钟。另一种获取余数的方法是使用求余运算符 %,该运算符将两个数相除并返回余数。 求余运算符 % 是一种十分实用的工具,它在很多场景下都能派上用场,比如验证一个数是否能被另一个数整除,或者在循环中确定何时结束等。这种运算符可以帮助程序员处理模数问题,确保代码的精确性和效率。 这一章节强调了在编写程序时如何灵活运用条件语句(if-else语句),根据程序当前的状态执行不同的指令。这些运算符和逻辑结构的掌握,有助于读者理解如何在编程中做出决策,并实现复杂的逻辑流程。 此外,整个章节的背景是《Think Like a Computer Scientist》,作者Allen Downey提倡的是一种像计算机科学家一样的思考方式,融合了数学、工程和自然科学的特点,鼓励读者通过形式化的语言表达思想,设计系统,分析复杂行为,并运用问题解决技巧来编写高效、清晰的代码。因此,第五章的内容不仅局限于地板除法和求余的具体操作,更是对编程思维方式的一种深化和扩展。

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 上传