Trying to make a maze - python

Hi I am learning Python from the week, and I got the idea to make maze in python. After a long time trying to do this, I always came to this starting point:
I would like to get the effect of what is on the 2 selection
My code:
def make(x):
if x%2 !=0:
return False
else:
table = []
for i in range(0,x):
if i == 0:
table.append([0]*x)
elif i == x-1:
table.append([0]*x)
return table
else:
if i == 1:
table.append([0])
table[i].extend([1]*(x-2))
table[i].extend([0])
elif i==x-2:
table.append([0])
table[i].extend([1]*(x-2))
table[i].extend([0])
else:
table.append([0]*(x))
for j in make(20):
print j

Try this. It's generic enough for any value of x that satisfies x%2==0:
def make(x):
if x%2 != 0:
return False
else:
table = []
for i in range(0,x):
if i>=x/2:
fac, rem = divmod(x-i-1,2)
else:
fac, rem = divmod(i,2)
table.append([0,1]*(fac+rem))
table[i].extend([rem]*(x-4*(fac+rem)))
table[i].extend([1,0]*(fac+rem))
return table
Probably better form to raise an exception instead of returning false but I don't know the larger context of what this fits into so I'll just leave it as is.
Or using the same approach as above you can split the single loop into two loops with a separate function like this:
def makeRow(x,fac,rem):
row=[0,1]*(fac+rem)
row.extend([rem]*(x-4*(fac+rem)))
row.extend([1,0]*(fac+rem))
return row
def make2(x):
if x%2 != 0:
return False
else:
table = []
for i in range(0,int(x/2)):
table.append(makeRow(x,*divmod(i,2)))
for i in range(int(x/2),x):
table.append(makeRow(x,*divmod(x-i-1,2)))
return table
Or if you prefer to turn the above into something more pythonic:
def make3(x):
if x%2 != 0:
return False
else:
table=[makeRow(x,*divmod(i,2)) for i in range(0,int(x/2))]
table.extend([makeRow(x,*divmod(x-i-1,2)) for i in range(int(x/2),x)])
return table

Why point out the error "table [i + j]. extend ([int (j% 2)] * (x-(4 * s))) IndexError: list index out of range" and whether in general has the right to work
def fun(x):
table=[]
s=0
for i in range(0,int(x/2)):
if i ==0:
table.append([0]*x)
else:
if i==((x/2)-1):
table.append([0,1]*(x/4))
table[i].extend([1,0]*(x/4))
elif i==(x/2):
table.append([0,1]*(x/4))
table[i].extend([1,0]*(x/4))
elif i == (x/2-1):
table.append([0]*x)
return table
else:
if i<(((x/2)/2)-2):
s+=1
for j in range(0,2):
table.append([0,1]*s)
table[i+j].extend([int(j%2)]*(x-(4*s)))
table[i+j].extend([1,0]*s)
if i>((x/2)/2):
for j in range(0,2):
if len(table) == (x-2):
break
else:
table.append([0,1]*s)
table[i+j].extend([int(j%2)]*(x-(4*s)))
table[i+j].extend([1,0]*s)
s-=1
for j in fun(20):
print j

Related

Runtime error when submitting Kattis problem in python: I can guess the data structure

I'm trying for a while now to submit my solution to the following problem on Kattis: I can guess the data structure!. However, I keep getting a runtime error; I cannot think of anywhere it can go wrong since it works with all my input. Here is my solution:
import heapq, sys
def throwin(q,s,h,x, results):
if results[0]:
q.append(x)
if results[1]:
s.append(x)
if results[2]:
heapq.heappush(h, -x)
return (q,s ,h )
def printstructures(l):
for j in l:
if j[0] and j[1] or j[0] and j[2] or j[1] and j[2]:
print("not sure")
elif not j[0] and not j[1] and not j[2]:
print("impossible")
elif j[0]:
print("queue")
elif j[1]:
print("stack")
else:
print("priority queue")
def main():
results_global = []
stackops = []
current = []
while True:
try:
line = input()
if len(line) == 1:
if len(current) != 0:
stackops.append(current)
current = []
else:
current.append(tuple(map(int, line.split(" "))))
except EOFError:
break
stackops.append(current)
for op in stackops:
q,s,h = [],[],[]
heapq._heapify_max(h)
results = [True, True, True]
for i in range(len(op)):
o, x = op[i]
if o == 1:
q,s,h = throwin(q,s,h,x, results)
else:
if len(q) == 0 or q[0] != x:
results[0] = False
else:
q.pop(0)
if len(s) == 0 or s[-1] != x:
results[1] = False
else:
s.pop()
if len(h) == 0 or h[0] != -x :
results[2] = False
else:
heapq.heappop(h)
if i == len(op)-1:
results_global.append(results)
printstructures(results_global)
if __name__ == "__main__":
main()
I was wondering if anyone can give me a push in the right direction and point out where my thinking is wrong or if I made a mistake somewhere I overlooked.
I had the same runtime-error problem for this question, I think it has something to do with python input/output EOFError. I couldn't figure the specific error out but I just put a try/except pass over my entire program and kattis accepted the solution.
import sys
try:
def solve(n):
stack = []
queue = []
priority_queue = []
type_ds = [True, True, True]
for i in range(n):
command, element = map(int, input().split())
if command == 1:
if type_ds[0] != False:
stack.append(element)
if type_ds[1] != False:
queue.append(element)
if type_ds[2] != False:
priority_queue.append(element)
elif command == 2:
if type_ds[0] != False:
if len(stack) == 0:
return "impossible"
if element != stack.pop():
type_ds[0] = False
stack.clear()
if type_ds[1] != False:
if len(queue) == 0:
return "impossible"
if element != queue.pop(0):
type_ds[1] = False
queue.clear()
if type_ds[2] != False:
if len(priority_queue) == 0:
return "impossible"
priority_queue.sort(reverse=True)
if element != priority_queue.pop(0):
type_ds[2] = False
priority_queue.clear()
if type_ds.count(True) > 1:
return "not sure"
elif type_ds.count(True) == 0:
return "impossible"
else:
if type_ds[0] == True:
return "stack"
elif type_ds[1] == True:
return "queue"
else:
return "priority queue"
for line in sys.stdin:
if line.strip() == "":
break
n = int(line.strip())
print(solve(n))
except:
pass
Are you sure you're breaking out of the while loop? Is it running correctly on your computer? In competitive programming, with time limits, it's normally not a good idea to use try/except statements, it's slowing down the script by a lot.

My function is returning an empty list and I don't understand why?

I am writing a file overlap function that takes two arguments: longestFile and shorterFile. I want to see if two files have the same numbers and if they do, it will append that number to an empty list.
These are the two lists I am using for the program:
The first file that I am using to compare and The second file that I use
def longestFile(firstFile, secondFile):
if len(firstFile)>len(secondFile):
return firstFile
else:
return secondFile
def shortestFile(firstFile, secondFile):
if len (firstFile) < len(secondFile):
return firstFile
else:
return secondFile
def middleNumber(theLongestFile):
return theLongestFile[len(theLongestFile)//2]
def fileOverlap(lstFirstFile,lstSecondFile):
lstMatchingNums = []
lstLongerFile = longestFile(lstFirstFile,lstSecondFile)
lstShortestFile = shortestFile(lstFirstFile,lstSecondFile)
for eachLines in range(len(lstShortestFile)):
lstLongerFile = longestfile(lstFirstFile,lstSecondFile)
for eachLine in range(len(lstLongerFile)):
if lstShortestFile[eachLines] == middleNumber(lstLongerFile):
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif lstShortestFile[eachLines] < middleNumber(lstLongerFile):
lstLongerFile = lstLongerFile[0:len(lstLongerFile)//2+1]
if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <=2:
break
elif lstShortestFile[eachLines] > middleNumber(lstLongerFile):
lstLongerFile = lstLongerFile[len(lstLongerFile)//2:]
if len(lstLongerFile) <= 2 and lstLongerFile[0] == lstShortestFile[eachLines]:
lstMatchingNums.append(lstShortestFile[eachLines])
break
elif middleNumber(lstLongerFile) != lstShortestFile[eachLines] and len(lstLongerFile) <= 2:
break
return lstMatchingNums
lstHappyNums = open('happynumbs.txt','r')
lstReadingHappyLines = lstHappyNums.readlines()
lstHappyNums.close()
lstPrimeNumsFile = open('primenumbers.txt','r')
lstReadingPrimeLines = lstPrimeNumsFile.readlines()
lstPrimeNumsFile.close()
print(fileOverlap(lstReadingHappyLines,lstReadingPrimeLines))
If I was to run this program, it would give me an empty list and I am not sure why.

Keep getting type error with decorative function

I keep getting a type error for this. I am experimenting with decorative functions. Any help is appreciated
def primer(func):
def primes(n):
print (n)
return None
#primer
def find_prime(n):
while True:
count = 2
if (count == n):
z = ("PRIME")
return z
elif (n % count == 0):
z = n / count
return z
else:
count += 1
continue
prime = find_prime()
prime(10)
def primer(func):
def primes(n):
print(n)
#return None: dont know why this is here, you could do without it
return primes
#The nontype error is occuring because your code is returning none
#so to fix that all you have to do is return the inner function
#primer
def find_prime(n):
while True:
count = 2
if (count == n):
z = ("PRIME")
return z
elif (n % count == 0):
z = n / count
return z
else:
count += 1
continue
prime = find_prime
# if you want to turn a function into a variable you have to make sure it's
# callable, which means no parantheses around it
prime(15) # then you can call it

Why does my Python recursive function not break?

I have this code that should break once it fulfills a certain condition, ie when the isuniquestring(listofchar) function returns True, but sometimes it doesn't do that and it goes into an infinite loop. I tried printing the condition to check if there's something wrong with the condition, but even when the condition is printed true the function still continues running, I have no idea why.
one of the strings that throws up an infinite loop is 'thisisazoothisisapanda', so when I do getunrepeatedlist('thisisazoothisisapanda'), it goes into an infinite loop.
would be really grateful if someone could help
thanks!
Here's my code:
def getunrepeatedlist(listofchar):
for ch in listofchar:
if isrepeatedcharacter(ch,listofchar):
listofindex = checkrepeatedcharacters(ch,listofchar)
listofchar = stripclosertoends(listofindex,listofchar)
print (listofchar)
print (isuniquestring(listofchar))
if isuniquestring(listofchar):
return listofchar
#print (listofchar)
else:
getunrepeatedlist(listofchar)
return listofchar
just for reference, these are the functions I called
def isrepeatedcharacter(ch,list):
if list.count(ch) == 1 or list.count(ch) == 0:
return False
else:
return True
def checkrepeatedcharacters(ch,list):
listofindex=[]
for indexofchar in range(len(list)):
if list[indexofchar] == ch:
listofindex.append(indexofchar)
return listofindex
def stripclosertoends(listofindices,listofchar):
stringlength = len(listofchar)-1
if listofindices[0] > (stringlength-listofindices[-1]):
newstring = listofchar[:listofindices[-1]]
elif listofindices[0] < (stringlength-listofindices[-1]):
newstring = listofchar[listofindices[0]+1:]
elif listofindices[0] == (stringlength-listofindices[-1]):
beginningcount = 0
endcount = 0
for index in range(listofindices[0]):
if isrepeatedcharacter(listofchar[index],listofchar):
beginningcount += 1
for index in range(listofindices[-1]+1,len(listofchar)):
if isrepeatedcharacter(listofchar[index],listofchar):
endcount += 1
if beginningcount < endcount:
newstring = listofchar[:listofindices[-1]]
else:
#print (listofindices[0])
newstring = listofchar[listofindices[0]+1:]
#print (newstring)
return newstring
def isuniquestring(list):
if len(list) == len(set(list)):
return True
else:
return False
It may be due to the fact that you are changing listofchar in your for loop. Try cloning that variable to a new name and use that variable for manipulations and return the new variable.

Inteviewstreet Median in python. Fails on all but the first test case

So i wrote this code and it passes the first test case, and fails all the rest. However, I can't seem to find an input that breaks it. Maybe it's because I've been staring at the code too long, but i would appreciate any help.
The algorithm uses two priority queues for the smallest and largest halves of the current list. Here's the code:
#!/bin/python
import heapq
def fix(minset, maxset):
if len(maxset) > len(minset):
item = heapq.heappop(maxset)
heapq.heappush(minset, -item)
elif len(minset) > (len(maxset) + 1):
item = heapq.heappop(minset)
heapq.heappush(maxset, -item)
N = int(raw_input())
s = []
x = []
for i in range(0, N):
tmp = raw_input()
a, b = [xx for xx in tmp.split(' ')]
s.append(a)
x.append(int(b))
minset = []
maxset = []
for i in range(0, N):
wrong = False
if s[i] == "a":
if len(minset) == 0:
heapq.heappush(minset,-x[i])
else:
if x[i] > minset[0]:
heapq.heappush(maxset, x[i])
else:
heapq.heappush(minset, -x[i])
fix(minset, maxset)
elif s[i] == "r":
if -x[i] in minset:
minset.remove(-x[i])
heapq.heapify(minset)
elif x[i] in maxset:
maxset.remove(x[i])
heapq.heapify(maxset)
else:
wrong = True
fix(minset, maxset)
if len(minset) == 0 and len(maxset) == 0:
wrong = True
if wrong == False:
#Calculate median
if len(minset) > len(maxset):
item = - minset[0]
print int(item)
else:
item = ((-float(minset[0])) + float(maxset[0])) / 2
if item.is_integer():
print int(item)
continue
out = str(item)
out.rstrip('0')
print out
else:
print "Wrong!"
Your original was not so legible, so first I made it object-oriented:
MedianHeapq supports methods rebalance(), add(), remove(), size(), median(). We seriously want to hide the members minset,maxset from the client code, for all sorts of sensible reasons: prevent client from swapping them, modifying them etc. If client needs to see them you just write an accessor.
We also added a __str__() method which we will use to debug visually and make your life easier.
Also added legibility changes to avoid the indexing with [i] everywhere, rename s,x arrays to op,val, add prompts on the raw_input(), reject invalid ops at the input stage.
Your actual computation of the median confuses me (when do you want float and when integer? the rstrip('0') is a bit wack), so I rewrote it, change that if you want something else.
A discussion of the algorithm is here.
Now it is legible and self-contained. Also makes it testable.
You might be making sign errors in your code, I don't know, I'll look at that later.
Next we will want to automate it by writing some PyUnit testcases. doctest is also a possibility. TBC.
Ok I think I see a bug in the sloppiness about locating the median. Remember the minset and maxset can have a size mismatch of +/-1. So take more care about precisely where the median is located.
#!/bin/python
import heapq
class MedianHeapq(object):
def __init__(self):
self.minset = []
self.maxset = []
def rebalance(self):
size_imbalance = len(self.maxset) - len(self.minset)
if len(self.maxset) > len(self.minset):
#if size_imbalance > 0:
item = heapq.heappop(self.maxset)
heapq.heappush(self.minset, -item)
#elif size_imbalance < -1:
elif len(self.minset) > (len(self.maxset) + 1):
item = heapq.heappop(self.minset)
heapq.heappush(self.maxset, -item)
def add(self, value, verbose=False):
if len(self.minset) == 0:
heapq.heappush(self.minset,-value)
else:
if value > self.minset[0]:
heapq.heappush(self.maxset, value)
else:
heapq.heappush(self.minset, -value)
self.rebalance()
if verbose: print self.__str__()
return False
def remove(self,value,verbose=False):
wrong = False
if -value in self.minset:
minset.remove(-value)
heapq.heapify(self.minset)
elif value in maxset:
maxset.remove(value)
heapq.heapify(self.maxset)
else:
wrong = True
self.rebalance()
if verbose: print self.__str__()
return wrong
def size(self):
return len(self.minset)+len(self.maxset)
def median(self):
if len(self.minset) > len(self.maxset):
item = - self.minset[0]
return int(item)
else:
item = (-self.minset[0] + self.maxset[0]) / 2.0
# Can't understand the intent of your code here: int, string or float?
if item.is_integer():
return int(item)
# continue # intent???
else:
return item
# The intent of this vv seems to be round floats and return '%.1f' % item ??
#out = str(item)
#out.rstrip('0') # why can't you just int()? or // operator?
#return out
def __str__(self):
return 'Median: %s Minset:%s Maxset:%s' % (self.median(), self.minset,self.maxset)
# Read size and elements from stdin
N = int(raw_input('Size of heap? '))
op = []
val = []
while(len(val)<N):
tmp = raw_input('a/r value : ')
op_, val_ = tmp.split(' ')
if op_ not in ['a','r']: # reject invalid ops
print 'First argument (operation) must be a:Add or r:Remove! '
continue
op.append(op_)
val.append(int(val_))
mhq = MedianHeapq()
for op_,val_ in zip(op,val): # use zip to avoid indexing with [i] everywhere
wrong = False
if op_ == 'a':
wrong = mhq.add(val_)
elif op_ == 'r':
wrong = mhq.remove(val_)
assert (mhq.size()>0), 'Heap has zero size!'
assert (not wrong), 'Heap structure is wrong!'
if not wrong:
print mhq.__str__()

Categories