A Little Python

Discussion of challenges you have already solved
Post Reply
indigochill
Posts: 3
Joined: Wed Mar 31, 2010 12:29 am

A Little Python

Post 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;
}
User avatar
CodeX
Posts: 350
Joined: Fri Oct 17, 2008 5:28 pm

Post by CodeX »

for x in xrange(a,b) a ≤ x < b, so it's not completely inclusive
indigochill
Posts: 3
Joined: Wed Mar 31, 2010 12:29 am

Post by indigochill »

That would do it. Thanks!
BosseBL
Posts: 6
Joined: Tue Aug 09, 2011 10:47 am
Location: Stockholm

Post by BosseBL »

lol. had same problem. i guessed it was something like that. pretty confusing.
User avatar
Cilyan
Posts: 1
Joined: Tue Nov 06, 2012 9:38 pm
Contact:

Post 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)]]))
User avatar
Grusewolf
Posts: 16
Joined: Sun May 29, 2011 7:58 pm
Location: Munich

reading it from the back

Post 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.
User avatar
hackout
Posts: 2
Joined: Wed Aug 13, 2008 9:44 am

a litter php

Post 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]
Post Reply