Python and python

Source: Internet
Author: User

Python and python

Joseph's ring problem: n people (represented by numbers 1, 2, 3... n) are known to be sitting around a round table. The number of people numbered k starts to report, and the person whose number is k is killed; the person whose number is k starts to report data from 1, and the person whose number is k is killed again; repeat this rule until there is only one person around the Round Table.

The idea is: when k is 1, the last person is alive. When k> = 2, construct a circular linked list with n elements, and then kill the k users in turn, the last one left is a person who can survive. The Code is as follows:

class Node():def __init__(self,value,next=None):self.value=valueself.next=nextdef createLink(n):if n<=0:return Falseif n==1:return Node(1)else:root=Node(1)tmp=rootfor i in range(2,n+1):tmp.next=Node(i)tmp=tmp.nexttmp.next=rootreturn rootdef showLink(root):tmp=rootwhile True:print(tmp.value)tmp=tmp.nextif tmp==None or tmp==root:breakdef josephus(n,k):if k==1:print('survive:',n)returnroot=createLink(n)tmp=rootwhile True:for i in range(k-2):tmp=tmp.nextprint('kill:',tmp.next.value)tmp.next=tmp.next.nexttmp=tmp.nextif tmp.next==tmp:breakprint('survive:',tmp.value)if __name__=='__main__':josephus(10,4)print('-----------------')josephus(10,2)print('-----------------')josephus(10,1)print('-----------------')

The output result is as follows:



Reprinted Please note:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.