Python is an interpreted, general-purpose high-level programming language whose design philosophy emphasizes code readability.
4
votes
1answer
30 views
Improve performance of Gaussian kernel function evaluation
I need to improve the performance of a function that calculates the integral of a two-dimensional kernel density estimate (obtained using the function stats.gaussian_kde) where the domain of ...
2
votes
1answer
56 views
Speedup cython dictionary counter
I wrote a simple cython script to optimize the collections.Counter of a dictionary counter and the python zip implementation (the main input is a list of tuples). Is there a way to speed it up?
...
5
votes
1answer
52 views
A non-blocking lock decorator in Python
I needed to impose on a Python method the following locking semantics: the method can only be run by one thread at a time. If thread B tries to run the method while it is already being run by thread ...
11
votes
5answers
3k views
Why is my C# program slower than my Python program?
I made a program on python, and wanted it to be faster, so I wrote it on C#, because it's compiled. To my surprise, the python program is much faster. I guess there is something wrong with my C# code, ...
3
votes
1answer
23 views
“Histogram of Oriented Gradients” (HOG) feature detector for Computer Vision: trying to optimize for speed
Below is a function that I've only slightly modified from it's original context, found here.
Before mentioning anything else, it should be noted that I'm desperately trying to optimize this code for ...
8
votes
3answers
194 views
Row/Column Transpose
I was wondering if there is a smarter way of doing the following code. Basically what is does is that it opens a data file with a lot of rows and columns. The columns are then sorted so each column is ...
2
votes
0answers
63 views
Checking multiple keys in a dictionary [on hold]
1st file:
for loop:
if all(k in data for k in ('current', 'resistance')):
current = data["current"]
resistance = data['resistance']
MyClass.myfunction(1st_arg, 2nd_arg, current, ...
4
votes
2answers
40 views
First program with scraping, lists, string manipulation
I wanted to find out which states and cities the USA hockey team was from, but I didn't want to manually count from the roster site here.
I'm really interested to see if someone has a more elegant ...
2
votes
0answers
24 views
Verlet integration movement - doubt for on_key_press() methods
Based on my understanding of Verlet integration I tryed to use it over my Euler method to move my character in a 2D space.
I will put only the neccessery code, but if anything else is needed I will ...
4
votes
1answer
51 views
Modified BFS code optimizations
I need some help reviewing this code in terms of making as fast as possible. This is a modified version of BFS that does quite a bit of processing on the side.
Use case:
I have a large graph ...
0
votes
1answer
23 views
Better implementation of Excel's SUMIFS using pandas, the Python Data Analysis Library
I've implemented Excel's SUMIFS function in pandas using the following code. Is there a better—more Pythonic—implementation?
from pandas import Series, DataFrame
import pandas as pd
df = ...
-3
votes
0answers
23 views
counting occurrences of system arguments, character was expected, but received a string of x length [on hold]
import sys
from scanner import *
def main():
print("the name of the program is", sys.argv[0])
for i in range(1,len(sys.argv),1):
print("argument", i, "is", sys.argv[i])
...
-1
votes
1answer
24 views
Determine if string's lowercase letters are surrounded by plus signs [on hold]
I've been working through the problems on Coderbyte and this on has me stuck. The assignment is to built a piece of code that processes a string and returns True if all lowercase alphabetical ...
3
votes
1answer
78 views
Speed up file format conversion
I wrote this quick script to convert a genotype file into a BED file. Running it seems to be taking a very long time.
#BED file format
#http://genome.ucsc.edu/FAQ/FAQformat.html#format1
#1.chrom - ...
0
votes
0answers
22 views
Calendar in Python [on hold]
I have a sloppy first program I want to learn how to simplify. DSM suggested using dictionary lookups to simplify complex if statements. I will read about that on my own but any advice would be ...
3
votes
1answer
37 views
Produce bitcoin private key from 31 playing cards
I've written some Python code to generate a random hexadecimal string using 31 playing cards drawn without replacement (so no card appears more than once). This is sufficient to provide more than 160 ...
6
votes
1answer
123 views
Solving the Reve's puzzle
I'm trying to solve the Reve's puzzle (a variant of the Tower of Hanoi puzzle with four pegs). This is what I've come up with so far:
def solve(disk, source, temppeg1, temppeg2, destination):
if ...
4
votes
2answers
72 views
First Chess project
I'd made a project using pygame in python around 3 months ago. This was my first big project after I started learning how to program in college.
Now I'd like to know just how good my programming ...
5
votes
4answers
316 views
Sieve of Eratosthenes - Python
So I've been doing a lot of Project Euler lately and just wanted to make sure my implementation was as good as it could be. Does anyone have any suggestions to speed this up?
def sieve(upperlimit):
...
0
votes
0answers
5 views
Usage of __ while declaring any variables or class member in python [migrated]
Is it good practice to use __ convention while declaring the member variable?
This also imparts private kind of feature of that data member. There have been cases when I found that its good to have ...
13
votes
2answers
96 views
Condorcet voting method in OOP Python
I'm currently learning Python and having a great time so far (coming from PHP, I have a feeling of suddenly seeing the light).
At the same time, I'm studying voting algorithms. So, for training ...
3
votes
3answers
80 views
Checking if multiple user-entered numbers are in the right range
str, ski = int(input("text here")), int(input("text here"))
if str < 1 or str > 50 or ski < 1 or ski > 50:
print("did not enter between 1 and 50")
Is there anyway to shorten ...
5
votes
3answers
48 views
Extracting changesets (or commits) between last two tags in Mercurial with Python
I have written the following script:
#!/usr/bin/python
import os
os.system('hg tags > tags.txt')
file = 'tags.txt'
path = os.path.join(os.getcwd(), file)
fp = open(path)
for i, line in ...
8
votes
3answers
109 views
Refactoring if-else structure with elements of dict
I have code which gets data from a POST request (request.form dict), compares with corresponding attribute in object accident and does some action. The code looks needlessly verbose. How can I ...
6
votes
1answer
96 views
Simple console roguelike game
I have written this small game for the "learn python the hard way" book. I ask for some opinions about it and how to improve it.
I know about pygame and others game engines but all the game runs in ...
3
votes
1answer
65 views
Does this tkinter-based web browser widget use a well implemented class?
I have fully functional code in class format, and as far as I am aware from my previous question, it conforms to PEP 8 and the code logic and implementation is suitably pythonic. My main concerns here ...
4
votes
0answers
35 views
A mongodb inventory system — More efficient db calls?
I am trying to develop a simple inventory system that takes JSON data gathered from a powershell script, inputs the data into a mongodb, and displays the info in an interesting manner for the user. It ...
3
votes
1answer
32 views
Tornado quiz app
I am writing a simple quiz app using Tornado and MongoDB. The user authentication is done using Facebook and each user is uniquely identified by their Facebook ID. When a user first creates an ...
1
vote
0answers
45 views
Copy a directory structure to another, but only copying specific files
script.py:
#!/usr/bin/python
import os
srcDir = os.getcwd()
dirName = 'target_directory'
dstDir = os.path.abspath(dirName)
def ignore_list(path, files):
filesToIgnore = []
for fileName ...
0
votes
1answer
33 views
Class-based signal generator [closed]
I'm creating a class-based signal generator that, given a buy threshold, sell threshold and a list of list of indicators, creates a 'buy' of 'sell' signal on a given day if the indicator from that day ...
16
votes
4answers
2k views
Simple card game to learn OOP
My goal was to get my hands dirty in OOP by designing and using classes and getting started with inheritance and other OOP concepts.
I have written a very small code to play a card Game called ...
0
votes
1answer
66 views
bottle.py upload document to mongodb
Simple post and download web app in bottle.
server.py
import sys
import bottle
from bottle import request, response
import pymongo
import gridfs
from bson.objectid import ObjectId
import ...
9
votes
2answers
88 views
Improve performance of math function applied to arrays
This block of code is already somewhat optimized thanks to some answers given over at Stack Overflow. In the last question I made (Improve performance of function without parallelization) the code was ...
4
votes
2answers
40 views
Proxy evasion browser in Python
This code works. It is designed to retrieve website data directly, parse it, and open it as normal. I will develop it further later. Right now I want to know if there is any way to improve efficiency, ...
6
votes
2answers
110 views
Exercism assignment word-count in Python
Can someone review my code which I put on exercism.io for the word-count exercise (found here)?
class Phrase:
def __init__(self, phrase):
self.phrase = phrase.strip().lower().split()
...
2
votes
1answer
63 views
Is it a good style to run external commands in Python?
I have lots of external shell commands to run.
So I gave every command a name and then run it.
tar_report_cmd = 'zip -r {0} {1} '%(report_file, _export_dir)
exec_proc(tar_report_cmd)
mv_report_cmd ...
3
votes
1answer
150 views
Simple in-memory database
How can I improve this code (elegance, best practices, etc)?
""" Simple in-memory database as a response to the Thumbtack coding challenge. """
class SimpleDb(object):
""" Simple in-memory ...
6
votes
2answers
172 views
Performance of collision detection in a grid
I have fairly simple collision checking and handling Python code which is currently bottlenecking my performance quite a bit. I haven't done too much coding in python and I'm quite sure there's ...
2
votes
1answer
31 views
Loop filling a set with logging
After watching Raymond Hettingers talk Transforming Code into Beautiful, Idiomatic Python I got back to a function I wrote.
I'm not quite sure how to make it more pythonic but I think this might be a ...
5
votes
1answer
88 views
Byte by byte directory comparison ignoring folder structures and file name differences
I haven't been able to find an existing tool that does this, so I'm attempting to create one. If anyone knows of one that already exists, I'd appreciate a pointer to it. I plan on using this primarily ...
5
votes
1answer
64 views
Case study with a biological populations. A list of lists of lists
I have a population (Pop) which has an attribute which is a list of individuals (Ind) where each individual has an attribute which is a list of chromosomes (Chromo). Each chromosome is a list of ...
8
votes
1answer
115 views
Rotating greyscale images
For educational purposes I wrote a little piece of code to rotate greyscale images as "low level" as possible, that is, not using any rotate() function, but doing the math. I was wondering if it could ...
0
votes
0answers
63 views
Script to import repositories to Bitbucket
I needed a script to import repositories from other Bitbucket account to my own Bitbucket account. I have some 250 repositories in my account and I wanted them to move under Team (which is same as ...
1
vote
1answer
53 views
Naming for a variable in before and after status and different type of variable
I'm not a native English speaker, so I'm unsure about this. Is it ok to name a variable and put the prefix "before" and "after"? If not, how could I give it a better name?
before_len = ...
17
votes
4answers
2k views
Is it a good practice to put an exception handler in every method?
I always add an exception handler when a new method is created, and I don't know if it is a good or bad practice. I thought it may be a bit of an annoyance when viewing the source code.
Is it a good ...
6
votes
1answer
97 views
Strange performance difference
For exercise, I wrote this code:
def BigPrime(numP, plist = [], x = 1, counter =0):
while len(plist) <= numP:
if x == 1 or x == 2 or x == 5:
plist.append(x)
...
6
votes
0answers
60 views
What is the most pythonic way to solve a Differential equation using the euler method?
For example with this Differential Equation how can I do it in a pythonic way?
dx/dt=f(x,t)
I have a way to do it but I think this is not the most pythonic way to do it. Here is how I do it:
...
6
votes
1answer
48 views
Python compress and send
The following two functions are used to compress arbitrary Python objects and send them safely via socket or email, using only printable chars. In my specific message protocol, '=' signs are also not ...
2
votes
1answer
75 views
Run a TCP server listening for incoming messages
I've written the following code, but I need some review on design style. I want to develop a library/module and expose an API to client programs. How do I do that?
The code just runs a TCP server ...
9
votes
3answers
307 views
Installing “mods” with Python
A little disclaimer: you're going to have a field day with this. It's horrible. Looking at it makes me want to vomit, and don't ask me to explain it, because I've long forgotten what I was thinking ...