#python-discussion
1 messages ยท Page 130 of 1
I'll send the list
.net install tool C/C++ C/C++ Extension Pack C/C++ Themes C# C# Dev kit CMake Tools MATLAB Pylance Python Python Debugger Python Environment
sadly the worst case scenario can be pretty bad tho. i usually have a recipe for my setup and installs. with a decent internet connection, an hr or two is enough to reset a pc to its former glory
did you read the code that they sent
for the packages
A few years ago I accidentally installed a malicious package, and the only reason that I didn't get pwned is that the package wasn't designed to work on Linux
Might as well reset i guess
welp
Once again
I'll transfer my usb files into another laptop then download
Great excuse to try Linux ๐
I know
@orchid vortex
https://pastebin.com/eezQ0sQe
Apparently scypy is effectively malware, it contains this obfuscated cv2.py script, which is probably a stage.
Yeah i checked it its freaking 4k lines
is it obfuscated?
Put it in copilot to check but said nothing awry
Not really, alot of matplot calls
this is quite obviously someone's hobby project that they uploaded to pypi out of confusion
Maybe thats what im thinking
can you point me to why you think it's obfuscated?
truth be told i might have missed something that you saw
yeah, this looks like little Ivan's first package
So should i reset? I'll do a basic reset first then i'll do usb reset tommorow
written with AI
Artificial Ivan
class Window:
def refresh(self) -> None:
y, x = self._calc_start_coords()
self.win.mvwin(y, x)
self.win.refresh()
class Screen:
cur_win: Window | None = None
def start(self) -> None:
while True:
ch = self.stdscr.getch()
if self.cur_win is not None:
self.cur_win.refresh()
self.stdscr.refresh()
why does the window disappear after decreasing terminal size and doesn't appear till next refresh and why does it leave trail when I increase terminal size
this is curses(this is intentional and I don't intend to use anything outside of stdlib)
Maybe it's just a wrapper, neither Gemini can find code execution...
there's no need to scare people for no reason
Nah at first glance I deduced russian characters were used to obfuscate, but it actually seems a legit file at first sight...
false alarm maybe
๐
Gonna do quick offline scan
quick question, does ONNX Runtime support CUDA 13? I'm on Arch Linux and downgrading CUDA is always a mess..
The setup is not malicious, it would not have infected just by installing it
it doesnt look malicious for sure
looks legit at first glance
we can never be sure, but i think it's probably overkill to reset the whole pc
Maybe
if it was me i would monitor for suspicious stuff
but otherwise i wouldnt do anything else
Honestly I checked all I think i could
I checked all the logon attempts which files they were from in event viewer
what is this scypy thing
cue xkcd 1217
Gemini says is a wrapper, as it loads some models like YOLO model and evalute it against images
dont worry about it, we were just investigating if it's malware
you need to stop relying on gemini
this is the fastest way to lose an argument
I'm not trying to win an argument
Thats what I saw the yolo stuff
But if you want I'll move to some other place
sorry i didnt mean we are arguing
i meant if you were debating someone else
and you brought up you got the knowledge from gemini
you will immediately get questioned
DeepSeek says telling people that something is malware based on an LLM response is not good
hi zehata
hello axis
Did you deobfuscate it
fix error can speak russian
Oh
there's nothing to deobfuscate, the code is not obfuscated. It just has comments in Russian
You know, anyone can come to the same conclusion that 4k lines are easily scannable by Gemini.
i think
i kinda just assumed that you were able to read the comments
in this case it's irrelevant what's in this file, because the package doesn't do anything upon installation
how did you tell?
what does a setup py that runs a file look like
Its start up.py is just naming its file
I mean setup
nvm I found the fix
has anyone applied at top tech like google/ meta?
I am curious to know your experience.
be prepared not to hear back for ages
oh
it doesn't mean anything, for better or worse. with a big tech company, you could email them as a check in/follow up but I wouldn't bother. They haven't lost your application, they're just very slow with it
hello
i want to work in top tech, because i feel i am unhirable to local businesses for a full time role
side note. anyone's opinion is welcomed. do you prefer this design:
@webhook.on(PushEvent)
def push(event: PushEvent):
print(event)
or
@webhook.on("push")
def push(event: PushEvent):
print(event)
I prefer the look of the second one but the type/typo safety of first one and I'd appriciate another opinion
idk if they are being dishonest with me to reject me, but everywhere they keep telling me they went with another candidate because they think i will get bored and leave them
i think both looks fine to me
First one
Well, depends, I guess
I prefer first one as I can clearly see the event object I'm attaching too
Guys once i develop my mini math ai how would I approach its gui? Like what code to use to make the gui and app
thank you all!
I think string-based APIs are falling of out favour in Python, now that we have Enum in the stdlib
Im only really familiar with Matlab gui not really anything else, I've done mostly math based coding
What does @ in python do?
@decorator
def func():
...
``` means the same as ```py
def func():
...
func = decorator(func)
ask whatever your doubt is , in #career-advice
Function inside a function?
it's a decorator, it basically wraps a function so you can run code before and after the function is called and even modify the return value etc
oqay
what is a "mini math AI" ? what does it do ?
What it does depends entirely on the decorator. It's commonly used for registering event handlers or adjusting how the function behaves. So if you see some code using the @ syntax, you'll need to read the documentation for decorator.
It is also the matrix multiplication operator (from 3.5)
Ty lemme see
https://peps.python.org/pep-0465/
No implementations of these methods are added to the builtin or standard library types. However, a number of projects have reached consensus on the recommended semantics for these operations; see Intended usage details below for details.
@vital spire here's a great resource:
https://realpython.com/primer-on-python-decorators/
especially the real-world examples
I still think they should have used @* for the operator
* has some meaning in matrices though (conjugate transpose)
For matrix multiplication?
yes. more mnemonic
Ah! I forgot this site existed
Its gonna be my own ai that does graphing calculating with its own lexical system, like an llm but not an llm if you get what I mean
and it standardizes with matlab
I wonder, does the @ operator cause any ambiguity in xonsh
Moreso actually like jarvis
Should have used ๐ฅธ for an operator.
why would i use it over wolframalpha?
I'll obviously do the calculations myself to confirm if they are right but once Its mostly correct and debugged I'll start partially relying on it
I like to make my own stuff and figure things out from scratch
I have to wait for spacy 3.14 support though for the speaking part
Kevin Spacey doesn't support 3.14?
no i dont get what you mean
can you explain what kind of stuff the "AI" will do ? And what do you mean by "AI" exactly ? when i hear "AI" , i correlate it with "prediction"
so are you predicitng the results or are you calculating the result of a mathematical expression? and what kind of math operations will your program do ?
i kinda just assumed they are trying to create a cas
Predicting, graphing, calculating, higher level calculations like vector calculus linear algebra quantum calculations higher calculus
Quantum quantum?
Quantum quantum
Field theory and quantum engineering
Thats pretty much what I want to work on
are you a college student?
what kind of predicting ?
can you give an example of what you will give your AI as input and what it will "predict" ??
all the other stuff like calc, lin alg sounds pretty simple to implement with an existing math library like numpy or smth
and i have no idea what you mean quantum calculations either , from what i know , that is just math , there is nothing "quantum" about the math from what i know , altho i could be wrong.
So an example of "quantum calculations" will also be appreciated
Yes 2nd year university student
are you taking quantum mechanics?
Right now im taking mechatronics engineering, then quantum engineering, then physics
its definately an interesting combination 
what is your degree about ? like after 4 years , you will get Bachlores of ..... ?
Quantum as in entanglement, Heisenberg equations, Schroedinger equations, predicting im not sure yet, extrapolation and interpolation is part of my aim for it
Mechatronics? Is that repair and maintenance of giant robots?
Honours for mechatronics, then quantum possibly master, then contingent on my thesis' hopefully physics phd
i assume you mean heisenberg uncertainty principle
All my thesis' are aimed around quantum computing
Yes yes
Its ambitious but it's what i like
sorry i think you misunderstood, i dont want to learn about terms that are used in quantum physics, i want to see an example of what your AI will do
like an example input and output
ahh mechatronics , cool
pretty nice field
i wish i had that much money for tuition
altho i dont imagine you would be doing much of "quantum" stuff for your current degree ....
definately would be good to do the math part tho , will strengthen your math knowledge
strengthen... is an understatement
My parents only paying for first degree, I have to hope for scholarships and a small university job, like a research assistant
Im working on it, my base is not weak but not strong, stronger than those i know my age, but still a hefty amount to bolster
when i took my first qm course, almost every symbol in the equations in the textbook is completely new to me
even after having taken all the freshman maths
so currently you are not sure what exactly you want to make but you just want to make something ?
thats cool
if you want to learn programming and somehow relate it to math , you can try to write a simple math equation parser to get started with , its a nice exercise
That is great advice
that's what they have now i think?
I have to relearn python fully once more, more than I used to know
im not sure , it sounded a lot with all the calc , lin alg and quantum stuff ๐
im talking about a simple math equation parser
like , user will input (4-5)*6/4 and you will do the math and spit out an answer
they were saying that they want to add things over time
For example I want to give it 3 vectors then evaluate its projection through gram Schmidt
Then plot said projections
what is gram schmidt
Its a procedure to calculate the projection of vectors on a dimensional span
ahhhh finding perpendicular vectors , okok
i had to look it up too haha
if you are new , try to start simple
I want it to find a contour integral and plot it, find convergence and divergence in an infinite series, find the saddle point, find stationary point
making a GUI , drawing plots , is not exactly a beginner project
start with more like , introduction to functions , while loops , if else statments and go from there
These things that I work with, wave functions with Fourier transform
Will my cpp and Matlab knowledge help
I recall them having kinship
if you already know cpp then you should have no problems at all
knowing a prior programming language definately helps
i'd say yes. if you know matlab, you basically already know numpy and jax
I know Java as well but it's uh we don't talk about java
i also came from cpp and matlab to python
And HTML which is pretty useless right now
I came from arduino to small python to html to Matlab to cpp now back to python
Arduino for me was just circuit based and improper coding
Java was its own thing
there are books on numerical differential eqs and numerical mwthods in python, as well as statistical methods for ai in python. all those should help both with math and programming
i think ml-oriented references are pinned in the data science channel, maybe check that out
Perfect
All I truly need now is not getting deterred
all the best!
Or demotivated
numerical mewthods 
My first goal should be force analysis calculations, just simple giving it parameters, complex numbers, matrices eigen vectors, and triple integrals
Why are some questions in coding competitions just troll? ๐ญ I literally saw a replay of AOC Day 12 today. the despair
:0
!cleanban @golden wraith some sort of scam
:incoming_envelope: :ok_hand: applied ban to @golden wraith permanently.
.uwu
nyumewicaw mewthods
Thanks I was waiting for it
@spice hill test
.uwu
@deweted-usew test
get deleted, punk
*deweted
Btw It was a discord invite link probably to his server ๐คฃ
can you give here your code?
None right now
Its just ideas right now came ti get advice
I have some code but it's just basic calculations and a mobius plot
Unrelated to the task just a bit of practice
๐ญ
Iโll be helping you resolve this issue today. Kindly provide your wallet address so we can check what the problem is and advise you on how to fix it. If you have the transaction hash (TX), please provide that as well. If you don't have it, that's fine. If your issue is unrelated to the wallet, please specify what the issue is so we can assist you further. While I check what the problem is, please stay in your ticket so you don't lose it. Thank you!
.
lmao wtf , got greeted with this message upon joining , ๐คฃ
.uwu
dammit
cryptocurrency 
people expect programmers to be this dumb?
Come on, let's share our homemade programs, small ones are fine, and we'll understand together.
#esoteric-python creeps up on us
anyone can get scammed
and upon knowning I don't have crypto I got insta banned ๐คฃ
Having a preconception that you cannot get scammed because you're very smart is very dangerous
I don't have money , hence I can't get scammed
Found a fun python snippet in a blog. Let's play "what does this code do?"
def foo():
try:
return os._exit()
finally:
return False
import os
foo()
raises a SyntaxWarning?
Info is also scammable
It doesn't need to be money
You think you can't get scammed because you are smart
I know I can't get scammed because I have $0 and only a debit card
We are not the same
assume an older python
People get phished all the time, even for a few cents of value that their account provides to spread scam messages
exit the interpreter?
_exit is the raw exit syscall. It shouldn't raise an exception.
does that even exist on Windows?
that's what I thought, but it's sillier
?
Kek its like scamming the one who knows the sytem
!d os._exit
os._exit(n)```
Exit the process with status *n*, without calling cleanup handlers, flushing stdio buffers, etc.
Note
The standard way to exit is [`sys.exit(n)`](https://docs.python.org/3/library/sys.html#sys.exit). `_exit()` should normally only be used in the child process after a [`fork()`](https://docs.python.org/3/library/os.html#os.fork).
oh
so the finally is run
If it takes 49 cents to take my last 50 cents out of my pocket, someone's gonna do it
Best platform to practice pyhton on? or best platforms to search for pyhton projects? to master python
๐คฃ
the terminal platform B)
if you're talking about IDE , it's vs code
- Your PC or laptop (or even your Android phone)
- Github, Gitlab, Codeberg, PyPI
damn
I use Notepad++, that takes 2 seconds to fully start, and I couldn't be happier
notepad people are crazy
yup
no i'm basically asking best softwares or websites on which i can find tasks to practice python and where i can can project ideas
I use (neo)vim which takes <200ms (btw)
it's hard to beat vim motions too for handling text in general
CodeWars is good for small exercises
im gonna keep telling everyone to do aoc
Notepad++ has syntax highlighting and even some documentation for builtins
I'm telling everyone to do Advent(2)
im going and search whats that
thanks i hate it
For Python, that's probably going to be dwarfed by the language server startup time (if you're using one)
agreed I've 50 extensions in vscode and I feel they're too less ๐คฃ
well we're compared it with notepad++
notepad++ doesnt have such weakness (lsp)
do any of you have participated in offline hackathons?
I got banned from that (and later unbanned) because I did a 1st kyu excercise right after creating my account
Imagine there was a extension which has all snippets ever known to man. idk why I've to download seperate for html, css, js , C, Python and maybe someone made a Django snippets extension
snippets?
basically autocomplete for syntax (small blocks of code)
<200ms startup with most plugins lazy-loaded (LSP server not loaded)
<450ms with a slightly large (~3k sloc) Python file loaded + LSP server loaded
not bad
We should all use GNU ed
I once made ed with support for extensions
pyright will definitely take a while to load once your workspace (not just file) goes beyond 10k lines or so
I'm using ty
}``` this is a snippet for c you get this immediately as soon as you write `for`
It's probably usable if you don't use generics a lot
Do people actually find those snippets useful?
probably some did
How far has ty and zuban come ?
I'm just lazy
I like snippets
Actually, I do use the html:5 snippet in VSCode
closing the brackets , etc
ty released their first beta version
not sure about zuban
can't you just... type that?
if I'm calling .split I probably want it called . imagine forgetting () and fixing it
Yo can I ask if participating in hackathons is worth?
I remember when emmet was the thing
this is literally 7 characters
laziness, productivity.
does anyone in here know how to add python to path becaue why are there a whole bunch on ways to download that thing
I'd spend more time moving my cursor around than just for(int i = 0; i < 255; i++) { code(); }
like 200 ways to download python and the advice on youtube is straight garbage
whats the use of termux
Can code
I have been using it since 2024 for editing and download streams
any language?
cuz theres a bunch of ways to download everything
if you're on windows you can check the button add python to path during installation
prolly just get your package manager to do it if youre comfortable with that
I am use python
or else get the installer...
need some views thx
someone in this server sent me a tutorial for installation of python in termux
Guys! how did you improve your logic in Python? I practice but still feel stuck uhh Any advice???
do people like getting banned doing promotion even though server says to not do it?
Pkg python pip-install
thats it?
google is your friend :>)
now we can write codes?
download the installer it's very good
promotion?
but personal experience is better
Jeez ignored..
Well everyone feels this just practice more
you will never get to a point where you like your code
The only answer is practice
ok
well, you might, but then you'll come back some time later and wonder why you ever liked it
well in general its practice too but the difference is that there isnt a problem there
Like what?? I do this every time everyday
yeah pretty much
Then you can run python on termux
what do you practice?
and yeah ill never stop telling people to do #advent-of-code
cuz being able to see what other people came up with is hella fun
๐ญUhh
Be patient (:
yeah the only way to practice your art is to practice your art
If else, loops and def..
Yeah but there isnโt at the level python like shits fucking horrendous like honestly
like the one I did ๐คฃ
try to write less shit code i guess
it started
you can post code here in help channels and ask for reviews
I thought we can only use ffmpeg in termux
no, like, how do you practice them? what problems do you solve?
Yeah this is good tipp
I only see install python and then it just installs
I search it on Google or chatgpt. Or sometimes in leetcode.
oh youre the million if statements guy
any experience python coder here?
are there any python coders in the python server
what's an example of a problem you couldn't understand?
good question
Logic! I'm not getting it at all
no, a specific problem
Okay wait I'll show you
can you tell me how do you learn python so good?
practice?

๐ญ๐ญ
there's no cheat code bro
How to do that?
just practice and time
how to practice??
do projects to solve problems you have or just make things find interesting
write progressively less shit code until its good code
I can suggest some beginner projects if you're looking for ideas
oh......
Bruh
How can I keep learning, and is there any good free course?
do you know python syntax already
Given a string, find the first non-repeating character.
Find the missing number from 1 to N when one number is missing in the list.
Move all zeros in a list to the end while maintaining the order of other elements.
Implement your own min() function logically without using min().
Check if a sentence is a pangram (contains all letters a to z).
Given a matrix, print its elements in spiral order.
Implement binary search logically without built-in functions.
(yesterday chatgpt give me this problems)
well then, go make a discord bot or whatever and you'll learn a lot more than just being stuck in tutorial hell
were you able to solve any of them?
Hello, how or where to start if I still don't quite know the Python syntax? I'm also willing to learn how to use this programming language.
I'm not really in the Python ecosystem, does anyone have suggestions?
ok
Man Icl this discord is so buns
Discord bot!!! I don't to how to make that 
Nah ๐ญ
Yo! New CoreDumped video on the GIL just dropped.
see this pinned message #python-discussion message
not even the min() one?
hell yes
I'm actually watching it right now ๐ญ
actually I'm 13, but wanted to learn python so hardddddddddd
min one is relatively annoying unless you can use sort
Same!
not really
I made my own bot around your age you can do it
i said relatively
I started programming in BASIC at your age.
._. seriously? I could do it in 2 lines
you don't have to sort
And started learning C++
boomer?
I've also
Millennial
i know you dont
I'm 37
think of it from a beginners perspective
I can make a working calculator
๐
you don't need to be that specific ๐ญ
NO.. I jus want a mentor/frnd who can help me get better at Python
๐
Wow, that message looks pretty loaded with useful information. Thanks.
Right on!
married?
read his profile bro

Divorced... but we're civil and basically friends. Plus, we have a son together
well, relative to what? I think it's a perfectly fine exercise in programmatic thinking for a beginner. it's a simple task, and they already know how to solve it instinctively, they just need to be able to turn it into a series of steps.
He's playing XBox right now
relative to some of the rest
what type of bot should I made
for you I would suggest reading a book or a course for learning Python. see the pinned message I linked above.
||the b isn't supposed to be capitalized in Xbox||
Is that what you want to do? What do you want to make?
๐
make a simple high-low game that uses a discord bot as its frontend
Where's the pin message??
well I remember implementing max then realizing max exists , same with maps
like many comprehensions still now are like [int(i) for i in list1]
||let's also go with MacOS and IPhone||
he's trying to avoid copyrightยฉ
|| ๐ญ ||
well, that actually makes a list instead of an iterator
Worth it na?
Discord already has a ton of bots out there. If it isn't a bot for playing mini-games and stuff like that, then I don't know. But apart from Discord bots and videogames, for what else can I use Python?
I guess u also bought Infinite Swril Using Orbs
?
really? to solve the pangram one sanely you need either a dictionary, or if not that then a list where you map character codes to indices (which further needs you to know about ord...)
meanwhile you can create min using one for loop, one variable, and one if condition.
yes , I wouldn't say I completed quests using legitimate methods.
||len(set())||?
Python Crash Course by Eric Matthes is what allowed me to learn the language
think about it from a beginner's perspective
Then again, I was already a programmer when I read that
sets arent high tech tho
I'm not sure how easy it would make things for a beginner.
it's not about how much of a cool oneliner you can make it with all your knowledge of Python, but how hard it would be for a beginner to solve
well if we discount the existence of data structures then yeah min is easiest
Yeah I also Know the inserting Script method ,but in my system the Embeded Backcode dosent open (crt +shift+U ,etc.)
Is it possible to make bot in Phone ๐ฑ
Is it worth reading a book..? istead of only working hard.. can we work smart by using AI to understand Python?? Uhh I. Might be wrong
that's kind of the point, though
if you know what a set is, and can think about how it would be useful here, you're already above the level of thinking needed to implement min
I only know how to write a couple CSS blocks, pretty much it ๐ซ .
android?
hmm okay
yup
I would recommend human-generated resources if you want to learn how to program
clearly using AI isn't working for you, so time to change tracks
then you can maybe jail break and get to the linux layer and then write a python from therem good luck coding with such small screen tho
I have to try this
Exactly ๐ญ๐ญ
๐ญ๐ญ๐ญ
"work smart with AI" doesn't work
I guess you can work smart with AI after you already know how to be smart
Using an LLM could theoretically be smart if it has a lot of training data on something that doesn't have thousands of good comprehensive books/guides written by humans already
That's programming. It's declarative programming but that's still a type of programming. That's a good start!
AI is only good for repetitive tasks , and still you'll have to fix stuff or just keep prompting
Congratulations @azure spear, You're a programmer! ๐
Buy and Ipad/Tablet, release it's "full potential", and attach a keyboard to it and voila, you have a laptop prototype for half the price of a real one. ๐
Fck it. I'm in. Thank you.. @bronze dragon I appreciate your help. GN
I can get a thinkpad on Amazon for 300ish bucks, install Linux, and boom, laptop for less than an iPad
ipad for half the price of a laptop? that's new
CSS feels annoying to me ngl , https://flexboxfroggy.com/ this is an interesting css game ngl
Nah, but like, that's nothing compared to a real programmer. CSS blocks is not a big deal.
CSS Grid really made things easy.
laptops don't have the extreme size and weight constraints of tablets, so it's going to be cheaper for the same performance
(and probably more repairable)
You're right, I should have specified: Android tablets.
everyone told me to use flexbox as it's clearly better and I never learnt grids
You write code in an editor, and a program interprets that code into a result. That's programming
._.
what is standard way of making interface(OOP) in python? or is there better alternative, my usecase is that I have a file which classes which are exposed for normal use and there are 2 other which implements those classes for unix and windows differently
said who? they're niche for sure, but not outdated
I've never heard that they're useful
I saw a talk on grid, and that was a gamechanger back when I started web programming.
???
Cuz i sent my code here and then someone was like "this is the first time i've seen someone use for else unironically"
guys I think the whole of programming might be oudated ngl
rare != outdated
oh ok
for/else is a good thing.
then ima keep usijg em ig
or do I just use a __init__.py which exposes those classes based on the os
I've only had to use it a small handful of times so far
what is the differene between .+ and ..+ in regex?
Bruh, that's like saying "building a dirt block house in Minecraft, makes you a Minecraft player".
but it's cool when you can find an application
..+ will match 2 or more characters. I haven't seen people use that.
Like im p sure you can replace every situation with it by just adding code after the loop
What do you need them for? Can you show the code maybe?
You don't have to create some sort of entity to have polymorphism in python:
class Cat:
def speak(self): print("meow")
class Duck:
def speak(self): print("quack")
def process_animals(animals):
for animal in animals: animal.speak()
process_animals([Cat(), Cat(), Duck()]) # no need to unify Cat and Duck under some interface or base class
..+ is just . followed by .+, it's not special
Imagine doing this:
grid: "left-pane middle-pane right-pane",
"left-pane bottom-pane bottom-pane";
and getting a left pane that goes all the way down the screen, a bottom pane that extends from the right of the left pane going all the way to the right, and above that a middle pane and a right pane
It's not exact code, but that's the idea
And it's awesome
what do you mean by 'match' even david malan used it but idk what it means
I would be super confused if I saw that tbh. I'd think it's some special thing, like how x+? is different from (?:x+)?.
..+ means .{2,}
No more tables, no more flexboxes, document content and layout are completely separated
. matches one character
+ means match the previous thing one or more times
so .+ means "at least one character"
and ..+ means "at least two characters" (the first is required by the first ., and the second by the .+)
Which means that you can use media queries to completely change the layout
maybe use reply so it's easier to track the conversations
no like in english terms
ah i see
The conversation is going too fast to not use them I see
Normally that works fine
The slowmode timer isn't helping
my usecase is something like this:
exposed.py
class IMyClass:
def a(self, x: int, y: str) -> float: pass
def b(self, x: int, z: float) -> float: pass
unix.py
class MyClass(IMyClass):
def a(self, x: int, y: str) -> float: # impl for unix
def b(self, x: int, z: float) -> float: # impl for unix
win32.py
class MyClass(IMyClass):
def a(self, x: int, y: str) -> float: # impl for win32
def b(self, x: int, z: float) -> float: # impl for win32
regex is used to match patterns in strings. abc matches the string abc. there are special symbols like . which means "any character", so something like a.c would match abc, and aac, and axc, and whatever else fits the pattern, you get the idea
ya i get it now thanks
I am now thinking that it would indeed be useless in python
Why's that?
If you want this for typing purposes, use either abc.ABC or typing.Protocol. Note that this class violates typing expectations quite severely:
class IMyClass:
def a(self, x: int, y: str) -> float: pass
def b(self, x: int, z: float) -> float: pass
``` because `a()` and `b()` return `None` while being annotated as returning `float`. A type checker will complain about that
I can just export the classes implementation based on the os via __init__.py
something like:
import os
if os.name=='nt':
from .win32 import *
else:
from .unix import *```
and since my current usecase doesn't require that strictness I think I can go without it
I am already overengineering this thing(intentionally)
Don't shave the yaks
now what is yaks
I think that's fine. (though I would not use *, I'd list things I want imported explicitly)
Just make sure both classes are accessible in some way on any OS. For example, I can mention pathlib.WindowsPath on Linux, even if pathlib.Path does some auto-detection
yeah but I just used it for example... too lazy to type
why does just a plain * not work in regex?
I got it from a book called "The Productive Programmer" which is an excellent book every programmer should read, but that aside, it's basically a perceived dependency chain. "Well, before I can do that I need to do this, and before I do that I need to do this, and before I do that, I need a Yak, but before I can use the Yak, I have to shave it...."
why .*?
i just code and import on the go, if i need something then it's lazily imported by me (humanly)
You endevored to milk the cows and somehow you're shaving a yak instead
what's the difference btw sys.stdin and input?
I think we need a ducky_yak emoji
earthquakeee
star means, zero or more of a thing. You have to specify the thing. in .* the thing is "any single character".
Because you can specify what pattern you want to repeat. For example a* means "a repeated zero or more times".
lol
true though
a bald yak with a baffled look on its face.
ah
input is abstraction for reading from stdin
oh i get it now but how does []* work?
input() is more of a wrapper for sys.stdin
[a-z]* is a composition of two features: "character sets" ([a-z]) and "repeating a pattern 0 or more times" (*)
and stdin has binary support thru .buffer
sys.stdin is a file-like object and input is a function
so why I've been told use sys.stdin.readline() instead of input() , how much is the performance difference?
due to the low-level access, mere tenths of a millisecond
i wouldn't recommend sys.stdin, who recommended it?
so what does it do exactly?
oh i was reading performance improvers for python blog in codeforces that's where it was recommended
ok, that makes no sense at all.
for inputs?
negligible, probably. Note that they do slightly different things (readline doesn't strip the newline character)```pycon
import sys
sys.stdin.readline()
10
'10\n'
input()
10
'10'
(thru pipes)
[a-z]* means "zero or more characters, each of which is a, b, c, ..., z". For example, [a-z]* matches "", "abc", "hello", but not "23" and not "has space"
1 microsecond on my machine $ python -m timeit 'import sys,io;sys.stdin=io.StringIO("abc\n"*100)' 'input()' 100000 loops, best of 5: 3.58 usec per loop $ python -m timeit 'import sys,io;sys.stdin=io.StringIO("abc\n"*100)' 'sys.stdin.readline()' 100000 loops, best of 5: 2.47 usec per loop(3.10.19)
i'm not even sure readline would be faster, since sys.stdin.readline has two attribute lookups.
main difference IMO is that input is built for interactive usage - it supports printing a prompt before taking input
if you need to like read all of stdin for a CLI program, then I would consider messing with sys.stdin
idk what's going on, but that seems like the wrong conclusion
does anyone know cheap vps hoster?
so [a-z]+ c matches the thiings u told with an addition of an exclusion ""
yes
yea i got it from a comment on the blog not the actual blog
I went back to that page and saw
ok thx
Idk why I'm reading 7 year ago posts on performance
competitive programming is a strange place anyway, you might want to optimize things there that would be completely counterproductive in a real software project
that was my vm so I also did on my main machine and its .6 microsecond```
E:\co> python -m timeit 'import sys,io;sys.stdin=io.StringIO("abc\n"*100)' 'input()'
200000 loops, best of 5: 1.31 usec per loop
E:\co> python -m timeit 'import sys,io;sys.stdin=io.StringIO("abc\n"*100)' 'sys.stdin.readline()'
500000 loops, best of 5: 747 nsec per loop
It was a 7 year old blog now even I'm not sure
I hope they don't think my submission is AI ๐คฃ
AI wouldn't even be that dumb to use sys.stdin
Too much stress made me believe rumours
So... check out #ot0-psvmโs-eternal-disapproval in 30 seconds
Ovh, hetzner
idk if I had to read all of stdin I think I would unironically use sys.stdin
its rare cases when you are constrained by microseconds like in competetive programming, for fast IO you want to avoid all abstractions
As opposed to interactive usage
also what does ^$ do in regex , when i look up its use in the documentation I get incomprehensible info
https://docs.python.org/3/library/re.html
`^`
(Caret.) Matches the start of the string, and in MULTILINE mode also matches immediately after each newline.
`$`
Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both โfooโ and โfoobarโ, while the regular expression foo$ matches only โfooโ. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches โfoo2โ normally, but โfoo1โ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.
``` what parts are unclear?
^ is start of a string. $ is end of a string.
nah 2s is the limit , there's nothing written to have fastest solution it's like aoc but harder questions (basically score = no of problems solved and tiebreakers is the total time from the start)
which reminds me
https://docs.python.org/3/library/fileinput.html
I was telling when you would use sys.stdin over input for reading single line
yeah i understand
also you would use it when you want ansi chars to work on older versions of windows without any 3rd party lib...... you would intercept to convert ansi char to win api calls
but how does this prevent one from writing more than one word
yea but y is it needed
~ yes "test line" | head -n 1000000 > test.txt
~ cat test.txt | python3 bench_input.py
input(): Read 1000000 lines in 4.3328 seconds
~ cat test.txt | python3 bench_stdin.py
sys.stdin: Read 1000000 lines in 0.5214 seconds```
wont it work normally?
Write tests and confirm it is needed. They might not be.
#python-discussion message #python-discussion message ยฏ_(ใ)_/ยฏ
i forgot to mention that this is on wsl on a 14yo laptop that's still running windows 10
also what version of python is this
and yeah the difference will be more noticeable on slower machines
in competitive programming, try to use the system-native input/output files (or file descriptors) as much as you can
no, I consider it a genuine question for beginner
It doesn't
๐ญ
What's the context? Are you reading some resource that you have questions about?
3.13.8
did you use .readline or .read
i used sys.stdin as mentioned originally, so pipes
I'm asking what method of sys.stdin you used
he's talking about sys.stdin.read() or sys.stdin.readline()
I expect reading the entire thing in one go will be much faster than reading line-by-line
we were orginally comparing sys.stdin.readline vs input
#!/usr/bin/env python3
import sys
import time
start = time.time()
count = 0
for line in sys.stdin:
count += 1
end = time.time()
print(f"sys.stdin: Read {count} lines in {end - start:.4f} seconds")```
we have perl at home
im lagging omfg
^ and $ are typically used when you're passing a regex to some generic program that always uses re.search or the equivalent.
Or if you want to only conditionally require that something is at the start. For example, apple|banana$|cherry will find apple in I like apples, cherry in I have a cherry in my pocket, and I am a banana. But it will not match I like bananas because banana is not followed by the end of the string
Or if you're using multiline mode (honestly, not a fan of this flag changing how fundamental things behave).
like in the cs50 vid , david made a code that takes an email as an input , and he use ^$ to prevent people to type in sentences like "my email is normal@gmail.com" instead of the usual "normal@gmail.com"
Can you link to the video?
any one of u guys do leetcode? need help in the help sec, thanks
what are the function() -> None text called?
function annotations
type hints
sure https://www.youtube.com/watch?v=hy3sd9MOAcc the part is at 33:00
.... thats not what we were really comparing also, use time.perf_counter when benchmarking
return annotation
having ^...$ forces a match to be the whole string, yeah
!e
There's an annoying caveat
import re
print(re.search(r"^[a-z]*$", "banana\n"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
<re.Match object; span=(0, 6), match='banana'>
which I just learned about
whole string meaning in this case just a word?
it's end of line, yeah
though I think that's a setting
re.MULTILINE?
You're thinking of MULTILINE. The default is that the multiline mode is not used.
outside of MULTILINE, $ matches the end of the string or just before final \n of the string.
That's some hot spaghetti if you ask me.
oh, is that the behavior?
eww
I'm always confused by re.match, which implies a ^, but not a $.
i think you can also use \A...\Z for absolute start and end
not word, the string as a whole (ignoring the \n shenanigans)
it's a prefix match, yeah
because why have obvious names
when an ambiguous ones does the job
it prevents whitespace?
no?
re.search performs "substring search". If the pattern is banana, it will find a match inside apple banana cherry.
If you use ^apple as the pattern, apple will be found. But if you use ^banana as the pattern, it will not be found, because it's not at the start of the string
The correct solution in this case is to use re.fullmatch instead of re.search which the lecturer introduces later in the lecture.
There's also fullmatch, which has strong mysql_real_escape_string energy
I don't mind fullmatch as a name
Oh yeah, re.match is such a misnomer
it's almost never what you want
should've been called prefix_match or something like that
but re.match really should be re.prefixmatch
Yeah
don't be silly and use underscores
right, we use smashedtogethercase in this house
ahh i see so it ignores the rest of the part of the string and only focuses on the part that has the pattern , right?
Here's a nuclear footgun btw: in OpenAPI, the pattern field implies substring search. So if you specify [0-9]+ for a pattern, it means that there's at least one digit somewhere in the string. 99% of the time you have to wrap the whole thing in \A...\Z. No clue why.
Especially dangerous if you do code generation based on OpenAPI.
thx
No problem
Or, I would wrap the whole thing in ^..$, before I knew of the $ spaghetti
fun thing that happened at work, I saw "" being used as a regex in a functional test that does partial regex matching
someone added validation on the provided regex that it should be non-empty
this broke a bunch of automated processes because these tests started erroring out
I can't blame the people adding the validation
any sensible expectation would have a non-empty regex, rather than something that's just always true
the check was also named something like RegexEmpty which does not fill me with confidence
my dislike for how arcane regexes are has come to a middle
see also: SQL syntax; something about the idea of composing a program in terms of what you want instead of how it gets done just fundamentally disagrees with my brain
I think the idea of regexes is great, but there are many problems with the existing implementation[s]
Will AI become advanced enough to replace coders in the future?
maybe
become even more advanced (go even further beyond)
learn how to build AI models?
ok
WTF. I need to check something when I come back from vacation...
While you're frantically updating all your YAMLs, also replace \d with [0-9] ๐
That I already do.
I was able to figure out that a particular service was written in Go because it showed \d as part of a regex but rejected a non-ASCII digit
(random trivia)
what I meant to say is, treat regexes as source code because they are source code
when I write regexes I try to split them into multiple lines with comments
I recently wanted to use re.VERBOSE, but couldn't because the pattern was going to be interpolated later into a larger pattern ๐
(?x:)
https://docs.python.org/3/library/re.html the (?aiLmsux-imsx:...) thing
yes, but that has to be the first thing in the pattern.
Anyone here good at langchain?
oh, maybe with the colon... hmm.
!e
import re
pat = re.compile("foo|bar|(?x:b a n a n a)")
print(pat.fullmatch("banana"))
:white_check_mark: Your 3.14 eval job has completed with return code 0.
<re.Match object; span=(0, 6), match='banana'>
works for me
i didn't try with a colon
can i overwrite another module's function
yes
amazing
hello python
thanks!
because there are no fancy things going on
arent you guys celebrating christman or new year
whoa whats 3.14j
That's another annoying issue with regex sigils. You can swap two characters and break everything. I frequently write ?!< instead of ?<!
amazing but also yikes if you do that for real
i discovered that for named groups, python has to have the python regex exclusive thing
its for my own code
maybe i could make my code better in order to not do this lolz
Iโve seen too many Python crimes
Ok.
the monkey is very exhausted
have mercy
I think monkey-patching for tests is a pretty common thing in Python. Because dependency injection is a pretty foreign concept and many people don't seem to like it
i think im just going to add an option to which stream the error handler module should write to
we had christmas decorations from the 1st to 25th
i celebrated christmas on the 24th, for no reason i have to tell you guys
that is dependency injection, and is often a good idea.
the default is going to be its normal behaviour
yes, classic dependency injection
I just had a fix accepted to typeshed! ๐
I have a fix to typeshed stuck for months ๐ฉ (since oct 1)
duality of open source
Typeshed fixed me.
it is admittedly a bit more complex
"I can fix her"
i have to admit i was surprised when it was merged in under 30 minutes: https://github.com/python/typeshed/pull/15182
maybe because you're a core dev and not some random guy with default github avatar
i feel personally attacked
i hope that is not the reason.
I don't mean that as throwing shade or anything
there are finite maintainer resources and many open PRs
i should change my github avatar
If I had PRs from gvanrossum and bananaenjoyer69000 I'd review Guido's PR first
69420*
why is webp so damn unsupported
where is it unsupported?
i feel like literally everywhere, like now when i tried uploading a new github avatar
WebP is unsupported, what?
it's not as supported as say, PNG or JPG, but webp support has definitely improved
i did it the other way around, importing my github avatar to discord
even the image editor tools on windows dont support webp
what about GDOlivercoding ๐ฅบ
at first I was confused what liver coding is
๐ญ
is that when you have a beer while programming
best youtube video which provide 5 star quality pyhton tutorials like for oops
no!
guys why x//y is a float and not an int? because it should always be an int then why is it treated as a float?
what is x? what is y?
I can understand about x/y that it sometimes returns a non integer hence it is assumed as a float
show code
x//y is always a integral value, but if x or y is a float, the answer is a float.
Then it's always an integer.
// will only be a float when either side is a float.

but still I'm confused shouldn't it still always be a int?
And this is ALWAYS a float. Even when ints are perfectly divisible. Like 2/1 gives 2.0
back in the day int / int was floordiv
yes, python 3 changed that.
future division
// is floordiv, not "intdiv"
And why is that? When / is always an int, why would another form of division (//) be a float?
yeah ik , I was just annoyed I use //1 to change it to int and it didn't work
that's what int(x) is for
Uh, just int(stuff here)... Or math.floor or math.ceil
passing a variable into a function and then accessing it after gives me rust vibes
I'm saying if 2.5//integer will always ne integer
&mut ahh
Command "mut" is not found
?
yeah ik I was saying it felt weird because I assumed floordiv always give integer
damn, Python functions have arguments, that's just like rust
!d float.is_integer only I this form it "is" integer, but not as type
float.is_integer()```
Return `True` if the float instance is finite with integral value, and `False` otherwise:
```py
>>> (-2.0).is_integer()
True
>>> (3.2).is_integer()
False
generally, if one of the operands is a float, then the result is a float
is that a hat you are wearing?
that's called an "out parameter" and admittedly it's not very common in Python
yes a toque/beanie
learnt something new today
yeah, thats because you have to edit its internal state rather than itself
guys can u tell me how is my code as an beginer
num1=int(input("EnterFirstNumber:"))
num2=int(input("EnterSecondNumber:"))
oper=(input("EnterOperator:"))
if oper=="+":
res=num1+num2
print(f"res={res}")
elif oper=="-":
res=num1-num2
print(f"res={res}")
elif oper=="":
res=num1num2
print(f"res={res}")
elif oper=="/":
res=num1/num2
print(f"res={res}")
elif oper=="%":
res=num1%num2
print(f"res={res}")
!code
its ok
ight
could be better
this is the default code every beginner learns as their first big code๐ฅฐ
hm
Still water + adrenaline + noradrenaline + hawk tuah + anger issues + balkan parents + english or Spanish + german stare + Balkan rage + jonkler laugh + phonk +Belgian edging + Baltic farting + bulgarian scratching + aggressive slovakian jelqing + polish footjob + indian respect moment those who know + Opponent uses Jamaican Smile + Russian Frown + Finnish wave + Icelandic blink + Thai grin + Hungarian punch + Swiss climb + Argentinian flex + Chilean dance + Peruvian squat + Kenyan grin + Jamaican jump + Russian slide + Filipino stretch + Balkan climb + Greek dash + Egyptian tilt + Vietnamese sit + American hop + Pakistani stomp + Hungarian march + Italian march + Japanese snap + German slide + Irish dash + Brazilian whistle + Turkish flick + French leap + Korean twist + Canadian clap + Indian bow + Nigerian stare + Italian kick + Chinese lean + Scottish grin + Mexican swing + Swedish dash + Moroccan leap + Ukrainian stretch + Danish whistle + Finnish kick + Icelandic jump + Thai clap + Hungarian dash + Swiss stretch + Argentinian whistle + Chilean wink + Peruvian hop + Kenyan sprint + Jamaican whistle + Russian clap + Filipino nod + Balkan bend + Greek run + Egyptian squat + Vietnamese smile + American point + Pakistani twist + Japanese wink + German bow + Irish hop + Brazilian cheer + Turkish skip + French flex
what?
those who know
okay? let's write messages about python that anyone in this channel can engage with
talking about it does math have the upper floor function?
like which rounds up regardless
lower floor + 1 doesn't work on integers and I'm feeling pretty lazy rn
are you a beginner?
how can i python that message into my website
yh
so you want 4.0 to go to 5.0?
math.ceil
math.ceil?
gonna start calling the ceiling the "upper floor" now
"upper floor" is an oxymoron
ty , Idk why I couldn't find it , might be too tired to search documentation
no it isn't
in a building with two stories, the upper floor would be the 2nd story
except in britain, it would be the 1st story
britain isn't real
no, it's the US state that purportedly contains Seattle that isn't real.
Excuse me, I'm trying to find a way to read from a public Google document. Is there a simple way to do that? Or do I have to work with service accounts and such?
Is it a bad idea to talk about goals..
i heard that talking about your goals make it difficult to achieve
I think google docs has an API
why do americans call the ground floor the first floor anyways
why don't british people do that? why is one or the other the default assumption?
well I was taught GIF and LIF , greatest integer function (floor) or lowest integer function
I was describing the other function because I didn't knew it's exact name
@woeful lark jsi v rbx ptk_dan61
Youโre telling me in your country itโs not? ๐ญ
not an American btw
I think I found the API guide, but it seems quite involved, including creating a quickstart application. Is there any other way?
what were you stating then
at least in the US, floor numbering starts at 1. In Britain, and possibly other places, it starts at Ground, and then 1. Neither one is inherently more natural than the other.
My all doubts are solved by the GEMINI OR CHATGPT.
Does anyone feel the need to ask for doubts in python discussion channel?
i was referencing the latter
right, and you asked why americans "call the ground floor the first floor", which presupposes that one is the natural way to do it.
yes
that doesn't make sense tbh
and I'm saying, neither one is inherently more natural. it's just two different systems.
My father told me...do it then speak about it
do indexes start at 0 /j
Unlike LLMs, humans have a less likely chance to spontaneously hallucinate.
in programming they do. normies don't care about that.
why are you calling it hallucinate..
It is very helpful..and saves a lot of time.
well i dont feel like its necessary to discuss which one is more natural but my personal opinion is that the latter is more rational
Good thing about humans is Cunningham's law - if you're wrong, two people will spawn and tell you.
LLMs don't want to be wrong, so they'll spout nonsense in the hope of being right.
"hallucinate" is when an LLM behaves as though something is true, but it is not. it is actually the technical term for that.
AI is like an overconfident intern. Its output is often wrong in subtle ways
I trust this place more for subtle and obscure topics
i trust any human more than AI because they're not as overconfident and i can prove them wrong
AI just doesn't act like a human and i kinda desire the need to talk to one
i mean there is a feedback thread always available if it saying something wrong.
but 95% of time it gives the correct results
specially gemini 3 pro
For example, I just asked DeepSeek if re.searching a string with the pattern ^[0-9]+$ will ensure that the string only contains ASCII digits. It said yes, but it's wrong, as we recently learned in this channel by reading the documentation.
but in last version..
i got slightly wrong results of maths questions...but now they claim to be a PHD level LLM
many people like talking here. You don't have to if you don't want to.
my favourite is observing how normie-semi normies think about programming
hi ned,
i want to talk...it creates connections in mind and world
you are not a wizard then
https://discord.com/channels/267624335836053506/1454518059636232477 if anyone can help thanks in advance
And it's not some obscure topic you can only find about by reading old mailing lists, it's literally written in the official documentation. One would hope that these edge cases are exactly what they'd be good at
ok, then why ask if anyone needs to ask questions here? People ask questions. It's good.
we stopped using bicycles for a long distances travel.and started using car or train...we evolve...no?
i just don't understand the point of your question. People ask questions here because they like talking to people. it builds connections, as you say.
I trust ned more than a robot.
And ned trust robot ๐ค
146 aqi here
yes its true,
But i think human to human talk for a doubt is for high achievers
many new learners here like talking to people. You like talking to people, why would you wonder why other people like talking to people?
@quartz fulcrum learning how to ask good questions of other people is a skill worth developing, it'll pay big dividends
not to sidetrack too much, but i do use bicycles for long distance travel
What are you talking about?
Here's the prompt btw:
<prompt>
In Python, can this function return True if the string contains something other than ASCII digits?
def is_digits(s: str) -> bool:
return re.search("^[0-9]+$", s) is not None
</prompt>
I wonder what other LLMs answer to this. DeepSeek is not nearly as advanced as many other models, I think
And another human forcing you to explain yourself leads to revelations.
oh
wait... what?
can you explain
Chatgpt: ```
Conclusion:
No, the function cannot return True if the string contains anything other than ASCII digits.
Edit: full output https://paste.pythondiscord.com/MKGQ
is_digits("123\n") is True
Whats the correct answer there?
is it wrong? can it return True for things that aren't ascii characters?
๐
DeepSeek and ChatGPT say that it can never return True
https://docs.python.org/3/library/re.html
$
Matches the end of the string or just before the newline at the end of the string, and in MULTILINE mode also matches before a newline. foo matches both โfooโ and โfoobarโ, while the regular expression foo$ matches only โfooโ. More interestingly, searching for foo.$ in 'foo1\nfoo2\n' matches โfoo2โ normally, but โfoo1โ in MULTILINE mode; searching for a single $ in 'foo\n' will find two (empty) matches: one just before the newline, and one at the end of the string.
This is why in reality,is_digit("123\n")is True.
and im guessing "123\nืฉืืื" too?
No, that doesn't match, because the \n is not at the end
Guys I have problem in my wife
wife
๐ญ ๐ญ
Uhhhh? huh?
Yes
What's the problem?
Can you talk with me in private
Have you tried turning her off and on again?
I do that 100 Tim
Oo la la
!warn 1432496795858112566 This is "Python Discussion". Stick to the topic.
:incoming_envelope: :ok_hand: applied warning to @pulsar dragon.
.topic shall be summoned
Suggest more topics here!
all the camelCase function names strewn about here and there
Time for a pep? Btw, why?
are there any outside logging?
Bytecode compilation optimizations, i.e. in lining of functions.
Do you know what the difference between re.match and re.fullmatch is?
Ok Print ("hello world")
It's obviously never going to change, no PEP is needed to figure that out. But yeah.
threading is the other example
Not familiar with regex really, but I'd assume partial match vs full match based on the names
unittest.TestCase
re.match("[0-9]+", "123abc") will match "123"
Every language needs a few inconsistencies. Feels wrong without them.
I would definitely make it so that you can pass an entire function body as a lambda.
xml is the other big one I think
And all of the Java-inspired packages, basically.
Oh I see, I think that makes sense
Edit; oh it only matches from the start of the string. It does not search the whole string?
it doesn't really
my_function = lambda (a, b, c):
a.foo = "bar"
b.foo = "baa"
c.foo = "baz"
๐
and tKinter iirc
alright im learning dictionaries today
they just seem like a bunch of variables stored in one place that you can refer to at will
why would you need this
instead of just using variables
think about when you would need to do a switch/case statement
perhaps, I could see the current def become a "function expression".
Dictionaries are a key part of python with a lot of value.
whats a case statement?
would you want a list instead of having variables, a1, a2, a3, a4, a5?
Oh thanks I reading the rules
i guess its better for organizing
it just feels less important than other features
dictionaries are perhaps the most important data structure
not only is it more organized, you can edit and access it dynamically, whereas you can't with variables. for example, you could read a dictionary from a file, and look up values in it. if you try to do that with just variables, you'll have a tough time
lua manages with essentially just dictionaries as its most complex data structure
can anyone tell me what field required learning all data structures in python?
match bar:
case "blah":
foo = "some value"
case "foo":
foo = "some other value"
case "bar":
foo = "some other other value"
or
foo = bar[thing] # returns the value you want
Random question, do you ever make a dictionary with duplicate items under different keys? Like if I have a bunch of user objects with IDs and emails and I want quick lookup based on either would it be a thing to put it in under both?
i would do separate dicts. or perhaps key it with a frozenset
you would create objects that have the subdata, and then key the dictionary to how you want to look it up
Fair that sounds cleaner
not sure what i'm looking at but i'll probably learn this lateer
key with frozenset helps you why?
codeWordsForChristmasMission = {
"THE RED CLAW" : "Santa Claus",
"LITTLE LAMB" : "Present Delta",
"GRAZE VICTIM" : "Christmas Tree"
}
print(codeWordsForChristmasMission.get("GRAZE VICTIM"))
um...
alr so thats a dictionary
Either way. A single dictionary cam make sense since you want a single lookup. But two dictionaries can also make sense if you want to track whether the match was made by id or email.
Also there is a merged dict that does this for you.. i forget the exact name
Basically it allows you to associate one thing to another thing and look it up by the one thing.
T.W// Christmas words (incase grinch sees this message)
how does bot reply
And by the way, that thing can also be a function
so a dictionary
Ohh interesting
If i try to get a key that doesnt exist instead of returning an error it just says "None"
btw what is "returning" exactly like i dont get the whole .pop thing
hm saying ```py
print(codeWordsForChristmasMission.pop("LITTLE LAMB"))
just returns the value associated with little lamb
OHhhhhhhhhhhhhh
it removes it but after telling u what you're removing
aha that makes sense now
AHA AND NOW SAYING THE SAME STATEMENT AFTER RETURNS AN ERROR
def add(a, b):
return a + b
def sub(a, b):
return a - b
def mul(a, b):
return a * b
def div(a, b):
return a / b
operators = {
"add" : add,
"sub" : sub,
"mul" : mul,
"div" : div
}
operation = input("Pick an operation [add, sub, mul, div]: ")
a = float(input("Pick a value: "))
b = float(input("Pick another value: "))
print(f"Your result is: {operators[operation](a, b)}")
whats that useful for??
Ahahhhhhhh
couldnt you also define the functions within the dictionary?
or is that just too messy innit
they would have to be lambdas
returning is what the function, once it's finished, is subbed out for, so like the value the function call evaluates to.
def add_five(a):
return a + 5
value = float(input("Put in a numeric value: "))
print(f"the result after adding five is {add_five(value)}")
Python doesn't have inline functions
!e
import operator
operators = operator.__dict__
result = operators['add'](1, 2)
print(result)
:white_check_mark: Your 3.14 eval job has completed with return code 0.
3
ahaaaaaaaaaaa
You can use a lambda though
you can still index an item in a dictionary using [] ok good to know
