I need help with 6. Practice Makes Perfect!


#1

I've been stuck on this for the past day, and I could've sworn I had everything right, I even checked this forum, but nothing I'm doing works.
It tells me that "by_three(1) resulted in an error: 'int' object is not callable".
My code is as follows:

def cube(n):
cube = n**3
return cube
def by_three(n):
if n%3 == 0():
print "n is divisible by 3"
return cube(n)
else:
print "n is not"
return False

I would greatly appreciate some help in figuring out what I did wrong!


#2

This looks irregular. Remove the ().


#3

Thank you, that worked!
I actually added that on due later in my edits to my code due to experience in Java where parentheses are frequently required in similar contexts, so I figured not having them was an issue.
I feel kinda stupid now. ^///^'


#4

I'm kind of curious to why it was n%3==0 and not n%3==cube, i'm not sure i have the hang of syntax just yet. Thanks!


#5

When n is not 0, cube(n) can never be 0. However, cube(n) % 3 can be 0.

The solution set, m for,

m = n % 3

is

{0, 1, 2} for all n; n is Integer

The solution set, y for

y = x % n

is

{0, .., n-1} for all x, n; x, n are Integer

Remainders turn up in all sorts of situations and are useful because of their predictible nature, they repeat over intervals of a given modulus (divisor). Take for example the days of the week. Their modulus is 7. Months of the year, 12. Others will surface. They are very useful in producing repetitive patterns.


#6

Off topic, but another demonstration of how remainders can be giant time savers:

Consider prime numbers. We are given a range in which we need to find all the primes. What is the first step? Okay, I may be wrong, but it makes sense to filter out of the sample set all numbers divisible by 5 or 6. The sample set would be reduced by well over half. Using a known list of primes in the range of 7 .. sqrt(n)+1 we could filter all the other none primes. The modulo is the main function in this task.

I don't have a link to offer, just off, but search around for discussions on generating and testing for prime numbers with Python. It's fun stuff, and will have long term value.


#7

def cube(number):
return number**3

def by_three(number):
if number % 3 == 0:
return cube(number)
else:
return False


#8

My first reply doesn't really answer the question, does it? If we follow the instructions, it asks us to only cube numbers that are divisible by 3. That is why we must test the modulo first, then call the cube function on accepted values.

Consider this ternary as a brief model:

def cube(n):
    return n**3
def by_three(n):
    return cube(n) if n % 3 == 0 else False
print by_three(27)
# 19683
print by_three(28)
# False

We return the return value of cube(n) only if n% 3 is 0, else we return False.