Int Object Is Not Iterable - python

I have come across a problem that I don't know how to resolve involving Dijkstra's algorithm - here is my code:
infinity = 1000000
invalid_node = -1
#startNode = 0
class Node:
distFromSource = infinity
previous = invalid_node
visited = False
def populateNodeTable():
nodeTable = []
f = open("twoDArray.txt", "r")
for line in f.readlines(): #get number of nodes from file
nodeTable.append(line.split(',')) # Create matrix of weights
numNodes = len(nodeTable) # Count nodes
print numNodes
#for all nodes in text file, set visited to false, distFromSource to infinity & predecessor to none
**for i in numNodes:
nodeTable.append(Node(i))**
#nodeTable.append(Node())
nodeTable[startNode].distFromSource = 0
print nodeTable
if __name__ == "__main__":
populateArray()
populateNodeTable()
When I run this code I get the following error:
Traceback (most recent call last):
File "2dArray.py", line 63, in <module>
populateNodeTable()
File "2dArray.py", line 18, in populateNodeTable
for i in numNodes:
TypeError: 'int' object is not iterable
I am not sure how I rectify this error (the section between the asterix) - what I am trying to do is to read my text file which is just a series of integers separated by commas, and count the number of nodes within that text file
Each node will then be assigned the values in the Node class

Try this:
for i in nodeTable:
why are you trying to iterate over numNodes? You just defined one line above as the length of the table.
But appending to the same table in the loop doesn't make sense. And it does not work together with the code that reads the file. Also the Node class isn't usable at all ...

How about for i in range(numNodes) ... numNodes is just a number, not an array of numbers, which is what you are after.

If you want to iterate over the element indexes, use for i, _ in enumerate(nodeTable)
If you want to access the element itself, too, use a real name instead of _

Related

How to fix: "Int object not iterable" when assigning variables to two lists?

I tried making a question on this earlier and did a horrible job of explaining what I wanted. Hopefully the information I provide in this one is more helpful.
The program I am trying to make will take read input from a file in the form of the following: (there will be multiple varying test cases)
7 10
4 8
The program will assign a variable to the top-right integer (in this case, 10) and the bottom-left integer (4). The program will then compute the difference of the two variables. Here is the code I have so far -
with open('C:\\Users\\ayush\\Desktop\\USACO\\paint\\paint_test.in', 'r') as fn:
matrix = fn.readlines()
input_array = []
for line in matrix:
input_array.append(line.strip())
for p,q in enumerate(input_array):
for x,y in enumerate(p):
pass
for a,b in enumerate(q):
pass
print(y - a)
When I, however, run this code I get the following error:
Traceback (most recent call last):
File "C:\Users\ayush\Desktop\USACO\paint\paint.py", line 16, in <module>
for x,y in enumerate(p):
TypeError: 'int' object is not iterable
[Finished in 0.571s]
I'm not sure as to what the problem is, and why my lists cannot be iterated.
I hope I did a better job explaining my goal this time. Please let me know if there are any additional details I could try to provide. I would really appreciate some help - I've been stuck on this for the longest time.
Thanks!
Were you going for something along the lines of:
with open('C:\\Users\\ayush\\Desktop\\USACO\\paint\\paint_test.in', 'r') as fn:
matrix = fn.readlines()
input_array = []
for line in matrix:
input_array.append(line.strip())
top_line, bottom_line = input_array # previously p, q
top_right, top_left = top_line.split() # previously x, y
bottom_right, bottom_lefft = bottom_line.split() # previously a, b
print(int(top_left) - int(bottom_right)) # you would have run into issue subtracting strings without the int() calls
?
If so, that should work, but you can avoid all the unpacking if you just use [0] and [-1] indexes to get the first and last items (this has the advantage of working on a matrix of any size):
with open('C:\\Users\\ayush\\Desktop\\USACO\\paint\\paint_test.in', 'r') as fn:
lines = fn.read().splitlines()
matrix = [
[
int(item)
for item in line.split()
]
for line in lines
]
top_left = matrix[0][-1]
bottom_right = matrix[-1][0]
print(top_left - bottom_right)

Error when trying to round values in an ndarray

I am working on a memory-based collaborative filtering algorithm. I am building a matrix that I want to write into CSV file that contains three columns: users, app and ratings.
fid = fopen('pred_ratings.csv','wt');
for i=1:user_num
for j=1:item_num
if R(j,i) == 1
entry = Y(j,i);
else
entry = round(P(j,i));
end
fprintf(fid,'%d %d %d\n',i,j,entry);
end
end
fclose(fid);
The above code is a MATLAB implementation of writing a multidimensional matrix into a file having 3 columns. I tried to imitate this in python, using:
n_users=816
n_items=17
f = open("guru.txt","w+")
for i in range(1,n_users):
for j in range(1,n_items):
if (i,j)==1 in a:
entry = data_matrix(j, i)
else:
entry = round(user_prediction(j, i))
print(f, '%d%d%d\n', i, j, entry)
f.close
But this results in the following error:
File "<ipython-input-198-7a444566e1ce>", line 7, in <module>
entry = round(user_prediction(j, i))
TypeError: 'numpy.ndarray' object is not callable
What can be done to fix this?
numpy uses square brackets for indexing. Since user_predictions is a numpy array, it should be indexed as
user_predictions[i, j]
The same goes for data_matrix.
You should probably read the Numpy for MATLAB users guide.
Edit:
Also, the
if (i,j)==1 in a:
line is very dubious. (i, j) is a tuple of two integers, which means it will never be equal to 1. That line is thus equivalent to if False in a: which is probably not what you want.

Code works for a small selection but not the entire database

I have a similar problem to this one.
I am working on Qgis. To speed things up, I've created a small selection of my map on which I test my code. It works great. Here is the section that poses problem later :
layer = qgis.utils.iface.activeLayer()
iter = layer.getFeatures()
dict = {}
#iterate over features
for feature in iter:
#print feature.id()
geom = feature.geometry()
coord = geom.asPolyline()
### GET FIRST AND LAST POINTS OF POLY + N ORIENTATION###
# Get Objective Orientation
d=QgsDistanceArea()
d.setEllipsoidalMode(True)
points=geom.asPolyline()
#second way to get Endpoints
first = points[0]
last = points[-1]
r=d.bearing(first, last)
b= "NorthOrientation= %s" %(math.degrees(r))
# Assemble Features
dict[feature.id() ]= [first, last]
### KEY = INTERSECTION, VALUES = COMMONPOINTS###
dictionary = {}
a = dict
for i in a:
for j in a:
c = set(a[i]).intersection(set(a[j]))
if len(c) == 1:
d = set(a[i]).difference(c)
c = list(c)[0]
value = list(d)[0] #This is where the problem is
if c in dictionary and value not in dictionary[c]:
dictionary[c].append(value)
elif c not in dictionary:
dictionary.setdefault(c, [])
dictionary[c].append(value)
else: pass
print dictionary
This code works for the 10 polylines of my small selection (which I've stored in a seperate shapefile). But when I try to run it though the 40 000 lines of my original database, I get the following Error:
Traceback (most recent call last):
File "<input>", line 1, in <module>
File "c:/users/16116/appdata/local/temp/tmp96wd24.py", line 47, in <module>
value = list(d)[0]
IndexError: list index out of range
A few things:
This code stems from a first question that you can find here. I'm still pretty new to python so to be honest I have a hard time understanding how this exact part of the code works, but I know it does (at least for the small dataset).
The small "test selection"'s structure is identical to the entire database. Only the length has changed.
If anyone has had the same experience or knows why this problem occures, I would be very greatful for any indications.

KeyError with Python dictionary

I've been practicing on a ><> (Fish) interpreter and am stuck on an error I'm getting. The problematic code seems to be here:
import sys
from random import randint
file = sys.argv[1]
code = open(file)
program = code.read()
print(str(program))
stdin = sys.argv[2]
prgmlist = program.splitlines()
length = len(prgmlist)
prgm = {}
for x in range(0,length-1):
prgm[x+1] = list(prgmlist[x])
The goal here was to take the code and put it into a sort of grid, so that each command could be taken and computed separately. By grid, I mean a map to a list:
{line1:["code","code","code"]
line2:["code","code","code"]
line3:...}
and so on.
However, when I try to retrieve a command using cmd = prgm[y][x] it gives me KeyError: 0.
Any help is appreciated.
Here's a traceback:
Traceback (most recent call last):
File "/Users/abest/Documents/Python/><>_Interpreter.py", line 270, in <module>
cmd = prgm[cmdy][cmdx]
KeyError: 0
And a pastebin of the entire code.
The input is the hello world program from the wiki page:
!v"hello, world"r!
>l?!;o
Few issues -
You are not considering the last line , since your range is - for x in range(0,length-1): - and the stop argument of range is exlusive, so it does not go to length-1 . You actually do not need to get the length of use range, you can simply use for i, x in enumerate(prgmlist): . enumerate() in each iteration returns the index as well as the current element.
for i, x in enumerate(prgmlist, 1):
prgm[i] = list(x)
Secondly, from your actual code seems like you are defining cmdx initially as 0 , but in your for loop (as given above) , you are only starting the index in the dictionary from 1 . So you should define that starting at 1. Example -
stacks, str1, str2, cmdx, cmdy, face, register, cmd = {"now":[]}, 0, 0, 1, 0, "E", 0, None
And you should start cmdy from 0 . Seems like you had both of them reversed.
You'll want to use something like
cmd = prgm[x][y]
the first part prgm[x] will access the list that's the value for the x key in the dictionary then [y] will pull the yth element from the list.

Default Dict append Attribute Error 'float' object has no attribute 'append'

I have read all the script from default dict and all the posts on here. I believe my syntax is correct.
influenceDict = defaultdict(list)
to fill with all tags from all tweets
Later, I am appending ALOT of float values, 1000+ list entries for a majority of dictionary keys. I get my error on line 47, specified below.
def addInfluenceScores(hashtagArr,numFollowers,numRetweets, influenceDict):
influenceScore = float(0)
if numFollowers == 0 and numRetweets != 0:
influenceScore = numRetweets + 1
elif numFollowers == 0 and numRetweets == 0:
influenceScore = 0
else:
influenceScore = numRetweets / numFollowers
print "Adding influence score %f to individual hashtags" % (influenceScore)
for tag in hashtagArr:
tID = tag2id_map[tag]
print "Appending ",tID,tag
# if not influenceDict.has_key(tID):
# influenceDict[tID] = list()
# influenceDict[tID].append(influenceScore)
# else:
# influenceDict[tID].append(influenceScore)
influenceDict[tID].append(influenceScore) **#LINE 47 I GET THE ERROR HERE**
for i in range(len(hashtagArr)):
for j in range(i+1, len(hashtagArr)):
tID1 = tag2id_map[hashtagArr[i]]
tID2 = tag2id_map[hashtagArr[j]]
if(tID2 < tID1): #ensure alpha order to avoid duplicating (a,b) and (b,a)
temp = tID1
tID1 = tID2
tID2 = temp
print "Appending ",tID1, hashtagArr[j],tID2,hashtagArr[i]
# if not influenceDict.has_key((tID1, tID2)):
# influenceDict[(tID1, tID2)] = list()
# influenceDict[(tID1, tID2)].append(influenceScore)
# else:
# influenceDict[(tID1, tID2)].append(influenceScore)
influenceDict[(tID1, tID2)].append(influenceScore)
The program runs for a while, and it actually does append values (or so I think) and then I get this error:
Traceback (most recent call last):
File "./scripts/make_id2_influencescore_maps.py", line 158, in <module
processTweets(tweets, influenceDict)
File "./scripts/make_id2_influencescore_maps.py", line 127, in processTweets
addInfluenceScores(hashtags, numFollowers,numRetweets, influenceDict)
File "./scripts/make_id2_influencescore_maps.py", line 47, in addInfluenceScores
influenceDict[tID].append(influenceScore)
AttributeError: 'float' object has no attribute 'append'
I am thinking that the list is just maxed out in memory. Maybe you guys can see something I don't. I am trying to loop through a file of tweets and for everytime I see the hashtag I want to append a score to the list associated with it. That way I can just take the average of all the scores in the list when I am completely done reading the file. Thanks ahead.
I am thinking that the list is just maxed out in memory.
I can assure you thats not the case if your error is
AttributeError: 'float' object has no attribute 'append'
The problem is not in the code you have shown here, as influenceDict is a parameter you have obviously set one of the keys to point to a float value elsewhere in your code. Just because it is a defaultdict(list) that doesn't prevent this from occurring.

Categories

Resources