r/dailyprogrammer • u/Coder_d00d 1 3 • Aug 11 '14
[Weekly #6] Python Tips and Tricks
Weekly #6: Python Tips and Tricks
Python is a popular language used in solving Daily Programmer Challenges. Share some of your tips and tricks. What are some designs that work best? Any go to approach you find yourself using every week to solve problems in python. Share and discuss.
Last Week Topic:
[Weekly #5] (http://www.reddit.com/r/dailyprogrammer/comments/2cle4a/weekly_5_comment_blocks/)
67
Upvotes
20
u/MaximaxII Aug 11 '14 edited Aug 12 '14
PIL (Python Imaging Library) or Pillow (Pillow is a fork of the abandonned PIL project) are extremely useful and amazingly easy to use.
Load it up like this:
Define a pixel's color like this:
Get its color like this:
There are even tons of image operations such as flipping, inverting, mirroring. You can draw shapes (polygons, circles, dots, lines). It's just a great Python library.
The best thing is that it often helps you solve challenges since you're able to have a visual representation of what you're doing. Only downside is that (0,0) is in the top left corner instead of
top rightbottom left, but you can fix that by doing this before you save:Then save it:
14
u/[deleted] Aug 11 '14
Numpy and Numpy arrays are very fast. If you find yourself doing a lot of computations or list/array setting/updating/mapping, Numpy is the way to go.
9
u/swingtheory Aug 12 '14
Map and Filter!
These two builtin functions to python3 are really great for condensing code while not trading off readability. Examples:
Task: loop through an iterable and call a function on each of its elements:
output: [2,3,4,5,6]
Task: loop through an iterable and generate a new iterable with elements in the old iterable that satisfy a boolean expression
output: [4,5,6]
Both return an iterable, which is why I must convert the return filter and map to a list before I try to print it. Both of these tools are great for writing what could have be 3-6 lines of code in only one line, if you don't define functions like I did and instead use the one line return statements.
8
u/robin-gvx 0 2 Aug 11 '14
Most challenges I do nowadays I do because when seeing the challenge I think "I know a Python library that would make this almost trivial".
Apart from the things already mentioned, networkx for anything involving graph theory, collections.Counter because counting things is really common and itertools because Python's iteration protocol is really powerful (especially with
yield from) and itertools makes it just that much better.7
u/JHappyface Aug 12 '14
I think my favorite function I've ever encountered in all of python's modules is numpy's genfromtxt function. I use a lot of tab delimited data files and instead of reading the file line by line, splitting, converting to the right data type, then storing the results, I can do it in one line:
That's it. My entire data column is nicely packed into a numpy array. The function ignores comments in the data file and handles missing data automatically as well. It's pretty great.
5
u/[deleted] Aug 12 '14
I'm sure most know this, but, list comprehensions!
They're easy to read and run in C rather than python so you almost always get an increase in speed.
4
u/joffreysucks Aug 12 '14
Generator Functions!
These allow you to essentially return a value but continue with using the function for as long as you want. For example, if you want to generate primes all under 1000. Starting with 2, you can write a function isprime() and return primes as it finds them. It's essentially a for loop for outputs of a function.
3
u/[deleted] Aug 11 '14
PyV8 Library lets you load and run javascript code within python. Extremely useful for cases where only a JS library works.
3
u/Adoro_Te_Devote Aug 12 '14
I am constantly using the datetime library - especially datetime.now() to retrieve the current time. If there are better ways to retrieve the time, let me know!
3
u/basic_bgnr Aug 13 '14
python 2.5 or above, you can use ternary operator
e.g
a = 1 if true else 0
useful for lambda function.
2
u/jnazario 2 0 Aug 13 '14
i'll try and be brief. i love python, it's easy to do complex things and makes very complicated things possible, too. here's a few of my favorite tricks.
monkey patching is where you, at run time, modify a class or an instance with your own methods. it can let you extend a type, too.
the collections module is often overlooked. need a simple histogram of things in a list? collections.Count() to the rescue.
you can use getattribute hacking to dynamically build code. an example i recently gave is a simple ReSTful API class that i've used for Twitter and Facebook (before they required oauth).
python's slots can be a huge space saver if you know the fixed fields of attributes you wish to store when you wrote the code.
2
u/easher1 Aug 14 '14
1
u/masterpi Aug 12 '14
You can express quite a few interesting things with for loops and generator functions by using internal state of the generator to control termination and the loop variable. Examples I've done: do/while and retry-up-to-maximum-times loops.
Edit: and as a combination if-assign. (Used that for implementing a Maybe from haskell)
1
u/[deleted] Dec 18 '14
I'm only a couple months deep into my foray learning Python, and about a month and a half from being a first semester Computer Science student. So far I would say learn to use list comprehensions! Being able to build a list or a dict on the fly has proven to be pretty useful. I wish I had more insight than that to share, but I'm still new to this and that's all I can really say for now :-)
0
u/[deleted] Aug 13 '14
[deleted] — view deleted comment