zoukankan      html  css  js  c++  java
  • python核心编程第五章练习-5.11-最大公约数和最小公倍数

    a、求两个数的最大公约数 

    def common_divisor(a, b):

        for i in range(1, min(a, b) + 1):
            if a % i == 0 and b % i ==0:
                m = i
        print ("The common divisor is %d" %m)

    一开始对上面这段代码始终没理解,为什么得到是就仅仅是6,因为按照目测,1, 2, 3, 6均符合if的条件,应该都会打印出来。

    讨教之后才知道是因为没有区分代码组,print()的位置决定了它最终打印出哪一个m值。

    区分一下代码的输出(以common_divisor(12, 18)为例):

     1、

    def common_divisor(a, b):
        for i in range(1, min(a, b) + 1):
            if a % i == 0 and b % i ==0:
                m = i

                print(i) 

                print ("The common divisor is %d" %m)

    2、 

    def common_divisor(a, b):
        for i in range(1, min(a, b) + 1):
            if a % i == 0 and b % i ==0:
                m = i

        print(i) 

            print ("The common divisor is %d" %m)

     对于1,只有if条件满足的时候,就执行print()语句;而对于2,每执行一次for循环,就执行一次print();最后,对于开头的代码,(是不是有点穷举的意思。。。),找到所有满足条件的m值,然后打印出最后一个,且只执行一次!!

    1、

    >>> common_divisor(12, 18)
    1
    The common divisor is 1
    2
    The common divisor is 2
    3
    The common divisor is 3
    6
    The common divisor is 6

     2、

    >>> common_divisor(12, 18)
    1
    The common divisor is 1
    2
    The common divisor is 2
    3
    The common divisor is 3
    The common divisor is 3
    The common divisor is 3
    6
    The common divisor is 6
    The common divisor is 6
    The common divisor is 6
    The common divisor is 6
    The common divisor is 6
    The common divisor is 6
    The common divisor is 6

    b、求两个数的最小公倍数:

    def common_mutiple(i, j):
        maxnum = max(i, j)
        while True:
            if maxnum % i == 0 and maxnum % j ==0:
                print ("The common mutiple is %d" %maxnum) ##列举,将遇到的第一个满足if条件的maxnum打印出来,然后break,跳出while循环。
                break
            else:
                maxnum = maxnum + 1
  • 相关阅读:
    python 类继承演示范例的代码
    C#监控指定目录的文件变化的代码
    如何开启红米手机4X的ROOT超级权限
    C# 发送电子邮件源码片段
    android中使用afinal一行源码显示网络图片
    (详细)华为畅享7 SLA-AL00的usb调试模式在哪里打开的流程
    C#自定义FTP访问类的代码
    C#的String.Split 分割字符串用法详解的代码
    红米Note 5A完美卡刷开发版获得ROOT超级权限的方法
    C# 类如何声明索引器以提供对类的类似数组的访问的代码
  • 原文地址:https://www.cnblogs.com/SWTwanzhu/p/6118357.html
Copyright © 2011-2022 走看看