Rewriting R's density() (not really) - python

In response to this question, I took upon the challenge to make my understanding on R's density() function.
Since I'm pretty much very new to R, I have no ideas about vectors regarding the c() function, which made me use a list as the closest form.
I would make this function:
def density(x, bw, adjust):
bw2 = None
result = 0
if bw == "nrd0":
bw2 = 31.39367
else:
print("No such bandwidth.")
for i in range[len(x)]:
x[i] = x[i] * bw2
for i in range[len(x)]:
result = result + x[i]
return result * adjust
And I wanted to test it:
x = [1, 3, 5]
kern = density(x, "nrd0", 1)
print(kern)
And I gained 2 errors, the main one being a TypeError.
If you want to look into it further, here's the whole terminal message:
Traceback (most recent call last):
File "density.py", line 15, in <module>
kern = density(x, "nrd0", 1)
File "density.py", line 8, in density
for i in range[len(x)]:
TypeError: 'type' object is not subscriptable
How do I fix the TypeError?

for i in range[len(x)]:
x[i] = x[i] * bw2
You have range with [] while it should be (). Try to change it.
Below is an example:
l = [10, 20, 30, 40]
for i in range(len(l)):
print(l[i], end =" ")
print()

Related

How to implement input function to a specific code without getting error messages

This is the whole code of the function I defined
def solve(eq, var=('x', 'y')):
import re
var_re = re.compile(r'(\+|\-)\s*(\d*)\s*\*?\s*(x|y)')
const_re = re.compile(r'(\+|\-)\s*(\-?\d+)$')
constants, eqns, coeffs, default = [],[], {'x': [], 'y': []}, {'': '1'}
for e in eq.split(';'):
eq1 = e.replace("="," - ").strip()
if not eq1.startswith('-'):
eq1 = '+' + eq1
eqns.append(eq1)
var_eq1, var_eq2 = map(var_re.findall, eqns)
constants = [-1*int(x[0][1]) for x in map(const_re.findall, eqns)]
[coeffs[x[2]].append(int((x[0]+ default.get(x[1], x[1])).strip())) for x in (var_eq1 + var_eq2)]
ycoeff = coeffs['y']
xcoeff = coeffs['x']
# Adjust equations to take out y and solve for x
if ycoeff[0]*ycoeff[1] > 0:
ycoeff[1] *= -1
xcoeff[0] *= ycoeff[1]
constants[0] *= -1*ycoeff[1]
else:
xcoeff[0] *= -1*ycoeff[1]
constants[0] *= ycoeff[1]
xcoeff[1] *= ycoeff[0]
constants[1] *= -1*ycoeff[0]
# Obtain x
xval = sum(constants)*1.0/sum(xcoeff)
# Now solve for y using value of x
z = eval(eqns[0],{'x': xval, 'y': 1j})
yval = -z.real*1.0/z.imag
return (xval, yval)
I tried using multiple ways to make the function solve input like
equation1 = int(input(("Enter the first equation: "))
num1 = int(input("Enter the second equation: "))
print (solve(equation1; num1))
with and without int and
num3 = input("Enter both equations using semicolon between them: ")
solve('num3')
and
b = int(input(("Enter both equations using semicolon between them: "))
print("The prime factors of", b, "are", solve(b))
but error messages like
Traceback (most recent call last):
File "C:/Users/ABDELRAHMANSHERIF/ujn.py", line 45, in <module>
solve('num3')
File "C:/Users/ABDELRAHMANSHERIF/ujn.py", line 15, in solve
var_eq1, var_eq2 = map(var_re.findall, eqns)
ValueError: not enough values to unpack (expected 2, got 1)
and some other error messages
so how can I put the input function where the user enters the equations and it gets solved. I know I can just use the solve function in the shell but its a part of a bigger project.
The function solves simultaneous equations by the way.
The function that you use is designed to solve a system of linear equations with two variables x and y. The syntax that you need to use is the following "first_equation;second_equation" :
equation1 = "2*x+3*y=6;4*x+9*y=15"
print(solve(equation1))
If you run it, you will have the result : (1.5, 1.0)
In order to have well written function, the best is to add docstring (or doctest) after the name of your function in order to know how to call it.

Fix a method to convert list of integers to NumPy matrix

I want to create random integers and convert them in binary format via NumPy matrix. I wrote the following code:
def toBinary(C):
l = []
for x in C:
b = [int(i) for i in bin(x)[2:]]
l = np.vstack((l, np.array(b)))
return l
list_vectors = [random.randint(0, 2 ** 64) for _ in range(2)]
print(toBinary(list_vectors))
But I still don't know how to solve this error:
Traceback (most recent call last):
File "test.py", line 31, in <module>
print(toBinary(list_vectors))
File "test.py", line 27, in toBinary
l = np.vstack((l, np.array(b)))
File "/anaconda3/lib/python3.6/site-packages/numpy/core/shape_base.py", line 234, in vstack
return _nx.concatenate([atleast_2d(_m) for _m in tup], 0)
ValueError: all the input array dimensions except for the concatenation axis must match exactly
Any suggestion is highly appreciated.
The issue here is that the conversion to binary does not always return a binary number of same length.
If the first integer in C is, let's say 3, it'll give '0b11'. Stack this in the array, then try to convert 17. Oops, you're trying to concatenate '11' and '1001' together, it won't work.
What I did here then, is forcing the converted binary number length to 10 using the format() function (Convert to binary and keep leading zeros in Python).
import numpy as np
import numpy.random as random
def toBinary(C):
binaries_length = 10
bin_format = f'#0{binaries_length+2}b'
array_rows = len(C)
l = np.empty((array_rows, binaries_length))
for i, x in enumerate(C):
l[i,:] = np.array([int(i) for i in format(x, bin_format)[2:]])
return l
list_vectors = [random.randint(0, 2 * 64) for _ in range(10)]
print(toBinary(list_vectors))
Also, the returned array is pre-allocated, since you now perfectly know what size it will be :
binaries_length = 10
bin_format = f'#0{10+2}b'
array_rows = len(C)
l = np.empty((array_rows, binaries_length))
By the way, the call random.randint(0, 2 ** 64) also triggers an exception because 2 ** 64 is insanely too high so I changed it to 2*64 here.
To go further, you can find the optimal binary length by finding the maximum of C.
Try this, it will return a list instead of array, so make the necessary adjustments if you like:
def toBinary(C):
l = []
for x in C:
b = [i for i in bin(x)[2:]]
a="".join(b)
a=int(a)
l.append(a)
return l

Datatype definition - TypeError

import cmath
import math
import random
import time
P = []
V = []
Vin = []
def Compute_wn_win(n,V,Vin):
for i in range (0,n):
V.append(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n)))
Vin.append(1/(complex(math.cos(2*math.pi*i/n),math.sin(2*math.pi*i/n))))
Compute_wn_win(8,V,Vin)
for i in range(0,8):
random_number = random.uniform(-1.0,1.0)
P.append(random_number)
def FFT(P,V,n):
if(n==1):
return P[0]
else:
Peven = []
Podd = []
for i in range(0,n/2):
Peven.append(P[2*i])
Podd.append(P[(2*i)+1])
Vsquared = []
for i in range(0,n/2):
Vsquared.append(V[i]*V[i])
Sole = FFT(Peven,Vsquared,n/2)
Solo = FFT(Podd,Vsquared,n/2)
Sol = [0 for x in range(0,n)]
for i in range(0,n/2):
Sol[i] = Sole[i]+V[i]*Solo[i]
Sol[i+n/2] = Sole[i]-V[i]*Solo[i]
return Sol
Sol = FFT(P,V,8)
I am new to Python. I have the following code. However I get the following error for lines Sole = FFT(Peven,Vsquared,n/2) and Sol[i] = Sole[i]+V[i]*Solo[i]. However, I have defined, Sole, Solo and Sol as list data type so I don't understand why it mentions that float datatype does not have an attribute getitem
Exact Error is
Traceback (most recent call last):
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 40, in <module>
Sol = FFT(P,V,8)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
Sole = FFT(Peven,Vsquared,n//2)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 33, in FFT
Sole = FFT(Peven,Vsquared,n//2)
File "/Users/globetrekker/Documents/CS5050/Assignment7/Test_py.py", line 37, in FFT
Sol[i] = Sole[i]+V[i]*Solo[i]
TypeError: 'float' object has no attribute '__getitem__'
Sole and Solo are the return values from recursive calls to FFT(), but FFT()'s base case (when n == 1) returns a float, not a list, so the step above the base case will fail by trying to index a float. Presumably, you want to change return P[0] in the base case to return [P[0]].
This is introducing a float:
for i in range(0,n/2):
Checkout: I keep getting this error for my simple python program: "TypeError: 'float' object cannot be interpreted as an integer"

Trying to run for-loop, being told that 'float' object is not iterable

I'm trying to do some fractal image processing, and when running my code, I get told
Traceback (most recent call last):
File "all_the_maps.py", line 72, in <module>
(xh, yh) = Hf(xf,yf,r)
TypeError: 'float' object is not iterable
The relevant code block is
(xf,yf) = (0,0)
(xh,yh) = (0,0)
for n in xrange(N):
r = random.randint(1,10000)
(xf,yf) = F(xf,yf,r)
(xh,yh) = Hf(xh,yh,r)
h[int(round(xh)),int(round(yh))] = f[int(round(xf)),
int(round(yf))]
and the full file is at http://pastebin.com/kbJD3BK9 (it's pretty long and I'm not very good at python, so it might be painful to read).
I've looked at other people getting this error, and it seems like they're iterating over something that can't be iterated over (e.g. for i in 7: instead of for i in range(7): ). However, this doesn't seem to be what I'm doing wrong, and I don't really have any idea what to do. If anyone could help, it would really be appreciated.
EDIT: Hf is defined as:
def Hf(x,y,r):
if r <= 10000*a*b:
return 0.5*x, 0.5*y
elif r <= 10000*b:
return 0.5*x + 255.0
elif r <= 10000*(1 - a + a*b):
return 0.5*x + 255.0, 0.5*y + 255.0
else:
return 0.5*x, 0.5*y + 255.0
Your second case
elif r <= 10000*b:
return 0.5*x + 255.0
doesn't return a tuple like the others.
To clarify - in your main program, in the line (xh,yh) = Hf(xh,yh,r), you're expecting two items on the right hand side. If r <= 10000*b, Hf will only return a single float rather than the tuple that the other cases return.

What is wrong with my merge sort in python?

I am trying to write merge sort and stuck here.
What is the problem here with my code? I am trying to implement it without referring any resources and unnecessarily writing this line since some dumb rule in Stackoverflow forces to me explain my code.
def merge_sort(A):
if len(A) <= 1:
return A
#split list in 2
mid = len(A)/2
B = A[:mid]
C = A[mid:]
B = merge_sort(B)
C = merge_sort(C)
#merge
result = []
while len(B) > 0 and len(C) > 0:
if B[0] > C[0]:
result.append(C.pop(0))
else:
result.append(B.pop(0))
if len(B) > 0:
result.extend(merge_sort(B))
else:
result.extend(merge_sort(C))
print merge_sort([8, 2, 1, 1, 4, 45, 9, 3])
I get this error:
Traceback (most recent call last):
File "merge_sort.py", line 31, in <module>
print merge_sort([8, 2, 1, 1, 4, 45, 9, 3])
File "merge_sort.py", line 11, in merge_sort
B = merge_sort(B)
File "merge_sort.py", line 16, in merge_sort
while len(B) > 0 and len(C) > 0:
TypeError: object of type 'NoneType' has no len()
You merge_sort() function needs to
return result
at the end but it does not. Functions return None by default and this is why you get the error.
You forgot to write return result at the end of the function. Without that line, the function returns None, which eventually leads to a len(None) and the subsequent TypeError: object of type 'NoneType' has no len().

Categories