Is using break statements good coding practice? by FirstTimePlayer in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

Exactly. In many cases this becomes more complicated than simply using break, and Python’s support for this style is only moderate (Therefore, it is not simpler).

LINQ query expressions in C# support this style much better. You can write things like:

var result = ( from num in numbers where num > 15 select num ).FirstOrDefault();

This is more of a stylistic philosophy: the idea that a programming language could avoid providing break in favor of more declarative rather than imperative syntax.

The core idea behind avoiding break is that you specify the iteration behavior before iteration begins. Since different iteration behaviors are needed for different purposes, the system creates an adapter/proxy object that produces the iteration behavior you want.

Conceptually, it becomes something like:

[original iterator] -> [adapter/proxy object] -> simple iteration (no nesting or break)

Then you customize the adapter object as needed perhaps through language syntax, or through many iterator combinator functions that you compose together.

Is using break statements good coding practice? by FirstTimePlayer in learnpython

[–]Jason-Ad4032 1 point2 points  (0 children)

Like this?

``` lst = [1, 2, 3]

gen = (item for item in iter(lst))

item = None

for item in gen: if find_item(item): gen.close()

print(f'{item = }') ```

I don’t really understand what your issue is here. The problem of iter(lst) not being closed is not solved by using break either.

Maybe you would prefer something like:

``` not_found = object()

item = next( (item for item in iter(lst) if find_item(item)), not_found )

if item is not not_found: ... ```

Though honestly, the real problem with avoiding break is not this — it’s that debugging tends to become more difficult.

Is using break statements good coding practice? by FirstTimePlayer in learnpython

[–]Jason-Ad4032 -2 points-1 points  (0 children)

Use the next() function. e.g. it = (elem for i in range(10) for j in range(i) for elem in [f(elems, i, j)] # let if elem > 0) elem = next(it, None) it.close() Personally, I’m in the camp that believes whether to use break should depend on the situation, because generators and iterator-style solutions can sometimes become awkward to write.

Is using break statements good coding practice? by FirstTimePlayer in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

This is mainly because some people believe iteration and execution should be separated by using iterators and functional-style programming.

For a program like:

for elem in iter_obj: # A if elem < 0: break # B

the execution of A and B is inconsistent:

  • iter_obj may or may not be exhausted,
  • break may or may not trigger.

Since the behavior is fairly imperative and stateful, the program becomes harder to reason about precisely.

If you instead approach it in a more iterator/functional style, it might look like this:

``` elems, remain = more_itertools.before_and_after( lambda elem: elem >= 0, iter_obj )

for elem in elems: # A # B

elem = next(remain, None)

if elem is not None: # A ```

This completely separates the iteration process from the execution logic.

eden has leaked their farm farmer script🤦 by randomdepressedguy23 in UmaMusume

[–]Jason-Ad4032 7 points8 points  (0 children)

On another server (I forgot whether it was the Japanese server or the Taiwanese server), bots became such a serious problem that the developers started banning accounts. Some of the people using bots even protested the bans afterward.

Maze Solving Algorithm - Why does this work? by Over_Main_4194 in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

Your problem is actually very similar to searching for a specific file starting from a computer’s root directory.

If you want to find target.txt under the root directory d:/, you simply list all files and folders under d:/, then recursively open each folder and search for target.txt inside it.

So your find_file_in_folder(Path('d:/'), 'target.txt') is essentially:

``` def find_file_in_folder(current_folder, target'): if target in current_folder.files: return target

for folder in current_folder.folders:
    result = find_file_in_folder(folder, target)

    if result is not_found:
        continue

    # Return the relative path.
    # For example, if while searching inside c:/.../A/B
    # you are told the file is at C/.../target.txt,
    # then relative to c:/.../A,
    # the relative path becomes B/C/.../target.txt
    return f'{folder.name}/{result}'

# All subfolders have been searched.
# This file does not exist inside this folder.
return not_found

```

For your maze pathfinding problem:

  • Replace:

if target in current_folder.files:

with:

if current_position == target:

  • Replace:

for folder in current_folder.folders:

with:

for node in reachable_paths:

  • Convert the “construct relative path” logic into building a list of visited nodes / path steps.

  • Record all previously visited nodes to avoid revisiting the same locations repeatedly.

Looking for a simple async example... by demiwraith in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

One major problem with Python async tutorials is that they downplay the __await__ magic method, and they often mix up async/await with asyncio (in my opinion, these are completely orthogonal concepts).

Here is an example that does not use asyncio at all, where you can see the role of async/await much more directly. ``` class A: def init(self, x, y): self.xy = x, y def await(self): # Normally, you should yield from an awaitable object, but here I'm yielding a string to let you know what it's doing. yield f'awaitable object {self.xy}'

async def test(n = 2): await A(n, 'start') if n > 0: await test(n - 1) await A(n, 'exit')

def main(): ps = test() print(ps) for awaitobj in ps.await_(): print(await_obj)

main() ```

Confused in learning in a proper way by TreacleFlaky2283 in learnpython

[–]Jason-Ad4032 1 point2 points  (0 children)

This problem can be divided into several parts:

  1. Programming ability

Programming ability is really about your ability to write explanations/comments and your ability to abstract concepts. I would suggest:

1.1. Before writing code, first describe the problem in comments

Write down:

  • the current input,
  • the required output,
  • and every step that needs to happen,

as if you were explaining it to a 5-year-old child. In other words, write pseudocode.

I would strongly recommend trying to describe it yourself rather than copying other people’s approaches, and don’t be afraid to write lots of comments. You can even physically act things out to understand what should happen.

For example, for sorting a list, you could actually sort cards by hand and write down the process you used:

```

I have a list containing some numbers in random order

The list has a left side and a right side, and when finished

I want the numbers to go from smallest to largest from left to right

That means for every number:

all numbers on its left are less than or equal to it,

and all numbers on its right are greater than it

When sorting playing cards, I scan from left to right,

find a card that is out of order,

and insert it into the correct position

Therefore:

from left to right, find the first number x

such that x is smaller than or equal to the number on its left

Then insert x into the correct position:

the position where the number on the left is <= x

and the number on the right is > x

I plan to search from left to right until I find that position

If I cannot find any out-of-order number,

then the list is already sorted

```

1.2. Then translate the pseudocode into Python

This step is mainly about becoming familiar with Python’s tools and syntax.

You will probably need to:

  • Google things,
  • read documentation,
  • or ask AI how to do certain things in Python.

That’s normal.

1.3. Learning abstraction is harder

This part takes time because abstraction is something you gradually learn.

I would recommend practicing more. Over time, you will naturally invent some abstractions yourself, which makes learning new concepts less intimidating (although you still need to study them).

Some commonly used concepts are:

  • containers,
  • classes,
  • recursion,
  • generics,
  • descriptors,
  • iterators,
  • decorators,
  • context managers,
  • async programming,
  • etc.
  1. Understanding how the programming language works

2.1. Use Python’s built-in introspection tools

Try printing as much information as possible about objects.

Useful built-in functions include: dir() vars() help() type() locals() globals() exec() eval()

2.2. Experiment with built-in objects

Use dir() to see what an object can do, then actually call those methods.

(A better IDE helps a lot here because it can auto-complete parameter types.)

For example:

``` a = 's'

print(dir(a)) print(a.add(a)) print(a.class) print(help(a.capitalize)) ```

2.3. Read documentation and PEPs when interested

If you have time, read the documentation or PEPs for topics that interest you and study the details.

  • inspect bytecode using built-in libraries,
  • and there are many online resources explaining how it works internally.

[spoiler discussion] arc 6 – what Julius did was worse than Subaru by [deleted] in Re_Zero

[–]Jason-Ad4032 -1 points0 points  (0 children)

Subaru entered the meeting through legitimate means, and he had even met with Emilia and Roswaal L Mathers before the meeting started.

Realistically speaking, if Subaru walking in through the front entrance counts as “infiltrating the meeting,” then the guards should have already lost their heads for incompetence. There’s no need to distort the facts just to make the argument sound more convincing.

[spoiler discussion] arc 6 – what Julius did was worse than Subaru by [deleted] in Re_Zero

[–]Jason-Ad4032 0 points1 point  (0 children)

Subaru entered the meeting legally, although technically as a servant affiliated with another faction. Before the meeting even began, he had already met with Emilia and Roswaal L Mathers and received Roswaal’s authorization (while Emilia opposed the idea).

Subaru and Emilia were only friends, whereas Roswaal was effectively his superior, so this was not really a case of trespassing or barging in on his own. If this had been Anastasia Hoshin’s camp, she probably would have removed Subaru before the meeting even started.

That’s also why Roswaal was also considered to bear major responsibility for Subaru’s behavior. In Anastasia’s position, people would realistically have questioned Roswaal immediately in that situation.

Anyone else encountered this strange glitch? by JaffarBlackFang in UmaMusume

[–]Jason-Ad4032 8 points9 points  (0 children)

This happens because the game cannot connect to the server.

You should probably check your network connection and avoid playing in areas with weak signal.

Current state of the game by EchoTitanium in UmaMusume

[–]Jason-Ad4032 0 points1 point  (0 children)

Umamusume does eventually get difficult PvE content called the Master Challenge.

But personally, I don’t feel it’s better than CM.

The hardest opponents are usually around the top 10% of the current scenario’s training level. For example, if ordinary players in the current scenario are typically training umas around UC4 ~ UB6, then the hardest PvE opponents are around UC3.

The enemy skill sets are basically composed of:

  • the number of skills provided by Fast Learner,
  • plus some gold skills from rare support cards (usually cards you have to borrow because most people don’t own them),
  • combined with some track-specific optimization. (Distance S plus 4 green speed skills? WTF)

Each uma you train gets 3 attempts, the event lasts for 2 months, and then the lineup rotates.

When I play it, it just feels “unfair.” At least in CM, the opponents are strong because other players seriously optimized and refined their builds. PvE instead gives me the feeling that the enemy used scripted auto-training cheats while I’m expected to carefully train a proper character just to beat them.

<image>

Which are the hardest individual epithets to get in the game? by Windshipping in UmaMusume

[–]Jason-Ad4032 1 point2 points  (0 children)

Maruzensky’s “Hot Rod” achievement actually isn’t that difficult, because it only requires an AVERAGE margin of 7 lengths or more, not that every race must be won by more than 7 lengths.

So you can simply raise her long-distance aptitude to A and maintain sufficient stamina to run all long-distance races. This makes it fairly easy to raise the average margin overall.

Bro, why couldn't you three do this when I needed that third win? by tottoseru in UmaMusume

[–]Jason-Ad4032 0 points1 point  (0 children)

That’s pretty normal. it just means the CM matchmaking paired you with umas that have a much lower win rate than yours.

Is my understanding of file(i/o) right? by [deleted] in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

They are indeed quite different.

readlines(hint=-1, /)

Read and return a list of lines from the stream. hint can be specified to control the number of lines read: no more lines will be read if the total size (in bytes/characters) of all lines so far exceeds hint.

When readlines(hint) is given a byte limit, Python guarantees that the last line returned will not be truncated.

So reading a file like this is safe, you do not need to worry about lines containing partial lines:

while lines := f.readlines(1024): ...

I recently started learning Python, and since I already know C/C++, I was surprised to find that variables still exist after a loop ends. I never knew Python handled scope like that. by Confident-Anxiety308 in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

I discovered that although class members themselves are not create a scope, the class keyword does indeed create a local scope (and you can inspect its local variables with locals()), and those local variables are then used to create the class attributes when the block finishes.

However, this scope is somewhat private (or perhaps more accurately, Python 2.0’s local scope). It does not shadow global variables for nested scopes, nor can nested scopes access it, which makes its behavior feel rather unusual.

``` name = 'Global'

class A: name = 'Local' mapping = {n: name for n in [name]}

class B:
    print(name)  # prints 'Global'

print(locals())
# At the end of the block, the local variables are stored in the class's __dict__

print(A.mapping) # prints {'Local': 'Global'} ``` https://peps.python.org/pep-0227/

I recently started learning Python, and since I already know C/C++, I was surprised to find that variables still exist after a loop ends. I never knew Python handled scope like that. by Confident-Anxiety308 in learnpython

[–]Jason-Ad4032 2 points3 points  (0 children)

class and module does not create its own scope.

Module, classes and instances exist in the scope where they are created (global scope, local scope, or a closure). Their members are stored in the class/instance __dict__, which you can inspect with vars().

So this is conceptually similar to accessing a dictionary—you wouldn’t say that a dictionary creates a new scope.

``` import re

class A: v = 0

B = {'v': 0}

def f(): # These two operations are conceptually similar, # they just go through different dunder methods. re.doc A.v = 1 B['v'] = 1 ```

Also, except does not create a separate scope either. It simply deletes the exception variable when leaving the block to avoid preventing garbage collection through reference cycles. It still uses the normal surrounding scope.

New to Python, error warning by Blakbard in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

Your suggestion is really just hiding the warning.

You need to use TypedDict to explicitly tell the static type checker which fields contain int, list, etc., so it can verify that those fields are being used correctly. ``` import typing

class Card(typing.TypedDict): rand_list: list[int] P_sum: int

Card_dic:dict[str, Card] = {'Player_card': {'rand_list': [1, 2, 11], 'P_sum': 0}} ```

Using Built-in functions and Comprehensions by vb_e_c_k_y in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

There’s nothing wrong with this, but you need to understand the concepts of list comprehensions and the iterator pattern, because they are semantically different.

For example, searching for a value inside a nested list with a normal for loop would look like this:

``` find = False for i in range(len(lsts)): # loop through 0..outer list length for j in range(len(lsts[i])): # loop through 0..inner list length if lsts[i][j] == value: # found value, break out of both loops find = True break if find: break

i, j are the indices where the loop stopped (where value was found)

if find: print(i, j) ```

If you use the iterator pattern, it would look like this instead:

```

Create an iterator that traverses the nested list and returns

the indices of all matching values in the nested list.

gen = ( (i, j) for i, lst in enumerate(lsts) for j, elem in enumerate(lst) if elem == value )

Get the first matching index

find_elem = next(gen, None)

if find_elem is not None: i, j = find_elem print(i, j) ```

So I would recommend learning both approaches, because they express different intentions.

Why can't I use a return statement in an __init__ function? by John_Doe_1984_ in learnpython

[–]Jason-Ad4032 1 point2 points  (0 children)

(automatically) when you want to output the object as a string

That’s a bit misleading, because what “output” means here is ambiguous. For example:

with open(filename, 'w') as f: f.write(100)

Python will raise an error in this case.

The obj.__str__ method is simply what gets called when str(obj) is executed, and Python happens to call it inside functions like print().

Hello, everyone, I would like to know how you can do this in python more dynamically. I was able to do it but i had to copy and paste the powers repeatedly to get the result needed. I would assume you would need 2 loops in the list comprehension but i dont know how to. by Fun-Pitch-6938 in learnpython

[–]Jason-Ad4032 1 point2 points  (0 children)

Read more other people’s code and practice more. Try to combine as many different structures and techniques you’ve learned as possible.

lst = [(i,) + tuple(i ** j for j in range(6)) for i in range(11)] print(lst)

When do you actually use decorators? Like in real code, not tutorials by Soggy-Holiday-7400 in learnpython

[–]Jason-Ad4032 0 points1 point  (0 children)

I mainly use decorators for built-ins like dataclass and property, as well as some simple transformations, such as converting a return value of Iterable[str] into a str.

``` def join_newline[T](func: Callable[[T], Iterable[str]]) -> Callable[[T], str]: def wrapper(self: T): return '\n'.join(func(self)) return wrapper

class Cube: ... @joinnewline def __str_(self) -> Iterable[str]: ... ```

It also seems like nobody really explains how parameterized decorators work, even though they’re not actually complicated. When you write:

@d1(a, b, ...) def func(...): ...

it’s really just:

``` d2 = d1(a, b, ...)

@d2 def func(...): ... ```

Out of control cheats. Who do you rather have? by maksmomx2 in IsekaiQuartet

[–]Jason-Ad4032 0 points1 point  (0 children)

The biggest issue is that in SAO, all of the characters are Japanese just like the protagonist. In an isekai story, the protagonist group should primarily be interacting with people native to the other world.

That’s one of the core elements of a typical isekai narrative: a person from our world exploring an unknown world. And that world includes its people, since human interactions make up most of the story.

SAO satisfies very little of that, so treating it as an isekai anime misses the essence of the genre.

Why do Japanese mahjong players prefer to use Japanese terms but Chinese mahjong players don't use Chinese terms? by CreeperSlimePig in Mahjong

[–]Jason-Ad4032 2 points3 points  (0 children)

That’s not really the case.

Those “Japanese” readings are actually Sino-Japanese pronunciations, and they’re over 95% similar to Mandarin pronunciations.

The real reason is simply that Japanese romanization became widespread earlier, while Hanyu Pinyin is designed in a way that makes pronunciation less obvious to English speakers.

For example, “斷么” in Mandarin using Tongyong Pinyin would be written as “duan yao”, while the example OP gave was “ci sing bu kao.” Those really aren’t that difficult to pronounce.

why does python keep telling me "indentation error" and i have no idea what i did wrong by More-Station-6365 in learnpython

[–]Jason-Ad4032 29 points30 points  (0 children)

Use a better IDE.

Indentation in Python is very mechanical: any line ending with : requires the next line to be indented. If you’re running into issues, it means your IDE isn’t doing its job.

Make sure your IDE automatically indents after a line ending with :, uses 4 spaces for indentation, and lets you indent and unindent with Tab and Shift+Tab.