this is my code:
import turtle
e = turtle.Turtle
e.speed(10)
d = 100
angle = 140
for i in range (1, 1000):
e.forward(d)
e.left(angle)
d = d - 1
when i run the code and this thing pop up.
Traceback (most recent call last):
File "C:\Users\User\Desktop\Python\TUrtle graphic.py", line 2, in <module>
e = turtle.Turtle
AttributeError: 'module' object has no attribute 'Turtle'
Instead of:
e = turtle.Turtle
you need to do:
e = turtle.Turtle()
Full code:
import turtle
e = turtle.Turtle()
e.speed(10)
d = 100
angle = 140
for i in range(1, 1000):
e.forward(d)
e.left(angle)
d = d - 1
turtle.mainloop()
Note that d will eventually become negative so your forward will effectively become a backward for the majority of the iterations.
Related
I keep having this error on my code, which says:
"AttributeError: 'NoneType' object has no attribute 'append'"
But there is interesting fact, it only occurs when "n" is odd.
Here is the piece of code I'm using:
Note: I'm using Python 2.7.18
def sol(n, df):
if n == 1:
result = df
elif n == 2 or n == 0:
df.append(1)
result = df
elif n % 2 == 0:
df.append(n/2)
df = sol(n/2, df)
else:
df_2 = df[:]
df_2 = df_2.append(n-1)
n_2 = n-1
df_2 = sol(n_2, df_2)
return df
df = []
n = input('n == ')
sol(n, df)
The error is as follow:
n == 3
Traceback (most recent call last):
File "Challenge_3_1_vTest.py", line 27, in <module>
solution(n)
File "Challenge_3_1_vTest.py", line 6, in solution
print((sol(n, df)))
File "Challenge_3_1_vTest.py", line 21, in sol
df_2 = sol(n_2, df_2)
File "Challenge_3_1_vTest.py", line 12, in sol
df.append(1)
AttributeError: 'NoneType' object has no attribute 'append'
The append function doesn't return a thing, that's why I was having the error and was passing a none when using number that are not power of 2.
df_2 = df_2.append(n-1)
This line of code was the source of the problem, I should have done:
df_2.append(n-1)
I try to use the following Python code (that uses multi-processing library) :
import multiprocessing as mp
def MAIN_LOOP(lll):
global aa
global bb
aa, bb = 0,0
if paramo == 3:
C_ij = np.zeros((len(zrange), len(zrange)))
C_ij_up = np.zeros((len(zrange), len(zrange)))
C_ij_dw = np.zeros((len(zrange), len(zrange)))
while aa < len(zrange):
while bb <= aa:
if paramo == 3:
C_ij[aa][bb] = Pobs_C(zpm, zrange[aa], zrange[bb], h[2], Omega_m[2], Omega_DE[2], w0[2], wa[2], E_tab, R_tab, DG_tab, W_tab, l[lll], P_dd_C, R_tab(z_pk))
C_ij_up[aa][bb] = Pobs_C(zpm, zrange[aa], zrange[bb], h[0], Omega_m[0], Omega_DE[0], w0[0], wa[0], E_tab_up, R_tab_up, DG_tab_up, W_tab_up, l[lll], P_dd_C_up, R_tab_up(z_pk))
C_ij_dw[aa][bb] = Pobs_C(zpm, zrange[aa], zrange[bb], h[3], Omega_m[3], Omega_DE[3], w0[3], wa[3], E_tab_dw, R_tab_dw, DG_tab_dw, W_tab_dw, l[lll], P_dd_C_dw, R_tab_dw(z_pk))
if aa != bb:
if paramo == 3:
C_ij[bb][aa] = C_ij[aa][bb]
C_ij_up[bb][aa] = C_ij_up[aa][bb]
C_ij_dw[bb][aa] = C_ij_dw[aa][bb]
bb=bb+1
bb=0
aa=aa+1
if paramo == 3:
aa, bb = 0,0
outF=open(CC_path[2]+"/COVAR_fid_"+str(l[lll]),'w')
while aa < len(C_ij):
while bb < len(C_ij):
outF.write(str("%.16e" % C_ij[aa][bb]))
outF.write(str(' '))
bb=bb+1
outF.write(str('\n'))
bb=0
aa=aa+1
outF.close()
aa, bb = 0,0
outU=open(CC_path[0]+"/COVAR_up_"+str(l[lll]),'w')
outD=open(CC_path[3]+"/COVAR_dw_"+str(l[lll]),'w')
while aa < len(C_ij_up):
while bb < len(C_ij_up):
outU.write(str("%.16e" % C_ij_up[aa][bb]))
outU.write(str(' '))
outD.write(str("%.16e" % C_ij_dw[aa][bb]))
outD.write(str(' '))
bb=bb+1
outU.write(str('\n'))
outD.write(str('\n'))
bb=0
aa=aa+1
outU.close()
outD.close()
lll=lll+1
lll = range(len(l))
if __name__ == '__main__':
pool = mp.Pool(12)
pool.map(MAIN_LOOP, lll)
pool.close()
pool.join()
But at the execution, I get the following error :
Traceback (most recent call last):
File "Photo_SAF_flat.py", line 412, in <module>
pool.map(MAIN_LOOP, lll)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 253, in map
return self.map_async(func, iterable, chunksize).get()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/multiprocessing/pool.py", line 572, in get
raise self._value
ValueError: `x` must contain at least 2 elements.
I tried to use generator with yield but still get the same error.
I would like to make work this part of code. How can I do so?
I have a list (coordpairs) that I am trying to use as the basis for plotting using LineCollection. The list is derived from a Pandas data frame. I am having trouble getting the list in the right format, despite what is admittedly a clear error code. Trimmed data frame contents, code, and error are below. Thank you for any help.
Part of the Data Frame
RUP_ID Vert_ID Longitude Latitude
1 1 -116.316961 34.750178
1 2 -116.316819 34.750006
2 1 -116.316752 34.749938
2 2 -116.31662 34.749787
10 1 -116.317165 34.754078
10 2 -116.317277 34.751492
10 3 -116.317206 34.751273
10 4 -116.317009 34.75074
10 5 -116.316799 34.750489
11 1 -116.316044 34.760377
11 2 -116.317105 34.755674
11 3 -116.317165 34.754078
Code
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
fig = plt.figure()
ax1 = plt.subplot2grid((2, 2), (0, 0), rowspan=2, colspan=1)
for ii in range(1,len(mydf)):
temp = mydf.loc[mydf.RUP_ID == ii]
df_line = temp.sort_values(by='Vert_ID', ascending=True)
del temp
lat = df_line.Latitude
lon = df_line.Longitude
lat = lat.tolist()
long = long.tolist()
coordpairs = zip(lat, long)
lc = LineCollection(coordpairs, colors='r') # this is line 112 in the error
ax1.add_collection(lc)
# note I also tried:
# import numpy as np
# coordpairs2 = np.vstack([np.array(u) for u in set([tuple(p) for p in coordpairs])])
# lc = LineCollection(coordpairs2, colors='r')
# and received the same plotting error
Error/Outputs
C:\apath\python.exe C:/mypath/myscript.py
Traceback (most recent call last):
File "C:/mypath/myscript.py", line 112, in <module>
lc = LineCollection(coordpairs, colors='r') # this is line 112 in the error
File "C:\apath\lib\site-packages\matplotlib\collections.py", line 1149, in __init__
self.set_segments(segments)
File "C:\apath\lib\site-packages\matplotlib\collections.py", line 1164, in set_segments
self._paths = [mpath.Path(_seg) for _seg in _segments]
File "C:\apath\lib\site-packages\matplotlib\path.py", line 141, in __init__
raise ValueError(msg)
ValueError: 'vertices' must be a 2D list or array with shape Nx2
Process finished with exit code 1
You would want to create one single LineCollection, with several lines, one per RUP_ID value from the first dataframe column. That means you best loop over the unique values of that column (not over every row!) and append the coordinates to a list. Use that list as the input to LineCollection.
u = """RUP_ID Vert_ID Longitude Latitude
1 1 -116.316961 34.750178
1 2 -116.316819 34.750006
2 1 -116.316752 34.749938
2 2 -116.31662 34.749787
10 1 -116.317165 34.754078
10 2 -116.317277 34.751492
10 3 -116.317206 34.751273
10 4 -116.317009 34.75074
10 5 -116.316799 34.750489
11 1 -116.316044 34.760377
11 2 -116.317105 34.755674
11 3 -116.317165 34.754078"""
import io
import pandas as pd
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
df = pd.read_csv(io.StringIO(u), sep="\s+")
verts = []
for (RUP_ID, grp) in df.groupby("RUP_ID"):
df_line = grp.sort_values(by='Vert_ID', ascending=True)
lat = df_line.Latitude
lon = df_line.Longitude
verts.append(list(zip(lon, lat)))
lc = LineCollection(verts, color='r')
fig, ax = plt.subplots()
ax.add_collection(lc)
ax.autoscale()
plt.show()
The following two codes do a simple bayesian inference in python using PyMC3. While the first code for exponential model compiles and run perfectly fine, the second one for a simple ode model, gives an error. I do not understand why one is working and the other is not. Please help.
Code #1
import numpy as np
import pymc3 as pm
def f(a,b,x,c):
return a * np.exp(b*x)+c
#Generating Data with error
a, b = 5, 0.2
xdata = np.linspace(0, 10, 21)
ydata = f(a, b, xdata,0.5)
yerror = 5 * np.random.rand(len(xdata))
ydata += np.random.normal(0.0, np.sqrt(yerror))
model = pm.Model()
with model:
alpha = pm.Uniform('alpha', lower=a/2, upper=2*a)
beta = pm.Uniform('beta', lower=b/2, upper=2*b)
mu = f(alpha, beta, xdata,0.5)
Y_obs = pm.Normal('Y_obs', mu=mu, sd=yerror, observed=ydata)
trace = pm.sample(100, tune = 50, nchains = 1)
Code #2
import numpy as np
import pymc3 as pm
def solver(I, a, T, dt):
"""Solve u'=-a*u, u(0)=I, for t in (0,T] with steps of dt."""
dt = float(dt) # avoid integer division
N = int(round(T/dt)) # no of time intervals
print N
T = N*dt # adjust T to fit time step dt
u = np.zeros(N+1) # array of u[n] values
t = np.linspace(0, T, N+1) # time mesh
u[0] = I # assign initial condition
for n in range(0, N): # n=0,1,...,N-1
u[n+1] = (1 - a*dt)*u[n]
return np.ravel(u)
# Generating data
ydata = solver(1,1.7,10,0.1)
yerror = 5 * np.random.rand(101)
ydata += np.random.normal(0.0, np.sqrt(yerror))
model = pm.Model()
with model:
alpha = pm.Uniform('alpha', lower = 1.0, upper = 2.5)
mu = solver(1,alpha,10,0.1)
Y_obs = pm.Normal('Y_obs', mu=mu, sd=yerror, observed=ydata)
trace = pm.sample(100, nchains=1)
The error is
Traceback (most recent call last):
File "1.py", line 27, in <module>
mu = solver(1,alpha,10,0.1)
File "1.py", line 16, in solver
u[n+1] = (1 - a*dt)*u[n]
ValueError: setting an array element with a sequence.
Please help.
The error is in this line:
mu = solver(1,alpha,10,0.1)
You are trying to pass alpha as a value, but alpha is a pymc3 distribution. The function solver only works when you provide a number in the second argument.
The code #1 works because this function
def f(a,b,x,c):
return a * np.exp(b*x)+c
returns a number.
this is the code:
import bisect
data = {'sal': 25000} # stored data from user input
table = {1249.99: 36.30, 1749.99: 54.50, 2249.99: 72.70, 2749.99: 90.80,
3249.99: 109.00, 3749.99: 127.20, 4249.99: 145.30, 4749.99: 163.50,
5249.99: 181.70, 5749.99: 199.80, 6249.99: 218.00, 6749.99: 236.20,
7249.99: 254.30, 7749.99: 272.50, 8249.99: 290.70, 8749.99: 308.80,
9249.99: 327.00, 9749.99: 345.20, 10249.99: 363.30, 10749.99: 381.50,
11249.99: 399.70, 11749.99: 417.80, 12249.99: 436.00, 12749.99:
454.20, 13249.99: 472.30, 13749.99: 490.50, 14249.99: 508.70,
14749.99: 526.80, 15249.99: 545.00, 15749.99: 563.20, 15750.00:
581.30}
# get corresponding value from the table
table_bisect = bisect.bisect(sorted(table), data['sal'])
if table_bisect >= 30:
table_bisect = 30
else:
table_bisect = table_bisect
s_table = sorted(table.value())
data['new'] = ''.join(s_table[table_bisect:(table_bisect+1)]
# TypeError: sequence item 0: expected string, float found
Everything works fine, until the last line, which return the error above. How can I fix the error or what are the work around?
It is because if you slice with list[index:index+1], it simply returns one value, which in this case is a float:
>>> y = [21, 4, 2, 5, 4, 3, 7, 9]
>>> y[5:6]
[3]
>>> ''.join(y[5:6])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: sequence item 0: expected string, int found
>>>
Instead, just do the following:
data['new'] = s_table[table_bisect:(table_bisect+1)][0]
Another option is to do this:
data['new'] = ''.join(str(s_table[table_bisect:(table_bisect+1)]))
the join() method expects string type if you need to use it.