0

I'm new to programming so let me know if you need anymore details but I've been having trouble getting this to output 2 instead of 1. Problem is I don't understand how to read read the last piece of code!

def sphinx_swap(start, goal, limit):
    """A diff function for autocorrect that determines how many letters
    in START need to be substituted to create GOAL, then adds the difference in
    their lengths.
    """
    # BEGIN PROBLEM 6
    if len(start) == 0 or len(goal) == 0:
        return abs(len(start) - (len(goal)))
    elif limit == 0:
        return 1
    elif start[0] != goal[0]:
        return 1 + sphinx_swap(start[1:], goal[1:], limit - 1)
    else:
        return sphinx_swap(start[1:], goal[1:], limit)

sum([sphinx_swap('yond', 'yo', k) > k for k in range(4)])       #line I don't understand
juanpa.arrivillaga
  • 65,257
  • 7
  • 88
  • 122
Jeffrey Cao
  • 21
  • 2
  • 9
  • 1
    That is a list comprehension, which is *not* a one-line for-statement, it isn't a statement at all, but an expression. Note, please *always* use the generic [python] tag for all python questions – juanpa.arrivillaga May 07 '20 at 21:12

1 Answers1

1

You example gives context but it isn't necessarily related to your confusion. Take a look at generators and list comprehensions (see link at bottom).

In the meantime, we ignore your context and pick a similar comprehension.

sum([k > 2 for k in range(4)])

This is just calling sum on a list that will be generated, which is roughly equivalent to:

no_name = []
for k in range(4):
    no_name.append(k > 2)
sum(no_name)

https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions

For completeness I should mention that a generator is usually better than a list if you don't actually use the list, since it will just be discarded e.g. sum(~ for ~) vs sum([~ for ~]).

Cireo
  • 3,593
  • 1
  • 13
  • 21
  • okay thanks for the example, helps me visualize it a lot better – Jeffrey Cao May 07 '20 at 21:17
  • 1
    sorry, also did you mean to put 2 > k? – Jeffrey Cao May 07 '20 at 21:19
  • 1
    it doesn't really matter because your example is `func(k) > k`, which has nothing to do with comprehensions either =). I just wanted to show you can put expressions there – Cireo May 07 '20 at 21:21
  • So doesn't append() here just add a boolean value to the list? Or is it saying if the value is > whatever K is at the time, add it to the list – Jeffrey Cao May 07 '20 at 21:24
  • 1
    It's adding a boolean and since booleans are integers too with `True` being `1` and `False` being `0` we can add up the values. – Matthias May 07 '20 at 21:49
  • 1
    Another way to write `sum([k > 2 for k in range(4)])` would be `sum([1 for k in range(4) if k > 2])`. In the second case the list will contain only the number `1` for each `k` that is bigger than 2. – Matthias May 07 '20 at 21:51