I have written a module memories.py using Python 2.7 (unfortunately, I cannot use the latest version due to some restriction). It looks as follows.
import random
def get_a_random_memory(length, upper_sum_range, lower_sum_range):
# Start with a blank memory
memory = list()
# For each bit along the length we add a random value
for i in range(0, length):
memory.append((2 * random.randint(0, 1) - 1))
return memory
The error message is as follows.
>>> import memories
>>> print memories.get_a_random_memory(5, 0, 10)
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "xyz\memories.py", line 21, in get_a_random_memory
# For each bit along the length we add a random value
NameError: global name 'randint' is not defined
Could anyone please help me out here?
Related
I already know this question has been answered a million times, and I tried to follow other user examples and got confused, so bear with me.
I have an assignment where I need to have 1 input integer from user, that makes turtle (I named it jamie) move n number of polygon sides and a function that (pulled from rubric):
has 3 parameters:
our_turtle draw a single regular polygon.
polygon should have num_sides number of sides,
sides of equal length side_length,
and all angles in a given polygon will be the same.
It keeps coming back with our_turtle as "NameError: name 'our_turtle' is not defined".
code below
def main():
import turtle
jamie = turtle.Turtle()
num_sides = int(input("please input positive integer that is 3 or greater: "))
draw_polygon(our_turtle, num_sides, side_length)
def draw_polygon(our_turtle, num_sides, side_length):
our_turtle = jamie.begin_poly()
side_length = (num_sides - 2) * (180 / num_sides)
for i in range(num_sides):
jamie.left(side_length)
return our_turtle
main()
Did the code and got this error:
please input positive integer that is 3 or greater: 3
Traceback (most recent call last):
File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 35, in <module>
main()
File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 12, in main
draw_polygon(our_turtle, num_sides, side_length)
NameError: name 'our_turtle' is not defined
I tried putting in our_turtle into main() to see what would happen, and then got this error:
Traceback (most recent call last):
File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 34, in <module>
main()
File "D:\2022FALL_INTO_PROG\ValentinePA04.py", line 12, in main
draw_polygon(our_turtle, num_sides, side_length)
UnboundLocalError: local variable 'our_turtle' referenced before assignment
I will say that local/global variables are really confusing to me, mainly because I am confused as to when python 'switches' between the two? So I am not sure how to fix this problem
I have a code in torch and I have to change it to keras but when I do this for the following code it produces this error:
Traceback (most recent call last):
File "", line 3, in
jpe[channel]=mask
TypeError: 'RefVariable' object does not support item assignment
I think this error is for assignment, but I do not know how can I solve it. the main code in torch was:
yuv_keep_weighs=(25,9,9)
requested_shape=(100,100)
jpeg_mask=None
if jpeg_mask is None or requested_shape > jpeg_mask.shape[1:]:
jpeg_mask = torch.empty((3,) + requested_shape)
for channel, weights_to_keep in enumerate(yuv_keep_weighs):
mask = torch.from_numpy(get_jpeg_yuv_filter_mask(requested_shape, 8, weights_to_keep))
jpeg_mask[channel] = mask
I changed it
yuv_keep_weighs=(25,9,9)
requested_shape=(100,100)
jpeg_mask=None
if jpeg_mask is None or requested_shape > jpeg_mask.shape[1:]:
jpeg_mask = K.zeros((3,) + requested_shape)
for channel, weights_to_keep in enumerate(yuv_keep_weighs):
mask = K.variable(get_jpeg_yuv_filter_mask(requested_shape, 8, weights_to_keep))
jpeg_mask[channel] = mask
but the last line produces the error and I do not know how can I do assignment in tensorflow? please, guide me about this issue.
I am getting more and more confused in python.
when i try on one row, it works, but when i work on the whole rows of one column, it shows error.
i want to use the function convert_hex_to_int for each row in the column,
but it shows me the error
Traceback (most recent call last):
File
"C:/Users/ranic/.PyCharmCE2018.3/config/scratches/scratch_2.py", line
59, in
result_print = (convert_hex_to_int(hex_int, 4))
File "C:/Users/r/.PyCharmCE2018.3/config/scratches/scratch_2.py", line 32,
in conver
t_hex_to_int
splitted = [hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)] TypeError: 'str' object cannot be
interpreted as an integer
here is my code:
cnxn = pyodbc.connect(conn_str)
cnxn.add_output_converter(pyodbc.SQL_VARBINARY, hexToString)
cursor = cnxn.cursor()
def convert_hex_to_int(n:int, interval:int):
splitted = [hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)]
return [int(hex(unpack('<H', pack('>H', int(i, 16)))[0]), 16) for i in splitted]
try:
cursor.execute(query)
row=cursor.fetchval()
row_list=[]
while row is not None:
row=cursor.fetchval()
hex_int = int(row, 16)
result_print = (convert_hex_to_int(hex_int, 4))
result_float = [float("{0:.2f}".format((i) * 10 ** -2)) for i in result_print]
row_list.append(result_float)
print(row_list)
Please leave any comment if I miss something, thanks in advance.
When I debugged it, it shows something like this:
Debugged screen
*sorry I had to attach the image as it is the debugged screen and i cant copy the code, and it had to be in link because i am a new user
**edit: i think it has to do with the use of .fetchval twice, but im not too sure
If the line
[hex(n)[2:][i:i + interval] for i in range(0, len(hex(n)[2:]), interval)]
Results in
TypeError: 'str' object cannot be interpreted as an integer
Then n must not be an integer.
Observe, if n is '0x94069206':
>>> hex('0x94069206')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object cannot be interpreted as an integer
As the code is taking slices of n it looks as if n needs to be a string, so the line should be:
splitted = [n[2:][i:i + interval] for i in range(0, len(n[2:]), interval)]
It follows that the function signature should be
def convert_hex_to_int(n:str, interval:int)
On the other hand, if n is an int then the next line needs to be reworked.
I am trying to replicate a section of code from the graph-tool cookbook to find the marginal probablity of the number of groups in a graph when using hierarchical partitioning. I however get an error telling me that 'NestedBlockState' object has no attribute 'get_nonempty_B' so presumably I have made a mistake somewhere. Does anybody know where I went wrong?
import graph_tool.all as gt
import cPickle as pickle
g = gt.load_graph('graph_no_multi_reac_type.gt')
gt.remove_parallel_edges(g)
state = gt.minimize_nested_blockmodel_dl(g, deg_corr=True)
state = state.copy(sampling=True)
with open('state_mcmc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
print 'equilibrating Markov chain'
gt.mcmc_equilibrate(state, wait=1000, mcmc_args=dict(niter=10))
h = np.zeros(g.num_vertices() + 1)
def collect_num_groups(s):
B = s.get_nonempty_B()
h[B] += 1
print 'colleting marginals'
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
callback=collect_num_groups)
with open('state_ncnc.pkl','wb') as state_pkl:
pickle.dump(state,state_pkl,-1)
with open('hist.pkl','wb') as h_pkl:
pickle.dump(h,h_pkl,-1)
The error I get looks as follows:
Traceback (most recent call last):
File "num_groups_marg_prob.py", line 42, in <module>
gt.mcmc_equilibrate(state, force_niter=10000, mcmc_args=dict(niter=10),
File "/usr/lib/python2.7/dist-packages/graph_tool/inference/mcmc.py", line 172, in mcmc_equilibrate
extra = callback(state)
File "num_groups_marg_prob.py", line 35, in collect_num_groups
def collect_num_groups(s):
AttributeError: 'NestedBlockState' object has no attribute 'get_nonempty_B'
Quoting from an answer from the graph-tool mailing list:
"The error message is clear. This attribute belongs to BlockState, not
NestedBlockState. What you wish to do is:
s.levels[0].get_nonempty_B()
"
http://main-discussion-list-for-the-graph-tool-project.982480.n3.nabble.com/self-state-couple-state-state-state-entropy-args-Python-argument-types-did-not-match-C-signature-td4026975.html
i am sorry,i am just a beginner in python language,i am quite stuck in this problem quite long.actually,i want to make a descending and ascending of list that the user input by creating a module of the descending and the ascending.but i couldn't get it work.
the main python file is pythonaslab.py and the module for the ascending and the descending is selectionmodule.py..the code:
this is the selectionmodule:
import pythonaslab
def ascendingselection():
for q in range(len(b)):
w=q+1
for w in range(len(b)):
if b[q]>b[w]:
f=b[q]
b[q]=b[w]
b[w]=f
print b
def descendingselection():
for q in range(len(b)):
w=q+1
for w in range(len(b)):
if b[q]<b[w]:
f=b[q]
b[q]=b[w]
b[w]=f
print b
And this is the main file,the pythonaslab:
import selectionmodule
a = int(input())
b = [int(input()) for _ in range(a)]
print b
print "1.ascending 2.descending"
c=input()
if c==1:
selectionmodule.ascendingselection()
if c==2:
selectionmodule.descendingselection()
can you point me where's the cause of all this error i got?
Traceback (most recent call last):
File "E:\Coding\pythonaslab.py", line 1, in <module>
import selectionmodule
File "E:\Coding\selectionmodule.py", line 1, in <module>
import pythonaslab
File "E:\Coding\pythonaslab.py", line 16, in <module>
selectionmodule.descendingselection()
AttributeError: 'module' object has no attribute 'descendingselection'
You created a circular import; your pythonaslab module imports selectionmodule which imports the pythonaslab module. You end up with incomplete modules that way, don't do that.
Remove the import pythonaslab line from selectionmodule; you are not using pythonaslab in that module.
Also, another module cannot read your globals; you need to pass those in as arguments:
# this function takes one argument, and locally it is known as b
def ascendingselection(b):
# rest of function ..
then call that with:
selectionmodule.ascendingselection(b)
Note that you are not limited to one-letter variable names. Using longer, descriptive names makes your code more readable.
if you don't want to use module name such as:
selectionmodule.ascendingselection(b)
you should import :
from selectionmodule import *
then you can call:
ascendingselection(b) # without module name
Or you can import your module and assigne a alias name:
import selectionmodule as o
o.ascendingselection(b) # with alias name
for more information read: import confusaion