0 ratings0% found this document useful (0 votes) 57 views14 pagesKotlin Vs Python Syntax
Comparison of syntax in Kotlin with syntax in Python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
@® Programming-Idioms.org
1 Print Hello World
Print a Iiteral string on
standard output
2 Print Hello 10 times
Loop to execute some
‘code a constant number
of times
3 Create a procedure
Like a funetion whieh
doesnt retum any value,
thus has only side
‘effects (e.g. Print to
standard output)
4 Create a function
Greate a function which
retums the square of an
integer
5 Create a 2D Point data
structure
Declare a container type
{or two floating-point
numbers xand y
6 lterate over list values
Do something with each
iter x of thelist (or
array) items, regardless
indexes.
Kiva
‘The snippets are under the CC-BY-SA license.
Creative Commons Attribution-ShareAlke 3.0
© Pytvon
printIn("Hello world!")
print("Hello World")
Alternative implementation:
print(*Hello World’)
(@..9)-forEach {
printin("Hello")
}
Alte
repeat(10) {
printIn("Hel1o")
ive implementation:
}
‘Alternative implementation
for(x in 1..10) {
printin("Hello")
>
for _ in range(10):
print("Hello")
Alternative implomentation:
print("Hello\n"*1)
Alternative implementation:
ise
while i < 10:
print(‘Hello')
ited
fun finish(name: string) {
printin("Ny job here is done. Goodbye
$name")
y
def finish(name):
print(f"My job here is done. Goodby
e {name)")
fun square(x: Int) = x * x
def square(x):
return x*x
‘Alternative implementation:
def square(x}
return x**2
data class Point(val x: Float, val y: F
oat)
@dataclass
class Point:
x: float
yz float
Alternative implementation:
Point = namedtuple("Point’
items.forEach { doSomething(it) }
items .forEach(: :
joSomething)
Alternative implementation:
for (x in items) doSomething(x)
Alternative implementation: .
for x in itens:
doSomething( x )
Alternative imp!
[do_something(x) for x in items]
tatlorK rcotin i vnon
7 Hterate over list indexes ( : ti i
‘and values items.forEachIndexed { i, x -> for i, x in enunerate(itens):
Print each index iwith its| | PrintIn("i=$i x=$x") print(i, x)
t
value x from an array.
lice collection items.
8 Create amap
{associative array)
Greate a new map object
x, and provide some Alternative implementation:
(key, value) pairs as val x = mutableMapof()-app
inital content
ye
this["one"]
this["two"] =
val x = map0f("one” to 1, "two" to 2) il x= (one : 1, “two” : 2} ]
1
2
Alternative implementation:
val x = mutablemapofcstring, Int>()
x["one"] = 1
x["two"] = 2
9 Create a Binary Tree
data structure
The structure must be
recursive because left
child and right child are
binary trees too. Anode
thas access to children
data class Node( class Node:
val key: Int, def _init_(self, data):
val left: Node? = null, self.data = data
val right: Node? = null self.left = None
self.right = None
‘nodes, but not to its Alternative implementation:
paren class Node:
def _init_(self, data, left_child,
right_child)
self.data = data
self._left_child = left_child
= right_child
10 Shutfe a ist
rrr ovandom | shuFfleQ) || stu rieco ]
permutation of the
ements olstx —_Altemativ implementation Alternative implementation:
[vay = xesnurrtea) || randon.shurfte¢s) ]
11 ick a random element :
Pik 9 ran List .random() || random. chotcecs) ]
Theis x rst be nor
empty.
12 check it contains a
che 8 an et |/ aan aie
{Chock tho ist contains
tho vat x Alternative implementation:
tats enterablefnte |” ese, contains (x) ]13 lterate over map keys
and values
‘Access each key Kwith
its value x from an
associative array
mymap, and print ther.
14 Pick uniformly a
random floating point
‘number in (a..b)
Pick a random number
‘greater than or equals to
2 strictly inferior to b,
Precondition : a println("$k
sv") }
Random. nextDouble(a,b)
fun pick(a: Int, b: Int):
return (a..b).random()
Int {
t
© Python
for k, v in mymap.items():
print(k, ¥)
random.uniform(a,b)
random. randint(a,b)
fun dfs(bt: BinaryTree) {
bt-left?.let { dfs(it) }
(bt)
bt.rigth?.1et { dfs(it) }
x.reverse()
Alternative implementation:
def dfs(bt):
if bt is None:
return
dFs(bt. left)
(bt)
dFs(bt.right)
reversed(x)
Alternative Implementation:
x = x.reversed()
y= xfii-a]
Alternative implementation:
Alternative implementation:
val reversedView = x.asReversed()
x.reverse()
search(m: ArraycArray>, x: Tn
Paircint, Int>? {
m.fortachindexed { i, row ->
row. foreachindexed { j, value -
if (value == x) {
return Pair(i, 3)
}
y
+
return null
def search(m, x):
for idx, item in enunerate(n):
if x in item:
return idx, item.index(x)21 Swap values
‘Swap the values of the
variables @ and b
22 Convert string to
integer
Exiract the integer value
‘from its sting
representation s (in radix
10)
Convert real number to
‘string with 2 decimal
places
Given a real number x,
create its string
representation s with 2
decimal digits folowing
the dot
26 Create a 2-dimensional
array
Declare and iniiaize a
matrix x having m rows
‘and n columns,
containing real numbers.
Fy
27 Create a 3-dimensional
array
Declare and inivalize a
80 array x, having
dimensions boundaries
‘m,n, p, and containing
real numbers.
28 Sort by a property
Sort the elements of the
list (or array-tke
collection) tems in
ascending order of xp,
where pis a felé ofthe
type item ofthe objects
in items.
29 Remove item from list,
by its index
Remove Fh item from
Ist tems,
‘This wil ater the orginal
list or roturn a new list,
depending on which is
more idiomatic,
Note that in mast
languages, the smallest
valid value for Fis 0
val i = s.toInt()
Alternative implementation:
val i = s.toIntorNull()
© Python
Alternative implementation:
int (input (“enter a number"))
b =int(input("enter b nunber"))
a, b=b,a
print("Value of a:", a)
print("Value of a", b)
int(s)
S = "%.2F". format (x)
*{5.26)' format (x)
Ss = F1(x.2F}
val x = Array(m, { Doublearray(n) })
x = [[0] * n for _ in range(m)]
val x = Array(m, { Array(n, { DoubleArr
ay(p) }) 2)
x = [[[@ for k in range(p)] for j in ra
nge(n)] for 4 in range(m)]
items.sortedBy { it.p }
items.removeat (i)
Alternative implementation:
x = numpy.zeros((m,n,p))
items = sorted(itens, key=lanbda x: x.
»)
items = sorted(items, key-attrgetter
ced)
del items(i]
Alternative implementation:
items.pop(i)30 Parallelize execution of
3
32
38
39
1000 independent
tasks
Launch the concurrent
‘execution of procedure f|
with parameter from 1
to 1000.
‘Tasks are independent
‘and fin doesn return
any value,
“Tasks need not run all at
the same time, so you
may use a pool
Recursive factorial
(simple)
Create the recursive
function fwhion returns
the factorial ofthe non=
negative integer
‘ealeulated from f-1)
by squaring
Create function exp
which calculates (fast)
the value x power
xand nare non
negative integers,
Extract a substring
K kotin
fun main() = runBlocking {
repeat (1000) {
launch {
(it)
>
>
>
fun (i: Int): Int = when (i) {
ea
else -> i * (i - 1)
Alternative implementation:
© Python
pool = Pool()
for i in range(1, 1001):
pool.apply_asyne(f, [1])
return 2
else:
return i * (4-1)
fun f(i: Int) = if (i == 0) 1 else i *
#4 +1)
irreger exponentiation | eum exp(x: Int, n: Int): Int = when { def exp(x, n):
nee @->d return x*#n
nesa->x
1X 2 == 0 -> exp(x * x, 0 / 2)
else -> x * exp(x * x, (n= 1) / 2)
>
val t = s.substring(i, 3) t
Find substring ¢
‘consisting in characters 7
(included) to j (excluded)
of string
Character indices start at
Ounless specified
otherwise,
Make sure that mutioyte
characters are properly
handled.
Check if string
contains a word
Set the boolean ok to
truei the sting word is
‘contained in string s as a
substring, orto false
otherwise,
val ok = s.contains(word)
Alternative implementation:
val ok = word in s
word in s40
“
“a
Graph with adjacency
lists
Declare 8 Graph data
structure in which each
Vertex has a collection
ofits neighbouring
vertices.
Reverse a string
Crwate the sting t
‘containing the same
characters as the string
«5, in reverse order.
“The original string s
must remain unaltered.
Each character must be
handled correctly
regardless its number of
bytes in memory.
Break outer loop
Look for a negative
value vin 2D integer
matrix m. Print and
stop searching
KK. Ktin
inline class VertexId(val id: Int)
data class Vertex(val id: Vertexid, val
neighbours: Set)
data class Graph(val vertices: Set)
val t = s.reversed()
Loop@ for (x in @..7) {
for (y in @..7)
val v = alx][y]
if (ve) {
println("found a negative value
at [Sx] [$y]: $v")
breakéloop
© Python
class Vertex(set): pass
class Graph(defaultdict):
def _init_(self, *paths):
self.default_factory = Vertex
for path in paths:
self.make_path(path)
def nake_path(self, labels):
for 12, 12 in zip(labels, labels
up:
self(11] .add(12)
self [12] .add(11)
G = Graph((@, 1, 2, 3), (1, 4, 2))
s.decode(‘utf8")[::-1] encode(‘utf
class BreakouterLoop (Exception): pass
try:
position = None
for row in m:
for colunn in m[row]:
if m[row][column] == v:
position = (row, colum
n)
raise BreakouterLoop
except BreakOuterLoop:
pass
Alternative implementation:
def loop_breaking(m, v):
for i, row in enumerate(m):
for j, value in enumerate(row):
if value
return (i, 5)
return None
print(loop_breaking(([1,2,3],[4,5,6],
(7,8,9]), 6))
‘Alternative implementation:
matrix = [[1,2,3],[4,-5,6],[7,8,9]]
try:
print(next(i for i in chain.from_it
erable(matrix) if i < @))
except StopIteration:
pass44 Insert element in list
Insert the element x at
positon fin the ists.
Further elements must
be shifted to the right.
45 Pause execution for 5
seconds
Sleep for § seconds in
‘eurrent thread, before
‘proceeding with the next
instructions.
46 Extract beginning of
string (prefix)
Create the sting ¢
‘consisting of the 5 first
charactors ofthe string
Make sure that mutioyte
characters are property
handled
47 Extract string suffix
Create string t consisting
inthe 5 last characters
‘of string s.
Make sure that mutibyte
characters are property
handled
48 Multi-line string literal
Assign to variable sa
string literal consisting in
‘several lines of text,
Including newlines.
49 Split a spac
‘separated string
Build list chunks
‘consisting in substrings.
of the sting s, separated
by one oF more space:
characters,
50 Make an infinite loop
Write @ loop that has no
‘ond clause.
51 Check if map contains
key
Determine whether the
‘map m contains an entry
for the key
52 Check if map contains
value
Determine whether the
‘map m contains an entry
with the value v, for
‘some key,
K kotin
s.add(i, x)
© Python
s.insert(i, x)
Thread.sleep(5000L)
‘time.sleep(5)
val t = s.take(5)
t= s[:5]
val t = s.takeLast(5)
val s
This is my
multi-line string.
val chunks = s.split("
\s#" toRegex())
chunks = s.split()
while (true) { }
while True:
pass
m.containsKey(k)
k inn
m.containsValue(v)
v in m.values()53 Join alist of strings
Coneatenate elements of
string list xjoined by the
separator", "to create a
single stingy.
54 Compute sum of
integers
Calculate the sum s of
the integer stor array x
55 Convert integer to
string
Create the sting
representation s (in rad
410) ofthe integer value i.
56 Launch 1000 parallel
tasks and wait for
completion
Fork-oin: Iaunch the
‘concurrent execution of
procedure fwith
parameter ifrom 1 to
1000.
‘Tasks are independent
‘and fi) doesn't return
any value,
“Tasks need not run all at
the same time, 80 you
may use a pool
Wat for the completion
‘of the 1000 tasks and
then print "Finished"
57 Filter ist
Create the lst y
‘containing the items
{rom the list x that satisy
the predicate p. Respect
the original ordering
Don't moxity x in-place.
58 Extract file content to a
string
Crvate the string lines
{rom the content of the
file wit flename f.
59 Write to standard error
stream
K kotin
ListOF(x).joinTostring(",
val y
© Python
y= 'y ‘join(x)
Alternative implementation:
y=", ‘ejoin(map(str, x))
val numbers = listof(1, 2, 3, 4) s = sum(x)
val sum
numbers. sum()
-toString()
(1..1000)
smap {i ->
Coroutinescope(Dispatchers.defa
ult) .asyne {
#G)
>
}
sawaitAll()
print(*Finished")
str(i)
def #(4):
ita
with Pool(100@) as p:
.map (Fun
", iterable-range(1,
1001))
print(*Finished" )
val y = x.filter(p)
y = list(filter(p, ))
Alternative implementation:
y = [element for elenent in x if p(elem
ent)]
Print the message "xis
negative" to standarc
‘error (stderr), with
intoger x value
substitution (og. -2is
negative")
File(f).readText()
System.err.printin("$x is negative")
Lines = open(#).read()
Alternative implementation:
with open(f) as f
Lines = fo.read()
print(x, "is negative", filé
r)
ys.stder69 Seed random
generator
Use seed s to initialize a
random generator.
val random
reachi
print1n)
exitProcess(@)
fun main(args: Array) = args.fo
© Python
rand = random.Random(s)
print(" ‘.join(sys.argv[1:]))
sys.exit(1)
94 Print the type of a
variable printAn(
:r¢lass.simpleName)
print(type(x))
Print the name of the
type of x. Explain ifitis a
static type or dynamic
‘ype.
‘This may not make
sense in all languages.
Check string prefix
Set the boolean b to
true string s stats with
prefix prefix false
othemise,
val b = s.startswith(prefix)
‘Alternative implementation:
print(x.__class_)
b = s.startswith(prefix)
97 Check string sulfix
Setboolsan bio weir | B= Seendshith( suffix)
b = s.endswith(suffix)
string s ends with sting
suffix, false otherwise,K kotin
© Python
100 Sort by a comparator
Sertekmentscranay. | 4tems.sortiith(c)
items. sort (key=c)
like colecton items,
sing a comparator
Alternative implementation:
items. sort (key=functools .cmp_to_key(c))
410 Check if string is blank
ene a ank| val blank = s.dsNullorBlank()
blank = not s or s.isspace()
true the sting sis
‘empty, or nll, or
‘contains only whitespace
false otherwise
117 Got list size
Set nto the number of | Val n= x-size
n= len(x)
‘elements ofthe list x
419 Deduplicate list
rent et irom| % 7 XetoSet()-tolist()
x = list(set(x))
the ist x,
Explain ithe original
‘order is preserved.
‘Aternative implementation:
[ x = x.distinct()
Alternative implementation:
x = list(OrderedDict(zip(x, x)))
Alternative imp!
def dedup(x):
y= 0
for i in x:
if not 4 in y:
y-append()
tatlor
126 Multiple return values:
Write a function foo that
returns a string and a
boolean value.
fun useFoo() {
val a, b = foo()
return y
fun foo() : Pair = Pai | def foo():
(5, true) return ‘string’, True
,
NStenter conan | 8 € f20 if a1 else (20 if @ else 80 iF
clonmarsserat | 2 20 G3 else None
Sinétoncraina or | &2 > 20
se £9 if condton 3 is
we y
Dont evaluate a
condition when a
previous condition was
tue
Alternative implementation:
if 1
1)
elif c2:
£20)
elif c3:
BO
134 Create a new list
Declare and intiaize a | Val items = listof(a, b, ¢)
‘now lst items,
containing 3 elements a,
be.K kotin
© Python
187 Check if string
‘contains only digits
Set the boolean bo
true the sting
val regex = Regex("[0-9]*
val b = regex.matches(s)
‘contains only characters Alternative implementation:
inthe range 0.9, false
‘otherwise,
fun String?.isOnlyDigits() = !this.isNu
‘1lorempty() && this.all { Character.isD
agit (it) }
b = s.isdigit()
144 check if file exists
Set boolean b to true it
b = File(fb).exists()
b = os.path.exists (Fp)
file at path fp exists on
filesystem; fatse
othemise,
Beware that you should
‘never do this and then in
the next instruction
‘assume the results stil
vali, this is a race
‘condition on any
‘multitasking OS.
Alternative Implementation:
b = Path(fp).exists()
482 Turn a character into a
string
val §: String = ¢.testring() }
sec
Crwate sting =
containing only the
character
487 Declare constant string}
Initialize a constant
val planet
PLANET = ‘Earth’
planet with string value
“Earth
var x = items.last()
x = items[-1]
the last element of the
lst items,
Create the list ab
‘containing all the
‘elements of thelist a,
followed by all the
‘elements ofthe list
1166 Concatenate two lists
val ab= a+b
ab
4169String length
‘Assign tothe integer n
val n = $.length
n= len(s)
the number of characters
of the sting s.
Make sure that mutioyte
characters are property
handled
‘ncan be diferent from
the number of bytes of =179Get center of a
rectangle
Return the center ¢ of
the rectangle with
cobrdinates(xt,y1 x22)
186 Tomorrow
‘Assign to variable ta
string represanting the
day, month and year of
the day after the curent
date.
4186Exit program cleanly
Exit a program cleanly
indicating no error to OS
196Pass a sub-array
Given an integer array a
‘of size n, pass the frst,
thir, fith and seventh,
up tothe a th element
to.a routine foo which
sets all hese elements
1042
197Get alist of
afile
Retrieve the contents of
fie at path into alist of
strings lines, in which
‘each elements a line of
the fle
208 Get an environment
variable
185 from
fun center(x1
2: int)
2)
int, yi: int, x2: ant, y
Pair((xd + x2)/2, (yt + y2)/
Alternative implementation:
data class Point(val
Double)
data class Rectangle(val x1: Double, va
Lyi: Double, val x2: Double, val y2: D
ouble)<
fun center() = Point( x
2, y (yt + y2)/2)
Double, val
(xa + x2)/
© Python
center = ((x1+x2)/2, (y1+y2)/2)
Alternative implementation:
Point = namedtuple('Point’, ‘x y')
center = Point((x1+x2)/2, (yi+y2)/2)
}
val t = LocalDate.now().plusDays(1).tos || t = str(date.today() + timedelta(days=
tring() »)
exitProcess(@) sys.exit(@)
fun foo(a : IntArray, idx: IntProgressi
on) =
idx.foréach{ a[it] = 42 }
foo(a, @ .. (m-1) step 2)
def foo(data, r):
for iin rt
data[i] = 42
foo(a, range(®, m1, 2))
val lines = File(path).readLines()
with open(path) as f:
lines = f.readlines()
Read an environment
variable with the name
“FOO” and assign itto
the sting variable foo. f
it dows not exist or ifthe
system does not support
‘environment variables,
‘assign a value of none’
val foo = System.getenv("FOO") ?: “non
try:
foo = os-environ{ 'F00"]
except KeyError:
foo
Alternative implementation:
foo = getenv('F00", ‘none")
‘Alternative implementation:
foo = os.environ.get("F00", ‘none*)K rcotin i vnon
220 Create a tuple value
val t = Triple(2.5, "foo", true) t= (2.5, “hello”, -1)
Crwate t consisting of 3
values having different
types.
Explain i the elements
of tare strongly typed or
not
223 or else loop
Loop through Ist items
‘checking a condition. Do
something else ino
matches are found
items.find { it for item in items:
?.let { printin(*found it") } if item == ‘baz':
println(“never found it' print(*found it*)
break
else:
Alternative implementation: Seine (*never found it")
‘Atypical use case is
looping through a series
‘of containers looking for
‘one that matches a
‘condition. If found, an
itemis inserted:
otherwise, a new
‘container is created.
if(items.any { it
printin("found it")
else
println("never found it")
String(Base64.getDecoder().decode(s)) || data
base64.decode(s)
246 Count distinct
‘elements val c = itens.distinct().size € = len(set(itens))
Set cto the number of
distinct elements in the
lst items,
val (a, b, €) = listoF( a, b, c= 42, ‘hello’, 5.0
Define variables a, b and
ina concise way,
Explain ifthey need to
have the same type.
252Conditional
assignment
‘Assign tothe variable x
the sting value “aif
calling the function
condition returns true,
‘or the value"
othemise,
val x = if(condition()) "a" else if condition() elseKK rotin © Pytnon
266 Repeated string
Assign tothe string sthe| Val S = v.repeat(n) seven
value of the string v printin(s)
repeated a times, and
wat tout
Eg. wiser, mS
sc omabenbcbeby
260 Enum to Sng F
Enum testing | vate = T.8IKE c= Tahorse
ventieerumernted | 1 ST psnane Sl esnene
Wen Bke‘car horse, Prntln(s) prints)
Sette enmrvnon ete JL
sno tte ale
aumeote
Sete sin thd
th aig ropresertaon
Sater ona
on
rte
Deshrate over characters
ofa string s.forEachIndexed { i, c -> for i, ¢ in enumerate(s):
Patan chertise | _ PPantln("char $i is $c") print('char (i) is {c)')
fceeasnenonserest |}
troutngnanere te
the recede
ina nat abe den
Make sure that mult-
byte characters are
properly handled, and
‘count for a single
character.
289 Concatenate two
strings
Create the string s by
‘concatenating the stings
and.
302 String Interpolation
Given the integer x
‘assign to the string s the
value “Our sun has 8
planets", where the
number 8 was evaluated
from x.
vals=a+b s=a+b
val s
"our sun has $x planets” f'our sun has {x} planets’
You might also like
Go, Rust, Python, Kotlin, Scala, Dart Cheat Sheet
Go, Rust, Python, Kotlin, Scala, Dart Cheat Sheet
108 pages