Last active
October 11, 2017 11:41
-
-
Save Biacco42/fa6d0ec82d0918024de789981b925e9c to your computer and use it in GitHub Desktop.
Fibonacci
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# coding: utf-8 | |
from itertools import takewhile | |
def fib(): | |
a = 1 | |
b = 1 | |
while True: | |
yield a | |
tmp = b | |
b = a + b | |
a = tmp | |
fib_stream = fib() | |
for x in takewhile(lambda n: n < 4000, fib_stream): | |
print(x) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Main extends App{ | |
// 真面目に書いた正格評価の fib seq | |
fib(10).foreach { println } | |
def fib(n: Int): Seq[Int] = { | |
assert(n > 0) | |
def rec(n: Int, a: Int, b: Int, seq: Seq[Int]): Seq[Int] = (n <= 1) match { | |
case true => seq | |
case false => rec(n - 1, b, a + b, seq :+ b) | |
} | |
rec(n, 1, 1, Seq(1)) | |
} | |
// Stream 調べたらソッコーで出てきてしまった fib stream | |
val fibStream: Stream[Int] = 1 #:: fibStream.scanLeft(1){ _ + _ } | |
fibStream.takeWhile{ _ < 40000}.foreach{ println } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment