Iterate through list of intervals in Python and return odd and even values? -
i'm working on fragment of code homework assignment.
i want to:
- get user input(n).
- make list out of input(n) range.
- iterate through list.
- count odds , evens.
- return odds , evens use in function
i stumped , far got:
def input(): n = eval(input("enter number: ")) def getodds(n): odd_count = 0 even_count = 0 list_start = list[1] list_cont = list[1:] in range(n): ## know i'll using ## if position % 2 == 0: even_count = even_count+1 return even_count return odd_count
you want like:
def getoddevencount(n): odd_count = 0 even_count = 0 elem in range(n): if elem % 2 == 0: even_count += 1 else: odd_count += 1 return odd_count, even_count
example usage :
odd_count, even_count = getoddevencount(10) print("odds:", odd_count, "evens:", even_count)
outputs:
odds: 5 evens: 5
note however, if you're returning counts, , not list of actual odd/even values, return value of function can computed trivially in o(1) time taking advantage of fact even integer n, return value (n/2, n/2)
, , odd integer n, return value (floor(n/2), floor(n/2) + 1)
Comments
Post a Comment