- Цикл от 1 до бесконечности в Python
- 9 ответов
- Looping from 1 to Infinity in Python
- Infinite loops using ‘for’ in Python
- Infinite for loop in Python like C++
- Infinity loop issue using for loops
- Easy way to keep counting up infinitely
- Why is my while function causing an infinite loop?
- Python for loop in enumerate list goes for infinite
- Запуск от 1 до бесконечности в Python
- Ответ 2
- Ответ 3
- Ответ 4
- Ответ 5
- Ответ 6
- Ответ 7
- Ответ 8
- Ответ 9
- Ответ 10
- Ответ 11
- Infinite range python
- Python for loop range function causing an infinite loop
Цикл от 1 до бесконечности в Python
Я не эксперт while (true): if reasonneeded(i) break i = i+1 но while (true): if reasonneeded(i) break i = i+1 Должен работать?
Не следует ли изменить название этого вопроса на «Цикл от 0 до бесконечности в Python»? Вы просто пытаетесь иметь «бесконечный range », поэтому вы можете избежать, while True: i += 1
9 ответов
import itertools for i in itertools.count(): if there_is_a_reason_to_break(i): break
В Python2 xrange() ограничен sys.maxint, чего может быть достаточно для практических целей:
import sys for i in xrange(sys.maxint): if there_is_a_reason_to_break(i): break
В Python3 range() может идти гораздо выше, хотя и не до бесконечности:
import sys for i in range(sys.maxsize**10): # you could go even higher if you really want if there_is_a_reason_to_break(i): break
Поэтому лучше всего использовать count() .
Для меня, for i in range(sys.maxint) разрывается с MemoryError . Вы также упомянули xrange() которая работает.
@scai, в range Python3 заменяет xrange Python2. В Python2 range создает и возвращает фактический список целых. У вас не будет достаточно оперативной памяти для такого большого списка
def to_infinity(): index=0 while 1: yield index index += 1 for i in to_infinity(): if i > 10:break
Повторяя комментарий thg435:
from itertools import takewhile, count def thereIsAReasonToContinue(i): return not thereIsAReasonToBreak(i) for i in takewhile(thereIsAReasonToContinue, count()): pass # or something else
Или, может быть, более кратко:
from itertools import takewhile, count for i in takewhile(lambda x : not thereIsAReasonToBreak(x), count()): pass # or something else
takewhile имитирует «корректный» цикл C: у вас есть условие продолжения, но вместо произвольного выражения у вас есть генератор. Есть вещи, которые вы можете сделать в цикле C, которые «плохо себя ведут», например, изменение i в теле цикла. Можно также имитировать их с помощью takewhile , если генератор является замыканием над некоторой локальной переменной i , с которой вы тогда сталкиваетесь. В некотором смысле, определение этого закрытия делает особенно очевидным, что вы делаете что-то потенциально запутанное с вашей структурой управления.
Looping from 1 to Infinity in Python
In Python 2, range() and xrange() were limited to sys.maxsize . In Python 3 range() can go much higher, though not to infinity:
import sys
for i in range(sys.maxsize**10): # you could go even higher if you really want
if there_is_a_reason_to_break(i):
break
So it’s probably best to use count() .
Infinite loops using ‘for’ in Python
range is a class, and using in like e.g. range(1, a) creates an object of that class. This object is created only once, it is not recreated every iteration of the loop. That’s the reason the first example will not result in an infinite loop.
The other two loops are not infinite because, unlike the range object, the loop variable i is recreated (or rather reinitialized) each iteration. The values you assign to i inside the loop will be overwritten as the loop iterates.
Infinite for loop in Python like C++
Python’s for statement is a «for-each» loop (sort of like range-for in C++11 and later), not a C-style «for-computation» loop.
But notice that in C, for (;;) does the same thing as while (1) . And Python’s while loop is basically the same as C’s with a few extra bells and whistles. And, in fact, the idiomatic way to loop forever is: 1
If you really do want to write a for loop that goes forever, you need an iterable of infinite length. You can grab one out of the standard library: 2
def forever():
while True:
yield None
for _ in forever():
But again, this isn’t really that similar to for (;;) , because it’s a for-each loop.
1. while 1: used to be a common alternative. It’s faster in older versions of Python, although not in current ones, and occasionally that mattered.
2. Of course the point of count isn’t just going on forever, it’s counting up numbers forever. For example, if enumerate didn’t exist, you could write it as zip(itertools.count(), it) .
Infinity loop issue using for loops
Now that you’ve shown the full code, your problem is obvious. Your original example didn’t show the issue because you didn’t include all relevant code. Here’s your example with the relevant code that’s causing the issue:
for us_code in us_code_list:
for macd_diff in macd_diff_list:
for profit_target in profit_target_list:
for stop_loss in stop_loss_list:
. # irrelevant code not shown
macd_diff_list.append(macd_diff)
The issue is that you’re looping through each item in macd_diff_list , but then for each loop iteration, you add an item to that list. So of course the loop will be infinite. You need to be looping through a different list, or adding items to a different list.
Easy way to keep counting up infinitely
Take a look at itertools.count().
count(start=0, step=1) —> count object
Make an iterator that returns evenly spaced values starting with n .
Equivalent to:
def count(start=0, step=1):
# count(10) --> 10 11 12 13 14 .
# count(2.5, 0.5) -> 2.5 3.0 3.5 .
n = start
while True:
yield n
n += step
import itertools
for i in itertools.count(13):
print(i)
would generate an infinite sequence starting with 13, in steps of +1. And, I hadn’t tried this before, but you can count down too of course:
for i in itertools.count(100, -5):
print(i)
starts at 100, and keeps subtracting 5 for each new value .
Why is my while function causing an infinite loop?
Because your I never actually increases in this while loop. If you really want to do it this way you can just add a i += 1 to the end of your function
def double_values_in_list ( ll ):
i = 0
while (i ll[i] = ll[i] * 2
print ( "ll[<>] = <>".format( i, ll[i] ) )
i += 1
return ll
print(double_values_in_list([1, 2]))
However, this is a lot of extra steps that you don’t need to take, you can simply run a pythonic for loop to make things a lot easier on yourself
def double_values_in_list (ll):
return [x*2 for x in ll]
print(double_values_in_list([1, 2]))
Python for loop in enumerate list goes for infinite
You can iterate over a copy of this list:
for index, item in enumerate(a.copy()):
Запуск от 1 до бесконечности в Python
В Python2 xrange() ограничен sys.maxint, чего может быть достаточно для практических целей:
import sys for i in xrange(sys.maxint): if there_is_a_reason_to_break(i): break
В Python3 range() может идти гораздо выше, хотя и не до бесконечности:
import sys for i in range(sys.maxsize**10): # you could go even higher if you really want if there_is_a_reason_to_break(i): break
Поэтому лучше всего использовать count() .
Ответ 2
def to_infinity(): index=0 while 1: yield index index += 1 for i in to_infinity(): if i > 10:break
Ответ 3
i = 0 while not there_is_reason_to_break(i): # some code here i += 1
Возможно, возникает соблазн выбрать ближайшую аналогию с C-кодом, который возможен в Python:
from itertools import count for i in count(): if thereIsAReasonToBreak(i): break
Но будьте осторожны, модификация i не будет влиять на поток цикла, как это было бы в C. Поэтому использование цикла while на самом деле является более подходящим выбором для переноса этого кода на C на Python.
Ответ 4
Повторяя комментарий thg435:
from itertools import takewhile, count def thereIsAReasonToContinue(i): return not thereIsAReasonToBreak(i) for i in takewhile(thereIsAReasonToContinue, count()): pass # or something else
Или, может быть, более кратко:
from itertools import takewhile, count for i in takewhile(lambda x : not thereIsAReasonToBreak(x), count()): pass # or something else
takewhile имитирует «корректный» цикл C: у вас есть условие продолжения, но вместо произвольного выражения у вас есть генератор. Есть вещи, которые вы можете сделать в цикле C, которые «плохо себя ведут», например, изменение i в теле цикла. Можно также имитировать их с помощью takewhile , если генератор является замыканием над некоторой локальной переменной i , с которой вы тогда сталкиваетесь. В некотором смысле, определение этого закрытия делает особенно очевидным, что вы делаете что-то потенциально запутанное с вашей структурой управления.
Ответ 5
Если вы делаете это на C, тогда ваше суждение будет таким же облачным, как и в Python: -)
int i = 0; while (! thereIsAReasonToBreak (i)) < // do something i++; >
int i; // *may* be better inside the for statement to localise scope for (i = 0; ! thereIsAReasonToBreak (i); i++) < // do something >
i = 0 while not thereIsAReasonToBreak (i): # do something i += 1
Только если вам нужно выйти из середины цикла, вам нужно будет беспокоиться о нарушении. Если ваш потенциальный выход находится в начале цикла (как представляется, здесь), обычно лучше кодировать выход в сам цикл.
Ответ 6
Это работает для всех версий python:
m=1 for i in range(m): #action here m+=1
Ответ 7
Вероятно, лучшим решением для этого является использование цикла while: i=1 while True: if condition: break . rest code i+=1
Ответ 8
Если вам нужно указать предпочитаемый размер шага (например, с диапазоном) и вы предпочитаете не импортировать внешний пакет (например, itertools),
def infn(start=0, step_size=1): """Infinitely generate ascending numbers""" while True: yield start start += step_size for n in infn(): print(n)
Ответ 9
a = 1 while a: if a == Thereisareasontobreak(a): break a += 1
Ответ 10
while 1==1: if want_to_break==yes: break else: # whatever you want to loop to infinity
Этот цикл с бесконечным ходом.
Ответ 11
Вы также можете сделать следующее:
list=[0] for x in list: list.append(x+1) print x
Это приведет к бесконечному for loop .
Infinite range python
Python for loop range function causing an infinite loop
I am building a sudoku function to learn how to code in python. I seem to be creating an infinite loop with a for loop but I don’t understand how. The code attempts to look at each empty square of the sudoku board and check if a value counter is allowed by the rules of sudoku. If counter is allowed the board is updated and the function moves on to the next empty square. If counter is not allowed than counter is incremented by 1 and tested again.
The issue I am having comes when counter is greater then 9. When this happens I want to look at the previous square which was empty on the original board (named puzzle) and delete the value in this square. The function than should set counter equal to the value in the previous square +1 and call itself to run again.
In essence the function is testing each empty square for possible values until it finds a value and than move on to the next square. If there are no possible values the function will back track, delete the last square and try running again.
My problem seems to happen in the else condition when counter is greater than 9. This part of the function is causing an infinite loop which prints out ‘no’ repeatedly.
I’m assuming that my function is getting stuck on the while loop but I’m not sure why.
puzzleBoard =[[1,2,3,4,5,6,7,8,9],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0,0]] def solvePuzzle(): #start by looking at each square in the 9x9 sudoku grid and check if that square is empty (=0) for i in range(9): for j in range(9): counter = 1 topX = 3*(i//3) topY = 3*(j//3) # while the board at index [i][j] is empty check if the value of 'counter' fits in the square and adheres to the sudoku rules # if counter is not an allowed value increment counter by 1 and try again while puzzleBoard[i][j] ==0: if counter < 10: row = all([counter != puzzleBoard[i][x] for x in range(9)]) column = all([counter != puzzleBoard[y][j] for y in range(9)]) box = all([counter != puzzleBoard[x][y] for x in range(topX, topX+3) for y in range(topY, topY+3)]) if row and column and box == True: puzzleBoard[i][j]=counter uploadBoard() else: counter = counter + 1 # if counter is larger than ten set the previous square ([i][j-1]) equal to zero, set the counter equal to one more than the previous squares value, and call the solvePuzzle function again. else: for k in range(i,0,-1): for l in range(j-1,0,-1): if puzzle[k][l]==0: counter = puzzleBoard[k][l] + 1 puzzleBoard[k][l]=0 solvePuzzle() return else: print("no")
I was able to work out the answer. There are a few issues with the code but the main problem is that in the lower else statement counter = puzzleBoard[k][l] + 1 and then the function was being called again, which resets the variable counter to 1.
I was able to fix this problem by creating a global variable countholder and modifying the else statement to say countholder = puzzleBoard[k][l] + 1
The full working code looks like this:
puzzleBoard =[[0,2,0,0,0,0,0,0,0],[0,0,0,6,0,0,0,0,3], [0,7,4,0,8,0,0,0,0],[0,0,0,0,0,3,0,0,2], [0,8,0,0,4,0,0,1,0],[6,0,0,5,0,0,0,0,0], [0,0,0,0,1,0,7,8,0],[5,0,0,0,0,9,0,0,0], [0,0,0,0,0,0,0,4,0]] puzzle =[[0,2,0,0,0,0,0,0,0],[0,0,0,6,0,0,0,0,3], [0,7,4,0,8,0,0,0,0],[0,0,0,0,0,3,0,0,2], [0,8,0,0,4,0,0,1,0],[6,0,0,5,0,0,0,0,0], [0,0,0,0,1,0,7,8,0],[5,0,0,0,0,9,0,0,0], [0,0,0,0,0,0,0,4,0]] countholder = 1 def solvePuzzle(): #start by looking at each square in the 9x9 sudoku grid and check if that square is empty (=0) for i in range(9): for j in range(9): global countholder counter = countholder topX = 3*(i//3) topY = 3*(j//3) # while the board at index [i][j] is empty check if the value of 'counter' fits in the square and adheres to the sudoku rules # if counter is not an allowed value increment counter by 1 and try again while puzzleBoard[i][j] ==0: if counter < 10: row = all([counter != puzzleBoard[i][x] for x in range(9)]) column = all([counter != puzzleBoard[y][j] for y in range(9)]) box = all([counter != puzzleBoard[x][y] for x in range(topX, topX+3) for y in range(topY, topY+3)]) if (row and column and box) == True: puzzleBoard[i][j]=counter print(puzzleBoard) countholder = 1 else: counter = counter + 1 # if counter is larger than ten set the previous square ([i][j-1]) equal to zero, set the counter equal to one more than the previous squares value, and call the solvePuzzle function again. else: run_One = True for k in range(i,-1,-1): if run_One == True: run_One = False for l in range(j,0,-1): if l == 0: print(run_One) elif puzzle[k][l-1]==0: countholder = puzzleBoard[k][l-1] + 1 puzzleBoard[k][l-1]=0 solvePuzzle() return else: continue else: for l in range(8,-1,-1): if puzzle[k][l]==0: countholder = puzzleBoard[k][l] + 1 puzzleBoard[k][l]=0 solvePuzzle() return else: continue solvePuzzle()
Why is my "while" function causing an infinite loop?, You are not incrementing i at any point inside your while loop so your i will always remain 0 because you initialized it with 0 at start