I am not quite sure what it is I am doing wrong with my code to get this error. I've been looking around to see if I could find somebody having the same problem but I have had no success thus far. The code is:
def sort(dislis):
for index in range(0,len(lst)):
currval= dislis[index]
position = index
while position>0 and dislis[position-1]>currval:
dislis[position] = dislis[position-1]
position = position-1
dislis[position]=currval
The traceback error is:
Traceback (most recent call last):
File "C:", line 49, in <module>
distance()
File "", line 47, in distance
sort(dislis)
File "", line 20, in sort
currval= dislis[index]
IndexError: list index out of range
def sort(dislis):
for index in range(0,len(dislis)):
currval= dislis[index]
position = index
while position>0 and dislis[position-1]>currval:
dislis[position] = dislis[position-1]
position = position-1
dislis[position]=currval
return dislis
result = sort([3,4,2,1])
print(result)
A few little bugs in there preventing it from running, try this out instead.
Also, I highly recommend using only spaces, and not tabs at all.
Related
I'm using a for loop to repeat a task which basically deletes specific objects in my active Illustrator doc. The code works but when it ends I got an error and I'm unable to execute the rest of the code.
My code:
def top_file():
for y in range(1, pathCount + 1):
path_items = activeDoc.PathItems(y).Filled
if path_items is False:
path_items = activeDoc.PathItems(y)
path_items.Delete()
This is the error I get:
Traceback (most recent call last):
File "C:\Users\joelq\Desktop\Joy Automation\main.py", line 88, in <module>
top_file()
File "C:\Users\joelq\Desktop\Joy Automation\main.py", line 61, in top_file
path_items = activeDoc.PathItems(y).Filled
File "C:\Users\joelq\AppData\Local\Programs\Python\Python39\lib\site-packages\win32com\client\dynamic.py", line 226, in __call__
self._oleobj_.Invoke(*allArgs), self._olerepr_.defaultDispatchName, None
pywintypes.com_error: (-2147352567, 'Ocurrió una excepción.', (0, 'Adobe Illustrator', 'No such element', None, 0, -2147352565), None)
It should be pretty clear from the error message. Collections in Illustrator's object model are numbered from 0, just like Python lists. Use range(pathCount).
Note, however, that what you're doing will fail later. If you Delete an item from a collection while you are iterating the collection, the counts will be wrong. If you delete item 3, then what was item 4 becomes item 3, and the number of items changes, so your range will be run off the end. You may need to iterate backwards from the end instead.
For a university assignment I was asked to convert a 1 line text file into a 2d array. However, when I run the program, I get this error:
(venv) D:\Uni Stuff\Year 2\AIGP\Assignment\PYTHONASSIGNMEN>python astar.py
Input file name: Lab9TerrainFile1.txt
Traceback (most recent call last):
File "D:\Uni Stuff\Year 2\AIGP\Assignment\PYTHONASSIGNMEN\astar.py", line 129, in <module>
main()
File "D:\Uni Stuff\Year 2\AIGP\Assignment\PYTHONASSIGNMEN\astar.py", line 110, in main
number_of_rows = maze_file[1]
IndexError: index 1 is out of bounds for axis 0 with size 1
This is the code for generating the maze:
def main():
maze_file = open(input("Input file name: "), "r").readlines()
maze_file = np.array([maze_file])
number_of_columns = maze_file[0]
number_of_rows = maze_file[1]
maze_column = np.array_split(maze_file[2:8], number_of_columns)
maze_row = np.array_split(maze_file[2:8], number_of_rows)
maze = np.concatenate([maze_column][maze_row])
start = np.where(maze == 2)
end = np.where(maze == 3)
maze_file.close()
path = astar(maze, start, end)
print(path)
Any help would be appreciated and thank you!
You can test this by checking the size of your array maze_file by running the code below.
print(len(maze_file))
If it returns 1, then it means it only has 1 element.
maze_file[0] means you are getting the first element. Hence, the index 0 between the square brackets. When you specify maze_file[1], its trying to get the 2nd element, which doesn't exists. Hence the error Index out of Bounds.
Reviewing your code, it looks like you are trying to get the number of columns and rows for the array. You can use the following code.
number_of_columns = len(maze_file)
number_of_rows = len(maze_file[0])
I have this for-loop:
for i in range(1000000000, 1000000030):
foo(i)
When I execute it this error is given:
Traceback (most recent call last):
File "/CENSORED/Activity.py", line 11, in <module>
for i in range(1000000000, 10000000030):
OverflowError: range() result has too many items.
As far as I know, this range-object should have exactly 30 elements...
Where is the problem?
Edit:
I have removed the extra zero, now I get this:
Traceback (most recent call last):
File "/CENSORED/Activity.py", line 12, in <module>
factorizeInefficient(i)
MemoryError
Edit 2:
def factorizeInefficient(n):
teiler = list()
for i in range(n):
if i != 0:
if (n%i)==0:
teiler.append(i)
print teiler
Just found the solution myself: There is a range(n) object in this as well and this causes the memory Error...
An extra question: How did you guys know this was python 2? (Btw you were right...)
Copy/pasting the range() part of your code:
>>> len(range(1000000000, 10000000030))
9000000030
So there are actually about 9 billion elements in the range. Your first argument is presumably missing a zero, or second argument has a zero too many ;-)
count your zeros once again ;) I'd say it's one too much.
I have a sample json:
I want to use the json module of python and recurse through to find the "MaxSize" in "pevcwebasg". Have the following code:
import json
param_file_handle = json.load(open("sample.json"))
print param_file_handle['Resources']['pevcwebasg']['Type']
resources = param_file_handle['Resources']
for asg in resources:
print asg["Type"]
The out put of which is :
> AWS::AutoScaling::AutoScalingGroup Traceback (most recent call last):
> File "test.py", line 8, in <module>
> print asg['Type'] TypeError: string indices must be integers
What I dont get is this line "print param_file_handle['Resources']['pevcwebasg']['Type']" works fine and gets me the output but when i recurse through and try and find asg["Type"], it fails. Any better way to do this ? I need to recurse through the tree and find the value.
Edit 1:
as I do recurse through values, I get stuck with error.
param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
for values in asg['Properties']:
print values["MaxSize"]
error :
Traceback (most recent call last):
File "test.py", line 9, in <module>
print values["MaxSize"]
TypeError: string indices must be integers
for asg in resources:
This iterates through the keys of resources, rather than the values. Try:
for asg in resources.values():
param_file_handle = json.load(open("sample.json"))
resources = param_file_handle['Resources']
for asg in resources.values():
if asg["Type"] == "AWS::AutoScaling::AutoScalingGroup":
print asg["Properties"]["MaxSize"]
try this.
you broke hirerchy, missed "pevcwebasg"
resources = param_file_handle['Resources']['pevcwebasg']
for asg in resources:
print asg["Type"]
Each line represents a single student and consists of a student number, a name, a section code and a midterm grade, all separated by whitespace.
The first parameter is already done and the file is open and
The second parameter is a section code
this is the link http://www.cdf.toronto.edu/~csc108h/fall/exercises/e3/grade_file.txt
My code:
def average_by_section(the_file, section_code):
'''(io.TextIOWrapper, str) -> float
Return the average midtermmark for all students in that section
'''
score = 0
n = 0
for element in the_file:
line = element.split()
if section_code == line[-2]:
mark = mark + float(line[-1])
n += 1
lecture_avg = mark / n
return lecture_avg
I'm getting an index out of range. Is this correct? Or am I just opening up the wrong file?
can someone test this code and download that file? I'm pretty sure it should work, but not for me.
Well, you can troubleshoot the index out of range error with a print line or print(line) to explore the number of items in "line" (i.e. the effect of split()). I'd suggest looking closer at your split() statement...
It looks like you are omitting parts of your code where you define some of those variables (section_code, mark, etc.), but adjusting for some of those things seems to work properly. Assuming that the error you got was IndexError: list index out of range, that happens when you try to access an element of a list by index where that index doesn't exist. For instance:
>>> l = ['one']
>>> l[0]
'one'
>>> l[1]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> l[-1]
'one'
>>> l[-2]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
Therefore in your code, you will get that error if line is ever fewer than two items. I would check and see what you are actually getting for line to make sure it is what you expect.