Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question appears to be off-topic because it lacks sufficient information to diagnose the problem. Describe your problem in more detail or include a minimal example in the question itself.
Closed 8 years ago.
Improve this question
I am new to Python and I am trying to write a for loop to go through a list of results, doing some calculations on them and then print them, but it is not working.
As I have said, I am new to this and trying to learn, if anybody has had experience with this could you please explain to me, I know it is probably a silly mistake but I cannot see it.
for test in test_set:
person_id = test['person_id']
place_id = test['place_id']
rating = test['rating']
predicted_rating = simple_nearestneighbours(person_id, place_id, 50)
n = 0
while n < 50:
mae = (abs(predicted_rating - rating))
#return mae/ 5
# print mae/50
print "MAE " + str(mae/50)
You are not incrementing the value of n in while loop.
This causes the while loop to run indefinitely, which in turn causes the for loop to run indefinitely.
Add a statement n += 1 in the while loop, if you really want to use it there.
Your while loop runs infinitely as n will always be less than 50 (you never change its value from 0), thus meaning your for loop gets stuck.
You could fix the while loop by incrementing n with n += 1 within the loop, but using a while loop is pointless here.
Instead of your while loop, I would just use a for loop instead:
for n in range(50):
This is better because you are essentially just iterating upwards an equal amount each time- the condition will always be fulfilled at the same moment.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 10 months ago.
Improve this question
My teacher has asked me to implement an array using python without using any inbuilt functions but I am confused and I don't know how to? this is the complete question...
Write a program in Python to implement the “Array” data structure. Perform operations like add or insert, delete or remove and display. Your program should be able to add/insert at any position in an array or remove/delete any element from an array. Take care of extreme conditions such as an empty array or full array and display an appropriate message to the user.
any help would be highly appreciated.
You can store the array in a list L, and write a function for each list operation. For example, to search for an element x in a list L and return the index of the first occurrence of x in L, rather than using the built-in function index, you would implement the linear search algorithm. So, the following code would be incorrect because it uses the built-in function index:
def search(L,x):
return L.index(x)
The following code would be acceptable because you are implementing the linear search algorithm yourself (presumably your teacher wants you to write programs from scratch, which is very good practice):
def search(L,x):
#input: a list L and an element x
#output: the index of first occurrence of x in L, or -1 if x not in L
n = len(L)
for i in range(n):
if L[i] == x:
return i
return -1
L=[3,1,4,2]
print(search(L,7))
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I am not sure where I went wrong with my below code, where I used two for loops to firstly iterate statename and then iterate each dictionary that contains that specific statename.
I finally resolved this via my second code (the right code on the snip) however would be keen to know why the first didn't work.
The file used is a census file with statename, countyname (a subdivision of the state) and population being the columns.
Couldn't work with the following snip (on the left) where the error is 'string indices must be integers':
As others have already suggested, please read up on providing a Minimal, Reproducible Example. Nevertheless, I can see what went wrong here. When you loop through for d in census_df, this actually loops through the column names for your data frame, i.e. SUMLEV, REGION etc. This is presumably not what you had in mind.
Then your next line if d['STNAME']==c causes an error, as the message says, because string indices must be integers. In this instance you are trying to index a string using another string STNAME.
If you really want that first method to work, try using iterrows:
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for index, row in census_df.iterrows():
if row['STNAME']==c:
count+=1
list.append(count)
return(max(list))
answer_five()
Don't know why the pic is not coming up...sorry first timer here!
the first code that I tried which I have questions over are: (regarding string indices must be integers):
state_unique=census_df['STNAME'].unique()
list=[]
def answer_five():
for c in state_unique:
count=0
for d in census_df:
if d['STNAME']==c:
count+=1
return list.append(count)
answer_five()
The second code helped resolve my question is:
max_county=[]
state_unique=census_df['STNAME'].unique()
def answer_five():
for c in state_unique:
df1=census_df[census_df['STNAME']==c]
max_county.append(len(df1))
return max(max_county)
answer_five()
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm querying a Postgres database (nfldb for anyone familiar) from Python and would like to make one of my query criteria a variable to streamline my data collection. The code I'm using
import nfldb
db = nfldb.connect()
q = nfldb.Query(db)
for i in range (1,15):
q.game(season_year=2015, season_type='Regular', week=i)
q.player(full_name='Julian Edelman')
print p.player.full_name, p.receiving_yds, p.receiving_tds
I would expect this to return each week's stats, but it returns the first week's stats 14 times. When I change week = i to explicit numbers, it returns the stats as I would expect. Why might this be happening?
Your question here will be difficult for anyone not familiar with nfldb to answer because the .game nomenclature is a special feature of nfldb that can be used to further filter your query q.
By narrowing the scope of your query to a single week, you are giving nfldb permission to discard all other non-fitting data. So when you repeat your loop and ask for the next week, you are asking for data that you just told nfldb to discard from q.
If you want to make the same query over each week individually, you will need to tuck your q = nfldb.Query(db) into the for loop so as to reset the expectation that the query starts with all data in the database available to it.
import nfldb
db = nfldb.connect()
for i in range (1,15):
q = nfldb.Query(db)
q.game(season_year=2015, season_type='Regular', week=i)
q.player(full_name='Julian Edelman')
As someone else mentioned, though, you are missing something from this codeblock since p appears out of nowhere.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
def evolve():
global pop,fvals
for g in xrange(0,gmax):
for i in xrange(0,NP):
while 1:
r1=random.randint(0,NP-1)
if r1!=i:
break
while 1:
r2=random.randint(0,NP-1)
if r2!=r1 and r2!=i:
break
while 1:
r3=random.randint(0,NP-1)
if r3!=r2 and r3!=r1 and r3!=i:
break
U=[]
V=[]
for j in xrange(0,dim):
U.insert(j,(pop[r3])[j] + F*((pop[r1])[j]-(pop[r2])[j]))
jrand = floor(int(rand1()*dim))
for j in xrange(0,dim):
if rand1()<=cr or j==jrand:
U.insert(j,(pop[r3])[j] + F*((pop[r1])[j]-(pop[r2])[j]))
else:
U.insert(j,(pop[i])[j])
V.insert(i,U)
fvals2.insert(i,fun(U))
x=open("x.out","w")
for i in xrange(NP):
for j in xrange(dim):
print i
print j
x.write(str((V[i])[j]) + '\t')
x.write(str(fvals2[i]))
x.write('\n')
While executing this code block shows an error:
x.write(str((V[i])[j]) + '\t')
IndexError: list index out of range
Here I have taken gmax=5, dim=2 and NP=5.
You're setting V to [] on each of your for n in xrange(0,NP) loops, losing any values it had previously. That means that by the time you're writing the file, V only has one value contained in it (at most), which is why you're getting an IndexError when you try to read xrange(NP) values out of it. You probably want to initialize V outside that loop.
You're also missing some indents on if rand1()<=cr or j==rand, but I'm guessing that happened when putting the code into your post or it probably wouldn't have ran far enough to get the IndexError when writing a file.
That aside, please consider the following:
Please name your variables with actual names - all these single letters and letter-number combinations make the code really hard to read.
You might also consider breaking some of these nested operations up into separate functions, which could also improve readability.
You aren't closing the output file after you're done writing it - you probably want to add an x.close() line to the end or do all the writing within an with open('x.out','w') as x: block. You're also overwriting that file on each of the loops of for g in xrange(0,gmax), so you might want to move it outside that loop as well.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I am trying to write over an existing list and skip over any index in the list where value[i] = -1, preserving that value at the correct index.
One problem is the last_item value seems to wrap around to the end of the list, is there a way to prevent that? Otherwise, is there a better way to do this? This seems too clumsy with all the logic.
The data looks like:
-1
1
2
3
-1
1
2
3
And Im trying to get it to look like this:
-1
1
2
3
-1
4
5...
EDIT
I modified the code that Alex posted below, it is working great now. Here is the code I used:
count = 1
for i range(len(my_list)):
if my_list[i] == -1:
new_list.append(-1)
else:
my_list[i] = count
count += 1
new_list.append(my_list[i])
You probably want to brush up on python lists, python loops, and iteration/indexing in general before you start to write this code. Here are some pages you might find useful
An Intro to Python Lists
For Loops in Python
Looping with Lists in Python
Another note, just because you set a variable equal to an element in a list, you can't expect that element in that list to change if you change the variable. That's like saying, I'm going to make a copy of this cookie that looks and tastes just like this other cookie. Then, if you eat the second cookie (the one you made), the first one will still exist until you go in and actually eat that cookie.
The same goes for that iterating variable, i. When you check if i==-1, you're really only saying "Is this the first loop in my loop?" because you're looping starting at -1. This should all make more sense when you glance over those loop articles.
Awesome, the input/output data helps a lot. It makes more sense now.
How about this:
count = 1
for i range(len(my_list)):
if my_list[i] = -1:
continue
else:
my_list[i] = count
count++
Where my_list is the input list
I'm not 100% understanding the problem here, but I think I do. And this code should give you the output you want given the input you provided. HTH