Iteration using "while"

3

I have a little trouble understanding while and I came across an exercise that asked me to do the following:

Read N sequences and find out how many 'f's' in each sequence. I can not use for on this issue.

My code looks like this:

i = 0
faltas = 0

while True:
    registros = raw_input()
    if registros == '-':
        break

    while i < len(registros):
        if registros[i] == 'f':
            faltas += 1

        i += 1


    print faltas

The problem is that if I type a sequence that has less' f's than the previous one it does not show the number of sequences missing.

Ex:

.f.f.f.f
faltas = 4

.f.f..
faltas = 4 (onde deveria imprimir 2)
    
asked by anonymous 10.12.2018 / 22:11

3 answers

2

The first problem is that it initializes the control and fault accumulator variables at the beginning of the algorithm, but when it finishes entering the first time they are not zeroed, so to do this, you need to put the initialization inside the main loop. p>

There is a problem in checking out, you have to analyze only the first character to see if it is a dash, not the whole text.

while True:
    registros = raw_input()
    if registros[0] == '-':
        break
    i = 0
    faltas = 0
    while i < len(registros):
        if registros[i] == 'f':
            faltas += 1
        i += 1
    print faltas

See running on ideone . And in Coding Ground . Also I put GitHub for future reference .

    
10.12.2018 / 22:36
0

You can use the str.count method to calculate the amount of f in its sequence:

while True:
    sequencia = raw_input('Digite uma sequência: ')
    if sequencia:
        print('Possui {} faltas na sequência'.format(sequencia.count('f')))
    else:
        break

See working at Repl.it

    
11.12.2018 / 12:59
-1

TL; DR

Try this:

def count_f(registros):
  faltas, i = 0, 0
  while i < len(registros):
    if registros[i] == 'f':
        faltas += 1

    i += 1
  return faltas

while True:
  registros = input()
  if registros == '-':
      break

  print(count_f(registros))

Test:

[aasfff
3
werf
1
asdfgffff
5

See working at repl.it

    
10.12.2018 / 22:38