#algos-and-data-structs
1 messages · Page 46 of 1
Is leetcode stats good for portofolio?
Given an unsorted array of integers(both positive and negative). Write a function to find the minimum positive integer that is missing in 𝑂(𝑛) time complexity.
min_pos_int(arr): return None
[3,9,2,−3,−5,1,9,6,4,8,72,5] return 7 [17,64,4,2,1,−3,76,−1,−5,16,13,9,10,18] return 3
how is O(n) even possible
there's several possible tricks but one I like is ||just calculating the sum||
hmmm...... what do you mean by that
(it's a bit arguable whether that's truly O(n) because it may be quite big)
ah, nevermind, I misread the task
you can create a boolean array found of size n + 1 (same as the input size), iterate over the array, and every time you see an element 0 <= e < n + 1, set the element found[a] to true. Then find the first element in found which is false, and return it's index
this function is usually called MEX btw (minumum excluded or something)
Then find the first element in found which is false, and return it's index
wouldnt the worst case time complexity of that be O(n) as well
so altogether the function would be O(n^2)
you don't do this for each element, you do it afterwards.
when you iterate through ur random array to create a boolean array thats O(n). checking which index is false is O(n). so although the function is O(n^2)?
oh wait
it would be O(2n)
sorry
brain shorted for a sec
@vocal gorge @outer rain thanks 🙏
To solve this problem:
https://codeforces.com/problemset/problem/431/C
I did a "standard" dfs like so:
n: int
k: int
d: int
n, k, d = line_integers()
# dfs with branch and bound
@lru_cache(None)
def dfs(sum_: int, has_d: bool) -> int:
if sum_ == n:
if has_d:
return 1
if sum_ > n:
return 0
s: int = 0
if has_d:
for m in range(1, k + 1):
s += dfs(sum_ + m, True)
else:
for m in range(1, k + 1):
s += dfs(sum_ + m, m >= d)
return s
ans: int = dfs(0, False)
print(ans % 1000000007)
But the editorial suggests a dp solution (https://codeforces.com/blog/entry/12369, their solution coded up is https://codeforces.com/contest/431/submission/6676700). But I don't understand their dp solution.
this part:
Dp[n][0] = Dp[n-1][0] + ... + Dp[n-min(d-1,n)][0]
kinda makes sense but then when do we even "fill" the Dp[n-1] etc ... if we start with Dp[n][0] we will never do Dp[4][0] for example.
EDIT: or is the "n" they refer to actually an index idx defined in ``for idx in range(n)`?
EDIT2: are both solution equivalent since my cache is basically their dp?
unrelated, but is the term "branch and bound" the right one? I'm referring to if sum_ > n: return 0
or is it just a basic constraint check and therefore does not fall under the name of "branch and bound"
Is there a library for... transforming discrete distributions, I guess? Rough example of what I'm talking about:
dist = uniform_range(0,10) # 0.1 probability each for elements in range(0,10)
dist2 = (dist*5 - 2).clip(20,30) # that's like doing max(20,min(30,x*5-2)) for each element in dist
# dist2 is then a distribution over 4 possible values with nonequal probabilities:
# {20: 0.5, 23: 0.1, 28: 0.1, 30: 0.3}
This isn't hard to implement from scratch (I've done this twice before, I think), but each time I feel like I'm reimplementing a wheel.
anyone ever venture into information science?
Branch and bound refers to a method used for solving maximisation / minimisation problems. Usually it is used on NP-hard problems (where the search space is huge).
What you have there is not branch and bound. Instead I would simply call your method DP
could someone explain why i'm getting this error
how can list index be out of range when for x in (whatever) goes through every element automatically lol
👍
I'm working on a pyqt5 browser and can't seem to load any form of captcha, here os the info I have...
js: unrecognized feature: 'cross-origin-isolated'
This is causing captcha to not load and only load as a string of random characters or more likely an ID, I really have 0 idea how to bypass or try to fix the issue to use the browser as my main browser.
So... is there any fix at all?
(this is copied from my reddit post to save time)
I'd like to learn encoders and machine learning but I don't know where to start.
I'm an intern for my last semester of college and the company asked me to make a machine learning model for a bunch of data with diffrent data types like strings, floats, bools in the shape of 0 and 1 and basically I didn't learn a thing from my college since we were online for a while and my course includes 2 out of 4 years of c++ for some reason etc anyway I cleaned the data and it's ready for use but now I know nothing about sklearn or any encoders, please give me some comprehensive but short ish resources to learn this, thank you in advance.
if you wanna use index, there are two ways to do that
for i in range(len(nums)):
i/ [i] are index and nums[i] it's the element
for i, v in enumerate(nums):
i index and v is a element or value, whatever you wanna call it
How do you know what rotation to perform after inserting into a AVL Tree?
how do i fix my code
@pastel thorn check dm
Whenever I need a linkedlist, should it always be Doubly?
depends whether you need backward references, so no, not always
I see, and the only advantage with a doubly list, is that when doing backward references its O(1)?
yes, it allows you to iterate in the reverse direction, but if you want to count advantages, I would also add that since you can iterate in reverse, looking up an item by index/count would take less time in doubly linked-list
(eg: getting index 8 in list of length 10 takes 8 iterations, in doubly linked-list only 3)
and of course the tradeoff would be extra memory, and you need to maintain more references in insert/delete operations
Awesome! Thanks I better understand 🫡
i dont know which channel to post this error in
I'm looking to understand how khan's algorithm is better compared to a naive BFS in the context of directed acyclic graphs with no weights
We could just do a BFS by adding in the initial queue all the vertices with no incoming edges
and adding the vertex we pop from that queue to a list we eventually return
Or maybe I'm getting something wrong:
Consider the following graph:
A -> B -> C
D -> C
E -> F
Is the topological order
A, D, E (all them interchangeable), B, F (these two interchangeable), C
or
A, D, E, (all them interchangeable) B, C, F (all them interchangeable)
Basically is C "3" (max of the number of edges to take to get to C) or "2" (min of the number of edges to take to get to C)
I think that's the second option, but that second option would be obtainable with a "basic" BFS
How I solved ?
The niceness of a pair (a, b) is the value you will get by subtracting their product from the difference of their squares. For example, the niceness of the pair (7, 4) is 5, because (7²-4²) - (74) is 5.
Find any pair of numbers with niceness 500, where both numbers have 4 digits. If you find a pair (a, b) then write the number (10000a)+b as the answer.
Any order where for each vertex all incoming one are located before it
A should be before B, B and D should be before C, E should be before F
I didn't understood what the exact task is, but for example the longest path
If you do that with bfs on such graph (screenshot)
You will get in 2 from the 1, later you will get in 2 again from 3, and you will need to start from 2 again to update the answers everywhere after it, then one more time from 7
2 has to come after 3 so bfs wouldn’t work I guess
Ok I understand
So in topological order, all vertices that could lead to i have to be before i
It’s not a matter of distance from the vertices that have no incoming edges
Is that right?
Ye, distance doesn't matter
Question - Bob has reviewed the external chaining policy, and he's designed a modification of it, which he calls "tree chaining". The idea is that rather than using a LinkedList for the chaining, he uses a BST instead. Alice comes over and sees the merits in the idea, but she cautions that the idea needs to be thought out carefully because it could have unexpected complications in implementation and unintended consequences in efficiency. Which of the following are plausible concerns that Alice might have?
- The requirements for keys in HashMaps do not match the requirements for data in a BST.
- BSTs only hold a singular data type, so it's non-trivial to store key-value pairs.
- The worst case performance (in terms of time complexity) is the same as before for searching.
- Performance may be worse when there are not many collisions.
- Performance may be worse in pathological cases with many collisions.
- Performance of resizing the table is asymptotically worse in the worst case.
- Alice's concerns are unfounded, and Bob is a genius for thinking of this idea!
definitely 7
I feel the answer should be 1,2,4,5,6 but it is turning out to be incorrect 😦
incorrect
indeed, that is incorrect. explain why you think those are true?
for 1st option - Storing key-value pairs directly in BST nodes might not guarantee unique keys. However, Bob could potentially implement a custom node structure or use a separate data structure within the BST node to handle key uniqueness.
for 2nd option - Storing both key and value efficiently requires thoughtful design. Bob might need to create a custom node structure with separate fields for key and value
for 4th option - Using BSTs adds overhead compared to linked lists. For small chains with few collisions, the overhead might outweigh the benefits, leading to slower performance
for 5th option - While BSTs can handle collisions better than linked lists in some cases, pathological cases can still lead to unbalanced trees and O(n) search complexity, negating the benefits.
for 6th option - Resizing a hash table with tree chaining might involve rebuilding BST chains, potentially making it asymptotically slower (O(n log n)) than resizing with linked lists (O(n)) in the worst case
you tell me, what do you think correct options are?
that's cheating 😛
i'm reading your answer
for number 1: what are the requirements for keys in a hash table?
requirements arent specifically laid out in the question so I just assumed that BST might not guarantee unique keys which would violate the condition for hashmap
duplicate keys might get added
yeah i think 1 is correct, but the reasoning is different. a BST requires the keys to be comparable, while a hashmap only requires being able to check equality
Are my other options correct?
i think this question is a bit poorly worded. i think 2 is not really plausible, since as you mentioned we can just create a struct/class/whatever to store both key and value
it also doesn't really define "few" in 4. i'm tempted to say 4 is not plausible, if there's only 1 collision, the performance is the same
it also depends how the BST is implemented, actually
if you implement using nodes like a linked list, then there's no memory overhead. but if you use an array then there would be
ok, so I just marked 1,5,6 and it is also incorrect 😦
yeah correct
for 5, the performance can never be worse, which i think is the key
the degenerate BST case is just a linked list, which can only be the same as a linked list
yup
but i think resizing in 6th would be worse
i think you're right for 6
hmm so is the final answer 1, 5 and 6 according to you?
I have tried my best to answer this but I dont know everytime it is throwing incorrect 😦
even after removing the answers which you deem incorrect, it is still showing incorrect
why did you not include 3?
hmm. i guess the question is just worded badly. i think it just wants "true or false". if true, select it
actually these 7 options have tick box against them so I need to select all the options that apply 😦
right, select the true ones
1, 5 and 6 you say?
i think 3 too
still incorrect 1,3,5 and 6
idk then
ok buddy thanks 🙂
can somebody help me with my python work 🙏 im not 100% sure where to put this
number = int(input("Enter an integer to see its powers: "))
amount = int(input("How many powers of " + str(number) + " do you want to see? "))
variable = 0
for i in range(amount + 1):
number = (number) ** (variable)
print(str(variable)+ ". " + str(number))
variable += 1
IS MY MATH WRONG OR SOMETHING bc variable never ends up adding up 😢
,e 2 4 ```py
number = int(input("Enter an integer to see its powers: "))
amount = int(input("How many powers of " + str(number) + " do you want to see? "))
variable = 0
for i in range(amount + 1):
number = (number) ** (variable)
print(str(variable)+ ". " + str(number))
variable += 1
you assign the result to the same name number
i thought because i assigned it the same it would overwrite
after the first iteration number becomes something ** 0 = 1 and then it stays 1 forever
it does overwrite, and then you lose the original number that was input
ohh i see, i would have to assign it to another variable?? how would I make the code work?
yes
Is there a way to have fixed-width integers in base python?
i guess for the math aspect i could just implement a numeric class that does value & base-1 for every op
Is there a way to overload all the math operators for a class without having to make a decorator for them actually
huh
oh i checked in C, it's the same result
i thought python handled it differently
ill have to look at that
cause my implementation of int16 looks like this lmao
i honestly have no idea how to use the ABCs
i guess this is the best it can be
there is no more convenient way
you also might want to ask about it in #esoteric-python to get interesting answers
If you need a short, you can just use the c_types library
Otherwise, just inherit from int and override what you need to
ah right
np.uint16 would also work
hello guys
i want to start python but is a prohlem
problem
can i use it as a freelancer and make a lot of money?
bcz some people that u cannot be an freelancer with python
i need help
i keep getting an error on my mac im trying to install pandas into python and keep getting error
i did it correctly in my mac terminal
topic pls
back testing a strategy
pick a channel relevant for this #algos-and-data-structs ain't it
#data-science-and-ml or just #python-discussion would be better
This is something like knapsack problem:
N (n <= 1e5) pairs of numbers l, r (l <= 1e13, 1.4 * l <= r <= 1e13) are given and a number s (s <= 1e13)
For each pair we can take some number x = 0 or l <= x <= r, then calculate the sum of these x values
We need to find out what is the maximum sum that is less or equal than s we can achieve and how much should we take in each pair to get it
Example
3 20
1 2
10 17
11 16
(first line is n and s, next n lines are l, r)
Answer
19
2 17 0
(first line is sum, second line is the value that we take for each segment)
To find only the answer sum value, we can do such algorithm:
segments = [(0, 0)] # stores segments with all the sums we can achieve
for i in range(n):
new_segments = []
l, r = A[i]
for L, R in segments:
new_segments.append((L, R))
new_segments.append((L + l, R + r))
# ...
# Find a union of the segments in `new_segments`
# ...
segments = new_segments
# ...
# The answer sum can be found easily with binsearch now (or just with a loop)
It works fast enough because we have a constraint 1.4 * l <= r <= 1e13
It means that in one time we can't have more than log(1.4, 1e13) ~ 90 non-intersecting segments
But idk how to restore the answer (second line)
anyone know an efficient sphere generation algorithm? i.e say i want to generate all the points on a sphere in a voxel grid (i.e like minecraft blocks)
i've tended to use the naive method of just iterating through a cube
and checking the distance
when you say "on" you mean the surface?
I know of some well known algorithms for the 2d case, i.e. pixels on a circles
e.g. https://en.wikipedia.org/wiki/Bresenham's_line_algorithm which is for lines, but have variants like https://en.wikipedia.org/wiki/Midpoint_circle_algorithm
Bresenham's line algorithm is a line drawing algorithm that determines the points of an n-dimensional raster that should be selected in order to form a close approximation to a straight line between two points. It is commonly used to draw line primitives in a bitmap image (e.g. on a computer screen), as it uses only integer addition, subtraction...
I'm not sure how easy these would be to generalize to 3d
ik bresenham's
Somewhat confused: the goal is to find x_i such that forall i, either x_i=0 or l_i<=x_i<=r_i, and sum_i x_i should be as high as possible without exceeding a certain goal s? If so, I think that's linear programming, with some caveats like integer-only values and being allowed to use 0 always. Nevertheless, scipy's scipy.optimize.linprog can handle both of these constraints (integrality=3 does exactly this).
(of course, I have no idea how HiGHS actually works under the hood, so that's not really an answer to what algorithm to use 🥴)
Yes, that's the goal
But yeah, I need a solution on my own, not some library
You can store for each non-intersecting segment in the DP how you got that segment
like if you have a segment [5, 12] and you want to know how can you get 10, you can trace back the evaluation of DP
so like, if, say, you got [5, 12] as a merge of segment [5, 8] you got from a previous iteration, and [7, 12] which you got as a sum of segment [5, 8] and item [2, 4], then you can store it with the segment itself, in some format, for instance, like ((5, 12), [((5, 8), None), ((5, 8), (2, 4))])
So when you are trying to restore the answer, look at the segment the answer lies in, trace back how you got it, then restore the segment you got it from, etc.
I know this is a bit confusing but its the best explanation I can give, I feel 😅
if you are generating a solid sphere, I don't see much reason to not simply iterate every 1x1x1 cube, evaluating distance
It's going to be O(n^3) either way, you may lose like x4 performance at most
the way that comes to my mind is
for z in range(-int(R), int(R)+1):
ymax = int(math.sqrt(R**2-z**2))
for y in range(-ymax, ymax+1):
xmax = int(math.sqrt(R**2-y**2))
yield from ((z,y,x) for x in range(-xmax,xmax+1))
(i may well have off-by-oned in many places.) but yeah, it's only a constant factor faster than any naive way.
actually, another answer to this is "I think skimage has a function for that" 😛
ah, only for circles though, not for 3d. big oof.
Anyone doing hackerrankone?
is this true for circles as well? for a non-filled one i can of course just use bresenham but
also is there an algorithm for generating points on a face? (once again in a cubic grid) say i have the positions of the vertices
for a triangular face, that is, since for quadrilaterals and above there's ambiguity on how they're attached and you can also get some really fucky layouts that aren't possible to solve without curves or multiple faces
For solid circles? I would expect it to be pretty fast, yeah
kk
that's an interesting question, I don't know, but I expect there to be
it'd be handy, since i've been having people wanting me to make an OBJ-to-blueprint (for a game) program
btw is there any advantage to using a generator in a function? im not sure when i'd use them
the only time i've ever really done yielding is in my vector class code implementing __iter__()
im guessing for large amounts of data it's more efficient to use a generator since it can take it 'piece by piece'
if that's how it works
Generators can be faster because they skip the whole "put elements into a list" step.
kk
so here's a basic function that returns a set of points within a circle
def gen_circle_points(pos,rad):
points = set()
for y in range(-rad,rad):
for x in range(-rad,rad):
if (x**2 + y**2) <= (rad**2):
points.add((x+pos[0],y+pos[1]))
return points
might try doing it with a generator
oh yep that worked, i just removed the return statement and the set and did yield instead of points.add
only issue is it only works if you're going to iterate through it afaik, but in this case idk when you wouldn't want to do that
def gen_circle_points(pos,rad):
for y in range(-rad,rad):
for x in range(-rad,rad):
if (x**2 + y**2) <= rad**2:
yield x+pos[0],y+pos[1]
much simpler
:D
its pretty fast too apparently, i ran it with a 100 radius circle and it didnt take long at all
i just used pillow and plotted a pixel for each point
of course, another option is to work scanline by scanline and solve a second degree equation to get the end points
(or even brensenham I guess)
and then you can say "draw a line at y from x=bleh to x=blah"
which might be a fast primitive
IT'S NOT SYMMETRICAL 👿 😡😡😡😡😡😡👺 👺 👺 👺 👺 👺 👺 👺
couldn't you just use numpy so that the operations are in constant time instead of using nested for loops?
that'd kinda defeat the point of doing it myself
also wdym constant time?
well you still use numpy and it's probably harder
since memory can operate on the values as matrices you don't have to iterate over individual values
since this is done in hardware
ah well i guess yeah
that's not constant time though, it's just faster
if i actually needed the performance i would probably do something like that but that was just an example of the idea
i wonder if there's a way to kind of cut out some of the work by 'removing the corners' of the square or if that'd just make it worse
i mean really if you take that to its logical conclusion you could just keep removing corners until you get a circle (or an octagon, depending on how you do it)
#algos-and-data-structs message this implementation does that
lemme fiddle with that and see
for most operations it will be very close
no, no it won't
using numpy doesn't magically improve time complexity
and it's not even "very close"
this is all the code i used to do the circle render btw, very simple
from PIL import Image
#====#
w,h = 250,250
radius = 100
#====#
im = Image.new("RGB",(w,h),(255,255,255))
px = im.load()
def gen_circle_points(pos,rad):
for y in range(-rad,rad):
for x in range(-rad,rad):
if (x**2 + y**2) <= rad**2:
yield x+pos[0],y+pos[1]
points = gen_circle_points((w//2,h//2),radius)
for i in points:
px[i]=(0,0,0)
im.save("circle_test.png")
it is, of course, less efficient to use px[pos] for a bunch of points rather than just putting it all into an array but i feel like for this it'd be weird to do that since i'm only filling some pixels
any matrix multiplication of reasonable size will be very very noticable
btw wouldn't this be a lot slower since it's using sqrt?
nah, should be cheap
ah, i avoided sqrt in mine in favor of doing a sort of distance2
oh wait i was trying to break it down to see if i could render it as a square without the corners but
oh wait that is a sphere isnt it
yeah
yeah ok that explains it
i cut out the wrong part i guess :p
i was going to make a mockup of the 'cutting out the corners' bit in algodoo (too lazy to do it properly in an image editor) and, wow you really do not cut off that much space if you remove the corners
i can actually check the area using algodoo
circle is 1m radius, so the square is 2m on a side (and therefore an area of 4 m², so removing π m² from it gives ~0.858 m², so a ratio of 0.21 between the total area of the square and the area not in the circle, and this isn't even accounting for the fact that removing a corner would be an even smaller fraction of that area
so yeah i can see why it wouldn't be a super significant speed increase by doing it more elegantly
did the math with a py func to be sure, it's a constant ratio, 0.21460183660255 give or take
the math is just (2r² - πr²)/2r²
im sure you could condense that down but whatever
Yo how you guys doin?? I learned max pairwise and i'm trying to write a brute force solution for magic square matrix. It's nearly done but it keeps appending to the array. I will post the code if anyone is interested
I'd like to know what its about
where do I go for a question about "return"?
i think you mean ((2r)² - πr²)/(2r)² = 1-π/4 ≈ 0.214 601 836 6
This is why I love programming. I got a very interesting question that i couldn't think of any idea. This is not a python code, instead it is a swift code. I would appreciate if someone can write me this in swift. Lets say I have the following struct and json data. Can We write a init(decode: Decoder) function to covert object with this condition? If the primaryKey for the selector exist, use the primaryKey value to look for the id for the option. If the primaryKey doesn't exist, then simply use the id.
Example, both the ids for the two options below would be ["1","2","3"]
My Struct
struct Selector: Decodable {
let primaryKey: String?
let id: String
let text: String
struct Option: Decodable {
let id: String
let text: String
}
}
Json Data
[
{
"id": "123",
"text": "text",
"primaryKey": "month",
"options": [
{
"text": "Hello",
"month": "1"
},
{
"text": "Hello2",
"month": "2"
},
{
"text": "Hello3",
"month": "3"
},
]
},
{
"id": "222",
"text": "text2",
"options": [
{
"text": "Hello",
"id": "1"
},
{
"text": "Hello2",
"id": "2"
},
{
"text": "Hello3",
"id": "3"
},
]
},
]
Currently I wrote sth like this, but I found that the optionJSON contain only the field I defined in the struct. In other words, the "month" doesn't exist
if let primaryKey = primaryKey {
print(primaryKey)
self.options = options.map { option in
var modifiedOption = option
if let optionData = try? JSONEncoder().encode(option),
let optionJSON = try? JSONSerialization.jsonObject(with: optionData, options: []) as? [String: Any],
let primaryKeyValue = optionJSON[primaryKey] as? String {
print(primaryKeyValue)
modifiedOption.id = primaryKeyValue
} else {
modifiedOption.id = ""
}
return modifiedOption
}
} else {
self.options = options
}
need some help with code of n^2 simulation, sorry if this is not the appropriate channel.
more precisely I am trying to implement 4th order runge-kutta, but facing some issues.
Can I ask here?
hi all, wondering why this leetcode solution doesn't work:
class Solution:
def twoSum(self, nums: List[int], target: int) -> List[int]:
for i in range(len(nums)):
for j in range(len(nums)):
if nums[i] + nums[j] == target:
return i,j
else:
continue
the problem is the "two sum" easy problem:
https://leetcode.com/problems/two-sum/
you may not use the same element twice.
ohhh
my second loop should thus be i+1
thanks
how do y'all solve leetcode problems, in IDE or in the web browser?
i don't like the browser because I cannot do print statements
why doesn't this palindrome number solution work:
class Solution:
def isPalindrome(self, x: int) -> bool:
x_inverted = str(x)[::-1]
x = str(x)
flag = 'true'
for i in range(len(x_inverted)):
if x_inverted[i] != x[i]:
flag = 'false'
return flag
here's another solution
class Solution:
def isPalindrome(self, x: int) -> bool:
xasstr = str(x)
xrev = xasstr[::-1]
print(xasstr,xrev)
if xasstr == xrev:
return 'true'
else:
return 'false'
how is this possibly not working
i'm verifying that they are not equivalent strings with my print
omg
its because in the problem description, they did not write True and False but true and false
ok
The return type will usually be very helpful, some of the problems actually get cryptical about what's supposed to be done
okay thanks. i've moved on to Longest Common Prefix
HELP ME
x = 27
y = 20
if x % 2 != 0:
if y < x:
z = 0
else:
z = 1
else:
if y < x:
z = 2
else:
z = 3
z=?
Ok what does % do
a % b == a - b * (a // b)
Ik what it does but i want to see if he knows
Hello everyone, I'm not very good at coding, i need help to understand the algorithm of data structures and learn how to write the code line by line. Can anyone help me?
for example this question: Create a recursive function, not within any class scope, that accepts a ListADT and reverses its content.
is there any way to visualize an algo in a flowchart directly from source code?
i don't know of any flow chart but pythontutor is helpful and offers some visuals like the arrays and stuff. let me find it
This is the only Python website that lets you visually debug your code step-by-step and get AI help from ChatGPT.
separately i need some help w leetcode
specifically all the code i'm seeing begin as classes, so i guess i'd like to know how to write my own functions within the class (a method) and how to execute.
also what is this arrow thing:
def isValid(self, s: str) -> bool:
->
also i have a solution i'd like to walk through w someone
to the easy question "valid parentheses"
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping: # Closing parenthesis
# Check if stack is empty or if top of stack doesn't match current closing parenthesis
if not stack or stack.pop() != mapping[char]:
return False
else: # Opening parenthesis
stack.append(char)
# Ensure the stack is empty at the end
return not stack
specifically i'm wondering about if the dictionary lookups go both ways. reading this is seems to be the case that one could look up the proper parenthesis by querying the mapping dictionary with either a key or a value.. is this correct?
thanks @fiery cosmos
happy to help. hope it is doing that
okay, i've learned that the arrow -> indicates the expected return type from a function
No, dict lookups don't go both ways. You can only find the value from a key and not the other way around.
Well, you technically can, it just won't be fast
thoughts on haskell?
That's not the best channel to ask about haskell. Try here
#ot0-psvm’s-eternal-disapproval #ot1-perplexing-regexing #ot2-never-nester’s-nightmare
Hello I need a bit of help, the else argument is giving me a bit of a headace because it pops up as soon as I fix one else argument or so I thought I have.
`def init(self):
self.todos = []
def add_todo(self, todo):
self.todos.append(todo)
def delete_todo_by_index(self, index):
print('List is empty.')
if len(self.todos) ==0:
else: self.todos.remove(self.todos[index])
def delete_todo(self, todo):
print('List is empty')
if self.todos == []
else: self.todos.remove(todo)
def checked_todo(self, isChecked, todoCheck):
for todo in self.todos
if isChecked is True
print('(x)', todoCheck)
else
print('( )', todoCheck)
break`
I'm not sure what I'm doing wrong and I've looked online and tried different methods
here's a ss just to see how it's formated
you are doing if else statements wrong
if [some_condition]:
code if condition is True
else:
code if condition is False
actually this should move to a help post, see #❓|how-to-get-help
does anyone know how to implement this? I have an idea but the code is not working with me
This is my code
if num == 0:
raise ValueError("can't divide by 0")
current = self._first
prev = None
count_deleted = 0
while current:
if current.data % num == 0:
if prev:
prev._next = current.next
else:
self._first = current.next
count_deleted += 1
current = current.next
self._size -= count_deleted
return count_deleted
Hey guys so I'm making a queuing system. I need to find the estimated waiting time for each person in the queue. Apparently queuing theory is a real thing people study so just wondering how I should go about doing this and what topics will be relevant for me to read up on to find out how to get the estimated waiting time per person
I need help with BFS -_-
I understand it from a graph theory perspective but get confused once queues are added.....
Can someone also give me an example on how you would implement it for this problem:
https://www.olympiad.org.uk/papers/2010/bio/bio-10-exam.pdf
(q3)
Thanks.
(@me in replies)
Wikipedia has a very nice pseudocode version that’s pretty simple, maybe take a look and ask any questions? https://en.m.wikipedia.org/wiki/Breadth-first_search
Breadth-first search (BFS) is an algorithm for searching a tree data structure for a node that satisfies a given property. It starts at the tree root and explores all nodes at the present depth prior to moving on to the nodes at the next depth level. Extra memory, usually a queue, is needed to keep track of the child nodes that were encountered ...
The idea is to push the children of each visited node into a queue, then visit the next node popped from the queue.
So, you push the root node 1 to initialize. You pop and visit node 1, then push children 2,3,4. Then pop (2) and push 5,6. Then pop (3) and so on.
hey people, what are some commendable ways to time arbitrary functions in python 3?
well, the timeit builtin. personally I use the %timeit magic from ipython.
Thank you!
Thank you!
ill be back with questions 🫡
fastest algorithm
Ye
Clamped between 0-255, hence the dimming
I used a histogram and manually found a good multiplier to keep it in range, basically
can be optimized
are you making this in python?
are you using some external libraries that speed up numeric stuff?
real
well you can put all possible input to a hash table that would work
?
open(...).write(...) is the fastest way i can think of
not sure why you need hash table to print something
Hi!
I'm currently doing this Leetcode problem: https://leetcode.com/problems/extra-characters-in-a-string/description/
My first instinct was to do that:
class Solution:
def minExtraChar(self, s: str, dictionary: List[str]) -> int:
@lru_cache(None)
def search(idx_start: int) -> int | float:
if idx_start == len(s):
return 0
final_penalty = float('inf')
for word in dictionary:
if s[idx_start:].startswith(word):
final_penalty = min(
final_penalty,
search(idx_start + len(word))
)
final_penalty = min(
final_penalty,
1 + search(idx_start + 1)
)
return final_penalty
return search(0)
but it seems the solution is not that great (only beats 30% in space and time). Any idea what I should improve?
I don't fully understand the complexities of the editorial, I think my solution is O(len(s) * len(dictionary))
Maybe s[idx_start:].startswith(word) is not O(1) actually? but O(len(word))?
Yes, it's not O(1)
Also just recursion usually takes a lot of time and memory
Fairs
I might wanna use a trie then
Trie ended up beating 99% even with recursion and not a manual stack
So it’s pretty good
i used pillow but otherwise just pure python since i was lazy
it took a damn while to render (probably like 30s) but i didnt really care since i just had it going in the background
its quite simlpe
what it does is iterate through every coordinate, and for each one calculates the hilbert index, gets the amount of collatz steps for that, then dims,clamps and casts the value to int and then puts the value into the data array
for y in range(res):
if y&15 == 0:
print(y,end=" \r")
for x in range(res):
index = xy2d(res,x,y)
steps = int(clamp(0,collatz(index)/(1.6),255))
data.append(steps)
im.putdata(data)
im.save("collatz_render.png")
the actual iteration part is this, the printing is just to give me an idea of how far along it is
i wrote it in like a few minutes
hello I I have a kaggle general question. Kaglge discord is totally dead hope it's okay I ask here.
I submitted something on kaggle which was pretty much boilerplate code, I just wanted to see how the website works.
I have now created my own steps and even though I could not beat my boilerplate code I would like to submit it. Once I submitted it still showed my previous score.
Is there a way I can delete my submission.csv and use this one, does it run everything in my notebook and go with most recent submission, or does it just go with highest.
I have no idea how it works
collatz sequence on a hilbert curve, colored white if it converges to a cycle
lol
Anyone could help explain why this codeforces submission https://codeforces.com/contest/1907/submission/239009018 is so much faster than this https://codeforces.com/contest/1907/submission/239009251. This is a really easy problem (https://codeforces.com/contest/1907/problem/B). The first solution is O(2n) and the second O(3n)* so i wouldn't have expected such a big difference in time. Am I missing something and the second might actually be quadratic or something?? I'm very confused!
* I had to use a list since append is O(1) and concatenating two strings is theoretically O(len(concatenated string)) so if i initialised ans: str = "" and did ans += char several times it would actually be quadratic.
O(2n) = O(3n). Concatenating two strings is O(len(concatenated string)), and in your case if you concatenate char by char, it's O(1), so list vs str makes no difference complexity-wise. So unless I am missing something, I think the issue is simply that the second solution does more work. You append a lot in the second one, and append is a rather slow operation, compared to just access. Initializing tuples might also be an issue, since they require allocating memory every time, while simple strings like single letters are allocated once.
Have you tried submitting those with PyPy?
looking at the runtimes of cases the second is ~2x slower on case 3
just doing a bit more work in a tight loop could easily account for 2x
and it just seems the second one does a lot more work
Yeh it doesn’t pass with pypy either (fails on test 3 actually instead of test 5 actually surprinsingly)
So it’s still O(n), just ill-optimised?
almost certainly
why did we take 1 from the index in the for loop? (this is a method in a linked list class)
def insert_at_pos(self, index, new_node):
if index < 0 or index > self.length:
raise IndexError("Index out of range")
if index == 0:
# Insert at the beginning
self.insert_at_beginning(new_node)
elif index == self.length:
# Insert at the end
self.insert_at_end(new_node)
else:
# Insert at the specified position
current = self.head
for i in range(index - 1):
current = current.next
new_node.next = current.next
current.next = new_node
self.length += 1
Where should I ask my question regarding a Raspberry Pi with Micropython?
hello guys i'm new here , i want a roadmap to learn dsa and have ability to solve leedcode prblems and thanks
Neetcode has a road map you can follow I guess?
A better way to prepare for coding interviews.
gracias
???
can anyone help me in this qs.
i'm working on leetcode problem 26. Remove Duplicates from Sorted Array if anyone is around to help
nvm the site seems to be down
ok its back
i have a solution that i am not understanding if anyone is there
class Solution:
def isValid(self, s: str) -> bool:
stack = []
mapping = {')': '(', '}': '{', ']': '['}
for char in s:
if char in mapping: # Closing parenthesis
# Check if stack is empty or if top of stack doesn't match current closing parenthesis
if not stack or stack.pop() != mapping[char]:
return False
else: # Opening parenthesis
stack.append(char)
# Ensure the stack is empty at the end
return not stack
i'd like to talk through this solution, specifically i would like to know if the if char in mapping: line checks only keys in the mapping dict or also values
this answers: https://leetcode.com/problems/valid-parentheses/
keys
if it checked values it would be super slow
does this return True by default?
i don't understand how it actually "answers" the question, where nowhere does it explicitly return True
yet when i run in leetcode it'll give true as an output
ugh i have to go as soon as @haughty mountain comes out of the woodworks. looking forward to working with you next time. i am aware of your expertise
any general advice you have for getting better at leetcode easy problems please drop here
default? it returns not stack
i.e. "is stack empty"
oh, and that is equivalent to true when stack is empty?
bool([]) is False
bool(non_empty_list) is True
this is stuff you really should have learned at some point, the truthiness of containers and whatnot 
agreed
well its good i'm working on this stuff now i suppose. leetcode is making me feel really dumb though
do you know the simpler solution when you only have one kind of parens?
This is a matter of truthy and falsey values. Empty Sequences (dicts, lists, tuples, sets, and their subclasses like TypedDict, frozenset, namedtuple, etc), None, False, 0, 0.0, and empty strings all are equivalent to False for each respective data type.
this solution is basically an extension of that, but in the case you have code for here you need to ||remember what the last open paren was|| hence the ||stack||
So when you say not foo, where foo is one of these things, then it evaluates to True
no
i'm also not understanding this solution to https://leetcode.com/problems/merge-two-sorted-lists/
#Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
dummy = ListNode(-1)
current = dummy
while list1 and list2:
if list1.val <= list2.val:
current.next = list1
list1 = list1.next
else:
current.next = list2
list2 = list2.next
current = current.next
# Append remaining elements if any
if list1:
current.next = list1
elif list2:
current.next = list2
return dummy.next
try figuring that problem out then, basically given a string of ( and ), is it balanced?
maybe elaborate on what is confusing, the thing looks pretty straightforward
it basically just does the thing, no real cleverness involved
the code for doing this with just two python lists is very similar
working on it
sorry my VScode seemingly just broke
i'm running a Python script in VSCode and nothing is happening
also, trying to launch IDLE is doing nothing
i'm reinstalling everything, should i do Python first or VSCode first?
reinstalled Python, running IDLE does nothing
is there a better name for the count variable that'll make this make more sense to me:
nums = [0,1,2,2,3,0,4,7]
val = 2
count = 0
# Loop through all the elements of the array
for i in range(len(nums)):
if nums[i] != val:
# If the element is not val
nums[count] = nums[i]
count += 1
print(count)
I found some kind of example like this at Geeks for Geeks;
https://paste.pythondiscord.com/U5JQ
for some reason, in the above solution having it named count really throws me. because its using a var named count to both count instances of elements nums which are not equal to val, but also using count as an index to reassign values within the array nums
the conflation of the two really confuses me
is there some other way i can think of count or a better variable name
[
Media(
(pk=123),
...stuff here...
}),
),
];
what type of data type is this?
or how do i convert it into something python can read
it is a count
"how many values that are not val have I put in the array"
this is also the index if I want to put a new element
guys who can help me plz in some thing in python
Sure?
look i have microbit
its a card like arduino
I use opencv. When the camera opens, the system tells me to identify anything it sees. For example, if it sees the keyboard, it says it is a keyboard, like artificial intelligence. What did I do? I put two lines in the camera, a green line and a red line, and I said I am in the code. When a being called a human presses the red one, it says the word open. And when he touches the green line, he says “close,” and the command succeeds. Then I said, “When I touch the red line, it says open.” And when he says it, he sends a message to Com4, which has a microbit. And I said in the microbit code. When you receive the message, open, it draws a smiley face with its lights, and the same goes for the red color and when you receive the microbit. Message: Close. The microphone draws a house with its lights, an unsmiling face. Everything works, but when the camera turns on and I touch the red color that is supposed to be in the microphone, it draws the face.
The smiley, but do not draw it, although I see that the microbet is receiving a change through there is a yellow light in the back that tells me if there is a change or not.
hello
class Node:
def __init__(self,item):
self.item = item
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def insert_at_beginning(self, new_node):
if self.length == 0:
self.head = self.tail = new_node
new_node.next = None
else:
new_node.next = self.head
self.head = new_node
self.length += 1
def insert_at_end(self, new_node):
if self.length == 0:
self.head = self.tail = new_node
new_node.next = None
else:
self.tail.next = new_node
self.tail = new_node
self.length += 1
def insert_at_pos(self, index, new_node):
if index< 0 or index> self.length:
raise IndexError("Index out of range")
elif index == 0:
self.insert_at_beginning(new_node)
elif index == self.length:
self.insert_at_end(new_node)
else:
current = self.head
for i in range(index-1):
current = current.next
new_node.next = current.next
current.next = new_node
self.length += 1
def remove_from_first(self):
if self.length == 0:
raise "remove from empty list"
elif self.length == 1:
self.head = self.tail = None
else:
self.head = self.head.next
self.length -= 1
def remove_from_end(self):
if self.length == 0:
raise "remove from empty list"
elif self.length == 1:
self.head = self.tail = None
else:
self.tail = None
self.length -= 1
def __str__(self):
current = self.head
lst = []
while current is not None:
lst.append(str(current.item))
current = current.next
return "[" + ", ".join(lst) + "]"
should I make my linked list doubly to become able to delete from the end with a constant time?
class Solution:
def decodeAtIndex(self, s: str, k: int) -> str:
length_str = 0
numbers_set = {str(x) for x in range(10)}
# Get the amount of char it has (we used counter to save space)
for char in s:
if char in numbers_set:
length_str *= int(char) # If it is number than multiply it
else:
length_str += 1 # Else if letter just add 1
for char in reversed(s):
# The entire length of 3x leetleetcode (36 char) modulo (k % 36) is the index of it in the first line
k %= length_str
if k == 0 and char.isalpha():
return char
# The one line of text "leetleetcode" is 12 char and since 3 is the last number it will be
# 3x in this case it will be 36 char, in this case we'll be turning it into one line so back to 12
if char.isdigit():
length_str //= int(char) # If the char is number we can divide it can reduce the iteration
else:
length_str -= 1
e = Solution()
print(e.decodeAtIndex("leet2code3", 10))
Idk I am just that stupid but It hard to visualize, like the math on how to get it makes it looks vodoo to me
is this method implemented correctly?
def remove_element(self,element):
if self.length == 0:
raise Exception("list is empty")
elif self.length == 1:
if self.head.item == element:
self.head = self.tail = None
self.length -= 1
else:
raise ValueError("element not found")
if self.head.item == element:
self.head = self.head.next
return
current = self.head.next
prev = self.head
while current.item != element:
prev = current
current = current.next
if current == None:
raise ValueError("element not found")
prev.next = current.next
self.length -= 1
i'd like to revisit this. i'll begin working on it now in VSCode
s = '{}'
mapping = {')': '(', '}': '{', ']': '['}
for i in range(len(s)-1):
try:
if s[0] != mapping[s[1]]:
print(False)
exit()
except KeyError:
print(False)
exit()
print(True)
this one properly validates a string of len 2 only containing a single set of parenthesis. it rejects incorrect matches or parenthesis occurring in the wrong order, eg '}{'
i took the mapping from the other solution
Anyone herer
idk why they wrote in the closing parentheses as keys and the opening ones as values, i suppose to skip them and allow them to be a part of the stack in the original problem
i am but newby
I am a newbie too
what you need
I am lost, I am not able to decide if I should use python for learning data structure or c/c++
what i did not understand here was how we can just point at the list without calling ListNode anywhere, e.g. list1.val instead of referencing the ListNode class
i'm not sure, i would guess it depends on which language you want to familiarize yourself with and use later. this server is a good resource should you decide to use Python
just use a stack man
the primary leetcode problem i was trying to solve uses just that, this was a modified one to solve just a single set of parentheses which was suggested by another user
Idk why you'd only write it for one parentheses but sure
my suggestion was to try to solve it for only one kind of parentsesis
e.g. (()(()))()
which is a simpler version of the version where you allow multiple kinds
ohh
hmm okay let me try
hmm getting KeyError
wait nope
doesn't work
okay this seems to work:
s = '()()()('
def validfindr(string):
mapping = {')':'(','(':')'}
for i in range(len(string)):
if string[i-1] != mapping[string[i]]:
return False
return True
print(validfindr(s))
!e does that even work for the example I gave?
s = '(()(()))()'
def validfindr(string):
mapping = {')':'(','(':')'}
for i in range(len(string)):
if string[i-1] != mapping[string[i]]:
return False
return True
print(validfindr(s))
@haughty mountain :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
that should eval to False
the original leetcode problem, so long as an parentheses is not immediately followed by it's matching closing parenthesis, the string evals to false
let me get the link
hmm no that doesn't seem to be a requirement (what i mentioned above)
anyhow, how would you solve? in the case of parentheses string composed of all one type?
a stack
s = '(()))'
def validfindr(string):
stack = []
mapping = {')':'('}
for char in string:
if char in mapping:
if stack.pop() != mapping[char] or not stack:
return False
else:
stack.append(char)
return True
print(validfindr(s))
this one seems to work, but then i just built it looking at a solution 😭
i'm trying to visualize how it works
in the first char, the ( is not in mapping, because if char in mapping: is only looking at keys?
move on to another problem and keep thinking about this problem when u are going on a walk or whenever convenient
facts
hmm #35 Search Insert Position should be interesting
notably the runtime must be O(log(n)), therefore a recursive solution would work
i was trying to implement a binary search type paradigm, however, i get tripped up on trying to return the index of where the search term should occur in the case that the search term does not occur in the array
you don't need a stack for this version
sure its just easier imo
than just keeping a variable for the depth?
sure less memory required makes sense ig
the stack is basically an extension of the depth counter, but in the case where you need to care about paren types matching
it's just simpler
that is true I just find the stack easier intuitively
is this true
maybe write the solution without the dict
to understand what the solution is about
i think i understand it
!e
s = '(()(()))()'
def validfindr(string):
depth = 0
for c in string:
if c == '(':
depth += 1
else:
depth -= 1
if depth < 0:
return False
return depth == 0
print(validfindr(s))
@haughty mountain :white_check_mark: Your 3.12 eval job has completed with return code 0.
True
this is the most basic thing
the multiple paren version is an extension of the same thing
the counter is just "how many ( did I put in my stack" 😛
yes I know
i guess this makes sense. not straight away
i'm having trouble where i can study a solution enough and understand it, but developing my own solutions to the easy problems is a challenge
i think i've solved like 3 of them without looking up an answer. i usually can get on the right track but never quite get it, like the case where a binary search for problem 35 was the right approach, but i didn't know how to return the index of where the search term should occur, in the case it doesn't appear in the array
going to work on #35
whats the VSCode shortcut for block comment out?
cntl + /
so the way i am recursively implementing a binary search for the above problem, it will not work as i am breaking the array into smaller bits each time, and thus losing the original index information. any direction?
seems like if rather than giving the recursive call a slice of the original array, i could instead give it new indices, effectively passing it a new space to search
here is a solution:
def binsearch(array, tar):
start, end = 0, len(array)-1
while start <= end:
mid = (start + end) // 2
if array[mid] == tar:
return mid
elif array[mid] < tar:
start = mid + 1
else:
end = mid - 1
return start
print(binsearch([1,2,3,5,7,9], 8))
i tried to have chatgpt walk me through the approach without giving me code or pseudocode, but it doesn't listen
i stepped through it in my head and it seems to make sense, but dreaming it up on my own is another story
at least i can see now that there is a different variable returned, start, for the case when the search term does not occur in the array, rather than in the case where it does, which is mid
def print_numbers_version_two(upperLimit):
number = 2
while number <= upperLimit:
print(number)
# Increase number by 2, which, by definition,
# is the next even number:
number += 2
How many steps are there in this algorithm? My textbook says 2.5N
But I just see 2N
if you look close enough, you can see 5N steps
so counting steps doesnt make any sense
you should be interested in asymptotics (O(N) in this example) or iteration count (N/2 in this example)
Idk if you guys are interested but he(textbook author) might have been talking about a different example
also yeah he mentioned that steps don't matter he was just showing an example of how to count them
hi I'm currently learning wave function collapse how does this work? its pretty confusing
So I have a strange question...
What is the actual complexity of sleep sort? I'm assuming that the scheduler that dispatches the calls is not really O(N) in the number of tasks
why not
Well, suppose you just finished handling an event and you need to pick the next one. You need to choose the next timer, so you need to order them somehow
For example you use a BST, so every pick will be logarithmic
usually sorted on a heap
yeah, so not an O(1) pop iirc?
Yeah, so while setting up the timers you'll be doing more than O(N)
suppose so
Actually there's stuff like radix sort, I wonder why not use a variation of that? since the durations are usually in a rather limited domain
maybe radix-sorted heap is not a thing and I'm a dummy
some languages might, dunno
python probably just uses the sort it already has implemented
maybe not, i think all heaps work the same
like, there are different kinds of heaps, but they all still sort in log n by moving down the tree
schedulers usually use multi level feedback queues right?
i dunno what a multi level feedback queue is
removing the min/max value is log n because it needs to heapify again
it's just a bunch of fifo queues with different priority for running
only seen heaps in python, like in twisted:
https://github.com/twisted/twisted/blob/88151eb454ebc30d3cd69e30ab6fd762cdbe3cfa/src/twisted/internet/base.py#L1051
or trio:
https://github.com/python-trio/trio/blob/e317d9ca8c206417a855b1c989ee4afbf59dd905/src/trio/_core/_run.py#L248
or curio:
https://github.com/dabeaz/curio/blob/8667999a81f9daa147d2032b6985fc367679f095/curio/timequeue.py#L93
src/twisted/internet/base.py line 1051
def runUntilCurrent(self) -> None:```
`src/trio/_core/_run.py` line 248
```py
def next_deadline(self) -> float:```
`curio/timequeue.py` line 93
```py
def expired(self, deadline):```
asyncio uses heapq as well:
https://github.com/python/cpython/blob/6ca0e6754eedf4c9cf48794fa6c27281668b8d7c/Lib/asyncio/base_events.py#L1923
Lib/asyncio/base_events.py line 1923
def _run_once(self):```
https://en.wikipedia.org/wiki/Brain_Fuck_Scheduler gets away with a single queue i think
The Brain Fuck Scheduler (BFS) is a process scheduler designed for the Linux kernel in August 2009 based on earliest eligible virtual deadline first scheduling (EEVDF), as an alternative to the Completely Fair Scheduler (CFS) and the O(1) scheduler. BFS was created by an experienced kernel programmer Con Kolivas.The objective of BFS, compared to...
cool
Hello, Is there a package similar to dataclasses that allows you to use other types of data structures, such as Mappings, models with editable constructors?
The data entered could be similar to these.
mappings with undefined keys
{
"34ba7bc2-329h-2352-2323-abj3a7c1": {
"type": 1,
"title": "..."
},
"12f2a8b1-a4b1-c6f1-bbc2-a8f5f4": {
"type": 1,
"title": "..."
}
}
objects without key reference
{
"media": [
2,
"https://the-web-url",
null,
{
"title": "metadata: title"
}
]
}
?
to create classes similar to dataclasses.
class MyObject:
type: int
title: str
class ObjectMapping(Mapping[str, MyObject]):
...
class Media:
type: int
url: str
description: str | None
metadata: dict
hey everyone, i'm having trouble with this simple graph problem. my first thought was "oh, this is just asking if there exists a path from (1, 1) to (M, N) in the graph of cells, which is equivalent to asking if there exists a path from (M, N) to (1, 1)."
and since computing products are cooler than computing factors, i went with that second option and did a BFS in this initial solution.
getting TLE on the later test cases, i thought it must be a constant factor issue since i'm sure O(MN) is the lowest possible time complexity. but i couldn't figure it out, so i changed my graph a teeny bit, resulting in the second solution.
still TLE! i gave up - must be a "python too slow" issue, i thought. then i find this DFS python solution that passes on one judging website but not on another!
can you help me figure out where's the bottleneck in my two solutions, and why the third works? i appreciate any and all help, thank you!
You could try this BFS solution. This is how I would have solved that problem
n = int(input())
m = int(input())
A = [[int(x) for x in input().split()] for _ in range(n)]
BIG = 10**6 + 10
mapper = [[] for _ in range(BIG)]
for i in range(n):
for j in range(m - (i == n - 1)): # Avoid (n-1,m-1)
mapper[A[i][j]].append((i,j))
bfs = [(n - 1, m - 1)]
for i,j in bfs:
prod = (i + 1) * (j + 1)
bfs += mapper[prod]
mapper[prod] *= 0 # Empty the list mapper[prod]
if mapper[A[0][0]]: # Has mapper[A[0][0]] not been seen?
print('no')
else:
print('yes')
To make it run fast, my solution is very basic and uses no hash tables. I kind of doubt that it is possible to make a Python solution that runs much faster than this.
Btw in your BFS solution, I think you should have visited.add(neighbor) when appending neighbor to dq. You should probably also empty ADJ[value] after iterating over it to avoid going through it multiple times:
for neighbor in ADJ[value]:
if neighbor not in visited:
visited.add(neighbor)
dq.append(neighbor)
del ADJ[value]
My guess is that if you change to this then you will get AC ^
Played around optimizing my code some more
import sys
input = sys.stdin.buffer.readline
n = int(input())
m = int(input())
max_val = min(n * m + 1, 10**6)
A = [[min(int(x), max_val) for x in input().split()] for _ in range(n)]
BIG = max_val + 1
mapper = [[] for _ in range(BIG)]
for i in range(n):
Ai = A[i]
for j in range(m - (i == n - 1)): # Avoid (n-1,m-1)
mapper[Ai[j]].append((i + 1) * (j + 1))
empty_list = []
bfs = [n * m]
for prod in bfs:
bfs += mapper[prod]
mapper[prod] = empty_list # Empty the list mapper[prod]
if mapper[A[0][0]]: # Has mapper[A[0][0]] not been seen?
print('no')
else:
print('yes')
It easily gets full score
TL is 2 s
Could someone help me?, I really need it.
maybe try a different channel, this is not really a very DSA related thing
Which one does it suggest, I wrote here for the title data-structs
this channel is more about the computer science side of things
you could just try #python-discussion if you can summarize the question short enough, or if you need to include a bunch of context make a help thread and then mention it in #python-discussion with a link to the help thread
okay thanks
Hey guys, i tried to make a guessing game but gave up when i couldn't figure out how to stop a glitch.
gameStatus = input("Hello, this is a guessing game. Type and enter start to play")
a = "start"
b = "Start"
min_value = 1
if gameStatus.lower() == a or gameStatus == b:
max_value = int(input("Enter the maximum number that the game should use:"))
average = int(input("Now enter the average number:"))
while True:
guess = int(input("Give it your best guess: "))
if guess == average:
print("You have guessed correctly and won the game!")
break
elif guess > average:
max_value = min(max_value, guess - 1)
print(max_value, guess - 1)
print("You have guessed too high, the new guess ranges are from", min_value, "to", max_value)
elif guess < average:
min_value = max(min_value, guess + 1)
print("You have guessed too low, the new guess ranges are from", min_value, "to", max_value)
if guess < min_value or guess > max_value:
print("You guessed out of the boundaries")
Chat GPT code ^
#This code is a guessing game for practice.
gameStatus = input("Hello, this is a guessing game. Type and enter start to play")
a = "start"
b = "Start"
min = 1
if gameStatus == a or b:
max = int(input("Enter the maximum number that the game should use:"))
average = int(input("Now enter the average number:"))
guess = 1
while average != guess:
guess = int (input("Give it your best guess"))
if guess == average:
print("You have guessed correctly and won the game!")
if guess > average:
max = guess - 1
print("You have guessed too high, the new guess ranges are from", min, "to", max)
if guess < average:
min = guess + 1
print("You have guessed too low, the new guess ranges are from", min, "to", max)
if guess < min:
print("You guessed out of the boundaries")
if guess > max:
print("You guessed out of the boundaries")
My code ^
basically every time someone guesses a wrong answer that's too large or too small the code should narrow the gusses down. But i couldn't figure out how to stop the boundary from expanding if someone was to give a number outside of it.
chatgpt figured it out but i don't understand how
ik it has to do with the min and max function
check the pins first
Hi , want to start leetcode but facing difficulties with run-time and on top of that my way of doing stuff is crude most of the time like I always try to use greedy approach which is not suitable for everything . Is there anyway I can improve on my DSA coding clean. Man I suffered alot when I did an interview just because of DSA 😦
Yeah it's alright
I was wondering if anyone could help explain to me why this is not O(N^2)
If X is the amount of elements in the inner arrays, doesn't the inner loop loop X times for N elements (inner arrays)?
I recommend the book a Common Sense Guide to DSA by Jay Wengrow, it's meant for beginners
I'm going through it right now, the screenshot is from it
it depends on what you mean when you say "N"
Ohhh I get it now. Since N is the number of arrays, it is defintely O(N) then
wrong
if N is the number of arrays and K is the average length of arrays, then complexity is O(N K)
N represents how many numbers there are
it's almost like the answer will depend on how you define your parameters 🫠
O(n²) is just wrong though ||unless you're making dumb parameter choices on purpose||
if we have all the dimensions the same size O(n^2) is correct for "let n = the size of a dimension"
So it is O(N) because N is the total number of elements
with that choice of N, sure
I think that's what the textbook was saying N was
only after saying that O(n²) is wrong without in connection to it saying what n is
this is an equally correct answer with different parameters
I get what the textbook is trying to teach, but the phrasing is iffy to me
I agree
hello
im getting a recursion depth error in day 16 part 1
though it works just fine with test input
I have a function receives the current position and calculates a list with the next positions
and then i use those in a recursive function that i use to fill a dict
the stopping condition is met whenever that position has already been visited with the same direction
the error that i get is:
if (nxt_pos[0] < h and nxt_pos[0] >= 0
^^^^^^^^^^^^^^
RecursionError: maximum recursion depth exceeded in comparison
and i find it weird, cause why would it point at comparison as the cause of the bug in the recursion?
im new to python and the reason i want to learn is thrtough data automation. Could someone help me and maybe even just show me down the rihgt path?
i have anoconda because i was told it is good for what i want to do
||```py
def fill_tiles(energized, grid, curr, dr):
if curr not in energized:
energized[curr] = [dr]
else:
found = False
for tmp_dr in energized[curr]:
if tmp_dr == dr:
found = True
break
if found:
return
else:
energized[curr].append(dr)
for nxt, nxt_dr in calc_nxt(curr, dr, grid):
fill_tiles(energized, grid, nxt, nxt_dr)
calc_nxt returns an array of the next tiles to visit. It checks current tile, and depending on previous direction (dr) it can calculate it
the issue is basically the calc_nxt function is being called too many times
it's a function call pushing it over the limit, and the limit is just 1000 calls deep
your options are either to not writing it recursively (which is what I usually do) or raising the limit and hoping it's fine
and no, it's mainly a huge call stack with fill_tiles, and just something that pushes it over the edge
untested, but this is how I would write it
||```py
def fill_tiles(grid, start_curr, start_dr):
stack = [(start_curr, start_dr)]
energized = collections.defaultdict()
while stack:
curr, dr = stack.pop()
if (curr, dr) in energized and dr in energized[dr]:
continue
energized[curr].append(dr)
stack.extend(
for nxt, nxt_dr in calc_nxt(curr, dr, grid):
stack.append((nxt, nxt_dr))
return energized
roughly
ty mate
trying to keep the core of your code
and no it's not, python is quite bad at deep recursion and is notorious for putting a pretty low limit which you can easily run into doing a recursive dfs
def tri_recursion(k):
if(k > 0):
result = k + tri_recursion(k - 1)
print(result)
else:
result = 0
return result
print("\n\nRecursion Example Results")
tri_recursion(4)
Hey guys i'm having a hard time figuring out why this loops
there's no for loop but it still loops
because it calls itself
How come it doesn't just calculate the recursion for the value "4"
I'm definitely thinking about it the wrong way but my logic right now is that
since there's only two instances where it calls itself in the code
shouldn't it only calculate the argument twice
When you input 4, it does:
- k=4
- 4 > 0
- result = 4 + tri(4 - 1) -> 4 + tri(3)
- k = 3
- 3 > 0
- result = 3 + tri(3 - 1) -> 3 + tri(2)
- k = 2
- 2 > 0
- result = 2 + tri(2 - 1) -> 2 + tri(1)
- k = 1
- 1 > 0
- result = 1 + tri(1 - 1) -> 1 + tri(0)
- k = 0
- 0 == 0
result = 0
- result = 1 + 0
- result = 2 + 1 + 0
- result = 3 + 2 + 1 + 0
- result = 4 + 3 + 2 + 1 + 0
- result = 10```
shoot
How come it doesn't stop at the first calculation after "return result"
because it goes into the next iteration before reaching the return
Ah i'm trying to understand but it's still confusing why
so k starts off as number 4 in this code
I'm imagining that k turns to 3....2...1 after each loop
but how does it know to do that
result = k + tri_recursion(k - 1)
print(result)
Here all i can see is that there's a variable named result being assigned to an int expression
and then it's being printed
when assigning result, it includes a call to the current function
so it'll evaluate the function, then use the result to continue
I get it
So after each iteration it returns the new value to the caller
and then since that if statement is there, it'll keep doing it until it's 0
I still might be confused because this is saying that "return result" isn't executed until 3....2...1 happens
but if it's executed before that then i get it
nvm i'm still wrong
thank's though i'm going to keep rereading your explaination
glad to be of help
@quaint gorge it would be nice if you google "what is recursion in programming" and get some more abstract explanation about the concept of recursion in computer science...
Yea i'm going to do this
I think i underestimated the topic because i was following w3schools lol
going to go watch some vids on it
although not resource efficient it is considered one of the most elegant ways to solve a problem and some problems can only be solved through recursion. but due to not being resource wise in terms of memory and stack it is generally avoided
curious: do you have an example of a problem with recursion as the only solution?
@errant hearthTowers of Hanoi
I get it now, love you both 🙏🏾@errant hearth @muted wharf
great job!
Glad we helped 👍
Technically there isn't one, because every recursive function can be translated into an equivalent iterative function, but the latter is a lot less elegant most of the time
For the specific case of the Tower of Hanoi, there's actually an alternative method that uses binary to solve it
which traverse the tree in a recursive way which makes almost no diference to the CPU.... The complexity (Big-O, Big-Θ, and Big-Ω) remains the same
I'm not sure what you mean by "traverse the tree in a recursive way;" The alternate solution I'm talking about finds the rightmost unset bit to determine which disk to move each turn
As for the CPU, I'm not too familiar with machine language yet, but I don't think so? Recursion overhead is definitely a thing
Though the complexity being the same is right
When I'm saying is the same for the CPU I mean in an abstract way. I mean the complexity. On a low level perspective it depends on the programming language and the compiler which I suspect most of the times is deferent than actual recursion yes
Im running into a bit of an issue.
I have a bunch of categories and some of them correlate with each other but not all of the ones that do do not correlate with each other.
Whats a good way to visualize this.
There are 33 categories so its a bit of a mess with a heatmap.
For example A B and C correlate, D correlates with A and B but not C
okay so
how do i clone the contents of a string and list instead of treating them as objects?
i realize my code is copying them as object instead as their contents
as you can see:
i: !roll
Initiator
command_pivot=['!roll']
i: (1d10+2)
simple command
main_command=[['!roll', '(1d10+2)']]
main command appender
i: !if
Initiator
command_pivot=['!if']
i: (!roll
Initiator
sub_command_pivot=['(!roll']
i: (1d20)
simple command
main_command=[['!if', '(1d20)'], ['!if', '(1d20)'], ['!if', '(1d20)']]
i: >
content
i: 10)
Ender
main command appender
i: !else
Initiator
command_pivot=['!else']
i: (!echo
Initiator
sub_command_pivot=['(!roll', '(!echo']
i: (Failure))
simple command
main_command=[['!else', '(Failure))'], ['!else', '(Failure))'], ['!else', '(Failure))'], ['!else', '(Failure))'], ['!else', '(Failure))']]
result: [['!else', '(Failure))'], ['!else', '(Failure))'], ['!else', '(Failure))'], ['!else', '(Failure))'], ['!else', '(Failure))']]
https://paste.pythondiscord.com/67NQ
it was suppose to be
[["!roll", "1d10+2"], ["!if", ["!roll", "1d20"], "> 10"], ["!else", ["!echo", "Failure"]]
that grabbing my from my args string
def intersectionOfTwoArraysHashTable(array1, array2):
hashTable = {}
intersection = []
for num in array1:
hashTable[num] = True
for num in array2:
if hashTable[num] == True:
intersection.append(num)
print(intersection)
intersectionOfTwoArraysHashTable([1, 2, 3, 4, 5], [0, 2, 4, 6, 8])
What is wrong with my hash table?
I keep getting a type error but I don't know how else I'm supposed to check for True in the second for loop
the error you're getting is due to the number not existing in the dict
you probably only wanted an membership check
sorry to be pendantic here but, in python you're passing an list1, list2, not an array1 nor array2
oh, so what is the correct way?
do a membership check
I'm just trying to use a hash table for the first time and this is the problem I got
consider what happens if 0 does not exist in the dict for example
even though I can use in I'm trying to use a hash table, so I guess a dictionary in python
well
I thought the for loop would just continue
@orchid violet :x: Your 3.12 eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "/home/main.py", line 3, in <module>
003 | print(example[1])
004 | ~~~~~~~^^^
005 | KeyError: 1
wait really? I'm putting in the value?
1 does not exist as a key, so it raises an KeyError
@orchid violet :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
does that make sense?
yeah
I'm just trying to learn whatever is the standard way of using a hash table is I guess
are you coming from another language?
can you give me the correct code now then?
i'll try sure
a membership check is basically just does x exist in the container?
I'm stuck on how to use a hash table though with this
I can get this function to work with in
but that's not using a hash table
yes it is
oh
because an in lookup uses the dictionary (hashtable) to do the lookup in constant time
you could also use uh
!d dict.get
get(key[, default])```
Return the value for *key* if *key* is in the dictionary, else *default*. If *default* is not given, it defaults to `None`, so that this method never raises a [`KeyError`](https://docs.python.org/3/library/exceptions.html#KeyError).
def intersectionOfTwoArraysHashTable(array1, array2):
intersection = []
for num in array2:
if num in array1:
intersection.append(num)
print(intersection)
intersectionOfTwoArraysHashTable([1, 2, 3, 4, 5], [0, 2, 4, 6, 8])
so that is using a hash table?
oh
ok
so here is my thing, the solution was in javascript and so I've been trying to implement it in python
and I guess I just have to learn how python works lol
this was the textbook's solution:
function getIntersection(array1, array2) {
let intersection = [];
let hashTable = {};
for(let i = 0; i < array1.length; i++) {
hashTable[array1[i]] = true;
}
for(let j = 0; j < array2.length; j++) {
if(hashTable[array2[j]]) {
intersection.push(array2[j]);
}
}
return intersection;
}
so I was trying to declare a hash table variable in my python earlier but I guess I didn't even need to declare any sort of hash table
this is simpler than what i had done for you lol
def intersectionOfTwoArraysHashTable(array1, array2):
hashTable = {}
intersection = []
for num in array1:
hashTable[num] = True
for num in array2:
if num in hashTable:
intersection.append(num)
return intersection
print(intersectionOfTwoArraysHashTable([1, 2, 3, 4, 5], [0, 2, 4, 6, 8]))
but what is the point of the dictionary in there? it's not being used
it is ```py
for num in array1:
hashTable[num] = True
here
but you're not actually using it, no
But in my final solution I didn't even use a dictionary
yeah you don't need one
so all I did was use in to look within a list for membership?
i would use a set here honestly
that's not using a hash table is it?
like literally I'm just trying to use a hash table in python. that's all i'm trying to do
this is roughly how i'd done it ```py
def KRRT_impl(list1, list2):
temp1 = set(list1)
temp2 = set(list2)
return list(temp1.intersection(temp2))
sets use a hashtable under the hood of sorts
ok yes that makes sense but I'm taking a DSA class so I'm trying to do it without too many built in methods ya know
what does this do?
if(hashTable[array2[j]]) {
intersection.push(array2[j]);
i dont know any js
it checks if the value in array2 at index j is not null I think and then pushes it to intersection
idk though exactly if its checking if its null or not
so
if num in hashTable:
intersection.append(num)
``` essentially what this is doing?
actually no
in a way yes
in python, it just checks if the number exists in the hash table
if it does, "push"it to the intersection list
def intersectionOfTwoArraysHashTable(array1, array2):
intersection = []
mySet = set(array1)
for num in array2:
if num in mySet:
intersection.append(num)
print(intersection)
intersectionOfTwoArraysHashTable([1, 2, 3, 4, 5], [0, 2, 4, 6, 8])
So is this better
idk if this works, but is this also valid?
def f(a, b):
return [x for x in set(a) if x in set(b)
basically what u did, but in one line
and u can do the set() on array2 too
def f(a, b):
return list(set(a) & set(b))
precompute set(b)
otherwise you're re-making the set for every element
does the iterative and recursive form of an algorithm always have same time complexity ? idts
who wants to practice matplotlib with me?
the question doesn't exactly make sense, since the two would technically be different algorithms
it is true that for any algorithm A that uses iteration, there is an algorithm B that solves the same problem, uses recursion instead of iteration, and has the same time complexity as A
(and vice versa)
I cannot figure out why my code is wrong. I'm supposed to be getting f but I'm getting None.
# Write a function that accepts a string that contains all the letters of the alphabet
# except one and returns the missing letter. For example, the string, "the quick brown
# box jumps over a lazy dog" contains all the letters of the alphabet except the letter,
# "f". The function should have a time complexity of O(N).
def myFunction(my_string):
dictionary = {}
alphabet = "abcdefghijklmnopqrstuvwxyz"
for character in alphabet:
dictionary[character] = True
for character in my_string:
if not dictionary.get(character, False):
return character
#missing alphabet character = f
print(myFunction('thequickbrownboxjumpsoveralazydog'))
btw the purpose of this exercise is to practice hash tables
You've loaded the dictionary with a..z; hence, no message of lowercase-only text will ever have a letter in the message that's not in the (a..z-containing) dictionary. But, should you call your function with, say, any uppercase letter… Bingo!
A set would be the more-natural choice here. Sets are for testing membership / whereas, dictionaries are for doing key-->value lookups. The tip-off: You store the same value [True] for every [a..z] key; if every key returns the same answer, it's a major clue that you're only interested in the presence or absence of a key—and that spells “set.”
set(string.ascii_lowercase) - set('thequickbrownboxjumpsoveralazydog') #==> {'f'}
Some style-notes: Instead of typing the 26 letters of the alphabet, my above solution used ‘string.ascii_lowercase’ (the digits, uppercase-letters, etc. are also available—see: https://docs.python.org/3/library/string.html#module-string ). Using Python-provided initialized strings avoids the risk of introducing a hard-to-spot bug caused by a typo. The rule is: “Let the machine do the dirty-work.”
Also: If you're going to be comparing different messages against a set or dictionary whose contents does not change, then, you want to load that set only once—you should not be pointlessly reloading the dictionary here with the same info every time you test a new message's text.
And finally: As for your program's use of double-negatives—namely, using “if not False that the letter is not in the dictionary” to trigger the return—all I can say is:
Not bad it's not,
because double-negatives are burdensome to decipher.
There's no need for a double-negative here,
because Python lets you say exactly what you mean:
if k in d: print('Eureka!')
or, conversely,
if k not in d: print('Key not here; have you checked under the bed?')
how would i find the longest common substring between a string and an individual string from a list of strings efficiently
def longest_sub_ss(s: str, t: str, z: int = 0):
# Wikipedia-based
L = {}
ret = set()
for i in range(len(s)):
for j in range(len(t)):
if s[i] == t[j]:
L[i, j] = Lij = L.get((i - 1, j - 1), 0) + 1
if Lij > z:
z = Lij
ret = {(i, j)}
elif Lij == z:
ret.add((i, j))
return z, ret
def longest_sub_sl(s: str, l: list[str]):
most_len = 0
most_len_set = set()
for i, t in enumerate(l):
t_len, t_set = longest_sub_ss(s, t, most_len)
if not t_set:
continue
t_set = {(y, i) for y in t_set}
if t_len > most_len:
most_len = t_len
most_len_set = t_set
elif t_len == most_len:
most_len_set |= t_set
return most_len, most_len_set
``` here's some basic code and i'm not sure if there's a better algorithm
I don't think it's the same problem; OP only needs a substring common between a given string and another inside the list, not a substring common between all of them
doesn't this get the common for all strings inside the list
you can technically solve the standard problem in O(n+m) with suffix trees, it's just...quite involved and in practice kinda costly
rather than the O(nm) you have
any more info about the input like string sizes?
i think 100 characters maximum?
probably applied on a list with a length of up to 1024
and the one string is similar in size with the ones in the list?
yep
so, suffix automatons might be an interesting thing
they are apparently less annoying than suffix trees
linking to the section applying it for LCS
https://cp-algorithms.com/string/suffix-automaton.html#longest-common-substring-of-two-strings
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.
seems it would be enough to build the automaton for the one string, and you can re-use it for every subproblem
If the goal is speedy execution in Python, I suspect that none of the classical results on the analysis of algorithms
will be directly applicable to the programs that you transliterate from C (& the like) into C-Python. In C-Python [without a JIT specializer], looping is slow. The way to gain speed is to delegate as much of the work as possible to those modules that are written in C—even when this involves oddly indirect and convoluted paths, because reducing the overall
execution-time is the goal.
Is there a python library for lattice data structure with ordering and meet and join operators?
what is the best way to store an arbitrary amount of data, given that i want it to occur in what could be easily converted to a single column of a spreadsheet
nvm, i think i want to run sentiment analysis first and then drop that value into a csv in a specific col
i wanna check is like a certain string is part of string in a loop but not the whole string just the first six charecters i cant figure out how to match patterns like that without regex
I am intending to run a backtracking algorithm for a game and store the states in a data struct, where each element stores the current state of the game, how many steps it took to get to this state from the starting position and the best predecessor state
Now, since the backtracking algorithm will repeatedly come across already seen states, I need to be able to update the struct if the predecessor state has improved (in specific: if it took less steps to get to the same state, update the predecessor)
however then I'd also have to update all states emerging from that updated state by changing their distances to the start position as well, which is where I'm currently a bit stuck
a sample of how this could look like:
The uppermost node would be the root in this case, its distance to itself is 0
now if add an edge to this graph (red)
the distances for the red-circled elements would decrease
but if my graph/struct contains millions of nodes and I continuously add edges, changing the distances for entire parts of the graph will likely be too slow
!e
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.
Currently only 3.12 version is supported.
We've done our best to make this sandboxed, but do let us know if you manage to find an issue with it!
So my next semester is going to my introduction to algorithms is there anything you guys recommend to learn so when they show up I'll be more pre-pare. (Context, I basically know nothing about algorithms expect binary search)
I recommend reviewing highschool maths: exponential, logarithmic, linear, and polynomial functions, the concept of a function, sets, basic logic, basic probability, and combinatorics/counting.
Khan Academy is pretty good for that.
They also have a short algorithms course, if you want to get a head start: https://www.khanacademy.org/computing/computer-science/algorithms
But prioritise the material of your actual algorithms course.
you can speed it up by making the "get distance" operation slower
instead of having the actual distance in each node, store how much the distance in the node is different from the distance in the parent node
and by "parent node" I mean any parent node of the node, any is fine
and then to get the distance from the node, you go up the predecessors of that node and sum up the differences
That way updating the distance is O(1), and getting the distance is O(depth), which is likely to be small in your case
but if it is not, you can look up "Heavy-Light decomposition", it's a pretty complex data structure which will get you to O(log n) update and O(log^2 n) get
okay so i suck at doing it in C apparently
i got like 2x slower when i benchmarked it
that's suspicious
i think it's all the C to python object conversions
even so, conversion is linear, the algorithm is not, it shouldn't that that long
yeah apparently too many C to python object conversions
i'll try to make a better one when i have time to
Lazy propagation? The idea is to update distance only when you need it
Let's call the node you circled red n
When you add the red edge, the distance got better, so you want to update n and all nodes below it
Here's the trick: Only update n and its direct children (for now)
Update the distance of n, and update a .tag attribute of n's direct children. Don't do anything to anything below that
The .tag will function like an unresolved update
Later, once you traverse to a node m, use the .tag to update m's distance, then update the .tag of m's children
yeah that's neat, how would the propagation work if two changes occured in upper nodes and I want to fetch m's distance?
Well to get to m first, you need to start from the root right?
maybe let's consider some sample, then it'll probably get clearer for me
e.g. if I add the following edge now:
then the node with distance 4 would update to distance 2
and as you mentioned its direct child would update from dist 5 to dist 3
now if I select the node at the bottom and ask for its distance, how would be prop. work?
You update the tag of the child to 2, not the dist itself
Actually, I've been building on the assumption that once you determine the red edge is better, the predecessor should switch and the 3-4 edge should be removed?
yeah, it'll reduce the storage amount, but doesn't speed up the distance determination
if I want to know the distance of the node which currently has dist 6, I'd go backwards until the "newest change" is reached
however my issue is that I can't know what's the newest change
for instance I'd store the best predecessor:
as an arrow symbolized here
if I add an edge
the predecessor of 5 updates
because it found a better one
so now the distance of that 5-node becomes 3
however I won't yet update all of the lower nodes of the changed node
now if I want to know the distance of the node with value 3
I'd walk backwards regarding the best predecessors
to determine the distance
the basic way would be to walk back to the root
and update all nodes on the way to the root
(I added another node on the bottom for clarity)
walked back to the root and now since I know the distance, I can update all of the circled nodes
however there is a problem with this approach
because if I don't update the children until I ask for the distance
then adding a new edge may change the predecessor falsely!
like this
so now I added an edge
but because the predecessor (6) was not yet updated
it thinks the connection to the left must be the best
but that isn't always the case
class Node:
parent: Node
distance: int
children: list[Node]
tag: int = float('inf')
def resolve(self):
if self.tag is not None:
self.distance = self.tag + 1
self.propagate()
self.tag = None
def propagate(self):
for child in self.children:
child.tag = self.distance
def get_dist(node: Node):
stack = [node]
while stack[-1].parent is not None:
stack.push(node.parent)
for n in stack[::-1]:
n.resolve()
return node.distance
```I was thinking something like this
The downside is that get_dist is now O(depth), and the upside is that updating is O(1)
yea that's not desirable for my case, sry
preferrably get_dist is O(1) and update is less than O(depth)
the nodes would somehow need to know which state they're in in order to tell whether they're up to date
hm maybe it's just best to update all of the children
I'm not sure if that's achievable
me neither, it'd certainly be a data struc I don't yet know, or at least some graph with grouping properties
well update doesn't have to be less than O(depth) depending on what update does
just get_dist needs to be O(1)
and update shall make minimal use of the graph
The only thing that comes to mind right now is something like heavy-light decomposition, which will knock both complexities down to log level
I'll experiment a bit more, thx for the suggestions :)
Actually it'll be more complicated as you're adding & removing edges, so you might need a link-cut tree
@narrow mica @slate hedge
just to check I understood the problem, it's conceptually trying to keep a shortest path tree up to date during edge additions?
In mathematics and computer science, a shortest-path tree rooted at a vertex v of a connected, undirected graph G is a spanning tree T of G, such that the path distance from root v to any other vertex u in T is the shortest path distance from v to u in G.
In connected graphs where shortest paths are well-defined (i.e. where there are no negative...
I think it is, though it's changing edges such that the graph is still a tree
wait
adding an edge will make a tree not a tree
Well it's not only adding, they'll remove the old edge connected to the parent if that new one is added
in my head there is the shortest path tree, and there is an underlying graph it's the shortest path tree to
and you add edges to the underlying graph
No it's just a tree
The red edge is them attempting to reduce the distance from a node n to the root, and if successful, n will swap its predecessor
is the end result not just wanting to know the shortest distance from the root to nodes?
for the current graph
Actually wait
I think they just want the depth of each node?
Because if it's just a tree the distance is just the depth
And I guess the problem is, in order for them to determine whether the original or the red edge is better, they need to know the depth at the moment
So they can't do offline updates
I'm saying that in my head you're adding this red edge to some underlying graph, which might cause the shortest path tree (or I guess just shortest path info in general) to update
Wait I think I get what you mean
I don't think OP said something about it though
I'm trying to see the x behind the y 😅
if this is the case the real problem seems more like a dynamic shortest path problem
as I add edges, track the shortest paths
Well this is the original quote
I am intending to run a backtracking algorithm for a game and store the states in a data struct, where each element stores the current state of the game, how many steps it took to get to this state from the starting position and the best predecessor state
Now, since the backtracking algorithm will repeatedly come across already seen states, I need to be able to update the struct if the predecessor state has improved (in specific: if it took less steps to get to the same state, update the predecessor)
but if the thing I think I see is actually what's going on and this is really a dynamic shortest path problem in disguise, then there are things like
https://en.wikipedia.org/wiki/D*
D* (pronounced "D star") is any one of the following three related incremental search algorithms:
The original D*, by Anthony Stentz, is an informed incremental search algorithm.
Focused D* is an informed incremental heuristic search algorithm by Anthony Stentz that combines ideas of A* and the original D*. Focused D* resulted from a further de...
!source
guys help, I am sort of new to python, I am wondering how I can sort a list of dictionaries by a value of the dictionaries??
please help!!!
check on stackoverflow, its a very popular question
or look at any docs for the sorting functions that will tell you that you can specify a key to sort by
is there a better way to get the length of the fractional part of a fractions.Fraction() than this ```py
def ndec_places(x):
assert isinstance(x, Fraction)
y = x
j = 0
seen = set()
while y := y % 1:
if y in seen:
# cycled; infinite places
return math.inf
seen.add(y)
j += 1
y *= 10
return j
check the prime factorizations of numerator and denominator
if any factor other than 2 or 5 is leftover then its inf
yeah but i also need to get the length
it seems more efficient to just add to a set and check for that while getting the length
I think the number of decimal places will be the maximum of the number of twos and fives in the prime factorisation of the denominator, right?
But your approach seems alright I guess ¯_(ツ)_/¯
def decimal_places(fraction):
twos = prime_exp(fraction.denominator, 2)
fives = prime_exp(fraction.denominator, 5)
if 2**twos * 5**fives == fraction.denominator:
return max(twos, fives)
else:
return math.inf
def prime_exp(number, prime):
exp = 0
while number % prime == 0:
exp += 1
number //= prime
return exp
you need to subtract the twos and fives in the numerator first i think
I think fraction.Fraction always reduces to lowest terms?
Not sure about that actually.
oh it does
so like ```py
def decimal_places(fraction):
if not fraction:
return 0
x = fraction.denominator
fives = 0
while not x % 5:
fives += 1
x //= 5
twos = 0
while not x & 1:
twos += 1
x >>= 1
return max(twos, fives) if x == 1 else math.inf
there should be a better way to do the twos loop right
https://stackoverflow.com/questions/40608220/pythonic-way-to-count-the-number-of-trailing-zeros-in-base-2
i'm gonna time it against this
Lgtm. Although I don't think you need to special case fraction == 0.
Oh yeah there is a trick to calculate the zeros at the end of a binary number right.
yeah the one-liner wins
oh cool l3viathan has an answer here
Small world lol
Hi guys !!
I need a little help in or-tools.
I am using this code but not sure how to allow multiple depots or different start and end location for each vechicle?
Hastebin is a free web-based pastebin service for storing and sharing text and code snippets with anyone. Get started now.
hi guys
really quick q
i have a string '20220101'
is it possible to use datetime module to convert it into a datetime object "year-month-day"
?
sure, use strptime with the right format specifier
right,thanks guys
Now answer my question 😄
def solution(number):
arr = []
if number == -1:
return
for num in range(1, number):
if num % 3 and num % 5 == 0:
print(f'{num}: 3 and 5')
#arr.append(num)
if num % 3 == 0:
print(f'{num}: 3')
#arr.append(num)
if num % 5 == 0:
print(f'{num}: 5')
#arr.append(num)
return arr
print(solution(10))
why does the first line get executed here? I know swapping the other 2 ifs to elifs gives the results I'm looking for. Just wondering why does the first if statement execute for the number 5?
oh wait nvm I think i see
lol oops
I'm not checking the first one to anything
Hello i have the following code about data with density in the earths core.
def premfunc(r):
R = 6371
x = r/R
if 0<=r<=1221.5: #inner core
rho_x = 13.0885-8.8381 x**2
elif 1221.5<r<=3480: #outer core
rho_x = 12.5815 - 1.2638x - 3.6426x**2 - 5.5281 x3
elif 3480<r<=5701: # Lower mantle
rho_x = 7.9565 - 6.4761x + 5.5283x2 - 3.0807x**3
elif 5701<r<=5771: # transition zone 1
rho_x= 5.3197 - 1.4836x
elif 5771<r<=5971: #transition zone 2
rho_x= 11.2494 - 8.0298* x
elif 5971<r<=6151: #transition zone 3
rho_x= 7.1089 - 3.8045x
elif 6151<r<=6291: #Low velocity zone
rho_x= 2.6910 + 0.6924x
elif 6291<r<=6346.6: #LID
rho_x= 2.6910 + 0.6924*x
elif 6346.6<r<=6356: #Lower Crust
rho_x=2.9
elif 6356<r<=6368: #Upper Crust
rho_x=2.6
elif 6368<r<=6371: #Ocean
rho_x=1.020
else:
rho_x = 0
rho_x = rho_x *1000
return rho_x
In this code r= the radius of the earth and R=the maximum radius or the radius of the earth with x being the density.
Now the exercise is to have the average density of each zone in the earths crust/mantle etc with numpy, i used np.average to get the average density of the whole earth. So the question is: How do i make a code for calculating the average density of each zone?
Thank you
R = 6371
x = r/R
if 0<=r<=1221.5: #inner core
rho_x = 13.0885-8.8381 *x**2
elif 1221.5<r<=3480: #outer core
rho_x = 12.5815 - 1.2638*x - 3.6426*x**2 - 5.5281* x**3
elif 3480<r<=5701: # Lower mantle
rho_x = 7.9565 - 6.4761*x + 5.5283*x**2 - 3.0807*x**3
elif 5701<r<=5771: # transition zone 1
rho_x= 5.3197 - 1.4836*x
elif 5771<r<=5971: #transition zone 2
rho_x= 11.2494 - 8.0298* x
elif 5971<r<=6151: #transition zone 3
rho_x= 7.1089 - 3.8045*x
elif 6151<r<=6291: #Low velocity zone
rho_x= 2.6910 + 0.6924*x
elif 6291<r<=6346.6: #LID
rho_x= 2.6910 + 0.6924*x
elif 6346.6<r<=6356: #Lower Crust
rho_x=2.9
elif 6356<r<=6368: #Upper Crust
rho_x=2.6
elif 6368<r<=6371: #Ocean
rho_x=1.020
else:
rho_x = 0
rho_x = rho_x *1000
return rho_x
jesus fucking christ 💀
bro just read A Common Sense Guide to DSA by Jay Wengrow. It's so good
ty
am not getting how to improve performance of my codes
def climbingLeaderboard(ranked, player):
# Write your code here
returnrank = []
highestscore = 0
for p in player:
prank = 1
for i in range(len(ranked)):
cscore = ranked[i]
if ranked[i-1] == cscore:
continue
if cscore > p:
prank += 1
returnrank.append(prank)
return returnrank
in this one i have to implement 'dense ranking'
Binary search?
i don't get it how will i keep track of multiple same scores then ?
The idea is for each number in player, binary search where it is in ranked to quickly get the ranking for that number
You could do a bit of pre-processing on ranked to reduce consecutive runs of the same number to a single number.
Or are the parameters of the problem such that ranked is much larger than player, and you have to find a solution that's less than O(n) with respect to the length of ranked?
Does anyone have any idea ab camera model and projection matrices ?
Hey guys I need some help
Is there anyway to take linux system calls and turn them into stack traces
i cannot understand this solution
You are given an array a of n integers. Count the number of pairs of indices (i,j) such that i<j and a_j−a_i=j−i.
basically the idea in an array is check if
nums[i] - nums[j] == i - j
obviously something like
n = 6
arr = [3 5 1 4 6 6]
total = 0
for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] - arr[j] == i - j:total += 1
basically that would be the easiest way
but the problem is you need to check larger inputs
so the real solution is
nums = [3, 5, 1, 4, 6, 6]
hashmap = {}
for i in range(len(nums)):
diff = nums[i] - i
if diff in hashmap:
hashmap[diff] += 1
else:
hashmap[diff] = 1
print(sum([n * (n-1) // 2 for n in hashmap.values()]))
i was researching a bit so i found
n * (n-1) // 2 is for count the number of unordered pairs of different values
for example
{a,b,c} = {a, b}, {a, c}, {b, c}
but i dont understand why would you store the diff
and how are you getting the solution by doing this
this is a simple code i dont know how i cannot understand it
Rearrange your original equation
a_j - a_i = j - i
a_j - j = a_i - i # <-- on each side is the difference between some index k and the value a_k
```So you can instead count how many indices `k` satisfies `a_k - k = d` for some arbitrary `d`.
Say there are `5` indices, `u, v, w, x, y`, satisfying `a_k - k = 1`. Choosing any 2 of the 5 indices from here will give you a pair of indices that satisfies the original equation. Thus, these 5 numbers will add to the answer the number of ways you can uniquely choose 2 items from a set of 5.
Now we only counted those with a_k - k = 1. We need to do that for all d.
Using a hashmap, we can record all the different values of d that showed up, and how many indices satisfy a_k - k = d. Then we can just go over each unique value of d and sum up count choose 2.
thanks buddy I will analyze it
thanks, it was helpful
no players can be approximately equal or even larger than ranked in size
is this doubly linked list method correct?
https://leetcode.com/problems/domino-and-tromino-tiling/description
Can someone plz hold my hand and tell me it's okay to think that this sentence is totally meaningless
Two tilings are different if and only if there are two 4-directionally adjacent cells on the board such that exactly one of the tilings has both squares occupied by a tile.
Can you solve this real interview question? Domino and Tromino Tiling - You have two types of tiles: a 2 x 1 domino shape and a tromino shape. You may rotate these shapes.
[https://assets.leetcode.com/uploads/2021/07/15/lc-domino.jpg]
Given an integer n, return the number of ways to tile an 2 x n board. Since the answer may be very large, retu...
What does 4-dirextionally adjacent mean in a 2xn board ?
Is cell=square ?
Hi, anyone would know how to translate "sketch data structure" in French or any other latin language? I fail to find translations for this?
The term "sketch data structure" in French would most likely be translated as "structure de données de sketch". In the context of computer science, "structure de données" is a direct translation of "data structure", and "sketch" is often kept in English, as it refers to a specific concept or type of data structure.
In simpler terms, you can distinguish two tilings by finding a pair of adjacent squares where one tiling covers both with a single tile, and the other tiling does not. This rule is probably used to count or compare different ways of covering a board with tiles.
thanks, "un sketch" donc 🙂 in French sketch is used as a comical scene ("saynète") so it's always a tad weird to use to describe a data structure, but I don't think it has another translation
Hey, so I have a weighted graph of connections. I'm using a dijkstra algorithm to find the shortest path between 2 nodes.
But what if I don't know the weight of some connections?
Let's say that the shortest path (weight-wise) between A and B would be A->C->D->B but in terms of jumps it would be A->C (we dont know the weight of A-C connection). So my program should return A->C in this case
and then if in any time we would discover the weight of A-C it would update it's path
how can i make dijkstra work like this?
guys
i'm a senior year highschool graduate
bout to take a degree in cs
i've got like a 4 months time for that
so
should i
start studying
data structures and algorithms
rn
Hi All, is there any book of O’reilly on algorithms and data structures (written in python)? Please let me know
the answer is an obvious yes I think
there's a book I had Algorithms in a Nutshell which uses python examples, however I'm not sure if there's an O'reilly book which explains DSA in depth since the one I mentioned gives a brief overview on each topic.
Hello everyone (and happy new year!). I have completed a couple python courses online, and i am now trying to practice on Codewars and Leetcode. However i am kinda reaching a plateau (especially on Leetcode) because of new data structures and/or algorithms i don't know at all (e.g. binary search, two pointers, linked lists, trees etc).
My request is kinda simple: can you please recommend some (free, if possible) resources that cover these? I did find so many online/on youtube, but they weren't great/comprehensive enough.
Thanks !
ok bro
what do you guys think of this bresenham circle implementation? to be honest i dont remember the specifics of why the algorithm works, i just found it in my old code and spruced it up
def bresenham_circle(pos,radius):
x2,y2 = pos
switch = 3-(2*radius)
x,y = 0,int(radius)
while x <= y:
yield from [
(x+x2,-y+y2),
(y+x2,-x+y2),
(y+x2,x+y2),
(x+x2,y+y2),
(-x+x2,y+y2),
(-y+x2,x+y2),
(-y+x2,-x+y2),
(-x+x2,-y+y2)
]
if switch < 0:
switch = switch+(4*x)+6
else:
switch = switch+(4*(x-y))+10
y-=1
x+=1
before i was adding all the points to a set but i think using a generator expression works better
unless it'd be faster to do individual yield statements, idk
I would probably write 8 yields instead
kk