Creating N Nested For-Loops

Creating N nested for-loops

You may use recursion instead with a base condition -

void doRecursion(int baseCondition){

if(baseCondition==0) return;

//place your code here

doRecursion(baseCondition-1);
}

Now you don't need to provide the baseCondition value at compile time. You can provide it while calling the doRecursion() method.

How to creating N number of nested for loops

The solution is mostly recursive function.

You can make a recursive function recFun(n : number) that take a value n and make n loops that are calling recFun(n-1) and stops at 1 or 0.

fun recFun(n : number)
if(n == 0) return ??? ;
else {
for(i = 0 ; i < n ; i++)
recFun(n-1);
}

You can find example in C++ here

N nested for loops in a python

Recursion is simply a function keeps calling itself until it meets certain condition. You can learn more here. I think in this case you can make the code above recursive by having it either push + go to another recursion level + undo or number += 1 by checking if the current loop level (level in the code below) is equal to N (max_level in the code below)

number = 0

def moves(level, max_level):
global number
if level < max_level:
for move in all_legal_moves():
push(move)
moves(level + 1, max_level)
undo()
else:
number += 1

moves(move, 1, 5)
print('Number of possible moves:', number)

Or if you don't want to have number as a global variable, you can make the function return the number of possible iterations instead

def moves(level, max_level):
number = 0
if level < max_level:
for move in all_legal_moves():
push(move)
number += moves(level + 1, max_level)
undo()
else:
number += 1
return number

number_of_possible_moves = moves(move, 1, 5)
print('Number of possible moves', number_of_possible_moves)

Nesting for Loop n Times

You do not need to repeat the for loop. Instead you need to nest it.

The most inviting solution to implement this is a recursive construct.

Pseudo code:

void nestloop(int depth, int width)
{
if(depth>0)
{
int i;
for (i=0; i<width; i++)
{
nestloop(depth-1, width);
}
} else
{
/* do whatever you need done inside the innermost loop */
}
}

How do you create any number of nested loops?

this should work; you enter the length in the repeat argument of product while enumerate enumerates the words (starting at 0 by default; you could add start=1 depending on your needs):

from itertools import product

search = "bike"

for i, item in enumerate(product(a.values(), repeat=len(search))):
word = "".join(item)
print(word, i)
if word == search:
break

it outputs:

...
bikb 23245
bikc 23246
bikd 23247
bike 23248

if you are only interested in this number you could translate the word into a number in base 26 and convert that using int:

alpha_to_digits = str.maketrans(
"abcdefghijklmnopqrstuvwxyz", "0123456789abcdefghijklmnop")

word = 'bike'

d = word.translate(alpha_to_digits)
print(d, int(d, base=26))
# 18a4 23248

which translates the word bike to its digit representation in base 26 (18a4) which can then be converted to an integer (23248).

packed into a function:

def number(word):
return int(word.translate(alpha_to_digits), base=26)

N nested for loops python

Generally, when you find yourself needing infinitely many nested loops, you should write a recursive function instead. Here's an implementation as a generator function:

def generate_strings(letters, transitions, k):
def helper(s):
if len(s) == k:
yield s
elif len(s) < k:
for letter in transitions[s[-1]]:
yield from helper(s + letter)
for letter in letters:
yield from helper(letter)

Example: note that you don't have to use a list of characters, since a string is also a sequence of characters.

>>> letters = 'abcd'
>>> transitions = {'a': 'bc', 'b': 'a', 'c': 'd', 'd': 'bcd'}
>>> for s in generate_strings(letters, transitions, 4):
... print(s)
...
abab
abac
acdb
acdc
acdd
baba
bacd
cdba
cdcd
cddb
cddc
cddd
dbab
dbac
dcdb
dcdc
dcdd
ddba
ddcd
dddb
dddc
dddd

How do I create nested for loops inside a function?

A possible (though maybe non-pythonic) solution is to use recursion:

def looper(loop_amount, loop_value):
if loop_value == 0:
# Code to be run in innermost loop
else:
for n in range(loop_amount):
looper(loop_value - 1)

This can be extended to access each loop's index, or have a return value in some fashion.



Related Topics



Leave a reply



Submit