Anonymous user
Talk:Abelian sandpile model: Difference between revisions
→A more readable Python solution.
Line 24:
This solution is more interactive, as it can also be used in imports on a Python console; plus, it is more readable.
<lang python>
from os import system, name
from time import sleep
if name == 'nt':
_ = system('cls')
else: _ = system('clear')
def exit():
import sys
clear()
sys.exit()
def make_area(x, y):
area = [[0]*x for _ in range(y)]
return area
def make_sandpile(area, loc, height):
loc=list(n-1 for n in loc)
x, y = loc
Line 37 ⟶ 48:
except IndexError: pass
def run(area, by_frame=False):
def run_frame():
while any([any([pile>=4 for pile in group]) for group in area]):▼
for y_index, group in enumerate(area):
y = y_index+1
Line 49 ⟶ 59:
else:
make_sandpile(area, (x
make_sandpile(area, (x
make_sandpile((x, y-1), 1)▼
make_sandpile((x, y+1), 1)▼
make_sandpile((x, y), -4)▼
if x_index-1 >= 0:
▲def show_area():
if y_index-1 >= 0:
display = [' '.join([str(item) for item in group]) for group in area]▼
▲ make_sandpile(area, (x, y-1), 1)
[print(i) for i in display]▼
▲ while any([any([pile>=4 for pile in group]) for group in area]):
if by_frame:
clear()
run_frame()
if by_frame:
show_area(area); sleep(.05)
def show_area(area):
for group in area]
▲ [print(i) for i in display]
clear()
if __name__ == '__main__':
area = make_area(10, 10)
print('\nBefore:')
show_area(area)
make_sandpile(area, (5, 5), 64); run(area)
print('\nAfter:')
show_area(area)
</lang>
|