Reputation: 239
I'm python newbie and got a problem while doing some practices.
Below is the code that I've got so far:
def gt(nums, n):
for c in nums:
if n < c:
return True
elif c < n:
return False
else:
break
With above code, it does not return properly. The examples of correct answers here:
gt([1,2,3],3) => False
gt([1,2,3],2) => True
Upvotes: 0
Views: 1339
Reputation: 8207
This could be better
def gt(nums, n):
for c in nums:
if n < c:
return True
return False
Upvotes: 0
Reputation: 95358
A simpler and more readable solution would be the following:
def gt(lst, n):
return max(lst) > n
Upvotes: 7
Reputation: 56694
Long-ish response to Niklas B.'s comment:
I decided to test this, and here are the results. Blue dots are your function, green are Mario's; y axis is runtime in seconds, x axis is len(nums).
As you said, both are O(n). Yours is faster up to about 45 items; for anything over 100 items, his is roughly twice as fast.
It's mostly irrelevant - this seems to be more of a beginner syntax question than anything else - and, as you say, Python isn't a speed demon to begin with. On the other hand, who doesn't like a bit more speed (so long as readability doesn't suffer)?
For those interested, here's the code I wrote to test this:
from random import randint
from timeit import Timer
import matplotlib.pyplot as plt
def gt1(nums, n):
# based on Niklas B.'s answer - NOTE comparison is corrected
return n < max(nums)
def gt2(nums, n):
# based on Mario Fernandez's answer
return any(e > n for e in nums)
def make_data(length, lo=0, hi=None):
if hi is None:
hi = lo + length - 1
elif lo > hi:
lo,hi = hi,lo
return [randint(lo, hi) for i in xrange(length)]
def make_args(d):
nums = make_data(d)
n = randint(0,d)
return "{}, {}".format(nums, n)
def time_functions(fns, domain, make_args, reps=10, number=10):
fns = [fn.__name__ if callable(fn) else fn for fn in fns]
data = [[] for fn in fns]
for d in domain:
for r in xrange(reps):
args = make_args(d)
for i,fn in enumerate(fns):
timer = Timer(
setup='from __main__ import {}'.format(fn),
stmt='{}({})'.format(fn, make_args(d))
)
data[i].extend((d,res) for res in timer.repeat(number=number))
return data
def plot_data(data, formats=None):
fig = plt.figure()
ax = fig.add_subplot(111)
if formats is None:
for d in data:
ax.plot([x for x,y in d], [y for x,y in d])
else:
for d,f in zip(data, formats):
ax.plot([x for x,y in d], [y for x,y in d], f)
plt.show()
def main():
data = time_functions([gt1, gt2], xrange(10, 501, 10), make_args)
plot_data(data, ['bo', 'g.'])
if __name__=="__main__":
main()
Upvotes: 1
Reputation: 47287
using a one liner
def gt(nums, n):
return any(e > n for e in nums)
this breaks when the first element bigger than n is found.
Upvotes: 4