Решение упражнения 1.3 из SICP

14 August, 2007 (22:13) | Решения упражнений

В третьем упражнении мы напишем самостоятельно первую процедуру.
Используем введенные в главе процедуры

(define (square a)  (* a a))  

(define (sum-of-squares a b)
  (+ (square a) (square b)))

и запишем:

(define (sum-of-biggest-squares a b c)
  (cond ((and (>= a c) (>= b c)) (sum-of-squares a b))
        ((and (>= a b) (>= c b)) (sum-of-squares a c))
        (else (sum-of-squares b c))))

Еще один очень элегантный вариант решения я обнаружил в комментариях к блогу Кена Дика:

(define (sum-of-biggest-squares a b c)
  (sum-of-squares (max a b) (max (min a b) c)))

Comments

Comment from thror
Date: February 14, 2008, 12:00 pm

Держите еще один “элегантный” вариант

(define (f a b c)
  (+ (square a)
     (square b)
     (square c)
     (- (square (min a b c)))))

Comment from Sergey Khenkin
Date: February 14, 2008, 3:20 pm

Принимается :)

Comment from evgeny
Date: April 16, 2009, 7:27 pm

Можно и так:

(define (f x y z)
(if (< x y)
(sum-of-squares y (max x z))
(sum-of-squares x (max y z))))

Comment from Juev
Date: August 22, 2009, 6:24 pm

Вот еще одно решение:

(defun my/square (x y z)
  "Возвращает сумму квадратов двух больших чисел"
  (defun square (x)
    "square x"
    (* x x))
  (defun sum_sq (x y)
    "sum square"
    (+ (square x) (square y)))
  (max (sum_sq x y) (sum_sq x z) (sum_sq y z)))

Comment from dmi3s
Date: September 29, 2009, 2:39 pm


(define (sum-of-biggest-squares a b c)
(if (and (<= a b) (<= a c))
(sum-of-squares b c)
(sum-of-biggest-squares b c a)))

2 Juev: в условии ни где не сказано, что числа неотрицательны ;)

Comment from синдикат
Date: December 15, 2009, 5:08 pm

Сначала написал на Си, потом перевёл на Лисп. Косность мышления сказалась (=

(define (square x) (* x x))

(define (sqsum2 x y z)
  (if (> x y)
      (if (> y z)
          (+ (square x) (square y))
          (+ (square x) (square z)))
      (if (> x z)
          (+ (square x) (square y))
          (+ (square y) (square z)))))

Write a comment