5. â€«× ×§×™â€¬ â€«×¡×™× ×˜×§×¡â€¬
class Main {
public static final String[] NAMES =
{"Yuval", "Keren", "Dvir"};
public static void main(String[] argv) {
for (String s: NAMES) {
System.out.println("Hello " + s);
}
}
}
for s in ["Yuval", "Keren", "Dvir"]:
print("Hello " + s)
19. ?â€«×ª×›× ×•×ªâ€¬ ‫זה‬ ‫מה‬import sys
def is_prime(n):
i = 2
while i < n:
if n % i == 0:
return False
else:
i = i + 1
return True
if __name__ == "__main__":
n = int(sys.argv[1])
print(is_prime(n))
20. ?â€«×ª×›× ×•×ªâ€¬ ‫זה‬ ‫מה‬
import sys


# more pythonic
def is_prime(n):
for i in range(2, n):
if n % i == 0:
return False
return True
if __name__ == "__main__":
n = int(sys.argv[1])
print(is_prime(n))
26. â€«×¤×™×‘×•× ×¦×³×™â€¬import sys


# assume n >= 3
def fib(n):
sum_i = 0
i = 3
f2, f1 = 1, 1
while i <= n:
sum_i = f2 + f1
f2, f1 = f1, sum_i
i += 1
return sum_i
if __name__ == "__main__":
n = int(sys.argv[1])
print(fib(n))
28. â€«×¤×™×‘×•× ×¦×³×™â€¬
import sys
# more pythonic
def fib(n):
f2, f1 = 1, 1
for i in range(3, n + 1):
f2, f1 = f1, f1 + f2
return f1
if __name__ == "__main__":
n = int(sys.argv[1])
print(fib(n))
29. â€«×¤×™×‘×•× ×¦×³×™â€¬
In [83]: %time %run fib 39
63245986
CPU times: user 15.5 s, sys: 63.1 ms,
total: 15.6 s

Wall time: 15.7 s
O(2â¿)
In [84]: %time %run fib2 39
63245986
CPU times: user 1.01 ms, sys: 664 µs,
total: 1.67 ms

Wall time: 1.14 ms
O(n)
30. â€«×¤×™×‘×•× ×¦×³×™â€¬import sys
known = {
1: 1,
2: 1,
}
def fib(n):
if n in known:
return known[n]
known[n] = fib(n - 2) + fib(n - 1)
return known[n]
if __name__ == "__main__":
n = int(sys.argv[1])
print(fib(n))
31. â€«×¤×™×‘×•× ×¦×³×™â€¬
import sys
from functools import lru_cache
# more pythonic
@lru_cache(maxsize=None)
def fib(n):
if n <= 2:
return 1
return fib(n - 2) + fib(n - 1)
if __name__ == "__main__":
n = int(sys.argv[1])
print(fib(n))
33. ‫רקורסיה‬
import sys
def power(x, n):
res = 1
while n > 0:
res *= x
n -= 1
return res
if __name__ == "__main__":
x = int(sys.argv[1])
n = int(sys.argv[2])
print(power(x, n))
34. ‫רקורסיה‬
import sys
# assume n is a power of 2
def power(x, n):
if n == 2:
return x * x
return power(x, n / 2) * power(x, n / 2)
if __name__ == "__main__":
x = int(sys.argv[1])
n = int(sys.argv[2])
print(power(x, n))
35. ‫רקורסיה‬import sys
def power(x, n):
if n == 1:
return x
elif n % 2 == 0:
half = power(x, n / 2)
return half * half
else:
return x * power(x, n - 1)
if __name__ == "__main__":
x = int(sys.argv[1])
n = int(sys.argv[2])
print(power(x, n))
36. ‫רקורסיה‬
%time %run power2 2 65536

[…]

CPU times: user 110 ms, sys: 8.22 ms,
total: 118 ms
Wall time: 116 ms
%time %run power3 2 65536

[…]

CPU times: user 8.6 ms, sys: 1.37 ms,
total: 9.97 ms
Wall time: 12.7 ms