What is the logic of python for i 'in'

Asked

Viewed 173 times

1

I’d like to know the logic of for i in vogais, as in the example.

Doubt, it carries the entire typed word in a list in memory and already sorts according to our classification,or it reads character by character?

For example, if you type: "alguma coisa aqui", using the debug Pycharm, he already knows the amount of letters a, for example.

def contaVogais(caracteres):
  caracteres = caracteres.upper()
  result = 0
  vogais = 'AEIOU'

  for i in vogais:
      result += caracteres.count(i)
  return result
  • The for Python performs a loop that other languages call foreach (for each). Given a sequence of elements, for each element within the sequence, make "codes".

2 answers

1


The for x in variavel is the same thing as foreach of other languages.

Doubt, it carries the entire typed word on a list in memory and already sorts according to our classification, or it reads character by character?

No, he doesn’t order the for, depends on the type of data, in your example you have a variable of type string, so when you use the syntax for i in vogais it’s just running a loop on each letter of the string.

For example, if you type "something here", using the pycharm debug, he already knows the amount of letters a, for example.

This is because you are using the method count inside the loop to count how many times a character appears in the string caracteres.count(i) where the irepresents the letter you want to know how often it occurs.

1

In this case there is no typing, but it can be elsewhere.

The for is an internally controlled loop, it knows where to start (0) and where to end (the size of the data collection).

One string Python is a collection of characters and before all of them has the amount of characters, so it’s easy for the loop to know when to stop. It’s a complete data structure. There’s no magic.

The count() is one of the ways to get the amount of characters, but then it has to sweep the whole string every time. This code is quadratic.

  • Count() is one of the ways to pick up this amount of characters. In this case it is running two loops (one of them is inside the upper()), and this is not efficient. In fact the whole code should not be like this. What would be the most efficient way, in my example?

  • @Elcypintoanjos I took this part because later I saw that there is a difference that makes necessary.

Browser other questions tagged

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