#algos-and-data-structs
1 messages Β· Page 143 of 1
and it's clearly written in the picture.
if you can't read the picture, how can you read our words?
you so rude
im also stress
so no need your bad input
go put your words where they belong in the toilet
you have four days to do this, and you claim it's for a career change. If you're stressed from this, then you're stressed because you're applying for a programming job with no experience. I suggest considering an entry level course in python
you so rude
in this context, they just want the largest number that's not in the array. So sort them, assign them to indexes, and then iterate until you find the first number that doesn't match the index. It's incredibly easy.
im bad but not that bad
i think i understand
i also said this earlier like half an hour ago
the core task is, find the smallest positive integer that is not in the array. So conceptually:
start at 1, if it's not in the array it's the answer we were looking for, otherwise look at 2 and do the same thing, ...
sooner or later we will find a number that is not in the array, and that's the answer
not so simple
i save it on notepad
still stuggled to understand
no need to sort though, sorting is the more annoying solution to write as well
you dont have to even write sort because it's built in. but knowing this is part of actually knowing the skills they're being asked to demonstrate on the interview question.
writing a sort function would probably help them get the job.
I'm not talking about the sorting part being annoying
this is the solution I instinctively went for
S = set(A)
i = 1
while True:
if i not in S: return i
i += 1
you can make it better by not using a hash set, but that's more of an implementation detail
A = A[A>-1]
A.sort()
if A[0] != 0:
A.insert(0, 0)
return [a.index if a.index != a for a in A]
code probably wont work like that but dont fix it, im not doing peoples code for them
the basic idea is correct
there are... 3 errors in this
does this even work for inputs like [1, 1, 2]? I feel like what you're doing there would answer 2 rather than 3
there is a similar solution to that, but starting to mix indices into the mix is confusing at best
it makes the code a LOT simpler
also ,you disregarded my insert 0
the very first index which isnt the value is the answer?
I dont even know how to use set
if I understand your code correctly it would check
0==0, ok
1==1, ok
1!=2, nope, so the answer is 2
1!?
you mean if there are redundant numbers
ah, but that's an exercise for another day
yes, duplicate numbers breaks your approach
A = [i for n, i in enumerate(A) if i not in A[:n]]
yeah, it's easy to fix, and the fix is to not use indices
n^2 π₯΄
^
select any two- memory, easy to write, fewest lines of code
i use indices for all my operations but i also use massively paralleized code
err...the set solution is fine on memory, is easy to write and has few lines of code
and avoids a bunch of pitfalls of e.g. the sorting approach
maybe I'll just write them all and benchmark π
the right data structure solves the task for you
and the set solution is obviously correct by inspection, it literally just does what the task asks, but with fast lookup
well, the right data structure is numpy.unique
sets are inferior to numpy, numpy is the future
but you can't use numpy
also, we want to select only positive values. with a list comprehension, isnt that easily done?
unique requires sorting
sets remind me of haskell and i loath haskell shudders
ill just stick with my nice little arrays
also no dicts! only arrays.
how is set haskelly?
I can solve this with only lists/arrays too, just use a ~N large boolean array to implement the set
one pass over the data, one (probably partial) pass over the bool array, done
@haughty mountain do you have a resource for simple help ?
Favtutor connects students with expert tutors to provide the best coding help instantly & 1:1 live tutoring for all computer science subjects.
its also butts
for python
The Resources page on our website contains a list of hand-selected learning resources that we regularly recommend to both beginners and experts.
I don't have any personal list of good resources, I'm mostly learning by doing and look up docs or random tutorials as I need them
same but now my use case if diffrent
but knowing what to search for can also be difficult in the beginning
I think looking at relevant topics in the official tutorial can be helpful to know what exists in python https://docs.python.org/3/tutorial/
e.g. the parts about the basic built-in data structures
there are also other relevant standard modules, like collections and heapq
and itertools and functools
tbh it's also hard to give specific recommendations since I would give very different advice to newbie programmers VS programmers new to python VS programmers new to python that has a good grasp of algos and data structures
or python programmers that are not used to reading and solving algorithm problems
i just feel so lost
i understand the theory of data structures
just struggle to program them
list' object cannot be interpreted as an integer
This way it is hard to tell what could be the problem
range(A) doesn't make sense
Also you are giving A = [1,2,3] and then looping inside the same list , why would the elif condition ever get satisfied?
range(len(A)) is closer to what you wanted, though it will have a bug for a case like [1,2,3]
what you really want is just a while loop like in the above
Can anyone help me with this one?
The question is that "In a given chessboard with NxN dimensions we have to add all the values in black squares and values in the white squares"
I wrote a working code but it's not getting past through the test cases
bsum=0
wsum=0
for i in range(n):
for j in range(n):
if ((i+j)%2==0):
bsum+=arr[i][j]
else:
wsum+=arr[i][j]
print(bsum)
print(wsum)
n=int(input())
arr=[]
for _ in range(n):
arr.append(list(map(int,input().rstrip().split())))
altmatsum(arr,n)```
Any ideas?
i love you
still doesn't work in demo test ide tho
but my editor work perfect
doesn't work as in?
the solution you had would time out because you repeatedly check if something is in the list, which is slow
with a set you can make that lookup fast
it does work on codility, I hope you didn't keep line 7 when running on their site
Is anyone into physics?
Alright π thanks man
what are some best research area in Deep Learning????
you probably want #data-science-and-ml
how do I get better at coming up with ds and algorithms? Is it just a lot of practice? My minds getting so boggled after drawing out a recursive function for a linked list..
yes, practice
and it might help to read about relatively simple algorithms in various domains, like BFS and DFS in graphs to get a feel for the data structures available to you and how to interact with them
is there an easy way to WRITE, not use, write a simple 1d autoregressive algorithm for use with a moving average algorithm to create an ARMA model
i have a bunch of highly accelerated numba functions
@numba.jit(numba.float64[:](numba.float64[:]), nopython=True, parallel=True, nogil=True,cache=True)
def regressive_average(data):
y = numpy.zeros_like(data)
data_pad = numpy.zeros(data.size + 5)
firstval = 2* data[0] - data[4:0:-1]
data_pad[0:4] = firstval[:]
data_pad[5:data.size] = data[0:data.size]
x = numpy.zeros((data.size, 6)) # create array for outputs
for i in numba.prange(data.size+5):
x[i , 0] = data_pad[max(0,i -5)] * 0.2
x[i , 1] = data_pad[max(0,i -4)] * 0.2
x[i , 2] = data_pad[max(0,i -3)] * 0.2
x[i , 3] = data_pad[max(0,i -2)] * 0.2
x[i , 4] = data_pad[max(0,i -1)] * 0.2
x[i , 5] = data_pad[i]
for i in numba.prange(data.size):
y[i+1] = numpy.sum(x[i,:])/2
return y
Have a real problem that can't be solved without new DSs and algorithms. Then check if anyone else has had the same or similar problem. (Also depending on what you are trying to make there will be a point at which you are forced to use some DS or algorithm you do not know yet, connecting DSs and algorithms to concrete problems really helps the idea stick in your mind and apply to other problems as you generalize from that concrete problem (specific -> general, other way around is hard without context))
Hi, can someone help me... I'm having trouble installing PySimpleGUI
thanks
Hi.
Please help me.
Limits:
1 <= n <= 10^5
1 <= a_i <= 10^9
Thanks in advance, and please ping me when you help
Mad because no one could answer
It's almost as if it's night for a lot of people. I guess after 3+ hours it's not worth it asking for a link to verify it's a public problem and not in some active hiring thing/contest.
The way of actually computing that is actually very straightforward, but coming up with the solution is not.
To begin with WLOG we can rearrange the array in descending order. This invariant will be maintained during operations.
Now we can make operations on prefixes on the array, we should note that operating on different prefix lengths are completely independent, so WLOG assume we do the shorter prefixes first.
When looking at a prefix we want to check how many times we can reduce everything in the prefix by 1. We can do this until the last element in the prefix is equal to the first element after the suffix. I.e.
[... last] [first ...]
```can be reduced `last - first` times. And including doing nothing it yields `last - first + 1` different arrays for that reduction.
These are actually all the puzzle pieces we need. We sort in decending order. For convenience we append a 1, which doesn't change the answer. Compute the difference between all adjacent elements plus 1. Multiply them all together (because the reductions for different prefix lengths are independent) mod `10**9 + 7`.
pythonesque pseudo-code
A = sort_descending(A) + [1]
D = adjacent_differences(A)
result = modded_product(d+1 for d in D)
```very straightforward, time complexity is dominated by the sorting
Looking in your respond...
You said that
We sort in ascending order
Then in the pythonesque pseudo-codeA = sort_descending(A) + [1]
And in my understanding, if A = [1,2] then the answer should be 2, right?
A = sort_descending(A) + [1] = [2,1,1]
result = ((2-1+1) * (1-1+1)) % (10**9+7) = 2 * 1 = 2
@haughty mountain ?
typo, it should be descending everywhere
then is this correct?
[1, 2] should have answer 2, yes.
the arrays are [1, 2] and [1, 1]
π€ why [0,1] doesn't count.
And how about if I say it counts?
the problem is pretty badly specified, but I'm assuming that numbers need to stay positive
if you allow the numbers to become arbitrarily small there are infinte solutions
@merry scroll
Can you explain for me if array items can get to 0, but can't be negative?
In that case the answer should be 4 ([0,0], [0,1], [1,1], [1,2])
Let me guess... Instead of adding 1 to A we will add 0 right?
that should work, yeah
yeah
whats your test
you need help with bubble sort?
i'm sorry idk what test you are talking about
!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.
I guess we can't help you
help people learn how to do the assignment without doing it for them. are you blind ?
thats a code challenge
it say to help me
do not help with ongoing exams
its not ongoing
anyway
i failed the second i enroll
my ongoing exam is life
i dont know what your problem is mate
You can just for all integers in range 1 - 1000000
But that is not "efficient".
yes i am doing bigO best practice
but will bubble sort help me ?
cuz i dont understand what they really asking me
you are problem
no
what algo help me with this ?
If you really want to do sort thing, then sort the list.
Then for each element a[i] in the sorted list, you need to check if a[i] > 0 and a[i] - a[i-1] > 1
If yes then the answer is a[i-1] + 1
I guess this is comprehensible
go be cringe at #python-discussion
Sorry for bothering but I have another question...
https://cdn.discordapp.com/attachments/896668187863679026/934025633506414612/865551884861702165.png
This is an example of a valid pyramid
B
B B
W R W
B R R B
R W B W R
B W W R B W
would someone be able to help with this loud and rich problem? ive almost solved it, but theres a couple issues with my code and im not sure how to fix it
class Solution:
def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
adjList = defaultdict(list)
ans = [-1] * len(quiet)
for i,j in richer:
adjList[j].append(i)
for i in range(len(quiet)):
ans[i] = self.dfs(i, adjList, quiet)
return ans
def dfs(self, i, graph, quiet):
if i in graph:
j = i
neighbors = graph[i]
for next in neighbors:
if min(quiet[i], quiet[self.dfs(next, graph, quiet)]) == quiet[i] and quiet[i] < quiet[j]:
j = i
else:
j = next
return j
else:
return i
my approach is to just iterate through each node, search each node's path to completion and return the node that has the smallest value in quiet
i noticed that one problem with my code was that if it finds the correct node, it would just be overwritten when the next dfs search is performed
so i tried fixing that by only updating j if quiet[i] is smaller than quiet[j] and setting j = i
but it didnt work
this is the same problem you asked about earlier, and the answer is still "use a set"
my head aches
expected output: [5,5,2,5,4,5,6,7]
my output: [1,1,2,3,4,5,6,7]
the last 4 values are correct because those nodes either have no neighbors or just one
sorry lol
im just getting into graph theory
so my head hurts too
its great for practicing dsa
dsa?
you gotta know this stuff to pass the technical interview for jobs
im not familiar with it
oh damn
have you learned a programming language?
I began learning Python about a month ago
then codecademy is great
there's a free python course
you can learn functions, classes, strings, lists, etc
ohh that's great
the hardest thing I did without watching a tutorial and stuff was making a guess game where you have to choose between 3 doors and one of them is a trap and makes you loose a life
then it gets harder, you can choose between 4 and 2 of them are traps
Can I show you the code really quick? I think i'd need an optimization
also thanks for the tip
huh
i forgot the name
By the way this is not for discussing about traps and doors game
Can sb help?
yeah its similar to the monty hall problem
I think the intended solution is to do a topological sort to then add nodes in order of decreasing wealth, keeping track of the minimum quietness as you add nodes
yes thats what im trying to do, im just failing at it
oh
but i could
put the min value in ans
then compare that value to the next search
and just keep updating ans[i] accordingly
wait, why is the constaint on n tiny?
because the runtime i think is quite large
im checking every node
and every node's neighbors
I think this task can be solved in O(#edges + #nodes)
I guess it's intended to be able to brute force it
from random import randint
score = 0
doors = None
answer = None
lives = 3
while lives != 0:
doors = randint(1, 3)
answer = int(input("You find yourself stuck in a dungeon. You have three doors in front of you. Which one will you take?: "))
if answer > 3 or answer < 1:
print("Warning, you must pick a door between 1 and 3")
elif score == 5:
break
elif answer != doors:
score = score + 1
print(f"You passed! You have {score} points!")
elif answer == doors:
lives -= 1
print(f"Only {lives} lives left!")
if score >= 5:
while lives != 0:
doors = randint(3, 4)
another_door = randint(1, 2)
answer = int(input("There are now 4 doors!! But two of them are traps! Beware!: "))
if answer > 4 or answer < 1:
print("Warning, you must choose a door between 1 and 4")
elif answer != doors and answer != another_door:
score = score + 1
print(f"You passed! You have {score} points!")
elif answer == doors or answer == another_door:
lives -= 1
print(f"Only {lives} lives left!")
else:
print(f"You lose! Your score was {score} !")
else:
print(f"You lose! Your score was {score} !")
sorry for sending it now, I didn't want to disturb your discussion but I couldn't find the right moment to send it
ohh nice
If I had to guess there is some clear pattern after a few rows that you are meant to notice and make use of. Try simulating some random cases and see if any patterns show up
Um I think the pattern is these following the exact rules
But there is no proof and it is not true
B
_ _
_ _ _
B _ _ B
_ _ _ _ _
_ _ _ _ _ _
_
_ _
_ R _
_ _ _ _
_ _ _ _ _
_ W _ _ B _
@haughty mountain
is this intermediate level of Python?
I thought I recognized the puzzle https://www.youtube.com/watch?v=9JN5f7_3YmQ
NEW (Christmas 2019). Two ways to support Mathologer
Mathologer Patreon: https://www.patreon.com/mathologer
Mathologer PayPal: paypal.me/mathologer
(see the Patreon page for details)
Today's video is about a recent chance discovery (2002) that provides a new beautiful visual key to some hidden self-similar patterns in Pascal's triangle and so...
data structures is advanced
and its not exclusive to python
it can be done in any language
Wait.
So my guessing is true?
it just deals with how you organize, find, and compute data
to briefly summarize it
here is what google shows when you search it:
A data structure is a named location that can be used to store and organize data. And, an algorithm is a collection of steps to solve a particular problem. Learning data structures and algorithms allow us to write efficient and optimized computer programs.
a list is an example of a data structure
you organize data in such a way where you can call a particular data point from memory in O(1) time
something like it, yeah
and you can search for a particular data point in O(n) time
where n is the number of data points in the list
there are also other types of data structures
such as hash maps and trees
ive gotten closer to solving this loud and rich problem
data structures can range from super simple (e.g. arrays and lists, dicts) to intermediate (e.g. tries and other simple tree structures) to advanced (e.g. suffix trees)
just the first 2 indeces are wrong now
oh the constraint on n goes to 500, but richer.length can range from 0 to n^2
hmm, thinking closer after toposort the problem actually becomes pretty trivial
its not hard conecptually
i can solve it conceptually
just start at each node
do a depth first search check every neighbor of every neighbor until i hit a dead end
and return the node that has the smallest value for quiet[node]
to do this i made an adjacency list
so for i, j in richer
j is the key
and i is stored at that key
i is richer than j so each node in the adjacency list points to nodes that are richer
if a node is not in the list
then there are no nodes that are definitively richer than that node
you could just do the dfs and have it return the minimum value, right?
so what im doing is checking each neighbor that can be reached from the starting node
and i check if quiet[i] is less than quiet[self.dfs(next)] where next is a neighbor to i
also, your dfs can end up doing O(#edgesΒ²) work since you don't make sure you visit a node only once, but that's separate from the correctness issue
yeah, i thought about that
but my first goal is correctness
then ill worry about optimization
class Solution:
def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
adjList = defaultdict(list)
ans = [-1] * len(quiet)
for i,j in richer:
adjList[j].append(i)
for i in range(len(quiet)):
ans[i] = self.dfs(i, adjList, quiet)
return ans
def dfs(self, i, graph, quiet):
if i in graph:
neighbors = graph[i]
for next in neighbors:
if min(quiet[i], quiet[self.dfs(next, graph, quiet)]) == quiet[i]:
if quiet[i] < quiet[next]:
j = i
else:
j = next
return j
else:
return i
richer = [[1,0],[2,1],[3,1],[3,7],[4,3],[5,3],[6,3]], quiet = [3,2,5,4,6,1,7,0]
my code returns [1,1,2,3,4,5,6,7]
while the expected output is [5,5,2,5,4,5,6,7]
so my code is getting stuck on quiet[1]
it should check quiet[1] against quiet[2] which hits a dead end
so it should return 2
and compare quiet[1] and quiet[2]
then it should check quiet[1] and quiet[3]
3 points to 4, 5, and 6
quiet[3] < quiet[4] and quiet[6]
but > quiet[5]
ok so i see the issue
it correctly sets j = 5 when it checks quiet[5]
would this work?
def dfs(self, i, graph, quiet):
minimum = quiet[i]
if i in graph:
neigh_min = min(self.dfs(neigh, graph, quiet) for neigh in graph[i])
minimum = min(minimum, neigh_min)
return minimum
but then it checks quiet[6]
quiet[3] < quiet[6]
so j is set to 6
sets it to 3 i mean
then thats compared to 1
and since quiet[1] < quiet[3] j becomes 1
wow, that means I'm far from that atm
that might
@cyan berry
i was thinking along the same lines but couldnt figure out how to do that lol
not really
it's just returning the minimum of the node and the minimum of the children
i started dsa after learning python
fiddling with the indices when you don't need to just adds fun ways in which the code can go wrong
@cyan berrywhat i'd do tbh is learn python, then learn dsa, which contains a lot of stuff, then pick a specialized field
only issue with that is i need to return the index since the index represents the ith person
my output is a list of people(nodes) where each value in ans[x] is the loudest person who is definitely richer than person x
but i like your idea of find all neighbors first
then comparing their values
so what i can do
is return quiet[i], i
for each search
ah, it does ask for the index, I see
compare all the quiet[i]s
this then?
def dfs(self, i, graph, quiet):
minimum = i
if i in graph:
neigh_min = min(self.dfs(neigh, graph, quiet) for neigh in graph[i], key=lambda x: quiet[x])
minimum = min(minimum, neigh_min, key=lambda x: quiet[x])
return minimum
actually...does min support key functions?
idk
ohh alright
maybe I'm too young to understand everything yet
dont worry i dont understand everything either
o
i have been trying to solve this problem for two days with no luck :(. i found solutions online but still cant comprehend the logic behind the solutions. like how can i check every possible slice within the time limit
A non-empty array A consisting of N integers is given. A pair of integers (P, Q), such that 0 β€ P < Q < N, is called a slice of array A (notice that the slice contains at least two elements). The average of a slice (P, Q) is the sum of A[P] + A[P + 1] + ... + A[Q] divided by the length of the slice. To be precise, the average equals (A[P] + A[P + 1] + ... + A[Q]) / (Q β P + 1).
For example, array A such that:
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
contains the following example slices:
slice (1, 2), whose average is (2 + 2) / 2 = 2;
slice (3, 4), whose average is (5 + 1) / 2 = 3;
slice (1, 4), whose average is (2 + 2 + 5 + 1) / 4 = 2.5.
The goal is to find the starting position of a slice whose average is minimal.
Write a function:
def solution(A)
that, given a non-empty array A consisting of N integers, returns the starting position of the slice with the minimal average. If there is more than one slice with a minimal average, you should return the smallest starting position of such a slice.
For example, given array A such that:
A[0] = 4
A[1] = 2
A[2] = 2
A[3] = 5
A[4] = 1
A[5] = 5
A[6] = 8
the function should return 1, as explained above.
Write an efficient algorithm for the following assumptions:
N is an integer within the range [2..100,000];
each element of array A is an integer within the range [β10,000..10,000].
i would appreciate any explanation
I know this is nothing about python, but my friend kicked me from his server, but when I try to rejoin it says I'm banned. I'm not on the banlist neither are any of my old accounts.
does anyone have a fix for this? Been trying for 1 hour+ and Tried clearing cache, vpn and a lot more.
not the right server, very much not the right channel
you don't check all slices, you use some clever insights about the problem
in this case, say you have a slice [a, b, c, d]
how will the average of it relate to e.g. the average of slices [a, b] and [c, d]?
they can be equal
the average of slices [a, b] and [c, d] can be equal or not equal
if it is equal that means the average of those slices are duplicate
how does avg([a,b,c,d]) and min(avg([a,b]), avg([c,d])) relate?
spoiler ||min(avg([a,b]), avg([c,d])) <= avg([a,b,c,d])||
what consequences does this kind of thing have?
makes sense
yk a server where I can get some usefull help with this information?
so this does something trippy
/run
def dfs(i, graph, quiet):
loud, y = quiet[i], i
if i in graph:
loudest_neighbor = [dfs(neighbor, graph, quiet) for neighbor in graph[i]]
#print(loudest_neighbor)
for loudest in loudest_neighbor + [quiet[i], i]:
print(loudest)
return [loud, y]
dfs(0, {0: [1], 1: [2,3], 7: [3], 3: [4,5,6]}, [3,2,5,4,6,1,7,0])
π€·ββοΈ
oh is there not a run command in this server?
it means like i can go by avg of slices with the length of 2 or 3 each time bcz this way i can get min avg right?
[6, 4]
[1, 5]
[7, 6]
4
3
[5, 2]
[4, 3]
2
1
[2, 1]
3
0
[3, 0]
this is the output i get
!e
def dfs(i, graph, quiet):
loud, y = quiet[i], i
if i in graph:
loudest_neighbor = [dfs(neighbor, graph, quiet) for neighbor in graph[i]]
#print(loudest_neighbor)
for loudest in loudest_neighbor + [quiet[i], i]:
print(loudest)
return [loud, y]
dfs(0, {0: [1], 1: [2,3], 7: [3], 3: [4,5,6]}, [3,2,5,4,6,1,7,0])β
@haughty mountain :white_check_mark: Your eval job has completed with return code 0.
001 | [6, 4]
002 | [1, 5]
003 | [7, 6]
004 | 4
005 | 3
006 | [5, 2]
007 | [4, 3]
008 | 2
009 | 1
010 | [2, 1]
011 | 3
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/awakesuhor.txt?noredirect
so for some reason
some "neighbors" dont return a list and instead return two integers
hmm
so here i should probably fix it so it doesnt visit already visited nodes
because its all there, just the nodes that are repeated mess it up
It would be tempting to even say 2 is enough, but we can't use the same argument to break apart [a,b,c] into [a,b] and [b,c]. So we need to look at slices of both length 2 and length 3, but that covers everything
other than me being dumb and using min instead of max, does this work? @wispy wren nvm, min is right
you want + [[quiet[i], i]]
Iβm facing small problem while writing the json items in excel multiple json are there so it is creating different excel done in panda excel writer
I need to write in all json on same excel and need to use openpyxl if anything releted to this article please share
where can I find such problems on algos and data structures?
leetcode, hackerrank
ty
i keep running into bug after bug
so i finally found something that works as long as i check each node one at a time
but if i iterate through each node
rip
ok nvm
i figured out a way around it
Iβll look into it thanks
I havea doubt the particular function which I implemented is written in panda and creating multiple excel can i pass that function as parameter
@wispy wren fwiw the code I posted earlier does work
def dfs(self, i, graph, quiet):
minimum = i
if i in graph:
neigh_min = min((self.dfs(neigh, graph, quiet) for neigh in graph[i]), key=lambda x: quiet[x])
minimum = min(minimum, neigh_min, key=lambda x: quiet[x])
return minimum
im not saying it doesn't, but i want to get it to work with my own code
plus i dont fully understand lambda functions
maybe you can figure out why im getting a None type error though
if you understand functions you understand lambda functions
def dfs(i, graph, quiet, visited):
if visited[i]:
return
visited[i] = True
loud, y = quiet[i], i
print(loud, y)
if i in graph:
loudest_neighbor = [dfs(neighbor, graph, quiet, visited) for neighbor in graph[i]]
#print(loudest_neighbor)
for loudest in loudest_neighbor:
print(loudest)
if loudest[0] < loud:
loud, y = loudest[0], loudest[1]
return [loud, y]
#for i in range(8):
#visited = [False] * 8
dfs(0, {1: [0], 2: [0,1]}, [0,1,2], visited)[1]
3rd line
hmm
you can return [10**9, None] or similar
messed up the order at first
just some result that is basically infinity
how in tf
that doesnt happen for every test case though
so im trying to understand why
if i = 0
yeah, it only happens in some graphs
it should skip the loudest_neighbor part entirely
and return [0, 0]
if i = 1
loudest_neighbor should be [[0, 0], [1, 1]]
you know the kind of cases that mess things up, right?
this kind of graph causes you to do the same work multiple times
o-->o-->o-->o
| ^
-------
you return None in the beginning of your function
return some "infinite" value like [10**9, None] and it should work fine
visited should be set to [False] * len(quiet) each iteration
well i cant see the problem
im gonna take a break and try to figure this out later
thank you for your help
this is the closest ive gotten to solving this problem
did you try what I proposed?
or do you want to know why what I proposed should work?
i dont even understand why your proposal works
its ok
i need a break
ill try to figure it out later
you have a loop that picks the minimum of all options, adding an infinite value there won't matter, it will be immediately discarded
a possibly cleaner solution would be to move the dfs call into your loop, and do the visited handling there
that way you don't need the inf value
math π
lol
it worked
i still dont really understand why
its super inefficient but it was accepted
faster than 5% of python submissions
class Solution:
def loudAndRich(self, richer: List[List[int]], quiet: List[int]) -> List[int]:
adjList = defaultdict(list)
ans = [-1] * len(quiet)
for i,j in richer:
adjList[j].append(i)
for i in range(len(quiet)):
visited = [False] * len(quiet)
ans[i] = self.dfs(i, adjList, quiet, visited)[1]
return ans
def dfs(self, i, graph, quiet, visited):
if visited[i]:
return [math.inf, None]
visited[i] = True
loud, y = quiet[i], i
if i in graph:
loudest_neighbor = [self.dfs(neighbor, graph, quiet, visited) for neighbor in graph[i]]
for loudest in loudest_neighbor:
if loudest[0] < loud:
loud, y = loudest[0], loudest[1]
return [loud, y]
the final product
oh i see why
so its hitting that visited[i] check after its already in the for loop
and then nothing is returned
so this fixes it by returning a list
@haughty mountainthanks
this problem was driving me insane
np
Please help?
He found the pattern here but my code is still to slow for the constrains
what are you actually doing in your solution to make use of the pattern?
So please look at my code.
I sent it to u
the pattern can be applied recursively
How can I do that?
Like creating a function?
I mean, there is a pattern for the 4 large triangles
that collapses everything but the corners
what if we repeat that?
Yeah, I collapsed it.
And repeated it
the pattern is true for (if I think correctly) lengths 4, 10, 28, 82, ...
Yeah, I know
After watching your video
how to do in order traversal in binary tree
so say you had n = 100, then you could make use of the 82 pattern to compute row...19 I think?
and then use the 10 to compute starting from row 19
and work your way down
runtime should end up as O(n) in total
for the example you posted earlier you can jump from row 6 to row 3
-
- -
W R W
- - - -
- - - - -
B W W R B W
hmm...
Let me try
from statistics import mean
def solution(A):
all_avg = 10**10
p = 0
for i in range(3, len(A)+1):
avg_3 = mean(A[i-3:i])
avg_2 = mean(A[i-2:i])
c = avg_3 if avg_3 < avg_2 else avg_2
if c < all_avg:
all_avg = c
c_p = i-2 if avg_3 < avg_2 else i-1
p = c_p-1
return p
solution is working for N = ~ 700. but failing for N = ~100,000. time complexity is O(N**2)
it's not O(nΒ²)
OMG thank you so much for helping me twice today @haughty mountain
Thank you so much
I guess the code should boil down to something like this
inp = 'B W W R B W'
A = ['BWR'.index(x) for x in inp.split()]
sizes = [2]
while sizes[-1] < len(A):
sizes.append((sizes[-1]-1)*3 + 1)
def cvt(a, b):
if a == b:
return a
return 3 - a - b
while sizes:
jump = sizes.pop() - 1
while len(A) > jump:
A = [cvt(A[i], A[i+jump]) for i in range(len(A)-jump)]
print('BWR'[A[0]])
Your code looks good
yeah. im not sure why it is showing O(N**2)
i'm using only one for loop which is O(N)
btw, you have a bug that you will miss if the first two elements forms the minimum
You are so smart
These problems seems to be easy for you.
You can do a fast solution in just some minutes, while I need 1 day (or more if you didn't help) to solve such problem
I've solved a lot of algorithmic problems over the years, you pick up on patterns and techniques over time
I've solved a problem similar to this a bunch of years back, though that one was about Pascal's triangle https://projecteuler.net/problem=148
A website dedicated to the fascinating world of mathematics and programming
similar speedup technique, pretty different problem
yeah right. btw it is a codility problem from Lesson 5 Prefix Sums. so i have to figure out how to implement prefix sum to this problem
lmao, apparently the mean from statistics is stupid slow
replace it with manual code, i.e. add and divide by 2 and 3 respectively
it's like 30x slower
wtf
it's optimized for accuracy and not speed
got it
def solution(A):
all_avg = 10**10
p = 0
first_2_avg = sum(A[:2])/2
for i in range(3, len(A)+1):
avg_3 = sum(A[i-3:i])/3
avg_2 = sum(A[i-2:i])/2
c = avg_3 if avg_3 < avg_2 else avg_2
if c < all_avg:
all_avg = c
c_p = i-2 if avg_3 < avg_2 else i-1
p = c_p-1
return 0 if all_avg >= first_2_avg else p
got 100%. thank you very much @haughty mountain. i really appreciate your help
np
Hey @rare dawn!
It looks like you tried to attach a Python file - please use a code-pasting service such as https://paste.pythondiscord.com
Hello, I have read in a csv file via pandas which has 14 columns. I need to arrange the values of the columns under each other. I.e. append values from column 2 under 1 and so on. Can someone please help me with this?
I was Wondering if anyone knew the python equivalent of 'case' from C++
There's match-case added in 3.10, but it's quite different (and more powerful)
If you want exactly switch-case from C, you can just have a chain of ifs
Or a dictionary, depending on why you need it
Hello here please I have a question to ask, I don't know if I can proceed
im noob at python who can help
I'm having a run-time error on some codes and I need support please. An error like this one
TypeError: '<' not supported between instances of 'tuple' and 'int'
What is the fastest way to change the value of an item in a sorted list
is lst[inx] = newvalue; sorted(lst)
the fastest way?
if the max of a list is ten does it even matter performance wise?
@dark aurora If there are 10 items max, it probably won't matter a great deal how you do it.
If there were a lot of items, it might be better to del/pop the item, then do a binary search to find the index at which to insert the new item.
That would be something like this: ```py
del mylist[idx]
mylist.insert(bisect(mylist, newval), newval)
Where bisect is imported from the bisect module.
A click counter is a small hand-held device that contains a push button and a count display. To increment the counter, the button is pushed and the new count shows in the display. Clicker counters also contain a button that can be pressed to reset the counter to zero. Design and implement the Counter ADT that functions as a hand-held clicker. in c++ anyone ??
wrong server, wrong language, wrong channel
Help
I don't really understand this
If I'm right about what the solution is the hard part is just making some observations about the problem
So, say we ignore the k operations you can do, do you get the basic setup?
You're given A and B (which presumably have non-negative elements?)
and you are (effectively) allowed to reorder the elements of A however you want to minimize f(P)
@merry scroll how would we minimize f(P), if we couldn't do any of the k operations?
Maybe sort A in ascending order and B in descending?
good guess, is there some simple argument to prove that is the best we can do?
I think when doing so we will always have one big and one small
So the product is the most balance?
And f(P) will be minimized?
say a<=b and c<=d, it's easy to show that
max(a*c, b*d) = b*d >= max(a*d, b*c)
so swapping never makes the maximum go up, but it might make it go down
this is a very typical argument for greedy problems like this, an exchange argument
so what's the consequence, what if we swap until we can't swap anymore?
@merry scroll
The maximum value can't be lowered down any more?
well, yes, but what about the sequences A and B?
They will be sorted?
Yes...
And how about the k operations?
I mean, we know the optimal configuration is. We don't have to worry that an operation will somehow make some completely different permutation be better. We can just focus on the permutation where things are sorted
Any ideas about what operation we want to do to bring the maximum down for that configuration?
Oh yeah, the operation is just that you're allowed to decrement an element in A by 1 (but you can't decrement it below 0)
@merry scroll
not the maximum element in A
And I can decrease an element in A down to 0.
With enough operations, of course
what is it that defines the maximum? i.e. what is f maximizing?
Maximizing?
When there is a pair of A_i and B_i (i is same for both) which A_i and B_i are maximum in the array they are in?
i is the same for both if we consider A and B to be our re-ordered arrays, sure
yeah...
f is maximizing the product of corresponding elements in A and B
how can we make that maximum go down with our operation?
Sort?
with our operation, i.e. decrementing some element in A
Decrease elements in A evenly?
to ask a dumb question:
what is it that makes the maximum value what it is?
it's just ||the a*b pair(s) that have that value||
those are the pesky ones that keeps our maximum high...if only we could make them smaller somehow
yes.
Then we will use the operations to reduce it?
my mental image is going around with a hammer and just bonking the largest thing around to make it smaller
and is there ever a reason to not bonk the thing with the largest product first?
oh okay
Okay I had a solution
But it is too slow...
How can I optimize the speed?
are you repeatedly scanning the list for the largest product?
if so you want to avoid that
you want some kind of a priority queue
!d heapq see this
Source code: Lib/heapq.py
This module provides an implementation of the heap queue algorithm, also known as the priority queue algorithm.
Heaps are binary trees for which every parent node has a value less than or equal to any of its children. This implementation uses arrays for which heap[k] <= heap[2*k+1] and heap[k] <= heap[2*k+2] for all k, counting elements from zero. For the sake of comparison, non-existing elements are considered to be infinite. The interesting property of a heap is that its smallest element is always the root, heap[0].
Sadly, I can't use heapq
why?
I read that in US you can never be more than 115 miles from a McDonald, so I was wondering how we can compute this? Like given a set of 2D points representing the stores + the border of the map, how can we compute the maximum distance between a point in the map to one of the stores?
- calculate min distance to mc for every point in a grid (for example, with step = 1km)
- choose several points that have maximum distance ()
- try to optimize every point:
3.1) move point a bit in some direction and look at how distance changes
3.2) if distance increases - it is good, move this point again in same direction
3.3) if distance decreases - it is bad, try move point in different direction
3.4) if distance always decreases (for every direction) - you've found a local maximum - it is a solution - you have several local maximums - choose biggest of them
Gradient descent (also often called steepest descent) is a first-order iterative optimization algorithm for finding a local minimum of a differentiable function. The idea is to take repeated steps in the opposite direction of the gradient (or approximate gradient) of the function at the current point, because this is the direction of steepest de...
@wispy hare
the problem is given a set of points, what's the minimum radius
one simple but dumb way is to binary search for the smallest radius such that the circles covers the shape
how to check that circles cover all shape?
that's the hard part, but it's easier than the original problem
I guess the original problem can be solved by looking at all the "corners" of a voronoi diagram, but even that's annoying
Voronoi is the way ig
thats interesting
if you have a voronoi diagram, you can just iterate through all "corners" and maximize distance to the nearest vertex
but building that diagrams is complicated task, i think
Binary search sounds easy at first sight but after thinking about it it is quite hard
why?
it's guaranteed not harder than the original question
Theres just no way to check if the circles cover the surface
Besides voronoi diagram already has a known algorithm to construct it
the solution to the original problem gives you the answer for the covering question
for all radii
it might just be that some version of voronoi diagrams solves both
You are trying to solve the original problem tho lmao
solving the simpler problem means we can solve the original problem
How to solve these
no one can read those
is this a competition
we can't help you with that
Thank you
hey , i need help , i have a project to do with python and HTML to create a website that asking you your password and username
then u can access to your own profile
how should i start?
It might be nice to draw a Voronoi map. There's quite a cool algorithm for this (Fortune's algorithm). I made this Desmos graph to demonstrate it a while back: https://www.desmos.com/calculator/g9d6rp21af
Hi
What did I do wrong here?
https://paste.pythondiscord.com/ewuwipomun.sql
@haughty mountain
I made a small fix to check (we can't allow negatives) and I rewrote the binary search to a form I'm more familiar with. Maybe only the check part was necessary, idk
from math import ceil
n,k = map(int,input().split())
a,b = [list(map(int,input().split())) for _ in range(2)]
a.sort()
b.sort(reverse=True)
def check(x):
lk = 0
for i in range(n):
lk += max(ceil(a[i] - x/b[i]), 0)
return lk <= k
low = -1
high = 10**12
while high - low > 1:
mid = (low + high) // 2
if check(mid):
high = mid
else:
low = mid
print(high)
@austere sparrow this is the problem
k can be up to 10**18, values in A are <= 10**6
and yes, it is
where i can find content to study about data structure and algorithm?
We have some in the pins of this channel
thank you. I'll see it
so I want to build a list using a masterlist and checking if they exists in all of the individual lists I have kind of like [x for x in masterlist if all(list_of_list_here)] here is the data I have -> https://replit.com/@mark-kevinkevi3/CoordinatedTightFirm#main.py
so, basically the intersection of everything?
set(masterlist).intersection(*individual_lists)
I mean it has to exist on ALL the list of list and if it is called intersection then yeah
unless you care about order and duplicates in masterlist, if so
isect = set.intersection(*map(set, individual_lists))
res = [x for x in masterlist if x in isect]
I ignored the fact that masterlist is a nested list, you probably didn't intend that
Hi when using polyfit it's giving me a very bad fit. Like pretttyyyy bad. I'm doing on a scale of 1-1000 (once every 10 it puts a point) and the ouputs are between ~35-50k but with a degree of three it screws up
my code is pretty normal there's nothing special
x = points[:,0]
y = points[:,1]
z = np.polyfit(x, y, 3).round(decimals=2)
f = np.poly1d(z)```
and I made sure x and y values are loaded properly
x
y
why do you round it?
I'm incredibly stupid that's why. Thanks π that fixed my problem.
lol
I just spent all day developing an INI parser and I need some guidance on how to polish it into a nice software product. I learned about toml later, but fortunately, I found the thinnest excuse for justifying reinventing the wheel.
Anyway, long story short, it builds up a nice doctree, and that all seems to work fine according to the cursory "battery" of tests I've subjected it to. But the problem is, there really aren't any good methods for accessing the data in it. I've implemented the bare minimum to just see that the parser is working correctly.
So if you wanted to use an INI file, so you typed one out, fed it to this parser, and this parser handed you an object, how would you like to interact with that object?
Here's the constructor for the doctree node class that forms the basis of the doctree:
class Section():
def __init__(self, name):
if isinstance(name, str):
self.name = name
else:
raise TypeError("'name' must be a string.")
self.parent = None
self.kwvals = {}
self.sections = {}
self.garbage = []
self._name = name
There's a class called Doctree that derives from Section, has "" for a name, and doesn't have a parent. Otherwise, the rest of these Sections all get a name, and they get a parent. kwvals are key/val pairs associated with the section, sections contain other Sections, and garbage is a list of strings that weren't comments but didn't otherwise parse into anything recognizable.
Does anyone have any opinions? The vals in the key/val pairs are all strings. Should I make available a way to coerce them into the types they appear to be? Should I implement a jquery-like path parser for accessing elements? Utilities for dumping out pretty-printed trees?
You sent the solution when I'm offline
And it also timed out.
Anyway... thanks
I am trying to find the derivative of a function using the limit definition (not via numpy/symby's differentiation method). I have a list of coefficiants (in order of degree) and am trying to create a numpy/sympy function using those coefficiants. I have included a picture of what I have tried (very bad, but i am very new to the sympy/numpy format), and I have gotten a 'expected non-empty vector for x' error. I am unsure of where to go to create this functon, and any help would be appreciated
coefficients = f.c[::-1]
x_func = Symbol('x')
y_func = (x_func * 0)
print(type(y_func))
for i in range(16, 0, -1):
temp_x = Symbol('x')
temp_y = temp_x
temp_y += 0.001
temp_y = temp_y**(i-1)
temp_y *= coefficients[i-1]
y_func += temp_y
time out is probably because some bug, idk what. the time complexity of the solution should be just fine
I've just started leetcode, started with a medium problem, I get the desired output in python, yet:
I think you're printing rather than returning
yeah , somewhow the return doesnt give any output.
thanks, it works now.
but for some reason it works in the website but not in python
Leetcode will run its own code that runs your function and expects a return not a print statement
so it's not exactly like it would be in console
It does. Except you need to print it.
oh, return doesnt mean printing
now i get it
thats why print worked in normal python
thanks
Also while making functions we usually return values. Yeah. Because we want to use the values in our programme.
ok
thanks
do we really need to go through the same stuff a third time?
it was discussed in detail after the first time you asked
with code, even
Guys wow
If you asked me for help on anything InfoSec you will look stupid
so stop being mean
i cant code but i cant inject binary into an application that will return it to the server and infect all users using that service
Obfuscation of binary injection type that i found out
most devs arent aware of this i even got award from my company
so shut up with being rude
im trying to learn
if you dont respect that you are a trash human
im not a programmer
im trying to learn
Im a Pentester
I know how to write bots
I dont know how to do math with code
im trying to learn
i can write a ruby script to crawl internet and look for SmexyCorny and all associated ip ,email ,other info
so stop being dick
you think you a smart dev but you and all the code you write can be hacked in 10 seconds @slim crest when i can program at least i wont be a child in security measures.
do you remember what was discussed last time? what did you try, why did that not work
!tempmute @rare dawn 4D We don't talk to people that way in this community. Telling people to shut up and stop being dicks or that they're trash humans is not welcome here. Take a few days to read our Code of Conduct, and the next time you get annoyed, step away from the computer instead of unloading a wall of ad hominem and petty bullshit.
:incoming_envelope: :ok_hand: applied mute to @rare dawn until <t:1643287220:f> (3 days and 23 hours).
I think people in here have been both patient and helpful. thanks for that.
1. Follow the Python Discord Code of Conduct.
!warn 897280611490857001 encouraging people to "just call it quits" is not acceptable in this community.
:incoming_envelope: :ok_hand: applied warning to @slim crest.
maybe you should read the CoC, too.
can we try to keep it a bit friendlier in here?
ask away I guess
don't worry about me, just ask. that's what the channel is for.
using a class for that is kinda weird if you only doing it once
the code is pretty bad
geeksforgeeks has... less than ideal code
inb4 w3geeks.com
oh wait, it's a real website
huh
an edge is a connection between two nodes
this graph doesn't have the ability to have nodes with no edges π
here is my dfs (in rust)for day12 part1, maybe it's helpful https://github.com/algmyr/aoc-2021/blob/master/src/solutions/day12.rs#L80-L96
yes, exactly
the graph is just an adjacency list, exactly what you would expect
Conceptually, yes. In CPython it's a double ended linked list of small (64) arrays
looking for help with graph visualization. I'd like to be able to specify locations for certain nodes. Eg Node A in Top Right, Node B Mid Left, etc. it looks like this with NetworkX and matplotlib
hmm maybe pygraphviz
hi , i need help , i have this string and i need to take from this string only things behind ,name=(names), I know how to get extract nickname from that string , but i need o it multiple times how many times i have ,,name= ,,there
info1 is this ["[Player(index=0, name='Jura', score=0, duration=2818.6748046875), Player(index=0, name='Dajvi', score=0, duration=2632.51708984375), Player(index=0, name='TT LaserJetPro', score=0, duration=2628.998291015625), Player(index=0, name='Lahvon', score=0, duration=2194.8251953125), Player(index=0, name='TT You know who', score=0, duration=345.0632019042969)]"]
its getting info about player from server , but i need only Nicknames
why info1 = str(info1) ???
you lose data
dont convert it to str and use it as list of objects
Yeah, you'll definitely get clearer graphs using Graphviz.
How could i make a script to remember where he pressed a key. Then go back to that place to resume functions ?
Develop Python code to show the application of both pivot()
function and pivot_table() function. how we do this
Probably a silly question but how do I return the string of a match object found via python's regex "re" library?
For example
re.search(r'\d{12}', filepath)
This only returns a re.Match object, but I'm not sure where to look to extract the match='somestring' part
Try re.search(r'\d{12}', filepath)[0], maybe?
Welp that was straightforward lol, thank you
('hi')
Hey,
I've never used classes before in python.
I want to make a tree where:
= each node has a score,
= each node has a list of child nodes,
= the name of each node is some string, and I can just look up any node if I input the matching string
Any ideas on how I can do this?
class Node:
def __init__(self):
self.children = []
self.score = "u"
This is what I have, but I don't know what I'm doing
If each node has a name, it should be a property in the class
Ah! That makes sense, i didn't know __name__ was a thing π
Thanks π
assuming that I use __name__ to accomplish what i want, which i'm not certain I do
Well, I've never used classes before. So I don't know what you mean
Have name
@harsh field If you just want a data structure, you could just have a dictionary:
{
"children": [],
"score": "u",
}
``` and functions that operate on it
I think I could make it work with a dictionary, thanks! π
I'm trying to randomly sample a 10 tuple (a1,...,a10) such that each ai is an integer from 0 to 100 and the ais sum to 100 in python
I cant seem to figure out how to do this
is there a numpy function for this?
cuz it seems like quite a natural problem
If you had not had integers the problem is trivial since you can just rescale. If you care about uniformity and want integers this questions gets quite annoying
If you can write recursive code to count the number of ways to generate N integers summing to S then it wouldn't be so hard to modify that to generate tuples, I think
Like, there are X such tuples, let me generate an integer r in [0, X) and generate the rth one.
With the help of the counting function this can be made quick enough
yeah its a bit weird
problem is since they must sum to 100 thats quite a large number of possible partitions
hm this reminds me of that problem.
https://en.wikipedia.org/wiki/Stars_and_bars_(combinatorics)
In the context of combinatorial mathematics, stars and bars (also called "sticks and stones", "balls and bars", and "dots and dividers") is a graphical aid for deriving certain combinatorial theorems. It was popularized by William Feller in his classic book on probability. It can be used to solve many simple counting problems, such as how many w...
but you care about only one right?
how do I make it so I can pip install my requirements.txt file?
so yeah use random.choices to pick 11 points
sort and find differences
something like that
no idea about distribution it makes
i guess 9 points
!e
from random import choices
def parts(sumto, n):
x = [sumto] + choices(range(sumto+1), k = n-1)
x.sort()
return [y-x for x,y in zip([0, *x], x)]
print(parts(5,5))
@runic tinsel :white_check_mark: Your eval job has completed with return code 0.
[2, 0, 2, 0, 1]
Hi, no idea where to post numerical things but:
Does anyone have an example implementation of a MUSCL scheme to solve 1d advection eq.?
cheers that works great
thanks for the help everyone
so you didn't care that the selection was uniform?
that matters a lot to what solution is ok
oh you're right, it avoids large numbers
but
no, that's natural
you can't tell if it's not uniform
like, at a glance
I'm more annoyed that the uniformity wasn't mentioned at all in the question. If you don't care about uniformity there are tons of ways. And if you ask about libraries that implement it I'll for sure assume you want a proper uniform solution π©
i think they care a lot
but trusted me 100%
you took it as "they don't care"
@prime merlin it's really really broken
given that you even said you didn't know the distribution, I do take it they either don't care (or don't know why they should care) π€·ββοΈ
fair enough
it's awful though
(3,6) β (2, 0, 0, 0, 0, 1) rarely happens but other permutations of it with 0 on the ends happen a lot
from random import sample
def parts(sumto, n):
x = sample(range(1, sumto+n) , n-1)
x.sort()
return [y-x-1 for x,y in zip([0, *x], [*x, sumto+n])]
```working version of that idea
Yeah, this is roughly what you want to do I think.
With the other solution, there's not a one-to-one correspondence, so some outcomes end up more likely than others.
you want ppl to give you code or tell you what to do ?
I got it
But I want people to guide me on how to do it
Not tell me what to do or give me the code
def bfs(self, start, end):
queue = [[start]]
while queue:
path = queue.pop(0)
node = path[-1]
if node == end:
return path
for adj_vert in self.graph.get(node, []):
new_path = list(path)
new_path.append(adj_vert)
queue.append(new_path)```
Can someone explain to me why I need to have:
new_path = list(path)
for finding a path with bfs?
path should always be a list...
why do i need to cast a list, to a list?
>>> x = ['1', '2', '3']
>>> list(x)
['1', '2', '3']
>>> x
['1', '2', '3']
>>> ```
i dont get it lol
its weird tho because if i dont do this, i do get different results
@round glacier list(path) creates a copy of the list
!e
x = [1, 2, 3]
y = x
y.append(4)
print(x, y)
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3, 4] [1, 2, 3, 4]
!e
x = [1, 2, 3]
y = list(x)
y.append(4)
print(x, y)
@austere sparrow :white_check_mark: Your eval job has completed with return code 0.
[1, 2, 3] [1, 2, 3, 4]

?
I've been planning to go to bed for a long time now, but there's a nice article by Ned Batchelder explaining all this: https://nedbatchelder.com/text/names.html
Why to you want to talk with me?
@fiery cosmos If you have a question, you should see #βο½how-to-get-help and claim a help channel. Then just ask your question in the channel.
Or, if your question is about algorithms or data structures, you can ask here.
Can you tell about python arrays in details ....?
Or if you have any tips for me ?
Give me the tips for better learning ?
ah i see
Not sure why or how using list() in the code below would lead to two entirely different outputs
def bfs(self, start, end):
queue = [[start]]
while queue:
path = queue.pop(0)
node = path[-1]
if node == end:
return path
for adj_vert in self.graph.get(node, []):
# creates a copy of the list
new_path = list(path)
new_path.append(adj_vert)
queue.append(new_path)```
like why would not using list() add new values
i feel like it should be the opposite
if ur using it, u get values that u wouldnt
because ur popping the path, copying it, then adding to it
but when u dont copy, you get MORE values?
If you had just this:
def bfs(self, start, end):
queue = [[start]]
while queue:
path = queue.pop(0)
node = path[-1]
if node == end:
return path
for adj_vert in self.graph.get(node, []):
path.append(adj_vert)
queue.append(path)
All the lists in the queue would be the same list, not different lists

whats wrong with that
oh ok
guys in competitive programming competitions, are we usually allowed to use modules?
like itertools, etc
i dont think so
standard modules yes, so itertools and similar are fine
any external dependencies, most often no
My code:
char = [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9'], ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'],
['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z' ]]
def check_password(string):
char_number = 0
char_lower = 0
char_upper = 0
for i in range(len(char)):
for j in char[0]:
char_number = char_number + string.count(j)
for k in char[2]:
char_upper = char_upper + string.count(k)
for l in char[1]:
char_lower = char_lower + string.count(l)
break
if char_number > 0:
if char_lower > 0:
if char_upper > 0:
return 'YES'
else:
return 'NO'
else:
return 'NO'
else:
return 'NO'
if __name__ == '__main__':
t = input()
string = input()
string_2 = input()
print(check_password(string))
print(check_password(string_2))
it produces correct output
but the website says its wrong
problem link so we know it's not some active contest or similar?
@haughty mountain
you're only doing 2 passwords, rather than t passwords
how to get t passwords?
read input and call check_password t times
currently you're doing it exactly 2 times
regardless of t
first line of input is test case ( lets assume a ), read that separately and call the loop a times and read input a times and call check_password a times right?
if __name__ == '__main__':
t = int(input())
for i in range(t):
string = input()
print(check_password(string))
something like this?
yep
compilation is successful lets see the answer
its correct
Thanks a lot @haughty mountain
the code for checking the password is a bit awkward, you can make it a lot simpler
if (any(c.islower() for c in string) and
any(c.isupper() for c in string) and
any(c.isdigit() for c in string)):
return 'YES'
else:
return 'NO'
oh thanks
can anyone suggest me the good source for learning data structures and algorithms?
siuuu
check the pins of channel:D
Hi do you know how to convert a str to utf-8 who is usable in a web browser ?
what do you mean by that?
urllib.parse.quote(string, safe='/', encoding=None, errors=None)```
Replace special characters in *string* using the `%xx` escape. Letters, digits, and the characters `'_.-~'` are never quoted. By default, this function is intended for quoting the path section of a URL. The optional *safe* parameter specifies additional ASCII characters that should not be quoted β its default value is `'/'`.
*string* may be either a [`str`](https://docs.python.org/3/library/stdtypes.html#str "str") or a [`bytes`](https://docs.python.org/3/library/stdtypes.html#bytes "bytes") object.
Changed in version 3.7: Moved from [**RFC 2396**](https://tools.ietf.org/html/rfc2396.html) to [**RFC 3986**](https://tools.ietf.org/html/rfc3986.html) for quoting URL strings. β~β is now included in the set of unreserved characters.
I will check this doc
that's more like it
I got a book but im thinking about returning it but i wanna get comfortable with an algor course before i return it
And i dont wanna go through a project based course
Theres only three resources in pinned
Any suggestions?
Or advice?
Can someone help me with my linkedlist and tell me what I am doing wrong?
Can you sort a list by two attributes but that they are both equally important
so this (0,4) (1,2), (1,3) ,(2,8)
would be this descending (2,8), (1,3), (0,4), (1,2)
instead of this
(2,8),(1,3),(1,2),(0,4)
How should [(1, 4), (2, 3)] be ordered?
And how should [(1, 10), (6, 7)] be ordered?
And what is your end goal with this sorting?
Hello anyone is here willing to help me with the project? I got rejected. Need someone help please inbox me if you are willing to help me
send ur problem
and ur solution too
Can anyone tell whether I should start learning how to analyze Algorithms (Time and Space Complexity) or should I learn Algorithms first? I thought it made more sense to first learn how to analyze these as that would help in understanding the difference but in the Analysis of Algorithms, people are constantly throwing around algorithm names and say that they're this and that (Like QuickSort's worst-case time complexity is O(n^2) but I yet have to see what QuickSort is) and I have trouble keeping up
(Ping if reply, Thanks)
I guess algorithms first but you learn them at the same time in my experience. So it's more like learn an algorithm -> learn why it has the complexities it does -> repeat.
Thanks and I do want to learn both simultaneously but it's hard for me to concentrate if I add more topics in list so I wanted to go with one and then another
learn how the algorithm works and then figure out the complexities of it, obviously they are highly connected
learning one without the other is kinda silly
I guess so, Thanks for responding
lets see
hello I have a problem
i am currently making a program thats DFS to generate a random maze in pygame
but when I run the program(uncommenting maze.GENERATE()) I get a blank screen
I knew my code was wrong from the beginning
I am not looking for solutions but I will appreciate suggestions
My questions is why did the screen go blank
um if you don't run the function, why will it run?
why do you have a stack and also recursion? if I would have to guess you're stuck in an infinite loop because of a bug in your code
i said when i uncomment it
cause its recursive backtracking ,isnt it?
when I see a dfs I expect either a recursive dfs or a iterative dfs using a stack, this is some weird mix of both
ohh so my code is incorrect?
presumably, I have a hard time making sense of it
what is the thing meant to do?
arghh hold on
I'm tired, hot and sun-burnt, holidays are never that relaxing. Anyway, here I introduce one of my favorite algorithms - the Recursive Back-tracker, to generate a maze. I love how perfectly complete this algorithm is, it can be used in all situations where you need to guarantee your network has all paths traversed. It's also my first video with ...
what that program does @haughty mountain
so they are writing their thing with a stack, so iterative, no recursion
it allows to easily do the execution step by step, i.e. their animation
if you want the step by step thing in python you have the option of either doing what he does, computing one step per function call, or making a recursive generator function
the latter is pretty cute, but maybe something you could revisit later
to do one step:
- let cur be the element on the top of the stack
- mark cur as visited
- find ok neighbors of cur
3a. if such neighbors exist, pick one and add it to the stack (continue exploring)
3b. otherwise pop the top element from the stack (this is the backtracking)
I never really write this kind of code with the intent of executing one step at a time, but I guess it's not much different 
normally this kind of logic would be in a while loop that executes until the stack is empty
okay thanks i will do it iteratively
So, I took coursera course about data structures and alghoritms. I got an PDF that's about what to do to check if solution is correct. I don't understand one part about generating tests.
I don't understand what's here "model solution"
Please, someone know opencv library ?
some solution that you know is correct, in practice that's likely a brute force solution
Thanks for response. What you mean by "brute force solution"?
often there is a slow solution that is obviously correct, and you can use that together with a test generator to check another solution for correctness
that's how I've used it in practice before
I suspect the "model solution" in your case might be a solution you're given though
hey guys, I'm trying to understand topsort for disconnected graphs
in the example of 1->2->3 4->5->6
wouldn't it come out to be something like [4,5,6,1,2,3]?
6 isn't necessarily before 1, is it?
all correct results are correct 
@lean walrus can you elaborate lol
A topological sort isn't a total ordering, there's many valid orders. So that would be valid, so would [1, 2, 3, 4, 5, 6], or [1, 4, 2, 5, 6, 3]
@ivory yacht ah, okay. I just thought the defintion was something like
it sorts it into an order where u->v implies that u is "before" v
or equal
That's the definition yeah, but since you don't define the relationship between every pair of elements, multiple solutions are possible that satisfies all the constraints.
Usually you only care about having one of the solutions.
So if you had the constraint 1 -> 3 and 2 -> 3, both [1, 2, 3 and [2, 1, 3] would be valid.
@ivory yacht ah, okay. thanks so much lol that cleared up everything
Can you not simply use input() in the appropriate cell?
I must be missing some context. Maybe I interpreted the question to generally; I thought you were simply asking how to incorporate user input into a project in Jupyter Notebook. Is there some specific project I am not aware of?
!rule 9
I have a question
How can I write a class attribute that has the type of itself?
class Foo:
all_foos: List[Foo]
...
List["Foo"], or a from __future__ import annotations at the top
(we also have a #type-hinting for questions like these)
I am tryin to debug a code in pycharm but its taking forever to do but its showing this any solutions?
huh?
cant see the image
!e print('2022-01-27')
@lean walrus :white_check_mark: Your eval job has completed with return code 0.
2022-01-27
Hee guys π
I'm makinga telegram bot but i'm stuck on the interactive part
if query.data == 'example':
context.bot.answer_callback_query(callback_query_id=query.id, text=f'test example', show_alert=True)
Instead of only pop up an alert box, i want a interactive part
like give me your pet name > bot waits then go to next question what is your age > then prints the info. but it should start with the button
wrong channel for this kind of question
import json
import random
def main():
def working():
workvalue = random.randint(1, 5)
print("You worked in your development job and gained $" + str(workvalue)
with open('data.json') as f:
data = json.load(f)
moneyvalue = data['money']
print('Money: $' + str(moneyvalue))
print('')
print('Actions:')
print('[1] Work')
print('[2] Exit')
print('')
action = input("> ")
if action == "1":
working()
why do i get syntax error
share the error
ah missing ) in print
print("You worked in your development job and gained $" + str(workvalue)
thats where it is
oh ok thank you
import json
print("Username:")
username = input("> ")
print("Password:")
password = input("> ")
if username == "crystalfur" and password == "root":
print("Welcome " + username + "!")
with open("cfc_bank.json") as f:
cfc_value = json.load(f)
print("Account Balance: " + cfc_value(str("crsystalfur")) + "CFC")
why wont the amount print
cfc_value is a dict, you're calling it like a function
also this is not the right channel for this kind of question, this is for algorithms and data structures
oh
can I ask what IDE you are running ?
Guys i need a book which has hard to extreme level of ds algo problems
Any recommendations
@trim obsidian Is 'not solved yet' exteme enough? π
https://en.wikipedia.org/wiki/List_of_unsolved_problems_in_computer_science
Ahhh i ment for practice tbh
ah
Not like impossible ones but hard problems
So i grill my concept
I want depth
And pratcie like a ton of hard problems
well, I'm a noob. so I don't have much advice for you