def summer(alist,total): # Start outer loop to run through each item # start inner loop with two markers. One from start other from end. Do this till they meet. # Check the sum against the reuired number # if < required number increase leftmarker else decrease right marker length = len(alist) for i in range(1,length): leftmarker = 0 rightmarker = length -1 while leftmarker < rightmarker: currenttotal= alist[i-1] + alist[leftmarker] + alist[rightmarker] print(str(currenttotal)) if currenttotal == total: print(str(i-1) + ':' + str(leftmarker) + ':' + str(rightmarker)) return True if currenttotal < total : leftmarker +=1 elif currenttotal > total: rightmarker -= 1 print(str(leftmarker) +"::" + str(rightmarker)) return False lister=[1,4,7,8,9,13,16] print(summer(lister,31))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question