#algos-and-data-structs
1 messages · Page 119 of 1
so ur trying to tell me available[name] and amount are not the index but the index?
then if its for test cases, u should ought to change them to integers like the problem
let me take another look give me a few moments to read and get some coffee
I didn't want to waste time on test cases because they were not the point of my question
what im confused about is, how do you know how much makes one cake
def cakes4():
recipe = {"apples": [3], "flour": [300], "sugar": [150], "milk": [100], "oil": [100]}
available = {"sugar": [500], "flour": [2000], "milk": [2000]}
for index, keys in enumerate(recipe):
for index2,keys2 in enumerate(available):
KEYS1 = recipe[keys]
KEYS2 = available[keys2]
for stuff, stuff2 in zip(KEYS1, KEYS2):
calc = stuff//stuff2
return calc
else:
if stuff > stuff2:
calc = stuff//stuff2
return calc
``` im getting the right answer but its giving me a type error for the interpretor on the website but in my IDE it runs just fine
yes its sloppy
but ehh
ahh its because im using a list
eitherway that should be faster than ur code and it still gives the right answer, now what i want u to do is figure out why it wont run with a list instantiated
2.842704500000764, 2.159629199999472, 1.8395526999993308, 1.0164244000006875, last one is mine
hmmmm, i dont watch tutorials anymore, back then when I did that I was trying to understand real basic stuff like list comp and dictionaries which i still need to become more versed in. I personally like to read tutorials/documentation/sourcecode examples. Make print statements within the code to see what variables mean, what is actually going on in that code is what u gotta do.
algorithms in my opinion (just scratching in the surface to them myself) is really just learning to traverse and manipulate arrays
think about it like ur trying to sort a list from least to greatest, what algo or what condition or even conditions would that consist of?
tbh with u, that problem above is the first algo problem i solved
first one i ever worked on
i would use bubble sort, learnt it from a Tom Scott video haha
that would be really nice
so you just, decided to
solve a problem and did it? 🤔
yes
yeah i guess u could say i did, didnt think of it like that but ye
not like i solved quantum entanglement though
Is the space and time complexity for .join() method O(n)?
llist = ["This", "is", "a", "test"]
string = " ".join(llist)
print(string)
>> "This is a test"
why is ds algo so hard for me 🥲
i can't understand a thing
can anyone suggest me any books
@fiery cosmos please lemme know if u find one 😆
i found one
please?
grokking algorithm
Oh
i have been told its a good book
I did happened to come across that
did that book help
No I just looked at first few chapters, It's fine ig
oh okie
What I'm thinking of is to somehow learn problem solving along with ds algo
At present I'm trying checkio.org btw
I just started, so not much review I can provide but it looks like a game 
noice
You should definitely check it out then
@dapper sapphire Space is definitely O(n) so is time, even I had feeling of quadratic. But checking stackover flow happened to be O(n)
And I think how it's done is you find the cumulative sum of length of all the sub-strings, then allocate required space, then you start copying! 😅
@fiery cosmos plus creative solutions by others 🎉
Yeah thanks! I am not sure how it's implemented. But if I were to implement something like this I guess I would use bytearray and pass in the size / length and then copy each element over of each substring index by index since bytearray is mutable.
can sombody suggest me a good book or any other reference for DSA.I have just started competitive programming any kind of help would be appreciated .thank you!
Objects/stringlib/join.h line 57
/* Here is the general case. Do a pre-pass to figure out the total```
This says you’re right
Oh wow thanks. What does "bytes-like" mean, when it says, and see whether all arguments are * bytes-like?
Oh so these are different types of bytes, like bytearray, mmap.mmap, array.array.
https://stackoverflow.com/questions/46750606/what-is-a-bytes-like-object
Hey guys for algorithm and data structure kindly visit tutorialspoint for better explaination on algorithm and data structures 🙏🏽🙏🏽
DSA proselytizers 
@fervent saddle thanks for the insight
I've always heard bad about goto but I see a lot of these here!
maybe someone has a idea to extract corners of a jigsaw puzzle piece... i tried almost everything... hough lines... polar coords with angle velocity.... contour defects...
No matter the programming language, every programmer must learn data structures and algorithms (DSA). Our DSA tutorial will guide you to learn all the major topics of data structures and algorithms with their implementation in Python, C/C++ and Java.
How do people feel about new finger(tip) and palm(up) forms of UI? https://www.youtube.com/watch?v=sbHvkL8IpOc
A holographic blob reacting to hand movement on the Hololens 2. This video demos the effect and walks through how it is achieved.
Only the index finger on each hand is used as the effect is much clearer on video that way.
Github with UE4.26.1 project here: https://github.com/JIoffe/HoloFluidBall
You know Guido is working for Microsoft now https://github.com/JIoffe/HoloFluidBall
I wonder how his IDE will look in HoloLens
wow, very cool
hey guys, what kind of file you would propose to hold some info and by one click can load it to the entry boxes ?
i mean for easy writing and reading
@chilly crane r u creating such file or looking for‽
i want load from file and save to file but wonder which would be easy to manipulate
can someone help pls?
i want to "reverse search" a dictionary, but id prefer to avoid for loops.
im dynamically generating lists of unknown length, and all the items in a given list should correspond to a particular string.
i can easily construct a dictionary as {"string":[generated list here]}, but that would make searching for the key via an item in the list slow.
i can also generate {"item":"string"} for each of the items, but again thats slow.
is there a better datatype for having multiple keys go to a single value without having to generate a dictionary entry for every key? or is there a method for searching a dictionary this way that doesnt need loops?
@lament oriole did you try sets in place of [generated list here], I believe even sets have O(1) time complexity
i have cast the list to sets (its a library generating the lists) but still have to iterate over the dictionary when searching, making it O(n) at worst
You looking for O(1) 🔥
every day
@lament oriole
I wonder how could this be slow:
i can also generate {"item":"string"} for each of the items, but again thats slow.
reversedDict = {
item: "string" for item in theList
} | {
item: "string" for item in theList
}
for == sadness
Well, you won't achieve O(1) If you also need to search that list
Also
also wdym by "search"
Do u just want to know If there is an element in that list
Or u want index or sth
btw what that theList contains
Also, what are those "items" in a list? Integers, strings or sth else?
What I'd do is
For each string I'd have a BST (or even Red-Black or AVL tree)
This would make searching O(logn) which is not that bad
the list is a list of strings, each of those strings is unique across both its list and all other lists, so casting to set isnt a bad idea.
for searching, i want to have some way of addressing the dict/whatever type by an item in a list, and it returns to me the key that its under.
ideally, theres a way to generate and index without iteration.
i can do generation without iteration;
{"string": myList} but i then have to iterate twice when searching, once for the dict and once for the list.
i can do searching without iteration, but then the list generation looks like
mydict = {}
for l in all_lists:
mydict.update({item: "string" for item in l})
which uses 2 loops.
i just wanna do this without loops, and faster than loops
im very new to data structures, idk what those 3 are lol
decided to bite the bullet on generation to ensure faster searching, just used this as it's fast enough at the scale im using it
reversedDict = {
item: "string" for item in theList
} | {
item: "string" for item in theList
}
you think i could build a discreet system for breaking things apart, based on the heat equation?
like instead of heat its would be stress and if it hit a certian amount the lattice connection would snap
@mint hedge #❓|how-to-get-help
also
!rule 8
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
im sorry
>>> from bidict import bidict
>>> element_by_symbol = bidict({'H': 'hydrogen'})
>>> element_by_symbol['H']
'hydrogen'
>>> element_by_symbol.inverse['hydrogen']
'H'
would
>>> element_by_symbol = bidict({'H': {'hydrogen'}}) # <- changed to singleton set
>>> element_by_symbol.inverse['hydrogen']
still work?
i doubt it, also sets aren't hashable, you need frozenset
oh right, shouldve made that a tuple really
element_by_symbol = bidict({'H': ('hydrogen',)})
element_by_symbol.inverse[('hydrogen',)]
this should work
for individual list elements, yeah you might need to build 2 dicts or use a fancier data structure
element_by_symbol.inverse[('hydrogen',)] would this singleton tuple work if there were multiple items in the stored tuple?
no
dang
still though, this seems like a useful library. ill make note of it. thank you
red-black and AVL trees are binary search trees that can be rebalanced (or are self-balancing) to provide better guarantees about time complexity when searching
things = {
'H': ('hydrogen', 'helium'),
'C': ('carbon', 'cobalt'),
}
things_rev = {
val: key
for key, vals in things.items()
for val in vals
}
query = 'H'
lookup = things.get(query, things_rev.get(query, None))
this could work if you don't know if you're looking for a key or value, and if you know that a value can only ever appear under one key
slow to construct + double storage, but still fast to do lookups
things = {
'H': ('hydrogen', 'helium'),
'C': ('carbon', 'cobalt'),
'?': ('cobalt', 'hydrogen'),
}
from collections import defaultdict
things_rev = defaultdict(list)
for key, vals in things.items():
for val in vals:
things_rev[key].append(val)
this works in the more general setting where you might need the reverse lookup to be multi-valued
you can also use https://pypi.org/project/multidict/ for the multi-dict
things = {
'H': ('hydrogen', 'helium'),
'C': ('carbon', 'cobalt'),
'?': ('cobalt', 'hydrogen'),
}
from multidict import MultiDict
things_rev = MultiDict()
for key, vals in things.items():
for val in vals:
things_rev.add(key, val)
hi guys how can i write base64 in a text file using pyhton
i want to clear the file before i write it too
@indigo berry just use with open in "write" mode
thanks
@fiery cosmos I don't think it's due to recursive function, by default maximum-recursion-depth is set to 1000, if that's not modified then it should yell error at you. I believe the problem is somewhere else. Correct if I'm wrong!
umm hello can someone teach the binary search
im just learn the python basic and i want to know more about binary search
@strange terrace know what sorting is?
gotta learn that first
oh k thanks
can i private chat with you so i can talk more about binary
just send a request friend
You must know what sorting is
Sorting as in putting things in order from least-to-greatest or greatest-to-least
Binary search is checking the middle spot between all the possible values that could have the value you’re looking for
It’s like if you have to guess a number between 1 and 100, and first you guess 50, then 25, then 12 or 13, etc
Hello. I needed guidance from the experts. Is there a way to compare two numbers in the list using xor without using brute force coding?
seq = [1, 2, 3, 3, 4, 4, 4, 10, 10, 10]
def algorithm():
result = 0
for i in range(len(seq)):
for j in range(i+1, len(seq)):
findNo1 = seq[i]
findNo2 = seq[j]
if findNo1 ^ findNo2 == 0:
print('X={}, Y={}'.format(findNo1, findNo2))
result += findNo1 ^ findNo2 == 0
print('Total Matches is {}'.format(result))
algorithm()
Is there a better solution to show the same output print without using brute force?
No offense. The project want me to use xor without using brute force
Given a sequence of positive integers, SEQ, sorted in ascending order, design and
implement an algorithm with Python to determine if there exist two integers X and Y in
the sorted sequence such that X XOR Y = 0
that doesn't say you need to use xor
or that you need to count matches
oh, it's about adding the end points probably
no that's not it
The project wanted me to use xor? Since using for loop twice is getting the numbers in list is treated as brute force.
like, I would never ever think that means I need to use xor
it's useless here
I would add the length to the first number
(1+10-1) = 10
that's the minimum the end number can be if there are no repeats
you can look at the end number, if it was 9, you immediately know there's a repeat
and then you can reevaluate that as you scan the list
and what about counting matches?
proof?
Counting matches is there but need to have better solution
A brute-force algorithm compares all possible pairs in the sorted sequence and
check if they Exclusive OR to 0. However, using this approach will only give you a
minimal points.
what about counting matches
if counting matches using xor operator then its fine
alright
Thank You Experts. Sorry I'm a newbie.
can someone check my code
i need experts
i just learn backtracking and this is the code
Hey @strange terrace!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
from typing import List, Optional, Tuple
Matrix = List[List[int]]
initial_grid: Matrix = [
[3, 0, 6, 5, 0, 8, 4, 0, 0],
[5, 2, 0, 0, 0, 0, 0, 0, 0],
[0, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
no_solution: Matrix = [
[5, 0, 6, 5, 0, 8, 4, 0, 3],
[5, 2, 0, 0, 0, 0, 0, 0, 2],
[1, 8, 7, 0, 0, 0, 0, 3, 1],
[0, 0, 3, 0, 1, 0, 0, 8, 0],
[9, 0, 0, 8, 6, 3, 0, 0, 5],
[0, 5, 0, 0, 9, 0, 6, 0, 0],
[1, 3, 0, 0, 0, 0, 2, 5, 0],
[0, 0, 0, 0, 0, 0, 0, 7, 4],
[0, 0, 5, 2, 0, 6, 3, 0, 0],
]
def is_safe(grid: Matrix, row: int, column: int, n: int) -> bool:
for i in range(9):
if grid[row][i] == n or grid[i][column] == n:
return False
for i in range(3):
for j in range(3):
if grid[(row - row % 3) + i][(column - column % 3) + j] == n:
return False
return True
def is_completed(grid: Matrix) -> bool:
return all(all(cell != 0 for cell in row) for row in grid)
def find_empty_location(grid: Matrix) -> Optional[Tuple[int, int]]:
for i in range(9):
for j in range(9):
if grid[i][j] == 0:
return i, j
return None
def sudoku(grid: Matrix) -> Optional[Matrix]:
if is_completed(grid):
return grid
location = find_empty_location(grid)
if location is not None:
row, column = location
else:
return grid
for digit in range(1, 10):
if is_safe(grid, row, column, digit):
grid[row][column] = digit
if sudoku(grid) is not None:
return grid
grid[row][column] = 0
return None
def print_solution(grid: Matrix) -> None:
its a sudoku with backtracking
is this wrong or right
im a begginer so sorry if its wrong😄
Looks about right? Does it solve your example sudoku?
i just test it and it say cannot find solution
and i dont know what is wrong with it
Wait, I think I see the problem
?
wait no
let me see the code again
hmmm what is the problem
i just check it and nothing wrong with it
When I run sudoku(initial_grid) it just gives me a solution?
In [1]: sudoku(initial_grid)
Out[1]:
[[3, 1, 6, 5, 7, 8, 4, 9, 2],
[5, 2, 9, 1, 3, 4, 7, 6, 8],
[4, 8, 7, 6, 2, 9, 5, 3, 1],
[2, 6, 3, 4, 1, 5, 9, 8, 7],
[9, 7, 4, 8, 6, 3, 1, 2, 5],
[8, 5, 1, 7, 9, 2, 6, 4, 3],
[1, 3, 8, 9, 4, 7, 2, 5, 6],
[6, 9, 2, 3, 5, 1, 8, 7, 4],
[7, 4, 5, 2, 8, 6, 3, 1, 9]]
let me check
wait.
ohh just solved the problem thanks
thank you so much😀
XD
I need experts to be able to help me for this code
So if I understand correctly, you want to find the number of equal pairs?
... why using xor?
"the project"?
Well normally I'd just combinations.Counter and some combinatoric maths
But it sounds like you have some sort of homework assignment
So is there a solution?
Not without knowing what exactly you need to do
I'm new to having to wrangle bunches of data in bespoke ways, and I've got a question about the best way to accomplish something if anyone's got a second
Need to print out x and y that has the same numbers
and each time the same number compare by the xor operator if it is true then result add 1
I've got a couple of nested classes that aren't really working like I expected, I was hoping to imitate some logic I've seen from some ML repos I've dug around in, but I have no idea how they implemented what they did.
Some semi-dummy code:
class TOKEN:
def __init__(self, address, abi):
self.address = address
self.abi = abi
self.contract = w3.eth.contract(address = self.address, abi = self.abi)
class ROUTER:
def __init__(self, address, abi):
self.address = address
self.abi = abi
self.contract = w3.eth.contract(address = self.address, abi = self.abi)
def quote()
self.quote = get_quote
BUSD = TOKEN(abi.busd_address, abi.erc20_abi)
PCS = BUSD.ROUTER(abi.pcs_router_address, abi.pcs_router_abi)
print(BUSD.address)
print(BUSD.contract)
print(PCS.address)
print(PCS.contract)
All of my print statements return as expected, but I'm going to have multiple PCS objects as sub-objects of different TOKEN objects
so BUSD will have a PCS and BSP class, but I'll also have another token TETH that will also have PCS and BSP classes.
How do I keep this clean?
I thought I could do print(BUSD.PCS.address) or print(BUSD.BSP.address), but apparently not.
ok so i am gonna drop a bomb here, and i really need some help. Like please, i dont know calculus, and i found this formula for calculating exp exponentially for a discord bot. here it is
(xp + xp_to_add) // 42) ** 0.55
xp is the amount of xp a user already has, which is pulled from my database. xp_to_add is a random int from 1 to 20, that is added every time a message is sent(if it passes the time lock.
now everything works except that i dont know how to calculate the ex needed to get to another level. Since its exponential, it needs to be gotten using a derivative(?), which i have no idea what that is since i am a middle schooler lmao. Anyway here is my final result(the rank card, and the problem is the
/370 XP~ that needs to be dynamic, calculating the xp needed to level up(and i have no idea) plzzzzz help me this is 3d day of headaches lol
What is the best collision detection algorithm?
i will drop pastebin if more elaboration is needed:
https://pastebin.com/QidQEweK
any good free course for dsa?
if you need to get the rate of change in the value of the exponents as the user gradually levels up, then just use sympy to do the derivative needed for that its a calculus library
What you could do is traverse that list and chech If i-th element is the same as i+1-th element. If yes, then the answer is yes, otherwise no
xor is equal to 0 only when both integers are same
This will be O(n)
And that would be the fastest you can go
hmm ok thx
i get the sympy part but can you explain the rate of change plz i lost u there lol
correct me if im wrong but i could technically just get the exponential value but using the ** operator so something like this?
exp_to_lvl = int((xp + xp_to_add) ** 0.55)
ugh, doesnt seem to work
Since its exponential, it needs to be gotten using a derivative(?), which i have no idea what that is since i am a middle schooler lmao.
nah, you just need to inverse the function.
Your level is calculated from xp asint(xp ** 0.55), if I understand it correctly. So to reachlvl, it needs to be thatxp**0.55is at leastlvl. Put both sides to the power of1/0.55, and you'll get thatxp = lvl**(1/0.55)
@winged hamlet does the data come sorted or unsorted?
i cant thank you enough, thank you so much man, this saves my day, ive been scouring the internet for calculus formulas for way too long lol
@winged hamlet Please paste the question if you cna
guys, how can i use subprocess to call function of another file ?
#script1.py
import subprocess
l=[3,5,6,7,8,9]
for i in l:
call fun(i) of script2
#script2.py
def fun(f):
f=f*f
print(f)
this is just an example. when i run code for 900 videos(research purpose), it works stopped after 10 videos despite of using gpu
I have paste the question above
Refer to this
it is sorted
If they just want you to determine if there exists two integers such that their XOR is 0 then y are you printing x and y and total number of such pairs?
@winged hamlet
Yes
Why are you doing that I am asking, you could break the loop on the first pair saying such pair exists
whats the output format?
seq = [1,2,3,4,4,6,6,10,10,10]
def isPair(seq):
for i in range(len(seq)):
if(seq[i]^seq[i+1] == 0):
return True
return False
This should do the if pair exists trick
@winged hamlet
Hey, Im trying to write a mathmatical program to calculate pi based using newtons method of using the unit circle formula, rearanging it into a binomial formula and Using the binomial theorem to solve for pi/
########### Atempting to Calculate PI using the binomial series and Calculus
import math
####Binomial series
iterations = 10
#x = int(input("Attempting to Calculate PI using the binomial series and Calculus\n The equation of a unit circle is x^2 + y^2 = 1 but we can rearrange that to get route(1-x^2) and simplify this \
#to (1-x^2)^0.5. Which is the equation for the top half of a circle since x can only be positive. by integrating this between the bounds 0 and 1 we can find the area of 1/4 of the circle \
#and therefore pi will be equal to 4 times that. "))
#n = float(input("n: "))
x= 1
n = 0.5
## First 2 terms in the binomial theorem
number = x+(n*(-x**3)/3)
print(number)
for i in range(1, iterations):
###Third term index
index = i+1
print(f"index: {index}")
##Working out the factorial
factorial = 1
for j in range(1, index+1):
factorial *=j
print( f"factorial: {factorial}")
####Working out the coefficient of x.
coefficient = 1
for k in range(0, -i-1, -1):
coefficient *= (n+k)
print(f"first coefficient: {coefficient} ")
#### Coefficient before integrating
coefficient= coefficient/factorial
print(f"real coefficient: {coefficient} ")
newindex = index + 1
value = -(coefficient)* (((x)**(2*newindex)) / 2*newindex)
print(f"value: {value}")
print(f"current value of pi is {number*4}")
number+=value
print("======================")
temp = math.sqrt(3) /8
pi = (12*number)- temp
pi = 4*number
print(f"pi = {pi}")
3.89660390218099 is the closest I can get
it should be more exact than that but for some reason I cant anyone see an error?
these are my workings if it helps
Output format must be
X=3, Y=3
X=4, Y=4
X=4, Y=4
X=4, Y=4
X=10, Y=10
X=10, Y=10
X=10, Y=10
Total match is 7.
It must be format like this
@rustic roost
you have way too many print statements in that
it makes it hard to understand what the logic is
I was using it for debugging
alright one sec
########### Atempting to Calculate PI using the binomial series and Calculus
import math
from decimal import *
####Binomial series
iterations = 124
#x = int(input("Attempting to Calculate PI using the binomial series and Calculus\n The equation of a unit circle is x^2 + y^2 = 1 but we can rearrange that to get route(1-x^2) and simplify this \
#to (1-x^2)^0.5. Which is the equation for the top half of a circle since x can only be positive. by integrating this between the bounds 0 and 1 we can find the area of 1/4 of the circle \
#and therefore pi will be equal to 4 times that. "))
#n = float(input("n: "))
x= 0.5
n = 0.5
### First 2 terms in the binomial theorem
number = x+(n*(-x**3)/3)
print(number)
for i in range(1, iterations):
###Third term index
index = i+1
#print(f"index: {index}")
##Working out the factorial
factorial = 1
for j in range(1, index+1):
factorial *=j
#print( f"factorial: {factorial}")
####Working out the coefficient of x.
coefficient = 1
for k in range(0, -i-1, -1):
coefficient *= (n+k)
#print(f"first coefficient: {coefficient} ")
#### Coefficient before integrating
coefficient= coefficient/factorial
#print(f"real coefficient: {coefficient} ")
newindex = index
value = (coefficient)* (x**((2*index)+1))/ ((2*index)+1)
#print(f"value: {value}")
#print(f"current value of pi is {number*4}")
number+=value
#print("======================")
sqrt = Decimal(3).sqrt
temp = sqrt /8
print(temp)
pi = (12*(number- temp))
#pi = 4*number
print(f"pi = {pi}")
print(cmath.sqrt(3))
BECAUUSE I NEED THEM
okay honestly my head hurts just looking at it
let me
take a while
one suggestion
space out your operators
in general you should have spaces around arithmetic operators
so like
value = coefficient * (x ** (2 * index + 1)) / (2 * index + 1)
instead of:
value = (coefficient)* (x**((2*index)+1))/ ((2*index)+1)
kk
if your code is easy to read
it will be easier for you to get help
ngl I feel tired just looking at that chunk
okay
also you might want to break your code up into smaller functions?
because then you can test them individually
to know they work
e.g. the factorial
no it's really not worth it
@brave oak :white_check_mark: Your eval job has completed with return code 0.
120
yeah wanted to see if I could do it myself
it was a bug fixing attempt I was going to add 1 to the index before I integrate but then I realised u cant so that
yeah, that's another thing
remove dead code
goes back to the readability thing
its removed on the main
main what
but I copied and pasted this ages ago
on my pc
the actual.code
########### Atempting to Calculate PI using the binomial series and Calculus
import math
from decimal import *
####Binomial series
iterations = 124
#x = int(input("Attempting to Calculate PI using the binomial series and Calculus\n The equation of a unit circle is x^2 + y^2 = 1 but we can rearrange that to get route(1-x^2) and simplify this \
#to (1-x^2)^0.5. Which is the equation for the top half of a circle since x can only be positive. by integrating this between the bounds 0 and 1 we can find the area of 1/4 of the circle \
#and therefore pi will be equal to 4 times that. "))
#n = float(input("n: "))
x= 0.5
n = 0.5
### First 2 terms in the binomial theorem
number = x+(n*(-x**3)/3)
print(number)
for i in range(1, iterations):
###Third term index
index = i+1
#print(f"index: {index}")
##Working out the factorial
factorial = 1
for j in range(1, index+1):
factorial *=j
#print( f"factorial: {factorial}")
####Working out the coefficient of x.
coefficient = 1
for k in range(0, -i-1, -1):
coefficient *= (n+k)
#print(f"first coefficient: {coefficient} ")
#### Coefficient before integrating
coefficient= coefficient/factorial
#print(f"real coefficient: {coefficient} ")
value = (coefficient)* (x**((2*index)+1))/ ((2*index)+1)
#print(f"value: {value}")
#print(f"current value of pi is {number*4}")
number+=value
#print("======================")
sqrt = Decimal(3).sqrt
temp = sqrt /8
print(temp)
pi = (12*(number- temp))
#pi = 4*number
print(f"pi = {pi}")
it's late I gtg
bye
Hmm it does not show the output that they wanted
wait no
too many matches
!e
seq = [1, 2, 3, 3, 4, 4, 4, 10, 10, 10]
def algorithm():
result = 0
counts = {}
for i in seq:
counts[i] = counts.get(i,0)+1
for k,v in counts.items():
p = (v*v-v)//2
for _ in range(p):
print('X={}, Y={}'.format(k, k))
result += p
print('Total Matches is {}'.format(result))
algorithm()
@runic tinsel :white_check_mark: Your eval job has completed with return code 0.
001 | X=3, Y=3
002 | X=4, Y=4
003 | X=4, Y=4
004 | X=4, Y=4
005 | X=10, Y=10
006 | X=10, Y=10
007 | X=10, Y=10
008 | Total Matches is 7
it doesn't use sortedness
How open addressing and chaining help to resolve collision resolution in hashing?
i am in my exam and this is question of Data Structure
someone help pls
i am 13
and i joined this server for fun
and i need help
its not related to python AT ALL
@charred fractal If it's not related to Python, we have off-topic channels.
(also keep in mind that we don't allow advertisement, if that's what you're hinting towards)
I was wondering how to use a list comparison to iterate over the first element in the defined list?
could you show an example of what you mean?
i almost kept channel link ty
dude same i was wondering yestarday
no @charred fractal, this is not a platform to advertise your youtube channel if that's what you're here for.
i mean this , i was wondering about this yestarday
!e
!eval [code]
Can also use: e
*Run Python code and get the results.
This command supports multiple lines of code, including code wrapped inside a formatted code
block. Code can be re-evaluated by editing the original message within 10 seconds and
clicking the reaction that subsequently appears.
We've done our best to make this sandboxed, but do let us know if you manage to find an
issue with it!*
!e for i in range(len(vectors)):
if (mask[i] != True):
near_dist = [[dissimilarity(vectors[i], vectors[i2]), [i, i2]] for i2 in range(len(vectors)) if (((dissimilarity(vectors[i], vectors[i2])) < near_dist[0]) and (i != i2) and (mask[i2] != True))]
@prisma lily :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | NameError: name 'vectors' is not defined

ok i just came for help
so ye
that's a pretty complicated comprehension
!code could you format it with this?
Here's how to format Python code on Discord:
```py
print('Hello world!')
```
These are backticks, not quotes. Check this out if you can't find the backtick key.
Lemme make a quick simple version
In short though instead of appending over a list I was wondering if it was possible for a list comprehension to replace the list
Alrighty
@prisma lily :x: Your eval job has completed with return code 1.
001 | Traceback (most recent call last):
002 | File "<string>", line 1, in <module>
003 | File "<string>", line 1, in <listcomp>
004 | NameError: name 'i' is not defined
outlist = [i*i for i in range(10)]
print(outlist)
This list comprehension returns:
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
I was wondering what I would need to do to iterate the first element of the list over all elements resulting in the list:
[81]
Would my only option be a for loop?
hey everyone, i couldn't find this online but does interpolation search work for strings in a list too?
It's currently doing this:
outlist = []
for i in range(10):
outlist.append(i*i)
print(outlist)
That's not what you want?
And I want it to do something more like this:
for i in range(10):
outlist[0] = i*i
print(outlist)
why do you want a list in that case? why not modify a single variable in the loop?
also, what are you iterating over in your main code?
This is to be nested within a list comprehension
I'm storing other elements in the list that relate to the iteration with the overall function
I'm iterating over an iteratable iterating over the length of another list if that makes any sense
hello can anyone suggest me a course for DS&A ??? Are joma tech's courses any good ??
It depends on the use case, but I think this "eventually" may come as soon as n=1
for this case:
def f(n):
lst = [(i,i+1) for i in range(n)]
%timeit next((el for el in lst if el[0]==n), None)
def g(n):
dct = {i:i+1 for i in range(n)}
%timeit dct.get(n,None)
(comparing a list of tuples to a dict), even for n=1 g(n) is faster; because the dict way doesn't need a genexpr with a comparison (all of which happens in Python code)
...
what do you mean by "best"?
and for that matter, by "collision detection algorithm"? Like, do you want Continious Collision Detection or something?
Worth mentioning in general searching a list like that takes time proportional to the length of the list O(N), whereas a dictionary lookup is constant time O(1) (with high probability
). So dict is definitely faster unless the list is tiny.
you can thank hashes for that 
I don't understand it entirely either, but it's an integral piece.
Try asking someone else (and relay it to me if you could)
What do you want to know about hashing?
There's a hash function, and there may sometimes be collisions (2 keys result in the same hash). There are generally 2 solutions to deal with collisions: one is to create a linked list and store all values that have the same hash in it. The other is a probing technique, where it keeps modifying the key until it results in a hash that hasn't been used before.
It’s basically making a list with a lot of empty space, and then doing some math formula on the value you want to put in the list to get a valid index position, and putting it at that index
A simple example for strings would be adding the numeric values of all the characters, then using the remainder of that sum divided by the length of the list
Then if you want to check if a string is in the list, you just use that formula and check at that index if it’s holding an equivalent string
That’s the basic idea of it. Then there’s also a lot of ways to deal with if multiple values get the same index position, like mark mentioned. If you don’t deal with that in some way then it won’t work right
But the idea of hashing is just using some formula to get an arbitrary non-random index position
The MIT 6.006 lectures 8 9 and 10 are on hashing and not bad. https://www.youtube.com/playlist?list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb In fact the whole DSA course and coursework is online.
@fiery cosmos 2021?
Or 40, honestly 😄
40 is conservative yeah
I was trying to make a math function that subtracts the minimum value of a list (lists are used as input). I end up getting this error:
Arr.minimum(*list1, *list2)
TypeError: minimum() takes 1 positional argument but 8 were given
My code:
class Arr():
def __init__(self, f_list, s_list):
self.f_list = f_list
self.s_list = s_list
def minimum(self):
self.f_list = min(f_list)
self.s_list = min(s_list)
difference = self.f_list - self.s_list
print(difference)
def maximum(self):
self.f_list = max(f_list)
self.s_list = max(s_list)
addes = self.f_list + self.s_list
print(addes)
list1 = [1,3,2,6]
list2 = [5,2,5,6]
Arr.minimum(*list1, *list2)```
I don't know much python. But can't you just make minimum() takes 2 lists instead?
What would a linked list implementation in Python look like especially since there's no way to store a reference to a certain location in memory?
If you have a Node class it can have a self.next member that is another Node instance
I'm currently taking a course about Data Structures and algos, I have this hackerrank thing that I have to do, and it is about Binary Search Trees. Can I inquire here? Very, very new at coding
Ask away.
I'm gonna be frequent here in the future, haha
I fixed that part but for some reason it still says f_list and s_list are undefined, even though it clearly shows them in the variables section on the right-hand side of this image
Thank you, maybe the error appeared due to the fact that I did not put self.f_num in min ()?
I think Ik what the problem is. In this case, f_list and s_list are objects rather than variables. The _init_ function passes these as variables, which is why they're not defined as variables, instead being defined as objects when called in the Arr class
What about using *args or **kwargs instead of what I did? Maybe that'll work
!e
reference to a certain location in memory?
Actually, in Python you can't do anything but reference a certain location in memory 🙂
xs = (1, (2, (3, (4, (5, None)))))
def iterate_over_linked_list(ll):
while ll:
head, ll = ll
yield head
for i in iterate_over_linked_list(xs):
print(i)
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 1
002 | 2
003 | 3
004 | 4
005 | 5
Or do something like this:
class Node:
def __init__(self, head, rest):
self.head = head
self.tail = tail
which will allow you to attach methods to it
what this means?
in the interactive console, _ will store the result of the last evaluated expression (12.5625 in this case)
where does this code come from?
but i'm getting error
this only works on console?
Yes.
okay, thanks
also, you don't need semicolons
yea, i just followed from c++ and it became a habit, lol
btw how many of u guys use virtual studio
vs code?
yep that one
i'm using that one
Yup, thanks for the reminder
Sometimes you confuse different languages, ya know
Why is an inner loop quadratic?
For example if I do
n = 4
for j in range(n):
for i in range(j + 1):
i is not quadratic for me. Even combining the sum of i and j goes nowhere near 16 times.
It doesn't have to be n^2 exactly to be quadratix
In that example, the complexity is n(n+1)/2
Simplifying you get (n^2+n)/2
Dropping the lower order terms, you get n^2 ;)
Big-O notation describes how an algorithm grows
@fiery cosmos Is this what you were looking for? (Sorry for the late response)
So your example grows quadratically
It doesn't necessarily have to be quadratic
Did this answer your question @last fulcrum ?
and I realised I didn't even use the *args variable
Yes, thank you 🙂
same result but without the extra *arglists in the bottom two functions
Yes a little. I'll like to find out how you got n(n+1)/2
np, glad to help
It's the partial sum of an arithmetic series! Are you familiar with that topic in maths?
So we would always take the highest number right?
Highest degree term, yes
No. Not at all. Do I need to to really understand DS & A?
the global statement I did is redundant, I was testing out some things with **kwargs so that's why it's there (got errors so I gave up on it, but I guess I forgot to remove the global statement afterwards)
Hi can i ask is it possible to get the key function to able to sort like name, title, etc if is selected?
@gritty marsh the book I'm reading says this. Although I don't understand the maths.
@last fulcrum ah. Are you familiar with arithmetic series?
... would you like me to prove that formula for you right now? 😆
Yes if you can. I'll like you to help me with maths if you can.
Never heard of it
An arithmetic series is simply a series of numbers produced by adding some other number to an original number repeatedly
Wow that's a bad definition
take for example the example series in that image you sent
1 + 2 + 3 + 4 + 5 + ... + (n - 2) + (n - 1)
here, the original number is 1
the common difference is 1
you get the second term of the series by adding 1 to 1 (resulting in 2)
you get the third term of the series by adding 2 to 1 (resulting in 3)
mmhmm
so the general formula that will be used to represent an arithmetic series is as follows:
(a_1) + (a_1 + d) + (a_1 + 2d) + ... + (a_1 + (n-2)d) + (a_1 + (n-1)d)
a_1 is the starting number
d is the common difference
n is the number of terms you want
so how does that go and transform into n2?
Do you understand this formula?
Yes.
if d is 7 you always need to add 7 to the previous number to get the next
Correct!
Instead of starting from the first term, we start from the last term
The last term in this case would be a_n
so we would represent that as follows:
(a_n) + (a_n - d) + (a_n - 2d) + ... + (a_n - (n-2)d) + (a_n - (n-1)d)
Do you understand that this is simply the series above but in reverse?
what is a _ n? Does_mean multiplication?
a_n is simply the last term in this series
if a_1 is the first term, and a_2 is the second term
and we have n terms
then a_n is the last term
_ in this case is just subscript notation
Oh that makes sense. So if we have 10 numbers we can say find a10
yes
Makes sense now
Alright, great!
Now, the result when you add up all of those terms is known as the "partial sum"
we call it the partial sum because of course, the series is infinite
so if we have the sum of the first 10 terms of the series it's only a part of the series
we use s_n to denote partial sum
Ok
if s_1 means the sum of the first 1 terms, and s_2 means the sum of the first 2 terms, then s_n is the sum of the first n terms
Are you following along with me?
Yes. Basically like a_n So we can say get the sum of the first 30 terms, which would be s30
Yep
Okay, we have all the bits and pieces to start our proof now
we have two equations to represent the partial sum:
s_n = (a_1) + (a_1 + d) + (a_1 + 2d) + ... + (a_1 + (n-2)d) + (a_1 + (n-1)d)
and
s_n = (a_n) + (a_n - d) + (a_n - 2d) + ... + (a_n - (n-2)d) + (a_n - (n-1)d)
Now tell me, do you notice anything interesting or useful about the two equations above?
One is the reverse of the other.
both have 2d, and (n-2)d
All I see is that the signs are reversed for both
Give me a min
I think that means we can get the first value of a sum if we are given the last
And the reverse is true
and d
Not quite, here's a hint:
s_n = (a_1) + (a_1 + d) + (a_1 + 2d) + ... + (a_1 + (n-2)d) + (a_1 + (n-1)d)
s_n = (a_n) + (a_n - d) + (a_n - 2d) + ... + (a_n - (n-2)d) + (a_n - (n-1)d)
what do you think will happen when we add them together?
We can add and subtract like terms?
Correct!
We can cancel out all the d's!
So our result is simply
2*s_n = (a_1+a_n) + (a_1+a_n) + (a_1+a_n) + ... + (a_1+a_n)
(a_1+a_n) is repeated n times
so we can simplify this as
2*s_n = n(a_1+a_n)
isolating the s_n, we get
Sorry, internet went out
Do you know how to isolate that s_n variable @last fulcrum ?
To isolate that s_n variable we simply perform algebra magic
s_n = n(a_1+a_n)/2
if we have the example series above 1 + 2 + 3 + ...
then a_n = n
a_1 = 1
thus
s_n = n(n+1)/2
ok so you just divided by 2 instead of s-n. 😅 I was thinking you divide by s-n
Yep
note this is only when a_1 = 1 and d = 1
which is of course the series you were asking about
but does not apply to all series
I was getting confused by that
this is the general equation that is applicable to all series
this is simply a simplification dedicated for the special series above that exists because of simplification magic
because a_1 = 1 and a_n = n
So how does the general or simplification go to n2?
Ah, this is a whole different explanation
okay so we've established that the complexity is quadratic
because of the above equation
n(n+1) / 2 expands to (n^2 + n) / 2
which expands to (1/2)*(n^2) + (1/2)*n
in big-O notation, we don't care about the lower order terms
we care about the algorithm's growth
thus, we throw away the lower order terms
n is a lower order term
(1/2) is a lower order term
so we simply say O(n^2)
because it grows quadratically
it does not necessarily have to be exactly n^2
let me throw up a quick desmos graph
This is the graph for very very small n
notice there are noticeable differnces
of course, they're different equations. there would be differences
but notice what happens when we zoom out
This is for n on the orders of the hundreds
They look like the same graph, don't they?
Because they grow the same
So basically it's growing quadratically compared to the other equations, even if it might not be n2.
Correct
😆 my pleasure
Welcome!
for key in emp_dict:
record_list.append(key)
templist = []
for key, value in emp_dict.items():
temp = [key, value]
templist.append(temp)
Can anyone help me for the coding
Basically i want to sort by name in dictionary. The key is Employee ID, and the following will have name, title, et
Have you tried googling something like "sort dictionary by value"?
im failing on the test case of [1] and 1 but i cant really see why?
its expected to return an empty list but this returns [1]
Anybody knows a video or tutorial about how to create a simulation for image processing? With photon amount and exposure time and all of that?
Okay so I m gonna ask here because i can t find a proper explanation. What is a B Tree and why the hell should I use a B tree? Is there any good explanations? I can't find a satisfying one (for me)
The only thing that I see in a B tree is that the B tree is some sort of BST but with arrays
I'm new in coding with Python and this Problem showed up when I wrote this code.
I tipped this code in the anaconda probt and this error does not disappear. Pls help me.
Pycharm by default (if you click through the project creation dialogue) creates a venv for each project.
So installing the package via anaconda will install it into your main environment, not the venv.
Instead, click that insall package prompt and it'll install it for you (or the slightly longer way - go to the Packages tab and search scikit-learn there)
^
(also, this isn't really what this channel is for)
thanks
Hi, I wanted to ask if I wanted to visualize merge sort then how do I exactly keep track of the main array ?
hey
huh. feeling myself being an idiot
!e
def decorator_factory(argument):
def decorator(function):
def wrapper(delay, *args, **kwargs):
print(f"getting argument {argument}")
print(f"magically knowing in advance value {delay} of the functiom!")
result = function(delay, *args, **kwargs)
return result
return wrapper
return decorator
@decorator_factory(10)
def pause(delay):
print(f"paused for {delay} seconds!")
pause(5)
I can actually use arguments of my function in decorator in a normal way... I always extracted from *args them
anyone know if I use windows development kit's sign tool on my exe converted file (from python) will it stop seeing it as threat on other computers ?
say i had a tree
with a bunch of numbers
i have to perform 2 operations:
sum of numbers on the path between any two vertices
increment or decrement all numbers on the path between any two vertices by a set amount
how would i do this (preferably in log (size of tree))
vertices?
the space between the vertices are the space
between Documents and Downloads?
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def mergeTrees(self, root1: TreeNode, root2: TreeNode) -> TreeNode:
if root1 and root2:
root = TreeNode(root1.val+root2.val)
root.left = self.mergeTrees(root1.left, root2.left)
root.right = self.mergeTrees(root1.right, root2.right)
print(root)
return root
else:
return root1 or root2
can someone help me understand this?
some weird meld function that creates a tree with nodes whose values are the sum of the corresponding nodes in root1 and root2
its a leetcode problem
but like im not sure how the algo works here...
like how does it know which is left or right?
when binary trees are densely packed into a list you can tell a left node from a right node by whether it's in an odd position or even position in the list
actually, because they're providing the trees as a list, you can massively simplify the solution
Hey 🙂 Well any two vertices share a common root, so the path between them will be going up to that root from the first vertex, then down to the second vertex. If the tree is balanced, then the length of this path is O(log(num nodes in tree)).
Instead of using 'last' from the 2nd line, if I use 'list1' in its place on lines 5 and 6 the code breaks, why is that? 'list2' is used without setting it to a variable: https://paste.pythondiscord.com/nefuhoneye.rb
please anybody that know how to get free rdp help me pls
i mean this is for arbitrary trees
it could be a straight line, or just a bunch of nodes connected to a central one
What's a good source to learn algo and ds?
hey, anyone know how to implement multilevel queue cpu scheduling algorithm in python
IDK i just started learning python I know nothing
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
print(factorial(5))
Can someone help me with the return in the else block? How does it decrease itself?
Data Structures and Algorithms in Python [Goodrich, Michael T., Tamassia, Roberto, Goldwasser, Michael H.] on Amazon.com. FREE shipping on qualifying offers. Data Structures and Algorithms in Python
isn't n-1 less than n?
What's the mathematical way to find the average speed with miles and speed limits
or is it the same as finding the average with any list of numbers
I don't really understand your question. I used 1 because n == 0 is the same as n == 1
you asked how the else-return line decreases itself. n-1 is decreasing n.
On the first iteration it's 5 - 4. But then n is still 5, that's why I'm confused. The value of 5 I gave does not change
So on the second it should still be 5 -4
your call to factorial has n=5, but then it calls factorial with n=4, which calls factorial with n=3
each call keeps its own value of n, but the function calls nest like russian dolls
Still confusing me. You said it calls factorial with n = 4, but the value of n I gave to the code never changed. I guess my problem is why is n changing. In a normal python code that would not be possible
I'll go watch some YouTube videos to help
The n will be different across function calls.
If you call factorial(2), it itself will call factorial(1) (in the else branch).
Data Structures and Algorithms in Python [Goodrich, Michael T., Tamassia, Roberto, Goldwasser, Michael H.] on Amazon.com. FREE shipping on qualifying offers. Data Structures and Algorithms in Python
Why is the n different? Is it like using a for loop where the value of i changes on every iteration?
!e
def print_numbers_down_from(n):
print(n)
if n > 0:
print_numbers_down_from(n - 1)
print_numbers_down_from(4)
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
001 | 4
002 | 3
003 | 2
004 | 1
005 | 0
Thank you but why do you recommend this book
When you call print_numbers_down_from(4), it creates a 'frame' where all the local variables and such live inside the function. Then, inside that frame print_numbers_down_from(3) is called, and the computation for print_numbers_down_from(3) will happen separately
In other words, n isn't a global variable.
Ya n in scope of function only
It covers everything, including Big O notation
I think the thing you are missing is that there are 5 different function calls happening, each of which has its own n.
Have you read it?
Yes that is what I'm using right now.
@fiery cosmos if you want to learn the basics of Big-O, this is a good less-mathematical introduction: https://bit.ly/bigopy
Perhaps this visualization will help:
http://pythontutor.com/visualize.html#code=def print_numbers_down_from(n)%3A
print(n)
if n > 0%3A
print_numbers_down_from(n - 1)
print_numbers_down_from(4)&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=[]&textReferences=false
Or this one, for the factorial: http://pythontutor.com/visualize.html#code=def factorial(n)%3A
if n %3D%3D 1%3A
return 1
else%3A
return n * factorial(n - 1)
print(factorial(5))&cumulative=false&curInstr=0&heapPrimitives=nevernest&mode=display&origin=opt-frontend.js&py=3&rawInputLstJSON=[]&textReferences=false
Ok, thank you again
Ok thank you @austere sparrow @onyx root I think what is confusing me is that I've never seen 5 different function calls happening.
Thank you
Is that you in the video?
yes 🙂
Here is the table of contents. Plus it teaches Python and OOP if you've never learnt them.
smh rule 6
@onyx root||/s||
that's the second time today i saw /s. what does that mean?
Wow, cool. I like the way how you explain
it means that the preceding phrase was sarcasm, not serious
@austere sparrow I really understood the print_numbers function. Not sure why it's not clicking for the factorial haha
do you have Thonny?
it has a really good visual debugger
I'll show a screenshot, but I have 2gb of updates to download
Nope. But I just understood the factorial also. I'll explain so you tell me if it's right
thanks, i gathered it meant that, but didn't know why "s" 🙂
So it's 5 right, then it calls the function on 5 saying factorial (5-1)
So now it's 4. So it calls the function on itself saying again 4-1, so it's basically like it stores the number subtracted and then on the next call uses that number.
It's not really "changing n", it just spawns an entirely separate function call, which will have its own, completely separate n variable.
@last fulcrum Look at this example:
def foo(n):
print(n)
n = 5
foo(10)
print(n)
The call to foo doesn't change the n on the outside, only the n on the inside
!e
def foo(n):
print(n)
n = 5
foo(10)
print(n)
@last fulcrum :white_check_mark: Your eval job has completed with return code 0.
001 | 10
002 | 5
So basically we give number to the function, that number then becomes a local variable, and then because the function is calling itself, each number becomes a separate local variable?
exactly
Imagine a shady Amazon seller. When you buy a book from him for $20, he goes on to buy it from another seller for $16. That seller in turn buys from another seller for $14, who just had it laying around.
Each of those transactions will have its own price, order ID etc.
Ok. Go on. And that's a great example
So I have one more question.
So then if it's doing separate calls how does it combine them all when it reaches the base case?
def factorial(n):
if n == 1:
return 1
else:
return n * factorial(n - 1)
If you call factorial(1), it's going to return 1.
If you call factorial(2), it's going to return 2 * factorial(1), which will in turn call factorial(1), which will return 1, so the result is 2
If you call factorial(3), it's going to return 3 * factorial(2), which will in turn call factorial(2), which will return 2 (as shown above), so the result is 6
If you call factorial(4), it's going to return 4 * factorial(3), which will in turn call factorial(3), which will return 6 (as shown above), so the result is 24
You could change the function like this:
def factorial(n):
if n == 1:
return 1
else:
previous = factorial(n - 1)
return n * previous
```, maybe that will help.
I like this better. Thank you and @onyx root for explaining to me
Maybe you'll understand it better if you implement this function:
def flatten(a_list):
...
>>> flatten([1, 2, 3])
[1, 2, 3]
>>> flatten([1, 2, [3, 4], 5, [6, 7]])
[1, 2, 3, 4, 5, 6, 7]
>>> flatten([1, 2, [3, [4, 5]], [6, 7], [[[8, 9], 10]]])
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
I'll work on it. Going to bed now. And thanks once again
👍
Hi! I was browsing the internet and found this golden ratio formula. I tried to code it, unfortunately it seems endless and I have trouble conceptualizing the code. Someone would have any idea ? Thank you.
Have you tried some implementation?
@onyx root Could you please recommend an algorithms and data structure book?
I don't have a recommendation.
I just want to have sevral choices
What's your source by the way
A favorite source
Check the pinned messages for some resource recommendations.
I don't know what to tell you, i don't have a source for data structures etc, I guess I google when i need things.
Okey, thank you
I saw but i'm searching for a good book which helps me to prepare for the coding interviews using Python
A book called Cracking the Coding Interview is often recommended for interview prep. I own a copy but I've not read any of it, so can't vouch for its quality 😄 A very popular undergraduate algorithms textbook is _Introduction to Algorithms, by Cormen, Leiserson, Rivest, and Stein. It's a good textbook, but quite mathy.
On behalf of our industry, i would like to apologize in advance for coding interviews
Heavy artillery math? 😄
But why? There is no problem i think
they expect you to write code on a whiteboard, while someone is watching, with no tools. You will never have to do that on the job.
they expect you to implement red-black trees, or something, which you will never have to do on the job.
if you can study for the interview, then what is the interview assessing?
Interesting
The trick to computing infinite fractions is usually to take some initial value and substitute it for the ....
For example, if you pick 1 for ... and some random depth, you end up with
phi = 1 + (1/(1 + (1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + ...))))))))
phi = 1 + (1/(1 + (1/(1 + 1/(1 + 1/(1 + 1/(1 + 1/(1 + 1))))))))
...which is 1.619047619047619.
The way you could get up to this point is, for example:
- take some value as your result, like
1 - compute
1 + 1 / (1 + result). It's going to be a slightly better approximation. - store the new approximation
- go to step 1
However, this gets a bit tricky.
Let's try to find an exact solution for phi:
φ = 1 + 1/φ
φ^2 = φ + 1
φ^2 - φ - 1 = 0
φ = (1 + √5)/2
φ = (1 - √5)/2
So there are two solutions to this equation.
If you try to substitute some number (except -1) using the algorithm above, you'll be slowly approaching (1 + √5)/2 (approx. 1.618). However, if you choose (1 - √5)/2 (approx. -0.618) as your starting point, you'll get:
φ0 = (1 - √5)/2
φ1 = 1 + 1/φ0 = 1 + 2/(1 - √5) = ((1 - √5) + 2)/(1 - √5) = (3 - √5)/(1 - √5)
Using some transformations (e.g. using the proportion rule, (3 - √5)/(1 - √5) = (1 - √5)/2 <=> (6 - 2√5) = (1 - √5)(1 - √5) <=> 6 - 2√5 = 6 - 2√5), you can see that you end up at the same point, and result is going to stick to (1 - √5)/2.
(with floating point numbers, of course, it's going to eventually drift, but it's still going to do that very slowly).
oops sorry for the text wall
But I think it's good idea to check problem solving skills which is very important to get fast and optimized solutions. But i'm not sure. What do you think about this
if you implement your own optimized red-black tree for a simple CRUD application, you'll probably get fired 👀
problem solving is a good thing to assess. I just don't see how studying data structures will help with an interview that assesses problem solving.
So again what do you think which is the most reliable way to do that?
Practice solving problems.
have you built anything interesting?
hey guys just completed the basic of python if i want to start dsa where do i start like any youtube channels,books,websites
any recommend
i'm also in the same path, if you get anything share with me too
job security
well, hopefully the company has code reviews 👀 👀
I think yes but not many
I guess it wasn't about competitive problem solving, right?
Geeeks4geeks for concepts.
Leetcode best for practicing learned concepts, filter by tags.
Elements of programming interviews Python edition, nice variety of questions, but solutions are little difficult.
But the theory of book, the approach is nice.
golden ratio is irrational.
Infinite and no pattern
you have formula to get closer, but never exact
Like pi
For binary search, is it better if your item has not been found to make the new upperbound the mid - 1 or is just mid?
Same thing for lowerbound if the item has not been found (mid + 1 or mid)
And is it better to use iteration or recursion for binary search?
performance-wise iteration is always better, you use recursion for aesthetic reasons like readability
well not always, often it's the same, depends on the compiler
for python you want iteration
Anyone knows what I'm doing wrong?
def binary_search(sequence, item_to_find):
lowerbound = 0
upperbound = len(sequence) - 1
while lowerbound <= upperbound:
midpoint = (lowerbound + upperbound) // 2
if sequence[midpoint] == item_to_find:
return sequence[midpoint]
elif sequence[midpoint] < item_to_find:
upperbound = midpoint
else:
lowerbound = midpoint
return None
Why is it >?
And why can't you do midpoint = lower, but you have to add one
[1,2] and you look for 2
midpoint is 0
you change lower bound to 0, nothing changed
just how numbers work out
It would be 1. 0 + 2 // 2 == 1
Ok makes sense.
hi there, I feel like I have been given a question in this practice paper which is not totally accurate and was hoping someone could help me understand. I need to apply branch-and-bound technique to a knapsack problem - but I need to do this by using jumptracking and not backtracking
I was under the impression knapsack problems were solved using backtracking and machine learning type problems were solved with jumptracking
so i'm at a loss when trying to solve a knapsack problem with jumptracking, any help is appreciated thank you
why does this doesnt work? (Ive a file were is the data I need, and its called codigos.py), appears an error in there
from Codigos import English
objQuestionnaire = English()
objQuestionnaire.empezar()
objQuestionnaire.respuestas()
objQuestionnaire.imprimir()
You probably want a help channel (see #❓|how-to-get-help), this doesn't appear to be DSA-related.
(also, please post the error you get if you do)
okok, thanks
If we modify the current array/list, we are not using any extra space, then is it considered O(1)?
Yes, inplace doesn't count as extra memory. For example, many inplace sorts are O(1) extra memory.
(timsort among them, I think)
ok got it thanks!!
Hi, Is this the right place to ask about resources related to algorithms and ds in python?
Yup
So I've been looking for resources lately, I tried CLRS, Princeton Uni's course on Algorithms, elements of programming interview in python but none of them were good for me atleast. I was looking for something which would just explain me the basic algorithms, ds and maybe the implementation from scratch w/o importing anything, I'm ok with video lectures but I prefer articles/books.
I recommend implementing data structures by hand in another language.
Is there anyone here knowledgeable about BSTs and heaps?
Came across this question in some test:
You have an array of integers.
You're supposed to remove those elements A[i] which satisfy A[i] > A[i-1]
Do this until you cannot find any more pairs. How many rounds does it take till you cannot find any more pairs?
For example
[3, 6, 2, 7, 5]
After 1 round, it becomes [3, 2, 5]
After 2 rounds, it becomes [3, 2]
And then it stays that way forever so the answer would be 2
Another example is:
[6, 5, 8, 4, 7, 10, 9]
After 1 round, [6, 5, 4, 9]
After 2 rounds, [6, 5, 4]
Then it stays that way
Constraints were len(arr) <= 10^5
Initially thought it had to do with next smaller element and stacks, but then got stuck
thoughts?
I also tried simulating it, but that timed out ofcourse
can't you do it in one pass? Like, just extract a descending subsequence from the list
iterate over the list, remembering the last accepted element. The first element is accepted, then accept only elements <= the remembered one.
well you're supposed to extract subarrays, not subsequences right cuz it states A[i] < A[i-1]
or maybe I don't understand clearly what you're trying to say
erm, okay you mean get rid of the elements that satisfy that condition
okay but then?
You need to remove all elements that's higher than the previous one. So for an element to remain, it has to be <= the previous one, and therefore <= than all previous ones
therefore, you just need to accept only elements that are lower or equal to the last accepted element
and that's pretty much it
a single pass over the list, O(n) complexity
how does that give us the number of rounds?
getting the numbers that remain in the end is easy, O(N) with a stack, yes.
However, the # of rounds is what's required.
oooh, I totally missed this. Hmm...
perhaps the number of turns for a number to get removed is something like "how many positions away the previous lower number is"
so did I, when I was solving it initially. Implemented the same idea before realising it -.-
haha, yeah I thought so too but then it's easy to come up with counterexamples for that
1, 10, 11, 12, 13, 4
vs
1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 4
Both cases require 2 days
and I tried handling that but then it got tricky because there can be examples like above where you need 3 days, 4 days, more
A number that gets removed but doesn't get removed right away must be a part of a nonincreasing subsequence that starts with a higher number than the last accepted number before it, so, hmm
hmm, indeed it's not obvious
thank you for saying that, makes me feel less bad that I couldn't solve it 😄
I do feel like it's the right way to dig, though - for each nonincreasing subarray, determine how many numbers need to be chipped off of it
yeah essentially you could simulate it till you realise there's no increasing subarrays left anymore
but that's gonna time out
in these cases, the subsequence is 13,4, and it needs to lose 1 number in the first (because then 5>4) and 2 in the second case (because 1 is lower than both of them)
yeah, I think getting the numbers isn't the hard part
I feel like it might be, for each nonincreasing subarray, the number of numbers in it that's higher than the last accepted number
and then you take the max over all these counts to get the value for the entire list
I mean, getting the final list of numbers that survive
i was thinking of cases where you have like
p , .....q, ..... , r, ......, s,..... w
the dots are the elements that are going to get removed
so if q > p, then q needs 2 days.
and then if r < q and r > p, it will need 3 days
but if r > q, it needs 2 days
but if q < p
then, it's like q becomes the new p
and now if r > q, r needs 2 days.
and if r < q, then.. r becomes the new q? and in turn the new p
and that's like
O(N^2) again because
it really makes no difference whether our array was
p , .....q, ..... , r, ......, s,..... w
or
p, q, r, s , w
because in the worst case
we could have p > q > r > s
and for w, we might have to wound back all the way upto p to check whether it gets removed
Agh, now that I think of it
TreeSet sounds like such a good idea
Oh god -.-
that would give us the position of w in the array [p, q, r, s] and essentially the number of days, in log(n) time
hm, I'm still fuzzy about it, maybe I'm just wrong
it still sounds to me like you don't need any ds here. Like...
def rounds(nums):
accepted = last = nums[0]
max_rounds = 0
noninc_count = 0
for num in nums[1:]:
#print(num,accepted,max_rounds,noninc_count)
if num<=last:
# we're in a nonincreasing subsequence
noninc_count += 1
if num <= accepted:
max_rounds = max(max_rounds, noninc_count+1)
accepted = num
noninc_count = 0
else:
noninc_count = 0
last = num
max_rounds = max(max_rounds, noninc_count+1)
return max_rounds
this seems to pass all examples you posted
The examples I posted initially? Those are the easy ones
This for example
fails nums = [5, 10, 11, 12, 4]
well, probably this is an easy one too, but what I meant to say is there were many more cases yeah
I failed on like the last 2 amongst all their cases
and ofc, the cases weren't revealed
now the answer for this case btw, should be 1, the code outputs 2
def rounds(nums):
accepted = last = nums[0]
max_rounds = 0
noninc_count = 1
for num in nums[1:]:
if num<=last:
# we're in a nonincreasing subsequence
noninc_count += 1
if num <= accepted:
#print(num,accepted,max_rounds,noninc_count)
max_rounds = max(max_rounds, noninc_count-1)
accepted = num
noninc_count = 0
else:
noninc_count = 1
#print(num,accepted,max_rounds,noninc_count)
last = num
max_rounds = max(max_rounds, noninc_count)
return max_rounds
passes it. Actually, lemme build a proper automatic tester...
well this one would fail on
nums = [5, 10, 11, 12, 6, 7]
it's very similar to what I'm talking about here
ah, I see
I generated an example [0, 1, 1, 2, 1]
which... yeah, it shows why my approach is flawed
my approach would predict that both subsequences here 1,1 and 2,1 dissolve in 2 turns
but in reality, after one turn, 0,1,1 is left, and the second 1 doesn't dissolve on that turn
also, let's just assume numbers are unique right now
(not that it changes anything ofcourse)
and yes, correct
here's the automated tester I used, using hypothesis to generate examples:
from hypothesis import given, strategies as st
def rounds_exact(nums):
"""Inefficiently (but, hopefully, correctly) calculates rounds needed by simulating"""
nums = list(nums)#copy
rounds = 0
while True:
new = [nums[0]]
skips = 0
for i in range(1,len(nums)):
if nums[i] > nums[i-1]:
skips += 1
continue
new.append(nums[i])
if skips == 0:
break
rounds += 1
nums = new
return rounds
# make hypothesis disprove this.
# Limiting the list size to 1000, otherwise rounds_exact would be too slow.
@given(st.lists(st.integers(0,1000),min_size=2,max_size=1000))
def test_rounds(nums):
true = rounds_exact(nums)
calc = rounds(nums)
assert true==calc,(true,calc)
test_rounds()
ah, quite cool
what's the st.lists() and given decorator doing
@given(st.lists(st.integers(0,1000),min_size=2,max_size=1000))
oh, building a list of ints from 0-1000 of 2 <= size <= 1000
hm
basically, hypothesis can automatically generate disproving test examples (mostly randomly, though once it finds one, it does smart stuff to reduce it to a hopefully-minimal one)
the decorator here describes the parameters - that nums should be a list of size 2 to 1000 of integers from 0 to 1000
wow, cool
how it works? by trying to fuzz whole AST?
you need to provide parameters for what input strategy to use (like, here, a list of ints)
it can also use type hints to infer the data to generate, which is cool
(if your data doesn't have additional constraints)
as for how exactly it works, uhh... I'm trying to read the source but it's unclear. I think it generates examples randomly starting from "simple" ones, but a lot of the niceness comes from it being able to shrink a disproving example to a simpler one
https://hypothesis.readthedocs.io/en/latest/details.html#use-with-external-fuzzers
looks like it support multiple fuzzers, this can be very useful for many use case, cool
this is the function used to decide whether to stop adding elements to a list, say:
https://github.com/HypothesisWorks/hypothesis/blob/2b7d74e5621057d0c9f0fcfbae8de1c80fbacfc9/hypothesis-python/src/hypothesis/internal/conjecture/utils.py#L164
hypothesis-python/src/hypothesis/internal/conjecture/utils.py line 164
def biased_coin(data, p, *, forced=None):```
it has... quite a bit of comments
Hi ! I have a problem ! I have a data file with an array of 7221721721171, I would like to split whenever it meets the number 7
the result I want is : [7..],[7..],[7..] , I tried np.split but I have some difficulties . thx you !
is there a library that has max_heap implemented? i only found minheap
Negate all the numbers
k thanks
is the data in a text file? or is it already loaded as a numpy array?
are there any performance constraints? is the file really big?
hey the datas are loaded in text file
nope , I can reduce it
Hey @fallen breach!
Uh-oh! It looks like your message got zapped by our spam filter. We currently don't allow .txt attachments, so here are some tips to help you travel safely:
• If you attempted to send a message longer than 2000 characters, try shortening your message to fit within the character limit or use a pasting service (see below)
• If you tried to show someone your code, you can use codeblocks
(run !code-blocks in #bot-commands for more information) or use a pasting service like:
so basically the problem is I have 2 list
how to implement dfs in edge list vector<pair<int,int>>edges
you can do it the "stupid way" like this
text = '7221721721171'
sections = []
section = []
for c in text:
if c == '7':
sections.append(section)
section = [c]
else:
section.append(c)
print(sections)
!e ```python
text = '7221721721171'
sections = []
section = []
for c in text:
if c == '7':
sections.append(section)
section = [c]
else:
section.append(c)
print(sections)
@loud trail :white_check_mark: Your eval job has completed with return code 0.
[[], ['7', '2', '2', '1'], ['7', '2', '1'], ['7', '2', '1', '1']]
I have another question , well basically this list is associated with time , how can I apply it on it ?
thx you a lot !
hello guys, I have a deque with maxlen of 50 items that belongs to [0, 640].
Most of the items fluctuate minimally with the range of about 50 or 60. But suddenly, some items emerge from the graph, rise above or go lower than the fluctuation range. How do I detect that change?
the reason it is maxlen of 50 is because the deque is updated per frame.
can you clarify this further? this might also be more suited for a help channel as per #❓|how-to-get-help .
may I talk to you in DM ?
i'd rather not, sorry
okay so basically I have two lists one with a serie of numbers and the second with the time associated
I asked how to split for the numbers and now I have to split for the time and then substract
for example : [7112],[7212] and the time associated [0,1,2,3],[4,5,6,7] and then I have to substract the second list ( there's a lot of number in the file ) [0,1,2,3],[4-4,5-46-4,7-4] @loud trail
you want to subtract the first number in a list from every number in the list?
are these lists, or numpy arrays?
In which topic you want us to mentor you?
in DSA??
https://paste.pythondiscord.com/novesuwohi.lua How to replay game (code) ?
After typing yes in input?
@lean spruce you'd have to put the entire thing in another while loop
while yes:
sure, something like that
maybe it's a good idea to put your entire game into a function
def run_game():
...
def ask_yn(prompt):
ask_repeat = True
while ask_repeat:
user_val = input(prompt).strip().lower()
if user_val == 'n':
return False
elif user_val == 'y':
return True
else:
print('That is not a valid response.')
def main():
play_game = True
while play_game:
run_game()
play_game = ask_yn("Play again? y/n: ")
if play_game:
print('Again!')
print('Goodbye!')
something like this
Does anyone have a good article where I can learn about algorthims in terms of N+1 , N(0), etc...?
please ping me if you do! 🙂
Maybe you mean O-notation? 🙂
Try this article: https://nedbatchelder.com/text/slowsgrows.html
geeksforgeeks has pretty good articles about time complexities
Thanks for your recommendations 🙂
That's probably what I meant haha, would N+1 be considered O-notation?
No, that's not correct O-notation
What term am I looking for that would explain N+1 complexities?
I don't understand what you're referring to.
Did you find that somewhere?
Maybe you are referring to the 'N+1 problem'?
Algorithms that suffer from N+1 , sorry I'm a bit of a noobie with time complexity.
Yes!
Is that just how it's referred to, N+1?
That's not really related to algorithms in general. It's about making N+1 queries when you really need 1.
https://stackoverflow.com/questions/97197/what-is-the-n1-selects-problem-in-orm-object-relational-mapping
Gotcha understood
What study material are you referring to
Just trying to prepare for a Python technical interview. So if they ask for time-complexity questions related to my algo's, I have it nailed down.
Okay
Time complexity is integral part of DSA
I learnt it from geeksforgeeks
Yeah I just visited the many articles they have about time complexity
super useful stuff, thank you 👍
It’s what type of line you’d see if you graphed how long something took vs how much data you have
So finding the length of a list is a flat horizontal line, it’s O(1), since lists keep track of their length
And finding the index position of something in an unsorted list would be a flat diagonal line, it would be O(n)
Like if the x axis was how much data you have, and the y axis was how long it took to do it
That’s why constant factors don’t matter for finding something’s time complexity
Because it doesn’t change what kind of line you see
I see
What would happen if the list is sorted? @fervent saddle
Then you could use binary search
I mentioned it being unsorted so it’s clear that I’m talking about linear search and not binary search
what notation would binary searches be?
O(log(n))
Hey anyone who can code discord bots. I am willin to pay or do what ever you want. I just want my own discord bot for my discord server..
why do we have gaming flag at the background?
ey you can learn it...there is a bunch of good tutorial in yt
you can find an open source bot and just host it
Check #discord-bots
Hello there, I'm not sure were to ask. I try to build a data line graph with dash and plotly. The CSV sadly seperats the date in two rows: Date and Time. Is there an easy way to combine this rows with panda? So i can display the datetime on my x scale?
hi
py
import random
word_list = ["aardvark", "baboon", "camel"]
chosen_word = random.choice(word_list)
print (chosen_word)
guess = input("chose a word ").lower()
display = ['-']
for i in chosen_word:
if guess==i:
print(guess)
else:
print(display)
how can i print my output vertically
please teach me am new to python
wdym vertically?
Each cell of an array must use the same number of bytes. This is true in statically typed languages like C, since I have to do
int data[100]; so everything in memory would be the same since they are all int's. In Python, the language is dynamically typed, so I can do list_1 = ['a', 'b', 4, 4, 4.0]. An int, a character and a float would all take up different spaces in memory, so how does the statement work in Python?
Hello!
Are you familiar with C?
In C, int data[100] creates a contiguous chunk of 400 bytes, and all the ints are stored in that chunk. However, you can make an array of pointers: char* strings[100]. Now you have an array of 100 strings, but the array itself only stores the memory addresses of where each string begins.
U have to add const to make it works
Can someone suggest me a good python data structures algorithm book or video tutorials?
hm?
No, you don't, const just means that you can't change something.
Yes
does my explanation make sense?
Click on my profile. And yes it makes sense
!e
import contextlib
@contextlib.contextmanager
def withandler(var):
try:
print("start stuff")
yield var
finally:
print("finish stuff")
with withandler("123") as var:
print(f"do stuff = {var}")
@unborn sundial :white_check_mark: Your eval job has completed with return code 0.
001 | start stuff
002 | do stuff = 123
003 | finish stuff
more decorators to the throne of decorators
!e ```python
import contextlib
@contextlib.contextmanager
def withandler(var):
print("start stuff")
try:
yield var
finally:
print("finish stuff")
with withandler("123") as var:
print(f"do stuff = {var}")
i'd do it like this
@loud trail :white_check_mark: Your eval job has completed with return code 0.
001 | start stuff
002 | do stuff = 123
003 | finish stuff

@austere sparrow can you help me explain this. The part of the referential structure.
Most significantly, the overall memory usage will be much lower for a compact structure because there is no overhead devoted to the explicit storage of the sequence of memory references (in addition to the primary data). That is, a referential structure will typically use 64-bits for the memory address stored in the array, on top of whatever number of bits are used to represent the object that is considered the element.
Yes thats the only way to make array of strings from array of char pointer without warning after compiling. This is happening when g++ is used as compiler. To make array of string that is editable, u have to make 2 dimensional array of char, not array of char pointer.
const char* strings1[100]; //this is non-editable
char strings2[100][101]; //this is editable
If you make a char* strings1[100], the strings will be perfectly editable, it's just that you can't put read-only strings into it.
A string literal like "Hello!" will point into a read-only part of memory, and not create a new string on the heap or the stack.
This: ```c
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
int main() {
char* strings[2];
char* hello = malloc(strlen("Hello!") + 1);
strcpy(hello, "Hello!");
char* world = malloc(strlen("world") + 1);
strcpy(world, "world");
strings[0] = hello;
strings[1] = world;
printf("%s %s\n", strings[0], strings[1]);
free(hello);
free(world);
}
(also, g++ is for C++, not C)
I miss malloc and pointers. Now python does everything
Yeah, the sky was bluer and the grass was greSegmentation fault (core dumped)
😂 Still, I think every new programmer should learn C before python. Makes understanding low lvl things far easier.
I would probably have given up programming if I started with C.
C is hard, no doubt. But the knowledge you get is so much. Most people would never learn C after python because python is far easier. So start with hard, then go to easy. But I digress.
U didn't what was the task was

hmm