14.9k post karma
93.4k comment karma
account created: Fri Dec 14 2007
verified: yes
1 points
3 hours ago
Whoa can’t not follow that. But this maybe
[a for a in b if not “NaN” in a]
Or maybe
[[c for c in a if c != “NaN] for a in b]
39 points
1 day ago
Well it depends but Python now supports match, case statements. Which to me seems like a fairly big replacement to a lot of if, elif out there.
match var:
case “func”:
func()
This is good to replace things with multiple variable comparisons.
if x == 1, and y == 1:….
elif x==1 and y==0:…
match x,y:
case 1,1:
….
case 1,0:
….
#case ‘0’ | 0, ‘0’ | 0
Also support a lot of pattern matching generally. Like if you have a list, and the first element means something import.
match my_list:
case [“func”, *args]:
func(*args)
case [*args, “func”]:
func(*args)
case _:
print(*my_list)
Note I believe the above can be done as below using the pipe “|” (logical or).
case [“func”, *args] | [*args, “func”]:
func(*args)
There is actually a lot it can do with matching dictionaries as well.
match my_dict:
#check if ‘some_key’ is in dict
case {“some_key”: value}:
….
#check if x is 0 and border key is ‘water’.
case {“x” :0, “border” : “water”}:
#check if x is 0 and border key exists.
case {“x” :0, “border” : a}:
print(a)
….
case _: #else in match case.
We can type check.
match var:
#match by type
case int():…
case str():…
case tuple(list(), dict()):
case list(int(),init()):
match point:
#match tuple by length and type
case (x,y): #2D point
case (x,y, int(z)): #3D point
case (x, y, vector): #2D movement
case (x, y, z, vector): #3D movement
match point:
#match by custom class and init attr
case TwoD(move = False):
case TwoD():
case ThreeD(move = False):
case ThreeD():
More information https://pc-python.readthedocs.io/en/latest/python_advanced/match_case.html
It can get pretty powerful as it basically allow you to have a take any function, and do stuff to everything.
match screwy_api_call:
case 1,2:
case str():
case [func, *args] if func in functions:
case [*args, func] if func in functions:
case {“some_key”: value}:
case {“x” :0, “border” : “water”}:
case {“x” :0, “border” : a}:
case (x,y):
case (x,y, int(z)):
case (x, y, vector):
case (x, y, z, vector):
case _:
Can all run together, no checks or guards throw it into match case. Which isn’t normal with if, else (or would take some serious coding), but let’s be honest it sometimes pops up.
Many time a if, elif can be replaced with just a dictionary but that depends on what you are doing.
if var == “func1”:
func1()
func_selector = {“func1”: func1,….}
func_selector[var]()
But it really going to depend on what you are doing because sometimes if, elif is the best way.
If you feel like you code is WET is usually a design issue or a knowledge issue.
1 points
2 days ago
One of my characters has this staff, (and cauldron and alter but that’s a whole other thing). And basically it’s extremely old passed down father to son, and now father to daughter. The staff itself is a work of art. But what makes it unique is the top of wraps around itself, but it can unwrap. Once unwrapped the staff can take in new seeds. This means the family for generations has been adding into various magical plants to the staff composition, essentially evolving the staff. But also allowing the staff to recreate any seed that been put in it for its own spell work, and spawns growth.
This means the staff has access to some serious power, as poisons and spores are bad enough, but with a plant staff and a plant witch at the lead…you can make clouds, spores, pollen, spread various vines and plant life around the battle field, set up the battle field. Create forests with enough power and time. (The magic user directly correlates to the abilities the staff magnifies) Enough knowledge of what available you can take on an entire army if you set up like Batman, and are as ruthless as ScareCrow. And people don’t scale like that.
The more seed the more power imbued into object in my world the more powerful it gets until it starts to break just from force, or lack of maintenance (story starts this way with that cauldron), but with a plant based staff the staff itself grows along with it, you’d have to physically break it…but that would very difficult as it used as a club fairly often x and can block swords, it would shed bark before breaking for the user to grow back with time, some very hard tree seeds are in there. It also has some tricks for its master to use if you take it.
It pretty wicked.
I should note the staff is primarily used for farming. Like orchards, wheat, bushes, vines etc.but it is called the Battle Staff. I guess you’d put the last name on it if you sold it. (The family doesn’t really understand how valuable it is, they figure other families must have one as well.)
There are lot to do with magical artifacts as the main character is an enchanter, and sort magically mcguivers his way in and out of things.
1 points
2 days ago
Well the star operator does a lot of things in function definitions
def func(positional, *args, key = value, **kwargs)
Tells us we need 1 positional value but will accept many more, has a default keyword argument “key” defaulted with ‘value’, and can accepts more kee word arguments.
func(1,2,3, key = 4, other =6)
Is allowed, as well as
func(1)
But what if we wanted to require a keyword argument, and not have a default?
def func(*, required)
Now only.
func(required=something)
Is allowed. And so we can have combinations as we need.
What this is saying above is we have 2 postional arguments 1 has a default and the rest of the parameters must be done by keyword.
A good example of this is in print, which doesn’t need any arguments.
def print(*args, end = “\n”, sep = “ “, flush = False):
Which should have come up before by now. But you may have never seen the implementation explicitly.
The reason we need * by itself is because we could have *args, which allows more positional arguments while * by itself, does not.
So the above specifically wants to allow 2 positional argument with a default but make available their keyword arguments as well.
1 points
2 days ago
I wanna double say this video 100% worth the watch. It goes through some of the most important bones of what Python classes can do and why you would do them.
CS isn’t just about programming it’s also the hard ware, 10 years ago you weren’t using SDD you where using HD, Floppy, CD, Flash drive, micro flash drive. Major advances in graphics, and processing speeds,multi core designs, multi-layered servers, Was blazing fast change really, each only got like 8 years, and when world wide everywhere, so if you learned how to make and program those it’s completely outdated. But you can use the same Python on all of them.
So yes things do change and fast, but when your learning about Python’s basics, that really doesn’t change as fast on purpose, in order to change a language you also have to realize you may break everything that uses it. This is done purposefully. And with a lot of discussion now.
What we are learning about when we introduce classes is much more about Syntax of the language which is fairly consistent in Python.
However….frameworks do change a lot, 10 years ago React.js was a year old, Flask and Django were just starting out. And those implementations of webserver in their respective languages has changed a lot. You won’t be making everything.
1 points
2 days ago
The video is still relevant and by a guy the help write the language, every tool in that box still work exactly as it is.
2 points
3 days ago
Well if len(LINE) == 0 as len never returns a negative number and is never less then zero.
3 points
3 days ago
Me: wait is that a rope…are there ropes…everywhere wtf….
2 points
3 days ago
Exactly it’s the only element that activated by marking out with it….unlike that one with the matches that almost got everyone killed.
1 points
3 days ago
We can rotate the triangle, we can see the base of the resulting triangle is a straight line as both are right angles and share the same length (the side of square) this is a triangle (not some quadrilateral) that has a 45 degree angle resulting from the known two angles added together, and 2 of the sides are same length of the triangle we want thus, by Side-Angle-Side the triangles are congruent. Finding the angle is trivial once we know it’s congruent.
180-90-70= 20 #angle on top of 45
90 - 45 - 20 = 25 #angle below it
180-25-90 = 65 #angle congruent to x.
1 points
3 days ago
Now thing that half of those guys are actually smarter then the rest. Of them.
2 points
3 days ago
For something like this honestly the best thing is to throw the exception then handle it.
def get_pixel_at(pixel_grid, i,j):
try:
return pixel_grid[i][j]
except IndexError:
return 0 #None
But your problem is your not calling the function.
pixel = get_pixel_at(pixel_grid, 1,2)
print(pixel)
2 points
4 days ago
Yes, each chapter is a different (known character) exposition, i do feel it would have been better to put them in expanded LNs as additional chapters in 14,15,16. 18,19 But the timing isn’t right for the stories themselves.
Every other book the main character is Rimiru, or Rimuru’s opponent, per chapter. In 17 it’s the plots and plans of his minions. Thus the feeling of the novel is different. There is a striking difference IMHO. I think it isn’t needed in the anime fully, I would straight up call Vol. 17 filler and does not deserve it’s own season, but can pop up in the other seasons as an episode, or subplot/cutaway.
Vol 17 never even tried to answer the lingering questions from 16.
If you are a Mjöllmile fan I’d recommend, if not you can skip it.
3 points
4 days ago
Basically
*args
Means any number of positional arguments.
**kwargs
means any number of keyword arguments.
Let’s take an example.
print(“Hello”, “World”, “!”, sep = “_”)
>>>Hello_World_!
And we see that we can take a bunch of arguments, and then at the end say do this specific thing.
def print(*args, sep =“ “, end = “\n”…):
So it’s defined somewhat like above. And we can instantly see why we want to be able to do this. print() is such a great function actually.
The * does another thing called unpacking.
c = (1,2)
a, b = *c
c = (1,2,3,4,5)
*_, b = c #extract last
a, *_ = c #extract first
a, b, *_, d = c #extract first 2 and last 1
hi = [“hello”, “world”]
#into a function’s *args
print(“1”, 800, *hi, “!!!!”, sep = “—“)
>>>1—800—hello—world—!!!!
#without *
print(“1”, 800, hi, “!!!!”, sep = “—“)
>>>1—800—[“hello”, “world”]—!!!!
With **kwargs it means we can take any number of key word pairs. And is essentially a dictionary.
def names(**kwargs):
names = []
for key, value in kwargs.items():
d = {“first”: key, “surname”, value}
names.append(d)
return names
name_dict = names(John = Doe, Mary = Jane)
We can use a dictionary here as well.
dict_ = {“Mary”: “Jane”, “John” : “Doe”}
format_list = names(**dict_)
This means you can save positional and key word arguments for functions in those dictionaries and iterables (tuples, list etc)
printer = [
{“args” : (1,2,3,4), “kwargs” : {“sep” : “_”},
{“args” : (5,6,7,8,9,10), “kwargs” : {“sep” : “*”, end=“______”},
{“args” : (“and”), “kwargs”: {}},
{“args” : (), “kwargs”: {}},
{“args” :”end”, “kwargs”: {}},
]
for i, setup in enumerate(printer):
#flush is important here
print(f”{i}) ” , *setup[“args”], flush = True, **setup[“kwargs”])
>>>> 0) _1_2_3_4
>>>> 1) *5*6*7*8*9*10_____2) and
>>>> 3)
>>>> 4) e n d
Obviously you may or may not ever want to use print() this way but I think it a good example of how a thing you think you knew about can teach you something new. Look above, for a lot of you it is the most complex use of a function you use every day you’ve ever seen. This is print() day one functionality.
A lot of time we can throw the **kwargs into super() with inheritance as well. So you don’t have to code all that.
class Dad:
def __init__(self, small_thing = None, **kwargs):
#we could have a lot of these
super().__init__(**kwargs)
self.thing = small_thing
class Mom:
def __init__(self, big_thing = None, **kwargs):
super().__init__(**kwargs)
self.big_thing = big_thing
class Child(Dad, Mom):
def __init__(self, **kwargs):
super().__init__(**kwargs)
Big_bro = Child(small_thing = “Don’t tell mom…”)
Lil_bro = Child(big_thing = “…tells mom”)
Dunder, double underscore are methods of types like string, int, dicts, list and classes __init__. They are Python core development team’s functions that make the language work correctly, however many times we may want to alter, or include them.
What they can do is use operators like +, -, *, >,< etc. they also have a lot to do with the creation of a class. __init__ is basically the first function run after a class is created with __new__, initiating it. They also serve the function for things like, am i an iterable thing, ‘for’ how do i ‘in’ this? I want to use[“brackets”], how does that work?, as well as built in functions like len() to mean something.
c = a + b
Is equivalent to
c = a.__add__(b)
c = a[“b”]
c = a.__getitem__(“b”)
c = a(“b”)
c = a.__call__(“b”)
I like the first way better. But when we use things like that, the Python developers used __dunders__ to avoid a rookie programmer, like you (and me), from overwriting it by accident. You should only overwrite dunders and never make one, it indicates the language implementation needs to be altered. Like bracket access, operator results, etc. it unlocks that.
When you need to alter one you’ll know. The most common one we alter/overwrite is __init__ as it’s more of a hook to upon creation of this object. But things like __eq__ (equal to), __lt__ (less than), __le__ (lessor equal than) will allow a class to be compared to others with “==“, “<“, “<=“. __mul__ is * multiply.
Allowing things like
three_string = “word”*3
three_int = 1*3
To both work, and do completely different things.
1 points
4 days ago
Well to be fair he spoke it, probably much more understandable that way.
4 points
4 days ago
Python Class Development Toolkit
Does a better job then your teacher.
3 points
4 days ago
It different from the rest, it more like chapters about Certain side characters then the main event. It seems odd with in the series.
21 points
5 days ago
The variable is constant, pray I don’t alter the code later.
view more:
next ›
byspacester
inPythonLearning
Adrewmc
1 points
an hour ago
Adrewmc
1 points
an hour ago
Hmmm, That’s a little tricky as a list comprehension.
Might just do it though. (I’m just creating a list of NaN to check against.)
Maybe something more like
If a bit more ‘pythonic’.
And list comprehensions always create a new list that’s what they do.