diff --git a/solutions.py b/solutions.py new file mode 100644 index 0000000..a5aca03 --- /dev/null +++ b/solutions.py @@ -0,0 +1,30 @@ +#!/ysr/bin/env python2 + +# 1. All primes from 0 to n +def allPrimesToN(n): + """ Assumes input is an whole number n. + Returns a list of integers which are prime (n is included if it is prime) or an empty list if no prime numbers exist between 0 and n. + """ + res = [] # results kept here + l = [True for i in range(n + 1)] # initialize primal + l[0] = l[1] = False + for i in range(2, n): + # Check all multiples of i as non prime + for j in range(2 * i, n + 1, i): + l[j] = False + for i in range(len(l)): + if l[i]: + res += [i] # Add to list if prime + return res + + +# 2. All factorials from 0 to n +def allFactToN(n): + """ Assumes input is a whole number n. + Returns a list of all factorials of the numbers 0 through n (inclusive) + """ + if n == 0: # Base case: if n is zero return a list with only 1 as its element + return [1] + ret = allFactToN(n - 1) + # multiply the last element of ret with n and append it onto the ret + return ret + [ret[-1] * n] diff --git a/solutions.scala b/solutions.scala new file mode 100644 index 0000000..bcc7159 --- /dev/null +++ b/solutions.scala @@ -0,0 +1,33 @@ +import scala.util.matching.Regex +// 3. Pattern matching + +def typeMatching(list: List[Any]) = list match { + case Nil => "Empty list; No types" + case (head:String) :: _ => "A string list" + case (head:Int) :: _ => "An integer list" + case (head:Float) :: _ => "A float list" + case _ => "Other type of list" +} + +// println(typeMatching(List("a", "a"))) // Outputs A string list +// println(typeMatching(List(1.5.toFloat, 2.5.toFloat))) // Outputs A float list +// println(typeMatching(List(1, 2))) // Outputs An integer list + + +// 4. Regex matching +def regexMatch(str: String) : Option[String] = { + val numPattern = new Regex("[0-9]+") + val match1 = numPattern.findFirstIn(str) + return match1 +} + +// println(regexMatch("7th floor Galana plaza, Kilimani")) // Outputs Some(7) + + +// 5. Case class Person +case class Person(name: String, age:Int) { + require(age > 0) +} + + +// new Person("Nathnael", 0) // Throws IllegalArgumentException