Each time your first loop runs, it sets linelist to a new value, overwriting any old value. After that first loop runs, linelist will contain only the split result from the last line of the file. Every time you process one line of the file, you are throwing away whatever you did with the previous line.
If you want to build a list of all words in the dictionary file, you need to make a list and append to it on each iteration of your for line in infile loop.
Also, it doesn't make much sense to use split on each line if each line is just one word, since there will be no splitting to be done.
I have a list of strings. I want to remove all items from the list that begin with the '#' character. But running my for loop only manages to remove a subset of targeted items. Then I run the loop again on the same list and it removes another set. But I have to do this several times before it gets through the whole list.
Here's my code:
for item in list:
if item[0] == "#":
list.remove(item)
print("item removed: ", item)When I run this code the first time it won't remove all the items I want it to remove. Only 9. So I copy and paste the same code into IDLE and run it again and it removes 4 more items, but still not all. So I paste and run it again and another 2 are removed, but not all. So I run it again and it removes 1, then again and it removes the last 1. This is really strange. What is happening?
It's because you're actively changing the length of the list while you're looping it! Its a mistake I make too easily.
Try instead to append items to a new list rather than altering the original list, you'll run into problems otherwise, others may correct me though. Try instead to append items you want to a "new_list" etc. Try this:
new_list = []
for item in list:
if item[0] != "#"
new_list.append(item)
print(new_list)
Let me know if that helps you
https://www.reddit.com/r/learnpython/wiki/faq#wiki_why_does_my_loop_seem_to_be_skipping_items_in_a_list.3F
https://unspecified.wordpress.com/2009/02/12/thou-shalt-not-modify-a-list-during-iteration/
Edit:
list is a terrible name for a variable and could cause bugs in your code. Stay away from words that have a special meaning in python when choosing the name of your variables!
Each time your first loop runs, it sets linelist to a new value, overwriting any old value. After that first loop runs, linelist will contain only the split result from the last line of the file. Every time you process one line of the file, you are throwing away whatever you did with the previous line.
If you want to build a list of all words in the dictionary file, you need to make a list and append to it on each iteration of your for line in infile loop.
Also, it doesn't make much sense to use split on each line if each line is just one word, since there will be no splitting to be done.
for line in infile:
line = line.strip()
linelist = line.split(" ")
Every time you do linelist = line.split(" "), that replaces the old linelist with words from just the last line. The list ends up only holding words from the last line. If you want words from the entire file, create a single linelist and extend it with new words:
linelist = []
for line in infile:
# split with no argument splits on any run of whitespace, trimming
# leading and trailing whitespace
linelist += line.split()
# ^ this means add the elements of line.split() to linelist
Since apparently every word is on its own line, though, you shouldn't even be using split:
words = [line.strip() for line in infile]
python - Why my for loop is not iterating all the values - Stack Overflow
python - Why is my for loop not iterating in this code? - Stack Overflow
python - Loop not iterating - Stack Overflow
Python: Why is my for loop not iterating over the entire list? - Stack Overflow
As stated in a comment, this is an easy fix. Simply move the else statement's return to outside of the loop.
def find(x):
if x > 1:
for i in range(2,x):
if x % i == 0:
return "its not a prime num"
return "Its a prime num"
user = int(input("Enter your no: "))
print(find(user))
Using a return inside of a loop will break it and exit the function even if the iteration is still not finished. use print instead.
Simple answer: because your return statement is inside the for loop. So, probably just an indentation error.
But this code is, I must say, pretty un-Pythonic. You're doing lots of iterating through ranges, which should always be a red flag: in Python you usually want to iterate through an actual thing, not a specially-constructed range. In any case, since you're not even using the loop variable (process), you should consider if a for loop is the right structure at all.
Plus, as volcano points out in the comments, most of your setup code can be shortened significantly.
You return tape in inner cycle, the one with process in range(...), so only one iteration happens. Your tape also is not long enough, you make several operations per each tape available space, I also didn't find any "termination" symbol, so it never will be long enough with such for conditions.
Here is "fixed" code:
eachconfig = [['a', ['blank', ['p1', 'r', 'r'], ['b']]], ['b', ['blank', ['p0'], ['c']]], ['c', ['blank', ['r', 'r'], ['a']]]]
def turingmachine(data):
a = 0
tape = []
finalmc = data[0][0]
for z in range(1,40):
tape.append(' ')
mcName = []
m = 0
for emc in range(1,len(data)+1):
goal = data[m][0]
mcName.append(goal)
m+=1
mcNumber = [h-1 for h in range(1,len(mcName)+1)]
mcNameNumber = dict(zip(mcName,mcNumber))
d = 0
tapeposition = d
tapescan = tape[d]
for process in range(1,len(tape) - 8):
b = 0
c = 0
cconfig = data[a][b]
if cconfig == finalmc:
b += 1
scannedsymbol = data[a][b][c]
if isinstance(scannedsymbol, str):
if scannedsymbol.lower() in ('any', 'blank'):
c += 1
operations = data[a][b][c]
for cycle in operations:
if cycle[0] in ('p','P'):
tape[tapeposition] = cycle[1:]
elif cycle[0] in ('r', 'R'):
tapeposition += 1
elif cycle[0] in ('l', 'L'):
tapeposition -= 1
elif cycle[0] in ('e', 'E'):
tape[tapeposition] == ' '
finalmc = data[a][b][-1][0]
a = mcNameNumber[finalmc]
return tape
print turingmachine(eachconfig)
You set RABBITS and RABBIT_BIRTH_RATE at the beginning. Then, on every loop iteration, you set RABBITS_START to some formula involving these two numbers. You never change the value of RABBITS or RABBIT_BIRTH_RATE or FOXES or anything, so every time you run through the loop, you're just calculating the same thing again with the same numbers. You need to update the values of your variables on each iteration --- that is, set a new value for RABBITS, FOXES, etc.
The biggest issue for me is what you named your "change in rabbits/foxes". RABBITS_START sounds like an initial count for RABBITS, but it's not. This is why I renamed it to RABBITS_DELTA, because really it's calculating the CHANGE in rabbits for each day.
I think I got it. At the very least this behaves more like a simulation now:
def run_simulation():
RABBIT_BIRTH_RATE = 0.01
FOX_BIRTH_RATE = 0.005
INTERACT = 0.00001
SUCCESS = 0.01
x = 0
y = 1
FOXES = eval(str(input("Enter the initial number of foxes: ")))
RABBITS = eval(str(input("Enter the initial number of rabbits: ")))
DAYS = eval(str(input("Enter the number of days to run the simulation: ")))
print("Day\t","Rabbits\t","Foxes\t")
print(0,"\t",RABBITS,"\t","\t",FOXES,"\t")
count = 0
while count < DAYS:
RABBITS_DELTA = round((RABBIT_BIRTH_RATE * RABBITS) \
- (INTERACT * RABBITS * FOXES))
FOXES_DELTA = round((INTERACT * SUCCESS * RABBITS * FOXES) \
- (FOX_BIRTH_RATE * FOXES))
y = y + x
RABBITS += RABBITS_DELTA
FOXES += FOXES_DELTA
print (y,"\t",(RABBITS),"\t","\t",(FOXES),"\t")
count += 1
run_simulation()
There is both too much and not enough code there, to be able to find the "actual" problem. I would guess, though, that you are probably iterating over a list or array or collection and simultaneously removing things from it. That's a common question here on SO.
In general, you will see weird behavior like skipping over elements, or (in your case) having a list that should be empty show up as not empty.
In particular, I see you in one function doing this:
for element in monster.inventory:
In another function, you are doing this:
for object in objects:
...
object.inventory.remove(self.owner)
I wonder if the monster.inventory list and the object.inventory list aren't the same at some point, which gives you a function accessing the list via an alias and removing elements, while you are trying to iterate over the list elsewhere.
Here's an example:
>>> inventory = [1,2,3]
>>> for item in inventory:
... print(item)
... inventory.remove(item)
...
1
3
>>> inventory
[2]
What happens is the iterator (for item in inventory) points to [1], the [1] gets .removed(), which means the iterator now points to [2], which is the new "first item" in the list. The loop finishes, the iterator advances, and now the iterator points to [3]. The [3] gets .removed(), the iterator tries to advance and reaches the end of the list, so it stops. You have now removed the [1] and the [3], and skipped over the [2].
Making a copy of the list, then iterating the copy, will ensure you iterate over every single item, while removing them from the official list.
It looks like in the first object:
Object( x=0, y=0, char='-', name='Dagger', color=libtcod.cyan, equipment=Equipment(slot='right hand', power_bonus=2) )
You don't declare the item attribute, so the following loop:
for element in monster.inventory:
if element.item:
element.item.drop()
the if clause interprets item as False and skips the first element.
If some exception is occurring in the initialization method of class Object (and catched) the attribute item will not exist causing the error.
You're calling return inside the loop because of where it is indented currently, so it gets executed after the very first iteration. Likely you want to move it outside the loop (the same indentation level as the for itself) so it gets called after the iteration is complete:
def computeBill(food):
total = 0.0
for item in food:
total += prices[str(item)] + stock[str(item)]
print total
return total
Your return statement is indented below the for statement. Fix that and you should be fine.
You read through the file once with your first for loop, so there isn't anything left to read for the second loop. Seek back to the beginning of the file before starting the second loop:
fyle.seek(0)
Although I'd just cache the lines as a list, if possible:
with open('filename.txt', 'r') as handle:
lines = list(handle)
Also, you can replace this:
if rows == 2:
self.collisionLayer[rowcount][colcount] = False
else:
self.collisionLayer[rowcount][colcount] = True
With:
self.collisionLayer[rowcount][colcount] = rows != 2
The loop:
for lyne in fyle:
... reads all of fyle and leaves nothing to be read by the loop:
for rows in fyle:
In pandas, DataFrame.iterrows() yields the index and the row. The index is something you control, and looking at your sample data you don't have an index that is densely-packed integers, but something else.
Try this code instead:
def dropNotIn(df):
print(df.shape)
removedlist = []
droplist = []
num_rows = 0
for i, x in df.iterrows():
num_rows += 1
print(num_rows)
print(len(df))
This counts the rows explicitly, instead of trying to use the index. If you really want to count rows during your operations, I'd suggest using the builtin function enumerate for this:
for num, (index, row) in enumerate(df.iterrows()):
pass
However, I suspect you probably don't want to do that, because when you're doing things with a dataframe you want to vectorize them as much as possible.
The iterrow iterate around the index which is not equal to rownum. You may have some indexes with more than one row.
Try unpacking the x,y = df.shape() and iterate around a range(x)