[Tutor] new to prog. question (cleared-up)
Alfred Milgrom
fredm@smartypantsco.com
Wed Mar 26 21:21:47 2003
At 02:52 AM 26/03/03 +0000, riex@ligbr.com.br wrote:
>What I was tinking is: in a list containing numbers, which could be
>randon, how would I go about
>figuring out if:
> x in the list is the given number >not the problen
>or x+x in the list is the given number
>or even x+x+x in the list is the given number
>So far just using addition.
I assume you mean x+y in the list
If you need to do this comparison a few times, it may be a good idea to
construct a new list of numbers which contain the sum of the elements of
the original list (plus the original list if you also want to compare
against just x)
The new list needs to be sorted and duplicates thrown out:
set = [1, 2, 3, 5, 6, 9, 11, 15, 17] # just a sample list of
random numbers
sumset = [(x+y) for x in set for y in set]
sumset = sumset + set # include original set if you want
to compare against x also
sumset.sort()
count = 0
newsumset = []
for element in sumset:
count = count + 1
if element not in sumset[count:]:
newsumset.append(element)
>>> print set
>>> [1, 2, 3, 5, 6, 9, 11, 15, 17]
>>> print sumset
>>> [1, 2, 2, 3, 3, 3, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8,
8, 9, 9, 9, 10, 10, 10, 11, 11, 11, 11, 11, 12, 12, 12, 12, 12, 13, 13, 14,
14, 14, 14, 15, 15, 15, 16, 16, 16, 16, 17, 17, 17, 17, 17, 18, 18, 18, 18,
18, 19, 19, 20, 20, 20, 20, 20, 20, 21, 21, 22, 22, 22, 23, 23, 24, 24, 26,
26, 26, 26, 28, 28, 30, 32, 32, 34]
>>> print newsumset
>>> [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 26, 28, 30, 32, 34]
>>> 24 in newsumset
1
>>> 25 in newsumset
0
This of course may not be practical if your original set is very large, but
your original post suggested ten elements or so.
HTH,
Alfred Milgrom