How to have two counters in the same loop?

Asked

Viewed 514 times

0

I have the following structure in my code:

for c in range(0, len(str(ListaTemp[4]))):
    for c2 in range(c+1, len(str(ListaTemp[4]))):
        if str(num)[c] == str(num)[c2]:
            valido = True

And so. My teacher is going to give a little extra notice to whoever makes the smallest code. I vaguely remember seeing something like:

for c, c2 in range(0, 10):

In this part of the code, I need to check that there are no repeated elements in a string. so I can’t just put the c+1, because an error occurs.

So I wonder if this is really possible.

  • 1

    Possible duplicate of two counters no for? Python

  • You can post the full code?

  • kkk it is complicated to post it all here... because some fellow can see and copy something. After delivering it to the teacher, there is no problem kkkk. But then. this part does not relate directly to the others (only at the end). there comes a variable of the whole type (so I convert to string there. to use the index). All I need is to check if there are identical digits in the string

2 answers

5


You need to use Slices to access parts of string together with the function zip:

texto = 'Stack Overflow em Português'

for a, b in zip(texto, texto[1:]):
    if a == b:
        print('Há caracteres iguais em sequência')
        break
else:
    print('Não há caracteres iguais em sequência')

See working on Repl.it | Ideone

Additional readings:

  • Thank you very much!!

2

In Python it is possible that a command for Sure go through multiple sequences at the same time.

But before I say I’d better clarify a few things: (1) the for in Python is not, in general, used for "counters". Since the for always going through a sequence, the natural is to run through each element of a sequence, not the element index (and then, given the index, extract the element from the sequence). In other languages this construction usually takes the name of "for each":

for letra in "palavra":
   print(letra)

instead of:

for i in range(len("palavra")):
   letra = "palavra"[i]
   print(letra)

E (2): being able to "see" at the same time a letter and the following letter will not help you with this particular issue problem - you will need two for one inside the same.

Then, in Python, the command for uses the element on which it will interact as an "iterator". That is, for item in minhalista: will call the equivalent of iter(minhalista), and on the object (let’s call ITER) returned so will do the equivalent of next(ITER). When the call to next fail (with an internal "Stopiteration" exception) for is terminated.

If the iterator used in for return a sequence, the values returned by the sequence are distributed to the variables of the for.

In the simplest case, if I have:

a = [[1,2], [3,4], [5,6]
for b, c in a:
   print(b, c)

The loop will repeat 3 times and each time one item of the internal sequence will be in b, and the other in c.

In the case of sequences, if you want to combine elements of them in the for, there is convenient call zip- which takes an element from each sequence and delivers so that it can be used in the:

a = range(10)
b = range(10, 20)

for c, d in zip(a, b):
   print(c,d)

In the case of a string, if you want to always take a letter and the next letter is possible to do:

a = "meu texto"
for letra1, letra2 in zip(a, a[1:]):
    print(letra1, letra2)

(a[1:] is simply string in a from the index letter "1" to the end, that is, if the string is "word", in the first interaction the letters "p" and "a")

And, explained how it works in Python - for your problem you will need to simply:

for letra1 in "palavra":
   for letra2 in "palavra":
      # coparações e atribuições necessárias para detectar repetição.

You may also need the enumerate, another built-in Python that in addition to each element of a sequence you get the index of it:

for i, letra1 in enumerate("palavra):
   for letra2 in "palavra"[i:]:
       # codigo
  • In the last example there will be the factor of considering the same letter on both loops, which can generate an unexpected result, not?

  • That’s her algorithm to take care of - but yes, it makes sense to use the enumerate to get the letter index as well.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.