牌語備忘録 -pygo

あくまでもメモです。なるべくオフィシャルの情報を参照してください。

牌語備忘録 -pygo

SICPのExercise 1.3.をPythonでやってみた

SICP(和訳:計算機プログラムの構造と解釈)の1.1.6 Conditional Expressions and PredicatesのExercise 1.3.をPythonでやってみた
(元はschemeの例題)

#Exercise 1.3.Define a procedure that takes three numbers as arguments and returns the sum of the squares of the two larger numbers.
#(練習 1.3 引数に3つの数字をとって、2つの大きな数字の二乗の合計を返す手続きを定義する)
def square(x):
    return x * x
def sum_of_squares(x, y):
    return square(x) + square(y)
def sum_of_two_large_num(x, y, z):
    if x > y:
        return sum_of_squares(x, (y > z) and y or z)
    else:
        return sum_of_squares(y, (x > z) and x or z)

#test
print sum_of_two_large_num(1,2,3)
print sum_of_two_large_num(3,5,4)
print sum_of_two_large_num(5,3,2)

schemeの場合

(define (square x)(* x x))
(define (sum-of-squares x y)
  (+ (square x) (square y)))
(define (sum-of-two-large-num x y z)
  (if (> x y)
      (sum-of-squares x (or (and (> y z) y) z))
      (sum-of-squares y (or (and (> x z) x) z))))
;test
(sum-of-two-large-num 1 2 3)
(sum-of-two-large-num 3 5 4)
(sum-of-two-large-num 5 3 2)
結果
13
41
34

こんな感じ?