Eidam
Eidam

Reputation: 11

My code works but sometimes gets into an infinite loop

So i got an assignment from school that the code should pick a string, remove the first and the last index, then randomize the middle letters and give back the string with the first and the last index again attached. The word should be at least 4 characters long and schould not give back the original string. It is warking and all, but it after a few attempts at giving a 4 letter word gets into an infinite loop and I can't figure out why. It's a python code. Thank you for your help. Also some variables are in my laguage which shouldn't be a problem...just to clarify the weird variable names.

import random
n=0
while n<4:
    slovo=input('Zadajte vase slovo: ')
    n=len(slovo)

l=[]
def shufle(slovo,l):
    for i in range(len(slovo)):
        if i==0:
            continue
        if i==len(slovo)-1:
            continue
        else:
            l.append(slovo[i])
    random.shuffle(l)

while True:
    shufle(slovo,l)
    s=slovo[0]
    for i in l:
        s+=i
    s+=slovo[-1]
    if s==slovo:
        continue
    elif len(s)!=len(slovo):
        continue
    else:
        print(s)
        break

Upvotes: 0

Views: 76

Answers (1)

Erik McKelvey
Erik McKelvey

Reputation: 1627

Here's a tip: if your function is always expecting the same input for one of its parameters, than that parameter is probably not necessary. This is the case with passing empty lists or similar objects to functions. There was also a check if s and slovo are the same size which is not needed so I removed it. Try this:

import random
n=0
while n<4:
    slovo=input('Zadajte vase slovo: ')
    n=len(slovo)

def shufle(slovo):
    l = []
    for i in range(len(slovo)):
        if i == 0:
            continue
        if i == len(slovo)-1:
            continue
        else:
            l.append(slovo[i])
    random.shuffle(l)
    return l

while True:
    l = shufle(slovo)
    s = slovo[0]
    for i in l:
        s += i
    s += slovo[-1]
    if s == slovo:
        continue
    else:
        print(s)
        break

Upvotes: 1

Related Questions