Reimplementation of min() in PythonReimplementation of C++ vectorSize improvements for cat reimplementationReimplementation of a Hashtable and hash functionReimplementation of Underscore _.throttleReimplementation of Laravel's config systemReimplementation of Python's dequeOptimisation suggestions for Min HeapMin/Max Heap implementation in PythonReimplementation of call() method in JavaScriptMin Heap implementation [C++]

In which case does the Security misconfiguration vulnerability apply to?

How to find directories containing only specific files

Why did Saruman lie?

Scam? Phone call from "Department of Social Security" asking me to call back

What is a "soap"?

Is there a SQL/English like language that lets you define formulations given some data?

How big are the Choedan Kal?

What is the difference between 王 and 皇?

Is it possible to grow new organs through exposure to radioactivity?

The cat ate your input again!

Case Condition for two lines

How should I write this passage to make it the most readable?

Why am I not billed for EOB balance?

Does EU compensation apply to flights where the departure airport closes check-in counters during protests?

How far did Gandalf and the Balrog drop from the bridge in Moria?

How to remove ambiguity: "... lives in the city of H, the capital of the province of NS, WHERE the unemployment rate is ..."?

Boss wants me to ignore a software API license prohibiting mass download

Word for an event that will likely never happen again

Why aren't rockets built with truss structures inside their fuel & oxidizer tanks to increase structural strength?

How would you translate this? バタコチーズライス

How can God warn people of the upcoming rapture without disrupting society?

How can I communicate my issues with a potential date's pushy behavior?

Do Reform Jews believe in a theistic God?

Why aren't rainbows blurred-out into nothing after they are produced?



Reimplementation of min() in Python


Reimplementation of C++ vectorSize improvements for cat reimplementationReimplementation of a Hashtable and hash functionReimplementation of Underscore _.throttleReimplementation of Laravel's config systemReimplementation of Python's dequeOptimisation suggestions for Min HeapMin/Max Heap implementation in PythonReimplementation of call() method in JavaScriptMin Heap implementation [C++]






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1












$begingroup$


I'm reimplementing the min() function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:



def my_min(num_list):
minimum = num_list[0]
for num in num_list[1:]:
if num < minimum:
minimum = num
return minimum


My question is: How bad is num_list[1:] in the for loop? And are there any other optimizations I could make to the code?



My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.










share|improve this question











$endgroup$













  • $begingroup$
    what happens if num_list has only 1 element?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    @dfhwze, I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element
    $endgroup$
    – jeremy radcliff
    8 hours ago










  • $begingroup$
    If the purpose is to comply to the specification of min, you are far away from home: programiz.com/python-programming/methods/built-in/min.
    $endgroup$
    – dfhwze
    8 hours ago






  • 1




    $begingroup$
    @dfhwze, good point, I edited my question
    $endgroup$
    – jeremy radcliff
    7 hours ago

















1












$begingroup$


I'm reimplementing the min() function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:



def my_min(num_list):
minimum = num_list[0]
for num in num_list[1:]:
if num < minimum:
minimum = num
return minimum


My question is: How bad is num_list[1:] in the for loop? And are there any other optimizations I could make to the code?



My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.










share|improve this question











$endgroup$













  • $begingroup$
    what happens if num_list has only 1 element?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    @dfhwze, I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element
    $endgroup$
    – jeremy radcliff
    8 hours ago










  • $begingroup$
    If the purpose is to comply to the specification of min, you are far away from home: programiz.com/python-programming/methods/built-in/min.
    $endgroup$
    – dfhwze
    8 hours ago






  • 1




    $begingroup$
    @dfhwze, good point, I edited my question
    $endgroup$
    – jeremy radcliff
    7 hours ago













1












1








1





$begingroup$


I'm reimplementing the min() function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:



def my_min(num_list):
minimum = num_list[0]
for num in num_list[1:]:
if num < minimum:
minimum = num
return minimum


My question is: How bad is num_list[1:] in the for loop? And are there any other optimizations I could make to the code?



My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.










share|improve this question











$endgroup$




I'm reimplementing the min() function as an exercise (EDIT: not all the functionality of the python std library function, just the minimum of a list of numbers). Here is my code:



def my_min(num_list):
minimum = num_list[0]
for num in num_list[1:]:
if num < minimum:
minimum = num
return minimum


My question is: How bad is num_list[1:] in the for loop? And are there any other optimizations I could make to the code?



My intention by truncating the list is to avoid comparing the list's first element to itself. While insignificant in terms of wasted time and resources, I just find it lacking elegance.







python reinventing-the-wheel






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 5 hours ago









200_success

135k21 gold badges173 silver badges443 bronze badges




135k21 gold badges173 silver badges443 bronze badges










asked 8 hours ago









jeremy radcliffjeremy radcliff

2502 silver badges9 bronze badges




2502 silver badges9 bronze badges














  • $begingroup$
    what happens if num_list has only 1 element?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    @dfhwze, I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element
    $endgroup$
    – jeremy radcliff
    8 hours ago










  • $begingroup$
    If the purpose is to comply to the specification of min, you are far away from home: programiz.com/python-programming/methods/built-in/min.
    $endgroup$
    – dfhwze
    8 hours ago






  • 1




    $begingroup$
    @dfhwze, good point, I edited my question
    $endgroup$
    – jeremy radcliff
    7 hours ago
















  • $begingroup$
    what happens if num_list has only 1 element?
    $endgroup$
    – dfhwze
    8 hours ago










  • $begingroup$
    @dfhwze, I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element
    $endgroup$
    – jeremy radcliff
    8 hours ago










  • $begingroup$
    If the purpose is to comply to the specification of min, you are far away from home: programiz.com/python-programming/methods/built-in/min.
    $endgroup$
    – dfhwze
    8 hours ago






  • 1




    $begingroup$
    @dfhwze, good point, I edited my question
    $endgroup$
    – jeremy radcliff
    7 hours ago















$begingroup$
what happens if num_list has only 1 element?
$endgroup$
– dfhwze
8 hours ago




$begingroup$
what happens if num_list has only 1 element?
$endgroup$
– dfhwze
8 hours ago












$begingroup$
@dfhwze, I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element
$endgroup$
– jeremy radcliff
8 hours ago




$begingroup$
@dfhwze, I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element
$endgroup$
– jeremy radcliff
8 hours ago












$begingroup$
If the purpose is to comply to the specification of min, you are far away from home: programiz.com/python-programming/methods/built-in/min.
$endgroup$
– dfhwze
8 hours ago




$begingroup$
If the purpose is to comply to the specification of min, you are far away from home: programiz.com/python-programming/methods/built-in/min.
$endgroup$
– dfhwze
8 hours ago




1




1




$begingroup$
@dfhwze, good point, I edited my question
$endgroup$
– jeremy radcliff
7 hours ago




$begingroup$
@dfhwze, good point, I edited my question
$endgroup$
– jeremy radcliff
7 hours ago










2 Answers
2






active

oldest

votes


















3












$begingroup$

iterators



You can use an iterator



def my_min(num_list):
# empty lists
if not num_list:
raise ValueError('Empty list')

list_iter = iter(num_list)
minimum = next(list_iter)
for num in list_iter:
if num < minimum:
minimum = num
return minimum


In response to Mathias' comment, here is a version that works with an iterable:



def my_min(seq):
seq = iter(seq)

try:
minimum = next(seq)

for num in seq:
if num < minimum:
minimum = num

return minimum

except StopIteration as e:
pass

raise ValueError('Empty list')





share|improve this answer











$endgroup$










  • 1




    $begingroup$
    This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the next call, you could handle all kind of iterables, not only lists.
    $endgroup$
    – Mathias Ettinger
    6 hours ago










  • $begingroup$
    @MathiasEttinger good idea. Added it to the answer.
    $endgroup$
    – RootTwo
    5 hours ago


















1












$begingroup$

Review




I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element




  • You have implemented a simple function, so it shouldn't have been that hard to provide a couple of unit tests. You would have immediately found bugs on the most obvious edge cases as (1) empty list and self-created edge case (2) single item.


While insignificant in terms of wasted time and resources, I just
find it lacking elegance.




  • What you gain in elegance is lost by the edge case guards you'd have to build in to fix the bugs.





share|improve this answer









$endgroup$














  • $begingroup$
    To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?
    $endgroup$
    – jeremy radcliff
    7 hours ago













Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "196"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: false,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: null,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226060%2freimplementation-of-min-in-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























2 Answers
2






active

oldest

votes








2 Answers
2






active

oldest

votes









active

oldest

votes






active

oldest

votes









3












$begingroup$

iterators



You can use an iterator



def my_min(num_list):
# empty lists
if not num_list:
raise ValueError('Empty list')

list_iter = iter(num_list)
minimum = next(list_iter)
for num in list_iter:
if num < minimum:
minimum = num
return minimum


In response to Mathias' comment, here is a version that works with an iterable:



def my_min(seq):
seq = iter(seq)

try:
minimum = next(seq)

for num in seq:
if num < minimum:
minimum = num

return minimum

except StopIteration as e:
pass

raise ValueError('Empty list')





share|improve this answer











$endgroup$










  • 1




    $begingroup$
    This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the next call, you could handle all kind of iterables, not only lists.
    $endgroup$
    – Mathias Ettinger
    6 hours ago










  • $begingroup$
    @MathiasEttinger good idea. Added it to the answer.
    $endgroup$
    – RootTwo
    5 hours ago















3












$begingroup$

iterators



You can use an iterator



def my_min(num_list):
# empty lists
if not num_list:
raise ValueError('Empty list')

list_iter = iter(num_list)
minimum = next(list_iter)
for num in list_iter:
if num < minimum:
minimum = num
return minimum


In response to Mathias' comment, here is a version that works with an iterable:



def my_min(seq):
seq = iter(seq)

try:
minimum = next(seq)

for num in seq:
if num < minimum:
minimum = num

return minimum

except StopIteration as e:
pass

raise ValueError('Empty list')





share|improve this answer











$endgroup$










  • 1




    $begingroup$
    This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the next call, you could handle all kind of iterables, not only lists.
    $endgroup$
    – Mathias Ettinger
    6 hours ago










  • $begingroup$
    @MathiasEttinger good idea. Added it to the answer.
    $endgroup$
    – RootTwo
    5 hours ago













3












3








3





$begingroup$

iterators



You can use an iterator



def my_min(num_list):
# empty lists
if not num_list:
raise ValueError('Empty list')

list_iter = iter(num_list)
minimum = next(list_iter)
for num in list_iter:
if num < minimum:
minimum = num
return minimum


In response to Mathias' comment, here is a version that works with an iterable:



def my_min(seq):
seq = iter(seq)

try:
minimum = next(seq)

for num in seq:
if num < minimum:
minimum = num

return minimum

except StopIteration as e:
pass

raise ValueError('Empty list')





share|improve this answer











$endgroup$



iterators



You can use an iterator



def my_min(num_list):
# empty lists
if not num_list:
raise ValueError('Empty list')

list_iter = iter(num_list)
minimum = next(list_iter)
for num in list_iter:
if num < minimum:
minimum = num
return minimum


In response to Mathias' comment, here is a version that works with an iterable:



def my_min(seq):
seq = iter(seq)

try:
minimum = next(seq)

for num in seq:
if num < minimum:
minimum = num

return minimum

except StopIteration as e:
pass

raise ValueError('Empty list')






share|improve this answer














share|improve this answer



share|improve this answer








edited 5 hours ago

























answered 7 hours ago









RootTwoRootTwo

1,2293 silver badges6 bronze badges




1,2293 silver badges6 bronze badges










  • 1




    $begingroup$
    This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the next call, you could handle all kind of iterables, not only lists.
    $endgroup$
    – Mathias Ettinger
    6 hours ago










  • $begingroup$
    @MathiasEttinger good idea. Added it to the answer.
    $endgroup$
    – RootTwo
    5 hours ago












  • 1




    $begingroup$
    This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the next call, you could handle all kind of iterables, not only lists.
    $endgroup$
    – Mathias Ettinger
    6 hours ago










  • $begingroup$
    @MathiasEttinger good idea. Added it to the answer.
    $endgroup$
    – RootTwo
    5 hours ago







1




1




$begingroup$
This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the next call, you could handle all kind of iterables, not only lists.
$endgroup$
– Mathias Ettinger
6 hours ago




$begingroup$
This is the right approach to avoid duplicating the whole list in memory. If only you took the special case of the empty parameter around the next call, you could handle all kind of iterables, not only lists.
$endgroup$
– Mathias Ettinger
6 hours ago












$begingroup$
@MathiasEttinger good idea. Added it to the answer.
$endgroup$
– RootTwo
5 hours ago




$begingroup$
@MathiasEttinger good idea. Added it to the answer.
$endgroup$
– RootTwo
5 hours ago













1












$begingroup$

Review




I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element




  • You have implemented a simple function, so it shouldn't have been that hard to provide a couple of unit tests. You would have immediately found bugs on the most obvious edge cases as (1) empty list and self-created edge case (2) single item.


While insignificant in terms of wasted time and resources, I just
find it lacking elegance.




  • What you gain in elegance is lost by the edge case guards you'd have to build in to fix the bugs.





share|improve this answer









$endgroup$














  • $begingroup$
    To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?
    $endgroup$
    – jeremy radcliff
    7 hours ago















1












$begingroup$

Review




I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element




  • You have implemented a simple function, so it shouldn't have been that hard to provide a couple of unit tests. You would have immediately found bugs on the most obvious edge cases as (1) empty list and self-created edge case (2) single item.


While insignificant in terms of wasted time and resources, I just
find it lacking elegance.




  • What you gain in elegance is lost by the edge case guards you'd have to build in to fix the bugs.





share|improve this answer









$endgroup$














  • $begingroup$
    To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?
    $endgroup$
    – jeremy radcliff
    7 hours ago













1












1








1





$begingroup$

Review




I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element




  • You have implemented a simple function, so it shouldn't have been that hard to provide a couple of unit tests. You would have immediately found bugs on the most obvious edge cases as (1) empty list and self-created edge case (2) single item.


While insignificant in terms of wasted time and resources, I just
find it lacking elegance.




  • What you gain in elegance is lost by the edge case guards you'd have to build in to fix the bugs.





share|improve this answer









$endgroup$



Review




I should check for the list having no elements anyway, so I could check for its having only 1 element and return that element




  • You have implemented a simple function, so it shouldn't have been that hard to provide a couple of unit tests. You would have immediately found bugs on the most obvious edge cases as (1) empty list and self-created edge case (2) single item.


While insignificant in terms of wasted time and resources, I just
find it lacking elegance.




  • What you gain in elegance is lost by the edge case guards you'd have to build in to fix the bugs.






share|improve this answer












share|improve this answer



share|improve this answer










answered 7 hours ago









dfhwzedfhwze

8,4411 gold badge18 silver badges49 bronze badges




8,4411 gold badge18 silver badges49 bronze badges














  • $begingroup$
    To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?
    $endgroup$
    – jeremy radcliff
    7 hours ago
















  • $begingroup$
    To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?
    $endgroup$
    – jeremy radcliff
    7 hours ago















$begingroup$
To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?
$endgroup$
– jeremy radcliff
7 hours ago




$begingroup$
To your second point, are you saying there's no way to get the best of both worlds and therefore comparing the first element to itself is the way to go in terms of readability of code, etc...?
$endgroup$
– jeremy radcliff
7 hours ago

















draft saved

draft discarded
















































Thanks for contributing an answer to Code Review Stack Exchange!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

Use MathJax to format equations. MathJax reference.


To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f226060%2freimplementation-of-min-in-python%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

Ласкавець круглолистий Зміст Опис | Поширення | Галерея | Примітки | Посилання | Навігаційне меню58171138361-22960890446Bupleurum rotundifoliumEuro+Med PlantbasePlants of the World Online — Kew ScienceGermplasm Resources Information Network (GRIN)Ласкавецькн. VI : Літери Ком — Левиправивши або дописавши її