Sunday, January 19, 2020

Scala vs Python

Scala vs Python

----------------VAR / CONST ------------
val a:String="123" // Scala
var a:String="123" // Scala

a="123"# Python
--------------COMMENTS------------------
// this is a commented line in Scala
/* and this is a multiline comment,
...just choose! */

#Hi # Python
""" # Python
multi
"""
or
''' # Python
multi Line
'''
---------------PRINT-----------------
print("whatever you want") #  Python
println("whatever you want") // Scala

a="hi"
print(f"{a}")

val a="hi"
println(s"$a")

---------------LIST/ARRAY-----------------
Declaration :
var myArray = Array(2, 5, "apple", 78) // Scala
my_list = [2, 5, 'apple', 78] # Python

Indexing
myArray(1) // Scala 
my_list[1] # Python 

Slicing
myArray.slice(0,3) // Scala
my_list[0:3] # Python 


myArray.last    // Scala last element
myArray.max     // Scala maximum element
myArray.min     // Scala minimum element

my_list[-1]    # Python last element
max(my_list)   # Python maximum element
min(my_list)   # Python minimum element

sum(my_list) # Python- sum

myArray.sum    // scala sum
myArray.product  // multiplying elements in array

my_list.append('last words') # Python
myArray :+= "last words" 

---------------LOOP-----------------
for i in my_list:print(i)# Python
for (i <- myArray){ println(i)}// Scala
val list = List(1, 2, 3)
list.foreach(x => println(x)) 


--------------MAP------------------
list(map(lambda x:x*3,my_list)) # map in Python
myArray.map(i => i*3) // map in Scala

---------------FILTER-----------------
list(filter(lambda x:x%3==0,my_list)# filter in Python
myArray.filter(i => i%3 == 0) // filter in Scala

---------------REDUCE-----------------
from functools import reduce # Python
print(reduce(lambdax,y:x+y,(1,2,3))) #Python

val lst = List(1, 2, 3) // Scala
list.reduce((x, y) => x + y) // => 6 // Scala

---------------LIST COMPREHENSION-----------------
[i*3 for i in my_list if i%2 == 0] # list comprehension
myArray.filter(i => i%2 == 0).map(i => i*3) // Scala

---------------SORT-----------------------
sortBy(f: T => K): Seq[T]

---------------DICTIONARY-----------------
Declaration:
my_dict = {'first_name': 'Emma','age': 18}# Python
var myMap = (("firstName", "Emma"),("age", 18)) // Scala

New key:
my_dict['country_of_origin'] = 'Italy' # Python
myMap += ("countryOfOrigin" -> "Italy") // Scala

Access:
my_dict['first_name'] # Python
myMap("firstName") // Scala

Loop:
for key, value in my_dict.items(): # Python
    print(key)
    print(value)

for ((key, value) <- myMap){ // Scala
    println(key)
    println(value)
}
--------------TUPLE------------------
my_tup = (1, 2, 3) # Python
my_tup[0] # Python


myTup = (1, 2, 3) // Scala
myTup._1 // Scala
// the indexing is way different than arrays!

-------------SET-------------------
my_set = {1, 3, 5, 1} # Python
mySet = Set(1, 3, 5, 1) // Scala

-------------FUNCTION-------------------
def chop_string(input_string): # Python
    return input_string[0:5]

def chopString(inputString: String): String = { // Scala
    inputString.slice(0, 5)
}
--------------NAMED TUPLE/CASE CLASS------
from collections import namedtuple
n=namedtuple("n",["a","b"])
n2=n(10,20)
print(n2.a)

case class n(a:String,b:Int)
val n2: n = n("name", 1)
println(n2.a)
----------------SORTED 1---------------------
List(10, 5, 8, 1, 7).sortWith(_ < _) // Scala asc
sorted([10, 5, 8, 1, 7] , reverse =false) # Python

----------------SORTED 2---------------------
val list = List(('b',30),('c',10),('a',20))// Scala
println(list.sortBy(_._2))

l=[[1,2],[2,1]] # Python
sorted(l,key=lambdax:x[1])

----------------SORTED 3---------------------
List("banana", "pear", "apple", "orange").sortWith(_.length < _.length) // Scala
sorted(["banana", "pear", "apple", "orange"],key=lambda x:len(x)) # Python

output:(pear, apple, banana, orange)

-----------------Switch / Case ----------------
val result =1
result match {
case -1 =>{println("-1")}
case 0 => { println("asd")}
case x:Int if(x>0) =>
{ println(x)}
}

------------------OPTION = Some/getorelse/match---------------------
To eliminate NullPointerExceptions.

val age:Option[Integer] = None //Some(28)
val x=age.getOrElse(throw new Exception("error"))

No comments:

Post a Comment