Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pythonic method of determining if a list's contents change from odd to even values

Tags:

python

list

Writing some test cases and my mind wanders, assuming there is a better way to write something like this. I have a list, its numbers transition from all odd values to all even, doesn't matter where. I need to assert this is the case, here's what I came up with:

values = [1, 3, 5, 7, 5, 3, 5, 3, 5, 7, 4, 6, 8, 4, 2, 2, 8, 6]

# find all the indexes of odd and even values
odds = [i for (i, v) in enumerate(values) if v % 2 == 1]
evens = [i for (i, v) in enumerate(values) if v % 2 == 0]

# indexes should be a continuous sequence: 0, 1, 2, 3 ... n
assert odds + evens == range(evens[-1] + 1)

Seems like a long way to go. Suggestions on how this could be reduced?

like image 808
Nick Veys Avatar asked Apr 20 '11 22:04

Nick Veys


People also ask

How do you determine if a list is even or odd?

Example 1: count Even and Odd numbers from given list using for loop Iterate each element in the list using for loop and check if num % 2 == 0, the condition to check even numbers. If the condition satisfies, then increase even count else increase odd count.

How do you check if all values in a list are even?

def is_list_even() returns true if all integers in the list are even and false otherwise. def is_list_odd() returns true if all integers in the list are odd and false otherwise.

What type of function can be used to determine whether a number is even or odd in Python?

num = int (input (“Enter any number to test whether it is odd or even: “) if (num % 2) == 0: print (“The number is even”) else: print (“The provided number is odd”) Output: Enter any number to test whether it is odd or even: 887 887 is odd. The program above only accepts integers as input.

How do you check if numbers in a list are even or odd Python?

Python Code:num = int(input("Enter a number: ")) mod = num % 2 if mod > 0: print("This is an odd number. ") else: print("This is an even number. ")


2 Answers

A possible solution is to consider that you allow only

odd->odd
odd->even
even->even

in other words the only forbidden transition is

even->odd

and this translates to

(0, 1) not in ((x%2, y%2) for x, y in zip(values, values[1:]))
like image 73
6502 Avatar answered Nov 09 '22 21:11

6502


[x for x in values if x % 2 == 1] + [x for x in values if x % 2 == 0] == values

This is only true, if values starts with all of it's own odd values, followed by all of its even values.

like image 37
Ishtar Avatar answered Nov 09 '22 21:11

Ishtar