如何写好程序📝📝📝

  • 计算机并不解决问题,它们只是执行解决方案
  • 软件设计有两种方式:一种方式是,使软件过于简单,明显没有缺陷;另一种方式是,使软 件过于复杂,没有明显的缺陷
  • 控制复杂性是计算机编程的本质 ——Brian Kernighan
  • A good programmer is someone who always looks both ways before crossing a one-way street——Doug Linder     好的程序员即使在过单行道时也总是会环顾两边。
  • Simple is better than complex     简洁胜于复杂
  • Complex is better than complicated    复杂胜于凌乱
  • Flat is better than nested     扁平胜于嵌套
  • Programs must be written for people to read, and only incidentally for machines to execute —— Harold Abelson , Gerald Jay Sussman 程序必须首先为了人去阅读而编写,其次才是为了机器执行。
  • Good code is its own best documentation. As you’re about to add a comment, ask yourself, ‘How can I improve the code so that this comment isn’t needed?’" —— Steve McConnell     好的代码本身就是最好的文档。当你打算添加注释时,问问自己:“我怎样改进代码,使之无需注释就能表达清楚?”




    def fibonacci(n):
        """
        返回前n个斐波那契数列的生成器。
        斐波那契数列定义为:F(0) = 0, F(1) = 1, F(n) = F(n-1) + F(n-2) (n > 1)
        """
        a, b = 0, 1
        for _ in range(n):
            yield a
            a, b = b, a + b

    # 使用斐波那契数列生成器
    for fib in fibonacci(10):
        print(fib, end=' ')


经典的Python程序片段,何为简洁胜于复杂, 它演示了斐波那契数列的生成器表达式,展示了简洁、高效的代码风格


    public class FibonacciExample {
        public static void main(String[] args) {
            // 初始化斐波那契数列的前两个数
            int a = 0;
            int b = 1;

            // 打印前10个斐波那契数
            for (int i = 0; i < 10; i++) {
                System.out.print(a + " ");
                // 计算下一个数
                int next = a + b;
                // 更新a和b的值
                a = b;
                b = next;
            }
        }
    }



    pub fn fibonacci() {
        let n = 10; // 假设我们要生成前10个斐波那契数列
        let mut fib_sequence = vec![0, 1];

        // 如果需要超过前两个数,则填充剩余的斐波那契数列
        while fib_sequence.len() < n {
            let next = fib_sequence[fib_sequence.len() - 1] + fib_sequence[fib_sequence.len() - 2];
            fib_sequence.push(next);
        }

        // 打印斐波那契数列
        for &number in fib_sequence.iter() {
            println!("{}", number);
        }
    }