Skip to content

Instantly share code, notes, and snippets.

View StephenClarkApps's full-sized avatar

StephenClarkApps StephenClarkApps

View GitHub Profile
@StephenClarkApps
StephenClarkApps / mapExample.py
Last active May 15, 2018 17:32
Example of using map higher order function in python
fahrenheit = [100, 120, 90]
celsius = map(lambda x: (float(5)/9)*(x-32), fahrenheit)
print (celsius)
"""return the nth term of a fib sequence using a naive method (start with 0)"""
def fibonacci_modern (n):
if n == 1:
return 0
elif n == 2:
return 1
elif n > 2:
return fibonacci_modern(n - 1) + fibonacci_modern(n - 2)
"""return the nth term of a fib sequence using a naive method (start with 1)"""
fibCache = {}
"""return the nth term of the sequence using explicit memoization (start with 1)"""
def fibonacciWithCache(n):
# If we have cached the value then we return it
if n in fibCache:
return fibCache[n]
# Compute the Nth term
if n == 1:
value = 1
if n == 2:
#!/bin/python3
from functools import lru_cache
"""method to find fib for n using python lru cache"""
@lru_cache(maxsize = 1000)
def fibonacciLRU(n):
if n == 1:
return 1
elif n == 2:
return 1
// Memoized recursive implementation in Swift
var fibCache: [Int: Int] = [:] // This is a Swift Dictionary
func fibonacciAtIndex(_ index: Int) -> Int {
if let fibonacci = fibCache[index] {
return fibonacci
}
guard index >= 2 else {
fibCache[index] = index
return index
#!/bin/python3
from functools import lru_cache
"""good method to find fib for n using python 3 lru_cache"""
@lru_cache(maxsize = 1000)
def fibonacciLRU(n):
if n == 1:
return 1
elif n == 2:
return 1
/* Example of using the golden ratio, which
is basically binet's formula to find a fib number */
import Foundation
let sqrt_of_5 = sqrt(Double(5))
let Φ: Double = ((1 + sqrt(5.0)) / 2.0)
func fibonacciBinet(_ index: Int) -> Int {
let fahrenheit = []
let celsius = fahrenheit.map({
(value: Int) -> Float in
return ((Float(5)/9) * Float(Float(value - 32))
})
// [37.77778, 48.88889, 32.22223]
// square all elements of an array using map
let values = [2.0, 3.0, 5.0, 8.0]
let squares = values.map {$0 * $0}
print(squares) // [4.0, 9.0, 25.0, 64.0]
package com.somepackage;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class Main {
public static void main (String[] args) {
List<Integer> numbers = Arrays.asList(1, 4, 10, 15);
List<Integer> result2 = numbers.stream() // convert list to stream
.filter(num -> (num%2 ==0)) // only results divisible by 0