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
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 1 year ago.
Improve this question
I have the below JSON response, I want to write a function that:
runs through the response looking for a match of 'risk-level' = [medium OR high]
if match found returns the corresponding alert-id in a list / array format (I think we should use .append here)
if no match is found, exit the program (I'm pretty sure it would "exit()" here)
I have managed to get it to match / find one input and bring back that response, I'm just struggling with feeding it a list with an "OR" logic to bring back an independent result.
[
{'event-num': 5520, 'alert-id': '6e310403-ca53-32ut-aec6-16ffc648f7b7', 'risk-level': 'very-low'},
{'event-num': 5521, 'alert-id': '0a6b15b7-3db3-2x7t-b4ab-b023cfb85eaf', 'risk-level': 'low'},
{'event-num': 5523, 'alert-id': '6e310403-3db3-4b5f-cehd-16ffc648f7b7', 'risk-level': 'medium'},
{'event-num': 5523, 'alert-id': '0a6b15b7-6ty5-4b5f-cehd-b023cfb85eaf', 'risk-level': 'high'}
]
You could use .append() as you mentioned, or, you could do this in a quick list comprehension.
Let's say your list is called events.
risky_events = [event['alert-id']
for event in events
if event['risk-level'] in {'medium','high'}]
The above code simply creates a list of matching risk levels. How would you use the snippet above to implement your exit() requirement? You would need to check if the list created above was empty. Give it a try.
What went wrong in the approach you took? Did you try using .append() yourself? Look up the Python docs section on lists to understand how append works, and give that approach a try.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
I'm currently working on a school assignment that involves me learning Python and I'm currently stuck on 'For Loops.' I'm stuck on understanding how they work and their syntax.
I have an example of code I've been trying to wrap my head around but just can't get it.
simple_list = ["Jack", "Dianne", "Alfred", "Erik"]
for x in simple_list:
print(x)
This is the code I've been focusing on and I don't understand why it prints a name from the simple list.
I also want to know what 'in' does as I couldn't find anything online that helped me understand it.
Thanks!
You can think like this:
for EVERY ITEM in THIS LIST:
print(THIS ITEM)
items = ["Jack", "Dianne", "Alfred", "Erik"]
for item in items:
print(item)
Look at it as a for each instead of the class for with indices.
for (each) item in items:
print(item)
For loops go over every item in a list. In this case you have a list
simple_list = ["Jack", "Dianne", "Alfred", "Erik"]
Now the for loop is going to look at every item in the list and do whatever is in the for loop with it. In this case, it will print it.
I'd recommend having a look at http://www.pythontutor.com/ to get a better feel for this sort of thing.
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 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.