[Tutor] Finding a nearest perfect cube

Alan Gauld alan.gauld at btinternet.com
Fri Nov 8 00:38:53 CET 2013


On 07/11/13 22:25, donsuni wrote:
> Hi, I am new to python and i have to write a following code without using any
> inbuilt function or a for loop. Only while and if loops are allowed.
>
> If i input a number, i should get a perfect cube nearest to it.
> For eg: if
> input=4, output=8
> input=8, output=27
> and so on....
> can some one help with the code?

We will help YOU write the code but we won't do it for you.
So what have you got so far? If you don't have code do you
know how to solve it in your mind? Can you write down the
algorithm you would use to solve it?

As for the restrictions, don't worry about them too much.
Anything you can do with a for loop you can do with a while
loop, just with a little more effort.

The restriction on not using inbuilt functions is a bit
more severe because you can't do a lot without using inbuilt
functions, but I assume they mean that using things
like +, -,*,etc is OK. As would be printing.

BTW it also helps to know which Python version you are
using (v2 or v3) and sometimes what OS you are running.

Finally, some questions about the problem:
The examples you give you always take the next cube
up the scale, but inputting 8 should surely give 8
as an answer since 8 is a cube?  And what if I input 9?
Can I count back down to 8 or must I go upwards
to the next cube? In which case it may not really
be the "nearest" cube but the "next" cube.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list