Dividing a list of number by itself - python

The question that I have is trying to find the highest degree of divisibility
I have a list of numbers and I to divide them by themseleves
Example below
a = [2,2,5,4,12,64]
2 can be divided by [2,2]
5 can be divided by [5]
4 can be divided by [2,2,4]
12 can be divided by [2,2,4,12]
64 can be divided by [2,2,4,64]
That means the highest degree of divisibility is 4
Here is the code the I wrote so far.
b = len(a)
for i in range(b):
c = np.divide(a, a[i])
print(c)
```
I am wondering how can write the code to output the highest degree of divisibility.
Thanks!

try like below
def test():
a = [2,2,5,4,12,64]
maxv = -999
for i in a:
counter=0
for j in range(len(a)):
if i%a[j]==0:
counter+=1
if counter>maxv:
maxv=counter
print('highest number:',maxv)
test()

Since the numbers you're checking for divisibility will give the same results (like the two 2's), iterate over the set of unique numbers and then try to divide each number in that set by each number in the original list a. Using the modulo operator %, each time the remainder is 0, increase the counter for that number and add the final result to a list. Then take the maximum:
a = [2,2,5,4,12,64]
divs = []
for num in set(a):
count = 0
for denom in a: # denominator
if num % denom == 0:
count += 1
divs.append(count)
print(divs) # to see the count of the divisors
# [4, 2, 3, 1, 4]
print('highest degree:', max(divs))
# highest degree: 4
This can be reduced to almost a one-liner using a list comprehension for the outer loop. For the inner 'count'ing loop, use a generator expression like so: in Python, True evaluates to 1 and False evaluates to 0. So if we sum the number of times that division check is True, we get the count:
divs = [sum(num % denom == 0 for denom in a) for num in set(a)]
print('highest degree:', max(divs))
And, since we're taking the max() of it, we could turn the outer loop into a generator expression as well:
highest = max(sum(num % denom == 0 for denom in a) for num in set(a))

Related

How to find even sum

I need to find the sum of all even numbers below the inserted number. For example if I insert 8 then the sum would be 2+4+6+8=20. If I insert 9 then it also needs to be 20. And it needs to be based on recursion.
This is what I have so far:
def even(a):
if a == 0:
else:
even(a - 1)
even(8)
I cannot figure out what to change under the "if" part for it to give the right outcome
If the function is called with an odd number, n, then you can immediately call again with the number below (an even).
Then if the function is called with an even number return that even number plus the result of summing all the even numbers below this number by calling again with n - 2.
Finally, your base case occurs when n = 0. In this case just return 0.
So we have
def even_sum(n):
if n % 2 == 1: # n is odd
return even_sum(n - 1)
if n == 0:
return 0
return n + even_sum(n - 2)
which works as expected
>>> even_sum(8)
20
>>> even_sum(9)
20
>>> even_sum(0)
0
To design a recursive algorithm, the first thing to wonder is "In what cases can my algorithm return an answer trivially?". In your case, the answer is "If it is called with 0, the algorithm answers 0". Hence, you can write:
def even(n):
if n == 0:
return 0
Now the next question is "Given a particular input, how can I reduce the size of this input, so that it will eventually reach the trivial condition?"
If you have an even number, you want to have this even number + the sum of even numbers below it, which is the result of even(n-2). If you have an odd number, you want to return the sum of even numbers below it. Hence the final version of your function is:
def even(n):
if n == 0 or n == 1:
return 0
if n % 2 == 0:
return n + even(n - 2)
return even(n - 1)
Both with o(n) time complexity
With For loop
num = int(input("Enter a number: ")) # given number to find sum
my_sum = 0
for n in range(num + 1):
if n % 2 == 0:
my_sum += n
print(my_sum)
With recursion
def my_sum(num):
if num == 0:
return 0
if num % 2 == 1:
return my_sum(num - 1)
return num + my_sum(num - 2)
always avoid O(n^2) and greater time complexity
For a recursive solution:
def evenSum(N): return 0 if N < 2 else N - N%2 + evenSum(N-2)
If you were always given an even number as input, you could simply recurse using N + f(N-2).
For example: 8 + ( 6 + (4 + ( 2 + 0 ) ) )
But the odd numbers will require that you strip the odd bit in the calculation (e.g. subtracting 1 at each recursion)
For example: 9-1 + ( 7-1 + ( 5-1 + ( 3-1 + 0 ) ) )
You can achieve this stripping of odd bits by subtracting the modulo 2 of the input value. This subtracts zero for even numbers and one for odd numbers.
adjusting your code
Your approach is recursing by 1, so it will go through both the even and odd numbers down to zero (at which point it must stop recursing and simply return zero).
Here's how you can adjust it:
Return a value of zero when you are given zero as input
Make sure to return the computed value that comes from the next level of recursion (you are missing return in front of your call to even(a-1)
Add the parameter value when it is even but don't add it when it is odd
...
def even(a):
if a == 0 : return 0 # base case, no further recusion
if a%2 == 1 : return even(a-1) # odd number: skip to even number
return a + even(a-1) # even number: add with recursion
# a+even(a-2) would be better
A trick to create a recursive function
An easy way to come up with the structure of a recursive function is to be very optimistic and imagine that you already have one that works. Then determine how you would use the result of that imaginary function to produce the next result. That will be the recursive part of the function.
Finally, find a case where you would know the answer without using the function. That will be your exit condition.
In this case (sum of even numbers), imagine you already have a function magic(x) that gives you the answer for x. How would you use it to find a solution for n given the result of magic(n-1) ?
If n is even, add it to magic(n-1). If n is odd, use magic(n-1) directly.
Now, to find a smaller n where we know the answer without using magic(). Well if n is less than 2 (or zero) we know that magic(n) will return zero so we can give that result without calling it.
So our recursion is "n+magic(n-1) if n is even, else magic(n-1)"
and our stop condition is "zero if n < 2"
Now substitute magic with the name of your function and the magic is done.
For an O(1) solution:
Given that the sum of numbers from 1 to N can be calculated with N*(N+1)//2, you can get half of the sum of even numbers if you use N//2 in the formula. Then multiply the result by 2 to obtain the sum of even numbers.
so (N//2)*(N//2+1) will give the answer directly in O(1) time:
N = 8
print((N//2)*(N//2+1))
# 20
# other examples:
for N in range(10):
print(N,N//2*(N//2+1))
# 0 0
# 1 0
# 2 2
# 3 2
# 4 6
# 5 6
# 6 12
# 7 12
# 8 20
# 9 20
Visually, you can see the progression like this:
1..n : 1 2 3 4 5 6 7 8
∑n : 1 3 6 10 15 21 28 36 n(n+1)/2
n/2 : 0 1 1 2 2 3 3 4
1..n/2 : 1 2 3 4
∑n/2 : 1 3 5 10 half of the result
2∑n/2 : 2 6 10 20 sum of even numbers
So we simply replace N with N//2 in the formula and multiply the result by 2:
N*(N+1)//2 --> replace N with N//2 --> N//2*(N//2+1)//2
N//2*(N//2+1)//2 --> multiply by 2 --> N//2*(N//2+1)
Another way to see it is using Gauss's visualisation of the sum of numbers but using even numbers:
ascending 2 4 6 8 ... N-6 N-4 N-2 N (where N is even)
descending N N-2 N-4 N-6 ... 8 6 4 2
--- --- --- --- --- --- --- ---
totals N+2 N+2 N+2 N+2 ... N+2 N+2 N+2 N+2 (N/2 times N+2)
Because we added the even numbers twice, once in ascending order and once in descending order, the sum of all the totals will be twice the sum of even numbers (we need to divide that sum by 2 to get what we are looking for).
sum of evens: N/2*(N+2)/2 --> N/2*(N/2+1)
The N/2(N/2+1) formulation allows us to supply the formula with an odd number and get the right result by using integer division which absorbs the 'odd bit': N//2(N//2+1)
Recursive O(1) solution
Instead of using the integer division to absorb the odd bit, you could use recursion with the polynomial form of N/2*(N+2)/2: N^2/4 + N/2
def sumEven(n):
if n%2 == 0 : return n**2/4 + n/2 # exit condition
return sumEven(n-1) # recursion
Technically this is recursive although in practice it will never go deeper than 1 level
Try out this.
>>> n = 5
>>> sum(range(0, n+1, 2))
with minimum complexity
# include <stdio.h>
void main()
{
int num, sum, i;
printf("Number: ");
scanf("%d", &num);
i = num;
if (num % 2 != 0)
num = num -1;
sum = (num * (num + 2)) / 4;
printf("The sum of even numbers upto %d is %d\n\n", i, sum);
}
It is a C program and could be used in any language with respective syntax.
And it needs to be based on recursion.
Though you want a recursion one, I still want to share this dp solution with detailed steps to solve this problem.
Dynamic Programming
dp[i] represents the even sum among [0, i] which I denote as nums.
Case1: When i is 0, there is one number 0 in nums. dp[0] is 0.
Case2: When i is 1, there are two numbers 0 and 1 in nums. dp[1] is still 0.
Case3: When i is 2, there are three numbers 0, 1 and 2 in nums. dp[2] is 2.
Case4: When i is greater than 2, there are two more cases
If i is odd, dp[i] = dp[i-1]. Since i is odd, it is the same with [0, i-1].
If i is even, dp[i] = dp[i-2] + i by adding the current even number to the even sum among [0, i-2] (i-1 is odd, so won't be added).
PS. dp[i] = dp[i-1] + i is also ok. The difference is how you initialize dp.
Since we want the even sum among [0, n], we return dp[n]. You can conclude this from the first three cases.
def even_sum(n):
dp = []
# Init
dp.append(0) # dp[0] = 0
dp.append(0) # dp[1] = 0
# DP
for i in range(2, n+1): # n+1 because range(i, j) results [i, j) and you take n into account
if i % 2 == 1: # n is odd
dp.append(dp[i-1]) # dp[i] = dp[i-1]
else: # n is even
dp.append(dp[i-2] + i) # dp[i] = dp[i-2] + i
return dp[-1]

Refining Factors in Python

I have to write a function factor, which takes an integer parameter n, and returns the least number from 2 through n-1 that divides n. If no such number exists, it returns -1.
I was able to create the function to find the factors, but am unsure on how to refine it to return the correct result.
def factors(n):
i = n
lst=[]
while i > 0:
if n % i == 0:
lst.append(i)
i -= 1
print(lst)
result=[i for i in lst if i > 2 and i < n-1]
print(result[1])
def main():
n=int(input("Enter n:"))
factors(n)
main()
You can use list comprehension to find the factors of a number. Also, to optimize your solution, you only need to run until half of the number.
e.g. for 12, the maximum factor of 12 can be 6.
A number greater than half of that number can't be its factor. So, you do not require to run your loop until n-1.
>>> [n for n in range(2, number/2+1) if number % n == 0]
In the above line, we will run a loop from 2 to (number/2 + 1) and check if the number is divisible by n, then add it to the list.
Your factor function should look from the smallest value first, then start increasing
def factor(n):
i = 2
while i < n:
if n % i == 0:
return i
i += 1
return -1
>>> factor(6)
2
>>> factor(21)
3
>>> factor(49)
7
>>> factor(13)
-1
Then factors can call that
def factors(n):
values = [1]
while n > 1:
f = factor(n)
if f > -1:
values.append(f)
n //= f
else:
values.append(n)
break
return values
>>> factors(21)
[1, 3, 7]
You're doing a lot of unnecessary work here: you find all factors, instead of just the smallest. However, you do have a correct answer at your fingertips: you print the second element as the lowest factor, but your list is in the opposite order. Try
print lst[-2]
That said you really should not bother with all of that. Instead, start at 2 and work upward, looking for the smallest factor. If you get to sqrt(n) without finding any, return a result of -1.
Here is optimized way for finding factor of a number in between 2 or n-1:
def factor(n):
i=2
a=[]
while i*i<=n:
if n%i==0:
if i!=n/i:
a.append(i)
a.append(n/i)
else:
a.append(i)
i+=1
a.sort()
print a
n=int(input())
factor(n)

Why are these lines of code in python only outputting the same answer?

I'm trying to get this program to return all possible multiples of 3 and 5 below 1001 and then add them all together and print it but for some reason these lines of code only seem to be printing one number and that number is the number 2 which is obviously wrong. Can someone point me in the right direction to why this code is grossly wrong?
n = 0
x = n<1001
while (n < 1001):
s = x%3 + x%5
print s
You've got a few mistakes:
x is a boolean type
Your loop never ends
adding values to mimic lists?
Edit
Didn't see the part where you wanted sum, so you could employ a for-in loop or just a simple one like so:
sum = 0
for i in range(1001):
if(i % 3 == 0 or i % 5):
sum += i
print(sum)
(Python 3)
You need to stop while at some point by incrementing n. Here is some code:
nums = []
n = 0
while (n < 1001):
# in here you check for the multiples
# then append using nums.append()
n += 1
This creates a loop and a list that accounts for every number in 0 to 1000. In the body, check for either condition and append to the list, then print out the values in the list.
num is a list where you are going to store all the values that apply, (those numbers who are divisible by 3 and 5, which you calculate with modulo). You append to that list when a condition is met. Here is some code:
nums = []
n = 0
while (n < 1001):
if(n % 3 == 0 or n % 5 ==0):
nums.append(n)
n += 1
print(n) #or for loop for each value
Explanation: a list of numbers called num stores the numbers that are divisible by 3 or 5. The loop starts at zero and goes to 1000, and for all the values that are divisible by 3 or 5, they will be added to the list. Then it prints the list.
Of course there is a simpler approach with a range:
for i in range(1001):
if(i % 3 == 0 or i % 5 == 0):
print(i)
This will print out all the values one by one. It is 1001 because the upper limit is exclusive.
true=1
false=0
so:
x = n<1001
we have x=1 because 0<1001 is true
s = x%3 + x%5
the remainder of 1/3 is 1 and 1/5 is 1
In your code:
1. x=n<1001 - generates a boolean value; on which we can't perform a mathematical operation.
In while loop:
your variable n,x are not changing; they are constant to same value for all the iterations.
Solution 1:
Below code will help you out.
s=0
for i in range(1,1002):
if( i%3 == 0 or i%5 == 0):
s = s + i
print(s)
Solution: 2
There is one more approach you can use.
var = [i for i in range(1,1002) if i%3==0 or i%5 ==0]
print(sum(var))

Using Fibonacci Program to Sum Even Elements

I am trying to solve the following using Python:
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.
So far, I have been able to generate the Fibonacci elements but in trying to sum the even elements, my code seems to stall. Here is the code below:
def fib(n):
if n==0:
return 0
elif n==1:
return 1
if n>1:
return fib(n-1)+fib(n-2)
n=0
total=0
while fib(n)<=4000000:
if fib(n)%2==0:
total+=fib(n)
print(total)
Any suggestions would be welcome.
You have an infinite loop as n isn't ever incremented up from zero in your while loop. Additionally, why not sum your Fibonacci total as well as find the next Fibonacci value in the same while loop, like this:
x= 1
y=1
total = 0
while x <= 4000000:
if x % 2 == 0:
total += x
x, y = y, x + y
print (total)
Outputs:
4613732
since this looks like a homework assignment, I threw in some interesting Python
from math import sqrt
# Using Binet's formula
def fib(n):
return int(((1+sqrt(5))**n-(1-sqrt(5))**n)/(2**n*sqrt(5)))
def sum_even_terms(limit = 4000000):
n = total = 0
while True:
term = fib(n)
n += 1
if term > limit: break
if term % 2 == 0:
total += term
return total
print sum_even_terms()
def is_nth_term_even(n):
return (fib(n) % 2 == 0)
print is_nth_term_even(30)
Just for fun, here's a really short solution:
def fib_even_sum(limit=4*10**6):
"""Sum of the even Fibonacci numbers up to the given limit."""
b, c = 1, 2
while c <= limit:
a = b + c; b = c + a; c = a + b
return b // 2
print fib_even_sum() # outputs 4613732
It's based on the following facts:
Every third Fibonacci number is even.
If Fib(n) is even, then the sum of the even Fibonacci numbers up to Fib(n) is equal to the sum of the odd Fibonacci numbers up to Fib(n) (because each even Fibonacci number is the sum of the two preceding odd Fibonacci numbers).
The sum of all Fibonacci numbers (even and odd) up to and including Fib(n) is Fib(n+2) - 1 (via an easy proof by induction).
So if Fib(n) is the last even number to be included in the sum, then
the total you want is just (Fib(n+2) - 1) / 2.
You can also use a generator and add the numbers
def fib():
a, b = 0, 1
while 1:
yield a
a, b = b, a + b
f = fib()
total = 0
while total <= 4000000:
current = f.next()
if current % 2 == 0:
total += current
print total

Sum of all the multiples of 3 or 5 below 1000

Beginner here- trying to make a simple python program that will compute/answer this problem:
If we list all the natural numbers below 10 that are multiples of 3 or 5, we get 3, 5, 6 and 9. The sum of these multiples is 23.
Find the sum of all the multiples of 3 or 5 below 1000.
Currently this is what I have:
a = 0
b = 0
while a < 1000:
a = a + 3
print (a)
while b < 1000
b = b + 5
print (b)
This will print all the numbers being considered. I just need to add them together and that's my answer.
I would like one of two things to happen, instead of the code that I have written:
I would like all of this to happen internally, and therefore not have to use the "print" function. The just print the sum of all of those multiples.
I would like all of this stuff to print, but then I want to be able to print the sum of all of them too. Is there a way to make the computer take the value of everything it has printed?
Actually this problem can be solved in O(1) instead of O(N) without using any loops or lists:
The required sum is the sum of all multiples of 3 plus sum of all multiples of 5 minus the sum of multiples of (3*5=15) below the given number 1000 (LIMIT=999). The sums are calculated as a sum of arithmetic series.
It can be calculated in following way:
LIMIT=999
# Get the upper bounds for the arithmetic series
upper_for_three = LIMIT // 3
upper_for_five = LIMIT // 5
upper_for_fifteen = LIMIT // 15
# calculate sums
sum_three = 3*upper_for_three*(1 + upper_for_three) / 2
sum_five = 5*upper_for_five*(1 + upper_for_five) / 2
sum_fifteen = 15*upper_for_fifteen*(1 + upper_for_fifteen) / 2
# calculate total
total = sum_three + sum_five - sum_fifteen
# print result with Python 3
print(int(total))
The result is:
>>>
233168
It is possible to do this in one line in Python using a generator expression:
print(sum(x for x in range(1000) if x % 3 == 0 or x % 5 == 0))
The range(1000) produces all the integers from 0 to 999 inclusive. For each one of those integers, if it is divisible by 3 or divisible by 5, then it is included in the result. The sum(...) function adds up all those numbers, and finally print(...) prints the result.
I would use a for loop to iterate over each number in your selected range. Then you can check if the modulus % is equal to 0, meaning it has no remainder when divided by those values, if so, add it to the total.
total = 0
for num in range(1000):
if num % 3 == 0 or num % 5 == 0:
print(num)
total += num
>>> total
233168
While a for loop would work, you could also use a generator expression and sum:
sum(n for n in range(1000) if n % 3 == 0 or n % 5 == 0)
def sum_multiply (n):
data = []
for num in range (1, n):
if num % 3 == 0 or num % 5 == 0:
data.append(num)
return sum(data)
sum_multiply(1000)
total=0
i=0
while i<1000:
if i%3==0 or i%5==0:
print(num)
total+=i
i+=1
print("Total is: ")
**with python**
print(sum([i for i in range(1,1000) if i%3==0 or i%5==0 ]))

Categories

Resources