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))
Related
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 find_even_index(arr):
for a in arr:
b = arr.index(a)
if sum(arr[b+1:]) == sum(arr[:b]):
return b
return -1
find_even_index([20,10,30,10,10,15,35])
>>> -1
My code works for all type of data except when it encounters a same digit before or after the number. The index does not change for other 10. Why?
Just writing out the solution that #Barmar is suggesting in his comments (+1):
def find_even_index(array):
for index in range(len(array)):
if sum(array[:index]) == sum(array[index + 1:]):
return index
return -1
print(find_even_index([20, 10, 30, 10, 10, 15, 35]))
Alternatively, if we wanted to avoid so many calls to sum(), and make good use of enumerate(), we could try:
def find_even_index(array):
total = sum(array)
partial_sum = 0
for index, number in enumerate(array):
if total - partial_sum == number:
return index
partial_sum += number * 2
return -1
The list.index() function will only return the index of the specified object closest to the start of the list. You can instead use enumerate to iterate through the list alongside each object's index:
def find_even_index(arr):
for i, a in enumerate(arr): # For index, number in arr
b = i
if sum(arr[b+1:]) == sum(arr[:b]):
return b
return -1
print(find_even_index([20,10,30,10,10,15,35]))
Output:
3
Given a list of integers and number, I want to find the sum of all numbers in the list such that numbers and before and after a given number are not added. The given number should also be excluded from the numbers used for the final sum.
Examples:
mylist=[1,2,3,4]
number=2
#output is 4
mylist=[1,2,2,3,5,4,2,2,1,2]
number=2
#output is 5
mylist=[1,7,3,4,1,7,10,5]
number=7
#output is 9
mylist=[1,2,1,2]
number=2
#output is 0
In the first example, only the number 4 is not adjacent to the number 2. Thus the sum is 4. In the last example, no numbers meet the criteria so the sum is 0.
This is what I tried:
def add(list1,num):
for i,v in enumerate(list1):
if v==num:
del list1[i-1:i+2]
print list1
add([1,7,3,4,1,7,10,5],7)
However, my code only works for first and third example.
I worked through your code and here is a working solution:
def check_around(array, index, num):
return True if array[index - 1] != num and array[index + 1] != num else False
def get_result(array, num):
arr = []
for i, number in enumerate(array):
if number != num:
if i == 0 and array[1] != num: # Beginning of list
arr.append(number)
elif (i > 0 and i < len(array) - 1) and check_around(array, i, num): # Middle of list
arr.append(number)
elif i == len(array) - 1 and array[i-1] != num: # End of list
arr.append(number)
return arr
test = [([1,2,3,4], 2),
([1,2,2,3,5,4,2,2,1,2], 2),
([1,7,3,4,1,7,10,5], 7),
([1,2,1,2], 2)]
for (arr, num) in test:
res = get_result(arr, num)
print(f'output is {sum(res)}')
#output is 4
#output is 5
#output is 9
#output is 0
The idea is to create a temp array that saves items that do belong in the summation. Otherwise, we ignore them.
I tried all the tests you gave and it seems to be working fine. Hope this helps.
Get the indexes of the element into a list. +1 and -1 to those will give you indexes of 'before' and 'after' elements. Then take the sum avoiding elements in all these indexes.
list=[1,2,2,3,5,4,2,2,1,2]
number=2
#get all indexes of that number
list_of_indexes=[i for i,x in enumerate(list) if x==number]
#no need to remove -1 if there b'coz we are going to enumerate over 'list'
before_indexes=[i-1 for i in list_of_indexes]
#no need to remove len(list) index if present
after_indexes=[i+1 for i in list_of_indexes]
#might contain duplicate values but no problem
all_indexes_to_avoid=list_of_indexes+before_indexes+after_indexes
sum=sum([x for i,x in enumerate(list) if i not in all_indexes_to_avoid ])
print(sum)
Output
5
Why not just use a if statement and generate a new list instead of removing from the list?
def add(list,num):
j=0
new_list=[]
for i in range(len(list)):
if (i<len(list)-1 and list[i+1]==num) or list[i]==num or list[j]==num:
pass
else:
new_list.append(list[i])
j=i
print(sum(new_list))
print(new_list)
return sum
add([1,2,3,4],2)
add([1,2,2,3,5,4,2,2,1,2],2)
add([1,7,3,4,1,7,10,5],7)
add([1,2,1,2],2)
OUTPUT
4
[4]
5
[5]
9
[4, 5]
0
[]
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))]
What I need is to show how many integers that are less than N that are not dividable by 2,3 or 5. I have managed to get the list of numbers that are less than N and are not divisible by 2,3 or 5 but I cannot for the life of me get Python to actually count how many integers there are.
What I have so far is
N = int(input("\nPlease input a Number "))
if N < 0:
print("\nThere are no answers")
else:
for a in range(1,N+1,2):
if a%3 !=0:
if a%5 !=0:
Try this:
N = 20
counter = 0
for a in range(1, N):
if a%2 and a%3 and a%5:
counter += 1
The result will be in counter at the end of the loop. Or for a fancier version, adapted from #iCodez's answer:
sum(1 for x in range(1, N) if all((x%2, x%3, x%5)))
=> 6
Have you tried declaring a global variable and incrementing it?
i = 0
... if a % 5 != 0:
i += 1
print i
This can be done quite easily using a list comprehension, all, and len:
>>> num = int(input(':'))
:20
>>> [x for x in range(num) if all((x%2, x%3, x%5))]
[1, 7, 11, 13, 17, 19]
>>> len([x for x in range(num) if all((x%2, x%3, x%5))])
6
>>>