楼主: liudeiq99
3015 12

[其他] Introduction to Computing Using Python [推广有奖]

11
Lisrelchen 发表于 2016-2-6 10:08:28 |只看作者 |坛友微信交流群
  1. # Practice Problem 5.9
  2. def add2D(t1, t2):
  3.     '''t1 and t2 are 2D lists with the same number of rows and
  4.        same number of equal sized columns

  5.        add2D increments every item t1[i][j] by t2[i][j]'''
  6.     nrows = len(t1)                # number of rows
  7.     ncols = len(t1[0])             # number of columns
  8.     for i in range(nrows):         # for every row index i
  9.         for j in range(ncols):         # for every column index j
  10.             t1[i][j] += t2[i][j]
复制代码

使用道具

12
Lisrelchen 发表于 2016-2-6 10:09:04 |只看作者 |坛友微信交流群
  1. # Practice Problem 5.10
  2. def interest(rate):
  3.     '''returns the number of years for investment
  4.       to double for the given rate'''
  5.     amount = 100                 # initial account balance
  6.     count = 0
  7.     while amount < 200:
  8.         # while investment not doubled in value
  9.         count += 1               # add one more year
  10.         amount += amount*rate    # add interest
  11.     return count
复制代码

使用道具

13
Lisrelchen 发表于 2016-2-6 10:09:36 |只看作者 |坛友微信交流群
  1. # Practice Problem 5.11
  2. def approxE(error):
  3.     'returns approximation of e within error'
  4.     prev = 1                        # approximation 0
  5.     current = 2                     # approximation 1
  6.     i = 2                           # index of next approximation
  7.     while current - prev > error:
  8.         # while difference between current and previous
  9.         # approximation is too large
  10.                                     # current approximation
  11.         prev = current              # becomes previous
  12.                                     # compute new approximation
  13.         current = prev + 1/factorial(i)  # based on index i
  14.         i += 1                      # index of next approximation
  15.   return current
复制代码

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加JingGuanBbs
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-28 19:28