Related
arr=[13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
for num in arr:
if num % 2 != 0:
a = sum(num)
print(a)
Output:
TypeError: 'int' object is not iterable
The problem is due because "num" is just an element inside your list and sum functions needs to receive an iterable, if you just want to count the odd elements inside arr you can use:
If you want to count the odd elements
oddsCounter = len([x for x in arr if x % 2 != 0])
print(oddsCounter)
If you want to get the total sum
oddsSum = sum([x for x in arr if x % 2 != 0])
print(oddsSum)
You cannot call sum on an int (num). You can do the following:
arr = [13, 15, 4, 6, 8, 71, 45, 54, 56, 77, 67, 88, 49, 33838, 3784376, 77735]
count = 0
for num in arr:
if num % 2 != 0:
count += 1
print(count)
or more simply:
print(sum(num % 2 == 1 for num in arr))
You can do with list comprehension,
In [1]: sum([i for i in arr if i %2 != 0])
Out[1]: 78072
And, sum(int) is not possible because sum only takes iterable (list, tuple, etc.) as the argument.
sum only accepts iterables, not single items.
try this:
a = a + num
take a look at this link to learn more about sum.
You need to remove a = sum(num). sum() takes an array but you have given it a int.
The code should be like this:
total = 0
arr=[13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
for num in arr:
if num % 2 != 0:
total = total + 1
print(total)
You are looping over the list, thus num is the current element in the iteration. You want to use sum on an iterable such as below:
> arr = [13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
> sum(num % 2 == 0 for num in arr)
8
I think you can get them with a list comprehension:
arr=[13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
elems = sum([ 1 if num %2 != 0 else 0 for num in arr])
print(f"Number of odd elements: {elems}")
Checkout as you are trying to sum the value of the "num" itself. Not sure if you were trying to append it to a list onto a.
im no sure what you mean by total number of odd elements as in all the times theres a odd number or the sum of all the odd numbers but here
arr=[13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
a = 0
for num in arr:
if num % 2 != 0:
a += num
print(a)
sum is used on lists so if you realy wanted to use the sum it looks like this
arr=[13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
a = []
for num in arr:
if num % 2 != 0:
a.append(num)
print(sum(a))
try using modulo and list comprehension
arr=[13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
def odd_elements(arr):
return len([x for x in arr if x % 2 != 0])
print(odd_elements(arr))
or, using sum()
arr=[13,15,4,6,8,71,45,54,56,77,67,88,49,33838,3784376,77735]
def odd_elements(arr):
return sum(1 for i in arr if i % 2)
print(odd_elements(arr))
I need to create a program that takes user input n and the finds the first n numbers that aren't divisible by any other prime numbers except 2, 3, and 5. This is what I've got so far:
def is_divisible(i):
for k in range(7, i):
if is_prime(k) == 1 and i % k == 0:
return 1
else:
return 0
def is_prime(k):
for j in range(2, k):
if k % j == 0:
return 0
else:
return 1
while True:
while True:
while True:
try:
n = input("How many numbers do you want to find: ")
n = n.replace(" ", "")
n = int(n)
break
except:
print("Input only natural numbers")
continue
if n == 0:
print("Input only natural numbers")
continue
else:
break
count = 0
i = 0
while count < n:
if i % 2 == 0 and i % 3 == 0 and i % 5 == 0 and is_divisible(i) == 0:
print(i)
count += 1
i += 1
else:
i += 1
repeat = input("To repeat press (1), to end press anything else: ")
if str(repeat) == "1":
continue
else:
print("Bye!")
break
If asked to find 10 numbers the program outputs:
30
60
90
120
150
180
240
270
300
330
The program didn't print 210 (which is divisible by 7) so the algorithm seems, at least, partly correct, but 330 is printed (which is divisible by 11) and I can't figure out why. If I manually change i to 330 and k to 11, the is_prime function correctly finds that 11 is a prime number, but the is_divisible function still returns 0. I can't figure out what's wrong. Any help will be greatly appreciated!
Thanks!
First, you need to fix your is_prime like #Barmar mentions above
Note, this can be optimized in multiple ways, the simplest of which is to only check for j in range(2, int(math.sqrt(k))+1) because a number k won't have any prime factors greater than sqrt(k). Also, we can memorize all the prime numbers found so far, so that if the same number is checked multiple times, subsequent checks are much faster. You can use better algorithms to check if a number is prime, but this should suffice for our purposes.
import math
# A set to remember prime numbers
primes = set()
def is_prime(k):
if k == 1: return False # 1 is not prime
if k in primes: return True # Check remembered prime numbers
# Check all numbers in the closed interval [2, sqrt(k)]
for j in range(2, int(math.sqrt(k))+1):
if k % j == 0:
return False
# Prime number, so remember it
primes.add(k)
return True
The first n numbers that aren't divisible by any prime numbers other than 2, 3, and 5
Since your number needs to be divisible by 2, 3, and 5, you don't need to look at all numbers as you do currently. Just look at multiples of 2 * 3 * 5, i.e. multiples of 30, since those are the only numbers that are going to be multiples of 2, 3, and 5.
So now your problem becomes: "Print 30 * i, where i is not a multiple of a prime number other than 2, 3, and 5. i.e., you need to get the prime factors of i, and check that this set contains only 2, 3, and 5.
There are a number of ways to get the prime factors of a number. Here's a simple one:
def prime_factors(k):
# If k is prime, it is its only prime factor
if is_prime(k):
return {k}
factors = set()
# If divisible by 2, add 2 as a prime factor
if k % 2 == 0:
factors.add(2)
# Check all odd numbers in the closed interval [3, k//2]
for i in range(3, k//2+1, 2):
if k % i == 0 and is_prime(i):
factors.add(i)
return factors
Now that we've defined our helper functions, we just need to call them:
n = 10
i = 1
count = 0
while count < n:
factors = prime_factors(i)
# If we remove {2, 3, 5} from factors, do we get an empty set?
if not factors.difference({2, 3, 5}):
print(2 * 3 * 5 * i)
count += 1
i += 1
Which prints:
30
60
90
120
150
180
240
270
300
360
If you are indeed looking for regular numbers as #Mark and #Kelly suggest in their comments, then you simply skip the multiplication by 2 * 3 * 5:
n = 10
i = 1
count = 0
while count < n:
factors = prime_factors(i)
# If we remove {2, 3, 5} from factors, do we get an empty set?
if not factors.difference({2, 3, 5}):
print(i)
count += 1
i += 1
gives:
1
2
3
4
5
6
8
9
10
12
Here's a bit of code that looks for values that have other factors besides 2,3,5. If there are other factors in there, they must be other prime values because we remove the prime factors 2,3,5 from the number.
primes = [ 2, 3, 5]
count = 10
answers = []
value = 2
while len(answers) < count:
test_value = value
for prime in primes:
while test_value % prime == 0:
test_value //= prime
if test_value == 1:
answers.append(value)
value += 1
print(answers)
Ok, the performance discussion from #Kelly Bundy bothered me - so I added a different approach - but it's got problems.
import sys
primes = [ 2, 3, 5]
count = int(sys.argv[1])
base = round( count ** (1./3.) )
powers = [0] * len(primes)
answers = []
while True:
value = 1
for n in range(len(primes)):
value *= primes[n] ** powers[n]
answers.append(value)
for n in range(len(powers)):
powers[n] += 1
if powers[n] != base:
break
powers[n] = 0
else:
break
for x in sorted(answers):
print(x)
Basically, all of the numbers we want to find are of the form: 2**x * 3**y * 5**z . And so, if we just vary x,y,and z, we can compute all of the qualifying numbers.
The the problem boils down to, which values of x,y, and z are valid. To be honest, I haven't figured that out. All I do is come up with count combinations of x,y,z where I just count values (using some base counting system). For instance, if I need to come up with 1,000 combinations, I just produce all of the combinations of x,y,z where the values are between 0 and 9. And so i get the values (000 - 999). And this produces the values: 2**0 * 3**0 * 5**0 all the way up to 2**9 * 3**9 * 5**9. Now, I'm definitely missing some values. The 1,000 numbers I come up with are NOT the first 1,000 numbers.
Your is_divisible method basically only checks 7 and then returns either 1 or 0.
You want to check all the numbers in the range.
def is_divisible(i):
for k in range(7, i):
if is_prime(k) == 1 and i % k == 0:
return 1
return 0
Your is_prime method suffers from this issue as well:
def is_prime(k):
for j in range(2, k):
if k % j == 0:
return 0
return 1
Fixing these issues, however, is going make this algorithm EXTREMELY slow so you will need to consider some strategies that will make it faster.
Caching the numbers that you have already checked for primeness would be a start.
I have tried to add sum of even numbers of a list and I am successful but in my second part I am not able to delete even numbers from the list. For example my input is [1,2,4,6,5] and When I tried this given code below, the output for sum of even numbers was 8 and new list was [1,4,5]. I want output as sum of even numbers as 12 and new list is [1,5].
n=list(map(int, input("elements of array:-").strip().split()))
even_sum = 0
for num in n:
if num%2==0:
even_sum += num
n.remove(num)
else:
odd_sum += num
print(even_sum)
print(n)
Here is a slightly more pythonic way to achieve what you want:
L = [1,2,4,6,5]
Lsum = sum([int(elem % 2 == 0) * elem for elem in L])
Lnew = [elem for elem in L if elem % 2 == 1]
You shouldn't iterate over the list and modify it.
n = [1,2,4,6,5]
odd_list = []
even_sum = 0
for num in n:
if num%2==0:
even_sum += num
else:
odd_sum += num
odd_list.append(num)
Heres a more nicer way achieving that only. It is called list comprehension
n = [1, 2, 4, 6, 5]
even_list = [i for i in n if i%2==0]
even_sum = sum(even_list)
// The OP wants an odd list as a result, revised version:
n = [1, 2, 4, 6, 5]
odd_list = [i for i in n if i%2==1]
even_sum = sum(n) - sum(odd_list)
This is happening because during iteration you are skipping some of the elements by removing others from the same sequence...
You can iterate backwards through the list instead. This eliminates the need for copying elements to a new list.
Like this:
n=list(map(int, input("elements of array:-").strip().split()))
i = len(n) -1
while i >= 0:
if n[i] % 2 == 0:
even_sum += n[i]
del n[i]
else:
odd_sum += n[i]
i -= 1
def is_prime(x):
count = 1
my_list = []
while count > 0 and count < x:
if x % count == 0:
my_list.append(x/count)
count += 1
return my_list
my_list = is_prime(18)
def prime(x):
my_list2 = []
for number in my_list:
if number <= 2:
my_list2.append(number)
else:
count = 2
while count < number:
if number % count == 0:
break
else:
my_list2.append(number)
count += 1
return my_list2
print prime(18)
Just started out with Python. I have a very simple question.
This prints: [9, 3, 2].
Can someone please tell me why the loop inside my else stops at count = 2? In other words, the loop inside my loop doesn't seem to loop. If I can get my loop to work, hopefully this should print [2, 3]. Any insight is appreciated!
Assuming that my_list2 (not a very nice name for a list) is supposed to contain only the primes from my_list, you need to change your logic a little bit. At the moment, 9 is being added to the list because 9 % 2 != 0. Then 9 % 3 is tested and the loop breaks but 9 has already been added to the list.
You need to ensure that each number has no factors before adding it to the list.
There are much neater ways to do this but they involve things that you may potentially find confusing if you're new to python. This way is pretty close to your original attempt. Note that I've changed your variable names! I have also made use of the x that you are passing to get_prime_factors (in your question you were passing it to the function but not using it). Instead of using the global my_list I have called the function get_factors from within get_prime_factors. Alternatively you could pass in a list - I have shown the changes this would require in comments.
def get_factors(x):
count = 1
my_list = []
while count > 0 and count < x:
if x % count == 0:
my_list.append(x/count)
count += 1
return my_list
# Passing in the number # Passing in a list instead
def get_prime_factors(x): # get_prime_factors(factors):
prime_factors = []
for number in get_factors(x): # for number in factors:
if number <= 2:
prime_factors.append(number)
else:
count = 2
prime = True
while count < number:
if number % count == 0:
prime = False
count += 1
if prime:
prime_factors.append(number)
return prime_factors
print get_prime_factors(18)
output:
[3, 2]
Just to give you a taste of some of the more advanced ways you could go about doing this, get_prime_factors could be reduced to something like this:
def get_prime_factors(x):
prime_factors = []
for n in get_factors(x):
if n <= 2 or all(n % count != 0 for count in xrange(2, n)):
prime_factors.append(n)
return prime_factors
all is a built-in function which would be very useful here. It returns true if everything it iterates through is true. xrange (range on python 3) allows you to iterate through a list of values without manually specifying a counter. You could go further than this too:
def get_prime_factors(x):
return [n for n in get_factors(x) if n <= 2 or all(n % c != 0 for c in xrange(2, n))]
Can somebody tell me why this should be wrong?
#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, ...
#Find the sum of all the even-valued terms in the sequence
#which do not exceed four million.
sum=2
list = [1,2]
for x in range(2,100):
a = list[x-2]+list[x-1]
print(a)
list.append(a)
if a % 2 == 0:
sum += a
print('sum', sum)
if sum >= 4000000:
break
Here's a completely different way to solve the problem using a generator and itertools:
def fib():
a = b = 1
while 1:
yield a
a, b = b, a + b
import itertools
print sum(n for n in itertools.takewhile(
lambda x: x <= 4000000, fib()) if n % 2 == 0)
Output:
4613732
So your code, even though it is wrong (see other answers), happens to give the correct answer.
replace
sum += a
print('sum', sum)
if sum >= 4000000:
break
with
if a > 4000000:
break
sum += a
print('sum', sum)
You should compare "a" with 4000000, not "sum", like Daniel Roseman said.
The question asked for the sum of even terms which do not exceed four million. You're checking if the sum doesn't exceed 4m.
I'm trying to solve the same problem - although I understand the logic to do it, I don't understand why this works (outputs the right sum)
limit = 4000000
s = 0
l = [1,2]
while l[-1]<limit:
n = l[-1]+l[-2]
l.append(n)
print n
And then then moment I put in the modulo function, it doesn't output anything at all anymore.
limit = 4000000
s = 0
l = [1,2]
while l[-1]<limit:
n = l[-1]+l[-2]
if n % 2 == 0 :
l.append(n)
print n
I'm sure this is fairly simple...thanks!
This is the code I used. It is very helpful and teaches you about generators.
def fib():
x,y = 0,1
while True:
yield x
x,y = y, x+y
def even(seq):
for number in seq:
if not number % 2:
yield number
def under_a_million(seq):
for number in seq:
if number > 4000000:
break
yield number
print sum(even(under_a_million(fib())))
-M1K3
Keep it simple and it should take you less than 0.1 seconds.
from datetime import datetime
x, y = 1, 1
total = 0
for i in xrange (1, 100):
x = x + y
if x % 2 == 0 and x <= 4000000:
total += x
y = y + x
if y % 2 == 0 and x <= 4000000:
total += y
print total
starttime = datetime.now()
print datetime.now() - starttime