#algos-and-data-structs

1 messages ยท Page 142 of 1

slim crest
#

this okay

high pewter
#

What do you mean?

slim crest
#

whats simulation?

haughty mountain
#

i.e. the precision depends on the dt here

haughty mountain
slim crest
#

oh okay

high pewter
#

I am trying to find the problem for part 2

#

But I can't figure

storm night
#

What's the equivalent of zip(*args)?

The context is, I'd like to find a way to get a list of the columns of a sudoku board. using zip(rows) will give me all the columns AFAIK, but I'm not sure if that's considered cheating or not. I wonder if there's a better way ๐Ÿ˜›

haughty mountain
#

the core part of the solution I would have expected if I asked this problem to someone is

t = 0
while pos1 < goal and pos2 < goal:
  pos1 += dt*vel1
  pos2 += dt*vel2
  t += dt
#

at the end we have final positions and the final time

high pewter
#

Yes

haughty mountain
#

for part 2 you have different logic for one of the people

high pewter
#

Yeah

haughty mountain
slim crest
#

does it take 20 mins for to charge

#

or hours

high pewter
#

Minutes

slim crest
#

try to code that

#

i'll do it this side too

high pewter
#

K

haughty mountain
slim crest
#

input()*2/10

#

thats works

#

if its allowed

high pewter
#

No maths unfortunately

#

0 math involved

high pewter
#

Thats what this problem got me too

haughty mountain
#

no maths here would surely just means don't use the closed form equation

#

but simulate instead

#

simulation will of course involve some math

storm night
high pewter
slim crest
#

log

haughty mountain
#

but you are adding and multiplying numbers in your code ๐Ÿ˜ฑ

high pewter
#

Oops my bad

high pewter
#

No math equations

#

That is not involved

haughty mountain
#

right

storm night
#

What if I was put in a situation where I cannot use zip? Would I have to use a naive solution like looping through the rows of a sudoku board, then getting all the 0 indexes, appending them to a new row, then moving to all the row[1]?

That would be n^2 huh

slim crest
#

input()*2/100 is not a equation tho

haughty mountain
#

why*2/10?

slim crest
#

then v2timetaken += (v2timetaken*0.4)

haughty mountain
#

0.4?

slim crest
#

sincr minues to charge is 20

haughty mountain
#

it's not in general, it's an input you get

slim crest
#

20*2/100

#

= 0.4

haughty mountain
#

you really can't assume a constant velocity here

#

they will run for a bit and then stay still while charging

slim crest
#

hmmm

#

true

#

but then why add it to time

#

since total tavelling time is 25

haughty mountain
#

this is one way of implementing the actual logic, only advance if we are in the operation phase

t = 0
while pos1 < goal and pos2 < goal:
  t_cycle = math.fmod(t, t_o+t_c)
  if t_cycle <= t_o:
    pos1 += dt*vel1
  pos2 += dt*vel2
  t += dtโ€Š
#

that's all the changes that would be needed for my solution

#

fwiw, math.fmod(x, m) takes x and removes as many multiples of m from it as it can (it's the float equivalent of modulo for integers)

high pewter
#

Never learned math.fmod in my class so I am unable to use this function

haughty mountain
#

the full operation-charge cycle takes t_o+t_c time, and we can only move in the first t_o time

#

(well f**k your teacher then...)

#

you can implement if manually, but it's dumb to have to do so

high pewter
#

I f***king agree

haughty mountain
#
t = 0
t_cycle = 0
while pos1 < goal and pos2 < goal:
  if t-cycle <= t_o:
    pos1 += dt*vel1
  pos2 += dt*vel2
  t += dtโ€Š
  t_cycle += dt
  if t_cycle >= t_o + t_c:
    t_cycle -= t_o + t_c
#

this would be doing it manually

#

(a cute way of implementing this whole thing would be to use generator functions, but let me guess those aren't allowed either)

high pewter
#

Yes sir

#

@slim crest are you close?

slim crest
haughty mountain
#

(god I hate seeing those 1s instead of a dt)

haughty mountain
#

also, there is no point in tracking both times, they are the same

slim crest
#

this was my solution of part 1

#

@high pewter i am using input*2/100

#

for part 2

haughty mountain
high pewter
#

Let him try

#

We will see

#

I understand your point though

haughty mountain
#

it's wrong and I want to spare the misery of implementing the wrong thing in vain...

high pewter
#

Make sense

haughty mountain
#

e.g. pick t_o = 1, t_c=999 and pick the distance that is 1*velocity

#

the actual solution is 1 minute

#

the solution with the constant velocity thing is 1000 minutes

#

it's just...wrong

high pewter
#

Ima head to bed because it's 2 where I am at and I have school tomorrow

slim crest
#

i'm back

high pewter
#

K

high pewter
#

Did u do it?

slim crest
#

hold up

#

nvm

#

the solution is simple

high pewter
#

Pardon?

#

Have u got the solution?

glossy breach
#

smh i still dont get why math shouldnt be involved in this problem

slim crest
pure ocean
#

does the adjacency list representation have a faster Big O time complexity than the adjacency matrix representation when both are applied with Dijkstra's Algorithm??

haughty mountain
#

adjacency matrix is really wasteful unless you have almost a fully connected graph

pure ocean
#

what would be their Big-O time complexities?

haughty mountain
#

time complexity for what exactly?

pure ocean
#

both adjacency list and adjacency matrix when they're applied with Dijkstra's Algorithm

haughty mountain
#

which of the two representations you use doesn't impact the time complexity of Dijkstra

slim crest
#

hello

#

can someone help make a binary search tree

haughty mountain
#

I guess technically is could be slower for adjacency matrix because you need to scan more elements to find neighbors pithink

pure ocean
# haughty mountain I guess technically is could be slower for adjacency matrix because you need to ...
#

does this explain it well or something

haughty mountain
#

if you want neighbors, adjacency list is just a nicer representation to work with

slim crest
#

class node:
def init(self,value= None):
self.value = value
self.left_child = None
self.right_child = None

class BST:
def init(self):
self.root = None

def insert(self,value):
    if self.root == None:
        self.root = node(value)
    else:
        self._insert(value,self.root)

def _insert(self,value,cur_node):
    #From root check whether to go right or left
    if value < cur_node.value:
        #if there is no value on the left child node inset value here
        if cur_node.left_child == None:
            cur_node.left_child = node(value)
        #else call recursive function to continue as if left node is root
        else:
            self._insert(value,cur_node.left_child)
    #From root check whether to go right or left
    elif value > cur_node.value:
        #if there is no value on the right child node inset value here
        if cur_node.right_child == None:
            cur_node.right_child = node(value)
        #else call recursive function to continue as if left node is root
        else:
            self.insert(value,cur_node.right_child)
    else:
        print('Value already in tree')

def print_tree(self):
    if self.root != None:
        self.print_tree(self>root)

def _print_tree(self,cur_node):
    if cur_node != None:
        self._print_tree(cur_node.left_child)
        print('%d'% cur_node.value)
        self._print_tree(cur_node.right_child)

def fill_tree(tree,num_elems = 100,max_int = 1000):
from random import randint
for k in range(num_elems):
cur_elem = randint(0,max_int)
tree.insert(cur_elem)
return tree

tree = BST()
tree = fill_tree(tree)

tree.print_tree

pure ocean
haughty mountain
#

the one thing adjacency matrix is useful for is if you want to answer "is a connected to b?" quickly, which is kinda rare

pure ocean
haughty mountain
#

I would say just use adjacency list as the default graph representation unless you have good reason to do otherwise

haughty mountain
#

I've never seen a use for that kind of BST pithink

#

balanced binary search trees (BBST) have good uses though

pure ocean
#

how do i develop a directed acyclic graph for a factorial?

slim crest
#

i am gonna code on my own since understand theory behind

pure ocean
#

in a fully connected undirected graph, which has a higher space complexity,

#

adjacency matrix or adjacency list representation

agile sundial
#

it's the same

pure ocean
# agile sundial it's the same

is there a case where a. matrix has higher space complexity than a. list considering the same fully connected undirected graph?

agile sundial
#

no

pure ocean
#

so the space complexity between the two are always the same under that kind of graph then?

agile sundial
#

yes, think about the two data structures

pure ocean
#

considering they deal the same problem

agile sundial
#

yes, when backtracking you can use the previous states to narrow down the states you have to search

pure ocean
agile sundial
#

no, complete search is almost always worse than everything else

agile sundial
#

i say almost because there's probably a case i didn't think of or don't know about

cerulean elk
#

if I have
arr = [["name1", number1],["name2", number2], "name3", number3]]

and i want to sort the array with respect to the numbers, how can i do that?

glossy breach
#

sort takes a key kwarg

#

which tells it what to sort the list by

cerulean elk
#

is it possible to do it wth a loop?

#

oh wait nvm

glossy breach
#

it's much simpler

#

in this case you can sort with key a[0]

haughty mountain
#

!d list.sort

halcyon plankBOT
#

sort(*, key=None, reverse=False)```
This method sorts the list in place, using only `<` comparisons between items. Exceptions are not suppressed - if any comparison operations fail, the entire sort operation will fail (and the list will likely be left in a partially modified state).

[`sort()`](https://docs.python.org/3/library/stdtypes.html#list.sort "list.sort") accepts two arguments that can only be passed by keyword ([keyword-only arguments](https://docs.python.org/3/glossary.html#keyword-only-parameter)):

*key* specifies a function of one argument that is used to extract a comparison key from each list element (for example, `key=str.lower`). The key corresponding to each item in the list is calculated once and then used for the entire sorting process. The default value of `None` means that list items are sorted directly without calculating a separate key value.
haughty mountain
#

the key function mentioned here

haughty mountain
slim crest
#

@haughty mountain you good ?

#

!d filter

halcyon plankBOT
#

filter(function, iterable)```
Construct an iterator from those elements of *iterable* for which *function* returns true. *iterable* may be either a sequence, a container which supports iteration, or an iterator. If *function* is `None`, the identity function is assumed, that is, all elements of *iterable* that are false are removed.

Note that `filter(function, iterable)` is equivalent to the generator expression `(item for item in iterable if function(item))` if function is not `None` and `(item for item in iterable if item)` if function is `None`.

See [`itertools.filterfalse()`](https://docs.python.org/3/library/itertools.html#itertools.filterfalse "itertools.filterfalse") for the complementary function that returns elements of *iterable* for which *function* returns false.
high pewter
#

thank you guys for your help

#

i got the solution to my problem

#

@slim crest

#

@haughty mountain

slim crest
high pewter
#

its stupid but i got it this morning

slim crest
#

its okay

high pewter
#

yeah it works with the problem

slim crest
#

okay thats cool

high pewter
#

thx for the help

slim crest
#

comeback if you have any more problems

high pewter
#

and is kuroko's basketball your fav anime?

slim crest
#

nah

#

but its a recent favourite

high pewter
#

yeah there is still 1 more part for this problem

#

i will see if i have any more problems

slim crest
#

share the part

#

lemme have a go

slim crest
high pewter
#

this the last part

slim crest
#

okay

high pewter
#

Have you tried @slim crest?

slim crest
#

no not yet

slim crest
#

df_out = dfs

slim crest
#

can some please help

agile sundial
#

help with what

slim crest
#

o notations

agile sundial
#

yes, but what specifically in this problem do you need help with

slim crest
#

however

#

heres my stab at a code challenge

#

how can I make my program more efficient

fiery cosmos
#

hm

austere sparrow
#

@high pewter Don't ask if anyone is available, just ask your question.

#

If people see a question, they will be more likely to help.

haughty mountain
#

the question was stated earlier

#

the code I sketched for part2 is easily adaptable to this task as well, this is just the same logic but for both simulations

high pewter
#

I tried to use the same thing

#

But Mr.Veera position does not change

haughty mountain
#

the thing you ended up writing does not generalize as easily I think

high pewter
#

K

haughty mountain
#

like, my code change is just

t = 0
while pos1 < goal and pos2 < goal:
  t_cycle = math.fmod(t, t_o+t_c)
  if t_cycle <= t_o:
    pos1 += dt*vel1
  pos2 += dt*vel2
  t += dtโ€Šโ€Š
```to
```py
t = 0
while pos1 < goal and pos2 < goal:
  t_cycle1 = math.fmod(t, t_o+t_c)
  if t_cycle1 <= t_o:
    pos1 += dt*vel1
  t_cycle2 = math.fmod(t, t_b+t_r)
  if t_cycle2 <= t_b:
    pos2 += dt*vel2
  t += dtโ€Šโ€Š
high pewter
#

ok makes sense

#

what does dt mean?

#

math.fmod also

#

i started coding stated b4

haughty mountain
#

dt is the time step, I guess you use 1 everywhere

high pewter
#

i did not know this

#

why did you use a time step

haughty mountain
#

maybe some examples help with what fmod does

fmod(1.0, 2.0) == 1.0
fmod(1.5, 2.0) == 1.5
fmod(2.0, 2.0) == 0.0
fmod(2.5, 2.0) == 0.5
fmod(3.0, 2.0) == 1.0
fmod(3.5, 2.0) == 1.5
fmod(4.0, 2.0) == 0.0
...
high pewter
#

i se

rich pelican
#

comebine your function with a positional argument? 1 function to process both?

high pewter
#

this is something i never learned

#

i am hoping 1 of you guys can help me out

fallow nymph
#

wish i could help you katakana!

#

is anyone know of a good cheat sheet for the basic python and data structure??
*guess google is my best friend lol.. for anyone that might be interested i found this:
https://www.pythoncheatsheet.org/

fiery cosmos
#

Heap is overrated

haughty mountain
fiery cosmos
#

I made an algorithm that reports possible swaps in a bejeweled board along with their potential streak.

fiery cosmos
#

id like to see if any one has a conceptual idea of how they would do it or an implementation

#

so i can compare mine to yours

#

im very proud of my way but there might be another way

slim crest
#

do any of you know partitions

#

i already tried

#

i am not in university

fiery cosmos
#

maybe give more context. Whats the problem and what are partitions.

high pewter
#

Thank you @slim crest and @haughty mountain

slim crest
high pewter
#

i am officially done with the mathematical challenged teacher question

#

bro i lost my soul in these past 2 days

high pewter
#

the problem was worth 30% of my mark

slim crest
high pewter
#

i am done

slim crest
high pewter
#

i will for sure come bac if i have any more problems

#

but thank you

#

and have a great weekend

slim crest
#

2+2

high pewter
#

may god bless you all

slim crest
#

1+1+2

high pewter
#

amen ๐Ÿ™

slim crest
#

since they 5 ways of adding up to 4

fiery cosmos
#

well see thats alot easier to grasp than all that math in the beginning. Now somone may be able to help. Just need to put it all in one sentence and post it.

autumn pendant
#

!e
for number in range(100,8):
print(number)

halcyon plankBOT
#

@autumn pendant :warning: Your eval job has completed with return code 0.

[No output]
slim crest
#

!e

thin river
#

Hey guys!
Can you please suggest how to sharpen data structures and algorithms skills?

slim crest
#

watch tutorials and solve problems like i am right now

barren solstice
#

what's the cooldown name in python?

clear vortex
#

!e
print("Hi"

#

o

#

!e
import Discord
from discord.ext import commands

client = commands.Bot="?"

@ember shore
async def ping(ctx):
await ctx.send("pong"

bot.run("123")

halcyon plankBOT
#

@clear vortex :x: Your eval job has completed with return code 1.

001 |   File "<string>", line 6
002 |     <@โ€‹!545576944008298516> 
003 |     ^
004 | SyntaxError: invalid syntax
shut breach
#

@clear vortex #bot-commands please dont spam here

fiery cosmos
#

Good morning to everyone, I'm working on a csv file and I would like to write another csv. In particular my csv is composed of persons and an associated measurements list ( person1|[m1,m2,m3....] person2|[m1,m2,m3...] ecc). I want obtain something like this: person1|m1|m2, person1|m2|m3, person1|m3|m4, person2|m1,m2|.... So I would loosen the list and write a row for each tuple. Any help? I hope I was clear

#

i try to explain better using pseudocode
FOR EACH ROW IN CSV
name= row[0]
surname=row[1]
list= row[2]
if list.size==1
write name,surname, list[0], null
else if list.size>1
for i=0, i<list.size-1, i++{
write name, surname, list[i], list[i+1]
}
so I want to read from a csv and write on another csv

runic anvil
#

You want each pairwise tuple?

#

I think itertools module might help you in breaking it up

#

perhaps the pairwise() function from it or product(), hope that helps... if I understood correctly

runic anvil
#

If anyone is interested on working with me with an expert-level hackerrank puzzle, send me a dm! I've been stuck on one for a while... i'm using python to solve it.

haughty mountain
#

not dm, but why not link the problem here?

fiery cosmos
#

i have a question would it be possible to loop without looping i have an issue with automatisation and i just can't figure it out any help or idea would be more than welcome

haughty mountain
#

would it be possible to loop without looping
what does this even mean?

fiery cosmos
#

my hash function for bejeweled swaps. only cares about combinations not permutations.

hash = is_horizontal ? min(swapee_index, swaper_index) : min(swapee_index, swaper_index) + (columns - 1) * rows
dapper sapphire
#

sorting a string is O(n log n) and then joining it back again via join is O(n).

So to sort a string and then join it, it would be O (n) + (n log n), but we would simplify it to O(n log n)?

#

and if we have to perform the same sequence on a list of words, then we would be looking at O(K N log N), where K would be the number of words in a list, and N would be the length of each word?

#

words = ["This", "is", "a", "test"]

slender sandal
#

Or O((1 + log n) n)

dapper sapphire
#

How would it be O(n^2 log n)?

dapper sapphire
storm night
#

Does anyone know of a weighted graph generator? I know its a super niche usage case but I really dont wanna manually write out a directed graph

#

OH wow this is really cool. I wish there was an option to simply export the graph in like python dictionaries

https://csacademy.com/app/graph_editor/

soft cape
#

Can somebody in here help me with the minimax algorithm? I make tic tac toe for a school project and struggle finding a way to implement this algorithm into my game so I can make an unbeatable ai. I would appreciate help alot.

gritty marsh
soft cape
#

wait

#

problem might be that it is mostly in german since its for a school project

#

but I can still send

#

and I tried multiple times but all tries didnt work

#

so should I just send you the code of my twolayerbot?

gritty marsh
#

yes

#

paste it here

#

!paste

halcyon plankBOT
#

Pasting large amounts of code

If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pythondiscord.com/

After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.

soft cape
#

if you have questions regarding the german words just ask

gritty marsh
soft cape
#

it's ok

gritty marsh
#

@soft cape is your problem coming up with the algorithm, or are you encountering some kind of error in your program

soft cape
#

I just can't figure out how I should rewrite the bot function to not just look 1 move into the future but simulate every possible outcome

#

I watched several videos but none of this worked and couldn't figure it out

soft cape
gritty marsh
#

Can you point me to your minimax implementation if it exists already in your code?

soft cape
#

but it should exist in the twolayerbot function

#

there already is a loop which predicts 1 move into the future

#

it should be the second for loop

gritty marsh
#

These components are:

  1. function that defines the utility (preference) of a state
  2. function that defines how to transition from state to state
  3. function that defines the transitions for a particular state
  4. function that defines if a desired state has been found
  5. function that defines what transition is best for the current state
#

The easiest to implement right now is 4.

#

It seems you've implemented it already, right? In the first function in your source code @soft cape

soft cape
#

yeah the first function tells if someone won

#

either the player or the bot

#

gewonnen is german for won

gritty marsh
#

Alright

#

The next easiest is 1.

#

The "utility" of a state is the sum of its score and the score of the states that come after it

soft cape
#

what do you mean with score?

gritty marsh
#

the score is defined by whether or not the state is a winner state, loser state, or neither

soft cape
#

ahh ok

gritty marsh
#

so, if it's a winner state, the score is 1

#

if it's a loser state, the score is -1

#

if it's neither, the score is sum of the score of the states that come after it

soft cape
#

and tie is 0

#

is that right?

gritty marsh
#

Yep

soft cape
#

ok

#

so i have to make a function that tells if the board has a score of 1, 0 or -1?

gritty marsh
#

Indeed

#

For our purposes, the "winner" state will simply be the state where X wins

soft cape
#

so if x wins the score equals 1

#

but I want x not to win

gritty marsh
soft cape
#

ok

#

if you go down to line 264 there is another win function (this is for the 2d list of the bot produces)

#

I changed the game_over in the case that 'O' wins to -1 and in case that 'X' wins to 1

#

and also made another elif that tells if it's a tie in which case it'd set it to 0

gritty marsh
#

Alright, good

soft cape
#

should I send you the function?

gritty marsh
#

It's all good you can send it later

soft cape
#

ok so this should solve 1.

#
    1. and 5. to go
gritty marsh
#

Next function to implement would be 3.

soft cape
#

ok

gritty marsh
#

Do you know how to implement it?

soft cape
#

not really if it isn't that what i already wrote in that for loop I told you about

gritty marsh
#

Alright, good then

#
  1. would just be applying an action, I see you've already done it
#
  1. is the main dish
soft cape
#

so 2. and 3. are both basically finished?

#

what my problem with 3. is ig is the swap between putting in 'O' and 'X'

gritty marsh
#

Well if you assume X goes first, it's X's turn if the number of X and O on the board are equal

soft cape
#

yeah I solve the via count%2 == 0: 'X' and count%2 == 1: 'O'

#

but when I try it in a loop for the minimax it doesn't really work

#

idk

gritty marsh
#

What do you mean?

soft cape
#

in the loop i did for that sometimes the board was full but there were more xs than os, sometimes the board wasn't full and sometimes the count extended over 9 which should be the time the board is full

#

so i don't know how to make that

gritty marsh
#

That's weird

soft cape
#

ik

gritty marsh
#

Maybe we should just write a dedicated function for it

soft cape
#

probably

gritty marsh
#
def turn(board) -> str:
  if board.count('X') == board.count('O'):
    return 'X'
  else:
    return 'O'
soft cape
#

what does that make

#

do

#

sorry

gritty marsh
#

It just returns the turn given a board

#

assuming board is a 2D list of strings

soft cape
#

ahh ok thank you

gritty marsh
#

of course you can change it to whatever your representation of X and O are

soft cape
#

understood

#

is that -> str: important?

#

?

gritty marsh
#

It's just a type hint

#

Here, i'm returning a string, so it's a visual hint that the function returns a string

#

it doesn't behave differently, it's just there for other developers in case they read it

soft cape
#

so it's basically like # -> string at the end?

gritty marsh
#

Yep

#

Except it's special syntax so that IDEs like PyCharm and VSCode can read it and give you helpful suggestions

soft cape
#

now I should try to do 2. again

#

can you help me there too?

#

so I got it for 1 turn into the future with either 'O' or 'X'

gritty marsh
#
  1. Is essentially just setting a value in a board
#

So, erm, it can be like this:

def transition(board: list[list[str]], position: tuple[int, int], turn: str) -> board:
  result = [row.copy() for row in board]
  i, j = position
  result[i][j] = turn
  return result
soft cape
#

for i in frei:
dummy2[i] = turn(dummy2)

#

?

#

is the : again like the ->?

#

and do I have to use a 3D list or does it work with a 2D list aswell?

gritty marsh
gritty marsh
#

Row and columns of lists?

#

What will the list represent

soft cape
#

sorry was afk for short

#

yeah rows and columns

#

the list I use for the 2layerbot is 2d

#

just index of each field

gritty marsh
#

Indeed

#

So are you done with implementing transition now?

soft cape
#

not really

#

what does result mean

#

do I need it for the 2d list

gritty marsh
#

result is just the result of applying the action

soft cape
#

and row.copy() for row in board

#

dummy2[i] = turn(dummy2)

#

isn't this all I need for a 2D list?

gritty marsh
#

What's dummy2 supposed to be?

soft cape
#

it's a copy of the original 2D list

#

so basically just the board

gritty marsh
#

Hold on let's hop on a call

#

I think we can communicate faster there

slim crest
quartz crest
#

How to determine the storage space complexity of algorithms?

shut breach
#

calculate how much it needs to store at one time

agile sundial
#

the same way you determine the time complexity, pretty much, but with storing stuff instead

slim crest
#

poop

rich dagger
#

Hey folks, does anyone have any good resoures on understanding and implementing ECS systems?

rich dagger
#

Wow, such quiet lol

half forge
#

yep

haughty mountain
alpine quiver
#

Hi! It's been a while since I've hung out here. cool to see this place has blown up. I've been trying to work on my fundamentals recently and would love some help on BSTs.

i noticed whenever i do leetcode problems i stumble more on BST-based problems. its prob cuz i havent used BSTs since college, but I feel like im just misunderstanding how pure BSTs are defined formally.

how i understand them is they are:

  • valid if empty
  • valid if left subtree node values are < root value
  • valid if right subtree node values are > root value
  • valid if left child value is < parent value
  • valid if right child value is > parent value

in the screenshot I'm reviewing logic to calculate unique BSTs from n nodes (1, ..., n). in my mind once i think of a counter example to the formula you'd want to use I will end up backing myself into a corner. with the root as 2, are any of those BSTs invalid?

i'm trying to do more and more hard-level problems on leetcode but i perform poorly on BST-based medium problems. so i wanna make sure i understand the fundamental data structure. for some reason I see people defining BSTs differently so I'm having trouble poking holes in my logic.

#

for context I've always enjoyed The Algorithm Design Manual by Steven Skiena. so I've been reviewing that text. I'm assuming I've missed something. I also do fine on problems from leetcode or hackerrank for validating BSTs.

alpine quiver
#

maybe theres actually 5? โ˜ ๏ธ

slim crest
#

do you have trouble understanding binary trees?

haughty mountain
alpine quiver
haughty mountain
alpine quiver
haughty mountain
alpine quiver
#

Recursively the function G(n) that implements f(i-1) * f(n-i) calculates the number of possible BSTs given n where f(i-1) calculates the possible left subtrees and f(n-i) for the right.

#

At least how I understand it

#

In this case i is the root

#

Youโ€™d sum G(n) over every root

haughty mountain
#

fwiw the number of unique bsts is the same as the number of unique binary trees, which ends up being the Catalan numbers

alpine quiver
#

Yea see maybe this is where Iโ€™m stuck

#

I might be overthinking it

haughty mountain
#

in short, you can put n different numbers at the top, which splits the tree into subtrees of size (0, n-1), (1, n-2), ..., (n-1, 0)

then
f(n) = sum(f(i)*f(n-1-i) for i=0,...,n-1)

#

haven't checked my work, but I think that thing is correct

#

yeah, that ends up being the catalan numbers

haughty mountain
# alpine quiver I might be overthinking it

The logic for the formula I wrote is simple, n choices for root, n corresponding splits of the tree. For every split we multiply the different configurations of the subtrees f(left_subtree_size)*f(right_subtree_size).

alpine quiver
alpine quiver
haughty mountain
#

i=3 has 5 BSTs

#

(typod and fixed)

alpine quiver
#

Hmm maybe I was interpreting the formula incorrectly

haughty mountain
#

the thing you drew up is one of the terms in f(5): f(1) * f(3)

alpine quiver
#

Yea exactly. Thatโ€™s whatโ€™s thrown me off. How Ive understood it itโ€™d be 3

haughty mountain
#

1*5

alpine quiver
#

1*3 sorry. f(2-1) * f(5-2)

#

Been grinding leetcode all weekend. Pretty brain fried haha

haughty mountain
#

f(3) is 5

#

ignore 1 and 2 in your diagram and those are f(3)

alpine quiver
#

You mean G(3) (if weโ€™re following my diagram word for word)?

haughty mountain
#

whatever you call the number of BSTs ๐Ÿ˜›

alpine quiver
#

hmm

haughty mountain
#

your G is just one term I guess?

alpine quiver
#

I split the function into left side right side with the fโ€™s and call that G(n) but I think Iโ€™m still confused on unique BSTs with root 2

haughty mountain
#

my f is your f, so that's good at least

alpine quiver
#

I think what Iโ€™m stuck on is are the unique BSTs I created valid? And if so how does that fit into #algos-and-data-structs message. Which is what Ive understood as the solution. But #algos-and-data-structs message I think checks out with what Iโ€™m thinking. Tho Iโ€™m not entirely sure yet.

Discord

Discord is the easiest way to communicate over voice, video, and text. Chat, hang out, and stay close with your friends and communities.

haughty mountain
#

the 5 trees you wrote are valid

alpine quiver
#

So if i = 2 given
[1,2,3,4,5]
right side would be
f(5-2)=3

#

G(n) = f(2-1) * f(5-2)

haughty mountain
#

f(3) = 5

#

not 3

#

that's the one confusion I think

alpine quiver
#

Can you elaborate on the math behind f(3)?

haughty mountain
#

as I mentioned f(3) are the trees you drew, ignoring the 1 and 2 that are just...there

alpine quiver
#

Then maybe i am interpreting the material wrong. Ive thought i=2 f(5-2)=3 since logically 3 nodes are available right of 2.

#

Thatโ€™s kinda the gist of what Ive read

haughty mountain
#

how many ways can you arrange 3 nodes into a BST?

alpine quiver
#

5

haughty mountain
#

yep, these ones

alpine quiver
#

Yea so thatโ€™s where Iโ€™m stumped. What Ive been studying has stated 3 unless Iโ€™m super misunderstanding. Granted none of the material actually โ€œshows the workโ€

#

Really appreciative of the help tho. Been struggling with this for a good chunk of today

haughty mountain
alpine quiver
#

Actually I think i 100% misunderstood and I even knew the logic. f(3) is G(3) recursion

#

Which I think would be the f(3) youโ€™re talking about

#

G(n) is recursive*

haughty mountain
#

your G is the number of trees if you fix a root
f is a sum of G for all choices of root

alpine quiver
haughty mountain
#

this is from your book

alpine quiver
#

Thatโ€™s where I failed to bring it all together. I was reading too much into verbiage.

haughty mountain
#

(I think it's the right book at least)

alpine quiver
#

I knew it had to be executed recursively but kept seeing โ€œgiven 3 nodes you have 3 structuresโ€. I think I misread it that way at least. Itโ€™s given three nodes you have G(3) I think

#

Which I believe is your point

haughty mountain
#

yeah, I kinda skipped past using G at all when I derived my expression and directly expressed it in terms of f

alpine quiver
#

Iโ€™m pretty confident I get it now. Thanks! Iโ€™ll give it another shot tomorrow.

haughty mountain
#

I hope you didn't misread tree as three in some place

#

ah, "three-node trees" not to be confused with "three node-trees"

alpine quiver
#

Maybe. Iโ€™ll see if I can find the examples. I got so desperate that I even watched a couple YouTube videos. So even then I was missing it. I was reading/hearing [1,2,3,4,5] gives you 3 trees.

alpine quiver
#

Super brain fries ๐ŸŸ

fiery cosmos
#

num = random.randint(0,8)

SwitchNum = [num]

def my_num(start):
current= start
while True:
continue current

nums= my_nums(SwitchNum)

for numz in nums:
print(numz)

#

how can i make work a randint object through a generator?

#

i have a little bit of trouble understanding the concpet

#

but i would like my loop to go infinitely through randoms numbers while remembering the last number

#

can someone help me with this a little bit?

fiery cosmos
#

You read me right

pearl leaf
#

is this the place to ask questions?

#

??????????

fiery cosmos
#

I have a question regarding solving some M number of equations.

Say I have N number of variables and M number of equations.

I want to resolve them, SUCH THAT

  1. they ALL should have values more than or eq to 0.
  2. the norm should be minimum
  3. the sum of all of them should be 1

What have I done so far?

I have tried to resolve it using lstsq (https://docs.scipy.org/doc/scipy/reference/generated/scipy.linalg.lstsq.html#scipy-linalg-lstsq)

Issues with it: while it gives least squares, it generates minimum values in solN if required(which is expected).

Can anyone suggest me what else can I try?
Can this be resolved with LPSolver? I can add constraint that they should have positive value, tho then I'm not sure if it will try to find least squared solN.

dire plume
#

Okay, so we first note that if M >= N we have either no, or exactly one solution; this probably isn't what you want, so we'll take M < N. You're also probably representing this as a matrix A and the variables by a row/col matrix x.

What do you mean by "they all" are >= 0? The values of A? And the norm of what, the matrix? Which norm? And the sum of what?

EDIT: Had M and N backwards.

fiery cosmos
dire plume
#

Whoops, you're right, I had my M and N backwards.

fiery cosmos
#

I'll add an example to explain more. It will be more convincing.

say I have 2 eqns.

x + y = 0.5
x + y + z = 1

now It's obvious that this has infinite solNs.

So I'd choose 0.25 0.25 0.5 since it's norm(norm 2) will be minimum and they are all positive.

#

I have also tried nnls but it's not giving me the least squared solN always, I added another equation at the end saying sum should be eq to 1.

dense vortex
#

are you guys talking about this expression as in maths? because in python its not possible.

dire plume
#

Why wouldn't it be possible in Python?

dense vortex
#

how?

fiery cosmos
dire plume
#

I think they want to just do an optimization problem? Maybe I'm mis-reading?

dense vortex
#

it can as a condition ofc

fiery cosmos
dire plume
#

They're noting the problem using mathematical notation for the sake of communicating the problem.

fiery cosmos
# dense vortex

oh i mean, you're looking at it the wrong way.
when we say we want to solve
above 2 eqns we make vectors of them and put them in Ax = b form and solve them.

haughty mountain
#

you can solve this as an LP, but it's generally better if you find a linear algebra approach

dire plume
fiery cosmos
haughty mountain
#

the LP would be to minimize the norm given the constraints

fiery cosmos
#

it will? then i would like to try it, but i mean i was reading the docs, I can't find it saying, it will minimize the norm.

#

constrains can be added as they all should be b/w 0 to 1. but how to add constraint for minimizing

haughty mountain
#

I mean, the LP needs to minimize/maximize something

fiery cosmos
dense vortex
#

Okay. maybe I'm not ready for learning that. anyways, I see a warning on discord here on void linux. I downloaded fresh install but still it's there.

fiery cosmos
dire plume
#

Right, so, that's not too bad working with, but summing things to one is a weirdo thing. So, I gave up doing it on paper and I'm trying brute force on an example to see if I can ween anything from that noise.

dense vortex
#

yeah I know I'm not gonna discuss on that. I thought if someone have gone through this. I could get a quick answer here. No prob.

dire plume
#

What is this for, by the way? I don't think I've seen this kind of structure in Linear Algebra before. Maybe like, cost networks or something?

fiery cosmos
#

see this is the result i get by nnls

#

however there is solN
0.15 0.15 0.3 0.4 which will have less norm

#

now I get THAT solN by least squares directly, but for bigger examples it goes in negative too

#

So I don't get why NNLS fucks up even after they claim its prone to minimize least squares.

haughty mountain
#

sum = 1 and minimize norm seems like an odd constraint pithink

dire plume
#

Yeah, which is why I asked above what this was for, haha.

#

Some kind of probability thing, but then L2 norm is weird for that.

fiery cosmos
#

it is odd but it is required for the paper I'm trying to have practically.

dire plume
#

Okay, I have a guess, but this is only because I've only seen this condition once before in my life: does this have anything to do with quantum computing?

fiery cosmos
dire plume
#

Ah, I was closer with probability. I'll have to read in a second about why we care about L2.

haughty mountain
#

yeah, I guessed it was probabilities

haughty mountain
#

the L2 norm of probablities was the odd part to me

fiery cosmos
#

in a nutshell it defines that our vector is more uniform.

dire plume
#

Jez, this is dense. I've not seen much of this notation before.

fiery cosmos
#

yeah notations are....well very complex.

#

my sir has suggested to look upon Groebner basis since it's a non linear problem but I got no idea about it right now.

haughty mountain
#

this paper is a bit over my head, especially after having been out of uni for a while ๐Ÿ˜›

dire plume
#

Huh. I'm not exactly sure why Grobner bases would work, I thought that was for polynomial rings, but I might also have been out too long.

#

Also, it shouldn't simplify the problem, the bases are fine for optimization --- there wouldn't be any bases, I feel, for which this would be an "easier" problem. We're pretty linear right now, except for L2.

haughty mountain
#

happy to see this kind of advanced topics though, always interesting

dire plume
#

Also, I just noticed this, but: what norm are we taking here? For example:

A = np.array([
    [1, 1, 1, 0],
    [0, 0, 0, 1],
    [1, 1, 0, 0],
    [0, 0, 1, 1],
    [1, 1, 1, 1]
])

x = np.array([0.6, 0.4, 0.3, 0.7, 1]).reshape(1, 5)
y = np.array([1.9, 1.9, 2.3, 2.1])  # xA
fiery cosmos
dire plume
#

We have a few things here. We have the original matrix, which has a norm, we have x (the thing we're multiplying A by) and we have the product.

#

We prob don't care about A's norm, so it's either x or y?

fiery cosmos
#

wait. I think you're mistaken.

dire plume
#

It's entirely possible.

haughty mountain
#

norm of (x, y) I thought?

fiery cosmos
dire plume
#

Okay, lemme reformulate.

fiery cosmos
#
A = np.array([
    [1, 1, 1, 0],
    [0, 0, 0, 1],
    [1, 1, 0, 0],
    [0, 0, 1, 1],
    [1, 1, 1, 1]
])

y = np.array([0.6, 0.4, 0.3, 0.7, 1]).reshape(1, 5)
find X such that its a pmf(which is in a way taken care by last eqN which i added)
and the X has least norm if there are more than one solNs(which will happen kinda always)
dire plume
#

Okay, but where are we getting y from? Is that given to us?

dire plume
#

Ahhhh, got it. And we want to minimize the L2 norm of the vector x, while keeping sum(x) == 1.

fiery cosmos
#

exactly.

dire plume
#

Okay, I was doing the problem in reverse.

haughty mountain
#

so we have some solution space in x coming from Ax=y, and the remaining constraint is x > 0 and minimize norm?

dire plume
#

I think x >= 0, yeah.

fiery cosmos
#

yep.

#

yeah >=0.

haughty mountain
#

and that's the one annoying part, x>=0, otherwise this is trivial

dire plume
#

I now understand why LSTSQ was the go-to. Okay, cool.

fiery cosmos
haughty mountain
#

I guess you either get the correct solution using least squares, or the answer has some components = 0

#

I guess solving 2^N least square problems isn't feasible?

fiery cosmos
#

yes. I am dealing with 400 variables here.

dire plume
#
from scipy.linalg import lstsq

A = np.array([
    [1, 1, 1, 0],
    [0, 0, 0, 1],
    [1, 1, 0, 0],
    [0, 0, 1, 1],
    [1, 1, 1, 1]
])

b = np.array([0.6, 0.4, 0.3, 0.7, 1]).reshape(5, 1)

data = lstsq(A, b)
print(data[0])

[out] 
[[0.15]
 [0.15]
 [0.3 ]
 [0.4 ]]
#

Hm, I'm able to get your solution in lstsq.

fiery cosmos
dire plume
#

Okay, so this does work on smaller things, though.

fiery cosmos
#

not fails, but goes in negative, yeah.

#

this is for i think 49 vars

#

gets bit worse in 400 vars

haughty mountain
#

could Lagrangian relaxation be relevant?

fiery cosmos
#

I am not aware of this term, lemme check.

dire plume
#

from scipy.optimize import lsq_linear

def find_min_norm_nn_vector(n_vars: int = 50, n_eqs: int = 55):
    A = np.random.randint(0, 2, size=(n_eqs, n_vars))  # 50 vars.
    b = np.random.rand(1, n_eqs)[0]
    data = lsq_linear(A, b, (0, 1))
    return data

data = find_min_norm_nn_vector(n_vars=400, n_eqs=500)
print(data.x)

[out]
[7.88516441e-003 1.62862014e-034 1.06090201e-035 1.07819825e-034
 3.07195273e-002 4.25550093e-034 1.19323658e-002 6.43827861e-036
 1.36033363e-032 6.95032406e-035 3.74116037e-029 7.25841010e-035
...
...

sum(data.x)
[out]
1.0099802704176166
#

This gets pretty dang close.

#

But, remember: as we increase the dimensionality of our thing, the minimal norm'd vector here will have values closer and closer to zero on average.

#

I dunno if this matters.

fiery cosmos
#

wait what is (0,1) here?

dire plume
#

That's the bound, they're all between 0 and 1.

fiery cosmos
#

wow is it possible!!

#

lemme check

dire plume
#

I'm not 100% sure, I haven't read their paper yet, this was just an attempt.

fiery cosmos
#

also see this is for dimensions (27**2)

dire plume
#

7

fiery cosmos
#

see the result is very good, except some vals are going negative

dire plume
#

Right, that's probably a tolerance issue or something.

fiery cosmos
#

no the issue is i was using the least squares only, without constraints, lemme add them

dire plume
#

Makes sense. I reproduced your original results with lsq_linear, so that's a good sign.

#
 active_mask: array([0., 0., 0., 0.])
        cost: 3.235562306570556e-32
         fun: array([ 1.11022302e-16, -5.55111512e-17,  2.22044605e-16,  0.00000000e+00,
        0.00000000e+00])
     message: 'The unconstrained solution is optimal.'
         nit: 0
  optimality: 3.3306690738754696e-16
      status: 3
     success: True
           x: array([0.15, 0.15, 0.3 , 0.4 ])

That's pretty cool. Optimization stuff, dang.

fiery cosmos
dire plume
#

I've never even heard of Lagrandian Relaxation. Cool, learned some new stuff today, haha.

haughty mountain
#

I've used related techniques for enforcing constraints way back, I just happened to remember the term

dire plume
#

This is pretty cool. I haven't done too much optimization stuff, so I only know the very basics. :']

fiery cosmos
#

I ran it, hold on, sending some results.s

#

I'm getting nearer with more equations in hand(which is expected since rank will increase)

but a few remarks to make

#

This is the values i get using just 1(or if we add sum = 1, then 2) equations.
theoretically, the middle values should be same.

#

but at the same time the difference is not too vast. I guess what makes it harder practically is that its a PMF, making values falling into smaller and smaller values, which makes it harder for atleast computer to achieve the result because of floating number issues.

#

moreover this is the original 7 we have(where we want to reach eventually)
So i guess we have kind of very nicely reached over there.

dire plume
#

Right, I think that as it grows, it's not getting sparser, it's just spreading the values out, so all the values will be very close to 0. I'm not sure exactly what to do in that case, since it's technically constrained by the constraints of the problem.

#

I've got to sleep, but I'll check in tomorrow to see if any progress was made!

fiery cosmos
#

sure. also thanks a lot @dire plume and @haughty mountain , you both have really been a great great help!!

#

I'm way more closer now!!

cerulean elk
#
print(main_data)

decoded_data = json.load(data)

filtered_array = []

for country in main_data:
  temp_array = []
  temp_array.append(country.get(["confirmed"])
  temp_array.append(country.get(["recovered"])
  filtered_array.append(temp_array)
``` Im trying to convert this array (data)from byte to int. I used json for that. Also it is saying append is invalid syntax
#
import numpy as np
import matplotlib.pyplot as plt
import pylab as plt
import json



conn = http.client.HTTPSConnection("covid-19-data.p.rapidapi.com")

headers = {
    'x-rapidapi-host': "covid-19-data.p.rapidapi.com",
    'x-rapidapi-key': ""
    }

conn.request("GET", "/country/code?code=it", headers=headers)

res = conn.getresponse()
data = res.read()

main_data = data.decode("utf-8")
print(main_data)

decoded_data = json.load(data)

filtered_array = []

for country in main_data:
  temp_array = []
  temp_array.append(country.get(["confirmed"])
  temp_array.append(country.get(["recovered"])
  filtered_array.append(temp_array)
``` whole code
pure ocean
#

is there a channel where i can ask about something related under automata theory and computability?

fiery cosmos
pure ocean
#

how do i give a high level description of a Turing Machine to show that this is enumerable?

fiery cosmos
#

Oh this is a famous problem. It has been proven in recent years.

austere sparrow
#

yeah the set is empty

fiery cosmos
#

But i am not aware of how to do what you said tho. Sorry for that.

fiery cosmos
austere sparrow
#

yeah, 1994

#

it's really complicated

pure ocean
#

apparently i was hinted to make use of the definition of enumerability

#

which is this

fiery cosmos
#

Fermats conjecture

pure ocean
pure ocean
austere sparrow
rich pelican
ivory vigil
#

Hi people, I am looking for an algorithm to calculate a large number fast enough with high efficiency. Anyone knows something like that?

native garden
#

use bianary?

ivory vigil
#

Nope it's just a massive number that can hardly be emitted with e scientific notations.

old rover
#

what does overlapping here mean

#

oh

#

i figured it out

sick fable
#

what type of algorithm and data structure beginner should know?

lean dome
idle pier
#

hello folks, currently doing 59. Spiral Matrix II on Leetcode

def generateMatrix(self, n: int) -> List[List[int]]:
        ans = [[0]*n for i in range(n)]
        i,j = 0, 0
        dire = [0,1,0,-1,0]
        po = 0
        for a in range(1,n*n+1):
            ans[i][j] = a
            ni,nj = i+dire[po],j+dire[po+1]
            if (not 0<=ni<n) or (not 0<=nj<n) or ans[ni][nj]!=0:
                po+=1
                po%=4
                ni,nj = i+dire[po],j+dire[po+1]
            i,j = ni,nj
        return ans```
I was having trouble solving it, so I looked up the solution. I understand most of the code but am having trouble understanding this part
```py
ni,nj = i+dire[po],j+dire[po+1]
if (not 0<=ni<n) or (not 0<=nj<n) or ans[ni][nj]!=0:
  po+=1
  po%=4
  ni,nj = i+dire[po],j+dire[po+1]
i,j = ni,nj```
haughty mountain
lost lark
slim crest
lost lark
# slim crest ?

Using list comprehension is something I use everyday. Id say a beginner would be best off learning as much about how to work with lists as possible. Everything else can be looked up as needed

haughty mountain
# idle pier hello folks, currently doing `59. Spiral Matrix II` on Leetcode ```py def genera...

That code isn't exactly written to be readable, is it? I made a recursive solution using generators, it's a lot nicer to look at and make sense of imo

def shells(n):
    if n <= 0:
        return
    for j in range(n): yield (0, j)
    for i in range(1,n): yield (i, n-1)
    for j in range(1, n): yield (n-1, n-1-j)
    for i in range(1, n-1): yield (n-1-i, 0)
    yield from ((i+1, j+1) for i,j in shells(n-2))

n = 4
res = [[0]*n for _ in range(n)]
for ix, (i,j) in enumerate(shells(n)):
    res[i][j] = ix+1
for row in res:
    print(row)
#

in short, generate all the positions (i, j) in order and then put the increasing numbers into the result following that order

#

the recursion builds the shell (outside layer of the pattern) and recurses to generate the inside

fiery cosmos
#

Guys, I've been working on counting the number of units assembled in the factory I'm working. I've developed a code to count them, but I'm facing some troubles

#

Python windows version does not support pip at all

#

I'm using Python 3.10.2

#

I tried in Colab but in that winsound would not work

#

Due to such troubles, I'm stuck with my work hanging in fate

#

Plus, I gotta develop a GUI to ensure that the hourly count and overall count is displayed

#

The factory's end time is not decided in morning itself and hence I gotta develop a command to stop so that total number of units manufactured are displayed at the end of the shift hours

#

Upon clicking End button

#

So far, I've been able to develop a code to count within an hour, but at the end of the hour code gets into infinite loop

#

Pls help

#

Sorry if I've typed in wrong channel

#

But this involves some data structures, I feel

slim crest
#

can someone please help with a code challenge

slim crest
lean walrus
#

@slim crest replace 26 with len(self.alphabet)

haughty mountain
#

I also don't think you should consume a key character for stuff like whitespace and similar, at least the variants I'm used to

#

one nice way of dealing with the repeated key is to use itertools.cycle() and then use next to get the next key char as needed

pure ocean
#

how to make a high level description of a TM to show that this is enumerable?

void tulip
#

Hi

#

I am Bash, And I am too a coder like u guys,

#

I code mainly Computer Vision and AI , Machine Learning, And i have also made some advanced Detection , and sensory Projects

nova sky
#

there are multiple ways to implement binary search right?

#

like one of the way is

int search(A, key, n)
  begin = 0
  end = n-1
  while begin < end do:
    if key <= A[(begin+end)/2] then
      end = (begin+end)/2
    else begin = 1+(begin+end)/2
  return (A[begin]==key) ? begin : -1```
#

but we can also have different conditions?
like py if key <= A[(begin+end)/2] then end = (begin + end)/2 - 1 else begin = 1 + (begin+end)/2?

#

like end = mid - 1 or begin = 1 + mid

#

or end = mid and begin = mid

slim crest
acoustic raptor
#

any guide using which I can plot graphs of price fluctuations of a share using python?

slim crest
#

have you tried google?

acoustic raptor
#

yes yfinance

slim crest
#

you should really try googling things before coming here

acoustic raptor
#

๐Ÿ‘

slim crest
#

it just makes it an inconvience for someone to help you if you havent tried all possible options

#

but anyway

#

good luck on making money

acoustic raptor
#

thanks so much @slim crest i appreciate that

slim crest
#

hello can someone please help me here i am using backtracking to solve a sudoko puzzle

#

but it doesn't work

fiery cosmos
#

unexpected attribute 'qaud' to Figure

hi. today i was following the cours and a weird error while trying to run the follwing code,

i was expecting to get a bokeh graph(squares with the function quad) and a interesting resultโ€ฆ an error: can anyone help me understand what the error means and how to fix it? That would mean a lot to me. Thank you.

#

note: df is a csv file(DataFrame)

#

please? ๐Ÿ˜„

somber kiln
#

what's qaud?

#

oh quad probably does but qaud no

somber kiln
#

"it doesn't work" is not very specific

haughty mountain
slim crest
# haughty mountain why the return in the loop? and you probably want to have a check in the beginni...

Fun comes in many forms - playing puzzles, or writing programs that solve the puzzles for you. Professor Thorsten Altenkirch on a recursive Sudoku solver.

https://www.facebook.com/computerphile
https://twitter.com/computer_phile

This video was filmed and edited by Sean Riley.

Computer Science at the University of Nottingham: https://bit...

โ–ถ Play video
slim crest
#

thanks for all the help man

nova hull
#

Please forgive me if this is the wrong thread, but I'm a two month novice at Python (worked with OOP, pandas, tkinter, and just starting on APIs) and I keep hearing about how important "DS&A" is. My background is law, government, and literature, so I have almost no prerequisites, but what would you all consider the best resources for such a beginner?

Again, I'm sorry if this is the wrong thread. Thank you.

shut breach
nova hull
neat violet
#

I want to make a program that's gonna check user input against a json file.
But the problem may be, that the user may mistype a word and therefore it won't be registered:

json = {'0': 'test', '1': 'blabla'}
input = 'tes t'

Error: Input not found!
----------------------
input = 'te5t'

Error: Input not found!
----------------------
input = 'test'

Success: Input found!

Another problem is, that I just can't delete all whitespaces for this (because some inputs need those).
Is there any good library or documentation on how to solve this problem?
Or has anyone an idea and would share it with me?
I'd be happy about any help ^^

fiery cosmos
fiery cosmos
#

It's horrid @fiery cosmos -- Why not produce a generator and keep the source code compact?

#

20.8k lines for an example is ... a bit much.

jolly mortar
#

Its a joke repository

fiery cosmos
#

Hah, my browser laughed for sure.

fiery cosmos
#

^ that's what I mean. Why'd you post 20k+ lines?

#

I'll remember the hardlink when I want to dos someone though ๐Ÿ™‚

#

Remember...

#

++++ Watch in FHD ++++
I DO NOT OWN the Video Footages, Images & Music in this Video.

โง แด ษชแด…แด‡แด: Hakuna Matata Scene (The Lion King, 1994 ) #LionKing

For everyone who
WATCHED/LIKED/DISLIKED/SUBSCRIBED/SHARED...
Thank you so much! ๐Ÿ˜Š


"Hakuna Matata; what a wonderful phrase.

Hakuna Matata; ...

โ–ถ Play video
neat violet
#

I still don't know what 51+50 is

soft cape
#

Hey I need help with my minimax algorithm in my tictactoe game

#

Most of the time it works but sometimes it just makes some mistakes

wary token
#

Hey, i am looping a graph data structure in for loop i made it using a dictionary and i want to access its contents in a range for example dictionary is from A to U and i only want to access its values from A to N i am really confused how i should approach it, is there any simple way to do it?

#
graph = {
    'A' : ['B','C','D'],
    'B' : ['E','F'],'C' : ['G','H'],'D' : ['I','J'],
    'E' : ['K','L'],'F' : ['M'],'G' : ['N'],'H' : ['O'],'I' : ['P','Q'],'J' : ['R'],
    'K' : ['S'],'L' : ['T'],'M' : [],'N' : [],'O' : [],'P' : ['U'],'R' : [],
    'S' : [],'T' : [],'U' : [],'Q' : []
}
q = []
visited = []
q.append('A')
visited.append('A')
flag = 1
    while  q and flag:
        x = q.pop(0)
        print(x, end = "->")
        
        for i in T[A]:
            if i not in visited and i != T[N]:
                visited.append(i)
                q.append(i)
        
            if i == T[N]:
                flag = 0
                break```
#

i tried doing like this but its not working apparently

wispy sedge
haughty mountain
wary token
charred kiln
# neat violet I want to make a program that's gonna check user input against a json file. But ...

Hey man, I've worked on a similar project in the past that was a simples dictionary app. repo >> https://github.com/RaphaelLMendes/English_Dictionary

I had a similar issue, and I resolved it using a python lib called difflib that has a function that gets close matches in the dict keys. Check it out, I hope it helps!

GitHub

A simple python project that gives you the meaning of a word typed in the prompt - GitHub - RaphaelLMendes/English_Dictionary: A simple python project that gives you the meaning of a word typed in ...

neat violet
merry scroll
#

Hi!
How can I find the number of binary trees having n nodes and minimum height of h?
(1<= h <= n < 35)
Thanks in advance!

keen hearth
merry scroll
keen hearth
#

๐Ÿค”

#

The way I'm thinking about it is that at least one of the two sub-trees of the root node needs to have a height of at least h - 1.

merry scroll
#

yes...

keen hearth
#

So there are three cases:

#
  • left tall, right short
#
  • left short, right tall
#
  • both tall
#

If the function takes n and h as arguments, then we can say "any height is ok" by setting h to 0.

#

But we can't specifically count the number of short trees.

#

Does that make sense so far? @merry scroll

keen hearth
#

Just do a recursive call where the minimum height is zero.

merry scroll
#

okay

keen hearth
#

So we need to add up, for each k in 0, ..., n-1:

  • count(k, h-1) * count(n-1-k, 0) (i.e. left tall, right any height)
  • count(k, 0) * count(n-1-k, h-1) (i.e. left any height, right tall)
#

But then we've double counted the cases where they are both tall, so we need to subtract out:
count(k, h-1) * count(n-1-k, h-1)

#

In other words, for every possible way to distribute the remaining nodes between the two sub-trees, we need to count the number of ways each sub-tree could be constructed, considering the cases where:

  • the left sub-tree must be at least h-1 in height,
  • the right sub-tree must be at least h-1 in height,
  • both sub-trees must be at least h-1 in height.
merry scroll
keen hearth
#

Well say you have to build a tree of size 5.

#

One of the nodes will be the root node, leaving four other nodes.

#

You could put all four in the right sub-tree.

#

You could put one in the left sub-tree, and three in the right sub-tree.

#

you could put two on the left, and two on the right.

#

Etc.

merry scroll
#

Oh

keen hearth
#

Would you like to see a solution and have me explain it, or would you like to write a solution yourself?

#

I'm not sure I'm explaining myself very clearly.

#

But the code may make it clear.

merry scroll
#

What is the Time Complexity of this approach?

merry scroll
keen hearth
#

With caching, I believe it will be O(n * n * h)

#
from functools import cache

@cache
def count(n, h):
    if h + 1 > n:
        return 0
    if n == 0:
        return 1
    total = 0
    for a in range(n):
        b = n - 1 - a
        total += count(a, h-1) * count(b, -1)
        total += count(a, -1) * count(b, h-1)
        total -= count(a, h-1) * count(b, h-1)
    return total
#

If you don't know what @cache does, it just saves the results from calls to the function, so if the function is called again with the same arguments the saved value can be returned, rather than re-computing it.

merry scroll
#

๐Ÿค” why can't we construct a binary tree with h+1 > n?

keen hearth
#

Well we can't construct one of that height with only so many nodes.

#

The tallest binary tree is one where all the nodes are in a line.

#

That would have height n - 1.

#

Something a little bit weird: the tree with zero nodes is defined as having height -1.

#

Just due to the way tree height is defined.

merry scroll
#
    0  |
   /   |
  0    | height: 3?
 /     |
0      |
keen hearth
#

That's meant to have three nodes right?

#

Conventionally, that tree would have height 2.

#

The height is defined as the number of edges on the longest path from the root to a leaf.

merry scroll
#

Oh
Thank you so much @keen hearth
You are so awesome

keen hearth
#

No worries!

#

Do you feel like you understand the code?

merry scroll
#

Yes.
I made one like this
But without the cache it doesn't work

keen hearth
#

Yes, the cache is important!

#

Without it, it's certainly exponential time.

#

I mean, just look at the answer for count(100, 10) lemon_sweat ```
896519947002960918869071082756320105290787033256522147392

haughty mountain
#

It's a weirdly constrained version of Catalan numbers. count(n, 0) should be the catalan numbers

keen hearth
open moth
#

Please DM

jagged whale
#

Hi guys! You may be interested in learning algorithms Steve Wozniak used in his first operating system for Apple-1 - Iโ€™ve rewritten it in Python to give an idea what simple operating system do and what are key algorithms. You could get the code from GitHub to play with it - more details here https://twitter.com/smartykite/status/1484057995466186752?s=21

Here is โ€˜helicopter viewโ€™ of 256 bytes @stevewoz operating system for #apple1 rewritten in #Python. Will discuss it at @fosdem and on #SmartyKit webinar. It has a kind of #shell as UI and simple Keyboard and Display โ€˜driversโ€™ as interface to hardware https://t.co/OsojGLzO83

fiery cosmos
#

does anyone even come in here

fiery cosmos
#

Hey, given an R^N space, are there any algorithms in place which would give us some M randomly generated subspaces(by giving their basis vectors) from it?
Basis vectors are important for my case.
It's good to note that we can basically generate infinite subspaces ofc.

#

that's incredibly beyond me.

#

i have median, mean, arma with coefficients set to 0.2, savinsky-goloy with coefficients for 2nd order. I have a 6th order HAAR discreet wavelet transform function.

#

I need, or want, to know how to optimize the combination to best reduce noise for single-channel 16bit audio normalized to between 0 and 1 with a real variance ptp no more than 1.0, which has been represented as 64 bit floating point numbers in a list of 48000 samples per second/48000khz.

I want to focus primarily on white noise reduction.

fiery cosmos
fiery cosmos
#

what is the case your working in? just because im curious. i am working on a linear audio decomposition project for noise reduction

#

I forget what a subspace is lemon_sweat

#

kind of wish i could just make an array of 48000 * 48000 /2 and decompose alllll of the energy in the audio frame into a non-euclydian geometric topology, then apply some kind of fancy algo to it, then recompose it back into audio

fiery cosmos
#

So a subspace of R^10 could be an R^9 or R^8 or R^1 (or trivially R^10 itself I guess)?

fiery cosmos
#

theoretically these lines are subspaces. we can imagine higher degrees ofc. like planes.

fiery cosmos
#

assuming we are not only considering ortho normal basis

#

So given the 10 basis vectors of an R^N you could select any 2 of them randomly for an R^2 subspace maybe?

fiery cosmos
fiery cosmos
#

Though, to get any random subspace within R^10 could you generate a random from 1-10 and generate that many random vectors and it's very likely they will be a basis of a subspace discre3Hmm

#

I might be way off btw lemon_sweat I took linear algebra ages ago, this is just interesting

fiery cosmos
fiery cosmos
# fiery cosmos Though, to get any random subspace within R^10 could you generate a random from ...

i mean, if you think about it.
If i narrow it down to say d dimensions.

Putting things in place.
we will have vectors of size n (however for all of them the n-d will be 0)

So we can first choose d random dimensions for each vector (say for n=4, and d=2, and m=2)
for mi = 1,
we chose [0,2]
dimension for first vector, and creating a basis we have [1,0,5,0]
creating another basis we have [3,0,2,0]

So we found a subspace {[1,0,5,0], [3,0,2,0]}

Same way for mi=2 perhaps.

Now this can be done.

#

but I mean I am searching for, is there any existing way to do this?
which will choose best subspaces. And yes, I do not YET know what do we mean by Best here very precisely.

rare dawn
#

can anyone help me ?

#

I have a test on data structures and algorithms in 4 days

#

i need help

slim crest
fiery cosmos
#

i need some help

#

with what should be a BASIC PROBLEM

slim crest
#

with

#

okay

fiery cosmos
#

i have two 1d lists of X elements of floating values

#

one comes after the other, in a chronological sense

slim crest
fiery cosmos
#

I need to take the end of one list and the beginning of the second and efficiently smooth their values together to eliminate a discongruity

fiery cosmos
#

no?

slim crest
#

l = [0.1,0.2,0.3]

#

!e

fiery cosmos
#

by "end" and "beignning i dont mean last value- i mean something more like last, first 200 values, where the trend is smoothed

slim crest
#

use list indices

#

arr[x:len(arr)]

fiery cosmos
#

i know how to select it

#

i need to smooth their values togethr

slim crest
fiery cosmos
#

i think you might be better suited to #python-discussion because you don't seem to care about what i'm asking but rather how you can explain simple things like syntax

rare dawn
fiery cosmos
#

i need algorithm help, not syntax help brah

rare dawn
slim crest
rare dawn
fiery cosmos
#

@rare dawn does this allow numpy?

rare dawn
#

no imports

#

must code the answer

#

not import it

fiery cosmos
#

this is either an essay or homework

#

why are you trying to get a programming job if you cant program

#

the question is actually asking you to sort a list of arbitrary size, then search it for zero, then find the value right above zero, then count upwards to see if each value is the same as the index, then return the index of the first value where it's not the same.
For negative integers, the assignment is slightly more complex.

rare dawn
#

Thank you

#

my English is bad

#

so i dont understand how they ask it

fiery cosmos
#

For negative values, you're being asked to disregard them and simply return the smallest positive number, which means you need to discard all elements of the list which are negative, sort those which are positive, assign those which are positive to indices, and then search through it. good luck

#

are you trying to be a programmer?

rare dawn
#

I come from a heavy cybersecurity background

#

and trying to move into software engineer

fiery cosmos
#

@haughty mountain i see u typing

rare dawn
#

but my data structures and algo is not so good

#

so im trying my best

fiery cosmos
#

@rare dawn this is a test to evaluate your programming skills. This is not actually a data structure question, it's a basic interview question.

slim crest
rare dawn
#

yeah i know

#

i just am bad at english

haughty mountain
rare dawn
#

i really appreciate your help

slim crest
fiery cosmos
#

@haughty mountain given a list and a desired end value, how would you convolve it to gradually bring it to that point near the end

haughty mountain
#

this is about the smoothing question?

slim crest
#

try this

haughty mountain
#

no need to sort things, put everything in a set or equivalent and just check whether 1, 2, ... exist

#

you can use a length N array of booleans as a set in this case to have true O(1) operations

rare dawn
#

someone call me

#

explain

#

for love of god

haughty mountain
#

what I wrote is the whole approach to the task

rare dawn
#

Thank you

haughty mountain
#

it's like...3 lines to implement

haughty mountain
slim crest
#

yea I tried it

#

it works

haughty mountain
#

and it's a stupid short implementation

slim crest
rare dawn
#

im still lost

slim crest
rare dawn
#

how do i put everything in a set ?

#

sorry my english

haughty mountain
#

!d set

halcyon plankBOT
#
set

class set([iterable])``````py

class frozenset([iterable])```
Return a new set or frozenset object whose elements are taken from *iterable*. The elements of a set must be [hashable](https://docs.python.org/3/glossary.html#term-hashable). To represent sets of sets, the inner sets must be [`frozenset`](https://docs.python.org/3/library/stdtypes.html#frozenset "frozenset") objects. If *iterable* is not specified, a new empty set is returned.

Sets can be created by several means:

โ€ข Use a comma-separated list of elements within braces: `{'jack', 'sjoerd'}`

โ€ข Use a set comprehension: `{c for c in 'abracadabra' if c not in 'abc'}`

โ€ข Use the type constructor: `set()`, `set('foobar')`, `set(['a', 'b', 'foo'])`...
slim crest
rare dawn
#

Thank you i know this as other words so your help is help me alot

#

im a Pentester not a programmer

slim crest
agile sundial
slim crest
#

!e sha256

#

!e hashlib.sha256

agile sundial
#

do testing in #bot-commands please

#

and, you need to import hashlib first

haughty mountain
rare dawn
#

guys im still stuck

slim crest
rare dawn
#

please send me code that work

#

so i can look then understand backways

#

i want to cry

haughty mountain
fiery cosmos
#

idk how to "convolve with a guassian

rare dawn
#

I have a test in 4 days

#

and im so lost

#

i feel like child

fiery cosmos
#

i know how to convolve, but not how to convolve with a guassian

fiery cosmos
#

i have ARMA and savitsky-goloy accelerated 1d window of 5 second order functions i built

rare dawn
#

please kind soul some 1 help

agile sundial
#

ah, I see that edit

rare dawn
#

I have a test ๐Ÿ˜ญ

#

Please help

#

im cry

#

dont want to fail

#

i feel so lost

#

also due to stress i feel im not understand simple things

fiery cosmos
#

do you reaally think we're this guilalble

#

not going to write your code for you

rare dawn
#

not what im ask

#

im ask to explain

#

i want understand

fiery cosmos
#

can someone write my code for me? i need someone to help me make my convolution function work to "convolute with a gaussian" whatever that is

rare dawn
#

not code

haughty mountain
fiery cosmos
#
@numba.jit(numba.float64[:](numba.float64[:]), nopython=True, parallel=True, nogil=True,cache=True)
def savgol(data: list[numpy.float64]):

    coeff = numpy.asarray([-0.08571429,  0.34285714,  0.48571430,  0.34285714, -0.08571429])
    #pad_length = h * (width - 1) // 2# for width of 5, this defaults to 2...
    data_pad = numpy.zeros(data.size + 4)
    data_pad[2:data.size + 2] = data[0:data.size]#leaving two on each side
    firstval =  2* data[0] - data[2:0:-1]
    lastvals = 2* data[-1] - data[-1:-3:-1]
    data_pad[0] = firstval[0]
    data_pad[1] = firstval[1]
    data_pad[-1] = lastvals[1] 
    data_pad[-2] = lastvals[0]
    new_data = numpy.zeros(data.size)
    x = numpy.zeros(((data.size-2),6)) #create array for outputs
    for i in numba.prange(2, data.size):
        x[ i - 2,0] =  data_pad[i - 2]
        x[ i - 2,1] =  data_pad[i - 1]
        x[ i - 2,2] =  data_pad[i]
        x[i - 2,3] =  data_pad[i + 1]
        x[i - 2,4] =  data_pad[i + 2]
        x[i - 2,5]=  data_pad[i + 3]

   
    #
    #multiply vec2 by vec1[0] = 2    4   6
    #multiply vec2 by vec1[1] = -    3   6   9
    #multiply vec2 by vec1[2] = -    -   4   8   12
    #-----------------------------------------------
    #add the above three      = 2    7   16  17  12 

    z = numpy.zeros((data.size, 30))

    for i in numba.prange(data.size):
        for n in numba.prange(30):
            for k in numba.prange(5):
                for gk in numba.prange(6):
                    z[i,n] = coeff[gk] * x[i, k]
    

        #create the array of each set of averaging values
    for i in numba.prange(data.size):
        new_data[i] = numpy.sum(z[i,:])
    return new_data
#

given this function

#

how would you make it into a guassian?

rare dawn
#

why you mean ?

#

i just want to understand

grizzled schooner
rare dawn
#

no

#

i have 4 days

#

to take it

#

this is study for it

fiery cosmos
#

well, in 5 days, come ask me for help and i'll write your code for you

rare dawn
#

i just want to understand

fiery cosmos
#

now if i had a girlfriend i might consider writing it sooner, but i dont, so im going to drink coffee and watch anime instead

rare dawn
#

i want to understand this things

grizzled schooner
rare dawn
#

i want help

#

please can a teacher call me

fiery cosmos
#

its not against the rules to write code for people. i said in 5 days, which is after their test ends @grizzled schooner

rare dawn
#

to understand not just give code

agile sundial
#

arguably it is against the rules now, since they told you not to

rare dawn
#

people

fiery cosmos
#

I don't think a helper decides the rules. Moderators might

#

anyway they're in the wrong channel

rare dawn
#

are you going to help or talk about rules while an innocent soul is here crying for help

#

?

#

you so rude

#

im ask for help

fiery cosmos
#

innocence must be established before the court of courtney freakin miller

rare dawn
#

so no help ?

agile sundial
#

what do you need explained

rare dawn
#

i dont understand the question

#

so how the hell must i make a fix

haughty mountain
#

what in particular don't you understand?

rare dawn
#

so A is unknown array ?

#

N is number of integers ?

#

must return a number bigger than 0 ? or must return index at bigger than 0 ?