駐站問題 Python 程式


在本文中,我們將瞭解對下列問題陳述的解決方案。

問題陳述− 給定兩個地點 A 和 B 之間有 13 箇中間站。我們需要找出列車在 2 箇中間站停靠的方式。且不停靠在相鄰的車站?

現在讓我們在下面的實現中觀察解決方案 −

示例

 線上演示

# stop station
def stopping_station( p, n):
   num = 1
   dem = 1
   s = p
   # selecting specified position
   while p != 1:
      dem *= p
      p-=1
   t = n - s + 1
   while t != (n-2 * s + 1):
      num *= t
      t-=1
   if (n - s + 1) >= s:
      return int(num/dem)
   else:
      # condition
      return -1
# main
num = stopping_station(2, 13)
if num != -1:
   print("No of stopping stations:",num)
else:
   print("I'm Possible")

輸出

No of stopping stations: 66

所有變數均在區域性作用域中宣告,其引用如上圖所示。

結論

在本文中,我們瞭解瞭如何編寫駐站問題 Python 程式。

更新於:20-12-2019

268 次瀏覽

開啟您的 職業生涯

完成課程獲得認證

開始
廣告
© . All rights reserved.