#algos-and-data-structs
1 messages Β· Page 117 of 1
so before n_0 cg(n) <= f(n)?
not necessarily. cg(n) can be anything
all we care about is that after n_0, cg(n) >= f(n)
ohhh got it
if you look at the graph, you can see that it fluctuates
okay, let's experiment on the graph
wait nvm this book explains it pretty well
sure lets experiment
wait why are we taking g(n) as n^2?
here, n_0 is 5
so we round up?
technically it's 4.7, but I don't like fractional inputs π
lmaoo i see
then c = 4?
no, not necessarily
oh
Yes
what you need to know @silk breach is that c just needs to be greater than 3
Its 8 I put it in the graph
Ohhh got it
it doesn't matter if it's 3.1, 3.01, 3.001, 3.0001
why?
well let's take 1 billion as input
let's say c = 3.0001
what is 3.0001 * 1 billion?
A lot
can you calculate it for me, please?
3,000,100,000?
3,000,000,008
you see?
Ohhh yea
as long as c > 3 (3 in this case is the leading coefficient of f(n)), there will always exist an n_0 such that cg(n) >= f(n) for all n >= n_0
So what's the n_0 for this question
No problem π
francis be a smart boi
@gritty marsh are you still here?
Yes, but busy
oh ok
Guyss any best course for dsa?
I wanna start but i am so confused, so please help me!
DSA? Digital Signature Algorithm? 
perhaps they meant Data Structures and Algorithms
π¦
π
Check pinned messages
can someone help me with oop function?
!mute @arctic nebula 1d please reread our code of conduct
:incoming_envelope: :ok_hand: applied mute to @arctic nebula until 2021-05-12 10:27 (23 hours and 59 minutes).
Dont ask to ask
!ask
Thought it was a tad, tldr just ask your question
New to python, want to learn data structs
Is there any more efficient algos for sorting list of positive unique integers , than quick sort?
what is 0/0
ZeroDivisionError
Has anyone worked with PNGs with transparency images and edge detections? Seems like there is nothing on internet
how tf did i forget that
There's radix sort
Thank you!
counting
i guess they are both linear
also counting is part of some radix implementations
tim sort which is python's sort
I think
same asymptotic complexity of O(n log n) as all the other general-purpose sorting algorithms; it's derived from mergesort
can I get some help on Min Conflict Algorithm?
Can anyone help me with this problem ?
https://www.hackerrank.com/challenges/find-second-maximum-number-in-a-list/problem
def runner(n, arr):
if n < 1:
print("Enter a value")
elif len(arr) > n:
print("There is more than {} no of scores".format(n))
elif len(arr) < n:
print("There is less than {} no of scores".format(n))
else:
print((sorted(set(arr))[-2]))
runner(3, [-10,0,10])
tried this code, all the test cases are getting passed in google colab but none of them are passing in the hackerrank IDE.. Please help
17
80000
You can use a tuple as a record, or a namedtuple
depends what you mean by |, in python its the binary or operator but that doesnt seem reasonable in the context of the question
| means divides
fr? thats new to me lol we always used /
yh
It's different from division.
If You use / it means you want to get the quotient. If you use |, you're just describing properties of two numbers.
36 | 2 and 36 | 3 implies 36 | 19?
wait mark so am i correct or wrong
I haven't read it all yet. Got distracted answering the | question
sorry lol
Yes you are claiming that 36 | 2 and 36 | 3 implies 36 | 19?
ig?
So does it?
Yeah, that proof looks solid to me.
Yeah it's not too complicated. You're just using the definition of | and some algebra.
nvm i dont have it lol but yeah thats what i did so i should get most of the poinst or all ig
You don't have what?
my version of it but obv i did the same as this method so i am fine
but thanks alot
@half lotus I don't see how it works at all >_>
What was it again? If a | b and a | c, then a | (5b + 3c)?
Yeah I got tripped up by that before
hey guys, how do i change the date format to May x, 2021?
ie. 2021-05-11 -> May 05, 2021
I am new to python can any one tell which string function can be used to find what is in a string at a specific index position
You can use a dictionary in which 05 can be set to May and same can be done for other months
how is that done?
ive seen people use datetime function on stack but i keep getting errors
!e use indexing with [] py mystring = "hey world" print(mystring[0]) print(mystring[2]) print(mystring[4])
@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.
001 | h
002 | y
003 | w
But that's not exactly an #algos-and-data-structs question
can always see #βο½how-to-get-help
Anyone know the average big O of the number of factors a number has? Looks like O(lgn) but I'm not certain https://oeis.org/A000005/graph
wikipedia mentions, uhh, this https://en.wikipedia.org/wiki/Divisor_function#Growth_rate:
any real number >0
The bottom seems to be saying log(d(n)) grows the same as log(n)/log(log(n))
(differing by a constant factor)
The former means that it grows so slowly it grows slower than n to any positive power, if I'm not mistaken
oh, weird
There's also this post by Terence Tao, lol
https://terrytao.wordpress.com/2008/09/23/the-divisor-bound/
Just casually doing complex math on wordpress 
but yeah, that tallies with what I was thinking wiki was saying
which boils down to n^(1/log(log(n)))

curious
Guyss anyone has practice list for list comprehensions
hey !!!! can anyone tell me where i can learn this python language easily ??
with time
from where i have to start for it ??
watch youtube courses if you dont want to pay for it and also read documentations and the most important practice a lot
can you suggest me some channels?
?
sure ... give me a sec
this one is a pretty good course on youtube but if you want other similar one then just search for PYTHON COURSES on yt, and freecodecamp has good courses online
I dont recommend to watch long parts of it , watch short βpiecesβ it and learn slowly also make notes
thanks a lot 
you are welcome π
whats the most common way used to print a Tree
To print a tree, people usually process it into thin white sheets, and they apply ink or a toner to them 
seriously though, I'd expect something like this
(depending on what the tree represents)
@paper yacht That's plain text. They're just using fancy ASCII characters to print out the lines
yeah sorry thats what i meant
i dont want to use those extra characters
coz it kinda gets complex just to print them out
You can use |-+/\
Another slightly less conventional way is to use S-expresisons:
basically, lots of parentheses
hmmz
but it depends on what kind of tree you want
then it's probably better to print it centered, otherwise it's awkward
but i have to do a lot of formatting right
yep
thats sad
doing it for arbitrary trees will be tricky, because you'd have to truncate very long strings etc.
yeah makes sense
i havent learnt yet how to render HTML but i can if its that good of a thing
its probably useful in a lot of areas apart from printing trees
hmm
thanks for the idea
basically, something like this
and then you can remove the borders π
yeah, you can merge table cells in HTML
alright
i have a printer for things similar to bsts -- the art data structure i implemented pretty prints
oh?
though it isn't centered, it just prints top to bottom
In [27]: t = AdaptiveRadixTree()
In [28]: t['Python'] = 1; t['Python Discord'] = 1; t['Picnic'] = 1
In [29]: print(t)
''
β°β'P'
ββ'icnic'
β°β'ython'
β°β' Discord'
where can i get help 
yeah, but you have to maintain order when you delete nodes
yeah i feel thats the most difficult part to code
I dnt think that messages like this are allowed here
if only we could actually read it
lol
Does anyone know if using list.clear on a list or deleting all of its reachable references so it will get garbage collected is O(1) in pypy?
memoryview shape casting is disappointing
it seems ideal at first for quickly passing binary data to constructors, except that you cant pass a sub view
i imagined it would be great for starmapping to ctors but nope
as usual in py, as you get lower, u get slower
oh you know what, i take that back. tolist also listifies the subarrays. its not ideal, but it gets the job done
definitely less than ideal if you have a very large amount of data though
Hope someone has time to help me :: Any idea how we can EXPAND, or STRETCH-out that polynomial graph? It's too narrow; would also like to see curved bottom (a bit below X-axis), any help appreciated :: https://i.imgur.com/g6Cbn02.png Thanks.
Or point us where we might find assistance, thanks π
Adjust your X/Y limits? You set specific ones on line 98-99, then read them back in and scale them up for some reason?
I need help deciphering a message can anyone help me?```
Key: Cipher Text:
β‘6 24 1β€ β‘654β€
β’13 16 10β₯ β’694β₯
β£20 17 15β¦ β£878β¦
Reference Table:
a 0 | g 6 | m 12| s 18| y 24|
b 1 | h 7 | n 13| t 19| z 25|
c 2 | i 8 | o 14| u 20|
d 3 | j 9 | p 15| v 21|
e 4 | k 10| q 16| w 22|
f 5 | l 11| r 17| x 23|
do you know about matrix multiplication?
No never heard what is it?
I heard it could also be an affine cipher but I don't know which @grizzled schooner
i doubt it's the affine cipher because affine has only 2 keys
oh ok
this looks like the hill cipher because of the matrices
How would I go about solving it there is no algorithm included?
err you basically multiply each number in the cipher text with all the numbers in a certain row of the key
i'm not that great at explaining math stuff, i recommend looking up an article on matrices
also not sure why the cipher text values are in the 600s?
I think there suppose to be separated...
what do you mean?
actually I got lost... is there any articles which can help me solve this cipher? @grizzled schooner
ok so your steering towards the hill cipher alright
i'm not that familiar with cryptography but I don't know any other ciphers that invove matrices
looks like hill cipher
lol, it's "KYS", so...make of that what you want
Actually you might be right I found this https://www.geeksforgeeks.org/hill-cipher/
have i sent 50 messages yet?
i'm familiar
you can check by searching with discord's search feature
yeah, the plaintext
please help i am facing problem with level order traversal check channel #help-donut
what are some good tutorials i have to check on python i wanna start a project but don't know what project i don't have one in my mind and also im a newbie webdev soo anything i have to learn in that era
Hey @dusk flare!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
does anyone have best source to learn algorithm and data structure ?
Have you seen pinned messages?
hey guys i am stuck on a problem in python involving writing a code about loans but only using min and max functions
can anyone help?
oh tks u so much
Hey @empty trout!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
i have quadtree class, which store points, how to write function to move points and not creating new tree again? https://paste.pythondiscord.com/ipixehabuk.rb
I wrote an app that takes an input from a separate class/module (only using this separate module to create a data structure similar to C/C++ dictionary.variable functionality). At the end of the app I pickle the file....and ideally would like to reload the app by feeding it the loaded pickle.
Unfortunately the pickled file has dependencies on the first module and the only way to load it is to rerun the first module (obviously not ideal). Any suggestions on how to get around this?
Outside of the obvious dont use the class for the C data structures functionality and just use pythons nested dictionary....so id have to reformat my code to dictionary['variable'] instead of dictionary.variable
A person died during the time I posted this
is this a dynamic programing question? https://adventofcode.com/2020/day/15#part2 bc it seems its taking forever for me to compute the answer
like is the sequence supposed to repeat itself or something?
or am i supposed to use the "fibanacci" strategy of storing previous values
Is it possible to find the shortest path in an unweighted cyclic graph using DFS?
Yes, it has cycles.
Every resource I read suggests BFS is the way to go
With DFS, the problem I run into is that it may first visit a longer path, and then all those nodes are marked as visited. Therefore, it will skip the nodes leading to the shorter path.
I've found an answer here that suggests to mark them as unvisited, and indeed that solves my problem https://cs.stackexchange.com/a/107125
Has anybody solved PS2 on MIT OCW's CS 6.0002 pset? I'm trying to solve the weighted DFS problems and could use some help checking my solution for accuracy
Just wanted some clarification
for a depth first search of this graph the
traversal order would be U,V,Y,X right
Because it cant traverse the nodes w and z?
Well, the order depends on what neighbour of u is processed first (which is an implementation detail) - UXVY is also possible
w isn't reachable from U (or any node at all other than itself, in fact), yeah.
is it reachable if you start at it?
Any help on this plz
3
300
100
100
300
output 2
why output is 2 , can u explain?
2 ways u can shift shops
does going from shop 1 to shop 2 and coming back regarded as 1
No it's ends up 2
1st take 2 100 blocks
While coming back u have 2 options
Which block u take
If u take any one block the other will make the 2nd way
All the items are different
isn't our goal to shift all goods to shop 2
Yes and count the possible eays
Possible ways having minimum steps
first take 2 goods weight 100, 100 each to shop 2
then come back to shop 1 with one good of 100,
then take good of 300 to shop 2
then again come back with 100 to shop 1
AND FINALLY take 100 , 100 to shop 2
isn't this the problem should be solved?
just wannna make things clear so I can work on it
Yes the problem is solved but while u bring the 100 block for the 1st time u have 2 ways
Better index 1st 100 block with Id 1
And 2nd 100 block with id 2
While coming from shop 2 to shop 1 u have option to take block 100 having id 1
This is 1st way
While coming to shop 1 u may carry block 100 having id 2
So in minimum steps u have 2 possible ways
Did u got my explanation?
Or shall I arrange a voice channel?
but all the goods haven't beenmoved yet
!mute 826452894689656873
:incoming_envelope: :ok_hand: applied mute to @mystic steppe until 2021-05-14 15:48 (59 minutes and 59 seconds).
All goods are unique bro
Ok atleast help me the problem what u understood
I can follow up to my question
okay, I get it I will let u know when I am done
@scarlet elm you got some more inputs for this problem
no mate only these
Can someone tell from where i can learn data structures and algorithms using python?
They cover all the topics??
yeah basics
Check pinned messages
how to do part 2 https://adventofcode.com/2020/day/15. the number seem to high to iteratively generate the sequence.
oh i got part 1
cuz i just looped though and generated
cuz u only needed 2020 iterations
yeah, but if you did it efficiently you should be able to just brute force part 2 also
I can't see it since I'm not logged in, is it 3 million?
30 mil
fn main() {
let result = input_parser::read_line_input(15, "numbers".to_string());
let mut g = game::Game::new();
match result {
Some(value) => {
let starting_nums = value[0].split(",");
for i in starting_nums {
let num: u32 = i.parse().unwrap();
g.insert_starting_num(num);
}
let n = g.nth_number(2020);
println!("Number is: {}", n);
},
None => {
println!("Could not parse input");
}
}
}
pub struct Game {
last_nums: HashMap<u32, u32>, // number and turn last said
last_last_nums: HashMap<u32, u32>, // number and turn last last said
last_said_num: u32,
turn: u32,
}
impl Game {
pub fn new() -> Self {
Game {
last_nums: HashMap::new(),
last_last_nums: HashMap::new(),
turn: 1,
last_said_num: 0,
}
}
pub fn insert_starting_num(&mut self, num: u32) {
self.last_nums.insert(num, self.turn);
self.last_said_num = num;
self.turn += 1;
}
fn insert_num(&mut self, num: u32) {
// essentially copy the values to last last if the value is already in last
match self.last_nums.get(&num) {
Some(val) => {
self.last_last_nums.insert(num, *val);
}
None => {}
}
self.last_nums.insert(num, self.turn);
self.last_said_num = num;
}
pub fn next_turn(&mut self) {
// check last number spoken
match self.last_last_nums.get(&self.last_said_num) {
// has been said before
Some(value) => {
let diff = self.last_nums.get(&self.last_said_num).unwrap() - value;
self.insert_num(diff);
},
// never said before
None => {
self.insert_num(0);
}
}
self.turn += 1;
}
pub fn nth_number(&mut self, n: u32) -> u32 {
while self.turn <= n {
self.next_turn();
}
self.last_said_num
}
}
the missing module too
didnt get zapped for pastebin yet lol
essentially what I do this this
pub fn nth_number(&mut self, n: u32) -> u32 {
while self.turn <= n {
self.next_turn();
}
self.last_said_num
}
which is loop though till i hit the turn number
did you compile with optimization flags
nope
like the previous day or 2 which was the plug one
apparently the trick was using previous calculation
https://adventofcode.com/2020/day/10 like this one
ngl, I'd just wait like a minute or two
but they did say in the beginning that each question should be 15 sec max
yeah, but who's counting
lol, nice
this is not a help channel
this is not a modmail thread
π
hi can anyone decipher this in the long format
list(k for k,_ in itertools.groupby(k))```
Wdym decipher
Thats pretty clear imo
It returns the unique elements in k in a list
it only dedupes adjacent elements
Yes correct my b, didnt think of that when testing
a bit annoying to use k as the loop variable as well, but whatever
actually, k is ok as the key, k as an iterable name is weird
Yea if this was a proper for loop k would be overwritten
def checker(_token):
r = get('https://api.eternal.com/login=nowl666')
if 'good' in r.text:
with open(good_path, 'a+') as f:
f.write(f'{_token}\n')
if __name__ == '__main__':
tokens = open(tokens_path, 'r').read().split("\n")
for token in tokens:
while True:
if threading.active_count() <= 250:
threading.Thread(target=checker, args=(token,)).start()
```how can i increase a speed i have file with 16k tokens
Use recursion rather than for loop
Define a function to read and call it inside the loop again
Python doesnβt optimize recursion
Yeah but time complexity will decrease mostly.
how?
Are you sure you need to repeatedly request the same web address?
Wouldnβt that just give the same thing each time?
that looks kinda malicious though ngl
and yeah, the while true inside the other loop doesn't make sense
What exactly is this code for? π€¨
nwm
Hi, I'm testing some algorithms and I was thinking can I use my gpu for calculations to increase performance?
or can I increase use of my cpu during calculations.
Right now I'm running algorithm to find 100, 200, 300... 1000 words in 400'000 words. CPU use is ~15%, and it's been running for ~9 mins
Depends on what kind of algorithm it is.
GPUs are good at very specific kinds of computation - stuff that's very parallelizable.
like processing graphics
make sure ur not being locked by GIL
like creating a bunch of python threads will use lots of mem but they wont run in parallel
how will time complexity decrease
Hi iron man u dead
You usually wouldnt create tokens like this in a nested for/while loop and then write them to a file to be used later.
You would create a token and then use it, if it expires then you would create a new one.
π€£ π€£ π€£
Because recursion uses stack and stack is time expensive if you operate it on large data
||recursion is never better||
Especially in competitive programming if you want to make something you would use recursion only if the data is small and to look fancy or use recursion because there is no other way
You can search on internet more about it, but I am sure most of the information you will find will be agains recursion even tho i use it :))
The time complexity of a recursive and iterative solution will generally be the same, regardless of which one is faster
not necessarily
there is always another way
iteration and recursion are equivalent
itβs all about ease of expression
And I think this is where you are wrong
On small data will be the same, but if you have very large data your program will have a constant of about 2-3
And that is a lot ...
Even if we take that as fact, that's still the same time complexity.
Sure, I agree but you donβt want to know how many points I lost with recursion and got with iterative at competitions
If one function is consistently 3x slower than another function regardless of the input, the two functions have the same time complexity.
Sure, I agree but maybe on some test cases it wonβt work just because it is 3x slower
It happened to me ;-;
that isnβt relevant
the point is not absolute time taken, but time complexity
which was the original topic
Have you guys been to real competitions ?
nobody is saying that an iterative solution might not be faster in some cases
and if you use recursion in a language which doesnβt have TCO
obviously you need to pay for it
π₯΄
Someone asserted that a recursive algorithm would have lower time complexity than an iterative one, which is how this whole conversation started. It won't. It will have the same time complexity.
Yes, but also, that's completely irrelevant. No one but you is talking about competitions.
and of course, in "real competitions", often an iterative solution is much more complicated than a recursive one
sure, but often in real competitions iterative solutions gives more pointes than the recursvie one
and by real competitions i don't mean an insult
i mean some competitoins but not codeforces
in codeforces you only get AC or not, there are no intermediate scores
Return the sum of the numbers in the array, except ignore sections of numbers starting with a 6 and extending to the next 9 (every 6 will be followed by at least one 9). Return 0 for no numbers.
summer_69([1, 3, 5]) --> 9
summer_69([4, 5, 6, 7, 8, 9]) --> 9
summer_69([2, 1, 6, 9, 11]) --> 14
can anybody help me with the logic of this example...please!!
def summer_69(arr):
total = 0
add = True
for num in arr:
while add:
if num != 6:
total += num
break
else:
add = False
while not add:
if num != 9:
break
else:
add = True
break
return total
here is the code
but i could not understand the second while loop
Yes the time complexity is the same, but space complexity is not hence in interviews and competitive programming its not preferred when we have space constraints.
Also recursion comes with the risk of stackoverflow. Could be the reason why you lost points when using a recursive solution instead of an iterative one.
Also, a recursive approach can be slower, even if the time complexity is same.
Magnitudes slower
A classic example is for generating n-th fibonacci number
@minor pumice
that is only related because it is exponential
lol
you can do the same exponential program iterativelly with a queue
and it's litarlly the same
i can do recursive dp and get a nice compleixty
Yeah, But I was talking about speed on same time complexity.
And it's NOT literally the same. And definitely not for getting just an n-th fibonacci number if we take space into consideration
well that is huge
Yeah, pretty big difference. But not magnitudes worse.
Generate 40th
magnitudes worse won't ever be
exactly but using iteration u can in microseconds
I generated 100th on the screenshot
becuase the iterative is O(n)
you can do iterative in expo as well
and you can do recursive in O(n) as well
dude
depends on how you implement
Yeah, that's the point lol, the difference is space complexity and repititive calls
in this case yes
The iterative is O(1) space complexity, the recursive is O(n) space complexity. Both are O(n) in time complexity.
also, the complexity for recursively calculating fib(n) the naive way isn't 2^n, it's fib(n), which is around phi^n, where phi is the golden ratio
how is the space complexity different? all you're doing when you switch between recursive -> iterative is substituting your own stack
Each function call occupies a space on the stack, unless the language has TCO
could you explain, i don't understand, for a dfs?
yeah, but that's just a constant isn't it
Well if you generating all the numbers then it is. For iterative n-th you don't need to store all. Just last 2 would do
No, since the calls are nested, a recursive call will make n stack frames.
I was also confused by that, but I assume they meant for the original task (some for loop) for which the iterative solution didn't use any extra memory, but the recursive one would (for the call stack)
gotcha
false
i don't think you are right
right, but you're just storing it on the call stack instead of your own stack, no?
In the iterative approach, you don't store anything besides the two numbers.
(look at my snippets)
right, but that's an entirely different approach, not simply converting between recursive to iterative. unless i'm confusing terms...
how come?
fib(n) = fib(n-1) + fib(n-2)
recurrent equation for complexity:
T(n) = T(n-1) + T(n-2)
T(0) = T(1) = 1
This is the equation for fibonacci numbers themselves, hence
T(n) = fib(n)
- the complexities for naive fibonacci is, itself, the fibonacci sequence.
Actually, that's a lie.
The iterative is O(log n) in space complexity. The recursive is O(n log(n))
Both are O(n log(n)) in time complexity.
Life ain't easy!
why is iterative log(n) lol
485384758347853748573847583475873485783475873485738475834785734875 takes up more space than 42
like, from what equation?
sure it does, becuse every call of the function will take a very amount of memrory
fixed π
there will be ever be an error
oh, lol, okay
computer science is all a lie
Computers aren't turing-complete because they have finite memory π
Because adding larger numbers takes more time. Adding two numbers of b units (bits/bytes/whatever) takes b steps.
therefore, all space complexities are O(1)
Can you please explain why iterative is logn space please?
but it is not log
it is log_10
lol
log means log_2
is that not log
and this is false
The code
for i in range(n):
# do something O(1) time and space
takes O(log n) memory just to store n.
log2(x) == log10(x) * (ln(2)/ln(10))
Are you saying that adding any two numbers takes a constant amount of time?
It is true. Definitely true for Python ints, which are variable- and infinite-size.
at least c++ uses another tehnique to add them
in c++ yes
c++ doesn't have infinite-sized ints.
it is a table of logatirhms
only with bounded ints
Please elaborate a bit more on this. Is it python specific?
but it can have
You can't add arbitrarily large numbers in constant time, of course.
Just general-specific. It takes log2 n bits to fit a number as big as n.
if the numbers are <= 2^128 we can
agree but have to specify that lol
it's not log time
it is log_10 time
O(n) is the same as O(2n)
O(log2(n)) is the same as O(log2(n) * constant)
what...
you sure about that
it is tho
it is a mathematical constant
!e
import math
print(math.log(2)/math.log(10))
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
0.30102999566398114
what other constants are there
And 2 is... biological?
spiritual
O(2^n) != O(e^n), but O(2n) = O(e*n), and O(lg n) = O(ln n)
that's just, like, how logarithms work
by that logic we can compute the n'th fibonacci number in log_10(n) time
yes
wait, no
can't you?
wait, how?
we dont ahve logatithmic constants
some matrix thing?
numerically via calculating it using the formula? I tried that, but it very quickly hits double precision limits.
Are you saying that O(log2(n)) is different from O(log4(n) * 2)?
Oh, so in general speaking, every constant integer solution is never O(1) space in the worst case?
that's what the formula I'm talking about is derived from, yes
i am saying that log_2 != log_10
and we can not have such constants
lol
Can you provide a definition of O notation for which O(log2(n)) is not the same as O(log10(n))?
the same way i can say log_2 = log10000* (ln(2)/ln(100000))
Yeah. It's usually not taken into account, but if your n really does go to infinity, operations on it can't truly be constant time and it's not O(1) space to store it.
it's different with floats, which are finite-size (and, due to that, can't actually go to infinity)
i can't provide any but in CS we don't use subunitar constants
and in cp the same
Indeed, log2(n) = log10000(n) * (ln(2)/ln(10000))
what's that? 
I can't find that term anywhere
because there are no written rules
ah yes, the unwritten rules of street CS
the same way i can say 2^n = 3^n
they aren't related by a constant factor
there's no such k that 2^n * k = 3^n
And you'd be wrong, just like you are about log2(n) and log10(n) not being constant multiples of each other.
mathematics isn't exactly opinion-based
i said just by assuming log2 == log10 in CS is not a thing
you can't
every where i have log2 i will write log1000000
than
log2 isn't equal to log10
but O(log2(n)) is equal to O(log10(n))
for the same reasons that O(2x) = O(10x)
Oh I understand for space and, for time when you say It can't truly be constant time, you mean we can also say storing a constant integer if it goes to infinity, the number of operations are log_2 n.
2^n = 3^n
2^n = (6)^n / 2^n
2^(2*n) = (6)^n
(2^n)^2 = 6^n
2^n = sqrt(6)^n
that about this @austere sparrow
i started with 2^n = 3^n
and got here 2^n = sqrt(6)^n
i manipulated the wrong thing into something else
the same way it can be manipulated if you take a prove to infinity sqrt(6)=2
if we repeat the operations an infinite ammount of time
what do you think will be the
value
@minor pumice Are you saying that log[a](n) = log[b](n) * ln[a]/ln[b] is wrong?
i perfecly agree that
i am saing that considerng ln[a]/ln[b] as a constant is wrong
even tho
mathematicaly
it is a constant
huh?
2^n = 3^n
2^n = (6)^n / 2^n
2^(2*n) = (6)^n
(2^n)^2 = 6^n
2^n = sqrt(6)^n
but what about this?
just take it to infinity and consider making this operation an infinite amount of time
i don't have that ammount of time now, but i will prove that by doing that an infinite ammount of time, it will converge
because it clearlly will
2^n = (6)^n / 2^n
2^(2*n) = (6)^n
``` This transition is wrong. It should've been ```
2^n = (6)^n
2^n * 2^n = (6)^n
2^(n + 1) = (6)^n
```, and this only holds for `n = ln(2)/ln(3)`
So not sure what you're trying to prove there.
no?
wait, right, that part is right.
Wait. This doesn't prove that 2 = sqrt(6). You're assuming that 2^n = 3^n, which only holds for n = 0
so... what's your point?
but by doing this operations
like
look
i can do now
2^n = sqrt(12/2)^n
2^n = 2^(n/2) * sqrt(12)^n
sqrt(2)^n = sqrt(12)^n
and by doing these operation on and on
the values are getting closer and closer
and those will converge
lna/lnb is constant for a fixed a and b assuming a and b belong to the domain of ln
and i will remain with a constant
becase calculus
(a field of math)
2 converging sequences at same point does not imply equality though
It just means that they can have equal limit at infinity.
damn, thought it was botany
and i could just say than that 2^n = 3^n * C
i just putted equal for visual purpose
i would take
the modulo
of the difference
of the terms
and it will converge into 0
because getting closer and closer with smaller and smaller steps
an the constant will be imaginary
sure
i agree
but hey
it's a constant
and NO it is not a constant
we dont take imaginary numbars as constants
Please do show it, then.
as i said i dont have the time to me, but be sure i will show it
A constant is always a constant if you are talking about it in the same underlying field of numbers.
If you work in 2 different domains, such as one which is not an integral domain and other which is, a constant in one domain may not be a constant in other (it might not exist)
but here we are working in the same domain
The definition of O notation (in CS sense, which is actually Big Theta in calculus) is:
f(x) = O(g(x)) means:
lim[x -> inf](f(x) / g(x)) = C,
where C is a non-zero constant
Then it follows
Let f(x) = O(g(x)). Also suppose that K is a non-zero constant.
since f(x) = O(g(x)), then lim[x -> inf](f(x) / g(x)) = C, where C is a non-zero constant.
then, from basic calculus:
lim[x -> inf](f(x) / (g(x) * K)) = C / K
C / K is also a non-zero constant, so clearly then f(x) = O(g(x) * K).
Therefore, for any non-zero constant K, O(g(x)) is the same as O(g(x) * K).
I think this is a pretty straightforward proof. So unless you come up with a different definition of O notation...
ok, so how i see her e
we can take complex numbers as constants
i dont have a problem with that
i literally dont
i love when i have to make an n^2 code and i can prove it is n
it's genius
just take ln(-1) as a constant and make conversions
why not
@austere sparrow
Just found a nice demonstration of n!=(n-2)!
Assume n!=(n-2)!
Divide both sides by (n-2)!
n(n-1)=1
n^2-n-1=0
have you thought of applying for Abel prize? 
you seem to not realise what the O-notation even is.
I just want to show you that by assuming log2=log10 because of an irrational constant is wrong
assuming log2=log10
Great, because it'd indeed be extremely strange to decide that, and no one here does it except for you.
.
.
.
Okay, what algorithm can you use to add two arbitrarily large integers, both b bits long, in less than O(log(n))? π
If you don't know the difference between O(f) == O(g) and f == g, that's on you π€·
in binary, yes
Times a constant but as you guys said does not matter
computers use binary
and wasn't the original claim O(log2 N) anyway
It claimed b steps
actually, python does store numbers as an array, that's how it's able to get arbitrary size ints
buble sort complexity it's O(n^2) or O(n*(n-1))?
O(n*(n-1)) = O(n^2-n)
only the highest degree term is kept,
so O(n^2-n) = O(n^2)
off topic question here, but are there any university professors specializing in mathematical modelling/statistics or economics here?
Assuming an instance of a class has references to other objects of that same type, as:
from dataclasses import dataclass
# please ignore syntax, I know it's wrong, it's just an example
@dataclass
class Node:
value: int = None
root: Node = None
left: Node = None
right: Node = None
But I can't exactly declare root, left, right type of Nodesince by the time I'm declaring it I've not declared the Node class (it's being built).
Does anyone have a good solution to use a typing approach to this problem?
@uncut talon That doesn't seem to fit the channel topic, but you could use a string instead (they're called forward references) left: 'None' = None
@fiery cosmos thanks, that works but seems like it's doing the same thing it'll do if I don't declare the types.
It still allows me to parse any non Node types. to left, root, right, I'd still have to explicitly check types.
@uncut talon Please ping me in a help channel if you want to continue, but the thing is that dataclass doesn't validate the type of arguments you pass in
I think this is not the right channel for such topic.
is learning algorithm a story and how to apply it is important ?
i found it so hard to apply when i write code
a story?
As I see you donβt really have to balance the tree
So you can just insert the new nodes lmao
checks if the value is empty ?
then again it is checking if all the values are empty simulatenously
basically the Attributes are stored in one file
and the data is stored in a database
Thats how they are inserted
But how does it actually retrieve the data?
you could use:py if all(self.EmployeeNumber.get(), self....):
not really visible from the code, probably another method somewhere
Did this
π₯΄ that looks painful.
so my strategy for this
is to treat the deque as just 2 stacks together
and try and put the largest elements at the top and the lowest elements in the queue
if (stack.empty() || queue.empty() || deck.empty()) {
if (stack.empty()) {
cout << "pushStack" << endl;
stack.push_back(op);
} else if (queue.empty()) {
cout << "pushQueue" << endl;
queue.push(op);
} else {
cout << "pushBack" << endl;
deck.push_back(op);
}
} else {
if (op > stack.back()) {
cout << "pushStack" << endl;
stack.push_back(op);
} else if (op > deck.front()) {
cout << "pushFront" << endl;
deck.push_front(op);
} else if (op > deck.back()) {
cout << "pushBack" << endl;
deck.push_back(op);
} else {
cout << "pushQueue" << endl;
queue.push(op);
}
}```here's my c++ code if it's relevant (yes ik this is a python discord,)
but that algorithm seems to WA
I'm doing search method for tree:
def __search(self, current, value):
print("current.value:", current.value)
if value == current.value:
return True
elif value < current.value and current.left is not None:
return self.__search(current.left, value)
elif value > current.value and current.right is not None:
return self.__search(current.right, value)
return False
def search(self, value):
current = self.root
return self.__search(current, value)
so if we did print(tree.search(1))
1 would return True
Then in the call stack 2 would return True that we received from 1
4 return True that we originally received from 1 and so on...?
is anyone good with algos ard here?
specifically uninformed and informed search
really need someone to guide me for an assignment
"myfloat = 7.0
print"(myfloat)"
"myfloat = float(7)
print"(myfloat)" whats wrong
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
hello, is it possible to create nested dict instantly like this?
given_key = "data.nest.nestagain"
sampledict = {}
sampledict[given_key] = "hello"
so far, this is what I found https://github.com/mewwts/addict , but it needs me to use it like this:
sampledict.data.nest.nestagain = "hello" # I cannot use this since my key is an actual string from db
you can write the literal
sampledict = {"data": {"nest" : {"nestagain" : "hello"}}}
or write a function that does it
class Node:
def __init__(self, data):
self.data = None
self.next = None
class ClinkedList:
def __init__(self):
self.head = None
def prepend(self,data):
if self.head:
self.head=Node(data)
self.head.next=self.head
else:
new_node=Node(data)
cur_node=self.head
while cur_node.next!=self.head:
cur_node=cur_node.next
cur_node.next=new_node
new_node.next=self.head
self.head=new_node
def append(self,data):
if not self.head:
self.head=Node(data)
self.head.next=self.head
else:
new_node=Node(data)
cur_node=self.head
while cur_node.next!=self.head:
cur_node=cur_node.next
cur_node.next=new_node
new_node.next=self.head
def printlist(self):
cue =self.head
while cue:
print(cue.data)
cue=cue.next
if cue ==self.head:
break
cclist = ClinkedList()
cclist.append("D")
cclist.append("C")
cclist.prepend("B")
cclist.prepend("A")
cclist.printlist()
circular linked list
output problem
what's the problem?
Hi! I'm looking for help for a formal proof of a boolean expression, namely "(True β x) β‘ x", as I keep getting stuck at ((x β¨ Β¬True) β§ (Β¬x β¨ True)) - anyone that can help?
does that emoji mean or
equivalent, I think
eh? isn't that =
probably
Either way
True <=> x
= (Β¬True β§ Β¬x) β¨ (True β§ x)
= False β¨ x
= x
In [17]: print(TruthTable('p and q', 'p or q', 'p then q', 'p iff q'))
βββββ¬ββββ¬ββββββββββ¬βββββββββ¬βββββββββββ¬ββββββββββ
β p β q β p and q β p or q β p then q β p iff q β
βββββΌββββΌββββββββββΌβββββββββΌβββββββββββΌββββββββββ€
β F β F β F β F β T β T β
β F β T β F β T β T β F β
β T β F β F β T β F β F β
β T β T β T β T β T β T β
βββββ΄ββββ΄ββββββββββ΄βββββββββ΄βββββββββββ΄ββββββββββ
flexin
can it take literals in place of p/q
yes
can it make me a smoothie
In [18]: print(TruthTable('T iff x'))
βββββ¬ββββββββββ
β x β T iff x β
βββββΌββββββββββ€
β F β F β
β T β T β
βββββ΄ββββββββββ
i'll take it!
β
any good resources for learning nested loops in python ? , i really struggle with problems where i need to print patterns.
There are several ways to break out of nested loops (multiple loops) in Python.This article describes the following contents.How to write nested loops in Python Use else, continue Add a flag variable Avoid nested loops with itertools.product() Speed comparison See the following article for the basic...
you are welcome π
Hello guys, making a task:
Some spherical balls are distributed in two-dimensional space. For each ball, the x-coordinates of the beginning and end of its horizontal diameter are given. Since space is two-dimensional, y-coordinates are irrelevant in this problem. Xstart is always less than xend. The arrow can be fired strictly vertically (along the y-axis) from different points on the x-axis. A ball with coordinates xstart and xend is destroyed by an arrow if it was fired from a position x such that xstart β©½ x β©½ xend. When the arrow is released, it flies through space for an infinite time (destroying all balls in the path). An array points are given, where points [i] = [xstart, xend]. Write a function that returns the minimum number of arrows you need to fire to destroy all the balls
Tested Cases
1.1 [[10,16],[2,8],[1,6],[7,12]] 2
1.2 [[1,2],[3,4],[5,6],[7,8]] 4
1.3 [[1,2],[2,3],[3,4],[4,5]] 2
1.4 [[1,2]] 1
1.5 [[2,3],[2,3]] 1
1.6 [[1,10],[2,11],[3,12],[4,13],[5,14]] 1
def balloons(matrix):
peeks = {}
for i in matrix:
for key in i:
peeks.update({key: 0})
for i in matrix:
for j in range(min(i), max(i)+1):
if j in peeks:
peeks[j] += 1
return int(len(matrix) / max(peeks.values()))
balloons([[10,16],[2,8],[1,6],[7,12]])```
but I`m feeling that i missed smth.
Will be helpfull if u can help me with some tests and bugfixes
Since space is two-dimensional, y-coordinates are irrelevant in this problem
what
I think they meant one-dimensional lol
The arrow can be fired strictly vertically (along the y-axis)
π
ah, I see what they mean
y-coordinates are indeed irrelevant, but their reasoning for why is rather wrong π
its been translated from russian, so maybe some mistakes
if u need, i can explain idea of that code
I don't think your algorithm works, because it only seems to care about ends of the ranges
but if arrow shoots between that ranges, we hit balloon
and subtask is make code than shows min arrows to hit all balloons
it means some balloons can overlap
and with 1 arrow we can hit unlimited balloons in X-axis
consider, say, [[1,10],[2,11],[3,12],[4,13],[5,14]]. All of these can be hit with one arrow, launched anywhere between 5 and 10
but it shows 2?
ah, your code does answer right on this one
yeah, 1
ah, I see now
i have my viva in 5 hours and they may ask questions on threading
can anybody suggest any docs / video abt threading which explains it real quick
i saw this i didnt understand
wow man, u reactive
Guys Im stuck on the second part of this question:
Write a Python program to create three classes. First, Second and Third such that
Second is a child class of First and Third is a child of Second. Each class contains
its own instance variable names 'data'. Describe a way for a method in Third to access
and set First's version of 'Data' to a given value, without changing Second or Third's
version.
Can someone pls helpp??
do u understand russian?
only english
wanna know why we use .join()
translate by google
join waits for a thread to finish.
why doesnt then it makes the code slow
i ran the code without .join()
the time difference wasnt much
so whats the benefit?
as more threads, more steps
on what code do u ran?
Not sure what you mean.
join is how you wait for a thread to finish. Sometimes that's something you need to do, sometimes not.
i guess he means that he ran with threading and without and wanna make from Python - C++ by using multithreads
D
import threading
import time
def smth():
print('qwerty')
time.sleep(1)
print('sleep done')
a = []
for i in range(10):
t1 = threading.Thread(target=smth)
t1.start()
a.append(t1)
for i in a :
i.join()
# smth()
# smth()
π
is join needed over here?
i dont really think that u need threading at this such code
since you loop from the min to the max, if you have a range like [0, 2**20] your algorithm will take forever
pfffff
im just learning
ofc it does
lel
it's possible to solve it better, without that issue lol
any ideas how?
import random
import threading
# dictionary which stores seat nos and names of people who got it
tickets = {
'T01': '',
'T02': '',
'T03': '',
'T04': '',
}
# Seats remaining to be alloted
remaining_seats = list(tickets)
# Function to randomly assign seats to people
def assign_ticket(dict, person, lock):
lock.acquire()
temp = random.choice(remaining_seats)
dict[temp] = person.name
remaining_seats.remove(temp)
lock.release()
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
lock = threading.Lock()
p1 = Person('Alvin', 19)
p2 = Person('John', 20)
p3 = Person('Pal', 19)
p4 = Person('Rahul', 19)
# Threads to simulate multiple people booking simultaneously
t1 = threading.Thread(target=assign_ticket, args=(tickets, p1, lock))
t2 = threading.Thread(target=assign_ticket, args=(tickets, p2, lock))
t3 = threading.Thread(target=assign_ticket, args=(tickets, p3, lock))
t4 = threading.Thread(target=assign_ticket, args=(tickets, p4, lock))
t1.start()
t2.start()
t3.start()
t4.start()
t1.join()
t2.join()
t3.join()
t4.join()
# Display the assigned seats
for i in list(tickets):
print(i, ':', tickets[i])
the question was: Write a python program to achieve thread synchronization using locks when multiple
passengers are booking the ticket simultaneously.
yeah. you can use greedy algorithm
hello, I have an array of vectors ( 2d shape n, 3 ) and I want to get the length ( np.sqrt(x.dot(x)) ) of each one...
You can do that in a vectorized fashion via np.sqrt((arr**2).sum(axis=1)), say.
will try thanks
it worked, noice
I got one more a bit complex ( maybe )
I have 2 arrays, different sizes, and I want to make an operation between them that would have a result of the shape of the first one, with a "stride" of the size of the second one ( both have size 3 on the second dimension )
have I explained it clearly?
oh, actually, the result will be the average ( or maybe some other operation )
of each result
or maybe a 2d array that I can operate on it afterwards
that might be more suited for #data-science-and-ml
sorry, I will go there thanks
(also, no, don't quite get what you want to do)
I have a list of ints which all start at 0, and theyβre randomly incremented by 1. They can also randomly be reset to 0 all at once. Is there a way to reset all of them to 0 in O(1) time? As in not actually going through the list and setting them to 0, but doing something which effectively achieves the same effect
You could use some custom objects instead of ints, and request their int value using a method.
They would all store the last time (in nanoseconds, perhaps?) when they were last incremented.
And then you could have a shared source of when the last reset occured.
Yeah, that might work, that seems like a good idea
They would all store the last time (in nanoseconds, perhaps?) when they were last incremented.
There's no reason to store a time, just a counter. Every time you reset, increment the "number of resets" counter, and every time you read a value, check whether the stored copy of the counter matches the current value of the counter.
that's using the counter as a generation id.
and then you just ignore values that were last incremented in a previous generation, and treat them as 0 instead.
Hey @analog pagoda!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
β’ If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
β’ If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
Hey I'm coding a small physics engine in micropython, however I get an error saying 'bool' object isnt subscriptable
!e That's what you'd get if you tried to do True[0]:
True[0]
@lean dome :x: Your eval job has completed with return code 1.
001 | <string>:1: SyntaxWarning: 'bool' object is not subscriptable; perhaps you missed a comma?
002 | Traceback (most recent call last):
003 | File "<string>", line 1, in <module>
004 | TypeError: 'bool' object is not subscriptable
you've got a [] being applied to the wrong type of object.
Pastebin.com is the number one paste tool since 2002. Pastebin is a website where you can store text online for a set period of time.
Could you take a look at this code, specifically
def scatter(self, particles, nparticles):
where = self.intersection(particles, nparticles)
if where[0] and particles[where[1]].isscatter:
# avoid multiple scatters at same moment
particles[where[1]].isscatter = False
self.isscatter = False
# Total and Difference Mass to Simplify Calculation
totalmass = self.mass + particles[where[1]].mass
massdiff = self.mass - particles[where[1]].mass
# store velocity variable to avoid error caused by sequential calculation
tempvelocity = [self.velocity[0], self.velocity[1]]
self.velocity[0] = (massdiff * self.velocity[0] + 2 * particles[where[1]].mass *
particles[where[1]].velocity[0]) / totalmass
self.velocity[1] = (massdiff * self.velocity[1] + 2 * particles[where[1]].mass *
particles[where[1]].velocity[1]) / totalmass
particles[where[1]].velocity[0] = (-massdiff * tempvelocity[0] + 2 * self.mass * tempvelocity[
0]) / totalmass
particles[where[1]].velocity[1] = (-massdiff * tempvelocity[1] + 2 * self.mass * tempvelocity[
1]) / totalmass
Nparticles = 2
rangeparticles = range(Nparticles)
mainparticles = []
mainparticles += [particle([64,0],30,[-1,0],0)]
mainparticles += [particle([64,0],30,[1,0],1)]
while True:
for i in rangeparticles:
mainparticles[1].clear()
for i in rangeparticles:
mainparticles[i].update()
for i in rangeparticles:
mainparticles[i].scatter(mainparticles,Nparticles)
for i in rangeparticles:
mainparticles[i].isscatter = True
mainparticles[i].move()
where = self.intersection(particles, nparticles)
if where[0] and particles[where[1]].isscatter:
That's buggy.
self.intersection can return False, and if it does then you subscript False[0]
Maybe you meant return [False] instead of return False in intersection
whoa that seemed to work!
def intersection(self, particles, nparticles):
for i in range(nparticles):
if i != self.index:
x = self.position[0] - particles[i].position[0]
y = self.position[1] - particles[i].position[1]
if x ** 2 + y ** 2 < 1:
return [True, i]
else:
return [False]
also - that only ever looks at the first or second particle
if self.index == 0, then it looks at the second particle, otherwise it looks at the first.
I think you meant to do:
def intersection(self, particles, nparticles):
for i in range(nparticles):
if i != self.index:
x = self.position[0] - particles[i].position[0]
y = self.position[1] - particles[i].position[1]
if x ** 2 + y ** 2 < 1:
return [True, i]
return [False]
so that the False case is only hit after iterating over all possible particles.
Oh okay, that makes more sense! I'm trying to port a simple physics engine into micropython, the code im trying to port is from a video on youtube, the uploader lost the original files
Aside from creating basic particles and moving them, now im trying to implement his collison detection
let me try this!!
@fervent saddle I should have pinged you on this ^
Thank you, that was the first thing I thought of following the idea. But still I was thinking about how long it would work if you were using nanoseconds. Even if you werenβt using python, even if you were in C or something with limited numeric sizes, it would still work for centuries if you used an 8 byte number
So thatβs cool. This was a good idea for this. This is a really helpful discord server
the reason not to use nanoseconds isn't that it'll overflow, it's that getting the current time is a relatively slow operation, and all you need is a value that changes over time without repeating, so there's no reason to pay the cost of getting the time.
right, that's a better idea
Yeah it seems like that would still be a better idea.
Guys, so I made a GIT with the physics engine, could some of you take a look if you have the time and help me figure out why it's broken?
https://github.com/theaxxxin/micropython-physics
Create a function called append_size that has one parameter named lst.
The function should append the size of lst (inclusive) to the end of lst. The function should then return this new list.
For example, if lst was [23, 42, 108], the function should return [23, 42, 108, 3] because the size of lst was originally 3.
Here's my code
#Write your function here
def append_size(lst):
counter = 0
for x in range(len(lst)):
counter += 1
print(lst.append(counter))
#Uncomment the line below when your function is done
print(append_size([23, 42, 108]))
but why doesn't this approach work? It prints out:
None
None
append doesn't return a new list it returns None
your function also doesn't return anything
ahhh
How hash-tables works, and why 3 in {1,2,3,4} works by O(1)?
magic they work by hashing (hence the name) the value, and using the hash value as an index in an array
since it only checks one spot, it's O(1)
objects get a unique* key through the hash function, so the table knows exactly where to look for it
*mostly
!e ```py
def string_hash(s):
return sum(map(ord, s))
def add_hash_set_string(hash_set, s):
hash_set[string_hash(s) % len(hash_set)].append(s)
def check_hash_set_string(hash_set, s):
return s in hash_set[string_hash(s) % len(hash_set)]
hash_set_size = 50
hash_set = [[] for _ in range(hash_set_size)]
test_strings = ("first", "second", "third", "fourth", "fifth")
for ind in range(0, len(test_strings), 2):
add_hash_set_string(hash_set, test_strings[ind])
for s in test_strings:
print(s, check_hash_set_string(hash_set, s))```
@fervent saddle :white_check_mark: Your eval job has completed with return code 0.
001 | first True
002 | second False
003 | third True
004 | fourth False
005 | fifth True
Thatβs the really basic idea of it
There are a lot of different ways to deal with if multiple hash values go to the same index. That way is closed addressing, where each index in the hash table is another data structure, in that case another list
Thereβs also open addressing where itβs just stored in a different place in the hash table array itself
It can be a lot more complex than that, involving things that are way over my head, but thatβs some of the basic ideas involved
In python, objects have __hash__ dunder methods which are used to get their hash values
And if they donβt have a __hash__ method then it uses their memory address
Write a function named append_sum that has one parameter β a list named named lst.
The function should add the last two elements of lst together and append the result to lst. It should do this process three times and then return lst.
For example, if lst started as [1, 1, 2], the final result should be [1, 1, 2, 3, 5, 8].
#Write your function here
def append_sum(lst):
for x in range(len(lst)):
update = lst[-1] + lst[-2]
lst.append(update)
return lst
print(append_sum([2,5]))
with 2,5 as my input it stops at 12, but it should be 2 , 5 , 7, 12, 19
because you don;t do it three times
you do length of list instead
so it needs to be three for you to do three, and it's not necessarily three
e.g. 2,5 is 2 and not 3
Hey guys, Is there any too to convert python code to java?
You can use Jython for example to run Python code in JVM
However I don't know the easy way to convert one language to another one
Thanks π
What have you tried? Do you have any error?
https://www.codewars.com/kata/5ed7625f548425001205e290
hi, having hard time solving this Typing challenge and can't progress.
Maybe because it's hard to debug locally or can't imagine using recursion for these 'Type things/objects?', which is a must to solve those nested Types probably.
Also Typing module seems to be changed between python versions, which adds to confusion maybe.
Basically you have to return type itself from args. Like:
to_type_hint((1, "2", 3, 4.0)) => Tuple[Union[int, str, float], ...]
to_type_hint(([1, 2], [])) => Tuple[List[int], list]```
I can check basic types with type(arg), but can't see even with intense googling how to solve it fully.
Thanks for tips.
Hi, I've a bug and I would like some indication about what's the issue.
import fs
from zipfile import ZipFile
# source zip in OSFS
src_zip = "/home/andrea/nmr/hsqc.topspin.zip"
# instantiate in-memory ephemeral FS
mem_fs = fs.open_fs('mem://')
with mem_fs:
# open zip as ZipFS, copy content of zip in mem_FS
with ZipFS(src_zip) as zip_fs:
fs.copy.copy_fs(zip_fs,mem_fs)
# how do I point at files?
os.listdir('mem://')
output:
----------------------------------
FileNotFoundError Traceback (most recent call last)
<ipython-input-35-b5cb46aef5ec> in <module>
11 fs.copy.copy_fs(zip_fs,mem_fs)
12 # how do I point at files?
---> 13 os.listdir('mem://')
14
15
FileNotFoundError: [Errno 2] No such file or directory: 'mem://'
How can I access to the PATH of the files in mem_fs?
context: I've got an ugly external library that accepts the path of a folder where it expects to find some files. The folder is the unzipped file in the mem_fs
How do I adjust Floyd's cycle detection for multiple duplicates? Here is what I thought.:
I think when having multiple duplicates, we would have more than one cycle. So my first step would be to adjust it so it finds multiple cycles.
Suppose somehow we are able to detect mutiple cycles, so for each cycle we would need two pointers ( I think) to find the entry point.
So we would have something like :
---------o ``` with `o` as the cycle and `------` as the part from where we start the pointers.
In case of multiple cycles , we would have multiple `-------o`, so I just need to FIND the first `-` from my `------o` , which would just be the number NOT in `------o` which I have already visited. HOW DO I FIND THIS optimally? - `(1)`
Now I need to find entry points of the cycle, so that is guaranteed by number of steps required to get from index 0 (or my first `-`), to the starting points mod length of cycle = no. of steps it takes from the meeting point of the two pointers in the cycle up to the entry point of the cycle and hence we have a duplicate.
Is this approach feasible? And if it is then how do I find `(1)`
How would you guys go about finding the least lines that will pass through all points on a 2D matrix?
are there any resources on the topic?
Won't that be just the minimum of {m,n} in a m*n matrix? Unless there is another constraint (going through specific points or avoiding certain points), u can look up Hungarian Algorithm
@serene mango It might be super simple, but my head is super fried
I want to begin with just solving that
Later I will add constraints as parameters
Imma check that out, thanks @serene mango
Four jobs need to be executed by four workers. A step by step explanation shows how the optimal assignment can be found using the Hungarian algorithm.
Awesome, thanks @serene mango
No problem :)) 
i dont really understand the question tho
@minor pumice Input are points like (1,2), (2,4),(5,5).... and I want to find the minimum number of lines that will pass through all those points
why using this and not bitmask dp?
the lines must pe paralel to the axis?
That can be a parameter but right now no, I don't want that
I want to start by just solving it
like we can put (1,1) and (2,2) on the same line?
Yeah, that's the point
what is the compleixty you want?
n^2 is ok?
i dont think you even can better but maybe i am wrong
Yep, that's great
ok so
you want
to see at every point the maximum number of coliniar points
and if you have 2 points with coordinates (x1,y1) and (x2,y2) do you know how to see if they are colliniar? (it is a math formula)
wait sry
2 points are coliniar no matter what
lol
ok so
you will want to see the maximum number of colliniar points
we can do this by the angle the points joined with the (0, 0) form
agree?
like if 2 points have the same angle with Ox they will be on the same line
Makes sense, yeah
and you can map the points but will have a log(n)
So you say i use the (0,0) as a comparison point for all the other points
if N and M are small you can use a trick
nope
you cont want to see the points in a matrix
!e
typing's API is indeed a bit hard, but for this you just need to subscript the types, right?
import typing
def get_list_type(xs): # doesn't support nested structures!
if xs == []:
return typing.List
else:
types = set(map(type, xs))
if len(types) == 1:
return typing.List[types.pop()]
else:
return typing.List[typing.Union[(*types,)]]
print(get_list_type([]))
print(get_list_type([1, 2, 3]))
print(get_list_type([1, 2, "foo"]))
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | typing.List
002 | typing.List[int]
003 | typing.List[typing.Union[str, int]]
you want to see them from a geometrical point of view
it's easier
so
just consider (0,0) as the point of reference
Okay cool
do you know how to sort the points with the angle formed with Ox?
Yeah, I can do that

