牌語備忘録 -pygo

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

牌語備忘録 -pygo

2.2.1 Representing SequencesをPythonでやってみた

SICP2.2 Hierarchical Data and the Closure Property2.2.1 Representing Sequences
あたりをPythonでやってみた

;2.2  Hierarchical Data and the Closure Property
;2.2.1  Representing Sequences
(define one-through-four
  (list 1 2 3 4))
(car one-through-four);1
(cdr one-through-four);(2 3 4)
(car (cdr one-through-four));2
(cons 10 one-through-four);(10 1 2 3 4)
(cons 5 one-through-four);(5 1 2 3 4)
;List operations
(define (list-ref items n)
  (if (= n 0)
      (car items)
      (list-ref (cdr items) (- n 1))))
(define squares
  (list 1 4 9 16 25))
(list-ref squares 3);16

(define (length items)
  (if (null? items)
      0
      (+ 1 (length (cdr items)))))
(define odds (list 1 3 5 7))
(length odds);4

(define (length items)
  (define (length-iter a count)
    (if (null? a)
        count
        (length-iter (cdr a) (+ 1 count))))
  (length-iter items 0))
(length odds);4

(append squares odds);(1 4 9 16 25 1 3 5 7)
(append odds squares);(1 3 5 7 1 4 9 16 25)

(define (append list1 list2)
  (if (null? list1)
      list2
      (cons (car list1) (append (cdr list1) list2))))
python
#2.2  Hierarchical Data and the Closure Property
#2.2.1  Representing Sequences
def one_through_for():
    return [1,2,3,4]
print one_through_for()[0]      # 1
print one_through_for()[1:]     # [2, 3, 4]
print one_through_for()[1:][0]  # 2
print [10] + one_through_for()  # [10, 1, 2, 3, 4]
print [5] + one_through_for()   # [5, 1, 2, 3, 4]
#List operations
def list_ref(items, n):
    if n == 0:
        return items[0]
    return list_ref(items[1:], n - 1)
def squares():
    return [1,4,9,16,25]
print list_ref(squares(), 3)#16
#recursive
def length(items):
    if not items:
        return 0
    return 1 + length(items[1:])
def odds():
    return [1,3,5,7]
print length(odds())#4
#iterative
def length_i(items):
    def length_iter(a, count):
        if not a:
            return count
        return length_iter(a[1:], 1 + count)
    return length_iter(items, 0)
print length_i(odds())#4

print squares() + odds()#[1, 4, 9, 16, 25, 1, 3, 5, 7]
print odds() + squares()#[1, 3, 5, 7, 1, 4, 9, 16, 25]

def f_append(list1, list2):
    if not list1:
        return list2
    return [list1[0]] + f_append(list1[1:], list2)
print f_append(squares(), odds())#[1, 4, 9, 16, 25, 1, 3, 5, 7]
print f_append(odds(), squares())#[1, 3, 5, 7, 1, 4, 9, 16, 25]