Function with varying number of For Loops (python)
for loop python 3
python for loop increment
dynamic number of for loops
nested for loops python lists
nested for loop python
multiple for loops python
double for loop python
My problem is difficult to explain.
I want to create a function that contains nested for loops, the amount of which is proportional to an argument passed to the function.
Here's a hypothetical example:
for x in range (y): for x in range (y): do_whatever()
for x in range (y): for x in range (y): for x in range (y): for x in range (y): for x in range (y): for x in range (y): whatever()
The variables of the for loop (y) are NOT actually used in the nested code.
Your first thought might be to create ONE for loop, with a range that is to the power of the number argument... THIS CAN NOT WORK because the product would be HUGE. I have instances required where there are 8 nested for loops. The product is too large for a range in a for loop.
There are other arguments needed to be passed to the function, but I can handle that myself.
Here's the code (it creates the Snowflake Fractal)
from turtle import * length = 800 speed(0) def Mini(length): for x in range (3): forward(length) right(60) penup() setpos(-500, 0) pendown() choice = input("Enter Complexity:") if choice == 1: for x in range (3): forward(length) left(120) elif choice == 2: for x in range (3): Mini(length/3) left(120) if choice == 3: for x in range (6): Mini(length/9) right(60) Mini(length/9) left(120) if choice == 4: for y in range (6): for x in range (2): Mini(length/27) right(60) Mini(length/27) left(120) right(180) for x in range (2): Mini(length/27) right(60) Mini(length/27) left(120) if choice == 5: for a in range (6): for z in range (2): for y in range (2): for x in range (2): Mini(length/81) right(60) Mini(length/81) left(120) right(180) for x in range (2): Mini(length/81) right(60) Mini(length/81) left(120) right(180) right(180) if choice == 6: for c in range (6): for b in range (2): for a in range (2): for z in range (2): for y in range (2): for x in range (2): Mini(length/243) right(60) Mini(length/243) left(120) right(180) for x in range (2): Mini(length/243) right(60) Mini(length/243) left(120) right(180) right(180) right(180) right(180) if choice == 7: for a in range (6): for b in range(2): for c in range (2): for d in range (2): for e in range (2): for f in range (2): for y in range (2): for x in range (2): Mini(length/729) right(60) Mini(length/729) left(120) right(180) for x in range (2): Mini(length/729) right(60) Mini(length/729) left(120) right(180) right(180) right(180) right(180) right(180) right(180)
I'd appreciate any help you can give me at all, though if you suggest a different method (such as recursion), please don't just paste the code; instead, suggests some ideas that could put me in the right direction.
(The algorithm is for a Specialist Math Assignment)
specs: Python 2.7.1 Turtle IDLE Windows7
This problem can be solved by recursion. I am just writing an algorithm here, since I believe this can be a general problem.
function Recurse (y, number) if (number > 1) Recurse ( y, number - 1 ) else for x in range (y) whatever()
For loops, As you can see, these loop constructs serve different purposes. You could use a for loop with a huge number in order to gain the same effect as a Basically, any object with an iterable method can be used in a for loop. To loop through a set of code a specified number of times, we can use the range () function, The range () function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number. Example. Using the range () function: for x in range(6):
I'm not clear why you can't use the product of the bounds and do
for x in range(y exp n)
where n is the # of loops.... You say y exp n will be huge, but I'm sure python can handle it.
However, that being said, what about some sort of recursive algorithm?
def loop_rec(y, n): if n >= 1: for x in range(y): loop_rec(y, n - 1) else: whatever()
Python Tutorial: For Loops, In each iteration step a loop variable is set to a value in a sequence or other data function range() is the right function to iterate over a sequence of numbers. Level Up For-Loops in Python With 4 Simple Functions. function, the original variable meals got reversed. function allows us to have a counter to track the number of loops in the iteration.
Recursion will be your best bet. Consider what it should do in the base case and in the recursive case.
Code left out, as per request.
For Loops in Python 3, In this tutorial, we'll be covering how for loops work in Python and how to This for loop sets up i as its iterating variable, and the sequence exists in the range of 0 to 5. Then within the loop we print out one integer per loop iteration. Instead, you should work with the list.append() method, which you can numbers = [1,10,20,30,40,50] sum = 0 for number in numbers: sum = sum + numbers print sum for i in range(1,10): print i Break. To break out from a loop, you can use the keyword “break”. for i in range(1,10): if i == 3: break print i Continue. The continue statement is used to tell Python to skip the rest of the statements
Here you go. Let ranges be your ranges, operate on result when you need to.
ranges=((1,4),(0,3),(3,6)) from operator import mul operations=reduce(mul,(p-p for p in ranges))-1 result=[i for i in ranges] pos=len(ranges)-1 increments=0 print result while increments < operations: if result[pos]==ranges[pos]-1: result[pos]=ranges[pos] pos-=1 else: result[pos]+=1 increments+=1 pos=len(ranges)-1 #increment the innermost loop print result [1, 0, 3] [1, 0, 4] [1, 0, 5] [1, 1, 3] [1, 1, 4] [1, 1, 5] [1, 2, 3] [1, 2, 4] [1, 2, 5] [2, 0, 3] [2, 0, 4] [2, 0, 5] [2, 1, 3] [2, 1, 4] [2, 1, 5] [2, 2, 3] [2, 2, 4] [2, 2, 5] [3, 0, 3] [3, 0, 4] [3, 0, 5] [3, 1, 3] [3, 1, 4] [3, 1, 5] [3, 2, 3] [3, 2, 4] [3, 2, 5] [1, 0, 4]
Testing with the following would give the same result:
for x in range(*ranges): for y in range(*ranges): for z in range(*ranges): print [x,y,z]
7. Iteration, In Python, an assignment statement can make two variables equal, but Each item in turn is (re-)assigned to the loop variable, and the body of the loop is executed. Let us write a function now to sum up all the elements in a list of numbers. In python, when you build a list of numbers, images, files, or any other object that you want to iterate through, you’re essentially piling up memory as you put new items on the list, i.e. every
Have you considered xrange ?
for x in xrange(y ** n): whatever()
And if you overshoot even xrange limit, you can use itertool
import itertools for x in itertools.product(xrange(y), repeat=n): whatever()
(previous itertool answer incorrectly used n for the range instead of y)
Nested loops with same variable - Python queries, In Python variables have function-wide scope which means that if two variables have the same name in the same scope, they are in fact one variable. 4.2. for Statements¶. The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order
Nested loops with same variable reused after inner loop body , Description: Redefining a variable in an inner loop and then using the variable In Python variables have function-wide scope which means that if two variables This example shows a function that processes a sequence of lists of numbers. The range () function in Python is often used in for statements to define the number of loop iterations. This built-in function creates lists containing arithmetic progressions. The syntax of the range () function is: range (start, stop [, step])
Python for loop, In Python for loop is used to iterate over the items of any sequence The for loop is also used to access elements from a container (for example list, string, tuple) using built-in function for <variable> in range(<number>):. Python for loop example using range() function Here we are using range() function to calculate and display the sum of first 5 natural numbers. # Program to print the sum of first 5 natural numbers # variable to store the sum sum = 0 # iterating over natural numbers using range() for val in range(1, 6): # calculating sum sum = sum + val
ProjPython – Lists and for-loops, So far, we've needed a new variable name for each new piece of information we find out how many items are in a list using the Python built-in function len . For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The difference between range and xrange is that the range function returns a new list with numbers of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3 uses the range function, which acts like xrange).
- Is there anything about using recursion for this that you don't understand?
- If you're concerned about the size of
rangethen just use
- The structure of this function cleared the fog from my brain on converting my code to be recursive. Thanks x 1000000!
- Recursion is certainly one way of tackling this problem but the above algorithm is wrong; regardless of the value of
number, it only loops
ytimes. See the solution provided by @RobertMartin for the correct code/algorithm.
- @Loax is right. This answer is incorrect. The logic behind this answer doesn't work.
- This answer is incorrect. It should be de-selected as the solution.
- It was too big for python! :(
- Holy crap! I'm impressed with your program then! Good luck with the recursion
- This is actually the best solution and possibly one of the only solutions which worked!
- Yup, that's a classic case for recursivity.
- Finally found an iterative solution :) This is some good code!
- ...but actually, your actual problem is not the first one you describe, as you want an extra "right(180)" in each loop. So go recursive is the right answer