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
Related
My code looks like this:
import random
x = random()
print (x)
and I get following error:
Traceback (most recent call last):
File "random.py", line 1, in <module>
import random
File "C:\Users\joshu\Desktop\random.py", line 2, in <module>
x = random()
TypeError: 'module' object is not callable
What did I do wrong? From my understanding, random should be installed with python, shouldn't it?
You have to use random.random() like this.
import random
x = random.random()
print (x)
or you can import specific functions in random module like this.
from random import random
x = random()
print (x)
You need to use the module you just import.
For example random.random() or random.randint() etc.
you are using whole random module which is why it's throwing the TypeError error. instead use random.random() if you want float type random numbers or random.randint() for int numbers.
import random
x = random.random()
print(x) # returns a random floating number between 0 and 1
Note: randint() method returns an integer number selected element from the specified range. The method is an alias for randrange(start, stop+1)
Here is My Python Code is given below:-
import networkx as nx
import matplotlib.pyplot as plt
from random import choice
g=nx.Graph()
city_set=['Delhi','Lucknow','Indore','Kolkata','Hyderabad','Chennai',
'Tivandrum','Banglore','Pune','Mumbai','Surat','Ahmedabad','Jaipur']
for each in city_set:
g.add_node(each)
costs=[]
value =100
while(value<=2000):
costs.append(value)
value=value+70
while(g.number_of_edges()<24):
c1=choice(g.nodes())
c2=choice(g.nodes())
if c1!=c2 and g.has_edge(c1,c2)==0:
w=choice(costs)
g.add_edge(c1,c2,weight=w)
nx.draw(g,with_labels=1)
plt.show(g)
and while compiling the code I got the error stated below:-
$ python cities.py
Traceback (most recent call last):
File "cities.py", line 22, in <module>
c1=choice(g.nodes())
File "/usr/lib/python2.7/random.py", line 277, in choice
return seq[int(self.random() * len(seq))] # raises IndexError if seq
is empty
File "/usr/local/lib/python2.7/dist-
packages/networkx/classes/reportviews.py", line 178, in __getitem__
return self._nodes[n]
KeyError: 7
I also created vitual enviourment of Pyhton but again it shows the smae error.
Also, I tried finding some stuff on Google and check for the solution but no one has similar problem like this.
Change
c1=choice(g.nodes())
c2=choice(g.nodes())
into
c1=choice(list(g))
c2=choice(list(g))
should work.
g.nodes() returns a NodeView and not a list of nodes.
import random
import networkx as nx
costs = []
value=100
while(value<=2000):
costs.append(value)
value+=100
print (costs)
while(G.number_of_edges()<16):
c1 = random.choice(list(G.nodes()))
c2 = random.choice(list(G.nodes()))
if c1!=c2 and G.has_edge(c1,c2)==0:
w= random.choice(costs)
G.add_edge(c1,c2,weight = w)
Try this code as there is some error in the syntax of the random shown in the video. I have pasted my code, test it.
G.nodes() needs to return a list but here is returning a NodeView. Hence change G.nodes() to list(G.nodes())
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
** EDIT: Copy-pasting my actual file to ease confusion. The code snippet below is in a file named train_fm.py:
def eval_fm(x,b,w,V):
# evaluate a degree 2 FM. x is p X B
# V is p x k
# some python code that computes yhat
return(yhat);
Now in my main file: I say the following
from train_fm import eval_fm
and I get the error:
ImportError: cannot import name f1
When I type
from train_fm import train_fm
I do not get an error.
OLD QUESTION BELOW :
def train_fm(x,y,lb,lw,lv,k,a,b,w,V):
# some code
yhat = eval_fm(x,b,w,V);
# OUTPUTS
return(b,w,V);
I have a file called f2.py, where I define 2 functions (note that one of the functions has the same name as the file)
def f1():
some stuff;
return(stuff)
def f2():
more stuff;
y = f1();
return(y)
In my main file, I do
from aaa import f1
from aaa import f2
but when I run the first of the 2 commands above, I get
ImportError: cannot import name f1
Any idea what is causing this? The second function gets imported fine.
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?