#algos-and-data-structs

1 messages · Page 32 of 1

vocal gorge
#

Mostly I just don't like query tbh.

fast swallow
#

I really don't either and have used .loc almost always, but I recently went back to look at the pandas cheat sheet after years and saw .query mentioned in there a lot.

snow anvil
#

In the huffman coding the longest codeword length is n-1 right?

#

nvm I figured it out I'm just stupid

magic lodge
#

even though that is a decent question, it looks a lot like a homework question, and so you will likely get no answers. if you rephrase the question, perhaps people can help

tidal cosmos
#

Given an image like this, represented as a 2D array, is there an easy way to fill the regions enclosed by the colored boundaries?

tiny jay
tidal cosmos
magic lodge
#

yeah no I completely get that, but it’s against the server’s rules to ask homework questions and realistically there’s no way for anybody to verify what you’re saying so you likely won’t get any replies until you re-phrase the entire question

#

That is fair, it is difficult. I think you would probably get an answer if you just asked for the upsides and downsides of the algorithm you mentioned

jovial creek
#

Not too sure the exact ask, but I’d think about this from a worst case scenario graph theory. So…

Assuming network :
A <-> B <-> C

And you want to delivery data from A to C. We know that there is 2 hops to get us there. A to B and B to C. From there I’d take the desired time and divide it by the rate ex

Goal : 1 KB / 10 seconds
Result : each edge needs at least 1KB / 5 seconds

With a more complicated graph you need to find the worst case distance and work backwards from there.

Not sure if this hit on what you were asking, but if so I hope it helps

thorny ivy
#

I wonder if we cant sort the intervals by where they end instead and then pick first that is "within reach". Although im unsure if sorting is still the bottle neck in this case

haughty mountain
#

you have a slightly different problem

haughty mountain
#

I think I posted it way earlier, this is some very easy version of vertex cover

thorny ivy
#

i think it was

haughty mountain
#

ah, right

#

it's pretty obvious what the greedy thing is

#

you need to include the leftmost point

#

what's the best choice of interval?

#

you have nothing to your left, so you can just pick the thing that extends the furthest to the right

#

if you didn't pick the one extending the furthest, you could swap the decision to the one that does and the solution will be as good or better

#

the above is a quite typical exchange argument to show the greedy choice is optimal

#

I would just sort and then do the greedy thing

#

I can't see any obvious thing you can do to make it better than that complexity-wise

thorny ivy
#

Since its sorted wrt to starting point

#

i guess the same argument could be made with my "approach"

haughty mountain
#

O(n²)?

thorny ivy
#

if we have n points we need to cover

haughty mountain
#

for all intervals starting before the first point pick the one that extends the furthest

#

you only need to look at the intervals starting before that point

#

and you never have to look at those intervals again

#

so you will end up looking at every interval only once

#

so O(n)

#

(O(n) after sorting first)

#

typing in discord on a phone sucks, but something like

intervals = [...]
points = []

intervals = deque(sorted(intervals))
points = deque(sorted(points))

while points:
    cur = points.popleft()
    candidates = []
    while intervals and intervals[0].left <= cur:
        candidates.append(intervals.popleft())
    covered = max(c.right for c in candidates)
    while points and points[0] <= covered:
        points.popleft()
#

switched to left/right which ought to be clearer than [0] and [1]

#

it's untested code anyway

thorny ivy
haughty mountain
#

remove all intervals starting <= current point these are candidates for the next interval to pick

#

after picking the interval we remove any "bonus point" we happened to cover for free

thorny ivy
haughty mountain
#

you could, but it wouldn't really be faster

#

you would need to sort to create the graph efficiently

#

and I can easily construct setups with O(n²) edges

thorny ivy
#

so you create 2*n edges

haughty mountain
#

I mean, this is basically graph that the greedy approach walks in, you just don't create the graph

thorny ivy
#

yes i just think this solution (if it is correct) is a bit more intuitive

haughty mountain
#

what's not intuitive about the greedy solution?

haughty mountain
thorny ivy
#

greedy is easy to prove though

haughty mountain
#

e.g.

*        *         *          *
--------------    ---------------
       -----                ------
thorny ivy
#

my statement of the problem was a bit vague

haughty mountain
#

the greedy algo doesn't change at all whether that's true or not, which is nice

haughty mountain
#

it's very similar

#

the problem is a tad different

#

the next point will always be the last end of segment

#

rather than some given point

#

but the approach is basically identical

hearty marsh
#

Umm.....

feral shale
#

Obviously learn Python

vapid sage
#

can I ask u guys a question? Im studying CompSci and Im learning through Python, and most universities offer a class called "Intro to algorithms and data structures" should I learn this before I tackle any sort of project/application?

ivory yacht
#

It may be a good idea. Understanding those fundamentals helps you know the vocabulary and techniques, so you have a good idea for what things are easy/hard to accomplish, how to do things more efficiently, etc.

vapid sage
#

Ok thank you for the response i understand the language like loops and stuff ig i just don’t know how to put it together where something would actually be made out of it kinda, ik i shouldn’t stop myself from learning and stuff but what do u think i could do to become better?

haughty mountain
#

ds&a is not language specific

quick wing
#

Hello guys, i alreday asked this in the help channel but my post disappear pretty fast everytime so i try here too myb here his my request :

"Hello, hello, I'm currently trying to code a small crowd movement simulation for a room evacuation, I've started using spyder for the first time, I was on edupython before and for some reason I never get the same errors between the two. Apart from the fact that spyder has a much harder time with animations, I have the following error on python that I can't manage to correct at all:
Cannot cast ufunc add output from dtype('float64') to dtype('int32') with casting rule 'same_kind' "

https://paste.pythondiscord.com/dovanegazo
Save me pls lmao

haughty mountain
#

I'm guessing pos is an array of int32 and v is an array of float64

#

posting the actual traceback really helps debugging

File "a.py", line 90, in animate
    self.update()
  File "a.py", line 65, in update
    ball.move(self.emergency)
  File "a.py", line 121, in move
    self.pos += self.v
numpy.core._exceptions._UFuncOutputCastingError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int64') with casting rule 'same_kind'
#

I think pos is int32 since you get it from argwhere earlier

#

make both the same type and that issue should go away

magic lodge
#

it is probably because there can be precision issues if you mix different float and int types. you need to enable "same_kind" casting which will allow the engine to do the conversion for you, at the cost of potential correctness

#

in numpy you can set casting="unsafe"

haughty mountain
quick wing
#

Thank you very much, you've clearly unblocked me and I've been able to make a lot of progress (on 1hour so not that much in general xD). I have a new problem for you, though, which concerns optimisation: on my computer with edupython and the new additions, the animation takes a good minute to activate, so how can I optimise this?
https://paste.pythondiscord.com/xijutoduba

halcyon plankBOT
#

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

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

sudden sedge
#

Hey everyone
I am currently trying to figure out how to create random floorplans for my TTRPG project through python code. I've seen different methods for dungeon floor generation but they don't fit what I need. So I thought I would create premade tiles in different sizes and shapes (e.g. 1x1, 2x1, 3x4 squares) and then write an algo to place it around hallways etc. to create something that at least resembles a proper floorplan.

Problem is, as it seems I am in way over my head. My knowledge of Python is currently not good enough. Do any of you know of projects with either documentation or open source code that I could study, that fit my idea?

There are a lot of information online. But most are more research based (MIT, Harvard) with the usage of GAN, sample data and letting an AI create floorplans

#

I basically just need to fit different rooms in a set sized layout and have it connect the doors to hallways, so that all rooms are accessible either through another room or a hallway

terse gorge
#

if you haven't already, I would suggest to read more about procedural generation with wave function collapse. I think you are trying to do the same (do correct me if i'm wrong).

https://medium.com/swlh/wave-function-collapse-tutorial-with-a-basic-exmaple-implementation-in-python-152d83d5cdb1 here is an article to get you started and I think TheCodingTrain also has a great video about it on his YouTube channel.

Medium

This algorithm will help you create amazing procedurally generated images, maps or textures from your sample

#

@sudden sedge

sudden sedge
terse gorge
#

no problem, glad I helped

sudden sedge
# terse gorge no problem, glad I helped

Just a quick question about wave function collapse. I see that it is able to solve tiles that are the same size etc. Do you know if it is possible to add different sized tiles?
e.g. I have a graphic created in Dungeondraft for a fixed sized room (3x3 squares or 2x2 squares or L shaped etc.). I thought about making sprites that resemble those rooms and show where is the floor, wall and door etc. so the algorithm can calculate based on the simple 9x9 pixel sprites what fits together and then substitute it with the PNG's from Dungendraft.

But I would need to write my python code in a way, that a 3x3 room uses up 9 squares in total in the grid

#

I understand the basics of Python and can work with example codes etc. to create some Frankenstein-code examples that usually work really well. But before I invest ungodly amount of time to achieve my idea, I'd like to know if that even is possible before I start

#

If not, then I could just create the tiles and let the wave function assemble it. But then it is going to be hard again to have a "proper floorplan" as an output, because it will be more random. I'm trying to find some middle way between the two

#

My idea about the premade rooms

#

Example sprite in a 9x9 pixel grid for the algorithm to figure out how to place it and then switch out with one of the PNG on top

#

This would be a 2x2 room with the door on the right

terse gorge
#

I think what you can do is to have tiles that are versatile, so they can be used to make 2x2 rooms and 3x3 rooms as well, which I think you already have. All that is left to do is to force the wave function collapse to have these rooms when it collapses. There should be a way to force certain patterns in the final output, maybe you can find an article about it online, or refer to TheCodingTrain video where he builds one from scratch and explains how it works throughout in-depth, and then you make your own custom wave function collapse

fiery cosmos
#

import random
user_action = input("Enter a choice (rock, paper, scissors): ")
possible_actions = ["rock" , "paper" , "scissors"]
computer_action = random.choice(possible_actions)
print(f"\nYou {user_action}, computer chose {computer_action}.\n")
if user_action == computer_action:
print(f"both players selected {user_action}. Its a tie")
elif user_action == "rock":
if computer_action == "scissors":
print("rock smashes scissors You win!!!")
if user_action == "paper" and computer_action == "rock":
print("you win paper covers rock")

#

why this dont work

orchid violet
sage flame
#

considered O(n)

#

and not O(n^2)

royal kestrel
#

because the inner loop can only ever execute a total of n times during the runtime of the program, not n times for each iteration

lone magnet
#

can someone help me out with an algorithms question?
consider the following statement: "if G is an undirected graph on n nodes and n edges, then G contains cycles" is this statement true or false? give proof, or a counterexample

#

i feel like the answer is true because i wasn't able to find a counterexample so far but a gut feeling (all the answers in the other 5 past papers i solved were false for the same numbered question) says the answer should be false

royal kestrel
#

start from just A-B and see what happens to the number of nodes and edges when you keep adding new nodes

lament totem
#

If you have 1 node and 0 edges then there is no cycle ig

#

Or just 0 edges in general

royal kestrel
#

that doesn't have n nodes and n edges though

lament totem
#

Oh right

#

A graph with 0 nodes and 0 edges? 😛

#

Otherwise there will always be a cycle pretty sure

agile sundial
#

oh wait that's not the question

lone magnet
#

if trees count as graphs i could be getting somewhere

agile sundial
#

a tree is a graph, yes

lone magnet
#

i managed to come up with a proof:

proof by contradiction. suppose that such a graph with no cycles exists with n >= 1. then there's a node with only one edge. keep removing that node and edge until n=3. since the minimum number of edges required to form a cycle is 3, 3 nodes and 3 edges will always be a cycle.

lament totem
#

Can n not be 0?

snow anvil
#

The question does not specify n element of N/{0} so I'd assume that is a valid counterexample

snow anvil
#

Unless it's for practice that is perfectly understandable

lone magnet
snow anvil
#

Did your question specify if n>0?

lone magnet
#

i mean.. you cant have a graph with negative nodes can you

snow anvil
#

And n=0?

lone magnet
#

also if n=1 it cant have an edge, if n=2 edges can only be one so the minimum number of n is automatically 3

lone magnet
snow anvil
#

That depends on how you defined it

lone magnet
#

from knowing my professor i can say that he definitely wouldnt write an exam question worth half the points on the paper just to be disproven by n=0

#

it is indeed one of two questions of the exam

royal kestrel
#

well it doesn't really make sense to talk about cyclic graphs for n < 3 so it's probably just an oversight

snow anvil
#

That would make sense

#

But it seems rather sloppy

haughty mountain
royal kestrel
#

it's undirected

#

you can't have duplicate edges

haughty mountain
#

undirected graphs can have duplicate edges

snow anvil
#

in the course I am taking rn we disallow that I assume similar for him

haughty mountain
#

but it ultimately comes down to definitions

#

often you disallow both self edges and duplicate edges

#

if that's the case there exist no graphs with n edges and n vertices for n=1 and n=2

#

if you allow these then such graphs exist and will have cycles

snow anvil
#

yup strange if its really worth that many points

#

that reminds me I should study 💀

haughty mountain
#

granted how we deal with the small n where such graphs don't exist kinda comes down to "vacuous truth"

#

but for n > 2 you can make quite basic arguments for why cycles must exist

#

if I had this question in an exam I would answer something like an if else

#

"this is somewhat ambiguous, if your definition is this then the answer is A otherwise it's B"

#

I had some linear algebra exam where most of the "give me an example of a matrix with this property" could be answered with the scalar 1

snow anvil
#

💀

haughty mountain
#

(or 1x1 matrix [1] if you prefer)

snow anvil
#

I genuinely hope my profs dont do that ´cuz Ill always take the easy way out if the qustion is badly defined

surreal garnet
#

hey, idk if this question belongs here or in another channel, but i have an issue with saving a 3d np array as a npy file ... the values i have in my array are all as they should, however when i load the .npy file it contains almost only zeros except the first line and i havent found the reason why it is doing that, can anypne help with that?

vocal gorge
fiery cosmos
#

hello guys, I have a question, does every value assigned to a variable is kept in the ram when you assign other?

#

does values 2 are the same or they have different address in the memory?

agile sundial
agile sundial
fiery cosmos
#

sort of

#

I want to know if the "2" are different

#

or the same value with the same address

#

like a copy of the same value in different addresses

vocal gorge
#

This is implementation-dependent, but in CPython the two references to 2 will be to the same object.

covert mulch
#

Somebody knows basic python servers

hushed spear
#

working through kragers algorithm right now, and overall it makes sense, but i'm confused on the random edge part. how do i select it, and what exactly do i select?

haughty mountain
#

meaning things that connected to either node now connects to the new merged nose

limber hollow
#

sadness

sacred meteor
#

I need help

#

@polar grotto

#

@jovial kernel

hushed spear
#

one more thing, with a graph setup like this:

graph = {"A": ["B","C"],
         "B": ["A","C"],
         "C": ["A","B"]}

whats the best way to format a supernode, and whats an efficient way to pick a random edge? should i just have an array of all the edges?

#

i think i would format a super node like this

graph = {["A","B"]: ["C"],
         "C": ["A","B"]}

but i have no idea if thats correct/best practice

lean walrus
#

You cannot put ['A','B'] into dict. ('A','B') will work but it is immutable

hushed spear
#

is a better solution "AB" then?

lean walrus
#

What if you have more than 26 nodes?

haughty mountain
#

caveat, I have never implemented this algo myself

#

I know the algo, but I don't know the exact book-keeping you need to do

hushed spear
haughty mountain
#

something like that, though I would probably think of it as joining A into B or B into A

#

like, merge A into B, B is the new node and A is gone

hushed spear
#

ah ok, that makes a bit more sense

haughty mountain
#

it probably doesn't matter much, but for me it's easier to think like that

hushed spear
#

nah it does make it a bit easier

#

also, how would i go about choosing an edge? do i just choose a random node, and then a random edge in the array that corresponds to said node?
i.e;

graph = {"A": ["B, "C"]
#choose A to merge into B
haughty mountain
#

ah, I was about to mention disjoint set union data structure, and it seems the wiki mentions something Kruskal like

#

but that's only to get some speedup

haughty mountain
#

you want to pick some edge at random

#

so you probably want a list of edges to randomly pick from

hushed spear
#

so with the example graph I've been running with it might look something like this

 graph = {"A": ["B","C"],
         "B": ["A","C"],
         "C": ["A","B"]}

graph_edges = ["A","B","C]

?

haughty mountain
#

how are those graph edges?

hushed spear
#

i guess thats what i'm confused on, how do you pick a random edge if you don't really label the edges?

haughty mountain
#

if I don't include duplicate edges you would have a list of edges like

[['A', 'B'], ['A', 'C'], ['B', 'C']]
#

(i.e. I don't include ['B', 'A'] because we already have ['A', 'B'])

#

a simple way to build this is just

edges = []
for node, neighs in graph.items():
  for neigh in neighs:
    if node < neigh:
      edges.append([node, neigh])
#

that if means you only keep one of the duplicate edges

#

(I guess a tuple (node, neigh) might be better here, but same idea)

hushed spear
#

yeah that makes sense. so from there, you would pick a random edge (say ["A","B"]), and do

graph["A"] = graph["A"] + graph["B"]
graph.pop(node1)
graph.pop(node2)
#

well I guess you would technically use indexes from the edge, but same concept

hushed spear
#

here's the code im using right now:

def merge_node(graph, node1, node2):
    graph[node1+node2] = list(set(graph[node1] + graph[node2]))
    graph[node1+node2].remove(node1)
    graph[node1+node2].remove(node2)

    graph.pop(node1)
    graph.pop(node2)

how do i go through the entire graph and remove any instances of node1 and node2? or is there a more efficient way to do it?

tawny prairie
limber hollow
#

I have one using lstm that works fine

#

2.00 loss

tawny prairie
#

im into writing algorithms i have several going in my head with sound, but my first project needs to be finished

limber hollow
#

I just did it because I wanted to try out yfinance and the data is pretty good

tawny prairie
# limber hollow I just did it because I wanted to try out yfinance and the data is pretty good

just like many things with programming, the data is important and having already good data is only as good as how that data in implemented. Organization of that data is good in both context and math. the biggest issue is always turning that data into the most compact and useful item in object oriented programming, if you can always reduce the value to the lowest common denominator you can algorithmically compute mass amounts of data quickly

limber hollow
#

True

tawny prairie
#

im trying right now to create my first program and having something on my portfolio.. and getting back into programming has been a crash learning curve since i made a script or two for mirc

#

its been roughly 34 years give or take a year or few

tawny prairie
# limber hollow True

but ive always understood programming my frist program was 11 in basic, it went from random dots on the screen to creating a module that kicked out a day of the week using just the numerical date. in about a month because i didn't have a computer, i went to the local boy's and girl's club that had like 10 apples LE's

haughty mountain
#

it seems you can do something similar to Kruskal's algorithm to speed it up, but that can be implemented later when you know the naive thing works correctly

limber hollow
#

I just need to fix the x axis

hushed spear
#

will removing D in this example cause a self loop?

hushed spear
tawny prairie
# limber hollow

hey that is a beautiful function.. you realized that this function could be used in audio right.. badass really

limber hollow
#

the points or the average?

#

the average is just the average distance between each point

#

the model plots those points and then I graph the average

tawny prairie
#

add a low, mid, high range segmented function to isolate those frequencies and combination style a base line for average variance and then you could use that as a filter in pure math that doesn't have odd sound ambiance and place up that the combo of all three ranges as

tawny prairie
# limber hollow the points or the average?

the point is i saw beauty in the function as you your average input showed segmented values in a set that could be represented segmented in high mid and low range, the mid range is evaluated with in a given average data set, the actual input is being compared to it, and within an average data set you could filter out general ambience in a average plot, matrix the compared values to give the average and combine all sets to equate the average of all frequencies to digitally represent a cleaned value of the audio.

limber hollow
#

oh you're talking about the actual function

tawny prairie
#

yeah

#

i saw it in your gui there

limber hollow
#

isn't it frequency response?

tawny prairie
#

yeah but a minded one, a averaged one, that is digitally represented with out all the other frequency junk but that junk is also being averaged out, and the point it combines and meets the general average of three sets, the main value data, and the average data set , when the actual data is compared any junk frequencies are omitted and only frequency junk that is averaged out is gently faded against the data so that the ambience is rendered beautifully.. btw this is all from seeing your output, and saw your function beautiful.

#

ive been toying with the idea of a 3d represented fourier transform that mathematically filters out noise. 3dishly with 1 60 interval and blah blah blah i haven't even started the code yet im doing something else. gotta make a gui for an organization that needs one, i usta be a client, i know their operations i already have a gui skeleton working but ugh

tawny prairie
# limber hollow isn't it frequency response?

think about that question for a moment, you can't make dynamic variables without input, you variable represents a value to the "frequency" of the input given, the reason your variable gives a value is because you set the average within an average, one that spits out a value of the average curve

limber hollow
#

fourier transformations scare me

#

I could've used it for this but the math is too heavy

tawny prairie
#

but your version of the same result but better is apparent

#

you helped me complete the one i had in my head for 7 years, well one of the modules anyhow, i have several figured out, i haven't started yet as i said im doing something else

limber hollow
#

nice

#

I need to still work on this though

tawny prairie
#

hold on, start a new one, as an experience point lol

#

save this one and start another of the same to change it.

#

the original code is valuable and good mindful programming common sense to do so

limber hollow
#

well this one doesn't even have the x axis properly tracked and the dataset is only using the past year

#

instead of the entire history

tawny prairie
#

you axis is there

#

you don't see it cause you don't see the function yet

#

i do

#

if you look at your output like i did

limber hollow
#

I want it to label the months instead of the days basically, 0 to 365 instead of just stopping at 140, its supposed to predict 30 days

tawny prairie
#

you can see that you can segment the whole thing in to into a 3rd, then those can be a 3, and those can be a 3rd,

#

a 3 by 3 matrix

#

you can average line those segmented values, and come up with an average plot between them

#

then compare them to another matrix of the learned average plot on all those values that can be compared to the actual data and filtered accordingly.

limber hollow
#

like that

#

I thought of having a regression shown too and having that in the dataset for the history

#

so that it'll try to match it

tawny prairie
#

which could be calculated by the value set created by the 3,3,3 representation, that is more confined within the original set

limber hollow
#

ok

tawny prairie
#

wait

limber hollow
#

I believe mine is 2,1 for the matrix though

tawny prairie
#

yeah

#

that that 2 one

#

because im thinking audio your thinking data sets, mind your input as an audio signal in this example and please save this to a new file.. but i only saw your function in the graph,

#

that 2,1 for me is left and right audio, what ever your two is just keep it for your purposes

limber hollow
#

I didn't learn much about audio signals. Only thing I know about audio is from music. I've only been learning statistics, and cal for this stuff in the program I used

#

I am trying to learn data science and thought this was cool

tawny prairie
#

im just helping you with my problem of your function, that i believe is perfect for the purposes of mine, not yours, remember you are master of your code, although i believe code is perfect pass on but ..

limber hollow
#

yeah I see what you mean

#

but this is mainly for me to learn from right now

#

so I get used to the libraries

tawny prairie
# limber hollow I didn't learn much about audio signals. Only thing I know about audio is from m...

basically think of your 'data' sets that you find in tangible land, as data being read off a audio file, that line your looking for is your current data entry's for your current code, basically i can change your module that inputs the code and mathematically plots your gui data set, the data function can use the audio input as a representation of a fourier transform that is being fed to your algorithm.

#

basically audio is gonna be easy for ya bro, just don't think as audio as sound think of it as data your gonna go places and you have something you already made that you can build into what we talked about

#

just hope i can beat you too it

limber hollow
#

you probably will, I just started with this stuff

tawny prairie
#

i started again after to 34 years, and i remember how fast i learned then

#

its been two weeks for me and i already have half the battle with my GUI, and i am stalling because im trying to get this ICON thingy in my window and i have in my parent where my code is running but i can't seem to get the stupid image up on my tkinter winodow, but i am adding this later and im wondering what im doing wrong

tawny prairie
limber hollow
#

Not yet

#

I'm gonna upload it when I think it's good

haughty mountain
hushed spear
#

so the little diagram i drew is correct?

haughty mountain
# hushed spear

idk, if the lists are super useful there, but yes that would be the end state

#

the duplicate edges are intentionally kept

vocal gorge
#

that's a warning, not an error. I'd guess ships_pos is very high and so cubing it overflows the float. It'd need to be more than around 10^100 for that.
(much less if you're using 32-bit floats.)

rich oasis
#

I will get a data from the user. This data should be 8 digits and consist of numbers only. I know I have to use the ascii table for this. but while providing these conditions, I get confused in the use of "while", "if" and I need help on this. (I'm new to python.) my codes:

#

print(f"---{sayac}. Demirbaşın Bilgileri---")
barkod_türü = input('''
(Bu program sadece 1D barkodlar için geçerlidir.)
1-EAN-8
2-EAN-13
3-UPC-A
4-UPC-E
5-COD 39
Demirbaşın barkod çeşidini seçiniz : ''')
if barkod_türü == "1":
barkod_no = input('''(8 HANELİ)
seçilen barkod türü: EAN-8
Barkod no giriniz : ''')

    if len(barkod_no) != 8:
        input('''Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
                         (8 HANELİ)
                         seçilen barkod türü: EAN-8
                         Barkod no giriniz : 
              ''')
elif barkod_türü == "2":
    barkod_no = input('''(13 HANELİ)
                         seçilen barkod türü: EAN-13
                         Barkod no giriniz : ''')
    if barkod_no != 13:
        input('''Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
                         (13 HANELİ)
                         seçilen barkod türü: EAN-13
                         Barkod no giriniz : 
              ''')
elif barkod_türü == "3":
    barkod_no = input('''(12 HANELİ)
                         seçilen barkod türü: UPC-A
                         Barkod no giriniz : ''')
    if barkod_no != 12:
        input('''Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
                         (8 HANELİ)
                         seçilen barkod türü: UPC-A
                         Barkod no giriniz : 
              ''')
#

elif barkod_türü == "4":
barkod_no = input('''(6 HANELİ)
seçilen barkod türü: UPC-E
Barkod no giriniz : ''')
if barkod_no != 6:
input('''Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
(6 HANELİ)
seçilen barkod türü: UPC-E
Barkod no giriniz :
''')
elif barkod_türü == "5":
barkod_no = input('''(max 43 HANELİ)
seçilen barkod türü: COD 39
Barkod no giriniz : ''')
if barkod_no > 43:
input('''Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
(max 43 HANELİ)
seçilen barkod türü: COD 39
Barkod no giriniz :
''')
else:
secim2 = input('''Seçiminiz hatalı, lütfen tekrar deneyiniz..
Demirbaşın barkod çeşidini seçiniz : ''')

hushed spear
#

also before i forget again thank you very much for all the help!

lone magnet
rich oasis
unborn yew
#

I am performing a Fourier transform on a function, let's say a Gaussian function, given by f(x). After applying the Fourier transform using the np.fft.fft(f(x)) function in Python, I obtain a set of coefficients stored in the variable coff.
coff = np.fft.fft(f(x))
However, instead of plotting the fft^-1 of the transform, I want to plot the Fourier series!
I tried to write it in Python and it didn't work for me.

limber hollow
haughty mountain
#

the former is the limit of the latter

#

I guess the DFT is quite related pithink

haughty mountain
#

!e

from math import pi

import numpy as np
import matplotlib.pyplot as plt

def plot_series(series: list[float], period: float = 2*pi, to_show: set[int] = set()):
    funlen = 4096  # Resolution of plot
    t = np.linspace(0, period, funlen)
    coeff = 2/len(series) * np.fft.fft(series) # Normalized

    plt.figure(figsize=(10, 10))
    plt.subplot(2, 1, 1)
    plt.title('Terms')
    plt.subplot(2, 1, 2)
    # Plot original function.
    series_t = np.linspace(0, period, len(series))
    plt.plot(series_t, series, 'k--', alpha=0.25)
    plt.title('Sum')

    y = np.zeros(funlen, dtype=complex)
    for n, c in enumerate(coeff):
        s = c * np.exp(2j * pi * n * t / period)
        y += s
        if n in to_show:
            plt.subplot(2, 1, 1)
            plt.plot(t, s.real)
            plt.subplot(2, 1, 2)
            plt.plot(t, y.real)

    plt.savefig('foorier.png', dpi=300)

n = 128
step = [1.0]*n + [-1.0]*2*n + [1.0]*n
interval_size = 2*pi

plot_series(step, interval_size, to_show={1, 3, 5, 7, 9})
halcyon plankBOT
#

@haughty mountain :warning: Your 3.11 eval job timed out or ran out of memory.

[No output]
haughty mountain
#

how does image support work with !e again?

#

I guess I'll need to upload it myself 😔

steady hamlet
#

how can k-SAT be reduced to #k-SAT in polynomial time?

robust dagger
tawny prairie
silver drift
#

@keen merlin it's depth first search using recursion, which means you go as far as you can down a path before searching through other branches ```py
def find_all_paths(graph, current_path, end):
def inner(current_path, end):
if current_path[-1] == end: # base case for recursion (if you got to the end node, then stop)
return [current_path]
paths = []
for node in graph[current_path[-1]]: # loop through possible next nodes
if node not in current_path:
n_paths = inner(list(current_path)+[node], end) # search for paths from the next node to the end
for n_path in n_paths: # store the paths that were found
paths += [n_path]
return paths
return inner(current_path, end)

silver drift
#

mb it should be path

keen merlin
silver drift
#

let's say we have a graph like this:

      C - D - E
     /     \
A - B       F - G
     \
      H - I

#

and we have to find the path from A to G

#

since there is an edge from A to B, the algo will start looking for a path between B and G

#

to find if there's a path from B to G, it either has to go from C to G or H to G

#

and it first checks for C->G

#

which becomes D->G

#

from here it has to either find a path from E->G or F->G

#

so it first checks for E->G and fails

#

and only then does it start searching F->G

keen merlin
#

i get the abstract concept but how does this translate to code

silver drift
#

I was just explaining how recursion results in going as far down the path before others (called 'depth first search') instead of a different ordering (called 'breadth first search')

#
def find_paths(graph, start, end):
    def inner(current_path, end):
        # Base case
        if current_path[-1] == end:
            yield current_path
            return
        # Look for potential next nodes
        for next_node in graph[current_path[-1]]:
            if next_node in current_path:  # Prevent visiting the same node more than once
                continue
            yield from inner(current_path + [next_node], end)
    return list(inner([start], end)
``` here's a cleaner version \:P
azure osprey
#

Has anyone here implemented a backtracking list?
I would like to know how you approach that

haughty mountain
naive oak
#

like backtracking?

mighty pelican
#

need some advice,

is this

self.idx -= 1 * (self.idx > 0)
self.offset -= 1 * (self.idx < self.offset and self.idx >= 0)
self.screen_idx -= 1 * (self.screen_idx > 0)

better than this?

if self.idx > 0:
    self.idx -= 1

if self.idx < self.offset and self.idx >= 0:
    self.offset -= 1

if self.screen_idx > 0:
    self.screen_idx -= 1
naive oak
#

in terms of readability second is defo better

#

idk if python does branch optimization

#

but it seems like it'd be negligible

silver drift
#

(and yield current_path.copy())

haughty mountain
#

if the caller can be trusted to not modify the list you can avoid the copy

rich oasis
#

vscode üzerinden bir python fonksiyonuyla bir txt dosyasına bilgi eklemeye çalışıyorum. Kodlarda hata yok. Bilgi eklendi olarak görünüyor AMA dosyaya herhangi bir veri yazılmıyor. Bunu nasıl çözebilirim bilen var mı ve biraz aciliyeti var.

#

I'm trying to add information to a txt file with a python function via vscode. There are no errors in the codes. Information appears as added BUT no data is written to the file. Does anyone know how I can solve this and it's a bit urgent.

silver drift
naive oak
#

i think they're assuming that all the processing you'll be doing with the path will be done in between calls

haughty mountain
#

right

#

if you actually need to store them you can make a copy

rich oasis
#

from re import search
import os
from datetime import datetime,timedelta
from os import system

#-------------------------------------------------------------------------------------------------------------------
#Bu fonksiyon txt dosyasına demirbaş kaydı eklemek içindir.
def demirbas_kayıt_ekle():
demirbas_kayıt = open("C:\Users\pc\projemk\demirbas_kaydı.txt","w")
secim = 'y'
sayac = 1
while secim == 'y' or secim == 'Y':
print(f"---{sayac}. Demirbaşın Bilgileri---")
isim = input("Demirbaşa bir ad giriniz : ")
barkod_türü = input('''
(Bu program sadece 1D barkodlar için geçerlidir.)
1-EAN-8
2-EAN-13
3-UPC-A
4-UPC-E
5-COD 39
Demirbaşın barkod çeşidini seçiniz : ''')
if barkod_türü == "1":
barkod_no = input('''
(8 HANELİ) (SADECE RAKAM)
seçilen barkod türü: EAN-8
Barkod no giriniz : ''')

    if len(barkod_no) == 8 and barkod_no.isdigit :
        print("")
    else : 
        input('''
              Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
              (8 HANELİ) (SADECE RAKAM)
              seçilen barkod türü: EAN-8
              Barkod no giriniz : 
              ''')
#

elif barkod_türü == "2":
barkod_no = input('''
(13 HANELİ) (SADECE RAKAM)
seçilen barkod türü: EAN-13
Barkod no giriniz : ''')
if len(barkod_no) == 13 and barkod_no.isdigit :
print("")
else :
input('''
Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
(13 HANELİ) (SADECE RAKAM)
seçilen barkod türü: EAN-13
Barkod no giriniz :
''')
elif barkod_türü == "3":
barkod_no = input('''
(12 HANELİ) (SADECE RAKAM)
seçilen barkod türü: UPC-A
Barkod no giriniz : ''')
if len(barkod_no) == 12 and barkod_no.isdigit :
print("")
else :
input('''
Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
(12 HANELİ) (SADECE RAKAM)
seçilen barkod türü: UPC-A
Barkod no giriniz :
''')
elif barkod_türü == "4":
barkod_no = input('''
(6 HANELİ) (SADECE RAKAM)
seçilen barkod türü: UPC-E
Barkod no giriniz : ''')
if len(barkod_no) == 6 and barkod_no.isdigit :
print("")
else :
input('''
Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
(6 HANELİ) (SADECE RAKAM)
seçilen barkod türü: UPC-E
Barkod no giriniz :

#

elif barkod_türü == "5":
if barkod_no < 43 and barkod_no.isdigit and barkod_no.isalpha :
barkod_no = input('''
(max 43 HANELİ) (RAKAM VE HARF)
seçilen barkod türü: COD 39
Barkod no giriniz : ''')
else :
input('''
Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
(max 43 HANELİ) (RAKAM VE HARF)
seçilen barkod türü: COD 39
Barkod no giriniz :
''')
else:
secim2 = input('''
Seçiminiz hatalı, lütfen tekrar deneyiniz..
Demirbaşın barkod çeşidini seçiniz : ''')

seri_no = input('''  
         (12 HANELİ) 
          Demirbaşın seri numarasını giriniz :  ''')
if len(seri_no) == 12 :
        print("")
else : 
        input('''
            Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
            (12 HANELİ) 
            Demirbaşın seri numarasını giriniz : 
              ''')
alınan_firma = input("Demirbaşın Alındığı Firma ismini giriniz :  ")
fatura_no = input('''
            (16 haneli) (SADECE RAKAM VE HARF)
            Demirbaş fatura numarasını giriniz :  ''')
if len(fatura_no) == 16 and fatura_no.isdigit and fatura_no.isalpha :
        print("")
else : 
        input('''
              Hatalı giriş yaptınız,lütfen tekrar deneyiniz..
              (16 HANELİ) (SADECE RAKAM VE HARF)
              Demirbaş fatura numarasını giriniz : 
              ''')
#

gun = input("(2 haneli) Gün bilgisi girin: ")
n1 = "."
ay = input("(2 haneli) Ay bilgisi girin: ")
n2 = "."
yil = input("(4 haneli) Yıl bilgisi girin: ")

while True:
    if int(gun) > 0 and int(gun) < 32 and len(gun) == 2:
        break
    else:
       print("Gün bilgisi girerken bir hata oluştu. Lütfen tekrar deneyin.")
       gun = input("(2 haneli) Gün bilgisi girin: ")

while True: 
    if int(ay) > 0 and int(ay) < 13 and len(ay) == 2:
      break
    else:
        print("Ay bilgisi girerken bir hata oluştu. Lütfen tekrar deneyin.")
        ay = input("(2 haneli) Ay bilgisi girin: ")

while True:
    if int(yil) > 0 and int(yil) < 2024 and len(yil) == 4:
       break
    else:
        print("Yıl bilgisi girerken bir hata oluştu. Lütfen tekrar deneyin.")
        yil = input("(4 haneli) Yıl bilgisi girin: ")

tarih = print("Girilen tarih: " + gun + n1 + ay + n2 + yil)
#

para_birimleri = {
"1": "TRY",
"2": "EUR",
"3": "USD",
"4": "JPY",
"5": "GBP",
"6": "CNY",
"7": "AUD",
"8": "CAD",
"9": "CHF",
"10": "HKD",
"11": "SGD",
"12": "SEK",
"13": "KRW",
"14": "NOK",
"15": "NZD",
"16": "INR",
"17": "MXN",
"18": "TWD",
"19": "ZAR",
"20": "BRL",
"21": "DKK",
"22": "PLN",
"23": "THB",
"24": "ILS",
"25": "IDR",
"26": "CZK",
"27": "AED",
"28": "HUF",
"29": "CLP",
"30": "SAR",
"31": "PHP",
"32": "MYR",
"33": "COP",
"34": "RUB",
"35": "RON"
}

while True:
    fiyat = input("Fiyat bilgisi girin: ")
    para_birimi_secim = input('''Para birimini girin:
1-TRY  2-EUR  3-USD  4-JPY  5-GBP
6-CNY  7-AUD  8-CAD  9-CHF  10-HKD
11-SGD 12-SEK 13-KRW 14-NOK 15-NZD
16-INR 17-MXN 18-TWD 19-ZAR 20-BRL
21-DKK 22-PLN 23-THB 24-ILS 25-IDR
26-CZK 27-AED 28-HUF 29-CLP 30-SAR
31-PHP 32-MYR 33-COP 34-RUB 35-RON
''')

    if para_birimi_secim in para_birimleri:
        para_birimi = para_birimleri[para_birimi_secim]
        if fiyat.isnumeric() and len(fiyat) > 0:
            fiyat = int(fiyat)
            print("Girilen fiyat: " + str(fiyat) + " " + para_birimi)
            break
        else:
            print("Hatalı giriş! Fiyat bilgisi sadece sayılardan oluşmalıdır.")
    else:
        print("Hatalı giriş! Geçerli bir para birimi seçiniz.")

   
marka = input("Demirbaşın marka bilgisini giriniz :  ")
model = input("Demirbaşın modelini giriniz :  ")
kategoriler = [
"1",
"2",
"3",
"4",
"5",
"6",
"7",
"8",
"9",
"10"
]
#

while True:
secilen_kategori = input('''
1-giyim
2-aksesuar
3-elektronik
4-kozmetik
5-kitap&kırtasiye
6-ev&mobilya
7-ayakkabı&çanta
8-oto&yapı
9-gıda
Ürün kategorisi seçin veya boş bırakın: ''')
if secilen_kategori in kategoriler:
if secilen_kategori == "1":
print("Seçilen kategori: " + secilen_kategori + " giyim")
elif secilen_kategori == "2":
print("Seçilen kategori: " + secilen_kategori + " aksesuar")
elif secilen_kategori == "3":
print("Seçilen kategori: " + secilen_kategori + " elektronik")
elif secilen_kategori == "4":
print("Seçilen kategori: " + secilen_kategori + " kozmetik")
elif secilen_kategori == "5":
print("Seçilen kategori: " + secilen_kategori + " kitap&kırtasiye")
elif secilen_kategori == "6":
print("Seçilen kategori: " + secilen_kategori + " ev&mobilya")
elif secilen_kategori == "7":
print("Seçilen kategori: " + secilen_kategori + " ayakkabı&çanta")
elif secilen_kategori == "8":
print("Seçilen kategori: " + secilen_kategori + " oto&yapı")
elif secilen_kategori == "9":
print("Seçilen kategori: " + secilen_kategori + " gıda")
break
elif secilen_kategori == "":
yeni_kategori = input("Eklemek istediğiniz kategoriyi yazınız: ")
print("Kategori alındı: " + yeni_kategori)
break

#

while True:
alici_ad = input("Adınızı girin: ")
if alici_ad.isalpha():
print("Girilen ad: " + alici_ad)
break
else:
print("Hatalı giriş! Ad sadece harflerden oluşmalıdır.")

while True:
  alici_soyad = input("Soy Adınızı girin: ")
  if alici_soyad.isalpha():
      print("Girilen soyad: " + alici_soyad)
      break
  else:
      print("Hatalı giriş! Soyad sadece harflerden oluşmalıdır.")
      
while True:    
  alici_tc = input("Zimmetçi TC numarasını giriniz : ")
  if len(alici_tc) == 11 and alici_tc.isdigit : 
      print("Girilen TC kimlik numarası: " + alici_tc)
      break
  else : 
      print("Hatalı giriş! TC kimlik numarası 11 haneli olmalı ve sadece rakamlardan oluşmalıdır.")
while True:    
  alici_tel = input("Zimmetçiye ait telefon numarası giriniz :  ")
  if len(alici_tel) == 11 and alici_tel.isdigit : 
      print("Girilen telefon numarası: " + alici_tel)
      break
  else : 
      print("Hatalı giriş! Telefon numarası 11 haneli olmalı ve sadece rakamlardan oluşmalıdır.")
  
  alici_mail = input("Zimmetçiye ait mail hesabı giriniz : ")
  
  departman_isimleri = {
     "1": "ÜRETİM DEPARTMANI",
     "2": "PAZARLAMA DEPARTMANI",
     "3": "PAZARLAMA DEPARTMANI",
     "4": "FİNANS DEPARTMANI",
     "5": "MUHASEBE DEPARTMANI",
     "6": "İNSAN KAYNAKLARI DEPARTMANI",
     "7": "AR-GE DEPARTMANI",
     "8": "HALKLA İLİŞKİLER DEPARTMANI",
     "9": "HUKUK  DEPARTMANI"
  }
#

while True :
alici_departman = input('''
"1": "ÜRETİM DEPARTMANI",
"2": "PAZARLAMA DEPARTMANI",
"3": "PAZARLAMA DEPARTMANI",
"4": "FİNANS DEPARTMANI",
"5": "MUHASEBE DEPARTMANI",
"6": "İNSAN KAYNAKLARI DEPARTMANI",
"7": "AR-GE DEPARTMANI",
"8": "HALKLA İLİŞKİLER DEPARTMANI",
"9": "HUKUK DEPARTMANI"

      Zimmetçi departman bilgisini giriniz : ''')
    if alici_departman in departman_isimleri:
          departman = departman_isimleri[alici_departman]
          print("Seçilen Departman : " + departman )
          break
    else:
          print("Hatalı giriş! Geçerli bir departman birimi seçiniz.")
   
   
    demirbas_kayıt.write("\n"+isim+"\n")
    demirbas_kayıt.write(barkod_türü+"\n")
    demirbas_kayıt.write(barkod_no+"\n")
    demirbas_kayıt.write(seri_no+"\n")
    demirbas_kayıt.write(alınan_firma+"\n")
    demirbas_kayıt.write(fatura_no+"\n")
    demirbas_kayıt.write(tarih+"\n")
    demirbas_kayıt.write(fiyat+"\n")
    demirbas_kayıt.write(marka+"\n")
    demirbas_kayıt.write(model+"\n")
    demirbas_kayıt.write(secilen_kategori+"\n")
    demirbas_kayıt.write(yeni_kategori+"\n")
    demirbas_kayıt.write(alici_ad+"\n")
    demirbas_kayıt.write(alici_soyad+"\n")
    demirbas_kayıt.write(alici_tc+"\n")
    demirbas_kayıt.write(alici_tel+"\n")
    demirbas_kayıt.write(alici_mail+"\n")
    demirbas_kayıt.write(departman+"\n")
print("YENİ BİR KAYIT EKLEMEK İSTER MİSİNİZ?")
secim = input("Y=yes, N=no: ") 
sayac = sayac + 1

demirbas_kayıt.close()
print("----------Kayıtlar demirbas_kayıt_ekle.txt ye eklenmiştir-----------")

demirbas_kayıt_ekle()

dull hawk
#

I try to create a tool for a game based on card, and I'm totally lost on where to start for the algorithm.

I will try to describe it if you have some ideas to give me.
It's simple but a bit hard for me to put an algo on that.

In a game where a card can be played at different position.
You have a roster of cards.

A card has a rating for every position possible.
Every card has different variants, each of this variants has 3 levels ( based on what others cards you choose and if the card can be played naturally at this position), and each of these variants have their own rating.

I want a tool where I can find, based on your roster, what is the best deck you can play ( the deck with the hightest sum of ratings )
The difficulty are the variants of these cards that depend on what others cards you currently have choose ...

Is it possible to find an algo for this kind of stuff, or should i just simulate every combination possible ?

spring summit
# dull hawk I try to create a tool for a game based on card, and I'm totally lost on where t...

I get from your vague description that there are a lot of possibilities. If you can run a full simulation of all possibilities, great! I would probably try to not find the best solution but just a pretty good one. Just try out some search algorithms. Maybe use a threshold for when to stop looking for a new solution.
Im not sure if a card in your deck can have multiple values simultaniously and it will be set once you play it or how the dynamics change with that, so i cant give u more details. If you are lacking creativity just ask chatgpt or any llm, they can usually give you some inspiration.

dull hawk
# spring summit I get from your vague description that there are a lot of possibilities. If you ...

no, the value of a card remains the same. To resume, each card can have multiple value A-B-C-D etc .. ( only one ) but certain value can only happen if a certain condition is real.

So imagine these cards as example (it's simplified)

Card name : Tank
Card value Position Top_level_1 : 3
Card value Position Top_level_2 : 6
Card Value Position Bot_level_1 : 6
Card Value Position Bot_level_2 : 12
Card color : Red
Card team : Allies

Card name : Boat
Card value Position Top_level_1 : 10
Card value Position Top_level_2 : 12
Card Value Position Bot_level_1 : 5
Card Value Position Bot_level_2 : 7
Card color : Blue
Card team : Allies

Top_level_2 is Right if your deck contains multiple card color Red
Bot_level_2 is Right if your deck contains multiple card team Allies

The aim of the tool is to find the best deck so the one with the max sum possible of the value " top level" " bot level" etc

As I imagine, the way to simulate all of this is with a lot of for loop, sum variable to compare the value everytime, when a value is better put the deck combination as the "best one". And in the loop, in this example, i have to set variable inside the function to count and increment the number of "card color" / "card team".

hushed spear
#

https://pastebin.com/hBFsu7iB (Kargers min cut)

why does this algorithm use the deepcopy function? I understand the contract function, the file read, but I don't understand the min_cut function itself.

hybrid epoch
haughty mountain
fervent saddle
#

How to become better at visualizing the data in your head?
Sometimes I can quickly think of a solution to an algorithm, but then it's very hard to write the code for it because I have a hard time keeping a mental image of what the data is doing and how the code is interacting with it.
https://leetcode.com/problems/insert-delete-getrandom-o1-duplicates-allowed/
I thought of the solution to this in 1-2 minutes (you use Dict[int, Set[int]], and List[int] for random access). But then when I tried to actually code it, I ended up fumbling around for like an HOUR, with long periods of just staring at the screen and trying to reorient myself. Is this normal? Will this problem eventually go away?

LeetCode

Can you solve this real interview question? Insert Delete GetRandom O(1) - Duplicates allowed - RandomizedCollection is a data structure that contains a collection of numbers, possibly duplicates (i.e., a multiset). It should support inserting and removing specific elements and also reporting a random element.

Implement the RandomizedCollection...

austere sparrow
fervent saddle
#

You swap the value at the end with the value you're removing

austere sparrow
#

ah

#

yeah, since you don't need to preserve order

#

actually you could have a dict[int, int]

#

each set will have at most 1 element

fervent saddle
#

Are you sure you aren't looking at the previous exercise where there can't be duplicate values?

austere sparrow
#

well, what elements do you store in the sets?

#

in your dict[int, set[int]]

fervent saddle
#

The set represents the indexes that the specific value exists at

austere sparrow
#

ah

#

yeah that makes sense then

fervent saddle
#

Dict[int, int] worked for the previous problem, which didn't allow duplicates.

#

And that one wasn't very hard. But this follow up was really challenging even though the idea behind the solution wasn't that hard to think of.

#

This is similar to an O(1) snake game pygame program I made, which had a similar idea: swapping values around so you can maintain a contiguous collection of values for random access (for food placement). And the same thing happened, it was insanely hard to visualize things even though I knew what to do. I ended up needing to write it out in words, step by step, before writing the code.

haughty mountain
#

sometimes just sketching out the high level flow can help you keep your bearings

#

like, basically pseudocode, or actual code calling some methods you would have to implement

#

I think you don't even need a set in a dict, a list in a dict should be enough

#

or maybe set makes the remove easier pithink

fervent saddle
#

You're right, maybe it could be done with lists. I'd have to check again. Because I think you just need any index of the value you're removing, it doesn't matter where. So you could take it from the end of the list.

haughty mountain
#

updating the index after the swap is the hairy part

#

though maybe you don't even need a swap, maybe you can just leave that entry in the list empty, maybe use a free list

#

though that probably messes with the get random op

#

I think your way makes a lot of sense, I mostly wanted to see if there were any tweaks that can be made 😅

fervent saddle
#

okay, I looked at the solution, and it needs set for that reason. Looks like you can't set it up in a way that allows for O(1) removes

#

But it is a set of contiguous values from 0 to size, though. So maybe there's something else that could be done.

#

It just seems like that points to a way which doesn't involve sets, maybe. A way which just involves a normal array and index mapping.

haughty mountain
#

I'm guessing what you did is basically this

from collections import defaultdict
import random

class RandomizedCollection:
    def __init__(self):
        self.indices = defaultdict(set)
        self.values = []

    def insert(self, val: int) -> bool:
        lst = self.indices[val]
        lst.add(len(self.values))
        self.values.append(val)
        return len(lst) == 1

    def remove(self, val: int) -> bool:
        lst = self.indices[val]
        if not lst: return False

        index = lst.pop()
        end_index = len(self.values) - 1
        end_value = self.values.pop()

        if index != end_index:
            self.values[index] = end_value
            self.indices[end_value].remove(end_index)
            self.indices[end_value].add(index)
        
        return True

    def getRandom(self) -> int:
        return random.choice(self.values)
#

ngl, it was a bit fiddly to get the swap logic figured out

#

I guess that's the part that also tripped you up

fervent saddle
#

Yeah that's what I did

fervent saddle
#

It's like juggling

haughty mountain
#

but at some points it falls into place and the end result is actually quite nice

#

like, the actual swap logic is kinda separated out

digital stirrup
#

Hi guys, I am trying to make a program that tries to add hex colors together in order to reach a target.
Some requirements: all weights must be natural numbers, and their sum must be equal or lower than 8.
So far I have this python prototype, but it doesn't seem to be working as expected.

Here are some helper functions

color_names = {
    0x993333: "Red",
    0xD87F33: "Orange",
    0xE5E533: "Yellow",
    0x7FCC19: "Green",
    0x667F33: "Dark Green",
    0x6699D8: "Light Blue",
    0x4C7F99: "Cyan",
    0x334CB2: "Dark Blue",
    0xF27FA5: "Pink",
    0x7F3FB2: "Purple",
    0xB24CD8: "Magenta",
    0x664C33: "Brown",
    0xFFFFFF: "White",
    0x999999: "Light Gray",
    0x4C4C4C: "Dark Gray",
    0x191919: "Black",
    #0x: "",
}

def hex2rgb(x):
    """Converts a hex color code to RGB"""
    return ((x >> 16) & 0xFF, (x >> 8) & 0xFF, x & 0xFF)

def rgb2hex(x):
    """Converts an RGB color to hex"""
    return (x[0] << 16) + (x[1] << 8) + x[2]

colors = np.array(list(color_names.keys()), dtype=np.int32)
colors = np.array(list(map(hex2rgb, colors)), dtype=np.float32)
# Reshape to 3xN
colors = colors.T
print("Colors:\n", colors)

def color_distance(c1, c2):
    c1 = np.array(hex2rgb(c1))
    c2 = np.array(hex2rgb(c2))
    return np.linalg.norm(c1 - c2)

def mix_colors(x, w):
    """Returns the color obtained by mixing the initial colors with the given weights"""
    x = np.array(hex2rgb(x))
    res = (x + np.dot(colors, w)) / (np.sum(w) + 1)
    res = np.floor(res)
    res = np.clip(res, 0, 255)
    res = np.array(res, dtype=np.int32)
    return rgb2hex(res)
#

here is the rest, aka the logic for computing weights. I thought about using the pseudo inverse and dropping colors until all the weights are positive, then using ceil on them to get non zero values as such:

def find_weights(x, t):
    # x is the initial color, t is the target color
    x = np.array(hex2rgb(x))
    t = np.array(hex2rgb(t))
    # T is a matrix of the target color repeated 16 times
    # We know that T*w + t = x + C*w
    # So we can solve for w
    # T*w - C*w = x - t
    # (T - C)*w = x - t
    # w = (T - C)^-1 * (x - t)
    w = None
    excolor = colors
    mapping = np.arange(16)
    while w is None:
        T = np.tile(t, (excolor.shape[1], 1)).T
        w = np.linalg.pinv(T - excolor) @ (x - t)
        if np.any(w < 0):
            # Remove the color with the lowest weight
            #mapping = np.delete(mapping, np.argmin(w))
            #excolor = np.delete(excolor, np.argmin(w), axis=1)
            #w = None
            w = np.clip(w, 0, np.inf)
    wres = np.zeros(16, dtype=np.float32)
    wres[mapping] = w
    wres = np.ceil(wres)
    return wres
#

Here is an example

color = 0xffffff
target = 0x993333
weights = np.array([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0])
weights = np.reshape(weights, (-1,))
print("Initial color: " + hex(color))
# print("Weights:\n", weights)
# print("Mixed color: " + hex(mix_colors(color, weights)))
seen = set()
dist = {}
while color not in seen:
    seen.add(color)
    distance = color_distance(color, target)
    dist[color] = distance
    weights = find_weights(color, target)
    print("Weights:\n", weights)
    color = mix_colors(color, weights)
    print("Mixed color: " + hex(color))

min_dist = np.inf
min_color = None
for c in dist:
    if dist[c] < min_dist:
        min_dist = dist[c]
        min_color = c
print("Closest color: " + hex(min_color))
print("Distance: " + str(min_dist))

With the output:

Colors:
[[153. 216. 229. 127. 102. 102. 76. 51. 242. 127. 178. 102. 255. 153.
76. 25.]
[ 51. 127. 229. 204. 127. 153. 127. 76. 127. 63. 76. 76. 255. 153.
76. 25.]
[ 51. 51. 51. 25. 51. 216. 153. 178. 165. 178. 216. 51. 255. 153.
76. 25.]]
Initial color: 0xffffff
Weights:
[0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 0. 1. 0. 0. 1. 1.]
Mixed color: 0x726c65
Weights:
[0. 1. 0. 0. 0. 0. 0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]
...
Closest color: 0x584a57
Distance: 77.78174593052023

#

which is still pretty far from the red color intended

#

does anyone know how I could improve the precision?

indigo pike
#

How

vocal gorge
#

That also needs the problem to be linear, but, hmm, I think yours can be represented as one.

haughty mountain
#

itertools.combinations_with_replacement(range(16), 8))
only has 490314 elements

#

so you could use combinations_with_replacement to get all the picks of 1, 2, 3, ..., 8 colors, compute the mixed color, and pick the closest one

#

so rough sketch

import itertools

colors = [...]
target_color = ...

cloest_color = None
min_distance = 10**10

for n in range(1, 9):
    for picks in itertools.combinations_with_replacement(colors, n):
        mixed = mix_colors(picks)
        distance = color_distance(mixed, target_color)
        if distance < min_distance:
            min_distance = distance
            closest_color = mixed
lilac cradle
outer tapir
#

I have an array say a[[1,2],[],[3],[4]]
I want to have all combinations like
[[1],[2],[1,3],[2,3],[2,4],[2,3,4],[1,3,4],[1,4],[3],[3,4],[4]]
I know there is a backtracking solution to this, but I want to know if there is optimised solution other backtracking
It is guaranteed that array contains only 4 nested arrays

sonic blade
#

anybody have info about stata 16?

dense flame
#

Please can someone help with this book? Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.

dense flame
agile sundial
#

come on man

obsidian field
summer fossil
snow anvil
haughty mountain
#

||it's not like it's hard to find a digital version||

fiery cosmos
#

||Lol, I know what you mean. Uni Students unite||

weary raptor
#

am I stupid or what

#

I just started with python

#

it just returns nothing

summer fossil
gritty otter
weary raptor
#

yea it's giving errors

#

how do I define an Int

gritty otter
#

You have to use int(input("waiting: "))

weary raptor
#

ok it works

#

thanks

#

I literally took python up 3 days ago

#

too used to C

gritty otter
#

How long have you been doing it per day

weary raptor
#

not much

#

like 1 hour

gritty otter
weary raptor
#

in C you just define variables at the beginning

#

with like Int variablename = something

gritty otter
#

Ohh

#

You can do that with python too

placid shuttle
#

how much bits get allocated for int? I've tried using sys.getsizeof() but it apparently shows bytes including entire int class.

I want to know how much bits gets allocated only for number

For example print(bin(6)) returns 0b110. Does that mean that for 6 it is only 110, or is it 00000110? Or maybe even 00000000 00000000 00000000 00000110 because it is 32bit?

#

I'm learning bit shifting and I want to know how much can I shift before I push the number 'of the edge'.

vocal gorge
#

sys.getsizeof(0) is 24 bytes - that's just the object header, the size of the array is 0 here.
sys.getsizeof(1) is 28, and so is sys.getsizeof(2**30-1) - that's using a single "digit".
sys.getsizeof(2**30) is 32 - the second digit is added. And so on.

#

I'm learning bit shifting and I want to know how much can I shift before I push the number 'of the edge'.
You can't, the int will just grow forever to accomodate the bitshift.

placid shuttle
vocal gorge
#

That's true, sure.

placid shuttle
vocal gorge
#

you might also be interested in int.bit_length, by the way. E.g. (6<<2).bit_length() is 5.

#

the number of 4-byte "digits" necessary to store x is ceil(x.bit_length()/30)

placid shuttle
#

Thank you, it is much clearer now

stray fractal
cyan snow
#
print("Just testing whether it will be printed in a box. Joined discord recently so I'm not much familiar with typing tricks.")
stray cliff
fervent saddle
#

https://leetcode.com/problems/basic-calculator/
Can this be O(n) with O(1) space?

LeetCode

Can you solve this real interview question? Basic Calculator - Given a string s representing a valid expression, implement a basic calculator to evaluate it, and return the result of the evaluation.

Note: You are not allowed to use any built-in function which evaluates strings as mathematical expressions, such as eval().

Example 1:

Input:...

stray cliff
#

I don't think it's possible to do in O(1) space, since you need to maintain a parse tree in some way, and the nesting could be arbitrarily deep

#

oh wait

#

yeah I think you can be clever and only track a sign bit...

fervent saddle
#

So if you see (3 + 2 - 1), you just ignore the parens and treat it like -3 + -2 - -1? If the sign bit is negative?

stray cliff
#

yeah although thinking about it more, I think nesting will catch you out

#

when you get to a closing bracket, that could change the "signedness state", or it could not - you need a stack to keep track of it, I think

#

consider (-(-(-(5)) + 2) + 3)

fervent saddle
#

Yeah, you need to know whether or not you're coming out of a negative expression

haughty mountain
#

a typical way of parsing this kind of expression is called the shunting yard algorithm

austere sparrow
#

so maybe

#

though I am doubtful

haughty mountain
#

oh, it's only plus and minus

austere sparrow
#

Parens tho

haughty mountain
#

so in +(...) parens can just be ignored, you're right -(...) is the one interesting thing

fervent saddle
#

It looks like in C++, the string isn't const, so you can write to it. I wonder if that would make a difference.

stray cliff
#

you need at most n bits of "sign stack", plus a stack pointer variable, so you put the base of the bit-stack at the start of the string and it will never overlap the bytes you're reading

#

but I'd say that's cheating and still counts as O(n) storage

haughty mountain
#

and yeah I wouldn't really count that as ok

fervent saddle
naive oak
#

any ideas on how to optimize this? I'm doing https://codeforces.com/problemset/problem/1840/F

for _ in range(int(input())):
    n, m = map(int, input().split())
    data = {tuple(map(int, input().split())) for _ in range(int(input()))}
    c_min = float('inf')
    end = n + 1j * m
    visited = set()

    call_stack = [(0, 0)]
    while call_stack:
        current, time = call_stack.pop()
        z = end - current
        if time + abs(z.real) + abs(z.imag) >= c_min
            continue
        elif current.real > n or current.imag > m:
            continue
        elif {(time, 1, current.real), (time, 2, current.imag)} & data:
            continue
        elif current == end:
            c_min = time
            continue

        new_time = time + 1
        candidates = [(current, new_time), (current + 1j, new_time), (current + 1, new_time)]
        candidates = [state for state in candidates if state not in visited]
        call_stack.extend(candidates)
        visited |= {*candidates}

    if c_min == float('inf'):
        print(-1)
    else:
        print(c_min)
naive oak
#

you probably want floor div

#

// not /

fiery cosmos
#

Hi I have a problem@naive oak

naive oak
#

just ask it and someone else might help you

#

im going to bed

fiery cosmos
fiery cosmos
snow anvil
fiery cosmos
snow anvil
fiery cosmos
#

But the server name is python

#

Every channel is for python

#

@snow anvil

snow anvil
vestal badge
#

I was wondering what is y'alls perfered method of dealing with collisions regarding hashmaps

static nymph
#

hello

#

im trying to figure out how to write the code for this sequence in the format 2p3q

#

i came up with this:

#

so basically ig the left power starts at i and the line stops when the right power becomes i and i increases top to bottom

stray cliff
#

seems like it should be doable with a simple nested loop?

static nymph
#

yeah but im not sure how to proceed

#

like one would be increasing from 0 increments of one thats the highest degree for the line lets say n

#

and for each line it starts at p = n q = 0 and then n-- until 0 and q++ until n

#

and store in sequence?

snow anvil
#

this is a tree so I using oop to make a tree is what I would to

static nymph
#

is it a tree tho

#

it's just a sequence right

snow anvil
#

oop is not nessecary here since it is a rather simple proble but I think you could still use it if u wanted

#

I think I slightly misunderstood you problem anyways have other shit frying brain rn

neat rover
#

Can an algorithm be dynamic and have the time complexity of O(1) at the same time? Could I make a dictionary and just access the element I need? I'm very confused on how to make it dynamic without it being at least O(n)

sinful arch
#

Hello, Im seeking help in developing a small function to calculate the price of a household's water tariff. The complexity of the problem stems from the trench structure of the tarffi, where m3 of waters are charged at different rates depending on the total amount consumed. I've been experimenting on my own and with chat GPT, unsuccesfully so I was wondering if someone could lend me a hand. Im starting the code in this manner: def calculate_water_tariff(consumed_water):
trench_rates = [0.6180, 1.2361, 1.8541, 2.4719, 3.0899]
trench_limits = [6, 9, 15, 18, float('inf')]

haughty mountain
#

it would be very weird, what's even connected to what?

#

!e ignoring formatting things nicely

p = 2
q = 3
for n in range(1, 6):
  print([p**(n-i)*q**i for i in range(n)])
vocal gorge
#

uhh

haughty mountain
#

wait, how tf did I get fractional stuff?

vocal gorge
#

it should be i-n and n

#

because n is the index that changes along a row for you.

#

and i>=n always

haughty mountain
#

!e

p = 2
q = 3
for n in range(5):
  print([p**(n-i)*q**i for i in range(n+1)])
halcyon plankBOT
#

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

001 | [1]
002 | [2, 3]
003 | [4, 6, 9]
004 | [8, 12, 18, 27]
005 | [16, 24, 36, 54, 81]
haughty mountain
#

welp, finally

haughty mountain
snow anvil
#

On a sidenote I do not comprehend avl tree rotations rn 😦 may or may not be related to the reason I was sleep deprived

ocean yoke
#

!code

halcyon plankBOT
#
Formatting code on discord

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.

For long code samples, you can use our pastebin.

naive oak
haughty mountain
#

well, I had a friend who liked talking ds&a a lot, so I got some mental exercise/fatigue that way

#

what contest are we talking?

naive oak
#

it's just a uni competition

#

might win a scholarship if I do well

#

so

snow anvil
#

Good luck

haughty mountain
#

idk how much you can do in 1 day

#

unless you want to gamble on 1 or 2 data structures or algos that might show up

#

maybe just practicing some problems in general might help, you could do a virtual div3 or div2 contest on codeforces

#

I can't remember how used to things you are. div3 should be quite easy problems up until the last few

#

div2 starts with some easier problem and after that starts getting fairly challenging

#

@naive oak

naive oak
#

I have like no experience outside of aoc

uncut field
#

i made a "toggle" data type. anyone have ideas on what to add to it?

class Toggle:
    def __init__(self, num: int, values = [0, 1]):
        self.num = num
        self.values = values
        checkInputs(self.num, self.values)
        
    def __str__(self):
        return str(self.num)
    
    def set(self, value: int):
        checkInputs(self.num, self.values)
        self.num = value


    def toggle(self):
        if self.num == self.values[0]:
            self.num = self.values[1]
        elif self.num == self.values[1]:
            self.num = self.values[0]
austere sparrow
snow anvil
#

Yeah I suspect I'll just have to keep looking at them until it clicks

haughty mountain
#

find some recent div3 contest, then there should be a link for a virtual contest

stray cliff
#

there's also no verification that values contains exactly two elements (and it should probably be a tuple)

#

toggle() will fail if values[0] compares equal to values[1]

#

it's possible to have two objects that are not strictly identical but still compare equal with ==

#

e.g. {"a": 0, "b": 1} == {"b": 1, "a": 0}

neat rover
# shut breach wdym by dynamic?

I assume that my teacher means this "Dynamic programming is defined as a computer programming technique where an algorithmic problem is first broken down into sub-problems, the results are saved, and then the sub-problems are optimized to find the overall solution — which usually has to do with finding the maximum and minimum range of the algorithmic query. "

lost relic
#

Where could I go to practice Python?

zealous monolith
lost relic
#

Awesome, thank you.

lime ether
#

leetcode also

robust dagger
# neat rover I assume that my teacher means this "Dynamic programming is defined as a compute...

O(1) complexity would mean that, no matter how large the input is, the program always generates a constant number of subproblems. For example, perhaps it generates five subproblems when the input has length n = 100, and five subproblems when the input has length n = 10^6, and five subproblems when the input has length n = 10^100, and so on. It's possible to come up with problems where this is true. For example, suppose that you want to compute a function f which takes natural number-valued inputs. Maybe f satisfies some complicated recursive formula for n ≤ 5, but it happens that f(n) = f(5) whenever n ≥ 5. Then you only ever need to compute the first five values of f, so the complexity is O(1).

uncut field
#

It’s the function called checkInputs()

naive oak
#

I'm kinda mad at myself

#

didn't get tower of hanoi and levenshtein distance

#

because I spent too much time on a combinatorics question

stable linden
#

which site is better to learn python..geeksforG or codeAcademy

hazy iris
#

hello i started working on algorithms i had a question

class Node():
    def __init__(self,data,next=None):
        self.data = data
        self.next = next
class Stack():
    def __init__(self) -> None:
        self.root = None
        self.count = 0
    def push(self,data):
        node = Node(data)
        arr = []
        if not self.isempty():
            while not(self.isempty()) and (self.root.data < data):
                arr.append(self.root.data)
                self.pop(False)
            node.next = self.root
            self.root = node
            while arr != []:
                node = Node(arr.pop())
                node.next = self.root
                self.root = node
        else:
            node.next = self.root
            self.root = node
        print(f"{data} pushed to the stack")
        
        
        
        
        
    def pop(self,Flag = True):
        if self.isempty():
            if Flag:
                print("Stack is empty!")
            return
        print(f"{self.root.data} poped from the stack")
        temp = self.root.data
        self.root = self.root.next
        return temp
    def peek(self):
        if self.isempty():
            print("Stack is empty!")
            return
        return self.root.data
    def isempty(self):
        if self.root == None:
            return True
        else:
            return False
    def treverse(self):
        print("-------------------------------------------------")
        while self.root is not None:
            print(str(self.root.data)+ " --> ",end="")
            self.pop(False)
            
stack = Stack()
stack.push(10)
stack.push(30)
stack.push(20)
stack.push(5)
stack.push(1)
# stack.pop()
# stack.pop()
# stack.pop()
# stack.pop()
#print (f"{stack.pop()} popped from stack")
# print (f"Top element is {stack.pop()}")
stack.treverse()

Is this approach to monotinic stack correct does someone have an efficient implementation for the same?

feral forge
#

I do not have a CS/Maths background. When presented with some coding puzzles, some of my colleagues who do have CS/Maths backgrounds can easily recognise the type of puzzle and the kind of solution it might need.

For example, traversing a grid puzzle solved using combinatorics. Combinatorics is something they studied and could apply to the puzzle, whereas it is not something I was familiar with.

What I want to know is, if I study algos and data structs, will it cover everything like this? Or are there other maths-related topics that should be studied too?

Hope this makes sense

fossil elk
naive vale
#

hello

faint storm
#

If you want to just get good at solving these type of problems, start Leetcoding

#

I'd recommend a problem-first approach instead of diving into the deep theory.

Learn about how to calculate time and space complexity for a given code and just start solving problems

buoyant junco
#

for this problem right here,

Complete the solution so that the function will break up camel casing, using a space between words.

Example

"camelCasing"  =>  "camel Casing"
"identifier"   =>  "identifier"
""             =>  ""

I used the code,

def solution(s):
    a = ''
    b = list(s)
    i = 0
    while i <= len(s):
        if b[i].isupper():
            b.insert(i, " ")
            i += 2
        i += 1
        
    return a.join(b)

52 test cases passed but one kept failing

craggy grotto
#

ive got a ton of stuff due in under 3 hours and ive got 14 problems left

#

can someone tell me why its like screaming at me

buoyant junco
#

I'm not kidding, I didn't make any changes to the code and now as I run it, all test cases passed

summer fossil
summer fossil
craggy grotto
#

the codes supper finicky

#

i have to format it like that

#

its just screaming at me over that first line for some reason

#

i tried like 5 differnt things

snow anvil
buoyant junco
craggy grotto
#

yeah

buoyant junco
#

as in... it only works for a certain length or so?

craggy grotto
#

i have to write the exact things its expecting

snow anvil
#

Your code NEVER runs

craggy grotto
#

its weird idl

#

how do i fix the s3 thing

#

thats all i need to fix

snow anvil
#

Make it so your if statement does not exclude all options

craggy grotto
#

all i need to fix is the s3

#

the rest of it is right acording to this thing

#

what do i do bout the s3

buoyant junco
craggy grotto
#

pre determined

#

just help me fix s3 i dont have time

#

got like 2 hours

#

;d

snow anvil
#

S3 = ""

craggy grotto
#

yeah it doesnt like that for some reason

buoyant junco
#

return s3

#

with the same indentation as that of for

craggy grotto
#

it doesnt give me the output

snow anvil
#

Because your code never runs

#

Once again

craggy grotto
#

no its litterally just how dog shit this website is put together

#

its not a proper program

snow anvil
#

Len s1 and len s2 are assumed to be the same

craggy grotto
#

yeah

snow anvil
#

Your first if statement says:
Run this code if len s1, s2 are NOT the same

buoyant junco
#
s3  = ''

i = 0
if len(s1)>len(s2):
    for i in range(0, len(s1), 2):
        s3 += s1 + s2
    return s3

Try this one

craggy grotto
#

s1 and s2 are the same

#

it says in the prompt thing

snow anvil
#

So your code will never run

buoyant junco
#

can you share the problem?

craggy grotto
#

man i dont understand

buoyant junco
#

LOL I did this exact question yesterday

craggy grotto
snow anvil
#

Also why is your loop going in steps of 2

buoyant junco
#

This was mine

class Solution:
    def mergeAlternately(self, x: str, y: str) -> str:
        a = ''
        lxy = len(x)-len(y)
        lyx = len(y)-len(x)
        
        if len(x) > len(y):
            for i in range(len(y)-1):
                a += x[i]
                a += y[i]
            a += x[lxy-1::]
        
        elif len(x) == len(y):
            for i in range(len(y)-1):
                a += x[i]
                a += y[i]
                
        elif len(x) < len(y):
            for i in range(len(y)-1):
                a += x[i]
                a += y[i]
            a += y[lyx-1::]
            
        return a
snow anvil
#

This code is very questionable

craggy grotto
snow anvil
#

Initiating i = 0 for no reason

buoyant junco
#

i know it's stupendously long, but it works like a charm

summer fossil
#

lol use zip!

buoyant junco
#

Yup, usig zip is the best way

snow anvil
#

Why is there a ,2?

buoyant junco
#

but if you're unfamiliar with it, my method won't do any harm either

craggy grotto
snow anvil
#

I did not

snow anvil
#

Not his code

#

Yours

craggy grotto
#

bro im like delerious rn

#

sorry lmfao

snow anvil
#

Full of things that show you did not study

craggy grotto
#

no yeah not this portion

#

most of its just stuff i just power through

#

powered*

#

the things i know are very scattered

snow anvil
#

Delete the first if statement delete the 2 in the loop

craggy grotto
#

ok

#

i did that

snow anvil
#

Add return

craggy grotto
#

did that

#

im like uber sped atm so bare with me

snow anvil
#

Oh idk how that website works how are u supposed to do the output?

craggy grotto
#

iffk how it works either

snow anvil
craggy grotto
#

here a thing i did succesfully if that helps

buoyant junco
#

you can substitute x and y with s1 and s2 as well as a with s3

a = ''
lxy = len(x)-len(y)
lyx = len(y)-len(x)
        
if len(x) > len(y):
    for i in range(len(y)-1):
        a += x[i]
        a += y[i]
        a += x[lxy-1::]
        
elif len(x) == len(y):
    for i in range(len(y)-1):
        a += x[i]
        a += y[i]
                
elif len(x) < len(y):
    for i in range(len(y)-1):
        a += x[i]
        a += y[i]
    a += y[lyx-1::]
            
return a
snow anvil
craggy grotto
#

whar

buoyant junco
#

try this code, I'm unfamiliar with the variables given so.. you should substitute

snow anvil
#

No return needed just do what I said then also do
s3 += s1
s3 += s2

#

And it should work

craggy grotto
#

you need to use brakets somehow

#

its wanting me to use s3 += s1 + s2

buoyant junco
#

this is exactly what we're using

buoyant junco
#

you need to use it with different iterations though

snow anvil
#
s3 = ""
for i in range(0, len(s1)):
    s3 += s1[i]
    s3 += s2[i]
craggy grotto
buoyant junco
snow anvil
#

yes and your if statement made the entire code not run

buoyant junco
craggy grotto
#

cat you use a 3rd thing to make it skip numbers

snow anvil
craggy grotto
#

whats the issue herer

snow anvil
#

U put 51 instead of k rename k to x

#

K+1 actually

craggy grotto
#

this one*

snow anvil
#

What?

#

Just reverse the strings

#

s1[::-1]

#

And do the same thing as before

craggy grotto
#

i got someone to help me im all good

#

ill come back here just in case

#

sorry for being like stupid

#

im strait up halucinating due to sleep deprovation

buoyant junco
# craggy grotto i got someone to help me im all good

Just copy-paste this one

s3 = ''
lxy = len(s1)-len(s2)
lyx = len(s2)-len(s1)
        
if len(s1) > len(s2):
    for i in range(len(s2)):
        a += s1[i]
        a += s2[i]
        a += s1[-lxy::]
        
elif len(s1) == len(s2):
    for i in range(len(s2)):
        a += s1[i]
        a += s2[i]
                
elif len(s1) < len(s2):
    for i in range(len(s2)):
        a += s1[i]
        a += s2[i]
    a += s2[-lyx::]
            
print(s3)
craggy grotto
#

to complicated

#

it wont take it

snow anvil
summer fossil
buoyant junco
craggy grotto
#

i was in the rush and saw the first channel people were talking in

#

im not really thinking rationally

#

last week of 1st grade 🐱 🚬

summer fossil
craggy grotto
#

aue

snow anvil
#

He's at the reversed strings question now

buoyant junco
craggy grotto
#

;d

buoyant junco
#

Me personally, I'm getting 4 hours

summer fossil
snow anvil
#

Makes the code more readable

buoyant junco
#

I'm kind of a newbie myself actually

snow anvil
buoyant junco
#

for 3 different conditions

#

I assume my code is not as abstract as it should be

snow anvil
#

Make a function

def idk(s1, s2, len):
    a = ""
    for i in range(len):
        a += s1[i]
        a += s2[i]
    return a

and call thes function everytime you'd write the loop

#

So

s3 = ''
lxy = len(s1)-len(s2)
lyx = len(s2)-len(s1)
        
if len(s1) > len(s2):
    a = idk(s1, s2, len(s2))
    a += s1[-lxy::]
        
elif len(s1) == len(s2):
    a = idk(s1, s2, len(s2))
                
elif len(s1) < len(s2):
    a = idk(s1, s2, len(s1))
    a += s2[-lyx::]
            
#

I think it looks nicer

buoyant junco
snow anvil
#

The point is to not repeat yourself

buoyant junco
#

Yes, That's a really good point. However, in the code that you posted, there still are repititions, right?

snow anvil
#

Well it's less to write and easier to understand

buoyant junco
#

Although, I agree my lack of expertise makes the code less abstract

snow anvil
#

If you give idk a good name that is

buoyant junco
#

yeah haha, I was reading this bokk, "Cllean code" it says, always give your variables, functions etc a suitable name

summer fossil
buoyant junco
#

however, since I was using jupyter notebook, and it doesn't have the autocomplete feature, I opted for shorter variable and parameter names

snow anvil
buoyant junco
# snow anvil If you give idk a good name that is

Here's the code that I submitted to Leetcode

class Solution:
    def mergeAlternately(self, x: str, y: str) -> str:
        a = ''
        lxy = len(x)-len(y)
        lyx = len(y)-len(x)
        
        if len(x) > len(y):
            for i in range(len(y)):
                a += x[i]
                a += y[i]
            a += x[-lxy::]
        
        elif len(x) == len(y):
            for i in range(len(y)):
                a += x[i]
                a += y[i]
                
        elif len(x) < len(y):
            for i in range(len(x)):
                a += x[i]
                a += y[i]
            a += y[-lyx::]
            
        return a
summer fossil
snow anvil
#

???????

snow anvil
buoyant junco
snow anvil
#

Zip is very neat definitely use that anytime it's convenient

buoyant junco
tardy stone
#

be honest with me chat: will i ever need to know bubble sort. like i mean keyword for keyword or is knowing its terrible time complexity & conecpt good enough

fossil elk
fervent saddle
buoyant junco
zealous monolith
#

itertools

next loom
#

This is a dumb question but if I assign the same mutex lock and release to two threads and one seems to lock-release and immediately lock again before the other subscriber gets the chance to get the lock , what could be the problem?
For each call back function: ```python
def callback1(msg):
message = msg

with mutex:
do some process...

def callback2(msg):
message = msg

with mutex:
do some process```

could one callback process be so much faster than the other?

next loom
#

I'm pretty sure it's not some deadlock situation either
There is one shared variable, variable x =True is used in a if statement in callback2, variable x can be assigned as True in callback1 depending on an if statement in which a variable zonly found in callback1 is used.

haughty mountain
next loom
haughty mountain
next loom
#

don't subscribers inherently run in their own thread/

#

?

haughty mountain
#

threads in python isn't typically running in parallel

#

because of the global interpreter lock

#

basically what will end up happening is python going "hey you in this thread, you can execute for a bit of time" and when that time has expired it does the same with another thread

#

letting each thread run for some quantum of time

next loom
#

Is there a way to bypass this global interpreter lock or I'm just fucked?

haughty mountain
#

the time.sleep(0) might fix this situation since it basically says "I'm done for now" to the scheduler

next loom
#
def callback1(msg):
message = msg

  with mutex:
    do some process...
  time.sleep(0)
def callback2(msg):
message = msg

  with mutex:
      do some process
   time.sleep(0)
``` ?
haughty mountain
next loom
#

This seems like a pretty major drawback of using python

haughty mountain
#

I mean, it is

#

I'm not sure about your case though

#

what's calling these callbacks?

next loom
#

subscribers

#

not sure what you meant though, also, my placement of the time.sleeps makes sense?

haughty mountain
#

I think so

#

but it feels like a somewhat hacky way of doing things

gleaming flax
#

@rare willow

next loom
#

@haughty mountain yeah it does

#

Maybe there is another way to get what I want through anither algorithm design

haughty mountain
#

it's possible these things might end up cleaner with async, but I'm not sure

gleaming flax
#

@haughty mountain heyy

#

How do I get premission to talk??

haughty mountain
#

async has slightly different semantics

#

!voice

halcyon plankBOT
#
Voice verification

Can’t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.

haughty mountain
#

but also why are you in this channel? @gleaming flax

#

doesn't seem topical

next loom
#

I'm trying to sync color image and depth image data. So when objects are detected in the color image, the corresponding depth image is used to calculate object distance

haughty mountain
next loom
#

May there's a better way than using mutex, although it really doesn't make sense to me at this point why python would bother with mutes if there is a GIL thing programmers have to worry about

haughty mountain
#

could a switch happening inside this part of code break correctness? if so mutex protection of that code is warranted

haughty mountain
rough tartan
#

So no other language can do it? That's why I should pay attention to python

next loom
haughty mountain
#

threading is more of a forced concurrency, while async with coroutines is collaborative concurrency

#

the coroutines need to decide when they yield control so other coroutines can do work

#

if they never do that, no other coroutines will run

next loom
#

does c++ have the same problem?

#

with GIL?

haughty mountain
#

no

next loom
#

faak

#

I hate that I primarily program in python

hushed spear
#
def dfs(graph, s):
    # s is our starting vertex
    #list of visited vertexes
    visited = set()

    #start of the recursive call
    dfs_traversal(graph,s,visited)


def dfs_traversal(graph, s, visited):
    #add the current vertex to the visited list
    visited.add(s)

    #go thru every vertex
    for outgoing in graph:
        if outgoing not in visited:
            dfs_traversal(graph, outgoing, visited)

dfs(graph, 1)

print(graph)

is this a proper dfs traversal? i understand the pseudocode and the code aligns with the pseudocode, but it just seems way too simple.

snow anvil
#

Dfs is a very simple algorithm

fossil elk
naive oak
hazy garden
#

there is a mathematical question in my mind, lets say there 10, if you add it consecutively from 1 (1+2+3+...+10) then you get 55 and if you do that same using multiplication i.e. 10! you get 3628800, so lets say I have given a number call 57 in first case as question and asked to find n I will say 10 as 55 is closer to 57, in similarly in multiplication. My question is how to find relationship between the two 55 and 362880 using 10 as variable(n)/constant in this case using O(1) time complexity, because using loops its O(n). Is there some formula in maths like sum of consecutive nos. is n(n+1)/2. Input: a big number. Output: n.

naive oak
#

if you do then for the summation you can just find an inverse by solving the quadratic

hazy garden
hazy garden
#

functions have time complexity I want constant

naive oak
#

constant time is still time complexity

#

you'll get a formula with a sqrt in it

#

for an inverse factorial that might be more difficult

#

besides it's O(1) arithmetic operations

hazy garden
naive oak
#

it'll still scale in time

naive oak
hazy garden
#

if I provide 57 then 114 = n^2 + n and I have to ensure 57 %55 < num

#

num is 10

naive oak
#

you can just take the floor of n

#

for an inverse factorial id probably use stirling's approximation and newton's method to find it

hazy garden
hazy garden
hazy garden
hazy garden
naive oak
naive oak
#

usually most people are fine with just the least/most

hazy garden
naive oak
#

yeah

fiery cosmos
#

not sure if this is the right channel for this, but this error doesn't make sense to me because ÿ is an ascii character

#

i even copy/pasted it from hxd in the decoded code section

#

decoded text*

#

it's the decoded text for FF byte

outer rain
fiery cosmos
outer rain
# fiery cosmos ah what would be the proper channel for this kind of discussion, all the others ...

I mean, it's mostly just python, so.. #python-discussion I guess? Or help forum.

There is no "right ascii encoding", the byte you want to represent is simply unrepresentable in ascii, and therefore not allowed in byte string as a character. Use hex-escape: b"\xFF"`.

Or, put it into a normal string, and encode it with your encoding. Make sure that the file encoding matches to avoid editors messing up the file.

#

Actually, don't use the second option, it's terrible

fiery cosmos
#

also what i'm trying to accomplish is: I want to make python move to the point in the file right before the "FF" byte

I created an experimental file via hxd, and most of it is 0s except for one byte which is FF, i wanted to try to make python to move the "cursor" to the beginning of the FF byte

#

but idk how to do that

#

the reason why i want to make pthon move to that offset, is so i could then modify the bytes in that offset. So in this case, modify the FF byte after going to it's offset

fiery cosmos
red rock
#

i mean i know to read it

outer rain
fiery cosmos
#

sure i can work like that too

#

i just want to make python go to an offset in the file and modify byte values

#

ah wait ascii letters?
so there's no ascii letter for ÿ?

#

i mean ascii number

outer rain
#

(also make sure the file is opened in "rb" mode)

fiery cosmos
#

I tried doing that but with b"\0xFF" since FF byte is located in AA offset, but it says subsection not found

outer rain
#

I messed up

#

Also why AA? The \xFF is a byte, the 0xAA is what you want to get

fiery cosmos
outer rain
fiery cosmos
#

ah ok

#

ah you're right

#

i did xFF and got the offset of it
how do i do the reverse tho lel

#

thanks for that tho, it may come in handy in the future

fiery cosmos
outer rain
#

Just index access: file[0xAA]

#

0xAA is just an integer 170 in decimal, that's what .index returned

fiery cosmos
#

Thank you so much it worked!

#

ok one more question: how easy is it to overwrite bytes in python?

#

i should be good after that

#

so let's say i go to a specific offset of a file, through python, then i replace the byte in that offset

outer rain
fiery cosmos
#

ah that's an interesting way to do it. I'll give that a try later. Thanks!
btw, for godot (a game engine that uses a language pretty similar to python) this is apparently all that needs to be done to overwrite a byte in a file. Could we translate some of these commands to python commands?

#

like the file.seek() and file.store_8() commands? how would we translate those to python commands? if possible

outer rain
#

Oh, with built-in struct module, of course

fiery cosmos
haughty mountain
#

!d bytearray

halcyon plankBOT
#

class bytearray([source[, encoding[, errors]]])```
There is no dedicated literal syntax for bytearray objects, instead they are always created by calling the constructor:

• Creating an empty instance: `bytearray()`

• Creating a zero-filled instance with a given length: `bytearray(10)`

• From an iterable of integers: `bytearray(range(20))`

• Copying existing binary data via the buffer protocol: `bytearray(b'Hi!')`...
haughty mountain
#

That's...not the most helpful doc extract, huh?

#

It's a mutable array of bytes

outer rain
fiery cosmos
#

it still overwrites the bytes, but because i copy every byte after offset 170, and paste them after 173 (after the bytes i modified) it gives same result as if i didn't overwrite

#

the only problem with this is, i had to specify to python that i wanted to jump to offset 173 before pasting the bytes

royal kestrel
#

the cursor moves after a write so you don't need to do that

fiery cosmos
#

ah ok thanks

#

i'll try that then without the seek173

outer rain
#

but still, be careful with inserts in the middle, they are slower than appends

#

(with big files, I mean, you won't notice the difference if the size is a few kilobytes)

fiery cosmos
#

yep it works great thanks guys!

fiery cosmos
#

is it literally just file.append(values)?

outer rain
#

uhm no

fiery cosmos
#

ah ok

outer rain
#
file.seek(0, 2) # 0 bytes, counting from the end (option 2)
file.write(<whatever>)
#

If you pass 0 (or nothing) as the first argument if seek, it will move cursor from the start of the file, 1 is from the current position, 2 is from the end of file

fiery cosmos
#

ah so you're saying i should go to the end of the file and do the write command, for adding new bytes?
i'm trying to learn how to create a tool that modifies a specific file type and, when i modify that file type, in most cases, i'll have to overwrite, and sometimes, append bytes to areas in-between other bytes, so i can't just start writing from the last byte of the file unfortunately
thankfully, this method works well (i removed the file.seek(173) line lel) #algos-and-data-structs message

fiery cosmos
outer rain
fiery cosmos
#

wait so is a in a mode stands for append?

outer rain
#

yep

fiery cosmos
#

ah lel ok makes more sense now lel

#

how many modes are there for opening files in python lel

outer rain
# fiery cosmos how many modes are there for opening files in python lel

r is for read (the default), w is for write (clears the file, overwrites), a is for append (which is write, and immediately seek to the end of file)
+ means also open in the other mode so (r+ is open for read and write, starting from the start of the file, do not overwrite anything, and w+ is clear the file, allow both reads and writes)
t is for text mode (the default, handles encoding and new lines for you), b is for bytes mode.
So stuff like a+t is equivalent to a+, which is open in read/write, start from the end of file, in text mode.

Maybe there is more but that's everything I know

fiery cosmos
#

can i do r+b+a? (read + bytes + append)

haughty mountain
#

the + is not a +

#

not in the addition sense

#

the spec for modes is....weird

outer rain
#
a+b
^^^
||| and read/write in bytes, not text
|| also allow reads, aside from writes
| open in write mode from the end

from bottom to top

jade mica
#

Print (2*9)

fiery cosmos
#

ah alright

outer rain
#

The order does not matter, afaik

#

but I may be wrong on that one

fiery cosmos
#

btw, about this #algos-and-data-structs message when performing it in that method, i need to mention seek(170) twice right? because when only the first time mentioning it, it messes up

fiery cosmos
outer rain
fiery cosmos
#

ah that's why then, good to know thanks

#

didn't know read changes the position too lel

haughty mountain
#

if I needed to deal with not huge files I would just do

with open('a.txt', 'rb') as f:
  b = bytearray(f.read())

...work with the bytearray...

with open('a.txt', 'wb') as f:
  f.write(b)
outer rain
#

honestly, just be ready for filesystem shenanigans, files are super difficult

#

there are a lot of different kinds of files, and this is like the tip of the iceberg

haughty mountain
#

reading the data and working with it outside the file avoids most of it

outer rain
#

I still don't know how the device files interact with seek lol

#

so just touch filesystem as little as you can, and as long your files are less than a megabyte you should be ok

outer rain
haughty mountain
#

but not needed at these sizes

outer rain
#

at least you know exactly what is happening

fiery cosmos
#

i'll use the old method for now

#

it serves the purpose i'm looking for

outer rain
fiery cosmos
#

i'll keep that in mind

hushed spear
naive oak
#

which doesn't seem right

snow anvil
naive oak
#

being comfortable with both forms is good imo

snow anvil
#

That is true but I don't know if that implementation is correct

tawny prairie
#

anyone ever think about storing data in 3 dimensions?

agile sundial
#

never been done before

outer rain
#

That's fairly common

#

The basic neural network is represented by a list of matrices for instance

#

Or do you mean like storing three dimensional objects?

tawny prairie
#

i can shoot a code that shows version of what im talking about

#

more like sorting data structure using mathematical constructs of math formulas that are stored based off their gometeric shape, like 3 data points stored on a 3d structure, and depending how that input was done and when, the shape was rendered those 3 data points can store information on the plane it was created on.

tawny prairie
# outer rain You mean array of array of arrays?

usually 3 data points are formed to create a triangle, this can be used as a reference of context, if the values of that reference do not equal the inteded context a new point can then be used and if the point that used has plane of it own, then the new context then can be referenced

outer rain
tawny prairie
#

a new implementation of machine learning to create an eventual AI model that learns from the implementation of its core model

snow anvil
#

stop with the buzzwords please

robust needle
#

Hi I'm doing a yr 12 algorithms course, and currently we're focusing on the time complexity of prim's algorithm

#

After some research, the implementation we're using is pretty similiar to the naive adjacency list implementation

#
Algorithm Prim(Graph, optional start):
    MST ← Graph ADT
    Add start node to MST (or random node if start isn't specified)
    While G ∉ MST do: #O(|V|)
        Get all outgoing edges from MST #O(|E|)
        Select cheapest edge e (u-v), where u is in MST
        If v in MST, discard it
        Add e to MST
    End do
    Return MST
End Algorithm 
#

I got a big-O of O(|V||E|)

#

so worst-case, (running on a complete graph), it should be O(|V|^3), right?
but my teacher said prim's has a big-O of O(|V|^2).

#

could someone explain why?

haughty mountain
#

you can just

  • linear search through this to find the node u with the minimum distance to the tree O(V)
  • find the actual edge from u that gives that distance +O(V)
  • update the neighbors of u with new distances if needed +O(#edges(u)) worst case O(V)
#

(and I suspect people who know their data structures is screaming ||heap||)

robust canyon
#

Hi! I just want to check that my understanding of SCC's is correct (not any algorithms, just the idea of a SCC itself)

With this directed graph, the SCC's would be (3,4,5), (2), (1). Is that correct?

outer rain
lean walrus
#

What is SCC?

outer rain
# lean walrus What is SCC?

Strongly connected components, that is disjoint sets of vertices of directed graph such that in each set every vertex is reachable from any other vertex of that set

lean walrus
#

Cool

#

What if we add edge 6->2?
SCC's would be (2,3,4,5,6), (1), right?

robust canyon
outer rain
robust canyon
#

thank you by the way!

outer rain
glossy flame
#

Which of the following matches 2(6 + 4x) = 8x + 6

a. x = all real numbers
b. x = 1
c. no solution

Could somebody walk through how to achieve this answer?

vocal gorge
manic kite
#

Does anyone know why popping from the beginning of the list is O(n)? I found out that its because the other elements are shifted by one position which makes sense, but why not simply change the start of the list to point to the second element? Or there isn't a mechanism to free only the first element of the list?

vocal gorge
manic kite
vocal gorge
# manic kite I thought a deque is a doubly linked list?

A deque is an abstract data structure, like a stack or a list, and can be implemented in different ways. You could use a doubly linked list, but you could also use a ring buffer (an array which you consider to be "wrapping around")

manic kite
vocal gorge
#

For one, you need to always maintain a pointer to the start of a memory allocation, since you'll need it to free the allocation when the list should be destroyed.
(and you can't deallocate only the start of an allocation, on almost any OS)

opal oriole
#

If they don't allocate it as a contiguous chunk of memory then they can't offset from the start to some index, so you can't do [i] in constant time.

#

(Indices are actually offsets from the start of the array, which it holds a pointer to)

#

(Which is also why it makes sense to have the first element be at index 0, because it's a 0 offset from the start)