#algos-and-data-structs
1 messages · Page 82 of 1
def recursion_starter(rest_number_of_stairs: int) -> int:
number_of_ways = 0
def recursive_climb(rest_number_of_stairs: int):
if rest_number_of_stairs == 0:
nonlocal number_of_ways
number_of_ways += 1
elif rest_number_of_stairs == 1:
recursive_climb(rest_number_of_stairs - 1) # one step
else:
recursive_climb(rest_number_of_stairs - 1) # one step
recursive_climb(rest_number_of_stairs - 2) # two steps
return number_of_ways
class ClimbingStairs:
@staticmethod
def climbing_stairs(number_of_stairs: int) -> int:
if number_of_stairs <= 0:
return 0
else:
return recursion_starter(number_of_stairs)
def func():
count = 0
def new_func():
nonlocal count
def new_new_func():
nonlocal count
...
You mean like this?
Feels like "break gosh darn it"
Because it seems to not change number_of_ways
you only increment it on == 0
you should declare nonlocal outside of the if statements probably
Yes I had it befire the if's but same result
why is incrementint it on == 0 a problem?
It worked before
because it should always reach == 0
It seems nonlocal does not work as expected
I finally understand why this function kept bothering me.
Why aren't we accumulating and adding number of steps?
Like an acc parameter that you keep passing through all recursive calls
because I don't want to count the number of steps
Sadly my brain can't think recursion
I want to calculate how many ways their is to climb the stairs
My brain keeps thinking that shouldn't matter.
I'll tell my brain to go quiet. Carry on
that is the task, and the first code I posted does work. But I wanted to know if there is a better way
>>> def stairs(n):
... if n <= 1:
... return 1
... return stairs(n - 1) + stairs(n - 2)
...
>>> stairs(10)
89
>>>
is that right?
What's the output of stairs 3?
Oh yes this seems to work too
3
Pretty.
it's like reverse fibonacci
look familiar?:
>>> stairs(3)
3
>>> stairs(4)
5
>>> stairs(5)
8
>>> stairs(6)
13
it's not reverse! it is fibonacci
nice
And I found the problem with my code
Forgot to call the recursive function
def recursion_starter(number_of_stairs: int) -> int:
number_of_ways = 0
def recursive_climb(rest_number_of_stairs: int):
if rest_number_of_stairs == 0:
nonlocal number_of_ways
number_of_ways += 1
elif rest_number_of_stairs == 1:
recursive_climb(rest_number_of_stairs - 1) # one step
else:
recursive_climb(rest_number_of_stairs - 1) # one step
recursive_climb(rest_number_of_stairs - 2) # two steps
recursive_climb(number_of_stairs)
return number_of_ways
That worked
Thanks guys
@cursive cloud you don't need an outer function or nonlocal or anything
def recursive_climb(rest_number_of_stairs: int):
if rest_number_of_stairs == 0:
return 1
elif rest_number_of_stairs == 1:
return recursive_climb(rest_number_of_stairs - 1)
else:
return recursive_climb(rest_number_of_stairs - 1) + recursive_climb(rest_number_of_stairs - 2)
This is exactly the same
Which you then can turn into what salt-die wrote
that complexity...
what state of the art algorithms?
@marble basalt the usual, GA, PSO, CA
@cursive cloud you don't need an outer function or nonlocal or anything
def recursive_climb(rest_number_of_stairs: int): if rest_number_of_stairs == 0: return 1 elif rest_number_of_stairs == 1: return recursive_climb(rest_number_of_stairs - 1) else: return recursive_climb(rest_number_of_stairs - 1) + recursive_climb(rest_number_of_stairs - 2)
@quasi oracle
How do I post my codes like this?
use the `
surround your code in `` and itll do it
like this
Not quite sure how you get the colors
you put py after the triple ``` and a newline
the colors are for different languages of code i think
```py
print("stuff")
```
py for python
print("stuff")
theres a lot of supported languages like java, c+, html, css, etc
wait maybe c+ isnt supported
theres a website that lists all of the supported languages
hello
i am using git
and i want to update the changes i made into the branch other than master
but when i do
git checkout <branch-name>
it tells me i have unsaved changes i need to commit them first
but commiting changes would update the changes in master branch
how do i solve this
?
Shouldn't it be git checkout -b <branch-name>?
that happened because you worked in master before @knotty rapids
probably you can use git stash first, then do this
Shouldn't it be
git checkout -b <branch-name>?
@chrome lava
yea
but i have a branch
if it already exist, you dont have to -b
no problem
😄
how is this
!warn 555874683086700551 This is not the place for ASCII spam. Do not send irrelevant messages to on-topic channels.
:incoming_envelope: :ok_hand: applied warning to @glossy rose.
https://www.youtube.com/watch?v=EK32jo7i5LQ&t=693s
Not sure if this is the right channel to ask this question, but i am currently doing an assignment and i need to do this spiral graph by following the youtube link as attached. How do i start?
A story of mathematical play.
Home page: https://www.3blue1brown.com
Brought to you by you: http://3b1b.co/spiral-thanks
Based on this Math Stack Exchange post:
https://math.stackexchange.com/questions/885879/meaning-of-rays-in-polar-plot-of-prime-numbers/885894
Want to lear...
I would start by figuring you how to draw circles
there are quite a few options: Processing.py, pygame, pillow, matplotlib, pyglet, blender, arcade, ...
anyone got a tldr on the chomsky hierarchy?
formal languages fall into different categories, depending on the formal automata that generate them
it goes regular < context free < context sensitive < recursive
and those correspond to finite acceptors, pushdown automata, queue automata, and turing machines
@rain relic
what are the main differences between these 4 levels of the hierarchy though
are they equivalent?
Aha
regular languages contain every finite language and every infinite language generated by a regular expression
context free contain every language generated by context free grammars
context sensitive contains every language generated by context sensitive grammar
and recursive languages are accepted by turing machines
turing machine are a superset of pushdown automata
pushdown automata is a superset of finite acceptors
Thanks for the overview, the lack of theory of computation at my undergrad keeps me wanting to learn more of it on my own
thanks again
good luck with your studies, here's all the facts from automata theory in 2 pictures
Can someone tell me how to fix these rounding issues?
pretty much every calculation ends up with x.9999999999999 or something similar, even when i subtract 0.0499999.. from 0.95 i get 0.899999.. wich makes absolutely no sense to me
essentially, floating points are not great for exact math. You can use either decimal.Decimal or fractions.Fraction
My numbers dont have to be very precise, is there any way to influence the output to round to the nearest number with k decimals or something?
You can use the .3f format specifier to round to that many digits
does that also apply to lists? eg print(x.3f) with x being a list of floats it doesnt appear to work
no, you will have to do something like
print([format(x, '.3f') for x in some_list])
ah nice tyvm
Can someone help with c xD
Idk how to check if the inputted string has duplicate chars
if you know you only get trivial ascii (0 - 128), you could make a 128 long array of 0s and put a char there when you find it. If you ever try to place a character twice, it is duplicate
essentially a simpler hash table
where the hash function is identity
Sry im new to this and im not rly sure wut u mean
This is what i tried
It is 26 characters hence the 13
Bc i didnt want the chars to meet in the middle and be equal
Although ik theres most definately a better way to go about this and i probably messed up the loops😭
If you're not required to do it in a C style language and you can use any builtin python functionality, there's a simpler way to do it.
I wish, unfortuantely this must be done in c..
This looks like Java though.
Since C99 or so you can
Well big thanks to my C professor.
xD
People have outdated knowledge of C and C++, and java, for that matter, quite often
Python is much more effective to use right?
Eh, it depends. For most things, python will be much easier than C
Im assuming they teach c to beginners in this course so that i have to suffer with typing out stuff that other languages would have as a command? XD
And understand the logic behind it
Idk tho
C is a solid starter language because it teaches you about the foundations of computing with memory management, pointers and such nonsense, while being pretty high level
Python is much more effective to use right?
@cyan gull
A lot of people feel that Python more effectively communicates what the code is doing, since that was one of its most important design principles. It's slow compared to C though.
Ah i see
Also i was just wondering
They make a big emphasis
On memory and stuff when creating variables
How often is that knowledge really applied
When coding
Is it really nessacary to know that much in detail?
Well, it you're not worried about memory management, it's because the language is handling it for you.
C doesn't.
There are cases for handling your own memory. Most people write C++ or rust, which has nicer memory management than C
Alright
Would C be considered sort of irelevant with all these new languages and c#?
Sry for all the questions
C++*
C# is basically Windows Java.
Ohhh thanks for clearing that up
These days, there are efforts at replacing C with languages like Zig, V, Go, .... There is no real reason to use C these days beyond short snippets which must go fast
I would only use C to make python modules
Hello
And even then that's not the same as C because the Python API for C does a lot of the work.
Simple take input, do math, write output programs are pretty simple in C and do often benefit from performance. There is a difference in feeling between something taking .5s And .03s
Alright thx guys for the help
@fiery cosmos hi
This channel is specifically for talking about computer science. python -i in your terminal will open an interactive session.
OK
Take a look at #❓|how-to-get-help if you have more questions
C# is basically Windows Java.
@oblique panther lmao, so true tho
!tempmute 555874683086700551 7d You have been told repeatedly to not interrupt on-topic channels, yet you continue to post unproductive messages. Take the time off and review what each of our channels are for by reading the channel description.
:incoming_envelope: :ok_hand: applied mute to @glossy rose until 2020-07-16 05:48 (6 days and 23 hours).
def minimax(move, depth, maximizingPlayer):
if depth == 0:
move.eval = calculate(move)
return move
if maximizingPlayer:
maximizedMove = Move(-math.inf)
for m in get_possible_moves(move.board):
evaluatedMove = minimax(m, depth - 1, False)
maximizedMove = evaluatedMove if evaluatedMove.eval > maximizedMove.eval else maximizedMove
return maximizedMove
else:
minimizedMove = Move(math.inf)
for m in get_possible_moves(move.board):
evaluatedMove = minimax(m, depth - 1, True)
minimizedMove = evaluatedMove if evaluatedMove.eval < minimizedMove.eval else minimizedMove
return minimizedMove
Hey guys! I've been trying to make this minimax algorithm work for quite some time, it seems to work well to determine best moves, but the thing is when the function is over it returns the last move that was played, but I want to receive the move that I need to play right now to follow the path determined...
can someone help with RL and time series?
Guys, what is the best way to find the index of the lowest integer in a list?
l = [3, 4, 2, 1, 9]
l.index(min(l))
this is inefficient
potentially you loop one time to find the min, and then another time to find the index
maybe a reduce-type of method where u keep the index with the lowest value and return?
this would work, but it is quite ugly min(map(reverse, enumerate(l)))[1]
or, for lists only, min(range(len(l)), key=l.__getitem__)
if you want to understand what's your doing, you could create your own function, but I guess it'll slower (?) than using builtins
something like that
def imin(l):
m = l[0]
m_i = 0
for i, x in enumerate(l):
if x < m:
m, m_i = x, i
return m_i
tx
took me a second but I get min(range(len(l)), key=l.__getitem__) and thanks for the long-hand explanation too
@astral path You have to iterate over all elements.
Note that @trail anchor will iterate over the list twice, so if performance is a concern, you might want to iterate over the list yourself rather than using min and index.
i just found out that in the list i have some integers that are equal to eachother, will that complicate things?
It depends if you only want the first one, last one, any of them or all of them. And either cases, it won't complicate things, just change the code. The usual behavior is to return the lowest index element.
okay, the usual behaviour will be enough
efficiency will also not be much of a problem
this is just practice for a competition so yeah i got time as long as i get it to work
If I want to become better at thinking recursively and writing recursive functions, should I read more python or try some Project Euler exercises in erlang?
Can anyome help with a basic c question pls
What do you mean by reading more python? I don't know if project euler specifically is the best place, but exercising is key @fiery cosmos
@cyan gull this is a python server
Yea ik xD i was just wondering lmao nvm then
Seeking out more recursion examples and recursion challenges.
And reading python solutions to them to understand them when I'm stumped
There are some classic recursion examples anyone should know. If you're familiar with them, you should try solving problems on your own
That's been my workflow so far. But I remember going to a conference about 8 years ago and attended an Erlang lab. I remember doing well on the exercises because Erlang doesn't have loop constructs. It forced me to think functionally and recursively versus defaulting to loops and iterators.
What are some of the examples you mention @quasi oracle ? Like BST traversal?
Anything from summing sequences (arithmetic, fibonacci etc) to BST traversal, DFS, and similar problems
You can open a help channel if you're struggling with something specific, but you need to try to get through it without looking at a solution (assuming you didn't jump right into super complicated stuff)
Why does this:
print([[list]])
result in this:
[[array(['a', 'b'], dtype='<U15')]]
why wont it just output it without all the nonsense?
I don't have that problem. Prints w/ expected behavior.
using numpy?
yes
def rec_perm(list):
res = []
if len(list) <= 2:
print([[list]])
return [[list]]
for i in range(len(list)-1):
touple = [list[0], list[i+1]]
tmp = rec_perm(np.delete(np.delete(list, i+1), 0))
for k in range(len(tmp)):
tmp[k].append(touple)
for x in tmp:
res.append(x)
return res```
full code
this is nearly unreadable, what is it supposed to be doing? and if you're doing this much appending/deleting i'd just not use numpy --- it won't be faster, especially with all these python loops
numpy creates an new array for each delete
hello everyone, I am new to this server and to python. I graduated in IT majoring in web & s/w dev in 2014 but feel like I dont know even basic coding concepts. I have enrolled in a DS course recently and committed to improving my coding skills.
I am having trouble understanding the use of flags in the code flow below:
#write a program to print prime number b/w 1 to 20
for n in range(2,20):
flag = True
for i in range(2,n):
if n % i == 0:
flag = False
break
if flag :
print(n)
When I try to run below code without the use of flads, I get even numbers as output:
#write a program to print prime number b/w 1 to 20
for n in range(2,20):
for i in range(2,n):
if n % i != 0:
break
print(n)```
Any help is appreciated. Thank you.
you should try using
l = []
x >1
for i in range(2,20):
if x % i != 0:
l.append(i)
print("these are the prime numbers between 2 and 20",l)
@cyan current i don't think you should get any ouput from the bottom code as the print is below a break so its unreachable, instead of using flags, you can use a similar aproach as the top but instead of having a flag, you can have an else or that for loop, that will only be run if there was no break so you can remove the flag variable all together end replace if flag: with else
however, a faster method of finding primes upto a limit is the Sieve of Eratosthenes, its not too complicated and should be a faster alternative for larger values if you are interested in that aproach
@visual dagger I tried that code but line x>1 is throwing error TypeError: '>' not supported between instances of 'list' and 'int' I tried declaring it as range(2,20) and list but it did not work. I will try @topaz pulsar 's approach now.
I really appreciate the help from you both. Thank you
hello everyone, I am new to this server and to python. I graduated in IT majoring in web & s/w dev in 2014 but feel like I dont know even basic coding concepts. I have enrolled in a DS course recently and committed to improving my coding skills.
I am having trouble understanding the use of flags in the code flow below:#write a program to print prime number b/w 1 to 20 for n in range(2,20): flag = True for i in range(2,n): if n % i == 0: flag = False break if flag : print(n)When I try to run below code without the use of flads, I get even numbers as output:
#write a program to print prime number b/w 1 to 20 for n in range(2,20): for i in range(2,n): if n % i != 0: break print(n)``` Any help is appreciated. Thank you.
@cyan current If a number n is divisible by any of the numbers 2 up to itself, it is not a prime number, as it is a number only divisible by 1 and itself.
The flag is there such that the non prime number will not be printed by the program (after it breaks from the inner loop because we found one counter example, and thus there is no reason to continue).
It might help if you write out the loops and try to trace the numbers and do the conditional checking for yourself to get more feeling for it
although renaming flag to prime or is_prime might have made it more descriptive
@visual dagger I tried that code but line
x>1is throwing errorTypeError: '>' not supported between instances of 'list' and 'int'I tried declaring it as range(2,20) and list but it did not work. I will try @topaz pulsar 's approach now.
I really appreciate the help from you both. Thank you
@cyan current mine loginc was that taking x as greater than one so that I can divide that "i" from the "x" to find if the remainder is zero or not
I'll try to correct my error
@cyan current If a number n is divisible by any of the numbers 2 up to itself, it is not a prime number, as it is a number only divisible by 1 and itself.
The flag is there such that the non prime number will not be printed by the program (after it breaks from the inner loop because we found one counter example, and thus there is no reason to continue).
It might help if you write out the loops and try to trace the numbers and do the conditional checking for yourself to get more feeling for it
@fiery cosmos HEY you should really try some short course on python by watching it on youtube or as you like
and for the code you asked about is that
the "Flag" is just a variable that is set to be "True" and when the condition "if n % i ==0" satisfies, then the value of "Flag" is changed to be "False"
and the below code that you tried to run has the wrong indentation and wrong conditions to be fulfilled so it will definately not run
you can have an
elseor that for loop, that will only be run if there was no break
@topaz pulsar
That's not quite right : anelsestatement after a loop will always be executed after the last iteation ; in fact, it's the same behaviour as plain code below the loop
!e
for x in range(10) :
print(x)
else :
print("Else block executed")
print("Out of the loop")
You are not allowed to use that command here. Please use the #bot-commands channel instead.
crap
well, it should display
0
1
2
3
4
5
6
7
8
9
Else block executed
Out of the loop
In [46]: for x in range(10) :
...: print(x)
...: else :
...: print("Else block executed")
...: print("Out of the loop")
0
1
2
...
7
8
9
Else block executed
Out of the loop
In [47]: for x in range(10) :
...: print(x)
...: break
...: else :
...: print("Else block executed")
...: print("Out of the loop")
0
Out of the loop
```nah, he is right
All right then, I learned something today ! I thought it was kind of like the finally statement, well, it's not 😉
When reading through design pattern literature, I always see the term "concrete class" but, through context, learned it means "a class that uses implements all of its methods"
But then you also find "concrete implementations/methods" that kind of relate (but not really)
Where did this "concrete" term come from and why is it used but never explained?
I can't answer why you haven't seen an explicit explanation, but the gist is that you have the "normal" concrete class, which as you said implements all its methods, and then you have an abstract class. An abstract class is any class that has at least one abstract method.
As a typical example, you might have the base class of Animal, and the classes Dog and Duck that inherit from it.
Those two latter classes inherit a function called "make noise", and each overrides it to match the desired behavior. Meaning, a dog will bark, and a duck will quack.
But what noise will a general animal make? there's no meaningful answer to that. You created that method inside the Animal class, to make sure that any class that inherits from it will also have that method.
In that context, the "make_noise" method in the Animal class will be defined as abstract (meaning you can't call it), which will make the Animal class abstract (meaning you can't initialize an object of that class). In order for Dog and Duck to not be abstract (meaning, to be concrete), they have to override the method and implement it properly.
A search on abstract classes in python (or not necessarily in python) should yield quite a few results
@visual dagger @fiery cosmos thank you for the explanation guys! I understand it properly now.
Can someone help me with this program, I'm a complete newbie so i don't know what to do but i realise that the error might lie in the filename
def WtoH():
p=open("student1.tst","w")
Rollno=int(input("enter the roll no"))
name=input("Student name")
Mark=float(input("Enter the mark"))
record=str(Rollno)+","+name+","+str(Mark)+"\n"
p.write(record)
p.close()
def RfromH(c):
q=open("student1.tst","r")
str=" "
while str:
str=q.read()
print(str)
q.close()
WtoH()
RtoH()
not the right channel, see #❓|how-to-get-help
@magic tendon
You have made function RfromH() but called RtoH().
Also u have given c in RfromH but didn't passed anything while calling it
Can someone tell me why i get a TypeError wich states that "key" is not a keyword argument for sort() even tho it should be?
np.vstack(([x for x in range(25)],priority)).T.sort(key=lambda x: x[1])```
Do you have a function named sort?
i thought its an inbuild function or am i wrong?
oh can i convert that somehow? this numpy stuff really screws me over all the time :/
ah nvm ty for the link 🙂
np.vstack(([x for x in range(25)],priority)).T.sort(axis=0)```
gives me `None` as a result. idk why this is so difficult
oh mb ty
so i found this expression a[a[:,1].argsort()]to sort a 2d-array by its second column, a[:,1] selects the column and a[:,1].argsort() returns the indices wich would sort that, but how does the outer a[] know how to use these indices to sort itself?
specifically, the argsort() returns a 1d ndarray, but when i try to change the order of a manually by entering an array into the brackets i get an error
a = [[7,3], [3,1], [4,2]]
a[ [2, 0, 1] ]```
@quasi oracle Thanks for taking the time to explain! Your example sounds straight out of the Head First: Design Patterns book
Although I don't think I've come across many articles/books that don't use domesticated/farm animals as examples
I can understand "animal" is abstract and "duck" or "dog" are so-called "concrete" implementations of animal, but it's mostly the use of the term "concrete."
Why not "solid" or "implemented"? My issue is pedantic, but there might be a historical component to this since interface/implementation are originally Java terms that have just become synonymous to general terms
@visual dagger @fiery cosmos thank you for the explanation guys! I understand it properly now.
@cyan current no problemo bro
Nickname: true
specifically, the argsort() returns a 1d ndarray, but when i try to change the order of
amanually by entering an array into the brackets i get an errora = [[7,3], [3,1], [4,2]] a[ [2, 0, 1] ]```
@fiery cosmos how are yo manually changing the order
@azure owl sorry i was asleep.
i change it the way i posted in the code:
a[ [2, 0, 1] ]```
i gave it a 1d array with the indices as elements in a specific order, like the argsort returns but it doesnt work. (not that i need it to work but i would like to understand why)
@fiery cosmos what do you mean?
a[a[:,1].argsort()]
sorts the list a by its second column, while a[:,1].argsort() returns an ndarray with the indices giving the order of the rows.
wouldnt
a = [ [2, 0, 1] ]
just change my array to that order instead of sorting the array?
hey can someone help me
I just want to know if the
ord()```
and py chr()
functions are important
so I wanna know if I need to learn it or not
you don't need to learn anything, if you want to deal with character codes then those functions are how you do it
The only things you need to learn are the tools to do what you want to do
we don;t know if they are important is what we're saying
so I wanna know if I need to learn it or not
@acoustic hearth there is nothing you have to learn they will come in use if they have to there is nothing that needs to be learn in this
just know how to use them
Hi, I was wondering if anybody knows the difference between PCA and distributed PCA?
umm tuple = ("value1", "value2") @faint sun
when i try to write a tuple to a file i keep getting ```python
TypeError: write() argument must be str, not tuple
you have to make it into a string
if youre writing it from 1 file to another
'tuple = ("value1", "value2")'
ok that somehow worked
im not sure how because i have been doing exactly that for the past hour
ok great
it mightve been written wrong or something because i used 4 " so i edited the code to fix the problem
when i try to write a tuple to a file i keep getting ```python
TypeError: write() argument must be str, not tuple
@faint sun you can dump it by using pickle module bro if you are writing that tuple to a text or anyfile just for binary you have to convert it to bytes by using
t = bytes(tuple)```
and if you encode it you can but it is optional
i did a string(my_tuple) and then i wrote it and i wasnt able to use it in my python file but then i tried it like 10 more times and somehow i was able to use it
ill use the bytes(tuple) next time i bump into the same thing
wait wait wait
bytes thing is for binary file bro
yeh
and you simply can loop it
like
for correct indentaion into a python file
or you can just dump
I prefer the dump method as str(tuple) can be altered easily
no problemo bro
thank you for letting me know I really appreciate it
@faint sun
its a huge tuple of over 7000 stuff so now i gotta figure out how to use it
thank you though!
yeh then dump will surely help It is meant for doing that lol
you should consider googling it tho pickle module in python
@faint sun for future reference this kind of question should go in a help channel #❓|how-to-get-help
got it! ill put it in the help chats next time! thanks for letting me know!
Hey so recently i just learned about Big O notation and im a little bit curious on why a set takes O(1)/constant time to look up things inside of it instead of O(n)/linear time like a list?
Hello, can anyone help me in understanding the core of Visual Scripting like PyFlow or Unreal Engine Blueprints? I did lot of research but I couldn’t get the gist of this flow-graphs. I tried studying open-source projects from different languages. Some are way too complex to study.
Hey so recently i just learned about Big O notation and im a little bit curious on why a set takes O(1)/constant time to look up things inside of it instead of O(n)/linear time like a list?
Because of something called hashing. It's basically a function that takes a value, and turns it into a number. So when you add an element to the set, its corresponding hash value (number) is calculated and using that you know where to store the element. When you want to look it up, you can get the hash value again, and with it know where it's stored.
The hashing takes O(1) time, and is designed to get as few collisions as possible, meaning that the probability of two objects getting the same hash value should be very low (If they do get the same value, there are techniques to deal with that).
So if you want to know more about how sets operate you should have a read about hash functions and hash tables. @stray condor
@quasi oracle Hashing sounds awesome! thank you mbaruh, I'm go and look into that right now!
any leetcoders here? I am having a hell of a time with this in python
https://leetcode.com/problems/partition-equal-subset-sum/submissions/
Anyone planning to go to Hack MIT?
@tropic dawn I went every year while I was in college, it's consistently the best hackathon out there
@swift ingot how selective are they in choosing the teams and stuff, i have a decent application but regardless, im still wondering
Hard to say because of covid this year
In the past it is pretty selective
Reason being that half of the attendees end up being MIT students
I always got in through the puzzle
The puzzle is legit very fun
and very hard
Just applied hoping to get in
Is it worth it to start making teams now or wait till the status updates?
Hey,I need urgent help.
Ok so I need to write a program that does ctrl f in python.
It should extrct values that have a word in them then it should only print thoose words.
Please help.
You should ask your question in a normal help channel
ok
@tropic dawn in past years, they accepted individuals, not teams
So if you start making a team now, theres a chance your whole team would not get in
However, if you complete the puzzle, your whole team is guaranteed admission, which is why I always did the puzzle
You can try networking with MIT students but the hackathon is virtual anyway...
You're not getting the full experience online, I can tell you that for sure
When do they give the puzzle
uh i need help not sure where to go
uh i need help not sure where to go
@fiery cosmos go to any channel in the PYTHON HELP:AVAILABLE and type your query
then the hannel you wrote on will be transfered to PYTHON HELP:OCCUPIED
yes I was able to find help. Thank you!!
can anyone answer my question please?
why do computers use 1 and 0?
why not some other pair of digits/
Computers have circuits, which have transisitors, now transistors can either be "Off" or "On" these states are reflected by the usage of 0 and 1
yeah but why 'on' is 1?
why not some other digits?
You could use other numbers surely
but the thing is, it becomes difficullt
binary in 0's and 1's is extremely straight forward
And it also follows convenction
What is a bandwidth
that's the amount of data that can pass through a communication line, usually expressed in bauds (symbols/second), or bits/second
is it like a limit to share data in a connection
why do computers use 1 and 0?
@fiery cosmos because they are true and false that program the computer to tell what is true and what is false
or you may say that they are the computer as without them it is just useless harware
they just do simplify everything in true and false and that is a program if you see clearly
Does this discussion include only Python language or is there more languages involved as well?
Does this discussion include only Python language or is there more languages involved as well?
@vague silo someone would help with other language too if they know
Thanks a lot
Hi guys can anyone explain me what is logic gates.
everytime i run with f5 in visual studio this thing comes up
and i want to skip having to click python file each time
This question belongs in #tools-and-devops
ok
anyone have a recommended python guides on graph algorithms and grasping graph concepts?
hello all, I have a table with two columns and I want to append values of columns to a list of dictionaries. I am trying to do it by [{'key1':i} for i in table['column1], {'key2':j} for j in table['column2']] but its giving me a sysntax error, any ideas?
you can't have two seperate list comprehensions for the same list
I would just use a for loop
kinda strange to have a whole bunch of one element dictionaries though
for i in table['column1']: {'key1':i} ? I need it this way to construct a table in plotly dash and the data entry requires a list of dictionaries 😦
I would assume each dictionary is a row
so it should have key1 and key2
and just putting a dictionary in the body of the loop doesn't do anything
it makes the object and then it goes away as you have no reference to it
I see thank you will try this
so it should have key1 and key2
@marble basalt this was it btw. thanks
Git is a software for version control. Github is just a service for people using git but github itself is not a version control tool.
Github is using git for version control so the real version control tool is git, not github. Github is a service built on top.
It sounded like homework and this is exactly how pedandic some profs can be. If you wanna give half complete answers go ahead, but I will question em.
you can't use github without git, so i think pucch is right here
You're still using git, you're just doing it on githubs server
The fact you're not using it the traditional way doesn't mean you aren't using it
I want to output matrix like this
9 8 7 6
10 11 12 5
1 2 3 4
I want to output spiral matrix...
this is my first message in this server... can someone to help me?
!!! i=x, j=x
for more example =>
if i give as arguments function: 3, 5, it mast print like this:
11 10 9 8 7
12 13 14 15 6
1 2 3 4 5
Is this a good channel to ask a question about time complexity?
@exotic merlin yes
cool cool. If I had a multidimensional array with some values in the inner most array and I want to print out all the values from within the inner most arrays. Would that be considered O(n^2) cause it would take at least a nested for loop statement to be able to print out the inner most array values or would it be considered O(n)?
If you have n^2 values to print, then it has to take at least O(n^2) time
let me create a code example real quick
So if I had something like
[1, 1, 1, 1, 1, 0],
[0, 0, 0, 0, 0, 0],
[0, 1, 1, 1, 1, 1],
[0, 1, 1, 1, 1, 1],
[0, 0, 0, 0, 0, 0]]
for i in arr:
for num in i:
print(num)```
would this be considered O(n^2) or O(n)?
Let's say the size of the array in each dimension is n
How many values do you have in the array?
you have n values
I mean, you have n rows, and each row has n values
What is the total number of values across all rows
n * n ?
Yeah
So how many values are you trying to print here?
for i in arr:
for num in i:
print(num)
n * n values
Yep
If you have n^2 values to print, then it has to take at least O(n^2) time
So this applies
hm
Thats what I thought of at first because I just saw that a for loop could just be considered O(n) in itself and since you have a nested for loop, it would be O(n) * O(n) = O(n^2). But I was reading what people were saying about this on a stackoverflow post and some people say that it could be considered O(n)
And I understand how it could be O(n^2) but not O(n)
In this case n is defined as the total number of values, not the size in each dimension
The first answer clears some of the confusion
hi @exotic merlin this blog has some python examples: https://stackabuse.com/big-o-notation-and-algorithm-analysis-with-python-examples/
There are multiple ways to solve a problem using a computer program. For
instance, there are several ways to sort items in an array. You can use merge
sort [https://en.wikipedia.org/wiki/Merge_sort], bubble sort
[https://en.wikipedia.org/wiki/Bubble_sort], insertion sort
[http...
It's a matter of what you define n to represent
So since n is defined as the total number of values, it's considered O(n^2)?
If you define n as the total number of values, then you have to print O(n) values, which is how the person asking in the post you sent got to their answer
In what I explained earlier, I referred to n as the size in each dimension. That led to the total number of values being n^2
ah, I think I get it
If I was given just the snipit of code above I pasted without any reference to what n is, I would automatically think that its just O(n^2) just because of the nested for loops. I can't see anyone look at the code and the first thing that pops up in their head is "yep that's O(n)"
But I guess in this case, it all just depends on the context of the problem beforehand
Yeah. saying it's O(n^2) would probably be standard
cool cool. Thanks for the help.
Just wondering if these notes are correct for calculating the derivative of a cost with respect to a weight or bias
currently trying to construct my first neural network
not sure if this is more suited to #data-science-and-ml, let me know if thats the case
can someone point me to any resource about alogorithms and data structures for beginners?
Your argument is literally the same as saying google isn't a search engine
@fiery cosmos
No. The background api is a search engine, it's searching documents.
You're using git through the interface of github
can someone point me to any resource about alogorithms and data structures for beginners?
@faint vale this channel's pins have a link
@faint vale check out algorithms specialization by stanford, ds & algo specialization by ucsd on Coursera
@random shale your second ping isn't right
@quasi oracle I'm a beginner taking these courses.
No, I mean, in the second message it was a different avi
You deleted it so nevermind
@random shale thank you very much. Do u recommend taking these courses after doing basic python?
@faint vale i would suggest knowing basics of python and some discrete math (mathematics for CS) before attempting these specializations.
@random shale any resource you would suggest for discrete maths? I am from electrical engineering background. Its a good chance i already have done most of it. But still won't hurt to brush up.
I personally found Concrete Mathematics to be a really useful book
@faint vale discrete math and it's applications by Rosen.
If you have less time, then try YouTube, lots of CS math videos by reputed institutions on youtube. @faint vale
@idle crow @random shale thank you gentlemen for your valuable advice. Cheers.
I personally found Concrete Mathematics to be a really useful book
@idle crow
This is also a great book.
Hi guys, sry, what book I should read? I'm a begginer
!resources has some links for getting started with programming in general - not a huge amount of books though. If you're looking to get started with CS in general, I can recommend CS50 or MIT6.001 video courses (I think both are linked !resources)
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
thankss!
uhh anyone comfortable with regex
I am trying to figure out how to capture something that DOES NOT match a certain regex
A sentence where there is not duplicate word side by side
^(?!.*\b(\w+)\s+\1\b.*)
Regex101 allows you to create, debug, test and have your expressions explained for PHP, PCRE, Python, Golang and JavaScript. The website also features a community where you can share useful expressions.
Might help you
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
I want to define a function wich prints spiral matrix like this:
8 7 6
9 12 5
10 11 4
1 2 3
this is printed out by the function when n = 3 and m = 4. n and m are tyhe arguments of the defined function.
I need this code as soon as it is possible... ❤️ thanks
what have you tried?
whait
Try coming up the with how to get the indexes of the next number from a given spot
N=int(input())
A=(N+2)*[(N+2)*[0]]
A[0]=A[N+1]=(N+2)*[-1]
for i in range(1,N+1):
A[i]=[-1]+N*[0]+[-1]
Di=(0,1,0,-1)
Dj=(1,0,-1,0)
M,i,j,m=0,1,0,0
while M<N*N:
M+=1
if A[i+Di[m]][j+Dj[m]]:
m=(m+1)%4;
i+=Di[m]
j+=Dj[m]
A[i][j]=M
for i in range(1,N+1):
for j in range(1,N+1):
print(A[i][j],end=' ')
print()
i tried this but it works only for one argument
well, the first step for making it work for distinct N and M would be to prompt the user for both.
this seems like homework, and no one here is going to do your homework for you. if you have specific questions about how to do some piece of the work, you'll get some help. if you are just hoping for someone to do the entire thing for you, you're in the wrong spot.
you should make your variable names more descriptive
its essentially completely unreadable rn
this seems like homework, and no one here is going to do your homework for you. if you have specific questions about how to do some piece of the work, you'll get some help. if you are just hoping for someone to do the entire thing for you, you're in the wrong spot.
@lean dome this isn't my home work
it's just a problem of e-olymp.com content
that doesn't anything I said. No one will solve the problem for you, and asking for help solving a problem is very different from asking for a solution.
consider you only have to solve the outside, then you can embed the next layer inside that, like in your example you can get all the outside numbers and then do the same thing for n=1 m=2 to get the inside numbers
Ok so what I've learned about perceptual hashs: they can be used for fingerprinting 8 bit greyscale images. Since every block in minecrsft is an 8bit data value. I should be able to convert the data set into a 8bit bmp and hash it?
@icy fulcrum you were talking earlier about having hash collisions where you thought the blocks were actually different? That's extremely unlikely.
@icy fulcrum I've never played minecraft, so this may be a dumb question, but - aren't there a finite number of types of blocks? Why do you need to hash a block, instead of just storing a unique integer per type of block?
can't you just say that lava is 0, basalt is 1, etc?
Not the block itself. But a region of blocks. A region contains 32x32 chunks each chunk is 16x16x256 blocks including air but only an average of 80 in altitude. The goal here is to fingerprint the map at the region file level as im working on 15 gig data set. Out of 4023 regions 451 of them are showing the same sha256 checksum. So I wanted to checksum in a different slightly more accurate way. I dont really care about the data value if the individual blocks but the integrity of the map as a whole
@icy fulcrum you say 451 of them are showing the same checksum. But you think they actually have different contents? That is extremely unlikely.
well, that depends on how you did the checksum
the most likely explanation is a bug in the summing
Its theoretically plausible that each region could contain the exact same dataset it is running a Parlin noise generator
I used the Linux cli sha256sum rwgion.name
what is "rwgion.name" there?
yeah. your checksum may have wound up amounting to "number of non-air tiles", in which case many regions would have the same value. It'll be up to you to make sure that the values you're feeding into the hash result in a sane hash value.
ok, but what data are you feeding into sha256sum?
The minecrsft region files named in the photo. After generating the map with the world generator
can you check two of those files with the same hash? They will have identical contents
I mqy not be understanding your question
I should be able to check. A binary diff maybe?
sure.
ok no they are the same byte for byte
cmp -b BopGen/DIM-1/region/r.-18.-15.mca BopGen/DIM-1/region/r.-1.-3.mca gave me no return and then i used cmp -b BopGen/DIM-1/region/r.-18.-15.mca BopGen/DIM-1/region/r.-1.3.mca says differ: byte 3, line 1 is 0 ^@ 2 ^B
so then all of those map tiles that are identical in the hash values are then identical in the map
O_e maybe im missing something here on how Perlin Noise works
yes. sha256 is very good at not randomly colliding
as i thought that it should be since its a cryptographic hashing alg
at least i know how to check my work now tho 🙂
so if binary data is equal in this case how am i using a Perlin noise generator to generate and save the same data in multiple regions? that would mean every block in the 3d grid was exactly the same
is that just a flaw of Perlin noise in this implementation? or... i wonder if i really have cloned chunks O_e
thats an interesting thought ^ ill need to dig into that and see where those chunks are to know for sure. Thank you Ned and Godlygeek
What is a region? Could it just be all air or water blocks or something like that
A region is a structure defining a set of chunks, inturn these are providing information on on all blocks that are not air. Water, lava, stone, dirt, etc. In game these are arranged in a 3d grid to define a terrain map. Usually generated by the game engine (parts of it are perlin noise based) however there are addon programs that can read, write, and generate data from other algorithms. Each file also contains a small set of information pertaining to tile entities (creepers, villagers, etc) if i remember correctly the entities may be a separate file.
that being said each region also contains the world coordinates by name of file
r.-18.-15.mca and r.-1.-2.mca in my examples are identical regions on the map. these are located at -18 X and -1 X by -15 Z by -2 Z respectively on a square grid these are defiantly not in the same grid location. but all of the data in the region (512×256×512 blocks, 67,108,864 total (although the air is NOT saved) ) are identical..... O_e my brain hurts i cannot fathom how a noise generator (like Perlin Noise) would even accomplish this.
Unless that is the pattern. I wonder if i plotted all the regions on a bigger grid if i could i see the noise patterns
Nat you are a genus. Thank you for asking that question I think that's exactly the direction I needed to go.
Hey guys need some advice
I found this question on stack overflow to find the line that touched most of the rectangles
I have no clue at the moment but we need to find the line which touches the most of the rectanles and does not have to be the corners
any clue?
the easiest solution I can think of involves starting with a random line, then rotating it 180 degrees, checking the number of rectangles it touches as you rotate
but thats too much processing and it will not work as height of this line needs to be adjusted
can you give the link for the stack overflow thing
What's the bounds of the input size?
Hello guys, i am beginner in python and i am working on an OCR thing, this way it works fine. but i want to make it take all the png files in the folder and extract them as text files with the png file name.
what should i do or where should i look for a tutorial for this?
Well, if you already have a code that can read one file, then this is mostly on you now.
Find something online that allows you to take all files in a folder. (for example. Os.listdir) then simply write a loop for this.
def get_guessed_word(x,y):
li =[]
for word in x:
if word in y:
li.append(word)
print(li)
return li
I'm getting error invalid character in identifier in the above function
please help
hi
i'm not still at that level of py
i'm beginner in python i just know few stuffs about it
can anyone tell me how to compile python on mac
in terminal
i use sublime text
That'd be more on topic in #unix - this channel is about the mathematical theory behind computing.
anyone good with algorithms and optimising them. i have a problems and im not even sure where to start
!ask
Asking good questions will yield a much higher chance of a quick response:
• Don't ask to ask your question, just go ahead and tell us your problem.
• Don't ask if anyone is knowledgeable in some area, filtering serves no purpose.
• Try to solve the problem on your own first, we're not going to write code for you.
• Show us the code you've tried and any errors or unexpected results it's giving.
• Be patient while we're helping you.
You can find a much more detailed explanation on our website.
i needed to type it out here because it was too big for discord but here is the problem
https://hastebin.com/cekanaxeri.py
Didn't quite get the pen part, but for efficiently handling image data you should look into numpy.
In your case you might benefit from dividing your image to connected components
the pen part is just how many times the pen draws something to the screen like this
@quasi oracle what do you mean by connected components
Huh, that's pretty awesome.
So what do you mean by minimize? Because it looks like it deals with one color each time and doesn't go back to it
well lets say you have a line of pixels like this
🟦🟥🟦🟩🟦🟥🟦🟦
lets say green has already been drawn
if when drawing the blue line i joined red and blue, thats more efficient as the pen will only need to make 2 movements instead of 4
like if i have 20 different colours. trying to join different ones in such a way to make less pen movements. not sure if that makes sense
if needed i can put my whole code up somewhere its not that long
the icon?
is this something youve made?
its iconbitmap or not ?
Just paste a picture on top of it? Or what.
its iconbitmap or not ?
@fiery cosmos its probably just an icon(ico) file
with an other
@fiery cosmos its probably just an icon(ico) file
@umbral gulch aight I'll try it
I think this is where you're making some fundamental assumption about where this is supposed to be changed but you don't realise you didn't tell us
I think this is where you're making some fundamental assumption about where this is supposed to be changed but you don't realise you didn't tell us
@candid osprey wdym
What are we looking at
This might be more suitable for #❓|how-to-get-help then theoretical cs?
Is this a screenshot of a browser tab?
well lets say you have a line of pixels like this
🟦🟥🟦🟩🟦🟥🟦🟦
lets say green has already been drawn
if when drawing the blue line i joined red and blue, thats more efficient as the pen will only need to make 2 movements instead of 4
@umbral gulch more efficient compared to what? What are the steps you want versus what you're doing now?
I get what they want. Basically imagine if the red boxes were blue instead
it's about tkinter
Then the pen draws blues in two strokes
And then they can always draw the red boxes separately later in 2 strokes
That sound about right?
Oh, versus the opposite, ok
@quasi oracle heres the full code, just now its sorts the colours based on what one will be doing the most pen strokes down to the one that will be doing the least. but instead of wither getting the pen strokes for all of the remaining colours i wanna try find if there is a combination of remaining colours that will lead to less pen strokes than just one colour https://hastebin.com/divodatoxu.py
That sound about right?
@candid osprey yeah
Does drawing more strokes really make it that much slower? That's the only part that I guess must be true.
To make this exercise worth it
Does drawing more strokes really make it that much slower? That's the only part that I guess must be true.
@candid osprey well the less strokes the quicker it will draw the image so yes, because i need to have a sleep or mspaint doesnt have time to draw the image and it just updates at the end in a big mess
Ah I see I see. So it's because you're essentially having to interact with Mspaint like almost an automation tool eh?
this is it without it sleeping
I imagine the more fragmented a color is, the higher priority it should have. Which seems to be what you're already doing.
Do you have an example of a more efficient order than what this priority sorting provides?
I imagine the more fragmented a color is, the higher priority it should have. Which seems to be what you're already doing.
Do you have an example of a more efficient order than what this priority sorting provides?
@quasi oracle its hard to show on a small scale
How did you record these videos btw?
@candid osprey ShareX
Well it's hard to help otherwise 😅
id say voice but theres people in there
@quasi oracle ill try and draw a small image in paint that would benifit from what im thinking about
Are strokes lines only? Drawing a region in 2d takes several strokes?
I'd assume that's the simplest way to do it, changing pen sizes might introduce more steps that make it even slower
this is the function thats getting the strokes for each color/set of colours. if 2 pixels are next to each other it joins them
def get_strokes(color_positions):
strokes = []
pos_index = 0
while pos_index < len(color_positions):
start_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
end_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
while True:
try:
if color_positions[pos_index+1][0]+paint_offset[0] == end_pos[0] + 1:
pos_index += 1
end_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
else:
break
except: break
strokes.append((start_pos,end_pos))
pos_index += 1
return strokes
then this part is it drawing each of the strokes for X colour
for stroke in all_colours:
pui.moveTo(stroke[0])
pui.dragTo(stroke[1])
Since this isn't simply a direct control over the image pixels, more like instructions to a bot
So each row is independent of the others. The only reason you draw one color at a time is because switching takes time
@quasi oracle yes, i can invite you to my server and talk in voice it might be easier to explain if you want
Here is fine for now I think
ill try and draw an image that will benifit from what i think the change should be
Im at the stage where I perfectly understand the problem but can't think of a way to approach the solution directly. I'm wondering if you'd just have* to settle for some kind of compromise
ill try and draw an image that will benifit from what i think the change should be
From what we just discussed you really only need to show one row
I can think of a simple example.
Essentially, filling the majority colour isn't always best. Imagine this
A row of blue. But one red dot on each end.
Red first then blue is two strikes. Blue first then red is 3.
Yes, but the red is more fragmented
From what we just discussed you really only need to show one row
@quasi oracle not exactly
Which makes it work if you order by this priority
So, the more distinct broken groups first?
If we only look at one row, probably
But like Pyro said it's not necessarily the case, because in the next line it might be very low priority
But if switching colors is expensive enough, the fastest solution would be a priority over the entire image
I think there simply compute across all lines and just take the overall best, call it a day
Exactly
Essentially a greedy approach
im trying something up 2 secs
You can calculate the fragmentation of a row in one pass I believe
GBRBRBRBG. Blue 4 red 3 green 2. 6 strokes with blue first. 5 strokes if G then B then R. Did I count correctly?
Essentially something I'm observing mentally is that eliminating edge pairs is important.
Why 6 stokes with blue? It's the most fragmented, so one stroke
I'm not yet convinced if there's an objective answer to this problem or if we'd have to settle for something that's good enough.
so like this, https://hastebin.com/oredubarov.shell. so by joining all the different colours in such a way to give the biggest saving for what colours are remaining and still need to be drawn
You know what, I had a pretty silly idea
so for drawing the black colour it would be best to join the positions of the black and green because that gives the biggest saving
Why don't we simply brute force the calculation
@candid osprey go through every possible colour combination?, well if you have 16 colours in the colour palette. thats just under 16! or 2.092279e+13. that will take along time to calculates every possible solution and find the shorest
Just calculate some random sequence of colours. You can even make it calculate only a small subset of all possible combinations and pick the best
Almost like a simple genetic algo / heuristic approach to drawing something that's "good enough"
Let the machine crunch the numbers first. It's good at those.
would it save time to use the paint bucket on the first (and most common) colour? just fill the screen initially like that
Not always no
Fragmentation creates bigger problems
Aye Pyro, I was realising that as I was saying it, so I was only wondering about taking subsets at random
seems like an interesting problem, i just can't think of a better solution
ill quickly get a brute force solution up 2 secs
Keep the current approach too for a "always calculate this" approach
Actually once you setup the logic to calculate strokes, visualizing different algos should become faster
You'll be able to generate exact stroke counts so even if this approach doesn't do it, the code should help
As for an algo based version, I keep thinking of trying to pair off colours from each end.
I'm wondering if there's something to that.
wait for a brute force how do i make it go through it like get all combinations of 2, then all combos of 3 and so on? ive never done that
well first its alot easier to have a small colour palette. ill just use the basic one from paint with 20 colours or is that still too many?
It's a crapton for sure, but go for it
i have like 30 different palettes ive borrows from illustrator
So I can formulate the problem as follows:
Let's say each color has its own channel. Joining the channels together creates an image in such a way that the channels in the front take priority. The earlier a color is chosen, the more in the back it is.
We want to create a series of channels such that their joining will create the desired image, and the sum of the number of connected components across all channels is minimal.
Something like that
Actually... It is a crapton
Connected-row-wise
What's 20 factorial? 🤔😅
ill try this one. its small and nice. only a max of 720 different itterations
What's 20 factorial? 🤔😅
@candid osprey big
ill use a small file aswell
with 6 brute force is fine
Calculating total strokes though seems useful for sure
ill do it wil this image, small but lots of varying colours
how do i to the iter thing?
for L in range(0, len(remaining_colour_positions)+1):
for subset in itertools.combinations(remaining_colour_positions, L):
print(subset)
could it be like this?
@candid osprey we could potentially combine the two approaches: what is the number of colors that are "in the way" of every color from being unified
Pyro I'm on my phone and code is formatted horribly on it so it's a little hard for me to tell
hm, im trying to understand why you need the nested loop. you should be able to simply run itertools (permutations. not combinations. order matters) on "all" colour choices at once
then pick one sequence, and "walk" through it from start to finish
so essentially, itertools happens first. the actual code flow happens later
Hmm no, not the number of colors. The number of segments
def brute_force_strokes(remaining_colour_positions):
shortest = 0
best_combonation = None
for L in range(0, len(remaining_colour_positions)+1):
for subset in itertools.combinations(remaining_colour_positions, L):
if subset != ():
calculated_strokes = get_strokes(subset[0])
if len(calculated_strokes) < shortest or shortest == 0:
shortest = len(calculated_strokes)
best_combonation = calculated_strokes
return best_combonation
this is the brute force way i came up with. it will just return the shortest combonation
ill test it now and see if it gives an improvement to the amount of pen strokes it does
After that you should try what I just suggested
It should give similar results in polynomial time I think
After that you should try what I just suggested
@quasi oracle will do
ok so i think i done my brute force wrong
without it it took 5649 pen strokes
with it it took 7860 pen strokes
plus it took longer th calculate
awe i know why its not working
its going through every itteration. i only want it to go through if it contains the current colours its checking
how can i check if an array contains a sub array
ok my brute force just isnt working. and it takes forever with larger pallettes, @quasi oracle how would i impliment the way you suggested
GBRBRBRBG. Blue 4 red 3 green 2. 6 strokes with blue first. 5 strokes if G then B then R. Did I count correctly?
Let's take this example
The two Gs which are the farthest apart have 7 segments between them
The Bs have 5
Sorry not 5, 3
Excluding the B
remember the total amount of pen strokes will be the sum of all the horizontal parts of the image
And Rs have 2
simple question from a noobie here. How do I create an array [0,1,2,3,4.......N] without using for and if's ?
list(range(n+1))
So the order is GBR.
From that order you can calculate how many strokes each color takes for that row
And you can some that across all rows
Or.. Hmm
You don't need to get the number of strokes
@quasi oracle i think thats what my base one is doing
maybe the way im doing it just now is the most optimal 
or trying to best a better one will just slow the code down
I didn't really understand your code, but if that's what you're doing I don't see something better
i guess if your on a phone itll be confusing to read maybe. like i think there is possibly a better solution but in order to get that to work the code would run slower aka then taking longer to draw the image
i guess if i understand of uncompressed png save colours that might help because im sure theyll do something similar, ye?
i think ive just though of a different way to do it. im off to walk to dog so ill think about it but i think it might works. its taking youd ideas and changding it slightly
@quasi oracle ive found a better method of doing it but its slower. do you know of anyway i could speed it up. i think because its looking in an array most of the time is why its slowing it down
def get_better_strokes(color_positions,current_col):
strokes = []
pos_index = 0
while pos_index < len(color_positions):
start_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
end_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
contains_current_col = color_positions[pos_index] in current_col[1]
while True:
try:
if color_positions[pos_index+1][0]+paint_offset[0] == end_pos[0] + 1:
pos_index += 1
end_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
if not contains_current_col and color_positions[pos_index] in current_col[1]:
contains_current_col = True
else:
break
except: break
if contains_current_col:
strokes.append((start_pos,end_pos))
pos_index += 1
return strokes
first one is the old method. second if that new method
fixed 🙂
change the get_strokes function to this
def get_strokes(color_positions,current_col=None,single=False):
strokes = []
pos_index = 0
if not single:
current_col = set(current_col[1])
while pos_index < len(color_positions):
start_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
end_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
if not single: contains_current_col = color_positions[pos_index] in current_col
while True:
if pos_index+1 < len(color_positions) and color_positions[pos_index+1][0]+paint_offset[0] == end_pos[0] + 1:
pos_index += 1
end_pos = color_positions[pos_index][0]+paint_offset[0],color_positions[pos_index][1]+paint_offset[1]
if not single and not contains_current_col and color_positions[pos_index] in current_col:
contains_current_col = True
else:
break
if single or contains_current_col:
strokes.append((start_pos,end_pos))
pos_index += 1
return strokes
https://github.com/DylanMcBean/MsPaintDrawer/tree/master if anyone wants to mess with it
!warn @chrome jacinth do not cross-post a question into multiple channels.
:incoming_envelope: :ok_hand: applied warning to @chrome jacinth.
Hi I am new
Hey I'm new to C and am having trouble running my program. My compiler is MinGW and I'm on a Windows. I get access denied in my terminal. Not the end of the world, I might use the python tutor C feature to practice my coding.
This isn't the right channel for that question. And AFAIK there is no right channel. You might have better luck looking for a more general programming Discord
@daring axle I can DM you invite links to some maybe relevant servers if you like?, I'd post them here but the filter will nab them
I am trying to create a simple Auto Video Editing tool. I am looking to use, OpenCV, FFMPEG, etc. Can you suggest some features and ideas to add? https://github.com/AP-Atul/Video-Editing-Automation
this isn't the right channel for that @fiery cosmos
how many module are acceptable for competitive programming in python.
I know that math, random and statistics, itertools and some other module is ok in competition. But when I use numpy or sympy in a coding competition of Codeforces or CodeChef I get runtime error.
normally it's just the standard lib that you have access to. Some let you access numpy specifically, but that's not the default
@random lotus Ideally you wouldn't use python in competitive programming, C++ instead.
But it's the standard library yeah.
some problems can be solved with python, but indeed C++/D/Rust/Go/other fast langs tend to be better
You don't even need to know much C++, as you won't be doing any allocations or freeing or messing with what people use normally
for competitive programming, python is usually reserved just for the simple problems that people can bash out in 2 lines
I also hear good things about julia in that regard
julia is definitely an interesting lang
Shop={'Apples':'2', 'Bananas':'5'}
Print(Shop)s
Why do we need a s after the parenthesis
@royal whale erm.. you don't?
For further help you should open a help channel #❓|how-to-get-help
Done thanks
Hey guys, Recently i'm doing dijkstra algorithm and implemented it using Priority Queues.. i got confused little bit here about it's iteration over different vertex.. I mean, is it okay for an naive dijkstra algorithm to iterate over those nodes who have less weight (or say cost) but do not lead to a correct path ?
Here, the neighbors of vertex(1) are 2 and 5 okay ?
So According to PriorityQueue, it dequeues vertex(5) because it has less weight than vertex(2) and enqueue another vertex(6) in PQ
Now, as i said, vertex having less weight will get Dequeue first.. So, it will dequeue vertex(2)... is it okay here to go to vertex(2) after vertex(5) ??
You don't know the path to the target node, otherwise you wouldn't need to run the algorithm
So yes, it's fine to consider nodes that eventually don't lead you to your destination
@placid sonnet yeah, actually I use both python and C++. If I see a problem is very easy and can be done by 4 or 5 line python where it is not so small in C++ then I use python. But when It requires less time and complexity I use C++. And also I think C++ is best for competitive programming
Good.
So yes, it's fine to consider nodes that eventually don't lead you to your destination
but don't you think it will increase some extra steps?
## Implementation of Dijkstra algorithm
from priority_queue import PriorityQueue
def Dijkstra(Gobj, source, destination):
PQ = PriorityQueue()
PQ.enqueue(source, 0)
visited = {source.id: True}
distance = {source.id: 0}
parent = {source.id: None}
found = False
while PQ.is_empty() is False:
PQ.printQueue()
vertex, weight = PQ.dequeue()
# If duplicate entry arrives and the orignal one got deleted
# but orignal one exists inside dict(distance).
if distance[vertex.id] < weight:
continue
for eachNeighbor in vertex.GetNeighbors():
if eachNeighbor.id not in visited:
# Calculate their distance
newDistance = distance[vertex.id] + vertex.GetNeighborWeight(eachNeighbor)
if eachNeighbor.id in distance.keys():
if newDistance < distance[eachNeighbor.id]:
distance[eachNeighbor.id] = newDistance
else:
distance[eachNeighbor.id] = newDistance
# Assign parent of eachNeighbor
parent[eachNeighbor.id] = vertex.id
PQ.enqueue(eachNeighbor, newDistance)
if eachNeighbor == destination:
found = True
break
# Assign it to visited
visited[vertex.id] = True
if found:
break
print(visited)
print(distance)
return parent
@quasi oracle this is my implementation of dijkstra using graph algorithm
You have no way of knowing in which direction you need to go. The idea of Dijkstra is to search for the destination in the vicinity of the source node, with increasing radius.
If there was some assumption you could make about the graph, then sure, it might be wasteful, but if you have no knowledge of the topology of your graph ahead of time, do you see any way to make it more efficient?
You're saying it's a waste to go in the vertex(2) route because you're looking at the whole graph from above, but in your algorithm, all you know is the vertices you already visited, and their neighbors
The idea of Dijkstra is to search for the destination in the vicinity of the source node, with increasing radius.
you meant, go through every possible nodes and then find the shortest distance from destination to source.. Just like i've done in this code snippet :
parent = {1: None, 2: 1, 5: 1, 6: 5, 3: 2, 4: 3, 7: 6, 8: 6, 9: 8, 10: 9} # obtained from Dijkstra function.
def printPath(parent, source, destination):
if source == destination:
return
print(parent[destination])
printPath(parent, source, parent[destination])
And yeah, it returns 9, 8, 6, 5, 1 (of that graph pasted above)
You're saying it's a waste to go in the vertex(2) route because you're looking at the whole graph from above, but in your algorithm, all you know is the vertices you already visited, and their neighbors
Hmm that's right i guess because telling a shortest path by just looking at a graph and obtaining a shortest path via code, both have lot of dfiference.,
if you have no knowledge of the topology of your graph ahead of time, do you see any way to make it more efficient?
Can you pleease tell me when you said "topology of your graph" what did you mean here? Like is it something about which node is pointing to other and in which structure (acyclic, cyclic, directed and other)
I just understood it recently and implemented by myself but i guess the problem is, it doesn't work in Dense graph because it has to go those nodes which are unnecessary .. what about you think, if i'm using a dense graph then what should i use?
@quasi oracle
does anyone know how to create a dictionary given user input
@balmy siren I'm not sure I understand your algorithm. You assume your graph is a tree?
@quasi oracle nope.. it's not a tree, it is a graph tho (directed graph)
ohh well i mean, i just took this graph as an example to implement dijkstra on it..
so you thought it isn't that correct ?
and does it make any difference or dijkstra ones are different ?
It just doesn't seem like you could represent a general graph that way
Also, in order to properly direct all edges, you sort of have to run a variation of Dijkstra anyway
@grim hedge I think you'll get more informative answers in #career-advice
@quasi oracle Thank you, didnt even notice that section 🙂
Starting here:
pd.DataFrame.reset_index(df, level=None, drop=False, inplace=True, col_level=0, col_fill='')
df.rename(columns={'index':'pcount'}, inplace=True)
returns a warning, "SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame"
How should I do this to avoid the warning?
@viscid mountain this is a better place to ask about algorithms and data structures in general.
When I took that course I looked up the algorithms on Geeks for Geeks and reimplemented them my way.
GeeksforGeeks saved all of us, even if the explanations were a bit crap at times.
🙂
how to transistor logic?
You mean like boolean algebra?
@magic locust hey are you doing graphs ?
oh yeah you're 😄
actually i want to ask something if you've done upto shortest path algo
yes
@magic locust can you tell me how did you store the edges of undirected Graphs ??
One method which i'm thinking right now is to, when user input the two vertex then first it creates (if it doesn't exist) and then connect them in this way :
adjacencyList[A] = B
adjacencyList[B] = A
am i right here? or can you show me your implementation of undirected graphs???
I used to insert both (A and B) two times if i've to make it as undirected graph but might be there's best way to do so
@magic locust Hey
@fiery cosmos Cool
@magic locust can you tell me how did you store the edges of undirected Graphs ??
One method which i'm thinking right now is to, when user input the two vertex then first it creates (if it doesn't exist) and then connect them in this way :
adjacencyList[A] = B
adjacencyList[B] = A
am i right here? or can you show me your implementation of undirected graphs???I used to insert both (A and B) two times if i've to make it as undirected graph but might be there's best way to do so
@balmy siren you can use adjacency matrix
any guess implementing it using adjacency list?
implementing what exactly ?
@magic locust recently i'm doing dijkstra but i got a problem because the graph which i'm using was an undirected graph and i'm using an adjancency list to represent the connection between vertices
so i want to know how do i exactly represent undirected graph..
basically, we do something like this if we're using an adjacency list ->
A -> B, C, D
B -> C
D -> A
you familiar with this?
@daring axle I can DM you invite links to some maybe relevant servers if you like?, I'd post them here but the filter will nab them
@last blaze Please send them. I tried switching over from VS Code to Notepad++ and that still won't let me access my file.
I hope not
@balmy siren you can use a dictionary of lists or sets. Using defaultdict would make implementation simple
import collections
graph = collections.defaultdict(list) # graph = collections.defaultdict(set)
@dark egret i already implemented it using arrays what i want to know i.e., if i'm going to add an undirected edge then is it right to store both the vertices like this (below) in the array :
adjacencyList[A] = B
adjacencyList[B] = A
self.vertList
[(A, B), (B, A)]
vertlist implies it's a list of vertices though, not edges
The adjacency lists can give you all the information you need about the structure of the graph, I don't think there's a point in having another list
Although it seems kind of redundant to store the undirected edge A-B
as
adjacencyList[A] = [B]
adjacencyList[B] = [A]
I think it is really helpful(in terms of time complexity) especially if you are running an algorithm like Djikstras. I agree with @quasi oracle that storing an edge once would capture all the information in the graph but it would be fast.
If you just store
adjacencyList[A] = [B]
adjacencyList[B] = []
then while running Djikstras if you encounter B before A then you wont be able to reach A because you haven't stored A as a neighbor of B
Also, for problems where you need to check if a node is a neighbor of another, I would prefer sets to store neighbors as you can do this in O(1) time
adjacencyList[A] = {B, ...}
adjacencyList[B] = {A, ...}
@balmy siren
Hope it makes sense. Also correct me if I am wrong
Ah, I should clarify.
adjacencyList[A] = [B]
adjacencyList[B] = [A]
Is good.
I was referring to
self.vertList
[(A, B), (B, A)]
The case of:
adjacencyList[A] = [B]
adjacencyList[B] = []
Implies a directed graph
oh alright
I misunderstood
This is a minecraft region (60 gig in data) under active pregeneration. each color is mapped to to the sha256 checksums of the regions using a bit mask. the data is rendered in Povray and then animated using moviepy. as you can see from the chunk gen there are a number of identical map tiles on the map in a noise pattern that i think aligns with Perlin Noise Generator. Due to the nature of sha256 checksums a single change in a block inside the game will cause an avalanche effect on the 256bit hash. slicing this hash into a 16 bit value gives a color. each frame in the animation provided is a 15 minute snapshot of sha256 sums of the regions if you look closely at the map you can see how much terrain is being effected by the map pregen. thank you to all the people who helped with this project 🙂
@austere sparrow @candid osprey hii
Hi. I stepped away for a bit. I got the gist of it already though, not a lot to add the the convo
Hey everyone, I have script that I cannot get to work and need some guidance. It iterates through a directory tree searching the containing files for a phone number. On the first iteration it breaks and returns a FileNotFound error, the problem is that not only does the file exist but the script does identify the file and puts its path into a viariable, which the traceback points to, so I know that it is being accessed, I am not sure what I am doing wrong so hopefully someone will see something in the code that I am overlooking.
# Search through files for a phone number
# Imports
import os, re
# Set search pattern
pattern = r'\d{3}-\d{3}-\d{4}'
path = '/home/dschuster/Udemy_Devs/Udemy_Python/Homework/extracted_content'
# Search function
def search(file, pattern=r'\d{3}-\d{3}-\d{4}'):
f = open(file, mode='r')
text = f.read()
if re.search(pattern, text):
return re.search(pattern,text)
results = []
# Walk through files
for root, dirs, files in os.walk(path):
for f in files:
full_path = path + '/' + f
results.append(search(full_path))
# Examine for pattern match
for number in results:
if number == '':
continue
else:
print(number.group())
Here is the Traceback:
Traceback (most recent call last):
File "/home/dschuster/Udemy_Devs/Udemy_Python/Homework/unpack.py", line 24, in <module>
results.append(search(full_path))
File "/home/dschuster/Udemy_Devs/Udemy_Python/Homework/unpack.py", line 12, in search
f = open(file, mode='r')
FileNotFoundError: [Errno 2] No such file or directory: '/home/dschuster/Udemy_Devs/Udemy_Python/Homework/extracted_content/XHZPVUQTXIO.txt'
As you can see in the above path, the file is identified! I can't get my head around this one.
@naive tinsel you're probably gonna have better luck in a normal help channel. See #❓|how-to-get-help
!rank
Iterating over range(len(...)) is a common approach to accessing each item in an ordered collection.
for i in range(len(my_list)):
do_something(my_list[i])
The pythonic syntax is much simpler, and is guaranteed to produce elements in the same order:
for item in my_list:
do_something(item)
Python has other solutions for cases when the index itself might be needed. To get the element at the same index from two or more lists, use zip. To get both the index and the element at that index, use enumerate.
@naive tinsel you're probably gonna have better luck in a normal help channel. See #❓|how-to-get-help
@last blaze Ah... lol didn't realize... haha thank you!
@magic locust Regarding our previous discussion, del for a slice won't create a copy. So it is truly in-place. It interprets the slice a bit differently, all it does is, lst[i:] tells del to delete items from some index. Since del is a special syntax, it inteprets lst[i:] a bit differently.
hey I have a subdomain[
example.demonx.ex] I want to open it in python and it should return a protocol and the subdomain for me eg.[http://example.demonx.ex] how do I do this? Do I need sockets or the urllib module can handle this for me
@magic locust Regarding our previous discussion, del for a slice won't create a copy. So it is truly in-place. It interprets the slice a bit differently, all it does is,
lst[i:]tellsdelto delete items from some index. Sincedelis a special syntax, it intepretslst[i:]a bit differently.
@serene mango Thanks for the clarification

hey ,Can I get a help with C?
@mystic osprey you might be able to in the offtopic channels, but it's possible you might have better luck in another discord. Or if it's specifically writing a python extension, maybe #c-extensions
umm thanks!
Hey guys I need help with visualizing an exponential function inside a for loop. I understand that if we have n number of bits that gives us 2^n different combinations that these bits can be ordered in. What I’m trying to understand is the doubling operations part. I just can’t visualize in my head what it means by doubling the operations. Is there a real life example of this somewhere?
Is this what you mean?
2^1 = 2
2^2 = 4
2^3 = 8
2^4 = 16
2^5 = 32
...
Yeah but I’m trying to understand how the number of bits has anything to do with the number of operations that we perform inside the for loop, for example I’m trying to understand why the number of operations inside the for loop would double.
I guess one example could be to simply print all numbers of up to n bits
In the first iteration it would be 0 and 1
In the second iteration: 00, 01, 10, 11
In each iteration the number of values you need to print doubles
Ah that makes much more sense, thank you!
There is another example that can be made with the analysis of merge sort, but to not confuse you it's better to study it as a whole
A breadth-first-search on a full binary tree can also be an example
I see, I’m sure the book I’m studying will introduce me to those later on, meanwhile I’ll take a quick look on yt to get a gist of how they work
If you want to delve into it I'd start with the tree example, the merge-sort example is a little less trivial, because it doesn't end with an exponential function
Okay I’ll do that, thank you
try to draw a binary tree
the amount of nodes increases exponentially as you go farther from the root node
I need to wait for a process to finish before executing the next command in my py script. Is there a better way to do it than using time.sleep()??
findStaticFolder(fileToImport) #imports a file inside the game engine
os.remove(fileToImport) #should delete the file from it's location after it is imported inside the game engine but is getting executed before the previous task has finished.
Since the importing time can differ, I don't wanna use sleep().
Make the script remove itself?
I mean, the script that loads the file
After its done, make it remove the file
@eternal bronze how are you running the background process
Oh i see. I recommend using a ThreadPoolExecutor to run this
you can do other work after the job has been submitted
Then when you're ready you can go back and wait for the job to finish
Ill post an example when i get to a computer
Suppose you have a number of numerical ranges
do you think there's an O(1) algorithm to figure out which of those ranges a given integer belongs to?
(if any?)
If you can assume the list of ranges is ordered, you can make it in O(logn). Otherwise, the mere act of finding out what ranges you even have will take O(n)
I don't see much of a difference from an ordinary search in a list
there is an O(1) algorithm assuming all ranges are finite and you are allowed to precompute things by just exploding all the ranges into a list of booleans and indexing into it (checking bounds naturally)
range(1, 3), range(4, 6) -> [0, 1, 1, 0, 1, 1, 0]
are they non-overlapping?
Yeah, it crossed my mind, but didn't seem like a general algorithm for any set of ranges considering the space requirements
Otherwise, the mere act of finding out what ranges you even have will take O(n)
@quasi oracle
Excellent point
I was thinking there might be a way to do it with hashing but I'm never going to have a high enough value of n for it to matter.
Like lak said you can explode the ranges
But you can place them in a set, and then not waste space on values that aren't in a range
I have a bunch of spacy Span objects, which know their character spans in the document they came from, so I just need a mapping of character spans to Spans.
def find_sentence(start: int, sentences: t.Dict[range, Span]):
for r, s in sentences.items():
if start in r:
return s
raise RuntimeError(f'start value {start} not in any range')
The preprocessing still has to be O(n) though
right
@loud trail @mortal arch hey thanks guys! I found another way to do it inside the game engine.
is it possible to write pure functions without doing functional programming stuff like recursion, map, reduce, filter, higher-order functions and still reap the benefits of FP? Those FP stuff are not easy to master.
you can write entirely pure functions and without using HOFs and still get all the benefits in easy to reason about code, but without HOFs it is extremely difficult to actually get something done
you can write entirely pure functions and without using HOFs and still get all the benefits in easy to reason about code, but without HOFs it is extremely difficult to actually get something done
@mint jewel good to hear that. HOFs need some mental adjustment. Not easy. I think pure functions shouldn't be too hard. Avoid global variables, avoid call by reference, use immutable input data etc Those are easy guidelines to follow
I would suggest not trying to do fully pure FP in python. Keeping most function pure is a good thing, but you cannot really do effects with pure functions in python like you can in e.g. haskell
A good practice would be to use pure functions as much as possible unless the particular application doesn't allow that. Maybe one can mix FP and non-FP code with python since python supports some FP features
Has anyone used a virtual machine before
I'm planning on setting it up
Even tho I don't have the CPU resources
I did, with Virtualbox on Ubuntu.
It's pretty straightforward, in fact, you install your OS like on a genuine machine.
Depending on your needs, you may want to add the Guest Additions, though (typically, to share a folder). It's like a driver to install on the guest machine.
As for your CPU, it really depends on what you have, and what you plan to do with your VM. If it works on the physical machine, and you just want to virtualize it (move a task from physical machine to virtual one), it shouldn't be a problem. I would be more concerned with the RAM space, as you will have the equivalent on two OS on the same space.
can - W10 based , 4 core @ 2Ghz , 16 Gig mem ok for virtual machine?
You can run a VM on pretty bare hardware, it will just be slow
they are all roughly equally good
@fiery cosmos computer science is a huge subject with a fairly unclear progression
What specifically are you interested in?
Hello guys, I have a dictionary that looks like this:
'Mammal': [('Mammal','Bear'),('Mammal','Tiger'), ('Mammal','Dolphin')]```
Assuming that this is a network graph, I am trying to get connected components from a network graph with the following algorithm
```def get_all_connected_groups(d):
already_seen=set()
result=[]
for node in d:
if node not in already_seen:
connected_group,already_seen=get_connected_group(node,already_seen)
result.append(connected_group)
return result
def get_connected_group(node,already_seen):
result=[]
nodes=set([node])
while nodes:
node=nodes.pop()
already_seen.add(node)
nodes.update(n for n in d[node] if n not in already_seen)
result.append(node)
return result,already_seen
components=get_all_connected_groups(d) ```
However it stops with the second element of the dictionary
```('Bird','Falcon')```
and gives me an error highlighting this line
```nodes.update(n for n in d[node] if n not in already_seen)```
I think is because the example uses numbers as the nodes and I am using strings but I am not sure, any help works!
@chrome jacinth this is better suited for a help channel. See #❓|how-to-get-help
Thanks!
Suppose I have a function which can return a random integer within a given range of integers then how can I make it such that it return a unique integer at every call.
I know about Fisher-Yates shuffling, but are there any other alternatives? (I am not looking from an optimization perspective, I just want to know an alternative method, But it should converge accordingly), but of course we have choosing a random integer and storing the visited elements in a set and then we can keep picking a random integer but it will converge slowly or may juggle within the set for the final element for a large set of numbers (for an unacceptable amount of time, I know the term unacceptable is vague here, but the point is, it should converge effectively). So if there is any feasible alternative then please recommend.
shuffle the range, give numbers from it, then shuffle a new one when it runs out
@serene mango
I guess you;re asking about low level implementation, I was just thinking python where shuffle is built in
Yes, using inbuilt shuffle kills the purpose, how to shuffle it?, that's one of the simplification of the problem statement(given we are relating shuffling and a random unique integer like that). I want to work on it from scratch with the only condition that I have a function which can give me random integer within a given range. So for python that would be random.randrange(low, high +1)
@runic tinsel
instead of building a set of already rolled numbers, remove them from the range?
it kinda still has performance issues
I am not worried about the performance issues now as in O(x) thing, the only condition is it should converge effectively because I already have Fisher-Yates with the best performance.
How do you suggest removing from the range will work? I mean, I would have to tell the algorithm that such numbers are removed and then they would have to be stored somewhere for me to tell the algo, then in the end, wouldn't it be same as storing in a set?
like you have an array of them [1,2,3,4,5], you roll a 3 replace it with the next number: [1,2,4,4,5], then you roll a 4, replace all 4: [1,2,5,5,5]. I'm just making this up nevermind
oops biased too
I was thinking what can I do on top of this to somehow make this work, but I got nothing xD'
xD' A decent attempt though.
i'm reading this link http://okmij.org/ftp/Haskell/perfect-shuffle.txt from wikipedia article on fisher yates and I don't understand it lmao
ok they're saying the random number list has a zero appended for some reason
Oh fisher-yates is very simple and kinda really not that smart but its interesting.
so u simply roll a number and swap it with the number at first index, and then you roll from the numbers from second index to the end, and whatever u get, u swap it with second index, and u keep on doing this till the end. lol
u not only get random, but u get uniform random .. O(n) time and O(1) space xD;
they aren't doing fisher yates, it's completely different they just start with a naive one and it has weird phrasing
the whole article is hard to read 😐
The article is labelled 'Perfect Shuffle', isn't perfect shuffle more like a permutation, rather than a random process?
yeah they didn;t know that they correct it the footnotes
how about, you add rolled numbers into a sorted list, you roll a smaller range and you find how many numbers you skipped and add that number to the rolled one
so it's O(nlogn) time?
Can you please explain on what do you mean by add that number to the rolled one, you mean, these numbers to be in the list to be rolled?
say you alrady rolled [5,7,3,2] previously. You don't have anything else in memory.
oh it's sorted, [2,3,5,7]
you roll a random number in range (0, n-4)
say it's 5
you search [2,3,5,7] and find out [2,3,5] are "on the left side" of 5, so you add 3
5+3 is 8
each roll takes (log n) time to update the list and (log n) again to find out the correction
guess it's the same operation, so just once
no it's not the same you find the position of 5 but you update with 8
i'm confused too
But this won't guarantee uniqueness, it might happen that when you find 5 then 5 + 3 = 8 is already in the list, and it may happen that all elements 5 +2 = 7 and all elements before 5 are in the list
then how do we guarantee uniqueness
yeah it doesn't work out
imagine our range [ . X X . . ] we already rolled Xs, our list is [1, 2] and we roll 0-2 because that's how many dots are left
we get 1, there's one number <= 1 in the list so we correct it to 2, and we repeat this because it changed the position, when it stablizes we got our number
we already know we rolled the second dot, we just need to know the actual position of that second dot
we simply need to correct it without doing the binary search again
Surely there's a complete algorithm in Knuth he like did all the shuffle methods on earth. Although he wasn't doing python so maybe not this one exactly
You already implemented fisher-yates?
no
Can't you just use like a queue and pop elements off it
import random
def rnd(low, high):
return random.randrange(low, high + 1)
def shuffle(the_list):
if len(the_list) <= 1:
return the_list
last_ind = len(the_list) - 1
for i in range(0,last_ind):
ran = rnd(i, last_ind)
if ran != i:
the_list[i], the_list[ran] = the_list[ran], the_list[i]
This is my fisher-yates implementation
we get 1, there's one number <= 1 in the list so we correct it to 2, and we repeat this because it changed the position, when it stablizes we got our number
@runic tinsel Can you please, explain this bit, or give a short example of your approach, like with 5 elements or so? I am having trouble understanding the stabilization part.
Can't you just use like a queue and pop elements off it
@shut osprey Will that be uniform though?
wdym uniform
The shuffling algorithm is what makes it random
you are just getting one element at a time from the shuffled list
like if you shuffle a deck of cards well, the probability of drawing any given card is the same
we're trying to avoid fisher yates, so any other shuffling or no shuffling
you are just getting one element at a time from the shuffled list
@shut osprey not all shuffling is uniform .. for example: simple swapping
we're trying to avoid fisher yates, so any other shuffling or no shuffling
@runic tinsel yeah and this.
you rolled 4 out of a smaller range and previously rolled [2,3,5,7]
import random
def random_walk(list):
while list:
index = random.randint(len(list))
yield list.pop(index)
Can't you just do this
you see that you're like off by 2, immediately you change 4 to 6, but that means you actually past 5 too, so you add 1 more, you get 7, 7 collides again, 8
8 is great
intuitively this stutter stepping could be done without binary search but it's probably wrong, and you should just search again on the right side
[ . . X X . X . X . . X] we can see that fifth dot is indeed in position 9
intuitively this stutter stepping could be done without binary search but it's probably wrong, and you should just search again on the right side
@runic tinsel
Yeah and then we would have to search the right side, and for an overflow in range we ignore it and roll again or we use a modulo on the range peak. I will try evaluating this one mathematically and see what could the edge case be.
we don't overflow the range
the range decreases by one after each roll
what do you mean
Oh, that was just for the edge, I mean when we add 1 more. But I get the idea.
Can't you just do this
@shut osprey yeah that works too. Uniqueness will be guaranteed by popping a visited element.
But that is kinda an implementation of fisher yates, I mean instead of swapping with an initial index(and move on with it), we pop this index and move on
@runic tinsel thanks for the detailed approach, I will work it out and see if something comes up in it, will mention you if that happens.
nice
What's a good api for image recognition
Vision AI???
umm I need a small help
hey I cant unmute on the general voice channel
ok.
I'm looking for a package suitable for spatial indexing and spatial queries (2d and 3d). It would be nice if someone at least somewhat familiar with one of those could recommend one.
Suitable in my case means:
- thread-safe (which rules out https://toblerity.org/rtree/)
- no unnecessary data structure baggage such as Pandas data frames. Bare minimum please (such as tuple, list or numpy array based) (which rules out https://geopandas.org/)
- sufficiently well-performing for what it does. Indexing and querying a set of objects amounting to a magnitude of about 100 to 1000 should be worthwhile - in comparison to naive iteration over all those objects. Indexing does not need to be particularly fast. All objects will be indexed once at the beginning of the run, whereafter there will be about a million or several million queries into the same index.
- maintained at least in the last 12 months and usable from modern Python (i.e. 3.6 or higher)
@somber wind have you considered postgres + postgis?
@loud trail I don't want a database. No storage. I just want a lightweight python module/package to integrate with my application. The objects are just needed for the run and are not that many. They don't need long-term storage. A full-blown database is not justified for my use-case.
Just an R-tree module (or equivalent approach) that is also thread-safe (in contrast to the above mentioned module).
No, just concurrent queries.
it does not
is there a C library that works for your use case? you could write a python lib to wrap it
evidently rtree wraps libspatialindex
i see
how about spatialite?
after all, sqlite is just a file on disk and fully in-memory databases are supported
you might have to build your own version of the sqlite3 python module to support it
Still, I'd like to avoid the added complexity of databases.
sql syntax seems like a small price to pay for a fully in-memory postgis equivalent
I'm really just looking for a recommendation of someone who has used a spatial query module. I'm going without spatial queries for now.
maybe re-ask your question in #databases where someone with experience is more likely to see it
and i really dont think sqlite is that much more complexity - you have very specific needs and it appears to meet them
@somber wind you can also look into PyGEOS which uses numpy but not pandas. not sure about its thread-safety though
You want to try spatial queries in 3d without a database? If you can find it, I'd be interested to hear about it!
Well, the rtree module mentioned above fits the bill, apart from thread-safety.
what's the trade off between thread-safety and the data integrity that a database would provide?
data integrity? not sure how that's relevant for my use-case
@red solstice the underlying library appears to just segfault if you use multiple threads even for read only queries
So its not a matter of data integrity in this particular case
You could look at scipy's cKDTrees. I suppose you can achieve parallelism by copying the data structure created, but I don't know if it suits your needs
i want to understand how other coders do stuff -- but i feel i have learned - BAD HABITS -- i want to have better more standard code -- is ther a good tutorial that can step me through - i want to do this so i can read what you do
and also i can show stuff
@frail valve maybe post a code sample that you are concerned about. I don't know of a good single resource. Reading code for big libraries can be enlightening. And read the PEP8 and Google style guides.
mmm ok thanks
is to get overload - so i ask first
easy to get overloaded - i ask first - time saver
my code is too crappy to show -- maybe one day
@runic tinsel Hey that worked well, with a slight modification!
Just letting you know!
@serene mango cool so it's O(n²)?
WELP
@serene mango cool so it's O(n²)?
@runic tinsel I haven't done the asymptotic analysis, but if we use Dynamic Programming then it could be done in less than O(n²) I guess. I will try!
what are the things we can do in python
@fiery cosmos Not just python you have to use other modules and frameworks to take the most out of it
There's a lot of things you can do in Python that there really isn't much accessible outside of it
The public library support is just so robust
Hi, I was wondering if there is like any free software to know if code is plagiarize or similar to an online source .
I doubt it, good code is usually pretty darn similar to other good code doing the same thing
Just want to look at something to gain an idea but don’t want to copy it fully
a quick google search for "code plagiarism checker" yields some interesting results. but yeah i think generally its agreed that you cant really plagiarize code lol, a lot of CS is abstraction and building upon other people's published work
can anyone take a look at my code and tell me if its good or not? if for a minigame that me and my friends have made
anyone have any advice to start learning phyton?
@potent pier don't look at it as if learning python, but programming in python.
so, anyone have any advice to start programming phyton?
I would start on udemy that is how I started
thenewboston has good Python Tutorials but like @arctic dome learn concepts to problem solve, make algorithms and think like a programmer
Regardless of where you learn, make sure your always making things
Showing it to other people and asking if it's good can also be super helpful
Hi I am trying to use a raspberry pi, I don't know what the hell i am supposed to do. Anybody know what I should start with to learn how to make a raspberry pi work?
It's just a computer without a case
Heres a guide on first time setup
Hey, can anybody here help me open a .res sound file?
I can't open it as it requires c++ or other visual studio to be opened.
@fiery cosmos congrats on the pi! It's really easy
I'd strongly encourage you to learn about ssh and headless setup
I use my raspberry pi over the terminal 99% of the time
@gentle spoke what is ssh and headless setup and where should i learn about it
basically, ssh is a protocol of communication
"Secure Shell is a cryptographic network protocol for operating network services securely over an unsecured network."
it's the standard way for easy, secure access over computers over the web
oh I THINK I get that
os.system("hostname")
f= open("name" , "w+")
f.write(????)
f.close()
question: how do i save command output into "name" file?
/
|
os.system("hostname")
someone can help
Don't use os.system
why