This question already has answers here:
Python's insert returning None?
(4 answers)
Closed 5 years ago.
I'm working on a polynomial organizer. I need to insert two items into the list of coefficients and powers, (a zero for the coefficient and the missing power) wherever needed.
print poly
poly=list(poly.split(','))
for i in range(0,13):
if int(poly[i*2+1])!=int(12-i):
poly=poly.insert((i*2+1),str(12-i))
poly=poly.insert((i*2+1),"0")
returns
0,12,0,11,0,10,0,9,0,8,-7,7,1,5,-1,4,1,3,-2,2,5,0
Traceback (most recent call last):
File "python", line 105, in <module>
File "python", line 97, in mypoly
AttributeError: 'NoneType' object has no attribute 'insert'
I'm confused because from what I've read on the insert function, it is made to work on lists, but here it seems not to. Please don't kill this question... I've been trying to figure it out on my own for a while now, and always run into this problem.
So I want it to look like this:
[0,12,0,11,0,10,0,9,0,8,-7,7,0,6,1,5,-1,4,1,3,-2,2,0,1,5,0]
Notice the 0,6 and 0,1.
The method insert of list returns None, since it modifies the list. You have to change poly = poly.insert(...) to just poly.insert(...):
print poly
poly=list(poly.split(','))
for i in range(0, 13):
if int(poly[i*2+1]) != int(12-i):
poly.insert((i*2+1), str(12-i))
poly.insert((i*2+1), "0")
Related
This question already has answers here:
Why do I get AttributeError: 'NoneType' object has no attribute 'something'?
(11 answers)
Closed 1 year ago.
I was working with doubly linked lists in Python when I encountered with this error:
def merge(self,other):
mergedCenter = HealthCenter()
selfPatient = self._head
otherPatient = other._head
print(selfPatient.elem)
print(selfPatient.elem < otherPatient.elem)
while (selfPatient or otherPatient):
if selfPatient.elem < otherPatient.elem:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
elif selfPatient.elem > otherPatient.elem:
mergedCenter.addLast(otherPatient.elem)
otherPatient = otherPatient.next
else:
mergedCenter.addLast(selfPatient.elem)
selfPatient = selfPatient.next
otherPatient = otherPatient.next
return (mergedCenter)
I get this output:
Abad, Ana 1949 True 0
True
Traceback (most recent call last):
File "main.py", line 189, in <module>
hc3 = hc1.merge(hc2)
File "main.py", line 112, in merge
if selfPatient.elem < otherPatient.elem:
AttributeError: 'NoneType' object has no attribute 'elem'
There's already a method implemented to compare .elem as you can clearly see in the second print, but I don't understand why in the first conditional it keeps breaking.
Thanks in advance.
Solution:
Had to take into account the length of both DLists, not to get one of both values 'Nonetype'. This is solved changing the OR for AND, and checking later which one is not 'Nonetype' to finish merging
This checks if either are non-None, so if one is, and not the other, the loop is entered
while (selfPatient or otherPatient)
If you want to access both elem attributes, then both need to be non-None, requiring you to change the or to and
Otherwise, you need separate logic before the if statements to handle when only one is None, then maybe break the loop so that the return will be reached. And still wouldn't hurt to wrap the rest of the existing logic in if selfPatient and otherPatient since you're using attributes from both
As for why one becomes None, that depends on your logic for iterating the linked lists
I have a table of data in a txt file.
I bring it into Python with:
a1_file=open(file_path,'r')
then I go to the second line to skip the headers:
a1_file.readline()
line_string=a1_file.readline()
Being a comma separated function I want to obtain a list where the position of the first 5 commas is stored. To this purspose I am trying to use this function:
def commas_in_line(table_row):
commas=[]
while len(commas) <5:
if len(commas)==0:
i=0
else:
i=commas[-1]+1
k=table_row.find(',',i)
commas=commas.append(k)
return commas
I call the function with:
commas_in_line(line_string)
The code reports this error:
Traceback (most recent call last):
File "<pyshell#52>", line 1, in <module>
commas_in_line(line_string)
File "C:/1WritingPrograms.py", line 11, in commas_in_line
while len(commas) <5:
TypeError: object of type 'NoneType' has no len()
with
>>> line_string
'30/04/2020,30,4,2020,122,0,Afghanistan,AF,AFG,37172386,Asia\n'
I tried substituting in the function:
commas=commas.append(k)
with:
commas=commas+[k]
and it works, but how can I use the append method? Why does it fail?
Essentially .append() does not return the new array. .append() is sort of like an inplace function, where the value is appended into the array. So you do not have to return anything. When you say commas=commas.append(k), a new entity is returned, which is NoneType. Please just leave it as commas.append(k)
You add values to a python list with:
commas.append(k)
You use the = operator to define a list, not to alter one. For instance, for
commas = ['a', 'b', 'c']
commas.append('d')
commas will now be (a, b, c, d).
There is more about python lists here https://www.w3schools.com/python/python_lists.asp
First post ever :)
I know that the if statement returns a Boolean value. But I am not using it to iterate a list, I'm using x. I just want all other variables (type = IntVar) to be set to 0 except for i which has to remain 1. Thanks in advance, my first ever time here...
def clear():
variables=[var, var0, var1, var2, var3, var4,var5,var6, var7, var8]
for i in variables:
if i.get() == 1:
x = variables.index(i)
for y in variables in range(0,x-1) and range(x,9):
y.set(0)
My original code is 500 lines long so not ideal to post it full here.
Full traceback:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\Thomas Jence\AppData\Local\Programs\Python\Python38-32\lib\tkinter\__init__.py", line 1883, in __call__
return self.func(*args)
File "G:\Mrs. Odewale\Computing coursework\options.py", line 187, in clear9
for y in variables in range(0,x-1) and range(x,9):
TypeError: 'bool' object is not iterable
for y in variables in range(0,x-1) and range(x,9):
is interpreted as (split up with parentheses and by line to make groupings clear):
for y in (
variables in (
range(0, x-1) and range(x,9)
)
):
The innermost parentheses then determine if range(0, x-1) is empty or not, and use it if it's not, and use range(x,9) if it is. The next layer then tests if variables is in the "winning" range. Then you effectively do:
for y in False:
because variables is a list, so it's definitely not in any range.
I don't know what you're trying to do, but you need to reconsider that line.
Not familiar with python, but as a standard coding practice you never want to change values in an array while you are iterating through them.
Instead create a new array, which has same values as the existing array. iterate the old array while setting values of the new array, and then after the loop, set the your array to the new values of the new array.
This question already has answers here:
How do I create variable variables?
(17 answers)
Closed 4 years ago.
I am trying to dynamically define variables from a dictionary in python. I need my variables to be strings, they should appear something like this: lightgreen = "#2ecc71". To do this I added HEX_VALUE = "'" + HEX_VALUE + "'" however adding this I encountered an error
> Traceback (most recent call last):
line 22, in <module>
exec("%s=%s" % (COLOUR_NAME, HEX_VALUE))
File "<string>", line 1
darkblue:='#2980b9'
^
SyntaxError: invalid syntax
As seen from above, this adds ':' to the first part of the variable, so my question is: how can I prevent this?
COLOURS = {
"lightgreen":"'#2ecc71'",
"darkgreen":"#27ae60",
"lightblue":"#3498db",
"darkblue:":"#2980b9",
"lightpurple":"#e74c3c",
"darkpurple":"#8e44ad",
"lightred":"#e74c3c",
"darkred":"#c0392b",
"lightorange":"#e67e22",
"darkorange":"#d35400",
"lightyellow":"#f1c40f",
"darkyellow":"#f39c12",
"lightteal": "#1abc9c",
"darkteal": "#16a085",
"lightnavy": "#34495e",
"darknavy": "#2c3e50"
}
for COLOUR_NAME, HEX_VALUE in COLOURS.items():
HEX_VALUE = "'" + HEX_VALUE + "'"
exec("%s=%s" % (COLOUR_NAME, HEX_VALUE))
As some mentioned in the comments, there is no reason to use exec to make python define new variables. The hex values are already strings in the dictionary so you can just access them directly like so:
lightgreen = COLOURS["lightgreen"]
Although I'll not there is no reason to define variables with the same name as the key of the dict since the dict can just always be accessed directly when necessary.
This question already has answers here:
l.append[i], object is not subscriptable? [closed]
(2 answers)
Closed 8 years ago.
exxy = ['mix', 'xyz', 'aardvark', 'xanadu', 'apple']
pleasework = []
ten = []
for s in exxy:
if s[0] == 'x':
pleasework.insert[0, s]
else:
ten.append[s]
pleasework.sort()
ten.sort()
pleasework.append(ten)
print pleasework
I keep getting an error that says that object is not subscriptable.
Traceback (most recent call last):
File "/Users/jerrywalker/Desktop/CompSci/Programming/Programming_Resources/Python/idle.py", line 10, in <module>
ten.append[s]
TypeError: 'builtin_function_or_method' object is not subscriptable
I'm not really sure what this means. I've just started Python yesterday... I'm sure it's something in the code that I'm not doing right, because even when I change the name of my variables around the error is the same.
"Subscriptable" means that you're trying to access an element of the object. In the following:
ten.append[s]
you're trying to access element s of ten.append. Since you want to call it as a function/method instead, you need to use parens:
ten.append(s)
You have defined two lines with the wrong syntax:
It shouldn't be:
pleasework.insert[0, s]
ten.append[s]
But rather:
pleasework.insert(0, s)
ten.append(s)
ten.append(s) is a list method and you cannot try to get a element s of ten.append(s).
Even assuming you were trying to do something like ten[s] it would still return a error because s has to be the index (which is a integer) of the element you want