python 實踐題

 

 

約瑟環問題

"""
《幸運的基督徒》
有15個基督徒和15個非基督徒在海上遇險,爲了能讓一部分人活下來不得不將其中15個人扔到海里面去,有個人想了個辦法就是大家圍成一個圈,由某個人開始從1報數,報到9的人就扔到海里面,他後面的人接着從1開始報數,報到9的人繼續扔到海里面,直到扔掉15個人。由於上帝的保佑,15個基督徒都倖免於難,問這些人最開始是怎麼站的,哪些位置是基督徒哪些位置是非基督徒。
"""

##main()函數與jos()等價

#!/usr/bin/python

def main():
    persons = [True] * 30
    counter, index, number = 0, 0, 0
    while counter < 15:
        if persons[index]:
            number += 1
            if number == 9: 
                persons[index] = False
                counter += 1
                number = 0
        index += 1
        index %= 30
    for person in persons:
        print('基' if person else '非', end='')

def jos(num1,num2,num3):
    #num1個人,數到num2丟人,丟下num3個人
    person=[True]*num1
    index=0
    num=0
    count=0
    while count<num3:
        index %= num1;
   #     print(index)
        if person[index]:
            num+=1;
            if(num%num2) == 0:
                person[index]=False
                count+=1
            else:
                index+=1
        else:
            num+=0
            index+=1  
    for p in person:
        print('基' if p else '非', end='')
        
if __name__ == '__main__':
    main()
    print()
    jos(30,9,15)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章