#Hi sir We need Exact answer we believe your Experience Show
Number of moves: you are given a nxn square chessboard with one bishop and k number of obstacles placed on it. A bishop can go to different places in a single move. find the total no.of places that are possible for the bishop in a single move. Each square is referenced by a type describing the row, R, and column, C, where the square is located. explanation: given N=6 K=2 bishop position 5 2 obstacle positions (2 2), (1 5) the bishop can move in so o/p is 6 I/p: 6 2 5 2 2 2 1 6 O/p: 6 I/p: 6 4 3 3 1 3 3 1 5 1 1 5 O/p: 7 Number of moves: you are given a nxn square chessboard with one bishop and k number of obstacles placed on it. A bishop can go to different places in a single move. find the total no.of places that are possible for the bishop in a single move. Each square is referenced by a type describing the row, R, and column, C, where the square is located. explanation: given N=6 K=2 bishop position 5 2 obstacle positions (2 2), (1 5) the bishop can move in so o/p is 6 I/p: 6 2 5 2 2 2 1 6 O/p: 6 I/p: 6 4 3 3 1 3 3 1 5 1 1 5 O/p: 7
AbstractThis
is a proposal for creating a way to assign to variables within an expression using the notation As part of this change, there is also an update to dictionary comprehension evaluation order to ensure key expressions are executed before value expressions (allowing the key to be bound to a name and then re-used as part of calculating the corresponding value). During discussion of this PEP, the operator became informally known as “the walrus operator”. The construct’s formal name is “Assignment Expressions” (as per the PEP title), but they may also be referred to as “Named Expressions” (e.g. the CPython reference implementation uses that name internally). RationaleNaming the result of an expression is an important part of programming, allowing a descriptive name to be used in place of a longer expression, and permitting reuse. Currently, this feature is available only in statement form, making it unavailable in list comprehensions and other expression contexts. Additionally, naming sub-parts of a large expression can assist an interactive debugger, providing useful display hooks and partial results. Without a way to capture sub-expressions inline, this would require refactoring of the original code; with assignment expressions, this merely requires the insertion of a few The importance of real codeDuring the development of this PEP many people (supporters and critics both) have had a tendency to focus on toy examples on the one hand, and on overly complex examples on the other. The danger of toy examples is twofold: they are often too abstract to make anyone go “ooh, that’s compelling”, and they are easily refuted with “I would never write it that way anyway”. The danger of overly complex examples is that they provide a convenient strawman for critics of the proposal to shoot down (“that’s obfuscated”). Yet there is some use for both extremely simple and extremely complex examples: they are helpful to clarify the intended semantics. Therefore, there will be some of each below. However, in order to be compelling, examples should be rooted in real code, i.e. code that was written without any thought of this PEP, as part of a useful application, however large or small. Tim Peters has been extremely helpful by going over his own personal code repository and picking examples of code he had written that (in his view) would have been clearer if rewritten with (sparing) use of assignment expressions. His conclusion: the current proposal would have allowed a modest but clear improvement in quite a few bits of code. Another use of real code is to observe indirectly how much value programmers place on compactness. Guido van Rossum searched through a Dropbox code base and discovered some evidence that programmers value writing fewer lines over shorter lines. Case in point: Guido found several examples where a programmer repeated a subexpression, slowing down the program, in order to save one line of code, e.g. instead of writing: match = re.match(data) group = match.group(1) if match else None they would write: group = re.match(data).group(1) if re.match(data) else None Another example illustrates that programmers sometimes do more work to save an extra level of indentation: match2 = pattern1.match(data) match2 = pattern2.match(data) if match2: result = match2.group(1) elif match2: result = match2.group(2) else: result = None This code tries to match match2 = pattern1.match(data) if match2: result = match2.group(1) else: match2 = pattern2.match(data) if match2: result = match2.group(2) else: result = None Syntax and semanticsIn most contexts where arbitrary Python expressions can be used, a named expression can appear. This is of the form The value of such a named expression is the same as the incorporated expression, with the additional side-effect that the target is assigned that value: # Handle a matched regex if (match := pattern.search(data)) is not None: # Do something with match # A loop that can't be trivially rewritten using 2-arg iter() while chunk := file.read(8192): process(chunk) # Reuse a value that's expensive to compute [y := f(x), y**2, y**3] # Share a subexpression between a comprehension filter clause and its output filtered_data = [y for x in data if (y := f(x)) is not None] Exceptional casesThere are a few places where assignment expressions are not allowed, in order to avoid ambiguities or user confusion:
Scope of the targetAn assignment expression does not introduce a new scope. In most cases the scope in which the target will be bound is self-explanatory: it is the current scope. If this scope contains a There is one special case: an assignment expression occurring in a list, set or dict comprehension or in a generator expression (below collectively referred to as “comprehensions”) binds the target in the containing scope, honoring a The motivation for this special case is twofold. First, it allows us to conveniently capture a “witness” for an if any((comment := line).startswith('#') for line in lines): print("First comment:", comment) else: print("There are no comments") if all((nonblank := line).strip() == '' for line in lines): print("All lines are blank") else: print("First non-blank line:", nonblank) Second, it allows a compact way of updating mutable state from a comprehension, for example: # Compute partial sums in a list comprehension total = 0 partial_sums = [total := total + v for v in values] print("Total:", total) However, an assignment expression target name cannot be the same as a For example, [[(j := j) for i in range(5)] for j in range(5)] # INVALID [i := 0 for i, j in stuff] # INVALID [i+1 for i in (i := stuff)] # INVALID While it’s technically possible to assign
consistent semantics to these cases, it’s difficult to determine whether those semantics actually make sense in the absence of real use cases. Accordingly, the reference implementation will ensure that such cases raise This restriction applies even if the assignment expression is never executed: [False and (i := 0) for i, j in stuff] # INVALID [i for i, j in stuff if True or (j := 1)] # INVALID For the comprehension body (the part before the first “for” keyword) and the filter expression (the part after “if” and before any nested “for”), this restriction applies solely to target names that are also used as iteration variables in the comprehension. Lambda expressions appearing in these positions introduce a new explicit function scope, and hence may use assignment expressions with no additional restrictions. Due to design constraints in the reference implementation (the symbol table analyser cannot easily detect when names are re-used between the leftmost comprehension iterable expression and the rest of the comprehension), named expressions are disallowed entirely as part of comprehension iterable expressions (the part after each “in”, and before any subsequent “if” or “for” keyword): [i+1 for i in (j := stuff)] # INVALID [i+1 for i in range(2) for j in (k := stuff)] # INVALID [i+1 for i in [j for j in (k := stuff)]] # INVALID [i+1 for i in (lambda: (j := stuff))()] # INVALID A further exception applies when an assignment expression occurs in a comprehension whose containing scope is a class scope. If the rules above were to result in the target being assigned in that class’s scope, the assignment expression is
expressly invalid. This case also raises class Example: [(j := i) for i in range(5)] # INVALID (The reason for the latter exception is the implicit function scope created for comprehensions – there is currently no runtime mechanism for a function to refer to a variable in the containing class scope, and we do not want to add such a mechanism. If this issue ever gets resolved this special case may be removed from the specification of assignment expressions. Note that the problem already exists for using a variable defined in the class scope from a comprehension.) See Appendix B for some examples of how the rules for targets in comprehensions translate to equivalent code. Relative precedence of :=The The Some examples to clarify what’s technically valid or invalid: # INVALID x := 0 # Valid alternative (x := 0) # INVALID x = y := 0 # Valid alternative x = (y := 0) # Valid len(lines := f.readlines()) # Valid foo(x := 3, cat='vector') # INVALID foo(cat=category := 'vector') # Valid alternative foo(cat=(category := 'vector')) Most of the “valid” examples above are not recommended, since human readers of Python source code who are quickly glancing at some code may miss the distinction. But simple cases are not objectionable: # Valid if any(len(longline := line) >= 100 for line in lines): print("Extremely long line:", longline) This PEP recommends always putting spaces around Change to evaluation orderIn order to have precisely defined semantics, the proposal requires evaluation order to be well-defined. This is technically not a new requirement, as function calls may already have side effects. Python already has a rule that subexpressions are generally evaluated from left to right. However, assignment expressions make these side effects more visible, and we propose a single change to the current evaluation order:
Differences between assignment expressions and assignment statementsMost importantly, since Conversely, assignment expressions don’t support the advanced features found in assignment statements:
Specification changes during implementationThe following changes have been made based on implementation experience and additional review after the PEP was first accepted and before Python 3.8 was released:
ExamplesExamples from the Python standard librarysite.pyenv_base is only used on these lines, putting its assignment on the if moves it as the “header” of the block.
_pydecimal.pyAvoid nested
copy.pyCode looks more regular and avoid multiple nested if. (See Appendix A for the origin of this example.)
datetime.pytz is only used for
sysconfig.pyCalling
Simplifying list comprehensionsA list comprehension can map and filter efficiently by capturing the condition: results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0] Similarly, a subexpression can be reused within the main expression, by giving it a name on first use: stuff = [[y := f(x), x/y] for x in range(5)] Note that in both cases the variable Capturing condition valuesAssignment expressions can be used to good effect in the header of an # Loop-and-a-half while (command := input("> ")) != "quit": print("You entered:", command) # Capturing regular expression match objects # See, for instance, Lib/pydoc.py, which uses a multiline spelling # of this effect if match := re.search(pat, text): print("Found:", match.group(0)) # The same syntax chains nicely into 'elif' statements, unlike the # equivalent using assignment statements. elif match := re.search(otherpat, text): print("Alternate found:", match.group(0)) elif match := re.search(third, text): print("Fallback found:", match.group(0)) # Reading socket data until an empty string is returned while data := sock.recv(8192): print("Received data:", data) Particularly with the ForkAn example from the low-level UNIX world: if pid := os.fork(): # Parent code else: # Child code Rejected alternative proposalsProposals broadly similar to this one have come up frequently on python-ideas. Below are a number of alternative syntaxes, some of them specific to comprehensions, which have been rejected in favour of the one given above. Changing the scope rules for comprehensionsA previous version of this PEP proposed subtle changes to the scope rules for comprehensions, to make them more usable in class scope and to unify the scope of the “outermost iterable” and the rest of the comprehension. However, this part of the proposal would have caused backwards incompatibilities, and has been withdrawn so the PEP can focus on assignment expressions. Alternative spellingsBroadly the same semantics as the current proposal, but spelled differently.
Special-casing conditional statementsOne of the most popular use-cases is if re.search(pat, text) as match: print("Found:", match.group(0)) This works beautifully if and ONLY if the desired condition is based on the truthiness of the captured value. It is thus effective for specific use-cases (regex matches, socket reads that return Advantages: No syntactic ambiguities. Disadvantages: Answers only a fraction of possible
use-cases, even in Special-casing comprehensionsAnother common use-case is comprehensions (list/set/dict, and genexps). As above, proposals have been made for comprehension-specific solutions.
Regardless of the spelling chosen, this introduces a stark difference between comprehensions and the equivalent unrolled long-hand form of the loop. It is no longer possible to unwrap the loop into statement form without reworking any name
bindings. The only keyword that can be repurposed to this task is Lowering operator precedenceThere are two logical precedences for the pos = -1 while pos := buffer.find(search_term, pos + 1) >= 0: ... Once find() returns -1, the loop
terminates. If While this behaviour would be convenient in many situations, it is also harder to explain than “the := operator behaves just like the assignment statement”, and as such, the precedence for Allowing commas to the rightSome critics have claimed that the assignment expressions should allow unparenthesized tuples on the right, so that these two would be equivalent: (point := (x, y)) (point := x, y) (With the current version of the proposal, the latter would be equivalent to However, adopting this stance would logically lead to the conclusion that when used in a function call, assignment expressions also bind less tight than comma, so we’d have the following confusing equivalence: foo(x := 1, y) foo(x := (1, y)) The less confusing option is to make Always requiring parenthesesIt’s been proposed to just always require parentheses around an assignment expression. This would resolve many ambiguities, and indeed parentheses will frequently be needed to extract the desired subexpression. But in the following cases the extra parentheses feel redundant: # Top level in if if match := pattern.match(line): return match.group(1) # Short call len(lines := f.readlines()) Frequently Raised ObjectionsWhy not just turn existing assignment into an expression?C and its derivatives define the With assignment expressions, why bother with assignment statements?The two forms have
different flexibilities. The Why not use a sublocal scope and prevent namespace pollution?Previous revisions of this proposal involved sublocal scope (restricted to a single statement), preventing name leakage and namespace pollution. While a definite advantage in a number of situations, this increases complexity in many others, and the costs are not justified by the benefits. In the interests of language simplicity, the name bindings created here are exactly equivalent to any other name bindings, including that usage at class or module scope will create
externally-visible names. This is no different from (The author wishes to thank Guido van Rossum and Christoph Groth for their suggestions to move the proposal in this direction. [2]) Style guide recommendationsAs expression assignments can sometimes be used equivalently to statement assignments, the question of which should be preferred will arise. For the benefit of style guides such as PEP 8, two recommendations are suggested.
AcknowledgementsThe authors wish to thank Nick Coghlan and Steven D’Aprano for their considerable contributions to this proposal, and members of the core-mentorship mailing list for assistance with implementation. Appendix A: Tim Peters’s findingsHere’s a brief essay Tim Peters wrote on the topic. I dislike “busy” lines of code, and also dislike putting conceptually unrelated logic on a single line. So, for example, instead of: i = j = count = nerrors = 0 I prefer: i = j = 0 count = 0 nerrors = 0 instead. So I suspected I’d find few places I’d want to use assignment expressions. I didn’t even consider them for lines already stretching halfway across the screen. In other cases, “unrelated” ruled: mylast = mylast[1] yield mylast[0] is a vast improvement over the briefer: yield (mylast := mylast[1])[0] The original two statements are doing entirely different conceptual things, and slamming them together is conceptually insane. In other cases, combining related logic made it harder to understand, such as rewriting: while True: old = total total += term if old == total: return total term *= mx2 / (i*(i+1)) i += 2 as the briefer: while total != (total := total + term): term *= mx2 / (i*(i+1)) i += 2 return total The But cases like that were rare. Name binding is very frequent, and “sparse is better than dense” does not mean “almost empty is better
than sparse”. For example, I have many functions that return result = solution(xs, n) if result: # use result I find that clearer, and certainly a bit less typing and pattern-matching reading, as: if result := solution(xs, n): # use result It’s also nice to trade away a small amount of horizontal whitespace to get another _line_ of surrounding code on screen. I didn’t give much weight to this at first, but it was so very frequent it added up, and I soon enough became annoyed that I couldn’t actually run the briefer code. That surprised me! There are other cases where assignment expressions really shine. Rather than pick another from my code, Kirill Balunov gave a lovely example from the standard library’s reductor = dispatch_table.get(cls) if reductor: rv = reductor(x) else: reductor = getattr(x, "__reduce_ex__", None) if reductor: rv = reductor(4) else: reductor = getattr(x, "__reduce__", None) if reductor: rv = reductor() else: raise Error("un(shallow)copyable object of type %s" % cls) The ever-increasing indentation is semantically misleading: the logic is conceptually flat, “the first test that succeeds wins”: if reductor := dispatch_table.get(cls): rv = reductor(x) elif reductor := getattr(x, "__reduce_ex__", None): rv = reductor(4) elif reductor := getattr(x, "__reduce__", None): rv = reductor() else: raise Error("un(shallow)copyable object of type %s" % cls) Using easy assignment expressions allows the visual structure of the code to emphasize the conceptual flatness of the logic; ever-increasing indentation obscured it. A smaller example from my code delighted me, both allowing to put inherently related logic in a single line, and allowing to remove an annoying “artificial” indentation level: diff = x - x_base if diff: g = gcd(diff, n) if g > 1: return g became: if (diff := x - x_base) and (g := gcd(diff, n)) > 1: return g That So, in all, in most lines binding a name, I wouldn’t use assignment expressions, but because that construct is so very frequent, that leaves many places I would. In most of the latter, I found a small win that adds up due to how often it occurs, and in the rest I found a moderate to major win. I’d
certainly use it more often than ternary A numeric exampleI have another example that quite impressed me at the time. Where all variables are positive integers, and a is at least as large as the n’th root of x, this algorithm returns the floor of the n’th root of x (and roughly doubling the number of accurate bits per iteration): while a > (d := x // a**(n-1)): a = ((n-1)*a + d) // n return a It’s not obvious why that works, but is no more obvious in the “loop and a half” form. It’s hard to prove correctness without building on the right insight (the “arithmetic mean - geometric mean inequality”), and knowing some non-trivial things about how nested floor functions behave. That is, the challenges are in the math, not really in the coding. If you do know all that, then the assignment-expression form is easily read as “while the current guess is too large, get a smaller guess”, where the “too large?” test and the new guess share an expensive sub-expression. To my eyes, the original form is harder to understand: while True: d = x // a**(n-1) if a <= d: break a = ((n-1)*a + d) // n return a Appendix B: Rough code translations for comprehensionsThis appendix attempts to clarify (though not specify) the rules when a target occurs in a comprehension or in a generator expression. For a number of illustrative examples we show the original code, containing a comprehension, and the translation, where the comprehension has been replaced by an equivalent generator function plus some scaffolding. Since Note: comprehensions are already implemented via synthesizing nested generator functions like those in this appendix. The new part is adding appropriate declarations to establish the intended scope of assignment expression targets (the same scope they resolve to as if the assignment were performed in the block containing the outermost comprehension). For type inference purposes, these illustrative expansions do not imply that assignment expression targets are always Optional (but they do indicate the target binding scope). Let’s start with a reminder of what code is generated for a generator expression without assignment expression.
Let’s add a simple assignment expression.
Let’s add a
Or instead let’s add a
Finally, let’s nest two comprehensions.
Appendix C: No Changes to Scope SemanticsBecause it has been a point of confusion, note that nothing about Python’s scoping semantics is changed. Function-local scopes continue to be resolved at compile time, and to have indefinite temporal extent at run time (“full closures”). Example: a = 42 def f(): # `a` is local to `f`, but remains unbound # until the caller executes this genexp: yield ((a := i) for i in range(3)) yield lambda: a + 100 print("done") try: print(f"`a` is bound to {a}") assert False except UnboundLocalError: print("`a` is not yet bound") Then: >>> results = list(f()) # [genexp, lambda] done `a` is not yet bound # The execution frame for f no longer exists in CPython, # but f's locals live so long as they can still be referenced. >>> list(map(type, results)) [<class 'generator'>, <class 'function'>] >>> list(results[0]) [0, 1, 2] >>> results[1]() 102 >>> a 42 ReferencesCopyrightThis document has been placed in the public domain. |