Iteration using "while"

Asked

Viewed 122 times

2

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 has in each sequence. I cannot use for in that matter.

My code went 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 amount of gaps in the sequence.

Ex:

.f.f.f.f
faltas = 4

.f.f..
faltas = 4 (onde deveria imprimir 2)
  • Can you read the while ? syntax, make sure it helps you understand https://answall.com/questions/220915/help-loop-while-em-python

  • Did any of the answers solve your question? Do you think you can accept one of them? Check out the [tour] how to do this, if you haven’t already. You would help the community by identifying what was the best solution for you. You can accept only one of them. But you can vote on any question or answer you find useful on the entire site.

3 answers

2

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

There is a problem in checking output, you have to parse only the first character to know if it is a dash, and 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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks for the answers! It worked here. I’m still new to kkkk programming

1

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

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 on Repl.it

-1

TL;DR

Try it like 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))

Testing:

[aasfff
3
werf
1
asdfgffff
5

See working on repl it.

  • Interesting: the person give a downvote but do not explain the reason.

Browser other questions tagged

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