Home > Enterprise >  Change amount of for loops (if only method) Required in function in Python
Change amount of for loops (if only method) Required in function in Python

Time:11-20

Here is my code:

import math
import random


def start_of_func():
    characters = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']
    total = ""
    look_for = input("search for a specific word: ")
    count = 0
    for x in characters:
        for y in characters:
            for z in characters:
                count  = 1
                print(f"{x}{y}{z}")
                total = total   f"{x}{y}{z}, "
                if look_for in total:
                    print(f"found it! This took {count} attempts.")
                    return
                else:
                    # coult not find it
                    pass
start_of_func()

Basically I want the user to be able to choose a word with a custom length, and then make the function go through it. The problem is though, that I only see one option which is to manually check the amount of words and then checking how many of the for loops are required. For example, this code only works on 3-letter words, as there are only 3 for loops. But what if I wanted to have a 4-letter word?

Help appreciated

CodePudding user response:

You can replace multiple loops with the only one using itertools.product:

from itertools import product
import string
    
def start_of_func():
    characters = string.ascii_lowercase
    total = ""
    look_for = input("search for a specific word: ")
    count = 0
    for seq in product(characters, repeat=len(look_for)):
        count  = 1
        print(''.join(seq))
        total = total   f"{''.join(seq)}, "
        if look_for in total:
            print(f"found it! This took {count} attempts.")
            return
        else:
            # coult not find it
            pass
start_of_func()

I've also added string.ascii_lowercase to make your alphabet easier.

CodePudding user response:

You can try:

from itertools import permutations as pm

def start_of_func():
    characters = [chr(i) for i in range(97, 97   26)]
    look_for = input('search for a specific word: ')
    count = 0
    for word in pm(characters, len(look_for)):
        count  = 1
        if look_for == ''.join(word):
            print(f'found it! This took {count} attempts. ')
            return
    
start_of_func()
  • Related