blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
305475a350f769ad0ae3c2f7130afd77a9b600a9 | betty29/code-1 | /recipes/Python/577915_Future_decorator_pretty_pythonic/recipe-577915.py | 3,359 | 4.03125 | 4 | from threading import Thread, Event
class future:
"""
Without thinking in thread creation the idea is to call several times
a function assigning a thread for each call with related parameters
and returning the list of results in a pretty pythonic way.
For example, if we have already defined the function 'func':
res = func(par)
we want to call that several times and get the values in the future. So:
func(par1)
func(par2)
func(par3).get()
func(par4).get_all()
assigning a thread for each call. The 'get' method returns the first possible results,
and 'get_all' returns all the values in a list. The decorator works fine with kwargs too.
This recipe is based on:
http://code.activestate.com/recipes/355651-implementing-futures-with-decorators/
that use only one call for the function. The problem in that recipe is that each call blocks the execution.
"""
def __init__(self, f):
self.__f = f
self.__init_values__()
def __init_values__(self):
self.__thread = []
self.__vals = []
self.__exception = None
self.__curr_index = 0
self.__event = Event()
def __call__(self, *args, **kwargs):
t = Thread(target=self.runfunc, args=args, kwargs=kwargs)
t.start()
self.__thread.append(t)
return self
def runfunc(self, *args, **kw):
try:
self.__vals.append(self.__f(*args, **kw))
self.__event.set()
except Exception, e:
self.__exception = e
def get(self):
"""
Returns the first possible value without order of calling the function.
"""
if self.__curr_index == len(self.__thread):
raise IndexError('The element doesn\'t exists')
if not self.__event.is_set():
self.__event.wait()
self.__event.clear()
res = self.__vals[self.__curr_index]
self.__curr_index += 1
return res
def get_all(self):
"""
Returns all the possible values and initialize them.
"""
for t in self.__thread:
t.join()
if self.__exception is not None:
raise self.__exception
res = self.__vals
# Get rid of everything
self.__init_values__()
return res
if __name__ == '__main__':
import time
import unittest
@future
def sleeping(s, t):
time.sleep(s)
return 'slept for '+str(s) + ' sec dreaming: ' + str(t)
sleeping(2, t='world')
sleeping(5, 'sheeps')
sleeping(1, t='soccer')
print(sleeping(2, t='women').get())
print(sleeping(1, 'beach').get_all())
class FutureTestCase(unittest.TestCase):
def tearDown(self):
sleeping(0, '').get_all()
def test_positive(self):
sleeping(5, t='sheeps')
sleeping(1, 'beach')
o = sleeping(3, 'nothing')
res = o.get_all()
self.assertEqual(3, len(res))
def test_bad_index(self):
sleeping(5, t='sheeps')
o = sleeping(4, 'world')
o.get()
o.get()
self.assertRaises(IndexError, o.get)
unittest.main(verbosity=2)
|
d5f1ae7134c1d67aaa6dcf667009a390e6892b1f | betty29/code-1 | /recipes/Python/579098_pick_all_combinations_items/recipe-579098.py | 521 | 3.71875 | 4 | #!/usr/bin/env python3
def of_bucket(lst, depth=0) :
""" return all combinations of items in buckets """
#dbg print("of_bucket({0}, {1})".format(lst, depth))
for item in lst[0] :
if len(lst) > 1 :
for result in of_bucket(lst[1:], depth+1) :
yield [item,] + result
else :
yield [item,]
if __name__ == '__main__' :
bucket_lst = [["ba", "be", "bi"], ["ka", "ko", "ku", "ke"], ["to", "ty"]]
for n, combination in enumerate(of_bucket(bucket_lst)) :
print("{0:2d}. {1}".format(n, '-'.join(combination)))
|
659dad60592f12de327cfd6c2f4c0ac2f2493477 | betty29/code-1 | /recipes/Python/578052_Print_List_Places_ie/recipe-578052.py | 492 | 3.53125 | 4 | """Hopefully this function will save you the trip to oocalc/excel. Py3k code.
"""
def nth(n):
m = abs(n)
if m % 10 < 4 and m // 10 != 1:
return '{}{}'.format(n, ('th', 'st', 'nd', 'rd')[m % 10])
return '{}{}'.format(n, 'th')
def rangeth(*args):
"""rangeth([start,] stop[, skip]) -> list of places (rankings)
returns a list of strings as places in a list (1st, 2nd, etc)
>>> rangeth(4)
['0th', '1st', '2nd', '3rd']
"""
return list(map(nth, range(*args)))
|
b9cbe4e6b43c1b14e887c7e2f37ec99b5bce4015 | betty29/code-1 | /recipes/Python/305321_SQLlike_ORDER/recipe-305321.py | 379 | 3.78125 | 4 | def orderBy(sortlist, orderby=[], desc=[]):
'''orderBy(sortlist, orderby, desc) >> List
sortlist: list to be sorted
orderby: list of field indexes
desc: list of field indexes that are to be sorted descending'''
orderby.reverse()
for i in orderby:
sortlist.sort(lambda x, y: cmp(*[(x[i], y[i]), (y[i], x[i])][i in desc]))
return sortlist
|
55fd25461b26b5b743f62c1329da43bad5015cb1 | betty29/code-1 | /recipes/Python/576785_Partitiiterable_inn/recipe-576785.py | 330 | 3.8125 | 4 | def divide(iterable, parts):
''' Partitions an iterable into parts number of lists. '''
items = list(iterable)
seqs = [[] for _ in xrange(parts)]
while items:
for i in xrange(parts):
if not items:
break
seqs[i].append(items.pop())
return seqs
|
0eef4eff2884f8831fa25cfba67742c7b67076e3 | betty29/code-1 | /recipes/Python/440526_Misspell_words_avoid/recipe-440526.py | 2,726 | 3.78125 | 4 | import random
import re
import StringIO
class misspell(object):
def __init__(self):
# create a regex to match a word with ending punctucation
self.punctuation = re.compile('\S+[' + re.escape(",'.:;!?") + ']$')
def misspell(self, text):
self.text = StringIO.StringIO(text).readlines()
misspelled = []
for line in self.text:
# split hyphenated words into independent words
line = re.sub(r'(\S+)\-(\S+)', r'\1 \2', line)
# split each line in a list of words
tokens = line.split()
for token in tokens:
# don't misspell a number
if token.isdigit():
misspelled.append(token + ' ')
continue
# don't misspell an email address or URL
if '@' in token or '://' in token:
misspelled.append(token + ' ')
continue
# does the word end with puncuation?
has_punc = re.match(self.punctuation, token)
# explode the word to a list
token = list(token)
# word doesn't end in puctuation and is longer than 4 chars
if not has_punc and len(token) >= 4:
start = random.randint(1,len(token) - 3)
stop = start + 2
f,s = token[start:stop]
token[start:stop] = s,f
# word does end in puctuation and is longer that 5 chars
elif has_punc and len(token) >=5:
start = random.randint(1,len(token) - 4)
stop = start + 2
f,s = token[start:stop]
token[start:stop] = s,f
# add the word to the line
misspelled.append((''.join(token) + ' '))
# end the line
misspelled.append('\n')
return ''.join(misspelled)
if __name__ == '__main__':
# example usage of the misspell class
message = """
According to research at an English University, it doesn't matter
in what order the letters in a word are, the only important thing is
that the first and last letters be in the right places. The rest can
be a total mess and you can still read it without problem. This is
because the human mind does not read every letter by itself, but
the word as a whole."""
msg = misspell()
print msg.misspell(message)
|
b4486555146d2d4321ab41a10073d06f20519129 | betty29/code-1 | /recipes/Python/442447_Generator_expressions_database/recipe-442447.py | 11,312 | 3.640625 | 4 | """A wrapper around DBAPI-compliant databases to support iteration
and generator expression syntax for requests, instead of SQL
To get an iterator, initialize a connection to the database, then
set the cursor attribute of the query class to its cursor
Create an instance of Table for the tables you want to use
Then you can use the class query. You create an instance by passing
a generator expression as parameter. This instance translates the
generator expression in an SQL statement ; then you can iterate
on it to get the selected items as objects, dictionaries or lists
Supposing you call this module db_iterator.py, here is an example
of use with sqlite :
from pysqlite2 import dbapi2 as sqlite
from db_iterator import query, Table
conn = sqlite.connect('planes')
query.cursor = conn.cursor()
plane = Table()
countries = Table()
# all the items produced by iteration on query() are instances
# of the Record class
# simple requests
# since no attribute of r is specified in the query, returns a list
# of instances of Record with attributes matching all the field names
print [ r.name for r in query(r for r in plane if r.country == 'France') ]
# this request returns a list instances of Record with the attribute
# c_country (c.country with the . replaced by _)
print [ country for country in query(c.country for c in countries
if c.continent == 'Europe') ]
# request on two tables
print [r.name for r in query (r for r in plane for c in countries
if r.country == c.country and c.continent == 'Europe')]
"""
import tokenize
import token
import compiler
import types
class ge_visitor:
"""Instances of ge_visitor are used as the visitor argument to
compiler.walk(tree,visitor) where tree is an AST tree built by
compiler.parse
The instance has a src attribute which looks like the source
code from which the tree was built
Only a few of the visitNodeType are implemented, those likely to appear
in a database query. Can be easily extended
"""
def __init__(self):
self.src = ''
def visitTuple(self,t):
self.src += ','.join ( [ get_source(n) for n in t.nodes ])
def visitList(self,t):
self.src += ','.join ( [ get_source(n) for n in t.nodes ])
def visitMul(self,t):
self.src += '(%s)' %('*'.join([ get_source(n) for n in t]))
def visitName(self,t):
self.src += t.name
def visitConst(self,t):
if type(t.value) is str:
# convert single quotes, SQL-style
self.src += "'%s'" %t.value.replace("'","''")
else:
self.src += str(t.value)
def visitAssName(self,t):
self.src += t.name
def visitGetattr(self,t):
self.src += '%s.%s' %(get_source(t.expr),str(t.attrname))
def visitGenExprFor(self,t):
self.src += 'for %s in %s ' %(get_source(t.assign),
get_source(t.iter))
if t.ifs:
self.src += ' if ' +''.join([ get_source(i) for i in t.ifs ])
def visitGenExprIf(self,t):
self.src += get_source(t.test)
def visitCompare(self,t):
compiler.walk(t.expr,self)
self.src += ' '
for o in t.ops:
oper = o[0]
if oper == '==':
oper = '='
self.src += oper + ' '
compiler.walk(o[1],self)
def visitAnd(self,t):
self.src += '('
self.src += ' AND '.join([ get_source(n) for n in t.nodes ])
self.src+= ')'
def visitOr(self,t):
self.src += '('
self.src += ' OR '.join([ get_source(n) for n in t.nodes ])
self.src+= ')'
def visitNot(self,t):
self.src += '(NOT ' + get_source(t.expr) + ')'
def get_source(node):
"""Return the source code of the node, built by an instance of
ge_visitor"""
return compiler.walk(node,ge_visitor()).src
class genExprVisitor:
"""Visitor used to initialize GeneratorExpression objects
Uses the visitor pattern. See the compiler.visitor module"""
def __init__(self):
self.GenExprs = []
def visitGenExprInner(self,node):
ge = GeneratorExpression()
self.GenExprs.append(ge)
for y in node.getChildren():
if y.__class__ is compiler.ast.GenExprFor:
ge.exprfor.append(y)
else:
ge.result = y
class GeneratorExpression:
"""A class for a Generator Expression"""
def __init__(self):
self.result = None
self.exprfor = []
class Record(object):
"""A generic class for database records"""
pass
class Table:
"""A basic iterable class to avoid syntax errors"""
def __iter__(self):
return self
class query:
"""Class used for database queries
Instance is created with query(ge) where ge is a generator
expression
The __init__ method builds the SQL select expression matching the
generator expression
Iteration on the instance of query yields the items found by
the SQL select, under the form specified by return_type : an object,
a dictionary or a list"""
cursor = None # to be set to the cursor of the connection
return_type = object # can be set to dict or list
def __init__(self,s):
self._iterating = False # used in next()
# First we must get the source code of the generator expression
# I use an ugly hack with stack frame attributes and tokenize
# If there's a cleaner and safer way, please tell me !
readline = open(s.gi_frame.f_code.co_filename).readline
first_line = s.gi_frame.f_code.co_firstlineno
flag = False
self.source = '' # the source code
for t in tokenize.generate_tokens(open(s.gi_frame.f_code.co_filename).readline):
# check all tokens until the last parenthesis is closed
t_type,t_string,(r_start,c_start),(r_end,c_end),line = t
t_name = token.tok_name[t_type]
if r_start == first_line:
if t_name == 'NAME' and t_string=="query":
flag = True
res = t_string
start = 0 # number of parenthesis
continue
if flag:
self.source += ' '+t_string
if t_name == 'OP':
if t_string=='(':
start += 1
elif t_string == ')':
start -= 1
if start == 0:
break
# when the source has been found, build an AST tree from it
ast = compiler.parse(self.source.strip())
# use a visitor to find the generator expression(s) in the source
visitor = genExprVisitor()
compiler.walk(ast,visitor)
# if there are nested generator expressions, it's too difficult
# to handle : raise an exception
if len(visitor.GenExprs)>1:
raise Exception,'Invalid expression, found more ' \
'than 1 generator expression'
ge = visitor.GenExprs[0]
self.sql = self.build_sql(ge)
def build_sql(self,ge):
""" Build the SQL select for the generator expression
ge is an instance of GeneratorExpression
The generator expression looks like
(result) for x1 in table1 [ for x2 in table2] [ if condition ]
It has 2 attributes :
- result : an AST tree with the "result" part
- exprfor : a list of AST trees, one for each "for ... in ..."
"""
self.res = []
if ge.result.__class__ is compiler.ast.Tuple:
# more than one item in result
self.res = ge.result.getChildren()
else:
self.res = [ge.result]
results = [] # a list of strings = result part of the SQL expression
for res in self.res:
# a result can be a stand-alone name, or a "qualified" name,
# with the table name first (table.field)
if res.__class__ is compiler.ast.Name:
results.append((res.name,None))
elif res.__class__ is compiler.ast.Getattr:
results.append((get_source(res.expr),res.attrname))
self.results = results
# "for x in y" produces an item in the dictionary recdefs :
# recdef[x] = y
recdefs = {}
conditions = []
for exprfor in ge.exprfor:
recdefs[get_source(exprfor.assign)] = \
get_source(exprfor.iter)
if exprfor.ifs:
# an AST tree for the condition
conditions = exprfor.ifs
# To build objects or dictionaries in the result set, we must
# know the name of the fields in all the tables used in the
# query. For this, make a simple select in each table and read
# the information in cursor.description
self.names={}
for rec,table in recdefs.iteritems():
self.cursor.execute('SELECT * FROM %s' %table)
self.names[rec] = [ d[0] for d in self.cursor.description ]
sql_res = [] # the way the field will appear in the SQL string
rec_fields = [] # the name of the fields in the object or dictionary
for (n1,n2) in results:
if n2 is None:
# "stand-alone" name
if n1 in recdefs.keys():
sql_res += [ '%s.%s' %(n1,v) for v in self.names[n1] ]
rec_fields+=[ v for v in self.names[n1] ]
else:
sql_res.append(n1)
rec_fields.append(n1)
else:
# "qualified" name, with the table name first
sql_res.append('%s.%s' %(n1,n2))
# in the result set, the object will have the attribute
# table_name (we can't set an attribute table.name, and
# name alone could be ambiguous
rec_fields.append('%s_%s' %(n1,n2))
self.rec_fields = rec_fields
# now we can build the actual SQL string
sql = 'SELECT '+ ','.join(sql_res)
sql += ' FROM '
froms = []
for (k,v) in recdefs.iteritems():
froms.append('%s AS %s ' %(v,k))
sql += ','.join(froms)
if conditions:
sql += 'WHERE '
for c in conditions:
sql += get_source(c)
return sql
def __iter__(self):
return self
def next(self):
if not self._iterating:
# begin iteration
self.cursor.execute(self.sql)
self._iterating = True
row = self.cursor.fetchone()
if row is not None:
if self.return_type == object:
# transform list into instance of Record
# uses the rec_fields computed in build_sql()
rec = Record()
rec.__dict__ = dict(zip(self.rec_fields,row))
return rec
elif self.return_type == dict:
return dict(zip(self.rec_fields,row))
elif self.return_type == list:
return row
self._iterating = False
raise StopIteration
|
6684db5f1934a4236e182f5c605f77e14796013d | betty29/code-1 | /recipes/Python/577930_Lefthanded_password_generator/recipe-577930.py | 1,161 | 3.796875 | 4 | #!/usr/bin/python
import argparse
import random
parser = argparse.ArgumentParser(description='Generate a left-handed random password.')
parser.add_argument('-n', action='store', dest='passNum', default=8, type=int, help='Number of passwords to generate.')
parser.add_argument('-l', action='store', dest='passLen', default=8, type=int, help='Length of password')
parser.add_argument('-s', action='store', dest='passStrength', default=4, type=int, help='Strength of password (1-4)')
lowerChars = "qwertasdfgzxcvb"
upperChars = "QWERTASDFGZXCVB"
lowerNum = "123456"*3 # repeated digits for 'weight'
upperNum = '!"$%^'*3
results=parser.parse_args()
#Generate character to select from according to passStrength (-s)
if results.passStrength == 1:
leftHand = lowerChars
elif results.passStrength == 2:
leftHand = lowerChars+upperChars
elif results.passStrength == 3:
leftHand = lowerChars+upperChars+lowerNum
elif results.passStrength == 4:
leftHand = lowerChars+upperChars+lowerNum+upperNum
for i in range(results.passNum):
leftPass = ''
for j in range(results.passLen):
leftPass = leftPass + leftHand[random.randint(0,len(leftHand)-1)]
print leftPass
|
7376d7576c0cac9375514d5914d63ae7426fd287 | betty29/code-1 | /recipes/Python/393265_Substitute_Decimals_floats/recipe-393265.py | 520 | 3.90625 | 4 | import re
number_pattern = re.compile(r"((\A|(?<=\W))(\d+(\.\d*)?|\.\d+)([eE][+-]?\d+)?)")
def deciexpr(expr):
"""Substitute Decimals for floats in an expression string.
>>> from decimal import Decimal
>>> s = '+21.3e-5*85-.1234/81.6'
>>> deciexpr(s)
"+Decimal('21.3e-5')*Decimal('85')-Decimal('.1234')/Decimal('81.6')"
>>> eval(s)
0.016592745098039215
>>> eval(deciexpr(s))
Decimal("0.01659274509803921568627450980")
"""
return number_pattern.sub(r"Decimal('\1')", expr)
|
8f1cb251047bc0f41c858c9af34575fb5203e192 | betty29/code-1 | /recipes/Python/578015_Simple_enum_mechanism/recipe-578015.py | 4,168 | 3.96875 | 4 | """
@author Thomas Lehmann
@file enum.py
@note The singleton example is taken from:
http://www.python.org/dev/peps/pep-0318/#examples
@note I don't use TAB's and indentation is 4.
@note epydoc wrongly interprets the class as a function.
Probably because of the decorator (without it works).
"""
__docformat__ = "javadoc en"
import inspect
import unittest
def singleton(theClass):
""" decorator for a class to make a singleton out of it """
classInstances = {}
def getInstance():
""" creating or just return the one and only class instance """
if theClass not in classInstances:
classInstances[theClass] = theClass()
return classInstances[theClass]
return getInstance
@singleton
class Enum(object):
""" class for providing enum functionality. An enum in C++ usually looks
like this: enum { A, B, C }; and the results are 0, 1 and 2 for A, B and C.
We provide similar functionality means auto incrementing of values for constants
added to an enum...
>>> TOP = enum("direction") # or enum(Direction) when Direction is a class
>>> LEFT = enum("direction") # or enum(Direction) when Direction is a class
>>> RIGHT = enum("direction") # or enum(Direction) when Direction is a class
>>> BOTTOM = enum("direction") # or enum(Direction) when Direction is a class
>>> assert TOP < LEFT < RIGHT < BOTTOM
<ul>
<li>You still can assign an individual value.
<li>You can place constants inside the class (if you like) -> Direction.TOP
<li>Same to C++: you have to pay attention where new constants are added. When
you insert it inbetween then you will 'move' the other values.
</ul>
"""
def __init__(self):
""" registered enums """
self.contexts = {}
def getNextId(self, context):
""" providing next id >= 0 on each call per context
@param context is a string
@return is an integer value being unique for given context
"""
if not context in self.contexts:
self.contexts[context] = -1
self.contexts[context] += 1
return self.contexts[context]
def enum(context):
""" wrapper for calling the singleton. Documentation is placed
at the class Enum.
@param context can be a string or a class
@return is an integer value being unique for given context
"""
if inspect.isclass(context):
return Enum().getNextId(context.__name__)
return Enum().getNextId(context)
class EnumTestCase(unittest.TestCase):
""" testing of class Enum """
def testSingleton(self):
""" testing the singleton mechanism """
instanceA = Enum()
instanceB = Enum()
self.assertEqual(instanceA, instanceB)
def testGetNextId(self):
""" example of creating two constants """
instance = Enum()
HORIZONTAL = instance.getNextId("orientation")
VERTICAL = instance.getNextId("orientation")
self.assertTrue(HORIZONTAL < VERTICAL)
def testEnumFunctionWithStringContext(self):
""" example of creating four constants with string as context """
class Direction:
TOP = enum("direction")
LEFT = enum("direction")
RIGHT = enum("direction")
BOTTOM = enum("direction")
self.assertTrue(Direction.TOP < Direction.LEFT < Direction.RIGHT < Direction.BOTTOM)
def testEnumFunctionWithClassContext(self):
""" example of creating four constants with a class as context
@note I have tried to move the enum code to the class but this
seems not to work """
class Vector:
def __init__(self):
self.vector = [0, 0]
X = enum(Vector)
Y = enum(Vector)
self.assertTrue(X < Y)
self.assertEqual(X, 0)
self.assertEqual(Y, 1)
if __name__ == "__main__":
suite = unittest.TestLoader().loadTestsFromTestCase(EnumTestCase)
unittest.TextTestRunner(verbosity=3).run(suite)
|
4a64299ccf02e40881c2ffc38b603becaf2cb17a | betty29/code-1 | /recipes/Python/576490_Using_pythimaging_library_generate_degraded/recipe-576490.py | 1,895 | 3.859375 | 4 | """This contains routines to generate degraded letter stimuli"""
import Image #The PIL
import ImageDraw
import ImageFont
import numpy
def generate_letter(contrast_energy = .01, #michelson contrast energy
noise = 30.,
bg_luminance = 128.,
letter = "a",
letter_size = 400):
N = 300 #size of image in pixels
#first figure out what is the ink-area of the letter
font = ImageFont.truetype("Data/arial.ttf", letter_size)
#we copy the .ttf file to the local directory to avoid problems
im_temp = Image.new("1", (1,1), 0)
draw = ImageDraw.Draw(im_temp)
#now we can draw on this
sz = draw.textsize(letter, font=font)
#this tells us the size of the letter
im_temp = Image.new("1", sz, 0)
#this is a temporary binary image created solely for the purpose of computing
#the ink-area of the letter
draw = ImageDraw.Draw(im_temp)
#now we can draw on this
draw.text((0,0), letter, font=font, fill=1)
pix = im_temp.load()
#pix is now an addressable array of pixel values
area_in_pixels = 0.
for row in xrange(sz[0]):
for col in xrange(sz[1]):
area_in_pixels += pix[row,col]
#since contrast_energy = contrast^2 * pixel_area
contrast = (contrast_energy/area_in_pixels)**0.5
fg_luminance = bg_luminance*(1+contrast)/(1-contrast)
print area_in_pixels
print contrast
print fg_luminance
im = Image.new("L", (N,N), bg_luminance)
#im is now a NxN luminance image with luminance set to bg_luminance
draw = ImageDraw.Draw(im)
#now we can draw on this
draw.text(((N-sz[0])/2, (N-sz[1])/2), letter, font=font, fill=fg_luminance)
#this centers the letter
if noise > 0:
pix = im.load()
#pix is now an addressable array of pixel values
rd = numpy.random.normal(scale=noise, size=(N,N))
for row in xrange(N):
for col in xrange(N):
pix[row,col] += rd[row,col]
im.show()
|
a752a877f7aa023a64622cb406d86f9655133808 | betty29/code-1 | /recipes/Python/577345_Maclaurinsseriescos_x/recipe-577345.py | 1,429 | 4.21875 | 4 | #On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 03/08/10
#version :2.6
"""
maclaurin_cos_pow2 is a function to compute cos(x) using maclaurin series
and the interval of convergence is -inf < x < +inf
cos²(x) = 1- x^2 + 2^3*x^4/4! - 2^5*x^6/6! ...........
"""
from math import *
def maclaurin_cos_pow2(value,k):
"""
Compute maclaurin's series approximation for cos^2(x).
"""
global first_value
first_value = 0.0
#attempt to Approximate cos^2(x) for a given value
try:
for item in xrange(4,k,4):
next_value = (2**(item-1))*(value*pi/180)**item/factorial(item)
first_value += next_value
for item in xrange(2,k,4):
next_value = -1*(2**(item-1))*((value*pi/180)**item/factorial(item))
first_value += next_value
return first_value +1
#Raise TypeError if input is not a number
except TypeError:
print 'Please enter an integer or a float value'
if __name__ == "__main__":
maclaurin_cos1 = maclaurin_cos_pow2(135,100)
print maclaurin_cos1
maclaurin_cos2 = maclaurin_cos_pow2(45,100)
print maclaurin_cos2
maclaurin_cos3 = maclaurin_cos_pow2(30,100)
print maclaurin_cos3
#############################################################
#FT python "C:
#0.5
#0.5
#0.75
|
4fa3aae5c740399583c47ed49c75b30d57e76557 | betty29/code-1 | /recipes/Python/499351_Format_number_function/recipe-499351.py | 777 | 3.875 | 4 | def format_positive_integer(number):
l = list(str(number))
c = len(l)
while c > 3:
c -= 3
l.insert(c, '.')
return ''.join(l)
def format_number(number, precision=0, group_sep='.', decimal_sep=','):
number = ('%.*f' % (max(0, precision), number)).split('.')
integer_part = number[0]
if integer_part[0] == '-':
sign = integer_part[0]
integer_part = integer_part[1:]
else:
sign = ''
if len(number) == 2:
decimal_part = decimal_sep + number[1]
else:
decimal_part = ''
integer_part = list(integer_part)
c = len(integer_part)
while c > 3:
c -= 3
integer_part.insert(c, group_sep)
return sign + ''.join(integer_part) + decimal_part
|
06ee5e10dd92faeda7c632c728f20445a136f9db | betty29/code-1 | /recipes/Python/578662_DEMO_show_how_write_text_inPythterminal_Title/recipe-578662.py | 772 | 3.53125 | 4 | # Title_Bar.py
# DEMO to show how to write some text into the Title Bar...
# Original code, (C)2013, B.Walker, G0LCU.
# Issued as Public Domain.
#
# Tested on OSX 10.7.5, Debian 6.0.x and PCLinuxOS 2009 using the default
# terminals running at least Python 2.5.2 to 3.3.2...
#
# A snapshot of the Title Bar here:-
#
# http://wisecracker.host22.com/public/Title_Bar.jpg
# To launch the DEMO enter:-
#
# >>> exec(open("/your/full/path/to/Title_Bar.py").read())<CR>
#
import time
#
print("Writing to the Title Bar...")
print("\x1B]0;THIS IS A TITLE BAR DEMO...\x07")
print("Wait for 5 seconds...")
time.sleep(5)
print("\x1B]0;\x07")
print("Title Bar returned to normal...")
#
# End of Title_Bar.py DEMO...
# Enjoy finding simple solutions to often very difficult problems...
|
750199b890339b4357d04d0553ca538c1489f732 | betty29/code-1 | /recipes/Python/520585_VectorObject/recipe-520585.py | 881 | 3.84375 | 4 | #a class used for creating any object moving in 2D or a Vector Object (VObject)
#for direction use degrees, think of a 2d environment like:
#
# 90
# |
# |
# 180 ----+----- 0
# |
# |
# 270
#
from math import cos as _cos, sin as _sin, radians as _rad
class VObject():
def __init__(self,x,y,speed,direction):
self.x = x
self.y = y
self.s = speed
self.d = _rad(direction)
def update(self,time=1):
distance = self.s*time
y = (_sin(self.d))*distance
x = (_cos(self.d))*distance
self.x += x
self.y += y
def addspeed(self,speed):
self.s += speed
def steer(self,angle):
self.d += _rad(angle)
def getx(self): return self.x
def gety(self): return self.y
|
47f27bfcbe59ddf5a9cbac9d80b8729e8f6f6a68 | betty29/code-1 | /recipes/Python/473832_Eight_Queens_using_Generator/recipe-473832.py | 3,221 | 4.09375 | 4 | import sys, itertools
from sets import Set
NUM_QUEENS = 8
MAX = NUM_QUEENS * NUM_QUEENS
# Each position (i.e. square) on the chess board is assigned a number
# (0..63). non_intersecting_table maps each position A to a set
# containing all the positions that are *not* attacked by the position
# A.
intersecting_table = {}
non_intersecting_table = {}
# Utility functions for drawing chess board
def display(board):
"Draw an ascii board showing positions of queens"
assert len(board)==MAX
it = iter(board)
for row in xrange(NUM_QUEENS):
for col in xrange(NUM_QUEENS):
print it.next(),
print '\n'
def make_board(l):
"Construct a board (list of 64 items)"
board = [x in l and '*' or '_' for x in range(MAX)]
return board
# Construct the non-intersecting table
for pos in range(MAX):
intersecting_table[pos] = []
for row in range(NUM_QUEENS):
covered = range(row * NUM_QUEENS, (row+1) * NUM_QUEENS)
for pos in covered:
intersecting_table[pos] += covered
for col in range(NUM_QUEENS):
covered = [col + zerorow for zerorow in range(0, MAX, NUM_QUEENS)]
for pos in covered:
intersecting_table[pos] += covered
for diag in range(NUM_QUEENS):
l_dist = diag + 1
r_dist = NUM_QUEENS - diag
covered = [diag + (NUM_QUEENS-1) * x for x in range(l_dist)]
for pos in covered:
intersecting_table[pos] += covered
covered = [diag + (NUM_QUEENS+1) * x for x in range(r_dist)]
for pos in covered:
intersecting_table[pos] += covered
for diag in range(MAX - NUM_QUEENS, MAX):
l_dist = (diag % NUM_QUEENS) + 1
r_dist = NUM_QUEENS - l_dist + 1
covered = [diag - (NUM_QUEENS + 1) * x for x in range(l_dist)]
for pos in covered:
intersecting_table[pos] += covered
covered = [diag - (NUM_QUEENS - 1) * x for x in range(r_dist)]
for pos in covered:
intersecting_table[pos] += covered
universal_set = Set(range(MAX))
for k in intersecting_table:
non_intersecting_table[k] = universal_set - Set(intersecting_table[k])
# Once the non_intersecting_table is ready, the 8 queens problem is
# solved completely by the following method. Start by placing the
# first queen in position 0. Every time we place a queen, we compute
# the current non-intersecting positions by computing union of
# non-intersecting positions of all queens currently on the
# board. This allows us to place the next queen.
def get_positions(remaining=None, depth=0):
m = depth * NUM_QUEENS + NUM_QUEENS
if remaining is not None:
rowzone = [x for x in remaining if x < m]
else:
rowzone = [x for x in range(NUM_QUEENS)]
for x in rowzone:
if depth==NUM_QUEENS-1:
yield (x,)
else:
if remaining is None:
n = non_intersecting_table[x]
else:
n = remaining & non_intersecting_table[x]
for p in get_positions(n, depth + 1):
yield (x,) + p
return
rl = [x for x in get_positions()]
for i,p in enumerate(rl):
print '=' * NUM_QUEENS * 2, "#%s" % (i+1)
display(make_board(p))
print '%s solutions found for %s queens' % (i+1, NUM_QUEENS)
|
0f41f7b982d54bc6d41e9e2631d6523968af7be5 | betty29/code-1 | /recipes/Python/466335_Closures_Highly_Readable_Sequence_Sorting/recipe-466335.py | 1,639 | 3.53125 | 4 | # -- use cases: --
def usecases():
from pprint import pprint
print '\n--- Sorting Simple Lists ---\n'
data = ['Jim', 'Will', 'Tom']
print data
data.sort( By(len) )
print data
print '\n--- Sorting Simple Tables ---\n'
data = [
('Jim', 21),
('Will', 24),
('Tom', 20),
]
pprint(data)
data.sort( ByColumn(0) ) # using straight forward comparator closure
pprint(data)
data.sort( By(Column(1)) ) # comparator/accessor closure combination
pprint(data)
print '\n--- Sorting Object Tables ---\n'
class Record:
def __init__(self, **kw): self.__dict__.update(kw)
def __repr__(self): return '<record %r>' % self.__dict__
data = [
Record(name='Jim', age=21),
Record(name='Will', age=24),
Record(name='Tom', age=20),
]
pprint(data)
data.sort( ByAttribute('name') ) # using straight forward comparator closure
pprint(data)
data.sort( By(Attribute('age')) ) # comparator/accessor closure combination
pprint(data)
# -- a straight forward approach: --
def ByColumn(key):
def compare(obj1, obj2): return cmp(obj1[key], obj2[key])
return compare
def ByAttribute(name):
def compare(obj1, obj2): return cmp(getattr(obj1, name), getattr(obj2, name))
return compare
# -- a somewhat more generic approach: --
def By(accessor):
def compare(left, right): return cmp( accessor(left), accessor(right) )
return compare
def Attribute(name):
def get(obj): return getattr(obj, name)
return get
def Column(key):
def get(obj): return obj[key]
return get
# -- demo: --
if __name__ == '__main__':
usecases()
|
1e7057b41443c4a39aa9b2b8f38c631aa30d0d35 | betty29/code-1 | /recipes/Python/577961_Bezier_Curve_using_De_Casteljau/recipe-577961.py | 1,175 | 3.6875 | 4 | # Random Bezier Curve using De Casteljau's algorithm
# http://en.wikipedia.org/wiki/Bezier_curve
# http://en.wikipedia.org/wiki/De_Casteljau%27s_algorithm
# FB - 201111244
import random
from PIL import Image, ImageDraw
imgx = 500
imgy = 500
image = Image.new("RGB", (imgx, imgy))
draw = ImageDraw.Draw(image)
def B(coorArr, i, j, t):
if j == 0:
return coorArr[i]
return B(coorArr, i, j - 1, t) * (1 - t) + B(coorArr, i + 1, j - 1, t) * t
n = random.randint(3, 6) # number of control points
coorArrX = []
coorArrY = []
for k in range(n):
x = random.randint(0, imgx - 1)
y = random.randint(0, imgy - 1)
coorArrX.append(x)
coorArrY.append(y)
# plot the curve
numSteps = 10000
for k in range(numSteps):
t = float(k) / (numSteps - 1)
x = int(B(coorArrX, 0, n - 1, t))
y = int(B(coorArrY, 0, n - 1, t))
try:
image.putpixel((x, y), (0, 255, 0))
except:
pass
# plot the control points
cr = 3 # circle radius
for k in range(n):
x = coorArrX[k]
y = coorArrY[k]
try:
draw.ellipse((x - cr, y - cr, x + cr, y + cr), (255, 0, 0))
except:
pass
image.save("BezierCurve.png", "PNG")
|
3d038303b6569c4e3f9960965fac283ed8682941 | betty29/code-1 | /recipes/Python/499347_Automatic_explicit_file_close/recipe-499347.py | 1,343 | 3.59375 | 4 | def iopen(name, mode='rU', buffering = -1):
'''
iopen(name, mode = 'rU', buffering = -1) -> file (that closes automatically)
A version of open() that automatically closes the file explicitly
when input is exhausted. Use this in place of calls to open()
or file() that are not assigned to a name and so can't be closed
explicitly. This ensures early close of files in Jython but is
completely unnecessary in CPython.
usage:
from iopen import iopen
print iopen('fname').read(),
for l in iopen('fname'): print l,
lines = [l for l in iopen('fname')]
lines = iopen('fname').readlines()
'''
class Iopen(file):
def next(self):
try: return super(Iopen, self).next()
except StopIteration: self.close(); raise
def read(self, size = -1):
data = super(Iopen, self).read(size)
if size < 0 or not len(data): self.close()
return data
def readline(self, size = -1):
data = super(Iopen, self).readline(size)
if size != 0 and not len(data): self.close()
return data
def readlines(self, size = -1):
data = super(Iopen, self).readlines(size)
if size < 0 or not len(data): self.close()
return data
return Iopen(name, mode, buffering)
|
435bbe5f0bbe27b900f0cd7f857391364345e5bf | betty29/code-1 | /recipes/Python/393010_Using_decorators_load/recipe-393010.py | 1,017 | 3.671875 | 4 | conversions = {} # the data structure -- a dict-of-dicts
def converter(source, dest):
'''A decorator that fills the conversions table with entries'''
def decorate(function):
'''Update the conversions table and return the original'''
try:
previous = conversions[source][dest]
except KeyError:
conversions.setdefault(source, {})[dest] = function
return function
raise ValueError, 'Two conversions from %r to %r: %r and %r' % (
source, dest, getattr(previous, '__name__', previous),
getattr(function, '__name__', function))
return decorate
@converter('inch', 'feet')
def tofeet(measure):
return 12 * measure
@converter('feet', 'inch')
def toinch(measure):
return measure / 12.
# ...
# converter can be used as a non-decorator to load other values.
converter('feet', 'hectare')(None)
print conversions['feet']['inch'](123)
print conversions['inch']['feet'](123)
print conversions['feet']['hectare']
|
767d7c0bee34358ef31e3f09145c99eebdf4fb1a | betty29/code-1 | /recipes/Python/577555_Object_wrapper_class/recipe-577555.py | 762 | 3.921875 | 4 | class Wrapper(object):
'''
Object wrapper class.
This a wrapper for objects. It is initialiesed with the object to wrap
and then proxies the unhandled getattribute methods to it.
Other classes are to inherit from it.
'''
def __init__(self, obj):
'''
Wrapper constructor.
@param obj: object to wrap
'''
# wrap the object
self._wrapped_obj = obj
def __getattr__(self, attr):
# see if this object has attr
# NOTE do not use hasattr, it goes into
# infinite recurrsion
if attr in self.__dict__:
# this object has it
return getattr(self, attr)
# proxy to the wrapped object
return getattr(self._wrapped_obj, attr)
|
79d246215be7494004a6a36b29a1ad933124e5ad | betty29/code-1 | /recipes/Python/438810_First_last_item_access_predicates_increase/recipe-438810.py | 1,055 | 4.03125 | 4 | def first(seq, pred=None):
"""Return the first item in seq for which the predicate is true.
If the predicate is None, return the first item regardless of value.
If no items satisfy the predicate, return None.
"""
if pred is None:
pred = lambda x: True
for item in seq:
if pred(item):
return item
return None
def last(seq, pred=None):
"""Return the last item in seq for which the predicate is true.
If the predicate is None, return the last item regardless of value.
If no items satisfy the predicate, return None.
"""
if pred is None:
pred = lambda x: True
for item in reversed(seq):
if pred(item):
return item
return None
# Just get the first item :)
# >>> seq = 'abc'
# >>> first(seq)
# 'a'
# Get the first item greater than 10
# >>> seq = [1, 2, 4, 12, 13, 15, 17]
# >>> first(seq, lambda x: x > 10)
# 12
# Get the last non-None/False/empty item
# >>> seq = ["one", "two", "three", "", None]
# >>> last(seq, bool)
# 'three'
|
0bda210435a7ca34e86a431b11fd03e086beb277 | betty29/code-1 | /recipes/Python/577840_Josephus_problem/recipe-577840.py | 4,716 | 4 | 4 | #!/usr/bin/env python
#let's speak about cladiators and the survivor (Josephus)
import sys
from math import log
CLDTRS_NUMBER = 0
last2first = lambda L : L[-1::] + L[0:len(L) -1]
def wholives(n):
## ---We search Within lowest-highest power of 2 that n Gladiators resides---
## wholives Function assumes that we have assigned each Gladiator a number in ascending order
## (in a way that Gladiators are ordered as they --have,need or must -- to. The numbers just follow their order)
## wholives is a FAST FUNCTION WITH CONSTANT TIME COMPLEXITY
## We calculate the log2 of the number of Gladiators if it is integer then we subtract one from the number raised in
## powers of 2 then we subtract the number of Gladiators from the base power and finally we subtract it from the number of
## Gladiators. If it the log2 is not integer we take the next exponent (successor) as Base
## The key here is that at every increment of exponent of power of 2 (minus 1) we can calculate all the previous Gladiators down to
## the previous exponent( minus 1) just by subtracting the nearest higher power of 2 (minus 1) and from Gladiators n and then
## subtracting the result from the Gladiators n itself.
## in order to select efficiently the correct nearest higher exponent we simply calculate the log2 of n Gladiators
## if it is integer we are in (we can use it as our Base exponent)
## it it is not then it means we need to take the next higher exponent for our Base exponent
## we are not interesting into any result of log2 of n Gladiators that is not integer since the subtractions
## between the limits of the lower power and higher power can give us the result
#there are two base cases
# if there are two Gladiators the first survives because he has the Sword
# if there is only one Gladiator ..he is already the Survivor...
if n == 1:
return 1
if n == 2:
return 1
LogN = log(n,2)
if not LogN.is_integer():
BaseExpo = int(LogN) + 1
BasePower = int(pow(2,BaseExpo)) - 1
Sub = BasePower - n
Res = n - Sub
return Res
else:
#Here we need to restart counting
#eg 7 lives 7 (2^3 -1) ,15 lives 15 (2^4 -1) ,31 lives 31 (2^5 -1) ,63 lives 63 (2^6 -1)\
# 127 lives 127 (2^7 -1 ) so we can just return 1 to restart at 8 , 16 , 32, 64, 128 respectively
# and so on and so forth...
#BaseExpo = int(LogN)
#BasePower = int(pow(2,BaseExpo)) - 1
#Sub = BasePower - n
#Res = n - Sub
#return Res
return 1
def isNotEven(x):
if not x % 2:
return False
else:
return True
def PrepareCladiators(NUMBER):
cladiators = tuple(xrange(1,NUMBER + 1))
return cladiators
def Survivor(cladiators):
if len(cladiators) < 2:
raise Exception ,"\n\n***** Cladiators must be at least 2!!! ***** \n"
##
##
## print"\nCeasar says:\n\tLET THE DEATH MATCH BEGIN!!!\
## \n\nThey started kiling each other... \nEach one kills the next one\
## \nand passes the Sword to the next one alive.. \
## \nthere are all",len(cladiators)," still alive and here they are \n" ,cladiators
FirstClads = len(cladiators)
Clads = cladiators
deathcycle =0
while len(Clads) > 1 :
if isNotEven(len(Clads)):
deathcycle += 1
Clads = Clads[::2]
Clads = last2first(Clads)
##
## print "\n",len(Clads), "left alive after the",deathcycle,"death cycle and "\
## ,FirstClads - len(Clads)," have died till know"
## print "\nThese are the live ones\n",Clads
##
else:
deathcycle += 1
Clads = Clads[::2]
##
## print "\n",len(Clads), "left alive after the",deathcycle,"death cycle and "\
## ,FirstClads - len(Clads)," have died till know"
## if len(Clads) > 1 :
## print "\nThese are the live ones\n",Clads
## else :
## print "\n**** The last Survivor **** \nis:\n***\n\tCladiator",Clads[0]\
## ,"\n\n*********************************"
return Clads[0]
if __name__ == "__main__":
try :
CLDTRS_NUMBER = int(sys.argv[1])
## print "\n\t**** Welcome to the Deadly Arena Survivor ****\n"
## print "\n",CLDTRS_NUMBER," Cladiators will fight and \n",CLDTRS_NUMBER -1 ," Cladiators are going to die ...\n"
## print "\tONLY ONE SHALL SURVIVE...\n"
## print "\tBUT who???\n"
## print " ohhh , HERE THEY ARE .. \n"
cladiators = PrepareCladiators(CLDTRS_NUMBER)
## print cladiators, "\n\n!!! HAIL Ceasar !!! \nthey say loudly..."
print CLDTRS_NUMBER,Survivor(cladiators)
except (IndexError ,ValueError ):
print "Please place one integer value as arguement\n"
|
142ed12ab1e4fc8150c5a682f3ab99b11cd4216b | betty29/code-1 | /recipes/Python/578630_Convert_decimal_basen_any_positive_n_less_thor/recipe-578630.py | 1,212 | 3.890625 | 4 | def base(num,base):
"""
Input: num can be any base 10 integer, base can be any positive integer<=10.
Output: num is returned as a string in the specified base integer.
"""
from math import log
# Create a list of all possible digits
digits=[x for x in range(base)]
# Solve for highest base power
highestExponent=int(log(num,base))
# Create base expansion list from greatest to least
baseExpansionList=[base**x for x in range(highestExponent+1)]
baseExpansionList.reverse()
# Get digits in base
newDigits=[]
for x in baseExpansionList:
tmp=getDigits(num,x,digits)
num=num-(tmp*x)
newDigits.append(tmp)
# Convert newDigits to str format
numStr=""
for x in newDigits:
numStr+=str(x)
return numStr
def getDigits(num,baseNum,digitsList):
"""
Input: num, baseNum, and digitsList must all come from base(num,base) as is
currently specified.
Output: returns each digit in the output number of base(num,base).
"""
tmpList=[]
for x in digitsList:
if x*(baseNum)>num:
tmpList.append(x)
return max((set(digitsList)-set(tmpList)))
|
0b54a8597359bf31bc81275b9ac10158dcc616bf | betty29/code-1 | /recipes/Python/577852_Iterator_Offsetter/recipe-577852.py | 833 | 3.6875 | 4 | import itertools
def offsetter(iterable, offsets=(0, 1), longest=False):
"""
Return offset element from an iterable.
Pad offset element with None at boundaries.
"""
# clone the iterable
clones = itertools.tee(iterable, len(offsets))
# set up the clone iterables
iterables = []
for offset, clone in zip(offsets, clones):
if offset > 0:
# fast forward the start
clone = itertools.islice(clone, offset, None)
elif offset < 0:
# pad the front of the iterable
clone = itertools.chain(itertools.repeat(None, -offset), clone)
else:
# nothing to do
pass
iterables.append(clone)
if longest:
return itertools.izip_longest(*iterables)
else:
return itertools.izip(*iterables)
|
8d5fe4bb37422526f3455494cc8f00f5b293909b | betty29/code-1 | /recipes/Python/577201_Infix_operators_for_numpy_arrays/recipe-577201.py | 962 | 3.9375 | 4 | import numpy as np
class Infix(np.ndarray):
"""
Creates a new infix operator that correcly acts on numpy arrays and scalars, used as X *op* Y.
The main motivation is to use np.dot as an infix operator for matrix multiplication.
example:
>>> x = np.array([1, 1, 1])
>>> x *dot* x
3
>>> 1 + x *dot* x # Multiplication has higher precedence than addition
4
"""
def __new__(cls, function):
obj = np.ndarray.__new__(cls, 0)
obj.function = function
return obj
def __array_finalize__(self, obj):
if obj is None: return
self.function = getattr(obj, 'function', None)
def __rmul__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __mul__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
dot = Infix(np.dot)
outer = Infix(np.outer)
|
70a1f16eefc4fbe3e03134c4046e29ffd845b322 | betty29/code-1 | /recipes/Python/87369_Priority_Queue/recipe-87369.py | 876 | 4.03125 | 4 | import Queue
class PriorityQueue(Queue.Queue):
def _put(self, item):
data, priority = item
self._insort_right((priority, data))
def _get(self):
return self.queue.pop(0)[1]
def _insort_right(self, x):
"""Insert item x in list, and keep it sorted assuming a is sorted.
If x is already in list, insert it to the right of the rightmost x.
"""
a = self.queue
lo = 0
hi = len(a)
while lo < hi:
mid = (lo+hi)/2
if x[0] < a[mid][0]: hi = mid
else: lo = mid+1
a.insert(lo, x)
def test():
pq = PriorityQueue()
pq.put(('b', 1))
pq.put(('a', 1))
pq.put(('c', 1))
pq.put(('z', 0))
pq.put(('d', 2))
while not pq.empty():
print pq.get(),
test() # prints z b a c d
|
e8b3840af3d15d43bf3522394b9f94d1ff59ff98 | betty29/code-1 | /recipes/Python/79735_Set_Default_Commandline/recipe-79735.py | 704 | 3.875 | 4 | import sys
def isint(x):
try:
x = int(x)
return 1
except:
return 0
def isarg(pos):
try:
temp = sys.argv[pos]
temp = 1
except:
temp = 0
return temp
def setarg(pos, val):
if isarg(pos):
if isint(sys.argv[pos]):
return int(sys.argv[pos])
else:
return sys.argv[pos]
else:
sys.argv.append(str(val)) # str(val) is used, because by default all arguments are strings
if isint(sys.argv[len(sys.argv)-1]):
return int(sys.argv[len(sys.argv)-1])
else:
return sys.argv[len(sys.argv)-1]
## usage : FileNameToProcess = setarg(1, "default.txt")
## Explanation:
## if there is an argument at sys.argv[1], return that value;
## if not, sys.argv[1] to "default.txt"
|
50da86ca5d24e4fcf513a600693ac1b9d56d4e89 | betty29/code-1 | /recipes/Python/577716_Simple_Sudoku/recipe-577716.py | 4,683 | 4.0625 | 4 | #<><><><><><><><><><><><><><><><><><><><><><><><> sodoko puzzle <><><><><><><><><><><><><><><><><><><><><><><><>
# By : Amir Naghvi , Olempico@Gmail.com #
import random
global Platform
global fill
Platform=[[0 for i in "."*9]for i in "."*9] # Main table to Handle Game
class main(object):
"------------- start --------------"
def __init__(self):
pass
def gameloop(self): # ----------------GAME LOOP
while True:
o=raw_input('to show puzzle enter s to quit enter q: ')
if o=="s":self.show()
elif o=="q":return
d=raw_input('first X then Y then NUM like XyNumber (for example 245): ')
x=int(d[0]);y=int(d[1]);num=int(d[2])
if self.give(x,y,num):
print "True"
else:
print "you entered incorrect";
self.show()
def show(self): # -------To Printing puzzle
c1=0
c2=0
for i in Platform:
if c1%3==0:print" ->>"*21,
print " "
c1+=1
for j in i:
c2+=1
if j==0:
print " ","_ _"," ",
if c2%3==0:print r"|||",;
else:
print " ",j," "," ",
if c2%3==0:print r"|||",;
print "\n";
print "\n\n";
def give(self,x,y,NUM): # ---for recieving number and it's position
""" first checks if the position in not filled then change position's number
then if the number is not valid changes the position number to 0 again and returns False"""
if Platform[x-1][y-1]!=0:
print"\n_________Already Filled__________\n";
return False
Platform [x-1][y-1]=NUM
if not self.control(x,y):
Platform [x-1][y-1]=0
return False
else:
return True
def control(slef,x,y):
"""There is Three checking stages:1st we find the number's row ,column and cube number then
check if the row has not the same numbers ,2nd we collect the number's colmn neigbours in 'colmns' list
and simply do checking again 3rd: for checking the number in its cube area i explain below:"""
row=x-1;#print row
col=y-1;#print col
# 1. row test >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.1
rows=[Platform[row][i] for i in range(9)]
for i in range(9):
for j in range(9):
if j!=i:
if rows[i]==rows[j] and rows[i]!=0 and rows[j]!=0:
if not fill:
print 'row'
return False
# 2. column test >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.2
colmns=[Platform[i][col] for i in range(9)]
for i in range(9):
for j in range(9):
if j!=i:
if colmns[i]==colmns[j] and colmns[j]!=0 and colmns[i]!=0:
if not fill:
print 'col'
return False
# 3. 3x3 Cubes >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>.3
""" 1.frst for 'first' cube number in X attitiude and sec second cube number in y ,for example centeral cube is (3,3)
or first cube from bottom is (0,6) 2.then in 'cube' list i gather the cube numbers and 3.then simply check if there is a
repeated numbers"""
# 1.
frst=-1
sec=-1
if row<3:frst=0
elif row<6:frst=3
elif row<9:frst=6
if col<3:sec=0
elif col<6:sec=3
elif col<9:sec=6
# 2.
cube=[Platform[frst][sec+i]for i in range(3)] # creating cube
cube.extend([Platform[frst+1][sec+i]for i in range(3)])
cube.extend([Platform[frst+2][sec+i]for i in range(3)])
# 3.
for i in range(9):
for j in range(9):
if j!=i:
if cube[i]==cube[j] and cube[i]!=0 and cube[j]!=0:
if not fill:
print 'cube'
return False
return True
# *********************************************************************
# *********************************************************************
if __name__=="__main__":
o=main() # RUN
o.gameloop()
# *********************************************************************
# *********************************************************************
|
11a7641848efccc92738d6cbe69018d8c36fdd8e | betty29/code-1 | /recipes/Python/576533_script_calculating_simple/recipe-576533.py | 247 | 4 | 4 | print "all amounts should be in dollars!"
while True:
P=float(raw_input("enter Principal:"))
i=float(raw_input("enter Percentage of interest rate:"))
t=float(raw_input("enter Time(in years):"))
I=P*t*(i/100)
print "Interest is", I,"dollars"
|
02f3f048199deebe01ea50cd06bcc7140dd9d102 | betty29/code-1 | /recipes/Python/252525_Just_in_time_instantiation/recipe-252525.py | 1,615 | 3.609375 | 4 | class JIT:
'''
JIT is a class for Just In Time instantiation of objects. Init is called
only when the first attribute is either get or set.
'''
def __init__(self, klass, *args, **kw):
'''
klass -- Class of objet to be instantiated
*args -- arguments to be used when instantiating object
**kw -- keywords to be used when instantiating object
'''
self.__dict__['klass'] = klass
self.__dict__['args'] = args
self.__dict__['kw'] = kw
self.__dict__['obj'] = None
def initObj(self):
'''
Instantiate object if not already done
'''
if self.obj is None:
self.__dict__['obj'] = self.klass(*self.args, **self.kw)
def __getattr__(self, name):
self.initObj()
return getattr(self.obj, name)
def __setattr__(self, name, value):
self.initObj()
setattr(self.obj, name, value)
class TestIt:
def __init__(self, arg, keyword=None):
print 'In TestIt.__init__() -- arg: %s, keyword=%s' % (arg, keyword)
def method(self):
print 'In TestIt.method().'
def oldWay():
# Create t whether or not it gets used.
t = TestIt('The Argument', keyword='The Keyword')
def main():
# JIT refactored
t = JIT(TestIt, 'The Argument', keyword='The Keyword')
print 'Not intstaintiated yet.'
# TestIt object instantiated here.
t.method()
if __name__ == '__main__':
main()
# OUTPUT:
# Not intstaintiated yet.
# In TestIt.__init__() -- arg: The Argument, keyword=The Keyword
# In TestIt.method().
|
047f090ed1e801f01ee2c1441ab3d0a1f434e668 | betty29/code-1 | /recipes/Python/528911_Barcodes__Convert_UPCE_to_UPCA/recipe-528911.py | 1,577 | 4.0625 | 4 | #This code is GPL3
def calc_check_digit(value):
"""calculate check digit, they are the same for both UPCA and UPCE"""
check_digit=0
odd_pos=True
for char in str(value)[::-1]:
if odd_pos:
check_digit+=int(char)*3
else:
check_digit+=int(char)
odd_pos=not odd_pos #alternate
check_digit=check_digit % 10
check_digit=10-check_digit
check_digit=check_digit % 10
return check_digit
def convert_UPCE_to_UPCA(upce_value):
"""Test value 04182635 -> 041800000265"""
if len(upce_value)==6:
middle_digits=upce_value #assume we're getting just middle 6 digits
elif len(upce_value)==7:
#truncate last digit, assume it is just check digit
middle_digits=upce_value[:6]
elif len(upce_value)==8:
#truncate first and last digit,
#assume first digit is number system digit
#last digit is check digit
middle_digits=upce_value[1:7]
else:
return False
d1,d2,d3,d4,d5,d6=list(middle_digits)
if d6 in ["0","1","2"]:
mfrnum=d1+d2+d6+"00"
itemnum="00"+d3+d4+d5
elif d6=="3":
mfrnum=d1+d2+d3+"00"
itemnum="000"+d4+d5
elif d6=="4":
mfrnum=d1+d2+d3+d4+"0"
itemnum="0000"+d5
else:
mfrnum=d1+d2+d3+d4+d5
itemnum="0000"+d6
newmsg="0"+mfrnum+itemnum
#calculate check digit, they are the same for both UPCA and UPCE
check_digit=calc_check_digit(newmsg)
return newmsg+str(check_digit)
#Usage example
print convert_UPCE_to_UPCA(UPCE)
|
545049864c75b1045885c8eddba22cc60de252d9 | betty29/code-1 | /recipes/Python/577289_Maclaurinsseriestan1/recipe-577289.py | 1,615 | 4.0625 | 4 | #On the name of ALLAH and may the blessing and peace of Allah
#be upon the Messenger of Allah Mohamed Salla Allahu Aliahi Wassalam.
#Author : Fouad Teniou
#Date : 06/07/10
#version :2.6
"""
maclaurin_tan-1 is a function to compute tan-1(x) using maclaurin series
and the interval of convergence is -1 <= x <= +1
sin(x) = x - x^3/3 + x^5/5 - x^7/7 ...........
"""
from math import *
def error(number):
""" Raises interval of convergence error."""
if number > 1 or number < -1 :
raise TypeError,\
"\n<The interval of convergence should be -1 <= value <= 1 \n"
def maclaurin_cot(value, k):
"""
Compute maclaurin's series approximation for tan-1(x)
"""
global first_value
first_value = 0.0
#attempt to Approximate tan-1(x) for a given value
try:
error(value)
for item in xrange(1,k,4):
next_value = value**item/float(item)
first_value += next_value
for arg in range(3,k,4):
next_value = -1* value **arg/float(arg)
first_value += next_value
return round(first_value*180/pi,2)
#Raise TypeError if input is not within
#the interval of convergence
except TypeError,exception:
print exception
if __name__ == "__main__":
maclaurin_cot1 = maclaurin_cot(0.305730681,100)
print maclaurin_cot1
maclaurin_cot2 = maclaurin_cot(0.75355405,100)
print maclaurin_cot2
maclaurin_cot3 = maclaurin_cot(0.577350269,100)
print maclaurin_cot3
#################################################################
#"C:\python
#17.0
#37.0
#30.0
|
64205295ae053ba8c05a1b822ad35b2af8032923 | betty29/code-1 | /recipes/Python/474116_Drop_shadows_with_PIL/recipe-474116.py | 2,060 | 3.984375 | 4 | """
Drop shadows with PIL.
Author: Kevin Schluff
License: Python license
"""
from PIL import Image, ImageFilter
def dropShadow( image, offset=(5,5), background=0xffffff, shadow=0x444444,
border=8, iterations=3):
"""
Add a gaussian blur drop shadow to an image.
image - The image to overlay on top of the shadow.
offset - Offset of the shadow from the image as an (x,y) tuple. Can be
positive or negative.
background - Background colour behind the image.
shadow - Shadow colour (darkness).
border - Width of the border around the image. This must be wide
enough to account for the blurring of the shadow.
iterations - Number of times to apply the filter. More iterations
produce a more blurred shadow, but increase processing time.
"""
# Create the backdrop image -- a box in the background colour with a
# shadow on it.
totalWidth = image.size[0] + abs(offset[0]) + 2*border
totalHeight = image.size[1] + abs(offset[1]) + 2*border
back = Image.new(image.mode, (totalWidth, totalHeight), background)
# Place the shadow, taking into account the offset from the image
shadowLeft = border + max(offset[0], 0)
shadowTop = border + max(offset[1], 0)
back.paste(shadow, [shadowLeft, shadowTop, shadowLeft + image.size[0],
shadowTop + image.size[1]] )
# Apply the filter to blur the edges of the shadow. Since a small kernel
# is used, the filter must be applied repeatedly to get a decent blur.
n = 0
while n < iterations:
back = back.filter(ImageFilter.BLUR)
n += 1
# Paste the input image onto the shadow backdrop
imageLeft = border - min(offset[0], 0)
imageTop = border - min(offset[1], 0)
back.paste(image, (imageLeft, imageTop))
return back
if __name__ == "__main__":
import sys
image = Image.open(sys.argv[1])
image.thumbnail( (200,200), Image.ANTIALIAS)
dropShadow(image).show()
dropShadow(image, background=0xeeeeee, shadow=0x444444, offset=(0,5)).show()
|
a5cc2f11cac04753563230af015b5b20c55697f5 | betty29/code-1 | /recipes/Python/577542_Pascals_triangle/recipe-577542.py | 350 | 3.65625 | 4 | def pascals_triangle(n):
'''
Pascal's triangle:
for x in pascals_triangle(5):
print('{0:^16}'.format(x))
[1]
[1, 1]
[1, 2, 1]
[1, 3, 3, 1]
[1, 4, 6, 4, 1]
'''
x=[[1]]
for i in range(n-1):
x.append([sum(i) for i in zip([0]+x[-1],x[-1]+[0])])
return x
|
f2258f962ce1b7a92eff606edad3bdab4969fd9a | betty29/code-1 | /recipes/Python/286129_Word_wrapping_generator/recipe-286129.py | 1,451 | 3.578125 | 4 | strings = [
"""Deep Thoughts
- by Jack Handy
===============""",
"It takes a big man to cry, but it takes a bigger man to laugh at that man.",
"When you're riding in a time machine way far into the future, don't stick your elbow out the window, or it'll turn into a fossil.",
"I wish I had a Kryptonite cross, because then you could keep both Dracula AND Superman away.",
"I don't think I'm alone when I say I'd like to see more and more planets fall under the ruthless domination of our solar system.",
"I hope if dogs ever take over the world, and they chose a king, they don't just go by size, because I bet there are some Chihuahuas with some good ideas.",
"The face of a child can say it all, especially the mouth part of the face."
]
def wordWrap(s,length):
offset = 0
while offset+length < len(s):
if s[offset] in ' \n':
offset += 1
continue
endOfLine = s[offset:offset+length].find('\n')
if endOfLine < 0:
endOfLine = s[offset:offset+length].rfind(' ')
if endOfLine < 0:
endOfLine = length
newOffset = offset + endOfLine
else:
newOffset = offset + endOfLine + 1
yield s[offset:offset+endOfLine].rstrip()
offset = newOffset
if offset < len(s):
yield s[offset:].strip()
for s in strings:
for l in wordWrap(s,20):
print l
print
|
336aa1483a7e6b27a66c7e5ebd5eddbb7a86f745 | betty29/code-1 | /recipes/Python/156546_Initializing_attributes_constant/recipe-156546.py | 372 | 3.5625 | 4 | # The natural approach would be to do initialization in the object
# constructor:
class counter:
def __init__(self):
self.count = 0
def next(self):
self.count += 1
return self.count
# But Python offer a terse and efficient alternative:
class counter:
count = 0
def next(self):
self.count += 1
return self.count
|
dda9fce9fbb4c1d1225a545866b3f2b6e44c9ea6 | betty29/code-1 | /recipes/Python/577122_transform_commline_arguments_args_kwargs_method_/recipe-577122.py | 1,122 | 3.671875 | 4 | def _method_info_from_argv(argv=None):
"""Command-line -> method call arg processing.
- positional args:
a b -> method('a', 'b')
- intifying args:
a 123 -> method('a', 123)
- json loading args:
a '["pi", 3.14, null]' -> method('a', ['pi', 3.14, None])
- keyword args:
a foo=bar -> method('a', foo='bar')
- using more of the above
1234 'extras=["r2"]' -> method(1234, extras=["r2"])
@param argv {list} Command line arg list. Defaults to `sys.argv`.
@returns (<method-name>, <args>, <kwargs>)
"""
import json
import sys
if argv is None:
argv = sys.argv
method_name, arg_strs = argv[1], argv[2:]
args = []
kwargs = {}
for s in arg_strs:
if s.count('=') == 1:
key, value = s.split('=', 1)
else:
key, value = None, s
try:
value = json.loads(value)
except ValueError:
pass
if key:
kwargs[key] = value
else:
args.append(value)
return method_name, args, kwargs
|
666d15630504fa2bb2719facd2433496075b3a66 | betty29/code-1 | /recipes/Python/580788_Implementing_classbased_callbacks/recipe-580788.py | 1,652 | 3.578125 | 4 | '''
File: callback_demo2.py
To demonstrate implementation and use of callbacks in Python,
using classes with methods as the callbacks.
Author: Vasudev Ram
Copyright 2017 Vasudev Ram
Web site: https://vasudevram.github.io
Blog: https://jugad2.blogspot.com
Product store: https://gumroad.com/vasudevram
'''
from __future__ import print_function
import sys
from time import sleep
class FileReporter(object):
def __init__(self, filename):
self._filename = filename
try:
self._fil = open(self._filename, "w")
except IOError as ioe:
sys.stderr.write("While opening {}, caught IOError: {}\n".format(
self._filename, repr(ioe)))
sys.exit(1)
def report(self, message):
self._fil.write(message)
class ScreenReporter(object):
def __init__(self, dest):
self._dest = dest
def report(self, message):
self._dest.write(message)
def square(i):
return i * i
def cube(i):
return i * i * i
def processor(process, times, report_interval, reporter):
result = 0
for i in range(1, times + 1):
result += process(i)
sleep(0.1)
if i % report_interval == 0:
# This is the call to the callback method
# that was passed to this function.
reporter.report("Items processed: {}. Running result: {}.\n".format(i, result))
file_reporter = FileReporter("processor_report.txt")
processor(square, 20, 5, file_reporter)
stdout_reporter = ScreenReporter(sys.stdout)
processor(square, 20, 5, stdout_reporter)
stderr_reporter = ScreenReporter(sys.stderr)
processor(square, 20, 5, stderr_reporter)
|
66f48db95df507012419b8f9986b994cc5e08c55 | betty29/code-1 | /recipes/Python/577059_Running_Median/recipe-577059.py | 3,530 | 3.515625 | 4 | from collections import deque
from bisect import insort
def grouper(seq, n):
'Split sequence into n-length deques'
return [deque(seq[i:i+n]) for i in range(0, (len(seq)+n-1)//n*n, n)]
class RunningMedian:
''' Updates median value over a sliding window.
Initialize with a window size of data. The call update(elem) with
new values. Returns the new median (for an odd-sized window).
'''
# Gains speed by maintaining a sort while inserting new values
# and deleting the oldest ones.
# Reduction of insert/delete time is done by chunking sorted data
# into subgroups organized as deques, so that appending and popping
# are cheap. Running-time per update is proportional to the
# square-root of the window size.
# Inspired by "Efficient Algorithm for computing a Running Median"
# by Soumya D. Mohanty. Adapted for Python by eliminating the
# map structure, check structure, and by using deques.
def __init__(self, iterable):
self.q = q = deque(iterable) # track the order that items are added
n = int(len(q) ** 0.5) # compute optimal chunk size
self.chunks = grouper(sorted(q), n) # sorted list of sorted n-length subsequences
row, self.midoffset = divmod((len(q) - 1) // 2, n) # locate the mid-point (median)
self.midchunk = self.chunks[row]
def update(self, new_elem, check_invariants=False):
# update the main queue that tracks values in the order added
old_elem = self.q.popleft()
self.q.append(new_elem)
# insert new element into appropriate chunk (where new_elem less that rightmost elem in chunk)
chunks = self.chunks
for new_index, chunk in enumerate(chunks):
if new_elem < chunk[-1]:
break
data = list(chunk)
insort(data, new_elem)
chunk.clear()
chunk.extend(data)
# remove oldest element
for old_index, chunk in enumerate(chunks):
if old_elem <= chunk[-1]:
break
chunk.remove(old_elem)
# restore the chunk sizes by shifting end elements
# chunk at new_index is too fat
# chunk at old_index is too thin
if new_index < old_index:
# propagate the now-too-fat chunk to the right
for i in range(new_index, old_index):
chunks[i+1].appendleft(chunks[i].pop())
elif new_index > old_index:
# feed the now-too-thin chunk from the right
for i in range(old_index, new_index):
chunks[i].append(chunks[i+1].popleft())
# check-invariants (slow)
if check_invariants:
assert sorted(self.q) == [elem for chunk in chunks for elem in chunk]
assert len(set(map(len, chunks))) <= 2 # are chunk sizes balanced ?
# return median
return self.midchunk[self.midoffset]
if __name__ == '__main__':
from random import randrange
from itertools import islice
window_size = 41
data = [randrange(200) for i in range(1000)]
it = iter(data)
r = RunningMedian(islice(it, window_size))
medians = [r.update(elem, True) for elem in it]
midpoint = (window_size - 1) // 2
median = lambda window: sorted(window)[midpoint]
target_medians = [median(data[i:i+window_size]) for i in range(1, len(data)-window_size+1)]
assert medians == target_medians
print(medians)
|
312245e2c134fde92ce72c18e19b000f7bede0c5 | betty29/code-1 | /recipes/Python/577241_Faster_Factorial/recipe-577241.py | 674 | 3.65625 | 4 | _FAC_TABLE = [1, 1]
def factorial(n):
if n < len(_FAC_TABLE):
return _FAC_TABLE[n]
last = len(_FAC_TABLE) - 1
total = _FAC_TABLE[last]
for i in range(last + 1, n + 1):
total *= i
_FAC_TABLE.append(total)
return total
def main():
from timeit import Timer
print("factorial: %.5f s" %
Timer("factorial(500)", "from __main__ import factorial")
.timeit(1000))
import math
if hasattr(math, "factorial"):
print("math.factorial: %.5f s" %
Timer("factorial(500)", "from math import factorial")
.timeit(1000))
if __name__ == "__main__":
main()
|
3540260c286efde65defb93fd20366ad803e588d | betty29/code-1 | /recipes/Python/578070_extending_xrange_support_slicing/recipe-578070.py | 2,936 | 3.8125 | 4 | def read_xrange(xrange_object):
'''returns the xrange object's start, stop, and step'''
start = xrange_object[0]
if len(xrange_object) > 1:
step = xrange_object[1] - xrange_object[0]
else:
step = 1
stop = xrange_object[-1] + step
return start, stop, step
class Xrange(object):
''' creates an xrange-like object that supports slicing and indexing.
ex: a = Xrange(20)
a.index(10)
will work
Also a[:5]
will return another Xrange object with the specified attributes
Also allows for the conversion from an existing xrange object
'''
def __init__(self, *inputs):
# allow inputs of xrange objects
if len(inputs) == 1:
test, = inputs
if type(test) == xrange:
self.xrange = test
self.start, self.stop, self.step = read_xrange(test)
return
# or create one from start, stop, step
self.start, self.step = 0, None
if len(inputs) == 1:
self.stop, = inputs
elif len(inputs) == 2:
self.start, self.stop = inputs
elif len(inputs) == 3:
self.start, self.stop, self.step = inputs
else:
raise ValueError(inputs)
self.xrange = xrange(self.start, self.stop, self.step)
def __iter__(self):
return iter(self.xrange)
def __getitem__(self, item):
if type(item) is int:
if item < 0:
item += len(self)
return self.xrange[item]
if type(item) is slice:
# get the indexes, and then convert to the number
start, stop, step = item.start, item.stop, item.step
start = start if start != None else 0 # convert start = None to start = 0
if start < 0:
start += start
start = self[start]
if start < 0: raise IndexError(item)
step = (self.step if self.step != None else 1) * (step if step != None else 1)
stop = stop if stop is not None else self.xrange[-1]
if stop < 0:
stop += stop
stop = self[stop]
stop = stop
if stop > self.stop:
raise IndexError
if start < self.start:
raise IndexError
return Xrange(start, stop, step)
def index(self, value):
error = ValueError('object.index({0}): {0} not in object'.format(value))
index = (value - self.start)/self.step
if index % 1 != 0:
raise error
index = int(index)
try:
self.xrange[index]
except (IndexError, TypeError):
raise error
return index
def __len__(self):
return len(self.xrange)
|
36ecce4200fcfb9cbda0d830ece14304f8fea442 | betty29/code-1 | /recipes/Python/576585_Lazy_recursive_generator/recipe-576585.py | 2,471 | 4.0625 | 4 | #>>>>>>>>>> Icon example of recursive generator >>>>>>>>>
##procedure star(chars)
## suspend "" | (star(chars) || !chars)
##end
##
class bang(object):
""" a generator with saved state that can be reset """
def __init__(self, arg):
self.arg = arg
self.reset()
def __iter__(self):
for item in self.iterable:
yield item
def next(self):
return self.iterable.next()
def reset(self):
if hasattr(self.arg, '__iter__') and \
hasattr(self.arg, 'next') :
self.iterable = self.arg
elif hasattr(self.arg, '__getitem__'):
if self.arg:
self.iterable = iter(self.arg)
else: self.iterable = iter([""])
else:
self.iterable = iter([self.arg])
def __repr__(self):
return repr(self.arg)
def alternation( *items ):
"""Lazy evaluation that flattens input items """
for alt_item in items:
if hasattr(alt_item, '__iter__'):
#flatten generator item
for item in alt_item:
yield item
else:
yield alt_item
def concatenate(g1, g2):
"""Lazy evaluation concatenation """
#list, tuple, and string iterators are not used implicitly
#Not generalized for sequences other than strings
if hasattr(g1, '__iter__') and hasattr(g2, '__iter__'):
#concatenations of left items to right items
#map(operator.plus, leftseq, rightseq)
for x in g1:
g2.reset()
for y in g2:
yield x + y
elif hasattr(g1, '__iter__') :
#concatenations of left items to right sequence
#map(operator.plus, [leftseq]*len(rightseq), rightseq)
for x in g1:
yield x + g2
elif hasattr(g2, '__iter__') :
#concatenations of left sequence to right items
#map(operator.plus, leftseq, [rightseq]*len(leftseq))
for x in g2:
yield g1 + x
else:
#string concatenation like Python
yield g1 + g2
def star(chars):
""" Recursive, infinite generator for all permutations
of a string taken 1 to N characters at time """
for item in alternation("", concatenate(star(chars), bang(chars))):
yield item
#star test >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
chars = 'abc'
limit = 3 # Limit infinite recursion
for n, x in enumerate(star(chars)):
if len(x) > limit: break
print n+1, repr(x)
|
62dd59b62d29681b98ab3646502da6f9e12eba1b | betty29/code-1 | /recipes/Python/578991_Create_tabular_PDF_reports_xtopdf_tablib/recipe-578991.py | 2,435 | 3.6875 | 4 | """
TablibToPDF.py
Author: Vasudev Ram
Copyright 2014 Vasudev Ram - www.dancingbison.com
This program is a demo of how to use the tablib and xtopdf Python libraries
to generate tabular data reports as PDF output.
Tablib is at: https://tablib.readthedocs.org/en/latest/
xtopdf is at: https://bitbucket.org/vasudevram/xtopdf
and info about xtopdf is at: http://slides.com/vasudevram/xtopdf or
at: http://slid.es/vasudevram/xtopdf
"""
import random
import tablib
from PDFWriter import PDFWriter
# Helper function to output a string to both screen and PDF.
def print_and_write(pw, strng):
print strng
pw.writeLine(strng)
# Set up grade and result names and mappings.
grade_letters = ['F', 'E', 'D', 'C', 'B', 'A']
results = {'A': 'Pass', 'B': 'Pass', 'C': 'Pass',
'D': 'Pass', 'E': 'Pass', 'F': 'Fail'}
# Create an empty Dataset and set its headers.
data = tablib.Dataset()
data.headers = ['ID', 'Name', 'Marks', 'Grade', 'Result']
widths = [5, 12, 8, 8, 12] # Display widths for columns.
# Create some rows of student data and use it to populate the Dataset.
# Columns for each student row correspond to the header columns
# shown above.
for i in range(20):
id = str(i).zfill(2)
name = 'Student-' + id
# Let's grade them on the curve [1].
# This examiner doesn't give anyone 100 marks :)
marks = random.randint(40, 99)
# Compute grade from marks.
grade = grade_letters[(marks - 40) / 10]
result = results[grade]
columns = [id, name, marks, grade, result]
row = [ str(col).center(widths[idx]) for idx, col in enumerate(columns) ]
data.append(row)
# Set up the PDFWriter.
pw = PDFWriter('student_grades.pdf')
pw.setFont('Courier', 10)
pw.setHeader('Student Grades Report - generated by xtopdf')
pw.setFooter('xtopdf: http://slides.com/vasudevram/xtopdf')
# Generate header and data rows as strings; output them to screen and PDF.
separator = '-' * sum(widths)
print_and_write(pw, separator)
# Output headers
header_strs = [ header.center(widths[idx]) for idx, header in enumerate(data.headers) ]
print_and_write(pw, ''.join(header_strs))
print_and_write(pw, separator)
# Output data
for row in data:
print_and_write(pw, ''.join(row))
print_and_write(pw, separator)
pw.close()
# [1] http://en.wikipedia.org/wiki/Grading_on_a_curve
# I'm not endorsing the idea of grading on a curve; I only used it as a
# simple algorithm to generate the marks and grades for this example.
|
9914d207c5d5343446238393b2d2f5c243fe69c2 | betty29/code-1 | /recipes/Python/81098_python_enum_with_strings/recipe-81098.py | 2,670 | 3.609375 | 4 | #
# enum.py
#
# This file contains the enum class, which implements
# C style enums for python
#
class EnumException(Exception): pass
class InvalidEnumVal(EnumException): pass
class InvalidEnum(EnumException): pass
class DuplicateEnum(EnumException): pass
class DuplicateEnumVal(EnumException): pass
class enum:
def __init__(self, enumstr):
self.lookup = { }
self.reverseLookup = { }
evalue = 0
elist = enumstr.split(',')
for e in elist:
item = e.strip().split('=')
ename = item[0].strip()
if ename == '':
continue
if len(item) == 2:
try:
evalue = int(item[1].strip(), 0)
except ValueError:
raise InvalidEnumVal, 'Invalid value for: ' + ename
elif len(item) != 1:
raise InvalidEnum, "Invalid enum: " + e
if self.lookup.has_key(ename):
raise DuplicateEnum, "Duplicate enum name: " + ename
if self.reverseLookup.has_key(evalue):
raise DuplicateEnumVal,"Duplicate value %d for %s"%(evalue,ename)
self.lookup[ename] = evalue
self.reverseLookup[evalue] = ename
evalue += 1
def __getattr__(self, attr):
return self.lookup[attr]
def __len__(self):
return len(self.lookup)
def __repr__(self):
s = ''
values = self.lookup.values()
values.sort()
for e in values:
s = s + '%s = %d\n' % (self.reverseLookup[e], e)
return s
def main():
str = """
JETTA,
RABBIT,
BEETLE,
THING=400,
PASSAT,
GOLF,
CABRIO=700,
EUROVAN,
"""
v = enum(str)
print v
print 'PASSAT = %d' % v.PASSAT
e1 = enum('TEST,,TEST2')
print 'e1 len = %d' % len(e1)
print e1
try:
e2 = enum('TEST,TEST1=jjj')
except InvalidEnumVal, msg:
print 'Invalid Enum Value Passed'
print ' %s' % msg
else:
print 'Invalid Enum Value Failed'
try:
e2 = enum('TEST,TEST1=76=87=KJK')
except InvalidEnum, msg:
print 'Invalid Enum Passed'
print ' %s' % msg
else:
print 'Invalid Enum Failed'
try:
e2 = enum('TEST,TEST')
except DuplicateEnum, msg:
print 'Duplicate Enum Passed'
print ' %s' % msg
else:
print 'Duplicate Enum Failed'
try:
e2 = enum('TEST,TEST1=0')
except DuplicateEnumVal, msg:
print 'Duplicate Enum Val Passed'
print ' %s' % msg
else:
print 'Duplicate Enum Val Failed'
if __name__ == "__main__":
main()
|
a63f914b185f81363e7d44d3a063f71102156f6a | betty29/code-1 | /recipes/Python/425445_once_decorator/recipe-425445.py | 848 | 3.578125 | 4 | def func_once(func):
"A decorator that runs a function only once."
def decorated(*args, **kwargs):
try:
return decorated._once_result
except AttributeError:
decorated._once_result = func(*args, **kwargs)
return decorated._once_result
return decorated
def method_once(method):
"A decorator that runs a method only once."
attrname = "_%s_once_result" % id(method)
def decorated(self, *args, **kwargs):
try:
return getattr(self, attrname)
except AttributeError:
setattr(self, attrname, method(self, *args, **kwargs))
return getattr(self, attrname)
return decorated
# Example, will only parse the document once
@func_once
def get_document():
import xml.dom.minidom
return xml.dom.minidom.parse("document.xml")
|
0bc6b8bd8d229bc0cdbcb0adade2307809baa8c3 | betty29/code-1 | /recipes/Python/279155_linenumpy/recipe-279155.py | 1,531 | 3.921875 | 4 | # linenum.py
import traceback, textwrap
def LN(*args, **kwargs):
"""Prints a line number and some text.
A variable number of positional arguments are allowed. If
LN(obj0, obj1, obj2)
is called, the text part of the output looks like the output from
print obj0, obj1, obj2
The optional keyword "wrap" causes the message to be line-wrapped. The
argument to "wrap" should be "1" or "True". "name" is another optional
keyword parameter. This is best explained by an example:
from linenum import LN
def fun1():
print LN('error', 'is', 'here')
def fun2():
print LN('error', 'is', 'here', name='mess')
fun1()
fun2()
The output is:
L3 fun1: error is here
L5 mess: error is here
"""
stack = traceback.extract_stack()
a, b, c, d = stack[-2]
out = []
for obj in args:
out.append(str(obj))
text = ' '.join(out)
if 'name' in kwargs:
text = 'L%s %s: %s' % (b, kwargs['name'], text)
else:
text = 'L%s %s: %s' % (b, c, text)
if 'wrap' in kwargs and kwargs['wrap']:
text = textwrap.fill(text)
return text
#=====================================================
# LNtest.py
#! /usr/bin/env python
from linenum import LN
def function():
print LN()
print LN('print', 'me')
print LN('abc', name='AName')
print LN('When the name variable is of the form ' \
'package.module, normally, the top-level package', wrap=1)
function()
|
e5c65886f8e2ce9027a07036542ed395762d38ef | betty29/code-1 | /recipes/Python/578456_class_decorator_creating_named/recipe-578456.py | 2,170 | 3.625 | 4 | from collections import namedtuple as namedtuple
def as_namedtuple(*fields_and_global_default, **defaults):
"""A class decorator factory joining the class with a namedtuple.
If any of the expected arguments are not passed to the class, they
are set to the specific default value or global default value (if any).
"""
num_args = len(fields_and_global_default)
if num_args > 2 or num_args < 1:
raise TypeError("as_namedtuple() takes at 1 or 2 positional-only "
"arguments, {} given".format(num_args))
else:
fields, *global_default_arg = fields_and_global_default
if isinstance(fields, str):
fields = fields.replace(',', ' ').split()
for field in defaults:
if field not in fields:
raise ValueError("got default for a non-existant field ({!r})"
.format(field))
# XXX unnecessary if namedtuple() got support for defaults.
@classmethod
def with_defaults(cls, *args, **kwargs):
"""Return an instance with defaults populated as necessary."""
# XXX or dynamically build this method with appropriate signature
for field, arg in zip(fields, args):
if field in kwargs:
raise TypeError("with_defaults() got multiple values for "
"keyword argument {!r}".format(field))
kwargs[field] = arg
for field, default in defaults.items():
if field not in kwargs:
kwargs[field] = default
if global_default_arg:
default = global_default_arg[0]
for field in fields:
if field not in kwargs:
kwargs[field] = default
return cls(**kwargs)
def decorator(cls):
"""Return a new nametuple-based subclass of cls."""
# Using super() (i.e. the MRO) makes this work correctly.
bases = (namedtuple(cls.__name__, fields), cls)
namespace = {'__doc__': cls.__doc__, '__slots__': (),
'with_defaults': with_defaults}
return type(cls.__name__, bases, namespace)
return decorator
|
ea92b091369322fb1036292e98ca8056edb12432 | betty29/code-1 | /recipes/Python/577374_monty_hall_problem/recipe-577374.py | 11,538 | 3.859375 | 4 | #!/usr/bin/env python
# Author: Mark Connolly
# Dedicated to my favorite sister, Caroline
# Contact: mark_connolly at acm dot org
class Monty_Hall(object):
"""Monty, teach me probabilities.
Monty_Hall is a gameshow host that proves that it is statistically better to switch
when offered the chance after getting additional knowledge in a fair game. The caveat
is "statistically better", which means any single trial can have unwanted results.
But "statistically better" is exactly where the fist-fights at bars and family reunions
start, so no matter the single trial outcomes.
Monty has a game set, which has doors. Monty has a scoreboard which keeps track of
wins and losses. You tell Monty waht to do, Monty does it.
You create an instance of Monty_Hall and send him messages. For example:
(when you start python, you first want to
>>> import gameshow
then you have access to what you need)
>>> monty = gameshow.Monty_Hall() # get yourself a gameshow Monty_Hall and attach its reference to a variable
>>> monty.choose_door(2) # 1. tell your Monty_Hall to choose a door (number 2 in this case)
>>> monty.switch() # 2. tell your Monty_Hall you'd like to switch
>>> monty.start_game() # 3. tell your Monty_Hall to start a new game, Monty_Hall will keep score
You can repeat the three steps to you heart's content. Stay with the same Monty_Hall
for he knows the score. Once you think you have suffered a sufficient number of games:
>>> monty.tell_me_the_score() # and your Monty_Hall will
You can also tell your Monty_Hall
>>> monty.start_new_series()
And your Monty_Hall will clear the scoreboard and start gathering statistics anew.
If Monty's music is bringing you down, you can set the wait to zero seconds:
>>> monty.music_duration = 0 # or any number of seconds. There is no actual music!
If you are lazy, you can have the gameshow automaton play for you:
>>> gameshow.automaton() # plays 100 games (by default) and has its Monty_Hall print out the statistics
You can have the gameshow automaton play any number of games for you with the form
>>> gameshow.automaton(iterations=1000)
Notes: The prize is randomly distributed to Monty's three game set doors for each game. The
statistical results will vary around the expected values 1/3 and 2/3. Variance is to be expected,
but large numbers of trials should be very close to the expected values. Mendel cooked his books.
"""
def __init__(self, music_duration = 4):
"""
Do all the initialization stuff when a new
instance of Monty_Hall is created. Granted,
this aint much.
"""
self.music_duration = music_duration
self.start_new_series()
def start_game(self):
"""
Starts a new game without resetting the scoreboard
"""
self.game_set = Game_Set()
print("\nYou can now choose a door.\n")
def start_new_series(self):
"""
A series is a set of games for which win/loss statistics are created.
Starting a new series clears the scoreboard and starts a new game.
"""
self.scoreboard = Scoreboard()
print("Scoreboard has been cleared")
self.start_game()
def choose_door(self, door_number):
"""
Monty gives you the door you ask for, then he opens a door you did not pick.
"""
import time
try:
self.game_set.select_door(door_number)
print("I will now open a door you did not select.")
print("(music plays)(no music actually plays)")
time.sleep(self.music_duration)
self.game_set.open_door()
except ValueError, explanation:
pass
print explanation
def switch(self):
"""
Monty switches your door with the one you did not pick. Monty then opens
your new selection to reveal the prize or the goat.
"""
try:
self.game_set.switch_door()
result = self.game_set.open_selected_door()
print("Door contains %s" % result)
if (result == "prize"):
print("You win!")
self.scoreboard.won_switched()
else:
print("Baaaaa!")
self.scoreboard.lost_switched()
except ValueError, explanation:
print explanation
pass
def stay(self):
"""
Monty understands you would like to stay. Monty shrugs and opens
your door to reveal the prize or the goat.
"""
result = self.game_set.open_selected_door()
print("Door contains %s" % result)
if (result == "prize"):
print("You win!")
self.scoreboard.won_stayed()
else:
print("Baaaaa!")
self.scoreboard.lost_stayed()
def tell_me_the_score(self):
"""
Monty has his scoreboard print itself out with the wins, losses, and percentages.
"""
self.scoreboard.tell_me_the_score()
class Scoreboard(object):
def __init__(self):
self.stats = {"Won switched" : 0.0, # this is a hash structure
"Lost switched": 0.0, # it is composed of keys and values
"Won stayed": 0.0, # values are set as float numbers (has a decimal
# component) as opposed to integers.
"Lost stayed": 0.0} # The reason is that the value will be used in
# calculating percentages. Integers would render
# integers and the decimal would be lost.
def won_switched(self):
self.stats["Won switched"] += 1
def lost_switched(self):
self.stats["Lost switched"] += 1
def won_stayed(self):
self.stats["Won stayed"] += 1
def lost_stayed(self):
self.stats["Lost stayed"] += 1
def tell_me_the_score(self):
play_made = "Stayed"
won = self.stats["Won stayed"]
lost = self.stats["Lost stayed"]
self.print_score(play_made, won, lost)
play_made = "Switched"
won = self.stats["Won switched"]
lost = self.stats["Lost switched"]
self.print_score(play_made, won, lost)
def print_score(self, play, w, l):
print("\nStats for " + play)
if (w + l > 0):
print(
"wins: %i losses: %i, percent win: %5.2f%%" # Text with formatting placeholders
%(w, l, (w / (w + l) * 100.0)) # The collection of ordered values to
# substitute and format
) # The %% prints a single % literal at
# the end of the formatted string
else:
print("No statistics for %s" % play)
class Game_Set(object):
"""
A collection of doors. Each door can hold something desireable
or something not so desireable. However, only one door in a game
can hold something desireable.
"""
def __init__(self):
import random
doors = {
0: Door(1),
1: Door(2),
2: Door(3)}
# random.randrange(startInt,endInt) generates a random integer in the range
# of startInt (which is included in the possibilities) to endInt (which is
# not included in the possibilities.
prize_door = random.randrange(0,3)
doors[prize_door].contents = "prize"
doors[((prize_door + 1) % 3)].contents = "goat"
doors[((prize_door + 2) % 3)].contents = "goat"
self.keep_track = {"doors": doors,
"prize": doors[prize_door],
"selected": None,
"opened": None}
def select_door(self, door_number):
"""
Select a door by number.
"""
# Has a door already been selected or switched this game?
if (self.keep_track["selected"]):
# raise an error to the caller and do no more
raise ValueError, "You have already selected a door."
# is an appropriate door being selected?
if door_number in (1,2,3):
# appropriate door number, transform to door key by subtracting 1
door_number = door_number - 1
else:
# raise an error to the caller and do no more
raise ValueError, "You entered %s, which is not a recognized door." % door_number
# that takes care of the possible errors
# now, moved the selected door out of the collection
self.keep_track["selected"] = self.keep_track["doors"][door_number]
del self.keep_track["doors"][door_number]
print("\nYou have selected door number %s.\nYou have a 1 in 3 chance of holding the prize."
% self.keep_track["selected"].label)
print("The house has a 2 in 3 chance of holding the prize.\n")
def open_door(self):
"""
Open one of the doors that has not been selected. One of the doors may have
the prize. Don't open that one.
"""
keys = self.keep_track["doors"].keys()
for key in keys:
if self.keep_track["doors"][key] == self.keep_track["prize"]:
pass
else:
self.keep_track["opened"] = self.keep_track["doors"][key]
del self.keep_track["doors"][key]
print("\nDoor %s is open and contains a %s.\n"
% (self.keep_track["opened"].label, self.keep_track["opened"].contents)
)
print("Your odds of holding the prize behind door number %s have not changed."
% self.keep_track["selected"].label)
print("The house odds have not changed just because one of the house doors has been opened.")
print("You now know which of the two doors held by the house does not contain the prize.")
print("Switching your selection is the same as switching to both doors held by the house.")
print("This is because you have taken the open door out of the selection options.")
print("Switching to the open door would just be silly, unless you want the goat.")
print("Switching to the house's closed door exchanges your odds (1 in 3) for the house odds (2 in 3)\n")
break
def switch_door(self):
"""
Exchange the selected door to the unopened door
"""
keys = self.keep_track["doors"].keys()
key = keys[0] # only one door left in the collection
# one removed when selected. one removed when opened
# swap the doors
hold_this_a_second = self.keep_track["doors"][key]
self.keep_track["doors"][key] = self.keep_track["selected"]
self.keep_track["selected"] = hold_this_a_second
print("\nYou now hold door %s.\n" % self.keep_track["selected"].label)
def open_selected_door(self):
"""
Opens the selected door to see if the prize is THE prize or a goat
"""
return self.keep_track["selected"].contents
class Door(object):
def __init__(self, label):
self.contents = None
self.label = label
def automaton(iterations=100, select_door="random"):
"""
Plays the game with its own Monty_Hall. Turns off the music so
the games proceeds apace.
default iterations is 100
door selection is random unless specified by the named variable select_door
"""
import random
"create a function that either returns a random door or a specified door"
if (select_door == "random"):
select_a_door = lambda : random.randrange(1,4)
else:
select_a_door = lambda : select_door
monty = Monty_Hall(music_duration=0)
for i in range(1,iterations):
select_door = select_a_door()
monty.choose_door(select_door)
monty.switch()
monty.start_game()
monty.choose_door(select_door)
monty.stay()
monty.start_game()
"finish up with the scores"
monty.tell_me_the_score()
"""
print a little help at import or reload
"""
help(Monty_Hall)
|
a5431bb48049aa784132d0a08a866223d580d2d4 | betty29/code-1 | /recipes/Python/577574_PythInfinite_Rotations/recipe-577574.py | 2,497 | 4.28125 | 4 | from itertools import *
from collections import deque
# First a naive approach. At each generation we pop the first element and append
# it to the back. This is highly memmory deficient.
def rotations(it):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
l = list(it)
for i in range(len(l)):
yield iter(l)
l = l[1:]+[l[0]]
# A much better approach would seam to be using a deque, which rotates in O(1),
# However this does have the negative effect, that generating the next rotation
# before the current has been iterated through, will result in a RuntimeError
# because the deque has mutated during iteration.
def rotations(it):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
l = deque(it)
for i in range(len(l)):
yield iter(l)
l.rotate()
# The trick is to use subsets of infinite lists. First we define the function tails,
# which is standard in many functal languages.
# Because of the way tee is implemented in itertools, the below implementation will
# use memory only propertional to the offset difference between the generated
# iterators.
def tails(it):
""" tails([1,2,3,4,5]) --> [[1,2,3,4,5], [2,3,4,5], [3,4,5], [4,5], [5], []] """
while True:
tail, it = tee(it)
yield tail
next(it)
# We can now define two new rotations functions.
# The first one is very similar to the above, but since we never keep all list
# elements, we need an extra length parameter.
def rotations(it, N):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
return (islice(rot,N) for rot in islice(tails(cycle(it)),N))
# The above works fine for things like:
# >>> for rot in rotations(range(4), 4):
# ... print (list(rot))
# ...
# [0, 1, 2, 3]
# [1, 2, 3, 0]
# [2, 3, 0, 1]
# [3, 0, 1, 2]
#
# But that is not really where it shines, since the lists are iterated one after
# another, and so the tails memory usage becomes linear.
#
# In many cases tails and infinite lists lets us get away with an even simpler
# rotaions function:
def rotations(it, N):
""" rotations([0,1,2]) --> [[0, 1, 2], [1, 2, 0], [2, 0, 1]] """
return islice(tails(cycle(it)),N)
# This one works great for instances where we are topcut anyway:
# >>> for rot in rotations(range(4), 4):
# ... print (list(zip(range(4), rot)))
# ...
# [(0, 0), (1, 1), (2, 2), (3, 3)]
# [(0, 1), (1, 2), (2, 3), (3, 0)]
# [(0, 2), (1, 3), (2, 0), (3, 1)]
# [(0, 3), (1, 0), (2, 1), (3, 2)]
|
f865ed5f77ba09d59e85d80f64631c26f1007809 | betty29/code-1 | /recipes/Python/578113_Humreadable_format_given_time/recipe-578113.py | 5,125 | 3.6875 | 4 | """
@author Thomas Lehmann
@file dateBack.py
@brief provides a human readable format for a time delta
"""
from datetime import datetime , timedelta
def dateBack(theDateAndTime, precise=False, fromDate=None):
""" provides a human readable format for a time delta
@param theDateAndTime this is time equal or older than now or the date in 'fromDate'
@param precise when true then milliseconds and microseconds are included
@param fromDate when None the 'now' is used otherwise a concrete date is expected
@return the time delta as text
@note I don't calculate months and years because those varies (28,29,30 or 31 days a month
and 365 or 366 days the year depending on leap years). In addition please refer
to the documentation for timedelta limitations.
"""
if not fromDate:
fromDate = datetime.now()
if theDateAndTime > fromDate: return None
elif theDateAndTime == fromDate: return "now"
delta = fromDate - theDateAndTime
# the timedelta structure does not have all units; bigger units are converted
# into given smaller ones (hours -> seconds, minutes -> seconds, weeks > days, ...)
# but we need all units:
deltaMinutes = delta.seconds // 60
deltaHours = delta.seconds // 3600
deltaMinutes -= deltaHours * 60
deltaWeeks = delta.days // 7
deltaSeconds = delta.seconds - deltaMinutes * 60 - deltaHours * 3600
deltaDays = delta.days - deltaWeeks * 7
deltaMilliSeconds = delta.microseconds // 1000
deltaMicroSeconds = delta.microseconds - deltaMilliSeconds * 1000
valuesAndNames =[ (deltaWeeks ,"week" ), (deltaDays ,"day" ),
(deltaHours ,"hour" ), (deltaMinutes,"minute"),
(deltaSeconds,"second") ]
if precise:
valuesAndNames.append((deltaMilliSeconds, "millisecond"))
valuesAndNames.append((deltaMicroSeconds, "microsecond"))
text =""
for value, name in valuesAndNames:
if value > 0:
text += len(text) and ", " or ""
text += "%d %s" % (value, name)
text += (value > 1) and "s" or ""
# replacing last occurrence of a comma by an 'and'
if text.find(",") > 0:
text = " and ".join(text.rsplit(", ",1))
return text
def test():
""" testing function "dateBack" """
# we need a date to rely on for testing concrete deltas
fromDate = datetime(year=2012, month=4, day=26, hour=8, minute=40, second=45)
testCases = [
("1 second" , fromDate-timedelta(seconds=1), False),
("5 seconds" , fromDate-timedelta(seconds=5), False),
("1 minute" , fromDate-timedelta(minutes=1), False),
("5 minutes" , fromDate-timedelta(minutes=5), False),
("1 minute and 10 seconds" , fromDate-timedelta(minutes=1, seconds=10), False),
("1 hour" , fromDate-timedelta(hours= 1), False),
("1 hour and 1 second" , fromDate-timedelta(hours=1, seconds=1), False),
("1 hour and 1 minute" , fromDate-timedelta(hours=1, minutes=1), False),
("1 hour, 1 minute and 1 second" , fromDate-timedelta(hours=1, minutes=1, seconds=1), False),
("1 week" , fromDate-timedelta(weeks=1), False),
("2 weeks" , fromDate-timedelta(weeks=2), False),
("1 week and 1 second" , fromDate-timedelta(weeks=1, seconds=1), False),
("1 week and 1 minute" , fromDate-timedelta(weeks=1, minutes=1), False),
("1 week and 1 hour" , fromDate-timedelta(weeks=1, hours=1), False),
("1 week, 1 hour, 1 minute and 1 second", fromDate-timedelta(weeks=1, hours=1, minutes=1, seconds=1), False),
("1 millisecond" , fromDate-timedelta(milliseconds=1),True),
("2 milliseconds" , fromDate-timedelta(milliseconds=2),True),
("1 microsecond" , fromDate-timedelta(microseconds=1),True),
("2 microseconds" , fromDate-timedelta(microseconds=2),True),
("1 millisecond and 1 microsecond" , fromDate-timedelta(milliseconds=1, microseconds=1),True) ]
for expectedResult, testDate, precise in testCases:
print("test case for '%s'" % expectedResult)
calculatedResult = dateBack(testDate, precise=precise, fromDate=fromDate)
try: assert expectedResult == calculatedResult
except: print(" -> error: wrong value: '%s'" % calculatedResult)
# future date in relation to 'fromDate' (1 hour)
futureDate = fromDate + timedelta(hours=1)
expectedResult = None
assert expectedResult == dateBack(futureDate, precise=False, fromDate=fromDate)
if __name__ == "__main__":
test()
|
53684f621287f1a2d7b2c4602b12d03108388e87 | betty29/code-1 | /recipes/Python/576526_compare_making_filter_fun_again/recipe-576526.py | 1,104 | 3.6875 | 4 | class compare(object):
def __init__(self, function):
self.function = function
def __eq__(self, other):
def c(l, r): return l == r
return comparator(self.function, c, other)
def __ne__(self, other):
def c(l, r): return l != r
return comparator(self.function, c, other)
def __lt__(self, other):
def c(l, r): return l < r
return comparator(self.function, c, other)
def __le__(self, other):
def c(l, r): return l <= r
return comparator(self.function, c, other)
def __gt__(self, other):
def c(l, r): return l > r
return comparator(self.function, c, other)
def __ge__(self, other):
def c(l, r): return l >= r
return comparator(self.function, c, other)
class comparator(object):
def __init__(self, function, comparison, value):
self.function = function
self.comparison = comparison
self.value = value
def __call__(self, *arguments, **keywords):
return self.comparison(self.function(*arguments, **keywords), self.value)
|
d821b07149089dba24a238c3ad83d5c8b6642fd6 | betty29/code-1 | /recipes/Python/577965_Sieve_Eratosthenes_Prime/recipe-577965.py | 986 | 4.34375 | 4 | def primeSieve(x):
'''
Generates a list of odd integers from 3 until input, and crosses
out all multiples of each number in the list.
Usage:
primeSieve(number) -- Finds all prime numbers up until number.
Returns: list of prime integers (obviously).
Time: around 1.5 seconds when number = 1000000.
'''
numlist = range(3, x+1, 2)
counter = 0 # Keeps count of index in while loop
backup = 0 # Used to reset count after each iteration and keep count outside of while loop
for num in numlist:
counter = backup
if num != 0:
counter += num
while counter <= len(numlist)-1: # Sifts through multiples of num, setting them all to 0
numlist[counter] = 0
counter += num
else: # If number is 0 already, skip
pass
backup += 1 # Increment backup to move on to next index
return [2] + [x for x in numlist if x]
|
7fec3af0dbd9245ceeb54ef70e2224443d6518b8 | betty29/code-1 | /recipes/Python/499350_NonLinear_Units/recipe-499350.py | 629 | 3.703125 | 4 | class DB:
'''
Convience class for decibel scale. Other non-linear scales such as the richter scale could be handled similarly.
Usage:
dB = DB()
.
. (later)
.
gain = 15 * dB
'''
def __rmul__(self, val):
'''
Only allow multiplication from the right to avoid confusing situation
like: 15 * dB * 10
'''
return 10 ** (val / 10.)
def __test__():
dB = DB()
gain = 10 * dB
assert abs(gain - 10) < 1e-8
try:
gain2 = dB * 10
raise Exception('Should raise a type error!')
except TypeError:
pass
__test__()
|
849e48eba0db9689f82e2c23ec9d9ae777c78a54 | betty29/code-1 | /recipes/Python/466321_recursive_sorting/recipe-466321.py | 443 | 4.25 | 4 | """
recursive sort
"""
def rec_sort(iterable):
# if iterable is a mutable sequence type
# sort it
try:
iterable.sort()
# if it isn't return item
except:
return iterable
# loop inside sequence items
for pos,item in enumerate(iterable):
iterable[pos] = rec_sort(item)
return iterable
if __name__ == '__main__':
struct = [[1,2,3,[6,4,5]],[2,1,5],[4,3,2]]
print rec_sort(struct)
|
3274283016dc6524d7a9714ed17d74d7957cd7ec | betty29/code-1 | /recipes/Python/578656_State_Machine_Framework_AI/recipe-578656.py | 5,148 | 4.03125 | 4 | from time import sleep
from random import randint, shuffle
class StateMachine(object):
''' Usage: Create an instance of StateMachine, use set_starting_state(state) to give it an
initial state to work with, then call tick() on each second (or whatever your desired
time interval might be. '''
def set_starting_state(self, state):
''' The entry state for the state machine. '''
state.enter()
self.state = state
def tick(self):
''' Calls the current state's do_work() and checks for a transition '''
next_state = self.state.check_transitions()
if next_state is None:
# Stick with this state
self.state.do_work()
else:
# Next state found, transition to it
self.state.exit()
next_state.enter()
self.state = next_state
class BaseState(object):
''' Usage: Subclass BaseState and override the enter(), do_work(), and exit() methods.
enter() -- Setup for your state should occur here. This likely includes adding
transitions or initializing member variables.
do_work() -- Meat and potatoes of your state. There may be some logic here that will
cause a transition to trigger.
exit() -- Any cleanup or final actions should occur here. This is called just
before transition to the next state.
'''
def add_transition(self, condition, next_state):
''' Adds a new transition to the state. The "condition" param must contain a callable
object. When the "condition" evaluates to True, the "next_state" param is set as
the active state. '''
# Enforce transition validity
assert(callable(condition))
assert(hasattr(next_state, "enter"))
assert(callable(next_state.enter))
assert(hasattr(next_state, "do_work"))
assert(callable(next_state.do_work))
assert(hasattr(next_state, "exit"))
assert(callable(next_state.exit))
# Add transition
if not hasattr(self, "transitions"):
self.transitions = []
self.transitions.append((condition, next_state))
def check_transitions(self):
''' Returns the first State thats condition evaluates true (condition order is randomized) '''
if hasattr(self, "transitions"):
shuffle(self.transitions)
for transition in self.transitions:
condition, state = transition
if condition():
return state
def enter(self):
pass
def do_work(self):
pass
def exit(self):
pass
##################################################################################################
############################### EXAMPLE USAGE OF STATE MACHINE ###################################
##################################################################################################
class WalkingState(BaseState):
def enter(self):
print("WalkingState: enter()")
def condition(): return randint(1, 5) == 5
self.add_transition(condition, JoggingState())
self.add_transition(condition, RunningState())
def do_work(self):
print("Walking...")
def exit(self):
print("WalkingState: exit()")
class JoggingState(BaseState):
def enter(self):
print("JoggingState: enter()")
self.stamina = randint(5, 15)
def condition(): return self.stamina <= 0
self.add_transition(condition, WalkingState())
def do_work(self):
self.stamina -= 1
print("Jogging ({0})...".format(self.stamina))
def exit(self):
print("JoggingState: exit()")
class RunningState(BaseState):
def enter(self):
print("RunningState: enter()")
self.stamina = randint(5, 15)
def walk_condition(): return self.stamina <= 0
self.add_transition(walk_condition, WalkingState())
def trip_condition(): return randint(1, 10) == 10
self.add_transition(trip_condition, TrippingState())
def do_work(self):
self.stamina -= 2
print("Running ({0})...".format(self.stamina))
def exit(self):
print("RunningState: exit()")
class TrippingState(BaseState):
def enter(self):
print("TrippingState: enter()")
self.tripped = False
def condition(): return self.tripped
self.add_transition(condition, WalkingState())
def do_work(self):
print("Tripped!")
self.tripped = True
def exit(self):
print("TrippingState: exit()")
if __name__ == "__main__":
state = WalkingState()
state_machine = StateMachine()
state_machine.set_starting_state(state)
while True:
state_machine.tick()
sleep(1)
|
10eb5529665e42ec85fca365b24d5af7ba0d916d | betty29/code-1 | /recipes/Python/578041_NamedList/recipe-578041.py | 2,611 | 3.5 | 4 | def namedlist(typename, field_names):
"""Returns a new subclass of list with named fields.
>>> Point = namedlist('Point', ('x', 'y'))
>>> Point.__doc__ # docstring for the new class
'Point(x, y)'
>>> p = Point(11, y=22) # instantiate with positional args or keywords
>>> p[0] + p[1] # indexable like a plain list
33
>>> x, y = p # unpack like a regular list
>>> x, y
(11, 22)
>>> p.x + p.y # fields also accessable by name
33
>>> d = p._asdict() # convert to a dictionary
>>> d['x']
11
>>> Point(**d) # convert from a dictionary
Point(x=11, y=22)
>>> p._replace(x=100) # _replace() is like str.replace() but targets named fields
Point(x=100, y=22)
"""
fields_len = len(field_names)
fields_text = repr(tuple(field_names)).replace("'", "")[1:-1] # tuple repr without parens or quotes
class ResultType(list):
__slots__ = ()
_fields = field_names
def _fixed_length_error(*args, **kwargs):
raise TypeError(u"Named list has fixed length")
append = _fixed_length_error
insert = _fixed_length_error
pop = _fixed_length_error
remove = _fixed_length_error
def sort(self):
raise TypeError(u"Sorting named list in place would corrupt field accessors. Use sorted(x)")
def _replace(self, **kwargs):
values = map(kwargs.pop, field_names, self)
if kwargs:
raise TypeError(u"Unexpected field names: {s!r}".format(kwargs.keys()))
if len(values) != fields_len:
raise TypeError(u"Expected {e} arguments, got {n}".format(
e=fields_len, n=len(values)))
return ResultType(*values)
def __repr__(self):
items_repr=", ".join("{name}={value!r}".format(name=name, value=value)
for name, value in zip(field_names, self))
return "{typename}({items})".format(typename=typename, items=items_repr)
ResultType.__init__ = eval("lambda self, {fields}: self.__setitem__(slice(None, None, None), [{fields}])".format(fields=fields_text))
ResultType.__name__ = typename
for i, name in enumerate(field_names):
fget = eval("lambda self: self[{0:d}]".format(i))
fset = eval("lambda self, value: self.__setitem__({0:d}, value)".format(i))
setattr(ResultType, name, property(fget, fset))
return ResultType
|
7eae2fff8be839e78f49e485ceb50a9e14cd46f3 | betty29/code-1 | /recipes/Python/170242_caseinsensitive_sort_list/recipe-170242.py | 337 | 3.859375 | 4 | def caseinsensitive_sort(stringList):
"""case-insensitive string comparison sort
doesn't do locale-specific compare
though that would be a nice addition
usage: stringList = caseinsensitive_sort(stringList)"""
tupleList = [(x.lower(), x) for x in stringList]
tupleList.sort()
return [x[1] for x in tupleList]
|
67254b3c7e76c5cbf7b59efadc2ae1c26a29b68e | betty29/code-1 | /recipes/Python/578291_String_to_Binary/recipe-578291.py | 405 | 3.609375 | 4 | #!/usr/bin/python3
# Author: pantuts
binary = []
def strBin(s_str):
for s in s_str:
if s == ' ':
binary.append('00100000')
else:
binary.append(bin(ord(s)))
s_str = input("String: ")
strBin(s_str)
b_str = '\n'.join(str(b_str) for b_str in binary) # print as type str
# replace '\n' to '' to output in one line without spaces, ' ' if with spaces
print(b_str.replace('b',''))
|
678efd79a73c2e3d1860736c8dcf03f76ddde306 | betty29/code-1 | /recipes/Python/302380_Formatting_platext/recipe-302380.py | 3,008 | 3.515625 | 4 | import re
LEFT = '<'
RIGHT = '>'
CENTER = '^'
class FormatColumns:
'''Format some columns of text with constraints on the widths of the
columns and the alignment of the text inside the columns.
'''
def __init__(self, columns, contents, spacer=' | ', retain_newlines=True):
'''
"columns" is a list of tuples (width in chars, alignment) where
alignment is one of LEFT, CENTER or RIGHT.
"contents" is a list of chunks of text to format into each of the
columns.
'''
assert len(columns) == len(contents), \
'columns and contents must be same length'
self.columns = columns
self.num_columns = len(columns)
self.contents = contents
self.spacer = spacer
self.retain_newlines = retain_newlines
self.positions = [0]*self.num_columns
def format_line(self, wsre=re.compile(r'\s+')):
''' Fill up a single row with data from the contents.
'''
l = []
data = False
for i, (width, alignment) in enumerate(self.columns):
content = self.contents[i]
col = ''
while self.positions[i] < len(content):
word = content[self.positions[i]]
# if we hit a newline, honor it
if '\n' in word:
# chomp
self.positions[i] += 1
if self.retain_newlines:
break
word = word.strip()
# make sure this word fits
if col and len(word) + len(col) > width:
break
# no whitespace at start-of-line
if wsre.match(word) and not col:
# chomp
self.positions[i] += 1
continue
col += word
# chomp
self.positions[i] += 1
if col:
data = True
if alignment == CENTER:
col = '{:^{}}'.format(col.strip(), width)
elif alignment == RIGHT:
col = '{:>{}}'.format(col.rstrip(), width)
else:
col = '{:<{}}'.format(col.lstrip(), width)
l.append(col)
if data:
return self.spacer.join(l).rstrip()
# don't return a blank line
return ''
def format(self, splitre=re.compile(r'(\n|\r\n|\r|[ \t]|\S+)')):
# split the text into words, spaces/tabs and newlines
for i, content in enumerate(self.contents):
self.contents[i] = splitre.findall(content)
# now process line by line
l = []
line = self.format_line()
while line:
l.append(line)
line = self.format_line()
return '\n'.join(l)
def __str__(self):
return self.format()
def wrap(text, width=75, alignment=LEFT):
return FormatColumns(((width, alignment),), [text])
|
e30cef9f6629497f9ab40442a1c4067958b23a4e | betty29/code-1 | /recipes/Python/577719_Chess_Notation_Player/recipe-577719.py | 18,894 | 4.15625 | 4 | # Chess Game
board = ["r", "n", "b", "q", "k", "b", "n", "r", "x", "x", "x", "x", "x", "x", "x", "x", " ", " ",
" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ",
" ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", "X", "X", "X", "X", "X", "X",
"X", "X", "R", "N", "B", "Q", "K", "B", "N", "R"]
# Black and White squares will be useful when checking bishop moves
blackSquares = [0,2,4,6,9,11,13,15,16,18,20,22,25,27,29,31,32,34,36,38,41,43,45,47,48,50,
52,54,57,59,61,63]
whiteSquares = [1,3,5,7,8,10,12,14,17,19,21,23,24,26,28,30,33,35,37,39,40,42,44,46,49,51,
53,55,56,58,60,62]
# 0 for white and 1 for black
player = 0
destination = 0
origin = 0
movingPiece = ""
def introScreen():
print("Hello, welcome to the Chess Notation Viewer")
print("This allows you to view every stage of a notated chess")
print("match as it would appear on the board.")
input()
print("The lower case letters represent White pieces and the")
print("upper case letters represent Black pieces.")
input()
print("Enter the notations and the board will show the moves.")
print("Here is the original position.")
# translates a letter-number coordinate such as e4 to a position on the board, eg 28
def coordinate(letter, number,notation):
location = (ord(notation[letter]) - 97) + 8 * (int(notation[number]) - 1)
return location
def calculateInput():
notation = input()
origin = 0
if player == 0:
# This is for moves made by pawns
if notation[0].islower() == True:
if notation[1] == "x":
destination = coordinate(2,3,notation)
origin = coordinate(0,3,notation) - 8
else:
destination = coordinate(0,1,notation)
if board[destination - 8] == "x":
origin = destination - 8
if board[destination - 16] == "x":
origin = destination - 16
movingPiece = "x"
# This is for moves made by bishops
if notation[0] == "B":
if notation[1] == "x":
destination = coordinate(2,3,notation)
else:
destination = coordinate(1,2,notation)
if destination in whiteSquares:
for i in range(31):
if board[whiteSquares[i]] =="b":
origin = whiteSquares[i]
else:
for i in range(31):
if board[blackSquares[i]] =="b":
origin = blackSquares[i]
movingPiece = "b"
# This is for moves made by Queens
if notation[0] == "Q":
if notation[1] == "x":
destination = coordinate(2,3,notation)
else:
destination = coordinate(1,2,notation)
for i in range(63):
if board[1] == "q":
origin = i
movingPiece = "q"
# This is for moves made by kings
if notation[0] == "K":
if notation[1] == "x":
destination = coordinate(2,3,notation)
else:
destination = coordinate(1,2,notation)
for i in range(63):
if board[1] == "k":
origin = i
movingPiece = "k"
if notation[0] == "N":
knightMoves = [15,17,6,10,-10,-6,-17,-15]
destination = coordinate(len(notation)-2, len(notation) - 1,notation)
if len(notation) > 3 and notation[1] != "x":
if notation[1].isalpha() == True:
for i in range(7):
if board[(ord(notation[1]) - 97)+8*i] == "n":
origin = (ord(notation[1]) - 97)+8*i
else:
for i in range(7):
if board[8*(int(notation[1])-1)+i] == "n":
origin = 8*(int(notation[1])-1)+i
else:
if destination <= 15:
if knightMoves.count(-17) == 1:
knightMoves.remove(-17)
if knightMoves.count(-15) == 1:
knightMoves.remove(-15)
if destination <= 7:
if knightMoves.count(-10) == 1:
knightMoves.remove(-10)
if knightMoves.count(-6) == 1:
knightMoves.remove(-6)
if destination >= 48:
if knightMoves.count(15) == 1:
knightMoves.remove(15)
if knightMoves.count(17) == 1:
knightMoves.remove(17)
if destination >= 56:
if knightMoves.count(6) == 1:
knightMoves.remove(6)
if knightMoves.count(10) == 1:
knightMoves.remove(10)
if destination % 8 == 0 or destination % 8 == 1:
if knightMoves.count(6) == 1:
knightMoves.remove(6)
if knightMoves.count(-10) == 1:
knightMoves.remove(-10)
if destination % 8 == 0:
if knightMoves.count(15) == 1:
knightMoves.remove(15)
if knightMoves.count(-17) == 1:
knightMoves.remove(-17)
if destination % 8 == 6 or destination % 8 == 7:
if knightMoves.count(10) == 1:
knightMoves.remove(10)
if knightMoves.count(-6) == 1:
knightMoves.remove(-6)
if destination % 8 == 7:
if knightMoves.count(17) == 1:
knightMoves.remove(17)
if knightMoves.count(-15) == 1:
knightMoves.remove(-15)
for i in range(len(knightMoves)):
if board[destination + knightMoves[i]] == "n":
origin = destination + knightMoves[i]
movingPiece = "n"
if notation[0] == "R":
destination = coordinate(len(notation)-2, len(notation) - 1,notation)
if len(notation) > 3 and notation[1] != "x":
if notation[1].isalpha() == True:
for i in range(7):
if board[(ord(notation[1]) - 97)+8*i] == "r":
origin = (ord(notation[1]) - 97)+8*i
else:
for i in range(7):
if board[8*(int(notation[1])-1)+i] == "r":
origin = 8*(int(notation[1])-1)+i
else:
for i in range(int(((destination % 8 + 56) - destination)/8 - 1)):
if board[destination + 8 * (i+1)] == "r":
origin = destination + 8 * (i+1)
break
elif board[destination + 8 * (i+1)] == " ":
pass
else:
break
for i in range(int((destination - (destination % 8))/8 - 1)):
if board[destination - 8 * (i+1)] == "r":
origin = destination - 8 * (i+1)
break
elif board[destination + 8 * (i+1)] == " ":
pass
else:
break
for i in range(int(destination % 8 - 1)):
if board[destination - (i+1)] == "r":
origin = destination -(i+1)
break
elif board[destination - (i+1)] == " ":
pass
else:
break
for i in range(int(6 - destination % 8)):
if board[destination + (i+1)] == "r":
origin = destination + (i+1)
break
elif board[destination + (i+1)] == " ":
pass
else:
break
movingPiece = "r"
if player == 1:
# This is for moves made by pawns
if notation[0].islower() == True:
if notation[1] == "x":
destination = coordinate(2,3,notation)
origin = coordinate(0,3,notation) + 8
else:
destination = coordinate(0,1,notation)
if board[destination + 8] == "X":
origin = destination + 8
if board[destination + 16] == "X":
origin = destination + 16
movingPiece = "X"
# This is for moves made by bishops
if notation[0] == "B":
if notation[1] == "x":
destination = coordinate(2,3,notation)
else:
destination = coordinate(1,2,notation)
if destination in whiteSquares:
for i in range(31):
if board[whiteSquares[i]] =="B":
origin = whiteSquares[i]
else:
for i in range(31):
if board[blackSquares[i]] =="B":
origin = blackSquares[i]
movingPiece = "B"
# This is for moves made by Queens
if notation[0] == "Q":
if notation[1] == "x":
destination = coordinate(2,3,notation)
else:
destination = coordinate(1,2,notation)
for i in range(63):
if board[i] == "Q":
origin = i
movingPiece = "Q"
# This is for moves made by kings
if notation[0] == "K":
if notation[1] == "x":
destination = coordinate(2,3,notation)
else:
destination = coordinate(1,2,notation)
for i in range(63):
if board[i] == "K":
origin = i
movingPiece = "K"
if notation[0] == "N":
knightMoves = [15,17,6,10,-10,-6,-17,-15]
destination = coordinate(len(notation)-2, len(notation) - 1,notation)
if len(notation) > 3 and notation[1] != "x":
if notation[1].isalpha() == True:
for i in range(7):
if board[(ord(notation[1]) - 97)+8*i] == "N":
origin = (ord(notation[1]) - 97)+8*i
else:
for i in range(7):
if board[8*(int(notation[1])-1)+i] == "N":
origin = 8*(int(notation[1])-1)+i
else:
if destination <= 15:
if knightMoves.count(-17) == 1:
knightMoves.remove(-17)
if knightMoves.count(-15) == 1:
knightMoves.remove(-15)
if destination <= 7:
if knightMoves.count(-10) == 1:
knightMoves.remove(-10)
if knightMoves.count(-6) == 1:
knightMoves.remove(-6)
if destination >= 48:
if knightMoves.count(15) == 1:
knightMoves.remove(15)
if knightMoves.count(17) == 1:
knightMoves.remove(17)
if destination >= 56:
if knightMoves.count(6) == 1:
knightMoves.remove(6)
if knightMoves.count(10) == 1:
knightMoves.remove(10)
if destination % 8 == 0 or destination % 8 == 1:
if knightMoves.count(6) == 1:
knightMoves.remove(6)
if knightMoves.count(-10) == 1:
knightMoves.remove(-10)
if destination % 8 == 0:
if knightMoves.count(15) == 1:
knightMoves.remove(15)
if knightMoves.count(-17) == 1:
knightMoves.remove(-17)
if destination % 8 == 6 or destination % 8 == 7:
if knightMoves.count(10) == 1:
knightMoves.remove(10)
if knightMoves.count(-6) == 1:
knightMoves.remove(-6)
if destination % 8 == 7:
if knightMoves.count(17) == 1:
knightMoves.remove(17)
if knightMoves.count(-15) == 1:
knightMoves.remove(-15)
for i in range(len(knightMoves) - 1):
if board[destination + knightMoves[i]] == "N":
origin = destination + knightMoves[i]
movingPiece = "N"
if notation[0] == "R":
destination = coordinate(len(notation)-2, len(notation) - 1,notation)
if len(notation) > 3 and notation[1] != "x":
if notation[1].isalpha() == True:
for i in range(7):
if board[(ord(notation[1]) - 97)+8*i] == "R":
origin = (ord(notation[1]) - 97)+8*i
else:
for i in range(7):
if board[8*(int(notation[1])-1)+i] == "R":
origin = 8*(int(notation[1])-1)+i
else:
for i in range(int(((destination % 8 + 56) - destination)/8 - 1)):
if board[destination + 8 * (i+1)] == "R":
origin = destination + 8 * (i+1)
break
elif board[destination + 8 * (i+1)] == " ":
pass
else:
break
for i in range(int((destination - (destination % 8))/8 - 1)):
if board[destination - 8 * (i+1)] == "R":
origin = destination - 8 * (i+1)
break
elif board[destination + 8 * (i+1)] == " ":
pass
else:
break
for i in range(int(destination % 8 - 1)):
if board[destination - (i+1)] == "R":
origin = destination -(i+1)
break
elif board[destination - (i+1)] == " ":
pass
else:
break
for i in range(int(6 - destination % 8)):
if board[destination + (i+1)] == "R":
origin = destination + (i+1)
break
elif board[destination + (i+1)] == " ":
pass
else:
break
movingPiece = "R"
if notation == "0-0" or notation == "O-O":
if player == 0:
board[6] = "k"
board[5] = "r"
board[7] = " "
board[4] = " "
if player == 1:
board[62] = "K"
board[61] = "R"
board[63] = " "
board[60] = " "
elif notation == "0-0-0" or notation == "O-O-O":
if player == 0:
board[2] = "k"
board[3] = "r"
board[0] = " "
board[4] = " "
if player == 1:
board[58] = "K"
board[59] = "R"
board[56] = " "
board[60] = " "
else:
board[destination] = movingPiece
board[origin] = " "
def showScreen():
print(" ---------------------------------")
print(" | | | | | | | | |")
print("8| " + board[56] + " | " + board[57] + " | " + board[58] + " | " + board[59] +
" | " + board[60] + " | " + board[61] + " | " + board[62] + " | " + board[63] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" | | | | | | | | |")
print("7| " + board[48] + " | " + board[49] + " | " + board[50] + " | " + board[51] +
" | " + board[52] + " | " + board[53] + " | " + board[54] + " | " + board[55] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" | | | | | | | | |")
print("6| " + board[40] + " | " + board[41] + " | " + board[42] + " | " + board[43] +
" | " + board[44] + " | " + board[45] + " | " + board[46] + " | " + board[47] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" | | | | | | | | |")
print("5| " + board[32] + " | " + board[33] + " | " + board[34] + " | " + board[35] +
" | " + board[36] + " | " + board[37] + " | " + board[38] + " | " + board[39] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" | | | | | | | | |")
print("4| " + board[24] + " | " + board[25] + " | " + board[26] + " | " + board[27] +
" | " + board[28] + " | " + board[29] + " | " + board[30] + " | " + board[31] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" | | | | | | | | |")
print("3| " + board[16] + " | " + board[17] + " | " + board[18] + " | " + board[19] +
" | " + board[20] + " | " + board[21] + " | " + board[22] + " | " + board[23] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" | | | | | | | | |")
print("2| " + board[8] + " | " + board[9] + " | " + board[10] + " | " + board[11] +
" | " + board[12] + " | " + board[13] + " | " + board[14] + " | " + board[15] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" | | | | | | | | |")
print("1| " + board[0] + " | " + board[1] + " | " + board[2] + " | " + board[3] +
" | " + board[4] + " | " + board[5] + " | " + board[6] + " | " + board[7] + " |")
print(" | | | | | | | | |")
print(" ---------------------------------")
print(" a b c d e f g h ")
introScreen()
showScreen()
while 1 == 1:
calculateInput()
player = (player + 1) % 2
showScreen()
|
b56702721038d25c4cc494a2c032dc588accfd61 | betty29/code-1 | /recipes/Python/286221_Temp_changer/recipe-286221.py | 1,160 | 4.09375 | 4 | # Temp changer by Josh Bailey (Riddle)
# July 10 '04
def print_options():
print "Options:"
print " 'p' print options"
print " 'c' convert celsius to fahrenheit"
print " 'f' convert fahrenheit to celsius"
print " 'k' convert celsius to kelvin"
print " 'x' convert fahrenheit to kelvin"
print " 'q' quit the program"
def celsius_to_fahrenheit(c_temp):
return (9.0/5.0*c_temp+32)
def fahrenheit_to_celsius(f_temp):
return (f_temp - 32.0)*5.0/9.0
def celsius_to_kelvin(k_temp):
return (temp + 273)
def fahrenheit_to_kelvin(k_temp2):
return (temp -32.0)*5.0/9.0 + 273
choice = "p"
while choice != "q":
if choice == "c":
temp = input("Celsius temp:")
print "Fahrenheit:",celsius_to_fahrenheit(temp)
elif choice == "f":
temp = input("Fahrenheit temp:")
print "Celsius:",fahrenheit_to_celsius(temp)
elif choice == "k":
temp = input ("Celsius temp:")
print "Kelvin:",celsius_to_kelvin(temp)
elif choice == "x":
temp = input ("Fahrenheit temp:")
print "Kelvin:",fahrenheit_to_kelvin(temp)
elif choice != "quit":
print_options()
choice = raw_input("option:")
|
a869bf434b9da79eb92a4209db6b163a8a106c79 | betty29/code-1 | /recipes/Python/577642_Mandelbrot_trajectories/recipe-577642.py | 1,571 | 3.890625 | 4 | """An interactive graph to plot the trajectory of points on and off the mandelbrot
set. Illustrates the use of sliders in matplotlib"""
import pylab
from matplotlib.widgets import Slider
def compute_trajectory(x0, y0, set_boundary = 2, n_iters = 100):
"""Take the fragment and compute a further n_iters iterations for each element
that has not exceeded the bound. Also indicate if we are inside or outside the
mandelbrot set"""
set = True
C = complex(x0, y0)
Z = pylab.ones(n_iters,'complex')*C
for n in range(n_iters-1):
if abs(Z[n]) > set_boundary:
Z[n+1:] = Z[n]
set = False
break
Z[n+1] = Z[n]*Z[n] + C
return Z, set
axcolor = 'lightgoldenrodyellow'
ax_x = pylab.axes([0.1, 0.04, 0.8, 0.03], axisbg=axcolor)
ax_y = pylab.axes([0.1, 0.01, 0.8, 0.03], axisbg=axcolor)
sx = Slider(ax_x, 'x', -1.0, 1.0, valinit=0)
sy = Slider(ax_y, 'y', -1.0, 1.0, valinit=0)
ax_plot = pylab.axes([0.12, 0.12, 0.85, 0.85])
Z,s = compute_trajectory(0,0)
l, = pylab.plot(Z.real, Z.imag,'.-') #Ain't that cool?
st, = pylab.plot(Z[0].real, Z[0].imag,'ok')
pylab.setp(ax_plot,'xlim',[-1,1], 'ylim', [-1,1])
#pylab.axis('scaled')
m_set = [[0],[0]]
ms, = pylab.plot(m_set[0], m_set[1],'k.')
def update(val):
x = sx.val
y = sy.val
Z, set = compute_trajectory(x,y)
l.set_xdata(Z.real)
l.set_ydata(Z.imag)
st.set_xdata(Z[0].real)
st.set_ydata(Z[0].imag)
if set:
m_set[0] += [x]
m_set[1] += [y]
ms.set_xdata(m_set[0])
ms.set_ydata(m_set[1])
pylab.draw()
sx.on_changed(update)
sy.on_changed(update)
|
a32ed5c9906f8e2d913c5067c4d5c727b090a55e | betty29/code-1 | /recipes/Python/118845_Loop_over_descend_insequences/recipe-118845.py | 6,824 | 4.0625 | 4 | def iterable( x, strict = 0 ):
"""Return true if +x+ allows application of the +in+ operator (which excludes, for example,
numbers and +None+), *and* the +in+ loop is actually entered into (excluding sequences of
length zero). If +strict+ is true, an affirmative answer is furthermore subject to the
condition that the first element retrieved within an +in+ loop be not equal to the thing
being iterated over, which excludes strings of length one. -- Used by +walk()+ and
+flatten()+."""
try:
for element in x:
if strict:
return element != x
return 1
except TypeError:
pass
return 0
class RecursiveContent:
"""Wrapper class for content classed as displaying recursive behavior. The original content
is available as ~+.data+. Given content +foo+ that prints a symbolic representation like,
say, +^blah$+, the representation +`RecursiveContent(foo)+ is +^...$+, ie, the surround
characters are kept, while the inner part is replaced by a typographical ellipsis. This is
somewhat compatible with the way Python symbolizes a recursive list. -- Used by +walk()+
and +flatten()+."""
def __init__( self, data ): self.data = data
def __call__( self ): return self.data
def __repr__( self ): return '%s...%s' % ( `self.data`[0], `self.data`[-1] )
def __iter__( self ): return iter( self.data )
def walk( seq, descend = ( list, tuple ), ancestry = None ):
"""This function provides a convenient and recursion-proof way to iterate over arbitrary
data (which is a surprisingly involved task). +seq+ may be anything accepting the
application of the +in+ operator; +descend+ should either be a sequence of types that will
be descended into, or a function that decides, when called with a sequence element as
argument, whether to descend into that element or not. +ancestry+ is an argument used by
+walk()+ for internal bookkeeping (but you can manipulate it for special effects). -- Note
that +descend+ is only checked when trying to decide whether to descend into *elements* of
the sequence given, not when iterating over the sequence itself. Hence, if you pass a tuple
but specify that only lists should be descended into, the outermost sequence will still be
analyzed into elements. For example::
seq = ( 0, 1, 2, [ 3, 4 ], 5, ( 6, 7 ), 8 )
for e in walk( seq, ( list, ) ):
print e,
will print ::
0 1 2 3 4 5 (6, 7) 8
onto the screen. It is possible to pass +str+ as an element in +descend+, which will split
strings into characters, so the results of ::
walk( ( 0, 'abc', 1 ), ( str, ) )
and
walk( ( 0, 'a', 'b', 'c', 1 ) )
become indistinguishable.
Note that data whose type appears in +descend+ but which are inherently non-iterable will
simply be absent from the result. This is logical since iterables whose types are listed in
+descend+ but happen to be empty likewise do not leave any trace in the result (since they
don't offer elements to be looped over).
As convenient spin-offs, there are two more functions related to walk: +iterable()+ and
+flatten()+, q.v.
IMPLEMENTATION
==============
The fundamental function is as simple as this::
def walk( seq, descend ):
for element in seq:
if descend( element ):
for subelement in walk( element, descend ):
yield subelement
else:
yield element
However, this definition is not safe if an iterable contains itself as an element. In order
to prevent the function from descending infinitely, we need to keep an account of what
elements we have already come across in the same branch; argument +ancestry+ does exactly
that (it is o.k. to put copies of he same container side by side into another container,
since that does not lead to recursion; we only need check for cases where a container
contains itself). If a recursive element is detected, an instance of +RecursiveContent+ is
returned (that the caller might want to check for). +RecursiveContent+s print out much the
same way Python's standard representation of recursive lists does.
Another difficulty comes with strings: when a string is being iterated over, it yields
characters. Now, a character is simply a string of length one, so once we allow descending
into strings on the ground of their type, we also allow to descend into characters, which
would result in recursion. To prevent this, +walk()+ additionally checks for 'strict
iterability', as defined by function +iterable()+ when called with +strict=1+.
THANKSTO
========
This code was inspired by the posting "Walk a directory tree using a generator" by Tom Good,
http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/105873.
"""
# If descend is not already a function, construct one that
# assumes that descend has been given as a list of types:
_descend = descend
if not callable( _descend ):
_descend = lambda x: type( x ) in descend
# Initialize ancestry:
if ancestry is None: ancestry = []
# Register sequence as ancestor:
ancestry.append( seq )
# Unconditionally loop over all elements in sequence:
for element in seq:
# If element is in ancestry:
if element in ancestry:
yield RecursiveContent( element )
# If element is not in ancestry:
else:
# If element is eligible for descend, see whether to actually descend
# into it, yield it wholly, or don't yield anything:
if _descend( element ):
# If element is eligible and strictly iterable (i.e., not inherently
# recursive and not an empty sequence), descend:
if iterable( element, strict = 1 ):
for subelement in walk( element, descend, ancestry ):
yield subelement
# If element is eligible and not strictly, but at least loosely iterable,
# yield it (because then it is something like a single-character string
# which should not be lost):
elif iterable( element ):
yield element
# If element is not eligible for descend, yield it:
else:
yield element
ancestry.pop()
def flatten( seq, descend = ( list, tuple ) ):
"""Return a list of all the elements that result from an exhaustive +walk()+ over a given
+seq+uence. See +walk()+ for the interpretation of +descend+."""
return [ element for element in walk( seq, descend ) ]
|
492f805832c4ac5701fb21218632d86133323e39 | betty29/code-1 | /recipes/Python/577086_heap_sort/recipe-577086.py | 826 | 3.84375 | 4 | def HeapSort(A):
def heapify(A):
start = (len(A) - 2) / 2
while start >= 0:
siftDown(A, start, len(A) - 1)
start -= 1
def siftDown(A, start, end):
root = start
while root * 2 + 1 <= end:
child = root * 2 + 1
if child + 1 <= end and A[child] < A[child + 1]:
child += 1
if child <= end and A[root] < A[child]:
A[root], A[child] = A[child], A[root]
root = child
else:
return
heapify(A)
end = len(A) - 1
while end > 0:
A[end], A[0] = A[0], A[end]
siftDown(A, 0, end - 1)
end -= 1
if __name__ == '__main__':
T = [13, 14, 94, 33, 82, 25, 59, 94, 65, 23, 45, 27, 73, 25, 39, 10]
HeapSort(T)
print T
|
31afdd5e0fc3e9bd3b18b3f6b23c9dfc2fef6ba5 | betty29/code-1 | /recipes/Python/280500_Console_built_with_Cmd_object/recipe-280500.py | 3,029 | 3.5625 | 4 | ## console.py
## Author: James Thiele
## Date: 27 April 2004
## Version: 1.0
## Location: http://www.eskimo.com/~jet/python/examples/cmd/
## Copyright (c) 2004, James Thiele
import os
import cmd
import readline
class Console(cmd.Cmd):
def __init__(self):
cmd.Cmd.__init__(self)
self.prompt = "=>> "
self.intro = "Welcome to console!" ## defaults to None
## Command definitions ##
def do_hist(self, args):
"""Print a list of commands that have been entered"""
print self._hist
def do_exit(self, args):
"""Exits from the console"""
return -1
## Command definitions to support Cmd object functionality ##
def do_EOF(self, args):
"""Exit on system end of file character"""
return self.do_exit(args)
def do_shell(self, args):
"""Pass command to a system shell when line begins with '!'"""
os.system(args)
def do_help(self, args):
"""Get help on commands
'help' or '?' with no arguments prints a list of commands for which help is available
'help <command>' or '? <command>' gives help on <command>
"""
## The only reason to define this method is for the help text in the doc string
cmd.Cmd.do_help(self, args)
## Override methods in Cmd object ##
def preloop(self):
"""Initialization before prompting user for commands.
Despite the claims in the Cmd documentaion, Cmd.preloop() is not a stub.
"""
cmd.Cmd.preloop(self) ## sets up command completion
self._hist = [] ## No history yet
self._locals = {} ## Initialize execution namespace for user
self._globals = {}
def postloop(self):
"""Take care of any unfinished business.
Despite the claims in the Cmd documentaion, Cmd.postloop() is not a stub.
"""
cmd.Cmd.postloop(self) ## Clean up command completion
print "Exiting..."
def precmd(self, line):
""" This method is called after the line has been input but before
it has been interpreted. If you want to modifdy the input line
before execution (for example, variable substitution) do it here.
"""
self._hist += [ line.strip() ]
return line
def postcmd(self, stop, line):
"""If you want to stop the console, return something that evaluates to true.
If you want to do some post command processing, do it here.
"""
return stop
def emptyline(self):
"""Do nothing on empty input line"""
pass
def default(self, line):
"""Called on an input line when the command prefix is not recognized.
In that case we execute the line as Python code.
"""
try:
exec(line) in self._locals, self._globals
except Exception, e:
print e.__class__, ":", e
if __name__ == '__main__':
console = Console()
console . cmdloop()
|
85934fcbb29a91c86a5a14a6d9f9437634a323ed | betty29/code-1 | /recipes/Python/389202_Series_generator_using_generators_/recipe-389202.py | 1,640 | 3.734375 | 4 | # Simple series generator with
# generators & decorators.
# Author : Anand B Pillai
# Beginning of recipe
def myfunc(**kwds):
def func(f):
# Condition function
cond = kwds['condition']
# Processing function
proc = kwds['process']
# Number of items
num = kwds['number']
x, l = 0, []
for item in f():
if cond and cond(item):
if proc: item=proc(item)
l.append(item)
x += 1
if x==num:
break
return l
return func
def series(condition=None, process=None, number=10):
""" Infinite integer generator """
@myfunc(condition=condition,process=process,number=number)
def wrapper():
x = 1
while 1:
yield x
x += 1
return wrapper
# End of recipe
-----snip-------------snip-------------------------
Examples.
def prime(x):
is_prime=True
for y in range(2,int(pow(x,0.5)) + 1):
if x % y==0:
is_prime=False
break
return is_prime
# Print first 10 prime numbers
print series(condition=prime, process=None, number=10)
[1, 2, 3, 5, 7, 11, 13, 17, 19, 23]
# Print first 10 odd numbers
print series(condition=lambda x: x%2, process=None, number=10)
[1, 3, 5, 7, 9, 11, 13, 15, 17, 19]
# Print squares of first 10 numbers
print series(condition=lambda x: x, process=lambda x: x*x, number=10)
[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# Print a few random numbers
import random
print series(condition=lambda x: x, process=lambda x: random.random(), number=10)
|
25fc1d2d9fe540cc5e2994ac04c875cb40df2f8c | betty29/code-1 | /recipes/Python/334695_PivotCrosstabDenormalizatiNormalized/recipe-334695.py | 2,599 | 4.40625 | 4 | def pivot(table, left, top, value):
"""
Creates a cross-tab or pivot table from a normalised input table. Use this
function to 'denormalize' a table of normalized records.
* The table argument can be a list of dictionaries or a Table object.
(http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621)
* The left argument is a tuple of headings which are displayed down the
left side of the new table.
* The top argument is a tuple of headings which are displayed across the
top of the new table.
Tuples are used so that multiple element headings and columns can be used.
Eg. To transform the list (listOfDicts):
Name, Year, Value
-----------------------
'Simon', 2004, 32
'Russel', 2004, 64
'Simon', 2005, 128
'Russel', 2005, 32
into the new list:
'Name', 2004, 2005
------------------------
'Simon', 32, 128
'Russel', 64, 32
you would call pivot with the arguments:
newList = pivot(listOfDicts, ('Name',), ('Year',), 'Value')
"""
rs = {}
ysort = []
xsort = []
for row in table:
yaxis = tuple([row[c] for c in left])
if yaxis not in ysort: ysort.append(yaxis)
xaxis = tuple([row[c] for c in top])
if xaxis not in xsort: xsort.append(xaxis)
try:
rs[yaxis]
except KeyError:
rs[yaxis] = {}
if xaxis not in rs[yaxis]:
rs[yaxis][xaxis] = 0
rs[yaxis][xaxis] += row[value]
headings = list(left)
headings.extend(xsort)
t = []
#If you want a list of dictionaries returned, use a cheaper alternative,
#the Table class at:
# http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/334621
#and replace the above line with this code:
#t = Table(*headings)
for left in ysort:
row = list(left)
row.extend([rs[left][x] for x in rs[left]])
t.append(dict(zip(headings,row)))
return t
if __name__ == "__main__":
import random
#Build a list of dictionaries
c = "Employee","Year","Month","Value"
d = []
for y in xrange(2003,2005):
for m in xrange(1,13):
for e in xrange(1,6):
d.append(dict(zip(c,(e,y,m,random.randint(10,90)))))
#pivot the list contents using the 'Employee' field for the left column,
#and the 'Year' field for the top heading and the 'Value' field for each
#cell in the new table.
t = pivot(d,["Employee"],["Year"],"Value")
for row in t:
print row
|
3c4478fc451a3428945e3ef2d19def333fddf268 | betty29/code-1 | /recipes/Python/409366_Implementing_Javinner_classes_using/recipe-409366.py | 4,419 | 4.375 | 4 | def testInner():
class Outer:
def __init__(self,x): self.x = x
# if python ever gets class decorators,
# an inner class could be specified as:
#@innerclass
class Inner:
def __init__(self, y): self.y = y
def sum(self): return self.x + self.y
# as of python 2.4
Inner = innerclass(Inner)
outer = Outer('foo')
inner = outer.Inner('bar'); assert inner.sum() == 'foobar'
# outer.x, inner.x, inner.__outer__.x refer to the same object
outer.x = 'moo'; assert inner.sum() == 'moobar'
inner.x = 'zoo'; assert inner.sum() == 'zoobar'
inner.__outer__.x = 'coo'; assert inner.sum() == 'coobar'
# an inner class must be bounded to an outer class instance
try: Outer.Inner('foo')
except AttributeError, e: pass #print e
else: assert False
def testStaticInner():
class Outer:
x = 'foo'
class Nested:
def __init__(self, y): self.y = y
def sum(self): return self.x + self.y
Nested = nestedclass(Nested)
outer = Outer()
nested = Outer.Nested('bar'); assert nested.sum() == 'foobar'
nested.x = 'moo'; assert Outer.x == 'moo' and nested.sum() == 'moobar'
nested.y = 'baz'; assert nested.sum() == 'moobaz'
def innerclass(cls):
'''Class decorator for making a class behave as a Java (non-static) inner
class.
Each instance of the decorated class is associated with an instance of its
enclosing class. The outer instance is referenced implicitly when an
attribute lookup fails in the inner object's namespace. It can also be
referenced explicitly through the property '__outer__' of the inner
instance.
'''
if hasattr(cls, '__outer__'):
raise TypeError('Cannot set attribute "__outer__" in inner class')
class InnerDescriptor(object):
def __get__(self,outer,outercls):
if outer is None:
raise AttributeError('An enclosing instance that contains '
'%s.%s is required' % (cls.__name__, cls.__name__))
clsdict = cls.__dict__.copy()
# explicit read-only reference to the outer instance
clsdict['__outer__'] = property(lambda self: outer)
# implicit lookup in the outer instance
clsdict['__getattr__'] = lambda self,attr: getattr(outer,attr)
def __setattr__(this, attr, value):
# setting an attribute in the inner instance sets the
# respective attribute in the outer instance if and only if
# the attribute is already defined in the outer instance
if hasattr(outer, attr): setattr(outer,attr,value)
else: super(this.__class__,this).__setattr__(attr,value)
clsdict['__setattr__'] = __setattr__
return type(cls.__name__, cls.__bases__, clsdict)
return InnerDescriptor()
def nestedclass(cls):
'''Class decorator for making a class behave as a Java static inner class.
Each instance of the decorated class is associated with its enclosing
class. The outer class is referenced implicitly when an attribute lookup
fails in the inner object's namespace. It can also be referenced
explicitly through the attribute '__outer__' of the inner instance.
'''
if hasattr(cls, '__outer__'):
raise TypeError('Cannot set attribute "__outer__" in nested class')
class NestedDescriptor(object):
def __get__(self, outer, outercls):
clsdict = cls.__dict__.copy()
# explicit read-only reference the outer class
clsdict['__outer__'] = outercls
# implicit lookup in the outer class
clsdict['__getattr__'] = lambda self,attr: getattr(outercls,attr)
def __setattr__(this, attr, value):
# setting an attribute in the inner instance sets the
# respective attribute in the outer class if and only if the
# attribute is already defined in the outer class
if hasattr(outercls, attr): setattr(outercls,attr,value)
else: super(this.__class__,this).__setattr__(attr,value)
clsdict['__setattr__'] = __setattr__
return type(cls.__name__, cls.__bases__, clsdict)
return NestedDescriptor()
if __name__ == '__main__':
testInner()
testStaticInner()
|
6b075ee745165b8a9626364558cd651bee0538f5 | betty29/code-1 | /recipes/Python/579015_Convert_HTML_text_PDF_Beautiful/recipe-579015.py | 1,956 | 3.53125 | 4 | """
HTMLTextToPDF.py
A demo program to show how to convert the text extracted from HTML
content, to PDF. It uses the Beautiful Soup library, v4, to
parse the HTML, and the xtopdf library to generate the PDF output.
Beautiful Soup is at: http://www.crummy.com/software/BeautifulSoup/
xtopdf is at: https://bitbucket.org/vasudevram/xtopdf
Guide to using and installing xtopdf: http://jugad2.blogspot.in/2012/07/guide-to-installing-and-using-xtopdf.html
Author: Vasudev Ram - http://www.dancingbison.com
Copyright 2015 Vasudev Ram
"""
import sys
from bs4 import BeautifulSoup
from PDFWriter import PDFWriter
def usage():
sys.stderr.write("Usage: python " + sys.argv[0] + " html_file pdf_file\n")
sys.stderr.write("which will extract only the text from html_file and\n")
sys.stderr.write("write it to pdf_file\n")
def main():
# Create some HTML for testing conversion of its text to PDF.
html_doc = """
<html>
<head>
<title>
Test file for HTMLTextToPDF
</title>
</head>
<body>
This is text within the body element but outside any paragraph.
<p>
This is a paragraph of text. Hey there, how do you do?
The quick red fox jumped over the slow blue cow.
</p>
<p>
This is another paragraph of text.
Don't mind what it contains.
What is mind? Not matter.
What is matter? Never mind.
</p>
This is also text within the body element but not within any paragraph.
</body>
</html>
"""
pw = PDFWriter("HTMLTextTo.pdf")
pw.setFont("Courier", 10)
pw.setHeader("Conversion of HTML text to PDF")
pw.setFooter("Generated by xtopdf: http://slid.es/vasudevram/xtopdf")
# Use method chaining this time.
for line in BeautifulSoup(html_doc).get_text().split("\n"):
pw.writeLine(line)
pw.savePage()
pw.close()
if __name__ == '__main__':
main()
|
a2e8e4bc7ec3c702eca1668891cfe72ea1a70113 | betty29/code-1 | /recipes/Python/502260_Parseline_break_text_line_informatted/recipe-502260.py | 1,089 | 4.1875 | 4 | def parseline(line,format):
"""\
Given a line (a string actually) and a short string telling
how to format it, return a list of python objects that result.
The format string maps words (as split by line.split()) into
python code:
x -> Nothing; skip this word
s -> Return this word as a string
i -> Return this word as an int
d -> Return this word as an int
f -> Return this word as a float
Basic parsing of strings:
>>> parseline('Hello, World','ss')
['Hello,', 'World']
You can use 'x' to skip a record; you also don't have to parse
every record:
>>> parseline('1 2 3 4','xdd')
[2, 3]
>>> parseline('C1 0.0 0.0 0.0','sfff')
['C1', 0.0, 0.0, 0.0]
"""
xlat = {'x':None,'s':str,'f':float,'d':int,'i':int}
result = []
words = line.split()
for i in range(len(format)):
f = format[i]
trans = xlat.get(f)
if trans: result.append(trans(words[i]))
if len(result) == 0: return None
if len(result) == 1: return result[0]
return result
|
adc238c067b9ea0c37b9116f00a0d69ae87e041e | betty29/code-1 | /recipes/Python/534137_Generate_Regular_ExpressiMatch_Arbitrary/recipe-534137.py | 4,356 | 4.21875 | 4 | #GPL3
def regex_for_range(min,max):
"""A recursive function to generate a regular expression that matches
any number in the range between min and max inclusive.
Usage / doctests:
>>> regex_for_range(13,57)
'4[0-9]|3[0-9]|2[0-9]|1[3-9]|5[0-7]'
>>> regex_for_range(1983,2011)
'200[0-9]|199[0-9]|198[3-9]|201[0-1]'
>>> regex_for_range(99,112)
'99|10[0-9]|11[0-2]'
Note: doctests are order sensitive, while regular expression engines don't care. So you may need to rewrite these
doctests if making changes.
"""
#overhead
#assert (max>=min) and (min>=0)
_min,_max=str(min),str(max)
#calculations
if min==max:
return '%s' % str(max)
if len(_max)>len(_min):
#more digits in max than min, so we pair it down into sub ranges
#that are the same number of digits. If applicable we also create a pattern to
#cover the cases of values with number of digits in between that of
#max and min.
re_middle_range=None
if len(_max)>len(_min)+2:
#digits more than 2 off, create mid range
re_middle_range='[0-9]{%s,%s}' % (len(_min)+1,len(_max)-1)
elif len(_max)>len(_min)+1:
#digits more than 1 off, create mid range
#assert len(_min)+1==len(_max)-1 #temp: remove
re_middle_range='[0-9]{%s}' % (len(_min)+1)
#pair off into sub ranges
max_big=max
min_big=int('1'+('0'*(len(_max)-1)))
re_big=regex_for_range(min_big,max_big)
max_small=int('9'*len(_min))
min_small=min
re_small=regex_for_range(min_small,max_small)
if re_middle_range:
return '|'.join([re_small,re_middle_range,re_big])
else:
return '|'.join([re_small,re_big])
elif len(_max)==len(_min):
def naive_range(min,max):
"""Simply matches min, to max digits by position. Should create a
valid regex when min and max have same num digits and has same 10s
place digit."""
_min,_max=str(min),str(max)
pattern=''
for i in range(len(_min)):
if _min[i]==_max[i]:
pattern+=_min[i]
else:
pattern+='[%s-%s]' % (_min[i],_max[i])
return '%s' % pattern
if len(_max)==1:
patterns=[naive_range(min,max)]
else:
#this is probably the trickiest part so we'll follow the example of
#1336 to 1821 through this section
patterns=[]
distance=str(max-min) #e.g., distance = 1821-1336 = 485
increment=int('1'+('0'*(len(distance)-1))) #e.g., 100 when distance is 485
if increment==1:
#it's safe to do a naive_range see, see def since 10's place is the same for min and max
patterns=[naive_range(min,max)]
else:
#create a function to return a floor to the correct digit position
#e.g., floor_digit_n(1336) => 1300 when increment is 100
floor_digit_n=lambda x:int(round(x/increment,0)*increment)
#capture a safe middle range
#e.g., create regex patterns to cover range between 1400 to 1800 inclusive
#so in example we should get: 14[0-9]{2}|15[0-9]{2}|16[0-9]{2}|17[0-9]{2}
for i in range(floor_digit_n(max)-increment,floor_digit_n(min),-increment):
len_end_to_replace=len(str(increment))-1
if len_end_to_replace==1:
pattern='%s[0-9]' % str(i)[:-(len_end_to_replace)]
else:
pattern='%s[0-9]{%s}' % (str(i)[:-(len_end_to_replace)],len_end_to_replace)
patterns.append(pattern)
#split off ranges outside of increment digits, i.e., what isn't covered in last step.
#low side: e.g., 1336 -> min=1336, max=1300+(100-1) = 1399
patterns.append(regex_for_range(min,floor_digit_n(min)+(increment-1)))
#high side: e.g., 1821 -> min=1800 max=1821
patterns.append(regex_for_range(floor_digit_n(max),max))
return '|'.join(patterns)
else:
raise ValueError('max value must have more or the same num digits as min')
|
486e319264ee6470f902c3dd3240f614d06dff83 | betty29/code-1 | /recipes/Python/498090_Finding_value_passed_particular_parameter/recipe-498090.py | 1,180 | 4.125 | 4 | import inspect
def get_arg_value(func, argname, args, kwargs):
"""
This function is meant to be used inside decorators, when you want
to find what value will be available inside a wrapped function for
a particular argument name. It handles positional and keyword
arguments and takes into account default values. For example:
>>> def foo(x, y): pass
...
>>> get_arg_value(foo, 'y', [1, 2], {})
2
>>> get_arg_value(foo, 'y', [1], {'y' : 2})
2
>>> def foo(x, y, z=300): pass
...
>>> get_arg_value(foo, 'z', [1], {'y' : 2})
300
>>> get_arg_value(foo, 'z', [1], {'y' : 2, 'z' : 5})
5
"""
# first check kwargs
if argname in kwargs:
return kwargs[argname]
# OK. could it be a positional argument?
regargs, varargs, varkwargs, defaults=inspect.getargspec(func)
if argname in regargs:
regdict=dict(zip(regargs, args))
if argname in regdict:
return regdict[argname]
defaultdict=dict(zip(reversed(regargs), defaults))
if argname in defaultdict:
return defaultdict[argname]
raise ValueError("no such argument: %s" % argname)
|
7d5a36a2027da142a84b5d0c6f5db2478323cd85 | betty29/code-1 | /recipes/Python/303176_Very_simple_accountants/recipe-303176.py | 1,141 | 3.75 | 4 | """A *very* simple command-line accountant's calculator.
Uses the decimal package (introduced in Python 2.4) for calculation accuracy.
Input should be a number (decimal point is optional), an optional space, and an
operator (one of /, *, -, or +). A blank line will output the total.
Inputting just 'q' will output the total and quit the program.
"""
import decimal
import re
parse_input = re.compile(r'(?P<num_text>\d*(\.\d*)?)\s*(?P<op>[/*\-+])')
total = decimal.Decimal('0')
total_line = lambda val: ''.join(('=' * 5, '\n', str(val)))
while True:
tape_line = raw_input()
if not tape_line:
print total_line(total)
continue
elif tape_line is 'q':
print total_line(total)
break
try:
num_text, space, op = parse_input.match(tape_line).groups()
except AttributeError:
raise ValueError("invalid input")
num = decimal.Decimal(num_text)
if op is '/':
total /= num
elif op is '*':
total *= num
elif op is '-':
total -= num
elif op is '+':
total += num
else:
raise ValueError("unsupported operator: %s" % op)
|
b76a13dd2ab92f0b5adf0c3bfb687af02f6cc42e | betty29/code-1 | /recipes/Python/577881_Equallyspaced_floats_part_2/recipe-577881.py | 716 | 3.84375 | 4 | from fractions import Fraction
def spread(count, start, end=None, step=None, mode=1):
if end is step is None:
raise TypeError('one of end or step must be given')
if not isinstance(mode, int):
raise TypeError('mode must be an int')
if count != int(count):
raise ValueError('count must be an integer')
elif count <= 0:
raise ValueError('count must be positive')
if mode & 1:
yield start
if end is None:
step = Fraction(step)
end = start + count*step
else:
step = Fraction(end-start)/count
start = Fraction(start)
for i in range(1, count):
yield float(start + i*step)
if mode & 2:
yield float(end)
|
19f7c5819c452ef66fdf93a4b891ae6f96a060d9 | betty29/code-1 | /recipes/Python/577879_Create_nested_dictionary/recipe-577879.py | 468 | 3.640625 | 4 | import os
def get_directory_structure(rootdir):
"""
Creates a nested dictionary that represents the folder structure of rootdir
"""
dir = {}
rootdir = rootdir.rstrip(os.sep)
start = rootdir.rfind(os.sep) + 1
for path, dirs, files in os.walk(rootdir):
folders = path[start:].split(os.sep)
subdir = dict.fromkeys(files)
parent = reduce(dict.get, folders[:-1], dir)
parent[folders[-1]] = subdir
return dir
|
bf4bc714f53aed7e723ca14ba94a7e5c2e325b41 | betty29/code-1 | /recipes/Python/496885_String_InterpolatiEvaluatiEmbedded/recipe-496885.py | 864 | 3.9375 | 4 | class InterpolationEvaluationException(KeyError):
pass
class expression_dictionary(dict):
def __getitem__(self, key):
try:
return dict.__getitem__(self, key)
except KeyError:
try:
return eval(key,self)
except Exception, e:
raise InterpolationEvaluationException(key, e)
# ---------- Usage ---------------
# Evaluate expressions in the context of a dictionary...
>>> my_dict = {'x': 1, 'y': 2}
>>> print "The sum of %(x)s and %(y)s is %(x+y)s" % expression_dictionary(my_dict)
The sum of 1 and 2 is 3
# or use in conjunction with locals() or globals() to evaluate in a namespace.
>>> ft = 14410.0
>>> ns = expression_dictionary(locals())
>>> print " Summit altitude: %(ft)0.1f feet (%(ft * 0.3048)0.1f meters)" % ns
Summit altitude: 14410.0 feet (4392.2 meters)
|
81294b5b25c8dfa8bdcf7ae41b8f6580d4ed8791 | betty29/code-1 | /recipes/Python/580611_Batch_download_all_pinned_pictures_your/recipe-580611.py | 1,109 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
Batch download all the pinned pictures in your Pinterest board to a local folder.
Be noted: you have to keep your internet browser signed in your Pinterest account first.
Please contact me @ alfred.hui.wong@gmail.com if any question
@author: awang
"""
URL_PinterestBoard=input("Please enter your Pinterest board url starting with Http:// ")
from tkinter import filedialog
Folder_saved=filedialog.askdirectory(title="Select a local folder where you want to put all the pinned pictures")
from lxml import html
import requests
page=requests.get(URL_PinterestBoard)
tree=html.fromstring(page.content)
pins=tree.xpath('//div[@class="pinHolder"]//@href')
del page, tree
import requests, bs4
import urllib
n=1
for singlePin in pins:
page=requests.get('http://www.pinterest.com'+singlePin)
page_soup=bs4.BeautifulSoup(page.text,"lxml")
page_element=page_soup.select('img[src]')
image_address=page_element[0].attrs['src']
resource=urllib.request.urlopen(image_address)
output=open(Folder_saved+"/"+"Image"+str(n)+".jpg","wb")
output.write(resource.read())
output.close()
n=n+1
|
e7cf5641a3e65dbfc5e7cdafdc566c34e469f3ef | betty29/code-1 | /recipes/Python/387776_Grouping_objects_indisjoint/recipe-387776.py | 1,757 | 4.0625 | 4 | class Grouper(object):
"""This class provides a lightweight way to group arbitrary objects
together into disjoint sets when a full-blown graph data structure
would be overkill.
Objects can be joined using .join(), tested for connectedness
using .joined(), and all disjoint sets can be retreived using
.get().
The objects being joined must be hashable.
For example:
>>> g = grouper.Grouper()
>>> g.join('a', 'b')
>>> g.join('b', 'c')
>>> g.join('d', 'e')
>>> list(g.get())
[['a', 'b', 'c'], ['d', 'e']]
>>> g.joined('a', 'b')
True
>>> g.joined('a', 'c')
True
>>> g.joined('a', 'd')
False"""
def __init__(self, init=[]):
mapping = self._mapping = {}
for x in init:
mapping[x] = [x]
def join(self, a, *args):
"""Join given arguments into the same set.
Accepts one or more arguments."""
mapping = self._mapping
set_a = mapping.setdefault(a, [a])
for arg in args:
set_b = mapping.get(arg)
if set_b is None:
set_a.append(arg)
mapping[arg] = set_a
elif set_b is not set_a:
if len(set_b) > len(set_a):
set_a, set_b = set_b, set_a
set_a.extend(set_b)
for elem in set_b:
mapping[elem] = set_a
def joined(self, a, b):
"""Returns True if a and b are members of the same set."""
mapping = self._mapping
try:
return mapping[a] is mapping[b]
except KeyError:
return False
def __iter__(self):
"""Returns an iterator returning each of the disjoint sets as a list."""
seen = set()
for elem, group in self._mapping.iteritems():
if elem not in seen:
yield group
seen.update(group)
|
f15d9fdb5bd40bfa44342919598f3df07340b086 | J-Cook-jr/python-dictionaries | /hotel.py | 334 | 4.125 | 4 | # This program creates a dictionary of hotel rooms and it's occupants.
# Create a dictionary that lists the room number and it's occupants.
earlton_hotel ={
"Room 101" : "Harley Cook",
"Room 102" : "Mildred Tatum",
"Room 103" : "Jewel Cook",
"Room 104" : "Tiffany Waters",
"Room 105" : "Dejon Waters"
}
print(earlton_hotel) |
e9006fa66e4d3ca6b25fddca8166c62634cf5faf | mentishinov/PythonPY1001 | /Занятие1/Домашнее_задание/task3/main.py | 219 | 3.828125 | 4 | n1 = int(input('Введите первое число: '))
n2 = int(input('Введите второе число: '))
n3 = int(input('Введите третье число: '))
list_ = (n1, n2, n3)
print(min(list_))
|
d7813aa043d0c6d1283c8e2c1028a3c7ab3ad431 | pani-ps1/my-practice-1-python | /20. in between.py | 313 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Sep 28 20:29:05 2020
@author: utob
"""
name = "some thing really long"
if len(name) < 3:
print("name must be at least 3 characters")
elif len (name) > 50:
print("name must be a maximum of 50 characters")
else:
print("name looks good!")
|
8874db6466208411d5a0d485b0a35ab862cfbcdc | pani-ps1/my-practice-1-python | /13.Comparison Operators Example.py | 484 | 3.8125 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Sep 9 17:39:17 2020
@author: utob
"""
a=9
b=4
print("the output of 9 > 4 is:",a>b)
print("the output of 9 < 4 is :",a<b)
print("the output of 9<=4 is: ",a<=b)
print("the output of 9>=4 is:",a>=b)
print("the output of 9 equal to 4 is:",a==b)
print("the output of 9 not equal to is:",a!=b)
x=10
y=25
if x>=y:
print("x value is greater than or equal to y")
else:
print("x value is less than or equal to y")
|
c27d42ecdf247610107765448f78297cbb2b1981 | pani-ps1/my-practice-1-python | /29.2d LISTS.py | 265 | 3.921875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Tue Sep 29 11:28:24 2020
@author: utob
"""
matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
#matrix[0][1]=20
#print(matrix[0][1])
#
for row in matrix:
for item in row:
print(item)
|
a681baddbe9c79f26571dbdcaf2c9d623330cc75 | pani-ps1/my-practice-1-python | /3.perimeter triangle tamrin sevom.py | 362 | 4 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sat Sep 5 18:01:23 2020
@author: utob
"""
#wrighting the area of the rectangle#
langth = float (input ("please enter the langth:"))
width = float (input ("please enter the width:"))
#caculating the area#
perimeter =2*(langth +width)
print("the number of perimeter is:",langth,"+",width,"=",perimeter)
|
9e36ae2e9d9c54c8ab28e726a45f03684010aacb | DanielSherlock/CryptoLib | /Atbash.py | 2,155 | 3.609375 | 4 |
from SimpleSub import (SimpleSub,
simplesub,
SIMPLESUB,
default_alphabet,
default_ignore,
default_remove)
class Atbash(SimpleSub):
'''Generic, Atbash-cipher-related, piece of text
'''
def reverse_alphabet(self, alphabet):
'''Return Type: Data
Returns own alphabet, reversed.
'''
result = ""
for i in range(len(alphabet)):
result += alphabet[- (i + 1)]
return result
class atbash(simplesub, Atbash):
'''A piece of text that will become an atbash cipher.
'''
def __init__(self, plaintext = '', key = False,
alphabet = default_alphabet.lower(),
ignore = default_ignore,
remove = default_remove):
super(atbash, self).__init__(plaintext, key,
alphabet, alphabet,
ignore, remove,)
def update_alphabets(self):
'''Return Type: MUTATES/None
Updates the alphabets, according to the key.
Also ensures that crypto-convention is followed.
'''
self.alphabet = self.do_remove(self.alphabet.lower())
self.cipher_alphabet = self.reverse_alphabet(self.alphabet).upper()
class ATBASH(SIMPLESUB, Atbash):
'''A piece of text that is an encrypted atbash cipher.
'''
def __init__(self, ciphertext = '', key = False,
alphabet = default_alphabet.lower(),
ignore = default_ignore,
remove = default_remove):
super(ATBASH, self).__init__(ciphertext, key,
alphabet, alphabet,
ignore, remove)
def update_alphabets(self):
'''Return Type: MUTATES/None
Updates the alphabets, according to the key.
Also ensures that crypto-convention is followed.
'''
self.plain_alphabet = self.do_remove(self.plain_alphabet.lower())
self.alphabet = self.reverse_alphabet(self.plain_alphabet).upper()
|
d115b6328db43b3819e6f6ee4b934470b255da00 | hamzzy/tkinter | /contact.py | 1,261 | 3.640625 | 4 | from Tkinter import *
import ttk
win = Tk() # Create instance
win.title("Python GUI") # Add a title
tabControl = ttk.Notebook(win) # Create Tab Control
tab1 = ttk.Frame(tabControl) # Create a tab
tabControl.add(tab1, text='Tab 1') # Add the tab
tabControl.pack(expand=1, fill="both") # Pack to make visible
def post():
val=vul.get()
fall=fell.get()
well=feel.get()
listbox.insert(END,val+" "+well+"---------"+"+234"+str(fall))
listbox.delete(END,val+" "+well+"---------"+"+234"+str(fall))
fell=IntVar()
vul=StringVar()
feel=StringVar()
win.config(background="orange")
lb=Label(tab1,text="NAME:").pack()
e1=Entry(tab1,textvariable=vul,width=50).pack()
lb=Label(tab1,text="SURNAME:").pack()
e3=Entry(tab1,textvariable=feel,width=50).pack()
lb=Label(tab1,text="NAME:").pack()
e2=Entry(tab1,textvariable=fell,width=50).pack()
btn=Button(tab1,text="drop",command=post).pack()
scroll=Scrollbar(tab1)
scroll.pack(side=RIGHT,fill=Y)
listbox=Listbox(tab1)
listbox.config(yscrollcommand=scroll.set)
listbox.pack(expand=YES,fill=BOTH)
scroll.config(command=listbox.yview)
tab2 = ttk.Frame(tabControl) # Create a tab
tabControl.add(tab2, text='Tab 1') # Add the tab
tabControl.pack(expand=1, fill="both") # Pack to ma
win.mainloop()
|
9bd43abf9d97ed63050466e32250af910545691d | cmp291/mini-project-1 | /cmput291for1.py | 4,218 | 3.90625 | 4 | import sqlite3
import sys
conn = sqlite3.connect(":register.db")
cursor = conn.cursor()
def check_location(locode):
#This function is used to return a location code,
# if it is not a location code, your system should return all locations that have the keyword as a substring in city, province or address fields
# If there are more than 5 matching locations, at most 5 matches will be shown at a time, letting the member select a location or see more matches.
# try to find the matched location code
try:
cursor.execute('select lcode from locations where locations.lcode = ?',locode)
result = cursor.fetchall()
if result is not None:
return result
except:
print("Error in sql 2")
# try to find the matched substrings in city , prov, address
try:
cursor.execute('select city from locations where city like %?%', locode)
resultcity = cursor.fetchall()
cursor.execute('select prov from locations where prov like %?%', locode)
resultprov = cursor.fetchall()
cursor.execute('select address from locations where address like %?%', locode)
resultadd = cursor.fetchall()
totalresult = resultcity + resultprov + resultadd
if not totalresult:
sys.exit("Error in reading in location")
while True:
for iterm in range(0, len(totalresult)):
# after showing the first five elements, let user select
if iterm == 5:
choose = input("Select a location or enter 1 to see more matches")
if choose != 1:
return choose
print(totalresult[iterm], ',')
except:
print("Error in sql 3")
def offeraride(email):
entered1 = input("Please enter the car number(optional) Enter 'Log out' if you want to quit:")
#log out option
if entered1 == 'Log out':
sys.exit("Log out successfully")
#if the user enters a car number, check its belonger
if entered1 is not None:
try:
cursor.execute('select email from members, cars where members.email = cars.owner and cars.cno = ?;',entered1)
result = cursor.fetchall()
if result != email:
print("Sorry. This car does not belong to you")
except:
print("Error in offeraride")
noseats = input("Please enter the number of seats offered. Enter 'Log out' if you want to quit: ")
if noseats == 'Log out':
sys.exit("Log out successfully")
noseats = int(noseats)
price = input("Please enter the price per seat,Enter 'Log out' if you want to quit:")
if price == 'Log out':
sys.exit("Log out successfully")
price = int(price)
date = input("Please enter the date by using format year-month-day.Enter 'Log out' if you want to quit: ")
if date == 'Log out':
sys.exit("Log out successfully")
luggage_description = input("Please enter a luggage description. Enter 'Log out' if you want to quit: ")
if luggage_description == 'Log out':
sys.exit("Log out successfully")
sourcelo = input("Please enter a source location. Enter 'Log out' if you want to quit: ")
if sourcelo == 'Log out':
sys.exit("Log out successfully")
else:
return_sourcelo = check_location(sourcelo)
destinationlo = input("Please enter a destination location. Enter 'Log out' if you want to quit: ")
if destinationlo == 'Log out':
sys.exit("Log out successfully")
else:
returndestinationlo = check_location(destinationlo)
# enroute = input("Please enter an enroute location by one space (optional): ")
# do not know how to deal with enroute locode and
#if not enroute:
#enroute1 = enroute[0] + enroute[1] + enroute[2]
#return_sourcelo = check_location(enroute1)
#enroute2 = enroute[4] + enroute[5] + enroute[6]
#returndestinationlo = check_location(enroute2)
cursor.execute("insert into rides values ('%%d','%%d', '%%s', '%%d', '%%s', '%%s', '%%s', '%%s','%%d')" % (None, price, date, noseats,return_sourcelo, returndestinationlo,email, entered1))
|
e61a6994596a466b8c09e11cf0db4716b3f625e9 | federicobortolato/Python---Projects | /TEXT GAME PROJECT/the_game_mechanics.py | 2,114 | 3.703125 | 4 | #the_game_mechanics
from useful_functions import *
from startup import base_game_mechanics
class The_game(base_game_mechanics):
def check_sex(self):
while True:
sex = input('\n-Are you male[m] or female[f]-?\n')
sexes = ['m','f']
types = ['boy','girl']
if sex.lower().strip() in sexes:
okay = input(stringy(f'-So you are a {types[sexes.index(sex)]}[y/n]?-'))
if okay == 'y':
return sex
elif okay == 'n':
print(stringy("-Are you kidding me?-"))
pass
else:
print(stringy('-Come oon...I won\'t eat you...-'))
pass
def check_name(self):
name = input(stringy("-What's your name?-"))
alf = 'abcdefghijklmnopqrstuvwxyz '
for i in name:
if i.lower() not in alf:
print("\n-I'm sure that's not your name, tell me what your name truly is! [only alphabet letters]\nSo...-\n")
name = self.check_name()
break
else:
pass
return name
def night_save(self , data = None):
while True:
alert = input(stringy("[It's night and you are sleeping like a child. Well, in fact, you are one. \
Anyway, would you like to save?[y/n] You may lose your game data otherwise. ]"))
if alert.lower() == 'y':
self.saving(data)
break
elif alert.lower() == 'n':
prints('You take your own risks')
break
else:
prints('Invalid input.')
pass
while True:
alert = input(stringy('[Would you prefer to sleep[s] till dawn or to exit[e] the game for a while?]'))
if alert.lower() == 's':
break
elif alert.lower() == 'e':
self.quit()
else:
prints('Invalid input.')
pass
|
34a01f23a29daf7b6d971dce96fc8feb170c2eb1 | cczhouhaha/data_structure | /1009数组,栈/数组相关操作.py | 3,595 | 3.75 | 4 | #在原数组去重
from typing import List
# 删除的思想:向前移动或向后移动(进行替换)
# =====有序数组去重======
#有序数组去重,返回新数组长度
nums1 = [0,0,1,1,2,2,3,4,5]
# #方案一:利用去重以及切片
def remove_re(nums:List) -> int:
n = len(set(nums)) #去重后的数组长度
i = 0
while i < n-1:
if nums[i] == nums[i+1]:
temp = nums[i+1]
nums[i+1:len(nums)-1] = nums[i+2:] # 利用切片将数组内的元素进行替换,但不影响原数组未进行替换的元素
nums[-1] = temp # 数组最后一位重新赋值
else:
i += 1
return i + 1
##方案二:双指针 快慢指针
#有序数组去重,返回新数组长度
# 快指针:找到和慢指针不同的元素,无论是否相同都要往前走一步
nums2 = [0,0,1,1,2,2,3,4,5]
def remove_deplicate(nums:List) ->int:
slow = 0
fast = 1
while fast < len(nums):
if nums[slow] == nums[fast]:
fast += 1
else:
# 先走一步,在进行交换.
slow += 1 #slow与fast之间最多差一个相同的值,必须先向前走一步,在进行替换.让其走到第二个重复元素.
nums[slow] = nums[fast]
fast += 1
return slow + 1 #fast从1开始,共走len-1步, 因此在返回长度时,slow需要加1
##=====将值0移动到末尾========
nums3 = [0,0,0,1,1,2,2,3,4,5,4,3,0,5]
# #方案一:利用切片将元组替换 (如果首位是0 会有问题)
value = 0
# def move_value(nums:List):
# fast = 0
# # slow = 0
# while fast < len(nums):
# if nums[fast] != value:
# fast += 1
# else:
# nums[fast:len(nums)-1] = nums[fast+1:]
# nums[-1] = value
# fast += 1
# return nums
# #方案二:利用双指针
## 快指针找到非0元素
# 移动0,将0 移动到最后
def move_value(nums:List):
fast = 0
slow = 0
while fast < len(nums):
if nums[fast] == value:
fast += 1
else:
# 一定要先交换,slow后移动(因为交换时nums[slow]一定是0,如果先移动会造成0值不能被替换)
nums[slow] = nums[fast]
slow += 1
fast += 1
for i in range(slow,len(nums)): #fast从0开始,共走len步,因此在返回长度时slow不用加1
nums[i] = value
return nums
##=========删除指定元素===========
# #方案一:快慢双指针
nums4 = [1,1,1,1,2,3,4,5,6,7,5,4,3]
def remove_value(nums:List,value):
fast = 0
slow = 0
while fast < len(nums):
if nums[fast] == value:
fast += 1
else:
nums[slow] = nums[fast]
slow += 1
fast += 1
new_nums = nums[:slow]
return new_nums,slow
# ##=======删除(顺序数组)指定元素,元素个数允许小于等于2=======
nums5 = [1,1,1,2,2,2,3,3,4,5,1,2,1]
def remove_re2(nums:List): #duplication
fast = 1
slow = 0
count = 1
while fast < len(nums):
if nums[fast] == nums[slow]:
count += 1
if count == 2:
slow = slow + 1
nums[slow] = nums[fast]
fast = fast + 1
else:
slow = slow + 1
nums[slow] = nums[fast]
count = 1
fast = fast + 1
return slow + 1,nums[:slow]
print(remove_re(nums1))
# aa = Solution()
# print(aa.remove_deplicate(numsa))
# print(remove_deplicate(nums2))
print(move_value(nums3))
print(remove_value(nums4,1))
print(remove_re2(nums5))
|
f45697cc98af080c7b9f815f253521b211e36faf | cczhouhaha/data_structure | /1006链表/链表测试5.py | 2,166 | 4.03125 | 4 | from typing import List
class Node:
def __init__(self,data,next=None):
self.data = data
self.next = None
def __repr__(self):
return "Node({})".format(self.data)
class linkedlist:
def __init__(self):
self.head = None
def insert_head(self,data):
new_node = Node(data)
if self.head:
new_node.next = self.head
self.head = new_node
def append(self,data):
if self.head:
temp = self.head
while temp.next:
temp = temp.next
temp.next = Node(data)
else:
self.insert_head(data)
def insert_mid(self,p,data):
if self.head is None or p == 1:
self.insert_head(data)
else:
temp = self.head
pre = temp
j = 1
while j <p:
pre = temp
temp = temp.next
j = j+1
node = Node(data)
pre.next = node
node.next = temp
def linklist(self,object:list):
self.head = Node(object[0])
temp = self.head
for i in object[1:]:
temp.next = Node(i)
temp = temp.next
def __repr__(self):
current = self.head
str = ""
while current:
str += "{}-->".format(current)
current = current.next
return str + "End"
def delete_head(self):
temp = self.head
if temp:
self.head = temp.next
def delete_tail(self):
temp = self.head
if temp:
if temp.next is None:
temp = None
else:
while temp.next.next:
temp = temp.next
temp.next = None
else:
print("此为空链表")
#实例对象
link_list = linkedlist()
#调用方法
link_list.insert_head(1)
link_list.insert_head(2)
link_list.insert_head(3)
link_list.insert_head(4)
link_list.append(5)
# 打印输出结果
print(link_list)
link_list.insert_mid(3,8)
print(link_list)
link_list.delete_head()
print(link_list)
link_list.delete_tail()
print(link_list) |
db4989cbb6ed6ca5edb83d0674cbc924b40e9a75 | cczhouhaha/data_structure | /1016堆,优先队列/练习2.py | 4,470 | 3.71875 | 4 | from pprint import pformat
class Node:
def __init__(self,data,parent):
self.data = data
self.parent = parent
self.left = None
self.right = None
def __repr__(self):
if self.left is None and self.right is None:
return str(self.data)
return pformat({"%s"%(self.data):(self.left,self.right)},indent=1)
class BST:
def __init__(self):
self.root = None
def is_empty(self):
if self.root is None:
return True
else:
return False
def __insert(self,data):
new_node = Node(data,None)
if self.is_empty():
self.root = new_node
else:
parent_node = self.root
while True:
if data < parent_node.data:
if parent_node.left is None:
parent_node.left = new_node
break
else:
parent_node = parent_node.left
else:
if parent_node.right is None:
parent_node.right = new_node
break
else:
parent_node = parent_node.right
new_node.parent = parent_node
def insert(self,*values):
for i in values:
self.__insert(i)
def __str__(self):
return str(self.root)
def is_right(self,node):
return node == node.parent.right
def reassign(self,node,new_child):
if new_child is not None:
new_child.parent = node.parent
elif node.parent is not None:
if self.is_right(node):
node.parent.right = new_child
else:
node.parent.left = new_child
else:
self.root = new_child
def search(self,data):
if self.is_empty():
raise Exception("The tree is empty")
else:
node = self.root
while node and data != node.data:
if data < node.data:
node = node.left
else:
node = node.right
return node
def remove(self,data):
node = self.search(data)
if node.left is None and node.right is None:
self.reassign(node,None)
elif node.right is None:
self.reassign(node,node.left)
elif node.left is None:
self.reassign(node,node.right)
else:
temp = self.get_max(node.left)
self.remove(temp.data)
node.data = temp.data
def get_max(self,node):
if node is None:
node = self.root
if not self.is_empty():
while node.right:
node = node.right
return node
#前序遍历
def preOrder(self,node):
if node is None:
return None
else:
print(node.data,end="-->")
self.preOrder(node.left)
self.preOrder(node.right)
def preOrder1(self,node):
stack = [node]
while len(stack) > 0:
print(node.data,end="-->")
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
node = stack.pop()
# 中序遍历
def midOrder(self,node):
if node is None:
return None
else:
self.midOrder(node.left)
print(node.data, end="-->")
self.midOrder(node.right)
def midOrder1(self,node):
stack = []
while node or len(stack)>0:
while node:
stack.append(node)
node = node.left
if len(stack) >0:
node = stack.pop()
print(node.data,end="-->")
node = node.right
# 后序遍历
def postOrder(self,node):
if node is None:
return None
else:
self.postOrder(node.left)
self.postOrder(node.right)
print(node.data,end="-->")
b = BST()
# b.insert(4)
# b.insert(3)
# b.insert(5)
# b.insert(6)
# b.insert(4)
# b.insert(1,2,3,4,5,6)
b.insert(8,3,10,1,6)
print(b)
aa = b.search(8)
print(aa)
# b.remove(3)
# print(b)
#
# b.preOrder(aa)
# print("End")
#
# b.preOrder(b.root)
# print("End")
# b.preOrder1(b.root)
# print("End")
# b.midOrder(b.root)
# print("End")
b.midOrder1(b.root)
print("End")
|
3a5aa812f28a502026dc0f5c1190336768fbe1cb | cczhouhaha/data_structure | /1008链表闭环,数组/test.py | 216 | 3.609375 | 4 | # a = int(input("请输入数字:") )
# if a > 5:
# raise IndexError("数字大于5")
# else:
# print(a)
# print("+++")
a = [1,4,7,3,8]
amin = a[0]
for i in a:
if i < amin:
amin = i
print(amin)
|
bf44d7003cfce950a3002a4bb62d4a91e5d6f0a8 | cczhouhaha/data_structure | /1016堆,优先队列/堆heap.py | 2,352 | 4.1875 | 4 | #堆是完全二叉树,又分为最大堆(根>左右孩子)和最小堆(根<左右孩子)
class Heap:
def __init__(self):
self.data_list = [] #用数组实现
# 得到父节点的下标
def get_parent_index(self,index):
if index < 0 or index >= len(self.data_list):
raise IndexError("The index out of range")
else:
return (index-1) >> 1 #孩子结点坐标(二进制)右移一位得到父节点坐标
def swap(self,child_index,parent_index): #孩子结点与父节点相互交换
self.data_list[child_index],self.data_list[parent_index]=self.data_list[parent_index],self.data_list[child_index]
def insert(self,data):
self.data_list.append(data)
index = len(self.data_list)-1
parent_index = self.get_parent_index(index)
while self.data_list[parent_index] < data and parent_index >= 0: #如果插入数值大于父节点值,进行循环替换操作
self.swap(index,parent_index) #先让两者的值进行交换
index = parent_index #下标进行交换
parent_index = self.get_parent_index(index) #找到新下标的父节点
def __repr__(self):
return str(self.data_list)
def pop(self): #删除堆顶
remove_data = self.data_list[0] #记录要删除的堆顶
self.data_list[0] = self.data_list[-1] #将堆顶的值替换为最后一个元素的值
del self.data_list[-1] #删除最后一个元素的值
self.heapify(0) #然后堆化 (即重新排序)
return remove_data
def heapify(self,index): #堆顶化 即重新排序
size = len(self.data_list)-1 #整个长度的范围
max_index = index #最大值下标max_index
while True:
if 2*index+1 <= size and self.data_list[max_index] < self.data_list[2*index+1]: #如果最大值发生变化,需要进行移位变换
max_index = 2*index+1
if 2*index+2 <= size and self.data_list[max_index] < self.data_list[2*index+2]:
max_index = 2*index+2
if max_index == index:
break
self.swap(index,max_index)
index = max_index
h = Heap()
h.insert(10)
h.insert(7)
h.insert(8)
h.insert(9)
h.insert(6)
print(h)
h.insert(11)
print(h)
h.insert(5)
print(h)
h.pop()
print(h)
|
f4ffec97c560b7f979543f69903254fc6f6cc8fb | bogsio/algos | /strings/rolling_hashes.py | 4,860 | 3.921875 | 4 |
"""
Rolling Hashes & Rabin-Karp
---------------------------
The Rabin-Karp string search algorithm is normally used with a very simple rolling hash function that only
uses multiplications and additions:
H = c_1 a^{k-1} + c_2 a^{k-2} + c_3 a^{k-3} + ... + c_k a^{0} where a is a constant and c_1, ..., c_k are the
input characters.
In order to avoid manipulating huge H values, all math is done modulo n. The choice of a and n is
critical to get good hashing; see linear congruential generator for more discussion.
Caveats:
--------
Hashing collisions are a problem.
One way to deal with them is to check for a match when two fingerprints are equal,
but this makes the solution inefficient if there are lots of matches.
Another way is to use more hashing functions to decrease the collision probability.
"""
import collections
def find(needle, haystack):
"""
Find all occurances of needle in haystack
"""
A = 10 # The constant coefficient
MOD = 29 # Prime number used for modulo
m = len(haystack)
n = len(needle)
if m < n: # precondition
return []
an = 1 # Init a^n as a^0
offsets = [] # results
hash_haystack = 0 # init hashes
hash_needle = 0
for c in needle:
hash_needle = (hash_needle * A + int(c)) % MOD
print 'hash_needle=', hash_needle
# an = 1
for c in haystack[:n]:
hash_haystack = (hash_haystack * A + int(c)) % MOD
an = (an * A) % MOD
print 'hash_haystack=', hash_haystack
if hash_haystack == hash_needle:
print "match, offset=", 0
offsets.append(0)
for i in range(1, m - n + 1):
# Add to the rolling hash the number corresponding to the next char,
# and subtract the number corresponding to the excluded char
hash_haystack = (hash_haystack * A + int(haystack[i + n - 1]) - an * int(haystack[i - 1])) % MOD
print 'hash_haystack=', hash_haystack
if hash_haystack == hash_needle:
print "match, offset=", i
offsets.append(i)
return offsets
def demo_find():
needle = '313'
haystack = '44411311166643134445553313'
print find(needle, haystack)
def common_substring(str_a, str_b):
"""
Longest common substring
------------------------
Given two strings A and B, compute their longest common substring.
Let's solve a simpler problem: Given two strings A and B, and a number X
find if they have a common sequence of length X.
We use the rolling hash technique to find the hash codes for all X length substrings of A and B.
Then we check if there is any common hash code between the two sets,
this means A and B share a sequence of length X.
We then use binary search to find the largest X.
The complexity of this algorithm is O(n log n).
"""
A = 10 # The constant coefficient
MOD = 15485863 # Prime number used for modulo
def _hashes_substrings(string, x):
hashes = collections.defaultdict(list)
# init hash
hash = 0
an = 1
n = len(string)
for c in string[:x]:
hash = (hash * A + ord(c)) % MOD
an = (an * A) % MOD
hashes[hash].append(0)
for i in range(1, n - x + 1):
hash = (hash * A + ord(string[i + x - 1]) - an * ord(string[i - 1])) % MOD
hashes[hash].append(i)
return hashes
len_a = len(str_a)
len_b = len(str_b)
# binary search for X
left, right = 0, min(len_a, len_b) - 1
X = -1
while left < right:
new_X = int(float(left + right) / 2)
if new_X == X:
break
X = new_X
if X == 0:
break
# print 'left=', left, 'right=', right, 'X=', X
hashes_a = _hashes_substrings(str_a, X)
hashes_b = _hashes_substrings(str_b, X)
keys_a = hashes_a.keys()
keys_b = hashes_b.keys()
intersection = set(keys_a) & set(keys_b)
# print intersection
# print [hashes_a[i] for i in intersection]
# print [hashes_b[i] for i in intersection]
if intersection:
left = X
else:
right = X
if intersection:
# print intersection
example = list(intersection)[0]
offset = hashes_a[example][0]
return str_a[offset: offset + X], X
return "", 0
def demo_substring():
print common_substring('alabalaportocala', 'portocalamea')
print common_substring('cccccc', 'bbbbbbbb')
print common_substring('123456789', '987654321')
print common_substring('a1b2c3d4e5f6', 'a1b2d5f6')
print common_substring('11113333222211114444', '111445533322211114444')
if __name__ == "__main__":
demo_find()
demo_substring()
|
2f53c1e3f23a8165774cd539896a404b04a12ef3 | Romyho/Crypto | /Scripts/Python/json_dates.py | 827 | 3.90625 | 4 | #!/usr/bin/env python
# Name:Romy Ho
# Student number:11007303
"""
This script selects specified data from csv and returns json file.
"""
import json
import pandas as pd
import csv
import sys
def convert(file_name):
# Read csv file
csv_name = file_name[0]
df = pd.read_csv(csv_name)
# Load top 100 ranked
top100 = list(range(67420))
df1 = df.loc[top100]
# Select name and first date in dataset
name_date = {}
boolean2 = ''
index = 0
for i in df1.name:
if i != boolean2:
boolean2 = i
name_date[i]= df1['date'][index]
index += 1
# Write json file
with open('name_date.json', 'w') as outfile:
json.dump(name_date, outfile, indent=4)
if __name__ == "__main__":
# Convert csv file to json
convert(sys.argv[1:])
|
3470daf6af664c56302c1f7e5d797363cd9b8129 | dashboardijo/interview | /insert_sort.py | 574 | 3.9375 | 4 | # 插入排序
# 主要思想是每次取一个列表元素与列表中已经排序好的列表段进行比较,然后插入从而得到新的排序好的列表段,最终获得排序好的列表。(debug查看排序步骤)
def insertion_sort(alist):
for index in range(1, len(alist)):
current_num = alist[index]
while index > 0 and current_num < alist[index - 1]:
alist[index] = alist[index - 1]
index -= 1
alist[index] = current_num
test = [90, 41, 22, 38, 13, 77, 29, 32, 62]
insertion_sort(test)
print(test)
|
3643c4ecde099b75984d9a614906219c482fc18b | 7-RED/Numpy | /midterm/9A617042_1.py | 344 | 3.96875 | 4 | year=int(input("輸入西元:"))
month=int(input("月份:"))
day=int(input("日期:"))
if(month>2 and month<9):
print("{0}/{1}/{2}為第二學期".format(year-1912,month,day))
elif(month==1):
print("{0}/{1}/{2}為第一學期".format(year-1912,month,day))
else:
print("{0}/{1}/{2}為第一學期".format(year-1911,month,day))
|
785fe358415d2f7acb48512b1aae17d0f69e9bee | daicotrosama/septiembre_30 | /menu.py | 1,317 | 4.09375 | 4 | #Crear menu con tres opciones:
#1. opcion 1: temperaturas
#2. opcion 2: datos de personas
#3 opcion 3: salir
import os
def Temperaturas():
print("***temperaturas***")
#Ingresar n temperaturas donde n es un numero ingresado por teclado
#mostrar el promerdio de las temperaturas ingresadas
veces=int(input("Cuantas temperaturas necesita ingresar?: "))
for x in range(veces):
tempe=float(input("Digite una temperatura: "))
suma=suma+tempe
print ("El promedio de las temperaturas ingresadas es : " , round((suma/veces),2))
pausa=input("Preione una tecla para continuar")
def Personas():
mayor=0
menor=0
print("*** datos de personas***")
tope=int(input("Cuantas personas ingresaran?"))
for x in range(tope):
n=input("Introduzca su nombre: ")
edad=int(input("Ingrese su edad: "))
if( edad > 18):
mayor +=1
if(edad < 18):
menor+=1
pausa=input("Presione una tecla para continuar")
seguir=True
while(seguir):
os.system('cls')
print("1.Temperaturas")
print("2. datos de personas")
print("3. salir")
op=int(input("Ingrese opcion 1,2,3: "))
if(op==1):
Temperaturas()
elif(op ==2):
Personas()
else:
print("Finalizar")
break |
f6c73845bb30b819a42262e0b5902f47c36dd48a | Jackson-H-Chen/learning_python | /codons.py | 289 | 3.828125 | 4 | #!/usr/bin/env python3
# Print out all the codons for the sequence below in reading frame 1
# Use a 'for' loop
dna = 'ATAGCGAATATCTCTCATGAGAGGGAA'
for i in range(0,len(dna)-3+1,3):
nmer = dna[i:i+3]
print(f'{nmer}')
"""
python3 codons.py
ATA
GCG
AAT
ATC
TCT
CAT
GAG
AGG
GAA
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.