2

Could you let me know how I can optimize the following code?

def f(y, list_or_elem):
  if getattr(list_or_elem, '__iter__'):
    y = max(y, *list_or_elem)
  else:
    y = max(y, list_or_elem)
mechanical_meat
  • 163,903
  • 24
  • 228
  • 223
Cheolho
  • 21
  • 1
  • Don't forget that strings are iterable too, so `f("xxx", "abz")` will return "z", which is probably not what you want. – Dave Kirby May 13 '10 at 06:07
  • On second thoughts your function does not return anything - it assigns the result to y, which is local to the function. It will do nothing, whatever arguments you pass it. – Dave Kirby May 13 '10 at 06:09

2 Answers2

1

The best optimization of all would be to avoid such silliness as taking "either a list or a single element" as an argument. But, if you insist, it's better to use a try/except to remove the anomaly ASAP and make what's sure to be an iterable:

try: iter(list_or_elem)
except TypeError: iterable = [list_or_elem]
else: iterable = list_or_elem
y = max(y, *iterable)
Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
0

if you are willing to have add flatten function in your code (theres a good one here) which can basically take a list of lists of lists of... and bring it down to a single list, you can do something like

y = max(flatten([y, list_or_elem]))
Aditya Mukherji
  • 9,099
  • 5
  • 43
  • 49