Check if string is palindrome on the Python language
1 2 3 4 5 6 7 8 |
def ispalindrome(string): decide=1 i=0 while i<=int(len(string)/2) and decide==1: if string[i]!=string[-(i+1)]: decide=0 i+=1 return decide |
How to reverse string in Python 😃
1 2 3 4 |
def reverse(s, rs=''): for i in range(1, len(s)): rs = rs + s[len(s)-i] return rs+s[0] |
Nice code in Model of Django Python based framework
1 2 3 4 5 6 7 8 9 10 11 |
# In Django model def processed_description(self): text = self.description. \ replace('<table', '<div class="table">' '<div class="bgtop"></div>' '<div class="overflow"><table'). \ replace('</table>', '</table></div>' '<div class="bgbottom"></div>' '</div>'). \ replace('<th', '<th width="50%" align="left"') return text |
How you do not need programming in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
if cells[x-1,y-1] == 1: pos+=1 else: if cells[x-1,y-1] == -1: neg+=1 if cells[x-1,y] == 1: pos+=1 else: if cells[x-1,y] == -1: neg+=1 if cells[x-1,y+1] == 1: pos+=1 else: if cells[x-1,y+1] == -1: neg+=1 if cells[x,y-1] == 1: pos+=1 else: if cells[x,y-1] == -1: neg+=1 if cells[x,y] == 1: pos+=1 else: if cells[x,y] == -1: neg+=1 if cells[x,y+1] == 1: pos+=1 else: if cells[x,y+1] == -1: neg+=1 if cells[x+1,y-1] == 1: pos+=1 else: if cells[x+1,y-1] == -1: neg+=1 if cells[x+1,y] == 1: pos+=1 else: if cells[x+1,y] == -1: neg+=1 if cells[x+1,y+1] == 1: pos+=1 else: if cells[x+1,y+1] == -1: neg+=1 |
Summer intern Python code this summer 🤗
1 2 3 4 5 6 7 8 |
try: # do some stuff except: e0 = sys.exc_info()[0] e1 = sys.exc_info()[1] e2 = sys.exc_info()[2] print '*** failed due to: %s %s %s' % (e0, e1, e2) sys.exit(3) |
How to write detailed TODO comments in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
# TODO: fix this hell def pretty_print(w, p): w = truncate(w) p = truncate(p) my_matrix = zip(p, w) print "\n".join(["\t\t".join(["\t".join(map(str, r)) for r in t]) for t in my_matrix]) # TODO: and this def truncate(m): for i in range(len(m)): for j in range(len(m[0])): if(len(str(m[i][j])) > 5): m[i][j] = "%.3f" % m[i][j] return m |
Price Formatting in Python
1 2 3 4 5 6 7 |
def format_price price, delimeter = ' ' s, i = price.to_s.reverse, 0 Array.new(s.size) do |n| c = n.zero? ? '' : ((i += 1) % 3).zero? ? delimeter.to_s : '' c + s[n, 1] end.join.reverse end |
Remove duplicates function in Python
1 2 3 4 |
def remove_duplicates(seq): seen = set() seen_add = seen.add return [x for x in seq if x not in seen and not seen_add(x)] |
Calculate factorial in Python 🙃
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
def factorial(x): """ Work out x! (with a little help from the google calculator...) """ import re import urllib import time time.sleep(2) class AppURLopener(urllib.FancyURLopener): def __init__(self, *args): # *Cough* *Cough* self.version = 'Mozilla 1.3' urllib.FancyURLopener.__init__(self, *args) opener = AppURLopener() page = opener.open('http://www.google.com/search?q=%d!' % x).read() result = re.findall('<b>%d ! = (.*?)</b>' % x, page) if result: return int(result[0].replace('<font size=-2> </font>', '')) else: raise Exception, "Google not willing today!:\n\n %s" % page |
Validate Line function in Python 😁
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
def validate_line(line): if len(line) <= 2: return False if line[0] == '""': return False if line[0] == "''": return False if line[0] == '+!': return False if line[0] == '-?': return False if line[0] == '- (': return False if line[0] == '-(': return False if line[0] == '-)': return False if line[0] == '-6a': return False if line[0] == '-6a )': return False if line[0] == '-a': return False if line[0] == '-aa': return False if line[0] == '-:': return False if line[0] == ':': return False if line[0][0] == '#': return False if line[0][0] == "'": return False if line[0][0] == '&': return False if line[0][0] == '(': return False return True |
Nice way to generate SQL query in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 |
async def register_experiment(self, pool): async with pool.acquire() as conn: async with conn.cursor() as cur: sql = "INSERT INTO " + str(self.auxname) + "." + str(self.auxtable) sql += " VALUES(NULL, '" sql += str(self.dbname) sql += "', '" sql += str(self.encoder) sql += "', 0, '" #goodEncoder sql += str(self.lattices) sql += "', 0, '" #goodLattices sql += str(self.complex) sql += "', 0, '" #goodComplex sql += str(self.verges_total) sql += "', 0, " #goodVerges sql += str(self.verges_total) sql += ", '" sql += str(self.trains) sql += "', 0, '" #goodTrains sql += str(self.tests) sql += "', 0, '" #goodTests sql += str(self.hypotheses) sql += "', 0, '" #goodHypotheses sql += str(self.type) sql += "')" await cur.execute(sql) await conn.commit() |
Function to check zip file in Python
1 2 |
def IsZIPFile(filename): return filename.lower().endswith('.zip') |
Spent a lot of time to understand this logic in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
def karatsuba_multiplication(x : int, y : int) -> int: sx, sy = map(lambda x: '0' + str(x) if len(str(x)) % 2 != 0 else str(x), (x, y)) return _karatsuba_multiplication(sx, sy, max(len(sx), len(sy))) def _prepend_nils(string : str, amount_of_nils : int) -> str: return ('0' * amount_of_nils + string) def _karatsuba_multiplication(x : str, y : str, n : int) -> int: x, y = map(lambda x: _prepend_nils(x, (n - len(x))), (x, y)) if (n == 1): return (int(x) * int(y)) mid = n // 2 a, b = int(x[:mid]), int(x[mid:]) c, d = int(y[:mid]), int(y[mid:]) p = a + b q = c + d ac = _karatsuba_multiplication(str(a), str(c), max(len(str(a)), len(str(c)))) bd = _karatsuba_multiplication(str(b), str(d), max(len(str(b)), len(str(d)))) pq = _karatsuba_multiplication(str(p), str(q), max(len(str(p)), len(str(q)))) adbc = pq - ac - bd return 10**n * ac + 10**(mid + n % 2) * adbc + bd |
Garbage Command in Python 😀
1 2 3 4 5 6 7 |
#parameters bellow may be None #leftSquare - a list of left hand coordinates used to crop the image: [left,top,height,width] #leftSquare - a list of right hand coordinates used to crop the image: [left,top,height,width] #img - a loaded image def garbageCommand(img, leftSquare,rightSquare): global exitVar exitVar=True |
Kidding, it's Fibonacci in Python
1 2 3 4 5 6 7 8 9 10 11 12 13 |
print("Is this a fib?") discard = input("Decide \n") print("Kidding, it's Fibonacci.") intToFib = input("Enter an integer \n") try: newInt = int(intToFib) except ValueError: print("Not cool, it wasn't an integer. No Fibonacci for you") else: if (newInt < 1): print("Not cool, it wasn't a positive integer. No Fibonacci for you") else: print("The Fibonacci of ", newInt," is ", fibonacci(newInt)) |