Good day. The task is to write a function that takes an input string with an integer. If the number is even, divide by 2. If odd, multiply by 3 and add 1. Do the same results, depending on the parity, of course. The output should be a string with a sequence of all result numbers separated by a space. The input number is> 0. The extreme number in the sequence is 1. This is what I got:

def col(n): sp = [n] if n < 1: return [] while n > 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 sp.append(n) for i in sp: print(i, end = ' ') 

The interpreter outputs everything correctly (for the number 17 for example):

 17 52 26 13 40 20 10 5 16 8 4 2 1 

But the problem book does not pass the test.

https://stepik.org/lesson/Collatz-conjecture-or-the-3n-+-1-problem-21305/step/1?adaptive=true&unit=5105 Link to the task. What have I done wrong? I guess the problem is with the output.

 return ' '.join(sp) 

I first did instead of prints, but in the list are numbers, not strings. Please advise.

  • No access to a problem book - Stanislav Grotto
  • Try logging in via VC, for example. Honestly, not the first time I encounter problems in their tests, but I don’t have to choose. - Emil Aliyev
  • You can use the generator instead of a list, for example - jfs
  • To my shame, I still do not know well. - Emil Aliyev

1 answer 1

Decision

 def col(n): sp = [n] if n < 1: return [] while n > 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 sp.append(n) for i in sp: print(i, end = ' ') col(int(input())) 

The test did not pass, because the input data was not read using input() and the col() function was not called

  • Thank you very much! Could you explain the last line? it's important for me to understand. - Emil Aliyev
  • @EmilAliyev input() gets the entered string (in this case it was the string "17", on the site "Sample Input 1"), int() converts it to an integer type. - Stanislav Grot
  • It's just that for the first time I see an object type change already outside the function. In the code, n behaved like an integer - the comparison was added to the list as a number (without quotes). I assumed that the snag was somewhere here, but I could not understand it. So, after the function is declared, instead of the argument, it is necessary to indicate that it has been transferred to another type. Thanks again. - Emil Aliyev
  • @EmilAliyev the matter was that the input data were not read and your function was not called - Stanislav Grot
  • that is, the test tried to give the function the string "17", and therefore it was not called? I gave the function the number 17 in IDLE, yes. And at the end you clearly indicated that the argument should be converted from a string to a number. Got it. - Emil Aliyev