Created
May 7, 2016 22:44
-
-
Save jaytaylor/12eb66c6016b64016d56615ec312b93d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
""" | |
5 philosophers at a round table w/ bowls of spaghetto | |
Forks are placed between each pair of philosophers (5 forks) | |
Must think and eat | |
Can only eat when he has both left and right forks | |
Each fork can only be held by 2 philosopher at a time | |
so they can only use it if not being used by another | |
After eating he must put down both forks and they become available to | |
others. | |
Ph can take one or the other, but cannot start eating until getting both | |
forks. | |
. o . o | |
o . | |
. o . o | |
""" | |
class Philosopher(object): | |
def __init__(self, name, **kw): | |
self.name = name | |
self.eating = False | |
self.num_times = 0 | |
for k, v in kw: | |
setattr(self, k, v) | |
def __repr__(self): | |
return 'Philosopher("%s", eating=%s, num_times=%s)' % (self.name, self.eating, self.num_times) | |
def step(self, left, right): | |
#print 'name=%s left(%s).eating=%s right(%s).eating=%s' % (self.name, left.name, left.eating, right.name, right.eating) | |
if self.eating: | |
self.eating = False | |
elif not left.eating and not right.eating: | |
self.eating = True | |
self.num_times += 1 | |
class System(object): | |
def __init__(self): | |
self.philosophers = [ | |
Philosopher('A'), | |
Philosopher('B'), | |
Philosopher('C'), | |
Philosopher('D'), | |
Philosopher('E'), | |
] | |
def __repr__(self): | |
out = '' | |
for i in range(0, len(self.philosophers)): | |
out += ' %s\n' % (self.philosophers[i],) | |
return out.rstrip() | |
def step(self): | |
for i in range(0, len(self.philosophers)): | |
right_index = i + 1 | |
if right_index >= len(self.philosophers): | |
right_index = 0 | |
#print 'i=%s rindex=-1 %s' % (i, self.philosophers[right_index].name) | |
self.philosophers[i].step(self.philosophers[i-1], self.philosophers[right_index]) | |
def main(): | |
system = System() | |
print 'Initial table configuration:\n%s' % (system,) | |
for i in range(1, 6): | |
system.step() | |
print 'i=%s Table configuration:\n%s' % (i, system,) | |
if __name__ == '__main__': | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment