This is really the first thing that I have written in python. I come from Java background. I don't want to just learn how to program java code with Python syntax. I want to learn how to program in a pythonic paradigm.
Could you guys please comment on how I can make the following code more pythonic?
from math import sqrt # recursively computes the factors of a number def factors(num): factorList = [] numroot = int(sqrt(num)) + 1 numleft = num # brute force divide the number until you find a factor for i in range(2, numroot): if num % i == 0: # if we found a factor, add it to the list and compute the remainder factorList.append(i) numleft = num / i break # if we didn't find a factor, get out of here! if numleft == num: factorList.append(num) return factorList # now recursively find the rest of the factors restFactors = factors(numleft) factorList.extend(restFactors) return factorList # grabs all of the twos in the list and puts them into 2 ^ x form def transformFactorList(factorList): num2s = 0 # remove all twos, counting them as we go while 2 in factorList: factorList.remove(2) num2s += 1 # simply return the list with the 2's back in the right spot if num2s == 0: return factorList if num2s == 1: factorList.insert(0, 2) return factorList factorList.insert(0, '2 ^ ' + str(num2s)) return factorList print transformFactorList(factors(#some number))
In short, “pythonic” describes a coding style that leverages Python's unique features to write code that is readable and beautiful. To help us better understand, let's briefly look at some aspects of the Python language.
So essentially when someone says something is un-Pythonic, they are saying that the code could be rewritten in a way that is a better fit for Python's coding style.
There is an excellent primer by David Goodger called "Code Like a Pythonista" here. A couple of things from that text re naming (quoting):
joined_lower
for functions, methods, attributes
joined_lower
or ALL_CAPS for constants
StudlyCaps
for classes
camelCase
only to conform to pre-existing conventions
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With