Welcome to the CSC Q&A.
Get help and give help!
Write great code!
It is our choices... that show what we truly are, far more than our abilities.

Categories

+6 votes

Hi friends,

Looking for tips and tricks to using the range function. I am having a hard time on how to do the sum of squares/odds after getting the list of numbers. Any general step-by-steps are appreciated and super helpful

asked in CSC201 Spring 2021 by (664 points)

3 Answers

+4 votes

The range function has 3 possible inputs. My advice is to look at each one, remember what it does, and try to see how it relates to your problem.
Ill break down the three parts:

for i in range(a, b, c)

a - the simplest part. What should the first value be? Put that here.
b - where should it end? This is often what the user inputs. Remember that the range() stops BEFORE it reaches this number. So if you have a variable that the user inputs(i have been calling mine 'stop') in order to set what number a sum goes up to, set this to be something like stop+1.
c. The increment - this is one by default, meaning the range function counts every whole number. Think about how big of steps you need to take; for counting odd numbers only, you use 2 because every other number is odd.

For taking running sums, make sure every time the range takes a step, you calculate the new sum. This is done by something like

theSum = theSum + i

Which adds whatever value the range function is currently "holding" - whatver number it just stepped to.

answered by (1.5k points)
+3 votes

If you get a list of numbers and you want to calculate the sum of squares of that list, you may want to find the patterns of the numbers. For example, if you have a list of (1, 3, 5, 7), you'll notice that these numbers are all odd, which gives you range(1, 8, 2). Similarly, if there is a list of (2, 4, 6, 8), if'll give you range(2, 9, 2).
After that, you make a for loop within that range. You'll need a variable (total) to keep track of the sum of squares after each iteration. After each iteration, that variable total will add the squares of the previous iterations. Finally, you'll get the sum of squares of that list when the loop ends.

You can apply this to other kinds of list as well. To calculate the sum of the list, you'll do the same as if you're calculating the sum of squares. First, you have a list. Then you find the range and loop through that range while having a variable that adds up each time the loop runs.

answered by (132 points)
+1 vote

When you get a list of numbers be that odd or even, first you need to find a range for it.

For example - for (1,3,5,7) you have the range (1,8,2).

And for your program, for the loop, add for i in range(1, variable + 1):
and Sum = Sum + anyVariable.

Hope it helps!

answered ago by (1.1k points)
...