#algos-and-data-structs
1 messages · Page 45 of 1
first off, do you see why the last equality I posted should be true?
if that's not clear nothing will make sense
the equality would be true for any node cur
yes I understand that the child must have more descandants than its father.
yep
so if the parent knew the correct answer for its children the answer for the parent is easy to calculate, right?
so the key here is that we want to do the calculations in an order where the results for the children are calculated before the result of the parent
In any traversal through a (rooted) tree you will encounter the parent before any of its children
so if we look at that order in reverse, all children will come before the parent
makes sense?
Need some urgent help:
Traceback (most recent call last):
File "/Volumes/Isaac's External Drive/neogapp/examples/gp/gp_example.py", line 30, in <module>
g = gp.GaussianProcess(X, Y, Sigma, cXstar=(xmin, xmax, nstar))
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/opt/homebrew/lib/python3.11/site-packages/gapp/gp.py", line 117, in init
if (xmin == None or xmax == None):
^^^^^^^^^^^^
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
use is for None checks
== for numpy arrays are overloaded to do elementwise comparison which is why it tells you about any/all
since it thinks it's not obvious what bool(array) means
thanks a bunch bro! It worked!
Even for things that aren't numpy arrays?
@haughty mountain
is for None checking is a good idea in general yes
thanks
Also: x1s = reshape(x1s, (nstar, nstar)) gave me TypeError: 'numpy.float64' object cannot be interpreted as an integer
Any idea?
i need some cache, but i dont know how it is called
i have two processes: client and server
client asks server to read some memory (real memory) and send it to client through socket
it works pretty fast if requested memory blocks are big, but for small memory regions it becomes awfully slow (because socket latencies are pretty much constant)
so i need the following cache:
- when client needs data from server's memory, it actually requests bigger memory block (aligned to page size, for example)
- cache stores
(memaddr_start, length, data)somewhere - when client requests cached memory, it is quickly returned back from cache
- cached values should be invalidated quickly (every several hundreds of milliseconds, for example)
i think i can implement it myself, but i have never done somwthing like this and im pretty sure there is an existing implementation somewhere
Got it nvm
(it sounds very similar to cpu caches, but implemented in a weird way)
this sounds kind of too specific to have a library designed for it tbh...
... but this also resembles how cpu cache works a little bit too closely (which you have just said), so perhaps you can hack an existing implementation you can steal from some simulator... not sure if that helps though, I would just write it myself
hmm, okay
thank you, i will implement it myself using existing implementations for inspiration
what language?
you're kinda describing mmap
but idk if you can slot mmap into it somehow
and idk if you can do invalidation with mmap
also why invalidate rather than just doing some lru cache? you're worried about staleness?
yes, im going to do runtime modification of game state, so big delays are not good
Are the client and server on the same machine?
yes :)

Use shared memory.
hmm
yeah, on the same machine there are way better ways
can i share entire process memory to other process?
I'm kinda questioning why you even have a server and a client at this point 😛
You can technically can, but usually there is only some chunk you need shared.
Server client on same machine is silly.
it depends
I see it a lot in web dev, sending data over sockets between processes (on the same machine, silly things like LSPs).
if multi client it can make a lot of sense
Unless you also want to actually have it happen over the network too.
i have a extremely simple server in fragile unfriendly environment of the game, i dont want to affect the game process too much
client lives in another process, i can quickly restart it, i can use whatever libraries i want and i can attach GUI to it (which is very tricky to do in game because it already has GUI window)
i wanna read all code, all static variables and entire dynamically allocated memory, so there is no such chunk
so you're writing a memory debugger basically
¡rule 5 :V
it already works
game windows is on the right side, im doing things there
client output is in the console window in the left, you can see values change there
fancy
You can read and write memory to another process pretty easily. But to make this actually nice to work with, it's best if your entire game state can be accessed by some big struct sitting there globally, then you only need to get one pointer.
Otherwise it can be a pain, since you need some registering system to make it easy to use (meta-programming baked for example).
game is not mine, im just researching it (and it is not violating their TOS (there is no TOS))
Oh, then I can't help you with that.
I wonder if there is any python real time debugger
there is a bunch of global static variables that hold pointers to all dynamically allocated objects, so if i know the pointer, i can reach to object and all its members
game is in delphi
im writing stuff in python (+ a little bit of C-API to spin up thread for CPython)
struct declaration looks like this (fully typechecker-friendly btw)
and you want to monitor the delphi stuff only, right?
yeah, there is no point in monitoring cpython, because it is only running 100loc server
and i know exactly what is happening inside of it
game stuff is a lot more interesting
thats boring
(it's scriptable in python)
i want to implement it myself
and it can be a foundation for things that manipulate game state (for example, game modifications)
how can i implement socket-like messaging using shared memory?
the only functionality i need is: ```py
def read(addr: int, size: int) -> bytes: ...
def write(addr: int, data: bytes) -> None: ...
def check(addr: int) -> bool: ... # check if readable
right now i am sending packets like `\1 addr size` to read, `\2 addr datadatadata...` to write and `\3 addr` to check if addr is readable
what should i do with shared memory to achieve similar functionality?
another advantage of sockets vs sharedmemory is that they dont depend on bitness of process
game is 32-bit only, but i can talk to it from 64-bit process
i dont think this is easily possible with shared memory
I feel just adding some dumb caching layer on the client side makes sense
like a layer that translates a "read n bytes at this address" to "fetch a bunch of N sizes blocks" and then gives you the data you asked for
should be a thin enough layer to write
write is trickier
flushing read-caches is pretty easy - just forget about them
flushing write-caches can break game's state:
- imagine we cached one page for writes
- write to some place A (this is written to cache, not to game's memory)
- at this time game writes to B in its own memory
- flush write cache by just writing cached page into game memory
- now game's write to B is discarded, and game is left in inconsistent state
why not keep it simple and keep the cache read only?
this can happen easily if two objects are allocated near each other: we change A, game changes B
this is definitely an option
if write latency is an issue. you can bundle a bunch of writes and send them all at once for the server to execute
and you probably want to invalidate the relevant parts of cache
i can cache page and keep track of bytes that were changed
then send changed page and list of changed bytes (or bitbytemask of changed bytes)
I imagine
------->
read pls
<-------
ok, have data
------->
here, some writes to execute
<-------
ok, done writing
now invalidate the cached chunks that intersect with your writes
or ignore the invalidation and just accept that your cache is stale for a bit
but that feels potentially racy
another a bit unrelated question:
is it possible to "freeze" game thread for several microseconds while i am doing all reading/writing stuff?
i dont think this is necessary in most cases, but in some very hot places can be helpful
surely yes, debuggers do that
as to how, that's a separate question 😛
on linux I would look if just suspending the process does what you need
is thread considered an another process on linux?
i heard something like that
enumerating all threads seems to be harder, but i remember that game stores their handles somewhere, so i can grab handles there
I think threads will be grouped under the same (user visible) pid
so that if you suspend that process all threads are suspended
but I don't really know
so thread that handles socket requests also will be suspended :'(
ah, your thing runs as part of the game process, huh?
yeah, you might want to be more fine grained then
good thing is that game uses only couple of threads and very rarely spawns new ones, so manually getting thread handles from some obscure game storage should not be very complicated
most of the time there is only thread that does game logic + draws gui (if we ignore music + sound threads)
there should be apis to get all threads for a process
i found winapi that extracts this info from process snapshot, i dont think this is a good idea
hmm, what would happen if i kill random thread? 🤔
sound just disappeared
and it fixed a bug
it worked for a moment and then crashed
no, it hanged
my thingy still works
not overly surprising if you're killing threads
suspending hopefully behaves more nicely
it is, game hangs if i suspend crucial thread and unhangs when i unsuspend the thread
no crashes
VfxvGYo3N8o-U0vTPLDxAq2PE-mPvvNqZjK5NAMn3iduohl-Te3TPLSIXidajTOQrDwz_YG_H0WpCwbSF-9Ky9wM6si4EJ5Tc5LK41sJaeuc8gyeOklol9TllUG9HlM2W4NZV03xe7bnnD8NuCXCuVwpwbAeoVH1dIx4o7GdHdSQvUxHvL3LDTww8PV04FTmfUtqJP-au0dFHIYxzJtoSGOEtmRtjtKEp7d5a8aUdqsKrfidxJUs21yRnhfVmHh40Zz8E7602zv9ZYx-2xs=
You think what is this?
some binary data encoded in base64
all codes this
@haughty mountain Is it possible to write code that will decode the url?
this is not #algos-and-data-structs related at all, ask elsewhere
one question
why nobody use codewars?
i mean there are a lot videos about leetcode in youtube, same with codeforces
but if you want to see someone solving hard problems in codewars you wont find
codewars hard problems are actually pretty hard haha
i dont know someone who have solve katas 2 or 1
i just want to know what do you think about it
people use it
it's not that rare for people in this server to recommend it
(I did solve a 2 kata, but katas 1-2 are usually more annoying than really hard)
I am late with respond, was solving some other problems, but this is better (not my) solution (I guess it is correct)
def findLength(self, str1, k):
window_start, max_length, max_repeat_letter_count = 0, 0, 0
frequency_map = {}
for window_end in range(len(str1)):
right_char = str1[window_end]
if right_char not in frequency_map:
frequency_map[right_char] = 0
frequency_map[right_char] += 1
max_repeat_letter_count = max(
max_repeat_letter_count, frequency_map[right_char])
if (window_end - window_start + 1 - max_repeat_letter_count) > k:
left_char = str1[window_start]
frequency_map[left_char] -= 1
window_start += 1
max_length = max(max_length, window_end - window_start + 1)
return max_length
For this problem
Given an array containing 0s and 1s, if you are allowed to replace no more than ‘k’ 0s with 1s, find the length of the longest contiguous subarray having all 1s.
Example 1:
Input: Array=[0, 1, 1, 0, 0, 0, 1, 1, 0, 1, 1], k=2
Output: 6
Explanation: Replace the '0' at index 5 and 8 to have the longest contiguous subarray of 1s having length 6.Example 2:
Input: Array=[0, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 1, 1], k=3
Output: 9
Explanation: Replace the '0' at index 6, 9, and 10 to have the longest contiguous subarray of 1s having length 9.
There is also interesting solution:
def findLength(self, arr, k):
n = len(arr)
max_length = 0
window_start = 0
num_of_zeros = 0
for i in range(n):
if arr[i] == 0:
num_of_zeros += 1
if (i - window_start - num_of_zeros + 1) > k:
if arr[window_start] == 0:
num_of_zeros -= 1
window_start += 1
max_length = max(max_length, i - window_start + 1)
return max_length
that's the thing I described
that's a more interesting solution, it makes use of the fact that the interval you might need to consider is monotonic
i.e.
- I saw 4 character repeats in a window of <=6
- so I need 5 character repeats in a window of <=7 to beat it
the monotonicity means you only need to keep track of the max number of repeats repeats you've seen in a window overall
rather than the number of repeats in a sliding window
I'm solving this problem:
https://codeforces.com/contest/356/problem/A
I'm trying to use a segment tree. My Python code would be this one (skip the snippets before if name == main):
https://codeforces.com/contest/356/submission/233010602https://codeforces.com/contest/356/submission/233010602
The solution is inspired from someone's solution https://codeforces.com/blog/entry/22616?#comment-332438 because I couldn't solve it on my own (and I wanted to train my segment trees skills).
I'm however confused as to the update part. I fully understand how to query stuff when the tree is done. I drew the whole binary tree to make sure I understand what's happening with the first example of the examples provided in the problem
I understand that
We update everyone except x[fight_number] - 1 because we don't want to update the winner of the fight as being "conquered by" themselves. hence the two calls
But then the partiy checks are a bit obscure to me, I understand that we go to the parents with >>=1 but other than that I'm a bit lost
I'd imagine:
if right & 1:
# if right is odd, it means it is a right child
right -= 1
is because right is excluded and we still want to update the [left; midpoint] range?
The only thing I understand in the update function is:
left += self.num_knights
right += self.num_knights
which is basically to go to the leaves (e.g. if fights are from knight 1 (index 0) to knight 4 (index 3)), we need to look at leaves which are at position 4 to 7 in the array
but why do we care so much about left and right being right children?
EDIT: I actually think I understood.
If left is odd, it's a right child of its parent node. We update it (because [left, right)) and then we will not go further up for the query so we can go "to the left child of the next parent node" by doing left += 1
If right is odd, it's a right child of its parent node. We don't update it (because [left, right)) but we update right - 1 since left < right and since we won't go "further up" it's fine to leave right at (right - 1) // 2 because the parent will be excluded too
guys i got a powerpoint code and i wanna put it in powerpoint but how do i do it
is it possible to increment a value of a tuple that occurs as part of a value of a dictionary
eg:
key: (value, desc)
to increment value here
you cant change tuples or integers
so the only option is to replace tuple completely with new one
hmm
i'm trying to keep track of occurences of a name as i parse a file, but also store the number of times it occurs and a description
i wonder what the best ds is for this
doesn't super work with dict
i was just building giant lists but that's super inefficient
Why not do the occurrence and it’s description as a tuple for the key and increment the value
is there something in the python standard library that can perform efficient binary searches on sorted lists? or do i need to write that myself?
i'm familiar with heapq but i don't see a binary search routine built in for it
!d bisect
Source code: Lib/bisect.py
This module provides support for maintaining a list in sorted order without having to sort the list after each insertion. For long lists of items with expensive comparison operations, this can be an improvement over linear searches or frequent resorting.
The module is called bisect because it uses a basic bisection algorithm to do its work. Unlike other bisection tools that search for a specific value, the functions in this module are designed to locate an insertion point. Accordingly, the functions never call an __eq__() method to determine whether a value has been found. Instead, the functions only call the __lt__() method and will return an insertion point between values in an array.
aha, that's the one. thanks!
out of curiosity, is there no equivalently efficient search algorithm for the binary tree data structure in heapq?
idk 🤷♂️
fair enough. in any case, my actual problem is that i have a list of pairs [(a1, a2), (b1, b2), ...] and i want something like this:
items: list[tuple[int, int]]
max(filter(lambda item: item[0] < k, items), key=lambda item: item[1])
in my actual code i could just write that as-is and i don't think it'd be a serious performance bottleneck. but i was interested in whether there might be some algorithmically-interesting way to do that, with better (theoretical) performance when running in a hot loop on lists of several thousand pairs.
I don't think that's possible without some extra datastructures
With binsearch we can only get that the value is one of the values from 0 to pos (the filter part)
But we can't get the max with it
But with anything that can search maximum on that segment - Segment Tree, Spare Table, etc.. sure
my thinking was that i want the "biggest thing in xs before x", but yeah i don't think that works with two different filter criteria
a heap doesn't give you any guarantees about the order except the min/max is the first. so there's no way to search a heap
i see
that's not how heaps work
I see I'm late to the party
thanks discord
always good to get confirmation!
hii
- your in the wrong channel
- why? just ask your question(s) in #1035199133436354600
Can I calculate the weighted average of the percentages?
in what context?
is there an easy way to "deepcopy" all the member variables of a variable except 1
something like:
best_model = copy.deepcopy(model, exclude="erb") # Here i want to copy all member variables in `model` to `best_model` except `model.erb`, which i do not care what value it gets (it can be `None` for example)
motivation: coping the erb member variable is plenty costly (1/3 of total runtime for my program) and is useless in my case
PS if there is a better channel for me to ask this question let me know
If you want specifically copy.deepcopy to have this behaviour - I think under the hood it pickles and unpickles the object, so you can modify the pickling methods like getstate
!e yeah, that seems to work:
import copy
class A:
def __init__(self, a, b=None):
self.a = a
self.b = b
# see https://docs.python.org/3/library/pickle.html#handling-stateful-objects
def __getstate__(self):
x = self.__dict__.copy()
del x["b"]
return x
def __setstate__(self, state):
self.__dict__.update({"b": None} | state)
print(copy.deepcopy(A(5, 10)).b)
@vocal gorge :white_check_mark: Your 3.12 eval job has completed with return code 0.
None
Thanks for the answer
but is there an alternative that does not modify the __getstate__, i do want keep the accessibility of erb member state
perhaps a function custom_deepcopy?
Sure, you could make a custom deepcopy. E.g. copy the __dict__ of the instance, delete the erb key, deepcopy the dict, and turn the copy into a new instance. I think that'll work.
but the whole point is that i want to avoid copying erb (because the copy is expensive), if i copy the __dict__ i end up copping erb
Hence the deletion of that key first. Like,
def deepcopy(self):
dct = self.__dict__.copy() # this isn't a deepcopy, note, so self.erb isn't itself copied
del dct["erb"]
return type(self)(**copy.deepcopy(dct)) # optionally add erb=None or something like that
that works if my class's constructor has as **kwargs all of the member variables, which it does not
Then it depends on the class, I guess, but if there's no "external state" (so to say) that you need to maintain, you can do something slightly evil like
def deepcopy(self):
dct = self.__dict__.copy()
del dct["erb"]
# we avoid the normal init. I *think* unpickling does something like this too?
other = type(self).__new__(type(self))
other.__dict__ = copy.deepcopy(dct)
other.erb = None
return other
is there a way to perhaps create an empty instance of class (without running __init__())
That's the __new__ call here.
A string of size n <= 2e5 and q <= 2e5 requests of two types are given:
1 p c -> change character on position p to c
2 l r -> print out minimal period of the substring s[l...r] (inclusive)
period of string is such k, that s[0...k] repeated some times equals to s
How to solve this faster than O(q*logn*d)? (d is the number of divisors, smth like n^(1/3))
This asymptotic is segment tree + hashes
We will store string hash in the tree, for each request we will iterate over all divisors of r-l and check if it is a period
From what I know segtree and hashes are correct, but there is a way to not check all the divisors of r-l
Hey guys, this code is taking forever to execute, does someone have a different algorithmic appraoch or know how to fix this? https://paste.pythondiscord.com/Z5NA
profile it
in my program i have a big circular buffer
import collections
...
self.buffer = collections.deque(maxlen=1_000_000)
which i am sampling many times in the runtime
return random.sample(self.buffer, 256)
so much so, that it takes <60% of my total program runtime sampling the buffer, is there a way to change the memory layout of the buffer
as far as i can tell, it uses a list data structure for the deque by default, by reserve engineering the memory accesses of it, is there a way for the degue to be allocated using a std::array type structure?
Thanks! (PS if you need clarifications on my requirements be sure to ask)
it's not possible in python. yes, deque is a linked list. the things you could do would be implement your own queue or see if you really need to append and pop on the left
you could try to make your own random sampling function
i only use append, which is cheap
it is the traversing of the buffer takes a lot of time, which can not be fixed with a custom sample function
why use a deque then?
deque indexing is slow in the center due to being a linked list. if you're just appending to the right that should just be a list
i needed a "circular buffer" and after a web search this is only i could find
can you elaborate on that? what properties do you need specifically
a buffer with a max_size that i can append to
(when i append while the buffer is full dump the oldest element)
like C++'s boost::circular_buffer<>
ok so just a normal queue with a max size
there exists queue.Queue but I don't know how it's implemented and I don't know if it supports indexing
you might have to just implement your own, sadly 😔
queue.Queue also uses the same memlayout, i probably will end up writing my own in C++
unfortunate
you can implement it as a subclass of OrderedDict probably
or a class with an ordereddict inside
it'd be a lot more expensive memory wise, but the lookups wouldn't be too bad
class Solution(object):
def isAnagram(self, s, t):
return sorted(s) == sorted(t)
if len(s) != len(t):
return False #if length of s is not equal to length of t, it's not an anagram.
countS, countT = {}, {}
for i in range(len(s)): #iterate through the range of the length of s.
countS[s[i]] = 1 + countS.get(s[i],0) #counts amount of times each character is in s.
countT[t[i]] = 1 + countT.get(t[i],0) #counts amount of times each character is in t.
for c in countS:
if countS[c] != countT.get(c,0): #checks if counts are equal.
return False
return True
"""
:type s: str
:type t: str
:rtype: bool
"""
solution_instance = Solution()
s = ["cat"]
t = ["tac"]
result = solution_instance.isAnagram(s,t)
print(result)
my ds algos era has returned
but why does this return False
aren't they clearly anagrams?
cat and tac?
or is it because i'm being dumb
oh i know
it is because i passed in lists
not strings
how to make a hash-statement
silly quesiton, but CLRS doesn't discuss the towers of hanoi. why would that be? I thought it was a super standard topic
does CLRS even try to teach "what is recursion?"
presumably they expect you to know what it is, and they focus on how to analyze recursion and specific recursive algos
hanoi is mostly just a simple example to teach basic recursion
try grokking algos i’m pretty sure it’s there
hey buds i really need someone to explain me this code and how this works
def findxor(n):
if n%4==0:
return n
elif n%4==1:
return 1
elif n%4==2:
return n+1
elif n%4==3:
return 0
for _ in range(int(input())):
a,b=map(int,input().split())
num=findxor(a-1)-findxor(b)
print("Even" if num%2==0 else "Odd")
this is a code to a problem that needs you to xor a range of numbers ex: 2,6 = 2^3^4^5^6 and check if the ans is odd or even
this is my approach and it doesnt work with a huge input
for i in range(int(input())):
a,b = map(int,input().split())
ans=0
for j in range(a,b+1):
ans = ans^j
if ans%2==0:
print("Even")
else:print("Odd")
ping me is somebody responds 
they define it and explain it in detail as part of divide and conquer approaches. they do assume that you have seen recursion at least in coding, but they explain it enough from scratch that I am a bit surprised they didn't discuss hanoi. for example, they cover fibonacci from scratch
oh thanks, it's all good. I've got it covered no problem. I was just wondering if CLRS uses it as a test case for a more advanced analysis, but apparently not
Fibonacci actually has interesting computational aspects though
There is the naive exponential approach, O(n) versions and O(log n) versions
well hanoi also does I think. there are many approaches to solving the problem
you can find entire books dedicated to the topic
no there isn't?
not for the usual 3 peg example at least
in that case there is only one option if you want to follow the optimal path
you can? 
for fibonacci the approaches span several different topics, which is very useful for a textbook
recursion, memoization, dp, exponentiation by squaring on matrices
probably more
well, there is the fact that there are many interesting variations, too. but there are different algorithms for solving the original problem too. there are recursive and iterative methods with several variations
the numbers also pop up in analysis of other algorithms
but all are the same complexity-wise
yes, sure, here is a book by a maths professor at LMU in Germany https://link.springer.com/book/10.1007/978-3-0348-0237-6
yes, but the algorithms are different, with different tradeoffs. I think it's an interesting case study that has produced a lot of research, at least from the kind of publications you can find on it. maybe it's just not such a good or central one for a textbook, more of a specialized problem
ok but this book..
Thorough presentation of the historical development
Numerous attractive figures and original photos
well, it's a proper mathematics book
I have read parts of it
sure ¯_(ツ)_/¯
that doesn't mean it's that interesting and multifaced from a cs point of view
I really struggle to see how a book having attractive figures and photos detracts from its mathematical interest. look at any book by raymond smullyan with its nice illustrations
I stumbled upon a binary solution while working on it and I found it interesting, at least
it has neat mathematical properities, but that doesn't necessarily translate to much in terms of cs topics
yes, that's certainly possible. it's also more of a thing for recreational math, so probably that's why they don't introduce it in CLRS. but it does seem to lend itself to some CS research work. the wikipedia page links to about 5 recent proper reserach articles. but certainly not such a central topic
"""Grouping bits by chunks in O(n)"""
def get_binstr(s: str) -> str:
"""Bit string representation of Unicode string"""
return "".join(bin(byte)[2:].zfill(8) for byte in bytes([ord(c) for c in s]))
def group_bits(binstr: str, chunk_size: int) -> str:
"""Returns bitstring representation with each bit moved to form evenly chunks"""
bitlst = list(binstr)
j = -1 # sub index
for i in range(len(bitlst) - 1):
if bitlst[i] != bitlst[i + 1]:
if j == -1 or (j + 1) % chunk_size == 0:
j = i
continue
bitlst[j + 1], bitlst[i + 1] = bitlst[i + 1], bitlst[j + 1]
j += 1
return "".join(bitlst)
# TODO
# def reconstruct_bits(binstr:str, chunk_size:int) -> str:
#
if __name__ == "__main__":
size = int(input("\nInsert chunk size >>").strip())
inp_str = input("\nInput string >>").strip()
BIN_STR = get_binstr(inp_str)
print(f"\noriginal bitstring: {BIN_STR}")
print(f"\nnew: {group_bits(BIN_STR, size)}\n")
Is anyone able to reverse this bit conversion?
`salutationsDict = {'de':'Keine Angabe', 'de':'Frau', 'de':'Mann', 'en':'not specified', 'en':'mrs', 'en':'mr'}
germanList = []
englishList = []
for k,v in salutationsDict.items():
if k == 'de':
germanList.append(v)
else:
englishList = [k]
print(germanList)`
Hello guys,
I loop over the key and the value of a dictionary. Then I would like to put all the keys that have 'de' into a list and output it. However, only the last value is always output.
I want to ask how can you compute n(n-1) / 2 % 10^9 + 7 for some large integer n.
What if n is less than 10^9 + 7 but the result of n(n-1) is larger than a 32 bit integer? The modular multiplication ((a % m) * (b % m)) % m basically did nothing in shrinking the number here?
Also, I am not very sure how do you do a modular division for the /2 part
could just check which of n or n-1 is even and halve that
do //2 because n(n-1) is guaranteed to be even
there is no such thing as 32bit int in python
integers have dynamic arbitrary large size, so you never get any kind of overflow
if you want to simulate C behaviour, then you have to do %2**32 or something like that after every operation
(optionally you can create class that does it for you)
I know about the python integers thing but how about ppl doing this in c? Basically I want to know whether the only way to solve this is using longer integers
How about a 64 bit integer?
If it's even bigger you need a BigInt type.
Anyone have a Idea?
.
There is also binary multiplication that uses only additions so you will fit in the int32, but here it is much easier and faster to just use int64
In general, when you do some division a / b mod m and both a and b get very big so you want to mod first, you instead replace it with an equivalent multiplication a * c mod m.
Here, c is the "modular multiplicative inverse" of b with respect to the modulus m. It satisfies bc = 1 mod m.
To find c, you can use the extended euclidean algorithm. If m is a prime (like 10^9+7, 10^9+9, 998244353, etc.), then you can just use c = pow(b, m-2, m) (by Fermat's little theorem)
Any Python library for diagramming nodes, naming the nodes, and naming their links?
Is networkx the most popular graph library?
probably
(I never really used it though, I've always just written my own stuff)
thanks for the answer!
different question: does anyone know if UML is enough to define SysML, at least, systems, interfaces, and processes?
hi guy i m new in ml can you just me difference between weights,parameter and hyperp... in simple words it making me more confuse on internet...
hello guys, so i was trying to apply kruskal algorithm to find the minimum spanning tree, but im not sure if i understand whats a spanning tree well, anyway i did it by hand than tried to apply into code. I had this initial graph and result.
So is the second image truly a spanning tree?
Obs.: i didn't add the weight because i'm in doubt more about the spanning tree concept itself than the algorithm
a spanning tree is just a tree that connects all the nodes
so yes the right thing is a spanning tree
awesome! ty fenix
Hello, i'm doing currently bubble sort on multiprocessing and im curious is there better way to merge arrays. So it looks like this im opening a n of proccesses and it returns array of n sorted arrays (n is num of processes) and i have to merge them
this is my solution
merged_list = []
left = 0
right = 0
while left < len(res) and right < len(l2):
if res[left] < l2[right]:
merged_list.append(res[left])
left += 1
else:
merged_list.append(l2[right])
right += 1
merged_list.extend(res[left:])
merged_list.extend(l2[right:])
return merged_list
def merge_arrays(results):
while len(results) > 1:
res1 = results.pop(0)
res2 = results.pop(0)
merged = merge_func(res1, res2)
results.append(merged)
return results[0]```
also tried this but its not working well on big arrays
def merge_sorted_arrays(arrays):
result = []
pointers = [0] * len(arrays)
while True:
min_val = float('inf')
min_idx = -1
for i, array in enumerate(arrays):
if pointers[i] < len(array) and array[pointers[i]] < min_val:
min_val = array[pointers[i]]
min_idx = i
if min_idx == -1:
break
result.append(min_val)
pointers[min_idx] += 1
return result```
my teacher said i should optimize it and said smth about merge sort but only merge part but i think the first algo is a some way of merging from merge sort
I'm learning hashmaps for the first time and I'm running into an issue with this anagram checker. If the two strings are cacc and acca then it reads true. This means I need to remove a value from the hashmap after I check it. del prevValues[ord(t[i])] however it deletes every instance of that value
which results in this
prevValues.pop(ord(t[i]), i) it looks like pop does the same or I am analyzing the issue wrong
I am so close
dict keys are unique, you can't have multiples
but you could instead have a key that maps to an integer where you keep the count
to be honest I don't understand hashmaps at all I think I need to get the neetcode course
how deeply do you need to understand it?
at high level it's just a mapping, it maps keys to values
what do you mean? enough to be able to use it?
it you just need to know roughly what it does that's pretty easy
if you want to dig into the details of exactly how hash tables work it gets more complicated
ok I think it's best I gain a deeper understanding just to be thorough
Hi guys, can anyone help me with this? I don't want to have a space after the 6.
Creating a Python string with your variables using the + operator can be difficult to write and read. F-strings (format-strings) make it easy to insert values into a string. If you put an f in front of the first quote, you can then put Python expressions between curly braces in the string.
>>> snake = "pythons"
>>> number = 21
>>> f"There are {number * 2} {snake} on the plane."
"There are 42 pythons on the plane."
Note that even when you include an expression that isn't a string, like number * 2, Python will convert it to a string for you.
def func_a():
if a:
if b:
print(yes)def func_b():
if a and b:
print(yes)
It seems like func_a is the same as func b but func_b looks better. However, for debugging purposes in my particular case, having nested ifs makes it easier to follow the code. Would it look bad to keep the nested ifs? does it hurt code maintainability?
func_b indeed looks better, but func_a is not that bad either
i dont think making nested ifs is bad (if you nest them 2-3 times)
nesting them 10 times is of course unreadable, and in this case you should prefer func_b approach
and if you think a is complex enough to be separate from b, then separate it with a variable. That way you can both "comment" on the meaning of the condition with a variable name, and simplify the debugging by allowing to see the intermediate result
def func_c():
safe_to_access = 0 <= i < n and 0 <= j < m
if safe_to_access and board[i][j] = '.':
...
but you can do whatever, strongly preferring one is nitpicking imo
Thank you guys. Yeah, in some cases it is complex enough (a is a recursive function that may call itself n times).
3 would be a big red flag for me
codefroces blog's looks pretty similar to reddit lol
instead of commas, use +
!e
a = "fiery"
b = "stickie"
c = "fenix"
print("CASE 1", a,b)
print("CASE 2 "+a+c)```
@olive badge :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | CASE 1 fiery stickie
002 | CASE 2 fieryfenix
The main drawback of using nested if statements (func_a) is that it creates an unnecessary amount of indentation.
If your issue is that a and b are complicated expressions and not nice to have as a one liner, then try moving some of that logic to before the first if statement.
In that case, func_b makes sense to me. But what if you needed else’s? Would be easy to imagine needing an else for both conditions that might be different
I wanted to access data from this dictionary
students_dict = {
"Student1": "ID001",
"Student2": "ID002",
"Student3": "ID003",
"Student4": "ID004",
"Student5": "ID005",
"Student6": "ID006",
"Student7": "ID007"
} how can I do that?
what do you mean by data
the student part or the ID00X part
btw this channel is for dsa
ill answer you in #ot0-psvm’s-eternal-disapproval
yeah, this is a case that can make things get very complicated very quickly
I've had to unnest a jungle of 3-4 level if-elses to even understand what logic a coworker tried to write
are you supposed to use imported modules on leetcode?
I'm running into an issue where my result is different than leetcodes for the output, when I do research one of the solutions is using
from collections import Counter
something feels off about using a module to problem solve.
stdlib libraries are usually fine since they're built into python
Counter isn't very hard to implement by hand anyways so it's not that big of an advantage
Thank you
from collections import defaultdict
class Solution(object):
def groupAnagrams(self, strs):
res = defaultdict(list) #mapping count to list of anagrams
for s in strs:
count = [0] * 26 # a-z
for c in s:
count[ord(c) - ord("a")] += 1
res[tuple(count)].append(s)
return res.values()
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
solution_instance = Solution()
strs = ["eat","tea","tan"]
result = solution_instance.groupAnagrams(strs)
print(result)
this is going to be a dumb question but
res[tuple(count)].append(s)
is this where the code matches the strings to the count?
len(prevNums) - 1 is 2 which is out of the bounds of the prevNums array
Id try printing out prevNums before/after the for loops and see how it changes
for whatever reason leetcode doesn't allow that
Oh actually it might have some error bc you’re trying to store an int as the name of the key which I don’t think can work for dictionaries
I’m not sure what nums you’re inputting
you're talking about indices, but you're using a map?
table maybe? no idea how this thing works but I am trying to use it
cracking the coding interview is coming soon hopefully that will explain it a bit better, at least provide more direction
I'm sure it will go into more depth than I can understand though
oh I am a dumbass this isn't a prevNums[0-7] the indicies are exactly the nums
What is the best data video to learn easily
can i ask questions here on ADT's?
what's your question?
i'd like to make an array implementation in python using list for ADT's
so you want to make an array implementation in Python using list
Yes
I wrote the linked implemenation
i want a array too now
and what kind of help do you need?
the most basic thing you need to do is decide if this is a static or a dynamic array
what would be the difference?
Is one hardcoded and one isn't or?
I have like a testcode that i need to write it on if that helps?
it needs to be a response to it in away
yes, you can show it to me
static array has a fixed number of indices, dynamic array can be expanded or shortened
okay one sec!
if name == "main":
s = MyStack()
print(s.isEmpty())
print(s.getTop()[1])
print(s.pop()[1])
print(s.push(2))
print(s.push(4))
print(s.isEmpty())
print(s.pop()[0])
s.push(5)
print(s.save())
s.load(['a','b','c'])
print(s.save())
print(s.pop()[0])
print(s.save())
print(s.getTop()[0])
print(s.save())
thats it
would you like to see my code for the linked part?
ok, but they want you to implement a stack, not an array
you are right
an array stack
so they don't want you to implement the array from scratch? they just want you to implement a stack using a list?
yeah
ok, then it's very easy
really?
yes, the stack basically is just the list
so what do ido?
all you need to do is put the list inside a class and define push with append, pop with remove last item, top with return last item, and is empty with return len(l) == 0
however, I am not sure what they mean by getTop()[1] instad of just getTop(), and I don't know what they mean by save()
do you have more instructions for it?
class Node:
def __init__(self, data):
self.data = data
self.next = None
class MyStack:
def __init__(self):
self.top = None
def isEmpty(self):
return not self.top
def getTop(self):
if self.isEmpty():
return None, False
else:
return self.top.data, True
def pop(self):
if self.isEmpty():
return None, False
else:
data = self.top.data
self.top = self.top.next
return data, True
def push(self, value):
new_node = Node(value)
new_node.next = self.top
self.top = new_node
return True
def save(self):
stack_data = []
current = self.top
while current:
stack_data.append(current.data)
current = current.next
return list(reversed(stack_data))
def load(self, stack_data):
self.top = None
for value in stack_data:
self.push(value)
this is my code for linked
maybe u can understand using this?
save returns everything
ok makes sense. sorry I don't have more time right now, but it's very simple. just create a class. initialize with self.stack = [] and then pop returns a tuple like (True, item) by accessing the last item in the stack, or if the length of the list is 0, it gives you (False, None)
push appends to the list, etc.
can't i reuse my code?
and change the names
no, it would be very different code
define them differently
would you mind continiuing this when have free time?
sometime this week or so
yes, you can reuse the template, but the different methods and init woud be defined differently
yes, I may be free, but lots of other people can help later
try to do it, it's not too hard, I think you can do it
i will try and let you know bro
thank you
hey guys do you think atcoder begginer contest are actually for begginers?
Hi, I dont currently really know where to put my question. Is here anyone who uses and builds actionaz automation scripting program? I have a little puzzle to build, can´t figure, how to build 2 script working parralel.
what about in #1035199133436354600
any interesting theoretical treatments of the subject of discoverability?
def majorityElement(self, nums):
numsTable = {}
for i in range(len(nums)):
numsTable[nums[i]] = 1
for i in range(len(nums)):
numsTable[nums[i]] += 1
return max(numsTable, key=numsTable.get)``` Is this O(n) or O(n^2)
the former
oh ok is there a way to avoid two for loops here?
just doing += 1 does not work and I am having a hard time checking for nil
Write an if statement to check if the number is in keys
sure
https://github.com/desultory/PyCPIO/tree/main/src/pycpio
i just got started making this, does anyone know if im doing the CPIO structure stuff wrong?
i want to get to making it write and im sorta referencing this but it may not be well designed: https://github.com/torvalds/linux/blob/090472ed9c922e699dc61dd601a9b376a64f4390/usr/gen_init_cpio.c#L173-L174
usr/gen_init_cpio.c lines 173 to 174
3, /* major */
1, /* minor */```
it seems to use that same major/minor on all entries, it also seems to start the inode at like 700, just kinda does weird thigns
That is the beauty of programming, nothing makes sense, while making all the sense in the world, programmatically.
^
there is a neat O(1) memory approach for this
The Boyer–Moore majority vote algorithm is an algorithm for finding the majority of a sequence of elements using linear time and a constant number of words of memory. It is named after Robert S. Boyer and J Strother Moore, who published it in 1981, and is a prototypical example of a streaming algorithm.
In its simplest form, the algorithm finds ...
In the n stairs problem, the solution can be obtained by the fibonacci sequence, which is an application of the addition principle? If so how to prove that the 2 sets (combinations of (n-1) and combinations of (n-2)) are disjoint.
I have very little idea what any of this means what should I do to better understand it?
implementing it
and i know data structures and algos are language agnostic
but i am reading a book in python
i believe CTCI is in java
it is
I have solved 2-3 problems using a hashtable on my own and 3 more after looking at the solution
so I can sorta use it, are you not supposed to use integers as keys?
are you talking about your majority element code
no I'm talking about hashtables
oh yea
maybe?
oh yes that and another similar problem that I solved today
a dictionary key has to be inmutable iirc
so integers work
pub will probably correct me if i'm wrong
Maybe try to write your own implementation of it
And don't use the built in
why would a int change over time? also I thought iirc was a programming term for a second
if i recall correctly
Hash tables use hashes to refer to values
Python dictionaries are a kind of a hash table where the hashes of the keys are used, so the keys must be hashable
Any key will do as long as it is hashable
Even keys of mutable types
ok thanks
tl;dr: one of the simplest types of hash table is:
to add an element x to the hash table
- compute
hash(x)to get an integerh - use
hto pick a bucket to put this element in - put
xin that bucket
to check if an element x is in the hash table
- compute
hash(x)to get an integerh - use
hto find the bucket this element must be in - look at the elements in the bucket to see if there is any equal to
x- if there is, the element is right there, answer is true
- if there isn't, the element is not in the table, answer is false
class Solution(object):
def replaceElements(self, arr):
rightMax = -1
for i in range(len(arr)-1,-1,-1):
newMax = max(rightMax, arr[i])
arr[i] = rightMax
rightMax = newMax
return arr
"""
:type arr: List[int]
:rtype: List[int]
"""
```
this problem is making me bug out
maybe i'm just tired
i just don't understand the point of iterating through the list backwards
It's a recursive pattern @old rover . The maximum element to the right of some position is the maximum between the element on the right, and the maximum of all the elements to the right of that position.
So by going backwards you only have to go through the list once
Because you use the result of each position to find the result of the next position to the left
thank you, i will re-read this tomorrow
It’s not easy being green
nope, but that won't stop me from trying
hey guys, quick performance problem. i'm learning dynamic programming and wanted some easy practice. the problem i picked: https://cses.fi/problemset/task/1633/
i solved it in linear time and even optimized to constant space (https://paste.pythondiscord.com/ZFZQ), but i get TLE starting from the case n = 654321. i came across this sol, linear time and linear space, and it passes the problem, running ~4-5x faster at n = 1 mil:```py
dp = [1]
for i in range(int(input())):
dp.append(sum(dp[-6:]) % (10**9 + 7))
print(dp[-1])
our logic seems equivalent. where's my bottleneck? thank you for the help!
the part where it adds 6 numbers in one sum() is probably 6 times faster than using += 6 times
i can't profile it accurately by sight, but i'm sure it's just from having that much less things to do, not because there's a particular part in your code that secretly takes ages
it might actually just be cpython being too slow
it's not less things to do, but it's avoiding doing work in python code
this seems to be fine runtime-wise
combos_n = [0] * 7
combos_n[0] = 1
for i in range(1, n + 1):
curr = i % 7
combos_n[curr] = 0
combos_n[curr] = sum(combos_n) % MODULUS
print(combos_n[n % 7])
sum is written in C
so this is a case of pure python code just being too slow
how do i come up with brute force solutions faster?
i know you’re supposed to do brute force and then optimize
actually
i was able to say the brute force algorithm in my head before i tried to implement it in code yesterday
idk about supposed to
with experience you can just figure out the optimal solution immediately in some cases
sometimes if you have no clue what to do brute force + optimization might be a good idea, but sometimes it's not feasible to just incrementally improve a naive solution
i see thanks
i have a problem with translating what’s in my head to code
maybe it’s a sign to brush up on the fundamentals
the boring answer is just practice
yes
pick some simpleish problem, figure out solution and implement in code
rinse and repeat
where are the discord backticks on mobile?
so i can type code from my phone
oh ok
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
for i in range(len(arr)):
max_value = -1
for j in range(i+1, len(arr)):
max_value = max(max_value, arr[j])
arr[i] = max_value
return arr
so i did this for this problem
it timed out lol
probably due to time complexity reasons
ur just doing max(max_value,arr[i:])```
||py class Solution: def replaceElements(self, arr: List[int]) -> List[int]: n = len(arr) nums = [-1]*n ans=-1 for i in range(n-1,-1,-1): nums[i] = ans ans = max(arr[i],ans) # print(nums) return nums||
huh
hint: go right to left
yep that’s one of the hints on leetcode
i didn’t even realize there were hints on leetxode before
Hello is there any algorithm for merging a n of sorted sub arrays ?
i only did this one but i want to know if there any way of optimize this code or do i can do it better
arrays is a list of sorted sublists
def merge_sorted_arrays(arrays):
if not arrays:
return []
merged_list = arrays.pop(0)
while len(arrays) > 0:
l2 = arrays.pop(0)
merged = []
left, right = 0, 0
while left < len(merged_list) and right < len(l2):
if merged_list[left] < l2[right]:
merged.append(merged_list[left])
left += 1
else:
merged.append(l2[right])
right += 1
merged.extend(merged_list[left:])
merged.extend(l2[right:])
merged_list = merged
return merged_list
You could pop the head of each list, and insert the min. Then pop the value from whichever list had the min, and repeat.
so u mean to take min from all lists in one time and just add 1 to index ?
The lists are already sorted right?
yup
So taking the first element is taking the min.
Then you just need to sort the first elements /take the min of the first elements
so how can i take min from all lists in same iteration ?
There are many ways. You could sort the lists by the head value. You could pop the first values and sort. You could take the min of the first values.
Okay i get the idea, so i will take the min of first elements in all lists then pop this element from for example first sublist and after this ill again take min from all list but now on 0 index there will be a 2nd element from this 1st list ?
[0,5,7] , [2,6,1], [8,10,12] -> min val 0
[5,7] , [2,6,1],[8,10,12] -> min val 2
and do it until all lists are empty or there is one list left, and if there is one list left just add all elements into this merged_list
It will look like this ?
l = [[1, 3, 5], [2, 4, 6], [0, 7, 8]]
merged_list = []
while True:
min_val = float('inf')
list_idx = -1
for i in range(len(l)):
if l[i] and l[i][0] < min_val:
min_val = l[i][0]
list_idx = i
if list_idx != -1:
merged_list.append(min_val)
l[list_idx].pop(0)
else:
break
print(merged_list)
Yes, exactly
how it would like on large datasets like 100000 divided into 8 sublists
Complexity analysis is an exercise left to the reader 🙂
I'm doing multiprocessing project for py lessons when im testing bubble sort with multiprocessing so im splitting a lists into number of processes after bubble sort on every list this im getting exacly a list of number of processes sorted sublists it can be like 100000 elements divided into sublists just in case it will change something in approach 🙂
Okay ill get it done , thanks for help
can someone tell what i did wrong
also if you can't tell i am trying to create a atom in python
i'm looking at some code for containsDuplicate
and i noticed that i is 0
but i'm confused as to how?
i also noticed it stays as 0 throughout
me to i am confused as well
maybe i'm just having a brainfart lol
idk waht to do next
actually i think it's intentionally placed at 0
so then j goes through the rest of the list
im new to python this is my 5th project actualy
that's good
class Solution(object):
def containsDuplicate(self, nums):
n = len(nums)
for i in range(n-1):
print(i)
for j in range(i+1, n):
print(j)
if nums[i] == nums[j]:
return True
return False
solution_instance = Solution()
nums = [99, 100]
result = solution_instance.containsDuplicate(nums)
ok so i think i understand this now
this will keep i at 0
while moving j forwards
peace out
guys i need help with designing an algorithm with the least possible complexity
i tried but i always get O(n^2), i cant get to O(n)
it wants me do encryp a message as follow:
for each number its value is added to next bigger number that follows its location
if there's no such number, keep that number without a change
example:
[7, 4, 5, 10, 2, 1, 7, 8, 2] result is [17, 9, 15, 10, 9, 8, 15, 8, 2]
function encode_message(input_numbers):
n = length(input_numbers)
result = new array of size n
for i from 1 to n:
current_number = input_numbers[i-1]
# Initialize next_index to the index after i
next_index = i + 1
# Find the next bigger number
while next_index <= n and input_numbers[next_index-1] <= current_number:
next_index = next_index + 1
# Check if a next bigger number is found
if next_index <= n:
result[i-1] = current_number + input_numbers[next_index-1]
else:
result[i-1] = current_number
return result
that's my pseudocode for the algo but isnt that brute-force that's why i get O(n^2) ? if so then what should i do :(
my intuition says to go in reverse and use a stack
that makes a lot of sense and i think that will be O(n) but i never did anything with stack so idk how to do it sadly :(
it's basically a linked list where you can either append or consume the end node
yea i understand what a stack is but i dont know how to type an algorithm/pseudocode for it
oh just use a deque
so from collections import deque
create a deque with stack = deque()
you can then do either stack.append() or stack.pop()
kinda screams monotonic stack to me
mhm thank you but it wants me before typing tha actual code using what you just said, it wants me to like type pseudocode so i can just say
stack = an empty stack
stuff like that
can i send you the question in dms if that's okay?
i.e. keep a stack as you go, as soon as you find something bigger than the thing on top of the stack, pop from the stack and process that element
uhh sure dm me
yea i think i need to do it with a stack for it to be O(n)
i understand what a stack is but i never typed pseudocode with it so idk how to do it
# add 2 to stack, go to next
2, 1, 3, 1
^
stack = []
# 1 is smaller, just add to stack and go to next
2, 1, 3, 1
^
stack = [2]
# 3 is bigger than 1, pop and handle
2, 1, 3, 1
^
stack = [2, 1]
# 3 is bigger than 2, pop and handle
2, 4, 3, 1
^
stack = [2]
# add 3 to stack and go to next
5, 4, 3, 1
^
stack = []
# 1 not bigger than 3, add to stack, advance
5, 4, 3, 1
^
stack = [3]
# done
5, 4, 3, 1
^
stack = [3, 1]
I mean, the point of pseudocode is to just be something that gets the point across
and you can kinda handwave the unimportant details
i see thank you for that great explanation
will try to do pseudocode with that
okay now i get everything here except why are we going in reverse? is it because the stack is last in last out?
Even in pseudo code, we’ll write actual code where it’s just simpler to do so. But perhaps I’d write mystack = stack(), and mystack.push() and mystack.pop() as pseudocode, where the stack implementation doesn’t matter.
Hi!
Can anyone help me with this question? I'm having a lot of trouble to solve it.
https://discord.com/channels/267624335836053506/1178783779473600654
this is not going in reverse
oh you mean the stack
the stack we maintain will always have items in decreasing order, which is the key to do this efficiently
in particular, the stack contains all the elements that haven't seen a larger element yet
so as soon as you get something larger you can start pairing it up with the elements it's the next largest elements for
Also it should be noted that my example was cheating a tad, I did not store enough info to know what number to modify
but if you store the index as well you have this info, so easy to fix
I just wanted to keep the example simple
Hey guys,
I'm not quite sure if this is the right group to ask this but I am in need of a Python coder that is experienced in trading bots/ algorithmic trading. Please send me a DM if you'd like to discuss a potential job.
hi, we don't do recruitment here
yes! thank you so much for the answer. i had a suspicion it was due to sum directly implemented in C, too. and i also completely forgot that my for loop is just sum(combos_n) since i've made combos_n store the last six computations already lmao
@runic tinsel thank you for the thoughts too!
how do you do [:] for dictionaries?
.copy()
https://github.com/desultory/PyCPIO/tree/main
could anyone critique this? im also not 100% sure im adhering to the CPIO format
Hello, I'm trying to solve this problem on LeetCode however I'm getting RTE. Would appreciate any help
public:
bool search(vector<int>& nums, int target) {
int low = 0;
int high = nums.size()-1;
while(low<=high){
int mid = low + (high-low)/2;
if(nums[mid]==target)
return true;
if(nums[low] == nums[mid] && nums[mid] == nums[high]){
low++; high--;
}
//check if left half is sorted
if(nums[low]<=nums[mid]){
if(nums[low]<=target && target<nums[mid])
high = mid-1;
else
low = mid+1;
} else { //check if right half is sorted
if(nums[mid]<target && target<=nums[high])
low = mid+1;
else
high = mid-1;
}
}
return false;
}
};```
class Solution(object):
def containsDuplicate(self, nums):
n = len(nums)
for i in range(n):
print(i)
for j in range(i+1, n):
print(j)
if nums[i] == nums[j]:
return True
return False
class Solution(object):
def containsDuplicate(self, nums):
n = len(nums)
for i in range(n-1):
print(i)
for j in range(i+1, n):
print(j)
if nums[i] == nums[j]:
return True
return False
solution_instance = Solution()
nums = [99, 100]
result = solution_instance.containsDuplicate(nums)
print(result)
hmm
why the -1
Once you reach the last element, there’s nothing to compare it to. You’re comparing the i th element to the elements from i+1 to n (the j loop)… so the very last check is i=n-2 and j=n-1
i think i need to brush up on my fundamentals
this is not doing me any good
back to automating the boring stuff i go lol
I don’t think it’s a fundamentals thing: it’s a debugging thing
hm
i look at the fundamentals and i think i get them but i see a leetcode easy and i'm stumped
Learn to add print statements and inspect the variables, that’s the biggest problem most new engineers have: they stare at the code to understand it
I rarely use a debugger. A few print statements usually are enough
But a debugger is good too
there is also python tutor which is a code visualizer
not sure why it's called that and not python visualizer but yeah
In this case, i recognize the general pattern: you have one loop over i, then a loop over j. Since you’re comparing the element at i to the elements at j, there’s no reason to check the last element
i end up coming with the brute force solution in my head, but then i can't translate it to code
it's so frustrating
it's like having a sentence in your head but being unable to speak it
Yah, i hear you. A lot of it is pattern recognition… my advice is to stew on this problem for a week. Think about it, walk through it, take a break, etc. try the Feynman method: try to explain it, not just understand it
bc i don't want to memorize solutions, then i get nothing out of it i won't actually learn
but i feel like a part of it is memorization
Yup, my point wasn’t to memorize it, but to truly understand it and why it works. That’s the Feynman method: in short: you don’t really know it if you can’t explain it
i think you'd be proud
i just solved a leetcode easy on my own
well
technically it was a similar question to contains sum 1
it was contains sum 2
Can you solve this real interview question? Contains Duplicate II - Given an integer array nums and an integer k, return true if there are two distinct indices i and j in the array such that nums[i] == nums[j] and abs(i - j) <= k.
Example 1:
Input: nums = [1,2,3,1], k = 3
Output: true
Example 2:
Input: nums = [1,0,1,1], k = 1
Output: t...
class Solution(object):
def containsNearbyDuplicate(self, nums, k):
n = len(nums)
for i in range(n-1):
for j in range(i+1, n):
if nums[i] == nums[j]:
if abs(i-j) <= k:
return True
return False
"""
:type nums: List[int]
:type k: int
:rtype: bool
"""
i wrote the psuedocode in my notebook
Nice, that’s exactly it… every problem will eventually seem similar to something else you’ve done!
edit: caught my mistake, it wasn't asking for abs(nums[i] - nums[j]) <=k, it was asking for abs(i - j) <=k. major difference
class Solution(object):
def minimumOperations(self, nums):
n = len(nums)
for idx, num in enumerate(nums):
if nums[idx] == 0:
nums.pop(idx)
min_number = min(nums)
this unfortunately is all i was able to come up with
Can you solve this real interview question? Make Array Zero by Subtracting Equal Amounts - You are given a non-negative integer array nums. In one operation, you must:
- Choose a positive integer x such that x is less than or equal to the smallest non-zero element in nums.
- Subtract x from every positive element in nums.
Return the minimum ...
identifying the minimum number
all i did was identify the number that's greater than zero
in the list
am I dumb or is the answer not just len(set(nums) - {0})?
it is, but i wanted to come up with a brute force solution
why would you want bruteforce if you can see a better solution? 
well
(a better solution that is also easier)
i thought it would be a good practice to come up with brute force solutions firsst
and then optimize from there
the brute force here is just...annoying
but i think doing it would help me learn
you're probably better off doing it on a task where you don't know a better way
try using pseudocode first, that might help
simulation seems pretty straightforward
subtract min of array
remove zeroes
over and over and over
that is the brute-force
O(n² + suffering)
though maybe suffering is constant
(in my defense I didn't set out to make that joke, it just happened)
- find the minimum value in the list by removing all zeroes and getting the minimum number from there
- iterate through the list
- subtract the minimum value from each number in the list
- increase the countOperations by 1 for each time a number in the list is zero
- update the minimum value
- return the countOperations
and from what i can see
it seems like the code from what i did above does finds the minimum the first pass
Hello everyone
I had a problem with my python
Take a look of it
When i run the code it doesn't work
Like the same i saw
it is input, not Inputs
Oh ok i will try
btw it literally said you that
Thank dude @lean walrus
how many easy problems should it take you to be able to solve a medium problem
That’s unanswerable. What medium is giving you difficulty?
K most common element in list
List is all internet
So like if k is 3 the top 3 most common
No idea how to only use K numbers
I assume you want problem solving advice, not a solution: try to reframe the question as something non coding. How would you do this with a room full of numbered blocks?
Don’t try to be clever in the first pass, just come up with a brute force or naive solution.
ok thanks 🙂
if you just add numbers to a hashtable without using a hashcode is it even a hashtable?
I don't know if that makes sense
do you mean treat the numbers themselves as their hashcode
if so then thats already almost the case in python, ints hash to themselves
i'd like to get into DSA
what books should I look for? if there's one with a gentle introduction i'd love to read it
nvm there's some on the pinned
ref = arr[0]
i=0
while i<len(arr):
if arr[i]!=ref:
return False
i+=1
return True
print(all_equal([1,0,0,0,0]))
```
line 8 seems to be the issue. it is something to do with the return keyword, if i just print "True", it seems to be working fine
whats wrong with it?
It says index out of range
!e it doesn't?
def all_equal(arr):
ref = arr[0]
i=0
while i<len(arr):
if arr[i]!=ref:
return False
i+=1
return True
print(all_equal([1,0,0,0,0]))
@solemn moss :white_check_mark: Your 3.12 eval job has completed with return code 0.
False
you dont handle the case of arr being empty
hi
Does anyone know the difference of a condition and a conditional? Have an exam and need help asap
Please refrain from spamming this channel with unrelated messages
class Solution(object):
def groupAnagrams(self, strs):
charCounter = {}
for s in strs:
for c in s:
charCounter[c] = 1 + charCounter.get(c, 0)
print(charCounter)
"""
input: strs = ["eat","tea","tan","ate","nat","bat"]
output: [["bat"],["nat","tan"],["ate","eat","tea"]]
1. start with a blank dictionary
2. iterate through the list
3. count each character that appears through the list
4. if the character count is the same, append the strings together in a list
5. return the strings
"""
"""
:type strs: List[str]
:rtype: List[List[str]]
"""
so this is weird
i'm getting {u'a': 6, u'b': 1, u'e': 3, u't': 6, u'n': 2}
what is u'?
unicode?
i can't for the life of me do this
https://docs.python.org/3/reference/lexical_analysis.html#grammar-token-python-grammar-stringprefix: "New in version 3.3: Support for the unicode legacy literal (u'value') was reintroduced to simplify the maintenance of dual Python 2.x and 3.x codebases. See PEP 414 for more information."
ooh
But, what version of python are you using?
You should be
Oh, python2?
yes my attention to detail... needs more attention
whoopsie
That's just terrible ergonomics by leetcode. They should at least label "python" as Python2
yeah i didn't realize
there's a neat way of doing this btw
!e
from itertools import groupby
def all_equal(seq):
g = groupby(seq)
return next(g, True) and not next(g, False)
for item in [[], [1], [1, 2], [1, 1], [1, 2, 1]]:
print(f'all_equal({item}) = {all_equal(item)}')
@naive oak :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | all_equal([]) = True
002 | all_equal([1]) = True
003 | all_equal([1, 2]) = False
004 | all_equal([1, 1]) = True
005 | all_equal([1, 2, 1]) = False
len(set(seq)) <= 1 is quite tempting
yo can somoee explain to me the usage of array in numpy library
shortcircuit tho
this one is kinda neat
not any(x != y for x, y in pairwise(seq))
or I guess all(x == y ...)
though the first reads better to me
(and no-one mention ||nan|| pls)
i would argue that [nan, nan] contains two different values (even if nan is nan)
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
numberCounter = {}
for n in nums:
numberCounter[n] = 1 + numberCounter.get(n, 0)
for key, value in numberCounter.items():
if value >= 2:
return True
return False
```
@modern gulch i wrote my own solution to contains duplicate 
by throwing a dictionary at it
is that considered brute force?
I don't know if I'd use the term brute force, but this is inefficient because: you keep going after you get your first duplicate.
brute force would just be the O(n^2) solution
But, you're just starting out, and this is a fine first pass at the problem.
at least i'm able to implement something
And there's other problems where you'd need something like this pattern. Yah, feel good about it.
But, consider how you could be more efficient by stopping as soon as you hit a duplicate.
so the neetcode solution for this uses a set. so i'd have to think of the tradeoffs between a set and a dictionary?
I personally think the set solution is a bit of a cheat. It's a fine python answer, but doesn't really teach you about algorithms.
Sorry, ignore what I just said... there's a "quick" solution using a set
But, ignore that...
In your solution: Why are you keeping a count?
because if the number occurs twice, i can check the value of the dictionary and return True if a duplicate occurs and false if it doesn't
my bad
why use a dictionary if you can return true as soon as the count gets to 2?
class Solution:
def containsDuplicate(self, nums: List[int]) -> bool:
numberCounter = {}
for n in nums:
numberCounter[n] = 1 + numberCounter.get(n, 0)
return True if numberCounter[n] >= 2 else False
but that fails [0,4,5,0,3,6]
hmmmm
i don't know why that fails
actually
i might
what if it's seeing a value that's not actually greater than 2
you're only checking the occurrences of the last element in nums
the value of n after the loop ends is the last element in the list
uhhh
isn't that what i want to do tho? count every value in the list and then stop?
you want to check the occurrences of every element, not just the last number in the list
i don't get it
your last line isn't indented
Think of it this way: you have a notebook and a pen. You go through a line of people one by one: and want to stop as soon as you find someone with the SAME name as one you’ve already visited. How would you instruct a 5th grader to do this?
go through the list of names, stop when they see the same name twice
how would a 5th grader remember what names they've seen? they have a bad memory
that's true.
idk then
maybe you would instruct them to look backwards from where they are and see if they find the word again
that way they only have to remember one word at a time
i've seen this iterating backwards through an array solution before
psm's question isn't just a theoretical... it's a hint: the 5th grader has a blank notebook and a pen. There's a line of people, and the 5th grader has very bad memory. How do you do it?
forget about code, python, etc.
i'm not sure, i would definitely start by going through the list of people
There is no list of people.
There's a line of people. And paper and pen.
The point is; the 5th grader needs to visit each person. And stop as soon as they get to the first duplicate. They have a bad memory, so must use their notebook and pen.
Explain the algorithm. Then, implement in Python.
when you say "write w notebook and pen," do you mean store it in a data structure?
sorry for all the questions
Yes eventually, but first step is to ignore code/data structures and just envision; what would you tell a 5th grader?
with open("input.txt", "r") as f:
lines = f.readlines()
def word_to_num(line):
replacements = {
"twone": "21", "oneight": "18", "eightwo": "82", "threeight": "38", "eighthree": "83", "fiveight": "58", "sevenine": "79", "nineight": "98", "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9"
}
for word, num in replacements.items():
line = line.replace(word, num)
return line
num_list = []
for line in lines:
modified_line = word_to_num(line)
counter = 0
indexed = 0
first_digit = 0
second_digit = 0
for ch in modified_line:
if ch.isdigit():
counter += 1
indexed = modified_line.index(ch)
first_digit = int(ch)
break
for i in range(len(modified_line)-1, indexed, -1):
if modified_line[i].isdigit():
counter+=1
second_digit = int(modified_line[i])
break
if counter == 1:
second_digit = first_digit
num = first_digit * 10 + second_digit
num_list.append(num)
print(sum(num_list))
so badly written 😭 please give some suggestions. Its AoC day 1
Yah, I’m not looking. Will do my aoc this evening.
do the roulette with us 🥺
(join the cult)
class Node:
def __init__(self, value):
self.value = value
self.next = None
#we create a class that creates a Node
class LinkedList:
def __init__(self, value):
new_node = Node(value)
self.head = new_node
self.tail = new_node
self.length = 1
#create a new node.
def print_list(self):
temp = self.head()
while temp is not None:
print(temp.value)
temp = temp.next
def append(self, value):
new_node = Node(value) #created a node
if self.head is None: #tested to see if the list is empty
self.head = new_node
self.tail = new_node
else: #otherwise do this
self.tail.next = new_node
self.tail = new_node
self.length += 1
return True
#create a node
#add it to the end.
my_linked_list = LinkedList(1)
my_linked_list.append(2)
my_linked_list.print_list()
```---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-7-e6aa84657e66> in <cell line: 38>()
36 my_linked_list.append(2)
37
---> 38 my_linked_list.print_list()
<ipython-input-7-e6aa84657e66> in print_list(self)
15
16 def print_list(self):
---> 17 temp = self.head()
18 while temp is not None:
19 print(temp.value)
TypeError: 'Node' object is not callable
what am i missing here?
there's a typo somewhere
is it indentation?
a type error usually indicates me trying to use an argument that's not compatible with a certain type
dude
i'm an idiot
there's no parentheses after self.head() in the print_list function
smhhhh
at least i caught the damn error
hi does anyone know about LZ77
is there an efficient way to convert rows to columns? say you have a list of list where each sublist is a row, so like say l = [a,b,c,d,e...] where a,b,c,etc are all sublists
is simply iterating through and making a column like [a[x],b[x],c[x],d[x],e[x]] the fastest way, or is there some other way to do it
!d zip is probably what you're looking for.
zip(*iterables, strict=False)```
Iterate over several iterables in parallel, producing tuples with an item from each one.
Example:
```py
>>> for item in zip([1, 2, 3], ['sugar', 'spice', 'everything nice']):
... print(item)
...
(1, 'sugar')
(2, 'spice')
(3, 'everything nice')
```...
Hello, Iam trying to learn QuickSort (just to get a bit ahead from the bubble sort that we are taught at school) and I am stuck on a few details.
I copied the code to experiment with from GeekForGeeks. The code works great, fast and with no functional problems. Problem is, that I am getting stuck in the logic behind it. I have looked at it from YouTube tutorials, explanations and I get the jist of it, but I can't make out how it actually does the sequence of operations.
This is the array sample I used to test it.
[1, 7, 4, 1, 10, 9, 21]
Code I am using: https://www.geeksforgeeks.org/python-program-for-quicksort/
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and programming articles, quizzes and practice/competitive programming/company interview Questions.
Can you explain what you’re stuck in? What do you understand so far?
well, for one, I understand that QuickSort is a variation of MergeSort (which I don't know how to do), that splits the arrays into 2 with each sequence, working in smaller groups so it can work faster.
I could be completely wrong but that's what I know (and that it is 100s of times faster than Bubble Sort if the array is not sorted or nearly sorted beforehand)
as for what I am stuck in, I am trying to make a table of how the values change with each iteration. My problem is that I don't really get how it does the itteration.
quicksort works pretty differently from mergesort, but they're both divide and conquer algorithms
the interesting part is in the pivot function
Hmm? Im wondering about bringing 5th graders into this again
Ok, I’ll try: let’s say you had a bunch of kids in a class and want to sort by height. The only thing you can do is divide them into two groups. So you pick a kid and put everyone shorter than the kid in the left group, and taller than the kid in the right group.
Then, for the left group, you do the same thing, shorter and taller group. You keep breaking them into smaller groups until you reach 1 kid in each group, at which point, you’re sorted.
i think that's cheating tbh. a 5th grader isn't sorting, they're just an element
I do (kinda) get how divide and conquer algorithms work. What I am confused is the order that it does the operations because I cannot seem to match it in my table
Fine. My fifth grader who is doing the sorting has a terrible memory and can only compare one kid at a time against a reference kid.
order of which operations?
The order depends on how you pick the pivot, of course, and there many ways of picking the pivot
(I feel like it's a good time to curse my limited vocabulary).
I mean how it goes through the array in this piece of code:
def quickSort(array, low, high):
if low < high:
# Find pivot element such that
# element smaller than pivot are on the left
# element greater than pivot are on the right
pi = partition(array, low, high)
# Recursive call on the left of pivot
quickSort(array, low, pi - 1)
# Recursive call on the right of pivot
quickSort(array, pi + 1, high)```
the whole code is in the link
I haven't really touched self nested (is that the term?) functions so I get confused in how it works
You mean ‘recursive’ functions?
yes, that
Oh. Think of my example for a moment:
But I’ll describe it recursively:
You pick a kid and find everyone shorter, and put them in the left group. Then, you go to the left group, and pick another kid and pivot them into a left and right group. Then you go to the left group (that you just created), and pick a kid and pivot again. You keep pivoting the left groups until the group has only one kid. Then, you go back and deal with the last right group
the idea is that we can describe a problem using smaller versions of itself
Tbh, maybe fib would be a better example to learn recursive…
That site is pretty neat and helps you visualize recursive Python functions
thanks, I will check it out and check out a few more sources. I am still fairly a beginner, despite how fast I progress
I think I finally get it (somewhat). With practice will make perfect. Thanks again guys!
is there a formalization of the idea of software ecology, or software as a complex system? comp sci wise
Can anyone pls help me convert this piece of C code to python accurately? I am having some problems.
#include <stdio.h>
#include <math.h>
int main() {
int t, b, a, y,z;
scanf("%d", &t);
while(t) {
scanf("%d", &b);
y = sqrt(b);
z = cbrt(b);
a = y + z - (int)(sqrt(z));
printf("%d\n", a);
t--;
}
}
What's your current attempt? Offhand, scanf might be annoying to reimplement if you want exact equivalence of action, because Python mostly takes input by line.
EDIT: this person has now made a help channel
I have no problem with I/O but there's some rounding(converting to int) errors happening in python. Output sometimes increases or decreases by 1.
I have tried converting everything to int in python but that does not help.
Here is my current attempt.
import math
for _ in range(int(input())):
b = int(input())
y = int(math.sqrt(b))
z = int(math.pow(b, (1/3)))
a = y + z - int(math.sqrt(z))
print(int(a))
This problem from code forces 1619B. Test case:
10
1
25
1000000000
999999999
500000000
1000000000**(1/3) is 999.9999999999997, hence the deviation. math.cbrt gives the right result, 1000.0.
C's cbrt presumably is equivalent to the latter.
I have used numpy.cbrt too it's the same
I'm getting a different result (32591) for b of 1000000000 compared to your snippet (which gives 32590) by replacing math.pow(b, (1/3)) with either math.cbrt(b) or np.cbrt(b) (these two give the same result here).
Sry, I cant use numpy and code forces uses python 3.8
Is there any alt to math.cbrt?
You can try using round instead of int in z = int(math.pow(b, 1 / 3))
!e You're kind of in trouble, then. You could try a simple fix, like applying one iteration of Newton's method to the inaccurate cuberoot:
def cbrt(x):
y = x ** (1 / 3)
y -= y / 3 - x / (3 * y**2)
return y
print(1000000000**(1/3), cbrt(1000000000))
@vocal gorge :white_check_mark: Your 3.12 eval job has completed with return code 0.
999.9999999999997 1000.0
but no guarantees it'd actually work
that'll probably break tons of other cases
No idea if they rely on flooring when it matters
You should consider coding this purely using integers instead of floating point numbers if you care about accuracy
ah, good point. implementing an accurate icbrt(x: int) -> int is much easier than a float one (pretty much do y = int(x**(1/3)) and then try it and y+1 for the outcome)
You might need to try -1 too
hmm
Just tested it, and as long as you don't use crazy large numbers (> 2**64), then you wont need -1. I think the reason why it works is that the floating point representation of 1/3 is just slightly less than 1/3
!e
import math
x = 259254712487743
y1 = int(x**(1/3))
y2 = int(x**math.nextafter(1/3, 1))
print(y1, y2)
@regal spoke :white_check_mark: Your 3.12 eval job has completed with return code 0.
63763 63763
Hmm on my computer locally this results in 63763 63764
This is the scary thing about using floating point numbers.
okay so, i realie that i'm instantiating my class wrongly:
async def _character(self, ctx):
embed = discord.Embed(
description=await Help(ctx.guild).character
)
await ctx.send(embed)
what is the correct way?
[2023-12-03 15:57:59] [ERROR ] discord.app_commands.tree: Ignoring exception in command 'math'
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 827, in _do_call
return await self._callback(self.binding, interaction, **params) # type: ignore
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\Documents\GitHub\RP-Utilities\cogs\MathCog.py", line 44, in math_slash
description= await Help(interaction.guild).math
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\Documents\GitHub\RP-Utilities\help.py", line 32, in math
prefix = await self.get_prefix()
^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\Documents\GitHub\RP-Utilities\help.py", line 10, in get_prefix
prefix = self.database.get_prefix(self.guild_id)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
TypeError: Database.get_prefix() takes 1 positional argument but 2 were given
The above exception was the direct cause of the following exception:
Traceback (most recent call last):
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\tree.py", line 1248, in _call
await command._invoke_with_namespace(interaction, namespace)
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 853, in _invoke_with_namespace
return await self._do_call(interaction, transformed_values)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "C:\Users\User\AppData\Local\Programs\Python\Python311\Lib\site-packages\discord\app_commands\commands.py", line 842, in _do_call
raise CommandInvokeError(self, e) from e
discord.app_commands.errors.CommandInvokeError: Command 'math' raised an exception: TypeError: Database.get_prefix() takes 1 positional argument but 2 were given
like, it seems my program detected self as a parameter to be filled
i don't know how i was suppose to instantiate to make it function properly without asking the "self"
i'm not sure if this should go here, but i'll give it a shot: i'm using the noise library to generate noise for my game and it sometimes produces strange results like you see here. here is my code to generate the noise (x and y are looped through and WORLD_SEED is set to random.randint(1, 1000)):
filled_value = max(0, (noise.pnoise2(x / 10, y / 10,
octaves=2,
persistence=0.8,
lacunarity=2.0,
base=WORLD_SEED) + 1))
Any ideas how to... make it look right?
(i'm looking for less uniform/repeaty and more random results, like caves)
(it works sometimes but every now and then when I run it it gives stuff like this)
Huh, weird, I can replicate this. The issue seems to be with the first octave of the noise for base=512 or base=1024 and probably some others.
Actually, all the octaves really.
This is probably some feature of perlin noise that I don't know enough about; maybe try the other functions from this package and see if they're less prone to periodicity.
@frail jetty```py
def s(n):
a = [[1],[0]]
for l in range(2, n+2):
a = [(1,)*l , *zip(*reversed(a)) , (0,)*l]
return a
for a in s(8): print(a)
!e ```py
def s(n):
a = [[1],[0]]
for l in range(2, n+2):
a = [(1,)*l , *zip(*reversed(a)) , (0,)*l]
return a
for a in s(8): print(a)
@lean walrus :white_check_mark: Your 3.12 eval job has completed with return code 0.
001 | (1, 1, 1, 1, 1, 1, 1, 1, 1)
002 | (0, 0, 0, 0, 0, 0, 0, 0, 1)
003 | (0, 1, 1, 1, 1, 1, 1, 0, 1)
004 | (0, 1, 0, 0, 0, 0, 1, 0, 1)
005 | (0, 1, 0, 1, 1, 0, 1, 0, 1)
006 | (0, 1, 0, 1, 0, 0, 1, 0, 1)
007 | (0, 1, 0, 1, 1, 1, 1, 0, 1)
008 | (0, 1, 0, 0, 0, 0, 0, 0, 1)
009 | (0, 1, 1, 1, 1, 1, 1, 1, 1)
010 | (0, 0, 0, 0, 0, 0, 0, 0, 0)
what is the best way to learn algorithms and data structures? as well as problem solving?
Can anyone help with #1181630386028154971
Check pinned messages!
Thank you I will have a look
I want to evaluate the effectiveness of a text classification algorithm in terms of how many mistakes it did, anyone has experience knows where to look? I want to know on average how many mistakes it will make in an n sample
i learned it by doing
is there some sort of approach to software programming where software is programmed modularly, so that different parts of the code can be ran individually without needing to run the entire program? is this possible in python?
Maybe you're looking for Dependency Injection?
will definitely look into this, thanks!
CodeAesthetic has a nice vido on the topic
Try using the attachment service at https://www.patreon.com/codeaesthetic
You'll also find deleted scenes, song names and more
ty for the reference!
👍
Maybe start with a question in #python-discussion ? It’s not clear what you’re asking.
I think English is his second or third language
He may be asking how to use the library twilio
Yah, I just wasn’t sure if they’re asking about how to import, if they’re getting an import running, did they write some code and it’s failing, etc. but either way, would probably be guided in pydis a little faster
Hey there. Do you have any suggestions for speeding up Python code? I was looking into Numba, but it doesn't work well in many cases.
(and it had nothing to do with #algos-and-data-structs)
Are you asking about how to optimize a particular algorithm? Or just about Python performance in general? If just general, ask over in #python-discussion , this is discussed a lot
kk
So I have this problem
And I think I know that I need to reduce it from Vertex Cover as that’s probably the closest thing to this
I’m just having trouble figuring out how to set it up as VC
Would I want students as edges or students as vertices?
It would have to be students as vertices right
Cause in VC not every vertex is used and if I need every course to be present that wouldn’t work
can someone check this pls before i send to my tutor
pick an appropriate channel pls
what about Set Cover?
that seems very close to the description of the problem
(or equivalently, hitting set)
VC is a special case of SC, but I suspect SC will serve you better
are there any language-independent approaches to designing algorithms? so that implementation in a particular language is a final step
pseudocode
to my knowledge, i wouldn't say the approaches are too different, only the syntax because in essence the algorithm is just a bunch of steps which COULD be very specific and leaving no room for implementation interpretations but it could also be very general instructions. in the end it depends on how general each step of the algorithm is
but the "standard" algorithms are pretty much implemented the same with minor details making the differnce
Guys, this is my personal reference of how to use decorators or what can be done with them, any suggestions to add or corrections of misunderstandings? https://paste.pythondiscord.com/EOWA
I g the class method implementation is incomplete, it fails if it is called without an instance
def _classmethod(f):
def mod_f(*args, **kwargs):
f_name = f.__name__
if args and getattr(type(args[0]), f_name, None) is mod_f:
self = args[0]
args = args[1:]
return f(type(self), *args, **kwargs)
else:
cls = getattr(importlib.import_module(f.__module__), f.__qualname__.rsplit(".", maxsplit=1)[0])
return f(cls, *args, **kwargs)
return mod_f```
This works for all cases I tested
Anyone wants to vet it? 👀
Hello, I am new here; please help me in my DSA learning journey!
Hey after implementing Binary Heaps in form of trees and arrays
we found arrays are better in all operations
in term of time complexity
is this correct?
why is it?
Pretty much every algorithm is designed to be language agnostic. Instead, we say an algorithm runs on a certain "abstract machine" with a certain "model of computation", for instance: turing machine, RAM machine, external memory machine, etc., and then knowing the properties of that machine, we construct a program using operations that machine can perform. Most single-threaded algorthims are designed for RAM machines, which is basically any cpu, which exists at the moment (ignore multiple cores for a sec), and you can implement basically any algorithm, in any language, which allows writing code for RAM machines. So, for instance, you can implement a heap as it is in Python, or C, or Java, or even Haskell, but you will find it difficult to implement in say, CUDA, a language for programming GPUs, which works on a different device which uses a different model of computation. All that is to say, in some sense, algorithms exist in a plane different from a plane languages exist in.
please check the pinned messages for resources
The time complexity is the same. It is basically impossible to know the time complexity from the experiment though, because of how complex measuring time is. Both are O(n) build, O(1) max, and O(log n) insert & pop. You get that from a theoretical analysis of the algorithm, not from an experiment (although you can refer to an experimental result, saying "the algorithm performs that good on our experimental data", you just can't conclude the complexity from that. The opposite is also somewhat true: you can only estimate the time it would take the algorithm to execute based on time complexity, but not measure time directly in a lot of cases).
yeah we are not trying to prove anything, we just found out that the array version takes less time in all operations
The reason why array implementation is faster, is because not all implementations are created equal. Some are faster, and some are not. What language did you use?
python
it is supposed to be like that
Well, I can't know the exact reason why, but I if I had to guess:
0. initializing tree nodes requires memory allocation, which an expensive operation, compared to pushing to an array
- Recursive function calls take more time than simple loops, so traversing a tree is slower than iterating over the array
- Memory layout of the array is better than the tree layout in memory, so it is easier for hardware to work with (although it is very difficult to estimate the effect of that in python, it is definitely present)
- The code python executes is simply more complex, since it requires accessing class fields
I would guess that tree-based implementation is anywhere from 3 to 8 times slower than the array one, but this is just a wild guess, you have to measure it
If you used pypy, then it is also possible that pypy optimized the simple array-based code significantly better than the plain python one, but I don't know pypy enough to reason much about that
hmm interesting
@outer rain also is timeit and lambda function the correct way to measure execution time? because Ive seen it get weird with bumps
like in this case
the graph on the right is supposed to be logn
sometimes it does look like logn sometimes it has these weird bumps when I run the function multiple times
that should be fine, but you say "sometimes" you get those bumps?
Check your environment. Make sure the data is randomly distributed in the way you want, and check that CPU load is as similar as possible between the runs. Also it might be just that your implementations actually works like this. It may be just me witch hunting (most likely, yes), but could it be that the performance with sizes close to the power of two behave slower?.. I am probably wrong, because I have no idea how can you even make it that way with binomial heap, but it might be worth checking. And, of course, make sure your implementation is correct, before benchmarking it.
Unfortunately measuring time is a whole science of it's own, so it make take a long time to explain why the time behaves like that.
this is with timeit ```py
heap1.createBinomialHeap(list[len(list)//2:])
heap2 = BinomialHeap()
heap2.createBinomialHeap(list[:len(list)//2])
execution_times.append(timeit.timeit(
lambda: heap1.mergeHeap(heap2), number=1))
very cool! any chance you have readings on abstract machines and such?
thanks for the answer btw
@outer rain sometimes it gives me this which does kinda look like logn
I would suggest putting the initialization code into timeit.timeit(setup=<...>) part and cranking up the number of iterations
You are trying to measure times of orders of microseconds, which is way too small for a single iteration
unfortunately, I am not sure how to easily measure union at all, since it takes way less time to complete compared to the setup required for it 🤔
hmmm... no, I afraid I can't... It's not something I have just read about, it's more of things you get introduced to by studying the subject. I can recommend you just reading the wikipedia article, or reading a theoretical informatics book, but I don't think that's what you are after, sorry
noted ty!
I dont really know how timeit works
I just followed some tutorial on how to measure a function
I don't know much about it either, unfortunately
!d timeit.timeit
timeit.timeit(stmt='pass', setup='pass', timer=<default timer>, number=1000000, globals=None)```
Create a [`Timer`](https://docs.python.org/3/library/timeit.html#timeit.Timer) instance with the given statement, *setup* code and *timer* function and run its [`timeit()`](https://docs.python.org/3/library/timeit.html#timeit.Timer.timeit) method with *number* executions. The optional *globals* argument specifies a namespace in which to execute the code.
Changed in version 3.5: The optional *globals* parameter was added.
It just runs stmt number number of times using globals as the global namespace. setup is run once beforehand, timer is time.perf_counter by default. The return value is the sum of the timer measurements
E.g. with stmt="time.sleep(1)", setup="import time", number=10, the return value is approximately 10
Isnt it the min
It runs the stmt code 1 million times by default and return the minimum
No
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec 7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> from timeit import timeit
>>> timeit(stmt="time.sleep(1)", setup="import time", number=10)
10.013792699901387
>>>
Congratulations, Python 3.12.1 is out now
Hi, I hope I choosed the right channel for this, but I have a machine that decorate a gingerbreads, Now I have a algorythm to detect the contours of the gingerbread. Do you have some ideas on how to do some filling patterns? Like some fancy decorating with the machine? (What algorythm to use to create the patterns specificly). Thanks a lot for answer!
Suggest me a playlist for dsa in python
hello people
so i was trying to make a graph with connections between nodes within a certain radius of one another. i used the sampling based rrt algorithm for sampling nodes
i modified the code i found in an online repo
and used dijikstra's algorithm to find the path between two nodes
i dont think the path that the algorithm found was the most optimal(i may be wrong here) can you guys tell me what could be the reason for that?
idk if i should link my code here so please let me know if you want it
is there any common discussion group here in this server?
yoo wassup
I just wanna to make my basic python code run in a window screen using Pygame
How can I do it
maybe #python-discussion , or by "common" you mean unrelated to python then the off-topic category, such as #ot1-perplexing-regexing
i think this is the correct space to ask this but apologies if not.
is the pulp library able to handle objective functions where the decision variables undergo some transformation and the result is what's optimized?
specifically if the decision variables are put into a vector and multiplied by a matrix.