It says I have invalid syntax at Sum += 1. If my code is incorrect what is a better way to go about counting how many even numbers are in a list?
def countEvens(listOfInts):
'''
- Returns an integer value representing the number of even numbers that
exist in listOfInts.
- Return 0 if listOfInts is not a list type or if no even number exists
in listOfInts.
- Note: elements in listOfInts can contain any data type.
'''
Sum = 0
for x in listOfInts:
if x % 2 == 0:
return Sum += 1
if type(listOfInts) != list:
return 0
In Python you cannot return assignments. And Sum += 1 is an assignment, it assigns Sum + 1 to Sum.
In fact the return isn't just a SyntaxError it's also wrong (in a logical sense), so just remove it:
Sum = 0
for x in listOfInts:
if x % 2 == 0:
Sum += 1
return Sum
Alternatively you can use sum with a generator:
return sum(1 for value in listOfInts if value % 2 == 0)
The syntax error comes from this line, as you say
return Sum += 1
That's because (Sum += 1) is not a valid value to return from a function. It's a separate statement
Keeping your code as close as possible, try this
Sum += 1
return Sum
or, more simply
return Sum+1
As for a more pythonic approach
def countEvens(listOfInts):
return sum( x % 2 == 0 for x in listOfInts )
does the entire thing
Related
Write a function that takes an array/list of numbers and returns a number.
See the examples and try to guess the pattern:
even_odd([1,2,6,1,6,3,1,9,6]) => 393
even_odd([1,2,3]) => 5
even_odd([0,2,3]) => 3
even_odd([1,0,3]) => 3
even_odd([3,2]) => 6
def even_odd(arr):
count = 0
index = 0
length = len(arr)
while index < length:
for num in range(len(arr)):
if arr[index] % 2 != 0:
count += arr[index]
index += 1
else:
count *= arr[index]
index += 1
return count
So basically the pattern is multiply the first 2 numbers and add the third and I set it to where for each index value if it it was the first number I would add it to the count to keep track and then multiply it with the second number and then add the third. I passed 3/4 sample cases except for one which was the first one ---> even_odd([1,2,6,1,6,3,1,9,6]) => 393. I am just wondering what is the flaw with my logic and does anyone have a better way to solve this that is efficient and clean.
Your question is a challenge on Codewars (https://www.codewars.com/kata/559e708e72d342b0c900007b), so maybe you should use this platform to discuss solutions with other competitiors, instead of Stackoverflow.
The main point of this challange is to investigate the calculated pattern and not the code itself.
If you know the required pattern, the code is easy (Spoiler!):
def even_odd(arr):
num = 0
for i, e in enumerate(arr):
if (i % 2) == 0:
num += e
else:
num *= e
return num
This produces the desired results:
from operator import add, mul
def even_odd(nums):
acc = nums[0] # accumulator
ops = [mul, add]
i = 0
for num in nums[1:]:
acc = ops[i](acc, num)
i = 1 - i # alternates between the two operators
return acc
I'm new to python and I'm trying to create a function which would count all the odd digits in a string and would return the average number calculated as a float. For example, if the string is ("*1*2*3*4"), the function should return the average of 1 and 3 (odd digits in string) which is 2. If there are no odd numbers, the function should return 0. I know the code below is incorrect but that's as far as I've been able to get. Thank you for your help.
def Odd(ww):
Result = 0.0
for i in (ww):
if i.isdigit():
if int(i) % 2 != 0:
Result = Result + int(i)
if int(i) % 2 == 0:
return Result
return Result // 2
You can't simply divide by 2; you have to count the quantity of odd digits and divide by that count.
You can't quit at the first even digits; you have to finish the string to find all the odds.
The problems are at the end of your code:
if int(i) % 2 == 0:
return Result # Nope -- keep a count and a running sum to use later.
return Result // 2 # Nope -- divide the sum by the count.
Here:
def avg(l):
if (l is None or len(l) == 0):
return 0
return sum(l) / len(l)
def odd(l):
return [e for e in l if e % 2 != 0]
def oddavg(l):
return float(avg(odd(l)))
def onlydigit(s):
return (int(c) for c in s if c.isdigit())
def oddavgstr(s):
return oddavg(onlydigit(s))
assert avg([1,2,3]) == 2
assert avg(None) == 0
assert odd([1,2,3]) == [1,3]
assert oddavg([1,2,3,4]) == 2
assert oddavg([2,4,6]) == 0
assert list(onlydigit('h3l00')) == [3, 0, 0]
assert oddavgstr('1*2*3*4') == 2
assert oddavgstr('2*2') == 0
I'm using function composition to achieve your goal. The avg can be found at numpy but the above is just enough. We covert the string to a list of digits (ints), the isolate the odds and calculate the average.
I hope this helps. Regards,
The problem is you need a count to find the number of odd numbers found in the string:
def Odd(ww):
Result = 0.0
count = 0
for i in (ww):
if i.isdigit():
if int(i) % 2 != 0:
Result = Result + int(i)
count += 1
return Result if not Result else Result/float(count)
print(Odd("*1*2*3*4"))
Output:
2
You could do something like this:
def odd(val):
result = 0
count = 0
for i in val:
if i.isdigit() and int(i) % 2 != 0:
result += int(i)
count += 1
return float(result / count) if result > 0 else 0.0
Note: Average is calculated with (sum of values) / (number of values)
For example: (1 + 3 + 5) / (3) = 3
I'm new to programming and was asked to sum odd numbers from 1 to (2*n)-1 using a while loop.
This is my attempt:
def sum_odd_n(n):
while n<2*n:
sum = 0
if n%2==1:
sum = sum+n
return (sum)
May i know my mistake? Any help will be appreciated
The condition while n<2*n: is always true while n >= 0, you'll have an infinite loop. Try the following
def sum_odd(n):
value = 1
total = 0
while value < (2*n) - 1:
if value % 2 == 1:
total += value
value += 1
return total
>>> sum_odd(25)
576
For completeness the more pythonic way to handle this would be using sum with a generator expression
def sum_odd(n):
return sum(i for i in range(1, 2*n -1) if i%2 == 1)
The first hint would be to take a look at your condition in while loop:
while n < 2*n
Notice that this will always be true, because if n>0, then 2*n is always greater. If you need more help, write a comment ;)
UPDATE: I will just tell you what is wrong so if you want to try it out first on your own, stop reading. So basically you need another variable, let's say i that will loop through integers. Then you can do something like this:
def sum_odd_n(n):
i = n
sum = 0
while i < 2*n:
if i % 2 == 1:
sum += i
i += 1
print sum # for python3: print(sum)
>>> def sum_odd_n(n):
... return sum([2 ** i for i in range(0,n,1) ])
...
>>> sum_odd_n(2)
3
>>> sum_odd_n(5)
31
>>>
I'll try to point out the mistakes you have done, and try to offer corrections.
def sum_odd_n(n):
while n<2*n: # n will always be less than ('<') 2*n. For eg, if n=5, 5<10.
sum = 0 # you are resetting the sum at every iteration. We need to take this outside.
if n%2==1:
sum = sum+n
return (sum)
Here's what I think should work.
def sum_odd_n(n):
sum = 0 # sum is initialized here, so that it doesn't reset inside the loop
iterator = 0
while iterator<2*n
if iterator%2==1:
sum = sum+iterator # or sum += iterator
iterator = iterator + 1 # otherwise this will be an infinite loop, as iterator will always be 0.
return sum
Hope this works for you. :-)
This worked for me:
def sum_odd(n: int):
total = 0
for x in range(2*n):
if x%2==1:
total += x
return total
I've been trying to find how do I do check the length of integer using recursion. For example: 100, it will say that there's 3 number. 12, it will say that there's 2 number.
What I've saw online is all about the summation of the last digit. I couldn't source for help on the length of an integer.
can someone help me out on this?
I've tried to use lens to count, but my output is always 0.
def num(x):
if x == 0:
return 0
else:
return num(x / 10)
print len(str(num(100)))
I've also tried this
def num(x):
if x == 0:
return 0
else:
return num(x / 10) + len(str(x % 10))
print num(100)
You need to add 1 with num(N/10) if N is not 0 :
>>> def num(N):
... if N==0:
... return 0
... return 1+num(N/10)
...
>>> num(100)
3
This code will add ones in each calling the function with N/10 until it get to 0, so at the end based on what time your number can bi divide by 10 you'll have 1's which have been sum together, and at last for 0 they eill be add with 0.
For example for 100 your function will do the following :
1+(100/10)
^
1+1+(10/10)
^
1+1+1(1/10)
^
1+1+1+0
Are you looking for this -
def numlen(i):
if i:
return numlen(i//10) + 1
return 0
I am wondering why this code prints 1 when I call the max() function? I want it to return 525 (the maximum length that can be created from the numbers below 1 million by the collatz function). I am new to python, and was just wondering what I am misunderstanding!
Question: https://projecteuler.net/problem=14 (I know the solution is not full)
def collatz(n):
count = 1
while n > 1:
count += 1
if n % 2 == 0:
n = n/2
else:
n = 3*n + 1
return count
def max():
greatest = 1
for i in xrange(1000000):
length = collatz(i)
if length > greatest:
length = greatest
return greatest
print max()
The value of greatest is never updated inside the for-loop of function max. This line is backwards:
length = greatest
It should be:
greatest = length
Yes you have done wrong assignment.
Use length = greatest in place of greatest = length