[Tutor] new to prog. question
alan.gauld@bt.com
alan.gauld@bt.com
Wed Mar 26 12:50:02 2003
> I've a simple question.
I love it when they say that... :-)
> I create a list containing numbers. list1=[1,2,4,8,16,32,64,128,512]
> If I wanted to find if a given number, 12 for example, is
> in the list would be easy. But, how about if x+y in the list equals
> the number (12) ?
Thats not very simple at all.
Think how you would do it in your head. Its not trivial, you have to
work out every combination of all the numbers in your list. What
if you allow multiplications too? There is no way Python can do
that for you easily(like a built in function).
Instead you will have to write some code(a function) to do it for
yourself. This will probably involve two loops nested one inside
the other.
Something like this:
for A in list
for B in the remaining numbers
if X == A + B: return True
else: return False
Also do you allow 3 numbers to add together (2+4+8)=14?
That is even more complex!
> Maybe I am just going the wrong way here, and there is a
> easier way to do this.
Nope you asked a much harder question than you realised!
Alan G.