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 f...
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__ == '...
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 pla...
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...
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()) re...
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() ...
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 y...
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', defa...
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('.12...
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 (wit...
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", ...
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 co...
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 = ...
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:- # # ht...
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 imp...
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...
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), ] ...
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(coor...
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 ...
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] ...
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. ...
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 pr...
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 hav...
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 h...
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 ...
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...
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...
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(s...
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): "------------- star...
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 instantia...
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 od...
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)...
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 ov...
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[...
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, beca...
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)...
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]) - keywo...
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...
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 cal...
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("fac...
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):...
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): fo...
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/xto...
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: ...
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 ...
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 ...
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 (i...
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 getti...
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)):...
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 th...
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...
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 seco...
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 confus...
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) ...
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. ''' d...
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 ...
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...
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...
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"...
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", ...
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 progra...
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...
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 cond...
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...
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 ...
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['numbe...
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/Rec...
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 #...
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...
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 ...
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-...
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 d...
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...
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...
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....
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: rai...
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 y...
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 ob...
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...
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 o...
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 perime...
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...
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()...
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 t...
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'] ...
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...
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(da...
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"%...
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 ...
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 inpu...
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 ...
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 ...
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...
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 """