I tried a challenge and I can't seem to get it right. I know Python doesn't support function overloading but I have seen some that has done it manually.
I used two arguments to add the 2 numbers and three arguments to add the 3 numbers then used an array with the size of 4 for adding the 4 numbers but I can't seem to get past the sum of the two numbers. I just used my other codes as reference as to how I came up with my code.
def add(a, b):
sum1 = sum(a,b)
return sum1
def add(c,d, e):
sum2 = sum(c,d,e)
return sum2
def add(f,g,h,i):
sum3 = sum(f,g,h,i)
return sum3
a,b = int(input("Enter two numbers: ").split())
print("The sum is: ", add(a,b))
c,d,e = int(input("Enter three numbers: ").split())
print("The sum is: ", add(c,d,e))
f,g,h,i = [int(x) for x in input("Enter four numbers: ").split()]
print("The sum of is: ", add(f,g,h,i))
if you just want to add numbers in n time in a function then you can do
if we keep 2 nums are minimum no require
def add(a, b, *args):
return a+b+sum(args)
or you can use
def add(*args):
return sum(args)
now you can add any amount of numbers
in other way
def add(**kwargs):
a = kwargs.get('a', 0)
b = kwargs.get('b', 0)
return a+b # or sum(kwargs.values())
print(add(a=1, b=2))
# if you want another variable in function so you need to write that also
Related
def generate(num):
res = 0
for i in str(num):
res = res + int(i)
return res + num
I was looking at someone's code for generating numbers and I don't understand why he used 'str(num)' to iterate i to num. Then he translates the str(i) again to int(i).
What is the intention behind this? Why can we not create
def generate(num):
res = 0
for i in num:
res = res + i
return res + num
from the beginning?
Thanks
By turning a number into a string, you are allowed to iterate over the various digits.
Try this:
for c in str(123):
print(c)
Of course, c is then a string, so if you want to use the digit as a number, you need to cast it back to an int.
In other words, the first function you shared computes the sum of the digits of a number. The second function you shared would compute the sum of numbers in an iterable, like a list of integers.
A single int is not an iterable, while a single str is - so for x in y: will work if y is a str, but it will cause an error if y is an int.
This code snippet,
def generate(num):
res = 0
for i in str(num):
res = res + int(i)
return res + num
assumes num is a numerical value and adds the individual digits of a given number to produce res and then it adds that res to the the number itself,
So, when you call generate(123) it adds (1 + 2 + 3) + 123 which produces 129
The second code snippet raises and error when num is a numerical value.
Hope it helps!
Trying to divide multiple numbers in a for loop, output is incorrect answer
Created a variable for the answer, in each for loop it will make answer equal to the previous loops answer divided by the integer from the for loops list.
def div(x):
ans = 0
for i in x:
ans = ans / int(i)
b = int(input("How many numbers would you like to " + opt + "?"))
c = range(0,b)
d = list()
for i in c:
d.append(input("What number would you like to " + opt + "?"))
print(div(d))
If 3 numbers are input to the list (d). I want to divide these 3 numbers and make the variable (ans) equal to the quotient
Example:
Input 3 numbers - 200, 10, 2
Result: 10
Actual Results from script: 0.0
You have two problems:
First, our function does not return a value. You can fix this by adding return ans at the end of the function.
Second, if you start with ans = 0, dividing ans will only get you more zeros.
Here's one solutions, using a placeholder to skip over the solution:
def div(x):
ans = None
for i in x:
if ans is None:
ans = i
else:
ans = ans / int(i)
return ans
Here's a slightly more elegant alternative, using an arbitrary argument list.
def div(init, *divisors):
ans = init
for x in divisors:
ans /= x # divide and assign together
return ans
div(100, 10, 2) # returns 5
div(*[100, 10, 2]) # returns 5
By declaring a function parameter with *, any extra parameters given will be packed into it as a list. You can then pass arguments to it without putting them in a list, or you can use another * to unpack the list into multiple arguments.
The div function doesn't actually return anything, so it should be printing None ?
this should fix your problem:
def div(x):
ans = 0
for i in x:
ans = ans / i
return ans
I edited the post to get the word cross sum instead of factorial in it, thanks for your help.
def assignment_2():
# write a function that outputs the cross sum of a number (54321 -> 5 + 4 + 3 + 2 + 1 = 15)
number = int(input('enter a number'))
result = 0
while number:
result = result + number % 10
number = int(number / I0)
return result, number
when I call the function I get the result no problem, but the number is = 0 because its going through that loop.
That's how I call the function
result, number = assignment_2()
print(f'assignment 2: the cross sum of {number} is {result}')
Just save the value to another variable:
number = int(input('enter a number'))
orig = number
result = 0
while number:
result = result + number % 10
number = int(number / 10)
return result, orig
You'll have to save it in another variable:
number = int(...)
saved_number = number
...
return result, saved_number
Also, I should note that what you're doing here is not the factorial, but the digit sum. Factorial is the product of all numbers from 1 to the argument—for instance, 5 factorial is 5×4×3×2×1 = 120.
You can use the input value as a string to get the digit sum, your algorithm does not need to transform its input at all:
def digit_sum(x):
return sum(int(xx) for xx in str(x)), x
def assignment_2():
return digit_sum(int(input("Please enter a number ")))
I want to define a function, sumAll(n) that sums all numbers from 1 to n.
For example, when I call sumAll(10) should return the answer 55...
Because:
1+2+3+4+5+6+7+8+9+10 = 55
The function sumAll needs to use a for loop to carry out this summation, and it will have to use a sum variable that increases in value over each iteration of the for loop.
I have a working function that does not use a for loop, but I need to know how to use a for loop to accomplish this as well.
Here is the working program:
def sumAll(n):
if n == 0:
return 0
return n + sumAll(n - 1)
number = int(raw_input("Please enter a number: \n"))
print ("The answer is: ") + str(sumAll(number))
How do I use a "for" loop to accomplish this?
Am I right in assuming the "for loop" should be nested in the "sumAll" function?
I have tried many times to do this using a for loop and I keep getting a infinite result and errors...
Here is my code:
def sumAll(n):
y = n + sumAll(n -1)
return y
num = int(raw_input("Please enter a number")
for n in range(num):
num = sumAll(num)
print num
By for loop
def sumAll(n):
sum_all = 0
for i in range(1, n+1):
sum_all = sum_all + i
return sum_all
number = int(raw_input("Please enter a number: \n"))
print ("The answer is: ") + str(sumAll(number))
Output:
Please enter a number:
10
The answer is: 55
You can also use list Comprehension:
print sum([i for i in range(number+1)])
Output:
55
You can also use a mathematical series formula:
def sumAll(n):
return n * (n + 1) / 2
you can even do it without a loop:
def sumAll(n):
return sum(range(1,n+1))
print(sumAll(10)) # -> 55
if you insist on using a loop:
def sumAll(n):
s = 0
for i in range(1,n+1):
s += i
return s
but the mathematical solution is simply:
def sumAll(n):
return n * (n + 1) / 2
# in python 3:
# return n * (n + 1) // 2
(there are n elements with an average value of (n+1)/2; this will always be an integer since either n or n+1 is even; the proof by induction is often the first example when math students learn about induction...).
You will get an error with sum(1, 2, 3, 4)
TypeError: sum expected at most 2 arguments, got 4
sum((1, 2, 3, 4)) # works cuz tuple inside
sum([1, 2, 3, 4]) # works cuz list inside
so the func will need to gather elements into a tuple, e.g.
numbers = 1, 2, 3, 4
print(sum(numbers)) # already a tuple so works
use * with your parameter to gather the caller's args into a tuple.
* enabbles any-number of args to be supplied by caller and they are converted into a tuple parameter.
def sumall(*args):
return sum(args)
print(sumall(1))
print(sumall(1, 2))
print(sumall(1, 2, 3))
print(sumall(1, 2, 3, 4))
produces the expected answers. Credit: author Downey asks for this exercises solution in chapter 12 of Think Python (2016)
I am trying to create a program that takes a user integer input, creates a list and then
using recursion adds the list. The problem is when I put in 6 it comes up with 15 and the
answer should be (0+1+2+3+4+5+6) = 21. Why is the math wrong? I think it must be somewhere in the indexing because if you leave off the 6 you do get 15.
#Program which accepts a number from the user
#take the numbers 0 to the number input
#and gives a total of the numbers
def main():
#Get the number from the user to define upper end of range
num = int(input('Enter a non-negative integer: '))
#Create the list of numbers
numbers = list(range(0,num, 1))
#Get the sum of the list of numbers
my_sum = range_sum(numbers, 0, - 1)
#Display the total
print('The sum of 0 to', num, 'is: ', my_sum)
def range_sum(num_list, start, end):
if start < end:
return 0
else:
return sum(num_list)
#call the main function
main()
Using tail recursion:
def range_sum(nums, sum=0):
if not nums:
return sum
sum += nums.pop()
return range_sum(nums, sum)
There is no recursive call in the code. You are using the sum function, which comes defined in Python.
This is a relatively simple function to implement either recursively:
def recursive(n):
if n == 1:
return n
return n + recursive(n - 1)
or iteratively:
def iterative(n):
return sum(range(n + 1)) # note n + 1 - range excludes the stop argument
which is equivalent to:
def iterative_longhand(n):
total = 0
for i in range(n + 1):
total += i
return total
or, if a list is a necessity:
def recursive_list_sum(nums):
if nums:
return nums[0] + recursive_list_sum(nums[1:])
return 0
recursive_list_sum(list(range(n + 1)))
Your title says "using recursion", but none of your functions call themselves. You are using recursion neither to build the list nor to add up its contents. This function:
def range_sum(num_list, start, end):
if start < end:
return 0
else:
return sum(num_list)
called like:
range_sum(numbers, 0, - 1)
is just sum(num_list), as start > end. It is not clear what you are trying to achieve - if it should be recursive, there should be a call to range_sum inside it.