pythonic

Python procedure return values

In Python it's possible to create a procedure that has no explicit return. i.e.: def test(val): if 0 == val: return 8 Further, it's possible to assign the results of that function to a variable: >>> a = test(7) >>> print `a` 'None' Why the heck is that? What language logic is behind that baffling design decision? Why ...

Python graceful fail on int() call?

I have to make a rudimentary FSM in a class, and am writing it in Python. The assignment requires we read the transitions for the machine from a text file. So for example, a FSM with 3 states, each of which have 2 possible transitions, with possible inputs 'a' and 'b', wolud have a text file that looks like this: 2 # first li...

Is there a better, pythonic way to do this?

This is my first python program - Requirement: Read a file consisting of {adId UserId} in each line. For each adId, print the number of unique userIds. Here is my code, put together from reading the python docs. Could you give me feedback on how I can write this in more python-ish way? CODE : import csv adDict = {} reader = csv.rea...

Pythonic way to only do work first time a variable is called

Hello, my Python class has some variables that require work to calculate the first time they are called. Subsequent calls should just return the precomputed value. I don't want to waste time doing this work unless they are actually needed by the user. So is there a clean Pythonic way to implement this use case? My initial thought was ...

Pythonic way to print a table

I'm using this simple function: def print_players(players): tot = 1 for p in players: print '%2d: %15s \t (%d|%d) \t was: %s' % (tot, p['nick'], p['x'], p['y'], p['oldnick']) tot += 1 and I'm supposing nicks are no longer than 15 characters. I'd like to keep each "column" aligned, is there a some syntactic suga...

What is the pythonic way to detect the last element in a python 'for' loop?

I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only between elements, being suppressed in the last one. Here is how I currently do it: for i, data in enumerate(data_list): code_that_is_done_for_every_element ...

Creating class instance properties from a dictionary in Python

I'm importing from a CSV and getting data roughly in the format { 'Field1' : 3000, 'Field2' : 6000, 'RandomField' : 5000 } The names of the fields are dynamic. (Well, they're dynamic in that there might be more than Field1 and Field2, but I know Field1 and Field2 are always going to be there. I'd like to be able to pass in this dict...

Converting a single ordered list in python to a dictionary, pythonically

I can't seem to find an elegant way to start from t and result in s. >>>t = ['a',2,'b',3,'c',4] #magic >>>print s {'a': 2, 'c': 4, 'b': 3} Solutions I've come up with that seems less than elegant : s = dict() for i in xrange(0, len(t),2): s[t[i]]=t[i+1] # or something fancy with slices that I haven't figured out yet It's obviously ...

How to assert that zero or only one of N given arguments is passed

I have a definition like this def bar(self, foo=None, bar=None, baz=None): pass I want to make sure a maximum of one of foo, bar, baz is passed. I can do if foo and bar: raise Ex() if foo and baz: raise Ex() .... But there got be something simpler. ...

OCaml question:How to construct a formated string in pythonic way...

All of these start from a simple idea: How to write python-style formatted string in ocaml. pythoners could init a string as: str = "this var: %s" % this_var str2 = "this: %s; that: %s" % (this_var, that_var) but ocaml's formatted string code as : let str = Printf.sprintf "this var: %s" this_var let str2 = Printf.sprintf "this: %s; ...

Summing Consecutive Ranges Pythonically

I have a sumranges() function, which sums all the ranges of consecutive numbers found in a tuple of tuples. To illustrate: def sumranges(nums): return sum([sum([1 for j in range(len(nums[i])) if nums[i][j] == 0 or nums[i][j - 1] + 1 != nums[i][j]]) for i in range(len(nums))])...

Is there a more succinct / pythonic way to do this? (counting longest seq of heads, tails in coin flips)

Count the longest sequence of heads and tails in 200 coin flips. I did this - is there a niftier way to do it in python? (without being too obfuscated) import random def toss(n): count = [0,0] longest = [0,0] for i in xrange(n): coinface = random.randrange(2) count[coinface] += 1 count[not coinface]...

"".join(reversed(val)) vs val[::-1]...which is pythonic?

So according to the Zen of Python ... Explicit is better than implicit...Sparse is better than dense...Readability counts...but then again Flat is better than nested...so then which is pythonic? val = "which is pythonic?" print("".join(reversed(val))) or print(val[::-1]) I'm just a Java programmer learning Python so I find this py...

Pythonic way to find a regular expression match

Is there a more succinct/correct/pythonic way to do the following: url = "http://0.0.0.0:3000/authenticate/login" re_token = re.compile("<[^>]*authenticity_token[^>]*value=\"([^\"]*)") for line in urllib2.urlopen(url): if re_token.match(line): token = re_token.findall(line)[0] break I want to get the value of the i...

Class Objects and comparing specific attributes

Hi all I have the following code. class person(object): def __init__(self, keys): for item in keys: setattr(self, item, None) def __str__(self): return str(self.__dict__) def __eq__(self, other) : return self.__dict__ == other.__dict__ Now I want to take this code and only do...

More pythonic way of skipping header lines

Is there a shorter (perhaps more pythonic) way of opening a text file and reading past the lines that start with a comment character? In other words, a neater way of doing this fin = open("data.txt") line = fin.readline() while line.startswith("#"): line = fin.readline() ...

Can this be made more pythonic?

I came across this (really) simple program a while ago. It just outputs the first x primes. I'm embarrassed to ask, is there any way to make it more "pythonic" ie condense it while making it (more) readable? Switching functions is fine; I'm only interested in readability. Thanks from math import sqrt def isprime(n): if n ==2: ...

Swapping 1 with 0 and 0 with 1 in a pythonic way?

In some part of my Python program I have a val variable that can be 1 or 0. If it's 1 I must change to 0, if it's 0 I must change to 1. How do you do it in a Pythonic way? if val == 1: val = 0 elif val == 0: val = 1 it's too long! I did: swap = {0: 1, 1:0} So I can use it: swap[val] Other ideas? ...

Pythonic way to select first variable that evaluates to True

I have some variables and I want to select the first one that evaluates to True, or else return a default value. For instance I have a, b, and c. My existing code: result = a if a else (b if b else (c if c else default)) Another approach I was considering: result = ([v for v in (a, b, c) if v] + [default])[0] But they both feel me...

Review my Django Model - Need lots of suggestions.

Hi all, I am pulling a variety of information sources to build up a profile of a person. Once I do this I want to the flexibility to look at a person in a different ways. I don't have a lot of expierience in django so I would like a critique (be gentle) of my model. Admittedly even as I coded this I'm thinking redundancy (against DRY...