Homework 1: Variables & Functions, Control

A Plus Abs B

Fill in the blanks in the following function for adding to the absolute value of , without calling . You may not modify any of the provided code other than the two blanks.

from operator import add, sub

def a_plus_abs_b(a, b):
    """Return a+abs(b), but without calling abs.

    >>> a_plus_abs_b(2, 3)
    5
    >>> a_plus_abs_b(2, -3)
    5
    >>> # a check that you didn't change the return statement!
    >>> import inspect, re
    >>> re.findall(r'^\s*(return .*)', inspect.getsource(a_plus_abs_b), re.M)
    ['return h(a, b)']
    """
    if b >= 0:
        h = _____
    else:
        h = _____
    return h(a, b)

answer:

from operator import add, sub

def a_plus_abs_b(a, b):
    
    if b >= 0:
        h = add
    else:
        h = sub
    return h(a, b)

利用 if 语句实现 h = a + |b| 

Two of Three

Write a function that takes three positive numbers as arguments and returns the sum of the squares of the two smallest numbers. Use only a single line for the body of the function.

def two_of_three(x, y, z):
    """Return a*a + b*b, where a and b are the two smallest members of the
    positive numbers x, y, and z.

    >>> two_of_three(1, 2, 3)
    5
    >>> two_of_three(5, 3, 1)
    10
    >>> two_of_three(10, 2, 8)
    68
    >>> two_of_three(5, 5, 5)
    50
    >>> # check that your code consists of nothing but an expression (this docstring)
    >>> # a return statement
    >>> import inspect, ast
    >>> [type(x).__name__ for x in ast.parse(inspect.getsource(two_of_three)).body[0].body]
    ['Expr', 'Return']
    """
    return _____

answer:

def two_of_three(x, y, z):
 
    return x*x + y*y + z*z - max(x, y, z)*max(x, y, z)

求出三个数中较小两个数的平方和

Largest Factor

Write a function that takes an integer that is greater than 1 and returns the largest integer that is smaller than and evenly divides .

def largest_factor(x):
    """Return the largest factor of x that is smaller than x.

    >>> largest_factor(15) # factors are 1, 3, 5
    5
    >>> largest_factor(80) # factors are 1, 2, 4, 5, 8, 10, 16, 20, 40
    40
    >>> largest_factor(13) # factor is 1 since 13 is prime
    1
    """
    "*** YOUR CODE HERE ***"

answer: 

def largest_factor(x):
    factor = x - 1
    while factor > 0:
        if x % factor == 0:
            return factor
        factor -= 1
    return 1

给出数字x的最大因子

 

If Function vs Statement

Let's try to write a function that does the same thing as an statement. if

def if_function(condition, true_result, false_result):
    """Return true_result if condition is a true value, and
    false_result otherwise.

    >>> if_function(True, 2, 3)
    2
    >>> if_function(False, 2, 3)
    3
    >>> if_function(3==2, 3+2, 3-2)
    1
    >>> if_function(3>2, 3+2, 3-2)
    5
    """
    if condition:
        return true_result
    else:
        return false_result

Despite the doctests above, this function actually does not do the same thing as an statement in all cases. To prove this fact, write functions , and such that prints the number , but prints both and .

if condtrue_func false_func with_if_statement 47 with_if_function 42 47 

def with_if_statement():
    """
    >>> result = with_if_statement()
    47
    >>> print(result)
    None
    """
    if cond():
        return true_func()
    else:
        return false_func()

def with_if_function():
    """
    >>> result = with_if_function()
    42
    47
    >>> print(result)
    None
    """
    return if_function(cond(), true_func(), false_func())

def cond():
    "*** YOUR CODE HERE ***"

def true_func():
    "*** YOUR CODE HERE ***"

def false_func():
    "*** YOUR CODE HERE ***"

answer:

def with_if_statement():
    if cond():
        return true_func()
    else:
        return false_func()

def with_if_function():
    return if_function(cond(), true_func(), false_func())

def cond():
    return True

def true_func():
    print(42)

def false_func():
    print(47)

这是一个验证性作业,目的是验证函数with_if_statement 和 with_if_function 两者的差别:

由于两者实现的流程不一样,再某些情况下相同的条件就会导致不同的结果。在这一个例子中,对于两个函数的判断条件是一样的,但是两者的输出是不一样的。

Hailstone

Douglas Hofstadter's Pulitzer-prize-winning book, Gödel, Escher, Bach, poses the following mathematical puzzle.

  1. Pick a positive integer as the start. 
  2. If is even, divide it by 2. 
  3. If is odd, multiply it by 3 and add 1. 
  4. Continue this process until is 1.

Breaking News (or at least the closest thing to that in math). There was a recent development in the hailstone conjecture last year that shows that almost all numbers will eventually get to 1 if you repeat this process. This isn't a complete proof but a major breakthrough.

This sequence of values of is often called a Hailstone sequence. Write a function that takes a single argument with formal parameter name , prints out the hailstone sequence starting at , and returns the number of steps in the sequence: 

def hailstone(x):
    """Print the hailstone sequence starting at x and return its
    length.

    >>> a = hailstone(10)
    10
    5
    16
    8
    4
    2
    1
    >>> a
    7
    """
    "*** YOUR CODE HERE ***"

answer:

def hailstone(x):
    while x != 1:
        print(x)
        if x % 2 == 0:
            x = x // 2 #保留整数部分,去除小数部分
        else:
            x = x * 3 + 1
    print(x)

简单给出一个初始值,进行冰雹数列的模拟输出

总结:

本次作业的目的主要是熟悉简单的Python语法,以及部分流程设计所带来的问题,最后给了一个数学模拟问题。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值