I am trying to import the cProfile module into Python 3.3.0, but I got the following error:
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
import cProfile
File "/.../cProfile_try.py", line 12, in <module>
help(cProfile.run)
AttributeError: 'module' object has no attribute 'run'
The complete code (cProfile_try.py) is as follows
import cProfile
help(cProfile.run)
L = list(range(10000000))
len(L)
# 10000000
def binary_search(L, v):
""" (list, object) -> int
Precondition: L is sorted from smallest to largest, and
all the items in L can be compared to v.
Return the index of the first occurrence of v in L, or
return -1 if v is not in L.
>>> binary_search([2, 3, 5, 7], 2)
0
>>> binary_search([2, 3, 5, 5], 5)
2
>>> binary_search([2, 3, 5, 7], 8)
-1
"""
b = 0
e = len(L) - 1
while b <= e:
m = (b + e) // 2
if L[m] < v:
b = m + 1
else:
e = m - 1
if b == len(L) or L[b] != v:
return -1
else:
return b
cProfile.run('binary_search(L, 10000000)')
As noted in a comment, it is likely that there unexpectedly exists a file named profile.py, possibly in the current directory. This file is being unintentionally used by cProfile, thereby masking Python's profile module.
A suggested solution is:
mv profile.py profiler.py
Next, for good measure,
If using Python 3:
rm __pycache__/profile.*.pyc
If using Python 2:
rm profile.pyc
try to use "import profile as cProfile"
Related
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()
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
import math
import pylab
from matplotlib.pylab import *
import numpy as np
import scipy.fftpack
from scipy.io.wavfile import read
w = read('c:/users/ggg.wav')
a=np.array(w[1])
l=len(a)
#from __future__ import division
#b=(l/w[0])
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
print d
print l/d
e=l/d
for i in range(0,d):
k[9]=np.array(a[(i*e)+1:((i+1)*e)])
print k
this is a python code to frame an audio signal. But when i executed this code,i got an error "ValueError: setting an array element with a sequence.". How can i avoid this error?
There is another problem with your code I can at least help you with:
You can't assign k[9] without k being undefined. E.g:
>>> k[9] = 'test'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'k' is not defined
'k' needs to be defined as an array and needs to get the 'proper' index. You can't assign the index on it straight after.
See the following examples:
>>> k[9]='test'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list assignment index out of range
and
>>> k = [None]*10
>>> k[9]='test'
>>> k
[None, None, None, None, None, None, None, None, None, 'test']
This works fine with a sample .wav
w = read('ggg.wav')
a = w[1] # already an array
l=len(a)
b=(float(l)/w[0])
c=b*1000
d=int(c/40)
e=l/d
k = a[:e*d].reshape(d,e)
print k.shape
print k
print ''
k = [[] for i in range(d)] # initialize python list
for i in range(0,d):
k[i] = a[(i*e)+1:((i+1)*e)]
for i in k:
print i
# or
k = np.zeros((d,e-1),dtype='int') # initialize np.array
for i in range(d):
k[i,:] = a[(i*e)+1:((i+1)*e)]
print k
w[1] is already an np.array. I think what you want to break a into blocks e long. To do that, I truncated a and reshaped it, producing my k. Your indexing misses a[0], a[e], etc.
My entire code is below (didn't want to miss anything). For some reason I keep getting an error where I can't convert a float to an int?
import math
def getRange(input):
if (1 <= input < 10):
return [1,1,9]
elif (10 <= input < 190):
return [2,10,99]
elif (190 <= input < 2890):
return [3,100,999]
elif (2890 <= input < 38890):
return [4,1000,9999]
elif (38890 <= input < 488890):
return [5,10000,99999]
elif (488890 <= input < 5888889):
return [6,100000,999999]
def getDigit(input):
workingRange=getRange(input)
multi_digit_dec = ((input-workingRange[1])/workingRange[0])+workingRange[1]
multi_digit_float = math.floor((input-workingRange[1])/workingRange[0])+workingRange[1]
print multi_digit_float
multi_digit_int = input(multi_digit_float)
decimal_remainder = multi_digit_int - multi_digit_dec
## digit_id = decimal_remainder * len(str(multi_digit_int))
## actual_digit = str(multi_digit_dec)[digit_id]
## return actual_digit
getDigit(100)
My error is:
Traceback (most recent call last):
File "C:\Users\Samuel\Desktop\Python\concatenate string of variables and product values.py", line 29, in <module>
getDigit(100)
File "C:\Users\Samuel\Desktop\Python\concatenate string of variables and product values.py", line 22, in getDigit
multi_digit_int = int(multi_digit_float)
TypeError: 'int' object is not callable
>>>
Code updated above to reflect change of variable called int to input
The problem is that you're using int as a variable name, and that shadows the built-in function. Rename the variable.
In general, it's worth familiarizing oneself with the names of the built-in functions, to avoid this type of problems.
Don't use int as variable name (function getDigit).
In your stack of elif statements, if you start by testing if the input number is less than 1, then there's no need to check the lower ends of ranges other than the first. This will cut out half of the verbiage in the elif's. Also, it is more compact to use a loop for tests like this. For example, the following code produces the output shown below it.
def getRange(k):
if k < 1: return None
e = 1
for d in [10, 190, 2890, 38890, 488890, 5888889]:
if k<d:
return [e, 10**(e-1), 10**e -1]
e += 1
return None
for i in range(14):
print '{:8} {:20}'.format(i * 3**i, getRange(i * 3**i)),
if i&1: print
Output:
0 None 3 [1, 1, 9]
18 [2, 10, 99] 81 [2, 10, 99]
324 [3, 100, 999] 1215 [3, 100, 999]
4374 [4, 1000, 9999] 15309 [4, 1000, 9999]
52488 [5, 10000, 99999] 177147 [5, 10000, 99999]
590490 [6, 100000, 999999] 1948617 [6, 100000, 999999]
6377292 None 20726199 None
I think you want:
multi_digit_int = math.floor(multi_digit_float)
Also, don't use int as a variable name.
The problem with the line multi_digit_int = input(multi_digit_float) in your updated code is that the argument input in def getDigit(input): is hiding the built-in input() function. Since you calle getDigit with an argument of 100, inside the function input is an int instance so the input(multi_digit_float) part is being interpreted as 100(multi_digit_float), i.e. an int calling something.
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().