#voice-chat-text-0
1 messages Β· Page 175 of 1
I would love to be able to use linux But it just isn't compatible with my company's ecosystem. Although Powershell does support a lot of commands And more all the time And I absolutely love WSL
Sad
nooooo
thank god not. we are very Microsoft based
I did try but using one drive on Linux is basically asking for trouble
Canβt talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
π
@somber heath I'm yet to hit the 50 message target.
I must be close
i'll use the 12 to describe the project I'm doing,
How can I know how many messages I have sent?
Ukraine currently cannot be accessed by plane
(I'm on desktop app)
Search yourself, perhaps.
Someone has created a handy website with guides on how to access ukraine via various land borders. it's agreat and comprehensive guide but it's unforunateley not in english
there are 42 results, so you've sent 42 messages
Thank you. (43)
I would suggest a download directory and A long term download directory, the script would empty the downloads directory
can't beat @somber heath . Talking is definitely faster than typing
it's 7.40 am here
my bad 9.40. my computer is on home time
Sorry did someone mention my name I wasn't listening
Am spy
@night ruin π
Hi, I don't have permissions to talk
!voice
Canβt talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
Ahh, all i clear
@merry cobalt π
People are bouncing in and out
n(n+1)/2 is the sum of integers from 1 to n.
It is also the binomial coefficients for 2 within n, i.e. the number of ways to pick 2 elements from a set of n elements.
n(n-1)/2 is the sum in integers from 1 to n excluded (so from 1 to n-1). It is the number of links you can make between n point, so it is also the number of glass sounds you will hear if n persons are cheering.
the proof is pretty simple also
binomial coefficients
it is if you are counting things with math ^_^
It is one of the most basic combinatorial tools
binomial coefficients appear in a lot of areas
nice
haha yeah that is sad. Also why i'm doing both CS and math bachelors.
yes
my mic is not on
Ok
@sand ermine I said the web browser version of Discord behaves worse than the desktop client version of Discord.
@sand ermine Your audio activation sensitivity is also a bit high.
@wispy rover π
@dull nexus π
hi
Hey : )
I wanna talk in voice chat but I need to send messages still
I really need help with a beginner problem π
bruh
just like this
Thatβs ok homie just keep going
yes yes : )
its good, have family visiting
Omg sound soo cool what you cooking
has anyone noticed anything? @somber heath
its like really beginner lmao
FINALLY got the stupid headphones away from the origami wires
I will send you the code via message if thats ok
i have the unfortunate obligation of attendings someones funeral today π¦
@somber heath you have a good evening? or having rather? i just woke a little while ago.
@whole bear baby...
oop
I send you a friend request by the way opal
Not exactly, but that's nothing new.
are you aware of the happenings out in Africa?
Looks like the standard bloodshed and political corruption.
i want to be able to talk lmao
yeah but its a bit more of issue then most people would assume. since, they are like the top of the food chain when it come to politics basically the fuse has been lit in my opionion.
Isn't Wagner sniffing around there, too?
im afraind i don't exactly know who is wagner. im assumping politician?
hey @somber heath was it ok if i messaged you that code?
its a russian mercinary group
a paramilitary group hired by russia
!code Send it in here.
@somber heath the sigh of relief when china said " uh, no, we don't like" to russia.
Indeed. So much that they ramped up supply to them.
A very strong message of disapproval, indeed.
Saying one thing, doing another.
rotate(90, rectangle())
R
E
C
T
N
G
L
E
Shocker.
sneaky
weapons of mass distraction
Mostly logistics hardware, I believe.
my file isnt uploading?
Edit it.
awesome
are you going to be running it?
Hello
Canadians are practically North American Brits
or french guys π
@echo garden Sorry for your loss
@turbid sandal hello
what's the story
@faint raven https://python.swaroopch.com/
@cerulean ridge
@somber heath grippy socks like this?
these are called barefoot shoes
Function GetFolderPath() As String
Dim FileDialog As Object
Dim SelectedFolder As String
' Create a FileDialog object as a Folder Picker dialog
Set FileDialog = Application.FileDialog(msoFileDialogFolderPicker)
' Show the dialog and capture the user's selection
If FileDialog.Show = -1 Then
' Get the selected folder path
SelectedFolder = FileDialog.SelectedItems(1)
GetFolderPath = SelectedFolder
Else
' User Canceled the dialog
GetFolderPath = ""
' Clean up
Set FileDialog = Nothing
End Function
the fudge
Ayep
A portmanteau of aye and yep. This is in effect a double-yes, which is 100% more effective than a single.
huh
yeye
!e
from typing import Callable, TypeAlias
def is_longer_than_10(s: str) -> bool:
return len(s) > 10
def is_cool(s: str) -> bool:
return "cool" in s
Rule: TypeAlias = Callable[[str], bool]
DEFAULT_RULES: frozenset[Rule] = frozenset({
is_longer_than_10,
str.isalpha,
str.isascii,
})
items: list[str] = []
def add(item: str, rules: frozenset[Rule] = DEFAULT_RULES) -> None:
if all(rule(item) for rule in rules):
items.append(item)
add("hello")
add("abcdefghijk")
add("abcdefghijkcool", DEFAULT_RULES | {is_cool})
print(items)
@uncut meteor :white_check_mark: Your 3.11 eval job has completed with return code 0.
['abcdefghijk', 'abcdefghijkcool']
would probs make RuleList class and allow for + to just add one rule rather than using the set union
π @vocal basin
do you have a idea how i can create a queue with the following logic?
I think it might be simpler to just have everything as AsyncIterable
with a function flatten: AsyncIterable[AsyncIterable[T]] -> AsyncIterable[T]
how is error handling done?
(or supposed to be done)
error handeling for the sorting?
they are saved in a mariaDB, and i fetch them from there
do you have enough RAM to just store them in a list?
you're trying to interleave them, right?
i.e. to make queueing balanced/fair
yes
because once i have connectec to a URL, i cant connect to a URL belonging to the same domain for 5 secs
separate queues per each domain + priority queue of domains
Hii ALisa #algos-and-data-structs
priority queue would contain pairs (time_to_next_connection, domain)
there's also another way
just have separate task per each domain
and asyncio.sleep(5) inside
Do I need to download code runner for Python vs code and is this orange text bad
Yes
all good then, it works
Is the orange text bad
And do I have to download code runner
it's okay as it is, seems like
this is just path to interpreter
i.e. it's not an error
Ok thanks
this will also properly handle domain running out of urls
@dry jasper are you using Python 3.11?
yes
for managing multiple tasks and waiting for them to finish:
https://docs.python.org/3/library/asyncio-task.html#task-groups
async def from_domain(domain, queue):
async for url in urls_of(domain):
await queue.put(url)
await asyncio.sleep(5)
(this without priority queue, just regular one)
isn't guaranteed to interleave domains fairly, but will ensure timeout
normaly a timeout is not needed it the urls got distributed evenly
queue can be size-limited, so producers of URLs don't proceed until there are consumers waiting on the other end
because there are multiple tousand of domains, and before it is able the finish the first iteration the 5 seconds should be over
async def run(domains):
queue = asyncio.Queue(maxsize=1)
async with consume(queue):
async with asyncio.TaskGroup() as tg:
for domain in domains:
tg.create_task(from_domain(domain, queue))
inner async with waits for all tasks to finish on exit
outer async with would wait for consumers to finish existing work, then stop them
(consumers are expected to call queue.task_done when then finish work on one url)
and consume's exit would just queue.join then .cancel consumers' tasks
is there any difference b/w trees and graph other than forming cycle?
connected acyclic undirected graph = tree
direction can be introduced into such tree by choosing a node as a root and edge directions such that any node can be reached from root
a tree can be directed a directed tree?
trees from graph theory don't involve directions
but what you usually find as a data structure, has parent-child relation defined for each edge
and basically what is the use of directed graph
i think undirected graph is flexible
acyclic directed graphs are useful for describing data structures
but can we create a directed tree like directed graph?
great discussion fellas
in some interpretation of what "tree" is
so 2 cant lead into 1
if root needs to exist and is defined as a node which you can reach any other node from
<t:1691772240:R>
alternate between different ways of learning
And what if I just listen to your keystrokes and memorize what each letter sounds like?
Oh wait.
Β―_(γ)_/Β―
var x = 5;
vs
let x: number = 5;
!e
print("Hello\tWorld")
@willow light :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello World
hot take: tabs and spaces are equally important, so we should use them interchangeably, but randomized
print(..., sep="\t") when too lazy to set up proper logging but want to have better output alignment
oh I just use logging.log()
I mean so it looks roughly like a table, even with different lengths of elements
Or I'll just write logs to Redis and hope to god it doesn't break datadog
What's the name of new language that coders using against python? I couldn't remember that
log to stdout
!e
for i in [1, 11, 111]:
print(i, i, i, sep="\t")
@vocal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 1 1 1
002 | 11 11 11
003 | 111 111 111
eh
x = 5
print(x)
Now I need a pythonic equivalent of console.table
would be useful for a project I've been working on
(current project at work is entirely in sh and terraform)
phone pictures of screens, straight to jail
I was halfway through replying with a phone picture of you saying that but I thought better
It's friday, no need to annoy Rabbit.
there is table output in Jupyter
part of the idea is to have it less manual, with automatic widths
but for that you'd have to pre-process everything
as you can't resize what you previously printed
\t allows it roughly aligned if lengths are similar without lookahead
you can also increase widths when needed
overall alignment is broken but it gets correct eventually
randomly guess widths, crash on overflow
ππ
sunos?
there's also wasi
haven't seen it used
Which one is that?
for, like, non-wasm application of same format
server-side wasm
kind of
allegedly
Interesting
there are also regional versions of chrome for tracking use data
https://www.wnycstudios.org/podcasts/otm/segments/enshittification-part-1-where-did-it-all-go-wrong-on-the-media comes to mind
Back in a sec
like with Yandex Browser in Russia
they have features Chrome doesn't have, therefore people switch over
and it comes pre-installed because laws
idk what China has for that
Warning: Alpha quality software, do not use in production.
https://github.com/containerd/runwasi
As someone whose entire social media presence these days is YouTube, Discord, and Mastodon....
I used to pay for nitro
but now, well, Russia, can't pay
it seems to use less bandwidth on deafen, but far from 0
I pay for "Unlimited" with Verizon and it's sooo expensive.
And "Unlimited" is in quotes for a reason
with a spike on undeafening
Something something raw radar files are 700 MB each, and I'm downloading six of them every seven minutes.
except during storms when it becomes 30 seconds
I host a Nextcloud server, seems good enough
I just pay for Dropbox
!pip netcdf
oh not that
ohno Yandex
!pip netcdf4
basically the same data structure
guys how can customize terminal like this?
Read the manual on your terminal
Alisa did you know?
its mac terminal
zsh?
yes
!e
curl https://api.weather.gov/stations/KBOS/observations/latest | jq '.properties'
@willow light :x: Your 3.11 eval job has completed with return code 1.
001 | File "/home/main.py", line 1
002 | curl https://api.weather.gov/stations/KBOS/observations/latest | jq '.properties'
003 | ^^^^^
004 | SyntaxError: invalid syntax
oh right
i try this one
this is likely the specific one
https://github.com/agnoster/agnoster-zsh-theme
or very similar
!gh WRF
it doesn't match to this
its looks good
WTF
yes it looks it like that
icon are diffrent
discord fucked up for a couple minutes
https://thredds.ucar.edu/thredds/catalog/catalog.html this is what I use for satellite data tbh
i saw this in mosh video
may be further customised
PDM is love, PDM is life.
I have never used cortana π
My TI-89 Titanium has entered the chat.
Same, Iβve never used it too π
Itβs the end of an era though. Farewell, Cortana. π«‘
Hey siri
Namespaces are one honking good idea, let's do more of those!
Per Python Discord's Rule 5, we are unable to assist with questions related to youtube-dl, pytube, or other YouTube video downloaders, as their usage violates YouTube's Terms of Service.
For reference, this usage is covered by the following clauses in YouTube's TOS, as of 2021-03-17:
The following restrictions apply to your use of the Service. You are not allowed to:
1. access, reproduce, download, distribute, transmit, broadcast, display, sell, license, alter, modify or otherwise use any part of the Service or any Content except: (a) as specifically permitted by the Service; (b) with prior written permission from YouTube and, if applicable, the respective rights holders; or (c) as permitted by applicable law;
3. access the Service using any automated means (such as robots, botnets or scrapers) except: (a) in the case of public search engines, in accordance with YouTubeβs robots.txt file; (b) with YouTubeβs prior written permission; or (c) as permitted by applicable law;
9. use the Service to view or listen to Content other than for personal, non-commercial use (for example, you may not publicly screen videos or stream music from the Service)
Sounds like hell lol
proceeds to name every python module in explicit detail while having a stroke
np
u2
lets gooooo
Subscribe to NoCopyrightSounds π http://ncs.lnk.to/SubscribeYouTube
NCS/NoCopyrightSounds: Empowering Creators through No Copyright & Royalty Free Music
Follow on Spotify: https://ncs.lnk.to/ncsreleasesid
Free Download: http://ncs.io/Desperate
Stream: http://ncs.lnk.to/DesperateID
[NCS]
β’ http://youtube.com/c/NoCopyrightSounds
β’ https://sound...
gtg
the following is actual code i've found in production:```python
def foo( bar='lorem',
baz=False,
spam='prod',
eggs=False
):
bar = 'lorem' if bar else 'ipsum'
baz = True if baz else baz
eggs = True if eggs else False # this is all ass but this line hurt me the most
spam = camelCase(getEnv()) if not eggs else camelCase('prod')
# my_module
for i, item in mylib.iiter(myDict):
...
# mylib
def iiter(dict):
return iter(dict.items())
def foo(calculators, bar):
...
return dict([(c, (c.resultSet(), bar)) for c in calculators]) # this legit is a performance hit
# `return {c, (c.resultSet(), bar) for c in calculators}` can be from 65% - 140% faster
config['lorem'] = True if foo not in ['bar'] else False
config['ipsum'] = True if foo not in ['bar'] else False
config['dolor'] = True if foo not in ['bar'] else False
config['sit'] = True if foo not in ['bar'] else False # instead, you can just do this
# `config['bar'] = True if foo != 'bar' else False`
logger.info( f"lorem : {config['lorem']}" )
logger.info( f"ipsum : {str(config['ipsum'])}" ) # don't need to wrap with str(), that's what the fstring does already
logger.info( f"dolor : {str(config['dolor'])}" ) # and the lines above and below this showcase that
logger.info( f"sit : {config['sit']}" )
iiter situation is excusable sometimes
for example, if that function had or is planned to have a different implementation
maybe including filtering, sorting, etc.
hmm maybe. just haven't found it used anywhere like that every time i've seen it
but
dict as parameter name is inexcusable
but eggs = True if eggs else False hurt me so much
there are cases adjacent to that, which are reasonable
when condition isn't bool
in seems to cast everything to bool
per-interpreter GIL in 3.12
in C API now
and this a version later
so, yes, Gates did take part in developing a compiler, and that's kind of important to know given what consequences it had on proprietary software in general
https://en.wikipedia.org/wiki/An_Open_Letter_to_Hobbyists
"An Open Letter to Hobbyists" is a 1976 open letter written by Bill Gates, the co-founder of Microsoft, to early personal computer hobbyists, in which Gates expresses dismay at the rampant software piracy taking place in the hobbyist community, particularly with regard to his company's software.
In the letter, Gates expressed frustration with mo...
hi
have fun with all web safe sRGB colors in Luv space
@elfin flicker https://www.tug.org/texlive/doc/tlmgr.html
So speak with confidence and be rich.
No college degree necessary.
Not entirely wrong
JR makes interview a journey and ask precise questions that touch real interest of who he interviews.
Joe Regan or Impact Theory?
Man of culture
victoria monet
Play World of Tanks TODAY! pretty please https://tanks.ly/3O9rGBX
Oppenheimer Nukes Barbie AKA BarbieHeimer is a romantic thriller noir film directed by Martin Scorsese, and stars Tom Shelby, also known as Cillian Murphy and sometimes goes by the name J Robert Oppenheimer. He crafts a nuclear bomb to nuke Barbie land and Margot Robbie as well ...

More VBA?
Is this your work?
It was the easiest way to achieve what I needed, especially since this will be used by accountants and will need to be done potentially monthly
So just having it all packed away in Excel itself made the most sense
Makes it available, means I don't have to install Python on multiple computers

Okay so
What does it actually do?
Iβm not quite following the logic
It takes a folder of excel files, dumps all the sheets into a single workbook and names them either BS for balance sheet or IS for income statement along with the client number for the sheet name
Nice
There's a way to do that on a per file basis built into excel, just not a per folder basis
Iβve spent literally months working on my Excel combining
hey
Yo
how are you guys
Exhasuted. You?
bored
Lol
Iβm handling a couple million dollars, and management is β basically like βthis better be right because we canβt double check itβ
Fucking terrifying
I'm sorry that u feel exhasuted
too lazy to split stuff up into multiple commits
Eh, it's just been a long workday. Not bad, just a lot
Wait wait wait, what do you mean there's no way to double check it
well wish something could just ease the pressure off you
I'll be heading home shortly, so that'll do it
actually, it's just a way too fundamental of a change, so there's no good way to do it other than just fix errors until it compiles
that's good to know my friend
"imagine manually writing + Send 800 times, because there is no sane way to automate it"
"Citrus maxima"
Not that itβs βnot possibleβ, just thatβ¦. I think they just get overwhelmed because of the amount of data.
But β I do have automated tests and I do manual review, I just donβt get a second set of human eyes
And even when I doβ¦. We fucked up the first year we had the project, and I was trying to understand the data, and my boss said βI need you in my office RIGHT NOW to figure this out!!β. I showed up in his office, andβ¦. Spent over an hour fixing typos in the seven additional Excel files he had created for himself just to get the data correct before we could even start reviewing it
Hello people
Ello all π
dictionary = {}
print("enter name and grade")
active = True
i = ""
while active:
if i.lower() != "exit":
name = input("enter name: ")
grade = input("enter grade: ")
dictionary[name] = grade
else:
active = False
i = input("enter 'exit' when you are done: ")
for name, grade in dictionary.items():
print(name, grade)
this program prints enter 'exit' when you are done twice when i enter exit someone help
!code @bright shoal
sorry i didnt got thisπ
Thanks
thanks
You can put the i = input line at the end of your if ... block and that would be a quick fix but it could also be restructured to be better.
i fixed it
thanks
dictionary = {}
print("enter name and grade")
while True:
i = input("enter 'exit' when you are done: ")
if i.lower() == "exit":
break
name = input("enter name: ")
grade = input("enter grade: ")
dictionary[name] = grade
for name, grade in dictionary.items():
print(name, grade)
dictionary = {}
print("enter name and grade")
active = True
i = ""
while active:
if i.lower() == "exit":
active = False
else:
name = input("enter name: ")
grade = input("enter grade: ")
dictionary[name] = grade
i = input("enter 'exit' when you are done: ")
for name, grade in dictionary.items():
print(name, grade)
ok
not rude at all....
if some one want to talk . i am in this voice chat π
never mind forget it
Why Hello
I created my first game
Very Basic
hahaha
where would i indent?
I get an error
Ahhh
!code
!import random
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print
("You rolled " + str(roll) + str(roll) + "You Loose")
else:
print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
Example:
>>> from math import *
>>> sin(pi / 2)
1.0
This is discouraged, for various reasons:
Example:
>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2) # uses sin from math rather than your custom sin
β’ Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
β’ Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
β’ Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.
How should you import?
β’ Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
β’ Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)
Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]
[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python
!code import random
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print
("You rolled " + str(roll) + str(roll) + "You Loose")
else:
print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
ok
!indent
Indentation is leading whitespace (spaces and tabs) at the beginning of a line of code. In the case of Python, they are used to determine the grouping of statements.
Spaces should be preferred over tabs. To be clear, this is in reference to the character itself, not the keys on a keyboard. Your editor/IDE should be configured to insert spaces when the TAB key is pressed. The amount of spaces should be a multiple of 4, except optionally in the case of continuation lines.
Example
def foo():
bar = 'baz' # indented one level
if bar == 'baz':
print('ham') # indented two levels
return bar # indented one level
The first line is not indented. The next two lines are indented to be inside of the function definition. They will only run when the function is called. The fourth line is indented to be inside the if statement, and will only run if the if statement evaluates to True. The fifth and last line is like the 2nd and 3rd and will always run when the function is called. It effectively closes the if statement above as no more lines can be inside the if statement below that line.
Indentation is used after:
1. Compound statements (eg. if, while, for, try, with, def, class, and their counterparts)
2. Continuation lines
More Info
1. Indentation style guide
2. Tabs or Spaces?
3. Official docs on indentation
!e py v = 5 v = v + 3 print(v)
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
8
Ahhh i see
!e py v = 5 v += 3 print(v)
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
8
Got ya
!d while
8.2. The while statement
The while statement is used for repeated execution as long as an expression is true:
while_stmt ::= "while" assignment_expression ":" suite
["else" ":" suite]
``` This repeatedly tests the expression and, if it is true, executes the first suite; if the expression is false (which may be the first time it is tested) the suite of the `else` clause, if present, is executed and the loop terminates.
A [`break`](https://docs.python.org/3/reference/simple_stmts.html#break) statement executed in the first suite terminates the loop without executing the `else` clauseβs suite. A [`continue`](https://docs.python.org/3/reference/simple_stmts.html#continue) statement executed in the first suite skips the rest of the suite and goes back to testing the expression.
How would i write, If my else statment was true to add to the Total... but if my "if statment" was true to take away from the total?
Ahhhh
That's what I needed
I'm still trying to get it working
mmm
So in my code, It asks for bet lets say 100, if they wiln it doubles to 200. How would i store this ammount for the next time they want to bet again?
Okay
So I would use a for loop?
Yes
Okay
Does the while go at the bottom of this code?
!e py import random while random.randint(0, 4) != 3: print('Helllo!') print('Bye!')
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Helllo!
002 | Bye!
okay
got it
import random
while Ballance < 4000
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
Ballance = bet x2
Ballance = Ballance
!import random
while Ballance < 4000
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
Ballance = bet *2
Ballance = Ballance
Wildcard imports are import statements in the form from <module_name> import *. What imports like these do is that they import everything [1] from the module into the current module's namespace [2]. This allows you to use names defined in the imported module without prefixing the module's name.
Example:
>>> from math import *
>>> sin(pi / 2)
1.0
This is discouraged, for various reasons:
Example:
>>> from custom_sin import sin
>>> from math import *
>>> sin(pi / 2) # uses sin from math rather than your custom sin
β’ Potential namespace collision. Names defined from a previous import might get shadowed by a wildcard import.
β’ Causes ambiguity. From the example, it is unclear which sin function is actually being used. From the Zen of Python [3]: Explicit is better than implicit.
β’ Makes import order significant, which they shouldn't. Certain IDE's sort import functionality may end up breaking code due to namespace collision.
How should you import?
β’ Import the module under the module's namespace (Only import the name of the module, and names defined in the module can be used by prefixing the module's name)
>>> import math
>>> math.sin(math.pi / 2)
β’ Explicitly import certain names from the module
>>> from math import sin, pi
>>> sin(pi / 2)
Conclusion: Namespaces are one honking great idea -- let's do more of those! [3]
[1] If the module defines the variable __all__, the names defined in __all__ will get imported by the wildcard import, otherwise all the names in the module get imported (except for names with a leading underscore)
[2] Namespaces and scopes
[3] Zen of Python
py
import random
while Ballance < 4000
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
Ballance = bet *2
Ballance = Ballance
import random
while Ballance < 4000
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
Ballance = bet *2
Ballance = Ballance
Thanks ahha
Sorry i was getting confused with somthing else
that kept popping up
π
import random
while Ballance < 4000:
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
balance = bet*2
balance = balance
import random
while Ballance < 4000:
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
balance = bet*2
balance = balance
import random
while balance < 4000:
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
balance = bet*2
balance = balance
Need to add a variable for balance
balance =
hmm
What should i say balance is?
0
ohh 100
So they have somthing
yeah
@pallid sundial π
py if balance > 1
!d and
6.11. Boolean operations
or_test ::= and_test | or_test "or" and_test
and_test ::= not_test | and_test "and" not_test
not_test ::= comparison | "not" not_test
``` In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: `False`, `None`, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. User-defined objects can customize their truth value by providing a [`__bool__()`](https://docs.python.org/3/reference/datamodel.html#object.__bool__) method.
The operator [`not`](https://docs.python.org/3/reference/expressions.html#not) yields `True` if its argument is false, `False` otherwise.
!e py print(5 > 0 and 5 < 10)
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
Will it only print if both are true?
!e
print(5 < 0 and 5 < 10)
@west lion :white_check_mark: Your 3.11 eval job has completed with return code 0.
False
!e
print(5 < 0 or 5 < 10)
@west lion :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
!e
print(5 = 0 or 5 < 10 or 1 = 2 or 1= 3 or 1=1)
h
!e py print(0 < 5 < 10)
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
Interesting
!e
print(5 == 0 or 5 < 10 or 1 == 2 or 1 == 3 or 1==1)
@west lion :white_check_mark: Your 3.11 eval job has completed with return code 0.
True
import random
balance = 200
while balance < 0:
print("GAMEOVER!")
or balance >4000:
print("YOU HAVE WON THE GAME!")
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
balance = bet*2
These are great!
My favorite people
import random
balance = 200
while balance < 0:
print("GAMEOVER!")
while balance > 4000:
print("YOU HAVE BEATEN THE GAME!")
#restart game and ask user to bet
#Else let the user know they have beaten the game
bet = int(input("Your Ballace is " "Bet Ammount:"))
roll = random.randint(1,100)
if roll >50:print("You rolled " + str(roll) + str(roll) + "You Loose")
else: print("You rolled " + str(roll) +(" WINNER! Total Win = ") + str(bet *2))
balance = bet*2
can I have 2 while like this?
Yes, but the question is if you want to or not.
!e
import random
balance = 1000
while balance < 4000:
bet = random.randint(1, balance)
print(f"Your balance is {balance}. Bet Amount: {bet}")
roll = random.randint(1, 100)
if roll > 50:
print("You rolled " + str(roll) + ". You Lose")
balance -= bet
else:
print("You rolled " + str(roll) + ". WINNER! Total Win = " + str(bet * 2))
balance += bet
if balance <= 0:
print("You have run out of money. Restarting game.")
balance = 1000
elif balance >= 4000:
print("Congratulations! You win!")
@desert wolf :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | Your balance is 1000. Bet Amount: 383
002 | You rolled 33. WINNER! Total Win = 766
003 | Your balance is 1383. Bet Amount: 1354
004 | You rolled 59. You Lose
005 | Your balance is 29. Bet Amount: 15
006 | You rolled 96. You Lose
007 | Your balance is 14. Bet Amount: 4
008 | You rolled 1. WINNER! Total Win = 8
009 | Your balance is 18. Bet Amount: 2
010 | You rolled 75. You Lose
011 | Your balance is 16. Bet Amount: 12
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/QKXAS6IKTTHDROWIJW73D4B2YM
Wow so I was close
Now just need to slow down the loop and treat each bet individually
"So the game can be played"
import random
balance = 1000
while balance < 4000:
bet = input("Your balance is" + balance + "Bet Amount: ")
roll = random.randint(1, 100)
if roll > 50:
print("You rolled " + str(roll) + ". You Lose")
balance - bet
else:
print("You rolled " + str(roll) + ". WINNER! Total Win = " + str(bet * 2) + balance)
balance + bet
if balance <= 0:
print("GAME OVER!")
elif balance >= 4000:
print("Congratulations! You win!")
It almost works
import random
balance = 1000
while balance < 4000:
bet = input("Your balance is" + balance + "Bet Amount: ")
roll = random.randint(1, 100)
if roll > 50:
print("You rolled " + str(roll) + ". You Lose")
balance = balance - bet
else:
print("You rolled " + str(roll) + ". WINNER! Total Win = " + str(bet * 2) + balance)
balance = balance + bet
if balance <= 0:
print("GAME OVER!")
elif balance >= 4000:
print("Congratulations! You win!")
!d f-string
String literals prefixed with 'f' or 'F' are commonly called βf-stringsβ which is short for formatted string literals. See also PEP 498.
!f-string
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
import random
balance = 1000
while balance < 4000:
bet = input(f"Your balance is" + {balance} + "Bet Amount: ")
roll = random.randint(1, 100)
if roll > 50:
print("You rolled " + str(roll) + ". You Lose")
balance = balance - bet
else:
print("You rolled " + str(roll) + ". WINNER! Total Win = " + str(bet * 2) + balance)
balance = balance + bet
if balance <= 0:
print("GAME OVER!")
elif balance >= 4000:
print("Congratulations! You win!")
print(f"Your balance is {balance}. Bet amount: ")
This is how f-strings work right?
Ah okay
bet = input(f"Your balance is" + {balance} + "Bet Amount: ") ```
Balance is not showing in output
what happen when I plug dict or list to it? will it auto spread it?
It needs to be inside the quotation marks
!e py age = 20 name = 'Peter' print(f'Hello. Your name is {name} and you are {age} years old.')
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello. Your name is Peter and you are 20 years old.
bet = input(f"Your balance is {balance} Bet Amount 50.")
!e
print(1 + 1)
@hollow jacinth :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
code
!eval [python_version] <code, ...>
Can also use: e
Run Python code and get the results.
This command supports multiple lines of code, including formatted code blocks. Code can be re-evaluated by editing the original message within 10 seconds and clicking the reaction that subsequently appears.
The starting working directory /home, is a writeable temporary file system. Files created, excluding names with leading underscores, will be uploaded in the response.
If multiple codeblocks are in a message, all of them will be joined and evaluated, ignoring the text outside them.
By default, your code is run on Python 3.11. A python_version arg of 3.10 can also be specified.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
!e
bet = input(f"Your balance is" + {balance} + "Bet Amount: ")
@minor elm :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 1, in <module>
003 | bet = input(f"Your balance is" + {balance} + "Bet Amount: ")
004 | ^^^^^^^
005 | NameError: name 'balance' is not defined
!e import random
balance = 1000
while balance < 4000:
bet = input(f"Your balance is {balance}" + "Bet Amount: ")
roll = random.randint(1, 100)
if roll > 50:
print("You rolled " + str(roll) + ". You Lose")
balance = balance - bet
else:
print("You rolled " + str(roll) + ". WINNER! Total Win = " + str(bet * 2) + balance)
balance = balance + bet
if balance <= 0:
print("GAME OVER!")
elif balance >= 4000:
print("Congratulations! You win!")
@minor elm :x: Your 3.11 eval job has completed with return code 1.
:warning: Note: input is not supported by the bot :warning:
001 | Your balance is 1000Bet Amount: Traceback (most recent call last):
002 | File "/home/main.py", line 8, in <module>
003 | bet = input(f"Your balance is {balance}" + "Bet Amount: ")
004 | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
005 | EOFError: EOF when reading a line
I love f-strings
!e
import string
alphabets = string.characters
print(alphabets)
my bad. it's ascii_letters
import random
balance = 1000
while balance < 4000:
bet = input(f"Your balance is {balance}" + "Bet Amount: ")
roll = random.randint(1, 100)
if roll > 50:
print("You rolled " + str(roll) + ". You Lose")
balance = balance - bet
else:
print("You rolled " + str(roll) + ". WINNER! Total Win = " + str(bet * 2) + balance)
balance = balance + bet
if balance <= 0:
print("GAME OVER!")
elif balance >= 4000:
print("Congratulations! You win!")
!e
import string
alphabets = srting.ascii_characters
print(alphabets)
!e
balance = 10
print(f"Your balance is {balance}" + "Bet Amount: ")
@hollow jacinth :white_check_mark: Your 3.11 eval job has completed with return code 0.
Your balance is 10Bet Amount:
me and my spelling mistakes xD
need to drop off, bye all π
Imma go as well. got an exam tomorrow
π€¨
haha allgood
This is the code i'm running
Could you try run the code?
Lets see if it's a user error
Visual Code
Your balance is 1000Bet Amount: 10
You rolled 63. You Lose
Traceback (most recent call last):
File "/home/betagmr/main.py", line 14, in <module>
balance = balance - bet
TypeError: unsupported operand type(s) for -: 'int' and 'str'
bet = int(input(f"Your balance is {balance}" + "Bet Amount: "))
.
print("You rolled " + str(roll) + ". WINNER! Total Win = " + str(bet * 2) + balance)
print(f"You rolled {roll}. WINNER! Total Win = {bet * 2 + balance}")
nice
Thanks for all the help, This was the best learning i have had! β€οΈ give my game a run if you like π Enjoy
balance = 1000
while balance < 4000:
bet = int(input (f"Your balance is = {balance} " + "Bet Amount: "))
roll = random.randint(1, 100)
if roll > 50:
print(f"You rolled {roll} You Lose")
balance = balance - bet
else:
print(f"You rolled {roll}. WINNER! Total Win = {bet * 2}")
balance = balance + bet
if balance <= 0:
print("GAME OVER!")
elif balance >= 4000:
print("Congratulations! You win!") ```
@eager sequoia π
Hi @somber heath
@somber heath what text editor do you use ?
I guess a one that has graphical features, considering your beautiful generated-art project
ok, unusual but i guess i understand it
bye @somber heath @cunning lake @echo garden
hi
@thick moon π
Nah, I didn't
@trail stag π
where did you get the idea that it was unpaid?
Hello @hexed saddle
Hello
@wind raptor
brb
something very wrong with that diagram
this is only valid for waterfall
because this is waterfall
Yeah, it's missing all the sprint cycles where it goes through each of these things in every sprint, but I think it gets the point across
this looks like something I haven't seen in other languages
https://kotlinlang.org/docs/enum-classes.html#anonymous-classes
Oh yeah, that is cool
gtg for now, see you guys
Have a good one
functionally, that seems similar to non-empty enum variants in Rust
enum variant in Rust is basically just a semi-anonymous struct definition;
except for how pub gets handled, I think
(pub inside enums is an error, but not a syntax error)
rust-analyzer doesn't even seem to error at that
oh, no, it does
okay, so, rust-analyzer treats it as syntax error
Well that's good
yo
whatsthat
.latex $x =\LaTeX
No logs available.
.latex
a \\
b
.latex $x = \LaTeX
No logs available.
.latex
\begin{align}
\omega(t,x) &= \frac{1}{\sqrt{1-(\frac{x}{t})^2}} \\
&= \frac{1}{\sqrt{1-(\frac{x^{2}}{t^{2}})}} \\
&= \frac{1}{\sqrt{\frac{1}{t^{2}}(t^{2} - x^{2})}} \\
&= \frac{1}{\frac{1}{t}\sqrt{(t^{2} - x^{2})}} \\
&=\frac{t}{\sqrt{t^2 - x^2}} \\
\end{align}
.latex
\font\donteveruseoutsidecartoons="Comic Sans MS" at 14pt
\font\donteveruseoutsidecartoonstwo="Comic Sans MS/IB:slant=.3pt" at 22pt
\input tikz
\usetikzlibrary{shapes.callouts,positioning}
\tikzpicture[mycallout/.style={draw,ellipse callout,inner sep=1.2ex,
callout relative pointer={#1}}]
\node[mycallout={(.5cm,-.5cm)}] (ico) {\donteveruseoutsidecartoons Be rational};
\node[mycallout={(-.5cm,-.5cm)}, right=of ico] (pco) {\donteveruseoutsidecartoons Get real};
\node[below=.1ex of ico.pointer] {\donteveruseoutsidecartoonstwo i};
\node[below left=.1ex of pco.pointer] {\donteveruseoutsidecartoonstwo Ο\vphantom(};
\endtikzpicture
\bye
!voice
Canβt talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
!voice
`
\font\donteveruseoutsidecartoons="Comic Sans MS" at 14pt
\font\donteveruseoutsidecartoonstwo="Comic Sans MS/IB:slant=.3pt" at 22pt
\input tikz
\usetikzlibrary{shapes.callouts,positioning}
\tikzpicture[mycallout/.style={draw,ellipse callout,inner sep=1.2ex,
callout relative pointer={#1}}]
\node[mycallout={(.5cm,-.5cm)}] (ico) {\donteveruseoutsidecartoons Be rational};
\node[mycallout={(-.5cm,-.5cm)}, right=of ico] (pco) {\donteveruseoutsidecartoons Get real};
\node[below=.1ex of ico.pointer] {\donteveruseoutsidecartoonstwo i};
\node[below left=.1ex of pco.pointer] {\donteveruseoutsidecartoonstwo Ο\vphantom(};
\endtikzpicture
\bye
b = 1
b.replace(2)
print (b)
what is the code problem?
!e
b = 1
b.replace(2)
print(b)
@vocal basin :x: Your 3.11 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 2, in <module>
003 | b.replace(2)
004 | ^^^^^^^^^
005 | AttributeError: 'int' object has no attribute 'replace'
why?
b = "1"
b = b.replace("1", "2")
print(b)
!e b = "1"
b = b.replace("1", "2")
print(b)
@prime kayak :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
time to patent UndefineDB
thank you bro
!e
b = 1
b = 2
print(b)
@vocal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
2
!e
print("balls")
@scarlet halo :white_check_mark: Your 3.11 eval job has completed with return code 0.
balls
LETS GOOO
slightly #esoteric-python
it was only for practice
... for the scope of what the original question was
!e```py
print(" ".join(["hello", "world"])
!e
print(str(["Hello", "World!"])[1:-1].replace("'", ""))
@vocal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
Hello, World!
These are the videos from NolaCon 2019:
http://www.irongeek.com/i.php?page=videos/nolacon2019/mainlist
Patreon:
https://www.patreon.com/irongeek
"joined late by some number of seconds, had to compress the code somewhat"
@vocal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
1 3 5 7 9 11
@vocal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
test
o
the timer resumed
ah, for cycles
for just duplicates I prefer this
||```py
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
s = set()
c = 0
while c < len(nums):
r = min(c+1000, len(nums))
s.update(nums[c:r])
c = r
if len(s) != c:
return True
return False
because it
- short-circuits
- chunked, therefore fast
@whole bear depends on text editor
some persist history after restarts
you can also enable auto-save
Installed too
yes
code: DrGAH4dJb9
type this in the leetroom right side pane
4 questions, you have to click on it
there's a problem
I have them all solved
I'll reset without memorising
at least I'll try
I can't join this one. I need to work on reading and other stuff right now π¦
I've wanted to make an LED Music Visualizer for the past year so I finally just did it. I had many problems designing the circuitry and although it is not perfect it actually turned out to be a pretty good result. The coding in this project was simple in comparison to the hardware and although this is not a programming video I want to show peopl...
This is an old video. I recently started to upload again. Scientific topics, and more, but animated! Check my new stuff out: https://www.youtube.com/RationalAnimations
π Support us on Patreon to receive rewards and to help make this channel self-sustaining: https://www.patreon.com/rationalanimations
Here is the program I used in the video to r...
another way is to learn how existing tools do that
for example, renpy
... which you can extend further on your own
Are the examples of that Alisa like videos explaining how to start that
@whole bear https://www.youtube.com/watch?v=YY7LIEHiAfg
Building a text and image-based game with ChatGPT as the backend via the api... plus a little help from ChatGPT to build it.
Github: https://github.com/Sentdex/GPT-Journey
Neural Networks from Scratch book: https://nnfs.io
Channel membership: https://www.youtube.com/channel/UCfzlCWGWYyIQ0aLC5w48gBQ/join
Discord: https://discord.gg/sentdex
Red...
Ren'Py is a dialect of Python used for visual novels
https://www.renpy.org/doc/html/index.html
Thank you
system itself is written in Python and configured via Python-like code
you can customize every aspect of your operating system, here is an example of someone making a beautiful "riced" linux @whole bear
another really pretty example:
more effort for simple customisation
less effort for deep customisation
powershell works on linux too
another beautiful example
> what was difficult on linux
wi-fi
just no, never again
ssh on windows just worked for me
tbf, that had to be done from CLI
I use a separate computer for Linux, works quite good
@quick cloak "*nix" not unix
linux isn't unix
unix-like but not unix
Solaris, BSD, MacOS -- unix, afaik
@verbal zenith posix
using VirtualBox is necessary evil
it used to be Sunβ’οΈ VirtualBox
just like Java
I was recently helping someone with virtualbox, and the course they were following still had Sunβ’οΈ in the screenshots
it requires quite a lot of thinking to get things done in Rust
starting with Rust has its benefits, but it's difficult
I couldn't imagine starting with rust
it's not as forgiving as GCd or manual-memory-management languages
hola guys
ello
How you doin?
for most things, the difference from C/Java/Python is not fundamental, at least in appearance
and some elements are just simpler
pretty decent hby?
pretty handsome
(ones allowed by enum)
what are you explaining btw
not mentioning traits, because that's far far away from beginner level programming, I think
Rust as a first language to learn
should we or not
traits seems understandable if you break down their actual use rather than how to use HAHAHA
loll
The concept of a trait is much more understandable than the application
!kindling
The Kindling projects page on Ned Batchelder's website contains a list of projects and ideas programmers can tackle to build their skills and knowledge.
though not ordered
@vocal basin I am a beginner to web developer.....can you guide me through what should be good for me to do now to keep my progress good
static sites or ones with server-side functionality?
static
useful resource for web development
https://developer.mozilla.org/en-US/
it doesn't provide any sort of roadmap but it provides tools to learn
it has two examples of server-side frameworks
Django (for Python) and Express (for Node)
anything else server-side usually has its own dedicated documentation/tutorials
for example:
https://fastapi.tiangolo.com/tutorial/first-steps/
HELLLOOOOOOOO
yes 100%
regret learning high level shit as first lang
@vocal basin Understood Thanks for your help
VS Code without extensions is just a text editor + terminal
keyword "without extensions"
not a lot of ppl are going for vanilla vscode
quite hard to compare languages based on what's more high-level
for C# and Rust that ordering isn't defined
fair enough
@whole bear @verbal zenith
404
||```py
class Solution:
def sumOfLeftLeaves(self, root: Optional[TreeNode], left=False) -> int:
match root:
case TreeNode(val=val, left=None, right=None) if left:
return val
case TreeNode(left=left, right=right):
return self.sumOfLeftLeaves(left, True) + self.sumOfLeftLeaves(right, False)
case _:
return 0
258
||```py
num and (num % 9 or 9)
```||
136
||```py
reduce(xor, nums)
```||
121
||```py
max(0, max(map(sub, prices, accumulate(prices, min, initial=float('inf')))))
```||
is this leetcode
yes
last three have all the boilerplate omitted for simplicity
(there's obviously return and other stuff in the solution)
can play another
the issue is that it picks early ones, and I have all easy solved up to around #700
oh, 222 got demoted
code: FCJJI44rBL
what game
leetrooms
anyone familiar with robin-stocks module?
yes, still here
no, not busy
it can be done without extra data storage
(except for call stack)
one option is to use a more general function
||```py
def solve(left, root, right):
if root:
return min(
solve(left, root.left, root.val),
solve(root.val, root.right, right),
root.val - left,
right - root.val,
)
else:
return float('inf')
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
return solve(float('-inf'), root, float('inf'))
another is to use a generator
||```py
def nodes(root: Optional[TreeNode]):
if root:
yield from nodes(root.left)
yield root.val
yield from nodes(root.right)
class Solution:
def minDiffInBST(self, root: Optional[TreeNode]) -> int:
return -max(starmap(sub, pairwise(nodes(root))))
!e
from itertools import pairwise
print(*pairwise(range(5)))
@vocal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
(0, 1) (1, 2) (2, 3) (3, 4)
!d itertools.pairwise
itertools.pairwise(iterable)```
Return successive overlapping pairs taken from the input *iterable*.
The number of 2-tuples in the output iterator will be one fewer than the number of inputs. It will be empty if the input iterable has fewer than two values.
Roughly equivalent to:
```py
def pairwise(iterable):
# pairwise('ABCDEFG') --> AB BC CD DE EF FG
a, b = tee(iterable)
next(b, None)
return zip(a, b)
```...
left -- left bound, starts at -inf
right -- right bound, starts at +inf
all values of nodes in root are between left and right
I think it can be simplified further
so it's just the smallest range any subtree falls into
||```py
def solve(left, root, right):
if root:
return min(
solve(left, root.left, root.val),
solve(root.val, root.right, right),
)
else:
return right - left
this is derived from pairwise-based solution
, which is almost equivalent to collecting nodes into a list, then comparing differences between adjacent elements
i like this β€οΈ
also, it uses the fact that, for each pair of adjacent values, one of two nodes is a parent to another
(otherwise there'd be a common parent, value of which is between them, therefore they aren't adjacent)
yes, not immediate
like, not parent, but something else, idk the term
yes, another option is to return min/max per subtree
should work too
but it's more difficult to accumulate
so, instead of moving min/max values upwards to the parent, it moves root.val downwards to children
hi @whole canopy π
hi @sterile tusk π
hi bro
hi. how are u
Are you working on anything interesting
I am studying python from scratch
I'm beginner
and you?
That's great where are you up to.
I'll say something super controversial. I've been working with Python programmers for years but never actually learnt to programme
I'm quite an advanced prompt engineer and I now use chat GPT to write my software. And of course produce unit tests.
learning concepts such as what data are: Integer, Float, String and Boolean how they are used learning to type codes, introduce myself to scripts, that's what I'm going to do, sorry if you find spelling mistakes, my mother tongue is Spanish jsjs
Show my friend isn't with me he could help me with the Spanish. Do you have any other programming background
like a programming background? I have a python server that is in Spanish in case you are interested friend
how can i speak in this chat
Canβt talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
Hi
hi
2M Up to 2M characters translated per month
Free
how are you @worldly roost
A unit test in Python is a way to test a small "unit" of code, usually a single function or method, in isolation. The goal is to validate that each part of a program is working as expected.
Some key points about Python unit testing:
Unit tests are usually written using the unittest module in the Python standard library. This provides tools for creating test cases, assertions, test runners etc.
A unit test typically exercises one method or function. It feeds in various inputs and verifies the outputs are as expected.
Good unit test cases cover both nominal/valid inputs, as well as edge cases like empty inputs, exceptions, special values etc.
Unit tests are organized into test classes and test cases that group together similar tests.
Test driven development (TDD) is a development process that relies on first writing unit tests that fail, then writing code to make them pass.
Unit testing requires writing additional code, but pays off in the long run with more robust, less buggy applications.
Unit tests can be run automatically, and often integrated into CI/CD pipelines to validate each change.
Important Python unittest features include test fixtures, mocks, parametrized tests, test runners and more.
So in summary, unit testing is a key technique for software quality and reliability, and the unittest framework provides powerful tools for it in Python. Writing effective unit tests takes practice, but pays dividends.
From claude.ai
Im desperate because math homework r so difficult. Prob i will translate some viernamese hw to english n ask for belp
Eats, Shoots & Leaves: The Zero Tolerance Approach to Punctuation is a non-fiction book written by Lynne Truss, the former host of BBC Radio 4's Cutting a Dash programme. In the book, published in 2003, Truss bemoans the state of punctuation in the United Kingdom and the United States and describes how rules are being relaxed in today's society....
A panda walks into a cafΓ©. He orders a sandwich, eats it, then draws a gun and fires two shots in the air.
"Why?" asks the confused waiter, as the panda makes towards the exit. The panda produces a badly punctuated wildlife manual and tosses it over his shoulder.
"I'm a panda," he says at the door. "Look it up."
The waiter turns to the relevant entry in the manual and, sure enough, finds an explanation.
"Panda. Large black-and-white bear-like mammal, native to China. Eats, shoots & leaves."
what kind of math?
issues with this text (found so far):
only mentions unittest, doesn't mention pytest;
unit testing in many cases speeds up development short term (literal minutes), not just in the long run;
that definition of tdd is wrong, it's not just a test-first approach, but instead a loop with minimal iterations switching between test writing, code writing and refactoring;
I've got this stupid problem.
I get a dict with nested list, then another nested dict. how can i pull something within a dict, in a list, then in a dict
like
{'id': '912083012', 'cost_variables': [{'currency': '12938018', 'direct_cost': 'I WANT THIS'}]}
ive just been staring at code for like 10 hours
and my brain is off
is list always only one element long?
its always the same size, num of elements, but no, its like 15 long
[element['direct_cost'] for element in d['cost_variables']]
can i not do it iteratively
alisa ur a godsend btw
i would never have structured it like this (but the api...)
!e
d = {'id': '912083012', 'cost_variables': [{'currency': '12938018', 'direct_cost': 'I WANT THIS'}]}
print([element['direct_cost'] for element in d['cost_variables']])
@vocal basin :white_check_mark: Your 3.11 eval job has completed with return code 0.
['I WANT THIS']
it will output a list with the same length as the original list
how can i pull just the value
do you know the exact index?
yeah but i dont have enough experience to know if it will change
so idk if it's SAFE
it's a real-money trading bot
so im nervous lol
do you need to get the value for the specific value of 'currency'?
specific value of 'direct_cost"
what do you pick the index based on?
whatever the value for the key 'direct_cost' is
i didnt make this abomination of data, its the api im working with
lol
what does the whole list look like?
i gotta blur data gimme a min
i tabbed it out for readability in a secondary file
so i need to grab
stock['cost_bases']['direct_cost_basis']
im trying to do something like
some_kinda_function(float(stock['cost_bases']['direct_cost_basis']))
nvm im stupid, just needed to do
stock['cost_bases'][0]['direct_cost_basis']
ty for your help @vocal basin
many hemlock emoji's await your future
@keen sentinel π
@slim gorge π
Hemlock is loved
@humble dagger π
Hello
What is this
@tender loom π
@lyric valve @sharp python π
can't talk
!voice
Canβt talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
they require me to send 50 messages
@prime burrow π
Hellooo
Do you know much about GUI?
Tkinter?
Okay I will hold off for now
Did you want to play my game?
It works okay
I want to build a progarm that compares prices of things from one country to another.
Is that where Dictonarys come in?
I'd expect a more practical solution use some data structure other than just hashmap (dictionary), but for low volumes of data it might be good enough
the following mapping is usually easy to construct from data:
country code -> local price
local prices aren't necessarily easy to compare
you might choose to store dollar equivalent of a price instead
(valid at some point in the past)
depending on amount an variety of requests, you might choose to store (country, currency, price)
also choice of data structure comes from where sorting and other processing happens
client-side vs server-side, if you offer up the results to somewhere else
(or, just inside the structure or outside)
it can also be animated
Heyo
I should've really been saving components of the video separate from the video
because the pink/purple thing here looks quite good compared to everything else
I will now go and try to generate something like this again
@somber heath @minor elm The way I would explain complex numbers is :
It is like two numbers together. So you can use them to represent coordinates, or many other things in physics etc.
The whole point is that, they are really together : you can treat them as one number, meaning you can add complex numbers, multiply them etc...
That makes them very practical for operating transformations (translations, rotations, zooms etc...), because instead of re-coding them, you simply do a simple math operation.
!e py print('123\n456\n789')
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
001 | 123
002 | 456
003 | 789
!e py print(len('\n'))
@somber heath :white_check_mark: Your 3.11 eval job has completed with return code 0.
1
I totally forgot how the code looked like
self.policy: HighLevelPolicy = NCHLP(Randomized())
self.manifold: Manifold = ProjectionalPlane()
@vocal basin is that python
yes
yes super
what is this for :
