Python number line cluster exercisePython sequence cluster exerciseCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How do I get the number of elements in a list in Python?How to read a file line-by-line into a list?Does Python have a string 'contains' substring method?Catch multiple exceptions in one line (except block)

Smoothness of finite-dimensional functional calculus

Theorems that impeded progress

What typically incentivizes a professor to change jobs to a lower ranking university?

How much RAM could one put in a typical 80386 setup?

How do we improve the relationship with a client software team that performs poorly and is becoming less collaborative?

Modeling an IPv4 Address

What's the point of deactivating Num Lock on login screens?

Prove that NP is closed under karp reduction?

Why does Kotter return in Welcome Back Kotter?

Why don't electron-positron collisions release infinite energy?

Why doesn't H₄O²⁺ exist?

How could an uplifted falcon's brain work?

Show that if two triangles built on parallel lines, with equal bases have the same perimeter only if they are congruent.

How does strength of boric acid solution increase in presence of salicylic acid?

Email Account under attack (really) - anything I can do?

Do I have a twin with permutated remainders?

What does it mean to describe someone as a butt steak?

Why are electrically insulating heatsinks so rare? Is it just cost?

Approximately how much travel time was saved by the opening of the Suez Canal in 1869?

What are these boxed doors outside store fronts in New York?

Mathematical cryptic clues

Dragon forelimb placement

Did Shadowfax go to Valinor?

Which models of the Boeing 737 are still in production?



Python number line cluster exercise


Python sequence cluster exerciseCalling an external command in PythonWhat are metaclasses in Python?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?How do I get the number of elements in a list in Python?How to read a file line-by-line into a list?Does Python have a string 'contains' substring method?Catch multiple exceptions in one line (except block)






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















I am working through an exercise in my textbook (Ex 4.7) and am implementing the code in Python to practice dynamic programming. I am having some trouble actually executing Algorithm 4.8. I understand what is going on until I get to 'Otherwise range s from 1 to t-1 and set s to minimize f(s). Why is the book using s in the for loop as well as setting it to the function f(s)? How should one go about implementing that line in Python?



[current code at bottom]



enter image description here



enter image description here



enter image description here



My current code is this so far:



x = [1,2,5,6,10]
k = 3
n = 5

r = [[0 for x in range(k)] for x in range(n)]
c = [[0 for x in range(k)] for x in range(n)]

def Union(lst1, lst2):
final_list = lst1 + lst2
return final_list

for j in range(k):
for t in range(n):
if j == 0:
r[t][j] = (x[t]-x[0])/2
c[t][j] = [(x[t]+x[0])/2]
else:
for s in range(t-1):
f = max(r[s][j-1], (x[t]-x[s+1])/2)
#set s to minimize f??
r[t][j] = f
w = []
w.append((x[t]+x[s+1])/2)
if c[s][j-1] == 0:
c[t][j] = w
else:
c[t][j] = Union(c[s][j - 1], w)

print(r)
print(c)


Any help is much appreciated!










share|improve this question






























    1















    I am working through an exercise in my textbook (Ex 4.7) and am implementing the code in Python to practice dynamic programming. I am having some trouble actually executing Algorithm 4.8. I understand what is going on until I get to 'Otherwise range s from 1 to t-1 and set s to minimize f(s). Why is the book using s in the for loop as well as setting it to the function f(s)? How should one go about implementing that line in Python?



    [current code at bottom]



    enter image description here



    enter image description here



    enter image description here



    My current code is this so far:



    x = [1,2,5,6,10]
    k = 3
    n = 5

    r = [[0 for x in range(k)] for x in range(n)]
    c = [[0 for x in range(k)] for x in range(n)]

    def Union(lst1, lst2):
    final_list = lst1 + lst2
    return final_list

    for j in range(k):
    for t in range(n):
    if j == 0:
    r[t][j] = (x[t]-x[0])/2
    c[t][j] = [(x[t]+x[0])/2]
    else:
    for s in range(t-1):
    f = max(r[s][j-1], (x[t]-x[s+1])/2)
    #set s to minimize f??
    r[t][j] = f
    w = []
    w.append((x[t]+x[s+1])/2)
    if c[s][j-1] == 0:
    c[t][j] = w
    else:
    c[t][j] = Union(c[s][j - 1], w)

    print(r)
    print(c)


    Any help is much appreciated!










    share|improve this question


























      1












      1








      1


      0






      I am working through an exercise in my textbook (Ex 4.7) and am implementing the code in Python to practice dynamic programming. I am having some trouble actually executing Algorithm 4.8. I understand what is going on until I get to 'Otherwise range s from 1 to t-1 and set s to minimize f(s). Why is the book using s in the for loop as well as setting it to the function f(s)? How should one go about implementing that line in Python?



      [current code at bottom]



      enter image description here



      enter image description here



      enter image description here



      My current code is this so far:



      x = [1,2,5,6,10]
      k = 3
      n = 5

      r = [[0 for x in range(k)] for x in range(n)]
      c = [[0 for x in range(k)] for x in range(n)]

      def Union(lst1, lst2):
      final_list = lst1 + lst2
      return final_list

      for j in range(k):
      for t in range(n):
      if j == 0:
      r[t][j] = (x[t]-x[0])/2
      c[t][j] = [(x[t]+x[0])/2]
      else:
      for s in range(t-1):
      f = max(r[s][j-1], (x[t]-x[s+1])/2)
      #set s to minimize f??
      r[t][j] = f
      w = []
      w.append((x[t]+x[s+1])/2)
      if c[s][j-1] == 0:
      c[t][j] = w
      else:
      c[t][j] = Union(c[s][j - 1], w)

      print(r)
      print(c)


      Any help is much appreciated!










      share|improve this question
















      I am working through an exercise in my textbook (Ex 4.7) and am implementing the code in Python to practice dynamic programming. I am having some trouble actually executing Algorithm 4.8. I understand what is going on until I get to 'Otherwise range s from 1 to t-1 and set s to minimize f(s). Why is the book using s in the for loop as well as setting it to the function f(s)? How should one go about implementing that line in Python?



      [current code at bottom]



      enter image description here



      enter image description here



      enter image description here



      My current code is this so far:



      x = [1,2,5,6,10]
      k = 3
      n = 5

      r = [[0 for x in range(k)] for x in range(n)]
      c = [[0 for x in range(k)] for x in range(n)]

      def Union(lst1, lst2):
      final_list = lst1 + lst2
      return final_list

      for j in range(k):
      for t in range(n):
      if j == 0:
      r[t][j] = (x[t]-x[0])/2
      c[t][j] = [(x[t]+x[0])/2]
      else:
      for s in range(t-1):
      f = max(r[s][j-1], (x[t]-x[s+1])/2)
      #set s to minimize f??
      r[t][j] = f
      w = []
      w.append((x[t]+x[s+1])/2)
      if c[s][j-1] == 0:
      c[t][j] = w
      else:
      c[t][j] = Union(c[s][j - 1], w)

      print(r)
      print(c)


      Any help is much appreciated!







      python algorithm cluster-analysis dynamic-programming






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 9 at 3:26

























      asked Mar 9 at 2:43







      user10322040





























          1 Answer
          1






          active

          oldest

          votes


















          1














          The algorithm is very good. My code is as follow.



          x = [1,2,5,6,10]
          k = 3
          n = 5

          r = [[[] for _ in range(k)] for _ in range(n)]
          c = [[[] for _ in range(k)] for _ in range(n)]


          def f(s, j_down, t):
          return max(r[s][j_down], (x[t]-x[s+1])/2.)

          def get_min_f_and_s(j_down, t):
          """ range s from 1 to t-1 and set s to minimize f(s)
          for example t=5 and j=3, so s range from 1 to 4, if f(1)=0.5, f(2)=0.4, f(3)=0.1, f(4)= 1.0, so f(4) is min one and s=2.
          And r[5][j] = f(2).
          """
          items = [(s, f(s, j_down, t))for s in range(t)]
          s, min_f = min(items, key=lambda x:x[1])
          return s, min_f

          for j in range(k):
          if j == 0:
          for t in range(n):
          for t in range(n):
          r[t][j] = (x[t]-x[0])/2.0
          c[t][j] = [(x[t]+x[0])/2.0]
          else:
          for t in range(1, n):
          s, min_f = get_min_f_and_s(j-1, t)
          r[t][j] = min_f

          c[t][j] = c[s][j-1] + [(x[t]+x[s+1])/2.,]

          print(r[-1][-1])
          print(c[-1][-1])


          A advice :
          When don't understand algorithm, you can run it by hand in scratch paper, maybe you will figure out how it work.






          share|improve this answer

























            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: "1"
            ;
            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: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            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%2fstackoverflow.com%2fquestions%2f55073517%2fpython-number-line-cluster-exercise%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown
























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            1














            The algorithm is very good. My code is as follow.



            x = [1,2,5,6,10]
            k = 3
            n = 5

            r = [[[] for _ in range(k)] for _ in range(n)]
            c = [[[] for _ in range(k)] for _ in range(n)]


            def f(s, j_down, t):
            return max(r[s][j_down], (x[t]-x[s+1])/2.)

            def get_min_f_and_s(j_down, t):
            """ range s from 1 to t-1 and set s to minimize f(s)
            for example t=5 and j=3, so s range from 1 to 4, if f(1)=0.5, f(2)=0.4, f(3)=0.1, f(4)= 1.0, so f(4) is min one and s=2.
            And r[5][j] = f(2).
            """
            items = [(s, f(s, j_down, t))for s in range(t)]
            s, min_f = min(items, key=lambda x:x[1])
            return s, min_f

            for j in range(k):
            if j == 0:
            for t in range(n):
            for t in range(n):
            r[t][j] = (x[t]-x[0])/2.0
            c[t][j] = [(x[t]+x[0])/2.0]
            else:
            for t in range(1, n):
            s, min_f = get_min_f_and_s(j-1, t)
            r[t][j] = min_f

            c[t][j] = c[s][j-1] + [(x[t]+x[s+1])/2.,]

            print(r[-1][-1])
            print(c[-1][-1])


            A advice :
            When don't understand algorithm, you can run it by hand in scratch paper, maybe you will figure out how it work.






            share|improve this answer





























              1














              The algorithm is very good. My code is as follow.



              x = [1,2,5,6,10]
              k = 3
              n = 5

              r = [[[] for _ in range(k)] for _ in range(n)]
              c = [[[] for _ in range(k)] for _ in range(n)]


              def f(s, j_down, t):
              return max(r[s][j_down], (x[t]-x[s+1])/2.)

              def get_min_f_and_s(j_down, t):
              """ range s from 1 to t-1 and set s to minimize f(s)
              for example t=5 and j=3, so s range from 1 to 4, if f(1)=0.5, f(2)=0.4, f(3)=0.1, f(4)= 1.0, so f(4) is min one and s=2.
              And r[5][j] = f(2).
              """
              items = [(s, f(s, j_down, t))for s in range(t)]
              s, min_f = min(items, key=lambda x:x[1])
              return s, min_f

              for j in range(k):
              if j == 0:
              for t in range(n):
              for t in range(n):
              r[t][j] = (x[t]-x[0])/2.0
              c[t][j] = [(x[t]+x[0])/2.0]
              else:
              for t in range(1, n):
              s, min_f = get_min_f_and_s(j-1, t)
              r[t][j] = min_f

              c[t][j] = c[s][j-1] + [(x[t]+x[s+1])/2.,]

              print(r[-1][-1])
              print(c[-1][-1])


              A advice :
              When don't understand algorithm, you can run it by hand in scratch paper, maybe you will figure out how it work.






              share|improve this answer



























                1












                1








                1







                The algorithm is very good. My code is as follow.



                x = [1,2,5,6,10]
                k = 3
                n = 5

                r = [[[] for _ in range(k)] for _ in range(n)]
                c = [[[] for _ in range(k)] for _ in range(n)]


                def f(s, j_down, t):
                return max(r[s][j_down], (x[t]-x[s+1])/2.)

                def get_min_f_and_s(j_down, t):
                """ range s from 1 to t-1 and set s to minimize f(s)
                for example t=5 and j=3, so s range from 1 to 4, if f(1)=0.5, f(2)=0.4, f(3)=0.1, f(4)= 1.0, so f(4) is min one and s=2.
                And r[5][j] = f(2).
                """
                items = [(s, f(s, j_down, t))for s in range(t)]
                s, min_f = min(items, key=lambda x:x[1])
                return s, min_f

                for j in range(k):
                if j == 0:
                for t in range(n):
                for t in range(n):
                r[t][j] = (x[t]-x[0])/2.0
                c[t][j] = [(x[t]+x[0])/2.0]
                else:
                for t in range(1, n):
                s, min_f = get_min_f_and_s(j-1, t)
                r[t][j] = min_f

                c[t][j] = c[s][j-1] + [(x[t]+x[s+1])/2.,]

                print(r[-1][-1])
                print(c[-1][-1])


                A advice :
                When don't understand algorithm, you can run it by hand in scratch paper, maybe you will figure out how it work.






                share|improve this answer















                The algorithm is very good. My code is as follow.



                x = [1,2,5,6,10]
                k = 3
                n = 5

                r = [[[] for _ in range(k)] for _ in range(n)]
                c = [[[] for _ in range(k)] for _ in range(n)]


                def f(s, j_down, t):
                return max(r[s][j_down], (x[t]-x[s+1])/2.)

                def get_min_f_and_s(j_down, t):
                """ range s from 1 to t-1 and set s to minimize f(s)
                for example t=5 and j=3, so s range from 1 to 4, if f(1)=0.5, f(2)=0.4, f(3)=0.1, f(4)= 1.0, so f(4) is min one and s=2.
                And r[5][j] = f(2).
                """
                items = [(s, f(s, j_down, t))for s in range(t)]
                s, min_f = min(items, key=lambda x:x[1])
                return s, min_f

                for j in range(k):
                if j == 0:
                for t in range(n):
                for t in range(n):
                r[t][j] = (x[t]-x[0])/2.0
                c[t][j] = [(x[t]+x[0])/2.0]
                else:
                for t in range(1, n):
                s, min_f = get_min_f_and_s(j-1, t)
                r[t][j] = min_f

                c[t][j] = c[s][j-1] + [(x[t]+x[s+1])/2.,]

                print(r[-1][-1])
                print(c[-1][-1])


                A advice :
                When don't understand algorithm, you can run it by hand in scratch paper, maybe you will figure out how it work.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Mar 9 at 7:42

























                answered Mar 9 at 6:57









                Happy BoyHappy Boy

                40629




                40629





























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • 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.

                    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%2fstackoverflow.com%2fquestions%2f55073517%2fpython-number-line-cluster-exercise%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

                    Thal And Out Agency railway station See also References External links Navigation menuOfficial Web Site of Pakistan RailwaysArchivedOfficial Web Site of Pakistan Railwayseeexpanding ite

                    Understanding generators in Python2019 Community Moderator ElectionGenerator function not working pythonFor loop not executing two timesGenerators - Printing generated valuesWhy can a python generator only be used once?What exactly do generators do?What does the “yield” keyword do?What does “list comprehension” mean? How does it work and how can I use it?sklearn Kfold acces single fold instead of for loopIs a generator the callable? Which is the generator?Apply Border To Range Of Cells Using OpenpyxlCalling an external command in PythonWhat are metaclasses in Python?What is the difference between @staticmethod and @classmethod?Finding the index of an item given a list containing it in PythonDifference between append vs. extend list methods in PythonHow can I safely create a nested directory in Python?Does Python have a ternary conditional operator?Understanding slice notationUnderstanding Python super() with __init__() methodsDoes Python have a string 'contains' substring method?

                    How can I change the color of pagination dots of UIPageControl?How to change UIPageControl dotsIs there a way to change page indicator dots colorCustomize dot with image of UIPageControl at index 0 of UIPageControlNo visible @interface for 'NSObject<PageControlDelegate>' declares the selector 'pageControlPageDidChange:'How to change the color of pagination dots in UIPageControl with a different color per pagepagecontrol indicator custom image instead of DefaultChanging the colour of UIPageControl dots in MonoTouchpagecontrol selectable page visibility color?Alternative way to load ViewControllers on a UIPageControlHow to set only layer.border-color for UIpage control dots in swiftHow can I develop for iPhone using a Windows development machine?How to change the name of an iOS app?UITableView - change section header coloruipagecontrol indicator(dot)issueCustom UIPageControl dots color not changingchange the interspace between UIPageControl dotsHow to change Status Bar text color in iOSHow can I change image tintColor in iOS and WatchKitUIPageControl dots with larger space in between each dotsHow to change the color of pagination dots in UIPageControl with a different color per page