#algos-and-data-structs
1 messages · Page 54 of 1
So I don't have to be using an adjacency list here?
Just an edge list?
And then sort it by weight
For 1, you just need two things
a). A list of the edges sorted by weight
b). A DSU (used to keep track of the sizes of the connected components)
Do you know what a DSU is?
It keeps track of unconnected elements in a relation
but i've never implemented one
https://github.com/cheran-senthil/PyRival/blob/4a735958bfd3ac130a1d60542a23390e99b756f4/pyrival/data_structures/DisjointSetUnion.py#L1-L29 you want something like this
What do you mean by size of connected components btw?
As in the largest weight of any edge connecting them?
No. The size of a connected component is that number of vertices in that component
Ohhh so that would be the max number of nodes reachable
yes exactly
Btw this is very reminicant of Kruskal's algorithm for computing MST, https://en.wikipedia.org/wiki/Kruskal's_algorithm
Kruskal's algorithm finds a minimum spanning forest of an undirected edge-weighted graph. If the graph is connected, it finds a minimum spanning tree. It is a greedy algorithm that in each step adds to the forest the lowest-weight edge that will not form a cycle. The key steps of the algorithm are sorting and the use of a disjoint-set data struc...
what prevents just adding all the edges < w and then just traversing to check reachability? 
if you want all possible answers then sure, you want the DSU solution
I'm describing something that runs instant for each type 1. query
I dont need all possible paths to a vertice if that's what you mean
Just what vertices I can reach
What @haughty mountain is trying to say is that if you are fine with a slower running algorithm, then you don't need anything as fancy as a DSU
Ohh
all possible answers in the sense that you have effectively computed the answer for all w
it's not even slower if it's only 1 query
where each file can contain up to 5k queries
the idea of multiple queries seems odd to me given that 3 can just be done in one way
Do you have a link to the problem?
So for the DSU thing, i'd initialize a DSU(num of vertices) and then for every edge, union them?
yes exactly
You might want to modify the implementation I sent you if you want to use dictionaries
it's a homework problem which they made somewhat esoteric to read but sure
or the vertices can just be shifted down by 1 and lists can be used
ye
So a nested list?

Ah, the vertices have to be represented by integers 1-N
theres no vertice 0
why does it have to be?
maybe use a list but just add a dummy element to make indexing easier
you can just subtract 1
and if really needed you can add 1 later if you need the 1 indexed ones for printing results or whatnot
Oh no that's not necessary
I personally always keep 0-indexing inside my own code. I handle the conversion between 1-indexing / 0-indexing at parsing/printing.
I think that is the most sane solution
Instead of adding a dummy 0
That's what I have now
[[0, [(1, 8), (2, 4)]], [1, [(0, 8), (4, 6), (5, 12)]], [2, [(0, 4), (3, 7), (4, 20), (6, 15)]], [3, [(2, 7), (5, 13)]], [4, [(1, 6), (2, 20), (5, 15)]], [5, [(1, 12), (3, 13), (4, 15), (6, 10)]], [6, [(2, 15), (5, 10)]]]
[False, False, False, True, True, False, True]
Here is how I would code the input parsing for that problem
n,m = [int(x) for x in input().split()]
has_weapon = [c == 'W' for c in input().split()]
edges = []
for _ in range(m):
u,v,weight = [int(x) for x in input().split()]
# Switch to 0-indexing
u -= 1
v -= 1
edges.append((u,v,weight))
# Sort edges by increasing weight
edges.sort(key = lambda e:e[2])
graph = [[] for _ in range(n)]
for u,v,weight in edges:
graph[u].append((v, weight))
graph[v].append((u, weight))
Not an adjacency list?
graph is an adjecency list
thats not the DSU I linked earlier
It is missing size
Oh my bad
Btw as an example of how to use the DSU, here is how I would find the MST (using kruskal's algorithm)
def mst(n, edges):
mst_edges = []
dsu = DisjointSetUnion(n)
for u,v,weight in edges:
if dsu.find(u) != dsu.find(v): # u and v are in different components
dsu.union(u, v) # Connect u and v
mst_edges.append((u,v,weight))
return mst_edges
Oh, so the third query can also be solved using dsu
Probably all of it can be solved using dsu in one way or another
However as @haughty mountain using DSU is probably overkill for this problem. I would expect a good DSU solution in Python to take like 0.1s with those constraints
Which is a lot faster than the time limit of 18s
so I assume the next step is to find the set which contains the current node i'm in (1, or 0 in this case) and then filter all un-weaponzied elements?
Are you talking about 2.?
1
So that would be the max amount of weaponized cities able to be reached from vertice (1)?
wait, i'm not accounting for weight
The weight part comes in from only using edges with weight <= x
so I'd initialize a DSU after running query F
F?
1*
No
If you want to solve 1. using DSU, then do the following
- Initialize a DSU object, and set
self.size = list(has_weapon)
Now dsu.set_size(v) corresoinds to number of weaponized cities in v's connected component
- Go over the edges (u,v,weight) in order from lowest weight, and join u and v in the DSU
oh, so i need to pass has_weapon as an argument to DSU()
Yes
- At the point in time when you've just added all edges with weight <= x, then you can solve a 1. query by calling
dsu.set_size(v)
and if you save the answer after adding each weight, you have effectively computed the answer for all possible w
ah ye. query of type 1. always starts at node = 1
So ye
i.e. you can save a list of (weight, answer) and binary search
DSU = DisjointSetUnion(n, has_weapon)
answers = [0]*(max(e[2] for e in edges) + 1)
for u,v,weight in edges:
if DSU.find(u) != DSU.find(v):
answers[weight] = DSU.set_size(u) + DSU.set_size(v)
DSU.union(u, v)
so i can just compute all answers at once and then check when running the query itself?
basically with slight variations you can either get answers for all nodes for a fix w, or for a fix node get the answer for all w
Two things. The weights can be really large (<=10^9), so you cant just index answers[weight] like that. It could also be that some w never appears as a weight, but appears in a type 1. query
Also you have a bug in your code
You should have something like
DSU = DisjointSetUnion(n, has_weapon)
answers = {}
for u,v,weight in edges:
if DSU.find(u) != DSU.find(v):
DSU.union(u, v)
answers[weight] = DSU.set_size(1)
or
DSU = DisjointSetUnion(n, has_weapon)
answers = {}
for u,v,weight in edges:
DSU.union(u, v)
answers[weight] = DSU.set_size(1)
{4: False, 6: 0, 7: 0, 8: 0, 10: 0, 12: 1, 13: 1, 15: 1, 20: 1}
so this means that I can reach 1 weaponized city if I have a W of 12 or above?
yes
10: should be '2' though 
Yeah i changed that too
I think it's because i should convert the list of booleans into 1 and 0s?
Since size depends on a +=
But that should work though
Eh? where
has_weapon = [c == 'W' for c in input()] should be has_weapon = [c == 'W' for c in input().split()]
Ohhhh 😭 i see , thanks
no idea how it was still making a list with false and true though
c == 'W' is false if c is a white space
Ohh that makes sense
Btw, this doesn't have much overhead right
so I can run it whenever the file is first initialized and then just call answer{} when a query needs it
What you probably should do is to convert answers into a list
and then binary search over it to solve queries
That will make everything take O(log n) per query
Isn't accessing an entry in a dict O(1)?
Or would there be a bottleneck finding the lower weight bound if the specific w isn't found in the dict
Accessing dict is O(1), yes
But you cant do binary search over answers if you store it as a dict
For example, suppose the answers dict is
{4: 0, 6: 0, 7: 1, 8: 2, 10: 2, 12: 3, 13: 3, 15: 3, 20: 3}
and someone asks for query type 1. with weight 11
Then you cant simply look up answers[11], because it doesn't exist
The answer to the query should be answer[w] for the largest w in answers with w <= 11
in other words, w = 10
Something like bisect?
Yes
Think about it like you want to "round down" 11 to the next edge weight (a weight that appears in some edge). Which is the same as the largest edge weight <= 11. This is easiest computed using the bisect module
The answer is simply print(answers[round_down(11)])
weight = int(query[1])
index = bisect.bisect_right(answers_list, (weight,))
if index:
print(answers_list[index-1][1])
else:
print(0)
works, thanks!
hello everyone, im studying DSA so i can start leetcoding, im just lost on how to start
To confirm, when using bisect if the given weight in the query is lower than the first entry in the answers list, it'll refer to the last entry in the list?
Think about it like this. When doing insert sort, if the same value appears multiple times, then there can be multiple possible valid indices to do the insert at.
bisect_left returns the smallest valid index
Ohh i see
bisect_right returns the largest valid index
memo = {}
if query[0] == "S":
city = int(query[1]) - 1
if has_weapon[city]:
print(0)
else:
if city in memo:
print(memo[city])
else:
DSU = weaponizedDSU(n, has_weapon_integer)
for u, v, weight in edges:
DSU.union(u, v)
if DSU.set_size(city) >= 1: # Break out of loop as soon as union found with weaponized city found
memo[city] = weight # Store the result in the memo dictionary
print(weight)
break
how do i shave .4 seconds off this
Don't do the break at the end there
To do more memoization?
Compute that memo thing once
the query has multiple posible cities
can start at any arbitrary vertice
so i have to add to memo once everytime i have a different city
Huh
In the dsu, start by connecting all 1 vertices
Then loop through the edges in increasing order of weight, and join u and v
1 vertices as in union (city 1, x...etc)?
1 vertices are all vertices with weaponds
Ohhh
So connect them with each other, or just union all of those vertice's edges first
Join all weaponized vertices first, before doing anything with edges
what do you mean by join
find a path between any pair in the set of weaponized vertices?
Do a Dsu join/merge /whatever it is called
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a != b:
if self.size[a] < self.size[b]:
a, b = b, a
self.num_sets -= 1
self.parent[b] = a
self.size[a] += self.size[b]
``` this?
I think of all weaponized vertices as essentially the same vertex
Oh there isn't any join/merge in dsu you sent
Use that function, yes
People call it by many different names
I see
if query[0] == "S":
weaponized_vertices = [i for i in range(n) if has_weapon[i]]
DSU = weaponizedDSU(n, has_weapon_integer)
base = weaponized_vertices[0]
for vertex in weaponized_vertices[1:]:
DSU.union(base,vertex)
Like that?
Yes
For each vertex, what you want to know is at which moment does the vertex get joined into the "1 component"
So do the usual for u, v, weight DSU union and check if that vertex is in the 1 component yet?
Kinda
im not sure how that works
You'll need a slightly different implementation of dsu
class DisjointSetUnion_smalltolarge:
def __init__(self, n):
self.parent = list(range(n))
self.components = [[i] for i in range(n)]
def find(self, a):
acopy = a
while a != self.parent[a]:
a = self.parent[a]
while acopy != a:
self.parent[acopy], acopy = a, self.parent[acopy]
return a
def union(self, a, b):
a, b = self.find(a), self.find(b)
if a != b:
if len(self.components[a]) < len(self.components[b]):
a, b = b, a
self.parent[b] = a
self.components[a] += self.components[b]
def find_connected_component(self, a):
return self.components[self.find(a)]
find_connected_component(v) returns a list of the vertices in v's component
weaponized_vertices = [i for i in range(n) if has_weapon[i]]
DSU = DisjointSetUnion_smalltolarge(n)
base = weaponized_vertices[0]
memo[base] = 0
for vertex in weaponized_vertices[1:]:
DSU.union(base,vertex)
memo[vertex] = 0
for u,v,weight in edges:
if DSU.find(u) == DSU.find(v):
continue
if DSU.find(v) != DSU.find(base):
u,v = v,u
if DSU.find(v) == DSU.find(base): # u's component will be merged into the weaponized component
for vertex in DSU.find_connected_component(u):
memo[vertex] = weight
DSU.union(u, v)
How does this work
This keeps track of when a components gets merged into the weaponized component
And at that time, it stores the answer for all of those vertices that just joined the weaponized component
What is vertex in this instance
ops
meant base there
fixed it
All of the already weaponized cities should have ans = 0, right
Mb if I ever offended u
hey if I have a list of list:
[['x1'],['x2'],['x3'],['x4', 'x5'], ['x6'],['x7', 'x8']
How would I check if x1 is also in x2?
I was quite confused about python been slow in CP than java and c++.
So, how much exactly is it slow?? is there a very big margin or just slightly.
Also, as I'm more comfortable at Python than Java.. I have switched to doing DSA in python.. ik its all about concepts.. but should I practice in java or python for placements as well as some sort of CP in future.. ??
CP means Competitive programming..
Or.. I should go with C++??
ping me when replying..
has anyone experience with CT Scans -> Organsegementation?
code
wut
That code is just a class defintion, nothing interesting would happen if you run it
There is a huge difference between CPython and PyPy. I would not attempt doing CP with CPython because it is too slow.
Under ideal circumstances, PyPy is like 3x slower than C++. But it can easily be a lot slower than that.
There are also other cons of using Python for CP other than it being slow. For example, Python can't really handle recursive solutions.
= 95% of everyone doing CP uses C++
It is the safe bet
if only there was a programming language built specifically for competitive programming, with good syntax, and performance, and tooling...
but I suppose no one is dumb and/or bold enough to dedicate their life appeasing everyone 😩
Kotlin tried to brand itself for being that. But then they didnt even bother fixing basic things like default IO being very slow
I think they failed from step 0 being a JVM language with completely unoptimized native backend
don't get me wrong: you can do CP on JVM, but it still puts you behind
There is a guy that tried using Kotlin for the ICPC-finals a couple of weeks ago
He is normally doing pretty well using Kotlin
But from what I heard he really struggled using Kotlin in the finals because of two reasons:
- His teammates don't know kotlin. So they couldnt help him debug code / find errors in the code
- There was some kind of bug in the judge system with Kotlin. Probably no one else had noticed it because litterarily no one else uses Kotlin.
yeah, that's understandable
I have heard similar stories from the guy who uses D
he was discovering interesting bugs in the compiler during some championship..
Never heard anyone use D in CP, other in random challenges where you are forced to use unusual programming languages
I mean, D seems good for CP
you get c++ like syntax
strong metaprogramming with string mixins
good standard library (with built-in fft!)
and so on
Does it have fast built in IO?
I think it's the same as C?.. I may be wrong
C is smart about its built in IO
It notices if stdout is a file or not. It uses a buffer for stdout only if it is a file.
In CP that is nice, because that avoids unnecessary flushing of stdout
https://codeforces.com/blog/entry/126390?locale=en there is this
im pretty low rated and ime ive never TLEd a question because of choosing python
its only been for having a suboptimal algorithm
it looks promising, but requires either the lack of OCD to put it at the top of your program and not be bothered and don't hit autoformat accidentally, or a custom preprocessor (also takes 7 kb of program size... but I have not had problems with it yet)
it gets worse though once you enter the datastructure heavy territory
like segment trees in python are tough
in my expereience, at least
Also graph problems
@regal spoke will tell a lot more 😂
yeah, also that: you get no dfs, basically
well, not "no" dfs, but, you know, less dfs
I think there is another side to performance: knowing "yep, I can probably survive 10^7 binary searches" is just nice... C++ performance is way more predictable that CPython/PyPy to me.
i can believe that
https://codeforces.com/contest/1292/problem/C here is a good one if you want a challenge
I learned of this problem because the problem creator claimed it was "impossible" to solve in Python
Turns out it wasn't impossible
div 1 C sounds way beyond my paygrade 💀
@regal spoke understood.
I will switch to C++ very soon.
most material on CP also assumes you use C++ and have their code in C++
guys is neetcode dsa and system design course is best for me
hello
I want to create a simple program that can simulate electrical circuits, though right now I have no clue where to start. I checked some existing projects but those have very large code bases and I wasn't able to understand anything
for starters i want to find a suitable data structure for storing the electrical components and the connections between the components (nodes)
No
If ur indian do striver
but i already purchased it(pirated)
Pirated? True indian
Yes u can do neetcode if ur doing it in python
pirated given by a german
It doesn't matter. An indian always looks for pirated options before buying a course and doesn't pay unless he absolutely have to
I am an indian as well
so can you suggest me any web sites for python bignner level questions
Hackerrank
Hackerrank python
It's very language specific
Nd not for dsa
But do that first
Before moving to doing dsa with python on leetcode
nah bro listen
If u want to do some more language specific questions u can go to codewars as well
i say i just finnish my python so i want to solve some questions
@wispy nacellewhat are you doing in studies??
i am passed my 12th at 2022-23 now
currently i am doing nothing
same me too..
In which college / course??
or dropper?
i am droppper
🤣 yes
%ile??
85
Ohh..
are you new at python or you know some basics
ohk i am bignner lol
koi ni bhai, ho jayega
just completed learn what matters series in python
yup
you can search it on you tube sheryians coding school python learn what matters series
nah my cutoff is not clear
@urban tundra
No..
check friend request
working on my final and maybe a bit confused about something time complexity related. we're doing a study on an algorithm that iterates over a sorted list, and normally the algorithm is O(n^2). there's an optimization we can apply that ends the algorithm once we iterate to a positive integer from our outer loop. would that mean the time complexity is still O(n^2) but theta(n^2 - nm) where m is the number of positive integers?
or am i misunderstanding theta
would that mean the time complexity is still O(n^2)
Yes
*but theta(n^2 - nm) *
Not sure yet, I also need to think on this, theta is goooood
Yes correct!!
see every function f(n) would always be theta(f(n)),
here confusion is regarding whether we can say if f(n) is theta(n^2) which depends on whether you consider m as a variable or not
wsp sussys
yeah I decided to avoid the confusion of that and just say that the algorithm is O(n^2) but use n^2 - nm to approximate the steps the algorithm takes
how do encodings like utf8 store text? i see it described as ‘variable length’ which indicates to me that not every character has to take up the full 4 bytes (now that i think of it, why is it called utf-8 if it only uses 4 bytes), but then how do you know what bytes represent a full character?
like cause you could have 4 bytes be 4 1-bytes chars, 2 2-byte chars, a 3-byte char and a single 1-bit char, etc
you look at first bits and see how much you need to eat to get a single character
it's called utf-8 because it 8 bits per character at least
* technically last bits of the first byte, but whatever
so literally every encoding ???
im sure you could do it with less than a byte using bitmasking but you'd barely be able to display any characters
if you split it into nibbles that's only 16 options
lmao
how do they deal with ambiguity though? do they just reserve some slots of each byte that cant be used for determining which character (in the byte) iti s?
Need some opinion
Im watching this tutorial for DSA, as I am a beginner and don't know DSA
Is this playlist good? Good amount of information I need? So I can actually do problems?
Or is there like more parts that I need to cover
I haven't seen the tutorial. Why not get a nice book?
There are some good resources in the pinned messages.
Im doing free
Ah. the MIT course in the pinned messages is free.
ok
utf-16 encodes each character in 2 bytes
Huffman (and other compression methods) encodes each character in variable number of bits
Look at the table again. You start with first byte - it's definitely a first byte of some character. You look at it first bits and see how long that character is. Let's say it's 3 bytes. You then read the next 3 bytes, and extract the meaningful bits out of them to get the codepoint. Then you know that fourth byte is a beginning of the next character (because the three bytes before is the first character, and the next one immediately follows), so you check how many bytes does the second character contains. Extract bits, get the codepoint. And then repeat until the whole encoded stream is exhausted
In fact, in utf-8 it's even easier. Look at any byte. If it starts with 0 - it's a one byte character. If it starts with 11 - it's a beginning of multibyte character. If it starts with 10 - it's a continuation of another character. You can go to the left and to the right to get the remaining bytes. Or slide forward, until you see the beginning of the next character.
could someone help me please at #1238796495340310548 ?
Why doesnt this code work?
Hey guys, so I havent done DSA in a bit, any good quick resources to refresh my mind
a fun library would be moviepy
Geeks for geeks has a decent DSA course that you could work through: https://www.geeksforgeeks.org/complete-guide-to-dsa-for-beginners/ or https://www.geeksforgeeks.org/complete-roadmap-to-learn-dsa-from-scratch/
You could also search: good resources to learn dsa site:reddit.com to find some good threads.
Most of the quality resources you will find double as a course and a reference
does anybody here do t levels course
cus i really need help asap
and the esp is soo close
starts tommorow
I want to create a simple program that can simulate electrical circuits
what will be a suitable data structure for storing the electrical components and the connections between the components (nodes)
i thought a graph might work but in parallel wire connections more than 2 components will reference one node, in a graph thatll be like one edge connecting to more than 2 vertices
you can use a graph, where both components and wires are vertices
!cban 708387638650077357
:incoming_envelope: :ok_hand: applied ban to @wintry fossil permanently.
holy moly
@ebon garden #c-extensions
does any1 have an intuition for the 3Sum leetcode problem?
once you've fixed 2/3 of the triplet, you know what the last number must be and only need to find out whether it's in the array
some ways of figuring out whether its in the array are faster than others
(Not sure if this is an appropriate topic...)
How to make an abstract generic class attribute?
The idea is to force the child class to define it while the base generic class handles this attribute to initialise some internal logic.
Something like this (but it doesn't work):
T = TypeVar('T')
class A(Generic[T], ABC):
@abstractmethod
some: Iterable[T]
def __init_subclass__(cls) -> None:
some_logic(cls.some)
class B(A[int]):
some = [1, 7, 90]
b = B()
https://leetcode.com/problems/path-with-maximum-gold
im interested in the upper bound on the number of paths starting from a given point in this setting
i feel like the worst case is when the 25 gold cells form a 5x5 subgrid and you start from a corner, is that true/can we prove that
if thats true then there's this bound
you want what? number of paths from top left to bottom right in a rectangular grid?
m x n grid, 25 of the cells have gold
for what (arrangement, starting point) pair is the number of paths maximized
you can only travel from one gold cell to another and you can't revisit a cell
hmm, yeah this is a non-trivial problem
what will be the edges?
connections between stuff
for example, this circuit can be modeled as just two nodes (one before and one after the resistor), each node representing an entire section of conductor (along with the voltage is fixed). These two nodes are connected with two edges - along one edge the resistance is fixed, along the other the voltage difference is fixed.
this is enough info to solve the circuit.
(Have you ever used Spice, by the way? It'd be a major source of inspiration.
oh, thanks for the explanation. understood
nope but ive got some inspiration from the web based circuit lab
I want to detect squares on my screen and return a list of coordinates for each square.
I use color pixel detection(RGB) to detect the 2 squares on the images:
def find_pixel_coordinates(target_color, image):
screenshot_array = np.array(image)
indices = np.argwhere(np.all(screenshot_array == target_color, axis=-1))
if len(indices) == 0:
return []
coordinates = [(idx[1], idx[0]) for idx in indices]
return coordinates
The function returns all green pixels found in the image:
[(317, 127), (318, 127), (319, 127), (320, 127), (307, 128), (308, 128), (309, 128), (310, 128), (311, 128), (312, 128), (313, 128), (314, 128), (298, 129), (299, 129), (300, 129), (301, 129), (302, 129), (303, 129), (304, 129), (305, 129), (292, 130), (293, 130), (294, 130), (295, 130), (321, 130), (292, 131), (321, 131), (293, 133), (322, 133), (293, 134), (322, 134), (294, 136), (323, 136), (362, 263), (331, 264), (331, 265), (363, 265), (363, 266), (332, 267), (332, 268), (364, 268), (332, 269), (363, 269), (364, 269), (358, 270), (359, 270), (360, 270), (333, 271), (353, 271), (354, 271), (355, 271), (333, 272), (348, 272), (349, 272), (350, 272), (343, 273), (344, 273), (345, 273), (334, 274), (338, 274), (339, 274), (340, 274), (334, 275), (335, 275)...]
How do I detect which x,y coordinates belong to which square?
This example isn't very useful I think since it's very idealized (you could solve this one by just e.g. floodfilling the image and excluding the outer region). For a solution that'd work in a real environment (where you have tons of stuff on the screen, including many green pixels and even closed regions that aren't squares and shouldn't be detected), try something like cv2's contour detection.
The only green pixels on screen are those of the squares. Since there is always a white distance between the square, then why can't I just look at the absolute differences? And determine when a new square begins?
I wanted to show the entire output but it's too long
The only green pixels on screen are those of the squares
If you can rely on that, then I'd domask = screenshot_array == target_colorand then apply cv2'sconnectedComponents. For this image, there's three connected components - the internals of the two squares, and the external one. The external one can be determined by e.g. looking at what component some boundary pixel belongs to. All other components are the internals of squares, which is what you're looking for.
Thanks will try 🙂
or just flood fill starting from green pixels
I don't see how that'd help
that finds the squares separately
but... how'd you direct the floodfill inwards and not outwards?
Hey guys I am new to this server and I came here to ask help on the flowchart I created and i wanted to see where I can improve on it as most of it is all input/output
This is my flowchart
I need feedback to see what i should improve and how I should structure it
maybe I misinterpreted what is the square in that image 🥴
I assumed the outline
ah, makes sense. I think that person wants to detect the rect (location, width, height) knowing the outline.
My birthdays trmw btw, looked up some object and getter/setter stuff
You should look for the difference between one pixel and the neighbor
If you know you're looking for exactly that shape, you actually only need to look for the four corners
Which can be defined by a 3x3 mask
Very simply, you can slide the mask over every pixel and wait for the match. That gives you the corner
I can make it shorter
But when the program will be created the user would have input the names/teams
I never thought of the loop I'll do that and I'll show you
Hello I am new to python and am trying to figure out why I can't find my self object in my method
you method implementation is on the same indentation level as the class, not as the function. In other words, your problem reduces to:
class Something:
def genres_string(self):
""" string """
self.something # wrong level of indentation
(btw I would highly recommend asking questions like this in #1035199133436354600 or #python-discussion, as this chat is for algorithms and math and such. It's likely to be answered anyway, but it might take longer)
oh okok thank you
Any1 have a good rationalization on how to deal with linked lists in python?
def is_leap(year):
if year % 4==0:
if year % 100!=0 or year % 400==0:
return True
else:
return False
year = int(input())
print(is_leap(year))
input = 2100
output = none
expected output = False
can anyone help mer here
@young tangle @buoyant monolith help me here
try walking through the code in your head for that input
what path is taken?
actually im solving rookie level python question from Hackerrank and I'm stuck in this Leap year question
sorry im newbie to programming so i'm unable to undertsand what you're asking here
walk through the code by hand, for input 2100 what happens in the code?
which branches of the ifs are followed?
i.e. what path is taken through the code
I'm using nested if else here
The year can be evenly divided by 4, is a leap year, unless:
The year can be evenly divided by 100, it is NOT a leap year, unless:
The year is also evenly divisible by 400. Then it is a leap year.
this are the conditions
that's not what I asked
expected output was False
Your code doesn't exactly reflect the conditions required for a leap year
again, not what I asked, let's start here, what happens for input 2100?
def is_leap(year):
-> if year % 4==0:
if year % 100!=0 or year % 400==0:
return True
else:
return False
1st if condition is to check if it is divsible by 4 or not
and the result is?
it is divisble
so we enter the if body.
ok, now what?
def is_leap(year):
if year % 4==0:
-> if year % 100!=0 or year % 400==0:
return True
else:
return False
in nested if condition is to check if year is also divisble by 100
and if it is divisible than output should be false
what is the answer for the input 2100 we're looking at?
False
ok, where in the code do we end up now?
2100 is divisble by 4 and also divisble by 100
so output should be "false" here
but it shows "None"
- The year can be evenly divided by 4, is a leap year, unless:
- The year can be evenly divided by 100, it is NOT a leap year, unless:
2-1) The year is also evenly divisible by 400. Then it is a leap year.
this might help
what happens after that?
please, just focus on the specific case of 2100
I'm trying to help you figure out the problem with the code on your own
okay
the condition here is false, what happens? what's the next line that executes?
there is no else, so we just continue, we were in the if branch of the outer if statement so we don't trigger that else
we end up at the end of the function
def is_leap(year):
if year % 4==0:
if year % 100!=0 or year % 400==0:
return True
else:
return False
->
which will implicitly return None
understood
so there are a few ways to solve it
this path of execution needs to end up returning false
you could put a return False at the end but that ends up quite messy
yes
this is one option
def is_leap(year):
if year % 4==0:
if year % 100!=0 or year % 400==0:
return True
else:
return False
else:
return False
```though an if-else returning True/False can be simplified into just
```py
def is_leap(year):
if year % 4==0:
return year % 100!=0 or year % 400==0
else:
return False
```which ends up fairly neat
trying to walk through the code for some input you know misbehaves is an important debugging technique
ohh okay
can you explain the working of your 2nd code
if year mod 100 is not equal to 0 or year modulo 400 is not equal to 0 then it returns true
if year modulo 4 is equal to 0 and year modulo 100 is also equal to 0, it returns false (since one of the conditions ot get "true" is year % 100 != 0)
and if year modulo 4 isnt equal to 0 then it just prints false
because its not a leap year
the last code is the same as the second to last one, just I replaced the kinda silly logic of "if thing is True return True, else return False"
into just "return thing"
i see
okay thank you i got it
okay with 2100 it satisfies 1st condition but it doesn't go with nested because 2100 was evenly divided by 100 but it is not evenly divide with 400 which conflicted my nested if condtion
if you put 2100, then its not a leap year
because its divisible by 100
the issue wasn't the logic
!e
def is_leap(year):
if year % 4==0:
return year % 100!=0 or year % 400==0
else:
return False
print(is_leap(2100))
@gentle cliff :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
but the code implementing the logic
so if i just merge my both of condtion making it 1 and getting rid of excess it will be sucess, right ?
like
def is_leap(year):
if ((year % 4==0) and (year % 100!=0 or year % 400==0)):
return True
else:
return False
year = int(input())
print(is_leap(year))
this
you forgot to add != after 400
but otherwise i think its okay
!e
def is_leap(year):
if ((year % 4==0) and (year % 100!=0 or year % 400==0)):
return True
else:
return False
year = 1978
print(is_leap(year))
@gentle cliff :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
seems like it works
yes all test cases are succes
thanks everyone
def is_leap(year):
if year % 4==0:
return year % 100!=0 or year % 400==0
else:
return False
print(is_leap(2100))
can we write conditions in return statement ??\
dont do this:```py
if x: return True
else: return False
do this instead: ```py
return x
I am wondering if there is any type of maze, path, system where performing a BFS is impossible?
Background: I am framing a question from a pedagogical perspective and rather than explicitly tell the problem-solver to find the path via DFS, Ideally, I'd like to create a scenario where if they attempt to use BFS it will either fail or take an unreasonable amount of time.
I have managed to do the opposite so far by creating a large maze with loops, thereby causing a DFS approach to not result in the shortest path but rather just the first path it encounters. But I cannot conceive of a scenario where doing BFS would be impossible/incorrect.
dfs; shortest path
dfs won't optimally find the shortest path in the first place though (you can, but basically have to explore every path)
I know this. It's not what I asked
ok I'll just assume you got that sorted then
one difference between dfs and bfs is the memory use, bfs will store all nodes that are the same distance to the origin at the same time
so if you had a very "wide" graph (e.g. many same-distance nodes, but not very deep), you might get the situation where bfs runs out of memory but dfs runs fine
So you're saying there is no pathfinding scenario that cannot be solved with bfs?
not really, imo at least bfs is a more natural choice than dfs if you're asked to find the shortest path
by design it will visit the nodes with smaller distances first, dfs doesn't guarantee that
I suppose I'll have to influence the choice of DFS in the wording of the question then
Subliminal messaging 😝
dijkstra's algo is also really bfs-y (with the heap implementation), and that's like one of the path finding algorithms
thanks
dfs, bfs and Dijkstra are basically the same algo
with the only difference being the data structure used
respectively: stack, queue and priority queue
guys how do we make a child class?
class Employee:
def init(self,HourlyPayp,EmployeeNumberp,JobTitlep):
self.HourlyPay = HourlyPayp
self.EmployeeNumber =EmployeeNumberp
self.JobTitle = JobTitlep
self.PayYear2022 = [0.0]*52
def GetEmployeeNumber(self):
return self.EmployeeNumber
def SetPay(self,week_nop,hour_workedp):
pay_of_week = hour_workedp*self.HourlyPay
self.PayYear2022[week_nop-1] = pay_of_week
def GetTotalPay(self):
total =0
for i in range(len(self.PayYear2022)):
total = total + self.PayYear2022[i]
return total
I have dont this so far
I have to do this
class Employee:
def init(self,HourlyPayp,EmployeeNumberp,JobTitlep):
self.HourlyPay = HourlyPayp
self.EmployeeNumber =EmployeeNumberp
self.JobTitle = JobTitlep
self.PayYear2022 = [0.0]*52
def GetEmployeeNumber(self):
return self.EmployeeNumber
def SetPay(self,week_nop,hour_workedp):
pay_of_week = hour_workedp*self.HourlyPay
self.PayYear2022[week_nop-1] = pay_of_week
def GetTotalPay(self):
total =0
for i in range(len(self.PayYear2022)):
total = total + self.PayYear2022[i]
return total
class Manager(Employee):
def __init__(self,BonusValuep):
self.BonusValue = BonusValuep
super.__init__
How is this??
I am trying to parse a dict like structure to dict. However I am stuck where key has list indices e.g. a[0][0] , this should create a list of values. Here is the code that I am working on: https://collabedit.com/mrahk (If this doesnt work, let me know I will create a paste)
!paste
If your code is too long to fit in a codeblock in Discord, you can paste your code here:
https://paste.pythondiscord.com/
After pasting your code, save it by clicking the Paste! button in the bottom left, or by pressing CTRL + S. After doing that, you will be navigated to the new paste's page. Copy the URL and post it here so others can see it.
Do you still need help?
i found this code i did a good long time ago for converting to a quaternion, do you guys know if there's a simpler way to do this
oh wait i can do the cos and sin just once for each but it'll take a lot more variable declarations
or only 6 actually nvm
hai guys
idk if it's easier, but feels like it could be composed into three quaternion multiplications
one rotation in each of X,Y and Z
why the quaternion a list not tuple (or custom class? could define funny operator overloads) im sad type safety
!eval 3.12.3 ```python
def is_leap(year):
if year % 4==0:
return year % 100!=0 or year % 400==0
else:
return False
print(is_leap(2100))
@ivory sun :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
Okay, okay. What do you have to do?
What's the question
Im on anew question now
class Card():
def __init__(self,Numberp,Colorp):
self.__num = Numberp
self.__Color = Colorp
def GetNumber(self):
return self.__num
def GetColour(self):
return self.__Color
def ChooseCard(ValInput):
CardsChosen = [0]*5
if (ValInput < 0) or (ValInput > 30):
return -1 #Value is not in range
if UserCardAttempt == 0:
return -2 #User has used up all his attempts
for i in range(30):
if ValInput == My_1D_Array[i]:
return i #Value has been found
UserCardAttempt = UserCardAttempt - 1
ValGuess = input("Your attempt was wrong try again.")
return ChooseCard(ValGuess)
#Main
My_1D_Array = [Card(0,"")]* 30
UserCardAttempt = 5
try:
file = open("CardValues.txt", 'r')
for i in range(30):
no = int(file.readline())
clr = file.readline()
My_1D_Array[i] = Card(no,clr)
except:
print("File not found")
I have done this so far
The rest I think is ok im at part (d)
def ChooseCard(ValInput):
CardsChosen = []
if (ValInput < 0) or (ValInput > 30):
return -1 #Value is not in range
if UserCardAttempt == 0:
return -2 #User has used up all his attempts
for i in range(30):
if ValInput == My_1D_Array[i]:
print("Your value has been found")
CardsChosen.append(ValInput)
return i #Value has been found
UserCardAttempt = UserCardAttempt - 1
ValGuess = input("Your attempt was wrong try again.")
return ChooseCard(ValGuess)
This is the procedure but I think im messign up somehwere
# your code goes here
print("Like this")
Do this for embedding code
Hmm, I see
okok
ohhh
those ^
def ChooseCard(ValInput):
CardsChosen = []
if (ValInput < 0) or (ValInput > 30):
return -1 #Value is not in range
if UserCardAttempt == 0:
return -2 #User has used up all his attempts
for i in range(30):
if ValInput == My_1D_Array[i]:
for y in range(len(CardsChosen-1)):
if ValInput == CardsChosen[y]:
ValGuess = input("Your attempt was laready ocne found")
return (ChooseCard(ValGuess))
print("Your value has been found, try to find another")
CardsChosen.append(ValInput)
return i #Value has been found
UserCardAttempt = UserCardAttempt - 1
ValGuess = input("Your attempt was wrong try again.")
return ChooseCard(ValGuess)
I think you should declare a var that stores the cards selected outside of the ChooseCard and then modify the ValInput to verify if it is already in the list of the selected cards
And if the card has not been selected, then you add it to that list
And if it has been selected, then you ask the user for another one
I don't know if I explain myself xd
The main issue I have with these things is that its hard for me to understand what the question is asking 😭
Im gon try to redo the whole thing and then see if that works better
I have done something not sure if that is fine
def ChoosenCard(ValInput):
if (ValInput < 0) or (ValInput > 30):
return -1 #Value is not in range
for i in range(30):
if ValInput == My_1D_Array[i]:
return i
#Main
CardsChosen = [] #array which will have the values which have been found already
for i in range (5):
if len(CardsChosen) < 4:
ValReq = input("Input a value to search (in the rnage of 0-30)")
Cardreturn = ChoosenCard(ValReq)
if Cardreturn == -1:
print("The value you have entered in not in the range try again")
else:
for y in range(len(CardsChosen-1)):
if ValReq == CardsChosen[y]:
print("You had already previously found this value try again")
print("Your value has been found at index {}".format(Cardreturn))
else:
print("you have used up all your attempts")
This the other part 🤔
im considering making a quat class, idk them super well tho
can anyone help me here? i cant run .py Files
complex numbers on crack
and you lose stuff like x y = y x when going from complex numbers to quaternions
ye im aware of that
just not all the specifics
oh huh i think i maybe got an algorithm i was working on for a couple hours to work
trying to group up pixels into rectangles, so as to more easily fill areas
i gave it this image as input, and it did this
i think it still needs some work tho
oh that's why
that orange rectangle kinda softlocked itself by going into that little divot, since it couldnt expand anymore
the algorithm basically has 4 options, expand right, expand down, expand left and expand up
i might remove the second two if they turn out not to be useful but it seems fine for rn
but it basically checks the new pixels in the area and if it's not occupied and they're all the same color, it expands to that area, and keeps trying to until it hits a dead end
after it hits one, it tries a different direction until it manages to expand again (resetting its amount of attempts to expand) or until it runs out of attempts
so there was this interesting video recently
This greedy mesher is blazingly fast. Written with Rust and Bevy, using clever bitwise operations we can generate chunk meshes, an average of 0.000195 per 32x32x32 mesh!!!
This mesher blows most culled meshers out of the water, and I want to teach you the "secrets" of how to implement this for own voxel engine.
There are 2 algorithms we'll explo...
the key part of this is the same as your problem
nvm i broke it
i fucking hate this algorithm
specifically write code to make it NOT OVERLAP
it overlaps
im just deleting this entire thing
i think the term for what i want specifically is Rectangular Image Separation or something like that
lemme check it out
oh i think i see why my implementation was failing, they are iterating through coordinates to choose the starting point
YES THERE IS VSCODE
ok i got it to work
its the same general idea but i rewrote it from the ground up
as a bonus it's like a gajillion times faster
the hue is showing which quad is being drawn
the image is just something i scribbled on, to test
Hey
HI, I have a string like this {a[0][0][0] : 'b'}, I want to create a list from this which would be { a : [ [ ['b'] ] ] }
I am trying with regex: list_pattern = re.compile(r"[([0-9]+?)]") , not sure how to create the lists and put data into it.
What would be the best book for leanring ds and algorithms? I was looking at CRLS and I am fairly certain that would be best. Any suggestions that would be better than that one?
I am in school and wondering if anyone knows about flowgorithm?
you want it to be nested?
btw thanks for this, i already mostly had this but it gave me the idea of how to choose starting points
np, glad my memory clogged of random programming stuff ended up helpful :P
heres a sc of the code btw
i had an issue with it 'hanging' for a while after it generated all the necessary quads, but i managed to fix it when i realized i never implemented a 'cut-off' for when there was no more space for them
and yeah idk if the nested function is cursed but its a hall of a lot cleaner than what i did before (i had the 'fail check' code for literally every condition individually)
im sure i could condense the multiple move types into one block but i dont think its worth it
also this script represents the first time i seriously used the debugger and breakpoints
unfortunately i couldnt debug some of it (like the 'hanging' issue since it took fucking ages with the debugger on lmao
btw, some specific questions related to it, 1. is there any efficient conversion from the image grid in pillow (i.e im.load()) to some other datatype? ideally this algorithm should be able to work on any 2d-array like object
and also, is there a good datatype for destructively reading something? one way that that one video mentioned increasing performance is by deleting the stuff to work on so you don't have to 'revisit' it, i could just write over the existing image grid but that'd probably be slower than just doing it like im already doing (i add all the positions that i visit to a set, and check if new coordinates are in that set)
in the impls in the video the solution to doing these efficiently is bit math
yea i saw that
that won't work for what i'm doing though
because a pixel can be any color
the reason the bitmath works is because they reduce it to binary and only have a few types of voxel iirc
how many unique colors are you working with? 
i mean theoretically, thousands
it just takes in an image and segments it
for a big enough image, millions but i think the segmenter would have a very hard time doing that
at that point segmenting doesn't help you anyway
yeah
but even in a small image you can potentially have a couple hundred
also maybe i should add a chroma key feature..
before, i had a simple alpha threshold option, so as to not bother creating useless transparent quads, but i think it'd be better to simply blacklist some colors
also just checked, the 'pixel grid' object i mentioned is properly called a PixelAccess object
maybe i could work with numpy arrays but afaik, numpy arrays excel at doing big operations, not lots of little ones like i'm doing here
numpy arrays and throwing numba at the problem is probably not a bad idea
assuming you can boil things down to fairly raw operations
and when doing that you might win a bunch from modifying the underlying array instead of keeping a set
im mainly doing this for things like besiege where im trying to make stuff out of the blocks
specifically the surface blocks which are very customizeable but super laggy
so like i can do it by just making each one at each pixel but it gets unbearable very quickly (like 75x75 with a transparent background was enough to instantly crash the game when i tried using the move tool)
so ideally i'd like to instead of having a bunch of them for each pixel, i just group them up and make big ones instead
god damn it the algo overlaps
fixed it, my 'passed checks' code was improperly placed so it went ahead and expanded it if even a single pixel was acceptable (since it was in the loop
for transparency i had to add it in the start selection code as well as the checks code, otherwise it just started quads on transparency, none of the checks passed,so transparency just ended up as a bunch of single pixels
Yes. Asked the same question in stackoverflow: https://stackoverflow.com/questions/78497151/parsing-dict-like-structure-to-dict
what's the actual semantics of -? 
noop, according to their example
guys I need a help
im mind___ over this
class Node:
def __init__(self, value):
self.value = value
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def __str__(self):
temp_node = self.head
result = ''
while temp_node is not None:
result += str(temp_node.value)
if temp_node.next is not None:
result += ' -> '
temp_node = temp_node.next
return result
def append(self, value):
new_node = Node(value)
if self.head is None:
self.head = new_node
self.tail = new_node
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1
def part(self , val):
temp = self.head
prev = None
while temp is not None:
if temp.value < val:
this_node = temp
temp = temp.next
this_node.next = self.head
self.head = this_node
else:
blah = temp
temp = temp.next
self.tail.next = blah
blah = self.tail
blah.next = None
The prblm is coming in the function PART() , so u dont need to check anything else (ur wish tho)
The Aim : Write a code to partition a linked list around a value x , such that all nodes less than x comes before all the nodes greater than x
there was not much of help in the doubt section so I thought of maybe asking it here
f = LinkedList()
f.append(12)
f.append(3)
f.append(9)
f.append(15)
f.append(13)
print(f)
f.part(10)
print("yahoo")
print(f)
```
Im trying to run this
tho it never prints after using PART() func , which ig means that a loop is forming
tho I would appreciate very much if someone can help me to solve this
Print inside the for loop so that you can see what's going on
that's a Java problem, not really related to Python. you're probably better off asking in a space that is dedicated to Minecraft
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
# Base case: If the root is None or the root's value is the target value
if root is None or root.val == val:
return root
# If the value to be found is less than the current node's value, search in the left subtree
if val < root.val:
return self.searchBST(root.left, val)
# If the value to be found is greater than the current node's value, search in the right subtree
else:
return self.searchBST(root.right, val)
not understanding how this code also returns the subtree rooted at a given value
it seems to me that it could only return a single value
i think i'm not understanding this line:
def searchBST(self, root: Optional[TreeNode], val: int) -> Optional[TreeNode]:
it is returning a TreeNode object which itself is a tree
ooohh
the left and right attributes in TreeNode are tree nodes (or None)
yeah, it is returning a single value
a single object?
looking for help with 374 guess number higher or lower
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
# 1 if num is lower than the picked number
# otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
if n == 1 or n == 2 or n == 3:
if n == 1:
return 1
first_guess = guess(2)
if first_guess == 0:
return 2
else:
if first_guess == 1:
return 3
else:
return 1
first_guess = n//2
ans = guess(first_guess)
if ans == 1:
for i in range((n//2),1,-1):
ans = guess(i)
if ans == 0:
return i
if ans == -1:
for i in range((n//2),n):
ans = guess(i)
if ans == 0:
return i
how am i getting a null out of this code
hm i'm not sure i agree with the categorization of some of the leetcode difficulties. i just solved a medium that was much simpler than the above problem
i'd guess certain problems are more easily solved in Python vs. other languages
it will never be accurate because different people will have learned different topics when they tackle a problem
could someone please explain to me why the program is outputting "None" after each message??? Any help appreciated

here is a more complete screenshot of the whole thing
what even is this attempt?
clearly the intention is a binary search
that's likely you returning None from the function
and yes there is a path where you do that
I'm also very confused why you special case some small sizes
@haughty mountain can you help me with the logic
just read about binary search
like, the idea of looking at the midpoint isn't wrong
but you need to take that further
also, LC 238 product of array except self is super interesting, i'm thinking it'll require a list comprehension or generator somewhere. the catch is you have to do it in O(n)
seems fairly trivial
idk how to implement the logic recursively
how would it be done if it was sum instead of product?
you'd add them all together and subtract the value at that location however, they forbid you from performing division, an added caveat
so in other words you cannot simply multiply everything in the array and then divide out that integer at that location
that's dumb
why?
with allowed division there is already gotchas
it's a neat problem bc of these constraints, i think
it's still a pretty trivial problem
medium LC problems are not yet trivial to me 😅
some easys are not as well, e.g. the number guessing one
the sum and product version of this problem is the same if division/minus is disallowed
🤔
well not same, but same approach works
only the operation differs
for sum you can just compute two cumulative sums, one from the left and one from the right
and then the problem is basically solved
perhaps we should return to the guess number higher or lower first, if you wouldn't mind
i moved toward an approach where my guess becomes my guess // 2 on the lower side and myguess + n//4 on the upper, but i'm well aware this will not work
i'll read on binary search
no i don't get it
i mean i get binary search but not how to make it work with the guess API that is part of problem 374
what's the difference between this and a regular binary search?
this takes n, not multiple parameters like array, high, low
really have no idea how to make it work within their existing guess() and guessNumber() functions
Is using bitflags a bad idea? Yesterday i ran into the problem of needing 3 boolean arguments for roughly the same thing (it was to change the “mode” of an input value between acting as if it was a single key or a string, but i needed that to be able to be changed for 2 inputs and an output) and i just said ‘screw it’ and made it a int, then bitmasked the individual flags from it
like is there something specific for this, or should i use something else, or what
Bit flags can be appropriate in some circumstances. E.g. python's re module uses flags to change certain things about how the regular expressions are interpreted. If you are going to use flags though I recommend using enum.Flag: https://docs.python.org/3/howto/enum.html#flag
kk
E.g. ```py
class Perms(enum.Flag):
READ = 4
WRITE = 2
EXECUTE = 1
does that allow combining them i.e WRITE | EXECUTE
Yep!
kk
i don't understand the leetcode situation at all. in this problem there is a notion of n but i don't know where it comes from or which functions have scope of it
this is leetcode 374 Guess Number Higher or Lower
trying to go in this direction:
class Solution:
def guessNumber(self, n: int) -> int:
myguess = n // 2
ans = guess(myguess)
if ans == 0:
return myguess
elif ans == -1:
low = 1
high = myguess
newguess = high // low
return guessNumber(newguess)
elif ans == 1:
low = myguess
high = n
newguess = high // low
return guessNumber(newguess)
guessNumber(n)
NameError: name 'guessNumber' is not defined
^^^^^^^^^^^
return guessNumber(newguess)
Line 28 in guessNumber (Solution.py)
^^^^^^^^^^^^^^^^^^^^^^^^^
ret = Solution().guessNumber(n)
Line 50 in __helper__ (Solution.py)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
guessed_number = __DriverSolution__().__helper__(n, pick)
Line 70 in _driver (Solution.py)
_driver()
so? the question you ask in a binary search doesn't really have to do with an array per se
you're just asking "is the value at this point >, < or =?"
which is exactly what the function given to you lets you ask
Is there any obvious misunderstanding of the leetcode solution class you’re perceiving that I may have
no, more a misunderstanding of binary search
you don't need an array to do binary search
let's assume the number you're looking for is between >=0 and <n
if so you start with an interval [0, n) where the value could be
you check the mid point
- if the value is lower you know the new relevant interval is [0, mid)
- if the value is greater you know the new relevant interval is [mid+1, n)
- if it's equal you have found the number, done
in the first two bullet points you now have a smaller instance of the same problem
so repeat the same procedure
I’m comfortable with the binary search logic just not implementing it recursively and in leetcode and without an array
I’ll try again tomorrow. I see some obvious mistakes in my above code
I don’t understand how to get the middle of the upper half of the array
The lower half you can always divide in two again from the midpoint
But if you tried to do the opposite (multiply by 2) to get the upper half array midpoint you’d instead just get n
I’m noticing that if I take the existing midpoint and add it to n (total length of array or in this case range of guesses) I could then divide by 2 to get a mid point
Of the upper half
why is that a class anyway
because leetcode
alright i got a working binary search going locally but it takes array, low, high, and search value as arguments and returns the index of the search term
so now i just need to shoehorn this into leetcode and get it working
ok so i actually cannot use an array to solve
you dont even need recursion, literally just a for loop would work
this is a good opportunity to learn recursive binary search tho
the cases aren't different
fair enough ig
you have a lower and upper bound, you check the midpoint, you update the bounds based on the result
repeat
yeah im seeing that now
i see the logic that i stumbled upon e.g. the existing mid plus the highest value // 2 is the mid of the upper half
mid becomes new low
et cetera
nailed it
every query you do here effectively splits the ranges in three
[low, high)
into
[low, mid), mid, [mid+1, high)
ty for not helping me, forced me to learn it on my own. plus it was bothering me all day so i refused to rest until i got it 💪🏻
you can write functions within the Solution class guessNumber method that comes predefined for you
here is the answer:
# The guess API is already defined for you.
# @param num, your guess
# @return -1 if num is higher than the picked number
# 1 if num is lower than the picked number
# otherwise return 0
# def guess(num: int) -> int:
class Solution:
def guessNumber(self, n: int) -> int:
x = n
def bin_search(low, high, x):
if high >= low:
mid = (high + low) // 2
if guess(mid) == 0:
return mid
elif guess(mid) == -1:
return bin_search(low,mid-1,x)
else:
return bin_search(mid+1,high, x)
return bin_search(1,n,n//2)
🥳
@signal canyon it's because i can add more than 1 language package
i wanna make it easy to maintain
when adding
if i don't use importlib
it would becomes a spagetti code
sorry for confusing the tops
*topics
okay so i feel like i'm gonna repeat this many times:
}
you guys probably knows the json thing that i forgot
how do i do that?
my plan here is to also allows cross stuffs
like bi for text
ils for ||text||
until i get into biuls
tha\t makes
||Hello World||
any hints on leetcode 238 Product of Array Except Self?
must run in O(n), no division
initial thought is make a list with all indices of the products, but i keep end up having to do a nested loop
hint ||prefix product||
Hi, I'm looking at this problem (https://leetcode.com/problems/the-number-of-beautiful-subsets/description/) (today's daily leetcode problem).
I found a solution that runs in O(n^2 * 2^n). It's a very simple solution and obviously naive one. I use bitmasks, define the forbidden couples of integers like so:
forbidden: set[int] = set()
for i in range(n):
for j in range(i+1, n):
if abs(nums[j] - nums[i]) == k:
forbidden.add((2**i) + (2**j))
and then I look at all the possible bitsets and check if they "conflict" with the at most n^2 elements of forbidden:
ans: int = 0
for i in range(1, 2**n):
for forbidden_couple in forbidden:
if (i & forbidden_couple) == forbidden_couple:
break
else:
ans += 1
My solution runs in 1s
Then i looked at the editorial which first solution is O(n*2^n)
So it should be about n times faster than mine
I implemented their solution, recursively and iteratively (they only provide it recursively, here is the one I used iteratively: https://pastebin.com/7KYye7f3)
and it takes 10 times longer instead of going n times faster (11 seconds with the recursive version, 9.7 seconds with the iterative one)
Am I missing something??
Is my initial solution (https://pastebin.com/pDd0pvEU) not as naive as I thought it was? (PS I'm not trying to understand how to make a solution to this problem in O(nlogn) (which is possible), but just trying to make sense of what I pointed out as inconsistent, theory-of-complexity-wise)
isn't recursion known to be slow
Not really.
Python fonction calls are quite expensive, python does not provide tail recursivity optimisation and will not, python has a (configurable) euristic to crash after too much recursive calls, and finally there is a theorem that says that for every recursive algorithm exists at least one non-recursive algorithm that is at least as efficient as the recursive one (this is true for all languages)
but being off by 10x while it should be simpler big-O wise doesn't add up. is it possible the complexity of your solution is different than what you stated
or that their O complexity is off?
it's precisely my question yeah
not really it makes sense
i coded up the iterative version too (cf. the pastebin) that's unfortunately not what makes it different
hey is there any dev can make tool can auto repost vidoes on tiktok
@stiff quartz have you done LC 238?
i need a hint but without giving it away
so far i know prefix sum
struggling w the time complexity requirement and doing everything other than a given position in the array
I don't think I have sorry :/
found this help online:
lmao
The goal of this project is to translate the wonderful resource http://e-maxx.ru/algo which provides descriptions of many algorithms and data structures especially popular in field of competitive programming. Moreover we want to improve the collected knowledge by extending the articles and adding new articles to the collection.
alright, i got it but w help from gpt
you basically make other prefix and suffix arrays and make them equal to the products of everything multiplied through up to that point except for that number which occurs at a given location/index
then populate the answer array by going through and multiplying all the prefix and suffix integers from each array
kind of hate AI for this but i also don't have unlimited time
that's not what you want
suffix array is a very different thing
and I mentioned the cumulative sums/products before
!e something like this
seq = [1, 2, 3, 4, 5]
left = [1]
right = [1]
for x in seq:
left.append(left[-1]*x)
for x in reversed(seq):
right.append(right[-1]*x)
left.pop()
right.pop()
for l, r in zip(left, reversed(right)):
print(l*r)
:white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | 120
002 | 60
003 | 40
004 | 30
005 | 24
no i know i just wanted to share that as it was a "today i learned"
this is more elegant, my solution required 3 arrays
it's soo hard for me to follow the logic. this is right up against my capabilities in this area
i'll have to study this to understand
saved, thanks
Very likely what happened is that Leetcode (as usual) has bad test data, and there are very few pairs with difference = k. So your forbidden set is almost empty
Btw it is possible to solve this problem in O(2**n) time by using the fact that ((x) ^ (x + 1)).bit_count() is O(1) in average
did this one yesterday, i dont know how you come up with the solution without just knowing it.. product of array except self, I cant think of a math operation that does this or algorithm (anyone know?)
Ah yes when I create test cases manually with loads of repetition it goes crazy (nums=[1, 2]*10, k=1). Should've tried that I'm stupid.
So all good, maths is not wrong, we are safe
I found a way to do it in O(2**n like so (a bit like when looking up the longest path in a graph)
class Solution:
def beautifulSubsets(self, nums, k):
def beautifulSubsetsRec(idx, count):
if idx == len(nums):
return 1
res = beautifulSubsetsRec(idx + 1, count)
if not count[nums[idx] + k] and not count[nums[idx] - k]:
count[nums[idx]] += 1
res += beautifulSubsetsRec(idx + 1, count)
count[nums[idx]] -= 1
return res
return beautifulSubsetsRec(0, Counter()) - 1
but don't really get what your solution would look like
how would a XOR be useful here?
looking at a particular element, to compute the result you need the product of everything to the left, and everything to the right
product of everything to the left/right is something we can easily and efficiently precompute across the whole array
okay so, is there a better way of selecting what i want to remove?
foir exaple here:
instead of removing all * i wanna just remove the ones at beggining and end
**Lifespan * Neutrality** -> Lifespan * Neutrality
instead of
**Lifespan * Neutrality** -> Lifespan Neutrality
.strip('*')
Hey guys do you use VS code or the cloud platforms
anyone here knows regex?
i need one that get all the characters that are inside in between _, __, ___, *, **, ***, ~~ and/or ||
so i can capture all of those strings which are inside this
and i'm planning to it also sabe those "special characters" as a reference
so i can work on it later
i can't ask this for an ai since it's way too complex
while the language you are trying to parse is technically regular, the regex parsing it somewhat decently is going to be so complex and long, it is impractical. Do yourself a favor and write your own parser for this. Do not use regex.
Unless I misunderstood..
if you want to just get what strings are inside the matching pairs, you can just match everything with /\b__.+?__\b/, for instance, but you won't be able to combine the expressions well
parsing something like a*b_c*d_ is going to be annoying
anyway, still, don't use regex please, it's probably not worth it
is 10h screentime bad?
< 1hr (less than one hour): Very healthy and minimal.
1 - 3 hrs: Healthy and moderate.
3 - 5 hrs: That must be your job and source of income.
5hrs+ : Either you work for NASA or at least maintaining an important infrastructure OR you have unhealthy addiction.
Btw this should be a linear time solution for the problem
import sys
n,k = [int(x) for x in input().split()]
A = [int(x) for x in input().split()]
import collections
buckets = collections.defaultdict(list)
for a in A:
buckets[a % k].append(a // k)
buckets = [buckets[key] for key in buckets]
new_buckets = []
for bucket in buckets:
bucket.sort()
for i in range(len(bucket) - 1)[::-1]:
if bucket[i] + 1 < bucket[i + 1]:
new_buckets.append(bucket[i + 1:])
del bucket[i + 1:]
new_buckets.append(bucket)
buckets = [[b - bucket[0] for b in bucket] for bucket in new_buckets]
dp0 = 1
dp1 = 0
for bucket in buckets:
m = max(bucket) + 1
counter = [0] * m
for b in bucket:
counter[b] += 1
for c in counter:
dp0, dp1 = dp0 + dp1, dp0 * (2**c - 1)
dp0, dp1 = dp0 + dp1, 0
# -1 to not count the empty set
print(dp0 - 1)
Well it is technically not linear since the numbers could become large. But it would be linear had the task been to print the answer mod 10^9 + 7.
Hii, I'm going to start leetcode from today to 12th July in my summer break (~45 days), 2q a day min - if someone wanna do alongside, let me know. I'm clear with data-structures concepts but haven't did much leetcode and cp yet.
Did this message go through?
wdym?
Nobody was replying to me on Discord, verified functioning
oohhhh
I could try, but depends if im free
Trying to check my understanding of something: PEP-342 and 380 effectively turned generators into de facto coroutines. Then, 492 gave us async/await syntax and a separate Coroutine type, but Generator objects still have all the methods and semantics required to be coroutines.
I was reading https://eli.thegreenplace.net/2009/08/29/co-routines-as-an-alternative-to-state-machines/, which was written before PEP-492 and is an example of using coroutines for an algorithm that has nothing to do with asynchronous I/O, which is pretty much what I understand to be the purpose of the Coroutine type in Python. I'm honestly not sure if this algorithm could be (easily) expressed with async/await, but that's probably just me being used to thinking of them as "functions that magically don't block" (and I do know that's inaccurate).
I guess I could condense my thoughts here into the question: with PEP-492, is there any case where one might write a coroutine algorithm using generator functions instead of coroutine functions and an event loop like asyncio?
yes, a few secs more
yes appending into a list at merge_json function,
tho i have a issue can u help me in rag
feel free to explain it here
Greetings people!
People I'm having an issue with a code. I'm trying to create a program where the user picks 2 values randomly (without repeting) from 2 different list. Then at the end I make a sum() about it but for some reason i'm getting errors. This is the code that I have
from random import sample
from random import choice
List1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
List2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 12]
User1_List = []
User2_List =[]
for i in range(2):
User1_List.append(sample(List1 or List2,1))
print(User1_List)
So, I created a list called User_List = [] where I assign 2 different values to the list by using he for loop!
This is the error that I'm getting
my basic take is that generators play well with synchronous code, the async coroutines don't
the print shows what's going on, no?
sample returns a list of samples
also, I don't think the List1 or List2 does what you think it does
Oh yeah! I found the isse
It was a missunderstanding and I fixed it!
Now I have to develop the logic to make it work
from random import sample
from random import choice
List1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12]
List2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,12]
List_Choice = [List1, List2]
User1_List = []
User2_List =[]
for i in range(2):
Random_List = choice(List_Choice)
if Random_List == List1:
print("First List was Selected")
else:
print("Second List was selected")
User1_List.append(choice(Random_List))
print(User1_List)
in this case it's equivalent to just List1
I had to create another list to select randomly a list
Now I have to develop a logic that when I select 2 different values randomly from one list and one from another list, it doesn't have repeat
what's the actual goal?
For example, if the software randomly selects the number 9 from the List1, that number can't be selected again from that list, but it can be selected from the other list.
I don't know if you understood me 
But I'll do it tomorrow because It's almost 2 am here 
say
List1 = [1]
List2 = [2, 3]
```and you pick one item, what should the chance of picking each item be?
1/3, 1/3, 1/3
or
1/2, 1/4, 1/4
Oh sorry, I didn't understand that 
with your current code and the lists I gave it would be 1/2, 1/4, 1/4
i.e. much more likely to pick the 1
uniformly random?
if so your current code doesn't work
Oh no, for now is currently working!
I mean, I can append numbers and make Sum!
But tomorrow, I'll develop the logic to add numbers on the list without repeating them 
I meant it's not uniform
ok, it is uniform only of the two lists are the same length
if you move away from that things become non-uniform like with my example lists
is all you want to do to treat the lists as if it was one long list for the sake of sampling?
Ohh
Yeah yeah!
Maybe like that!
if that's what you want, why not just make one big list and sample that? 
Oh sorry Fenix, I was a little busy! Can we talk about this later and give you more details of what I'm doing 
say i have a class A and a subclass of A, called B
if i have some method that returns an instance of A or B, how would i make it so that when an instance of B uses the method, it returns an instance of B, rather than an instance of A?
if we're talking methods on A and B, a class method is probably appropriate:
class B(A):
@classmethod
def method(cls, *args) -> "B":
# do stuff
return cls(*args)
If you're trying to use a standalone function or static method, maybe something like
def func(obj: T) -> T:
# logic to make init_args, if needed
return type(obj)(*init_args)
Otherwise, return self should pretty much handle a regular method returning an object of the same class (by simply returning itself).
kk
I guess what I'm wondering is if there are algorithms that aren't async but still benefit from using a coroutine (i.e. a Generator that makes use of the send and throw methods, which are the magic sauce for making coroutines)
ones which are able to conserve memory by yielding values using a generator that + itertools islice
what exactly is dynamic programming? in my brain all it means is the good not iterating through every possible solution answer
https://leetcode.com/problems/coin-change/editorial/
https://en.wikipedia.org/wiki/Knapsack_problem
like the other one is walking up stairs I think, the only patter I see is like turning something into an array and reusing the previous answer. but if someone asked me what dynamic programming is I wouldnt know what to say
it's divide & conquer(break problem into smaller problems) + memoization(remember past results)
e.g. for your coin change, if you had coins of 1, 2, 5, and you wanted to get to 17, you could
- get
16then take a1coin - get
15then take a2coin - get
12then take a5coin
the question now becomes, how do you get to16,15, or12? but pause, because notice that you've just asked the same question - "How do I get tox" - just with smaller inputs. That's the divide & conquer part
let's draw a tree of dependencies (and go 1 layer deeper on 16 - to get there, you can do 15 + 1, 14 + 2, or 11 + 5)
--- 17 ----
/ | \
12 15 - 16 --
/ | \
11 14 15
```notice that the problem of "How do I get to `15`" appears twice - you could just calculate it twice, or you can calculate it once, store the result, and just use the result if you need it again. That's the memoization part
wow that was super helpful, now I know what they mean by divide and concur (split up) then cache/memoize thank you very much!
is there a way to sort of template for an object with classes? so say i have different types of NPC, so some can be ranged, melee, or not attack at all, some are from different areas, etc
would i just use if statements to check for something like 'if npc.is_ranged' and then run code for that, or is there a more elegant way
or like say im storing a bunch of properties about different types, so like say "warrior":{is_ranged: False, health: 200, armor: 15, attack: 10} or whatever, would i just use a dictionary for that or is there something for it
im pretty sure theres some concept in oop im grasping at here but im not sure what it is
inheritance 😛
i guess
i just was thinking using a subclass for each thing would be a bit much but i might just try it
rn im doing this lmao
oh wait i dont think i even needed to do this
oh well
Hey! I'm a super new coder and I know very little so take what I say with a HUGE grain of salt, but surely using a class would work better here and be more code length efficient right?
If your objects don't have additional behaviour aside from just storing data, then you can use TypedDicts + inheritance
that way you can use the existing syntax (literal dicts) for defining new objects
Hey guys so the question is to encode and decode a given list into a string and back. Its a leetcode question. I dont know what my error is please do help
a = ["Hello", "world", "he::o", "Hello World ", "hello##world"]
temp_str = ""
for i in a:
temp_str = temp_str +str(len(i)) + "#" + i
result, j = [], 0
while j < len(temp_str):
k = j
while temp_str[k] != '#':
temp = ""
k += 1
length = int(temp_str[j])
temp = temp_str[k+1: k+1+length]
result.append(temp)
j += k+1+length
print(result)
does anyone know what's the mistake in this
it's C code in python
okayy thank youu



if you still need help by the time i get on pc (prob less than 30m) ill see what i can do
the obvious thing that comes to mind is that it might index out of bounds, you have a check in the first while loop but you increment the value, i’ll have to check to be sure though
Honestly i actually somewhat prefer the Enum syntax since i have to manually enter TONS of stuff (i’m working on my besiege thing and extending it to level editor stuff, and that means i need to have the IDs for the various objects to add)
ok im on pc now, for one you're trying to turn a character from a string into a number, for some reason?
the problem with doing that is that you run into other characters than numbers so it doesnt know how to convert it and errors
oh i see what you're trying to do, you have the numbers for how long each segment is and then try and jump to the next from that
the problem with that is that even though you check for a character being '#' for the index k, you don't check the index after that since you add 1 to k after that check
you're also only using one character for the number of characters to jump to, so if something has, say, 10 characters, it won't interpret that '10' that you encode as the number 10, but as a '1' and a '0' respectively, so it jumps into the wrong character and errors
took me a bit but i wrote what i think is a working version of that encoding/decoding process
a = ["Hello", "world", "he::o", "Hello World ", "hello##world"]
def encode_list(l):
temp_list = []
for i in l:
temp_list.append(f"{len(i)}#{i}")
return "".join(temp_list)
def decode_list(s):
result = []
k = 0
while k < len(s):
digits = ""
new_char = s[k]
while new_char.isdigit():
digits += new_char
k += 1
new_char = s[k]
else:
length=int(digits)
temp = s[k+1:k+1+length]
result.append(temp)
k += 1 + length
digits = ""
return result
encoded_string = encode_list(a)
print(encoded_string) # "5#Hello5#world5#he::o12#Hello World 12#hello##world"
decoded_list = decode_list(encoded_string)
print(decoded_list) # "['Hello', 'world', 'he::o', 'Hello World ', 'hello##world']"
a = ["Hello", "world", "Hello", "#hel" ,"j@#@"]
temp_str = ""
for i in a:
temp_str = temp_str +str(len(i)) + "#" + i
result, j = [], 0
while j < len(temp_str):
k = j
while temp_str[k] != '#':
temp = ""
k += 1
length = int(temp_str[j])
temp = temp_str[k+1: k+1+length]
result.append(temp)
j = k+1+length
print(result)```
I did it like the above and ig it seemed to work
Btw thanks for the reply
np
how i can master data structs and algos
can someone explain why this while loop gets skipped?
putting the "g+=2" in the loop does nothing
I just rewrote the entire thing except:
g=-9
while g<69:
looks like you're going to get infinite recursion since you are always calling self.in_order_travelrsa
have you studied OOP?
in_order_traversal is an instance method so you need to call it as a member of self
the function with the 2 is the one Bing AI made
You aren't even calling in_order_traversal properly. Please read this ^
where is your own code?
please don't rely on the AI to generate code for you, especially when you're still learning
it can and will generate bad code
I think you should try using a debugger to go through the code line by line
it would help you understand the recursion that's going on
can you guys give some tips on implementing codes with deep logic, where a simple mistake can lead to days of debugging.. example: implementing a toy compiler/interpreter..
ive been coding for 3 years now, but im still, really not good.. still at beginner level.. i just want to know how you guys work with really complex or difficult algorithms, because its really hard.. i used to just copy algos in the internet, use it on my projects, if it works, i just let it be.. but right now i wanna start understanding how things work.. then i realize that to understand how 1 works.. u need to understand 0.9 and 0.8 and 0.7 etc etc.. i really dont know, please give me ur experiences on this thanks
Break down complex problems into smaller steps. In terms of code, use functions to scope your variables so you don't have to keep track of many variables at the same time. If a function has too many variables/logic inside, then it is usually a good idea to break it apart into smaller functions
Prefer immutable objects over mutable ones to avoid accidentally breaking invariants elsewhere
hi
can someone explain to me how traversal 1 correction done, coz i have no idea how with this is i can verify
can someone answer ii the bottom question
WHAT?
hey i want to learn data structures and algorithms using python can anyone help me in this?
Try the book Data Structures and Algorithms in Python
Are you familiar with depth first and breadth first searches?
yeah kinda isnt depth it goes all the way to the bottom of 1 branch before going back
and breadth checks the whole level before going down so bredth would check e g r then go down
Yup
is that correct?
or does it go back to q then down another route
but those are the only2 methods i can think of anyways it asks for 3
Yeah except you don't have to check e twice, so the order would just be q, e, n, u, ...
There are three subsets of depth first search called preorder traversal, inorder traversal, and postorder traversal
ıslak baba kralı
alright thank you
i have another questions lol
for this question
i got the big o as
O(n) for adding element
O(1) for removing an element
reasoning for adding element, you would have to go through the whole set to make sure ur not adding a duplicate
removing element is 1 since you dont have to go through the set and just remove it instantly
would that get me the full marks?
i dont think so. why do you think you need to go through the whole set "to make sure you're not adding a duplicate"? what do you think is the time complexity of x in some_set?
Isn’t that just N
N is the length of the set
Yeah
I’d that wrong
Is that wrong
Wait
Is it actually just a constant
But doesn’t it take longer if the set is longer
So it’s not just constant
nope, thats the point of a set
what do you think dictionary key lookup time complexity is? same problem
Is that the same in every language
not really, no
This exam is kinda in c
Lol
I know I’m asking in a python server
It’s the only active computer science server
I’m in atleast
mh, its always an implementation detail, but usually sets are backed up by a hash function
in haskell there is no magical hash function for everything though (or, well, there is, but stdlib containers dont use it as its not really pure and not implemented for a lot of types), so it is backed up by comparison of elements and stored as a tree, so its log(n)
I mean I think the question is just a bad question
They don’t mention how it’s implemented
depends if there is previous context, e.g. if you implemented it in your classes