Selection Sort Algorithm (Python)Sorting Algorithms (Python)Heap selection sort in JavaAdaptive counting sort for integer arrays in JavaExact sort - sorting with few move operationsHackerrank Insertion Sort Part 2Sorting almost sorted array with a minimum heapQuick Select C#Quicksort with Insertion Sort and Improved Pivot Selection

Why would an airline put 15 passengers at once on standby?

Can you trip a breaker from a different circuit?

Why does C++ have 'Undefined Behaviour' and other languages like C# or Java don't?

When did Unix stop storing passwords in clear text?

Why isn't there armor to protect from spells in the Potterverse?

Smallest number containing the first 11 primes as sub-strings

split 1 column input into 5 column bed file

Why is a road bike faster than a city bike with the same effort? How much faster it can be?

The TI quad-XOR gate acts as it is short circuit

What's the hidden joke/meaning behind "Don't drink and park - accidents cause people"?

Is the order of words purely based on convention?

Lambda functions with template parameters, not in function parameters

A word that refers to saying something in an attempt to anger or embarrass someone into doing something that they don’t want to do?

Calculate the Ultraradical

Is there a list of world wide upcoming space events on the web?

Is there no "respectively" in german language when listing (enumerating) something?

An impressive body of work

Would an object shot from earth fall into the sun?

Where is the bomb: How to estimate the probability, given row and column totals?

"I will not" or "I don't" as an answer for negative orders?

What makes learning more difficult as we age?

London Congestion Charge on A205

Garage door sticks on a bolt

ZFS inside a virtual machine



Selection Sort Algorithm (Python)


Sorting Algorithms (Python)Heap selection sort in JavaAdaptive counting sort for integer arrays in JavaExact sort - sorting with few move operationsHackerrank Insertion Sort Part 2Sorting almost sorted array with a minimum heapQuick Select C#Quicksort with Insertion Sort and Improved Pivot Selection






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








4












$begingroup$


Selection Sort




The selection sort algorithm sorts a list by finding the minimum
element from the right unsorted part of the list and putting it at the
left sorted part of the list. The algorithm maintains two sub-lists in
a given input list.



1) The sub-list which is already sorted.

2) Remaining sub-list which
is unsorted.



In every iteration of selection sort, the minimum element from the
unsorted sub-list is picked and moved to the sorted sub-list.




I've been trying to implement the Selection Sort algorithm using Python magic functions such as __iter__ and I'd appreciate it if you'd review the code for changes/improvements.



Code



"""
This class returns an ascending sorted integer list
for an input integer list using Selection Sort method.

Sorting:
- In-Place (space complexity O(1))
- Efficiency (time complexity O(N^2))
- Unstable Sort (Order of equal elements might change)


"""
class SelectionSort(object):
"""
"""
def __init__(self, input_list:list)->list:
self.input_list = input_list
self.__iter__()

def __iter__(self)->list:
"""
Iterates through the list and swaps the min from the right side
to sorted elements from the left side of the list.
"""

# Is the length of the list
input_length = len(self.input_list)

# Iterates through the list to do the swapping
for element_index in range(input_length - 1):

min_index = element_index

# Iterates through the list to find the min index
for finder_index in range(element_index+1, input_length):
if self.input_list[min_index] > self.input_list[finder_index]:
min_index = finder_index

# Swaps the min value with the pointer value
if element_index is not min_index:
self.input_list[element_index], self.input_list[min_index] = self.input_list[min_index], self.input_list[element_index]

print(self.input_list)
return self.input_list


SelectionSort([10, 4, 82, 9, 23, -30, -45, -93, 23, 23, 23, 0, -1])


Reference



  • Selection Sort (Geeks for Geeks)

  • Selection Sort (Wiki)









share|improve this question









$endgroup$




















    4












    $begingroup$


    Selection Sort




    The selection sort algorithm sorts a list by finding the minimum
    element from the right unsorted part of the list and putting it at the
    left sorted part of the list. The algorithm maintains two sub-lists in
    a given input list.



    1) The sub-list which is already sorted.

    2) Remaining sub-list which
    is unsorted.



    In every iteration of selection sort, the minimum element from the
    unsorted sub-list is picked and moved to the sorted sub-list.




    I've been trying to implement the Selection Sort algorithm using Python magic functions such as __iter__ and I'd appreciate it if you'd review the code for changes/improvements.



    Code



    """
    This class returns an ascending sorted integer list
    for an input integer list using Selection Sort method.

    Sorting:
    - In-Place (space complexity O(1))
    - Efficiency (time complexity O(N^2))
    - Unstable Sort (Order of equal elements might change)


    """
    class SelectionSort(object):
    """
    """
    def __init__(self, input_list:list)->list:
    self.input_list = input_list
    self.__iter__()

    def __iter__(self)->list:
    """
    Iterates through the list and swaps the min from the right side
    to sorted elements from the left side of the list.
    """

    # Is the length of the list
    input_length = len(self.input_list)

    # Iterates through the list to do the swapping
    for element_index in range(input_length - 1):

    min_index = element_index

    # Iterates through the list to find the min index
    for finder_index in range(element_index+1, input_length):
    if self.input_list[min_index] > self.input_list[finder_index]:
    min_index = finder_index

    # Swaps the min value with the pointer value
    if element_index is not min_index:
    self.input_list[element_index], self.input_list[min_index] = self.input_list[min_index], self.input_list[element_index]

    print(self.input_list)
    return self.input_list


    SelectionSort([10, 4, 82, 9, 23, -30, -45, -93, 23, 23, 23, 0, -1])


    Reference



    • Selection Sort (Geeks for Geeks)

    • Selection Sort (Wiki)









    share|improve this question









    $endgroup$
















      4












      4








      4





      $begingroup$


      Selection Sort




      The selection sort algorithm sorts a list by finding the minimum
      element from the right unsorted part of the list and putting it at the
      left sorted part of the list. The algorithm maintains two sub-lists in
      a given input list.



      1) The sub-list which is already sorted.

      2) Remaining sub-list which
      is unsorted.



      In every iteration of selection sort, the minimum element from the
      unsorted sub-list is picked and moved to the sorted sub-list.




      I've been trying to implement the Selection Sort algorithm using Python magic functions such as __iter__ and I'd appreciate it if you'd review the code for changes/improvements.



      Code



      """
      This class returns an ascending sorted integer list
      for an input integer list using Selection Sort method.

      Sorting:
      - In-Place (space complexity O(1))
      - Efficiency (time complexity O(N^2))
      - Unstable Sort (Order of equal elements might change)


      """
      class SelectionSort(object):
      """
      """
      def __init__(self, input_list:list)->list:
      self.input_list = input_list
      self.__iter__()

      def __iter__(self)->list:
      """
      Iterates through the list and swaps the min from the right side
      to sorted elements from the left side of the list.
      """

      # Is the length of the list
      input_length = len(self.input_list)

      # Iterates through the list to do the swapping
      for element_index in range(input_length - 1):

      min_index = element_index

      # Iterates through the list to find the min index
      for finder_index in range(element_index+1, input_length):
      if self.input_list[min_index] > self.input_list[finder_index]:
      min_index = finder_index

      # Swaps the min value with the pointer value
      if element_index is not min_index:
      self.input_list[element_index], self.input_list[min_index] = self.input_list[min_index], self.input_list[element_index]

      print(self.input_list)
      return self.input_list


      SelectionSort([10, 4, 82, 9, 23, -30, -45, -93, 23, 23, 23, 0, -1])


      Reference



      • Selection Sort (Geeks for Geeks)

      • Selection Sort (Wiki)









      share|improve this question









      $endgroup$




      Selection Sort




      The selection sort algorithm sorts a list by finding the minimum
      element from the right unsorted part of the list and putting it at the
      left sorted part of the list. The algorithm maintains two sub-lists in
      a given input list.



      1) The sub-list which is already sorted.

      2) Remaining sub-list which
      is unsorted.



      In every iteration of selection sort, the minimum element from the
      unsorted sub-list is picked and moved to the sorted sub-list.




      I've been trying to implement the Selection Sort algorithm using Python magic functions such as __iter__ and I'd appreciate it if you'd review the code for changes/improvements.



      Code



      """
      This class returns an ascending sorted integer list
      for an input integer list using Selection Sort method.

      Sorting:
      - In-Place (space complexity O(1))
      - Efficiency (time complexity O(N^2))
      - Unstable Sort (Order of equal elements might change)


      """
      class SelectionSort(object):
      """
      """
      def __init__(self, input_list:list)->list:
      self.input_list = input_list
      self.__iter__()

      def __iter__(self)->list:
      """
      Iterates through the list and swaps the min from the right side
      to sorted elements from the left side of the list.
      """

      # Is the length of the list
      input_length = len(self.input_list)

      # Iterates through the list to do the swapping
      for element_index in range(input_length - 1):

      min_index = element_index

      # Iterates through the list to find the min index
      for finder_index in range(element_index+1, input_length):
      if self.input_list[min_index] > self.input_list[finder_index]:
      min_index = finder_index

      # Swaps the min value with the pointer value
      if element_index is not min_index:
      self.input_list[element_index], self.input_list[min_index] = self.input_list[min_index], self.input_list[element_index]

      print(self.input_list)
      return self.input_list


      SelectionSort([10, 4, 82, 9, 23, -30, -45, -93, 23, 23, 23, 0, -1])


      Reference



      • Selection Sort (Geeks for Geeks)

      • Selection Sort (Wiki)






      python beginner algorithm object-oriented sorting






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked 8 hours ago









      EmmaEmma

      5052 gold badges2 silver badges17 bronze badges




      5052 gold badges2 silver badges17 bronze badges























          2 Answers
          2






          active

          oldest

          votes


















          4














          $begingroup$

          I agree with @Reinderien that this shouldn't be a class. You can see evidence for this in your constructor:



          def __init__(self, input_list:list)->list:
          self.input_list = input_list
          self.__iter__()


          You are constructing the object (and calling the constructor) simply to call self.__iter__(). There is no reason for the creation of an object here just to sort the list. If you needed to maintain some state between sorts or something (I'm not sure why you would though), then it may be appropriate.



          I'll also point out, you're attempting to violate at least two "contracts" with your usage of __init__ and __iter__:




          • __init__ must return None:




            no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.




            Now, you aren't actually returning anything, but your type hinting is saying that you are. If you're going to use type hinting, the hints should make it clearer what types are involved, not make false claims.




          • __iter__ should return an iterator:




            This method should return a new iterator object that can iterate over all the objects in the container




            The problem is, you're returning a list, and a list isn't an iterator, it's an iterable (it has an iterator). This isn't just a theoretical problem. Note how this can bite you:



            class T:
            def __iter__(self):
            return [1, 2, 3]

            for n in T():
            print(n)

            # TypeError: iter() returned non-iterator of type 'list'


          Use of "dunder" methods can be helpful for writing clean code, but only if you aren't abusing them. Make sure to read the documentation and understand the purpose and contracts of methods before attempting to use them.




          And on the subject of type hints, you could make use of a TypeVar to allow the type checker to see the consistency between the element types going in and out of your sorting function. After making your class into a standalone function, you basically have:



          def selection_sort(input_list: list) -> list:


          The problem with this is, it doesn't tell the checker what the relationship is between the types of elements in input_list and that of the list that selection_sort returns. This can lead to subtle issues where it won't be able to help you with types:



          lst: List[int] = [1, 2, 3]
          sorted_list = selection_sort(input_list)
          x = sorted_list[0] # It has no idea what type x is


          You can fix this by introducing a TypeVar that tells it that the element type remains consistent. I'm also changing from using list to List since list doesn't seem to support generics yet:



          from typing import List, TypeVar

          T = TypeVar("T")

          # The sort returns the same element type T that it received
          def selection_sort(input_list: List[T]) -> List[T]:
          . . .


          Now, it is able to infer the type of x, and can give you better completions and type warnings.






          share|improve this answer











          $endgroup$






















            3














            $begingroup$

            This is mostly pretty good. Only a couple of things:



            Delete this -



             print(self.input_list)


            You should leave printing to the caller.



            Also - why the class at all? This really boils down to a single function. You only have one member variable, and only one method.



            There's another issue - this class results in "surprising mutation". Iterating over it modifies one of its members. This is another argument for a simple function. If you keep the class, you could possibly



            • Cache the sorted output, as a separate list from the input list, and/or

            • store a copy of the input list instead of the input list itself.

            That last point speaks to another issue - you assume that you're being passed a list, which isn't strictly necessary; all you need is an iterable. If you create a list from the input, you place fewer demands on your caller.






            share|improve this answer









            $endgroup$

















              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/4.0/"u003ecc by-sa 4.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%2f229509%2fselection-sort-algorithm-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









              4














              $begingroup$

              I agree with @Reinderien that this shouldn't be a class. You can see evidence for this in your constructor:



              def __init__(self, input_list:list)->list:
              self.input_list = input_list
              self.__iter__()


              You are constructing the object (and calling the constructor) simply to call self.__iter__(). There is no reason for the creation of an object here just to sort the list. If you needed to maintain some state between sorts or something (I'm not sure why you would though), then it may be appropriate.



              I'll also point out, you're attempting to violate at least two "contracts" with your usage of __init__ and __iter__:




              • __init__ must return None:




                no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.




                Now, you aren't actually returning anything, but your type hinting is saying that you are. If you're going to use type hinting, the hints should make it clearer what types are involved, not make false claims.




              • __iter__ should return an iterator:




                This method should return a new iterator object that can iterate over all the objects in the container




                The problem is, you're returning a list, and a list isn't an iterator, it's an iterable (it has an iterator). This isn't just a theoretical problem. Note how this can bite you:



                class T:
                def __iter__(self):
                return [1, 2, 3]

                for n in T():
                print(n)

                # TypeError: iter() returned non-iterator of type 'list'


              Use of "dunder" methods can be helpful for writing clean code, but only if you aren't abusing them. Make sure to read the documentation and understand the purpose and contracts of methods before attempting to use them.




              And on the subject of type hints, you could make use of a TypeVar to allow the type checker to see the consistency between the element types going in and out of your sorting function. After making your class into a standalone function, you basically have:



              def selection_sort(input_list: list) -> list:


              The problem with this is, it doesn't tell the checker what the relationship is between the types of elements in input_list and that of the list that selection_sort returns. This can lead to subtle issues where it won't be able to help you with types:



              lst: List[int] = [1, 2, 3]
              sorted_list = selection_sort(input_list)
              x = sorted_list[0] # It has no idea what type x is


              You can fix this by introducing a TypeVar that tells it that the element type remains consistent. I'm also changing from using list to List since list doesn't seem to support generics yet:



              from typing import List, TypeVar

              T = TypeVar("T")

              # The sort returns the same element type T that it received
              def selection_sort(input_list: List[T]) -> List[T]:
              . . .


              Now, it is able to infer the type of x, and can give you better completions and type warnings.






              share|improve this answer











              $endgroup$



















                4














                $begingroup$

                I agree with @Reinderien that this shouldn't be a class. You can see evidence for this in your constructor:



                def __init__(self, input_list:list)->list:
                self.input_list = input_list
                self.__iter__()


                You are constructing the object (and calling the constructor) simply to call self.__iter__(). There is no reason for the creation of an object here just to sort the list. If you needed to maintain some state between sorts or something (I'm not sure why you would though), then it may be appropriate.



                I'll also point out, you're attempting to violate at least two "contracts" with your usage of __init__ and __iter__:




                • __init__ must return None:




                  no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.




                  Now, you aren't actually returning anything, but your type hinting is saying that you are. If you're going to use type hinting, the hints should make it clearer what types are involved, not make false claims.




                • __iter__ should return an iterator:




                  This method should return a new iterator object that can iterate over all the objects in the container




                  The problem is, you're returning a list, and a list isn't an iterator, it's an iterable (it has an iterator). This isn't just a theoretical problem. Note how this can bite you:



                  class T:
                  def __iter__(self):
                  return [1, 2, 3]

                  for n in T():
                  print(n)

                  # TypeError: iter() returned non-iterator of type 'list'


                Use of "dunder" methods can be helpful for writing clean code, but only if you aren't abusing them. Make sure to read the documentation and understand the purpose and contracts of methods before attempting to use them.




                And on the subject of type hints, you could make use of a TypeVar to allow the type checker to see the consistency between the element types going in and out of your sorting function. After making your class into a standalone function, you basically have:



                def selection_sort(input_list: list) -> list:


                The problem with this is, it doesn't tell the checker what the relationship is between the types of elements in input_list and that of the list that selection_sort returns. This can lead to subtle issues where it won't be able to help you with types:



                lst: List[int] = [1, 2, 3]
                sorted_list = selection_sort(input_list)
                x = sorted_list[0] # It has no idea what type x is


                You can fix this by introducing a TypeVar that tells it that the element type remains consistent. I'm also changing from using list to List since list doesn't seem to support generics yet:



                from typing import List, TypeVar

                T = TypeVar("T")

                # The sort returns the same element type T that it received
                def selection_sort(input_list: List[T]) -> List[T]:
                . . .


                Now, it is able to infer the type of x, and can give you better completions and type warnings.






                share|improve this answer











                $endgroup$

















                  4














                  4










                  4







                  $begingroup$

                  I agree with @Reinderien that this shouldn't be a class. You can see evidence for this in your constructor:



                  def __init__(self, input_list:list)->list:
                  self.input_list = input_list
                  self.__iter__()


                  You are constructing the object (and calling the constructor) simply to call self.__iter__(). There is no reason for the creation of an object here just to sort the list. If you needed to maintain some state between sorts or something (I'm not sure why you would though), then it may be appropriate.



                  I'll also point out, you're attempting to violate at least two "contracts" with your usage of __init__ and __iter__:




                  • __init__ must return None:




                    no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.




                    Now, you aren't actually returning anything, but your type hinting is saying that you are. If you're going to use type hinting, the hints should make it clearer what types are involved, not make false claims.




                  • __iter__ should return an iterator:




                    This method should return a new iterator object that can iterate over all the objects in the container




                    The problem is, you're returning a list, and a list isn't an iterator, it's an iterable (it has an iterator). This isn't just a theoretical problem. Note how this can bite you:



                    class T:
                    def __iter__(self):
                    return [1, 2, 3]

                    for n in T():
                    print(n)

                    # TypeError: iter() returned non-iterator of type 'list'


                  Use of "dunder" methods can be helpful for writing clean code, but only if you aren't abusing them. Make sure to read the documentation and understand the purpose and contracts of methods before attempting to use them.




                  And on the subject of type hints, you could make use of a TypeVar to allow the type checker to see the consistency between the element types going in and out of your sorting function. After making your class into a standalone function, you basically have:



                  def selection_sort(input_list: list) -> list:


                  The problem with this is, it doesn't tell the checker what the relationship is between the types of elements in input_list and that of the list that selection_sort returns. This can lead to subtle issues where it won't be able to help you with types:



                  lst: List[int] = [1, 2, 3]
                  sorted_list = selection_sort(input_list)
                  x = sorted_list[0] # It has no idea what type x is


                  You can fix this by introducing a TypeVar that tells it that the element type remains consistent. I'm also changing from using list to List since list doesn't seem to support generics yet:



                  from typing import List, TypeVar

                  T = TypeVar("T")

                  # The sort returns the same element type T that it received
                  def selection_sort(input_list: List[T]) -> List[T]:
                  . . .


                  Now, it is able to infer the type of x, and can give you better completions and type warnings.






                  share|improve this answer











                  $endgroup$



                  I agree with @Reinderien that this shouldn't be a class. You can see evidence for this in your constructor:



                  def __init__(self, input_list:list)->list:
                  self.input_list = input_list
                  self.__iter__()


                  You are constructing the object (and calling the constructor) simply to call self.__iter__(). There is no reason for the creation of an object here just to sort the list. If you needed to maintain some state between sorts or something (I'm not sure why you would though), then it may be appropriate.



                  I'll also point out, you're attempting to violate at least two "contracts" with your usage of __init__ and __iter__:




                  • __init__ must return None:




                    no non-None value may be returned by __init__(); doing so will cause a TypeError to be raised at runtime.




                    Now, you aren't actually returning anything, but your type hinting is saying that you are. If you're going to use type hinting, the hints should make it clearer what types are involved, not make false claims.




                  • __iter__ should return an iterator:




                    This method should return a new iterator object that can iterate over all the objects in the container




                    The problem is, you're returning a list, and a list isn't an iterator, it's an iterable (it has an iterator). This isn't just a theoretical problem. Note how this can bite you:



                    class T:
                    def __iter__(self):
                    return [1, 2, 3]

                    for n in T():
                    print(n)

                    # TypeError: iter() returned non-iterator of type 'list'


                  Use of "dunder" methods can be helpful for writing clean code, but only if you aren't abusing them. Make sure to read the documentation and understand the purpose and contracts of methods before attempting to use them.




                  And on the subject of type hints, you could make use of a TypeVar to allow the type checker to see the consistency between the element types going in and out of your sorting function. After making your class into a standalone function, you basically have:



                  def selection_sort(input_list: list) -> list:


                  The problem with this is, it doesn't tell the checker what the relationship is between the types of elements in input_list and that of the list that selection_sort returns. This can lead to subtle issues where it won't be able to help you with types:



                  lst: List[int] = [1, 2, 3]
                  sorted_list = selection_sort(input_list)
                  x = sorted_list[0] # It has no idea what type x is


                  You can fix this by introducing a TypeVar that tells it that the element type remains consistent. I'm also changing from using list to List since list doesn't seem to support generics yet:



                  from typing import List, TypeVar

                  T = TypeVar("T")

                  # The sort returns the same element type T that it received
                  def selection_sort(input_list: List[T]) -> List[T]:
                  . . .


                  Now, it is able to infer the type of x, and can give you better completions and type warnings.







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited 2 hours ago

























                  answered 6 hours ago









                  CarcigenicateCarcigenicate

                  7,3591 gold badge19 silver badges48 bronze badges




                  7,3591 gold badge19 silver badges48 bronze badges


























                      3














                      $begingroup$

                      This is mostly pretty good. Only a couple of things:



                      Delete this -



                       print(self.input_list)


                      You should leave printing to the caller.



                      Also - why the class at all? This really boils down to a single function. You only have one member variable, and only one method.



                      There's another issue - this class results in "surprising mutation". Iterating over it modifies one of its members. This is another argument for a simple function. If you keep the class, you could possibly



                      • Cache the sorted output, as a separate list from the input list, and/or

                      • store a copy of the input list instead of the input list itself.

                      That last point speaks to another issue - you assume that you're being passed a list, which isn't strictly necessary; all you need is an iterable. If you create a list from the input, you place fewer demands on your caller.






                      share|improve this answer









                      $endgroup$



















                        3














                        $begingroup$

                        This is mostly pretty good. Only a couple of things:



                        Delete this -



                         print(self.input_list)


                        You should leave printing to the caller.



                        Also - why the class at all? This really boils down to a single function. You only have one member variable, and only one method.



                        There's another issue - this class results in "surprising mutation". Iterating over it modifies one of its members. This is another argument for a simple function. If you keep the class, you could possibly



                        • Cache the sorted output, as a separate list from the input list, and/or

                        • store a copy of the input list instead of the input list itself.

                        That last point speaks to another issue - you assume that you're being passed a list, which isn't strictly necessary; all you need is an iterable. If you create a list from the input, you place fewer demands on your caller.






                        share|improve this answer









                        $endgroup$

















                          3














                          3










                          3







                          $begingroup$

                          This is mostly pretty good. Only a couple of things:



                          Delete this -



                           print(self.input_list)


                          You should leave printing to the caller.



                          Also - why the class at all? This really boils down to a single function. You only have one member variable, and only one method.



                          There's another issue - this class results in "surprising mutation". Iterating over it modifies one of its members. This is another argument for a simple function. If you keep the class, you could possibly



                          • Cache the sorted output, as a separate list from the input list, and/or

                          • store a copy of the input list instead of the input list itself.

                          That last point speaks to another issue - you assume that you're being passed a list, which isn't strictly necessary; all you need is an iterable. If you create a list from the input, you place fewer demands on your caller.






                          share|improve this answer









                          $endgroup$



                          This is mostly pretty good. Only a couple of things:



                          Delete this -



                           print(self.input_list)


                          You should leave printing to the caller.



                          Also - why the class at all? This really boils down to a single function. You only have one member variable, and only one method.



                          There's another issue - this class results in "surprising mutation". Iterating over it modifies one of its members. This is another argument for a simple function. If you keep the class, you could possibly



                          • Cache the sorted output, as a separate list from the input list, and/or

                          • store a copy of the input list instead of the input list itself.

                          That last point speaks to another issue - you assume that you're being passed a list, which isn't strictly necessary; all you need is an iterable. If you create a list from the input, you place fewer demands on your caller.







                          share|improve this answer












                          share|improve this answer



                          share|improve this answer










                          answered 7 hours ago









                          ReinderienReinderien

                          9,71515 silver badges41 bronze badges




                          9,71515 silver badges41 bronze badges































                              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%2f229509%2fselection-sort-algorithm-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

                              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

                              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

                              François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480