#algos-and-data-structs

1 messages · Page 47 of 1

lilac cradle
#

im sure i could do some shit like make it iterate through all possibilites but idk

languid thistle
#

you can for real just chill

#

unless you wanna be one of those people who works late every day. It's fine to walk in on day 1 and start learning. You'll be slightly behind but nothing crazy.

#

I say this as somebody who switched my degree to bioinformatics as a junior at an R1 research university and had no problem going through data structures, algorithms, comp bio, linear algebra, etc.

#

flipside of my advice: all the best coders I know started as actual children

#

why they are good at it has nothing to do with academic work

#

and everything to do with reading about compilers and interpreters

#

like not academic reading, just reading documentation. If you go look at postgres or python's docs, you'll find chill-style explanations of how stuff works. Python for example is actually an extremely flexible runtime, like lisp

#

but the way it's designed is not actually taught in schools cause you gotta learn what a linked list is, which isn't actually going to help u say interface with a bank's api or assemble a hodgepodge of code into a singular behemoth that operates via some coordinating principle u probably learnt from studying other behemoths

#

should say, it's taught, but it's glanced over

stoic belfry
#

Does anyone knows where i can find oreilly books for free (learning algorithms book specifically)

keen hearth
#

But then I think the subscription is quite expensive after that.

#

If you're currently studying at a university, they may have it in their physical/digital library.

honest comet
#

why does nobody help me

#

I am desperate

true dew
#

sup daddys

#

whats going onm

thorn torrent
#

Has anyone programmed A gex bot using python

mortal sparrow
#

"these days going low level doesnt actually what gives you ideas, it is to express your ideas so cleanly that you can think about it and then optimizer can understand what youre up to"
hey guys i found this on my keep notes... to everyone here.. when or what was the catalyst that helped you able to express your ideas in code... like what helped you or what made it so that coding was like a second nature to you. thanks!

azure flame
#

yo, I just added another class to my schedule, and he gave me the first homework assignment. I've figured out a few of the problems, but I'm not sure what he means by "provide a tree of recursive calls for a(2, 1)". Problem 4 btw

#

I would assume it's something like these, but I wouldn't know how to structure it the same way.

spring stratus
#

What is the idea making a simple photo editor?

  • Load the photo
  • Apply Blur
  • Apply Brightness
  • Reduce Blur
  • Reduce Brightness

How can I store these data? So i can go back and forth?
In my current implementation i load the image and apply the blur then save the image in the loaded variable. So next time if i reduce the blur it just apply the new blur in the blurred image that leaded to blur the image but a small amount. It does not reverse.
So I am thinking like
Using a container and adding the new operation to it and removing the duplicate operation like ``adding new blur operation and removing the duplicate blur operation". Applying 1st added operation 1st and 2nd add operation 2nd on the original image instead of applying the modified image.
Will this work? What technique the image editor use? What container will appropriate for this?

olive badge
#

hey smart people, im studying bfs and i found that sometimes you can use something like

graph = {}

deque = [(start, [start])]

while deque:
    curr, path = deque.pop(0)
    if curr == end:
        print(path);break
    if curr in graph:
        for neighbor in graph[curr]:
            deque.append((neighbor, path + [neighbor]))

that´s just an example btw

but sometimes I've seen codes where instead of that they use

from collections import deque
graph = {}

deque = deque([(start, [start])])

while deque:
    curr, path = deque.popleft()
    if curr == end:
        print(path);break
    if curr in graph:
        for neighbor in graph[curr]:
            deque.append((neighbor, path + [neighbor]))

i dont understand why would you import deque when you can avoid it without any problem, if you know more about the topic or you can give me more tips about bfs it would be great

narrow mica
heady charm
#

c# vs python

#

?

wise glen
#

How much knowledge of python should I have before moving on to algos and data structures?

lean junco
#
int memoise(vector<int> &W, vector<int> &V, int n, int cap, int index, int v, int w, vector<vector<int>>& memo){
    if (w>cap) 
        return 0;
    if(index==n) return v;

    if (memo[index][w] != -1) return memo[index][w];

    int not_inclu = memoise(W, V, n, cap, index+1, v, w, memo);
    int inclu = memoise(W, V, n, cap, index+1, v+V[index], w+W[index], memo);
    
    int here = max(inclu, not_inclu);
    return memo[index][w] = here;
}```
knap sack, where is the problem???
n= 7 
W = 1 5 6 9 7 9 7 
V = 1 7 1 5 1 7 7 
cap = 37
case doesnt pass
cedar totem
# wise glen How much knowledge of python should I have before moving on to algos and data st...

I'd say you should be familiar with the basics such as functions, flow-control (if, while, for) and classes,
python's types including str, list, dict, set, int and some of their methods,
some common builtin functions such as max, min, sum

since these are pretty essential in DSA and it's good to be able to focus on the new DSA stuff when learning than to trip up on the python part.

ornate rover
#

Im screwed @cedar totem

#

with my DSA course

wise glen
cedar totem
haughty mountain
haughty mountain
#

it will cause severe performance problems

#

popping from the beginning of a list is O(n), popping from the beginning of a deque is O(1)

fiery cosmos
#

hey guys, need some help rq

#

so heres my code:

#

``# Python program for binary search
import random

Create randomNumbers array

def randomNumbersArray():
randomnumbers = []
i = 0
while i < 24:
randomnumbers.append(random.randint(1, 100))
i += 1

print(randomnumbers)
print(len(randomnumbers))
print()
return randomnumbers

def sorting(numbers):
list.sort(numbers)
print(numbers)

return numbers

def numToGuess(numbers):
pos = random.randint(1, 24)
target = numbers[pos]

print("What number am I thinking of?")

return target

def binSearch(numbers, number):
array = numbers
toguess = number
minimum = 0
maximum = len(array-1)
guess = maximum+minimum/2

numToGuess(sorting(randomNumbersArray()))
binSearch(target, array)
``

#

problem is, apparently that last line throws an unresolved reference error

#

what did i do wrong?

fiery cosmos
# fiery cosmos ``# Python program for binary search import random # Create randomNumbers array ...
import random
# Create randomNumbers array


def randomNumbersArray():
    randomnumbers = []
    i = 0
    while i < 24:
        randomnumbers.append(random.randint(1, 100))
        i += 1

    print(randomnumbers)
    print(len(randomnumbers))
    print()
    return randomnumbers


def sorting(numbers):
    list.sort(numbers)
    print(numbers)

    return numbers


def numToGuess(numbers):
    pos = random.randint(1, 24)
    target = numbers[pos]

    print("What number am I thinking of?")

    return target


def binSearch(numbers, number):
    array = numbers
    toguess = number
    minimum = 0
    maximum = len(array-1)
    guess = maximum+minimum/2
        

numToGuess(sorting(randomNumbersArray()))
binSearch(target, array)
olive badge
#

ask it in a help channel

hexed ravine
#

Ok thanks!

haughty mountain
toxic hare
#
buckets = []
outliers = [ [] ,  [],  [] ]  # <- data and stuff
minis = [mini,davg,uavg]
maxis = [davg,uavg,maxi]
for y in range(0,3):
    if outliers[y]!=[]:
        m = minis[y]
        buckets.append([0 for x in range(0,maxis[y]+1-minis[y])])
        for x in range(0,len(outliers[y])):                    # <-  this loop      
            buckets[y][outliers[y][x]-m]+=1
    else:
        buckets.append([])

is there a way to make the inner for loop faster?

stable pecan
#

do you want to use numpy

toxic hare
stable pecan
#

billions probably, if you have memory

#
buckets = []
outliers = [[], [], []]  # <- data and stuff
minis = [mini, davg, uavg]
maxis = [davg, uavg, maxi]
for outlier, mini, maxi in zip(outliers, minis, maxis):
    if outlier:
        bucket = [0 for _ in range(maxi + 1 - mini)]
        for out in outlier:
            bucket[out - mini] += 1
    else:
        bucket = []
    buckets.append(bucket)

as numpy:

import numpy as np
buckets = []
outliers = [[], [], []]  # <- data and stuff
minis = np.array([mini, davg, uavg])
maxis = np.array([davg, uavg, maxi])
widths = maxis + 1 - minis
for outlier, mini, width in zip(outliers, minis, widths):
    if outlier:
        bucket = np.zeros(width)
        bucket[outlier -  minis] += 1
    else:
        bucket = np.zeros()
    buckets.append(bucket)
stable pecan
#

though depending on what you're doing, numpy has histogram functions already

toxic hare
stable pecan
#

let's you iterate over multiple things at the same time!

#

!e

for a in zip("cat", "dog"):
    print(a)

for a, b in zip("cat", "dog"):
    print(a, b)
halcyon plankBOT
#

@stable pecan :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | ('c', 'd')
002 | ('a', 'o')
003 | ('t', 'g')
004 | c d
005 | a o
006 | t g
stable pecan
toxic hare
#

another part of my code which is really slow is

list1 = [ 1,2,3 ]
llen = len(list1)
outliers= [ [],[],[] ]
for y in range(1,llen):
  a = list1[llen-y]
  if a < davg:
    outliers[0].extend([a])
  elif a >= uavg:
    outliers[2].extend([a])
  else:
    outliers[1].extend([a])
  list1.pop()
list1=[]
print(outliers)
#

i feel like adding and popping things repeatedly are slow, but i profiled it and it said it wasnt

stable pecan
#

you're creating lists just to have python delete them immediately with extend([a])

stable pecan
#

no, it doesn't create an intermediate list

#

the [a] in extend([a]) creates a list, append(a) does not

#

so you're creating a list, that then gets garbage collected (deleted), and extend also has to iterate over this list which is slower than just appending a single element

toxic hare
stable pecan
#

this is another thing that can be vectorized by numpy though

#
list1 = np.array([1, 2, 3])
below = list1 < davg
upper = list1 >= uavg 
middle = ~below & ~upper
#

!e

import numpy as np

list1 = np.array([1, 2, 3])
below = list1 < 2
upper = list1 >= 3
middle = ~below & ~upper
print(below, upper, middle)
halcyon plankBOT
#

@stable pecan :white_check_mark: Your 3.12 eval job has completed with return code 0.

[ True False False] [False False  True] [False  True False]
toxic hare
stable pecan
#

yes, numpy does things in a compiled language

#

it's doing the if states in c++ instead of python

#

which can be 100x or 1000x faster depending

toxic hare
#

ohhh, so its faster but in the algorithm is the same

stable pecan
#

yep

#

for instance

list1 = np.array([1, 2, 3])
below = list1 < 2

to compute below, numpy iterates over list1 comparing each element with 2 just like your loop

#

!e you can get the indices of the truth values btw:

import numpy as np
list1 = np.array([1, 2, 3])
below = list1 < 2
print(below)
print(np.nonzero(below))
halcyon plankBOT
#

@stable pecan :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | [ True False False]
002 | (array([0]),)
stable pecan
#

!e or probably better:

import numpy as np
list1 = np.array([1, 2, 3])
below = list1 < 2
print(below)
print(np.flatnonzero(below))
halcyon plankBOT
#

@stable pecan :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | [ True False False]
002 | [0]
toxic hare
#

pretty cool
ill try and see if i can think of a way to algorithmically make it faster instead of relying on thousands of if statements lol

#

i have a different algorithm that does basically the same thing but with a much larger auxillary array

the auxillary verison takes 0.8 seconds to sort a list of 1000000
and the version without the array takes 2 seconds to sort the same sized list lol

stable pecan
#
for a in reversed(list1):
    outliers[2 - a < davg - a < uavg].append(a)
toxic hare
#

ngl, ur probably better and cleaner at the syntax thats for sure lmao

stable pecan
#

or can flip the conditions i think

#
for a in reversed(list1):
    outliers[a >= davg + a >= uavg].append(a)
toxic hare
#

just from what i was testing

stable pecan
#

yeah, for the branchless version, python has to do some coercions and call some dunders --- i think branchless would be faster in c though

toxic hare
#
gc.disable()
for y in range(0,len(list1)):
  a = list1[y]
  if a < davg:
    outliers[0].append(a)
  elif a >= uavg:
    outliers[2].append(a)
  else:
    outliers[1].append(a)
list1=[]
print(list1)
gc.enable()

out of all the versions this one seemed to run the fastest

#

weird lol

stable pecan
#

you don't need to disable gc for that

toxic hare
stable pecan
#

i mean, you can, but there's nothing to gc, it just prevents python from checkiing

toxic hare
stable pecan
#

it won't be each time, it will just check after some number of operations

#

i don't really know much about the internals, just at some point python will check if anything needs to be collected

toxic hare
#

yeah, bulk garbage collection seems to be faster than lots of little collections and redundant checks

stable pecan
#

range(0, n) is the same as range(n) though

#

you can iterate directly over the list1:

for a in list1:
  if a < davg:
    outliers[0].append(a)
  elif a >= uavg:
    outliers[2].append(a)
  else:
    outliers[1].append(a)
toxic hare
toxic hare
fiery cosmos
#

fixed most of my issues, rest of my issues are logic issues which i am dealing with one by one now, will update in 30 minutes hopefully

fiery cosmos
#

anyone down to help me rq?

#
import random
# Create randomNumbers array


def randomNumbersArray():
    randomnumbers = []
    i = 0
    while i < 24:
        randomnumbers.append(random.randint(1, 100))
        i += 1

    print(randomnumbers)
    print(len(randomnumbers))
    print()

    return randomnumbers


def sorting(randNums):
    list.sort(randNums)
    print(randNums)

    return randNums


def numToGuess(numbers):
    pos = random.randint(0, (len(numbers)-1))
    print(pos)
    target = numbers[pos]

    print("What number am I thinking of?")
    print(target)

    return target


def binSearch(target, numbers):
    minimum = 0
    maximum = len(numbers)-1
    guess = round((maximum + minimum)/2,)
    valGuess = numbers[guess]

    while guess != target:
        print(f"My guess is {valGuess} at position {guess}\n")

        if guess < target:
            print("Target is larger than your guess\n")
            minimum = guess + 1
            guess = round((maximum + minimum)/2, )
            print(f"My new guess is {guess}\n")

        elif guess > target:
            print("Target is less than your guess\n")
            maximum = guess - 1
            guess = round((maximum + minimum)/2, )
            print(f"My new guess is {guess}\n")

        else:
            print(guess)
            print(f"My final guess is {guess}")
            print(f"That's right my number is {target}!")


def main():
    randNums = randomNumbersArray()
    sortedNums = sorting(randNums)
    target = numToGuess(sortedNums)
    binSearch(target, sortedNums)


main()
#

my binary search never fully completes

fiery cosmos
outer rain
#

also don't use round(smth/smth), use // operator if you want to round down (and here you want to round down)

#

round does not round how you want, most likely

fallow ginkgoBOT
#

This is not a Modmail thread.

outer rain
#

oops

#

!eval

for x in range(1, 11):
  for y in range(1, 11):
    print(f"{round((x + y) / 2):>4}", end="")
  print()
halcyon plankBOT
#

@outer rain :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 |    1   2   2   2   3   4   4   4   5   6
002 |    2   2   2   3   4   4   4   5   6   6
003 |    2   2   3   4   4   4   5   6   6   6
004 |    2   3   4   4   4   5   6   6   6   7
005 |    3   4   4   4   5   6   6   6   7   8
006 |    4   4   4   5   6   6   6   7   8   8
007 |    4   4   5   6   6   6   7   8   8   8
008 |    4   5   6   6   6   7   8   8   8   9
009 |    5   6   6   6   7   8   8   8   9  10
010 |    6   6   6   7   8   8   8   9  10  10
fiery cosmos
#

you want to see?

outer rain
#

uhm not really, if it work for you then it's great

fiery cosmos
#

Is there any webpage that visualise how are recursive calls made and what is returned by given code and data?

haughty mountain
#

have you tried just adding some prints?

#

!e untested code, go

def fib(n, depth=0):
  print('  '*depth + f'call fib({n})')
  if n <= 1:
    res = n
  else:
    res = fib(n-1, depth+1) + fib(n-2, depth+1)
  print('  '*depth + f'return {res}')

fib(4)
halcyon plankBOT
#

@haughty mountain :x: Your 3.12 eval job has completed with return code 1.

001 | call fib(4)
002 |   call fib(3)
003 |     call fib(2)
004 |       call fib(1)
005 |       return 1
006 |       call fib(0)
007 |       return 0
008 | Traceback (most recent call last):
009 |   File "/home/main.py", line 9, in <module>
010 |     fib(4)
011 |   File "/home/main.py", line 6, in fib
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/BRJSL5ZDU2V5CFAFMT4YHF5QQQ

haughty mountain
#

err

#

oh, return

#

!e

def fib(n, depth=0):
  print('  '*depth + f'call fib({n})')
  if n <= 1:
    res = n
  else:
    res = fib(n-1, depth+1) + fib(n-2, depth+1)
  print('  '*depth + f'return {res}')
  return res

fib(4)
halcyon plankBOT
#

@haughty mountain :white_check_mark: Your 3.12 eval job has completed with return code 0.

001 | call fib(4)
002 |   call fib(3)
003 |     call fib(2)
004 |       call fib(1)
005 |       return 1
006 |       call fib(0)
007 |       return 0
008 |     return 1
009 |     call fib(1)
010 |     return 1
011 |   return 2
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/4MSR6REIDRNAPRIUOHWX5UR6GE

haughty mountain
#

you know @halcyon plank, getting a few more lines would be nice

fiery cosmos
haughty mountain
#

I mean, a lot of the time I don't need to visualize

#

often reasoning about the recursion can be done as "assuming the recursive calls I make returns the correct thing, do I do the right thing?"

stoic belfry
#

Hi Guys, I am new to DSA. Although i am an intermediate level python developer i am finding it hard to understand backtracking and dynamic programming. Could anyone suggest some good material to learn those?

toxic hare
#

sorting algorithm go brrrrr

toxic hare
#

this is the sorting algorithm code if anyone would like to run it

lilac cradle
#

is yielding or returning a list/set faster? I’ve been assuming the former is faster

#

Like say i want to output a million numbers from some arbitrary function that i generate through some iterative method

would it be faster to yield each number or add each one to a list/set/dict, and then return that list/set/dict

midnight dew
#

Does anyone know of a library that supports sparse matrices of n > 2 dimensions on GPU in python? I'm currently using cupy for GPU matrix operations, but their implementation is just a copy of SciPy so their sparse matrices only support 2D matrices.

lean walrus
lilac cradle
#

kk

haughty mountain
haughty mountain
#

creating a list, set, ... whatever directly

dusk hinge
#

Wouldn’t the be even worse performance?

haughty mountain
#

I guess the question was really generators

#

not iterators

dusk hinge
#

Im just confused by the part where you said there’s a tiny performance loss using iterators rather than making a list

#

Cause wouldn’t making a list be the performance loss part

haughty mountain
#

generators have some overhead from being coroutines

dusk hinge
#

Ah, so in cases where you need to iterate through all of it, making a list would actually be a little bit better performance?

haughty mountain
#

right

dusk hinge
#

Cool ty for clarifying 🙂

fiery cosmos
#

is it worth paying for LeetCode premium?

#

Also, is there anybody who would like to discuss about system design? We can share insights about what we learn and explain to each other how to create different systems. I am not some experienced dude, but I am passionate about it.

jovial gazelle
#
  • there's always solutions on each problem
#

And every learning resource is available online

#

In videos, books, etc

dawn cliff
#

Is this correct?

#

I just made this in my notes

haughty mountain
#

blue subtree is incorrect

dawn cliff
#

that's what I thought

#

so a subtree always starts with a root node, therefore the blue is incorrect because there are 2 root nodes, each with their own tree

haughty mountain
#

basically every non-root node is the root of its own subtree

agile sundial
#

the blue circle isn't a tree, it doesn't have a root node. also it's disconnected

haughty mountain
#

(it's a forest)

agile sundial
#

ye

dawn cliff
#

mmmm

#

ty

fiery cosmos
#

When doing a depth first search on a tree, should I use pythons deque import instead of making the stack a list?

lean walrus
#

why? dfs needs only stack

vocal gorge
midnight dew
tawdry nebula
#

i want to learn data structure and algorithm in python can recommend any best course for it ???

harsh linden
#

hi guys i was wondering i am newbie could you help me with something i would like to make a graph bassed on some data and i dont really know how

keen hearth
fiery cosmos
dawn cliff
#

Question,

[4, 2, 7, 11, 12, 8]

What is considered the "front" and what is considered the "end"? If this list was a queue?

#

is the front always the left side? that kind of thing

lean walrus
#

it doesn't really make sense to implement queue using list

#

but if it was stack, then top of stack is the end of list

narrow mica
# dawn cliff Question, ```py [4, 2, 7, 11, 12, 8] ``` What is considered the "front" and wha...

In a stack, the most recent element is removed first, so you do one of these:

# Option 1 - use list[-1] as the top
list.append(e)  # stack.push(); adding a new element to the stack
list.pop()      # stack.pop();  removing an element from the stack

# Option 2 - use list[0] as the top
list.insert(0, e) # .push(); very slow
list.pop(0)       # .pop();  very slow
```And as `Option 1` can do both fast, we can code it that way to use a `list` as a stack without being very slow

Where as in a queue, the oldest element is removed first, so then you have to do
```py
# Option 1 - use list[0] as the front and list[-1] as the end
list.append(e)  # queue.push()
list.pop(0)     # queue.pop(); very slow

# Option 2 - use list[-1] as the front and list[0] as the end
list.insert(0, e) # .push(); very slow
list.pop()        # .pop()
```And both options have an operation that is very slow if the queue gets large enough
midnight cloak
#

hello guys can anyone here give me some dsa courses for beginners because i'm Dispersed

keen hearth
#

It's not comprehensive, but it's a good introduction to thinking about algorithms.

shadow glen
#

okay so if i do this ">" -> > in my grammar, will the json parser identify a ">" as a > comparator?

#

that about lark

#

Lark library

#

i don't know if this would work

#

this is what i'm trying to do in lark

#

comparator: (">" -> > | "<" -> < | ">=" -> >= | "<=" -> <= | "!=" -> != | "==" -> ==) (string | number)

#

i got how it works basically

#

like -> this arrow allows me to alias a thing to some other thing

#

then i'm planning to verify if it's true or false:

compare: ((roll | math | echo | select | if*) comparator) -> ("true" | "false")
fiery cosmos
crimson kestrel
#

yo chat real talk

#

what would you rate my A* algo from a scale of 1 to 10

pure crest
#

pure graph theory question: can a 4-regular graph have 2 vertices?

#

the only thing I see is that the degree of a 4 regular must be 4 on all vertices

#

so I would think you could have parallel edges

#

unless this could be solved in a different way

shadow glen
#

okay so i got a dillem:

macro_grammar = Lark(
    r"""
    use_var: "&" int
    variable: "$" command
    command: (if |roll | math | echo | select) ws? (if |roll | math | echo | select)*
    
    if: (roll | math | echo | select) ws "!if" ws comparator ws else
    else: "!else" ws (if+ | roll | math | echo | select)
    
    roll.3:  "!roll" ws string
    math.3: "!math" ws string
    echo.3: "!echo" ws (string|"[" input "]")
    select.3: "!select" ws input

    comparator.2: ((roll | math | echo | select | if+) ws comparator_indx) -> ("true" | "false")
    comparator_indx: (">" | "<" | ">=" | "<=" | "!=" | "==") (string | number)
    
    input: "(" string ")" ("," "(" string ")")*
    string: ESCAPED_STRING
    number: SIGNED_NUMBER 
    ws: WS
    
    %import common.SIGNED_NUMBER
    %import common.ESCAPED_STRING
    %import common.WS
"""
)


class Compiler(Transformer):
    def command(self, str_mc):
        (cmd,) = str_mc
        return cmd

    def math(self, cmd):
        (m,) = cmd
        expression = m.replace("!math ", "")
        result = exemath(args=expression, res_type="all")
        return result

    def select(self, cmd):
        (sl,) = cmd
        options = sl.replace("!select ", "")
        result = exeselect(arg=options)
        return result

    def roll(self, cmd):
        (rl,) = cmd
        roll_prompt = rl.replace("!roll ", "")
        result = exeroll(args=roll_prompt, res_type="all")
        return result

    def echo(self, cmd):
        (ec,) = cmd
        op = ec.replace("!echo ", "")
#

in echo i need to compare if the value inside is just a tring or a set of inputs
if it' a set of inputs it should divide the inputs into pages
so i will need to use it with my paginator
which is already created
if it's a string it just return
also i don't know if replace is a good idea of removing the identifier
like !roll, !select, etc
my plan here is just to work with the secondary part of each command
maybe i don't need replace !command's

#

and also have an impasse
if i use subcommand and makes the "##" as their identifier
it will coment
*comment
how do i use # inside strings without it commenting?

haughty mountain
haughty mountain
#

in this case going a bit bigger is the solution

#

overall the construction is just this kind of pattern extended, and then connected back to itself to form a "ring"

north frigate
#

I'm from VietNam.Could you help me how to learn DSA through book ,document or youtube, and give me some information about it

thorny lily
#

Any good crash course on utube for python dsa? Wanna learn the basics and start doing leetcodes

#

Prolly something like sub 10 hrs ish?

edgy hemlock
#

I made a crummy weather thing and refined it a lil after having it critiqued and that taught me a lot

#

Leetcode is for interviews and most people say that you’ll never really use leetcode stuff outside of that. Unless you specialize in something that requires the fundamentals idk

thorny lily
shadow glen
#

i need help with this two dillems

lilac cradle
#

anyone know an efficient conversion from arabic to roman numerals? i modified some code i found on stackoverflow and have this but i dont think its the most efficient

def roman_numeral(num):
    numerals = (
        (1000,'M'),(900,'CM'),(500,'D'),
        (400,'CD'),(100,'C'),(90,'XC'),
        (50,'L'),(40,'XL'),(10,'X'),
        (9,'IX'),(5,'V'),(4,'IV'),
        (1,'I')
    )
    s = ""
    for n,digit in numerals:
        s+=(digit*(num//n))
        num%=n
    return s
#

im not really fond of how it has to have the subtracted bit as well as the regular numerals in it

narrow mica
# lilac cradle anyone know an efficient conversion from arabic to roman numerals? i modified so...

Not sure what you mean by efficient, but there are some things you can change I guess

def roman_numeral(num):
    numerals = (
        (1000,'M'),(900,'CM'),(500,'D'),
        (400,'CD'),(100,'C'),(90,'XC'),
        (50,'L'),(40,'XL'),(10,'X'),
        (9,'IX'),(5,'V'),(4,'IV'),
        (1,'I')
    )
    s = [] # <-- repeated string concat is slow
    for n, digit in numerals:
        q, r = divmod(num, n) # <-- you can get the quotient and remainder in 1 go
        s.append(digit * q)
        num %= r
    return ''.join(s) 
shadow glen
#

guys, can someone make a regex for Lark that includes all characters, including other language characters and also numbers?

#

cus ESCAPED_STRING don't accept numbers in their set

vocal gorge
#

"all characters"? that's just ..

halcyon plankBOT
#

lark/grammars/common.lark lines 23 to 29

//
// Strings
//
_STRING_INNER: /.*?/
_STRING_ESC_INNER: _STRING_INNER /(?<!\\)(\\\\)*?/

ESCAPED_STRING : "\"" _STRING_ESC_INNER "\""```
shadow glen
keen hearth
#

I wouldn't use that as it's an implementation detail. Can you give some examples of tokens you want to match?

shadow glen
#

then i want to execute and parse this string[

#

"!roll 1d20"

keen hearth
#

Are you sure you need a full parser for this, or could you use regular expressions?

shadow glen
#

?

keen hearth
keen hearth
#

You'd use a parser when you aren't able to represent the input using a regular expression.

shadow glen
#

the thing used in regex

keen hearth
#

For example, you can't represent a language with matched parentheses using a regular expression.

#

I.e. there's no regex that will match all possible matched parentheses strings: (), ()(), (()), (())(), etc.

#

But that doesn't look to be the case with the inputs you want to process.

shadow glen
#

being this my grammar:

macro_grammar = Lark(
    r"""
    chain_command: command (ws command)*
    command: (fif | command2)
    command2: (variable |roll | math | echo | select)

    variable: "$" command

    fif.2: command2 ws "!if" ws comparator ws felse
    felse.2: "!else" ws command

    roll.3:  "!roll" ws content
    math.3: "!math" ws content
    echo.3: "!echo" ws finput
    select.3: "!select" ws finput

    comparator.2: command ws comparator_indx
    comparator_indx: (">" | "<" | ">=" | "<=" | "!=" | "==") (content | number | command2 | sub_command)

    use_var: "&" int
    sub_command: "+>" string
    content: (string? (("{" (use_var | sub_command | command) "}"))+ string? | string)
    finput: "[" ("(" content ")" ("," "(" content ")")*) | content "]"

    int: INT
    string: ESCAPED_STRING
    number: SIGNED_NUMBER 
    ws: WS

    %import common.INT
    %import common.SIGNED_NUMBER
    %import common.ESCAPED_STRING
    %import common.WS
""",
    start="chain_command",
)
#

i want to my string rule accepts all characters

#

i don't know if regular expression could do

shadow glen
shadow glen
#

to see which would fit better

keen hearth
#

Yeah maybe. I'm just looking at the grammar you posted to see whether it's something you could do with just regular expressions.

#

Ah right, yeah this isn't a language you can parse using regular expressions. Nevermind.

#

Can you give some examples of some more complex commands?

shadow glen
#

+>mresult -> "!echo [Sucess: {&1}] !if !roll 1d20 >10 !else !echo [Failure]"
+>mdamage -> "!echo [{&1}\nDamage: {!roll 1d10+5}] !if $!echo {+>mresult} == Sucess !else !echo [{&1}]"
+>multiplex -> "!echo [(Banana)(Acid)(Clockwork)] !if !roll 1d20 !if !echo [Monkey] == [Monkey] !else !roll 1d10 >10 !else !echo [Azura is a robber]"
+>azaki -> "!math 2+2 !if !echo [Apple] == [Pineapple] !else !math 4+4 !if !echo [Pineapple] == [Cupuaçu] !else !select [(Lapiz Lazuli)(Emerald)(Ruby)]"

shadow glen
#

this is complex

shadow glen
#

so @keen hearth

keen hearth
shadow glen
#

the part on the right hand side -> is what i want to parse

#

the left ones are their names

keen hearth
#

Oh ok

lilac cradle
#

I meant more structural things but thats true

#

ideally it would work without the explicit declaration of values like ‘iv’, ‘ix’, etc

#

i think what makes it hard is the alternating power of roman numerals; it switches between 5 and 2

fiery cosmos
shadow glen
#

guys, how do i clear tracemalloc

#

cus even with cleartraces it's not giving me memory

#

for my tracemallocs

#
Traceback (most recent call last):
  File "C:\Users\User\PycharmProjects\Learning_Lark\fifth_lark.py", line 366, in <module>
    snapshot = tracemalloc.take_snapshot()
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\tracemalloc.py", line 556, in take_snapshot
    raise RuntimeError("the tracemalloc module must be tracing memory "
RuntimeError: the tracemalloc module must be tracing memory allocations to take a snapshot
deft rampart
#

in each second i gateway receives a request from domain request [i]. The gateway allows atmost 2 requests from a domain within 5 seconds and atmost 5 requests within 30 seconds hackerrank solve

#

has anyone came across this problem before?

crimson storm
#

Is there an easy way to evaluate a math expression where the terms can be non-numerical variables? In my case, they can have special characters in them, so something like:
(-ABC123 + CDE$01 - XYZ§02 + AAA-12 + BBBC=2)*-1 (Each term has 6 characters, so it would be no problem for me to extract the terms and maybe replace them, to make the evaluation easier). I would probably replace the terms and evaluate it and then insert the terms again. Any suggestions? I actually liked ast, but it doesn't work with special characters and is more for processing python code. Any suggestions?

outer rain
# crimson storm Is there an easy way to evaluate a math expression where the terms can be non-nu...

Learn how to write recursive descent parsers. It will be hard, but not that hard, you will learn a lot along the way, and most importantly, it will give up an idea why solutions like "replace the terms and evaluate it" are very unclean.

Alternatively, go a completely different route, and learn how to use a parser combinator, like compynator. That way you won't have to learn anything, you will have a faster and less error prone solution, and maybe even learn a good tool in your skill list, but since you even asked that question in the first place, I might recommend against it (using parser combinators without knowing at all how they work at least on the basic level is very questionable in my opinion, but who knows, maybe first using one will give you a better ground)

crimson storm
opal oriole
# crimson storm thank you. Unfortunately time is of the essence right now, which is why I went w...

Lexical tokenization is conversion of a text into (semantically or syntactically) meaningful lexical tokens belonging to categories defined by a "lexer" program. In case of a natural language, those categories include nouns, verbs, adjectives, punctuations etc. In case of a programming language, the categories include identifiers, operators, gro...

In computer science, the shunting yard algorithm is a method for parsing arithmetical or logical expressions, or a combination of both, specified in infix notation. It can produce either a postfix notation string, also known as Reverse Polish notation (RPN), or an abstract syntax tree (AST). The algorithm was invented by Edsger Dijkstra and name...

stray fractal
#

is there a better way to assign IPA/ARPABET phonetics to letters in a word?

#

currently i have a mapping of latin letters to possible IPA phonetics and it's pretty messy

haughty mountain
#

and ambiguous going both ways: homophones, homographs, ...

stray fractal
#

how about just distinguishing vowel and non-vowel areas in the word

placid shuttle
#

I have a algorithm that takes dict of fields in format field_name: value, then in the csv file checks if all field_name contain the specified value in the same row.
For example if I get dict that looks like this {"car": "audi", "price": 3000} it needs to return only those rows where both fields match.
This is my code:

field = {"car": "audi", "price": 3000}
list_of_truth = []
for key, value in field.items():
    if row[key] == value:
        list_of_truth.append(True)
    else:
        list_of_truth.append(False)
if all(list_of_truth):
  # append to a list
else:
  continue

There is also outer loop that provides me with each row.
Is this a good way to solve this or there's something more efficient?

chilly apex
#

First make this change

field = {"car": "audi", "price": 3000}
list_of_truth = []
for key, value in field.items():
  list_of_truth.append(row[key] == value)
if all(list_of_truth):
  # append to a list
else:
  continue
placid shuttle
polar stone
#
field = {"car": "audi", "price": 3000}
if all(row[key] == value for key, value in field.items()):
  # append to a list
else:
  continue
#

it would avoid looping twice (+ it looks cleaner IMO but that's subjective)

haughty mountain
shadow glen
#

@keen hearth i discovered a thing about Lark, if you acess the input of a transformer, you get the token like a list

#

for example cmd[0] you acess the first token

#

since it don't work like a normal list you need to use a for

#

otherwise it won't work

#

problem solved

#

okay guys, how do i compare if a variable is a string?

clear light
halcyon plankBOT
#

@clear light :white_check_mark: Your 3.12 eval job has completed with return code 0.

True
shadow glen
#

@keen hearth for some reason i don't know why my grammar don't detect symbols that i included in CHAR as part of the char_set

#

like, i included the +

#

for math operations

#

i don't know why it's not detecting

hidden glacier
#

how can i get started learning data structures and algorithms and start solving leetcode problems

hidden glacier
fiery cosmos
#

Given a binary tree and a number sequence, find if the sequence is present as a root-to-leaf path in the given tree.

This is my solution

#class TreeNode:
#  def __init__(self, val, left=None, right=None):
#    self.val = val
#    self.left = left
#    self.right = right

class Solution:
  def findPath(self, root, sequence):
    # TODO: Write your code here
    return self.checkPath(root, sequence, [])

  def checkPath(self, root, sequence, currentPath):
    if root is None:
      return False
    currentPath.append(root.val)
    if root.left is None and root.right is None:
        if currentPath == sequence:
            return True
        else:
            return False
    else:
      return self.checkPath(root.left, sequence, currentPath) or self.checkPath(root.right, sequence, currentPath)
      del currentPath[-1]

I know other correct solution but I was wondering why this above is incorrect

haughty mountain
fiery cosmos
haughty mountain
#

you just keep appending to currentPath and never popping

#

when you do a dfs like this, the append should be paired with a pop, as written here you need to do it in two or three places

polar stone
haughty mountain
stable pecan
cinder maple
#
import matplotlib.pyplot as plt
import math

x_values = []
y_values = []

for n in range(2,100): #avoided the edge cases for fun.
    x_values.append(n)
    flag = 0
    count=0

    for i in range(2, int(math.sqrt(n) + 1)):
        count=count+1

        if n % i == 0:
            flag = 1
            y_values.append(count)
            break

    if flag == 1:
        print(n, "is not a prime")
    else:
        print(n, "is a prime")
        y_values.append(count)

y_real=[math.sqrt(x)-1 for x in x_values]

plt.title("Time Complexity of Primality check: $\mathcal{O}(\sqrt{n})$")
plt.scatter(x_values, y_values, color='magenta')
plt.plot(x_values, y_real, color='black')

plt.show()
#

I tried to plot the prime number checking algorithm

#

i'm a beginner, can you check the code and give suggestions

#

as in better way to code this or missed edge cases etc.

outer rain
# cinder maple ```py import matplotlib.pyplot as plt import math x_values = [] y_values = [] ...

I would have formatted the code (spaces around operators, like in count = count + 1), used f-strings instead of multiple parameters to print print(f"{n} is not a prime"), and used while loop (while i * i <= n instead of for i in range(2, ...)) with integers instead of for with sqrt. sqrt can be imprecise. Try running your code for a number 100_000_007 ** 2. It will take a while, but I should terminate eventually and say that it is prime even though it is a square. This is because floating point numbers don't have enough precision to represent numbers like these accurately.

#

oh, wait, sorry, no, it will work correctly, my bad

#

100_000_007 ** 2 is not big enough, I forgot float is 64 bits... I still would raise an eyebrow on such code though

vocal gorge
#

i'd use math.isqrt in modern python

cinder maple
#

for any number n, the worst case is $\floor{\sqrt{n}}$ right?

#

ie, we take square root and round down to the nearest integer

outer rain
#

yep

cinder maple
#

so, this will give a mess int(math.sqrt(n) + 1))?

cinder maple
outer rain
#

!e import math; print(int(math.sqrt(10 ** 36) + 1))

halcyon plankBOT
#

@outer rain :white_check_mark: Your 3.12 eval job has completed with return code 0.

1000000000000000000
outer rain
#

1-off

cinder maple
#

why isn't it adding the one ?

vocal gorge
#

i think it may in fact be guaranteed that (int(math.sqrt(x))+1)**2 >= x, though not sure how to prove it.

vocal gorge
outer rain
#

yeah, math.sqrt calcualates the square root in floating-point numbers, which have limited precision

cinder maple
#

10**18 is same as 10^18 right?

outer rain
#

well, if you mean power by ^ -- yes

cinder maple
#

idk the notation

#

yes

cinder maple
#

10**18 is 10 followeded with 18 zeros

#

why is it considering to be same?

outer rain
cinder maple
#

because of the range of float datatype ?

outer rain
#

(obligatory)

vocal gorge
# cinder maple why is it considering to be same?

a floating-point number can be thought of as a number written in scientific notation with a fixed-length mantissa. for example, if it was using decimal (instead of binary like real floats do), 10^18 wouldbe represented something like 1.00000000000000000 * 10^18, with, let's say, exactly 17 decimal digits in the mantissa.

#

so it can't represent 10^18 + 1, because that'd need another decimal digit in the mantissa. the next lowest number it can represent is instead 1.00000000000000001 * 10^18, which is 10^18 + 10.

#

Real floats work pretty much like this, just in binary. Their mantissa is 52 bits long. So they can exactly represent all integers up to 2**53 - but at that point the precision runs out, and 2**53 and 2**53 + 1 are the same float (the next exactly representable float is instead 2**53 + 2).

outer rain
#

(2 ** 53, not 2 ** 52)

#

!e print(float(2 ** 52) + 1)

stuck blaze
#

Hi im a very noob programmer and im starting python, is this the right place to ask for help?

vocal gorge
#

ah, true.

halcyon plankBOT
#

@outer rain :white_check_mark: Your 3.12 eval job has completed with return code 0.

4503599627370497.0
cinder maple
vocal gorge
outer rain
cinder maple
#

theoretically it will only in square numbers right?

#

not anywhere else?

#

just wanted see if i got the math right

outer rain
#

I think so, but I may be wrong

#

floating point arithmetic is tricky

cinder maple
#

i still don't catch all of it

#

perphaps if you can give an analogy in C

outer rain
#

analogy to what, sorry? 😅

cinder maple
#

like something similar like this happening in C programing

#

10^18 wouldbe represented something like 1.00000000000000000 * 10^18, what does this mean?

#

like 10^18 is stored as 1.00000000000000000** 10^18

#

like a 18 digit long float and the number in its power?

cinder maple
vocal gorge
# cinder maple like a 18 digit long float and the number in its power?

i'm talking about how floats are internally stored. i'm using hypothetical "decimal floats" as an analogy - suppose you represent numbers in scientific notation, m * 10**e, where m is a decimal number, 1<=m<10, and, crucially, m has no more than 17 decimal digits (it can't be arbitrarily long). and e should be integer.
this approach can only represent some numbers. for example, you can represent 10**20 (it's just 1.0 * 10^20), but you can't represent 10**20 + 1, because you'd need more than 17 decimal digits in m.
for the same reason, floats can't represent some large enough integers.

cinder maple
#

oh so this is how floating point is implement in python

#

makes sense

vocal gorge
#

floating point numbers are implemented the same way everywhere.

cinder maple
#

i get what you mean by limitation now

outer rain
#

the calculation here goes like this:

# this is the initial number you are working with
10 ** 36

# this is an exact integer it is equal to, integers are stored precisely
1000000000000000000000000000000000000

# this is the first operation you are trying to do
math.sqrt(1000000000000000000000000000000000000)

# internally, `math.sqrt` converts argument to float:
# here is this number is converted to the nearest floating point number
math.sqrt(1000000000000000042420637374017961984.0)
# notice how it is already not precise: 53 bits of mantissa is not enough to represent it precisely

# this is the result of math.sqrt.
# again, remember that floating point numbers are not precise
# this is not an exact square root of that number above, but it is the closest
# floating point number to the exact square root of that number
1000000000000000000.0

# finally, you are adding 1 to that number...
1000000000000000000.0 + 1

# and again, since the exact result can't be represented precisely,
# we take the closest floating point number to the exact result, which is...
1000000000000000000.0
cinder maple
#

so only walkaround to avoid this is not to use square root?

#

stick with integer arithmetic?

#

i suppose thats why you used a while loop i*i <=n

outer rain
vocal gorge
#

in python i'd just use math.isqrt. in general, I think just adding a 1 to the loop's upper limit will make it valid, though proving this might be annoying

#

the while-loop way would be obviously correct, though maybe a bit less performant

outer rain
outer rain
cinder maple
#

i don't think adding 1 to the upper bound is nice

vocal gorge
#

frankly this problem is a hypothetical one anyway, because this algorithm would take way way too long on the largest number that it can correctly factorize. so who cares that it fails above that :p

cinder maple
outer rain
cinder maple
#

is appending into array and then plotting it the standard way?

outer rain
#

well... no...

#

maybe

#

uhm... no...

vocal gorge
#

i'd note that it's "number of iterations", not "time", but if it's an iterative algorithm, you could.

cinder maple
#

what else can I try

outer rain
#

it's sometimes difficult to figure out what to plot, and in relation to what, but you will figure it out lol

vocal gorge
#

your y-axis.

cinder maple
#

it's the count right?

#

shouldn't it be my y axis?

#

im really new

vocal gorge
#

i'm saying that the number of iterations isn't quite the same thing as time taken, so it's slightly misleading to label this "time complexity".

#

(but of course, actually measuring the time would be much more annoying and noisy.)

cinder maple
#

isn't time complexity the number of iterations ?

#

like the worst case scenario for number of iterations

outer rain
#

it is, if you define iteraton correctly..

#
import math

def is_prime(n):
    return math.factorial(n - 1) % n != 0
#

this algorithm technically does not iterate anywhere (visibly), but it's far from O(1)

vocal gorge
cinder maple
#

i think when we said time, we really mean time in as in 2 times 2

#

not the clock time

#

can it also mean clock ticking time?

outer rain
#

when talking about algorithmic complexity, we usually count amount of primitive operations a machine does

#

(e.g. instructions)

clever palm
#

Hey anyone sorry for disturbing can u suggest me one thing.....

outer rain
#

but you can't really count them from python anyway

clever palm
#

Is it better to know many programming languages or only master one

outer rain
#

the most useful metric (and related to algorithmic complexity kind of loosely) is the real running time

clever palm
#

Hey elteammate can you suggest me pls??

#

not much time

outer rain
#

this is not the channel for this

clever palm
#

sry for that

cinder maple
#

so when i say for a number n, the worst case of finding a divisor is \sqrt{n}

#

what complexity are they mentioning?

outer rain
outer rain
outer rain
# cinder maple what complexity are they mentioning?

Imagine you having an abstract executor, which has infinite addressable memory, where each cell can store any whole number, and a processing unit capable of doing arithmetic instructions such as addition, multiplication, ... Then, if you write an algorithm equivalent to what you have written, for that abstract machine, given a number n in one of the memory cells, it is capable of checking whether it is prime or not in O(sqrt(n)) primitive operations.

O(sqrt(n)) means that there is a constant C such that an amount of iterations your machine does is less than C * sqrt(n). Notice that this is a very rough estimate: for even numbers your machine will terminate almost immediately. You can say that your algorithm actually works in O(d(n)) where d(n) is the smallest divisor of n, but it is not a pleasant function to work with, so you "round up" the time to sqrt(n).

Now, in real world, there is no infinite memory nor infinite numbers. The bigger the integers are in python, there slower operations on them become. However, you don't care about numbers that big. So, instead you say that your algorithm closely resembles one running on the abstract machine, and therefore, works in O(sqrt(n)). Even though technically, it would work slower with very very large numbers. Of course, you can just sat that everything is O(1) because the memory is limited anyway, but it's not a useful estimate either.

So, in other words, time complexity in practical applications is a lie. What it means is that the real time taken by the algorithm to finish for large inputs resembles the amount of instructions an abstract machine with infinite memory would execute to finish that program, and what O(f(n)) means, is that for large inputs, the algorithm on such abstract machine will take at most C * f(n) operations for some C.

#

Finally, it's worth mentioning that it isn't really a lie, and it can be formalized through a thing called "transdichotomous model", but I won't go into that...

cinder maple
#

give me some time

#

i have to read through this carefully

#

i'll comment after that

#

So for the above code, it had the assumption that the codeblock inside the for loop is single operation?

#

@outer rain

outer rain
#

not a single operation, but a bounded number of operations

#

because think about it, from the point of complexity, it doesn't actually matters how much operations some part of code does as long as it is independed from the input

cinder maple
#

So is counting the iteration count really the way to explain algorithmic complexity?

outer rain
#

if you assume the body of for does twice the operations, take C twice as large: the number of operations < C * sqrt(n) is still true

outer rain
cinder maple
#

very formally, if there was a operator that checks a number is a divisor of n, then it would be done in exactly \sqrt{n} right?

#

ie choose c=1

cinder maple
outer rain
cinder maple
#

suppose % is the only operation

outer rain
#

not really, because loop does quite a few more things..

#

increment i, jump to the next iteration

#

compare the result of % with 0

#

all of that are operations

outer rain
#

as long as it's bounded, you can find such C, and you don't care what that C would be

#

can be 19045685096834059683049586

#

as long as it doesn't depend on the input - it's fine

cinder maple
#

sort of like a scalar away

#

idk how it put it

#

is this the formal definition of?

outer rain
#

yeah, this is a definition of O

#

and when taking about time complexity you basically mean amount-of-operations(size-of-input) = O(g(size-of-input))

#

well, maybe not "size" of input, maybe something else

#

like in factorization the value of the number you are trying to factorize

cinder maple
#

isn’t g(x)= sqrt(n) here?

outer rain
#

yep

cinder maple
#

can I define ‘time’ to be number of steps

#

and do some math on top of that?

outer rain
#

yeah, that's pretty much what I do with the number of operations

cinder maple
#

so it’s sort of an abstract setting

outer rain
#

it is

cinder maple
#

makes sense

outer rain
#

but it's not that abstract actually, like the CPU does some operations: sure, they don't take the same time to finish, but that time is bounded by something (like 1000 CPU clock cycles), and you don't care about the exact time.

outer rain
# cinder maple

the more abstract stuff arises here, where you say "as x --> oo": unlimited memory is pretty abstract

cinder maple
#

makes sense

#

Thanks a lot for your help

#

I have no formal background in computer science

#

I got interested into this when taking a number theory class

outer rain
#

oh, this is cool :)

cinder maple
#

We have proved Lame theorem which gives an upper bound for euclidean division algorithm

outer rain
#

I have not been taught what time complexity is for a long time too, I just had some intuition lol

cinder maple
#

so thought to dig more into that and now i am here

outer rain
#

I see

cinder maple
#

my next step was to try for primes

#

I know mathematically, there exist a prime divisior less than \sqrt{n}, easy to prove

#

just plotted in thinking it’s time complexity lol

outer rain
outer rain
cinder maple
#

yes, the notion is consecutive fibanocci numbers gives the worst case scenario

#

in gcd algorithm

#

like it will go all the way down to 1, as consecutive fibanocci are relatively prime or gcd=1

outer rain
#

there is a pretty interesting corollary from that theorem, which is pretty useful

cinder maple
#

what’s that?

outer rain
#

is that if you take gcd of not just 2, but a lot of numbers, say N, then it works in O(N + log min(a1, a2, ..., aN))

#

it is a surprisingly useful fact which doesn't necessarily useful by itself, but in the context of some data structures for calculating gcd is pretty interesting

cinder maple
#

glad you found it useful, but I’m really unaware

outer rain
#

because normally if some operation <*> can be performed in O(log min(a, b)), then a1 <*> a2 <*> ... <*> aN will take O(N * log (a1 + a2 + ... + aN)), but with gcd it's special

cinder maple
#

comparing, it’s a huge difference

outer rain
#

if you decide to pursue you number theory journey through programming and will experiment with gcd, just remember this fact: that gcd works faster than you expect when taken from multiple numbers at once, it may explain some interesting measurements you may get

#

just a small caution 😉

cinder maple
#

Have you tried complexity of RSA Algorithm?

outer rain
#

I have never played with any cryptography, actually :(

cinder maple
#

I’m planning try that next

#

Idk cryptography either

outer rain
#

that would be pretty fun

cinder maple
#

It’s essentially abstract algebra

#

number theory with in algebraic structures

outer rain
#

I was at a camp-thingy-or-something-idk with people from my class, and we had a few lessons dedicated to basic cryptography

#

and there was a practice day where we had to implement RSA and a few other algorithms

#

and there was also a challenge for breaking RSA with relatively small numbers

cinder maple
#

iirc it’s based of fermat theorem

outer rain
outer rain
cinder maple
#

I’m just getting started tho

#

Is there any resources you can suggest me to learn more on complexity?

#

I tried searching a lot tbh

outer rain
#

uhm, I am afraid not...

#

there are a few resources in pins, you can check them out

cinder maple
#

How do people do it in standard way?

outer rain
#

well, my story is that we had a class dedicated to algorithms in school, and now in uni

cinder maple
#

from scratch?

outer rain
#

I don't know about most people though

outer rain
cinder maple
#

I think most people study data structures then complexity

#

I have somewhat zero exposure to data structures

#

I took a C++ course for a year in grade 11 and 12

outer rain
#

well, if you study DSA you will have some understanding of time complexity anyway for sure

#

but then there is a whole other direction to that

#

theoretical informatics, where everything works slightly differently, I would say

#

like in DSA you mostly care about practical applications, and in theoretical informatics you mostly think about wide classes of algorithmic complexities

#

both are important, and I wouldn't say there is a strong correlation between them

cinder maple
#

The formalism of these notions are really great

#

it’s par with most of our adv analaysis course

outer rain
#

I sometimes like learning about the formalism of these things a lot, and sometimes just find it very painful and boring

cinder maple
#

In my opinion, having intution is far superior than being able to define formally

#

Feel free to bounce off, if you are busy

#

Don’t mind to reply lol

outer rain
outer rain
cinder maple
#

yes, it’s just a step away

#

but i know people who got caught in formalism

outer rain
#

yeah, sometimes happens... I was that person some time ago actually, but I got bored eventually

#

I will say though: writing your proof in LEAN (formal verifier) and having it finally not yell at you is so, so satifsying

cinder maple
#

It’s very analogous to algebra, you can do solve equations and really caught in algebra without knowing what you are doing

#

idk if it’s relatable lol

#

but most people can do algebra closing their eyes

outer rain
#

I was never that good in algebra to do it that way, but I know what you are saying

cinder maple
#

nice

#

Thanks for your time

#

have a great day

outer rain
#

no problem man, just trying to procrastinate ❤️

cinder maple
#

wishing you all the best to get your stuff done

#

hff

restive cypress
#

hey, what is the best platform to host my python files (on replit) for free?

shadow glen
#

do anyone knows how do i use regex to get all non-alphanumeric numbers?

#

i need it for my lark

vocal gorge
#

what's a "non-alphanumeric number"??

lament totem
#

floats I guess

vocal gorge
#

if you mean non-alphanumeric character, can do e.g. [^a-zA-Z0-9], depending on what you mean by alphanumeric. not sure there's a good way to match what python considers an alpha char (the Letter unicode category)

lament totem
#

maybe scientific notation

shadow glen
#

now i'm having problem with sympify

#

why my code is returning numbers as interger where there is no interget?

#

*interger

#

like

#

it's all string

#

there is no interger there

#

what my problem is smokin'?

shadow glen
#

okay guys, how do i compare the origin of a returned value?

#

i need that for Lark

#

so i can compare if the value comes from key_cont

#

so if yes i can join the strings

glacial cloak
#

Which python DSA course is best for solving leetcode problems? is udemy good enough

fiery cosmos
#

Btw, if you are into LeetCode, maybe it would be good to check NeetCode

glacial cloak
glacial cloak
fiery cosmos
ornate rover
#

look at this @keen hearth

#

so I understand everything

#

until the total

keen hearth
#

One sec

#

So, the sum of the first n perfect squares is the nth "square pyramidal number". The formula for it is n * (n + 1) * (2*n + 1) / 6.

#

So they've just substituted in n*n into this formula.

ornate rover
#

what if I didnt know the formula tho

#

or know that its a square pyramidal number

keen hearth
#

Alternatively it's n**3/3 + n**2/2 + n/6. Even if you don't remember the exact formula, you can remember that the largest term is an n**3 term.

ornate rover
#

well in the exam I dunno how im gonna anseer

#

lol

keen hearth
#

Right yeah. Do they provide you with a formula sheet?

#

Or alternatively is the exam open-book?

keen hearth
ornate rover
#

its not

#

open book either

#

he will give a code and ask us to find the o notation

#

like that one

keen hearth
#

I think in general sum(i**k for i in range(n)) is O(n^(k+1)). I'm not sure if thats a fact you can just quote as part of your argument in the exam.

#

Are the questions the kind where you just have to find the right answer, or the kind where you have to prove the answer?

coral coral
ornate rover
#

prove the answer @keen hearth

keen hearth
#

It might be worthwhile memorising the triangle number and square pyramidal number formulas. I'd get clarification from your instructor about what's expected of you in the exam.

#

Btw, the sum of the first n cubes is just the nth triangle number squared. So you get that one for free.

lean walrus
#

i'd remember how to derive these formulas

keen hearth
#

Is there a simple way to derive the sum of squares formula?

lean walrus
#

solve this
f(n)=f(n-1)+n^2
f(0)=0

#

hmm, i actually dont know how to solve this without:

  • exhaustive search
  • knowledge of differential equations
  • knowledge of generating function
    my bad, it is indeed easier to just remember formulas
vocal gorge
coral coral
#

can anyone provide tips for working with these formulas? I was able to get the temp one working but the humidity one is not returning sensible values

coral coral
#

I think that is actualyl correct

#

I think im getting the wrong stats for H4+

#

h4 and the rest are offset by 4 bits i think

#

is there some way i can just add 4 bits into the bytes string i read?

#

im trying to do that but can't get it to work, the half byte offset is messing me up

coral coral
#

im not sure if the library is right?

#

I've been working this out, the library says I should get 50 for H5

#
01111110 00000001 00000000 00010001 00100001 00000011 00011110
#

This is the data from each register

#

I'm getting 515 which I think could also be a reasonable value

somber mango
#

would this channel be appropriate to post about dynamic programming on the 0/1 knapsack problem ?

haughty mountain
#

it would

somber mango
#

ok

#

so basically here I'm solving the 0/1 knapsack problem and I implemented a naive dynamic programming approach with a table and the Bellman recursive equations

#

here is the code

#
#!/usr/bin/python
# -*- coding: utf-8 -*-

from collections import namedtuple
import numpy as np
from operator import itemgetter

Item = namedtuple("Item", ['index', 'value', 'weight'])

def solve_it(input_data):

    # parse the input
    lines = input_data.split('\n')

    firstLine = lines[0].split()
    item_count = int(firstLine[0])
    capacity = int(firstLine[1])

    items = []

    for i in range(1, item_count+1):
        line = lines[i]
        parts = line.split()
        items.append(Item(i-1, int(parts[0]), int(parts[1])))

    # start of selection
    value = 0
    weight = 0
    taken = [0]*len(items)

    # preparation of the table
    array = np.zeros((capacity+1,item_count))
    # sort items by weight to start filling the table
    items = sorted(items, key=itemgetter(Item._fields.index('weight')))
    
    # Bellman recursion
    for i in range(item_count):
        item = items[i]
        for k in range(capacity+1):
            if i==0 and k==0:
                array[k][i]=0
            elif item.weight<=k:
                array[k][i] = max(array[k][i-1],item.value+array[k-item.weight][i-1])
            else:
                array[k][i] = array[k][i-1]

    value = int(array[capacity-1][item_count-1])
#

I'm able to get the optimal solution using this code

#

However, I'd like to implement a way of getting a decision variable vector

#

with each entry being either 0 or 1 depending on if we select the item or not

#

But for some reason I'm not capable of finding a way to do so. I know I should use the table to do that

#

my table has a column for each item and the rows are the capacities of the knapsack, going from 0 to K

#

if somebody can give me a hint on this one I'd be more than happy

#

thanks!

tawdry bay
#

Hey guys, has anyone worked with the concorde algorithm which is implemented in C?

vast creek
#

heelo

#

Fatimah has many digits. She wants to construct two numbers using these digits, so that the product of these two numbers is maximum.

For example, if she had digits 1 2 2, the best she could do is to construct the numbers 2 and 21, and get the product 42.

For the given list of digits, what is the remainder modulo 998244353 of the biggest product she can get.

Note: There are three different cases you need to solve.

5 9 3 7 4 8

#

any idea how can i do it ?

warm quail
modern gulch
buoyant scaffold
fiery cosmos
sage flame
#

can someone help me understand why exactly is the space complexity O(bm)

haughty mountain
#

I would say O(m), but depends on how you implement

#

if you use a stack I can see O(b m)

somber mango
#

Hi guys

#

I’m new to BnB algos for knapsack problems

#

And I’m wrapping my head around the upper bound calculation

#

From what I’ve understood there is no unique way of computing an upper bound at each node and some people still do write papers on the subject. Also sorting by decreasing value of value to weight ratio will improve the pruning for certain upper bound formulas

#

That’s what I’ve understood

#

Is it correct?

sage flame
haughty mountain
sage flame
haughty mountain
sage flame
#

if the "b" is different on each level

haughty mountain
#

huh? I meant in the example b is assumed to be constant across every node, at least that's the one sane setup given the diagram

#

per layer: 1 node, b nodes, b² nodes, b³ nodes, ...

#

that occurs when every node has b children

#

iirc it would be called a "branching factor"

lilac cradle
#

im wondering if there’s a more efficient method to doing this; so say i have a 3d grid of points, and i want to draw like, a line, or a curve, but with some thickness

what i would currently do is generate the line or curve, then for each position on that curve, fill in a sphere and add those positions to the final result, repeat until finished
the problem with this is that there's a ton of redundancy, though using something like a set to hold all the positions and then check if a position is already in the set helps remove a lot of that

sage flame
haughty mountain
#

what happens in the iterative version is
push b children, pop 1
push its b children, pop 1
push its b children, ...

#

so (b-1) + (b-1) + ...

lilac cradle
# lilac cradle im wondering if there’s a more efficient method to doing this; so say i have a 3...

here's a function i wrote to give an idea of what im currently doing

def add_thickness(points,r):
    output_points = set()
    for p in points:
        for z in range(-r,r+1):
            for y in range(-r,r+1):
                for x in range(-r,r+1):
                    if (x,y,z) == (0,0,0):
                        continue
                    pos = (p[0]+x,p[1]+y,p[2]+z)
                    if pos in points:
                        output_points.add(pos)
                        continue
                    if pos not in output_points:
                        if (x**2 + y**2 + z**2) < r**2:
                            output_points.add(pos)
    return output_points

it takes in a collection of 3-tuples (or lists, or whatever) representing positions, and a value r (for radius) and generates a set of points which fill a spherical area around each of the input points

#

one thing i might try and add is a start and end thickness, and interpolate between them

#

but that might not work since im generally taking in a set

#

might change 'x2,y2,z2' to just 'x,y,z' since im not using anything called 'x,y,z' rn

#

there

#

i tested it out and it seems to work pretty well

keen hearth
lilac cradle
keen hearth
#

Maybe you could join a pair of points together, making a line segment. Then use the unit vector pointing along this line segment to determine how far a voxel is from the line? 🤔

haughty mountain
#

at least that seems like a half sensible idea

#

acutally...maybe it's not that easy...

lilac cradle
#

oh wait im dumb, i dont need that membership check anyway

haughty mountain
#

you would need to check if the point is close to any input point

lilac cradle
fiery cosmos
#

Find the tangent to a point on your curve and draw a circle such that the tangent line goes through its center.

#

@lilac cradle

haughty mountain
#

I suspect that will look pretty weird given the discreteness of the points

fiery cosmos
#

If you do it for lots of points in-between it will fill

haughty mountain
#

yeah, that will create a cylinder following the path

#

if you only have the points given to you it gets sketchier

#

you could probably do some interpolation

fiery cosmos
#

That'd be really cool.

haughty mountain
#

the 2d version of this is already a bit of a challenge to get right

fiery cosmos
#

Would you use quadratic interpolation so it is smooth?

#

Or curves I mean

haughty mountain
#

pick your favorite

lilac cradle
#

that sounds kinda complicated to implement but i guess i could try that, though this is meant less for an actual curve and more for just any set of points

#

this was pretty hacky to implement but here's a somewhat smaller torus with a rainbow gradient

fiery cosmos
#

@lilac cradle what is this for?

lilac cradle
#

i just wanted to make an umbilic torus in minecraft

#

thats all

#

looks cool on the map view

fiery cosmos
#

More algorithms please.

jovial gazelle
#

Woah that looks cool

simple abyss
#

That's awesome.

polar breach
#

What's a good way to learn DSA? (python)

#

as someone whos is beginner-intermediate with python

summer fossil
polar breach
#

leet code problems make me want to smash my head against a wall

summer fossil
#

i think u can follow neetcode roadmap

#

Check the pin

narrow mica
tranquil sentinel
#

Hi, can anyone help me, I'm working on a project using Keras but I have a problem with the result graph

narrow mica
#

Also didn't Keras merge with tensorflow or something?

keen hearth
# polar breach What's a good way to learn DSA? (python)

Check out the learning resources in the pinned messages. I think, for practical purposes, you should try to get a basic understanding of the analysis of algorithms (that is, asymptotic complexity, a.k.a. big-oh) and also learn about the data-structures and algorithms that are available to you in Python.

Khan Academy also have a short introduction to algorithms course which, although it's not comprehensive, provides a nice introduction to the analysis of algorithms. It uses Javascript for the exercises, but you can skip them if you want to. https://www.khanacademy.org/computing/computer-science/algorithms

oak horizon
polar breach
#

@keen hearthWhat do you tink about these resources

#

A beginner-friendly introduction to common data structures (linked lists, stacks, queues, graphs) and algorithms (search, sorting, recursion, dynamic programming) in Python. This course will help you prepare for coding interviews and assessments.

🔗 Course website: https://jovian.ai/learn/data-structures-and-algorithms-in-python

✏️ Created by A...

▶ Play video
#

Which out of these would be a good ROI for my time?

keen hearth
polar breach
#

So what would be the way to go, out of all the options above, or any other option you suggest?

keen hearth
#

I recommend you start with the Khan Academy course.

#

The KA course was put together in collaboration with Thomas Cormen, who wrote the most widely used algorithms textbook, and has been teaching the subject for decades.

#

It's a pretty short course. It doesn't cover some popular data structures such as hash tables, but it looks like it would give you a good foundation to proceed from.

fiery cosmos
#

Hello is there a better algorithm i can apply to reduce a time complexity and do not complicate a code too much ?

#
def sub_palindromes(string):

    max_len = 1

    for i in range(len(string)):
        left, right = i, i
        while left >= 0 and right < len(string):
            if string[left] != string[right]:
                if right - left - 1 > max_len:
                    max_len = right - left - 1
                break
            left -= 1
            right += 1

    for i in range(len(string)):
        left, right = i, i + 1
        while left >= 0 and right < len(string):
            if string[left] != string[right]:
                if right - left - 1 > max_len:
                    max_len = right - left - 1
                break
            left -= 1
            right += 1

    if max_len == 1:
        return None
    else:
        return max_len


sub_palindromes('CABCAB')
#

function has to return a len of longest palindrom in a string

narrow mica
#

The best algo complexity wise is Manacher's algorithm at O(n), but it's really complicated
Slightly worse is to use a polynomial hash, giving you O(n log n), but it's complicated

cinder maple
#

I don’t have any computer science background, can you please check if the material is wrote is correct

#

ie if it fits the definition of complexity you are aware of

cinder maple
# cinder maple

The reason why i feel sloppy is, the graph doesn’t necessarily capture what I’m trying to do, ie if I change the loop upper bound, different graph will be plotted.

lean walrus
#

your pink graph is incorrect
algorithm you wrote always does floor(sqrt(n)) iterations, which looks nothing like your pink graph but more like staircased black graph

cinder maple
#

The back graph is the real valued graph

#

It’s just drawn as a boundary to get some sense to function f(x)= \sqrt{x}, where x is any real no

lean walrus
cinder maple
#

do you mean for all input ?

#

@lean walrus

#

That's not true, you would only need to check till \sqrt{n} if the number is a prime

#

take n=10 for example, this will exit in first iteration. since 10%2==0

#
import matplotlib.pyplot as plt
import math

x_values = []
y_values = []

for n in range(2,100): #avoided the edge cases for fun.
    x_values.append(n)
    flag = 0
    count=0

    for i in range(2, int(math.isqrt(n) + 1)):
        count= count + 1

        if n % i == 0:
            flag = 1
            y_values.append(count)
            break

    if flag == 1:
        print(n, "is not a prime")
    else:
        print(n, "is a prime")
        y_values.append(count)

y_real=[math.sqrt(x)-1 for x in x_values]

plt.title("Time Complexity of Primality check: $\mathcal{O}(\sqrt{n})$")
plt.scatter(x_values, y_values, color='magenta')
plt.plot(x_values, y_real, color='black')

plt.show()```
lean walrus
#

i dont see any logic that would handle early exit

cinder maple
#

take n=10, floor(sqrt(10))=3

#

ie the loop iterates from 2 to 3

#

when i=2, 10 mod 2 =0 is true, so it will flag 1 and exit the loop

lilac cradle
#

is there an algorithm that can do this? in other words, take an image, upscale it, then sort of smooth the rough pixels (without blurring)?
maybe hq2x would work but idk

#

i don't mean antialiasing btw, imagine the image being 1 bit color depth, so just on and off

lilac cradle
#

so not like this

vocal gorge
lilac cradle
#

might work

#

lemme test it

#

the problem i can imagine that having is with close by shapes but im not sure

#

i used GIMP to do it for that S shape and...

vocal gorge
#

maybe a bit less :p

#

but yeah, this combination basically fills voids, so it's a bit problematic for some shapes

outer rain
lilac cradle
#

hm

#

not so much for the upscaled version but yeah that might be true for the unscaled version

#

see what i was figuring it'd be was either some sort of convolution or seperating it into chunks and applying rules to each one

outer rain
#

trivially upscale it, then do the thing for each pixel

#

I don't know about the convolution

#

well... I suppose you can think of that as convolution, and maybe even make kernel smart enough to figure out how to not fill the 1x1 holes, for instance

fickle linden
#

on the random sort, what is its complexity? n!?

vocal gorge
#

about right, yeah. more like O(n n!)=O((n+1)!), I think, because each shuffle is O(n).

lean walrus
#

O(n) is the same as O(n+1)
O(n^2) is the same as O((n+1)^2)
O(n^k) is the same as O((n+1)^k)
but O(n!) is not the same as O((n+1)!)

#

annoying

vague maple
#

For example, it's likely some kinda color = mix(col1, col2, fac)
Set it to:
color = fac > 0 ? col1:col2

silent mantle
lean walrus
vocal gorge
#

because (n+1)! is n+1 times bigger than n!, and n+1 sure isn't a constant.

lean walrus
#
(1) f(n+1) / f(n) = C
(2) f(n+1) = f(n) + f'(n) * 1 // not really, but good enough for our purposes
subst (2)->(1): (f(n) + f'(n) * 1) / f(n) = C
1 + f'(n)/f(n) = C
f'(n)/f(n) = C-1
f'(n) + (1-C)*f(n) = 0
solve it:
f(n) = K * exp((C-1) * n) // for any K
f(n) = C1 * C2^n // different form

conclusion:
for any function that grows not faster than (anything)^n: O(f(n)) == O(f(n+1))
for other functions: O(f(n)) < O(f(n+1))

(i probably handled cases C<1 and C<0 incorrectly, but i don't care enough)
(and i probably shouldn't use big-O here, but i don't care about this too)
solemn moss
# lean walrus annoying

I like more the fact that
O(nk) is the same as O(n) if we say that k is always equal to some constant value, like 10^9

lean walrus
#

in python integers are limited by 2^2^64, so every integer in python is O(1)

tardy galleon
#

Sorry for the more general coding question.

I was taught that in general "a function does 1 task". So in a situation where you have to take user input, validate that input, and then act on that input. Validation and Action (based on the input) would be 2 separate functions. Which makes sense.

But someone decided to leave some comments on my github over the poor practice I have of bundling, propting user input and validating (and re-prompting the user if the input is invalid) in the same function. Is this really that wrong. And is there a best practice for getting and validating input in a console app?

haughty mountain
unreal root
#

Anybody want to help with a trading Model I’m building ?🔥🔥

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied timeout to @pearl zinc until <t:1706814199:f> (10 minutes) (reason: duplicates spam - sent 4 duplicate messages).

The <@&831776746206265384> have been alerted for review.

earnest escarp
#
>>> import math
>>> hash(math.inf)
314159
>>> hash(314159)
314159
>>> hash(math.inf) == hash(314159)
True
>>> # however...
>>> math.inf == 314159
False
>>> {math.inf: "foo", 314159: "bar"} # silent hash collision resolved by equality check
{inf: 'foo', 314159: 'bar'}

It is inefficient to use infinity and 314159 as keys in the same dictionary 😨 please be aware of this performance trap 🙏. Joking of course

cinder maple
#

How do I compute the complexity of this algorithm?

#

If I assume, reading variable, summing, declaring are three primitive operations

#

then inner loop statement sum+=1 runs 3n^2 times

tight cedar
#

what's the problem then

cinder maple
#

The resource that im reading says the total complexity is 5n^2+2n+3

#

I understand the 3 cames from lines 1, 2, 7

narrow mica
cinder maple
#

It’s giving motivation to the big oh notation

#

It’s a step before that

#

This is their explanation, i think there are some typos

#

They assumed range(n) has a cost of n

naive oak
#

they don't

#

they assume range(n) is one primitive operation

#

the second range(n) is in the for loop so it runs n times

#

they do seem to think range(n) includes n tho

#

which would be wrong

#

actually no they do, but not in that table

#

I guess maybe reading from the range takes one operation, and creating it doesn't

unreal root
#

Just found out what a parameter grid does 😭😭😭😭

#

🔥🔥🔥🔥🔥

dense finch
#

Hi, i am currently trying to make my own calcification neural network from scratch. Im done with the most part except the training part. my plan is to use gradient descent and i think understand the conzept of it but its really hard for me to apply it. i was able to "train" a one neuron per layer model but i have some questouion marks in my head when it comes to a multi neuron per layer mode. ive drawn this image to explain what i dont understand.
my goal is it to update the weight which is shown as a read line. now i dont know which of the blue lines i should take or if i should use both and add the derivatives together.
can someone help me?

fiery remnant
#

I want to learn dsa but before that I wanna learn python

#

i love the way he teaches

#

should i go for it?

lean walrus
#

looks nice, i guess

#

it definitely doesnt contain anything, but for only 11 hours it is awesome

fiery remnant
#

go for it or refer something else?

lean walrus
#

i would go for it, 11 hours is not that much actually

fiery remnant
#

Yes

dawn cliff
#

So this is O(3N) which equals O(N) right? My practice test says that it is N^3 but I guess the zero indenting confused me. I took these for statements as 3 empty for statements with nothing inside of them

for x in range(N):
for y in range(N):
for z in range(N):
tot = tot + z
print tot

A. O(3)
B. O(N^2)
C. O(N)
D. O(N^3)

vocal gorge
#

I took these for statements as 3 empty for statements with nothing inside of them
that wouldn't be valid syntax

#

but it sure is evil of your test if it ruined the formatting.

keen hearth
vocal gorge
#

also, yikes, python 2

dawn cliff
dawn cliff
quasi oracle
# dawn cliff this is how it is on the test 😦

The test is a bit messed up then. You have to have some statement inside a loop, even if it's pass. The only way this code makes sense is if it's actually:

for x in range(N):
    for y in range(N):
        for z in range(N):
            tot = tot + z
print tot
vocal gorge
#

technically the print can be indented to somewhere but yeah, that's the most likely indentation

quasi oracle
#

I knew the "only way" would come back to bite me

dawn cliff
#

This is also from my test

haughty mountain
#

11 hours of nothing

dawn cliff
#

but its not even on there

haughty mountain
#

I agree the question is atrocious, but isn't the answer just 0 1 2?

dawn cliff
#

Oh I didn't see the n = 2

#

yeah it's literally one single loop at that point

#

you might as well just have one for loop with i = 2 at the top

haughty mountain
#

for n=2 it just reduces to

for (j=0; i <= n; j++) {
  display j;
}
dawn cliff
#

Oh you're right

lean walrus
ornate rover
#

hey guys

fiery cosmos
fiery cosmos
#

instead of o(n^3), it would be o(1)

stray fractal
#

is there a way to factorially distribute a number's prime factors

#

i don't know what i'm saying

#

sf(6) (super-factorial) is 1!2!3!4!5!6! = 24883200 = 1 * 1 * 2 * 1 * 2 * 3 * 1 * 2 * 3 * 4 * 1 * 2 * 3 * 4 * 5 * 1 * 2 * 3 * 4 * 5 * 6 or just 2 * 2 * 2 * 2 * 2 * 3 * 3 * 3 * 3 * 4 * 4 * 4 * 5 * 5 * 6 whose prime factors are 12 2's, 5 3's, and 2 5's

#

distribute it so that the number of consecutive numbers are consecutively descending

vocal gorge
#

distribute what?

stray fractal
#

the factors

#

basically make consecutive factors from prime factors

#

whose counts are consecutively descending the higher the factor

vocal gorge
#

like, rearrange {2: 12, 3: 5, 5: 2} into {2: 5, 3: 4, 4: 3, 5: 2, 6: 1}?

stray fractal
#

yea

minor torrent
#

hey imagine the user inputs the command : "go to desktop 5" now i will have match/ifelse to find go to desktop in string
then i need to find the number 5. any good way to get this values?

dawn nest
#

Can anyone suggest a good free DSA course in python

fiery forge
#

How can I make my code quicker/more efficient?
There are n people standing in a line: person 1, person 2, ..., person n
You are given the arrangement of the people as a sequence a[] of length n where i-th element (1-indexed) represents the following information:
-- if it equals -1 then person i is at the front of the line
-- if not, i.e. it equals x then person x is in front of person i
The task is to print the people's numbers in the line from front to back
See example below:

Example 1:
liningUp(6, [4, 1, -1, 5, 3, 2])
Output 1:
3 5 4 1 2 6

Example 2:
liningUp(10, [-1, 1, 2, 3, 4, 5, 6, 7, 8, 9])
Output 2:
1 2 3 4 5 6 7 8 9 10

Example 3:
liningUp(30, [3, 25, 20, 6, 18, 12, 26, 1, 29, -1, 21, 17, 23, 9, 8, 30, 10, 15, 22, 27, 4, 13, 5, 11, 16, 24, 28, 2, 19, 7])
Output 3:
10 17 12 6 4 21 11 24 26 7 30 16 25 2 28 27 20 3 1 8 15 18 5 23 13 22 19 29 9 14

def liningUp(n, a):
new = []
last = -1
for item in a:
last = (a.index(last)+1)
new.append(last)
print(new)

quasi oracle
quasi oracle
# fiery forge How can I make my code quicker/more efficient? There are n people standing in ...

The first step is understanding why your code might be inefficient. Looking at it, I see a loop over N items, and each iteration does a.index(last) which is O(N) each. So O(N^2) in total. So the first thing I try to think of is whether I can get the order in a single pass over the list instead, or at least a constant number of single passes.

It takes some practice to recognize what might be helpful here, but my intuition looking at the problem is that I don't know immediately the absolute position of a person, only who is in front of them. If I could construct a "bridge" between a person and the one behind him, I could go over the list once to construct the bridges, and then just walk the bridges, starting with the person who had -1, to get the right order.

dark current
#

how can i link a def file to a python file?

#

for example i have a file with print_main_menus(): and i want to use that file with my current python file with all the elif statements

ornate rover
#

omgggg

#

Option 1:  all arriving passengers are placed in a single queue, and service stations take passengers from the front of that queue.

Option 2:  each service station has its own queue, and arriving passengers are dispatched to a queue according to one of many policies:

2.A:  round robin (1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, ...).

2.B:  arriving passenger is placed in a shortest queue.

2.C:  arriving passenger is placed in a random queue.

 Inputs to the simulation:
The duration of the simulation measured in minutes (D:  make it arbitrarily long, do not worry about it being or not being realistic).
The average arrival rate measured in minutes (A:  arrivals are random, but on average there is one new passenger every A minutes), 
The average service rate measured in minutes (S:  service rates are random, but on average they need about S minutes of service).
For the sake of this study, make sure to crowd the system, by choosing S >> 5*A, without causing an overflow of your queues.  Also choose D to be long enough to get rid of any transitory effects.

 Outputs of the Simulation for each queuing policy:
The duration of the simulation (which may be longer than the input parameter, as when check-in closes, there may be passengers in the waiting queues and service stations).
The maximum length of the queue for each queue.
The average and maximum waiting time for each queue.
The rate of occupancy of each service station (percentage of time each station was busy).
If you want: show the real-time evolution of the queues during the run-time simulation.
#

so this is the question I am working on 😄

#
import random


class Customer:
    def __init__(self, arrival_time):
        self.arrival_time = arrival_time
        self.service_start_time = None
        self.service_end_time = None
        self.service_time = None


class ServiceCounter:
    def __init__(self):
        self.queue = []


class QueueSimulation:
    def __init__(self, duration, arrival_rate, service_rate):
        self.duration = duration
        self.arrival_rate = arrival_rate
        self.service_rate = service_rate
        self.service_counter = [ServiceCounter() for _ in range(0, 5)]
        self.customers = []

    def queue_policies(self, policy):
        current_time = 0

        while current_time < self.duration:
            if random.random() < 1 / self.arrival_rate:
                arrival_time = current_time
                customer = Customer(arrival_time)
                self.customers.append(customer)

                if policy == "1":
self.service_counter[0].queue.append(customer)
                elif policy == "2A":
                    round_robin = len(self.customers) % 5
                    self.service_counter[round_robin].queue.append(customer)
                elif queuing_policy == "2B":
                    shortest_queue = min(self.service_counter, key=lambda counter: len(counter.queue))
                    shortest_queue.queue.append(passenger)
                elif queuing_policy == "2C":
                    random_counter = random.choice(self.service_counter)
                    random_counter.queue.append(passenger)
#

am I going in the right direction?

cinder maple
#

I’m trying to learn insertion sort

#

is it swapping the elements ?

#

in line 6 i feel like a[j] and a[j+1] have the same value

naive oak
# cinder maple is it swapping the elements ?

it doesn't swap the elements
insertion sort needs to shift the elements up the list to insert the new element into the sorted subarray, so it does that by progressively rewriting elements until it gets to the place the element belongs
an example of one insertion might help

1 5 6 8 9 7

we're trying to insert 7 into the sorted subarray 1 5 6 8 9
the insertion would look like

1 5 6 8 9 7
1 5 6 8 9 9
1 5 6 8 8 9
at this point A[j] is 6, which isn't larger than 7, so we stop and assign 7 to A[j+1]
1 5 6 7 8 9
cinder maple
#

other than rewriting each time, can we just push the index of every element right of it and place wherever nessecary?

#

1 5 6 8 9 // insert 7 into array

1 5 6 8 9

15 6 7 8 9

narrow mica
cinder maple
#

if there are n elements

#

n-i elements are already sorted

narrow mica
narrow mica
cinder maple
#

Can i just randomly say?

#

idk if it’s correct

narrow mica
#

yea go ahead

cinder maple
#

I’ll first use a for loop to check what index to should be replaced

latent cairn
#

i know i know , can i tell can i tell

#

btw i tried it using heap sort but can't get it working , can write a code for the previous one bro?

narrow mica
latent cairn
#

haha

cinder maple
#

ie i’ll use such a for loop until the spot to be replaced

#

I suppose

narrow mica
cinder maple
#

I can make it more general if i get more time ig

narrow mica
cinder maple
#

I see

#

Essentially both are same

#

one use a for loop, while other does on the go

#

What is a more better way to sort?

narrow mica
#

Faster algorithms like quick sort, merge sort, heap sort, are O(n log n) algorithms, and you can't really do much better than that without losing generality

cinder maple
#

@narrow mica

narrow mica
#

ye?

cinder maple
#

O(n(n+1)/2)

#

can this be the worst case of insertion?

narrow mica
#

I think so

#

the worst case is a reverse list no?

cinder maple
#

I suppose the worst case is descending for asc algorithm

#

so n+ (n-1)+ (n-2) + …+ 3 + 2+ 1

narrow mica
cinder maple
#

so the exact number of iterations is not really a matter?

#

im a beginner

narrow mica
#

Time complexity measures how well an algorithm scales, it doesn't care about actual run time

#

O(n^2 / 10000000000) is the same as O(1000000000000000 * n^2)

cinder maple
#

oh

#

Big Oh

narrow mica
#

What "better time complexity" really means is that given a big enough input, one algorithm with better complexity will run better than the other
How big is "big enough" depends on the algo themselves

cinder maple
#

I recall now, the function inside should be a scalar multiple for all n>n0, for some n_0

#

$f(n)= O(g(n))$ , if $f(n)= c* g(n)$, whenever $n \geq n_0$

#

We don’t have TeXit here?

narrow mica
#

There's a bot command, I don't use it though idk what it is
found it, .latex

#

.latex $f(n)= O(g(n))$ , if $f(n)= c* g(n)$, whenever $n \geq n_0$

grand havenBOT
cinder maple
#

Is this the same thing you were mentioning?

#

I suppose yes

narrow mica
#

It's a more mathy way, but otherwise yes

cinder maple
#

Idk have cs background

#

trying to learn stuff

narrow mica
#

You don't really need all the mathy stuff to under stand time complexity though
Just remember that it measures how well something scales, not how well it runs

cinder maple
#

Makes sense

narrow mica
#

In fact, there are a whole set of "galactic algorithms" that have great time complexity, but the constants are so big they're never used in practice

fiery forge
cinder maple
#

Why does bogosort has its name?

#

is it a meme? idk

#

maybe from the word ‘bogus’

dark current
#

Given an array of size N containing only 0s, 1s, and 2s; sort the array in ascending order.

Example 1:

Input:
N = 5
arr[]= {0 2 1 2 0}
Output:
0 0 1 2 2
Explanation:
0s 1s and 2s are segregated
into ascending order.
Example 2:

Input:
N = 3
arr[] = {0 1 0}
Output:
0 0 1
Explanation:
0s 1s and 2s are segregated
into ascending order.

Your Task:
You don't need to read input or print anything. Your task is to complete the function sort012() that takes an array arr and N as input parameters and sorts the array in-place.

#

i don't understand this.

narrow mica
dark current
#

don't understand where to start.

#

this is my homework assignment, and i've never played with sort() before

narrow mica
#

Well it's pretty simple to use

my_list = [ ... ] 
sorted_list = sort(my_list)
```Though I'm 90% sure that this isn't what they want you to do
dark current
#

oh, what are they askin gme to do?

narrow mica
dark current
#

so i should asort the numbers and assign them to the self,arr,n

narrow mica
dark current
#

okay ill try to work this through

narrow mica
#

Try and think about how you can (ab)use the fact that you only get 0s 1s and 2s

dark current
#

hmm okay

#

this whole coding thing is confusing to me

#

all the syntax, rules, parameters, and my class room is moving so fast

#

class Solution:
def sort012(self, arr, n):
low = 0
mid = 0
high = n - 1

    while mid <= high:
        if arr[mid] == 0:
            arr[low], arr[mid] = arr[mid], arr[low]
            low += 1
            mid += 1
        elif arr[mid] == 1:
            mid += 1
        else:
            arr[mid], arr[high] = arr[high], arr[mid]
            high -= 1
#

i tried this, and it's saying

Runtime Error
Test Cases Passed:
0 /35
For Input:
65754
2 0 2 0 0 1 2 2 2 1 1 0 1 1 1 2 0 1 2 1 0 1 2 0 0 0 2 0 1 0 0 0 1 2 1 1 1 2 1 2 1 2 2 1 1 2 0 2 0 0 1 2 1 2 1 1 2 1 2 0 0 1 0 2 1 1 2 0 2 0 1 2 2 2 2 1 0 1 2 2 0 1 1 1 0 1 2 0 0 2 1 0 0 2 2 1 0 .................
Input is too large Download Full File
Your Output:
File "/home/014629319a406e51cb768a7745e673f1.py", line 15
elif arr[mid]] == 1
^
SyntaxError: invalid syntax

Its Correct output is:
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 .................

latent cairn
dark current
wispy tinsel
fiery remnant
#

good resources to learn dsa in python?

fervent light
#

if u want to call one class method from another, whats the proper way of doing it?

keen hearth
fervent light
#

i guess cls is a reference to the class, so what katy said does make sense in python discussion

keen hearth
#

Oh right. Just access the other class method as an attribute of cls, assuming you mean two class methods within the same class?

fervent light
fervent light
#

i see...

#

so cls is a reference to the class

#

that reference calls its a attribute

#

and it gets passed as the first parameter

keen hearth
#
class C:
    @classmethod
    def a(cls):
        ...

    @classmethod
    def b(cls):
        cls.a()
fervent light
#

i see, cool, thanks for the help

keen hearth
haughty mountain
fiery remnant
#

Alright 👍🏼

cinder maple