Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions solutions.py
Original file line number Diff line number Diff line change
@@ -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]
33 changes: 33 additions & 0 deletions solutions.scala
Original file line number Diff line number Diff line change
@@ -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