Dev102.com programming challenge #10

| | Comments (0)

Programming challenge #10 has been posted at dev102.com.

If all the numbers 1..n were present, then they would sum to n(n+1)/2. If some x is absent, then they will sum to n(n+1)/2 - x. So to determine which number is missing, subtract the sum of the series from the expected sum.

This python code finds the missing number in the series named values:

def test(values) :
	max_val = len(values) + 1
	expected_sum = max_val*(max_val + 1) / 2
	return expected_sum - sum(values)

Here is a complete test:

import random
def test(values) :
	max_val = len(values) + 1
	expected_sum = max_val*(max_val + 1) / 2
	return expected_sum - sum(values)

test_range = 200
for i in range(1,test_range) :
	a = range(1, i) + range(i+1, test_range+1)
	random.shuffle(a)
	x = test(a)
	if x != i :
		print "Failed at ", i
		print a
		print sum(a)
		break

Leave a comment

About this Entry

This page contains a single entry by Hugh Brown published on July 2, 2008 5:59 PM.

US State Quarters Update 3 was the previous entry in this blog.

.NET interview questions and answers is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.