Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Beginner wondering if his code is 'Pythonic' [closed]

Tags:

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)) 
like image 399
jjnguy Avatar asked Sep 25 '08 17:09

jjnguy


People also ask

What is considered Pythonic?

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.

What is non pythonic?

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.


1 Answers

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

like image 107
unmounted Avatar answered Sep 29 '22 11:09

unmounted