简体   繁体   中英

Optimizing code for python, values from a 2d array

I just wrote this bit of code and was wondering if there was any way to optimize the print out. I attempted to use a .format() to include the total and the 'even' or 'odd'. If I just assign the return from the function to a variable prior to calling would I be able to limit to one print statement?

Basically this code you enter a 2d array and it will return the total value.

def evenrow(TwoDArray):
    counter = 0
    counterTwo = 0
    lengthArray = len(TwoDArray)
    lengthList = len(TwoDArray[0])
    while counter < lengthArray:
        while counterTwo < lengthList:
            value = TwoDArray[counter][counterTwo]
            value += value
            counterTwo += 1
        counter += 1
    return value

TwoDArray = eval(input("Enter a 2D array: "))
print('Total Value: ', evenrow(TwoDArray))
if evenrow(TwoDArray) % 2 == 0:
    print('Even or Odd: Even')
else:
    print('Even or Odd: Odd')

Example of output:

Enter a 2D array: [[0,2],[1,1]]
Total Value:  4
Even or Odd: Even

Thanks!

Welcome to StackOverflow! I hope you have a great time here.

As to your question - easy as pie:

ret = evenrow(TwoDArray)
if ret % 2 == 0:
    print('Total Value: %d\nEven or Odd: Even' % ret)
else:
    print('Total Value: %d\nEven or Odd: Odd' % ret)

I can even do you one better and get it down to one line using Python's equivalent of the ternary operator:

ret = evenrow(TwoDArray)
print('Total Value: %d\nEven or Odd: %s' % (ret, 'Odd' if ret % 2 else 'Even'))

You'd want to save the return value anyway. Imagine if evenrow() were a computationally expensive operation -- you certainly wouldn't want to run it twice.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM