Why doesn't this code give the right results for numeric comparisons?Why does comparing strings using either '==' or 'is' sometimes produce a different result?Why does Python code run faster in a function?Find if there are consecutive occurrences of an int in a list of intsPython's all() not giving the expected result checking a list of small numbers are less than some valuerewinding multiple lines when iterating with f.next()Right code but still test case is not running in pythonHow to make sure the sting appear in somewhere in the listReturn True if an array has a 2 directly next to another 2Determine whether any permutation of a given array such that the sum of all subarrays of length K are equalStuck with writing a regex in python

Is there a better way to do partial sums of array items in JavaScript?

Was self-modifying code possible using BASIC?

What does the homotopy coherent nerve do to spaces of enriched functors?

Parsing text written the millitext font

How to change the headfont of newtheorem environments to match komascript font?

What do I need to do, tax-wise, for a sudden windfall?

How can powerful telekinesis avoid violating Newton's 3rd Law?

Are the guests in Westworld forbidden to tell the hosts that they are robots?

What class is best to play when a level behind the rest of the party?

How to befriend someone who doesn't like to talk?

Traceroute showing inter-vlan routing?

Suppose leased car is totalled: what are financial implications?

Course development: can I pay someone to make slides for the course?

In Pandemic, why take the extra step of eradicating a disease after you've cured it?

Is it true that "only photographers care about noise"?

Why do I seem to lose data using this bash pipe construction?

Can I use 220 V outlets on a 15 ampere breaker and wire it up as 110 V?

Should Ethernet MDI Pairs all be Length Matched (Inter-Pair) before going into magnetics?

How to Handle Many Times Series Simultaneously?

Placement of positioning lights on A320 winglets

In American Politics, why is the Justice Department under the President?

Problem with pronounciation

What is this Amiga 2000 mod?

Dedicated bike GPS computer over smartphone



Why doesn't this code give the right results for numeric comparisons?


Why does comparing strings using either '==' or 'is' sometimes produce a different result?Why does Python code run faster in a function?Find if there are consecutive occurrences of an int in a list of intsPython's all() not giving the expected result checking a list of small numbers are less than some valuerewinding multiple lines when iterating with f.next()Right code but still test case is not running in pythonHow to make sure the sting appear in somewhere in the listReturn True if an array has a 2 directly next to another 2Determine whether any permutation of a given array such that the sum of all subarrays of length K are equalStuck with writing a regex in python






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








0















I am currently doing Udemy course for Python by Jose Portilla. I am still a complete beginner. The excercise is the following:



"Given a list of ints, return True if the array contains a 3 next to a 3 somewhere."



has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False


My code is the following. For my logic it should give me the above results, but it gives False, False, True, which is completely off:



def has_33(nums):
for n in nums:
a = nums.index(n)
x = nums[a + 1]
y = nums[a - 1]
if n == 3 and (x == n or y == n):
return True
else:
return False









share|improve this question
























  • To be clear, are you asking how to solve the problem or why your code doesn't work?

    – Aran-Fey
    Mar 23 at 18:05











  • I am asking why it does not work? I simply don't get it. All of the steps are stroed in variables so they should not give any None Types. Clueless.

    – StingerWolf
    Mar 23 at 18:08











  • a = nums.index(n) noo. Don't do that. That isn't even correct, that always gives you the first index where n occurs.

    – juanpa.arrivillaga
    Mar 23 at 18:09












  • You should use for i, n in enumerate(nums): to get the corresponding index for n

    – Sheldore
    Mar 23 at 18:11






  • 1





    @Carcigenicate no it is not going out of bounds. When the index gets negative it just accesses the list from reverse. Hence, no error is thrown.

    – jeanggi90
    Mar 23 at 18:25

















0















I am currently doing Udemy course for Python by Jose Portilla. I am still a complete beginner. The excercise is the following:



"Given a list of ints, return True if the array contains a 3 next to a 3 somewhere."



has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False


My code is the following. For my logic it should give me the above results, but it gives False, False, True, which is completely off:



def has_33(nums):
for n in nums:
a = nums.index(n)
x = nums[a + 1]
y = nums[a - 1]
if n == 3 and (x == n or y == n):
return True
else:
return False









share|improve this question
























  • To be clear, are you asking how to solve the problem or why your code doesn't work?

    – Aran-Fey
    Mar 23 at 18:05











  • I am asking why it does not work? I simply don't get it. All of the steps are stroed in variables so they should not give any None Types. Clueless.

    – StingerWolf
    Mar 23 at 18:08











  • a = nums.index(n) noo. Don't do that. That isn't even correct, that always gives you the first index where n occurs.

    – juanpa.arrivillaga
    Mar 23 at 18:09












  • You should use for i, n in enumerate(nums): to get the corresponding index for n

    – Sheldore
    Mar 23 at 18:11






  • 1





    @Carcigenicate no it is not going out of bounds. When the index gets negative it just accesses the list from reverse. Hence, no error is thrown.

    – jeanggi90
    Mar 23 at 18:25













0












0








0








I am currently doing Udemy course for Python by Jose Portilla. I am still a complete beginner. The excercise is the following:



"Given a list of ints, return True if the array contains a 3 next to a 3 somewhere."



has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False


My code is the following. For my logic it should give me the above results, but it gives False, False, True, which is completely off:



def has_33(nums):
for n in nums:
a = nums.index(n)
x = nums[a + 1]
y = nums[a - 1]
if n == 3 and (x == n or y == n):
return True
else:
return False









share|improve this question
















I am currently doing Udemy course for Python by Jose Portilla. I am still a complete beginner. The excercise is the following:



"Given a list of ints, return True if the array contains a 3 next to a 3 somewhere."



has_33([1, 3, 3]) → True
has_33([1, 3, 1, 3]) → False
has_33([3, 1, 3]) → False


My code is the following. For my logic it should give me the above results, but it gives False, False, True, which is completely off:



def has_33(nums):
for n in nums:
a = nums.index(n)
x = nums[a + 1]
y = nums[a - 1]
if n == 3 and (x == n or y == n):
return True
else:
return False






python






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 23 at 22:56









belwood

2,05232935




2,05232935










asked Mar 23 at 18:03









StingerWolfStingerWolf

52




52












  • To be clear, are you asking how to solve the problem or why your code doesn't work?

    – Aran-Fey
    Mar 23 at 18:05











  • I am asking why it does not work? I simply don't get it. All of the steps are stroed in variables so they should not give any None Types. Clueless.

    – StingerWolf
    Mar 23 at 18:08











  • a = nums.index(n) noo. Don't do that. That isn't even correct, that always gives you the first index where n occurs.

    – juanpa.arrivillaga
    Mar 23 at 18:09












  • You should use for i, n in enumerate(nums): to get the corresponding index for n

    – Sheldore
    Mar 23 at 18:11






  • 1





    @Carcigenicate no it is not going out of bounds. When the index gets negative it just accesses the list from reverse. Hence, no error is thrown.

    – jeanggi90
    Mar 23 at 18:25

















  • To be clear, are you asking how to solve the problem or why your code doesn't work?

    – Aran-Fey
    Mar 23 at 18:05











  • I am asking why it does not work? I simply don't get it. All of the steps are stroed in variables so they should not give any None Types. Clueless.

    – StingerWolf
    Mar 23 at 18:08











  • a = nums.index(n) noo. Don't do that. That isn't even correct, that always gives you the first index where n occurs.

    – juanpa.arrivillaga
    Mar 23 at 18:09












  • You should use for i, n in enumerate(nums): to get the corresponding index for n

    – Sheldore
    Mar 23 at 18:11






  • 1





    @Carcigenicate no it is not going out of bounds. When the index gets negative it just accesses the list from reverse. Hence, no error is thrown.

    – jeanggi90
    Mar 23 at 18:25
















To be clear, are you asking how to solve the problem or why your code doesn't work?

– Aran-Fey
Mar 23 at 18:05





To be clear, are you asking how to solve the problem or why your code doesn't work?

– Aran-Fey
Mar 23 at 18:05













I am asking why it does not work? I simply don't get it. All of the steps are stroed in variables so they should not give any None Types. Clueless.

– StingerWolf
Mar 23 at 18:08





I am asking why it does not work? I simply don't get it. All of the steps are stroed in variables so they should not give any None Types. Clueless.

– StingerWolf
Mar 23 at 18:08













a = nums.index(n) noo. Don't do that. That isn't even correct, that always gives you the first index where n occurs.

– juanpa.arrivillaga
Mar 23 at 18:09






a = nums.index(n) noo. Don't do that. That isn't even correct, that always gives you the first index where n occurs.

– juanpa.arrivillaga
Mar 23 at 18:09














You should use for i, n in enumerate(nums): to get the corresponding index for n

– Sheldore
Mar 23 at 18:11





You should use for i, n in enumerate(nums): to get the corresponding index for n

– Sheldore
Mar 23 at 18:11




1




1





@Carcigenicate no it is not going out of bounds. When the index gets negative it just accesses the list from reverse. Hence, no error is thrown.

– jeanggi90
Mar 23 at 18:25





@Carcigenicate no it is not going out of bounds. When the index gets negative it just accesses the list from reverse. Hence, no error is thrown.

– jeanggi90
Mar 23 at 18:25












3 Answers
3






active

oldest

votes


















2














I try to explain the working of your function for has_33([1, 3, 3]). This way it gets obvious why your function is not doing what you expect it to do.



def has_33(nums):
# Call function and nums = [1, 3, 3]

for n in nums:
# Iterate over nums. n = 1

a = nums.index(n)
# Get the index of the list a where element = 1; a = 0

x = nums[a + 1]
# 0 + 1 = 1 -> x = nums[1] = 3

y = nums[a - 1]
# 0 - 1 = -1 -> y = nums[-1] = 3 (index -1 points to the last element of the list)

if n == 3 and (x == n or y == n):
# False, since n != 3 (even though x = 3 and y = 3)

return True
else:
return False
# When returning, the functin stopts executing, hence n never reaches another element.





share|improve this answer
































    1














    As pointed out in the comments, the main reason why this doesn't work is that you return false on the first iteration. Concerning the implementation, you can simplify things a bit to understand a bit more clearly what's going on:



    def has_33(nums):
    for a in range(len(nums)-1):
    x = nums[a]
    y = nums[a + 1]
    if x == 3 and y == 3:
    return True
    return False


    In your original solution, you were iterating over items by group of 3, adding print(y, n, x) right before your test would have output the following (for a call to has_33([1, 2, 3, 3, 4])):



    item at: i-1 i i+1
    ---------------
    i = 0 4 1 2
    i = 1 1 2 3
    i = 2 2 3 3


    In the first line, 4 1 2, the 4 is the item at position 0-1 = -1, in python, negative indexes correspond to positions relative to the end of the list. For example, nums[-1] is the last item from nums and nums[-2] is the one before the last, etc.



    In this second code we just iterate through nums's indexes to get every x item together with the following item y, printing print(x, y) would give:



    item at: i i+1
    ---------
    i = 0 1 2
    i = 1 2 3
    i = 2 3 3


    Remark that, in the end we just used the indexes to get items, when the index is not used for anything else, you can often use the zip function instead:



    def has_33(nums):
    for x, y in zip(nums, nums[1:]):
    if x == 3 and y == x:
    return True
    return False

    has_33([1, 2, 3, 3, 1])


    This outputs True, and for the record:



    >>> nums
    [1, 2, 3, 3, 1]
    >>> nums[1:]
    [2, 3, 3, 1]
    >>> list(zip(nums, nums[1:]))
    [(1, 2), (2, 3), (3, 3), (3, 1)]


    The zip function will pair item at index i from the first list with item at index i from the second list. Here we just removed the first item from nums to form our second list, using this strategy we managed to pair item i with item i+1.



    As mentioned in the comments, you can even use the function any that does exactly what our loop does



    def has_33(nums):
    return any(p == (3, 3) for p in zip(nums, nums[1:]))





    share|improve this answer




















    • 1





      you can further shorten your solution to def has_33(nums): return any(x == y == 3 for x, y in zip(nums, nums[1:]))

      – Boris
      Mar 23 at 18:28












    • You surely can, introducing zip to the OP was the main goal here, as I think it really is something hard to understand for python beginners. Both any or all are pretty straightforward (I think). But that's always worth mentioning, if you think I should add it I will.

      – cglacet
      Mar 23 at 18:31



















    0














    There is a logic error in your code at line 3. You mustn't use:



    a = nums.index(n)


    To get the index but you need to use this way:



    for a, n in enumerate(nums):


    Finally there is your corrected code:



    def has_33(nums):
    for a, n in enumerate(nums):
    x = nums[a + 1]
    y = nums[a - 1]
    if n == 3 and (x == n or y == n):
    return True
    else:
    return False


    WHY? nums.index(n) return the first position of n not the current position.






    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%2f55316807%2fwhy-doesnt-this-code-give-the-right-results-for-numeric-comparisons%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      2














      I try to explain the working of your function for has_33([1, 3, 3]). This way it gets obvious why your function is not doing what you expect it to do.



      def has_33(nums):
      # Call function and nums = [1, 3, 3]

      for n in nums:
      # Iterate over nums. n = 1

      a = nums.index(n)
      # Get the index of the list a where element = 1; a = 0

      x = nums[a + 1]
      # 0 + 1 = 1 -> x = nums[1] = 3

      y = nums[a - 1]
      # 0 - 1 = -1 -> y = nums[-1] = 3 (index -1 points to the last element of the list)

      if n == 3 and (x == n or y == n):
      # False, since n != 3 (even though x = 3 and y = 3)

      return True
      else:
      return False
      # When returning, the functin stopts executing, hence n never reaches another element.





      share|improve this answer





























        2














        I try to explain the working of your function for has_33([1, 3, 3]). This way it gets obvious why your function is not doing what you expect it to do.



        def has_33(nums):
        # Call function and nums = [1, 3, 3]

        for n in nums:
        # Iterate over nums. n = 1

        a = nums.index(n)
        # Get the index of the list a where element = 1; a = 0

        x = nums[a + 1]
        # 0 + 1 = 1 -> x = nums[1] = 3

        y = nums[a - 1]
        # 0 - 1 = -1 -> y = nums[-1] = 3 (index -1 points to the last element of the list)

        if n == 3 and (x == n or y == n):
        # False, since n != 3 (even though x = 3 and y = 3)

        return True
        else:
        return False
        # When returning, the functin stopts executing, hence n never reaches another element.





        share|improve this answer



























          2












          2








          2







          I try to explain the working of your function for has_33([1, 3, 3]). This way it gets obvious why your function is not doing what you expect it to do.



          def has_33(nums):
          # Call function and nums = [1, 3, 3]

          for n in nums:
          # Iterate over nums. n = 1

          a = nums.index(n)
          # Get the index of the list a where element = 1; a = 0

          x = nums[a + 1]
          # 0 + 1 = 1 -> x = nums[1] = 3

          y = nums[a - 1]
          # 0 - 1 = -1 -> y = nums[-1] = 3 (index -1 points to the last element of the list)

          if n == 3 and (x == n or y == n):
          # False, since n != 3 (even though x = 3 and y = 3)

          return True
          else:
          return False
          # When returning, the functin stopts executing, hence n never reaches another element.





          share|improve this answer















          I try to explain the working of your function for has_33([1, 3, 3]). This way it gets obvious why your function is not doing what you expect it to do.



          def has_33(nums):
          # Call function and nums = [1, 3, 3]

          for n in nums:
          # Iterate over nums. n = 1

          a = nums.index(n)
          # Get the index of the list a where element = 1; a = 0

          x = nums[a + 1]
          # 0 + 1 = 1 -> x = nums[1] = 3

          y = nums[a - 1]
          # 0 - 1 = -1 -> y = nums[-1] = 3 (index -1 points to the last element of the list)

          if n == 3 and (x == n or y == n):
          # False, since n != 3 (even though x = 3 and y = 3)

          return True
          else:
          return False
          # When returning, the functin stopts executing, hence n never reaches another element.






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 23 at 18:27

























          answered Mar 23 at 18:14









          jeanggi90jeanggi90

          590621




          590621























              1














              As pointed out in the comments, the main reason why this doesn't work is that you return false on the first iteration. Concerning the implementation, you can simplify things a bit to understand a bit more clearly what's going on:



              def has_33(nums):
              for a in range(len(nums)-1):
              x = nums[a]
              y = nums[a + 1]
              if x == 3 and y == 3:
              return True
              return False


              In your original solution, you were iterating over items by group of 3, adding print(y, n, x) right before your test would have output the following (for a call to has_33([1, 2, 3, 3, 4])):



              item at: i-1 i i+1
              ---------------
              i = 0 4 1 2
              i = 1 1 2 3
              i = 2 2 3 3


              In the first line, 4 1 2, the 4 is the item at position 0-1 = -1, in python, negative indexes correspond to positions relative to the end of the list. For example, nums[-1] is the last item from nums and nums[-2] is the one before the last, etc.



              In this second code we just iterate through nums's indexes to get every x item together with the following item y, printing print(x, y) would give:



              item at: i i+1
              ---------
              i = 0 1 2
              i = 1 2 3
              i = 2 3 3


              Remark that, in the end we just used the indexes to get items, when the index is not used for anything else, you can often use the zip function instead:



              def has_33(nums):
              for x, y in zip(nums, nums[1:]):
              if x == 3 and y == x:
              return True
              return False

              has_33([1, 2, 3, 3, 1])


              This outputs True, and for the record:



              >>> nums
              [1, 2, 3, 3, 1]
              >>> nums[1:]
              [2, 3, 3, 1]
              >>> list(zip(nums, nums[1:]))
              [(1, 2), (2, 3), (3, 3), (3, 1)]


              The zip function will pair item at index i from the first list with item at index i from the second list. Here we just removed the first item from nums to form our second list, using this strategy we managed to pair item i with item i+1.



              As mentioned in the comments, you can even use the function any that does exactly what our loop does



              def has_33(nums):
              return any(p == (3, 3) for p in zip(nums, nums[1:]))





              share|improve this answer




















              • 1





                you can further shorten your solution to def has_33(nums): return any(x == y == 3 for x, y in zip(nums, nums[1:]))

                – Boris
                Mar 23 at 18:28












              • You surely can, introducing zip to the OP was the main goal here, as I think it really is something hard to understand for python beginners. Both any or all are pretty straightforward (I think). But that's always worth mentioning, if you think I should add it I will.

                – cglacet
                Mar 23 at 18:31
















              1














              As pointed out in the comments, the main reason why this doesn't work is that you return false on the first iteration. Concerning the implementation, you can simplify things a bit to understand a bit more clearly what's going on:



              def has_33(nums):
              for a in range(len(nums)-1):
              x = nums[a]
              y = nums[a + 1]
              if x == 3 and y == 3:
              return True
              return False


              In your original solution, you were iterating over items by group of 3, adding print(y, n, x) right before your test would have output the following (for a call to has_33([1, 2, 3, 3, 4])):



              item at: i-1 i i+1
              ---------------
              i = 0 4 1 2
              i = 1 1 2 3
              i = 2 2 3 3


              In the first line, 4 1 2, the 4 is the item at position 0-1 = -1, in python, negative indexes correspond to positions relative to the end of the list. For example, nums[-1] is the last item from nums and nums[-2] is the one before the last, etc.



              In this second code we just iterate through nums's indexes to get every x item together with the following item y, printing print(x, y) would give:



              item at: i i+1
              ---------
              i = 0 1 2
              i = 1 2 3
              i = 2 3 3


              Remark that, in the end we just used the indexes to get items, when the index is not used for anything else, you can often use the zip function instead:



              def has_33(nums):
              for x, y in zip(nums, nums[1:]):
              if x == 3 and y == x:
              return True
              return False

              has_33([1, 2, 3, 3, 1])


              This outputs True, and for the record:



              >>> nums
              [1, 2, 3, 3, 1]
              >>> nums[1:]
              [2, 3, 3, 1]
              >>> list(zip(nums, nums[1:]))
              [(1, 2), (2, 3), (3, 3), (3, 1)]


              The zip function will pair item at index i from the first list with item at index i from the second list. Here we just removed the first item from nums to form our second list, using this strategy we managed to pair item i with item i+1.



              As mentioned in the comments, you can even use the function any that does exactly what our loop does



              def has_33(nums):
              return any(p == (3, 3) for p in zip(nums, nums[1:]))





              share|improve this answer




















              • 1





                you can further shorten your solution to def has_33(nums): return any(x == y == 3 for x, y in zip(nums, nums[1:]))

                – Boris
                Mar 23 at 18:28












              • You surely can, introducing zip to the OP was the main goal here, as I think it really is something hard to understand for python beginners. Both any or all are pretty straightforward (I think). But that's always worth mentioning, if you think I should add it I will.

                – cglacet
                Mar 23 at 18:31














              1












              1








              1







              As pointed out in the comments, the main reason why this doesn't work is that you return false on the first iteration. Concerning the implementation, you can simplify things a bit to understand a bit more clearly what's going on:



              def has_33(nums):
              for a in range(len(nums)-1):
              x = nums[a]
              y = nums[a + 1]
              if x == 3 and y == 3:
              return True
              return False


              In your original solution, you were iterating over items by group of 3, adding print(y, n, x) right before your test would have output the following (for a call to has_33([1, 2, 3, 3, 4])):



              item at: i-1 i i+1
              ---------------
              i = 0 4 1 2
              i = 1 1 2 3
              i = 2 2 3 3


              In the first line, 4 1 2, the 4 is the item at position 0-1 = -1, in python, negative indexes correspond to positions relative to the end of the list. For example, nums[-1] is the last item from nums and nums[-2] is the one before the last, etc.



              In this second code we just iterate through nums's indexes to get every x item together with the following item y, printing print(x, y) would give:



              item at: i i+1
              ---------
              i = 0 1 2
              i = 1 2 3
              i = 2 3 3


              Remark that, in the end we just used the indexes to get items, when the index is not used for anything else, you can often use the zip function instead:



              def has_33(nums):
              for x, y in zip(nums, nums[1:]):
              if x == 3 and y == x:
              return True
              return False

              has_33([1, 2, 3, 3, 1])


              This outputs True, and for the record:



              >>> nums
              [1, 2, 3, 3, 1]
              >>> nums[1:]
              [2, 3, 3, 1]
              >>> list(zip(nums, nums[1:]))
              [(1, 2), (2, 3), (3, 3), (3, 1)]


              The zip function will pair item at index i from the first list with item at index i from the second list. Here we just removed the first item from nums to form our second list, using this strategy we managed to pair item i with item i+1.



              As mentioned in the comments, you can even use the function any that does exactly what our loop does



              def has_33(nums):
              return any(p == (3, 3) for p in zip(nums, nums[1:]))





              share|improve this answer















              As pointed out in the comments, the main reason why this doesn't work is that you return false on the first iteration. Concerning the implementation, you can simplify things a bit to understand a bit more clearly what's going on:



              def has_33(nums):
              for a in range(len(nums)-1):
              x = nums[a]
              y = nums[a + 1]
              if x == 3 and y == 3:
              return True
              return False


              In your original solution, you were iterating over items by group of 3, adding print(y, n, x) right before your test would have output the following (for a call to has_33([1, 2, 3, 3, 4])):



              item at: i-1 i i+1
              ---------------
              i = 0 4 1 2
              i = 1 1 2 3
              i = 2 2 3 3


              In the first line, 4 1 2, the 4 is the item at position 0-1 = -1, in python, negative indexes correspond to positions relative to the end of the list. For example, nums[-1] is the last item from nums and nums[-2] is the one before the last, etc.



              In this second code we just iterate through nums's indexes to get every x item together with the following item y, printing print(x, y) would give:



              item at: i i+1
              ---------
              i = 0 1 2
              i = 1 2 3
              i = 2 3 3


              Remark that, in the end we just used the indexes to get items, when the index is not used for anything else, you can often use the zip function instead:



              def has_33(nums):
              for x, y in zip(nums, nums[1:]):
              if x == 3 and y == x:
              return True
              return False

              has_33([1, 2, 3, 3, 1])


              This outputs True, and for the record:



              >>> nums
              [1, 2, 3, 3, 1]
              >>> nums[1:]
              [2, 3, 3, 1]
              >>> list(zip(nums, nums[1:]))
              [(1, 2), (2, 3), (3, 3), (3, 1)]


              The zip function will pair item at index i from the first list with item at index i from the second list. Here we just removed the first item from nums to form our second list, using this strategy we managed to pair item i with item i+1.



              As mentioned in the comments, you can even use the function any that does exactly what our loop does



              def has_33(nums):
              return any(p == (3, 3) for p in zip(nums, nums[1:]))






              share|improve this answer














              share|improve this answer



              share|improve this answer








              edited Mar 24 at 22:40

























              answered Mar 23 at 18:19









              cglacetcglacet

              1,785821




              1,785821







              • 1





                you can further shorten your solution to def has_33(nums): return any(x == y == 3 for x, y in zip(nums, nums[1:]))

                – Boris
                Mar 23 at 18:28












              • You surely can, introducing zip to the OP was the main goal here, as I think it really is something hard to understand for python beginners. Both any or all are pretty straightforward (I think). But that's always worth mentioning, if you think I should add it I will.

                – cglacet
                Mar 23 at 18:31













              • 1





                you can further shorten your solution to def has_33(nums): return any(x == y == 3 for x, y in zip(nums, nums[1:]))

                – Boris
                Mar 23 at 18:28












              • You surely can, introducing zip to the OP was the main goal here, as I think it really is something hard to understand for python beginners. Both any or all are pretty straightforward (I think). But that's always worth mentioning, if you think I should add it I will.

                – cglacet
                Mar 23 at 18:31








              1




              1





              you can further shorten your solution to def has_33(nums): return any(x == y == 3 for x, y in zip(nums, nums[1:]))

              – Boris
              Mar 23 at 18:28






              you can further shorten your solution to def has_33(nums): return any(x == y == 3 for x, y in zip(nums, nums[1:]))

              – Boris
              Mar 23 at 18:28














              You surely can, introducing zip to the OP was the main goal here, as I think it really is something hard to understand for python beginners. Both any or all are pretty straightforward (I think). But that's always worth mentioning, if you think I should add it I will.

              – cglacet
              Mar 23 at 18:31






              You surely can, introducing zip to the OP was the main goal here, as I think it really is something hard to understand for python beginners. Both any or all are pretty straightforward (I think). But that's always worth mentioning, if you think I should add it I will.

              – cglacet
              Mar 23 at 18:31












              0














              There is a logic error in your code at line 3. You mustn't use:



              a = nums.index(n)


              To get the index but you need to use this way:



              for a, n in enumerate(nums):


              Finally there is your corrected code:



              def has_33(nums):
              for a, n in enumerate(nums):
              x = nums[a + 1]
              y = nums[a - 1]
              if n == 3 and (x == n or y == n):
              return True
              else:
              return False


              WHY? nums.index(n) return the first position of n not the current position.






              share|improve this answer



























                0














                There is a logic error in your code at line 3. You mustn't use:



                a = nums.index(n)


                To get the index but you need to use this way:



                for a, n in enumerate(nums):


                Finally there is your corrected code:



                def has_33(nums):
                for a, n in enumerate(nums):
                x = nums[a + 1]
                y = nums[a - 1]
                if n == 3 and (x == n or y == n):
                return True
                else:
                return False


                WHY? nums.index(n) return the first position of n not the current position.






                share|improve this answer

























                  0












                  0








                  0







                  There is a logic error in your code at line 3. You mustn't use:



                  a = nums.index(n)


                  To get the index but you need to use this way:



                  for a, n in enumerate(nums):


                  Finally there is your corrected code:



                  def has_33(nums):
                  for a, n in enumerate(nums):
                  x = nums[a + 1]
                  y = nums[a - 1]
                  if n == 3 and (x == n or y == n):
                  return True
                  else:
                  return False


                  WHY? nums.index(n) return the first position of n not the current position.






                  share|improve this answer













                  There is a logic error in your code at line 3. You mustn't use:



                  a = nums.index(n)


                  To get the index but you need to use this way:



                  for a, n in enumerate(nums):


                  Finally there is your corrected code:



                  def has_33(nums):
                  for a, n in enumerate(nums):
                  x = nums[a + 1]
                  y = nums[a - 1]
                  if n == 3 and (x == n or y == n):
                  return True
                  else:
                  return False


                  WHY? nums.index(n) return the first position of n not the current position.







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 23 at 18:20









                  Cpp ForeverCpp Forever

                  1525




                  1525



























                      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%2f55316807%2fwhy-doesnt-this-code-give-the-right-results-for-numeric-comparisons%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

                      Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                      SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                      은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현