#algos-and-data-structs

1 messages · Page 150 of 1

haughty mountain
#

maybe it could make sense phrasing it like: if I expected the direction to be CCW/CW, how well does that match the data?

#

and then come up with some sensible scoring

#

it allows you to more sensibly model 2s if you want to

#

my suggested naive approach would score by treating 2s as zeroes and basically just sum everything up (+ a sign change in relevant scenarios)

random crater
#

Yes yes I think this is staring to make sense. The mod also helps me comprehend the cyclical nature too. I was way overcomplicating it to try and get the cycle effect. I'll give it a few implementations. I think I have a general idea of extrapolating it into more complex scenarios. Thank you!

haughty mountain
#

Finding the right way to model things tends to simplify the problem a bunch 🙂

random crater
#

Indeed :) The actual use case has a lot more pieces, but this model makes it like 1000x easier to comprehend

haughty mountain
#

having it constrained to only 4 options does also make the problem more annoying than if it was a real value representing the direction

#

because of the case where you have +-2 which you can't easily say too much about

random crater
#

Well the values are actually 8, with the 45 degrees incorporated. In terms of understanding, I limited it to 4 but in 8 directions, the 2 isn't as glaring of an issue

#

And ultimately it should be able to be extrapolated to any amount, ideally

haughty mountain
#

8 feels like a nicer problem to deal with, yes

burnt trellis
#

does anyone have issues running this code ?

#
import numpy as np
from matplotlib import pyplot as plt

arr = np.zeros(10*10).reshape(10,10)

plt.imshow(arr)
plt.show()
#

whenever i run it the matplotlib pyplot starts glitching out a lot whenever i put my mouse on the plot itsself

random crater
#

This is a jupyter notebook though

burnt trellis
#

this is what i get when my mouse isnt on the plot

#

this is what happens when i put my mouse on it

#

ive been getting this with maplotlib plots for a long time rn

#

i have no idea if theres anything wrong with the code or with me

#

im not sure if this is the correct channel to ask this in , i tried with the help channels but no one responded 2 times in a row so ill try here

haughty mountain
burnt trellis
#

yea it looks fine, i can try to record a video of it or smth, it just glitches non stop when i put my mouse on the actual plot

haughty mountain
#

fwiw we probably have very different setups

#

what os are you on? windows/linux/other?

burnt trellis
#

ye, im on a laptop

#

windows 10

haughty mountain
#

you could try switching the matplotlib backend to see if that helps

#
import matplotlib
matplotlib.use(<some backend>)
#

though idk how many would work on windows without installing some extra dependencies

jolly mortar
#

given a list A of N ints and a target K, how do you select upto 3 elements from A such that their sum is minimum, but above K

#

the obvious n^3 solution was good enough to pass the time limits but surely there are better ways

haughty mountain
#

I mean, without thinking much O(n^2 log n) is trivial, all possible sums and look up in a sorted array

#

improving that to O(n^2) should also be easy enough, create sums in increasing orders, lookup the last element in decreasing order (so keep two pointers/indices, one goes strictly up, one goes strictly down

#

err, at least I think creating the sums in increasing order should be doable pithink

#

how big is K?

jolly mortar
#

hm i cant see the problem statement anymore now

#

why does it matter?

haughty mountain
#

if it's not so large you can consider options that scale in K

#

e.g. some variation of the classic dp for the subset sum problem

jolly mortar
#

alright ill look into those, thanks for the ideas

dark aurora
#

"If a = b, do not do anything, because the subarray is already sorted." -it says for the merge sort algorithm, but what if the subarry looks like this [3, 4, 5, 2, 3] here a=b will be the same but the subarray won't be sorted? - this is from andri laaksonen's book

#

So I am planning when finishing a theme in the textbook, solving most cses tasks (for that theme) and also finding other tasks from the same theme in my local competition, SPOJ, Usaco etc... Is that fine

turbid stream
#

hi guys can you see if my webpage works make a bookmark with the following link and go to a blocked page for it to work:converts characters into a format that can be transmitted over the Internet.

stark rapids
#

guys this was a question from daily codinng questions and can you guys help me solve this:

#

pls help

fervent saddle
#

You could try to make a ternary search tree

#

Or a trie if it wants O(n)

#

IIRC that’s how this problem is solved

dark bear
#

Hi Everyone, this is my solution to a program on code wars but I dont understand why Im getting it wrong. Problem: In this kata you are required to, given a string, replace every letter with its position in the alphabet.
If anything in the text isn't a letter, ignore it and don't return it. ```def alphabet_position(text):
if text == "":
return ""

alphabet: dict = {'a':1,'b':2,'c':3,'d':4,'e':5,'f':6,'g':7,'h':8,'i':9,'j':10,'k':11,'l':12,'m':13,'n':14,'o':15,'p':16,
                  'q':17,'r':18,'s':19,'t':20,'u':21,'v':22,'w':23,'x':24,'y':25,'z':26}
result = ""
for letter in text.lower():
    if letter in alphabet.keys():
        result  += str(alphabet[letter])
        result += " "
        
print(result)
return result ```
fervent saddle
#

You aren’t adding the non alphabet characters, and you’re adding spaces too

halcyon comet
austere shell
#

Hi i have to find median of K numbers and everytime i find it new number will come up so I need to find the new median again (and it must be in O(log n) for operation) and i found this article that has the same question but im not sure the answer is right, so if just someone could tell me if the first answer is right. thx https://stackoverflow.com/questions/7842347/find-median-in-olog-n

haughty mountain
# fervent saddle Or a trie if it wants O(n)

A trie is the obvious solution, yeah. Especially if you want to have quick inserts.

Other fun solutions is storing things sorted is another option, if you write rarely you can just store the data sorted, some simple file formats like sstables does this to store key value pairs. If you do updates then a BBST would also work.

I guess in the end a trie is also storing things sorted, you could call it a radix sort tree, even

spare parcel
#

hi guys how would you start with this question given two lists, list_1 = [a, b, c, d, e] list_2 = [x, y, z, k] return all combination of length 4 containing elements from both lists

haughty mountain
#

reduce it to the problems of picking k items from list_1 and 4-k from list_2?

#

I'm assuming you need to pick at least one from each list? Otherwise the question is silly

spare parcel
#

yes

#

i m thinking i will need all conditions of picking 3, picking 2, and pick 1

#

from list 1

#

and do the same for other list

#

then just append

#

3 from list 1, 1 from list 2

#

for the case of 2 from both list

#

will have to run combination again

spare parcel
#

i think i m leaning on discrete cases

haughty mountain
spare parcel
#

what if these imports cant be used?

haughty mountain
#

some recursive implementation, I guess

spare parcel
#

halp

#

i m not even covering all conditions even with the imports

#

something like this eh

haughty mountain
# spare parcel something like this eh

yes, that's the kind of thing I meant, you can make it a generator which makes things neat and tidy

from itertools import combinations

def pick_4(list_1, list_2):
  for k in range(1, 4):
    for comb_1 in combinations(list_1, k):
      for comb_2 in combinations(list_2, 4 - k):
        yield comb_1 + comb_2

for x in pick_4([1, 2, 3, 4], [5, 6, 7]):
  print(x)
spare parcel
#

tyty

#

what if its combo with repetition

#

like, [1, 1, 1, 5] is valid

haughty mountain
#

itertools.combinations_with_replacement

spare parcel
#

yah..

haughty mountain
#

it's not terribly hard to write these things yourself, it's just annoying and they have a bunch of edge cases

spare parcel
#

im trying to write it myself lol

#

not so good with recursion

#

trying to change this into take input as two list

haughty mountain
#

e.g. here is a simple implementation on combinations

from itertools import combinations

def my_combinations(inp, k):
  def pick(picked, next_valid):
    if len(picked) == k:
      yield tuple(picked)
      return
    for i in range(next_valid, len(inp)):
      picked.append(inp[i])
      yield from pick(picked, i + 1)
      picked.pop()
  return pick([], 0)

def pick_4(list_1, list_2):
  for k in range(1, 4):
    for comb_1 in combinations(list_1, k):
      for comb_2 in combinations(list_2, 4 - k):
        yield comb_1 + comb_2

def my_pick_4(list_1, list_2):
  for k in range(1, 4):
    for comb_1 in my_combinations(list_1, k):
      for comb_2 in my_combinations(list_2, 4 - k):
        yield comb_1 + comb_2

a = sorted(pick_4([1, 2, 3, 4], [5, 6, 7]))
b = sorted(my_pick_4([1, 2, 3, 4], [5, 6, 7]))
print(a == b)
#

I make a nested function just to make things cleaner for the caller

#

Changing my_combinations to allow repetitions is just a small change to that

#

one change to one line, I think

spare parcel
#

ty man

#

i hate this prob lol

#

wat are these two lines doing

haughty mountain
fiery cosmos
#

hey guys, do you know how to remove this text inside / / with / in python?````
text /WANT TO REMOVE IT/ text```

fiery cosmos
fiery cosmos
lament totem
#

Each position is either ( or ), so that's just 2^n

fiery cosmos
#

I guess it's just a weird writeup... because O(2^(2n)*n) is just O(2^n) anyway I think

glossy breach
#

The statement gives you n pair of parentheses

#

So the length of the sequence should be 2n

#

👀

fiery cosmos
glossy breach
#

Yeah its (2^n)^2

#

Its like comparing n to n^2

fiery cosmos
#

right thanks, my rusty math
if anyone has insight to the 2^2n part please let me know

fiery cosmos
#

alternatively think of ( as 0 and ) as 1 and note that a m-bit binary number can take 2^m values (m = 2n here)

#

ooooh I get it thank you

#

n is the number of pairs not the length of it

#

yeh

haughty mountain
#

number of valid bracket would be the catalan numbers iirc

warm snow
#
  File "C:\Users\user\Desktop\python\linkedlist.py", line 39, in <module>
    my_list.insert_beggining(1)
  File "C:\Users\user\Desktop\python\linkedlist.py", line 11, in insert_beggining
    node=Node(data, self.head)
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given```
#
class Node:
    def __init__(self,data=None):
        self.data = data
        self.node = next

class Linked_list:
    def __init__(self):
        self.head = Node()

    def insert_beggining(self,data):
        node=Node(data, self.head)
        self.head = node

    def insert_end(self,data):
        node=Node(data)
        cur=self.head
        while cur.next!=None:
            cur=cur.next
        cur.next=node

    def length(self):
        cur=self.head
        total=0
        while cur.next!=None:
            total+=1
            cur=cur.next
        return total 

    def display(self):
        elems = []
        cur=self.head
        while cur.next!=None:
            cur=cur.next
            elems.append(cur.data)

        print(elems)

my_list = Linked_list()
my_list.insert_beggining(1)
my_list.display
#

on this code

#

can anyone help

haughty mountain
warm snow
#

done it

#

next = none\

#
class Node:
    def __init__(self,data=None,next=None):
        self.data = data
        self.node = next

class Linked_list:
    def __init__(self):
        self.head = Node()

    def insert_beggining(self,data):
        node=Node(data, self.head)
        self.head = node

    def insert_end(self,data):
        node=Node(data)
        cur=self.head
        while cur.next!=None:
            cur=cur.next
        cur.next=node

    def length(self):
        cur=self.head
        total=0
        while cur.next!=None:
            total+=1
            cur=cur.next
        return total

    def display(self):
        if self.head is None:
            print('this linked list is blank')
            return

        current = self.head
        llist = ''
        while current:
            llist += str(current.data) + '--->'
            current = current.next
        print(llist)


ll = Linked_list
ll.insert_beggining(5)
ll.display()```
#

the insert beggining is not working\

#

TypeError: insert_beggining() missing 1 required positional argument: 'data'

orchid laurel
#

insert_beginning needs the parameter self

#

because its part of the class

#

oh wait

warm snow
#

i putted 5

orchid laurel
#

yeah just saw my bad

#

oh wait

#

data needs to be self.data

warm snow
#

where

#

oh okay

#

wait

#

why though

orchid laurel
#

node=Node(data, self.head)

#

because it is in a class

warm snow
#

????

orchid laurel
#

its the classes data, and variables in classes must have self

#

i found it weird too but thats the way it is

warm snow
#

got the same problem

#

TypeError: insert_beggining() missing 1 required positional argument: 'data'

#

i did what u asked

#

got the same problem

orchid laurel
#

oh hold on

#

keep what i said

#

try ll = Linked_list()

#

did it work?

warm snow
#

yes

#

thanks

haughty mountain
# orchid laurel i found it weird too but thats the way it is

it must know whether it's a local value or a member of the class, python uses self to make references to class members explicit, this is especially important since python wouldn't have any clue if x = 3 meant to create a local variable or to assign to a member of the class. Unlike other langs, python has no way to tell the different types assignments apart. E.g. in C++ it's optional to use this when referring to class members, but C++ also has variable declaration syntax which makes that possible

#

in shory, python as designed can't distinguish between these two concepts in C++:

struct Bleh {
  Bleh() {
    // these two refer to the class member
    // i.e. the this usage is optional
    x = 0;
    this->x = 0;
    // this creates a new local variable
    int x = 0;
  }
  int x;
}
still mural
#

Ignore

simple leaf
#

Hey guys, I need a simple algorithm, that given a deck of cards (for example, user input would be - 4,2,king,9,queen) will sort it ascending values, can anyone do that for me real quick?

muted thorn
#

Hey guys, how do i make terminal usable after running python script. it's code editor and it prevents the use of this terminal

muted thorn
#

okay but i wont to program working and make this terminal where it was executed usable, not to stop working code

quick anvil
#

u can't just do two processes simultaneously on a single terminal shell

agile sundial
#

can't you run things in the background

smoky dew
lilac minnow
#

Is list.getitem O(n) or O(1)?

agile sundial
#

O(1)

lilac minnow
#

Okay, thanks

ivory copper
#

Can someone help me in #help-bagel? It's somewhat related to data structs, at least the graph part

oak timber
#

I needed a place to post this, couldn't find a better place. But I wrote a script to dynamically populated data into an excel spreadsheet from nested dictionaries and I'm pretty damn proud of it. Coding under a year.

def insert_data(nested_data):

        # Iterate over dict into team str and dict
    for team_key, nested_dict in nested_data.items():
            # Iterate over nested dict into col str and entry data
        for col_key, entry_data in nested_dict.items():
                # Iterate over rows in worksheet
            for i in range(1, ws_daily.max_row+1):
                    # iterate over cells in row
                for cell_in_rows in ws_daily[i]:
                        # If cell in row contains team_key
                    if cell_in_rows.value == team_key:
                            # set row 
                        row = cell_in_rows.row
                            # iterate over cells in row
                        for cell in ws_daily[row]:
                                # iterate over columns of each cell in row
                            for cell in ws_daily[cell.column]:
                                    # If a cell in a column contains
                                if (cell.value == col_key):
                                    col_let = get_column_letter(cell.column)
                                        # convert target cell to LetterNumber string
                                    cell_target = str(f"{col_let}{row}")
                                        # Insert data into cell.
                                    ws_daily[cell_target] = entry_data

    return
#

Context, this is for automating report compilation into a single excel spreadsheet from a bunch of sources.

fiery cosmos
feral trail
#

Hey guys I recently read google's internship interview question this year. So given a 2d binary matrix with N lines, with each lines you can invert it if you want, find the maximum number of identical line possible

#

So for example

[
[0,1,1]
[1,1,0]
[1,1,1]
[0,1,1]
]

then the answer would be 3

#

since we can make 3 [0,1,1] or [1,1,0]

#

I'm thinking of using a map to store each lines then count

haughty mountain
#

what does invert mean in this case?

feral trail
#

Basicallly [::-1]

haughty mountain
#

so reverse

feral trail
#

yep

haughty mountain
#

invert sounds like swapping ones with zeroes, like bit inverse

feral trail
#

O(n^2) would be easy but that sounds horrible

#

Yeah I guess reverse is the better word here mb

haughty mountain
#

also, why is the answer 3 in your case?

feral trail
#

Mb I wrote wrong

haughty mountain
#

there are two groups of identical elements, no?

feral trail
#

The third row is supposed to be different

haughty mountain
#

ah

#

when you say n^2, isn't that just the cost of looking at all the elements in the matrix?

#

or, I guess n*m

#

n = number of lines, m = number of columns

#

or did you mean O(n² m)

haughty mountain
feral trail
#

I don't have the link but I think I have screenshot

#

Give me a secx

#

Here it is

#

My bad the guy who took it said he wasn't allowed to ctrl P the page or screenshot

#

idk why the quality is so horrible tho

#

It looks good before I uploaded it

#

Open original makes it good quality again

plucky cedar
#

so the invert operation could only be applied once?

#

and the cell changing to opposite k times in the entire matrix?

elder comet
#

hi

feral trail
#

Or invert a column K times

haughty mountain
#

and invert in this case means flipping all 0s to 1s (and vice versa)

feral trail
#

And yeah it was inverted, I remembered it wrong somehow

haughty mountain
#

I think grouping elements if they are related by an inversion is a good first step. After that point you can go through the groups and see what you can accomplish with your K inversions

feral trail
#

I see... But how do we group elements together? Do we use itertools to remember indexes of the group that are related by inversion for example?

haughty mountain
zenith axle
#

Good evening
Can someone explain to me how a recursive function works?, question in the help-burrito Help Channel

oak timber
fiery cosmos
oak timber
fiery cosmos
#

yeah

oak timber
#

Thanks a ton, I'll play around with that and see where I can break my code and... not break it 🙂

gloomy mason
#

can someone help me make a function that lets u insert some data after a certain value in a linked list

gloomy mason
#

no sir

fallen fulcrum
#

hi!

#

I'm having trouble with some basic nparray manipulation

#

x_test.shape # (10000, 28, 28)

#

x_test[:1].shape # (1, 28, 28)

#

What does x_test[:1] do?

#

what I want is xtest[53] (which has shape (28, 28) ) but to be shape (1, 28, 28) like above

#

actually I just figured it out. TY!

dark cedar
#

highest_salaries = salary.sort_values(by='salary', ascending=False)
eighth_highest_salary = tenpaid.get['salary'].index[9]
eighth_player_name = tenpaid.get['name'].index[9]
print('Player:', eighth_player_name, '\nSalary:', eighth_highest_salary)

#

what is the issue in this code

frail lava
#

Good morning
Can anyone explain me how can I replace every 3rd item in a list?

thin parcel
#
def mergeSort(array):
    if len(array) == 1:
        return array
    middleIdx = len(array) // 2
    leftHalf = array[:middleIdx]
    rightHalf = array[middleIdx:]
    return mergerSortHelper(array, mergeSort(leftHalf), mergeSort(rightHalf))

def mergerSortHelper(array, leftHalf, rightHalf):
    sortedArray = [None] * (len(leftHalf) + len(rightHalf))
    i = j = k = 0
    while i < len(leftHalf) and j < len(rightHalf):
        if leftHalf[i] <= rightHalf[j]:
            sortedArray[k] = leftHalf[i]        
            i += 1
        else:
            sortedArray[k] = rightHalf[j]
            j += 1
        k += 1
    while i < len(leftHalf):
        sortedArray[k] = leftHalf[i]
        i += 1
        k += 1
    while j < len(rightHalf):
        sortedArray[k] = rightHalf[j]
        j += 1
        k += 1
    return sortedArray

Can someone help me with this code, what I want to do is I want to access the index of elements that are being compared and swapped, I tried out many things but I failed, can someone help ? This is merge sort code btw.

haughty mountain
#

it seems to work on the one list I tries throwing at it

#

the code could be tidied up, e.g. removing the array and not using a k and appending instead, but that's not a correctness issue

def mergeSort(array):
    if len(array) == 1:
        return array
    middleIdx = len(array) // 2
    leftHalf = array[:middleIdx]
    rightHalf = array[middleIdx:]
    return merge(mergeSort(leftHalf), mergeSort(rightHalf))

def merge(leftHalf, rightHalf):
    sortedArray = []
    i = j = 0
    while i < len(leftHalf) and j < len(rightHalf):
        if leftHalf[i] <= rightHalf[j]:
            sortedArray.append(leftHalf[i])
            i += 1
        else:
            sortedArray.append(rightHalf[j])
            j += 1
    sortedArray += leftHalf[i:]
    sortedArray += rightHalf[j:]
    return sortedArray
halcyon plankBOT
#

Hey @fiery cosmos!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

solemn solstice
#

hi, is this the right channel to ask smth. about the pyparsing-package ?

toxic locust
#

I have a health score that decays over time, that is when a user reads the score, the initial score and a time stamp for when it was last set are read from the database, then a simple decay algorithm calculates the current score as function of the time elapsed between now and the time stamp. So far, so good that part is easy.
Intermittently the user can take certain actions that will change the score either increasing or decreasing it, or in an extreme case set it to 0. Changes to score will result in a setting of a new value in the database. Whereas the "decayed score" is calculated in real-time and the value displayed is not written to the database. This is done because the score is displayed on a public (no auth required) web-page and I only allow state changing actions for authenticated users.
Updating the score: To update the score, I would calculate the "decayed score" increment or decrement the value as needed and then save that value, with a new time stamp to the DB.
My question is, do I need to keep memory of the past score values and time stamps. Should I save the data in an array? I'm using Mongodb, so it would be JSON, array of dicts:
[{score:10, ts: 1654986544},...]
or is the last score and ts sufficient?
As I write this post I realize that the question is almost hypothetical as it really depends on whether I would have other needs for the data. So then more generally, is this a suitable method for keeping such a score are there any set patterns for this type of thing?

frank vault
#

what's the time complexity of the in operator between strings?

#

substring in string

#

is the same as string.find(substring)?

runic tinsel
#

linear

#

sure

frank vault
#

O(n) where n = |string|?

#

or O(n + m) where m = |substring|

runic tinsel
#

actually i don't know

#

because e.g. "ssssm" in "ssssssssssssss" could take about nm

#

but there's no reason it would be worse than find

frank vault
#

I think it depends on the algorithm

#

but I don't know how to browse the CPython source code to look for that

frank vault
#

this means that it's not needed to implement a KMP or Two Way by ourselves right

#

we can just call the Python builtin operators

ionic meteor
#

Why is this runtime not O(n)?

twilit heron
#

How can I count the number of terns (three consecutive values) of positive and negative numbers in a list of numbers?

shut breach
# ionic meteor

it would have to be spending only constant time in each iteration of the for loop for it to be O(n)

shut breach
ionic meteor
shut breach
# ionic meteor

on every iteration, twiddle-thumbs takes longer to execute

ionic meteor
#

Hmmm

shut breach
#

so squander-time is Theta((n+n^2)/2) == Theta(n^2)
which is big-O of everything bigger than it

ionic meteor
#

From the n(n+1)/2 formula right

shut breach
#

Gaussian formula

#

it comes up in these nested loops often

ionic meteor
shut breach
ionic meteor
#

Gotcha

#

Ty

twilit heron
shut breach
fiery cosmos
twilit heron
shut breach
#

what is i?

twilit heron
shut breach
#

when is it less than 0?

twilit heron
#

ahhhhhhhhhhhh

#

Ingrese una temperatura distinta de cero: -2
Ingrese una temperatura distinta de cero: 1
Ingrese una temperatura distinta de cero: 3
Ingrese una temperatura distinta de cero: -2
Ingrese una temperatura distinta de cero: -3
Ingrese una temperatura distinta de cero: -3
Ingrese una temperatura distinta de cero: -4
Ingrese una temperatura distinta de cero: 5
Ingrese una temperatura distinta de cero: 6
Ingrese una temperatura distinta de cero: -2
Ingrese una temperatura distinta de cero: -4
Ingrese una temperatura distinta de cero: 6
Ingrese una temperatura distinta de cero: -3
Ingrese una temperatura distinta de cero: -4
Ingrese una temperatura distinta de cero: -5
Ingrese una temperatura distinta de cero: 7
Ingrese una temperatura distinta de cero: 8
Ingrese una temperatura distinta de cero: -2
Traceback (most recent call last):
File "C:\Users\lucio\AppData\Roaming\JetBrains\PyCharm2021.3\scratches\scratch.py", line 21, in <module>
if valores[i+1] < 0 and valores[i+2] < 0:
IndexError: list index out of range

#

hmm

#

not good yet

#
for i in range(len(numbers)):
    if i < 0:
        if numbers[i+1] < 0 and numbers[i+2] < 0:
            negative_terns += 1
#

Ah, the complete exercise is:

#

Enter 18 non-zero temperature values. You are asked to determine and report how many terns (three values in a row) of positive and how many negatives values there are.

shut breach
#

so you'll have to look at positive numbers too

agile sundial
#

and you need numbers[i] in the first if

toxic jacinth
#

Is Traveling Salesman Problem Simulated Annealing = Artificial Intelligence?

haughty mountain
#

what kind of question is that even? no

past vale
#

Does anybody know about the traveling salesman problem with restricted maximum travel distance without returning to the certain node?

#

Said Agent is a drone and needs to recharge at a certain point which is a moving truck.

lofty meadow
#

In highschool the salesman never hit the same node twice

#

sorry, im a newb, i just loved that class and got excited, i have nothing to contribute

#

dont even know how you'd formulate a moving point into X!

#

crunch every single series including truck current location until it hit max, then use min distance that includes all x? The formula will be similar to a layover formula

lament shale
#

class Solution:
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
my_dict = {}
for i in nums:
if i not in my_dict:
my_dict[i] = 1
else:
my_dict[i] += 1
sort_dict = sorted(my_dict.items(), key=lambda x: x[1], reverse=True)
ans = list()
for i in range(k):
ans.append(sort_dict[i][0])
return ans

#####################
Can anyone suggest me a better way to sort the dictionary using the values without using built in functions?
Above solution in for Leetcode Problem 347.

past vale
#

No idea what the hell is the latter one and I didn't understand despite reading a ton of things

#

Some actually uses genetic algorithm where the route is the chromosome with randomly added truck-node genes

past vale
#

This is a combinotorial problem O(n!) actually takes giant time really

past vale
#

There is no better way to sort dictionary once you have entered the values. Maybe you will get a tiny amount of up from finding a better sort algorithm.

#

The percentile changes with each submission :\

lofty meadow
#

@past vale I'm only just learning python, my coding isn't fluent but I think about the problem like this, you have points abcde

#

hmmm having trouble with the code but basically start by trying to deliver each payload and returning

#

then fewer stops and returning

#

until you have a route that allows for recharge

#

find each route then determine the most effective

fervent saddle
lofty meadow
#

@past vale not randomly, organize it however you like but the way i was taught the traveling salesmen problem was that you have check every single route to find the shortest mathmatically

past vale
#

oh okay. Yes this is a combinatorial problem.

#

Meaning to find the most optimal solution it is needed to be checked for every combination

#

I think I can reduce the problem to, say you can meet at the nodes only. so truck can deliver items to nodes as well as the drone. It is not much easier but somewhat easier.

lofty meadow
#

I was thinking about it as a truck on a set route moving a predetermined speed

#

don't think you could solve it with any precision in real-time

lament shale
lyric breach
#

It's technically legal. They HAVE to hire you

#

It's one weird algorithms trick they don't want you to know about

river bough
#

Are data containers and data structures the same thing?

haughty mountain
#

like, don't trust the times and memory usage too much

#

they should be roughly right, but will fluctuate a lot

nimble ravine
haughty mountain
#

also, how tf is the top k frequent elements problem a medium problem?

#

it's so easy

nova igloo
#

Need help

#

The map contains islands named from Island 1 to island n .forvany two islands i and j you can go to island j frm i if the values i divides j.

#

Given the value for the last island equal to n find number of ways to reach island n from Island 1

agile sundial
haughty mountain
#

assuming we have dict

#

if you want me to implement dict in python...pls no

agile sundial
#

i mean, it's not that hard to make a dict that works

#

works well is a different story 🥴

haughty mountain
ionic shuttle
#

You know how there's a way to to get the minimum element in a given range within an array in O(logn)? You know what the data structure used for that is called? I remember that it was some ___ tree.

past vale
# lament shale Is this kind of code allowed in the interviews ?

Okay this kind of depends on interviews. This will change with each company and sometimes they will ask you to not import anything when solving the problem. But this solution has a close to top score on readability and performance, more than often, writing the actual logic instead of importing from library will score poorer and will be many lines of code. And yeah this uses the heap method.

#

If I was the interviewer, I would ask the person both. Their ability to workout the algorithm and test their python knowledge such as stdlib.

ionic shuttle
fervent saddle
#

Can’t you do it with a regular bst too?

#

But I guess it’s not made for that

glossy breach
#

You would need a bbst like treap or splay tree

#

But its very slow compared to segment tree

#

Also theres a thing called sparse table that supports O(1) per query

calm shale
#
if x in big_dictionary:
   if y in big_dictionary[x]:

### VERSUS ###

try:
    if y in big_dictionary[x]:
except:
    pass

which one should i be using froggy_chill

spring jasper
fiery cosmos
#

is there a way to hide a value

#

like, let's say i have a numpy array a, i'm going to use concat, vstack, interpolate, matrix and comparison operators on this to re-arrange it into a different representation

#

for all of these operations i want it to take the values contained in the cells of the array, however, i also want to conserve the original index

#

later on, i'm going to briefly do some simple algebra on cell values and combine some of them, i'd like to conserve and attach the index's of all the original values for use in reversing them

#

i want to use this method to make reversing a decomposition method much more simply than deconstructing the operations to a deterministic pattern

stray fractal
#

some python principle says you should do the latter

dark aurora
#
a1 = list(a)
a1[0][0] = 3
print(a, a1)``` why are a and a1 the same?
#

when they shouldn't be?

dark aurora
stray fractal
#

hmmm

#

oh

#

it just shallow copies the list

#

@dark aurora the elements still are the same

#

but the lists are different

dark aurora
#

Is there a way to change the elements without importing deepcopy

stray fractal
#

idk
you could probably do ```py
a1 = [a[0][:], a[1][:], a[2][:]]

dark aurora
#

Im guessing both list indicate to the same elements inside them but have diffrent "shells". (By shells i mean outer lists) Is that true?

eager hamlet
#

hey looking @ this problem here

#
def morgan_and_string(a: str, b: str) -> str:
    a += 'z'
    b += 'z'
    res = ''
    for _ in range(len(a) + len(b) - 2):
        if a < b:
            res += a[0]
            a = a[1:]
        else:
            res += b[0]
            b = b[1:]
    return res


for _ in range(int(input())):
    jack = input()
    daniel = input()
    print(morgan_and_string(jack, daniel))
#

isn't this code O(N^2)? why does it still run under the time limit?

haughty mountain
#

it's quite possible that the test cases are weak

#

fwiw slicing is a fairly cheap linear operation, it should just be a memmove in the end

fiery cosmos
#

are data structures important for getting into a cybersecurity world

#

is anyone here cyber expert

dark aurora
#

"Let us consider the problem of calculating the number of paths in an n × n grid from the upper-left corner to the lower-right corner such that the path visits each square exactly once. For example, in a 7 × 7 grid, there are 111712 such paths"- I solved this problem in python, but it takes 30mins to calculate the result, is there any way to make it faster?

#

Here is the code

#
from copy import deepcopy

n = int(input())
pro = [[1]*(n+2)]+[[1]+[0]*n+[1] for i in range(n)]+[[1]*(n+2)]

    
def check2(x,y,mx):
     a, b = (mx[x][y-1] ^ mx[x][y+1]), (mx[x-1][y] ^ mx[x+1][y])
     return False if (mx[x][y-1], mx[x][y+1]) != (mx[x-1][y], mx[x+1][y]) and (a,b) == (0,0) else True


def baseFunc(cor, ct, mx):
    pathr = 0
    x, y  = cor
    mx[x][y] = 1
    if check2(x,y,mx)==False: return 0
    dirc = [(x,y+1), (x+1,y), (x-1,y), (x,y-1)] if (x,y) != (1,1) else [(x+1,y)]
    if (x,y) == (n,n):
        return 1 if ct==(n*n) else 0
    for z in dirc:
        i, j = list(z)
        if mx[i][j] != 1:
            pathr = pathr+baseFunc([i,j], ct+1, deepcopy(mx))

    return pathr

print(baseFunc([1,1], 1, pro)*2)  
halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @fiery cosmos until <t:1650118584:f> (9 minutes and 59 seconds) (reason: burst rule: sent 8 messages in 10s).

topaz dune
#

Hello guys how should i merge 2 pandas dataframes in this way:
id name
1 a
2 b
3 d

id
1 e
4 g
5 f

result :
id
1 e
2 b
3 d
4 g
5 f

slender geode
eager hamlet
#

hey so

#

in python

#

my computer dies when i recurse 10^5 times

#

but in c++ or java

#

it works just fine

#

is python that bloated?

fervent saddle
#

There’s also no tail call optimization

#

Wait, Java doesn’t have that either, does it?

eager hamlet
#

for context, i'm just dfs-ing through a tree

#

with max 10^5 nodes

agile sundial
#

your "computer dies"?

glossy breach
#

Theres a max recursion depth in python btw and you have to set it higher

haughty mountain
haughty mountain
glossy breach
#

Maybe its just slow

eager hamlet
#

no like

#

intellij gives the weirdest exit code

opal oriole
#

segmentation fault probably

glossy breach
#

Can i see your dfs then

opal oriole
#

(core dumped)

halcyon plankBOT
#

Hey @eager hamlet!

It looks like you tried to attach file type(s) that we do not allow (.in). We currently allow the following file types: .gif, .jpg, .jpeg, .mov, .mp4, .mpg, .png, .mp3, .wav, .ogg, .webm, .webp, .flac, .m4a, .csv, .json.

Feel free to ask in #community-meta if you think this is a mistake.

eager hamlet
#

f

haughty mountain
#

considering you don't return anything in the recursion, rewriting it to be iterative would be straightforward

opal oriole
opal oriole
#

A new guard page for the stack cannot be created.

eager hamlet
#

yeah i see how it is

fervent saddle
eager hamlet
#

oh well i'll just stick to c++/java for recursion then

opal oriole
eager hamlet
#

yeah

opal oriole
#

Aka the "iterative" (simulated recursion) method.

eager hamlet
#

that's just a pain tbh

glossy breach
#

Not quite

eager hamlet
#

last time i un-recursion-ed a tree dfs i needed to add flags and everything

haughty mountain
#

it's not a pain in this case though, the code is almost identical

import sys

with open('planting.in') as read:
    field_num = int(read.readline())
    neighbors = [[] for _ in range(field_num)]
    for _ in range(field_num - 1):
        field1, field2 = [int(i) - 1 for i in read.readline().split()]
        neighbors[field1].append(field2)
        neighbors[field2].append(field1)

needed_types = [0 for _ in range(field_num)]
needed_types[0] = 1

stack = [(0, 0)]
while stack:
    at, prev = stack.pop()
    type_num = 1
    for n in neighbors[at]:
        if n == prev:
            continue

        while type_num in [needed_types[at], needed_types[prev]]:
            type_num += 1

        needed_types[n] = type_num
        stack.append((n, at))
        type_num += 1

print(max(needed_types), file=open('planting.out', 'w'))

eager hamlet
#

hm lemme submit

glossy breach
opal oriole
haughty mountain
#

I didn't test it, so it's possible I typod something or made some mistake

glossy breach
#

Even a recursion of depth 1e5 shouldnt take much memory

eager hamlet
#

oh wow

#

it works!

#

tysm!

haughty mountain
haughty mountain
# eager hamlet it works!

cool, as I said in this case because you don't have return values in your dfs it's super easy to convert to iterative form

#

the code is almost identical

#

if you need to emulate return values things get less fun, but still doable

#

or you find some nicer way of rephrasing things to not have to do return values

opal oriole
#

The case in which you need to return stuff is not bad either, it just takes some getting use to. But there is an easy to follow pattern to convert any recursive algorithm to non-recursive.

haughty mountain
#

I don't know if I've ever had to properly emulate return values when doing things iteratively

glossy breach
#

Its not always easy

haughty mountain
#

most of the time there are easier ways to do it

opal oriole
#

Often you don't and it will be faster if you don't / use less memory.

glossy breach
#

Dynamic programming on tree is complicated if you want to make it iterative

fervent saddle
#

500 * 100000 it’s like 50 megabytes

opal oriole
haughty mountain
#

a typical default stack size is a few MiB iirc

#

seems to be 8MiB by default on my machine ulimit -s

#

though you can easily change it on linux

#

(it's considerably more annoying on windows)

glossy breach
#

Oh right

#

I always have my stack on 256mb

opal oriole
#

8 MiB is probably way more than you need. In CPython it has a conservative limit because Python stack frames are big.

#

(If you are in something like C, it may also optimize it (copy vs move))

haughty mountain
#

he knows way too much about how pypy behaves just from having played around with it so much 😛

glossy breach
#

Wow this is interesting

#

Thanks for sharing this

next loom
#

For anyone that has applies quadtrees to their work. I have been looking through and testing the code below. For some reason, this algorithm is not able to insert all the points inside of it. I'm not sure why, I have tried to make several tweaks to no avail. I post te original code below

halcyon plankBOT
#

Hey @next loom!

You either uploaded a .txt file or entered a message that was too long. Please use our paste bin instead.

next loom
#

class Point:
    """A point located at (x,y) in 2D space.

    Each Point object may be associated with a payload object.

    """

    def __init__(self, x, y, payload=None):
        self.x, self.y = x, y
        self.payload = payload

    def __repr__(self):
        return '{}: {}'.format(str((self.x, self.y)), repr(self.payload))
    def __str__(self):
        return 'P({:.2f}, {:.2f})'.format(self.x, self.y)

    def distance_to(self, other):
        try:
            other_x, other_y = other.x, other.y
        except AttributeError:
            other_x, other_y = other
        return np.hypot(self.x - other_x, self.y - other_y)

#
    """A rectangle centred at (cx, cy) with width w and height h."""

    def __init__(self, cx, cy, w, h):
        self.cx, self.cy = cx, cy
        self.w, self.h = w, h
        self.west_edge, self.east_edge = cx - w/2, cx + w/2
        self.north_edge, self.south_edge = cy - h/2, cy + h/2

    def __repr__(self):
        return str((self.west_edge, self.east_edge, self.north_edge,
                self.south_edge))

    def __str__(self):
        return '({:.2f}, {:.2f}, {:.2f}, {:.2f})'.format(self.west_edge,
                    self.north_edge, self.east_edge, self.south_edge)

    def contains(self, point):
        """Is point (a Point object or (x,y) tuple) inside this Rect?"""

        try:
            point_x, point_y = point.x, point.y
        except AttributeError:
            point_x, point_y = point

        return (point_x >= self.west_edge and
                point_x <  self.east_edge and
                point_y >= self.north_edge and
                point_y < self.south_edge)

    def intersects(self, other):
        """Does Rect object other interesect this Rect?"""
        return not (other.west_edge > self.east_edge or
                    other.east_edge < self.west_edge or
                    other.north_edge > self.south_edge or
                    other.south_edge < self.north_edge)

    def draw(self, ax, c='k', lw=1, **kwargs):
        x1, y1 = self.west_edge, self.north_edge
        x2, y2 = self.east_edge, self.south_edge
        ax.plot([x1,x2,x2,x1,x1],[y1,y1,y2,y2,y1], c=c, lw=lw, **kwargs) ```
#
    """A class implementing a quadtree."""

    def __init__(self, boundary, max_points=4, depth=0):
        """Initialize this node of the quadtree.

        boundary is a Rect object defining the region from which points are
        placed into this node; max_points is the maximum number of points the
        node can hold before it must divide (branch into four more nodes);
        depth keeps track of how deep into the quadtree this node lies.

        """

        self.boundary = boundary
        self.max_points = max_points
        self.points = []
        self.depth = depth
        # A flag to indicate whether this node has divided (branched) or not.
        self.divided = False

    def __str__(self):
        """Return a string representation of this node, suitably formatted."""
        sp = ' ' * self.depth * 2
        s = str(self.boundary) + '\n'
        s += sp + ', '.join(str(point) for point in self.points)
        if not self.divided:
            return s
        return s + '\n' + '\n'.join([
                sp + 'nw: ' + str(self.nw), sp + 'ne: ' + str(self.ne),
                sp + 'se: ' + str(self.se), sp + 'sw: ' + str(self.sw)])
#
        """Divide (branch) this node by spawning four children nodes."""

        cx, cy = self.boundary.cx, self.boundary.cy
        w, h = self.boundary.w / 2, self.boundary.h / 2
        # The boundaries of the four children nodes are "northwest",
        # "northeast", "southeast" and "southwest" quadrants within the
        # boundary of the current node.
        self.nw = QuadTree(Rect(cx - w/2, cy - h/2, w, h),
                                    self.max_points, self.depth + 1)
        self.ne = QuadTree(Rect(cx + w/2, cy - h/2, w, h),
                                    self.max_points, self.depth + 1)
        self.se = QuadTree(Rect(cx + w/2, cy + h/2, w, h),
                                    self.max_points, self.depth + 1)
        self.sw = QuadTree(Rect(cx - w/2, cy + h/2, w, h),
                                    self.max_points, self.depth + 1)
        self.divided = True

    def insert(self, point):
        """Try to insert Point point into this QuadTree."""

        if not self.boundary.contains(point):
            # The point does not lie inside boundary: bail.
            return False
        if len(self.points) < self.max_points:
            # There's room for our point without dividing the QuadTree.
            self.points.append(point)
            return True

        # No room: divide if necessary, then try the sub-quads.
        if not self.divided:
            self.divide()

        return (self.ne.insert(point) or
                self.nw.insert(point) or
                self.se.insert(point) or
                self.sw.insert(point))```
#
        """Find the points in the quadtree that lie within boundary."""

        if not self.boundary.intersects(boundary):
            # If the domain of this node does not intersect the search
            # region, we don't need to look in it for points.
            return False

        # Search this node's points to see if they lie within boundary ...
        for point in self.points:
            if boundary.contains(point):
                found_points.append(point)
        # ... and if this node has children, search them too.
        if self.divided:
            self.nw.query(boundary, found_points)
            self.ne.query(boundary, found_points)
            self.se.query(boundary, found_points)
            self.sw.query(boundary, found_points)
        return found_points


  
#
        """Find the points in the quadtree that lie within radius of centre.

        boundary is a Rect object (a square) that bounds the search circle.
        There is no need to call this method directly: use query_radius.

        """

        if not self.boundary.intersects(boundary):
            # If the domain of this node does not intersect the search
            # region, we don't need to look in it for points.
            return False

        # Search this node's points to see if they lie within boundary
        # and also lie within a circle of given radius around the centre point.
        for point in self.points:
            if (boundary.contains(point) and
                    point.distance_to(centre) <= radius):
                found_points.append(point)

        # Recurse the search into this node's children.
        if self.divided:
            self.nw.query_circle(boundary, centre, radius, found_points)
            self.ne.query_circle(boundary, centre, radius, found_points)
            self.se.query_circle(boundary, centre, radius, found_points)
            self.sw.query_circle(boundary, centre, radius, found_points)
        return found_points ```
#
    def query_radius(self, centre, radius, found_points):
        """Find the points in the quadtree that lie within radius of centre."""

        # First find the square that bounds the search circle as a Rect object.
        boundary = Rect(*centre, 2*radius, 2*radius)
        return self.query_circle(boundary, centre, radius, found_points)


    def __len__(self):
        """Return the number of points in the quadtree."""

        npoints = len(self.points)
        if self.divided:
            npoints += len(self.nw)+len(self.ne)+len(self.se)+len(self.sw)
        return npoints

    def draw(self, ax):
        """Draw a representation of the quadtree on Matplotlib Axes ax."""

        self.boundary.draw(ax)
        if self.divided:
            self.nw.draw(ax)
            self.ne.draw(ax)
            self.se.draw(ax)
            self.sw.draw(ax) ```
#
import matplotlib.pyplot as plt
from quadtree import Point, Rect, QuadTree
from matplotlib import gridspec

DPI = 72
np.random.seed(60)

width, height = 600, 400

N = 500
coords = np.random.randn(N, 2) * height/3 + (width/2, height/2)
points = [Point(*coord) for coord in coords]

domain = Rect(width/2, height/2, width, height)
qtree = QuadTree(domain, 3)
for point in points:
    qtree.insert(point)```
eager hamlet
#

is there any way to compare strings lexicographically using some form of hashing?

mystic sinew
#

anyone knows the alternative for st.mode in numpy?

#

plz help

fathom delta
#

Hi guys appreciate any tips on how to tackle this problem. This is a max-flow problem. Thanks

#

i think the conditions requires a min-cut, but then the other condition is tricky

#

like. Disconnecting the customers from the generators involves a cut, but it doesn’t
account for the number of trips.

next loom
#

I dont under stand the data I', getting from scipy KD tree: ``` import numpy as np
from scipy.spatial import KDTree
pts = np.random.rand(150,3)

T1 = KDTree(pts, leafsize=20)

neighbors1= T1.query_ball_point((0.3,0.2,0.1), r=2.0)
print(neighbors1) ```

#

I get this[18, 48, 53, 54, 73, 83, 89, 90, 103, 127, 136, 3, 12, 47, 58, 63, 82, 95, 96, 108, 148, 4, 13, 28, 33, 34, 37, 38, 46, 50, 92, 93, 99, 138, 2, 5, 16, 24, 42, 43, 51, 65, 78, 94, 107, 113, 130, 140, 143, 146, 31, 39, 40, 57, 75, 105, 106, 116, 118, 121, 122, 145, 8, 56, 72, 74, 80, 85, 104, 110, 117, 120, 126, 1, 9, 15, 25, 26, 35, 36, 60, 61, 64, 71, 77, 98, 115, 125, 128, 129, 139, 142, 0, 44, 67, 69, 76, 87, 91, 111, 124, 147, 21, 22, 41, 52, 66, 88, 100, 101, 102, 112, 131, 11, 19, 32, 49, 59, 68, 81, 84, 109, 114, 123, 132, 133, 135, 137, 141, 6, 10, 17, 23, 29, 30, 45, 7, 14, 20, 27, 55, 62, 70, 79, 86, 97, 119, 134, 144, 149]

fathom pebble
#

hello everyone I have a problem in pandas how I could do to change the data of column 2 in full knowing that I have a table of 1000 lines so I could not change for each line
I had thought of calculating the average then dividing by 10 for example for line 1: 91+100/2 =95.5 /10 = 9.55 but I know how to write it in code so that it works for the whole table

next loom
#

I dont know how I am to translate this array to the points around (0.3,0.2,0.1)

half shore
#

Does anyone know where I could find the code for some DFO (derivative-free optimization / black box) algorithms?

#

Local search, random search, simulated annealing etc..

haughty mountain
fiery cosmos
#

When you iterate a set, since its unordered, should the output be random each time?

#

Or is my IDE bugging out?

s = {"1", 2, True}
for x in s:
    print(x)```
#

This prints "True", "2", 1" and sometimes "2", "True", "1"

agile sundial
#

this is because the hashes of strings are randomized for every time you run the interpreter

#

if you looped over it multiple times in the same run of the interpreter, you should get the same ordering

shut breach
#

although that isn't guaranteed by the language, just an implementation detail

loud orbit
#

is a parser that generates a tree an algorithm and the tree a data structure?

twilit ibex
#

I am trying to take a polynomial as input and apply newton raphson method to solve it but it gives error

x = Symbol('x')
f = input("Enter a Polynomial: ")
f_prime = f.diff(x)
f = lambdify(x,f)
f_prime = lambdify(x,f_prime)

x= float(input('enter the value of x : '))
n= int(input('enter the required correct decimal places : '))

i=1
condition = True
while condition:
    g=str(x)
    x_n = x - (f(x)/f_prime(x))
    print("i= ",i,"x= ",x,"f(x)= ",f(x))

    m=str(x_n)

    if m[0:n+2] == g[0:n+2]:
        condition = False
    else:
        condition = True
        x = x_n
        i = i+1

print("Required root is ",x) ```
line 4, in <module>
    f_prime = f.diff(x)
AttributeError: 'str' object has no attribute 'diff'

how to solve it
rich socket
#

can anyone help me with a good machine learning course

serene portal
#

Can somebody tell me how to make a store in python with the "def" command?

celest scarab
#

Looks like 91+100/2 is the interval of what you define as "classroom". You continue with 95.5 /10. What is this "10". What do you want to compute?

fathom pebble
#

for the last column the values ​​are between 0 and 10

celest scarab
#

So in the "classroom", when we see "91-100" you want those two values right?

#

Then you divide by the last column?

fathom pebble
cold mulch
#

how do i plot contours onto an irregularly spaced grid in matplotlib?

#

so what i have is the array for the x values is just an array of all the latitude values, the y array is an array of all the longitude values, and the z array is the snowfall (height data for x/y)

#

problem is that the z array doesn't have data for every lat/long value

#

only some lat/long values, so it's quite uneven

cold mulch
#

also just a note that tricontour doesn't work for me

halcyon plankBOT
#

termfx/session.py lines 42 to 45

arguments = value.split("(")[1].split(")")[0]
arglist = arguments.split(",")  if len(arguments.split(",")) > 1 else [arguments]
arguments = [int(x) if x.isdigit() else float(x) if re.match(r"^-?\d+(?:\.\d+)$", x) else self.stripper(x) for x in arglist]
func = self.functions.get(value.split("(")[0])```
loud orbit
#
def addnot2toall(lst,var):
    new = []
    for elem in lst:
        new.append(elem + 1)
    return [elem for elem in new if elem != 2]

How would this function be noted down in O?
I'm thinking O(n), but it runs two loops that aren’ nested in each other, so it seems to me this is more like O(2n)?

tight hazel
#

0(2n) or else you can try saving it and running it again @loud orbit

loud orbit
#

i didnt run it

#

im determining it manually

fiery cosmos
#

O(2n) is the same as O(n) since with big oh you ignore constant multiples

#

course you can reduce it to a single pass with a slightly different comprehension py return [elem + 1 for elem in lst if elem + 1 != 2]

lean dome
#

Every function that is O(n) is also O(2n), and vice versa. It's not just that you ignore constant multiples, it's that what big O tells you is that there exists some constant multiple for which some condition holds

#

The same statement would apply equally to O(n) as O(2n), you'd simply need to choose a constant that's half or twice as large

#

In practice, you can just ignore constant multiples, but that's not just laziness or a shortcut or anything like that, it arises from the very nature of what big o notation is conveying

strong sinew
#

how much algos should i know before starting leetcode grind

loud orbit
#

thanks.

#

mapping and filteris O(n) too, yes?

feral trail
#

It is possible to implement a queue such that both enqueue and dequeue have O(1) performance on average. In this case it means that most of the time enqueue and dequeue will be O(1) except in one particular circumstance where dequeue will be O(n).

#

Isn't this just a deque?

#

Or am I misunderstanding something

agile sundial
#

why would dequeue ever be O(n)

#

unless you don't mean Theta(n)

feral trail
#

Yeah that's what I'm a bit confused about

#

It would always be O(1) in case of deque right?

agile sundial
#

you'd have to mess up really badly to dequeue in O(n) pithink

feral trail
agile sundial
#

¯_(ツ)_/¯

feral trail
#

I mean

#

I'm currently implementing a Queue using python lists

#

Which is basically cheating

#

So they probably want me to do it differently instead

vocal gorge
#

like, as a circular buffer? that's a fine way to implement a queue/deque IMO

agile sundial
#

much better for caches

kind valley
#

Folks I have a expression I don't know how to simplify:

from sympy import *
from sympy.abc import w, x, y, z

expr = (w - x) * (x - y) + (y - z) * (z - w)
expanded = expand(expr)
back = factor(expr)

I want back to be something similar to expr. I tried factor/simplify/cancel and stuff and seems non of these works.
Anyone know what should I try?

fiery cosmos
#

Hello guys is there a specific channel do discuss about selenium ?

celest scarab
#

This basically splits the classroom column and computes a ratio dividing with the values in the very last column I read as performance. Other numerical computations are possible, too.

celest scarab
urban plover
#

I need to create a recursive function that does that
But I cannot find the recursive function anyone can help me find it please?

regal zephyr
fervent saddle
#

f(0) == 1
f(1) == 1
f(n) == f(n-1) + f(n-1) + f(n-2)

#

I think that’s what it’s doing

urban plover
#

Yeah I figure it out
Thank you so much

#

It should return F(n -1)*2 + F(n-2)

atomic torrent
#

hi, i'm really interested in learning python but i really just cant remember or figure it out. is there any help or tips anyone can give me? thank you.

keen hearth
#

!resources

halcyon plankBOT
#
Resources

The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.

proven bolt
#

Hello guys

dapper sapphire
#

What can I name collections.Counter()?

#

for example, if I did:

#

!e

import collections
string = "abcdefaaab"
counter = collections.Counter(string)
print(counter)
halcyon plankBOT
#

@dapper sapphire :white_check_mark: Your eval job has completed with return code 0.

Counter({'a': 4, 'b': 2, 'c': 1, 'd': 1, 'e': 1, 'f': 1})
dapper sapphire
#

I usually name dict as dictionary, set as cache, not sure what to call collections.Counter(). In the above example, I just called it counter.

delicate bluff
#

Hi there, anyone here using zipline? Cheers

haughty mountain
#

a set could be used for a cache, but could also be something else entirely

#

just picking a generic name isn't a good way to name instances most of the time

dapper sapphire
#

letter_counts works. I chose a generic name for leetcode purpose, but I agree generic name isnt a good practice.

lean junco
#

Suggest an approach so that i can nail every dp problem

haughty mountain
#

there is no single approach

#

finding a good dynamic programming formulation tends to require you to look at a problem from some specific angle where things work out nicely and where you can make use of the underlying structure

#

and this tends to be pretty different between types of problems

haughty mountain
#

not the right channel for thia

tepid patrol
#

what is the right channel?

haughty mountain
#

try the general channel

tepid patrol
#

ok cheers

thin briar
#

hi everyone! iI have to pick a topic that could be the most interesting for a student led lecture- which do u think is the most interesting topic?
1 .Latent Dirichlet Allocation (Gensim)

  1. Deck.gl (pydeck)

  2. Sentiment Analysis (VADER)

  3. K-Means & K-Medians (qualitative and quantitative)

  4. K-Anonymity

  5. Ward Clustering

  6. Neural Networks

  7. Agent-Based Modelling

  8. Random Forest

  9. Support Vector Machines (SVM)

haughty mountain
raven kraken
#

Hey all, Can I anyone tell me what's the difference between these two different chunk of code snippets -
1]

nums =[2,7,9,3,1]
prev, curr = 0, 0
        
        for n in nums:
            prev, curr = curr, max(curr, prev + n)
            
        return curr

Output = 12
2]

nums =[2,7,9,3,1]
prev, curr = 0, 0
        
        for n in nums:
            prev = curr 
            curr = max(curr, prev + n)
            
        return curr

Output = 22

#

Basically my problem is why can't we write prev, curr = curr, max(curr, prev + n) as

prev = curr 
curr = max(curr, prev + n)
haughty mountain
#

like

# prev = 123   curr = 456
prev = curr
# prev = 456   curr = 456
raven kraken
#

@astral bone , @haughty mountain Thank you for explaining it to me and clearing my doubts!!!!

dark aurora
#

Can someone explain how meet in the middle works and why?

#

Like if you can square root the time complexity by splitting the list in half, why don't we do that every time?

#

So by splitting the list in half we get two n/2 lists and then we sort them and etc...

#

why don't we then half those two n/2 lists thus improving the time complexity, than do that until we have just two items?

#

I know this may sound stupid to some but i really don't understand

slender geode
haughty mountain
normal sphinx
#

😆

fiery cosmos
#

found this problem in a textbook and have no idea how to do it. Any ideas?

haughty mountain
# fiery cosmos found this problem in a textbook and have no idea how to do it. Any ideas?

it's basically https://en.wikipedia.org/wiki/Subset_sum_problem but trying to minimize difference instead of finding an equal split/a particular sum

The subset sum problem (SSP) is a decision problem in computer science. In its most general formulation, there is a multiset

    S
  

{\displaystyle S}

of integers and a target-sum

    T
  

{\displaystyle T}

, and the question is to decide whether any subset of the integers s...

#

(nice link preview)

#

the dp solution I'm familiar with should solve both problems

fiery cosmos
#

do you mind sharing it?

#

the dp solution that is, I'm completely lost I'm sorry

haughty mountain
#

It's a very classic knapsack like algorithm. The idea is to find which numbers are constructible, start with
reachable = [1, 0, 0, 0, ..., 0]
i.e. sum 0 is reachable using no elements
then for every possible weight w_i, looping backwards, set reachable[i + w_i] if reachable[i] is set

#

After going through all your numbers you know what numbers are constructible, so finding the closest to even split it trivial

#

Though reconstructing the solution is a tad more annoying

#

I guess the actual problem it resembles is the partition problem. Though it and subset sum can be easily translated into each other from what I remember

#

like, the second paragraph in the partition problem wiki article is exactly the problem from the textbook

#

an optimization version of the partition problem

#

I guess in general, reading up on the knapsack family of problems is probably helpful

#

this is a special case, and one of the easier ones

fiery cosmos
#

how would we trace back which weights are in each knapsack?

#

@haughty mountain

#

because I think that's part of the problem as well

haughty mountain
#

one way would be storing something nicer than 0/1. like store reachable[i + w_i] = w_i if it's the first time seeing reachable[i + w_i]

#

then you can easily backtrack

fiery cosmos
#

but there can be multiple weights, how would we get those? @haughty mountain

#

like multiple weights make up the contents of the bag

haughty mountain
#

what's the problem with multiple weights?

fiery cosmos
#

I just don't see how you can get the multiple weights back, so we have a reachable array which stores whether certain weights are reachable

#

and as you mentioned above, we would simply set it equal to w_i

#

but then how would we chain these to figure out what is in each bag individually

haughty mountain
#

one way to get to j was from k = j - reachable[j]

#

and so on

#

can confirm this approach works

#

the dp part is very simple

from typing import List, Optional

weights = [5,1,2,9]

reachable: List[Optional[int]] = [None]*(sum(weights) + 1)
reachable[0] = 0

for w in weights:
  for i in reversed(range(len(reachable) - w)):
    if reachable[i] is not None and reachable[i + w] is None:
      reachable[i + w] = w
#

the dp logic is 4 lines, writing code to backtrack from any particular sum is like 6-7 lines of logic more

brave hound
#
def square_mul_method(b: int, e: int, mod: int) -> typing.Generator[int, None, None]:
    bc = b
    steps = ['s' if n == '0' else 'sm' for n in bin(e)[3:]]
    for step in steps:
        if step == 's':
            yield (b := (b * b) % mod)
        else:
            yield (b := (b * b) % mod)
            yield (b := (b * bc) % mod)


args = (9832489237482759232, 1232748927398574897589349878329, 289237489789345897496283423132)
with timer('py method'):
    print(pow(*args))
with timer('s-m method'):
    print([*square_mul_method(*args)][-1])

👀

222240966389595545659107585232
py method                                          -> 3.609999930631602e-05
222240966389595545659107585232
s-m method                                         -> 5.599999985861359e-05
#

args = (183, 342, 3423)

2661
py method                                          -> 1.2500000593718141e-05
2661
s-m method                                         -> 8.400000297115184e-06

the difference decreases with increase in nums

#

👀 👀

#

ya creating a list and getting the last value was dumb

tiny plank
#

Hello there i have a class stored in a numpy array

@dataclass
class Item:
  count: int
  ...

item_array = np.array(10, dtype=Item)

i would like to increase every item in the array, normally i would do

for c_item in item_array:
  citem.count += 1 

is there a better way or a vectorized way of doing this ?
thanks

stable pecan
#

you can use np.vectorize or, alternatively, add an __add__ method to your class

#

this works:

In [25]: @dataclasses.dataclass
    ...: class Item:
    ...:     count: int = 0
    ...:
    ...:     def __add__(self, val: int):
    ...:         self.count += val
    ...:         return self

In [26]: arr = np.array([Item(0) for _ in range(10)])

In [27]: arr += 1

In [28]: arr
Out[28]:
array([Item(count=1), Item(count=1), Item(count=1), Item(count=1),
       Item(count=1), Item(count=1), Item(count=1), Item(count=1),
       Item(count=1), Item(count=1)], dtype=object)

though vectorizing over objects won't necessarily be faster than pure python

raw hill
#

Hello, I'm stuck with this problem and I can't come up with even the brute force solution, here is the problem:

#

'''
Test Case 1:
teamA = [1, 4, 2, 4]
teamB = [3, 5]
Output: [2, 4]

Explanation:
1. For teamB[0] = 3, we have 2 elements in teamA 
(teamA[0] = 1 and teamA[2] = 2) that are <= teamB[0].

2. For teamB[1] = 5, we have 4 elements in teamA
(teamA[0] = 1, teamA[1] = 4, teamA[2] = 2, and teamA[3] = 4)
that are <= teamB[1]

###############################################################
Test Case 2:
teamA = [1, 2, 3]
teamB = [2, 4]
Output: [2, 3]

Explanation:
1. For teamB[0] = 2, we have 2 elements in teamA 
(teamA[0] = 1 and teamA[1] = 2) that are <= teamB[0].

2. For teamB[1] = 4, we have 3 elements in teamA
(teamA[0] = 1, teamA[1] = 2, teamA[2] = 3)
that are <= teamB[1]
'''


def counts(teamA, teamB):
    pass


print(counts([1, 2, 3], [2, 4]))  # [2, 3]
# print(counts([1, 4, 2, 4], [3, 5]))  # [2, 4]
# print(counts([2, 10, 5, 4, 8], [3, 1, 7, 8]))  # [1, 0, 3, 4]


haughty mountain
#

and you could easily speed this up to be O(n log n + m log n) where n and m are the lengths of teamA and teamB respecively

#

by sorting teamA and binary searching for every element in teamB

raw hill
#

Correct, that's the brute force solution.

#

I will try to optimize it. Thanks though.

opal oriole
gilded onyx
#

I'm solving this recursively and I got lost on something:
https://leetcode.com/problems/palindrome-number/

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x = str(x)
        def helper(x, l, r):
            if l >= r:
                return True
            if x[l] != x[r]:
                return False
            
            helper(x, l+1, r-1)
            
            
        return helper(x, 0, len(x)-1)

This doesn't work. But when I put return helper(x, l+1, r-1) it works. Why is that?

class Solution:
    def isPalindrome(self, x: int) -> bool:
        x = str(x)
        def helper(x, l, r):
            if l >= r:
                return True
            if x[l] != x[r]:
                return False
            
            return helper(x, l+1, r-1)
            
            
        return helper(x, 0, len(x)-1)

^This works.

runic tinsel
#

the line helper(x, l+1, r-1) can be replaced by an empty line

#

it's like if you had a line that says m * 10

#

the point of calling a function is to get the output and use it somehow

#

even when it's recursive

gilded onyx
#

huh??

fringe bone
#

hello good people

#

can anyone help me out ?

#

I am trying to rename files with the names which i have in txt file, it does it randomly and thats okay it doesn't have to be in order or smth, the error which i ran into is that when it runs and it gets to a duplicate it stops completely and tells me it cant create an already existing file, is there a way i can tell it to not use the already used names from the txt file. heres the code


base_path = "C:/Users/B O S S/Desktop/salomee/salomeo/"
files = [base_path + file for file in os.listdir(base_path)]

with open("C:/Users/B O S S/Desktop/namessalome.txt") as f:
    new_names = [base_path + name + ".jpg" for name in f.read().rstrip().split(", ")]
    
for old_name, new_name in zip(files, new_names):
    os.rename(old_name, new_name)
past sorrel
#

Hi Everyone, I was just doing an easy leetcode and found something weird and would like to understand the reason. This is the problem link: https://leetcode.com/problems/contains-duplicate/

#

I have submitted two solutions which are as follows:

#

class Solution: def containsDuplicate(self, nums: List[int]) -> bool: seen = set() for x in nums: if x in seen: return True seen.add(x) return False

#

class Solution: def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums))

#

I found that the second solution was significantly faster than the first one

#

But, as per my understanding, in most cases the first one will return very fast due to the duplicate finding, while the second one will always fully traverse the whole list

#

So, why is the second solution faster? Thanks in advance.

fervent saddle
#

It adds everything to the set in C instead of in python

#

If you were writing the solution in a compiled language, leaving early would probably be faster on average.

thick echo
#

exactly right

last fulcrum
#

Hi

#

I need an algorithm to solve wordle but I don't even know where to start

#

Does anyone have any idea?
I know in AI we have the min-max strategy for games

agile sundial
#

the idea is to guess words that maximize the amount of information you gain

feral trail
#

I'm currently learning DSA, and the textbook has 2 different exercises
I implemented a queue using single linked list and keep track of the head and tail node
Which I suppose is the case where both are O(1) -> Exercise 28
But I don't know what kind of implementation would have an average time complexity for queue and dequeue of O(1) but have 1 case where it's O(n)
Can someone tell me what that case and which implementation that is?

fervent saddle
#

If it was implemented with a circular buffer, I think it would be enqueue that would be O(n) sometimes, not dequeue, so I wonder what the answer is too. Hopefully someone knows.

agile sundial
#

it makes no sense that dequeue would be O(n), maybe an error

fervent saddle
#

Maybe they meant “enqueue and dequeue”

copper ginkgo
#

Can I ask for help solving ODEs here?

#

In python of course

vocal gorge
#

maybe #data-science-and-ml would be more fitting (the description there mentions "scientific Python"), this is more for computer-science and DSA

haughty mountain
agile sundial
#

ew

vocal gorge
#

🥴

fiery cosmos
#

And I guess if your stack is a dynamic array then enqueue aka pushing is O(1) on average already pithink

#

so both enqueue and dequeue are O(1) on average

agile sundial
fiery cosmos
agile sundial
#

no way. just using an array would be better in pretty much every way

#

well, ig if you're not thinking that could be a solution

umbral wagon
#

hey i was wondering if this is an O(n) operation? i'm checking whether a character at an index is inside an substring
if s[right] not in s[left:right]:

fiery cosmos
feral trail
#

I see yeah that's O(n) worst case dequeue and O(1) on average

#

But isn't just keeping a head and tail pointer simpler and guarantee O(1) for both dequeue and enqueue?

fiery cosmos
jolly widget
#

hi guys.. is there a way to save something for period of time and delete after it expires in this case :

`X = 0
Entry = close > EMA200 and X != 2
StopLoss = when price drops 3% from entery
TakeProfit = when price goes up 6% from entry

if StopLoss :
X += 1
f = open("demofile3.txt", "w")
f.write(X)
f.close()

`
Now how to reset the value of X to 0 after 24 hours from it being == 2

#

if there is a more convenient way to do please let me know !

dim kernel
#

if

#

hi can someone help me with this

limpid crown
#

#Nandan Bhut
#Gr 11
#ICS 3U0
#Mr veera 

investment = 2500
years = 1

while (investment <= 5000): 
    investment = investment * (7.5/100)
    years += 1
print(years)
 
feral trail
#

I'm just a bit curious, if you get good at DSA can you read a solution like this and immediately understand what the answer is trying to do?

#
class Solution:
    def removeNthFromEnd(self, head, n):
        def remove(head):
            if not head:
                return 0, head
            i, head.next = remove(head.next)
            return i+1, (head, head.next)[i+1 == n]
        return remove(head)[1]
#

It took me quite a while to even understand what the author is attempting

feral trail
#

Especially this part (head, head.next)[i+1 == n]

haughty mountain
shut breach
#

yeah it has less to do with DSA and more to do with writing readable python

brave hound
#
def square_mul(base: int, exponent: int, mod: int = 0) -> int:
    base_copy = base
    for n in bin(exponent)[3:]:
        if n == '0':
            base = (base * base) % mod
        else:
            base = (base * base % mod) * base_copy % mod
            # base = (base * base_copy) % mod
    return base

Is there anything faster than this

%%timeit
square_mul(*args)
224 µs ± 4.03 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

%%timeit
pow(*args)
200 µs ± 2.87 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

is there a way i can match cpython

opal oriole
#

You will find stuff like this in the wild though, but not for trivial stuff like this. The idea is turning an if-else chain into a lookup table (in this case only 1 if, and 1 else), which can be well worth it when the number of cases is large enough and you may want to dynamically add more cases.

#

And if your key is not just an index (enum) (and/or that index does not cover all integers between some range (e.g. you have not something like 1-4, but rather [1, 3, 4])), you can use a dict.

#
if x == 0:
  return "foo"
elif x == 1:
  return "bar"
elif x == 2:
  return "baz"

# vs

lst = ["foo", "bar", "baz"]
return lst[x]
fervent saddle
#

return head.next if i+1 == n else head
It could have been written like that

fiery cosmos
#

^ which has the advantage of being lazy evaluated hachuCozy

solemn zodiac
#

an example of someone elses graph. they did linear regression but thats based on their data and who knows if its right. my axes and plots would look similar though

remote wind
#

what's a better way to write this hash table?

last fulcrum
#

So I have an algorithm that given a list of words calculates the best word to choose out of the list. Can anyone point me in any direction on how to improve it?

#
def best_guess(possible_words: List[str]) -> str:
    LETTER_COUNTER = Counter(chain.from_iterable(
        possible_words))

    LETTER_FREQUENCY = {
        character: value / sum(LETTER_COUNTER.values())
        for character, value in LETTER_COUNTER.items()
    }

    def calculate_word_commonality(word: str) -> float:
        """
        Calculates how common the letters are in a word. 
        """
        score = 0.0
        for char in word:
            score += LETTER_FREQUENCY[char]
        return score / (5 - len(set(word)) + 1)

    word_rankings = {}
    for word in possible_words:
        word_rankings[word] = calculate_word_commonality(word)

    return max(word_rankings, key=word_rankings.get)
haughty mountain
haughty mountain
#

for wordle it's more interesting to consider how much info you get from picking some particular word

#

I wrote a dumb solver a while back that basically did considered all combinations of words I can pick and words that could still be correct given the hints

for pick in all_possible_words_to_pick
  for target in all_possible_target_words
    number_of_possible_words_left(pick, target)
#

I decided to pick the max(num_words_left) over all targets as a score

#

and then I picked the word that minimizes that

#

it basically tries to make the worst case outcome as good as possible

last fulcrum
haughty mountain
#

you'll end up having to implement the wordle output (green, yellow, gray), and implement code to check if a word follows the constraints you know so far

last fulcrum
haughty mountain
#

green just locks a character completely

#

the set of yellow characters must be part of the non-green ones in the target word

last fulcrum
glad vale
#

Hi!
I have a problem with one algorithm.
I want to get an answer which buildings should i choose among the whole T array of buildings that will contain the most people and will not intersect. The total price TotalPrice of those buildings must lower than p.
The amount of people that building can contain is given by this formula
`capacity = h * (b - a)

**We need to return an array that will contain the indexes of building that we should chose in order given in T array **

Buildings are presented like
(h, a, b ,w) where:

  • h is a height of building
  • a is starting point of building
  • b is ending point of building
  • w is the price of the building

Example:

T = [ (2, 1, 5, 3),
(3, 7, 9, 2),
(2, 8, 11, 1) ]
p = 5

Answer: [0, 2]

One more example:
T = [(3, 3, 4, 19), (3, 11, 17, 7), (4, 8, 15, 15), (3, 1, 7, 15), (4, 12, 17, 7), (3, 1, 7, 3), (4, 8, 9, 7), (3, 11, 18, 15), (4, 20, 31, 19), (3, 17, 26, 7)]
p = 20

Answer: I not have indexes yet but the maximum capacity should be 49 capacity = 49

I need to create a select_buildings(T,p) function ( where p is a maximum price TotalPrice < p )

It's similar problem to Weighted Interval Scheduling Problem
I've already created an algorithm but it's not working for every situation... ( I modified the Weighted Interval Scheduling Problem solution )

#

My solution:

#
def select_buildings(T, p):
    n = len(T)
    sorted_indexes = sorted(range(n), key=lambda x: T[x][2])

    maxSize = [0 for _ in range(n + 1)]
    bestIndexes = [(0, 0) for _ in range(n + 1)]    # (index, sumOfCost)


    for i in range(1, n + 1):
        currEl = T[sorted_indexes[i - 1]]
        # print(f'currEl = {currEl}')

        # @TODO: Implement binary search
        # Searching the building that is not intersecting with currEl
        # currEl.a > tmpEl.b
        for j in range(i - 1, 0, - 1):
            tmpEl = T[sorted_indexes[j - 1]]
            if currEl[1] > tmpEl[2] and currEl[3] + bestIndexes[sorted_indexes[j - 1] + 1][1] <= p:
                bestIndexes[sorted_indexes[i - 1] + 1] = (sorted_indexes[j - 1] + 1, currEl[3] + bestIndexes[sorted_indexes[j - 1] + 1][1])
                break

        # If there is no such a building we save the (0,currentElementCost)
        if bestIndexes[sorted_indexes[i - 1] + 1] == (0,0):
            bestIndexes[sorted_indexes[i - 1] + 1] = (0, currEl[3])
        # print(bestIndexes)

        eqItem = bestIndexes[sorted_indexes[i - 1] + 1][0]
        currElSize = currEl[0] * (currEl[2] - currEl[1])

        maxSize[sorted_indexes[i - 1] + 1] = max(currElSize + maxSize[eqItem], maxSize[sorted_indexes[i - 2] + 1])

    # print(maxSize)
    # print('--------------')
    # for i in range(1, n + 1):
    #     print(maxSize[sorted_indexes[i - 1] + 1], end=", ")
    # print('\n--------------')

    print(maxSize[sorted_indexes[n - 1] + 1])

T = [(2, 1, 5, 3),
     (3, 7, 9, 2),
     (2, 8, 11, 1)]
p = 5

# T = [(3, 3, 4, 19), (3, 11, 17, 7), (4, 8, 15, 15), (3, 1, 7, 15), (4, 12, 17, 7), (3, 1, 7, 3), (4, 8, 9, 7), (3, 11, 18, 15), (4, 20, 31, 19), (3, 17, 26, 7)] # 49
# p = 20
print(select_buildings(T, p))
#

For example it's not working for such an array:
T = [(5, 3, 4, 15), (4, 1, 11, 11), (3, 1, 6, 7), (2, 1, 7, 3), (3, 4, 7, 19), (4, 15, 28, 7), (3, 1, 2, 7), (4, 7, 14, 19), (3, 8, 22, 15), (4, 13, 17, 3), (3, 12, 14, 15), (4, 23, 34, 15), (3, 20, 23, 3), (4, 13, 15, 15), (3, 8, 14, 11), (2, 23, 26, 19), (3, 16, 29, 11), (4, 27, 32, 15), (3, 28, 30, 19), (4, 19, 36, 11), (3, 18, 22, 19), (3, 33, 46, 7), (4, 28, 35, 3), (3, 25, 27, 7), (2, 30, 32, 11), (3, 23, 31, 11), (2, 32, 38, 11), (3, 29, 38, 11), (4, 22, 26, 15), (3, 35, 45, 15), (4, 24, 25, 3), (3, 33, 35, 3), (2, 30, 32, 19), (3, 31, 47, 7), (4, 34, 38, 11), (3, 43, 52, 3), (2, 34, 36, 3), (3, 35, 37, 3), (3, 36, 39, 19), (2, 25, 28, 7), (3, 44, 45, 3), (3, 41, 42, 19), (3, 60, 71, 19), (4, 35, 39, 11), (3, 48, 58, 7), (4, 51, 52, 15), (3, 38, 46, 7), (4, 43, 50, 3), (3, 50, 51, 11), (4, 41, 45, 7), (3, 50, 53, 15), (3, 37, 39, 3), (3, 52, 55, 11), (3, 43, 46, 3), (2, 56, 59, 3), (3, 55, 58, 15), (3, 44, 57, 15), (2, 69, 82, 19), (3, 68, 84, 15), (3, 63, 67, 11), (2, 70, 76, 15), (3, 75, 90, 11), (2, 60, 69, 15), (3, 69, 78, 7), (2, 64, 66, 11), (3, 69, 71, 7), (3, 70, 74, 19), (4, 51, 59, 7), (3, 62, 64, 15), (4, 67, 78, 11), (3, 62, 63, 19), (3, 75, 76, 11), (3, 70, 79, 3), (3, 71, 74, 7), (4, 80, 85, 3), (3, 73, 75, 7), (4, 70, 73, 19), (3, 69, 77, 19), (4, 62, 80, 15), (3, 87, 96, 11), (3, 90, 92, 19), (3, 83, 92, 7), (2, 86, 92, 7), (3, 77, 81, 3), (3, 84, 86, 15), (3, 71, 76, 3), (2, 88, 89, 3), (3, 87, 90, 3), (2, 86, 89, 15), (3, 103, 111, 3), (3, 88, 91, 7), (2, 95, 97, 7), (3, 96, 102, 11), (4, 97, 100, 7), (3, 98, 103, 3), (2, 93, 96, 11), (3, 92, 99, 3), (2, 95, 98, 7), (3, 96, 102, 7), (3, 105, 107, 7)]

p = 20

My code: answer = 224 ( capacity)
Correct Answer: 152 ( capacity )

lean walrus
# remote wind what's a better way to write this hash table?

sum of items isnt good hash
use multiplication:

def better_but_still_bad_hash(text: str, bucket_count: int) -> int:
    result = 1
    for char in text: # for x in range(len(a)) is a bad practice
        result *= ord(char) + 1 # add 1 to prevent multiplication to 0 ('\0')
    return result
jolly mortar
#

java's set uses sum of items as the hash

#
jshell> Set.of(1,3,78).hashCode()
$1 ==> 82
#

well, sum of hashes of items

vocal gorge
#

doesn't Java also make HTTP requests to calculate the hash of URLs or something 🥴

sweet berry
#

Hi! Im very new to python, im watching YT guides to learn the basics but cant figure out why this isnt working.

weight = int(input("Weight: "))
unit = input("(K)g or (L)bs: ")

if unit.upper() == "K":
converted = weight / 0.45
print("Weight in Lbs: " + str(converted))
else:
converted = weight * 0.45
print("Weight in Kgs: " + str(converted))

vocal gorge
#

Uhh, is it not working?

sweet berry
#

i get the runtime error: int.lbs = (weight * 0.45)
TypeError: can't multiply sequence by non-int of type 'float'

hallow flame
#

but it works fine?

vocal gorge
#

this can only mean the code you're showing us isn't the code you're actually running.

hallow flame
#

yeah

lean walrus
raven kraken
#

Can anyone recommend me a youtube channel from where I could learn dfs and bfs?

hushed badge
#

Having a really hard time while trying to break my own encrypting algorithm.

#

where is the link...

#

https://pastebin.com/FTAGUTp7, encrypt_txt_files() encrypts txt files like this (decrypt_txt_files() works for passing files but my stupid fucking brain cant even crack its own encrypted shit)

#

but really having hard time when I try to solve some very basic algo that my sick brain created, helps appreciated ofc.

vocal gorge
#

Wait, so do you have a working decryption function or not?

#

also, looking at what you're doing - if you can't reverse it properly, it might be that your encoding is ambigous (that is, there's more than one message corresponding to one ciphertext) or at least that you can't decode it via a greedy algorithm.

#

Yup, looks like you have tons of codes that are prefixes of others - e.g. & gets encoded as A AAA A A A while a as A AAA. So when you see A AAA when decoding, you can't know right away whether this is an a, or part of a &

#

oh, or are you using an extra space between every character? that'd solve the ambiguity

inland perch
#

my computer crashed while encrypting 15k line of text

#

4 gb ram gang

inland perch
#

or I can do " "

vocal gorge
#

Ah, yeah, iterating here is silly. The main feature of dicts is that you can very quickly (no matter how large the dict is) look up a key in it.

#

Instead of iterating over the original dicts, construct the reverse dicts - mapping encoded strings to the original letters - and look up in them.

inland perch
#

so how will that work

#

like keys and values are swapped

#

and combination will match keys

vocal gorge
#

Yup

inland perch
#

for extra space in words...

#

" " this will be enough right? with 2 spaces

vocal gorge
#

and then you'd do

s = ""
for letter in msg:
    s += letter
    if s in reverse_dict:
        deciphered += reverse_dict[s]
        s = ""

or something like that

vocal gorge
#

By the way, I don't really see why you need separate dicts for lower and upper letters. Why not just have one?

inland perch
#

just using like it is now

#

trying your tips, thanks a lot matey

haughty mountain
solid ember
#

What is the easiest solution for this?

min_gas = 20
max_gas = 40
rarity = 1  # Can be between 0% and 10%

# If rarity is 0, then the gas variable will be 40
# If rarity is 5, then the gas variable will be 30
# If rarity is 10, then the gas variable will be 20

gas = ...
vocal gorge
#

uhh, max-2*rarity?

inland perch
#

like simply everything is decoded to E or e

vocal gorge
#

if you use double-spaces to separate letters, then you can get all letters by just msg.split(" ")

#

then map them using the dict, and assemble into a message

inland perch
#

yeah solved that letter problem by putting "00" in the end of it, pretty similar solution

#

prolly need to rewrite dict as you said

#

everyone is matching everyone

static fossil
#

hello pips, its been a long day and I literally cant wrap my head around this, can someone help :
if any(device for device in list_of_devices):

#

how is this working as a condition, if device isnt specified anywhere outside of this line

sweet berry
#

hi, im making a kg to lbs converter and i cant get this to work, anyone know what wrong with?

weight = int(input("Weight: "))
unit = input("(K)g or (L)bs: ")

if unit.upper() == "K":
    converted = weight / 0.45
    print("Weight in Lbs: " + str(converted))
else:
    converted = weight * 0.45
    print("Weight in Kgs: " + str(converted))
#

i get the error:
int.lbs = (weight * 0.45)
TypeError: can't multiply sequence by non-int of type 'float'

haughty mountain
#

check that you're actually running the right thing

sweet berry
#

very new at pycharm, thanks 🙂

#

yeah now it works, man im such a potato

#

thanks alot algmyr

fiery cosmos
#

hello i have a pandas dataframe with a column that looks like this

#

how can i select rows within a time range

keen hearth
fiery cosmos
#

okay. thank you

sour badger
#

i want to get into competitive programming but does anyone have any book suggestions on the basic skills needed. doesnt have to be specific to python

tame chasm
#

Hello world =), I am looking for an algo to make an icosahedron as pentagons and hexagons. There are plenty for making the icosahedron itsel which I have done but scratching my head as to how to group the triangles correctly. Thanks

haughty mountain
#

!e so basically this

from collections import Counter
s = 'abdicated'
print(''.join(letter*count for letter, count in sorted(Counter(s).items(), key=lambda x: x[1], reverse=True)))
halcyon plankBOT
#

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

aaddbicte
gaunt parcel
#

Can someone explain why the algorithm described in the link runs in O(|V|+|E|) time? https://en.wikipedia.org/wiki/Degeneracy_(graph_theory)#Algorithms

In graph theory, a k-degenerate graph is an undirected graph in which every subgraph has a vertex of degree at most k: that is, some vertex in the subgraph touches k or fewer of the subgraph's edges. The degeneracy of a graph is the smallest value of k for which it is k-degenerate. The degeneracy of a graph is a measure of how sparse it is, and ...

split tangle
#

guys why im having this error?

agile sundial
#

did you mean def meme_dodo(**ddd)

split tangle
agile sundial
split tangle
split tangle
#

why im not getting the 'key' and im only getting the value?

agile sundial
#

you used value twice in your print statement

split tangle
agile sundial
#

key?

#

well, because you didn't use the key

split tangle
#

no wait lol

split tangle
agile sundial
#

you did not use it

#

you changed the string, but you still reference value twice

split tangle
# agile sundial you changed the string, but you still reference `value` twice

lol I'm confused, this is my code can you tell me where should i change things:
`def meme_dodo(**kwagrs):
print(kwagrs)
print(type(kwagrs))

meme_dodo(name='gmail', lamp='billy', animal='bird')

def meme_dodo(**kwargs):
for key, value in kwargs.items():
print("key: ",value,"\t\t", "key: ",value)

meme_dodo(name='gmail', lamp='billy', animal='bird')`

agile sundial
#

fwiw, this is the wrong channel for this. you should get a help channel, #❓|how-to-get-help
but in your print statement, you use value twice, instead of key once and value once

jolly widget
#

i = 0 x = 10 if i < x : x += 1 print(x) if i == x : break

how to ask it to restart again after the break command, other than

**if i == x : i = 0**

#

i want it to break stop the algo, and reset all values and start again like its the first time if that makes sense

brave hound
#

use a loop

#

and break doesn't work outside a loop

#

!e

i = 1
x = 10
while i < x:
    i += 1
    print(i)
halcyon plankBOT
#

@brave hound :white_check_mark: Your eval job has completed with return code 0.

001 | 2
002 | 3
003 | 4
004 | 5
005 | 6
006 | 7
007 | 8
008 | 9
009 | 10
jolly widget
# brave hound use a loop

thanks for the reply, understood..
my main issue is that after the condition is met i want it to reset all values and restart allover again like it is the first time is that a possible thing?!

#

it runs good, just when it is done throw all the loops, it says nothing left to do and stops

i want it insted to reset all values to default and start all over again

#

i hope this makes sense

brave hound
#

u want to restart the loop?

jolly widget
#

the whole algo, but i can't use while True:
or anything similar because i want it to take a chance to reset all appends and other varaiables

brave hound
#
i = 1
x = 5
while i < x:
    i += 1
    if i == x: 
        i = 0
    print(i)

like this?

jolly widget
#

let me write a sample code one second!

#

i = 0
x = 5
r = list ()
while i < x :
i += 1
r.append (i)
if i == x
r.append(x) # just as an example
print(r, i)

now what will happen it will print it will print and end the app

what i want it to do is print and end the app obviously, but i want to know if there is a way to make it relaunch it self automatically after it end, why is that because the algo has litreally 30 appends and maybe 50 diffrent loops if statments and api requests and these being live data might change

so i want it to take a chance to end and then add a peace of code that will force it restart, but with all the values being default like it has right now started, i know if i add while True :
at the begining that will do the trick but i want it to stop first and ask it to relaunch all over again if that is an option !

#

so to make it more simple, is there a peace of code that will allow an app to stop after its done then make it relaunch without me having to press the run botton (shift+f10) manually

acoustic nova
#

is anyone worked with selenium library and proxies?

main idol
#

can anyone explain sorting algorithms in python and their time complexities? I know the sorting algos in python are searching, selection, duplicates, and distribution and the significance behind measuring their runtime complexity but are there other sorting algos and time complexities?

warped yoke
#

where do i go for help with my code

lament shale
# main idol can anyone explain sorting algorithms in python and their time complexities? I k...

Merge Sort, Quick Sort = O(nlogn) Time
Selection Sort, Bubble Sort = O(n^2) Time
Insertion Sort = Average Case -> O(n^2)
Shell Sort = O(n*(log(n))^2) -> Not Sure

This YouTube playlist is great for learning Searching and Sorting Algorithms.
https://youtube.com/playlist?list=PLzgPDYo_3xunyLTJlmoH8IAUvet4-Ka0y

main idol
#

thanks a bunch @lament shale

grim flare
#

guys i have a concern

#

i know that python is relatively slower than cpp

#

so is it still ok to practice dsa in python?

cold smelt
jolly widget
cold smelt
jolly widget
oak horizon
#

Question for anyone who knows both Javascript and Python. I'm trying to convert a naive bayes algorithm written in Javascript to Python. What am I missing here?

subtle coyote
#

i'm missing my glasses

fallow agate
#

Hi,
If anyone comfortable with AVL Tree Left-Right rotation, Please clear my confusion. I am struggling to understand since so much time.

#

Let’s consider below Binary Search Tree

#

My teacher is saying as below:

#

But, my doubt is:
disbalancedNode = 30
So, disbalancedNode.rightChild = None
So; newRoot = None
But, as per my Teacher; newRoot = 20. How is that?

#

if you need any further information, to clear my doubt, please ask me..

severe tusk
#

Maybe I'm misunderstanding, but it seems like the arrow is saying after only the first line of the function, newRoot = 20. "After execution of this step"

fallow agate
austere shell
#

Hi if i want to do the incremental hash from one hash table to another how would i do it that each operation (Find, Insert,Delete) would take constant time ? im completely lost with it :(( any help appreciated

toxic locust
#

Are there any tricks or patterns for writing a temporarily idempotent function that returns a random value? This sounds a little oxymoronic, so let me explain the details. I have a web-app and a user action sets some random date in the database. But if the user for some reason "replays" that action I don't want to reset that date to a new one. I know that I can simply check the db and see if a value is there and then only update if it is not there. But ideally I would like to avoid the additional db request.

#

So really the question is, is there a way to generate a random number that is dependent on the date/time (Technically it would be random in that case) such that as long as the date is the same the random number output is the same?

shut breach
toxic locust
shut breach
#

if you hash the datetime you get a number that is dependent on the datetime

toxic locust
#

I see, I need to think about that for a bit.

slim vault
#

what is the purpose of the output value being random?

#

if you write a function that returns the current date in a YYYYMMDD format, it will keep returning the same value throughout the day

toxic locust
slim vault
#

if you add the requesting user's ID and maybe some identifier of the operation to it, you get something that uniquely identifies a user doing some action in a given day, which can be used to remember that this specific user cannot perform the same action until we reach the next day - is this roughly what you're looking for?

toxic locust
#

I can use hashid and simply trim the last digits and round or something.

fiery cosmos
#

so i just made this simple code and i was wondering if this is actually a algo: ```py
def test():
n, i = random.randint(1, 100), random.randint(1, 100)

if n > i:
    if (n % n) == 0:
        value = str((n / 2)**2)
        print('n: Resolved even number:' + value)
    
    if (n % n) != 0:
        value = (n * 3) + 1
        print('n: Resolved odd number:' + value)

if n < i:
    y = math.ceil(i)
    if (y % y) == 0:
        value = str((y / 2)**2)
        print('y: Resolved even number:' + value)
    
    if (y % y) != 0:
        value = (y * 3) + 1
        print('y: Resolved odd number:' + value)

test()

shut breach
#

an algorithm is just a series of steps to solve a problem

fiery cosmos
#

well this code does that no? or im wrong

shut breach
#

in a sense, all code solves some problem
whether this code solves your problem is hard for me to say because I don't know what it is

fiery cosmos
#

well yeah maybe its a little bit hard to understand what this is xd

shut breach
#

which one?

full sonnet
fiery cosmos
#

whats wrong there?

fiery cosmos
full sonnet
fiery cosmos
#

oh

#

wait loop for what?

full sonnet
#

Because it takes many steps to bring n to 1 in some cases

#

suppose n = 10

#

10 % 2 == 0 so we return n / 2 = 5

#

5 % 2 == 1 so we return n * 3 + 1

#

16 % 2 == 0 so we return n / 2 = 8

fiery cosmos
#

oh

full sonnet
#

and you loop until n == 1

fiery cosmos
#

then ig everything is wrong?

full sonnet
#

It's not the collatz conjecture

#

yeah

#

I suggest you do it both ways

#

recursively and using a while loop

fiery cosmos
#

sure

quasi siren
#

Looking for project ideas as a beginner with python. Was thinking about something like historical data sets and seeing if python can find markers for reccesions

#

Am i being niave on how achievable that would be ?

full sonnet
quasi siren
#

Thanks for the reply

#

Nice so im not taking the piss then

feral trail
#

I'm solving this problem on leetcode

#

But I don't know why I'm getting infinite recursion

class Solution(object):
    def floodFill(self, image, sr, sc, newColor):
        rows, cols , color = len(image), len(image[0]), image[sr][sc]
        def dfs(row, col, color):  
            if row < 0 or row >= rows or col < 0 or col >= cols:
                return
            current = image[row][col]
            if current != color or current == newColor:
                return
            current = newColor
            dfs(row + 1, col, color)
            dfs(row - 1, col, color)
            dfs(row, col + 1, color)
            dfs(row, col - 1, color)
        dfs(sr, sc, color)
        return image
#

Nvm I'm stupid I was redeclaring current instead of modifying image[row][column]

toxic locust
#

Let's try the eval again.

#

!e

from datetime import datetime, timedelta

def set_pseudo_random_future_date(uid, delay=365, range=30):
    today = datetime.utcnow()
    multiplier = (((today.day + today.month) * today.year * int(uid)) % 51) / 51
    delta = timedelta( delay + round(multiplier * range - 0.5 * range) )
    return datetime(today.year, today.month, today.day) + delta

print(set_pseudo_random_future_date(42))
halcyon plankBOT
#

@toxic locust :white_check_mark: Your eval job has completed with return code 0.

2023-04-20 00:00:00
fallow agate
#

Hi, Anyone please clarify this. I am struggling since 3 days.

#

Let’s consider below Binary Search Tree

#

My teacher is saying as below:

#

But, my doubt is:
disbalancedNode = 30
So, disbalancedNode.rightChild = None
So; newRoot = None
But, as per my Teacher; newRoot = 20. How is that?

vocal gorge
#

I'd guess this is talking about executing it with disbalancedNode being the 10 one. Hence the circle around that subtree.

jaunty cave
# fallow agate

yes, this would return None if this rotateLeft applied directly to this tree. I think the correct way is:

  1. applying rotateLeft to left-sub-tree, so the result would be like this:
         30
         /
        20
        /
       10
  1. And then apply rotateRight to the tree in step 1 (above), which will return newRoot = 20, so the final result is:
         20
         /\
       10  30
hushed badge
#

can anyone help me understand why postfix and prefix expressions are so important in algos or data structures

#

like I am studying it because huge portion of my midterm will be from them, but cant find motivation behind it, from start why they even exist

haughty mountain
#

postfix and prefix notation is super easy to work with compared to infix

hushed badge
#

but isnt infix much much readable compared to polished notations

haughty mountain
#

expressions like a*b + c*d has awkward precedence rules

#

readable to who?

#

human yes

#

machine no

hushed badge
#

oh

#

well..

#

thank you, but still huge weirdness why this is huge part of my data structures course :/

haughty mountain
#

it would make more sense if you were writing a parser

hushed badge
#

yeah probably

#

they are just bashing us to teach how computers or compilers work, most of the things

#

is this normal by the way, like is the main purpose of computer sciences curriculum is this?

haughty mountain
#

it feels a bit weird for a data structures course

#

other than maybe as an application of stacks or something

hushed badge
#

nvm will not judge any kind of nonsense thing going on this course lol

haughty mountain
#

there are more classical examples where a stack is useful, e.g. if I give you an expression like ([]{[])}, is this a "valid" bracket sequence? i.e. does every start have a corresponding end, and are things properly nestes

#

in this case it's not valid because we encounter an ) when we expect a closing }

#

I guess there are parallels between this and parsing prefix expressions

hushed badge
hushed badge
#

I need to continue to learn it someway... thx for making it at least more senseful @haughty mountain

haughty mountain
#

fwiw postfix being easier to deal with is a pretty big reason why lisp like languages were common in early computing

dapper sapphire
#

Should you know the Brute Force approach for every question?
Or can you just jump to Optimized solution if you find Brute Force hard to explain/implement?

zealous nymph
#

in an interview setting (which is what I assume you're asking about), I would at least mention the brute force solution

dapper sapphire
#

Yeah, I meant in an interview setting.

#

And are you expected to implement Brute Force solution?

I can mostly figure out Brute Force solutions, but there are always question that are hard to implement.

next loom
#

I am trying to make something akin to a convolution algorithm akin to what openCv uses to blur images and what not. I'm confused how to create a "stride" process for my kernel matrix to move around the 2D array I wish to use my kernel on. right now I have an algortihm that only works if the kernel and the 2D array are the same size, please see here: ``` import numpy as np
k=np.array([[1,2,3,4,5],[6,7,8,9,2],[3,4,5,8,12],[4,6,23,14,5],[13,6,3,4,6]])

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

def wash(rc,w):
acc = 0
for i in range(len(rc)):
for j in range(len(rc[0])):

        for m in range(len(w)):
            for n in range(len(w[0])):

                if i==m and j==n:
                    acc+=(rc[i,j] * w[m,n])
print(acc)

rc = np.array([[2,3,4],[3,5,2],[0,9,8]])
wash(rc,w) ```

zealous nymph
dapper sapphire
#

ok thank you!!

haughty mountain
#

why would you implement something where you know a better solution?

#

sometimes brute force can be improved upon to make it better, but otherwise writing a brute force solution is just a waste of time

dapper sapphire
#

I dont know that's why I asked.

I dont know what the leetcode style coding interview would look like, so I wondered if the interviewer could be like, "ok forget the optimized approach. Can you implement a brute force instead", or "Optimized approach looks good and we still have plenty of time. Can you implement Brute force now".

haughty mountain
#

the latter for sure no

zealous nymph
#

can't imagine a situation where the interviewer would ask for a worse solution after you finish a better one

haughty mountain
#

if you hear the former you're probably either doing quite badly, or the interviewer wants something simple first to then ask for improvements on

dapper sapphire
#

ok I see.

sonic lagoon
#

Hello every one

#

The maximum number of subdivisions (100) has been achieved.
If increasing the limit yields no improvement it is advised to analyze
the integrand in order to determine the difficulties. If the position of a
local difficulty can be determined (singularity, discontinuity) one will
probably gain from splitting up the interval and calling the integrator
on the subranges. Perhaps a special-purpose integrator should be used.

#

can someone explain to me

#

and what should I do

limber orbit
#

Hey guys! This can be a rather stupid question, but I'm struggling to understand 1 thing:

suppose we have a binary search algorithm:

def binarysearch:
    low = 0
    high = len(list) - 1

    while low <= high:
        middle = low + (high - low) // 2

        if numbers[middle] == number_to_find:
            return middle
        elif numbers[middle] < number_to_find:
            low = middle + 1
        else:
            high = middle - 1
    return -1

Why do we add 1 to low and subtract 1 from high?

jolly mortar
#

low and high represent the first and last indices at which the element can potentially occur
if the element is greater than the middle, the first index it can occur at is middle + 1

#

likewise if its smaller, the last index it can occur at is middle - 1

haughty mountain
limber orbit
#

hmmm, you mean, that we do it because lists in python starts from 0 and not from 1?

haughty mountain
#

e.g. searching for the first integer where cond(x) is True

l = 0 # assume cond(0) == False
r = n # assume cond(n) == True
while r - l > 1:
  mid = l + (r - l)//2
  if cond(mid):
    r = mid
  else:
    l = mid
# now, l and r are next to each other and are the last False value and first True value respectively
limber orbit
#

yeah

haughty mountain
#

having l and r different sides of the False->True transition makes things quite nice

#

and the if check and assignment is pretty obvious, if cond(mid) is true we should move r to mid, because r is on the True side of the transition

#

cond in your case would check some value at an index in a list, but the technique is a lot more general

limber orbit
#

yeah I see

#

it's like a template

#

you can apply that binary search "template" to wide range of problems

just change that condition

#

yeah seems good

haughty mountain
#

I like to point this out because I see a lot of people assuming that binary search is something you do on arrays, while in reality it's very general

limber orbit
#

thanks for making things a lil bit clearer for me!
having a tough time to implement algorithms in python

haughty mountain
#

np

limber orbit
#

sometimes I feel like I understand how it works, and I can explain it on paper...
but when it comes to python.. ehh.. My brain goes absolute blank

haughty mountain
#

it's all down to practice translating thoughts into code

#

you get used to it

limber orbit
#

"practice makes perfect"
I agree. Thanks for help!

haughty mountain
#

in the beginning you'll struggle a bit with even simple algos, then you get used to the simple stuff and start being able to use those as building blocks for other algorithm

#

and so on

#

I like to think about data structures and algorithms as useful tools in your toolbox for solving algorithmic problems

#

binary search is a very useful tool to have, it's useful in a lot of places

limber orbit
#

ha ha yes I'am struggling even with simple ones, for instance binary search. I've started reading a book "Grokking Algorithms" and I faced that problem again.. I understand how it works, I can explain it on paper, but implementing binary search in python.... :/

#

I'm just preparing for a code interview. I guess there are still some jobs which doesn't really require knowledge of algorithms...

gleaming bough
#

guys how can i write

if a list is descending:
  do something (e.g. <=)
elif a list is not descending:
  do the exact opposite (e.g. >=)

with just one if-statement?

the clue ive been given is by doing:

if a list is descending and [something] or if a list is not descending and [again something]:
  do something
wide flower
#

does know how to switch from using the nltk to spacy

fiery cosmos
#

hey, i have a question about merge sort

#
def merge_sort(array):
    if len(array) > 1:
        midpoint = int(len(array) / 2)
        left_array = array[:midpoint]
        right_array = array[midpoint:]
        #recursive call on left and right side
        merge_sort(left_array)
        merge_sort(right_array)
        #merge step, compare the left most element of one array to the left most of the other
        leftpointer = 0
        rightpointer = 0
        mergedpointer = 0
        while leftpointer < len(left_array) and rightpointer < len(right_array): #check if both left and right have values in it
            if left_array[leftpointer] < right_array[rightpointer]:
                array[mergedpointer] = left_array[leftpointer]
                leftpointer += 1
            else:
                array[mergedpointer] = right_array[rightpointer]
                rightpointer += 1
            mergedpointer += 1 #increment the position of the merged pointer we do this for both cases
        #once we have ran out of elements in either one of the sublists, we can add the remaining elements to the array

        while (leftpointer < len(left_array)):
            array[mergedpointer] = left_array[leftpointer]
            leftpointer += 1
            mergedpointer +=1 
        
        while (rightpointer < len(right_array)):
            array[mergedpointer] = right_array[rightpointer]
            rightpointer +=1 
            mergedpointer += 1
        

array = [5,23,1,2,45,6,4,2,1,5,6,1,3,4,6,3,2,1,3,4,5,6,3,2]
merge_sort(array)

print(array)```