How to create a typed dict in Numba where (key, value) = (str, list) - numba

I am trying to create a dictionary in nopython mode. This is what I have:
import numba
#numba.njit()
def func():
d = numba.typed.Dict.empty(
key_type=numba.types.unicode_type,
value_type=numba.ListType(np.float64)
)
d["a"] = [1, 1]
return d
print(func())
Error:
Invalid use of Function(<class 'numba.types.containers.ListType'>) with argument(s) of type(s): (Function(<class 'float'>))
* parameterized
In definition 0:
TypeError: typer() takes 0 positional arguments but 1 was given

Seems that there's need to declare ListType outside of njit block (at least I'm not able to do that differently). Also you have to append elements to list one by one. Try this code:
import numba
list_type = numba.types.ListType(numba.types.float64)
#numba.njit()
def func():
d = numba.typed.Dict.empty(
key_type=numba.types.unicode_type,
value_type=list_type
)
d["a"] = numba.typed.List.empty_list(numba.types.float64)
d["a"].append(1)
d["a"].append(1)
return d
print(func())
Output:
{a: [1.0, 1.0]}

Related

trying to solve palindrome integer in python 3 code is working but giving wrong output

enter code here''' class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
lst = list(x)
str_val = []
count = len(lst)
for i in range(len(lst)):
str_val.append(lst[count-1])
count -= 1
value = [str(i) for i in str_val]
res = int("".join(value))
if int(res) == x:
return True
else:
return False
'''
trying to solve palindrome integer in python 3 code is working but giving wrong output.
If you're just trying to check for integers only, you can try the below code. It's a two pointer approach.
class Solution:
def isPalindrome(self, x: int) -> bool:
x = str(x)
if len(x) < 2: return True
s, e = 0, len(x)-1
while s < e:
if x[s] != x[e]: return False
s += 1
e -= 1
return True
You can also do this in one line in python to check if a number (as a string) and it's reverse is same or not.
str(x) == str(x)[::-1]
The reason your results are not as expected is due to the type change that you make in the first line of your function.
x = str(x)
It is necessary to convert x into a string so that you can iterate over it and put it into a list for your second line of code:
lst = list(x)
but by re-assigning that back to x, you get an x at the end of the function call that is not equal to the int(res) when you make the final comparison to get your boolean:
if int(res) == x:
A simple solution is to just not assign the temporary string that is created from the parameter x back to itself, and rather to just merge the first and second lines of your function into one:
lst = list(str(x))

How to implement twice function (function that executes other function twice)? Could not match type Record with type Function Int

Here is the code
module Main where
import Prelude
twice1 f = f . f
transform :: Int -> Int
transform n = n + 1
apply1 x = (twice1 transform) x
I have an error
Could not match type
Record
with type
Function Int
What's wrong? (you can try code here http://try.purescript.org)
PureScript uses the dot . for accessing record fields, as in:
r = { a: 42, b: "what?!" }
fourtyTwo = r.a
The function composition operator in PureScript is <<< (or >>> for left-to-right composition), for example:
twice1 f = f <<< f

Unable to create a variable of an Enumeration

I have created an Enumeration as follows:
scala> object J extends Enumeration {
| type J = Value
| val Fail, Success = Value
| }
defined object J
Question 1 - I tried to create a variable of its type but got the following error. Why?
scala> val j:J
<console>:11: error: not found: type J
val j:J
^
<console>:11: error: only classes can have declared but undefined members
val j:J
^
Question 2 - I could create a variable as follows. I suppose the Fail's value is actually 0. How could I print 0?
scala> val j = J.Fail
j: J.Value = Fail
scala> println(j)
Fail
You are using the wrong syntax to assign a type variable, you should do:
val j = J
j: J.type = J
Regarding the value, Fail and Sucess has no value apart from its own name, if you want to assign a value to them you should use this syntax:
object J extends Enumeration {
type J = Value
val Fail = Value(0)
val Success = Value(1)
}
Then you can access to it ussing its id property
scala> j.id
res: Int = 0
scala> j
res: J.Value = Fail

Can't use a negative number in named parameters in Scala

I'm using Scala 2.11.2.
If I have this Fraction class:
case class Fraction(numerator: Int, denominator: Int) {}
Then this gives an error:
val f = new Fraction(numerator=-1, denominator=2)
But this is not:
val f = new Fraction(-1, denominator=2)
The error message is:
Multiple markers at this line
- not found: value
numerator
- not found: value
numerator
I tried to use negative numbers in other snippets with the same result, but the documentation doesn't mentions that this is not possible.
Am I doing something wrong?
Thanks
You need a space between the = and the -, or you can wrap the -1 in parentheses, otherwise the compiler gets confused. This is because =- is a valid method name, so the compiler cannot tell whether you are assigning a value to a named parameter, or making a method call.
so this gives an error:
val f = Fraction(numerator=-1, denominator=2)
but this is OK:
val f = Fraction(numerator = -1, denominator = 2)
and so is this:
val f = Fraction(numerator=(-1), denominator=2)

Creating immutable instances and modifying copies in an idiomatic way

I would like to conditionally create copies of an object instance depending on information external to that instance. Most of the information in the copies will be the same as the original, but some of the information will need to change. This information is being passed around between actors, so I need the objects to be immutable in order to avoid strange concurrency-related behavior. The following toy code is a simple example of what I would like some help with.
If I have the following code:
case class Container(condition:String,amount:Int,ID:Long)
I can do the following:
val a = new Container("Hello",10,1234567890)
println("a = " + a)
val b = a.copy(amount = -5)
println("b = " + b)
println("amount in b is " + b.amount)
and the output is
a = Container(Hello,10,1234567890)
b = Container(Hello,-5,1234567890)
amount in b is -5
I can also conditionally create copies of the object doing the following:
import scala.Math._
val max = 3
val c = if(abs(b.amount) >= max) b.copy(amount = max,condition="Goodbye") else if(abs(b.amount) < max) b.copy(amount = abs(b.amount))
println("c = " + c)
If I set the amount in the b object to -5, then the output is
c = Container(Goodbye,3,1234567890)
and if I set the amount in the b object to -2, then the output is
c = Container(Hello,2,1234567890)
However, when I try to print out c.amount, it gets flagged by the compiler with the following message
println("amount in c is " + c.amount)
value amount is not a member of Any
If I change the c object creation line to
val c:Container = if(abs(b.amount) >= max) b.copy(amount = max,condition="Goodbye") else if(abs(b.amount) < max) b.copy(amount = abs(b.amount))
I get the compiler error
type mismatch; found: Unit required:
Container
What is the best, idiomatic way of conditionally creating immutable instances of case classes by copying existing instances and modifying a value or two?
Thanks,
Bruce
You are not including a final else clause. Thus the type of c is Any -- the only type that is supertype both of Container and Unit, where Unit is the result of not including a catch-all else clause. If you try to force the result type to be Container, by writing c: Container =, the compiler now tells you the missing else clause resulting in Unit is not assignable to Container.
Thus
val c = if (abs(b.amount) >= max) {
b.copy(amount = max, condition = "Goodbye")
} else if (abs(b.amount) < max) {
b.copy(amount = abs(b.amount))
} else b // leave untouched !
works. The compiler isn't smart enough to figure out that the last else clause cannot be logically reached (it would need to know what abs and >= and < means, that they are mutual exclusive and exhaustive, and that abs is purely functional, as is b.amount).
In other words, since you know that the two clauses are mutually exclusive and exhaustive, you can simplify
val c = if (abs(b.amount) >= max) {
b.copy(amount = max, condition = "Goodbye")
} else { // i.e. abs(b.amount) < max
b.copy(amount = abs(b.amount))
}