Hey I'm looking for a solution to the belowe question. Any recommendations on how to write this algorithm???
Thanks:
You are given a sequence s of numbers, in increasing order, for example:
s = 2, 5, 7, 9, 13, 15.
You are also given a number n, say n = 16. You have to try to find two numbers x and y from s, such that x+y = n, if such numbers exist. In this example, you could take x = 7 and y = 9.
However, you must do so as efficiently as possible: you must not perform more additions than the number of elements in s. Describe an algorithm to do this.
9 1475
efficiency not taken into consideration: -
s = [2, 5, 7, 9, 13, 15]
-
n = 16
-
l = [n] * len(s)
-
if n in s:
-
print "16 + 0"
-
else:
-
r = [ operator.sub(*i) for i in zip(l,s) ]
-
print set(s).intersection(set(r))
-
I have not tried on other variations, so this method may not be what you want
-
buldu=0;
-
left = 0;
-
right= Length-1;
-
-
while (left == right || buldu==1) {
-
if a[left]+ a[right] > KEY
-
right--;
-
else if a[left]+ a[right]<KEY
-
left++;
-
else if a[left]+ a[right]==KEY
-
buldu = 1;
-
}
best optimized i coud find.
bvdet 2,851
Expert Mod 2GB
Hey I'm looking for a solution to the belowe question. Any recommendations on how to write this algorithm???
Thanks:
You are given a sequence s of numbers, in increasing order, for example:
s = 2, 5, 7, 9, 13, 15.
You are also given a number n, say n = 16. You have to try to find two numbers x and y from s, such that x+y = n, if such numbers exist. In this example, you could take x = 7 and y = 9.
However, you must do so as efficiently as possible: you must not perform more additions than the number of elements in s. Describe an algorithm to do this.
Assuming your sequence will always contain unique numbers (no duplicates): - s = [2, 5, 7, 9, 13, 15]
-
-
result = 16
-
-
# count the number of iterations
-
i = 1
-
-
# no need to check the last element in the list
-
while len(s) > 1:
-
print i
-
n = result - s[0]
-
if n in s:
-
print '%d + %d = %d' % (s[0], n, result)
-
# remove 'n' from list
-
s.remove(n)
-
# remove first element from list
-
s = s[1:]
-
i += 1
Output:
>>> 1
2
3
7 + 9 = 16
4
>>>
If your sequence is always increasing in value, you can stop iterating after result/s[0] = 1.
Assuming your sequence will always contain unique numbers (no duplicates): - s = [2, 5, 7, 9, 13, 15]
-
-
result = 16
-
-
# count the number of iterations
-
i = 1
-
-
# no need to check the last element in the list
-
while len(s) > 1:
-
print i
-
n = result - s[0]
-
if n in s:
-
print '%d + %d = %d' % (s[0], n, result)
-
# remove 'n' from list
-
s.remove(n)
-
# remove first element from list
-
s = s[1:]
-
i += 1
Output:
>>> 1
2
3
7 + 9 = 16
4
>>>
If your sequence is always increasing in value, you can stop iterating after result/s[0] = 1.
I like it! But on line 17, instead of recreating/reassigning the list, I'd use
as an efficiency improvement.
bvdet 2,851
Expert Mod 2GB
I like it! But on line 17, instead of recreating/reassigning the list, I'd use
as an efficiency improvement.
You are correct Barton! Thanks.
BTW - Congrats on breaking the 5000 barrier.
You are correct Barton! Thanks.
BTW - Congrats on breaking the 5000 barrier.
Thank you <takes a deep bow>, thank you very much.
Hi,
I don't know if you're still interested, but a much more efficient algorithm would be to not do a linear search (at least for an arbitrarily large sequence). The following code does a binary search which converges on the two values which would sum to the target value (based on the premise that if no values are repeated and the sequence is increasing then the first value < target/2 < second value). -
from math import floor
-
from math import ceil
-
from random import choice
-
-
s = [0]
-
-
for i in range(1,10000):
-
s.append(s[i-1] + choice([1,2,3,4,5]))
-
-
n = float(raw_input( "Enter a test number: "))
-
-
testn = int(floor( n/2 ) )
-
-
oldlistlen = len(s)
-
listlen = int( floor(len(s) / 2) )
-
foundit = False
-
keepgoing = True
-
i = 0
-
upperlen = oldlistlen
-
lowerlen = 0
-
-
while keepgoing == True:
-
print "Testing listlen %d, %d and %d" % (listlen, s[listlen], s[listlen + 1])
-
listlentemp = listlen
-
i = i + 1
-
-
if s[listlen] + s[listlen + 1] == n:
-
foundit = True
-
keepgoing = False
-
-
elif s[listlen] < testn and s[listlen + 1] > testn:
-
print "No solution (<> test)"
-
keepgoing = False
-
-
elif listlen == 0 or listlen == oldlistlen - 1:
-
keepgoing = False
-
-
elif s[listlen] > testn:
-
upperlen = listlen
-
listlen = lowerlen + int( floor( ( upperlen - lowerlen ) / 2 ) )
-
-
elif s[listlen] == testn:
-
print "No solution (found testn)"
-
keepgoing = False
-
-
else:
-
lowerlen = listlen
-
listlen = lowerlen + int( ceil( (upperlen - lowerlen) / 2 ) )
-
-
if foundit:
-
print "Found it after %d iterations at index %d." % (i, listlen)
-
-
else:
-
print "Not found after %d iterations." % (i)
-
Let me know what you think.
Hi,
What is the solution if in case we need to select more than on digit?
for example : in our list [2,5,7,9,13,15] and we need to find 16.
16 = 2+5+9 . and also it might more than 3 digits for example
31 =2+5+9+15 and so on......
Regards
That is a much more difficult problem, which has it's own wikipedia page.
Sign in to post your reply or Sign up for a free account.
Similar topics
by: John Cho |
last post by:
// CHO, JOHN
#include<iostream>
class fracpri{
int whole;
int numer;
int denom;
|
by: hoopsho |
last post by:
Hi Everyone,
I am trying to write a program that does a few things very fast
and with efficient use of memory...
a) I need to parse a space-delimited file that is really large,
upwards fo a...
|
by: Al |
last post by:
Hi,
I need to store literally thousands if images and scanned document in the Database. I would like to know what is the most efficient algorithm both in terms of speed and storage for saving images...
|
by: pedagani |
last post by:
Dear comp.lang.c++,
I'm interested in knowing the general techniques used to handle large
binary files (>10GB) efficiently such as tweaking with filebuf , etc.
Reading chunk by chunk seems to be...
|
by: sovixi |
last post by:
Hey I'm looking for a solution to the belowe question. Any recommendations on how to write this algorithm???
Thanks:
You are given a sequence s of numbers, in increasing order, for example:
...
|
by: Luna Moon |
last post by:
seeking highly efficient caches scheme for demanding engineering computing?
HI all,
To same the time of costly function evaluation, I want to explore the
possibility of caching.
Suppose in...
|
by: pedagani |
last post by:
Dear comp.lang.c++,
Could you make this snippet more efficient? As you see I have too many
variables introduced in the code.
//Read set of integers from a file on line by line basis in a STL...
|
by: Bill David |
last post by:
SUBJECT: How to make this program more efficient?
In my program, a thread will check update from server periodically and
generate a stl::map for other part of this program to read data from....
|
by: seemanikam |
last post by:
Can anyone suggest me how to devise an efficient divide-and-conquer algorithm for the Tower-of-Hanoi problem when the disks are colored alternately red and blue, and with the extra rule that no disk...
|
by: Charles Arthur |
last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
|
by: emmanuelkatto |
last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud.
Please let me know.
Thanks!
Emmanuel
|
by: BarryA |
last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
|
by: marktang |
last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
|
by: Hystou |
last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
|
by: Oralloy |
last post by:
Hello folks,
I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>".
The problem is that using the GNU compilers,...
|
by: jinu1996 |
last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
|
by: tracyyun |
last post by:
Dear forum friends,
With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
|
by: agi2029 |
last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
| |