Blm33 Blm33 - 3 months ago 19
Python Question

How to write more Pythonic Code

I started learning python today from the tutorial on the official site.

When reading about filter(function, sequence) i thought of making a function that returns if a number is prime to use it with the filter.

notDividedBy = [2,3,4,5,6,7,8,9]

def prime(num):
"""True if num is prime, false otherwise"""
copy = notDividedBy[:]
check = True
if num in copy:
copy.remove(num)
for x in copy:
if num % x == 0:
check = False
break
return check


The above code works in the shell.

My question is: Since i feel like although a solution, it is not the most elegant one, can anyone transform this code to something more python-like?(better structure? less lines?)

I believe it would help me for better understanding of the basics of the language.

The thing is, don't use any imports or anything, just simple staff.

dfb dfb
Answer

One thing off the bat, if you are going to implement prime testing in this fashion, there's no reason to use an auxillary array

def prime(num):
    """True if num is prime, false otherwise"""    
    check = True
    #if num in copy:
    #    copy.remove(num)
    for x in range(2,x-1):
        if num % x == 0:
            check = False
            break
    return check
Comments