Python练习——约瑟夫环问题、用类方法描述一个数字时钟

一、约瑟夫环问题

有15个基督徒和15个非基督徒在海上遇险,为了能让一部分人活下来不得不将其中15个人扔到海里面去,有个人想了个办法就是大家围成一个圈,由某个人开始从1报数,报到9的人就扔到海里面,他后面的人接着从1开始报数,报到9的人继续扔到海里面,直到扔掉15个人。由于上帝的保佑,15个基督徒都幸免于难,问这些人最开始是怎么站的,哪些位置是基督徒哪些位置是非基督徒。
def main():
    persons=[True]*30   #创建一个列表,元素全部为True,即假定30个人全为基督徒
    count,i,number=0,0,0
    while count<15:     #记数,非基督徒有15人
        if persons[i]:
            number+=1   #遍历列表元素
            if number==9:   #第9个人
                persons[i]=False    #将该列表元素改为False,即非基督徒
                count+=1
                number=0
        i+=1    #从下一个人开始数
        i%=30
    for person in persons:
        print(''if person else '',end='')
main()

二、用类方法描述一个数字时钟

from time import sleep
import os
class Clock(object):
    def __init__(self,hour=0,minute=0,second=0):#初始化方法
        self.hour=hour
        self.minute=minute
        self.second=second
    def run(self):  #走字
        self.second+=1
        if self.second==60:
            self.second=0
            self.minute+=1
            if self.minute==60:
                self.minute=0
                self.hour+=1
                if self.hour==24:
                    self.hour=0
    def show(self): #显示
        print("{}时{}分{}秒".format(self.hour,self.minute,self.second))
def main():
    clock=Clock(12,23,56)
    while True:
        clock.show()
        sleep(1)
        clock.run()
        os.system("cls")    #清屏
main()

猜你喜欢

转载自www.cnblogs.com/hyz1900457346/p/11782225.html