0
\$\begingroup\$
import random

myNumbers = [random.randint(1, 10) for i in range(0, 7)]
myNumbers.sort() #Binary search works on a sorted list.

print(myNumbers)

#How about this code:

binSearch = lambda anyList, item: anyList[int(len(anyList)/2)] \
if anyList[int(len(anyList)/2)] == item \ 
else None \ 
if int(len(anyList)/2) == 0 \
else binSearch(anyList[0:int(len(anyList)/2)], item) \ 
if anyList[int(len(anyList)/2)] > item \ 
else binSearch(anyList[int(len(anyList)/2):], item)

print(binSearch(myNumbers, 6))

Is it more or less elegant code? I'm beginner and I'm wondering if writing recursion in one line is a good practice.

\$\endgroup\$
2
  • 5
    \$\begingroup\$ I wouldn't say that writing anything in one line is good practice if multiple lines would be clearer (and yes, here I would find a normal function much easier to read). \$\endgroup\$ Apr 2, 2022 at 18:48
  • \$\begingroup\$ Is it more or less elegant code? : After 10 months, have a look at that code again. The answer will be ... \$\endgroup\$
    – AcK
    Feb 18 at 13:19

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.