Python Program for Number of Stopping Station Problem (original) (raw)

Last Updated : 14 Nov, 2025

Given two places A and B with 12 intermediate stations, the task is to find the number of ways a train can stop at 4 of these stations such that no two stopping stations are consecutive. For example:

**Input: n = 12, s = 4
**Output: 126
**Explanation: There are 12 stations and we need to choose 4 such that no two are consecutive. The total possible ways to do this come out to be 126.

Let’s explore different methods to solve this problem in Python.

Using Combinatorial Formula

This is the most efficient way to solve the problem using combinatorics. If we have n stations and need to choose s such that no two are consecutive, the number of ways is given by the formula: C(n−s+1,s). This means we are choosing s positions from (n - s + 1) possible ones.

Python `

import math n, s = 12, 4 res = math.comb(n - s + 1, s) print(res)

`

**Explanation:

Using Dynamic Programming

This method builds a table to count the number of ways to choose stations without consecutive stops. It's useful when you need to calculate for multiple values of n and s.

Python `

n, s = 12, 4 dp = [[0] * (s + 1) for _ in range(n + 1)]

for i in range(n + 1): dp[i][0] = 1

for i in range(1, n + 1): for j in range(1, s + 1): if i < 2 * j - 1: dp[i][j] = 0 else: dp[i][j] = dp[i - 1][j] + dp[i - 2][j - 1]

print(dp[n][s])

`

**Explanation:

Using Recursion with Memoization

This approach recursively decides whether to include or skip a station, caching results for efficiency.

Python `

from functools import lru_cache

@lru_cache(None) def count_ways(n, s): if s == 0: return 1 if n < s or n <= 0: return 0 return count_ways(n - 1, s) + count_ways(n - 2, s - 1)

n, s = 12, 4 print(count_ways(n, s))

`

**Explanation:

Using Loops

This approach manually computes the combination value using simple multiplication and division helpful when avoiding built-in combinatorial functions.

Python `

n, s = 12, 4 num = 1 den = 1

numerator: (n - s + 1) * (n - s) * ... till (n - 2*s + 2)

for i in range(n - s + 1, n - 2 * s + 1, -1): num *= i

denominator: s!

for j in range(1, s + 1): den *= j

if (n - s + 1) >= s: print(int(num / den)) else: print("Not Possible")

`

**Explanation:

Please refer complete article on Number of stopping station problem for more details!