Dividing multiple numbers in a for loop - python

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

Related

How to implement manually a function overloading of adding integers in python?

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

How can I reimplement this recursive function?

So I'm trying to solve a puzzle and I came across this code. I can't figure out what the output would be and any attempts to run it result in a "reached the maximum amount of recursion" error. Sorry in advance for the goofy variable names.
How can I modify this to achieve the same output, without the recursion error? The initial numbers I'm passing are 13379446(arg 1) and 5(arg 2).
import sys
num1 = int(sys.argv[1])
num2 = int(sys.argv[2])
def doot(num1, num2):
print num1
print num2
doritos = 0
if num2 > num1:
pass
else:
if num2 == 0:
print "if"
doritos = 1
else:
if num2 == num1:
doritos = 1
else:
wew = doot(num1 - 1, num2 - 1)
doritos = wew
wew = doot(num1 -1, num2)
doritos = doritos + wew
print doritos
Let me get you started. I'm assuming that doritos is supposed to be the return value, that is, that the code should say return dortitos instead of print doritos. Also, I'm completely ignoring the line print if.
Now what do we know? Looking at the code we see that
doot(x,y) = 0 if y > x
doot(x,0) = 1
doot(x,x) = 1 and
doot(x,y) = doot(x-1,y-1) + doot(x-1,y) otherwise
So we want to figure out the value of doot(x+h,x) where h > 0. Start with the simplest case, h=1. We already know that doot(1,0)=1, so
doot(2,1) = doot(1,0)+doot(1,1) = 1+1 = 2
doot(3,2) = doot(2,1)+doot(2,2) = 2+1 = 3
and now it's easy to guess that
doot(x+1,x)=x+1 for all x>= 0.
t's also easy to prove this by induction, if you're so inclined.
So now, work out some examples when h=2, and figure out the formula for doot(x+2,x). Then figure out the formula for doot(x+3,x) and so on, until you're ready to guess the the formula for doot(x+h,x)
Okay, I overhauled your code to use a dictionary (values) and a queue.
import sys
num1 = int(raw_input("num1: "))
num2 = int(raw_input("num2: "))
def doot(num1, num2):
print num1
print num2
doritos = 0
n1 = num1
n2 = num2
values = {}
queue = [(num1,num2)]
while queue:
num1,num2 = queue.pop()
#print queue
#print values
if (num1,num2) not in values:
if num1 >= num2:
if num2 == 0:
#print "if"
#doritos = 1
values[(num1,num2)] = 1
else:
if num2 == num1:
#doritos = 1
values[(num1,num2)] = 1
else:
#wew = doot(num1 - 1, num2 - 1)
#doritos = wew
#wew = doot(num1 -1, num2)
#doritos = doritos + wew
if (num1-1,num2-1) in values and (num1-1,num2) in values:
values[(num1,num2)] = values[(num1-1,num2-1)] + values[(num1-1,num2)]
else:
queue.append((num1,num2))
if (num1-1,num2) not in values:
queue.append((num1-1,num2))
if (num1-1,num2-1) not in values:
queue.append((num1-1,num2-1))
#print values
doritos = values[(n1,n2)]
print doritos
return doritos
doot(num1,num2)
In essence, I use the queue to keep track of the sums I don't have yet. If both of the descendants of (num1,num2) are in the dictionary, then I put it in the dictionary with the sum of their values. Otherwise, I put either or both descendant that's not in the dictionary on the queue along with itself. The other times that I don't put (num1,num2) back on the queue are when num1 == num2 or num2 == 0, in which cases I put them in the dictionary with value 1. At the end, I return the value in the dictionary that corresponds to the original inputted numbers.
Now, a word of caution: this code is horribly inefficient. I just had to reboot my computer because I tried the inputs you gave in the question, and it gobbled up all of the available RAM. So, you should instead consider what exactly is being done with the recursion, and figure out how to work forwards from the base cases instead of backwards from the input. That task, I will leave to you.
Your code is a recursive implementation of a combination function, which calculates the number of combinations of k distinct elements that can be drawn from a set of n elements.
A tidied up version of your function would look like this (note I have removed all the print statements and ensured that the function returns something - otherwise it won't work at all).
def doot(n, k):
if n < k:
return 0
if k == 0 or n == k:
return 1
return doot(n - 1, k - 1) + doot(n - 1, k)
This works fine for small values of n and k. A faster version that doesn't rely on recursion uses factorials, as shown in this answer.
import math
def nCr(n, r):
f = math.factorial
return f(n) / f(r) / f(n - r)
However, calculating the factorial of 13379446 still takes a long time and may not be accurate because the result is so huge. My system hangs when I try it. The other answer to the same question appears to work better.

Get sum of numbers using a Function and For Loop

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)

How would I make a condition that requires an odd number in a certain range?

Here is a pretty simple example of what I mean:
def work():
x = input("Give me a number : ")
if x in range(30000):
print "hello"
So as long as I put in a number in that range it will print hello, but what if I want it to only accept an odd number in that range? I tried defining a separate function that's range is only odd numbers like this:
def work():
a = input("Give me a number : ")
if a in range(30000):
X = range(30001)
y = (2*X)-1
if a in range(y):
print "hello"
but that doesn't work.
if 0 <= x < 30000 and x % 2 == 1:
print "hello"
Note: Python 2.x didn't do the optimisation - so this only applies to Python 3.x's range
You can take advantage that xrange (or range in 3.x - needn't generate the list and can do membership testing...) by providing it with a step parameter as well as the start and end stops...
So, you could use to check for odd numbers up until 30000:
if number in xrange(1, 30000, 2):
pass
eg:
>>> for number in (1, 2, 3, 999999):
print number in xrange(1, 30000, 2)
True
False
True
False
An odd number doesn't divide by 2, so you verify this using the modulo operator:
x % 2
In Python a number not equal to 0 is considered True, so this will do the work:
def work():
x = input("Give me a number : ")
if x in range(30000) and x % 2:
print "hello"
If you wanted to list the numbers, here is a general way to do this (but you should just use the range() function):
def every(increment, range, offset=0):
current = offset
yield current
while(1):
current += increment
if current < range:
yield current
else:
break
So for odds to 30,000 it would be :
for i in every(2, 30000, 1):
...

Solving Project Euler #2 in Python

I am attempting to do Project Euler problem #2. Which is:
Each new term in the Fibonacci sequence is generated by adding the previous two
terms. By starting with 1 and 2, the first 10 terms will be:
1, 2, 3, 5, 8, 13, 21, 34, 55, 89, ...
By considering the terms in the Fibonacci sequence whose values do not exceed
four million, find the sum of the even-valued terms.
However the terminal window hangs when I use the following code with 4000000. Smaller numbers run ok. Is there something about this code that is really inefficient, hence the lagginess?
n = int(raw_input("Enter the start number: "))
def fib_generator():
a, b = 0, 1
yield 0
while True:
a, b = b, a + b
yield a
def even_sum(fib_seq):
seq = []
seq = [next(fib_seq) for number in range(n)]
seq = [number for number in seq if number % 2 == 0]
return sum(seq)
def start():
fib = fib_generator()
even_sum = even_sum(fib)
print even_sum
start()
You have a bug. You're generating the first 4,000,000 Fibonacci numbers, but the problem statement only asks for those Fibonacci numbers whose values are not more than 4,000,000.
Since the Fibonacci numbers grow exponentially (Fn ~ 1.618n), you're generating some numbers with a very large number of digits (log10 Fn ~ n / 5) and that will take an immense amount of time.
Fix the bug, and you'll be okay.
You just need to add logic to stop when the next fibonacci number exceeds 4000000.
Also, I spy a potential problem with this line:
def start():
fib = fib_generator()
even_sum = even_sum(fib) #<--- right here
print even_sum
It isn't good to have a variable name the same as the function name.
Yes, there is something inefficient in your code, you load a very long list into memory twice, with your two seq = ... statements. Why not try one generator expression rather than two list comprehensions? Also, you could alter your Fibonacci generator to stop at a certain number:
def fib_generator(n):
a, b = 0, 1
while a < n:
yield a
a, b = b, a + b
def even_sum(fib_seq):
seq = (number for number in fib_seq if not number % 2)
return sum(seq)
def start():
n = int(raw_input('Enter max constraint: '))
fib_seq = fib_generator(n)
even_sum1 = even_sum(fib_seq)
print even_sum1
start()
This ran pretty fast for me
lst = []
num1 = 1
num2 = 2
sum = 0
jump = 0
next = 0
while next<4000000:
next = num1 + num2
if next<4000000:
if jump ==0:
num1 = next
jump = 1
else:
num2 = next
jump = 0
if next%2 == 0:
lst.append(next)
for item in lst:
sum+=item
print ''
print "Sum: ",
print sum

Categories

Resources