Page 1 of 1

A Little Python

Posted: Mon Apr 19, 2010 1:52 pm
by indigochill
I feel really slow for this taking as long as it did for me to get the answer. However, I'm still puzzled as to why my C program produced the wrong answer. It looks like it added 1 too many numbers, but isn't xrange(3,11) going to generate all numbers 3-11 inclusive? Here's the code I failed to get the right answer from (the correct answer was the second-to-last value printed to screen rather than the last).

Code: Select all

#include <stdio.h>

int main (int argc, const char * argv[]) {
	int array[7];
	int y = 0;
	int x = 0;
	int t = 0;
	int r;
	int s = 0;
	int n = 3;
	for (t=0; t<9; t++) {
		array[t] = n++;
		y = array[t];
		x = y * y;
		r = x * (x - 1);
		s = s + r;
		printf("%d\n", s);
	}
    return 0;
}

Posted: Mon Apr 19, 2010 1:58 pm
by CodeX
for x in xrange(a,b) a ≤ x < b, so it's not completely inclusive

Posted: Mon Apr 19, 2010 2:27 pm
by indigochill
That would do it. Thanks!

Posted: Wed Aug 17, 2011 7:43 am
by BosseBL
lol. had same problem. i guessed it was something like that. pretty confusing.

Posted: Mon Nov 12, 2012 1:41 am
by Cilyan
Be warned that this code is no longer valid in Python 3:
- print is a function and should get surrounding parenthesis
- xrange is now range and range no longer exists

Code: Select all

print(sum([x * (x - 1) for x in [y * y for y in range(3,11)]]))

reading it from the back

Posted: Tue Apr 01, 2014 7:49 pm
by Grusewolf
I read it straightbackward
my solution in groovy:

Code: Select all

def yRange = []
def sum = 0

(3..<11).each{y -> yRange+= y*y}
yRange.each {x -> sum+= x*(x-1)}

println sum
and I also learned, that pythons xrange area is exlusive upper bound.

a litter php

Posted: Mon Apr 14, 2014 8:19 am
by hackout
print sum([x * (x - 1) for x in [y * y for y in xrange(3,11)]])

Code: Select all

for($y=3;$y<=11;$y++){
 $x[]=$y*$y;
}
foreach($x as $i){
 $a+=$i*($i-1);
}
echo $i;
[/code]