#๐ help with code
52 messages ยท Page 1 of 1 (latest)
@plush marsh
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
def largest_cube(n):
'''
Assume n is an integer > 1.
Return the largest value of k such that k**3 is strictly
less than n. For example, if n is 30, the answer would be
3, since 3**3 = 27, which is the largest perfect cube
less than 30.
'''
number = 0
for i in range(n):
while n**3 < n:
if n**3 < n:
number += n
return number
print(largest_cube(30))
^same code in photo
I don't think you'll need a for loop and a while loop here
but shouldnt this work also
No, it doesn't quite make sense what you're doing with this code
all you need to do is increase number, check it's cube, and stop when the cube is greater than n
so if the number is 30 like in the example
we would check
1 ** 3
2 ** 3
3 ** 3
4 ** 3 is greater than 30, so the loop would stop
I would use a while loop here instead of a for loop
if you do for num in range(n)
that's going to give you 0, 1, 2, 3, 4, 5....30
you don't need to check all 30 numbers
you only need to check numbers whose cube is smaller than 30
be careful with the difference of = and ==
oh it works
and why do you think you need num and number? How are they different?
Just because it works for one example, doesn't mean you got it correct
run more tests
yea nvm
You're overthinking it a bit
Your while loop condition is good
except is should be <= instead of <
Oh nevermind it says less than n
< is correct
idk how to increment num in a while loop
def largest_cube(n):
number = 1
while number ** 3 <= n:
number += 1
Look at this logic here
This logic will check 1 ** 3 to see if it is below 30 (if n is 30)
if it's still less than 30, then it will check 2 ** 3
if it's still less than 30, it will check 3 ** 3
do you see how this is working?
yea
We're going to keep increasing number by 1 until number ** 3 is greater than (or equal to) n
much simpler
The issue is that number has to go one too far to figure out when the cube is too large
when n is 30, number will be 4 after the loop, because when testing 4 ** 3, we can see that 64 is larger than 30
So for this, we want to return 3, not 4
would subtracting 1 help?
exactly ๐
!close
This help channel has been closed and it's no longer possible to send messages here. If your question wasn't answered, feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.