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 ...
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...
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...
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 ...
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...
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
...
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...
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 ...
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.
...
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; ...
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))])...
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]...
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...
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...
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...
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()
...
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:
...
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?
...
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...
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...