Home > Mobile >  how to change slice to loop?
how to change slice to loop?

Time:10-14

how to change slicing to looping?

i will make connect the words game, i must take the connected character in first_word and second_world

in example: utara can connect by ut on institut

my lecture was prohibited the slicing and def function on my task (just looping)

first_length = 8
second_length = 5
first_word = 'institut'
second_word = 'utara'

result = []
if first_length <= second_length :
    for i in range(1,first_length   1):
        if first_word[-i:] == second_word[:i]:
            result = first_word[-i:]
else:
    for i in range(1,second_length   1):
        if first_word[-i:] == second_word[:i]:
            result = first_word[-i:]

print(result)

thank you a lot:))

CodePudding user response:

You can replace the slice assignments with the all() function and a generator loop.

        if first_word[-i:] == second_word[:i]:

can be rewritten as

if all(first_word[-i   x] == second_word[x] for x in range(i))

You can also use a for loop, but it gets more complicated.

for x in range(i):
    if first_word[-i   x] != second_word[x]:
        break
else:
    result = first_word[-i:]

The else: clause of a for or while loop is executed if the loop ends normally instead of due to a break statement.

CodePudding user response:

Not sure if this interpretation of the question is correct.

Looks like the challenge is to determine if a sequence of characters in second_word occurs in first_word. That sequence can be any length >= 2.

If that's correct then this seems to work. Of course it's not the right way to do it the question clearly states that slicing is not permitted.

first = 'institut'
second = 'utara'
minseq = 2
result = []

for k in range(len(second)):
    for i in range(k minseq, len(second) 1):
        if (w := ''.join(second[j] for j in range(k, i))) in first:
            result.append(w)

print(result)

Note:

This code looks for all possible patterns - i.e., doesn't stop if a single pattern is observed. That's easily changed if required.

Output:

['ut']
  • Related