Python 約瑟夫圈問題

來源:互聯網
上載者:User

標籤:false   列表   str   color   sdi   python   port   for   參數   

  • 需求:有n個人圍成一圈,順序排號, 從第1個人開始報數(從1到3),凡報到3的人退出圈子,問最後留下的是原來第幾號的那位
  • 代碼邏輯
    • n個人,通過輸入參數n,產生一個長度為n的列表
    • 通過報數邏輯函數,只要數到3的就把那個位置相對應的列表值設定為0,同時留下的人數也要減1,直到剩下的人數為1,才退出迴圈
    • 通過報數邏輯函數,最後得到新的列表(只有一個值是1,其餘都是0),進行迴圈即可
  • 代碼如下:
     1 #coding:utf-8 2 #__author__ = ‘Diva‘ 3 # 使用者輸入n,n代表人數,圍成一圈,順序排號 4 # 從第一個開始報數,1,2,3,數到3的人,退出圈子 5  6 # 報數邏輯,數到3的把對應的位置置為0,直到剩下最後一個人 7 def num_report(list_create): 8     n = 0 9     list_size = len(list_create)10     number_stay = list_size     # 剩下的人數(值為1的個數)11     while not number_stay == 1:12         for i in range(list_size):13             if list_create[i] == 1:14                 n = n + 115                 if n == 3:16                     list_create[i] = 017                     n = 018                     number_stay = number_stay - 119             if i == list_size:20                 i = 021 22 # 通過報數函數最後產生的新的列表,遍曆,找到唯一一個值不是0的人23 def remove_num_3(list_create):24     num_report(list_create)25     print(‘經過報數邏輯最後得到的列表是:‘ + str(list_create))26     i = 027     while i < len(list_create):28         if list_create[i] == 1:29             print(‘最後剩下的編號是:‘ + str(i + 1))30             return True31         i = i + 132 33 # 根據使用者輸入的人數n,產生列表,同時執行移除動作34 def list_create_rm(n):35     try:36         if not n.isdigit():37             return False38     except ValueError as e:39         pass40 41     nn = int(n)42     i = 043     list_create = []44     while i < nn:45         list_create.append(1)46         i = i + 147     print(‘產生的列表是:‘ + str(list_create))48     remove_num_3(list_create)49 50 if __name__ == ‘__main__‘:51     n = raw_input(‘請輸入人數:‘)52     list_create_rm(n)

     

  • 測試結果
  •  

Python 約瑟夫圈問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.