Skip to content

Commit

Permalink
Min coins. Maze. Codejam prep
Browse files Browse the repository at this point in the history
  • Loading branch information
makhtardiouf committed Apr 15, 2016
1 parent e7c9d0d commit 16c8961
Show file tree
Hide file tree
Showing 22 changed files with 329 additions and 48 deletions.
Empty file added Codejam/A-test.in
Empty file.
Empty file added Codejam/B-test.in
Empty file.
Empty file added Codejam/C-test.in
Empty file.
1 change: 0 additions & 1 deletion Codejam/qualif/2016/a.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@
# Problem A: counting sheep

import sys
import math

target = set()
for i in range(10):
Expand Down
23 changes: 0 additions & 23 deletions Codejam/qualif/2016/template-readstrs.py

This file was deleted.

Empty file added Codejam/round1a/2016/A-test.in
Empty file.
Empty file added Codejam/round1a/2016/B-test.in
Empty file.
Empty file added Codejam/round1a/2016/C-test.in
Empty file.
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
#!/usr/bin/env python3
# Codejam 20160408
# $Id$
#

"""
Codejam 20160416 R1A
Makhtar Diouf
$Id$
"""
import sys
# import os
# import math
# import numpy as np
# from scipy.optimize import minimize

# If cols and rows size are the same, t[y][x] can check cols
def solve(t, n, m):
Expand All @@ -13,14 +18,13 @@ def solve(t, n, m):

#### main
try:
file = "a-test.in" #"A-small-practice.in"
file = "A-test.in" #"A-small-attempt0.in
inp = open(file)
outp = open(inp.name + ".out", mode='w')

nCases = int(inp.readline().strip())
print(nCases, " test cases")

for k in range(1, nCases + 1):
for c in range(1, nCases + 1):
n, m = [int(x) for x in inp.readline().split(sep=' ')]
print("n, m:", n, m)

Expand All @@ -30,7 +34,7 @@ def solve(t, n, m):
row = [int(x) for x in inp.readline().split(sep=' ')]
t.append(row)

line = "Case #{}{}{}\n".format(k, ': ', solve(t, n, m))
line = "Case #{}{}{}\n".format(c, ': ', solve(t, n, m))
sys.stdout.write(line)
outp.write(line)

Expand Down
42 changes: 42 additions & 0 deletions Codejam/template-readstrs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
#!/usr/bin/env python3
"""
Codejam 20160416 R1A
Makhtar Diouf
$Id$
"""
import sys
# import os
# import math
# import numpy as np
# from scipy.optimize import minimize

def solve():
pass



#### main
try:
file = "A-test.in" #"A-small-attempt0.in
inp = open(file)
outp = open(inp.name + ".out", mode='w')
nCases = int(inp.readline().strip())
print(nCases, " test cases")

for c in range(1, nCases+1):
board = []
for i in range(0,5):
board.append(inp.readline().strip())

line = "Case #{}{}{}\n".format(c, ': ', solve())
sys.stdout.write(line)
outp.write(line)

except Exception as ex:
print("Error: ", sys.exc_info()[0], ex)
raise

finally:
inp.close()
outp.close()

3 changes: 1 addition & 2 deletions asn1converter/asn1convert.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,10 @@
#!/usr/bin/env python3
"""
Parse a file containing ASN1 pseudo-code and prep it for C++ conversion.
Shares some similarities with asn1c, but this version focus on the latest 3GPP TS docs extraction.
Shares some similarities with asn1c, but this version focus on the latest 3GPP LTE specifications
Formats the output file with 'astyle'.
Ref: http://www.itu.int/en/ITU-T/asn1/Pages/introduction.aspx
Reviewed-by: Makhtar Diouf <[email protected]>
$Id: asn1convert.py, 9ddcffa7b4df makhtar $
"""
import sys
Expand Down
4 changes: 2 additions & 2 deletions asn1converter/asn1test.txt.h
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,8 @@
SLCommTxPoolToAddModListExtr13 poolToAddModListExtr13;
};
};
bool commTxAllowRelayDedicatedr13;
bool commTxAllowRelayDedicatedr13;
};
;
// -- ASN1STOP
11 changes: 7 additions & 4 deletions makhtar/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,13 @@ def typewrite(s, sleeptime=0.05):

def logit(msg):
logging.debug(msg)


def time_code(func, *args, **kwargs):
from timeit import timeit as tm
print(func, args)
s = [ str(_) for _ in args]
print(tm("stmt=" + func + "(" + ','.join(s) + ")", setup="from __main__ import "+func))

# Profiler
def do_cprofile(func):
"""Add @utils.do_cprofile just before the target function definition"""
Expand All @@ -41,6 +47,3 @@ def profiled_func(*args, **kwargs):
finally:
prof.print_stats()
return profiled_func

if __name__ == "__main__" :
typewrite("Loaded makhtar's module")
153 changes: 153 additions & 0 deletions maze.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
#!/usr/bin/env python3
"""
Maze, Labyrinth
Kill the beast and find the way to exit the maze
Makhtar Diouf
$Id$
Ref: http://interactivepython.org/runestone/static/pythonds/Recursion/ExploringaMaze.html
"""
import sys
import os
import turtle
from pathlib import Path

PART_OF_PATH = 'O'
TRIED = '.'
OBSTACLE = '+'
DEAD_END = '-'


class Maze:

def __init__(self, mazefile):
if not Path(mazefile).exists():
exit("The input file maze2.txt is missing")

mazeFile = open(mazefile, 'r')
self.mazelist = []

rowsInMaze = 0
columnsInMaze = 0

for line in mazeFile:
rowList = []
col = 0
for ch in line[:-1]:
rowList.append(ch)
if ch == 'S':
self.startRow = rowsInMaze
self.startCol = col
col = col + 1
rowsInMaze = rowsInMaze + 1
self.mazelist.append(rowList)
columnsInMaze = len(rowList)

self.rowsInMaze = rowsInMaze
self.columnsInMaze = columnsInMaze
self.xTranslate = -columnsInMaze / 2
self.yTranslate = rowsInMaze / 2
self.t = turtle.Turtle()
self.t.shape('turtle')
self.wn = turtle.Screen()
self.wn.setworldcoordinates(-(columnsInMaze - 1) / 2 - .5, -(
rowsInMaze - 1) / 2 - .5, (columnsInMaze - 1) / 2 + .5, (rowsInMaze - 1) / 2 + .5)

def drawMaze(self):
self.t.speed(10)
self.wn.tracer(0)
for y in range(self.rowsInMaze):
for x in range(self.columnsInMaze):
if self.mazelist[y][x] == OBSTACLE:
self.drawCenteredBox(
x + self.xTranslate, -y + self.yTranslate, 'orange')
self.t.color('black')
self.t.fillcolor('blue')
self.wn.update()
self.wn.tracer(1)

def drawCenteredBox(self, x, y, color):
self.t.up()
self.t.goto(x - .5, y - .5)
self.t.color(color)
self.t.fillcolor(color)
self.t.setheading(90)
self.t.down()
self.t.begin_fill()
for i in range(4):
self.t.forward(1)
self.t.right(90)
self.t.end_fill()

def moveTurtle(self, x, y):
self.t.up()
self.t.setheading(
self.t.towards(
x + self.xTranslate, -y + self.yTranslate))
self.t.goto(x + self.xTranslate, -y + self.yTranslate)

def dropBreadcrumb(self, color):
self.t.dot(10, color)

def updatePosition(self, row, col, val=None):
if val:
self.mazelist[row][col] = val
self.moveTurtle(col, row)

if val == PART_OF_PATH:
color = 'green'
elif val == OBSTACLE:
color = 'red'
elif val == TRIED:
color = 'black'
elif val == DEAD_END:
color = 'red'
else:
color = None

if color:
self.dropBreadcrumb(color)

def isExit(self, row, col):
return (row == 0 or
row == self.rowsInMaze - 1 or
col == 0 or
col == self.columnsInMaze - 1)

def __getitem__(self, idx):
return self.mazelist[idx]


def searchFrom(maze, startRow, startColumn):
# try each of four directions from this point until we find a way out.
# base Case return values:
# 1. We have run into an obstacle, return false
maze.updatePosition(startRow, startColumn)
if maze[startRow][startColumn] == OBSTACLE:
return False
# 2. We have found a square that has already been explored
if maze[startRow][startColumn] == TRIED or maze[
startRow][startColumn] == DEAD_END:
return False
# 3. We have found an outside edge not occupied by an obstacle
if maze.isExit(startRow, startColumn):
maze.updatePosition(startRow, startColumn, PART_OF_PATH)
return True
maze.updatePosition(startRow, startColumn, TRIED)
# Otherwise, use logical short circuiting to try each direction
# in turn (if needed)
found = searchFrom(maze, startRow - 1, startColumn) or \
searchFrom(maze, startRow + 1, startColumn) or \
searchFrom(maze, startRow, startColumn - 1) or \
searchFrom(maze, startRow, startColumn + 1)
if found:
maze.updatePosition(startRow, startColumn, PART_OF_PATH)
else:
maze.updatePosition(startRow, startColumn, DEAD_END)
return found


myMaze = Maze('maze2.txt')
myMaze.drawMaze()
myMaze.updatePosition(myMaze.startRow, myMaze.startCol)

searchFrom(myMaze, myMaze.startRow, myMaze.startCol)
12 changes: 12 additions & 0 deletions maze2.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
++++++++++++++++++++++
+ + ++ ++ +
+ ++++++++++
+ + ++ ++++ +++ ++
+ + + + ++ +++ +
+ ++ ++ + +
+++++ + + ++ + +
+++++ +++ + + ++ +
+ + + S+ + +
+++++ + + + + + +
++++++++++++++++++++++

46 changes: 46 additions & 0 deletions min_coins.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
#!/usr/bin/env python3
"""
Find a min number of coins to give back to a client as change
Uses caching/memoization and Dynamic Programming
Makhtar Diouf
$Id$
"""
from makhtar import utils

#@utils.do_cprofile
def probmin_coins(coinsList, change, known):
minCoins = change
if change in coinsList:
known[change] = 1
return 1

elif known[change] > 0:
return known[change]

else:
for i in [c for c in coinsList if c <= change]:
numCoins = 1 + probmin_coins(coinsList, change - i,
known)

if numCoins < minCoins:
minCoins = numCoins
known[change] = minCoins
return minCoins

# With Dynamic prog


def dp_min_coins(coinsList, change, minCoins=[0] * 64):
for cents in range(change + 1):
nCoins = cents
for j in [c for c in coinsList if c <= cents]:
if minCoins[cents - j] + 1 < nCoins:
nCoins = minCoins[cents - j] + 1
minCoins[cents] = nCoins
return minCoins[change]


coinsList = [1, 5, 10, 25]

print(probmin_coins(coinsList, 63, [0] * 64))
utils.time_code("dp_min_coins", coinsList, 63)
File renamed without changes.
8 changes: 5 additions & 3 deletions recurse.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
#
# Recursivity timing test
# $Id$
"""
Recursivity timing test
Makhtar Diouf
$Id$
"""
import random
from timeit import timeit as tm
#from makhtar import utils as ut
Expand Down
Loading

0 comments on commit 16c8961

Please sign in to comment.