class Board:
def __init__(self, state):
self.state = state
self.childrenList = []
self.parent = None
self.depth = 0
self.visited = False
#Function to generate the list of child boards.
def generateChildList(self):
#--TODO-- make sure children are legal and not the same as parent.
tempState = self.state
temp = Board(self.up(tempState))
temp2 = Board(self.down(tempState))
temp3 = Board(self.left(tempState))
temp4 = Board(self.right(tempState))
#Set child depth.
temp.depth = self.depth + 1
temp2.depth = self.depth + 1
temp3.depth = self.depth + 1
temp4.depth = self.depth + 1
#Check to make sure that a child does not have the same board layout as a parent.
#If the parent is not the solved state, then a child with that same state will not be solved.
if temp.state != None:
self.childrenList.append(temp)
if temp2.state != None:
self.childrenList.append(temp2)
if temp3.state != None:
self.childrenList.append(temp3)
if temp4.state != None:
self.childrenList.append(temp4)
#Set visisted to true.
self.visited = True
#Board moves. (Up,Down,Left,Right)
#If the 0 is in the top line, it cant go up.
def up(self, state):
position = state.index(0)
#Check for an illegal move.
if position in (0,1,2):
return None
else:
#Create a temp list for the new positions.
newPositions = list(state)
#Swap the positions of the board.
newPositions[position], newPositions[position-3] = newPositions[position-3], newPositions[position]
#Return the new list of positions.
return tuple(newPositions)
#If the 0 is in the bottom line, it cant go down.
def down(self, state):
position = state.index(0)
#Check for an illegal move.
if position in (6,7,8):
return None
else:
#Create a temp list for the new positions.
newPositions = list(state)
#Swap the positions of the board.
newPositions[position], newPositions[position+3] = newPositions[position+3], newPositions[position]
#Return the new list of positions.
return tuple(newPositions)
#If the 0 is in the left most side, it cant go left.
def left(self, state):
position = state.index(0)
#Check for an illegal move.
if position in (0,3,6):
return None
else:
#Create a temp list for the new positions.
newPositions = list(state)
#Swap the positions of the board.
newPositions[position], newPositions[position-1] = newPositions[position-1], newPositions[position]
#Return the new list of positions.
return tuple(newPositions)
#If the 0 is in the rightmost side, it cant go right.
def right(self, state):
position = state.index(0)
#Check for an illegal move.
if position in (2,5,8):
return None
else:
#Create a temp list for the new positions.
newPositions = list(state)
#Swap the positions of the board.
newPositions[position], newPositions[position+1] = newPositions[position+1], newPositions[position]
#Return the new list of positions.
return tuple(newPositions)
#algos-and-data-structs
1 messages · Page 145 of 1
:ok_hand: applied mute to @fiery cosmos until <t:1644302146:f> (9 minutes and 59 seconds) (reason: duplicates rule: sent 4 duplicated messages in 10s).
I figured out my issue. I implemented IDDFS. Only issue now is it's super super slow.
there is a 3 litre and a 5 litre jug. how can he measure a exactly one litre of water?
whats the quickest way to do this?
this is what i found online
can't understand it
3*2-5=1
first fill the 5 litre jug with 3 litre jug once. then there will be two litres space in 5 litre jug.
fill 5 litre jug until full with 3 litre jug once.
that is good!
just remained only one litre in 3 litre jug.
so u fill the 3 litre jug fully with 5L one
fill 5 litre jug until full with 3 litre jug once.
whats that suppose to mean
also idk why we have to do this is algorithmics class
ig it suppose to be a introduction
Does this help
[_____]
[___]
[_____]
[###]
[###__]
[___]
[###__]
[###]
[#####]
[#__]
oooh yep
thx a lot
Hi. which algorithm should i use to solve this problem thanks.
what's Big o for py def Add(self,*data): temp = self.head self.head = Node(data[0]) self.head.next = temp temp.previous = self.head for i in data[1:]: self.head.previous = Node(i) self.head.previous.next = self.head self.head = self.head.previous
what do you think?
n
does someone know what change i need to make to the dijkstra algorithm to make it so that the edges can be for a car or someone walking (or both), when the algorithm chooses to use a walking path it needs to leave the car behind and only choose walking paths until its at the destination vertex
i have changed the edges to include the data, tho idk what id need to change in the algorithm
you could include some flag or enum or something to show off your a car or walking, then you can choose paths based on the flag
the algorithm needs to choose for itself if its going to leave the car to do the rest walking
so it starts in a car and then at every node it can choose to leave the car behind and do the rest walking
I c
so it somehow needs to explore all edges in a car without finishing the vertices and then explore all walking paths and finish the nodes
something like that i think, tho im not sure
Hey @halcyon kraken!
It looks like you tried to attach file type(s) that we do not allow (.save_multipla). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
Well i thought generally length of data will be 1 so it will be constant and even if data is 2 or 5 or any constant no, it was like O(2) or O(5). So its again constant but then i also thought that len(list) can be 1 and constant integer and if i was to iterate through it , big O will be O(n). but still i wasn't sure. What is it ?
just keep a boolean in the state of whether you've ditched the car, and in the traversal allow "car path+keep car" and "walk path+ditch car" if car not ditched yet, or walk path only if car ditched
thanks! gonna try it
you can also model is just by changing the graph, have two copies of the graph, one with car and one without
and then allow to move to the corresponding node in the graph without car for free
it's probably the neater option
car graph, no car graph, directed edges from the first to the second graph
ahh thats pretty smart! so find best path in both and then check in both results from where it could be faster to ditch the car?
So gcd stands for greatest common divider
Is this underlined statement gcd(a', b) % d true because gcd(a', b) = d and d % d
Does anyone know—or know any literature on—the amount of error introduced by doing comparisons on the floating point representation of rational numbers, versus comparing the rationals themselves?
Like, for a Fraction in the fractions package, rational numbers are compared by converting each to the same denominator, and then comparing the numerators.
well, naively (or exactly? not sure. It is basically asking if float division is perfectly accurate to within float precision, which I believe is true), the error of converting a rational into a float is around the float precision near that float - so, basically math.ulp(a/b)
so at worst, I think the difference between Fraction(a,b) - Fraction(c,d) exactly and a/b - c/d is around math.ulp(a/b)+math.ulp(c/d)
if that error is higher than the difference between the fractions, then floats may cause the comparison to have a wrong result
If that's not what you want, try asking on the Computer Science server too - I have asked questions about floating-point errors there with great success
No, that answers my question 😅 Thank you! Now I just have to contemplate whether that is small enough that I can safely say it will never occur...
it can definitely occur sometimes, e.g. consider:
!e
from fractions import Fraction as F
def cmp(x,y):
return (x>y)-(x<y)
def test(f1,f2):
return cmp(f1,f2) != cmp(float(f1),float(f2))
x = 10**20
a = F(x,x)
b = F(x,x+1)
print(test(a,b))
print(a,b)
print(float(a),float(b))
@vocal gorge :white_check_mark: Your eval job has completed with return code 0.
001 | True
002 | 1 100000000000000000000/100000000000000000001
003 | 1.0 1.0
here, the second fraction is 1 too as far as floats are concerned
!e
from fractions import Fraction as F
import math
x = 10**20
a = F(x,x)
b = F(x,x+1)
total_error = math.ulp(float(a)) + math.ulp(float(b))
delta = float(a-b)
print(f"{delta=}, {total_error=}")
@vocal gorge :white_check_mark: Your eval job has completed with return code 0.
delta=1e-20, total_error=4.440892098500626e-16
the total error is indeed much higher than the delta between the numbers, so the rule works here
I certainly see what you mean. I was really hoping to get away with using floats, but for robustness it seems that won't work.
How to make discord bot with python
it means the runtime increases linearly as you increase the input size
or the amount of memory you use
I generally think of it in terms of the effect of doubling the size of the input.
O(n) runtime (essentially) means if you double the size of the input, n, you double the runtime.
O(1) means if you double n, the runtime stays the same.
O(n^2) means if you double n, the runtime is multiplied by four.
O(n^3) ... multiplied by eight.
And so on.
Linear runtime
O(N):
for i in range(my_list):```
O(1):
```py
for i in range(10):```
O(N^2):
```py
for i in range(my_list):
for j in range(my_list):```
O(N^3):
```py
for i in range(my_list):
for j in range(my_list):
for x in range(my_list):```
for a in range(lmao):
for b in range(lmao):
for c in range(lmao):
for d in range(lmao):
for e in range(lmao):
for f in range(lmao):
for g in range(lmao):
for h in range(lmao):
for i in range(lmao):
for j in range(lmao):
for k in range(lmao):
for l in range(lmao):
for m in range(lmao):
for n in range(lmao):
for o in range(lmao):
for p in range(lmao):
for q in range(lmao):
for r in range(lmao):
for s in range(lmao):
for t in range(lmao):
for u in range(lmao):
print('lol')
This is O(n^21) time complexity
script:
a=''
b=97
while True:
print(a+'for '+chr(b)+' in range(lmao):')
a+='\t'
b+=1
Hey @rain sparrow!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
how to find time complexity
import random
while True:
if random.randint(0, 1) == 0:
break
``` what is time complexity of this code?
strictly speaking it is O(inf), but in practice it is O(1)
Hello everyone, if there is no issue, could you please help me. Actually I just want to alter bars' colours and the background colour. However when I do add color="gold" for example, some syntaxis error appear. I am a newbie to Python, so would be grateful if you help. The code was taken from sergei perfiliev. He allows to change it on his twitter acc.
https://paste.pythondiscord.com/anovozucuc.py
Could you please help me with that
arr=[3,2,4,5,21,2,4,5]
for x in range(len(arr)):
for i in range(len(arr)-1):
if arr[i]%2!=0 and arr[i+1]%2==0:
current=arr[i]
arr[i]=arr[i+1]
arr[i+1]=current
print(arr)
This is a program that puts all even numbers in first half of the list and the odd numbers after that what I don't understand is why does outer loop have to go to len(arr)
help !!
I wanna create a sub array from a given array , but for a specific range..
how this could be done?
for eg-
arr = [ 1, 2, 3 , 7, 4, 9 ,8]
new array from 3 to 9 , in the same order as in "arr"
new_arr = [3,7,4,9]
plzz help!
arr = [ 1, 2, 3 , 7, 4, 9 ,8]
arr2=[]
a=int(input('a='))
b=int(input('b='))
x=0
while arr[x]!=a:
x+=1
y=0
while arr[y]!=b:
y+=1
if y>x:
for i in range(x,y+1):
arr2.append(arr[i])
else:
for i in range(y, x+1):
arr2.append(arr[i])
print(arr2)
tfw you reimplement slicing
Hey guys, I dont really know how to use this server ahaha, but I have been trying to navigate my way through telemetry Scripting in python. Can anyone provide any sources to help me find some info?
Hi! How can i change a repeated element inside a column of a Matrix?
The Matrix Is NxM
O(lmao^21)
If I had to find the longest path in a graph would this code/solution work
function findlongest(inx, distance)
maxdistance = 0
proccesed[vertex] = 1
for vertex in connections(inx)
if proccesed[vertex] = 1:
continue
if findlongest(vertex, distance+1)>maxdistance
maxdistance=findlongest(vertex, distance+1)
return (distance+maxdistance)
#this is kinda the logic, not the actual code
not really, it would kinda work for a tree, but not for a general graph
longest path in a general graph is a NP-hard problem
hey anyone cna help me so i started coding like few days ago and im making pong game yk for learning and the ball gets stuck in the ground
ball.setx(ball.xcor() + ball.dx)
they say this is the problem
but for going up its the same just changed xcore and dx to y
ball.sety(ball.ycor() + ball.dy)
what do i do?
the update rules for dx and dy is probably the issue
you haven't posted how you update dx and dy
wdym posted
code
which one
for what the logic for dx and dy is
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
actaully 90 lines
import turtle
wn = turtle.Screen()
wn.title("Pong by @roberts_vierpe")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
Paddle A
paddle_a1 = turtle.Turtle()
paddle_a1.speed(0)
paddle_a1.shape("square")
paddle_a1.color("white")
paddle_a1.shapesize(stretch_wid=5, stretch_len=1)
paddle_a1.penup()
paddle_a1.goto(-350, 0)
Paddle B
paddle_b1 = turtle.Turtle()
paddle_b1.speed(0)
paddle_b1.shape("square")
paddle_b1.color("white")
paddle_b1.shapesize(stretch_wid=5, stretch_len=1)
paddle_b1.penup()
paddle_b1.goto(350, 0)
Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.1
ball.dy = 0.1
Functions
def paddle_a1_up():
y = paddle_a1.ycor()
y += 20
paddle_a1.sety(y)
def paddle_a1_down():
y = paddle_a1.ycor()
y -= 20
paddle_a1.sety(y)
def paddle_b1_up():
y = paddle_b1.ycor()
y += 20
paddle_b1.sety(y)
def paddle_b1_down():
y = paddle_b1.ycor()
y -= 20
paddle_b1.sety(y)
Keyboard Binding
wn.listen()
wn.onkeypress(paddle_a1_up, "w")
wn.onkeypress(paddle_a1_down, "s")
wn.onkeypress(paddle_b1_up, "Up")
wn.onkeypress(paddle_b1_down, "Down")
Main Game loop
while True:
wn.update()
# Move The Ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border Checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dx *= -1
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
its at move ball
do
```py
your code here
```
for code formatting
k
import turtle
wn = turtle.Screen()
wn.title("Pong by @roberts_vierpe")
wn.bgcolor("black")
wn.setup(width=800, height=600)
wn.tracer(0)
# Paddle A
paddle_a1 = turtle.Turtle()
paddle_a1.speed(0)
paddle_a1.shape("square")
paddle_a1.color("white")
paddle_a1.shapesize(stretch_wid=5, stretch_len=1)
paddle_a1.penup()
paddle_a1.goto(-350, 0)
# Paddle B
paddle_b1 = turtle.Turtle()
paddle_b1.speed(0)
paddle_b1.shape("square")
paddle_b1.color("white")
paddle_b1.shapesize(stretch_wid=5, stretch_len=1)
paddle_b1.penup()
paddle_b1.goto(350, 0)
# Ball
ball = turtle.Turtle()
ball.speed(0)
ball.shape("square")
ball.color("white")
ball.penup()
ball.goto(0, 0)
ball.dx = 0.1
ball.dy = 0.1
# Functions
def paddle_a1_up():
y = paddle_a1.ycor()
y += 20
paddle_a1.sety(y)
def paddle_a1_down():
y = paddle_a1.ycor()
y -= 20
paddle_a1.sety(y)
def paddle_b1_up():
y = paddle_b1.ycor()
y += 20
paddle_b1.sety(y)
def paddle_b1_down():
y = paddle_b1.ycor()
y -= 20
paddle_b1.sety(y)
# Keyboard Binding
wn.listen()
wn.onkeypress(paddle_a1_up, "w")
wn.onkeypress(paddle_a1_down, "s")
wn.onkeypress(paddle_b1_up, "Up")
wn.onkeypress(paddle_b1_down, "Down")
# Main Game loop
while True:
wn.update()
# Move The Ball
ball.setx(ball.xcor() + ball.dx)
ball.sety(ball.ycor() + ball.dy)
# Border Checking
if ball.ycor() > 290:
ball.sety(290)
ball.dy *= -1
if ball.ycor() < -290:
ball.sety(-290)
ball.dx *= -1
if ball.xcor() > 390:
ball.goto(0, 0)
ball.dx *= -1
if ball.xcor() < -390:
ball.goto(0, 0)
ball.dx *= -1
its at ball move
move the ball *
i guess this shouldn't be dx here?
if ball.ycor() < -290:
ball.sety(-290)
ball.dx *= -1
frr
lemme go check
bruh
how do you see it
ty sm
how tf did u see it
thanks
I saw dx being updated on 3 lines and dy on 1 line, rather than 2 for each, which was immediately suspicious
wow
and then having a y coordinate check together with a change to dx just looked wrong
Can you explain why my solution wouldn't work? (if it isn't a problem)
one more thing something is wrong but doesent show up
nvm im just stupid
nvm something is wron
g
i made th code so the ball bounces off the paddle but it goes through
!code
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
# Paddle and ball collisions
if ball.xcor() > 340 and (ball.ycor() < paddle_b1.ycor() + 40 and ball.ycor() > paddle_b1.ycor() -40):
ball.dx *= -1
is is something wrong in there?
take a very simple example like this where you start in the red circle, what path to pick? with the code as is, picking a means you will never find the longest path, and you don't know beforehand what choice is correct
def example4(manatees):
oldest_manatee = "No manatees here!"
for manatee1 in manatees:
for manatee2 in manatees:
if manatee1['age'] < manatee2['age']:
oldest_manatee = manatee2['name']
else:
oldest_manatee = manatee1['name']
print oldest_manatee
what is the big o notation of this?? I am confused as to what to count and what not to
It'd be O(n^2) for the for loop iteration but how do I count the if else statements or do I not count them at all?
and is it just +2 for the other 2 declaring and print statements?
cause the quiz I am doing says in the answer that
def example2(manatees):
print manatees[0]['name']
print manatees[0]['age']
big o notation of this is O(1) but in the lesson they add 2 for a declaring command and print command
I have just started with O notations so am confused
sorry if my questions seem silly
big O notation is basically drop all constants and lower order terms, so e,g, 3x^2 + 2x + 1 is O(x^2)
count the number of "simple" operations, and find the order of that
and because you only care about the O of the thing you can be a bit sloppy (in ways that won't affect the final answer)
I see
I don't really understand the example
lower order terms don't matter, we can drop 2x and 1
constant factors don't matter, we can drop the factor of 3
I see
thank you 🙇♂️
thanks a lot, could you avoid this problem if every iteration of the function has it's own copy of the "proccesed" list, if that is achiavable
I mean, checking every possible path ever will work
but there are...many paths
yeah i think the max size would be 400 vertices
So I know i may sound dumb, but how do you do that?
something similar to the recursion like you mentioned with different copies of a processed list would work
thanks, will try it out!
Hi, I don't undestand something ,is it normal that an 8*8 array made with a numpy array is much larger than an 8*8 array made with a python list using the getsizeof method? Isn't numpy array supposed to use less memory than python lists? (I understand the concept of lists using pointers ,and of array being a "chain" in the stack memory but still...). I intend to do a project using machine learning ,so I would like to store a lot of data (8*8 array) using as little space as possible ,which should I prefer ? the python list implementation or the numpy array ? :/
getsizeof doesn't compute the occupied memory recursively
it's not particularly useful if you want to know how much memory something occupies
!e
import sys
xs = [[0]*1000, [0]*1000, [0]*1000, [0]*1000]
ys = [1, 2, 3, 4]
print(sys.getsizeof(xs))
print(sys.getsizeof(ys))
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 88
002 | 120
for some reason the ys list is even larger.
but the idea is the same
so I would like to store a lot of data (8*8 array)
an8x8array of integers is not a lot of data 🙂
This is because sys.getsizeof computes the "shallow" memory of an object. All a 4-element list stores is 4 pointers, so that's what's included in the size.
ty for the replies , I see the getsizeof isn't a good method to evaluate, it explains the absurd results I get from it . It's not just one 8x8 matrix but probably 1 million of it in the end that's why i don't want to regret it later using the wrong data structure
Moreover, you can have shared ownership, like ```py
a = [0] * 1000
b = [1] * 2000
c = [2] * 3000
xs = [a, b, b, b, b, b]
Ys = [c, c, c, b, b]
``` so it doesn't really make sense to say "xs occupies (some amount) of bytes" or "ys occupies (some amount) of bytes"
Depends on what you want to do with that matrix.
If you want to perform some fast operations provided by numpy, use numpy
it's for encoding chess positions ,so yeah a lot of fast operations too
numpy doesn't make your program faster automatically, but it lets you apply certain operations on the whole array, like multiplying the whole array by some number, really fast.
it is somehow faster than a python list because of the adjustment of the array in memory no ?, like for example for a dichotomic search
but i guess this is relevant when the array is really big
adjustment of the array in memory
what do you mean by that?
A Python list is not a linked list, it's actually a dynamic array. So looking up an element by index is O(1)
If you want a fixed-size fixed-type integer array, you can also use the built-in array module. I think it will be more memory-efficient than a list, but not sure about speed.
!d array
This module defines an object type which can compactly represent an array of basic values: characters, integers, floating point numbers. Arrays are sequence types and behave very much like lists, except that the type of objects stored in them is constrained. The type is specified at object creation time by using a type code, which is a single character. The following type codes are defined:
Similar names: numpy.term.array
python
https://www.techiedelight.com/shortest-superstring-problem/
I want to convert the C++ solution for this to Python and have written the Python code below. It doesn't output anything. Please debug it. C++ code is in the link above and my Python code is below. Thank you, would be of enormous help.
https://pastebin.com/Tgy91nCF (edited)
Given a list of strings where no string is a substring of another, find the shortest string that contains each string in the list as a substring.
Pastebin
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
!code
hay boy
same coefficients as the LHS, with the order of the highest term
for the purpose of combining the terms
what exactly do you mean by that? I am not sure that I know about which terms are you talking about
3n^2 + 5n^2 + 2n^2 = 10n^2
This is the line of reasoning:
- For example,
3n^2 + 5n + 2 <= 10n^2 - Therefore, 3n^2 + 5n + 2 = O(n^2), because
3n^2 + 5n + 2is at most10 * (n^2)
they could pick 100 instead of 10 and it would also be right
To prove that 3n^2 + 5n + 2, they say:
3n^2 <= 3n^25n <= 5n^22 <= 2n^2- (from 1, 2, 3),
3n^2 + 5n + 2 <= 3n^2 + 5n^2 + 2n^2 - add up the right part,
3n^2 + 5n + 2 <= 10n^2
@austere sparrow Yeah, I understand that, but I don't understand why we compare that, I mean, isn't it a case that if there is some largest exponentiation, big o will always be O(n^largest exponentiation in expression)?
This passage is introducing the formal definition of O(n^2). As an example of that definition, they show that 3n^2 + 5n + 2 is O(n^2)
big o will always be O(n^largest exponentiation in expression)?
In a polynomial, yes. But it's not a separate rule - it's derived from this definition
the blue is the definition, the green is proving that 3n^2 + 5n + 2 meets that definition
This passage is introducing the formal definition of O(n^2)
Hmm, I don't understand how is that derived from definition above about Big O. I mean, isn't it said that second expression should be multiplied by some constant c? In this case, what was done is that they just raised all unknowns (variables, in this all x) to the same exponentiation
Are you familiar with big O, informally?
what does that mean? word "informally" confuses me?
Like, have you used big O before? without defining it formally
yeah at university before 4 years but I forgot about it
@austere sparrow @shut breach did they just wanted to show that whatever n if taken as input, it will always be less than 10n^2?
f(x) is O(g(x)) means that there exist some factor and starting_point, so that for for all x starting with starting_point, f(x) <= factor * g(x).
For example, let's take f(x) = 3x^2 + 5x + 2 and g(x) = x^2. We can pick factor to be 10 and starting_point to be 1, therefore f(x) is O(g(x))
that's what they meant
yeah the point is that 3n^2 + 5n + 2 <= 3n^2 + 5n^2 + 2n^2 <= 10n^2
math examples are bad at separating levels of abstraction
Haha, now what does that mean? what are levels of abstraction?
The idea is that we want something that cares about what happens when the inputs get very large and sort of only care about things up to constants.
what is meant here up to constants?
it It's the level of detail a function or a class is operating with. For example, this would be a very strange function: ```py
def update_customer_avatar(customer):
try:
avatar = customer.create_avatar()
except psycopg2.UniqueConstraintViolation:
# already exists
avatar = customer.avatar()
if user.is_pro_user():
avatar.add_star()
# save the avatar to cache
with open(os.path.join(cache.avatars_path, customer.uuid + ".png"), "wb") as fh:
... # do some file I/O
because you're mixing high level concepts (like the premium status of a user) with low level concepts (file I/O, a database exception all of a sudden). Compare to this:py
def update_customer_avatar(customer):
try:
avatar = customer.create_avatar()
except CustomerAlreadyHasAvatar:
avatar = customer.avatar()
if user.is_pro_user():
avatar.add_star()
avatar.sync()
I think the textbook example mixes levels of abstraction because it presents a high-level concept (f is O(g)) but then all of a sudden starts multiplying stuff. It usually turns out a bit confusing, obscuring the bigger picture
anyway... that's a bit of a side note
yeah now I think I understand what you meant by level of abstractions
If you compare f(n) = 50 + n and g(n) = 10 + n, they will have very different values at small ns, but as n increases they will be very similar.
If you compare f(n) = 10n and g(n) = (1/1000) * n^2, f will be bigger at first, but then g will win over it
btw, this is a very good introduction to big O: https://nedbatchelder.com/text/slowsgrows.html
the details are interesting, but this is a good explanation of the bigger picture
(levels of abstraction came back 🙂 )
or rather, it comes from a computational angle, rather than a (purely) mathematical
thanks will read that
you can make a graph 🙂
I don't remember the exact proof to be honest, let me think for a bit
I understand how did they get n^5, that's big o polynomial, but how did they get big o ((sqrt(2)^2)?
wdym?
Isn't it a case that in the example above they wanted to show difference in growth between polynomial function and exponential function?
So I said that I guess that n^5 is big of of particular polynomial here highest exponentiation is 5
but I don't know why is n^5 = O((sqrt(2)^n)
the short answer is that exponentials just grow faster than polynomials no matter the base
haha, that's the point but I am interested why did they wrote n^5 = O((sqrt(2)^n)
i think they were just giving an example of that
yeah
fwiw I disagree with their use of = here
it should technically be a set contains, yeah
what you mean?
but using = is convenient (and not that incorrect)
There isn't a single "big O" for a function, it's a relation between two functions. For example, x is O(x^2), but also O(x) and O(10x) and O(x!) and O(6^x).
O(f(x)) is a set
it should be g(x) ∈ O(f(x))
yeah, they are families of functions
it's not at all an equivalence relation, so i think using an equals sign is very confusing
O(n) * O(n) = O(n^2) is very convenient though, granted I'm a physicist/engineer and not a mathematician 😛
you can make that work for some creative definition of *
or more usefully f(x) = g(x) + O(small term that we can disregard)
did they mean that for particular polynomial, for example for polynomial with highest exponential 5 where big o is 5 is equal to big o for exponetiation function here n is equal to 5 and big o for exponentiation function is O((sqrt(2)^n)?
e.g. ignoring O(epsilon^2)
I read that as: n^5 is not "larger than" O(sqrt(2)^n)
guys, when you write O, does that mean big O?
O(f(x)) is the set of functions that grow slower or the same as f(x)
there are several related notations
O is an upper bound
Ω is a lower bound
Θ is a tight bound
"slower" as defined here
you mean faster
oh wait, no
I'm stupid sorry
and for the right expression n^100 = O(1.1^n) is same? I mean n ^ 100 is not larger than O(1.1^n)?
polynomials are in general smaller than exponentials (for large input)
(finite degree polynomials, before someone complains)
for any n you can always come up with a polynomial that is larger at that n than an exponential, however for all p(x) and e(x) there exists an n such that e(x) * C >= p(x) for x>n
like i said, the equalities are misleading, what they mean is that those functions exist in those sets
writing them as equalities is technically not correct, as mentioned earlier
but my reading is what is meant
n^100 ∈ O(1.1^n)
Best Book/tutorials for learning data structures and algorithms??
n^100 is in the family/set of function that aren't "larger" than 1.1^n for large n
there are some in the pins
formally: there exist constants C and N such that n^100 <= C*1.1^n when n >= N
well, it is a true statement
it's a terrible bound, but it's correct
what you mean by terrible bound?
I mean how does that picture above relates to this text
What's more surprising is that if you have any polynomial and any exponential, the exponential always grows faster. So n to the fifth is O of root two to the n.
so are these big o for expontiation functions?
@shut breach
it's not too surprising that exponential functions grow faster if you know the series for e^x
it has all these higher order terms
e.g. x^4 <= 24*e^x
i dont understand what you're asking
Damn
It's confusing for me
why this underlying is a case
why not?
fwiw n^5 = O(1.1^n) and n^100 = O(sqrt(2)^n) as well
one very big reason to not use = here is that you can't reverse the relation
n^5 ∈ O(1.1^n) and n^100 ∈ O(sqrt(2)^n)
for all functions f ∈ O(1.1^n) it's also true that f ∈ O(sqrt(2)^n)
but the reverse is not true
for all functions f ∈ O(sqrt(2)^n) it's not generally true that f ∈ O(1.1^n)
O(sqrt(2)^n) is "bigger" than O(1.1^n)
yeah but how did they found out that n^5 = O(1.1^n)?
@haughty mountain @shut breach @austere sparrow
you show that there exist constants C and N such that n^5 <= C*1.1^n when n >= N
like I said the definition was
That's because from some point (about 300), n^5 <= 1.1^n for all n, as you can see from the graph
are you asking how to prove this formally?
Ok I will read what you guys wrote after break, I think I don't understand Big O definition that much clearly as to think in way of families of functions
the general definition of f(n) being in O(g(n)) is that there exist constants C and N such that f(n) <= C*g(n) when n >= N
yeah I understand that, that's all I understand about big O
is the confusion about how you prove that n^a is in O(b^n)?
there are many ways of proving or motivating it
one way using the binomial theorem: https://math.stackexchange.com/a/55488
if you're comfortable with the Taylor series of b^n it's also very straightforward to convince yourself it's true that way
can you explain why?
try applying the definition? it should end up being obvious enough
O(1) are constants, let's pick some constant k
Does there exist constants C and N such that k <= C*n when n >= N?
||C = k|| and ||n >= 1|| works
@haughty mountain Differently said, O(1) means for some function, upper bound is 1, that means that for any given X, biggest output value is always less than 1?
less than 1 times some constant
some constant times 1
also for large enough inputs
what this says^
i.e. the run time does not scale with the size of the input at all
So to start with the definition. The idea is that we want something that cares about what happens when the inputs get very large and sort of only care about things up to constants.
I don't understand part "about things up to constants"
the constant C in the definition I gave
n and 123n are "the same", up to a constant factor
I see, thanks. That's what I meant but just wanted to check
how to print ('helo(hi))
I think it's asking if you plug in come concrete number n0 into both at what point does A do better than B
It's Maths
Solve the inequality 5n^2 <= 1000n
The question is basically, find the maximum 'n' such that A is better than B
You need to find n0, and the condition is that for all numbers below that and including that n0, algo A is better than algo B
n0 is what we're looking for; n0 here = the maximum value of n such that A(n) is better than B(n)
Yes
👍 that's it
Does anyone have any advice/resources to learn + practice python lists and algorithms and working with data to improve on those topics
Maybe you can first start with basics in python in hackerrank
Is there any platform or site which will provide dsa examples or code which have most functionality and efficiency like for linked list , stack etc
Will try that, thanks.
GeeksForGeeks
I was looking for file to download or look to learn on my own how they did it, but i guess that works as well
I'm having trouble implementing the algorithm for min max heap mentioned on this page as find(k) which retrieves the kth smallest element. The time constraint for this should be O(logn) or less. link: https://en.m.wikipedia.org/wiki/Min-max_heap#:~:text=In computer science%2C a min,and maximum elements in it.
In computer science, a min-max heap is a complete binary tree data structure which combines the usefulness of both a min-heap and a max-heap, that is, it provides constant time retrieval and logarithmic time removal of both the minimum and maximum elements in it. This makes the min-max heap a very useful data structure to implement a double-ende...
#help-cookie pls
I tried to use google translate for coincide but I don't understand what would it mean in this context?
yeah but what would that mean in this context?
G1 = G
"If G1 = G, then our lemma is proved already"
what does it mean in this context g1 = g?
and how do you mean that g1 = g if g is further than g1?
Where does it say that G is further than G1?
It says that G is the furthest point, not that it is further than G1
Does anyone know how to find kth smallest in min max heap tho?
I suspect the argument is that if some optimal path contained G1 you could pick G instead and still have an optimal path. So you can always greedily pick the last ok point
@haughty mountain is english your native lang?
not native
yeah I had assumption that it is furthest point because it is said "that G is the furthest point"
G is the furthest point, but nothing prevents G1 from also being that furthest point
but the point you'll get to is that if G1 < G you can just pick G and the path is not worse
so as a consequence you can just pick the furthest reachable point
? Isn't it obvious from picture that G is furthest, not G1? How do you mean "nothing prevents G1 from also being that furthest point"?
You don't, at least not with a min/max heap in O(log n). You can do it in O(k log n) with a min heap. You're looking for some tree that supports kth order statistic in O(log n)
@agile sundial Do you think that coincide in question above means that G1 = G?
In computer science, a min-max heap is a complete binary tree data structure which combines the usefulness of both a min-heap and a max-heap, that is, it provides constant time retrieval and logarithmic time removal of both the minimum and maximum elements in it. This makes the min-max heap a very useful data structure to implement a double-ende...
In constant time
Don't look at the picture like it's the truth. It's one scenario. G1 could be anywhere between A and G
The strangest thing is I cannot find info about this anywhere online
Do you mean the thing mentioned in the extensions section?
The min-max-median heap is a variant of the min-max heap, suggested in the original publication on the structure, that supports the operations of an order statistic tree.
Despite the 100s of algorithm articles i can't find a single about min-max heap getting kth smallest element
No it's mentioned in the second paragraph
Find(k)
I think that's referring to that extension
delete-median,[2]find(k) (determine the kth smallest value in the structure) and the operation delete(k) (delete the kth smallest value in the structure), for any fixed value (or set of values) of k. These last two operations can be implemented in constant and logarithmic time, respectively.
Yes, the paragraph that begins with
The structure can also be generalized to support other order-statistics operations efficiently...
Oh yeah
check the original paper they are referring to, section 3 http://akira.ruc.dk/~keld/teaching/algoritmedesign_f03/Artikler/02/Atkinson86.pdf
Ohh I see
Thank you so much
Hmmm
I don't really understand
I'm having trouble implementing the find kth smallest
seems the min-max heap for order statistics trees only works with pre-determined k
and not any k at runtime (after construction)
By k u mean the kth smallest element?
yes, the k in "kth smallest element"
I see
just count them? also not the right channel for this
Oh would this work? https://en.m.wikipedia.org/wiki/Order_statistic_tree
In computer science, an order statistic tree is a variant of the binary search tree (or more generally, a B-tree) that supports two additional operations beyond insertion, lookup and deletion:
Select(i) — find the i'th smallest element stored in the tree
Rank(x) – find the rank of element x in the tree, i.e. its index in the sorted list of elem...
I don't think u need AVL for this
I think the more general solution to kth order statistic is some variant of a self balancing tree, e.g. an AVL tree or a RB tree with some extra metadata
Ah I see
is k a constant you know beforehand or not?
The thing is Im not allowed to use AVL
K is a constant determined by Ciel(0.618*Len(tree))
0.618 is golden ratio I think
So k changes everytime tree gets or loses an element
if so, can't you just keep one min-heap and one max-heap and balance them against each other
oh, you need to be able to remove elements as well?
No I dont
I just need to lookup kth smallest element in O(logn) or less time
Sorry do you mind explaining this idea
I know how to build min and max but I'm stuck on the actual algorithm to find kth smallest
you have elements less than the ratio (the current k) in a max-heap, and elements larger in a min-heap
when you add an element you add it to whatever side should contain it, and maybe you need to move an element between the heaps to keep the ratio right
@gusty spire you get the idea?
Sorry just reading
Do you mind giving an example I still don't quite understand
"If G is closer than G2, refill at G instead of G1". G2 = next stop in R. G1=position of first reffil in R. First thing that confuses me - If G2 is next stop, how can G be closer than G2?
Ohhh I think I get it
if you have two heaps where you have the balance you need (in your case the smaller one should be something like 0.618 of the size)
small large
[..., max] [min, ...]
```when you add a new element it just goes whereever it needs to go, and then you rebalance to keep your ratio correct
I think you only ever need to rebalance by moving 1 element
I see
So whenever you insert an element x you check if x > ratio then insert in min otherwise max.
almost, you insert x in whatever partition it fits in atm, so if it's small it goes in the small partition and if it's large in the large partition
if it goes in the small partition you might need to pop the max from there and move it to the large partition to keep the ratio right
and vice versa if you end up adding it to the large one
I see
Sorry just to confirm by small partition you mean max heap and large partition min heap right?
right, when I say small partition I mean the max-heap containing the small values, and when I say large partition I mean the min-heap containing the large values
this setup structure allows you to shuffle elements between the parts to keep the balance at all times
I see
So if I wanted kth smallest which will just be the result of Ciel(0.618*Len(tree) how do I get that?
something like keep a fraction 0.618 of elements in the small part
e.g. such that the element you're looking for is always the min element in the large heap
Ohh I see
with this you have O(log n) insertion and O(1) lookup for your current value of k = Ciel(0.618*Len(tree))
But how would I get min elem of large heap?
it's a min heap
Ohhh I see
That makes sense
The only thing I don't understand is how do I know what position and where element should go when I insert.. won't I have to know the order of the elements to do that?
no? If you are inserting element x
small large
[..., max] [min, ...]
```if `x <= max` insert among small, if `x >= min` insert among large, otherwise do whatever (you could be clever in this case, but lets not)
then you check if the balance between `len(small)` and `len(large)` is right, if it's not then shuffle elements across until the balance is correct
fwiw even if that was to make sense I don't like that proof approach. All you need to prove is that if you can reach multiple points, you can always pick the furthest one, you will end up further along with the same amount of fuel
classic exchange argument
So, G = farthest reachable refill from current position, G1 = position of first refill in R, G2 = next stop in R (refill or B). "If G is closer than G2, refill at G instead of G1" - isn't it a case to 1) move to G1 which is first refill place 2) move at next refill station G2 which is refill station after G1? So if it's a case that G is the farthest refill station that is reachable from current position, G1 is only place before G2, isn't it a case that it's a must to refill at G1?
if G > G1 then you can go to G and you're not in a worse situation than before
that's pretty much the whole argument that's needed
from G you can for sure reach G2, so the solution after G is still valid
now you can again pick the furthest point from G
and if you keep going you have a solution that is as good or better than the presumed optimal solution you started with
that only makes the greedy choice of picking the furthest refill station
@haughty mountain Could you please answer to my question because it confuses me?
I understand general logic, but proof confuses me
I don't really know what they are trying to say 🤷♀️
Haha, okay
btw what are some other places where I could ask for help with regards to alghoritms?
you would pick G even if it was for some reason to the right of G2, so I have no clue why they say the G < G2 thing
will it be better to use jupyter rather then ide for NN
idk many places, the one place on discord I know where people like to discuss algos is a competitive programming server where you need to have good rating to join
Maybe it has to do with this lemma
lol I don't have any score in competitive programming
the cutoff for that server is candidate master on codeforces, which is 95th percentile 😛
does anyone have any good beginner small project ideas for a beginner like myself? I've done some search algorithms and stuff like that
Hi
why doesn't this code work for finding longest path in directed acyclic graph (i need to find the longest path with the same charachters through a grid)
from copy import deepcopy as dcopy
n = int(input())
mx = [list("#"+input()+"#") if i != 0 and i != (n+1) else ["#"]*(n+2) for i in range(n+2)]
pro = [[1]+[0]*(n)+[1] if i != 0 and i != (n+1) else [1]*(n+2) for i in range(n+2)]
pro1 = dcopy(pro)
def dfs(tup):
x,y = tup[0], tup[1]
pro1[x][y] = 1
cn = [(x,y+1),(x,y-1),(x+1,y)]
dist = 0
for i in cn:
if pro1[i[0]][i[1]] == 1 or mx[x][y] != mx[i[0]][i[1]]: continue
disttemp = dfs((i[0],i[1]))
if disttemp>dist:
dist = disttemp
return (dist+1)
rez = 0
for k in range(1, (n+1)):
for l in range(1, (n+1)):
reztemp = dfs((k,l))
if reztemp>rez:
rez = reztemp
pro1 = dcopy(pro)
print(rez)```
check out advent of code
plsss
someone
how to get kth smallest element from a heap in O(1) time
and dont just link the wikipedia page for max-min heap cus it doesnt explain it
I outlined the process already, but sure here is a sample implementation that it quite literally just what I outlined
import heapq
import math
class MinHeap:
def __init__(self):
self.data = []
def push(self, value):
heapq.heappush(self.data, value)
def pop(self):
return heapq.heappop(self.data)
def top(self):
return self.data[0]
def __len__(self):
return len(self.data)
class MaxHeap:
def __init__(self):
self.data = []
def push(self, value):
heapq.heappush(self.data, -value)
def pop(self):
return -heapq.heappop(self.data)
def top(self):
return -self.data[0]
def __len__(self):
return len(self.data)
class PercentileTracker:
def __init__(self, percentile):
self.percentile = percentile
self.small = MaxHeap()
self.large = MinHeap()
def push(self, value):
# Add to appropriate place
if len(self.small) and value <= self.small.top():
self.small.push(value)
else:
self.large.push(value)
# Rebalance
total = len(self.large) + len(self.small)
k = math.ceil(self.percentile * total)
while len(self.small) >= k:
self.large.push(self.small.pop())
while len(self.small) < k - 1:
self.small.push(self.large.pop())
def value_at_percentile(self):
return self.large.top()
# Test code to check against brute force sorting to get kth order statistic
percentile = 0.618
pt = PercentileTracker(percentile)
data = [1, 3, 2, 5, -7, 1, 2, 3, 4, 1, 7]
reference = []
for value in data:
reference.append(value)
reference.sort()
pt.push(value)
k = math.ceil(percentile * len(reference))
assert reference[k - 1] == pt.value_at_percentile()
print(reference[k - 1], pt.value_at_percentile())
do you have any idea why the first solution is giving about 3000 ms?
it just taking the last item in the array with pop() and adding that to index 0
it's not doing calculations as other solutions like #2 and #3. i mean it seems like, it doing less calculations than others but no
i guess the time complexity of #2 and #3 is O(n) but what #1 is?
is it giving such high ms because it uses build-in functions or something?
like insert and pop
(i don't know much about time complexity)
the first one is really bad compared to the others since to insert an element to the front of a list, you have to shift all the other elements to the right
and you do this every rotation, so it's quadratic
the others are just linear
i see thx
what does this mean
the cambridge definiton of abstraction is "the situation in which a subject is very general and not based on real situations"
how does it relate to algorithmics
It's my take at it, but maybe it means that you don't have to know exactly how and what the algorithm does but you know its purpose. You may know about merge sort and not know about what it does or how it works, but you know its purpose is sorting
A lot of times if you can abstract out the idea of an algorithm you can make it more general and more powerful. Like an algorithm that solves a maze can be abstracted into a more general graph search algorithm.
ooh that make sense
thx u both for providing the examples as well
it helps a lot for understanding
also merge sort and graph search algorithms are "algorithm designs patterns" right?
u can use these general ideas to complex problems
is that what mean here?
I'm haven't really heard that term "algorithm designs patterns" before
Merge sort is a particular algorithm that can sort lists, and there are multiple types of graph search algorithms. But that text is right that getting a high level overview (aka abstract overview) of a problem can help you solve other problems.
ooh ic
i just started learning a subject called "Algorithmics" in school
im making sure that i understand theory
In programming, abstraction is to take something as a given and just use it. You know that merge sort is a sorting algorithm, use it for this purpose. Abstraction hides the complexity of code under a function, a class or anything else.
I thought abstraction meant hiding? ( edit: nvm did not read the whole message )
thx for your explanation
how this relates to Abstract data types
so for example a variable is a abstract data type
by using variable it makes easier to apply them since we dont have to worry about String, int, bool?
Variables are an abstraction of how data is stored in memory. Instead of worrying about the memory and addresses of data stored in it, you can use the name of your variable to access and manipulate your data.
Data types is an abstraction of operators done upon the data in memory. They restrict functionalities data can have
i see
Yeah, that's a good way to put it. Like you can do merge sort on both lists of strings or ints, and when thinking about it you abstract away the idea of how they compare less/greater than each other. How doesn't exactly matter, you just know that you can sort things that can be compared as less than/greater than.
i guess another importance of these abstractions is you can reuse them
there are like patterns
like you dont have reinvent the wheel
i think this is good representation of abstraction
hay guys, someone in here
maybe 
well, i have a little
i dont really understand this import the twitter package and run help() on it
try in a python console py import itertools help(itertools) but replace itertools with the name of the tiwtter package
Though this channel is for dsa. Best to ask in #python-discussion or see #❓|how-to-get-help for further assistance
i did but i had no reply
like?
Huh?
Hey guys, so i have a problem regarding this topic. create a program to find minimum steps to get all treasures, we know how many treasures are there in the maze and starting point depends from input. let me elaborate on my thought process. also i'm using C but if you want to explain in any language, then no problem.
P=Path
T=Treasure
W=Wall
12345
------
1 | PPTPT
2 | WPWWW
3 | TPPWT
4 | PPPPP
5 | TWWWP
the starting position will depend on the input, but lets say we start at (1,1) then the minimum steps to collect all treasures is 18 (can use same path)by going right 4 steps to collect 2 treasures, then go left 3 steps then go down 2 steps, go left 1 step, go down 2 steps, go up 1 step, go right 4 steps and finally up ending at (3,5)
at first i was thinking about DFS and to optimize the DFS by checking whether i have explore a coordinate or no.
char maze[5][5];
bool wasExplored[5][5]={false};
void exploreMaze(int x,int y){
(if x<1 || x>5 || y<1 || y>5 || wasExplored[x][y]==true) return;
wasExplored[x][y]=true;
exploreMaze(x-1,y);
exploreMaze(x+1,y);
exploreMaze(x,y-1);
exploreMaze(x,y+1);
}```
but i realize that i cant optimize it by simply checking like that because i might have a faster solution. i consider to change array type from bool to int, but if i found a better way to get into a certain coordinate, then i would have to explore it all over again right?
also i still dont get when or how should i start counting the steps, my current solution is like this
```c
char maze[5][5];
int wasExplored[5][5]={0};
int exploreMaze(int x,int y){
(if x<1 || x>5 || y<1 || y>5 ,maze[x][y]=='W') return;
int step=0;
if(maze[x][y]=='T') step=1;
if(exploreMaze(x-1,y)>0)step+=wasExplored[x-1][y]+1;
if(exploreMaze(x,y-1)>0)step+=wasExplored[x][y-1]+1;
if(exploreMaze(x+1,y)>0)step+=wasExplored[x+1][y]+1;
if(exploreMaze(x,y+1)>0)step+=wasExplored[x][y+1]+1;
wasExplored[x][y]=step;
return step;
}```
to elaborate more why there's if condition before increment the step, is that we only start counting steps if we found a treasure.
so, that is my current solution, but i couldnt grasp the idea how to compare between 2 paths. also since we know how many treasures are there, i think that we could make a condition to stop if we have found all treasures. but that would mean if i visited the same treasure via 2 routes, that would be a miscalculation?
i heard about BFS algorithm to find exit but i cant imagine it being use for this problem.
Does anyone know/have a script that reconstructs images in a cool way? Like this; https://www.reddit.com/r/Python/comments/ghxqod/thanks_to_everyones_advice_my_mouse_drawing/
the reason i picked this is very specific, I have to see the process of reconstructing so it looks cool. Not saving it as a png file after it finises.
what is the time complexity for mergesort? one book says that it is O(n lg(n)), while another video says its \theta(n lg(n))
its same
it's technically not the same
how? theta represents the tight bound while O is the upper bound
to be precise, the average case is \Theta(n lg n)
is there a nice way to get the kth largest element from a max heap?
for example if i have the following max heap [18,17,14,16,9,11,13,10,15,3,8,2,6,5,12,1,7,4] and i wanted to find the 7th largest element that would be 12
i first thought about sorta finding the general area the kth largest element would be then making another max heap with the elements in this range but i realized that it doesnt really work out in the case above
average case?
i thought about it when i was dealing with finding the second largest number in [3,1,2] and [3,2,1] both should return 2
merge sort is always n log n
i.e. both O(n log n) and Ω(n log n), so Θ(n log n)
so, both
is there a nice way to find the kth largest element from a max heap if i know what k is before hand?
combine a min and max heap, the code I wrote yesterday is trivial to adapt to a fixed k rather than a percentile @quasi sorrel
assuming you don't have to be able to remove elements
if you need removing elements you need something fancier
i was trying for a solution with a better space complexity like working directly with a list
better space complexity than O(n)?
im not that good with guessing space complexity
heaps are just stored as lists
wouldnt a object oriented approach use more space?
how is it object oriented?
your solutions uses classes doesnt it?
it uses one object per heap, the overhead is miniscule
the actual data inside them is just a list
if it was a list containing classes then maybe overhead might start to matter
but this is just classes that holds large chunks of data and provides a nice interface
you could inline the logic, but it will be super messy
when you pop in your max heap part is that removing the largest element or the smallest? @haughty mountain
popping from a max heap removes the maximum element in the heap
i see
so it looks like your algorithm takes about logn time to push or maybe im wrong
also why are the values going to the maxheap being multiplied by -1
because heapq is a min heap
log n, yeah
Hey @open moth!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
Guys, what do you think is complexity, BigO of this algorithm?
In the video, instructor said "And the external loop and internal loop combined also spend at most linear time of iterations. Because they change variable currentRefill and it changes at most linear number of times. "
"spend at most linear time of iterations" part confuses me
and also "and it changes at most linear number of times."
so linear time is O(n)
so because these both loops, internal and external depend on same value which is increased linearly, complexity is O(n)?
It's O(n), but it's difficult to explain without just repeating what the instructor said. Because the loops share the same looping variable, the combined number of times that you go back to the beginning of either loop is n. Or in other words, every iteration through the inner loop reduces the number of iterations you need to perform through the outer loop by 1.
Thanks for comment
Also, to check this - safe move is a move that is done instead of first other move in optimal solution - what is important is that taking safe move doesn't influence optimal solution, so the expected outcome is same
is there a way to sum all the elements of an avl tree/bst in logn time?
you could just keep track of the sum as you insert/delete elements
then you have the sum in O(1)
Basically, this algorithm will consider every possible partition of the children into groups
I am not sure what does that mean, can someone explain?
So basically if I have ages of children 1,2, 3, then there are partitions: { {1}, {2}, {3} }, { {1, 2}, {3} }, { {1, 3}, {2} }, { {1}, {2, 3} }, { {1, 2, 3} } - is by word "partition" that meant?
presumable yes, this would be a brute force thing where you consider any possible grouping, which are those 5
this problem can be solved greedily: the lowest age can't be paired with anyone younger, so the best we can do is to just remove the youngest and hope we can get the year above for free as well, repeat with the new youngest
thanks for response
This really weird thing is happening and i don't know why?
So i want to add a[i]+a[i+1] from either side and in these two seemingly same cases, only one of them works
here is the code for the case that doesn't
dis = [[0,0]*(8)]
for i in range(1, 7):
j = -(i+1)
dis[i][0] = dis[i-1][0]+1
dis[j][1] = dis[j+1][1]+1
print(dis)```
and this one does, i am seriously so confused?!
dis = [[0,0], [0,0], [0,0], [0,0], [0,0], [0,0], [0,0], [0,0]]
for i in range(1, 7):
j = -(i+1)
dis[i][0] = dis[i-1][0]+1
dis[j][1] = dis[j+1][1]+1
print(dis)```
The problem is that multiplying a list doesn't create copies of the items in the list, it just gives you a list containing the same item multiple times. So in the first code (I think you mean [[0, 0]] * 8), there's only one [0, 0] list in existence. When you modify it, that change is visible from all the indexes.
BRUH THANK YOU YOU ARE A LIFE SAVER
I was just so confusedd
?
@cedar cove delete your stuff 😅
Lets say I have an array A. I want to make an array B, with elements in A from i:j. (less than O(n) time)
can it be done? is there a function to directly put in elements in A in a given range to B?
if you want a copy of the elements it will take O(j-i) time
other languages solve this by having a span or slice type that acts as a wrapper and just indexes into the original array
what's the difference between using an OrderedDict and a list of tuples?
like orderedDict of values {1: "I", 5: "V"} vs list like [(1, "I"), (5, "V")]
both can iterate through the values in order, which is what I want/ought to do for this problem
Normal dicts are ordered too in modern python versions
But dicts/lists have different lookup times and other behaviors as you may know
If you only need iteration then lists may be fine
OrderedDict also has methods to change the order, where normal dicts don't
basically, I dont want a loop.
it will still be linear time
if not in python, is it possible in other languages
oh ok
e.g. this does what you want but is linear time because it copies stuff
B = A[i:j+1]
ah
got it
thanks!
because its still looping through
its still the same time
as it would have been to use a for loop
is a similar function possible in c++ tho?
C++20 has std::span for this kind of thing
okay
you could always write your own Span type in python
that delegates indexing and slicing to the underlying list
really? so what's the point
I see
what do you mean by change the order? like more than just reversing it?
how is that done?
ordereddict remembers the order that the items were inserted in
how is OrderedDict implemented? oh it's doubly linked list
!e
from collections import OrderedDict
ord_dict = OrderedDict().fromkeys("abcdefg")
print(ord_dict)
ord_dict.popitem()
print("popping last item")
print(ord_dict)
ord_dict.popitem(last = False)
print("pop first item")
print(ord_dict)
@strong ledge :white_check_mark: Your eval job has completed with return code 0.
001 | OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None), ('f', None), ('g', None)])
002 | popping last item
003 | OrderedDict([('a', None), ('b', None), ('c', None), ('d', None), ('e', None), ('f', None)])
004 | pop first item
005 | OrderedDict([('b', None), ('c', None), ('d', None), ('e', None), ('f', None)])
yeah, so you can pop from end and beginning in O(1)
the purpose is so that you can iterate over the keys in a certain order
I'm confused so OrderedDict has the complexity of Doubly-linked list?
because apparently that's how it's implemented
so even tho it has "dict" in the name, it's not actually a dict/hashmap
that's confusing
it also has O(1) lookup
Lib/collections/__init__.py line 78
class OrderedDict(dict):```
feel free to look at the implementation : p
but yes, setitem, popitem, and move_to_end are constant time
how is that possible?
it is
magic as far as I'm concerned
it acts like a doubly linked list at times and at other times like a normal dict?
interesting
argh
!e
from collections import OrderedDict
d = OrderedDict()
for x in range(100):
d[x] = x+1
print(len(d))
print(d[0])
print(d[99])
@strong ledge :white_check_mark: Your eval job has completed with return code 0.
001 | 100
002 | 1
003 | 100
?
@fiery cosmos it is a "lookup table", implemented internally with a dict + doubly linked list
oh I see
Lib/collections/__init__.py lines 106 to 112
def __setitem__(self, key, value,
dict_setitem=dict.__setitem__, proxy=_proxy, Link=_Link):
'od.__setitem__(i, y) <==> od[i]=y'
# Setting a new item creates a new link at the end of the linked list,
# and the inherited dictionary is updated with the new key/value pair.
if key not in self:
self.__map[key] = link = Link()```
this is the "magic" i tihnk
I dont understand
they still keep a mapping of key to doubly linked list node
in order to do O(1) lookup
internally they still store things in a normal dict, which is the self.__map variable
it is wasting memory?
for fast lookup
i dunno, if it's good enough for CPython it's good enough for me 😅 if you only used doubly linked list, how else would you achieve O(1) lookup..
so actually it's better to use a list of tuples when you just want to iterate in order
actually the reason why I didnt want to do that is just because typing out the list of tuples is longer
but I see that it actually saves memory
well, yes, if you don't need to randomly lookup tuple key -> tuple value, then list of tuple is enough
I also came to ask this lol
don't normal dicts use an array instead of a linked list?
how is popitem/del O(1) in a dense array
it doesn't resize after a del, it just marks the spot "dummy", which can be turned into an active key on another insertion
wouldn't that make the next popitem or iteration slower?
surely it can't reuse the spot and maintain insertion order?
Objects/dictobject.c line 88
Preserving insertion order```
I'll take a look thanks
How do defaultdicts work from the collections module? I can't seem to understand the KeyError thing, because I get them as well...
you can format python code by doing:
```python
my code here
```
so, the code will look like:
# my code here
Hey @tired sapphire!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
Please help me to resolve this problem
Might anyone know if there is an advantage to using linked lists in Python? I know it's advantageous in languages such as Java due to how their Arrays and ArrayLists are built, but how about in Python?
they have similar memory usage. the main performance difference is with time complexity
Ah gotcha, do we know the time difference between those or is that too hard to calculate?
linked lists have constant time complexity
in what field?
if append yes
if search no
if delete no
if sort definitely not
ye i meant in append
Which is great for things like queues (collections.deque) since you can append or remove from both sides in constant time 
Though I think queues can also be implemented in a circular buffer which uses an underlying array rather than a doubly linked list 
Linked lists aren't commonly used in practice because they are slow and memory-hungry in absolute terms (rather than asymptotically)
a naively implemented linked list needs one (for single-) or two pointers (for doubly linked) for each element. That's 8/16 bytes of overhead for each element. If your element is even 8 bytes, that's kinda massive.
Similarly, to iterate over a linked list requires following a pointer for each next element. That's O(1), but slow compared to just looking into an array, and has no cache locality.
There are smart hybrid implementations, though. Say, collections.deque is implemented as a linked list of arrays. That way, there's only a pointer to the next node every X elements, rather than every one element, and so the memory and runtime overheads are X times smaller.
yup, not sure why they didn't use a vecdeque
Thats smart 👀
There are basically no modern languages that aren't just using vectors for many of these things
things like rust have really weird stuff going on in their DS/Collections and some of them are really really innovative, like the btreemap that more or less outperforms the hashmap in the collections because of modern caches
is this the correc channel? anyway i made a wordle solver
^^^^
Can anyone help me solve these
hello, I have a question about divide and conquer method/ recursion in min max
I have done this code passing whole array each time but, I want to do it by passing half array each time. How to do it?
Hey @urban creek!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Do you know about list slicing? Like A[start:end+1] You can do it with that.
However, the way you're doing it by passing indexes around is technically more efficient because slicing is an O(N) operation since it makes a shallow copy of the sliced portion of the list 
Hi, I am working on a subset sum problem, which states that "Given an array of non-negative integers and a value sum, determine if there is a subset of the given set with sum equal to given sum." I have to solve this problem in constant complexity 0(1) in iterative method.
``def get_sum(arrays, target):
result = [False]*(target+1)
# initializing with 1 as sum 0 is always possible
result[0] = True
# loop to go through every element of the arrays
for ele in arrays:
# to change the value o all possible sum values to True
for j in range(target, ele - 1, -1):
if result[j - ele]:
result[j] = True
# If target is possible return True else False
return result[target]
Driver code
arrays = [2, 3, 5]
target = 17
if get_sum(arrays, target):
print("YES")
else:
print("NO")``
Just wanted to know that this is the correct method for the constant space 0(1) using iterative method. Can anyone please help me out.
I don't think there is a O(1) way of solving this. I think it would be at least O(N)
I guess the question is constant space, not time - so you use the same amount of memory regardless of the size of the input array.
RIght.. sorry, my bad.. I didn't read the constant space there.. just O(1)..
hey I have been trying to create an algo that uses divide and conquer to find the longest contiguous increasing subarray
but I'm not sure how to create the crossarray function that finds the longest chain in the middle
Guys, do you have any advice with regards to learning algorithms? How to learn them as much as efficiently as possible?
I have two idea: break what I don't understand in parts and then learn about particular part
when I finish with particular material from course, book or whatever, then I should write about what I learnt in order to check whether I understood it
Any other idea?
Start with the basics, having a good understanding of statistics and linear algebra goes a long way
^
and practice them
big o notation also
and notes are very helpful to look back on later
yeah learn about the theoretically, think about what usecases they have, the pros, the cons, and maybe try em out for an example problem
don’t be ashamed
what parts of linear algebra and statistics is used in a & ds?
you don’t memorize programming syntax, etc you memorize the logic and principles
oh I thought you meant "any adive with regards to learning algorithms"
So I was giving advice on understanding ML/AI
lol
yeah ignore that
Linear algebra is the basis for some graph algorithms
yeah, I mean about a & ds that are used in interviews
What really helped me after getting to know the basics, is practicing a lot with codewars/leetcode/hackerrank @fiery cosmos
I see, thanks
Could anyone here help me out with a recursive inplace quicksort, deets;
#help-broccoli message
How much python should I know before starting with DSA?
Fundamentals of programming are what you need to focus on while going for DSA. As long as your basic python concepts are okay, you should be good to go.
Yeah, DS&A is really about learning the concepts. Python would just be one way of encoding the concepts into instructions a computer can make sense of
The concepts generalize across languages
Thanks guys!
Detect text inside the circle?
I am trying to detect the text in the circle, i have two pictures one is plain and one has some circle on it i need to extract only text which has a circle around it. i have tried EasyORC, Tesseract already but did not get actual result also i have tried OPENCV too but in open cv the accuracy is very low because of the picture red background is there anyone who can help or suggest to me how i achieve these text under circle I am also attaching some pictures below.
Picture: My Result
is this going to work
maybe ask in #data-science-and-ml 
try it for e.g. 9
is this gonna work
Is this for a test 
Looks better. Do you really need the r variable?
oh yeah u can do it without r as well
thx
btw do u use return keyword in pseudocode
N is divisible by N -> r is False
It will always return False.
(except for when N = 1)
Hey guys can you tell me good resources to learn data structures and algorithms. I have a decent understanding of python. I just finished OOP.
pins
seems to be working
i recreate the alogrithm in python
N = 9
r = True
for i in range(2, N):
print(i)
if N % i == 0:
r=False
print(r)
By default python subtracts 1. Because it's a programming language and it comes from the convention in older languages of doing i = 0 ... i < N
N = 2
r = True
for i in range(2, N):
print(i)
if N == 2:
r=True
break
if N % i == 0:
r=False
print(r)
ez fix
make sense
Translating your latex to Python is something like for i in range(2, N + 1):
>>> N = 10
>>> for i in range(2, N + 1):
... print(i)
...
2
3
4
5
6
7
8
9
10
2 to N -> 2 to 10
[2, 10]
i could do this
You can just do 2 to N - 1
Or since this is whatever made up language you could do something like i <- [2, N)
That's pretty well understood as exlcusive.
yep
if it is make it less ambiguous
thx for the clarification
You really want to help people avoid off-by-one errors and stuff like that when reading your pseudocode.
im still bit unsure what u meant here
ik that list index starts with 0
do u mean that
The python range range(N) gives values from 0 to N-1.
or the fact that
when u do
for i in range(2,4):
print(i)
it only print 2 and 3
oh got it
is this pseudocode ambiguous
add the ith letter to r
if it was in python i would do i-1 letter
but ig in this pseudocode
it is clear enough
How about subtract 1 from i? Remove makes it sound like a list or something
oh yeah thx for the suggestion
I am trying to print a pattern ```
*
**
**** and this is the code which I hav written
for row in range(1,6):
for col in row:
print('*')
'/n'``` I am getting error ```for col in row:
TypeError: 'int' object is not iterable``` Can someone help me out what am I doing wrong
This might help.. for col in (1,row)
it won't
I am new to python the code in Java is ```
int n=5;
for(int i=1;i<=n;i++){
for(int j=1;j<=i;j++){
System.out.print('*');
}
System.out.println();
}```
for row in range(1, 5):
print('*'*row)
or if you really want to replicate the java code verbatim
for row in range(1, 5):
for col in range(row):
print('*', end='')
print()
what is end=''
print adds a newline by default (end='\n')
and how are we getting to know that the col is starting from 1
wdym? col in the loop goes 0, 1, ..., row-1
it loops row times
I am so sorry, for asking silly questions, but how are we getting to know that col is going 0 ..1.. row-1 .. because like in row we have specified that for row in range(1,5) that row is going from 1 ..6 but similarly in col we havent specified anything.. in col we have specified that whatever the value of row is . it is the same value of column
range(1, 5) is going 1, 2, 3, 4
and wrt the single argument version, range(n) is the same as range(0, n), so 0, 1, ..., n-1
ooh okaay understood..Did not know that.. and one last thing .. in the end why we have written print() . what does this do
print nothing, but the end will be still be printed, so it just prints a newline
I would much recommend the first version I posted, messing with end in print is pretty hacky
though the second version might be good as a learning exercise, I guess
Have understood clearly now.. Thaank you so much for bearing with me and helping me explain so clearly 😄
np
now for my question:
for col in zip(*board):
unit = [i for i in unit if i != '.']
what is zip(*board)
why does the above code work
it seems to give the column of the 2D array/list
like
[1
2
3
4]
then
[-- 2
-- 5
-- 6
-- 8
]
for the second column
when I try to print out the zip(*board) in Python, it just returns the whole list
but I know the code works (I copied it 🙂 )
oh wait, it turns every column into a row, and vise versa?
nvm I thought it printed the copy of the list
it's effectively transposing the list of lists
I thought zip command was for combining two values or lists
like zip(a,b) = [[a0,b0), etc] ]
it combines however many arguments you give, in this case you give a bunch of lists as arguments
if board is [list1, list2, ...] then zip(*board) expands to zip(list1, list2, ...)
what is *
do the lists need to be of the same size? (Does board need to be a square or can it be a rectangle?)
how can I can do this without zip? I mean how can I iterate through the columns one by one
like this?
for col in range(board[0]):
for row in range(board):
hi guys I have a large 3d scene with roughly 2000 stars/orbiting planets and am looking to use an octree spatial query structure to improve performance. I am using django with three js on the front end; from my understanding I cannot import modules/libraries and can only import within html tags linking to a hosted text doc. The following library looks great, however I do not see a relevant html tag https://github.com/vanruesc/sparse-octree. Am I correct in my understanding, that I need an html tag? Is there a way to create one? Alternatively, is there another appropriate library that does have an appropriate html tag? Thanks in advance.
it unpacks an iterable, you can use it where you normally put arguments, as I showed with zip
it will stop after the shortest iterable ends, just like zip normally behaves
and yeah you could iterate over columns by indexing into board
when I tried to run this code it failed ;-;
range(len(board)) and similarly for the other one
oh yea sorry I did that
In the 8 queens algorithm where you use permutations and pruning, you build up an array which starts out as being filled with empty space, right? And when you backtrack, you’ll reset the positions to being empty, right?
So like:```
1*******
13******
135*****
And then eventually you backtrack to:```
2*******
24******
241*****
Is that how it works?
Hey @patent ore!
It looks like you tried to attach file type(s) that we do not allow (.pdf). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.
Feel free to ask in #community-meta if you think this is a mistake.
im learning linked lists and i notice it uses yield to show the list
how does yield work
a yield in a function makes it a generator function so it can be put in a for loop like for yielded_value in yielding_func(): ...
yield is kinda like return but the state of the variables in the function are remembered and you can resume it to, for example, get the next loop value
!e py def yields123(): for i in range(1, 4): yield i for yielded_value in yields123(): print(yielded_value)
@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
the for loop extracts all the yielded things from the yields123 generator
I still do not understand it, what all it does is to return value from the loop
It's nothing but the return function
yields123 effectively returns 3 values (1, 2, and 3) when you call and loop over it
So?
but, importantly, the internal state of the function is remembered between each of those 1, 2, and 3
which isn't the case with a normal function call
Yo I get it I get it
and this is a simple example, but remembering the internal state is super handy sometimes, like if you wanted to write itertools.permutations yourself, yield helps https://docs.python.org/3/library/itertools.html#itertools.permutations
Okay I think it returns all the three integers at once after iteration.
I need help with github can anyone help me out? ;-;
Hey, I have a question about Big O. If I have a function with time complexity = x^2 + 2x + 3 so f = O(x^2) is it also true that f = O(2^x)
sure
Why is that?
cause big O is an upper bound (though people often speak of it like a tight bound) 
j=hi
hi
Ban me pls
<@&831776746206265384>
@fiery cosmoss
ban me
fix errors
pls
!mute 722821122743205960 666y seems like you're here just to spam
:incoming_envelope: :ok_hand: applied mute to @fiery cosmos until <t:22661973327:f> (665 years and 11 months).
Hey guys, can you help me?
Hey @stiff wing!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hey @stiff wing!
You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.
I can't debug this. will you help me?
Hi guys, if my algorithm is O(n/2) do I skip the 1/2 part when writing it as an answer?
yes, O(N) is exactly the same as O(N/2) or O(100N) or O(10N + 5) or O(N + log N)
oh okay, thanks mate. Appreciate it. Just started with algorithms
hi
In my PyCharm I want my file to be formatted automatically like when we code in Intell ij it formats the file autmatically.How can I do that, can someone please tell me
this channel is about algorithms and data structs, youcould ask in #editors-ides though
How sould I learn data stuctures for FREE??
Plus some book's table of contents (as a guide for which order to learn them in).
Also see pins.
Hi guys. Can someone help me debug a basic merge sort algorithm? I have been sitting here for ages, and i think it's a small detail
def Merge(A,i,m,j): #Merging SORTED arrays
#if len(A) == 1: return A
L = A[:m]
R = A[m:]
i = j = o = 0
while i < len(L) and j < len(R):
if L[i] < R[j]:
A[o] = L[i]
i += 1
else:
A[o] = R[j]
j += 1
o += 1
while i < len(L):
A[o] = L[i]
i += 1
o += 1
while j < len(R):
A[o] = R[j]
j += 1
o += 1
def MergeSort(A,i,j):
if i < j:
m = (i+j)//2
MergeSort(A,i,m)
MergeSort(A,m+1,j)
Merge(A,i,m,j)
newarray = [16,31,1,36,47,50,42,12,7,4,51,28,45,25,18,33]
j = len(newarray)-1
MergeSort(newarray,0,j)
print(newarray)
Output: [1, 4, 12, 7, 16, 31, 33, 36, 42, 45, 25, 18, 47, 50, 51, 28]
Expected output: [1, 4, 7, 12, 16, 18, 25, 28, 31, 33, 36, 42, 45, 47, 50, 51]
anyone got a turotial or something that explains how pathfinding works, i want to make a program that finds the best way between x amount of points, something that explains pathfinding would be helpful
I recommend reading this article by Ned Batchelder: https://nedbatchelder.com/text/names.html
!e
Basically:
def f(x):
x = 5
print("x =", x)
y = 10
f(y)
print("y =", y)
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | x = 5
002 | y = 10
Thanks. I'll look into it! ❤️
thanks
this channel is for questions about algorithms and data structures, you could ask your question in a help channel: #❓|how-to-get-help
sry
in python? it's the matrix multiplication operator
you can implement if for a class by implementing __matmul__
Can you give me a example how to use it
this channel is for questions about algorithms and data structures, you could ask your question in a help channel: #❓|how-to-get-help
ok sry
when you solve problems how do you create well designed code
or what makes certain codes well designed
def find_positions(positions, diags1, diags2, l, r):
global x
if l == r:
print(diags1, diags2, positions, " - - - - - ", sep="\n")
x += 1
return
for col in range(l, r):
d1 = col + positions[l]
d2 = len(positions) - 1 - positions[l] + col
if not (diags1[d1] or diags2[d2]):
diags1[d1] = True
diags2[d2] = True
positions[l], positions[col] = positions[col], positions[l]
find_positions(positions, diags1, diags2, l + 1, r)
diags1[d1] = False
diags2[d2] = False
positions[l], positions[col] = positions[col], positions[l] # backtrack
x = 0
positions = list(range(8)) # 8 queens
r = len(positions)
diags1 = [False] * ((r * 2) - 1) # downwards from left to right
diags2 = diags1.copy() # upwards from left to right
find_positions(positions, diags1, diags2, 0, r)
print(x) # this prints 0
This is 8 queens but it doesn't work, it prints 0
Why is it doing this?
def diag(x, y, queens):
return (x + y, queens - 1 - y + x)
def check_valid(diags1, diags2):
if all(d < 2 for d in diags1) and all(d < 2 for d in diags2):
return True
return False
def find_positions(positions, l, r):
global result
if l == r:
diags1 = [0] * ((r * 2) - 1)
diags2 = diags1.copy()
for x, y in enumerate(positions):
d1, d2 = diag(x, y, len(positions))
diags1[d1] += 1
diags2[d2] += 1
result += check_valid(diags1, diags2)
return
for i in range(l, r):
positions[l], positions[i] = positions[i], positions[l]
find_positions(positions, l + 1, r)
positions[l], positions[i] = positions[i], positions[l] # backtrack
result = 0
positions = list(range(8)) # 8 queens
r = len(positions)
find_positions(positions, 0, r)
print(result)
This is how I solved it, but it's not very good
It fully generates all 40,320 permutations
I wanted to do it the way which prunes them and only generates 5,508, like what the 8 queens problem wikipedia page mentions
def diag(x, y, queens):
return (x + y, queens - 1 - y + x)
def check_valid(diags1, diags2):
if all(d < 2 for d in diags1) and all(d < 2 for d in diags2):
return True
return False
def find_positions(positions, l, r):
global result
if l == r:
result += 1
return
for i in range(l, r):
positions[l], positions[i] = positions[i], positions[l]
diags1 = [0] * ((r * 2) - 1)
diags2 = diags1.copy()
for n in range(l + 1):
d1, d2 = diag(n, positions[n], len(positions))
diags1[d1] += 1
diags2[d2] += 1
if check_valid(diags1, diags2):
find_positions(positions, l + 1, r)
positions[l], positions[i] = positions[i], positions[l] # backtrack
result = 0
positions = list(range(8)) # 8 queens
r = len(positions)
find_positions(positions, 0, r)
print(result)
How to do this without needing to rebuild diags1 and diags2 every time? Can it be done where you only need to update the specific diagonals which were changed?
I tried to do it like this, but it printed 0 instead of 92, so I must have done it wrong
Yes retry
def diag(x, y, queens):
return (x + y, queens - 1 - y + x)
def check_valid(diags1, diags2):
if all(d < 2 for d in diags1) and all(d < 2 for d in diags2):
return True
return False
def find_positions(positions, diags1, diags2, l, r):
global result
if l == r:
result += 1
return
for i in range(l, r):
positions[l], positions[i] = positions[i], positions[l]
d1, d2 = diag(i, positions[i], len(positions))
diags1[d1] += 1
diags2[d2] += 1
if diags1[d1] < 2 and diags2[d2] < 2:
find_positions(positions, diags1, diags2, l + 1, r)
diags1[d1] -= 1
diags2[d2] -= 1
positions[l], positions[i] = positions[i], positions[l] # backtrack
result = 0
positions = list(range(8)) # 8 queens
diags1 = [0] * ((len(positions) * 2) - 1)
diags2 = diags1.copy()
r = len(positions)
find_positions(positions, diags1, diags2, 0, r)
print(result) # it still prints 0
It still doesn’t work
crazy how many solutions are possible for this problem
I dont know so much about Python even after years of using it :_:
ayo mates,tell me the best platform to learn python
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
sort_lambda = sorted(nums, key = lambda x: x%2)
print(sort_lambda)
how is key getting any value? how is this lambda function getting any value
anyone here know how to solve a recursion tree with a square root?
Do you know how a normal function (defined with def) works?
yes
The sorted function will just call the key function on each of the items
but where is the key function?
lambda is just a shorthand for creating a function. You could rewrite your snippet like this:
nums = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
def my_key(x):
return x % 2
sort_lambda = sorted(nums, key = my_key)
print(sort_lambda)
so in this case how will the my_key function get the argument?
Internally, sorted will call this function on each element of the list
ohhh thank you
!e
For example, this is how you could implement bubble sort accepting a key function:
def bubble_sort(a_list, key):
swapped = True
while swapped:
swapped = False
for i in range(len(a_list) - 1):
if key(a_list[i]) < key(a_list[i + 1]):
a_list[i], a_list[i + 1] = a_list[i + 1], a_list[i]
swapped = True
nums = [6, 7, 1, 3, 4, 5, 2]
bubble_sort(nums, key = lambda x: x)
print(nums)
bubble_sort(nums, key = lambda x: x % 2)
print(nums)
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | [7, 6, 5, 4, 3, 2, 1]
002 | [7, 5, 3, 1, 6, 4, 2]
to be pedantic, that is not how the internal sort would work, it's documented to only call the function once per element
the end result will be the same though, unless you have a really weird key function
(maybe slower, if the key function is slow)
right
well, it doesn't really matter here
just pointing out that the semantics are a tad different 🙂
e.g. you could implement shuffle in a really silly way by generating a random number in your key function with the internal sort
#esoteric-python: you're hired 🤝
it is sorting the nums list on the basis of values that is returned by lambda function
For example, if we pass a list of strings in sorted(), it gets sorted alphabetically. But if we specify key = len, i.e. give len function as key, then the strings would be passed to len, and the value it returns, i.e. the length of strings will be sorted. This means that the strings would be sorted based on their lengths instead
0 or 1?
oh I see
it's sorting all the even numbers first
and then the odd numbers
because % 2 returns 0 for even numbers
nice
L = ["cccc", "b", "dd", "aaa"]
print("Normal sort :", sorted(L))
print("Sort with len :", sorted(L, key=len))
output
Normal sort : ['aaa', 'b', 'cccc', 'dd']
Sort with len : ['b', 'dd', 'aaa', 'cccc']
Python is cool
yes it sure is
yes
can anyone help me with a DP solution i implemented
def rob_house_memo(nums,memo={}):
if tuple(nums) in memo:
return memo[tuple(nums)]
elif len(nums) <=2:
return max(nums,default=0)
else:
memo[tuple(nums)] = max(nums[0]+rob_house_memo(nums[2:]),nums[1]+rob_house_memo(nums[3:]))
return memo[tuple(nums)]
this is for the 198. House Robber on leetcode, i did DP properly here, but the thing is my memoization is not ideal
im bascially storing slices of the input array as tuples in the dictionary
is there a better way of memoizing in this scenario?
DP?
yea
what is DP?
dynamic programming
There seems to be a O(n) time complexity solution that doesn't use any memoization
Yeah it seems linear in time complexity, just the space complexity could be a problem
think that might actually be quadratic
yeah i thought so too
There also already is a memoization decorator you could use if you wanted to go that route
functools.lru_cache
that could work, also do you think i could store indexes instead of the whole array in the dictionary?
if there is only 1 solution for a given index then yes
