#algos-and-data-structs

1 messages Β· Page 133 of 1

fiery cosmos
#

They asked to show this in Big O notation but there are no answers

  1. O(n^2)
  2. O(n^3)
#
  1. O(n^3)
  2. O(2^n)
  3. O(n!)
#

is this correct?

trim fiber
fiery cosmos
#

how so?

trim fiber
#

2^n < 3^n for n > 0

fiery cosmos
#

oh okay... i see

#

for this is it
left) O(n^2)
right) O(n)

trim fiber
slender sandal
#

4 is not 3^n

fiery cosmos
#

@slender sandal what is your take?

slender sandal
#

uh

trim fiber
#

Check plots

#

After some n 3^n will be always bigger than 7(2^n)

slender sandal
#

right

#

never mind me

fossil pulsar
#

I think that it's a basic question which is basically a grading system.... It can be done with if else but I want to make it without if else or any other loop or advance topics like classes or anything

#

Let me know if you need to see the code

thorn prism
#
if marks < 80:
  print(C)
elif marks < 90: # elif means else if
  print(B)
elif marks < 100:
  print(A)

You could also put another else below the last elif

deft locust
#

how would i find number of subarrays all of whose elements except the first and last are less than first and last element?

#

(without O(n^2) that is)

#

example:
2 37 4 32
output:
4 because (2, 37) (37, 4) (4, 32) and (37, 4, 32)

#

there could be a DP approach but i'm not able to find the base case in recursion

#

ping me if you reply ^^

winged plover
#

I am not very sure of this approach but you can try something like :-

Find the 2 maximum distinct numbers in list
Traverse the list and split them about those two numbers
Here in this case you found one slice till now
Then pass those the split lists you got into the same function again... Take the return and add it to the total lists found

#

Oh fuck I forgot to tell this up there... Don't pass lists with less than 3 elements into the function while recursion
Just add the 2 elemented lists to the count I guess
And then garbage the others I guess

#

@deft locust would that work?

#

Oh hmm wait I don't thing it would pithink I guess I over looked some cases shiet

#

@deft locust is repetition of elements allowed?

deft locust
deft locust
winged plover
#

Are you sure this is not the type of questions which has one and only one solution?
Best I could thing of was O(n^2)

#

I mean I could be missing some solution

deft locust
#

same, all the solutions i tried were O(n^2)

winged plover
#

But O(n) really seems like an out of the box algo for it

deft locust
#

O(n) or O(nlogn) works too

#

the input list can have 10^6 elements

#

i need it to complete in 3 secs

#

O(n^2) would make it equivalent to iterating through 10^12 or smth πŸ’€

winged plover
#

That would definitely not be my first choice πŸ’€πŸ’€

supple peak
#
rows = 5
cols = 5
for i in range (rows):
    for j in range (cols):
        ## I want a logic for presenting data like 
        ## 00 01 02 03 04 05 \n
        ## 10 11 12 13 14 15 \n
        ## ....
        ## 50 51 52 53 54 55 \n
onyx umbra
#

is this what you are looking for?

onyx umbra
halcyon plankBOT
#

@onyx umbra :white_check_mark: Your eval job has completed with return code 0.

001 | 00 01 02 03 04 05 
002 | 10 11 12 13 14 15 
003 | 20 21 22 23 24 25 
004 | 30 31 32 33 34 35 
005 | 40 41 42 43 44 45 
006 | 50 51 52 53 54 55 
jolly mortar
#

@deft locust building a max-heap from the list in O(n) would be a good starting point, so that from a list like [14, 6, 12, 0, 16, 9, 13, 1, 2, 4] you get a heap like

#

then i think the solution is to sum the number of children of each node

shut breach
#

!mute 323179820009652225 πŸ”Ž

halcyon plankBOT
#

:incoming_envelope: :ok_hand: applied mute to @willow jackal until <t:1633105633:f> (59 minutes and 59 seconds).

deft locust
#

i don't know what max-heap is, but i'll read it up

jolly mortar
#

can think of it like a tree where the value of the parent is always more than that of its subtrees

deft locust
#

ah

#

that seems extremely convenient for this question πŸ‘€

#

i should do data structs properly before trying CP :(

tropic glacier
#

What's cool is you can build a max heap directly in an array structure, and there are algorithms for pushing and popping nodes that work automatically in log time

jolly mortar
#

i think the ends of the array have to be handled differently in some cases, idk

sterile rain
#

hi.

import re
liste = ["1", "2", "5a", "10b", "abc"]
#1
for i in liste:
    trueliste = []
    if re.search("[0-9]", i):
        trueliste.append(i)
print(" ".join(trueliste))```
i wrote this code but returns null
jolly mortar
#

you reset it to an empty list in every loop iteration

sterile rain
#

what can i do

#

i'm still learning python

jolly mortar
#

move the trueliste = [] line outside the loop

sterile rain
#

oh thanks.

#

how can i remove a data from an list?

#

example adding:

liste = []
liste.append('abcdef')```
#

like this but not appending, removing

#

.remove()?

lime fable
#

yes liste.remove('abcde')

sterile rain
#

thanks

#

my new code is this:

#

but output is

#

i dont want 10b

lime fable
#

make a regex that searches for an element that starts with a digit/number and ends with an alphabet/word that's what you want right?

sterile rain
#

ohh

#

i remember .isdecimal()

#

but how can i edit it to include

lime fable
#

its most likely going to be i.isdecimal() in your case

sterile rain
lime fable
#

then why are you trying to use regex, doesn't make sense

lime fable
sterile rain
#

is 're' regex?

lime fable
#

mhm

sterile rain
lime fable
#

move that isdecimal() logic in the first loop

#

and remove the regex searching you're doing, it should work fine then

sterile rain
#

is this ok?

lime fable
#

yes that's going to give you a list with all the elements that contain a letter or space

#

if you want a list with only numbers you should remove the not from your logic

sterile rain
#

doesn't this method send us values with letters or spaces?

lime fable
#

you can read about it here

sterile rain
#

thx

#

thanksss

#

ok, how can i do this with regex?

fiery cosmos
#

Hello, I don't know how to solve this problem, can you tell me which algorithm would be ideal?
How many drivers will be able to receive a suitable car, assuming that the cars are optimally distributed? Note that each car can only be assigned to a maximum of one driver. Input The first line contains N integers: Li is the minimum speed of driver i . The second line contains N integers: Ri is the maximum speed of driver i The third line contains M integers: the speed of the cars to distribute

dense forge
#

hello guys, I need some help with regex in python. Suppose there are several strings like 'QR1.png', 'QR2.png', 'QR14.png' or 'QR100.png' like these are the strings of file names. I want to exactly extract the number like any number containing digits from 0 to 9 just after the word 'QR', like if the file name name is 'QR100.png' then the result will be 100. But if the file name is 'QRabracadabra.png' then it will return nothing. How can I do this in python? Please, help, it is too much appreciated

dense forge
winged plover
#

!e ```py
import re
reg_str = re.compile(r"^\d+?(.\d+?)?$")
for i in ["1", "2.2", "2.", "a1"]:
print(reg_str.search(i))

halcyon plankBOT
#

@winged plover :white_check_mark: Your eval job has completed with return code 0.

001 | <re.Match object; span=(0, 1), match='1'>
002 | <re.Match object; span=(0, 3), match='2.2'>
003 | None
004 | None
dense forge
#

extract any number exactly after the word 'QR'

sterile rain
#

thx

dense forge
#

and that will also ends with '.png'

#

extract any size of numbers from a string that will start with 'QR and end with '.png'

#

suppose a string 'QR4101kkgf700.png' then result will only be 4101, 700 will not be included

winged plover
#

!e ```py
import re
reg_str = re.compile(r"QR(\d*?).png")
test_list = ["QR1.png", "QR99.png", "QRerhui.png", "QR98he.png"]
out = {}
for i in test_list:
try:
out[i] = reg_str.search(i).group(1)
except AttributeError:
out[i] = None
print(out)

halcyon plankBOT
#

@winged plover :white_check_mark: Your eval job has completed with return code 0.

{'QR1.png': '1', 'QR99.png': '99', 'QRerhui.png': None, 'QR98he.png': None}
dense forge
#

woow

#

are you using dictionary here?

winged plover
#

basically if a match is found you can just see group(1) of it

#

else it will return None type
which will gave an error

dense forge
#

what group() does

winged plover
dense forge
#

sorry to say I never learnt regex, that's why I'm asking

#

btw thank you for your help

winged plover
dense forge
winged plover
idle pier
#

am currently doing 463. Island Perimeter

def islandPerimeter(self, grid: List[List[int]]) -> int:
        rows = len(grid)
        cols = len(grid[0])
        
        result = 0
        
        for r in range(rows):
            for c in range(cols):
                if grid[r][c] == 1:
                    result += 4
                    
                    if r > 0 and grid[r-1][c] == 1:
                        result -= 2
                    
                    if c > 0 and grid[r][c-1] == 1:
                        result -= 2
                        
        return result```
am having trouble understanding 
```py
if r > 0 and grid[r-1][c] == 1:
  result -= 2
                    
if c > 0 and grid[r][c-1] == 1:
  result -= 2```
fiery cosmos
#

But +4 otherwise for each land cell

#

It's an interesting way of doing it pithink kinda nifty it works out. Unintuitive but I guess it does about half the neighbor checks you'd normally have to do. (Though I wonder if bfs/dfs once you find land would be faster anyway)

paper yacht
#

If Arrays can be Abstract, doesnt it mean literally any data type can be made abstract?

brave oak
paper yacht
brave oak
#

well

#

one view of data structures

#

is that they can be defined in terms of what operations you can perform on them, and the associated semantics

paper yacht
#

lol

brave oak
#

you could define an interface for any data structure

paper yacht
#

ADTs always confused me

brave oak
paper yacht
#

Abstract

brave oak
#

okay, maybe think about it this way

paper yacht
#

heaps are not considered as ADTs

brave oak
#

an abstract data type is simply a description of a particular structure; what you can do to it, and how it will react

paper yacht
#

just what the input and output are

brave oak
#

you can reify (make concrete) this abstract data type by providing a particular implementation; e.g. Python's list

paper yacht
#

not how its produced

brave oak
#

but there are degrees of reification

brave oak
#

abstract data type (purely abstract model) <----------------------------> Python class (purely concrete)

#

however

#

in a language with interfaces

#

abstract data type (purely abstract model) <--------------- interface (less abstract) -------------> class (purely concrete)

#

less abstract because

#

the first one exists only as an idea

#

the second exists as code that represents that idea, but it's just an interface

#

it's not something you can actually use

#

so it is partially abstract and partially concrete

#

does that make sense

paper yacht
brave oak
paper yacht
#

so we can make any data type as abstract or as concrete as per need

brave oak
#

we can think of an Array interface, for sure

#

but even then...

#

Array, Set, LinkedList etc. can all be thought of as some sort of Collection

#

which in turn can be thought of as a kind of Iterable

paper yacht
#

hm.

#

makes sense

minor notch
#

Hey guys do you mind if I ask a question here about a line of code in my pandas

spring jasper
#

Sets dont have to be iterable do they?

#

They are in python but do they have to be

#

Lists are sequences, it makes sense for a sequence to be iterable
sets are just collections of unique elements

jolly mortar
jolly mortar
echo egret
#

hey can anyone help me with learning how to reverse a linked list?

brave oak
#

but it would be a rare collection indeed that wasn't iterable

#

I can't think of any way to use the elements of a collection other than random access and iteration

tropic glacier
#

Sets should be iterable, but there is no reason they should be ordered

keen hearth
#

But in order to be a collections.abc.Set in Python, an object does have to be iterable.

limber cypress
#

HI how can i verify if in my list is the same string , and if it is there how can i remove the twin

raven kraken
limber cypress
#

I found out solution but thnx

fiery cosmos
#

Can anyone help me understand how recursion works for this problem? https://leetcode.com/problems/path-sum/description/

#

This is the code that I saw from a YouTube video ```py
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:

    if not root:
        return False
    elif not root.left and not root.right and targetSum - root.val == 0:
        return True
    else:
        return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)```

I understand that the code is subtracting the targetSum from each node's value but when it gets to node 11 for ex, and it goes left and finds that the targetSum - the value isn't 0, doesn't the recursion just terminate? How is it going from 11 -> 2?

idle pier
vocal gorge
# fiery cosmos This is the code that I saw from a YouTube video ```py def hasPathSum(self, ...

hasPathSum on 5 calls itself on 4.
hasPathSum on 4 calls itself on 11
hasPathSum on 11 calls itself on 7
hasPathSum on 7 calls itself on None twice (the left and right children on 7, which are both None), which gives it two Falses, so it returns a False.
hasPathSum on 11 calls itself on 2 instead.
hasPathSum on 2 returns True, because the sum is right. That True is returned to the hasPathSum on 11, which returns True to hasPathSum at 4 as a result, and so on

#

doesn't the recursion just terminate? How is it going from 11 -> 2?
The 11 node does self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val). Since the left side of the or (which calls the function on 7) evaluated to False, the right side (which calls the function on 2) is evaluated.

idle pier
#

currently trying to improve my matrix solving skills because its one of my major weaknesses. am doing 1351. Count Negative Numbers in a Sorted Matrix on leetcode

def countNegatives(self, grid: List[List[int]]) -> int:
        row_len =len(grid[0])
        col_len = len(grid)
        
        row = 0
        col = row_len - 1
        counter = 0
        
        while row < col_len and col >= 0:
            if grid[row][col] < 0:
                counter += col_len - row
                col -= 1
            else:
                row += 1
        return counter```
Can someone explain it in a simple way?
raven kraken
#

watch from 22:52, if you got enough time then watch the entire video

raven kraken
#

Can someone suggest me how should I approach this problem?

onyx umbra
# raven kraken Can someone suggest me how should I approach this problem?

Larry solves and analyzes this Leetcode problem as both an interviewer and an interviewee. This is a live recording of a real engineer solving a problem live - no cuts or edits!

Problem: https://leetcode.com/problems/stone-game-ix
Twitch: https://www.twitch.tv/larryny
Discord: https://discord.gg/6QKRCdR
Instagram: https://www.instagram.com/lar...

β–Ά Play video
#

all leetcode solutions are onlineπŸ˜…

mild hound
raven kraken
mild hound
#

am I the only one who doesn't like leetcode ?

knotty magnet
#

no, but probably for other reasons

tropic glacier
#

I've never tried Leetcode

knotty magnet
#

for what it is, a problem solving site, it's alright

tropic glacier
#

What is it exactly? Some algorithm contests, basically?

knotty magnet
#

it's just a website with a bunch of programming problems and a solution checker

feral hound
#

its main aim is for practicing for interview questions

tropic glacier
#

Seems kind of strange for that purpose

feral hound
#

I think they also let you see questions specific to companies such as google for example

#

to be clear its for technical interviews specifically

tropic glacier
#

I mean sure, but as interview questions, are they really expecting you to rattle off a memorized solution like that? I would think it would be more valuable to get some insight into someone's thinking process.

feral hound
#

a lot of people do end up memorising solutions which might be bad for the companies they apply for since it gives a false evaluation of their skill level but leetcode doesnt care about that it just aims to help people pass interviews in anyway

tropic glacier
#

Eh, I think the interviewer can tell when you've memorized solutions. And they probably have to spend some time coming up with new problems, because they'd rather see your thought process πŸ˜›

knotty magnet
#

it's very easy to tell when someone doesn't actually understand and has just memorized the solution. just change one parameter in the problem and see how they deal with it

feral hound
tropic glacier
#

Sure. I guess in my job I'm actually not very computer science focused. People have to know quantum computation. But it's rare that someone actually knows what a data structure is.

knotty magnet
#

interesting, you'd think that'd be a prerequisite πŸ€”

tropic glacier
#

You'd be surprised. Quantum algorithms are very different from classical ones.

#

And it's a physics route.

feral hound
#

wouldnt you still need new data structures for your quantum computation?

tropic glacier
#

It really just doesn't work the same way.

#

In fact the no-cloning theorem forbids a lot of classical data structures.

feral hound
#

how would you store data then?

tropic glacier
#

You can't.

#

You can never copy a single bit. You have to operate in place on everything.

feral hound
#

im really confused now then lol how can you do any meaningful work if you cant store any data

tropic glacier
#

The problem is you can't copy a quantum state. So you can use quantum states to do something, but "storage" is a funny thing to talk about.

feral hound
#

hmmm its gona be interesting to learn about this in future when quantum computation actually becomes viable

tropic glacier
#

Curious what "viable" means to you. πŸ™‚ There are certainly a lot of challenges to overcome regarding system size, decoherence times, cryogenics, etc.

feral hound
#

since right now I know you can emulate a quantum computer but it ends up being a lot slower at everything since its emulated

knotty magnet
#

a normal person doesn't really care about quantum computers though, they're not useful for things a normal computer can do well

#

afaik they're only useful for certain problems that normal computers aren't good at

feral hound
#

tbh i dont know what quantum computers can do well other then that they will somehow break most encryption algorithms

#

I just think that if in future I run into a problem that I cant solve traditionally I could give quantum computation a try

tropic glacier
#

One thing they are useful for already is that there are guaranteed true random number generators using quantum computers. These exist now and cost money to use, of course. They're used where someone needs very high security, or very unbiased statistical modelling.

knotty magnet
#

lava lamps aren't random enough?

tropic glacier
#

I mean unbiased and unpredictable, so that a sequence of random bits truly contains zero information.

feral hound
#

the way I see it all random numbers even the ones in real life follow some law however we just dont understand those laws well enough/ arent able to account for all the possible variables at play so nothing is really trully random

knotty magnet
#

that's not true, there are truly random things

feral hound
#

like what?

knotty magnet
#

well actually, if you say "what if there's this one thing we don't know about" then not really

tropic glacier
#

With quantum computers you can generate random numbers which are truly random, and guaranteed by mathematical proof.

feral hound
#

everything is pseudo random otherwise the unvierse wouldnt work

tropic glacier
#

The universe doesn't work that way

feral hound
#

the unvierse operates on laws what we perceive as random is just due to a lack of understanding about those laws

tropic glacier
#

Anyway, the biggest data structures question I usually ask is when should you use a list vs a set? (Since this is Python). Very few people coming from physics seem to know a good answer to that.

knotty magnet
#

ok but that's just a non-argument, you can never prove anything then

feral hound
feral hound
#

are you interviewing theoretical physicists?

tropic glacier
#

yes, people who did a PhD in quantum computation, usually

#

CS is generally not relevant for that

feral hound
#

why do you ask about it in interviews then?

tropic glacier
#

It's relevant for what we do πŸ™‚

feral hound
#

ahh fair

feral hound
#

I assume anyone intelligent enough to get a PhD in quantum computation wont have a problem learning CS quickly

tropic glacier
#

They do learn CS things after they're hired, and I didn't say I was rejecting people for not knowing the answer to one question πŸ™‚

#

But we're very small and we have a lot of code to write, so it is important that someone knows as much as possible

feral hound
#

^^ understandable, just out of curiosity what exactly do you do?

tropic glacier
#

Well, there isn't a good name for it yet. Some people are calling it a "quantum operating system", but it's not an operating system like you're used to. Sometimes it's called a "compiler", or an "architecture", but in any case, it's an abstraction layer between quantum computing algorithms and real devices.

feral hound
#

interesting so your essentially just writing the interface layer to allow people to use quantum computers effectively?

tropic glacier
#

Basically. So people can design quantum algorithms in a hardware-agnostic way, and then the abstraction layer figures out how to make them work on a given device.

keen hearth
#

@radiant pecan Don't post off-topic memes here please.

#

In fact, any memes.

radiant pecan
#

Oh shoot, i'm so sorry

#

I posted it in the wrong server

grave dome
#

Can anyone tell how to solve this problem?

mild hound
sleek gust
dense wraith
#

can somebody pls help me with my hw

sleek gust
void fossil
#

hello, I have a question on how best to show this issue:
I have 3 types of paint gallon: 0.5L, 2.5L and 3.6L
Each liter paints 5 square meters

I need to paint 15 square meters of wall, the best gallon paint recommendation is: 1 gallon of 0.5L and 1 gallon of 2.5L

How can I structure a function that always returns me the best possibility without losing ink?

fiery cosmos
chrome raven
#

hELLO

#

I am trying to implement a graph function

#

can anyone hel p

oak trail
#

Has anyone constructed a self-aware algorithm that can learn on its own using Python?

astral current
#

hey guys

#

am using the turtle in python. I am trying to make shapes with my arrows and then trying to fill them. But somehow. It only colors in the turtle and not the shape drawn.

#

Anyone know the solution?

coral obsidian
#

Hey guys, i was wondering why my get all paths function is getting paths that cant literally exist? i would like some help, thanks!

crisp isle
#
def heap_sort(array):
    build_max_heap(array)
    for end in reversed(range(1, len(array))):
        swap(0, end, array)
        sift_down(0, end, array)
    return array


def build_max_heap(array):
    first_parent_index = (len(array) - 1) // 2
    for current in reversed(range(first_parent_index + 1)):
        sift_down(current, len(array) - 1, array)


def sift_down(current_index, end_index, heap):
    child_one_index = current_index * 2 + 1
    while child_one_index <= end_index:
        child_two_index = current_index * 2 + 2 \
            if current_index * 2 + 2 <= end_index else -1

        if child_two_index > -1 \
                and heap[child_two_index] > heap[child_one_index]:
            index_to_swap = child_two_index
        else:
            index_to_swap = child_one_index

        if heap[index_to_swap] > heap[current_index]:
            swap(current_index, index_to_swap, heap)
            current_index = index_to_swap
            child_one_index = current_index * 2 + 1
        else:
            return


def print_kth_smallest_largest(numbers, k):
    print(f"The kth smallest element is {numbers[k - 1]}")
    print(f"The kth largest element is {numbers[-k]}")


def swap(i, j, array):
    array[i], array[j] = array[j], array[i]


numbers = []
with open("numbers.txt") as file:
    for line in file:
        numbers.append(int(line.rstrip()))
k = int(input("Enter k: "))
heap_sort(numbers)
print(numbers)
print_kth_smallest_largest(numbers, k)
#
Enter k: 4
[56, 45, 45, 34, 90, 56, 76, 89, 33, 334]
The kth smallest element is 34
The kth largest element is 76
#

Why am I not getting a sorted array when I print it?

#
33
45
76
56
34
56
90
45
89
334
#

This is numbers.txt

#

Can someone help me?

#

Oh! I got it!

fiery cosmos
#

can anyone help me with selenium in dm?

faint sentinel
#

what should be the exact complexity of expression O(nlogn + 3n) , confused on which is less dominating , as even with n = 1million , values of both are significant
Please help fast , if anyone is here

winged plover
#

It would be O(nlogn) I guess pithink

faint sentinel
#

yes , i also think so

#

But even upto 1 million the values of both are significant

#

you see this is the comparison

feral hound
#

big O is not concerned with the exact complexity it just finds the relationship between input size and time/space

#

so O(nlogn + 3n) = O(nlogn)

faint sentinel
#
x  = [1,2,3,4,2,3,4,9,8,8,12,1,9,19]

def unique(n):
    n.sort()
    res = 0
    for i in x:
        res = res^i
    if res:
        return "The unique number in the array is :{}".format(res)
    else:
        return "Their is no unique number in the given array"
    
    
y = unique(x)
print(y)
#

using bitwise , this is my algorithm , to find the unique number in array

#

can you help me in suggesting where can i improve , at two points
1.IN decreasing the time complexity
2. In making the code more elegant and wonderful

#

Please respond as soon as possible

feral hound
#

!e

x  = [1,2,3,4,2,3,4,9,8,8,12,1,9,19]

def unique(n):
    numbers = set()
    for num in n:
        if num not in numbers:
            numbers.add(num)
        else:
            return f"The unique number in the array is :{num}"
            break
    else:
        return "Their is no unique number in the given array"
    
y = unique(x)
print(y)
halcyon plankBOT
#

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

The unique number in the array is :2
feral hound
#

@faint sentinel

faint sentinel
#

yes , i am here

#

i am analyzing the solutionn

feral hound
#

this solution is O(n) for both space and time

faint sentinel
#

ok

#

Yah , but it is not using bitwise operator

thorny vector
#

hi so I am in college and want to learn data structs and algos, is there a course I can refer to

feral hound
#

do you have to use that operator?

faint sentinel
thorny vector
#

Do they teach in python because its the only language I am comfortable with

thorny vector
#

oh

#

do you know any channel or courses who teach in python

faint sentinel
#

NO

#

Dsa is language independent

#

Even i learn in python

#

if you are comfortable in basic python , you can easily go

#

But you should be atleast comfortable with one language

thorny vector
#

ok

#

but the problem is my professor was teaching stacks

#

and taught us pop and push

#

which I thought were easily doable by using append and remove

#

so I didnt see any point of using stacks

faint sentinel
# thorny vector ok

No , therea are different use cases for all this , what they are teaching you should know it very well

#

Just go through my code school , one of best lectures in world , you will be able to know use cases of all

#

which country are you from???

feral hound
# thorny vector so I didnt see any point of using stacks

in terms of python you might not fully understand why a stack might be useful but if you learn about how things are fundamentally implemented you will understand a bit better about what he advantages are and where it might be used, particularly learn about linked lists

#

but again in python you dont have to worry about the implementation details and just use what you have for now, the ideas of a queue and stack still come into play at some points though

#

for example there are two graph search algorithms called
Depth first search (DFS)
Breadth first search (BFS)

the only difference between the two fundamentally is that DFS uses a stack and BFS uses a queue

#

I would say you dont have to worry about them too much rn just keep these data structures in the back of your head, you will probably know when you need them

thorny vector
raven kraken
#

When we implement stack using a list in python we can't use peek(), top() etc. So how do we implement stack such that we can use all these functions(I know this is a pretty dumb question but I have just started with stacks and having a hard time implementing it)?

keen hearth
#

But you may wish to check that the list is not empty first, to avoid an index error.

raven kraken
fiery cosmos
#

A list works fine for a stack, you can use thelist[-1] in lieu of peek() as LX just mentioned pithink

#

You could make a thin Stack class wrapper around a list that has actual peek() if you wanted

raven kraken
#

Alright got it thanks

fiery cosmos
chrome raven
#

Hello

#

Any kind soul can help me improve the efficiency of my code

fiery cosmos
#

post it

halcyon plankBOT
#

Hey @chrome raven!

Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:

β€’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)

β€’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:

https://paste.pythondiscord.com

chrome raven
#

A 2D list represents a 2D board with cells of a Maze. Each cell may only be in one of five states: Entrance (3), Exit (2), Wall (1), Path (0) and Treasure (4). Given a 2D list of a Maze and the Entrance coordinates, you are required to write an algorithm

To exit the maze and return a result list containing coordinates of the path from entrance to exit.

Start at the Maze Entrance (3), find your way to the Maze Exit (2) by moving horizontally or vertically along the Maze Path (0) / Treasure (4) via 1 cell movement.

Assumptions:

You may assume that all maze given will have an exit and one treasure

#

@fiery cosmos

eager narwhal
fiery cosmos
chrome raven
#

sounds complicated

#

I m not sure how to implement that

#

Btw treasure is just another "cell" for this case

#

the treatsure serve a different purpose in the subsequent use case

carmine nest
#

Hi, I just want to check that I have this correct in my head with regards to the definition of a loop within decomposition.

count apples in 4 boxes then display total

count apples in box 1 then record data (loop1)
count apples
record apples counted (total update)

move to next box to count (loop2)
move to next box in range

This shows two loops within the one problem (albeit it in basic detail not full constructed)

idle pier
#

am currently doing 114. Flatten Binary Tree to Linked List.

def flatten(self, root: Optional[TreeNode]) -> None:
        """
        Do not return anything, modify root in-place instead.
        """
        def dfs(root):
            if not root: return None
            
            leftTail = dfs(root.left)
            rightTail = dfs(root.right)
            
            if leftTail:
                leftTail.right = root.right
                root.right = root.left
                root.left = None
                
            last = rightTail or leftTail or root
            return last
        
        dfs(root)```

am dont fully understand this part
```py 
if leftTail:
  leftTail.right = root.right
  root.right = root.left
  root.left = None```
so `leftTail.right = root.right` is basically taking the left subtree and putting it on the right subtree correct?
#

The part of confused is when does it take the 3 and merge onto the right side child

feral hound
#

nvm confused it with a BST its fine

idle pier
marsh pewter
dapper sapphire
#

I'm looking at this 3sum implementation below is the pseudocode:

sort(S);
for i = 0 to n - 2 do
    a = S[i];
    start = i + 1;
    end = n - 1;
    while (start < end) do
        b = S[start]
        c = S[end];
        if (a + b + c == 0) then
            output a, b, c;
            // Continue search for all triplet combinations summing to zero.
            // We need to update both end and start together since the array values are distinct.
            start = start + 1;
            end = end - 1;
        else if (a + b + c > 0) then
            end = end - 1;
        else
            start = start + 1;
    end
end
#

My question is about end = n - 1 line 5 in the for loop. We reset end/right each time, so we dont miss out a sequence. Below is an example:

nums = [-3, -2, -1, 0, 1, 2, 3]
i = -3
left = 0
right = 3

i = -3
left = 1
right = 2

i = -2
left = -1
right = 3 # When we reset end/right back to len - 1, we are able to grab this value. Is this why we reset end/right?
idle pier
chrome raven
#

Hello

brave light
#

!e

s = 'This is a random string'
split_s = []
while len(s) >= 4:
    split_s.append(s[:4])
    s = s[4:]
split_s.append(s)
print(split_s)
halcyon plankBOT
#

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

['This', ' is ', 'a ra', 'ndom', ' str', 'ing']
grand trench
#

what does a != b mean in phyton
Equal To
Not Equal To
More Than
Less Than or Equal To
which of these four
options

cold mulch
#

this seems like a quiz, wecan't help with that

#

!rule 8

halcyon plankBOT
#

8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.

grand trench
chrome raven
#

AHello

#

any one familiar with path finding algo

#

Need some help here

feral hound
grand trench
#

not equal

brazen flume
#

Guys, give me some courses if possible free on ds and algos with python

trim fiber
carmine dagger
#

does anyone here knows how to decrypt caesar cipher?

#

what does it mean when it says: A to Z MINUS the J?

last cosmos
#

can i ask a question about circularqueues?

#
class CircularQueue:
    def __init__(self, size):
        self.maxsize = size
        self.data = [None] * size
        self.size = 0
        self.head = 0
        self.tail = -1

    def enqueue(self, value):
        if self.maxsize == self.size:
            return "Queue full"
        else:
            self.tail = (self.tail + 1) % self.maxsize
            self.data[self.tail] = value
            self.size += 1

    def dequeue(self, value):
        if self.size == 0:
            return "Queue is empty"
        else:
            elem = self.data[self.head]
            self.head = (self.head + 1) % self.maxsize
            self.size -= 1
            return elem

i was told that using if self.maxsize == self.size: was a canonical way to check for a full queue

#

if so which other method is preferred?

stable pecan
#

check if head + 1 = tail

last cosmos
#

and for an empty queue its just self.head == self.tail?

#

or self.head == -1?

raven kraken
#

Hey how do i paste my python code here?

shut breach
#

!code

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

raven kraken
#
for i in range(len(array) -1):
       for j in range(i+1, len(array)):
#

For the above for loops what should be the time complexity? Should It be O(N)?

jolly mortar
#

no, its still N^2

#

the no. of inner iterations is N + N-1 + N-2 + ... + 2 + 1 which is N(N+1)/2, or O(N^2)

serene mango
# carmine dagger does anyone here knows how to decrypt caesar cipher?

Ceaser cipher uses a fixed shift over the whole corpus, so there are 26 possible shifts. A->B means a shift of 1, or A-> C means a shift of 2. Similarly for negative numbers on the opposite side.
Since the number of possibilities is only 26 checking every shift, and if there is a large corpus, we can find the decrypted answer without any key. The idea is to look at 2-3 letter words inside our corpus (they can be "the", "is" , "and"), and check which shift gives such output. Manually(by checking which sentence makes sense) or programmatically (by checking counts and picking the one which maximizes counts of such three-letter or two letter words) depending upon the objective.

If you have a key, then it is trivial and would follow a direct shift.

opaque ermine
#

Hey, im almost done with a point graph in terminal. However i get a problem when the y tuple has the same value. The x coordinate shifts too far.

    for i in reversed(range(y_min, y_max + 1)):
        result += "#"
        if i in ys:
            for idx, j in enumerate(ys):
                if j == i:
                    for n in range(x_min, x_max + 1):
                        if n != xs[idx]:
                            result += " "
                        elif n == xs[idx]:
                            result += "*"
        else:
            result += " " * (x_diff + 1)
        result += "#\n"
    result += "#" * (x_diff + 3)
    return result
#

Does anyone have a tip? πŸ˜„

feral hound
#

it would also be helpful if you showed what output should correspond to a given input

fiery cosmos
#

the x coordinate deviates beyond parameters

opaque ermine
#

the program is taking the input of coords: [(-3, 9), (-2, 4), (-1, 1), (0, 0), (1, 1), (2, 4), (3, 9)] the "*" is marked as the coords. The correct output should be:

feral hound
#

what are the numbers of the rows and columns here?

#

nvm I think I got it its from x -3 to 3 and y 0 to 9

opaque ermine
#

Yes that would be the range

feral hound
#
        if i in ys:
            for idx, j in enumerate(ys):
#

whats ys?

#

also I think you got idx and j in the wrong order

opaque ermine
#

ys is a tuple of all y coords

feral hound
#

enumerate returns
index item

opaque ermine
#

I have zipped the coords to xs and ys. So that the index of ys corresponds to the index of xs

#

If it would be easier to understand, I could write the rest of the function

feral hound
#

hmm I have a suggestion for rewriting everything which will make it easier to work with

#

make a matrix (list of lists) which has all the hashes without the *

#

then loop over the coords and change the spaces to *s

#

and then you can just use ""join() to get your rows as strings

opaque ermine
#

hmmm, that could work. Thanks I will try πŸ˜„

fiery cosmos
#

yea I am in the right place, Python algorithms!

opaque ermine
feral hound
#
for i in range(len(matric)):
        matric[i][0] = "#"
#

try this

opaque ermine
feral hound
#

lol

#

just to explain whats going on in python a for loop is really a for each loop

#

it iterates over iterables so

#

!e

my_list = ["hi", "bye"]

for word in my_list:
    print(word)
halcyon plankBOT
#

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

001 | hi
002 | bye
feral hound
#

I could have put i j or k instead of word here but you should try to make your variable names as descriptive as possible

opaque ermine
#

Thanks, that clears things up πŸ™‚

feral hound
#

!e

print(list(range(10)))
halcyon plankBOT
#

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

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
feral hound
#

to give a bit more context for why doing range(len(matric)) worked btw

opaque ermine
#

I know i need to do something like this ```
for i in range(len(matric)):
if i>0 and i<max(range(len(matric))):

feral hound
#

no nothing like that

feral hound
#

you can iterate over the tuples which are your coords and then use them as indexes to your matrices

#

matrix[y][x] or matrix[i][j] is how you can think of it

#

first index is for the row second index is for the column

#

@opaque ermine

opaque ermine
feral hound
halcyon plankBOT
#

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

12
feral hound
#

the reason I suggested this in the first place is because now you can do something like this
(-3, 9)
i j
matric[j][i+3]

#

instead of 3 just make sure to add the number of the minimum x value

#

so if -3 is the smallest x coord do +3 for all coords when indexing

#

you dont want to hardcode this make it so that it adds the correct number for any number but I think you get the point

dapper sapphire
#

Took me 5 days to fully understand what each part of a 3sum's implementation does. Good Lord!!

#

Actually 3, since I didnt spend time on it on the weekend.

rough lynx
#

So I have some data I want to put into a container object, sometimes the order is meant to be sorted and other times it may be random. When an element is accessed, it's supposed to be popped off the containing object, used, and then put back inside the container
Right now I'm using a queue for storing this data and using queue.get() and queue.put() to take/restore the elements
The only way to have the elements in the queue be random is to create a lit of all the elements, then do something like this:```py
my_list = list(range(100))
my_queue = Queue()
random.shuffle(my_list)
for i in my_list:
my_queue.put(i)

Is there a better way to do this?
vocal gorge
opaque ermine
rough lynx
#

I suppose I could use a collections.deque since it supports being declared with an iterable and can useextend but I'd have to make it block for get calls for my program

dapper sapphire
#

So are most problems basically optimization problems?

rough lynx
#

A lot of problems can be related to poor or no optimization, yes

knotty magnet
rough lynx
#

Mathematically speaking, sorta

knotty magnet
#

how so?

quiet jay
feral hound
#

is there a data structure like a hashmap that instead of having single key value pairs it can have multiple keys refer to the same value

#

btw my main issue for this is because of storage with json, since I could always point the key to the value of the other key to make them both have the same value but how could I represent this in json or is there another format for this?

#

thinking about this again this will only work for things passed by reference not things passed by value, is there anyway I can make a request to have pointers added to python?

feral hound
feral hound
#

!e

class multi_key_dict():
    def __init__(self):
        self.dict = {}
        self.key_maps = {}
        self.count = 0

    def add(self, key, value, key2=None):
        self.key_maps[key] = self.count
        self.dict[self.count] = value
        self.count += 1

    def link(self, link_to_key, *args):
        for key in args:
            self.key_maps[key] = self.key_maps[link_to_key]

    def get(self, key, default=None):
        if key in self.key_maps:
            return self.dict[self.key_maps[key]]
        else:
            return None

    def update(self, key, value):
        self.dict[self.key_maps[key]] = value

    def unlink_key(self, key, value):
        self.add(key, value)

    def remove(self, key):
        del self.key_maps[key]


a = multi_key_dict()
a.add("key1", "hello")
a.link("key1", "key2", "key3")
a.update("key2", "bye")

print(a.get("key1"))
print(a.get("key2"))
print(a.get("key3"))
halcyon plankBOT
#

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

001 | bye
002 | bye
003 | bye
feral hound
#

this is the kind of thing Im talking about btw ended up writing my own class for it

#

I still need to figure out a good format to store this as json and then load it into this class

manic hatch
#

what's the best way to turn a nested dict coming from json into an object with attributes?

mint jewel
#

@manic hatchdepending on scope, pydantic, a dataclass with **json, or attrs

#

I personally have had a good experience with pydantic

manic hatch
#

ok, thanks

raven kraken
#

Can someone suggest me how can I work upon my coding skills. Currently I am solving leetcode questions on stacks and almost everytime I can figure out the correct approach, but am unable to code it down. It's kind of frustating.

grizzled schooner
#

maybe try starting with easier questions (if you have trouble with the easier questions on leetcode you could try a different site like codewars.com or codingbat)

raven kraken
grizzled schooner
feral hound
#

I would say either you dont fully understand the data structures or you are trying to use them where they dont make sense

grizzled schooner
#

ok. i'm not completely sure what to recommend other than reading articles/textbook sections. something else you could do is implement them yourself (if you haven't already) to gain a better understanding of how they work

feral hound
#

you could also just look up the answers for a few of the questions take time to understand them and then try different questions

#

sometimes you just need to see it in practice a few times before you get how to use it

raven kraken
#

When it comes to stack I get really confused , maybe I used again try to implement them

grizzled schooner
#

additionally, you could ask for help on a specific problem (in this channel, a help channel, or you could ask a friend)

feral hound
#

also as a side note I would recommend taking cs50, it will give you a strong foundation and will give more context as to why these data structures even exist

#

they go over implementing some of them in c which makes a lot more sense than doing that in python

mint jewel
#

is there a common way to represent finite automata, I have a massive chain of if statements which essentially check which state I am in and what the input is and where should we go based on that

vocal gorge
#

I think I've seen a Python library for finite automata that heavily used decorators on methods

shut breach
keen hearth
mint jewel
#

I have an enum for now

#

I will try a sparse matrix, that could work well

steady maple
#

Guys I got fu**ed up rn during coding

#

Don't know why

#

But I am confused

#

That shall I laugh or just sry

keen hearth
#

@mint jewel This is kind of what I meant: ```py
from abc import ABC, abstractmethod

class State(ABC):

@abstractmethod
def successor(self, symbol: str) -> State:
    ...
#

Or maybe, if you're dealing with NFAs: ```py
from abc import ABC, abstractmethod
from collections.abc import Iterable

class State(ABC):

@abstractmethod
def successors(self, symbol: str) -> Iterable[State]:
    ...
mint jewel
#

hmm, that could work

tropic glacier
#

This is more or less the standard way to implement a state machine, I think it's even called the State Machine Pattern

keen hearth
#

You could even implement unions, intersections, and so on.

tropic glacier
#

Today I wrote a Monte Carlo tree search algorithm...to sort a list πŸ˜›

knotty magnet
#

how does that even work

tropic glacier
#

How does which part work?

fiery cosmos
tropic glacier
#

oh, I didn't write an efficient sorting algorithm

#

It took 130k iterations to sort a list of 20 integers

#

I was mainly trying to learn how to write a Monte Carlo tree search

knotty magnet
#

wouldn't that be like bogosort

tropic glacier
#

Not quite

#

It's written as a tree search, where every child node appends one new integer to a partially completed list, with the rule that it be greater than the previous entry.

Then to estimate the value of that partial list, it does a "rollout" step, which involves randomly filling in the remaining slots in the list, and then counting how many integers are in order. It uses that to assign a score to the ordered partial list, and then navigates to the appropriate next child in the tree based on the accumulated scores.

#

So it's like a selection sort with random selections, but then it estimates the value of each new selection by bogosorting the rest of the list, and checking how good it did. Lol

#

Imagine you've been assigned to work on a group project and the goal is to sort a list. You've actually seen sorting before and know how it should be done, but your friend doesn't want to listen to you. They just want to get started. They have a vague idea that every item should be less than the next one, but that's as far as they're willing to think before they just start grabbing things and trying to sort them. That's my sorting algorithm. πŸ˜†

cosmic cloak
#

Hey guys, can someone give me some help with a loop?
I have the following code:

while True:
    if active_window1 is True:
        pyautogui.click(icon1)

    elif active_window2 is True:
        keyboard.click(icon2)

    elif active_window3 is True:
        pyautogui.click(icon3)
    
    elif keyboard.is_pressed('space') == True:
        break

I'd like to make it possible for the loop to detect if a certain window is active and, when that happens, click on a certain icon. After that, I want for that loop to check again if one of those active_windows are active and then react accordingly. However, I don't know how to do that. Using this code, when active_window1 == True, the loop just keeps repeating the action pyautogui.click(icon1), even when active_window1 is not True anymore.

Is there a function for Python that allows me to "restart" the loop over and over?

young tangle
#
def has_repeats(L: list):
  """
  Returns `True` if any of the elements of `L` are not
  unique; `False` otherwise.
  """
  if len(L) < 2:
    return False
  if len(L) == 2:
    return L[0] == L[1]
  return (
       has_repeats(L[0:1] + L[1:2])
    or has_repeats(L[0:1] + L[2:])
    or has_repeats(L[0:1] + L[2:3])
    
    or has_repeats(L[1:2] + L[2:3])
    or has_repeats(L[1:2] + L[3:])
  )
``` Can this be simplified? ^
safe vigil
#

Hey I needed help with something. Was getting help from #🀑help-banana but they suggested to come here.

polar hearth
#

Hi, I am not sure if this is the right place to ask. I had a coding test (writing a topological sort for scheduling tasks) for a high frequency trading firm couple of months ago, but I was rejected anyway (the code I written works but maybe not up to the quality).

I am curious if where is the right place to seek some help/advice here to help me learn and improve the way I write these algorithms/ classes as I'm not a software developer. Part of the process also tested my knowledge in using things like unit testing, pylint, attrs etc.

tropic glacier
#

Did they give any feedback about what they didn't like?

tropic glacier
#

Can't share it unfortunately. Maybe I'll write another version in my free time.

polar hearth
grizzled schooner
young tangle
grizzled schooner
#

oh, yikes πŸ˜”

tropic glacier
#

You should bisect your list and then call your function recursively on each half list

feral hound
tropic glacier
#

Ah, true, if they end up in different sublists, you'll have a problem

twin sequoia
#

For pathfinding algorithms, what website would be the best place to start?

feral hound
halcyon plankBOT
#

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

True
feral hound
#

another approach took me a while to get this one lol

young tangle
#

tbats a lot simpler

gusty valley
#

Hello ! Can someone help me with my problem?
I want to remove duplicates from a list and replace them with other numbers that are not duplicates but I still have them. I have done this:

    g = []
    for i in l:
        if i not in g:
            g.append(i)
        else:
            rnd = randint(1, 10)
            g.append(rnd)
    return g

print(duplicatesOrNot([6, 5, 6, 4, 5]))
young tangle
feral hound
#

!e

def has_repeats2(L: list):
    for i in range(len(L)):
        for j in range(len(L)):
            if i != j and L[i] == L[j]:
                return True
    return False

print(has_repeats2([1, 7, 8, 9, 2, 5, 6, 7]))
halcyon plankBOT
#

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

True
feral hound
#

its equivalent to this

#

recursive_check(num, L[1:])

#

comapres all numbers in the list with num

#

recursive_check(L[0], L[1:])
compares all numbers in the list with the next number

#

recursive_check(L[0], L[1:])
this is also the starting point

young tangle
#

so would just
recursive_check(L[0], L[1:])
be sufficient?

feral hound
#

no you need to do
return recursive_check(num, L[1:]) or recursive_check(L[0], L[1:])

#

think of it as branching into 2 paths

#

the left path checks all the numbers against that particular number

#

the right opens a new path to check the other numbers against each other

#

!e

def has_repeats(L: list):
    """
    Returns `True` if any of the elements of `L` are not
    unique; `False` otherwise.
    """
    def recursive_check(num: int, L: list):
        print(num, L)
        if num == L[0]:
            return True
        elif len(L) < 2:
            return False

        return recursive_check(num, L[1:]) or recursive_check(L[0], L[1:])
    
    if len(L) < 2:
        return False
    return recursive_check(L[0], L[1:])

print(has_repeats([1, 7, 8, 9, 2, 5, 6, 7]))
halcyon plankBOT
#

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

001 | 1 [7, 8, 9, 2, 5, 6, 7]
002 | 1 [8, 9, 2, 5, 6, 7]
003 | 1 [9, 2, 5, 6, 7]
004 | 1 [2, 5, 6, 7]
005 | 1 [5, 6, 7]
006 | 1 [6, 7]
007 | 1 [7]
008 | 6 [7]
009 | 5 [6, 7]
010 | 5 [7]
011 | 6 [7]
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/piyigoxofa.txt?noredirect

feral hound
#

have a look at this output

#

on every print its comparing the number on the left against the first number in the list

young tangle
#

i see

feral hound
#

just to give more context to the prints
list = [1, 7, 8, 9, 2, 5, 6, 7]
first call compare L[0] against all other numbers in the list

second call is doing this but also creates a new branch
recursive_check(L[0], L[1:])
to compare L[1] against all other numbers in the list excluding L[0] but thats fine since that check already happend in the first call

third call same as before but
recursive_check(L[0], L[1:])
is now starting the branch to compare L[2] to all the other numbers other than L[0] and L[1]

and so on

#

but the reason you see it print like this is because it completes the first branch before moving on to the other branches

#

its also not effcient because it makes way more calls then it needs to adding memoization to prevent checked paths from being generated would fix that issue

#

anyway gtg rn but will be back later if u got any more questions

young tangle
feral hound
#

!e

def has_repeats(L: list):
    """
    Returns `True` if any of the elements of `L` are not
    unique; `False` otherwise.
    """
    def recursive_check(num: int, L: list, first_branch: bool):
        print(num, L)
        if num == L[0]:
            return True
        elif len(L) < 2:
            return False
        if first_branch:
            return recursive_check(num, L[1:], first_branch) or recursive_check(L[0], L[1:], False)
        else:
            return recursive_check(num, L[1:], first_branch)
    
    if len(L) < 2:
        return False
    return recursive_check(L[0], L[1:], True)

print(has_repeats([1, 7, 8, 9, 2, 5, 6, 7]))
halcyon plankBOT
#

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

001 | 1 [7, 8, 9, 2, 5, 6, 7]
002 | 1 [8, 9, 2, 5, 6, 7]
003 | 1 [9, 2, 5, 6, 7]
004 | 1 [2, 5, 6, 7]
005 | 1 [5, 6, 7]
006 | 1 [6, 7]
007 | 1 [7]
008 | 6 [7]
009 | 5 [6, 7]
010 | 5 [7]
011 | 2 [5, 6, 7]
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/xutuquluzo.txt?noredirect

feral hound
#

this only generates new branches from the first branch instead of making unnecessary ones on all calls

#

also if you were gona do memoization you might as well just use a set to get O(N) time instead of O(N^2)

feral hound
#

you can use the set both recursivley and iteratively btw so if you just need recursion you can still use it

young tangle
#

first_branch is new -- that's to save extra calls?

feral hound
#

yup

#

if you want I can draw a little diagram to show you what the difference between having it and not having it

#

although you gota give me like 30 mins eating rn lol

#

!e

def has_repeats(L: list):
    """
    Returns `True` if any of the elements of `L` are not
    unique; `False` otherwise.
    """
    def recursive_check(num: int, L: list, first_branch: bool):
        print(num, L)
        if num == L[0]:
            return True
        elif len(L) < 2:
            return False
        if first_branch:
            return recursive_check(num, L[1:], True) or recursive_check(L[0], L[1:], False)
        else:
            return recursive_check(num, L[1:], False)
    
    if len(L) < 2:
        return False
    return recursive_check(L[0], L[1:], True)

print(has_repeats([1, 2, 3, 4]))
halcyon plankBOT
#

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

001 | 1 [2, 3, 4]
002 | 1 [3, 4]
003 | 1 [4]
004 | 3 [4]
005 | 2 [3, 4]
006 | 2 [4]
007 | False
feral hound
#

this is probably a much clearer case to see whats going on btw

young tangle
#

i see exactly whats happening

#

kinda like bubble sort

cold cairn
#

Hey anyone able to help me I'm doing a deterministic quicksort recursive algorithm. But I'm trying to do a list of size 10000 that is sorted in the way 10000,9999,9998,.....,1 . I changed my recursion limit it to 10000, but I can only go up to a list of 2800 without having a mem leak. Anyone ever have this issue and be able to help?

idle pier
#

hello folks am currenlty doing Ransom Note on leetcode

def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        if len(ransomNote) > len(magazine): return False
        
        dict = {}
        for i in magazine:
            if i in dict:
                dict[i] += 1
            else:
                dict[i] = 1
                
        for char in ransomNote:
            if char not in dict:
                return False
            if dict[char] == 0:
                return False
            
            dict[char] -= 1
        return True```
Why are we reducing the char we have seen already? `dict[char] -= 1`
brave oak
#

but

#

just guessing from the name

#

and the algorithm

#

because you have a set number of each letter

eager tiger
#

hey

#

i need help πŸ˜…

faint latch
#

i have a problem with the code

foo = 30

def bar():
    exec('foo = 50')
    return foo

print(foo)
print(bar())

output:

30
30

but expected output is:

30
50

how can i edit the program to get what i want? (there is a 'exec' command, i need it, so i can't remove this from function)

trim fiber
fiery cosmos
covert raptor
#

Hello, I came up with this Binary Search recursive structure, but it's returning None

#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    if left > right or len(arr) == 0:
        return "Target Not Found"
    if midpoint == target:
        return f"Target Found at index {midpoint}"
    if target > arr[midpoint]:
        return binary_search(arr[midpoint + 1:], target)

    if target < arr[midpoint]:
        return binary_search(arr[:(midpoint - 1)], target)


print(binary_search([1, 2, 3, 4, 5], 3))
      ```
#

is left always 0 btw?

#

shouldn't it be!

turbid flicker
#

hi

jolly mortar
covert raptor
# jolly mortar ```py if midpoint == target: return f"Target Found at index {midpoin...
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    if left > right or len(arr) == 0:
        return "Target Not Found"
    if arr[midpoint] == target:
        return f"Target Found at index {midpoint}"
    if target > arr[midpoint]:
        return binary_search(arr[midpoint + 1:], target)
    if target < arr[midpoint]:
        return binary_search(arr[:(midpoint - 1)], target)
#

then now, I noticed that the length of the original array was decreasing

#

soo it's not returning the actual index number

#

πŸ˜”

#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    temp = arr
    print(temp)
    if left > right or len(arr) == 0:
        return "Target Not Found"
    if temp[midpoint] == target:
        return f"Target Found at index {midpoint}"
    if target > arr[midpoint]:
        return binary_search(arr[midpoint + 1:], target)
    if target < arr[midpoint]:
        return binary_search(arr[:(midpoint - 1)], target)

I did this then noticcd

#
print(binary_search([1, 2, 3, 4, 5, 6, 7], 5))
[1, 2, 3, 4, 5, 6, 7]
[5, 6, 7]
[]
Target Not Found
jolly mortar
covert raptor
jolly mortar
#

ah yeah, you should probably return just the index from the function, not a message

covert raptor
#

ooo

#

return midpoint?

jolly mortar
#

yeah

#

and probably -1 when not found

covert raptor
#

wait

#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    temp = arr
    print(temp)
    if left > right or len(arr) == 0:
        return "Target Not Found"
    if temp[midpoint] == target:
        return f"Target Found at index {midpoint}"
    if target > arr[midpoint]:
        return midpoint + 1 + binary_search(arr[midpoint + 1:], target)
    if target < arr[midpoint]:
        return binary_search(arr[:(midpoint - 1)], target)
#

where

jolly mortar
#

where what?

covert raptor
jolly mortar
#

hmm

#

that is true

covert raptor
#

it worked-

#

lemme test it a bit more

jolly mortar
#

think you should do

    if target > arr[midpoint]:
        t = binary_search(arr[midpoint + 1:], target)
        if t == -1:
          return -1
        return midpoint + 1 + t
covert raptor
#

It's crashinhg with even arrays

#

ooh bet

#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    if left > right or len(arr) == 0:
        return -1
    if arr[midpoint] == target:
        return f"Target Found at index {midpoint}"
    if target > arr[midpoint]:
        if target > arr[midpoint]:
            t = binary_search(arr[midpoint + 1:], target)
            if t == -1:
                return -1
            return midpoint + 1 + t
    if target < arr[midpoint]:
        return binary_search(arr[:(midpoint - 1)], target)

#

this

print(binary_search([1, 2], 2))

returns


    return midpoint + 1 + t
TypeError: unsupported operand type(s) for +: 'int' and 'str'
#

but

jolly mortar
#

you're returning a string when its found

#

return the index (midpoint)

#

also

    if target > arr[midpoint]:
        if target > arr[midpoint]:

is redundant

covert raptor
#

this

print(binary_search([1, 2, 3], 2))

returns

Target Found at index 1
jolly mortar
#

you should return just the index

covert raptor
#

and this

print(binary_search([1, 2, 3, 4, 5], 2))

returns

-1
covert raptor
#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    print(arr)
    if left > right or len(arr) == 0:
        return -1
    if arr[midpoint] == target:
        return f"Target Found at index {midpoint}"
    if target > arr[midpoint]:
        t = binary_search(arr[midpoint + 1:], target)
        if t == -1:
            return -1
        return midpoint + 1 + t
    if target < arr[midpoint]:
        return binary_search(arr[:(midpoint - 1)], target)


print(binary_search([1, 2, 3, 4, 5], 2))
#
[1, 2, 3, 4, 5]
[1]
[]
#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    print(arr)
    if left > right or len(arr) == 0:
        return -1
    if arr[midpoint] == target:
        return 0
    if target > arr[midpoint]:
        t = binary_search(arr[midpoint + 1:], target)
        if t == -1:
            return -1
        return midpoint + 1 + t
    if target < arr[midpoint]:
        return binary_search(arr[:(midpoint)], target)


covert raptor
jolly mortar
#
    if arr[midpoint] == target:
        return 0

return midpoint

covert raptor
#

it's working 😳

jolly mortar
#

nice πŸ‘

covert raptor
#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    print(arr)
    if left > right or len(arr) == 0:
        return -1
    if arr[midpoint] == target:
        return midpoint
    if target > arr[midpoint]:
        t = binary_search(arr[midpoint + 1:], target)
        if t == -1:
            return -1
        return midpoint + 1 + t
    if target < arr[midpoint]:
        return binary_search(arr[:midpoint], target)
#
        if t == -1:
            return -1
#

is this part necessary ?

jolly mortar
#

yeah, if the thing is not found in the list then it shouldn't offset the -1

covert raptor
jolly mortar
#

yes

#

if its not found, it should return -1

#

it shouldnt return midpoint + 1 - 1

#

without that, if you searched for 4 in [1, 2, 3] it would return 1 + 1 + -1 or 0, implying that the first item in the list is 4

#

which is false

covert raptor
#

1 more thing

#
if left > right

I don't think there's any use of this in my code right?

#

instead I'll use:

    if len(arr) == 0:
        return -1
jolly mortar
#

try it out

#

yeah its unnecessary

covert raptor
#
def binary_search(arr, target):
    left = 0
    right = len(arr) - 1
    midpoint = (left + right) // 2
    print(arr)
    if len(arr) == 0:
        return -1
    if arr[midpoint] == target:
        return midpoint
    if target > arr[midpoint]:
        t = binary_search(arr[midpoint + 1:], target)
        if t == -1:
            return -1
        return midpoint + 1 + t
    if target < arr[midpoint]:
        return binary_search(arr[:midpoint], target)
jolly mortar
#

the conditions left > right and len(arr) == 0 are equivalent

since left = 0 and right = len(arr) - 1, if left < right then len(arr) has to be 0

covert raptor
#

btw, what is "t" like what exactly is my function returning there?

#

ooh wait

covert raptor
#

why's recursion a bit complicated sometimes lol

#

hmmmmmmmm

#

ooooh so t becomes -1 inside one of the functions that has a length of 0
so we say when t becomes -1, it means that the length became 0

#

but how is it inside my if statement, that's whats confusing me

jolly mortar
jolly mortar
#

πŸ‘

worldly dune
#

Does anyone know how to create a code that helps you write backwards?

feral hound
halcyon plankBOT
#

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

cba
feral hound
#

do you mean something like this?

faint latch
fiery cosmos
naive cloak
#

When running this code I get a list with the same values but I don't understand why:

`lst = list()
years = 0 #initial year iterator

while years < 20:
i = 1.02
if (roi*(netincome - costi + initial)) < 50000:
lst.append(roi
(netincome - costi + initial))
else:
lst.append(tax1
(roi*(netincome - cost*i + initial)))

years += 1    
i = i*i
`

I should get lst with different values

feral hound
#
lst = list()
years = 0 #initial year iterator

i = 1.02
while years < 20:
    if (roi*(netincome - cost*i + initial)) < 50000:
        lst.append(roi*(netincome - cost*i + initial))
    else:
        lst.append(tax1*(roi*(netincome - cost*i + initial)))
        
        
    years += 1    
    i = i*i
feral hound
idle pier
#

am currently doing 542. 01 Matrix on leetcode

 def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        m = len(mat)
        n = len(mat[0])
        q = []
        
        
        for i in range(m):
            for j in range(n):
                if mat[i][j] == 0:
                    q.append((i,j))
                else:
                    mat[i][j] = "#"
                    
                    
        for row,column in q:
            for dx,dy in (1,0),(-1,0),(0,1),(0,-1):
                nr = row + dx
                nc = column + dy
                
                if 0 <= nr < m and 0 <= nc < n and mat[nr][nc] == "#":
                    mat[nr][nc] = mat[row][column] + 1
                    q.append((nr,nc))
        return mat```
For this part 
```py
for dx,dy in (1,0),(-1,0),(0,1),(0,-1):
                nr = row + dx
                nc = column + dy```
I know its checking all 4 directions but I don't understand why we are adding `dx` and `dy` to row and column
keen hearth
#

The first offset, (1, 0) adds 1 to the row, and 0 to the column. So the coordinates (nr, nc) represent the cell immediately below the cell with coordinates (row, column).

naive cloak
#

How can I multiply 2 floats whose decimals get very small accurately? This code arrives at numbers too big for my pc
`lst = list()
years = 0
i = 1.02

while years<20:

lst.append(i)

i *= i
years += 1`
pulsar moat
#
  1. Write a strategy to reach the goal node efficiently and quickly. Your logic/algorithm should be ideated while keeping in mind that you have prior knowledge of those black obstacles, but you only come to know about the grey obstacles once you reach a cell adjacent to it.
jolly mortar
feral hound
feral hound
# pulsar moat Okay

btw you dont have to recalculate at each step just when you encounter the grey walls, and at that point you could either recalculate the shortest path again or first check first if your current path is blocked and then recalculate, either way all the methods should still work, this is just about efficiency

fallen sable
#

Can anyone help me with this one

worldly dune
feral hound
#

happy to help πŸ™‚

fallen blade
#

I've some sets of combinations of inequalities in form of [{(x>y),(y>x)},{(y>z),(z>y)},...] and I want to get all unique correct combinations.
One set can have more than 2 inequalities, but for simplification I'm omiting it now.
I'm looking for:

  1. Is there similar problem explained anywhere else?
  2. Implementation of check function.
  3. Implementation of get_all_correct_combinations that returns only unique results.
  4. [Optional] Some way to iterate from "greatest" to "lowest"(heuristics is ok)
  5. [Optional] Get count of orders that are correct for single combination with complexity <n!
@dataclass
class Greater:
    """Relationship like greater-than sign between two nodes
    Irreflexivity: not a<a, i.e. no element is related to itself
    Transitivity: if a<b and b<c then a<c
    Asymmetry: if a<b then not b<a.
    """
    base: int
    destination: int


def check(combination: Tuple[Greater]):
    "check if combination is correct"
    raise NotImplementedError()


def get_all_correct_combinations(possibilities: list[list[Greater]]):
    "yield all correct combination of inequalities"
    for option in itertools.product(*possibilities):
        if check(option):
            yield option

# Example problem
my_options = [
    [Greater(1, 2), Greater(2, 1)],
    [Greater(2, 3), Greater(3, 2)],
    [Greater(3, 4), Greater(4, 3)],
    [Greater(4, 5), Greater(5, 4)],
    [Greater(5, 6), Greater(6, 5)],
    [Greater(6, 1), Greater(1, 6)],
]
for x in get_all_correct_combinations(my_options):
    print(x)

Solutions:
Could return set[Greater], but to show solution indices of my_options are more readable
❌ 000000 1>6 & 6>1
βœ… 000001 1>2 2>3 3>4 4>5 5>6 1>6
βœ… 000010 1>2 2>3 3>4 4>5 6>5 6>1
βœ… 000011 1>2 2>3 3>4 4>5 6>5 1>6
βœ… 000100 1>2 2>3 3>4 5>4 5>6 6>1
βœ… 000101 1>2 2>3 3>4 5>4 5>6 1>6
βœ… 000110 1>2 2>3 3>4 5>4 6>5 6>1
βœ… 000111 1>2 2>3 3>4 5>4 6>5 1>6
[...]

blissful sierra
#

hey , currently working on LeetCode 21. Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/
Recursive Solution is as follows:

def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
            # Recursive
            if not l1 and not l2:
            # both l1 and l2 are empty list
                return None
        
            elif not l1:
            # l1 is empty, directly return l2
                return l2
        
            elif not l2:
            # l2 is empty, directly return l1
                return l1
            if l1.val < l2.val:
                l1.next = self.mergeTwoLists(l1.next, l2)
                return l1
            else:
                l2.next = self.mergeTwoLists(l1, l2.next)
                return l2
#

I am having some difficulty understanding it - i was hoping someone might be able to break it down for me if possible, thanks. Im referring to the** final if else statement where the recursive calls are made**

eager narwhal
# blissful sierra I am having some difficulty understanding it - i was hoping someone might be abl...

(am supposing l1.next is l1 from the second element to the last one)

the "if l1.val < l2.val":
If the value of (the first element of) l1 is superior than l2, you know that the first element you'd need to return in the list is the first elemet of l1, and the rest is the sorted of l1 (without it's first element) and l2.

the "else" which translate into "l1.val >= l2.val"
Same as above, but for l2, by remplacing l1 by l2

(if I don't make sense, ask me, I'm not entirely sure if what I wrote is clear or not)

#

so, let's have two list, l1 = [1, 3, 7] and l2 = [2, 5]

let's try this alg
l1 not empty, l2 not empty, l1.val > l2.val, so
l1.next = self.margeTwoLists(l1.next, l2)
so, now, we have l1 = [3, 7] and l2 = [2, 5]
l1 and l2 not empty, l1.val !> v2.val, so we do
l2.next = self.margeTwoLists(l1, l2.next)
so, we have l1 = [3, 7] and l2 = [5]
l1 and l2 not empty, l1.val > l2.val, so
l1.next = self.mergTwoLists(l1.next, l2)
so we have l1 = [7] and l2 = [5]
l2.val > l1.val, so we have
l2.next = self.mergeTwoLists(l1, l2.next)
l2 is empty, so return l1 = [7]
l2.next = [7], so l2 = [5, 7]
return [5, 7]
so l1.next = [5, 7] so l1 = [3, 5, 7]
return [3, 5, 7]
so l2.next = [3, 5, 7], so l2 = [2, 3, 5, 7]
return [2, 3, 5, 7]
so l1.next = [2, 3, 5, 7], so l1 = [1, 2, 3, 5, 7]
return [1, 2, 3, 5, 7]

eager narwhal
# fallen blade I've some sets of combinations of inequalities in form of [{(x>y),(y>x)},{(y>z),...

I'm not entirely sure to get what you need... 1. Idk

  1. I guess something like: (I don't know python really well, but that'll be the idea)
def check(combination: Tuple[Greater]):
    for i in combination:
        if !(i.a > i.b):
            return False
    return True
  1. use a set I guess: (again, try it on your own)
def get_all_correct_combination(possibilities: list[list[Greater]]):
    for option in set(possibilities):
        if check(option):
            yield option
  1. how do you distinguish "higher" and "lower"??
#

(again, I don't use python much, and mostly, am a bit confused on what you need)

fallen blade
# eager narwhal I'm not entirely sure to get what you need... 1. Idk 2. I guess something like:...

What I fount out:

  1. Partial order in math
  2. Check if result creates DAG:
def check(combination: Tuple[Greater]):
    """check if combination is correct"""
    dag = nx.DiGraph()
    for x in combination:
        if dag.has_node(x.base) and x.destination in nx.ancestors(dag, x.base):
            return False
        dag.add_edge(x.base, x.destination)
    return True
  1. Current solution, but can be improved by getting cartesian product with early rejection: https://stackoverflow.com/a/65918605
def get_all_correct_combinations(possibilities: list[list[Greater]]):
    """yield all correct combination of inequalities"""
    for option in itertools.product(*possibilities):  # use frozenset
        if check(option):
            yield option
  1. use topological sorting from networkx library
nx.topological_sort(graph)
  1. I haven't found out yet.
fallen blade
#
tropic glacier
#

The Cartesian product is just itertools.product

shut breach
#

check the pins

idle pier
#

hello folks, am currently 21. Merge Two Sorted Lists on leetcode. This is my code

def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        tail = dummy = ListNode()
        
        while l1 and l2:
            if l1.val < l2.val:
                tail.next = l1
                l1 = l1.next
            else:
                tail.next = l2
                l2 = l2.next
                
            tail = tail.next
            
            
        if l1:
            tail.next = l1
        elif l2:
            tail.next = l2
            
        return dummy.next```
I dont fully understand `tail.next`. I know exactly what everything else is doing but its just that specific part I dont understand
marble basalt
#

this is an example of a linked list, where instead of storing all the values in memory right next to each other, you just have each value contain a reference to the next value. This way you can go through the list by continuously looking at the next value

#

so the next field of the tail variable should point to the next item in the list

#

Try following along with the algorithm manually to see how it is manipulating this field to merge the two input lists

winter dune
#

Hey comrades! I need a bit explaining please.

#

What does the 'CheckRowClueR' function do here? Can anyone please help.

#

Anyone πŸ™„

south umbra
#

hey i have just started ds algo

#

got some knowledge of algorithm , it's all 3 possible cases , rules of a algo , basis of judgement

#

n then binary search nd linear search

#

now got into Big O notation n all

#

cant understand what r they

#

In this course you will learn about algorithms and data structures, two of the fundamental topics in computer science. There are three main parts to this course: algorithms, data structures, and a deep dive into sorting and searching algorithms.

By the end, you will understand what algorithms and data structures are, how they are measured and e...

β–Ά Play video
south umbra
#

can any1 tell why big 0 notations ? what r they when needed
i just learned it defines the complexity of algo as a func of time

#

linear search-O(n)
binary search-o(log n)

#

n yeh explain me logarithm

#

plz

wary pivot
#

Decided to start looking into Algorithms & Data Structures. Already using AlgoExpert. Any books that explain the topic really well? (Considering buying a book on it in advance of learning it in class in about 3 months)

south umbra
jolly orchid
#

!python

#

!python code

fiery cosmos
#

!code ?

halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

versed fractal
#

why this backticks are used?

winged plover
raven kraken
#

Can someone share any resources from where I can learn how to solve problems based on matrix like valid sudoku or finding sum of diagonals. I always have a hard time solving questions based on matrix.

eternal ember
#

Hey just inquiring if anyone here has a discord server dedicated to solving codewars or hackerrank on regular basis? Trying to find a social group of people who enjoy solving such challenges so that I can motivate myself to be regular πŸ™ƒ

dapper sapphire
#

So if we have a string and we want to sort it as following:

string = "".join(sorted(string))

Then the time complexity will be O(n) + O(n log(n))
O(n) - for join
O(n log(n)) - for sorting the string

tropic glacier
#

That would just be O(n log n), since that one is bigger

#

O(f(n)) gives an upper bound

sacred meteor
#

hey

#

I am trying to replicate code for a game

#

the original is in javascript

#

however

#

when doing it in python

#

it gives an entirely different result

#
var seed = "a407ad70682db53dc93912dd3e30cc678f4e1e6015f56675c3f064010dc772e0"
var salt = "0000000000000000000fd438478cd50a858def3b606d43dfe12a22144f3a5f1b"

const nBits = 52;

const start = CryptoJS.enc.Hex.parse(seed)
console.log(start.toString(CryptoJS.enc.Hex))

const hmac = CryptoJS.HmacSHA256(start, salt);
seed = hmac.toString(CryptoJS.enc.Hex);
console.log(seed);

seed = seed.slice(0, nBits / 4);
const r = parseInt(seed, 16);
console.log(r);

let X = r / Math.pow(2, nBits);
console.log(X);

X = 99 / (1 - X);
console.log(X);

const result = Math.floor(X);
console.log(result);

console.log(Math.max(1, result / 100));
```this is the original js version
#

these are the outputs

#

anybody know at least how I can do the HMAC part in python? Whatever I do with hmac and hashlib just gives entirely different results, which leads to a different game result

dapper sapphire
dapper sapphire
tropic glacier
#

A function of n

dapper sapphire
#

Sorry, I dont get it. What do you mean by, A function of n?

feral hound
#

O(f(n)) means the big O of the function f with input n

dapper sapphire
#

When you said O(f(n)) gives an upper bound, in this case f(n) is replacing O(n) + O(n log(n)), since we use the one that takes the longest time we will use O(n log(n)).

feral hound
#

what your being told is that big O (O()) is concerned with the worst relationship between input size n and time/space

#

f(n) is replacing O(n) + O(n log(n))
almost
O(f(n)) is replacing O(n) + O(n log(n))

#

in this case that is

#

f can refer to any function but in this case its referring to your function

dapper sapphire
#

oh ok

fiery cosmos
#

like f(n) = n or f(n) = n*log(n) or f(n) = n^2, just some expression involving n

feral hound
#

O(f(n)) == O(n) + O(n log(n)) == O(n + nlogn) == O(nlogn)

dapper sapphire
#

oh ok thank you!! I see what you mean.

fiery cosmos
#

Is there a word wrap algorithm that preserves columns of text while still wrapping paragraphs? For example here.

 THE TURN OF THE SCREW
 I
 II
 III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case

Id like the columns to be preserved but the paragraphs of text to be word wrapped.

#

if i feed this to pythons textwrap function it will wrap everything

stable pecan
#

i started to do something similar for another project but didn't finish it

#

but, yeah, python's built in text wrap will modify all the text

#

Though, I think I could do something hacky real quick

fiery cosmos
stable pecan
#

i came up with something

#

messed up something

feral hound
# fiery cosmos Is there a word wrap algorithm that preserves columns of text while still wrappi...

sorry in case im misunderstanding but you just want this

The story had held us, round the fire, sufficiently breathless, but except the obvious remark that it was gruesome, as, on Christmas Eve in an old house, a strange tale should essentially be, I remember no comment uttered till somebody happened to say that it was the only case

to turn into this

The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
#

the first one is all on the same line discord just wrapped it

#

am I correct?

stable pecan
#

!e

my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""

def word_wrap(text, line_length=100):
    lines = text.splitlines()

    i = 0
    while i < len(lines):
        line = lines[i]
        i += 1

        if len(line) <= line_length:
            continue

        truncated = [ ]
        words = line.split()
        while len(words) + sum(map(len, words)) > line_length:
            truncated.insert(0, words.pop())  # could use a deque

        lines[i - 1] = " ".join(words)

        if i < len(lines):
            lines[i] = f'{" ".join(truncated)} {lines[i]}'
        else:
            lines.append(" ".join(truncated))

    return "\n".join(lines)

print(word_wrap(my_text, 50))
halcyon plankBOT
#

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

001 | 
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire,
008 | sufficiently breathless, but except the obvious
009 | remark that it was gruesome, as, on Christmas Eve
010 | in an old house, a strange tale should
011 | essentially be, I remember no comment uttered
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/rafuluwera.txt?noredirect

stable pecan
#

did i fix it

#

this could be prettified, it's hacky atm

fiery cosmos
#

wow i didnt think it was possible.

#

!e

my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""

def word_wrap(text, line_length=100):
    lines = my_text.splitlines()

    i = 0
    while i < len(lines):
        line = lines[i]
        i += 1

        if len(line) <= line_length:
            continue

        truncated = [ ]
        words = line.split()
        while len(words) + sum(map(len, words)) > line_length:
            truncated.insert(0, words.pop())  # could use a deque

        lines[i - 1] = " ".join(words)

        if i < len(lines):
            lines[i] = f'{" ".join(truncated)} {lines[i]}'
        else:
            lines.append(" ".join(truncated))

    return "\n".join(lines)

print(word_wrap(my_text, 90))
halcyon plankBOT
#

@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.

001 | 
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire, sufficiently breathless, but
008 | except the obvious remark that it was gruesome, as, on Christmas Eve in
009 | an old house, a strange tale should essentially be, I remember no
010 | comment uttered till somebody happened to say that it was the only case
fiery cosmos
#

ah i see

#

it will just skip the lines that are not past max

#

so it can only get smaller. It doesnt care if the columns go past its line length

#

so it wont try and fill

#

well anyways thanks

feral hound
fiery cosmos
#

yeah

#

but still preserve columns

#

of text

feral hound
#

ok will you paragraphs always be encased in
...
text
...

#

if that is the case its a lot easier since otherwise there is not real way of differentiating what is a paragraph

fiery cosmos
#

well im not sure i wanted support for any text file

#

yes it would be easier.

feral hound
#

so how do you know what is a paragraph?

#

if you can figure out a rule for that its possible

fiery cosmos
#

yeah i think what im shooting for is not possible

#

i guess ill just try and see what most pdfs or text files conform to

#

and try and make an algorithm for that

#

and everything else will turn out sloppy

stable pecan
fiery cosmos
#

hmm it might be better to do something like this instead

#

i just adjust the margins to have the text centered

#

instead of filling the page

#

i think long lines of text are harder to read anyways instead of nice decent size width paragraphs

#

that does mean id have to get the longest line of text in the pdf or whatever

stable pecan
#

you can add to the function to increase line lengths too

#

i didn't know you wanted that

#

just grab words from the next lines.

#

in a similar type of while loop

fiery cosmos
#

yes but wouldnt this cuase a problem with the columns of text?

feral hound
#

I have an idea instead of all this, are the paragraphs always guaranteed to have the longest line lengths?

fiery cosmos
#

im not sure.

feral hound
#

if that is the case what you can do is set a minimum line length check all the lines in the file until you reach a line of a certain minimum length lets say 10

stable pecan
#

columns can be identified by being less than some line length and having no full stops

feral hound
#

then keep appending those lines longer than 10 into a variable called text

#

use pythons text wrap on that variable and then just replace the lines where they need to be replaced

#

this way you set a min and a max value so that it only does wrapping on lines longer than the min value and wrap them to the width of the max value

fiery cosmos
#

lots of things to think about.

#

i think ill just make a random mad libs style text generator

#

becuase im still trying to build the app

#

pythons textwrap module can handle that

feral hound
#

!e

import textwrap
my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""

def wrap(text, threshold, width):
    start = []
    middle = []
    end = ""

    for line in text.split("\n"):
        if len(line) > threshold:
            middle.append(line)
        elif len(middle) == 0:
            start.append(line)
        else:
            end += line

    start = "\n".join(start)
    start += "\n" + "\n".join(textwrap.wrap("\n".join(middle) ,width=width))

    return start



print(wrap(my_text, 30 ,200))
halcyon plankBOT
#

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

001 | 
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire, sufficiently breathless, but except the obvious remark that it was gruesome, as, on Christmas Eve in an old house, a strange tale should essentially be, I
008 | remember no comment uttered till somebody happened to say that it was the only case
feral hound
#

its not completed yet but I think this is more along the lines of what you want

#

@fiery cosmos

#

!e

import textwrap
my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case

THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""

def wrap(text, threshold, width):
    start = []
    middle = []
    wrapped_text = []
    for line in text.split("\n"):
        if len(line) > threshold:
            middle.append(line)
        elif len(middle) == 0:
            start.append(line)
        else:
            start = "\n".join(start)
            start += "\n" + "\n".join(textwrap.wrap("\n".join(middle) ,width=width))
            wrapped_text.append(start)
            start = []
            middle = []

    return "\n".join(wrapped_text)

print(wrap(my_text, 30 ,200))
halcyon plankBOT
#

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

001 | 
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire, sufficiently breathless, but except the obvious remark that it was gruesome, as, on Christmas Eve in an old house, a strange tale should essentially be, I
008 | remember no comment uttered till somebody happened to say that it was the only case
009 | THE TURN OF THE SCREW
010 | I
011 | II
... (truncated - too many lines)

Full output: https://paste.pythondiscord.com/rayicayita.txt?noredirect

feral hound
#

and its completed πŸ™‚

#

threshold is used to determine where a paragraph starts and ends

#

its not the best way to do it but its the best we got rn until you can figure out some pattern to identify paragraphs

fiery cosmos
#

yes im looking at free ebooks and finding patterns.

#

Like here for instance

#

i can word wrap the paragraphs that have the full stops.

#

i dont want continuation of word wrap on the bullet point lists though. they have full stops but are separated by newlines

#

so maybe i can use that

#

i think ill just do random words for right now

feral hound
#

well depending on how general you want it to be you might have to do a lot check whats a paragraph and whats not

#

but as long as you can do that you can do something similar to what I did

#

in my code it just assumes that a paragraph is everything between a line longer (inclusive) than the threshold and a line shorter than the threshold (not inclusive)

heady latch
#

Hello all!

I'm looking for help with an algorithmns question. It was originally for HW but the submission date passed and I still can't wrap my head around the solution. I got the other 3 in the problem set but couldn't get an algo to pass all test cases for this problem.

Alice has chosen n holiday gifts for her friends. Alice knows that each gift will be on sale during Black Friday. The Black Friday sale price of giftiwill begiftPrices[i].sale. Theprice of item i before Black Friday will be giftPrices[i].before; and the price of gift i after Black Friday is going to be giftPrices[i].after. Alice wants to plan when to buy each gift to minimize the total cost of all gifts. The challenge is that Alice can buy at most k gifts on BlackFriday. She, however, can buy any number of gifts before and after Black Friday. Design and implement an algorithm for finding the minimum total cost of all n gifts. Write the following function

MinCost(const std::vector<Price>& giftPrices, int k) 

The parameters of this function are const std::vector<Price>& giftPrices – the list of prices and k – the maximum number of items Alice can buy on the Black Friday sale. Each element ofthe array/vector giftPrices contains three fields: sale, before, and after, as described above. Function MinCost should return the minimum possible total cost of all gifts. All numbers are integers

My original idea was to calculate the difference between Price.before and Price.after, Price.before and Price.sale. Then find the difference of those differences and choose the K largest difference of differences and for the rest swapping between before price and after price depending on which is less. This week was Greedy Algorithmns which I thought I had a good handle on from my AI course but clearly, I'm still struggling a bit.

I don't want a straight solution if possible, just some help finding the right steps. Thanks in advance.

fiery cosmos
lean dome
#

for each gift, you can choose to either buy it before black friday, after, or on black friday. Since you can buy any number of gifts before black friday, and any number after, the cheapest thing is either to buy it on Black Friday (for up to k gifts) or at the cheaper of the before price and after price (for n - k gifts).

#

so you want to choose the k gifts with the biggest delta between sale and min(before, after) - those are the k gifts that you save the most by buying on black friday.

#

and for each remaining gift, you take it at the min(before, after) price.

fiery cosmos
#

oh I wasn't thinking about differences pithink my strat may be wrong

lean dome
#

it never makes sense to buy a gift at the higher of the before price and the after price. So for each gift, you're choosing between buying it at min(before, after), and sale.

#

and since you can only buy k at sale, they should be the k where sale is most below min(before, after), because those are the k that you save the most by buying on black friday.

fiery cosmos
#

Yeah, taking the k gifts with the biggest abs(sale - min(before, after)) makes sense, then just min(before, after) after that

#

or that's not quite right lemon_glass

heady latch
#

I forgot to mention, I'm not sure this changes the solution, the sale price is not always less than the after and the before prices.

I think this is sort of similar to calculating the differences of differences and selecting on that, no? More straightforward but close to being the same metric? If the sale price could be more expensive that throws a wrench in this solution, I think.

I say that as a strong novice in algos

fiery cosmos
#

Sorting by min(before, after) - sale and taking the first k of those where the sale is chosen lemon_glass

heady latch
#

Also thank you so much for both of your responses

#

YouΕ•e right, the way I was calculating the heuristic was incorrect and this accounts for the sale price being greater

lean dome
heady latch
lean dome
#

right.

heady latch
#

Thank you so much, both of you! I had gotten off the Greedy path and the solution ended up being less complex than I originally thought. I would've spun my wheels for hours on that.

quiet jay
#

can someone help me with euler cycle

#

dm me

grim coral
#

Hello, i have a problem with list comprehension:

following code doesnt work, i basically wanna append 2 items into the list in one for loop.

class Solution:

def shuffle(self, nums: List[int], n: int) -> List[int]:
listo = [nums[i],nums[i+n] for i in range(n)]
return listo

the code should do the following:

class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
listo = list()
for i in range(n):
listo.append(nums[i])
listo.append(nums[i+n])

    return listo
halcyon plankBOT
#

Here's how to format Python code on Discord:

```py
print('Hello world!')
```

These are backticks, not quotes. Check this out if you can't find the backtick key.

trim fiber
#

[x, y for i in range(n)] returns list of tuples
It should be something like that

elements = [[nums[i], nums[i + n]] for i in range(n)]
elements = list(sum(elements, []))
#

!e

numbers = list(range(100))
n = 4
elements = [[numbers[i], numbers[i + n]] for i in range(n)]
elements = list(sum(elements, []))
print(elements)
halcyon plankBOT
#

@trim fiber :white_check_mark: Your eval job has completed with return code 0.

[0, 4, 1, 5, 2, 6, 3, 7]
grim coral
#

ahhhhhh okay thanks a lot @trim fiber

indigo wave
#

Hi There, I am trying to add a column to a dataframe using a function to provide the values. I am trying to figure out why this doesn't work:
change_df['Change (%)'] = format_change(change_df['Change'])
In my head that should create a new column called "Change (%)" and populate it with the function "format_change" and pass the value in "Change".

#

The error juypter is spitting out is
ValueError: -1 is not in range
which looking further down suggests that it has an issue with this line of the function
if string[-1] == '%':

#

But I cannot understand why it's unhappy as all my rows have values, stored as objects and have a minimum length of 3.

#

OK so I stumbled on the answer and I think my issue is using SQL like code, this is going to be a problem.

#

The code should be:
change_df['Change (%)'] = change_df['Change'].apply(format_change)

gilded vale
#

Hi everyone! I am just starting out in Python and made a program to calculate prime numbers and then store them in a csv file. Everytime I start the program I want it to move on where it left off so I read the csv file (every prime has its own row) into a list in python but because I work with rows the list becomes a list of lists. primes = [[2][5][7][9][11][13]]. The problem with that is if I want to access them I need to double index it prime[3][0] and the primes that are read into the list from the csv are stored as strings, where the new primes added are stored as ints. I can not index an int and as a result I get an error. Can anyone help with this problem? (this description is a mess I know ask for more info if needed please)

vocal gorge
#

Well, unpack the sublists once and get left with only one list.

#

something like primes = [row[0] for row in primes].

gilded vale
# vocal gorge something like `primes = [row[0] for row in primes]`.

I tried that but im fairly sure I used wrong syntax. Right now I am trying to solve the problem at the beginning to just convert every element to an int before it gets read into my list. So all the items in the list primes are ints from the beginning and I never have to subscript

fiery cosmos
#

hey

#

i need urgent help

#

how can i obfuscate code in python

sick bear
#

Hey fellas, simple slicing question.... If:
a = np.array([[1,2,3,4], [1,2,3,4]])
a[:, 1::4] = [[1], [1]],
how would I extract [1, 1] ?

vocal gorge
sick bear
#

Oh! I didn't think about that! thanks

#

Yup, that's perfect

fiery cosmos
#

@vocal gorgesorry for ping but how can we obfuscate code in py

#

?

hollow quiver
#

any reason why this would stop working? lat_hla = hla[-1] #get last char from string

#

the input comes from hla = pytesseract.image_to_string(im_hla)

agile sundial
#

empty string?

hollow quiver
#

for some reason the last char is blank now, so i had to change it to [-2], \n is being added to the end of the string by OCR, i need to figure how how to remove that first

agile sundial
#

!d str.strip

halcyon plankBOT
#

str.strip([chars])```
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or `None`, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:

```py
>>> '   spacious   '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
```  The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
hollow quiver
#

thanks that worked

granite pawn
#

Hello I Am Struggling With A Problem For Class:

Given two strings and a list of allowed "substitutions," return
whether one string can be converted into the other.

Example:

Input:
string 1: hello
string 2: helper
substitutions:
lo -> pa
pa -> per

Output:
true

This is true because "hello" => "helpa" => "helper."
white imp
#

you'd want to iterate over the string looking for match between the substring and the substitution

#

then iterate over the substitutions

#

?

granite pawn
#

That Only Shows If A Substitution Can Be Used?

#

What If You Need To Use More Than One?

white imp
#

iterate again would be the easiest

granite pawn
#

If The First Substitution Is h -> hh, Wont You Get Stuck On hello -> hhello -> hhhello?

#

Forever ?

white imp
#

depends what your code looks like

#

but it shouldn't

granite pawn
#

Thanks For Your Help

night blaze
#

i'm a bit confused about where you got this problem because it's not actually solvable

white imp
#

It should be solvable, it just seems arduous b/c you have to iterate over the substitutions multiple times

#

...or update the substitution list to include transitive substitutions, and avoid loops

gritty marsh
#

but that assumes its solvable and will search forever if not

night blaze
#

it's a bit tricky to explain why, but this is undecidable

#

no algorithm can solve it in the general case

shut breach
night blaze
#

and this is very loose but we can fairly easily construct some primatives right

#

eg.

1#stateA -> #stateA1
0#stateA -> #stateA0

would be moving our head to the left

#

we can come up with similar primitives for writing and stuff

white imp
#

Sounds complicated... if it's just a homework question, why not just iterate over all substrings

#

then look for mismatches

#

then substring(s) from 1 and iterate over the substitution list and look for matches

arctic spoke
#

hellp

#

im new to python

#

okk

radiant moat
# granite pawn Hello I Am Struggling With A Problem For Class: ``` Given two strings and a list...
def main(string1: str, string2: str):
    substitutions = {
        "lo": "pa",
        "pa": "per"    
    }
    save_string_1 = string1
    for key, value in substitutions.items():
        for key2, value2 in substitutions.items():
            for i in range( len(string1) ):
                for start in range(0, len(string1), 1 ):
                    try:
                        if string1 == string2: return print(string1) 
                        if key in string1[start:start+i]:
                            temp = string1[start: start+i].replace(key,value)
                            string1 = string1[0: start ] + temp + string1[start + i:]
                        if string1 == string2: return print(string1)
                        if key2 in string1[start:start+i]:
                            temp = string1[start: start+i].replace(key2,value2)
                            string1 = string1[0: start] + temp + string1[start + i:]
                    except:
                        break
    return print("no")                    


if __name__ == '__main__':
    main("hello", "helper")

I actually made something like this

#

not sure it properly works but it does for ur exampel

blissful sierra
#

Does anyone know of some good resources for explaining memoization?

tropic glacier
#

It just means caching the result of a computation so that it can be looked up in the future rather than recomputed

#

For example, if you want to write a function that tells you the n-th prime, you'll have to compute all the (n-1) primes first, so you might want to just save those results, in case you get asked to find another prime again.

radiant moat
#

if u copy the for start loop and add it after but with a descreasing loop, the code will work with only two syllabus in input/output. If u want more u need to find a way to nest for loop

#

Maybe not the best solution but i will work

#

For further optimisation you can detect all iterations of substitutions strings and iterate over them

faint sentinel
#

can anyone please share the solution of how to calculate time complexity of this , with the mathematics involved also ,step by step

#

Please help

trim fiber
faint sentinel
#

yes

#

but i think it is simple enough , to be easily understood

trim fiber
#

Time complexity is O(n^3) as far as I see

#

Or not

#

It's rather O(n^2)

faint sentinel
#

i calculated it is O(n^3) coming ,

#

i am wanting a detailed step by step solution for this problem

feral hound
#

so your outer for loop actually only does one iteration

#

so the time complexity all comes from i<n*n; i++ which is n^2

#

also you should really think about how you style your code that looks disgusting with wrong/inconsistent indents and no spaces in the for loops

sudden urchin
#

Hi , I have a problem

#

let's say the tuples are random rgb values
I want all the ones with a lot of red at the top
and all the ones with a high (yellow - blue) on the left
but i want to do it by sorting it into quadrants and then sorting the individual quadrants into quadrants etc

feral hound
sudden urchin
#

a 2d array

feral hound
#

ok I think I get what you want now

sudden urchin
#

(i have exactly 4**n tuples, btw)

feral hound
#

btw do you mean green and blue?

sudden urchin
#

yes, sry

feral hound
#

and how would that work for the green and blue what rule would you use there?

#

or are you treating them equally?

sudden urchin
#

basically lambda x: x[1]-x[2]

feral hound
#

because if you want a nice gradient thats not what your gona get by sorting both on the left without some specific rule

#

you could do red on the top, green on the bottom and blue on the right if you want a nice gradient

sudden urchin
#

I only used colors because i thought it would be easier to understand

feral hound
#

what im trying to say is do you want something like this?

sudden urchin
#

no, i have a list of tuples that have nothing to do with colors other and i want to make them more or less binary searchable in two dimensions

feral hound
sudden urchin
#

they have something to do with each other but not with colors

#

sry

feral hound
feral hound
#

do you actually care about how they're stored or are you only doing it for the binary search

#

and do you care about their order, or is it again just for the binary search?

sudden urchin
#

In the end I would like to have a 2d array that i can feed into my cnn

feral hound
#

ahh I see so as long as its a 2d array you dont care?

sudden urchin
#

I want similar tuples to be close together

#

basically

feral hound
#

well my question is because I want to change the definition of a similar tuple

#

you could just have it so that you sort it using the sum of the values in the tuple

sudden urchin
#

that wouldn't work for me

feral hound
#

why not?

#

you can achieve what you want but you need to first have a very clear definition of how to compare the tuples

#

wouldnt that still work?

#

I'm thinking of it now since your doing deltax + deltay if you sort them using x+y it should still work no?

sudden urchin
feral hound
sudden urchin
#

or maybe I'm not understanding you correctly