0

I am a newbie here. If I do something wrongly, please show me tolerance.

I tried to solve this problem: Problem_Picture_1 Problem_Picture_2

My first solution didn't work:

# Uses python3
import sys

# Uses python3
def get_fibonacci_last_digit(n):
    fib = [0, 1]
    if n <= 1:
        return n

    for i in range(2, n):
        current = (fib[i-1] + fib[i-2]) % 10
        fib.append(current)
    return fib[-1]

n = int(input())

if __name__ == '__main__':
    input = sys.stdin.read()
    n = int(input)
    print(get_fibonacci_last_digit(n))

But my second solution worked:

# Uses python3
def calc_fib(n):
    fib = [0, 1]
    if n <= 1:
        return n

    for i in range(2, n+1):
        current = (fib[i-1] + fib[i-2]) % 10
        fib.append(current)
    return fib[-1]

n = int(input())
print(calc_fib(n))

What is the difference between these two approaches? Why didn't work my first solution? Please explain to me.

Edit: When I worked my first approach, It's still running. It couldn't return a number

When I worked my first approach, It could return a number

Brad Figueroa
  • 869
  • 6
  • 15

1 Answers1

0

The range(A, B) object iterates from A (inclusive) to B (exclusive). Eg.- range(2, 5) will return (2, 3, 4).

PS - Please use proper indentation while posting a question

lyadh_god
  • 11
  • 2
  • 3
  • Thanks for your answer. I changed this line "for i in range(2, n):" with "for i in range(2, n+1):" in my first solution but it still doesn't work. – Burak Aslantas Jul 09 '20 at 15:30
  • @BurakAslantas Elaborate a little more on what is it showing and what is the expected value? – lyadh_god Jul 09 '20 at 15:34
  • 1
    The reason why the first script is not running is that sys.std.read function needs the max no. of characters to read. If nothing specified then it reads until EOF. But, stdin reaches EOF only on termination of the terminal. Thus, the system is never stopping to check for any input. Thus, for such simple I/O operations, stick to input(). Hope this helps. – lyadh_god Jul 09 '20 at 16:26