I am trying to find the odd numbers in a range of numbers, and adding them all up.
I set my variable which is the range of numbers (5)
I then made a function which had the for statement, looking for the numbers in range from 1 to 1+num(this is for including the number) and the comma after that to skip every other number.
Then I printed the total sum, and outside of the function I called the function.
num = 5
def sumOfOdds():
sum = 0
for i in range(1, 1+num, 1):
sum = sum+i
print(sum)
sumOfOdds()
I tried to read other ways to fix this, but was unable to find a solution.
The third parameter in the range is the incremental value of the iterator which means that you want it to be 2, not 1, as you want to skip every other number. (By default its value is 1).
def sumOfOdds():
sum = 0
for i in range(1, 1+num, 2): # Here we set it to 2
sum = sum+i
print(sum)
For more info on range() visit https://docs.python.org/3/library/stdtypes.html#range
This is an easy fix. the third argument in range should be 2, not 1.
num = 12
def sumOfOdds():
sum = 0
for i in range(1, 1+num, 2):
sum = sum+i
print(sum)
sumOfOdds()
To add to the provided response, I would add that there's a more pythonic way to write it using the reduce function:
def sumOfOdds():
return reduce(lambda x, y: x + y, range(1, 1 + num, 2))
Also, let's say you'd like to pass the list to iterate as a parameter, you can use the following writing in Python
def sumOfOdds(values):
return reduce(lambda x, y: x + y, values[::2])
sumOfOdds(range(1, 1 + num))
Where in python [x:y:i] means: start at iterable index of x, end at iterable index of y-1, skip every i values. So [::2] means start at the beggining, end at the end, and skip every 2 values.
Related
I want to make a function that gets the sum of the squares of its each digits. Although, I have seen some solutions in the internet, the one I have seen is "getting the sum of the squares of its digits" but given a list. For example, instead of starting at the integer 133, they use [1,3,3] as an input. I tested this function and it works great, but I want to use an integer as an input and not a list.
Edit: For example the given is 123. So the function must return 14. (1^2 + 2^2 + 3^2)
My idea is:
def squarer(x): # where x is an integer (not a list)
# <insert a recursive formula>
# return the sum
One simple way to make a recursive function is, to always square the first digit and then call the same function with the remaining digits.
def squarer(x: int) -> int:
if x < 10: # trivial case, when x has only one digit
return x**2
first_digit = int(str(x)[0]) # extract the first digit
return first_digit**2 + squarer(int(str(x)[1:])) # recursive call
Here, I used the functions int() and str() to always access the individual digits and cast the the variable back to an integer.
You can use an integer as an input and transform it into a list.
arr = [int(x) for x in input("Enter a number: ")]
and then you pass your list into your function.
def squarer(arr): # where arr is a list
# <insert a recursive formula>
# return the sum
Try to convert your number to string so you can iterate by each digit. And after you can convert string to list or just convert each digit to int before you apply other logic
If I understood the question correctly, this code should solve your problem
It is not of the highest quality but it works :)
def sq(x):
sum = 0
while x > 0:
y = x/10
r = y*10
r = x-r
r = r*r
sum = sum+r
x = y
return sum
print(sq(12))
Recursive and without any transformations:
def squarer(n):
if n <= 0:
return 0
rest, first_digit = divmod(n, 10)
return first_digit**2 + squarer(rest)
I am a beginner at Python and I'm trying to use a while loop to sum up all of the squared n values in a given n value range.
Code:
def problem2(n):
x = 0
y = 0
while x < n:
y = (n**2)+y
x+=1
return y
For some reason, this equation returns the input number cubed.
Can someone explain why this happens and how to fix it?
You need to perform the ** on x, the value that is being incremented:
def problem2(n):
x = 0
count = 0
while x < n:
count += pow(x, 2)
x += 1
return count
You keep squaring the same number n, instead of the one being incremented x.
def sum_of_squares(n):
sum = 0
for x in range(0, n):
sum += x*x
return sum
You also don't really need the while loop, avoiding having to manually keep track of which variable is the counting variable and which one is the result variable (which is what you are confusing, as explained e.g. by #Ajax1234 in their answer).
It is a lot more Pythonic to use the built-in function sum, a generator expression and range:
def problem2(n):
return sum(x**2 for x in range(n))
This would be a lot more readable and better (unless of course you are being forced to use while).
Looks good. You're almost there.
It makes it the cube root because you add y to (n**2) everytime. Because you code runs until x !< n it runs n times. That means that you add n**2 to n**2*n.
That means that it gives 1(n**2)*(n-1)(n**2) which equals n(n**2) = n**3
Hope this was clear enough.
How can I write a function to get the sum of the items in the given list between the indices a and b. For example give aList=[6,3,4,2,5] and a=1, b=3, the function should return 9. Here is my code:
def sumRange(L,a,b):
sum= []
L = [6,3,4,2,5]
for i in range(a,b+1,1):
sum +=L[i]
return sum
You can achieve this with list slicing:
sum(your_list[a:b + 1])
Here, your_list[a:b+1] is a slice - a part of your list starting from the index a and ending with the index b, including the values at both indexes (this is why you need b + 1).
You can simply use index slicing in python and the sum function.
return sum(L[a:b])
It seems like you want do roll your own solution. You can do it like this (based on the code you had in your question):
def sumRange(L,a,b):
sum = 0
for i in range(a,b+1,1):
sum += L[i]
return sum
L = [6,3,4,2,5]
a = 1
b = 3
result = sumRange(L,a,b)
print "The result is", result
This program prints
The result is 9
so if the function is:
function(n)
what can i do to if i want.
function(5)
to return as
1
2
3
4
5
I'm thinking towards creating an empty list, but i don't know what to append into the list to get the number 1 up to 'n'
You can try
def function(n):
for x in range(0, n):
print x+1
if you want to print the values, or
def function(n):
returnlist = []
for x in range(0, n):
returnlist.append(x+1)
return returnlist
to return a list.
The for x in range(0, n): part of the code is called a for loop. It repeats itself n times, and x is incremented by one each time is repeats. You can then use x to accomplish different tasks within your code. In this case, we're simply taking its value plus one and printing it or appending it to a list. We have to add one to the value because x is zero based, although it doesn't have to be. We could just as easily have written for x in range(1, n+1): and not have had to add one to the x value.
Here is a simple example:
def function(n):
for i in range(1, n+1):
print i
So I understand this simple for loop:
sum = 0
for number in {1,2,3,4}:
sum = sum + number
print sum
>>>
1
3
6
10
>>>
Then here is a neat little code that combines a for loop and a function I found on the interwebs:
def sum_list(l):
sum = 0
for number in l:
sum = sum + number
return sum
print sum_list([1, 7, 4])
>>>
12
What I don't understand is how python interprets this code (rather how Python knows to add the 3 arguments 1,7,4 together).
I would really help if you can break it down for me!
To tack on another question for you guys to review:
sum = 0
for number in {1,2,3,4}:
sum = sum + number
return sum
Spits out an error. print sum will list the results as 1,3,6,10
Error says: Syntaxerror: 'return' outside of function
[EDIT] #sshashank124
For example: This code spits out 3 answers. It prints out:
sum = 0
for number in {1,7,4}:
sum = sum + number
print sum
>>>
1
8
12
>>>
But this:
def sum_list(l):
sum= 0
for number in l:
sum = sum + number
print sum
print sum_list([1, 7, 4])
>>>
12
none
Spits out only 1 answer, 12. My question is why that occurs.
for number in l:
This iterates over the l, and number will have each and every element of l on every iteration. You can check that like this
for number in l:
print number
# 1
# 7
# 4
You are adding those numbers to the sum variable. You can check that like this
sum = 0
for number in l:
sum = sum + number
print sum
# 1
# 8
# 12
I believe you are doing this for educational purpose. If you actually wanted to find the sum of an iterable, then you can use the builtin sum function, like this
sum([1, 7, 4])
It knows to add them together, because you tell it to do that.
Let me rewrite the code a bit to show what's happening. Rewrite one, adding 1,7,4 and then 2,8,5, but adding more numbers requires more lines:
sum = 0
sum = sum + 1
sum = sum + 7
sum = sum + 4
print sum
sum = 0
sum = sum + 2
sum = sum + 8
sum = sum + 5
print sum
Rewrite two - using a loop. Two lines shorter, but it can now handle lists of more items - adding four, five, even ten numbers, without adding more lines of code, just by making the lists longer:
sum = 0
for number in [1,7,4]:
sum = sum + number
print sum
sum = 0
for number in [2,8,5]:
sum = sum + number
print sum
Rewrite three - moving the lists out of the loop. The code got longer again, but something interesting happened - see how the loop code is now identical both times:
myList = [1,7,4]
sum = 0
for number in myList:
sum = sum + number
print sum
myList = [2,8,5]
sum = 0
for number in myList:
sum = sum + number
print sum
Rewrite four - now it's identical, why does it have to be there twice? Can't we ... write it once, and use it twice? That way if we need to change it, we only have to change it in one place. Yes - make it a function and call the function:
def sum_list():
sum = 0
for number in myList:
sum = sum + number
print sum
myList = [1,7,4]
sum_list()
myList = [2,8,5]
sum_list()
Rewrite five - what's happening above works fine, because you called everything 'myList' it all works. But if you write bigger programs like that it gets messy fast - one myList could be several pages of code away from another, we'll tend to forget that something pages and pages away could be affecting things. So we humans can keep track of what's going on, we need to clearly and explicitly give the function something to work on, and not have it just reaching far away and pulling things out of the rest of the code.
def sum_list(working_list): # working_list is whatever the function gets
sum = 0 # by a different name
for number in working_list:
sum = sum + number
print sum
myList1 = [1,7,4]
sum_list(myList1)
myList2 = [2,8,5]
sum_list(myList2)
See in the above code, I've called them myList1 and myList2 - yet whatever you give to the function, the function sees it called 'working_list'. The names don't have to match.
But because sum_list has it's own name for whatever you give it, you don't have to have a name for what you give it. You can just give it a list directly without a name:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
print sum
sum_list([1,7,4])
sum_list([2,8,5])
The next move is, once you're feeding things into sum_list, sum_list is looking away and writing to the screen. We can't have that. For the sake of humans tracking what's happening, that's a bad idea - you want to give functions some work to do and have them give you back an answer. That way you know you can use them anytime you need, without worrying about them printing to the screen unexpectedly. That's where 'return' comes in:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
return sum
result = sum_list([1,7,4])
print result
result = sum_list([2,8,5])
print result
Now sum_list is a self contained adder, it does nothing else. You can trust it. It's not reading from names all over your code, it's only reading explicitly what you gave to it. It's not writing to the screen at surprise times, or anything. You give it a list, you get a result, it's isolated, limited, controlled, predictable, easy to work with, easy to reuse. And like the list names, if all you do is get the result and print it, you don't need to give that a name either:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
return sum
print sum_list([1,7,4])
print sum_list([2,8,5])
Edit: I hope that explains several of your questions.
What that code is doing
Why it prints one answer instead of three - because you are giving it one thing (a list).
Why it makes no sense to use return on its own - because you have to call a function and then return from the function, and you can bring something back with you or you can go somewhere and bring nothing back (function with no return). But you can't bring something back if you don't go anywhere first.
In Python you will realise that when you initialise a variable you don't need to assign a type to it, you can just initialise anything in there.
in this case l was interoperated as an object, or an array to be specific.
as for the loop.
for number in l:
is like a for each statement, it goes through each of the elements. and stores it in number, then iterates after the block is executed, moving on to the next l.
Hope that helped? (if i understand your question.
The for number in l: line takes each of the elements in [1,7,4] and adds them to the sum variable which represents the total sum of the elements in the list.
This is what it looks like:
Take first element of l: 1
Add to sum --> sum is now 1
Take second element of l: 7
Add to sum --> sum is now 8
Take third element of l: 4
Add to sum --> sum is now 12
Return sum --> sum is 12
Might I suggest that sum([1,7,4]), the builtin python method would also work.