Why a Groovy List (of maps) arithmetic doesn't work as expected - groovy

I was trying to remove from a list of maps the elements that are present in another list. But found out that it doesn't work as i expected.
I can't understand the reason why.
def p1 = [1,2,3,4,5]
def p2 = [1, 3, 5]
assert p1[0] == p2[0]
assert p1[2] == p2[1]
assert p1[4] == p2[2]
assert [2,4] == p1-p2 // all ok
def q1 = [[1],[2],[3],[4],[5]]
def q2 = [[1], [3], [5]]
assert q1[0] == q2[0]
assert q1[2] == q2[1]
assert q1[4] == q2[2]
assert [[2], [4]] == q1-q2 // all ok
def t1 = [[1,2,3], [4,5,6], [7,8,9], [10,11,12], [13,14,15]]
def t2 = [[1,2,3], [7,8,9], [13,14,15]]
assert t1[0] == t2[0]
assert t1[2] == t2[1]
assert t1[4] == t2[2]
assert [[4,5,6], [10,11,12]] == t1-t2 // all ok
def r1 = [[a:1, b:1], [a:2,b:2], [a:3,b:3],[a:4,b:4], [a:5,b:5]]
def r2 = [[a:1, b:1], [a:3,b:3], [a:5,b:5]]
assert r1[0] == r2[0]
assert r1[2] == r2[1]
assert r1[4] == r2[2]
assert [[a:2,b:2], [a:4,b:4]] == r1-r2 // this is what I expected but fails
assert [] == r1-r2 // this is totally unexpected but it's ok
I can't figure out why. Can someone shed some light on this.
Thanks

Related

Is there a way i can avoid getting "None" when i print out my function?

I am trying to calculate the avarage grade of a subject. but when i print the function i get printed None.
And i do not know how to fix it.
Ive tried returning the value instead then printing the function, but it wont work.
def karakterKonversjon(bokstav):
if bokstav == 'A':
return 6
if bokstav == 'B':
return 5
if bokstav == 'C':
return 4
if bokstav == 'D':
return 3
if bokstav == 'E':
return 2
if bokstav == 'F':
return 1
def konversjonTilBokstav(tall):
if tall == 6:
return 'A'
if tall == 5:
return 'B'
if tall == 4:
return 'C'
if tall == 3:
return 'D'
if tall == 2:
return 'E'
if tall == 1:
return 'F'
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in emner:
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
THe result i am expecting is
4
C
But i am getting
4
None
I made a few modifications to your code:
(I assume you are importing math in the eksamen file)
def karakterKonversjon(bokstav): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(len(atof)):
if bokstav.upper() == atof[i]:
return len(atof) - i
def konversjonTilBokstav(tall): # make this function more efficient
atof = ['A','B','C','D','E','F']
for i in range(1,7):
if tall == i:
return atof[len(atof)-i]
def beregnSnitt():
nummer_karakter = 0
suM = 0
for i in range(len(emner)): # if enmer == "enmer"(for example) you cannot reference enmer['e'] without raising an error
if emner[i] != "":
tall_karakter = eksamen.karakterKonversjon(emner[i])
suM += (tall_karakter * studiepoeng)
suM /= totalPoeng
rundetSvar = eksamen.normal_round(suM)
eksamen.konversjonTilBokstav(rundetSvar)
print(rundetSvar)
def normal_round(suM):
if (float (suM) < 5):
print(math.floor(suM))
else:
print(math.ceil(suM))
apart from the differences i made, your code should work well however i cannot test without knowing what enmer is (i assume it's a string) or what studiepoeng is.
the function konversjonTilBokstav did work fine for me. But what I have included in the code snippet should be less spaghetti code

Why is this BFS queue returning None?

I am currently attempting the Hackerrank problem called Castle on the Grid,
in which I have implemented a BFS in Python 3 as follows:
#!/bin/python3
import math
import os
import random
import re
import sys
from collections import deque
def minimumMoves(grid, startX, startY, goalX, goalY):
n = len(grid)
queue = deque()
queue.append((startY,startX))
goal = (goalY,goalX)
turnsMatrix = [[0]*n]*n
while queue:
current = queue.popleft()
(Y0, X0) = current
print(current)
d = turnsMatrix[Y0][X0]
if current == goal:
return(d)
for X in range(X0-1,-1,-1):
if grid[Y0][X] == 'X':
break
elif turnsMatrix[Y0][X] == 0:
turnsMatrix[Y0][X] = d + 1
queue.append((Y0,X))
for Y in range(Y0-1,-1,-1):
if grid[Y][X0] == 'X':
break
elif turnsMatrix[Y][X0] == 0:
turnsMatrix[Y][X0] = d + 1
queue.append((Y,X0))
for X in range(X0+1,n):
if grid[Y0][X] == 'X':
break
elif turnsMatrix[Y0][X] == 0:
turnsMatrix[Y0][X] = d + 1
queue.append((Y0,X))
for Y in range(Y0+1,n):
if grid[Y][X0] == 'X':
break
elif turnsMatrix[Y][X0] == 0:
turnsMatrix[Y][X0] = d + 1
queue.append((Y,X0))
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
n = int(input())
grid = []
for _ in range(n):
grid_item = input()
grid.append(grid_item)
startXStartY = input().split()
startX = int(startXStartY[0])
startY = int(startXStartY[1])
goalX = int(startXStartY[2])
goalY = int(startXStartY[3])
result = minimumMoves(grid, startX, startY, goalX, goalY)
fptr.write(str(result) + '\n')
fptr.close()
However, despite only one return statement which is supposed to return an int d, my code returns a None. I know that the deque eventually becomes empty and returns None, but I am having trouble figuring out why things stop appending to the queue.
For the test case
3
.X.
.X.
...
0 0 0 2
I noticed that what would happen is:
1) castle moves right and breaks at X.
2) castle moves down one cell, and the turns matrix becomes
[[1, 0, 0], [1, 0, 0], [1, 0, 0]].
3) queue becomes deque([(1, 0)]).
4) A None is returned.
What is going on? I've been staring at my code for days and I'm going crazy... please help, thank you!

Why does groovy map key evaluation behave differently in similar circumstances when using GStrings?

I would appreciate someone explaining to me why the following is true:
def t = "test"
assert [test: 1] == ["test": 1] // 1. expected
assert ["$t": 1] != ["test": 1] // 2. unexpected
assert ["$t": 1] != [test: 1] // 3. unexpected
assert ["$t": 1] == ["$t": 1] // 4. expected
println ["$t": 1] // output: [test: 1]
println ["test": 1] // output: [test: 1]
I don't understand why there is the inequality for results #2 and #3.
I ran into this in writing a test where the key get dynamically created in the code, but given the test conditions I know it should be the string "test". The problem is that the returned "appears" correct but is not considered equal. And I don't understand why.
Further, the following "works":
def t = "test"
def odd = ["$t": 1]
assert !odd["$t"]
assert !odd.test
assert !odd["test"]
assert !odd."$t"
println odd // output: [test: 1]
def d = new Date()
def t2 = "$t"
def odd2 = [(t2): 1, (d): 2]
assert odd2[d] == 2
assert !odd2[d.toString()]
assert !odd2[t2] // expected 1
odd2.put(t2, 3)
println odd2 // output: [test: 3, /* date#toString */: 2]
assert odd.getAt(d) == 2
assert !odd2.getAt(t2) // expected 3
Add these 2 lines
assert "$t".class.simpleName == 'GStringImpl'
assert t.class.simpleName == 'String'
or just
println "$t".class
println t.class
after the first line, you will be able to understand why. :)
If you actually want to use the value of t then you should use as:
assert [(t): 1] == ["test": 1] //use (t) to use the variable value as key
assert [(t): 1] == [test: 1]
assert [(t): 1] != ["$t": 1]
UPDATE
//String key as before, hence encouraged to use (t) instead of GStringImpl
def odd = [("$t".toString()): 1]
assert odd["$t"]
assert odd.test
assert odd["test"]
assert odd."$t"
//Equality by reference and by value in Groovy
assert "$t" == "test" //Value Equality == overridden in Groovy
assert !"$t".is("test") //Object Reference equality equivalent to == in Java

Adding curried closure as static property with expando metaclass loses default parameter value

I encountered this in both Groovy 1.8.6 and 2.0.0.
So these scenarios all work as expected:
def ay = { one, two=[:] -> [one, two] }
def be = { one, two, three=[:] -> [one,two,three] }
def ayprime = ay.curry('PRIME')
def beprime = be.curry('PRIME')
def beprimer = be.curry('PRIME', 'PRIMER')
assert ay(1,2) == [1,2]
assert ay(1) == [1,[:]]
assert be(1,2,3) == [1,2,3]
assert be(1,2) == [1,2,[:]]
assert ayprime(1) == ['PRIME', 1]
assert ayprime() == ['PRIME', [:]]
assert beprime(1,2) == ['PRIME', 1, 2]
assert beprime(1) == ['PRIME', 1, [:]]
assert beprimer(1) == ['PRIME', 'PRIMER', 1]
assert beprimer() == ['PRIME', 'PRIMER', [:]]
As does this:
class Klass {
static def smethod = { one, two=[:] -> [one, two] }
}
assert Klass.smethod(1,2) == [1, 2]
assert Klass.smethod(1) == [1, [:]]
This also works, as expected:
Klass.metaClass.static.aymethod << ay
assert Klass.aymethod(1) == [1, [:]]
The default parameter to the uncurried closure survives the assignment to Klass.
However, this fails:
Klass.metaClass.static.ayprimemethod << ayprime
assert Klass.ayprimemethod() == ['PRIME', [:]]
thusly:
assert Klass.ayprimemethod() == ['PRIME', [:]]
| |
[PRIME, null] false
and similarly, this fails:
Klass.metaClass.static.beprimermethod << beprimer
assert Klass.beprimermethod() == ['PRIME', 'PRIMER', [:]]
thusly:
assert Klass.beprimermethod() == ['PRIME', 'PRIMER', [:]]
| |
| false
[PRIME, PRIMER, null]
With the curried closures, the default parameter value works directly, but is lost when the closure is assigned as a static member of Klass.
This seems like a bug. I couldn't find this behavior documented anywhere. Am I missing something?
If the problem is still bothering you, i think this might be a workaround, until it gets fixed in groovy trunk. The python way to curry stuff:
def ayprime = { x -> x ? ay('PRIME', x) : ay('PRIME') }
def beprime = be.curry('PRIME')
def beprimer = { x -> x ? be('PRIME', 'PRIMER', x) : be('PRIME', 'PRIMER') }

Groovy sample application using queue and linked list

Can you please give me a sample application using Groovy which makes use of queue and linked list?
An exemple with a queue:
def q = ["elem1", "elem2"] as Queue
q.offer("inserted string")
assert q.peek() == "elem1"
assert q.poll() == "elem1"
assert q.poll() == "elem2"
assert q.poll() == "inserted string"
Here is an exemple with a linked list:
def l = [1, 2, 3] as LinkedList
assert l[0] == 1
l.add(4)
assert l.last() == 4

Resources