TypeError: 'int' object is not iterable in merge sort - mergesort

I am trying to write merge sort algorthim in python. I am keeping this error TypeError: 'int' object is not iterable
def merge(c,b,m,e):
i = b,j = m+1
l=[]
while (i<=m) and (j<=e):
if (c[i] < c[j]):
l.append(c[i])
else:
l.append(c[j])
if (i<=m):
while (i<=m):
l.append(c[i])
else:
while(j<=e):
l.append(c[j])
for i1 in l:
print(l[i1])
def merge_sort(collection,beg,end):
if(beg<end):
mid=(beg+end)//2
merge_sort(collection,beg,mid)
merge_sort(collection,mid+1,end)
merge(collection,beg,mid,end)
#return collection
if __name__ == '__main__':
user_input = input('Enter numbers separated by a comma:\n').strip()
unsorted = [int(i) for i in user_input.split(',')]
l = len (unsorted)
merge_sort(unsorted,0,l)

Related

I am getting None type object error but I do not know how and why it is occuring?

so I am writing a code for a binary tree and for some functions regardnig it, I am having some trouble running the code and I cannot figure out why this error is occuring.
def insertelement(self,n):
newnode = Node(n)
itr = self.root
x = False
if itr == None:
self.root = newnode
elif itr != None :
while x is False:
if itr.data > n:
itr = itr.right
elif itr.data < n:
itr = itr.left
elif ((itr.right == None) and itr.data > n):
itr.right = newnode
elif ((itr.left == None) and itr.data < n):
itr.left = newnode
else :
return 0
def binarysearchfordatass(self,n):
pppointer = self.root
i = 0
while pppointer.data != n:
if pppointer.data < n:
pppointer = pppointer.left
i = i+1
else:
pppointer = pppointer.right
i = i+1
return i
when I run the following code I get an error message
if itr.data > n:
AttributeError: 'NoneType' object has no attribute 'data'
so here as u can see in the code I already have an if statement which makes self.root = newnode if self.root is None, however I dont why the elif loop below it will execute on self.root if it is none since if it were none the if statement above it would have been executed.
Can someone please help me understand why this error is occuring ?
You are running into an infinite loop as you have set x to False and you are never updating x within the loop, thus the while condition is always True.
And yes you are checking if itr == None first but then you go into this inifinite loop and you might possibly be setting itr to None again in the first iteration of the loop and in the second iteration it will consequently then fail.
This is theoretically possible but you could easily find out what is actually going on by debugging your code and stepping through it line-by-line.

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

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]}

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

Scala Mismatch MonteCarlo

I try to implement a version of the Monte Carlo algorithm in Scala but i have a little problem.
In my first loop, i have a mismatch with Unit and Int, but I didn't know how to slove this.
Thank for your help !
import scala.math._
import scala.util.Random
import scala.collection.mutable.ListBuffer
object Main extends App{
def MonteCarlo(list: ListBuffer[Int]): List[Int] = {
for (i <- list) {
var c = 0.00
val X = new Random
val Y = new Random
for (j <- 0 until i) {
val x = X.nextDouble // in [0,1]
val y = Y.nextDouble // in [0,1]
if (x * x + y * y < 1) {
c = c + 1
}
}
c = c * 4
var p = c / i
var error = abs(Pi-p)
print("Approximative value of pi : $p \tError: $error")
}
}
var liste = ListBuffer (200, 2000, 4000)
MonteCarlo(liste)
}
A guy working usually with Python.
for loop does not return anything, so that's why your method returns Unit but expects List[Int] as return type is List[Int].
Second, you have not used scala interpolation correctly. It won't print the value of error. You forgot to use 's' before the string.
Third thing, if want to return list, you first need a list where you will accumulate all values of every iteration.
So i am assuming that you are trying to return error for all iterations. So i have created an errorList, which will store all values of error. If you want to return something else you can modify your code accordingly.
def MonteCarlo(list: ListBuffer[Int]) = {
val errorList = new ListBuffer[Double]()
for (i <- list) {
var c = 0.00
val X = new Random
val Y = new Random
for (j <- 0 until i) {
val x = X.nextDouble // in [0,1]
val y = Y.nextDouble // in [0,1]
if (x * x + y * y < 1) {
c = c + 1
}
}
c = c * 4
var p = c / i
var error = abs(Pi-p)
errorList += error
println(s"Approximative value of pi : $p \tError: $error")
}
errorList
}
scala> MonteCarlo(liste)
Approximative value of pi : 3.26 Error: 0.11840734641020667
Approximative value of pi : 3.12 Error: 0.02159265358979301
Approximative value of pi : 3.142 Error: 4.073464102067881E-4
res9: scala.collection.mutable.ListBuffer[Double] = ListBuffer(0.11840734641020667, 0.02159265358979301, 4.073464102067881E-4)

Scala: how to get random element form given list

I want to pick random element from given list:
def randomAlphaNumericChar(): Char = {
val ALPHA_NUMERIC_STRING = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789".toCharArray
Gen.oneOf(ALPHA_NUMERIC_STRING)
}
So currently this now compile:
type mismatch; found : org.scalacheck.Gen[Char] required: Char
Gen.oneOf(ALPHA_NUMERIC_STRING)
def randomAlphaNumericChar(): Char = {
/*
ASCII Codes
[0-9]: (48 to 57)
[A-Z]: (65 to 90)
[a-z]: (97 to 122)
*/
val alphabet = (48 to 57) union (65 to 90) union (97 to 122)
val i = scala.util.Random.nextInt(alphabet.size)
alphabet(i).toChar
}
For
val xs = ('a' to 'z') ++ ('A' to 'Z') ++ (1 to 9)
try
xs.maxBy(_ => scala.util.Random.nextInt)
Here maxBy applies a function to each element of the collection and then selects the maximum value returned by the function applied to each element. In this case the function is a random value returned from Random.nextInt.
Something like this will work
def randomAlphaNumericChar(): Char = {
val ALPHA_NUMERIC_STRING = "aAbBcCdDeEfFgGhHiIjJkKlLmMnNoOpPqQrRsStTuUvVwWxXyYzZ0123456789".toList
scala.util.Random.shuffle(ALPHA_NUMERIC_STRING).head
}