#algos-and-data-structs
1 messages · Page 32 of 1
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.
In the huffman coding the longest codeword length is n-1 right?
nvm I figured it out I'm just stupid
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
Given an image like this, represented as a 2D array, is there an easy way to fill the regions enclosed by the colored boundaries?
cv2.floodfill?
Thank you, but i am not too familiar with that method. What should the mask be in this case?
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
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
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
picking the first end point is how you maximize the number of non-overlapping intervals
you have a slightly different problem
the interval scheduling problem
I think I posted it way earlier, this is some very easy version of vertex cover
1D geometric set cover
i think it was
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
but will that really be bottle-necked by sorting? Wont we have to search for interval that extends the furthest to the right O(n^2) times in a worst case scenario?
Since its sorted wrt to starting point
i guess the same argument could be made with my "approach"
O(n²)?
if we have n points we need to cover
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
okay so we remove every interval whose right-most point is covered?
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
actually, if every point has a tile with non-zero left and right length (except for the left-most and right-most points), couldnt we transform this into a graph problem by connecting every point like this and then finding the shortest path?
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
you only connect a point with its far-left and far-right points it can reach
so you create 2*n edges
I mean, this is basically graph that the greedy approach walks in, you just don't create the graph
yes i just think this solution (if it is correct) is a bit more intuitive
what's not intuitive about the greedy solution?
is basically all you need to prove the correctness of the greedy choice
nothing really, its just easier for me to grasp and write down but im pretty biased since that was my original solution
greedy is easy to prove though
it won't be a single connected graph in general, which makes things a bit annoying
e.g.
* * * *
-------------- ---------------
----- ------
you can assume that every tile reaches two other points
my statement of the problem was a bit vague
the greedy algo doesn't change at all whether that's true or not, which is nice
is this equivalent to your greedy alg? https://stackoverflow.com/questions/58014028/develop-algorithm-to-get-minimum-number-of-subranges-needed-to-cover-range-from
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
Umm.....
Obviously learn Python
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?
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.
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?
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
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
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"
fwiw float64 += int32 would be ok, the reverse (like here) not
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
: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.
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
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.
This algorithm will help you create amazing procedurally generated images, maps or textures from your sample
@sudden sedge
Thank you so much! I think this might be exactly what I was looking for
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
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
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
wowo u did that ? with python
for future reference, please use the right channels or help threads for these questions
how is this code https://leetcode.com/problems/minimum-size-subarray-sum/solutions/3498091/python3-beats-97-o-n/
considered O(n)
and not O(n^2)
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
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
start from just A-B and see what happens to the number of nodes and edges when you keep adding new nodes
If you have 1 node and 0 edges then there is no cycle ig
Or just 0 edges in general
that doesn't have n nodes and n edges though
Oh right
A graph with 0 nodes and 0 edges? 😛
Otherwise there will always be a cycle pretty sure
isn't that a tree also
oh wait that's not the question
i was actually thinking about this
if trees count as graphs i could be getting somewhere
a tree is a graph, yes
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.
Can n not be 0?
The question does not specify n element of N/{0} so I'd assume that is a valid counterexample
Why do a proof when it is far easier and safer to give a counterexample
Unless it's for practice that is perfectly understandable
i couldnt find a counter example because i believe the answer is true
Did your question specify if n>0?
i mean.. you cant have a graph with negative nodes can you
And n=0?
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
thats just not a graph at all, it's nothing
That depends on how you defined it
In the mathematical field of graph theory, the term "null graph" may refer either to the order-zero graph, or alternatively, to any edgeless graph (the latter is sometimes called an "empty graph").
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
well it doesn't really make sense to talk about cyclic graphs for n < 3 so it's probably just an oversight
it does as long as you're ok with self edges and/or duplicate edges
undirected graphs can have duplicate edges
in the course I am taking rn we disallow that I assume similar for him
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
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
💀
(or 1x1 matrix [1] if you prefer)
I genuinely hope my profs dont do that ´cuz Ill always take the easy way out if the qustion is badly defined
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?
This is a help channel or #data-science-and-ml thing, I'd say. You'll want to post the code you're using for saving and for the loading.
ok thanks 👍
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?
if something isn't referred to anymore, it will eventually be destroyed and the memory it uses will be freed
are you asking if x and y are stored at the same spot
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
This is implementation-dependent, but in CPython the two references to 2 will be to the same object.
ty very much ❤️
ty very much ❤️
Somebody knows basic python servers
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?
you select some edge in the graph and you merge the two nodes that the edge connects
meaning things that connected to either node now connects to the new merged nose
sadness
this finally makes sense, thanks
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
You cannot put ['A','B'] into dict. ('A','B') will work but it is immutable
is a better solution "AB" then?
What if you have more than 26 nodes?
or actually merge the nodes and make the needed changes in the graph
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
just to make sure we're on the same page, do you mean something like this?
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
ah ok, that makes a bit more sense
it probably doesn't matter much, but for me it's easier to think like that
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
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
random node then random edge of that node will not be uniform
you want to pick some edge at random
so you probably want a list of edges to randomly pick from
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]
?
how are those graph edges?
i guess thats what i'm confused on, how do you pick a random edge if you don't really label the edges?
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)
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
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?
don't fret thats more then most
No it's because I wrote my own algorithm and it didn't plot correctly.
I have one using lstm that works fine
2.00 loss
yeah i got that when the history didn't make any sense although technically your not wrong lol
im into writing algorithms i have several going in my head with sound, but my first project needs to be finished
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
True
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
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
I would say do the simple thing to begin with
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
duly noted, I'll try that
hey that is a beautiful function.. you realized that this function could be used in audio right.. badass really
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
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
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.
oh you're talking about the actual function
isn't it frequency response?
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
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
fourier transformations scare me
I could've used it for this but the math is too heavy
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
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
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
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
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
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.
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
which could be calculated by the value set created by the 3,3,3 representation, that is more confined within the original set
ok
wait
I believe mine is 2,1 for the matrix though
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
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
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 ..
yeah I see what you mean
but this is mainly for me to learn from right now
so I get used to the libraries
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
you probably will, I just started with this stuff
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
you have this in git hub or ?
^ bump
you would remove self loops
so the little diagram i drew is correct?
idk, if the lists are super useful there, but yes that would be the end state
the duplicate edges are intentionally kept
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.)
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 : ''')
oh i was looking for an example here, guess I just didnt find one
also before i forget again thank you very much for all the help!
python türkçe karakter kabul ediyor muydu ya
google colab'da çalıştırdığımda sıkıntı almıyorum ama vscode'da kod hatasız ama çalışmıyor. Yani sorunun cevabını bilmiyorum. Ama yukarda attığım sorunu hallettim ben.
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.
https://github.com/Iheuzio/TickerPricePrediction
don't know who asked for the code but decided to upload it
the fourier transform and fourier series are somewhat different
the former is the limit of the latter
I guess the DFT is quite related 
!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})

@haughty mountain :warning: Your 3.11 eval job timed out or ran out of memory.
[No output]
how does image support work with !e again?
I guess I'll need to upload it myself 😔
how can k-SAT be reduced to #k-SAT in polynomial time?
Suppose you want to solve k-SAT and have a #k-SAT oracle. Apply the #k-SAT oracle to your problem. If it returns 0, return "Unsatisfiable." Otherwise, return "Satisfiable."
that was me bro thanks im highly into it, funny how the guy next to your comments was referring to the very thing i was trying to speak two you about lol
@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)
what's a branch?
mb it should be path
recursion = going as far down the path before others? how?
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
i get the abstract concept but how does this translate to code
that's what this does
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
Has anyone here implemented a backtracking list?
I would like to know how you approach that
don't understand
a nice optimization in a dfs is to append/pop the path before/after the recursive call
like backtracking?
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
in terms of readability second is defo better
idk if python does branch optimization
but it seems like it'd be negligible
like this? ```py
current_path.append(next_node)
yield from inner(current_path, end)
current_path.pop()
(and yield current_path.copy())
yeah
depends
if the caller can be trusted to not modify the list you can avoid the copy
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.
won't it all be references of the same list without it?
i think they're assuming that all the processing you'll be doing with the path will be done in between calls
show your code
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()
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 ?
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.
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".
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.
Next time, please try to use a service such as pastebin to post this many lines of code
I guess it wants a completely separate copy of the graph that it can modify
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?
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...
unrelated to your main question, but if you use list[int] for random access how do you remove elements in O(1)?
You swap the value at the end with the value you're removing
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
Are you sure you aren't looking at the previous exercise where there can't be duplicate values?
The set represents the indexes that the specific value exists at
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.
some parts go away with practice
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 
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.
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 😅
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.
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
Yeah that's what I did
It's too confusing to keep track of it in my head, there's too many moving parts.
It's like juggling
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
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?
Since the weights are all natural numbers, you can maybe use one of the integer programming in scipy.optimize, like milp
https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.milp.html#scipy.optimize.milp
That also needs the problem to be linear, but, hmm, I think yours can be represented as one.
couldn't you brute force this?
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
so if i'm reading it right, you wanna basically have a color be recreated by a sort of 'sum' of other colors?
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
anybody have info about stata 16?
Please can someone help with this book? Introduction to Algorithms" by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, and Clifford Stein.
What’s the question tho?
I don’t have question, I just need the book
come on man
You can buy it on Amazon ig
from itertools import combinations
80€ 💀 thankfully there are other ways of obtaining these things
||it's not like it's hard to find a digital version||
||Lol, I know what you mean. Uni Students unite||
try int(input())
You used the wrong datatype. Variable xvalue takes a string as input. But in the if statement your using '10'
You have to use int(input("waiting: "))
How long have you been doing it per day
Doesn't C use the same principles as python in this scenario. Not sure since I have never used C
in C you just define variables at the beginning
with like Int variablename = something
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'.
how much bits get allocated for int?
In CPython, an int is an array of 4-byte* "digits", and 30 bits of each are actually used.
*might be platform-dependent; there's a 2-byte option
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.
but if I shift it only two places(if value is 6 for example) it won't grow because it has plenty of space left.
That's true, sure.
so for 6 it is allocated 00000000 00000000 00000000 00000110 as I said
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)
Thank you, it is much clearer now
i think they've gone to using 4-byte digits by default
print("Just testing whether it will be printed in a box. Joined discord recently so I'm not much familiar with typing tricks.")
I recently implemented the "merkle search tree" data structure. I think it's kinda neat, so just thought I'd share: https://github.com/DavidBuchanan314/merkle-search-tree
https://leetcode.com/problems/basic-calculator/
Can this be O(n) with O(1) space?
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:...
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...
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?
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)
Yeah, you need to know whether or not you're coming out of a negative expression
I think worst case you need O(n) space regardless
a typical way of parsing this kind of expression is called the shunting yard algorithm
there's no operator priority here though
so maybe
though I am doubtful
oh, it's only plus and minus
Parens tho
so in +(...) parens can just be ignored, you're right -(...) is the one interesting thing
It looks like in C++, the string isn't const, so you can write to it. I wonder if that would make a difference.
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
that won't help much, unless you plan to totally ruin the string
and yeah I wouldn't really count that as ok
That was the idea. Like with some of the problems, like "find the first missing positive", you can completely change the array to achieve O(n) time O(1) space.
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)
Hi I have a problem@naive oak
import requests
data = {
"chat_id": "<1001910965>",
"text": "hi"
}
token = "My token"
url = 'https://api.telegram.org/bot{token}/sendMessage'
print(requests.post(url,data=data).text)
This my problem
is this channel called python-help?
Yes
Oh
But the server name is python
Every channel is for python
@snow anvil
I was wondering what is y'alls perfered method of dealing with collisions regarding hashmaps
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
seems like it should be doable with a simple nested loop?
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?
this is a tree so I using oop to make a tree is what I would to
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
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)
wdym by dynamic?
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')]
I would not describe this as a tree
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)])
uhh
wait, how tf did I get fractional stuff?
it should be i-n and n
because n is the index that changes along a row for you.
and i>=n always
!e
p = 2
q = 3
for n in range(5):
print([p**(n-i)*q**i for i in range(n+1)])
@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]
welp, finally
yeah, thanks
I guess I'm not fully awake yet
Ye I was sleep deprived and only looked at the pascals triangle looking thing
On a sidenote I do not comprehend avl tree rotations rn 😦 may or may not be related to the reason I was sleep deprived
!code
you do competitive programming right? what do you usually do for practice before a comp? i've got one tmr
I didn't practice much outside contests 🥴
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?
Good luck
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
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]
I still don't really have an intuition and I've looked at a bunch of sources
Yeah I suspect I'll just have to keep looking at them until it clicks
try a virtual div3 contest on codeforces then
find some recent div3 contest, then there should be a link for a virtual contest
there's no verification that the initial value of num is an element of values
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}
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. "
Where could I go to practice Python?
Codecademy or your own project
Awesome, thank you.
leetcode also
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).
There is I just didn’t show it
It’s the function called checkInputs()
Same with this
finished the comp
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
which site is better to learn python..geeksforG or codeAcademy
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?
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
learning DS&A indeed helping you to formulate a kind of algorithm topic. In addition, discrete math and number theory are common knowledge to help you in some computational thinking problems
hello
Yes. You will learn the related math topics along the way
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
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
which test case failing it?
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
I'm not kidding, I didn't make any changes to the code and now as I run it, all test cases passed
for x,y in zip(s1,s2):
s+=x
s+=y```
s="camelCasing"
s= list(s)
i=1
while i<len(s):
if s[i-1].isupper():
s.insert(i-1," ")
break
i+=1
print(''.join(s))```
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
Tasks says assuming they are equal length does it not?
really?
yeah
as in... it only works for a certain length or so?
Your code NEVER runs
Make it so your if statement does not exclude all options
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
when did you even declare s2?
S3 = ""
yeah it doesnt like that for some reason
it doesnt give me the output
no its litterally just how dog shit this website is put together
its not a proper program
Len s1 and len s2 are assumed to be the same
yeah
Your first if statement says:
Run this code if len s1, s2 are NOT the same
s3 = ''
i = 0
if len(s1)>len(s2):
for i in range(0, len(s1), 2):
s3 += s1 + s2
return s3
Try this one
So your code will never run
can you share the problem?
man i dont understand
LOL I did this exact question yesterday
with this its expecting []
Also why is your loop going in steps of 2
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
This code is very questionable
Initiating i = 0 for no reason
i know it's stupendously long, but it works like a charm
lol use zip!
Yup, usig zip is the best way
Why is there a ,2?
but if you're unfamiliar with it, my method won't do any harm either
you wrote the code idk
I did not
he did
nbm
nvm*
Full of things that show you did not study
no yeah not this portion
most of its just stuff i just power through
powered*
the things i know are very scattered
Delete the first if statement delete the 2 in the loop
Add return
Oh idk how that website works how are u supposed to do the output?
iffk how it works either
len(s1) in the loop
here a thing i did succesfully if that helps
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
Dont return
whar
try this code, I'm unfamiliar with the variables given so.. you should substitute
No return needed just do what I said then also do
s3 += s1
s3 += s2
And it should work
this is exactly what we're using
you need to use it with different iterations though
s3 = ""
for i in range(0, len(s1)):
s3 += s1[i]
s3 += s2[i]
i was forgetting the brackets thins like a monkey
yes and your if statement made the entire code not run
it works, see
cat you use a 3rd thing to make it skip numbers
Also i = 0 is not needed since i gets initialized in the loop
whats the issue herer
this one*
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
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)
Please go to #1035199133436354600 instead this channel is supposed to be for dsa
s1 = "hello"
s2 = "world"
s=""
for i in range((len(s1))):
s += s1[i]+s2[i]
print(s) ```
you can try though, just saying
yeah sorry
i was in the rush and saw the first channel people were talking in
im not really thinking rationally
last week of 1st grade 🐱 🚬
its work only s1==s2 @craggy grotto
aue
He's at the reversed strings question now
Same with me bro, I'm sitting in front of my laptop since 3 days. Didn't even see sun.
ive been working with 1 hour of sleep everyday for more than a week
;d
Me personally, I'm getting 4 hours
?
Just a tip since you are repeating yourself so often just write a helper function
Makes the code more readable
like...?
I'm kind of a newbie myself actually
for i in range(len(s2)):
a += s1[i]
a += s2[i]
Notice how you repeat this 3 times?
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
I'm sorry... Uhmm... I don't get the point. It's the same code. Initially, I submitted the code to leetcode within a class the code was a method withing that class originally.
The point is to not repeat yourself
Yes, That's a really good point. However, in the code that you posted, there still are repititions, right?
Well it's less to write and easier to understand
Although, I agree my lack of expertise makes the code less abstract
If you give idk a good name that is
yeah haha, I was reading this bokk, "Cllean code" it says, always give your variables, functions etc a suitable name
but u can use cycle for different length!
however, since I was using jupyter notebook, and it doesn't have the autocomplete feature, I opted for shorter variable and parameter names
What r u talking about I just rewrote his code to something I think is a little cleaner
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
we can use cycle instead of elif else
Okay!
???????
It's fine but anytime you write the same thing multiple times consider a helper function
after submitting mine, I saw other solutions by different people, they mostly opted for zip function. But since I'm unfamiliar with it's functionality as of now, I moved on to the next.
Sure Thing!
Zip is very neat definitely use that anytime it's convenient
I'll need to further learn about it. WIll do.
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
understanding the concept behind the bubble sort is a good foundation to learn how to play with 2 "pointer" in an array/list. after all, no need to dig deep about it.
itertools.zip_longest would work well. With "" as fillvalue.
What module would I have to import for that? Or does it come preloaded by defult?
itertools
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?
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.
I think time.sleep(0) is a canonical way for threads to yield to other threads
e.g. see the usage of delayfunc in https://docs.python.org/3/library/sched.html
I'll read this tomorrow but your saying this might be the reason one of a callback might seem to be greedy with the mutex lock right?
if the mutex is taken again very soon after it was released it might be that the python never switched which thread to run
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
Is there a way to bypass this global interpreter lock or I'm just fucked?
the time.sleep(0) might fix this situation since it basically says "I'm done for now" to the scheduler
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)
``` ?
the GIL basically says python code in the same process can't run at the same time
This seems like a pretty major drawback of using python
I mean, it is
I'm not sure about your case though
what's calling these callbacks?
subscribers
not sure what you meant though, also, my placement of the time.sleeps makes sense?
@haughty mountain yeah it does
Maybe there is another way to get what I want through anither algorithm design
it's possible these things might end up cleaner with async, but I'm not sure
Can’t talk in voice chat? Check out #voice-verification to get access. The criteria for verifying are specified there.
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
in particular with async python will run your coroutine until it awaits or returns
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
asyncs the way to go you think?
the switch between threads could still happen at pretty arbitrary times, which is why you might need mutex
could a switch happening inside this part of code break correctness? if so mutex protection of that code is warranted
might be worth a look, but it basically requires your whole program being async
So no other language can do it? That's why I should pay attention to python
so I still need mutex with async?
afaik with async your coroutine has more control, it will execute until it gives up control
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
no
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.
Dfs is a very simple algorithm
it is as simple as you thought
what is your graph? because it looks like you're just going thru every node in the graph on the first call regardless of its connection to your start node
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.
you mean like inverse functions?
if you do then for the summation you can just find an inverse by solving the quadratic
if I give input to inverse as 57 will it return 10
not really a function, a formula
functions have time complexity I want constant
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
I found the formula of sum, rem < num
it'll still scale in time
?
110 = n^2 + n we have to find n
if I provide 57 then 114 = n^2 + n and I have to ensure 57 %55 < num
num is 10
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
(-1 (+/-) (1+8N)^0.5)/2 = n for sum
newton's method, means raphson or incremental?
floor of n would give incorrect results better ternary operator
and how to find relationship?
incremental?
oh if you want like closest then yeah
usually most people are fine with just the least/most
stirling is approximation right?
yeah
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
You are correct, it's not the right channel :).
ASCII is 127 characters, this one (\xFF) is not one of them. Your hex editor is likely using some other regional ascii-compatible encoding.
ah what would be the proper channel for this kind of discussion, all the others don't seem to fit this topic as well as this channel does
Also how do i find the right ascii encoding? HxD is the most popular hex editor
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
i wanted to use #python-discussion but i can't post images there
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
is this binary code or something
hhex code, so yea pretty much binary code
i know binary code
i mean i know to read it
Do you know how to do this is the byte was, say 0x42? (ascii letter 'A')
so you mean via decimal values rather than hex values?
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
I mean, I'm pretty sure you got it there. Just replace the b"ÿ" with b"\0xFF" and you are good.
(also make sure the file is opened in "rb" mode)
I tried doing that but with b"\0xFF" since FF byte is located in AA offset, but it says subsection not found
Oh sorry \xFF, no zero
I messed up
Also why AA? The \xFF is a byte, the 0xAA is what you want to get
I did AA because AA is the offset in the file where the FF byte is at
That's what you want to get, not what you want to find
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
how do i input the offset and get the byte value in the offset*
Just index access: file[0xAA]
0xAA is just an integer 170 in decimal, that's what .index returned
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
Not easy. Turn in into a list: a = list(file) (I hope this works), work with that. After you done, turn it back into bytes: bytes(a), and just overwrite the file with that.
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
You will need to open a file in "r+b" mode. Seek is just .seek, nothing changes, write_8 is a write of 8 bytes. I don't remember how to turn the integer into bytes
Oh, with built-in struct module, of course
ah actually someone helped me with that here #1119921207077240832 message
bytearray is kinda made for this
!d bytearray
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!')`...
Ooohhhh yeah I forgot about it!
i tried something that's sort of similar to what you suggested and it works pretty well
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
the cursor moves after a write so you don't need to do that
don't worry, that's how you are supposed to do it (and seek(173) is not required, as it has been mentioned)
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)
yep it works great thanks guys!
ah there's an append method/command instead for if i don't want to overwrite the bytes and only add bytes?
is it literally just file.append(values)?
uhm no
ah ok
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
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
But writing from the end of the file may come in handy in future projects, thanks for sharing that tip
you usually will need to just write, in which case the just open the file in a mode and write
f = open("a.txt", "w")
f.write("hello, ")
f.close() # overwrites the entire file with `hello, `
f = open("a.txt", "a")
f.write("world!")
f.close() # appends `world` to the file, the content now is `hello, world!`
wait so is a in a mode stands for append?
yep
ah lel ok makes more sense now lel
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
can i do r+b+a? (read + bytes + append)
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
Print (2*9)
ah alright
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
i'll give this a try tho, thx
yea, read does a read from the current position, to the end, moving the cursor along the way
ah that's why then, good to know thanks
didn't know read changes the position too lel
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)
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
reading the data and working with it outside the file avoids most of it
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
this is the great example of this
there is mmap that can kinda bridge that gap
but not needed at these sizes
yeah, honestly, manually doing syscalls is just the best option sometimes
at least you know exactly what is happening
ah this didn't work well for me, i thought it was going to append the bytes to the offset but it appended to the end of the file
i'll use the old method for now
it serves the purpose i'm looking for
yeah if you do seek at the start, r+ or a+ does not matter, you will move the cursor where you need anyway, just don't accidentally clear your file with w+ lol
i'll keep that in mind
should just be traversal, I’m not doing a search or anything. I can send the graph when I get back on PC, but it’s relatively simple
well your traversal doesn't have anything to do with s except adding it to visited
which doesn't seem right
I agree with the guy above me try to write a dfs with a stack I find that one more intuitive
being comfortable with both forms is good imo
That is true but I don't know if that implementation is correct
anyone ever think about storing data in 3 dimensions?
never been done before
You mean array of array of arrays?
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?
sorta
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.
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
what would the use case for such structure be?
a new implementation of machine learning to create an eventual AI model that learns from the implementation of its core model
stop with the buzzwords please
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?
I don't have great intuition about Prim, but I think the gist of the V² impl is to keep the distances from vertices to the tree
you can just
- linear search through this to find the node
uwith the minimum distance to the tree O(V) - find the actual edge from
uthat gives that distance +O(V) - update the neighbors of
uwith new distances if needed +O(#edges(u)) worst case O(V)
(and I suspect people who know their data structures is screaming ||heap||)
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?
You forgot (6), but yeah, you are right
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
Why is 6 a SCC? You can't reach any other vertexs from 6, that's why I thought it wasn't.
that does not matter, (6) is still SCC. SCC divide your graph into components, every vertex must go exactly to one component. There is nothing special about vertex 6 not leading anywhere. What if there was a cycle (6, 7), which does not lead anywhere else? Would you consider it an SCC in that case?
alright, that makes more sense. also to answer your question on the (6,7) cycle, that should be an SCC.
thank you by the way!
no problem!
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?
That's more fit for offtopic, I think. ||Start by simplifying the equation as much as you can.||
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?
What you're describing would be a deque implemented using an underlying array (Rust calls it a VecDeque, say). It requires keeping track of where in the array elements start and end, but it's valid, sure.
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")
Hmm. I don't think this is what i had in mind. What i thought of is when we do list.pop(0), why not make the list simply point to list[1], and free list[0] or this isn't possible? Like is there a reason lists in python aren't implemented this way?
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)
Thanks!
list[0] is part of the same contiguous chunk of memory that was allocated, they can only deallocate all of it or none of it.
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)