HiveBrain v1.2.0
Get Started
← Back to all entries
patternpythonMajor

Program to find the largest odd number among three variables

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
threeamongthenumberprogramlargestvariablesfindodd

Problem

def greatest(a,b):
    if a>b:
        return a
    return b
def odd_check(a):
    return not(a%2 == 0)
def go(x,y,z):
    a = odd_check(x)
    b = odd_check(y)
    c = odd_check(z)
    if a and b and not c:
        print greatest(x,y)
    elif a and not b and c:
        print greatest(x,z)
    elif not a and b and c:
        print greatest(y,z)
    elif not a and not b and c:
        print z
    elif not a and b and not c:
        print y
    elif a and not b and not c:
        print x
    elif a and b and c:
        print greatest(x,greatest(y,z))
    else:
        print "None of them are odd"
go(int(input()),int(input()),int(input()))


Doing the problem it felt like I am going over all the eight combinations \$2^3\$ for three variables. Is there any way to avoid this?

Solution

You could filter out the even numbers, and then get the maximal value:

def odd_check(a):
    return not(a%2 == 0)

def go(x, y, z):
    l = [e for e in [x, y, z] if odd_check(e)]
    try:
        print(max(l))
    except ValueError:
        print("None of them are odd")

Code Snippets

def odd_check(a):
    return not(a%2 == 0)

def go(x, y, z):
    l = [e for e in [x, y, z] if odd_check(e)]
    try:
        print(max(l))
    except ValueError:
        print("None of them are odd")

Context

StackExchange Code Review Q#138510, answer score: 28

Revisions (0)

No revisions yet.