#algos-and-data-structs
1 messages Β· Page 133 of 1
- O(3^n) from my point of view
how so?
2^n < 3^n for n > 0
Right is not O(log n)?
4 is not 3^n
@slender sandal what is your take?
uh
Check plots
After some n 3^n will be always bigger than 7(2^n)
I think that it's a basic question which is basically a grading system.... It can be done with if else but I want to make it without if else or any other loop or advance topics like classes or anything
Let me know if you need to see the code
if marks < 80:
print(C)
elif marks < 90: # elif means else if
print(B)
elif marks < 100:
print(A)
You could also put another else below the last elif
how would i find number of subarrays all of whose elements except the first and last are less than first and last element?
(without O(n^2) that is)
example:
2 37 4 32
output:
4 because (2, 37) (37, 4) (4, 32) and (37, 4, 32)
there could be a DP approach but i'm not able to find the base case in recursion
ping me if you reply ^^
I am not very sure of this approach but you can try something like :-
Find the 2 maximum distinct numbers in list
Traverse the list and split them about those two numbers
Here in this case you found one slice till now
Then pass those the split lists you got into the same function again... Take the return and add it to the total lists found
Oh fuck I forgot to tell this up there... Don't pass lists with less than 3 elements into the function while recursion
Just add the 2 elemented lists to the count I guess
And then garbage the others I guess
@deft locust would that work?
Oh hmm wait I don't thing it would
I guess I over looked some cases shiet
@deft locust is repetition of elements allowed?
how do i split them about those two numbers? you mean, create 3 lists?
yeah
the 2 element lists are just len - 1 so i could do that
Yeah that's what I thought but it doesn't actually count for all cases
Are you sure this is not the type of questions which has one and only one solution?
Best I could thing of was O(n^2)
I mean I could be missing some solution
same, all the solutions i tried were O(n^2)
But O(n) really seems like an out of the box algo for it
O(n) or O(nlogn) works too
the input list can have 10^6 elements
i need it to complete in 3 secs
O(n^2) would make it equivalent to iterating through 10^12 or smth π
That would definitely not be my first choice ππ
rows = 5
cols = 5
for i in range (rows):
for j in range (cols):
## I want a logic for presenting data like
## 00 01 02 03 04 05 \n
## 10 11 12 13 14 15 \n
## ....
## 50 51 52 53 54 55 \n
is this what you are looking for?
!e
rows = 6
cols = 6
num = 1
for i in range(rows):
num = i*10
for j in range(cols):
print(f'{num:02}',end=' ')
num+=1
print()
@onyx umbra :white_check_mark: Your eval job has completed with return code 0.
001 | 00 01 02 03 04 05
002 | 10 11 12 13 14 15
003 | 20 21 22 23 24 25
004 | 30 31 32 33 34 35
005 | 40 41 42 43 44 45
006 | 50 51 52 53 54 55
@deft locust building a max-heap from the list in O(n) would be a good starting point, so that from a list like [14, 6, 12, 0, 16, 9, 13, 1, 2, 4] you get a heap like
then i think the solution is to sum the number of children of each node
!mute 323179820009652225 π
:incoming_envelope: :ok_hand: applied mute to @willow jackal until <t:1633105633:f> (59 minutes and 59 seconds).
oh
i don't know what max-heap is, but i'll read it up
can think of it like a tree where the value of the parent is always more than that of its subtrees
ah
that seems extremely convenient for this question π
i should do data structs properly before trying CP :(
What's cool is you can build a max heap directly in an array structure, and there are algorithms for pushing and popping nodes that work automatically in log time
this wasnt as straightforward as i thought though
just adding the no. of children of each node seems to be off by a bit
i think the ends of the array have to be handled differently in some cases, idk
hi.
import re
liste = ["1", "2", "5a", "10b", "abc"]
#1
for i in liste:
trueliste = []
if re.search("[0-9]", i):
trueliste.append(i)
print(" ".join(trueliste))```
i wrote this code but returns null
you reset it to an empty list in every loop iteration
move the trueliste = [] line outside the loop
oh thanks.
how can i remove a data from an list?
example adding:
liste = []
liste.append('abcdef')```
like this but not appending, removing
.remove()?
yes liste.remove('abcde')
make a regex that searches for an element that starts with a digit/number and ends with an alphabet/word that's what you want right?
its most likely going to be i.isdecimal() in your case
i did not learned regex
not works
i did tried
then why are you trying to use regex, doesn't make sense
what's the output/error you're getting
is 're' regex?
mhm
move that isdecimal() logic in the first loop
and remove the regex searching you're doing, it should work fine then
is this ok?
yes that's going to give you a list with all the elements that contain a letter or space
if you want a list with only numbers you should remove the not from your logic
i want it but
doesn't this method send us values with letters or spaces?
The isdecimal() method returns True if all characters in a string are decimal characters. If not, it returns False.
you can read about it here
Hello, I don't know how to solve this problem, can you tell me which algorithm would be ideal?
How many drivers will be able to receive a suitable car, assuming that the cars are optimally distributed? Note that each car can only be assigned to a maximum of one driver. Input The first line contains N integers: Li is the minimum speed of driver i . The second line contains N integers: Ri is the maximum speed of driver i The third line contains M integers: the speed of the cars to distribute
hello guys, I need some help with regex in python. Suppose there are several strings like 'QR1.png', 'QR2.png', 'QR14.png' or 'QR100.png' like these are the strings of file names. I want to exactly extract the number like any number containing digits from 0 to 9 just after the word 'QR', like if the file name name is 'QR100.png' then the result will be 100. But if the file name is 'QRabracadabra.png' then it will return nothing. How can I do this in python? Please, help, it is too much appreciated
I would be so happy if someone helps me in this.. this can save me lots of time, thanks
!e ```py
import re
reg_str = re.compile(r"^\d+?(.\d+?)?$")
for i in ["1", "2.2", "2.", "a1"]:
print(reg_str.search(i))
@winged plover :white_check_mark: Your eval job has completed with return code 0.
001 | <re.Match object; span=(0, 1), match='1'>
002 | <re.Match object; span=(0, 3), match='2.2'>
003 | None
004 | None
@sterile rain
extract any number exactly after the word 'QR'
thx
and that will also ends with '.png'
extract any size of numbers from a string that will start with 'QR and end with '.png'
suppose a string 'QR4101kkgf700.png' then result will only be 4101, 700 will not be included
!e ```py
import re
reg_str = re.compile(r"QR(\d*?).png")
test_list = ["QR1.png", "QR99.png", "QRerhui.png", "QR98he.png"]
out = {}
for i in test_list:
try:
out[i] = reg_str.search(i)
except AttributeError:
out[i] = None
print(out_list)
!e ```py
import re
reg_str = re.compile(r"QR(\d*?).png")
test_list = ["QR1.png", "QR99.png", "QRerhui.png", "QR98he.png"]
out = {}
for i in test_list:
try:
out[i] = reg_str.search(i).group(1)
except AttributeError:
out[i] = None
print(out)
@winged plover :white_check_mark: Your eval job has completed with return code 0.
{'QR1.png': '1', 'QR99.png': '99', 'QRerhui.png': None, 'QR98he.png': None}
yeah just to store the outputs and then print them to show lol
basically if a match is found you can just see group(1) of it
else it will return None type
which will gave an error
what group() does
well you might want to see about it
sorry to say I never learnt regex, that's why I'm asking
btw thank you for your help
ah oh ohkay
basically in regex if you surround any stuff by parenthesis in raw string
the regex module treats it as a different group
its made to easily access certain part of the string
the numbers in your case
hi can you tell me why you wrote .group(1), I mean why only 1? not any other?
so by convention group(0) is the entire found string
and then it number groups in ascending order
i.e. first found , lower number given
so in this case we just have one so it is assigned the number 1 for group
if we had 2 groups.. they would be given numbers 1 and 2
okay, got it
am currently doing 463. Island Perimeter
def islandPerimeter(self, grid: List[List[int]]) -> int:
rows = len(grid)
cols = len(grid[0])
result = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1:
result += 4
if r > 0 and grid[r-1][c] == 1:
result -= 2
if c > 0 and grid[r][c-1] == 1:
result -= 2
return result```
am having trouble understanding
```py
if r > 0 and grid[r-1][c] == 1:
result -= 2
if c > 0 and grid[r][c-1] == 1:
result -= 2```
When you have two land cells next to each other (horiz or vertically) the -2 is for their two borders that touch. Like in |0|0|0|A|B|0|0| if 0 is water and A and B are land, the -2 is for the right side of A and the left side of B
But +4 otherwise for each land cell
It's an interesting way of doing it
kinda nifty it works out. Unintuitive but I guess it does about half the neighbor checks you'd normally have to do. (Though I wonder if bfs/dfs once you find land would be faster anyway)
If Arrays can be Abstract, doesnt it mean literally any data type can be made abstract?
why do you say arrays can be abstract
hm.
well
one view of data structures
is that they can be defined in terms of what operations you can perform on them, and the associated semantics
so, in a sense, yes
lol
you could define an interface for any data structure
ADTs always confused me
algebraic or abstract?
Abstract
okay, maybe think about it this way
heaps are not considered as ADTs
an abstract data type is simply a description of a particular structure; what you can do to it, and how it will react
just what the input and output are
you can reify (make concrete) this abstract data type by providing a particular implementation; e.g. Python's list
not how its produced
but there are degrees of reification
ahh
abstract data type (purely abstract model) <----------------------------> Python class (purely concrete)
however
in a language with interfaces
abstract data type (purely abstract model) <--------------- interface (less abstract) -------------> class (purely concrete)
less abstract because
the first one exists only as an idea
the second exists as code that represents that idea, but it's just an interface
it's not something you can actually use
so it is partially abstract and partially concrete
does that make sense
like function prototypes in C?
somewhat, yes
yes...
so we can make any data type as abstract or as concrete as per need
and going back to your question: there are degrees of abstraction
we can think of an Array interface, for sure
but even then...
Array, Set, LinkedList etc. can all be thought of as some sort of Collection
which in turn can be thought of as a kind of Iterable
Hey guys do you mind if I ask a question here about a line of code in my pandas
Sets dont have to be iterable do they?
They are in python but do they have to be
Lists are sequences, it makes sense for a sequence to be iterable
sets are just collections of unique elements
I think they do
sets allow [...] enumerating the values in some arbitrary order
from https://en.wikipedia.org/wiki/Set_(abstract_data_type)
(also, in python, collection => iterable)
hey can anyone help me with learning how to reverse a linked list?
no
but it would be a rare collection indeed that wasn't iterable
I can't think of any way to use the elements of a collection other than random access and iteration
Sets should be iterable, but there is no reason they should be ordered
You might have an object that represents a collection abstractly. E.g. in a computer algebra system, you might have an object that represents the set of solutions to an equation.
But in order to be a collections.abc.Set in Python, an object does have to be iterable.
HI how can i verify if in my list is the same string , and if it is there how can i remove the twin
There are multiple ways you can use two pointer, Dictionary, count(). dictionary would be the best i guess
I found out solution but thnx
Can anyone help me understand how recursion works for this problem? https://leetcode.com/problems/path-sum/description/
This is the code that I saw from a YouTube video ```py
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
elif not root.left and not root.right and targetSum - root.val == 0:
return True
else:
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)```
I understand that the code is subtracting the targetSum from each node's value but when it gets to node 11 for ex, and it goes left and finds that the targetSum - the value isn't 0, doesn't the recursion just terminate? How is it going from 11 -> 2?
Yea I saw a bfs/dfs solution but I found it hard to understand, this solution made much more sense to me but yea, a bfs/dfs algo is a much better solution
hasPathSum on 5 calls itself on 4.
hasPathSum on 4 calls itself on 11
hasPathSum on 11 calls itself on 7
hasPathSum on 7 calls itself on None twice (the left and right children on 7, which are both None), which gives it two Falses, so it returns a False.
hasPathSum on 11 calls itself on 2 instead.
hasPathSum on 2 returns True, because the sum is right. That True is returned to the hasPathSum on 11, which returns True to hasPathSum at 4 as a result, and so on
doesn't the recursion just terminate? How is it going from 11 -> 2?
The 11 node doesself.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val). Since the left side of theor(which calls the function on 7) evaluated to False, the right side (which calls the function on 2) is evaluated.
currently trying to improve my matrix solving skills because its one of my major weaknesses. am doing 1351. Count Negative Numbers in a Sorted Matrix on leetcode
def countNegatives(self, grid: List[List[int]]) -> int:
row_len =len(grid[0])
col_len = len(grid)
row = 0
col = row_len - 1
counter = 0
while row < col_len and col >= 0:
if grid[row][col] < 0:
counter += col_len - row
col -= 1
else:
row += 1
return counter```
Can someone explain it in a simple way?
@idle pier see this video - https://youtu.be/enI_KyGLYPo?t=1372
In this video we cover searching in 2D arrays/matrices and how you can apply binary search to get optimal solutions.
Take part in the learning in public initiative! Share your learnings on LinkedIn and Twitter with #DSAwithKunal & don't forget to tag us!
Complete Java DSA playlist: https://www.youtube.com/playlist?list=PL9gnSGHSqcnr_DxHsP7AW9f...
watch from 22:52, if you got enough time then watch the entire video
Larry solves and analyzes this Leetcode problem as both an interviewer and an interviewee. This is a live recording of a real engineer solving a problem live - no cuts or edits!
Problem: https://leetcode.com/problems/stone-game-ix
Twitch: https://www.twitch.tv/larryny
Discord: https://discord.gg/6QKRCdR
Instagram: https://www.instagram.com/lar...
all leetcode solutions are onlineπ
the hype is strong with leet code
I just wanted a hint anyways I will look at it, thanks for sharing
am I the only one who doesn't like leetcode ?
no, but probably for other reasons
I've never tried Leetcode
for what it is, a problem solving site, it's alright
What is it exactly? Some algorithm contests, basically?
it's just a website with a bunch of programming problems and a solution checker
its main aim is for practicing for interview questions
Seems kind of strange for that purpose
a lot of the questions are questions actually asked by companies during an interview at some point
I think they also let you see questions specific to companies such as google for example
to be clear its for technical interviews specifically
I mean sure, but as interview questions, are they really expecting you to rattle off a memorized solution like that? I would think it would be more valuable to get some insight into someone's thinking process.
100% but you still need to practice somehow right?
a lot of people do end up memorising solutions which might be bad for the companies they apply for since it gives a false evaluation of their skill level but leetcode doesnt care about that it just aims to help people pass interviews in anyway
Eh, I think the interviewer can tell when you've memorized solutions. And they probably have to spend some time coming up with new problems, because they'd rather see your thought process π
it's very easy to tell when someone doesn't actually understand and has just memorized the solution. just change one parameter in the problem and see how they deal with it
^^ pretty much but practice still helps since you end up learning by doing the problems
Sure. I guess in my job I'm actually not very computer science focused. People have to know quantum computation. But it's rare that someone actually knows what a data structure is.
interesting, you'd think that'd be a prerequisite π€
You'd be surprised. Quantum algorithms are very different from classical ones.
And it's a physics route.
wouldnt you still need new data structures for your quantum computation?
It really just doesn't work the same way.
In fact the no-cloning theorem forbids a lot of classical data structures.
how would you store data then?
You can't.
You can never copy a single bit. You have to operate in place on everything.
im really confused now then lol how can you do any meaningful work if you cant store any data
The problem is you can't copy a quantum state. So you can use quantum states to do something, but "storage" is a funny thing to talk about.
hmmm its gona be interesting to learn about this in future when quantum computation actually becomes viable
Curious what "viable" means to you. π There are certainly a lot of challenges to overcome regarding system size, decoherence times, cryogenics, etc.
I guess publicly accessible and more performant then normal computation
since right now I know you can emulate a quantum computer but it ends up being a lot slower at everything since its emulated
a normal person doesn't really care about quantum computers though, they're not useful for things a normal computer can do well
afaik they're only useful for certain problems that normal computers aren't good at
tbh i dont know what quantum computers can do well other then that they will somehow break most encryption algorithms
I just think that if in future I run into a problem that I cant solve traditionally I could give quantum computation a try
One thing they are useful for already is that there are guaranteed true random number generators using quantum computers. These exist now and cost money to use, of course. They're used where someone needs very high security, or very unbiased statistical modelling.
what do you mean by true random?
lava lamps aren't random enough?
I mean unbiased and unpredictable, so that a sequence of random bits truly contains zero information.
the way I see it all random numbers even the ones in real life follow some law however we just dont understand those laws well enough/ arent able to account for all the possible variables at play so nothing is really trully random
that's not true, there are truly random things
like what?
well actually, if you say "what if there's this one thing we don't know about" then not really
With quantum computers you can generate random numbers which are truly random, and guaranteed by mathematical proof.
everything is pseudo random otherwise the unvierse wouldnt work
The universe doesn't work that way
the unvierse operates on laws what we perceive as random is just due to a lack of understanding about those laws
Anyway, the biggest data structures question I usually ask is when should you use a list vs a set? (Since this is Python). Very few people coming from physics seem to know a good answer to that.
ok but that's just a non-argument, you can never prove anything then
maybe my point is just there are things that are more random than others is what I'm trying to get at it just depends on your use case
thats quite surprising I would have assumed anyone looking into the field would have at least been exposed to some CS at some point
are you interviewing theoretical physicists?
yes, people who did a PhD in quantum computation, usually
CS is generally not relevant for that
why do you ask about it in interviews then?
It's relevant for what we do π
ahh fair
but if its to that point why dont you just ignore that aspect and have them learn some CS after they get hired?
I assume anyone intelligent enough to get a PhD in quantum computation wont have a problem learning CS quickly
They do learn CS things after they're hired, and I didn't say I was rejecting people for not knowing the answer to one question π
But we're very small and we have a lot of code to write, so it is important that someone knows as much as possible
^^ understandable, just out of curiosity what exactly do you do?
Well, there isn't a good name for it yet. Some people are calling it a "quantum operating system", but it's not an operating system like you're used to. Sometimes it's called a "compiler", or an "architecture", but in any case, it's an abstraction layer between quantum computing algorithms and real devices.
interesting so your essentially just writing the interface layer to allow people to use quantum computers effectively?
Basically. So people can design quantum algorithms in a hardware-agnostic way, and then the abstraction layer figures out how to make them work on a given device.
school home work ?
I am looking to study and hopefully master alogs in python π . Would you recommend to start with this book: Problem Solving with Algorithms and Data Structures using Python by Brad Miller et. al. https://runestone.academy/runestone/books/published/pythonds/index.html
An interactive version of Problem Solving with Algorithms and Data Structures using Python.
can somebody pls help me with my hw
fixing my hardware now as well. what issue do you have with your hw?
hello, I have a question on how best to show this issue:
I have 3 types of paint gallon: 0.5L, 2.5L and 3.6L
Each liter paints 5 square meters
I need to paint 15 square meters of wall, the best gallon paint recommendation is: 1 gallon of 0.5L and 1 gallon of 2.5L
How can I structure a function that always returns me the best possibility without losing ink?
Seems like knapsack problem to me. You may wonna check it out.(if I'm not mistaken)
Has anyone constructed a self-aware algorithm that can learn on its own using Python?
hey guys
am using the turtle in python. I am trying to make shapes with my arrows and then trying to fill them. But somehow. It only colors in the turtle and not the shape drawn.
Anyone know the solution?
Hey guys, i was wondering why my get all paths function is getting paths that cant literally exist? i would like some help, thanks!
def heap_sort(array):
build_max_heap(array)
for end in reversed(range(1, len(array))):
swap(0, end, array)
sift_down(0, end, array)
return array
def build_max_heap(array):
first_parent_index = (len(array) - 1) // 2
for current in reversed(range(first_parent_index + 1)):
sift_down(current, len(array) - 1, array)
def sift_down(current_index, end_index, heap):
child_one_index = current_index * 2 + 1
while child_one_index <= end_index:
child_two_index = current_index * 2 + 2 \
if current_index * 2 + 2 <= end_index else -1
if child_two_index > -1 \
and heap[child_two_index] > heap[child_one_index]:
index_to_swap = child_two_index
else:
index_to_swap = child_one_index
if heap[index_to_swap] > heap[current_index]:
swap(current_index, index_to_swap, heap)
current_index = index_to_swap
child_one_index = current_index * 2 + 1
else:
return
def print_kth_smallest_largest(numbers, k):
print(f"The kth smallest element is {numbers[k - 1]}")
print(f"The kth largest element is {numbers[-k]}")
def swap(i, j, array):
array[i], array[j] = array[j], array[i]
numbers = []
with open("numbers.txt") as file:
for line in file:
numbers.append(int(line.rstrip()))
k = int(input("Enter k: "))
heap_sort(numbers)
print(numbers)
print_kth_smallest_largest(numbers, k)
Enter k: 4
[56, 45, 45, 34, 90, 56, 76, 89, 33, 334]
The kth smallest element is 34
The kth largest element is 76
Why am I not getting a sorted array when I print it?
33
45
76
56
34
56
90
45
89
334
This is numbers.txt
Can someone help me?
Oh! I got it!
can anyone help me with selenium in dm?
what should be the exact complexity of expression O(nlogn + 3n) , confused on which is less dominating , as even with n = 1million , values of both are significant
Please help fast , if anyone is here
It would be O(nlogn) I guess 
yes , i also think so
But even upto 1 million the values of both are significant
you see this is the comparison
you can clearly see that nlogn is much more significant here
big O is not concerned with the exact complexity it just finds the relationship between input size and time/space
so O(nlogn + 3n) = O(nlogn)
yah , you are right
x = [1,2,3,4,2,3,4,9,8,8,12,1,9,19]
def unique(n):
n.sort()
res = 0
for i in x:
res = res^i
if res:
return "The unique number in the array is :{}".format(res)
else:
return "Their is no unique number in the given array"
y = unique(x)
print(y)
using bitwise , this is my algorithm , to find the unique number in array
can you help me in suggesting where can i improve , at two points
1.IN decreasing the time complexity
2. In making the code more elegant and wonderful
Please respond as soon as possible
!e
x = [1,2,3,4,2,3,4,9,8,8,12,1,9,19]
def unique(n):
numbers = set()
for num in n:
if num not in numbers:
numbers.add(num)
else:
return f"The unique number in the array is :{num}"
break
else:
return "Their is no unique number in the given array"
y = unique(x)
print(y)
@feral hound :white_check_mark: Your eval job has completed with return code 0.
The unique number in the array is :2
@faint sentinel
this solution is O(n) for both space and time
hi so I am in college and want to learn data structs and algos, is there a course I can refer to
do you have to use that operator?
yes , go to youtube Kunal Khushwaha , and my code school , my code school is excellent in understanding concepts
Do they teach in python because its the only language I am comfortable with
no c and java
NO
Dsa is language independent
Even i learn in python
if you are comfortable in basic python , you can easily go
But you should be atleast comfortable with one language
ok
but the problem is my professor was teaching stacks
and taught us pop and push
which I thought were easily doable by using append and remove
so I didnt see any point of using stacks
No , therea are different use cases for all this , what they are teaching you should know it very well
Just go through my code school , one of best lectures in world , you will be able to know use cases of all
which country are you from???
in terms of python you might not fully understand why a stack might be useful but if you learn about how things are fundamentally implemented you will understand a bit better about what he advantages are and where it might be used, particularly learn about linked lists
but again in python you dont have to worry about the implementation details and just use what you have for now, the ideas of a queue and stack still come into play at some points though
for example there are two graph search algorithms called
Depth first search (DFS)
Breadth first search (BFS)
the only difference between the two fundamentally is that DFS uses a stack and BFS uses a queue
I would say you dont have to worry about them too much rn just keep these data structures in the back of your head, you will probably know when you need them
india
When we implement stack using a list in python we can't use peek(), top() etc. So how do we implement stack such that we can use all these functions(I know this is a pretty dumb question but I have just started with stacks and having a hard time implementing it)?
If you're using a list as a stack in python, peek would be mylist[-1].
But you may wish to check that the list is not empty first, to avoid an index error.
What if I want to use peek(), top() and all those functions should I implement it using queue for that?
A list works fine for a stack, you can use thelist[-1] in lieu of peek() as LX just mentioned 
You could make a thin Stack class wrapper around a list that has actual peek() if you wanted
Alright got it thanks
a deque also works but peek is still dq[-1] https://docs.python.org/3/library/collections.html#collections.deque
post it
Hey @chrome raven!
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:
A 2D list represents a 2D board with cells of a Maze. Each cell may only be in one of five states: Entrance (3), Exit (2), Wall (1), Path (0) and Treasure (4). Given a 2D list of a Maze and the Entrance coordinates, you are required to write an algorithm
To exit the maze and return a result list containing coordinates of the path from entrance to exit.
Start at the Maze Entrance (3), find your way to the Maze Exit (2) by moving horizontally or vertically along the Maze Path (0) / Treasure (4) via 1 cell movement.
Assumptions:
You may assume that all maze given will have an exit and one treasure
@fiery cosmos
ik am a bit late, but if you divide the two, you see that the limit approach 1 when n -> \inf
(btw, i don't use python, it was just to show that)
Looks like you're mapping out the whole maze with distances to each cell? I think a faster way is to BFS from start to treasure, then from treasure to end (no map), so you don't need to map the entire grid
sounds complicated
I m not sure how to implement that
Btw treasure is just another "cell" for this case
the treatsure serve a different purpose in the subsequent use case
Hi, I just want to check that I have this correct in my head with regards to the definition of a loop within decomposition.
count apples in 4 boxes then display total
count apples in box 1 then record data (loop1)
count apples
record apples counted (total update)
move to next box to count (loop2)
move to next box in range
This shows two loops within the one problem (albeit it in basic detail not full constructed)
am currently doing 114. Flatten Binary Tree to Linked List.
def flatten(self, root: Optional[TreeNode]) -> None:
"""
Do not return anything, modify root in-place instead.
"""
def dfs(root):
if not root: return None
leftTail = dfs(root.left)
rightTail = dfs(root.right)
if leftTail:
leftTail.right = root.right
root.right = root.left
root.left = None
last = rightTail or leftTail or root
return last
dfs(root)```
am dont fully understand this part
```py
if leftTail:
leftTail.right = root.right
root.right = root.left
root.left = None```
so `leftTail.right = root.right` is basically taking the left subtree and putting it on the right subtree correct?
The part of confused is when does it take the 3 and merge onto the right side child
idk if im missing something but isnt that tree invalid?
nvm confused it with a BST its fine
lol, its just a binary tree
Do you use any tool to build these graphs?
I'm looking at this 3sum implementation below is the pseudocode:
sort(S);
for i = 0 to n - 2 do
a = S[i];
start = i + 1;
end = n - 1;
while (start < end) do
b = S[start]
c = S[end];
if (a + b + c == 0) then
output a, b, c;
// Continue search for all triplet combinations summing to zero.
// We need to update both end and start together since the array values are distinct.
start = start + 1;
end = end - 1;
else if (a + b + c > 0) then
end = end - 1;
else
start = start + 1;
end
end
My question is about end = n - 1 line 5 in the for loop. We reset end/right each time, so we dont miss out a sequence. Below is an example:
nums = [-3, -2, -1, 0, 1, 2, 3]
i = -3
left = 0
right = 3
i = -3
left = 1
right = 2
i = -2
left = -1
right = 3 # When we reset end/right back to len - 1, we are able to grab this value. Is this why we reset end/right?
um no lol, it was just a screenshot
Hello
!e
s = 'This is a random string'
split_s = []
while len(s) >= 4:
split_s.append(s[:4])
s = s[4:]
split_s.append(s)
print(split_s)
@brave light :white_check_mark: Your eval job has completed with return code 0.
['This', ' is ', 'a ra', 'ndom', ' str', 'ing']
what does a != b mean in phyton
Equal To
Not Equal To
More Than
Less Than or Equal To
which of these four
options
8. Do not help with ongoing exams. When helping with homework, help people learn how to do the assignment without doing it for them.
oh ok
well I wont give you the answer staright up but
! means not
== means equal (if your checking for equality you need 2 = signs because 1 = sign is for assignment)
< means less than
means more than
<= means less than or equal to
= means more than or equal to
!= so based on all this what do you think this means?
not equal
Guys, give me some courses if possible free on ds and algos with python
Have you seen pinned messages?
does anyone here knows how to decrypt caesar cipher?
what does it mean when it says: A to Z MINUS the J?
can i ask a question about circularqueues?
class CircularQueue:
def __init__(self, size):
self.maxsize = size
self.data = [None] * size
self.size = 0
self.head = 0
self.tail = -1
def enqueue(self, value):
if self.maxsize == self.size:
return "Queue full"
else:
self.tail = (self.tail + 1) % self.maxsize
self.data[self.tail] = value
self.size += 1
def dequeue(self, value):
if self.size == 0:
return "Queue is empty"
else:
elem = self.data[self.head]
self.head = (self.head + 1) % self.maxsize
self.size -= 1
return elem
i was told that using if self.maxsize == self.size: was a canonical way to check for a full queue
if so which other method is preferred?
check if head + 1 = tail
Hey how do i paste my python code here?
!code
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.
for i in range(len(array) -1):
for j in range(i+1, len(array)):
For the above for loops what should be the time complexity? Should It be O(N)?
no, its still N^2
the no. of inner iterations is N + N-1 + N-2 + ... + 2 + 1 which is N(N+1)/2, or O(N^2)
yeah you are right
Ceaser cipher uses a fixed shift over the whole corpus, so there are 26 possible shifts. A->B means a shift of 1, or A-> C means a shift of 2. Similarly for negative numbers on the opposite side.
Since the number of possibilities is only 26 checking every shift, and if there is a large corpus, we can find the decrypted answer without any key. The idea is to look at 2-3 letter words inside our corpus (they can be "the", "is" , "and"), and check which shift gives such output. Manually(by checking which sentence makes sense) or programmatically (by checking counts and picking the one which maximizes counts of such three-letter or two letter words) depending upon the objective.
If you have a key, then it is trivial and would follow a direct shift.
Hey, im almost done with a point graph in terminal. However i get a problem when the y tuple has the same value. The x coordinate shifts too far.
for i in reversed(range(y_min, y_max + 1)):
result += "#"
if i in ys:
for idx, j in enumerate(ys):
if j == i:
for n in range(x_min, x_max + 1):
if n != xs[idx]:
result += " "
elif n == xs[idx]:
result += "*"
else:
result += " " * (x_diff + 1)
result += "#\n"
result += "#" * (x_diff + 3)
return result
Does anyone have a tip? π
could you give some more info on what exactly your trying to do?
it would also be helpful if you showed what output should correspond to a given input
the x coordinate deviates beyond parameters
the program is taking the input of coords: [(-3, 9), (-2, 4), (-1, 1), (0, 0), (1, 1), (2, 4), (3, 9)] the "*" is marked as the coords. The correct output should be:
what are the numbers of the rows and columns here?
nvm I think I got it its from x -3 to 3 and y 0 to 9
Yes that would be the range
if i in ys:
for idx, j in enumerate(ys):
whats ys?
also I think you got idx and j in the wrong order
ys is a tuple of all y coords
enumerate returns
index item
I have zipped the coords to xs and ys. So that the index of ys corresponds to the index of xs
If it would be easier to understand, I could write the rest of the function
hmm I have a suggestion for rewriting everything which will make it easier to work with
make a matrix (list of lists) which has all the hashes without the *
then loop over the coords and change the spaces to *s
and then you can just use ""join() to get your rows as strings
hmmm, that could work. Thanks I will try π
yea I am in the right place, Python algorithms!
Hey, im trying to replace the space edges with "#"
matric[i][0] = "#"
but get typer error:TypeError: list indices must be integers or slices, not list. Any solutions?
You are a god
lol
just to explain whats going on in python a for loop is really a for each loop
it iterates over iterables so
!e
my_list = ["hi", "bye"]
for word in my_list:
print(word)
@feral hound :white_check_mark: Your eval job has completed with return code 0.
001 | hi
002 | bye
I could have put i j or k instead of word here but you should try to make your variable names as descriptive as possible
Thanks, that clears things up π
!e
print(list(range(10)))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
to give a bit more context for why doing range(len(matric)) worked btw
I have made the matrice with all spaces surrounded by an edge of "#", however I have no clue how to iterate over it and change the spaces with the coords(I have never worked with matrices before)
I know i need to do something like this ```
for i in range(len(matric)):
if i>0 and i<max(range(len(matric))):
no nothing like that
remember this
you can iterate over the tuples which are your coords and then use them as indexes to your matrices
matrix[y][x] or matrix[i][j] is how you can think of it
first index is for the row second index is for the column
@opaque ermine
I just cant figure out how to properly index the coords. Maybe Im just to tired π΄
!e
matrix = [["00", "01", "02", "03"],
["10", "11", "12", "13"],
["20", "21", "22", "23"]]
print(matrix[1][2])
@feral hound :white_check_mark: Your eval job has completed with return code 0.
12
the reason I suggested this in the first place is because now you can do something like this
(-3, 9)
i j
matric[j][i+3]
instead of 3 just make sure to add the number of the minimum x value
so if -3 is the smallest x coord do +3 for all coords when indexing
you dont want to hardcode this make it so that it adds the correct number for any number but I think you get the point
Took me 5 days to fully understand what each part of a 3sum's implementation does. Good Lord!!
Actually 3, since I didnt spend time on it on the weekend.
So I have some data I want to put into a container object, sometimes the order is meant to be sorted and other times it may be random. When an element is accessed, it's supposed to be popped off the containing object, used, and then put back inside the container
Right now I'm using a queue for storing this data and using queue.get() and queue.put() to take/restore the elements
The only way to have the elements in the queue be random is to create a lit of all the elements, then do something like this:```py
my_list = list(range(100))
my_queue = Queue()
random.shuffle(my_list)
for i in my_list:
my_queue.put(i)
Is there a better way to do this?
For one, that loop can be a my_queue.extend(my_list). But yeah, I don't really see a better way to shuffle the elements.
Hey, I finally got it. Thanks for all the help
Unfortunately there's no extend function for queues, and you can't create a queue from an existing iterable/container without doing put for each element
I suppose I could use a collections.deque since it supports being declared with an iterable and can useextend but I'd have to make it block for get calls for my program
So are most problems basically optimization problems?
A lot of problems can be related to poor or no optimization, yes
i think what he meant was are most problems like https://en.wikipedia.org/wiki/Optimization_problem
Mathematically speaking, sorta
how so?
#help-chili max 3 heap
is there a data structure like a hashmap that instead of having single key value pairs it can have multiple keys refer to the same value
btw my main issue for this is because of storage with json, since I could always point the key to the value of the other key to make them both have the same value but how could I represent this in json or is there another format for this?
thinking about this again this will only work for things passed by reference not things passed by value, is there anyway I can make a request to have pointers added to python?
actually even then it wont work if I assign a completely new object to one key the other one will still refer to the old object...
!e
class multi_key_dict():
def __init__(self):
self.dict = {}
self.key_maps = {}
self.count = 0
def add(self, key, value, key2=None):
self.key_maps[key] = self.count
self.dict[self.count] = value
self.count += 1
def link(self, link_to_key, *args):
for key in args:
self.key_maps[key] = self.key_maps[link_to_key]
def get(self, key, default=None):
if key in self.key_maps:
return self.dict[self.key_maps[key]]
else:
return None
def update(self, key, value):
self.dict[self.key_maps[key]] = value
def unlink_key(self, key, value):
self.add(key, value)
def remove(self, key):
del self.key_maps[key]
a = multi_key_dict()
a.add("key1", "hello")
a.link("key1", "key2", "key3")
a.update("key2", "bye")
print(a.get("key1"))
print(a.get("key2"))
print(a.get("key3"))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
001 | bye
002 | bye
003 | bye
this is the kind of thing Im talking about btw ended up writing my own class for it
I still need to figure out a good format to store this as json and then load it into this class
what's the best way to turn a nested dict coming from json into an object with attributes?
@manic hatchdepending on scope, pydantic, a dataclass with **json, or attrs
I personally have had a good experience with pydantic
ok, thanks
Can someone suggest me how can I work upon my coding skills. Currently I am solving leetcode questions on stacks and almost everytime I can figure out the correct approach, but am unable to code it down. It's kind of frustating.
are you having trouble with remembering syntax? or just writing down code in general?
maybe try starting with easier questions (if you have trouble with the easier questions on leetcode you could try a different site like codewars.com or codingbat)
No I am not facing problem with the syntax but how to convert my thought process into code and its not something that I face with every data structure. I am face this problem on questions based on stacks, queue and Linkedlist.
are you having trouble with implementing the data structures or using them?
Using them
I would say either you dont fully understand the data structures or you are trying to use them where they dont make sense
ok. i'm not completely sure what to recommend other than reading articles/textbook sections. something else you could do is implement them yourself (if you haven't already) to gain a better understanding of how they work
you could also just look up the answers for a few of the questions take time to understand them and then try different questions
sometimes you just need to see it in practice a few times before you get how to use it
When it comes to stack I get really confused , maybe I used again try to implement them
This is the question that I was solving - https://leetcode.com/problems/daily-temperatures/
additionally, you could ask for help on a specific problem (in this channel, a help channel, or you could ask a friend)
yeah I do that quite often
also as a side note I would recommend taking cs50, it will give you a strong foundation and will give more context as to why these data structures even exist
they go over implementing some of them in c which makes a lot more sense than doing that in python
Yeah okay
is there a common way to represent finite automata, I have a massive chain of if statements which essentially check which state I am in and what the input is and where should we go based on that
I think I've seen a Python library for finite automata that heavily used decorators on methods
could use a current/symbol/next matrix
Could represent each state as an object/class maybe.
Guys I got fu**ed up rn during coding
Don't know why
But I am confused
That shall I laugh or just sry
@mint jewel This is kind of what I meant: ```py
from abc import ABC, abstractmethod
class State(ABC):
@abstractmethod
def successor(self, symbol: str) -> State:
...
Or maybe, if you're dealing with NFAs: ```py
from abc import ABC, abstractmethod
from collections.abc import Iterable
class State(ABC):
@abstractmethod
def successors(self, symbol: str) -> Iterable[State]:
...
hmm, that could work
This is more or less the standard way to implement a state machine, I think it's even called the State Machine Pattern
You could even implement unions, intersections, and so on.
Today I wrote a Monte Carlo tree search algorithm...to sort a list π
how does that even work
How does which part work?
Maybe something to do with taking a random permutation tree path
https://youtu.be/_KhZ7F-jOlI?t=183
oh, I didn't write an efficient sorting algorithm
It took 130k iterations to sort a list of 20 integers
I was mainly trying to learn how to write a Monte Carlo tree search
wouldn't that be like bogosort
Not quite
It's written as a tree search, where every child node appends one new integer to a partially completed list, with the rule that it be greater than the previous entry.
Then to estimate the value of that partial list, it does a "rollout" step, which involves randomly filling in the remaining slots in the list, and then counting how many integers are in order. It uses that to assign a score to the ordered partial list, and then navigates to the appropriate next child in the tree based on the accumulated scores.
So it's like a selection sort with random selections, but then it estimates the value of each new selection by bogosorting the rest of the list, and checking how good it did. Lol
Imagine you've been assigned to work on a group project and the goal is to sort a list. You've actually seen sorting before and know how it should be done, but your friend doesn't want to listen to you. They just want to get started. They have a vague idea that every item should be less than the next one, but that's as far as they're willing to think before they just start grabbing things and trying to sort them. That's my sorting algorithm. π
Hey guys, can someone give me some help with a loop?
I have the following code:
while True:
if active_window1 is True:
pyautogui.click(icon1)
elif active_window2 is True:
keyboard.click(icon2)
elif active_window3 is True:
pyautogui.click(icon3)
elif keyboard.is_pressed('space') == True:
break
I'd like to make it possible for the loop to detect if a certain window is active and, when that happens, click on a certain icon. After that, I want for that loop to check again if one of those active_windows are active and then react accordingly. However, I don't know how to do that. Using this code, when active_window1 == True, the loop just keeps repeating the action pyautogui.click(icon1), even when active_window1 is not True anymore.
Is there a function for Python that allows me to "restart" the loop over and over?
def has_repeats(L: list):
"""
Returns `True` if any of the elements of `L` are not
unique; `False` otherwise.
"""
if len(L) < 2:
return False
if len(L) == 2:
return L[0] == L[1]
return (
has_repeats(L[0:1] + L[1:2])
or has_repeats(L[0:1] + L[2:])
or has_repeats(L[0:1] + L[2:3])
or has_repeats(L[1:2] + L[2:3])
or has_repeats(L[1:2] + L[3:])
)
``` Can this be simplified? ^
Hey I needed help with something. Was getting help from #π€‘help-banana but they suggested to come here.
Hi, I am not sure if this is the right place to ask. I had a coding test (writing a topological sort for scheduling tasks) for a high frequency trading firm couple of months ago, but I was rejected anyway (the code I written works but maybe not up to the quality).
I am curious if where is the right place to seek some help/advice here to help me learn and improve the way I write these algorithms/ classes as I'm not a software developer. Part of the process also tested my knowledge in using things like unit testing, pylint, attrs etc.
Did they give any feedback about what they didn't like?
Well, where is it
Can't share it unfortunately. Maybe I'll write another version in my free time.
they didn't actually, so I wasn't sure exactly what went wrong.
you could simply create a set from the list and compare their lengths
Thanks, good idea. here i'm avtually being forced to use only recursion and the len and index / slice methods
oh, yikes π
You should bisect your list and then call your function recursively on each half list
thats what I thought initially as well but issue is that this only works if the repeating numbers are adjacent
Ah, true, if they end up in different sublists, you'll have a problem
For pathfinding algorithms, what website would be the best place to start?
!e
def has_repeats(L: list):
"""
Returns `True` if any of the elements of `L` are not
unique; `False` otherwise.
"""
def recursive_check(num: int, L: list):
if num == L[0]:
return True
elif len(L) < 2:
return False
return recursive_check(num, L[1:]) or recursive_check(L[0], L[1:])
if len(L) < 2:
return False
return recursive_check(L[0], L[1:])
print(has_repeats([1, 7, 8, 9, 2, 5, 6, 7]))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
True
another approach took me a while to get this one lol
oh nice
tbats a lot simpler
Hello ! Can someone help me with my problem?
I want to remove duplicates from a list and replace them with other numbers that are not duplicates but I still have them. I have done this:
g = []
for i in l:
if i not in g:
g.append(i)
else:
rnd = randint(1, 10)
g.append(rnd)
return g
print(duplicatesOrNot([6, 5, 6, 4, 5]))
but how does it work when items aren't adjacent?
!e
def has_repeats2(L: list):
for i in range(len(L)):
for j in range(len(L)):
if i != j and L[i] == L[j]:
return True
return False
print(has_repeats2([1, 7, 8, 9, 2, 5, 6, 7]))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
True
its equivalent to this
recursive_check(num, L[1:])
comapres all numbers in the list with num
recursive_check(L[0], L[1:])
compares all numbers in the list with the next number
recursive_check(L[0], L[1:])
this is also the starting point
so would just
recursive_check(L[0], L[1:])
be sufficient?
no you need to do
return recursive_check(num, L[1:]) or recursive_check(L[0], L[1:])
think of it as branching into 2 paths
the left path checks all the numbers against that particular number
the right opens a new path to check the other numbers against each other
!e
def has_repeats(L: list):
"""
Returns `True` if any of the elements of `L` are not
unique; `False` otherwise.
"""
def recursive_check(num: int, L: list):
print(num, L)
if num == L[0]:
return True
elif len(L) < 2:
return False
return recursive_check(num, L[1:]) or recursive_check(L[0], L[1:])
if len(L) < 2:
return False
return recursive_check(L[0], L[1:])
print(has_repeats([1, 7, 8, 9, 2, 5, 6, 7]))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1 [7, 8, 9, 2, 5, 6, 7]
002 | 1 [8, 9, 2, 5, 6, 7]
003 | 1 [9, 2, 5, 6, 7]
004 | 1 [2, 5, 6, 7]
005 | 1 [5, 6, 7]
006 | 1 [6, 7]
007 | 1 [7]
008 | 6 [7]
009 | 5 [6, 7]
010 | 5 [7]
011 | 6 [7]
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/piyigoxofa.txt?noredirect
have a look at this output
on every print its comparing the number on the left against the first number in the list
i see
just to give more context to the prints
list = [1, 7, 8, 9, 2, 5, 6, 7]
first call compare L[0] against all other numbers in the list
second call is doing this but also creates a new branch
recursive_check(L[0], L[1:])
to compare L[1] against all other numbers in the list excluding L[0] but thats fine since that check already happend in the first call
third call same as before but
recursive_check(L[0], L[1:])
is now starting the branch to compare L[2] to all the other numbers other than L[0] and L[1]
and so on
but the reason you see it print like this is because it completes the first branch before moving on to the other branches
its also not effcient because it makes way more calls then it needs to adding memoization to prevent checked paths from being generated would fix that issue
anyway gtg rn but will be back later if u got any more questions
i see, thanks for the thlrough explanation !
turns out you dont need memoization
!e
def has_repeats(L: list):
"""
Returns `True` if any of the elements of `L` are not
unique; `False` otherwise.
"""
def recursive_check(num: int, L: list, first_branch: bool):
print(num, L)
if num == L[0]:
return True
elif len(L) < 2:
return False
if first_branch:
return recursive_check(num, L[1:], first_branch) or recursive_check(L[0], L[1:], False)
else:
return recursive_check(num, L[1:], first_branch)
if len(L) < 2:
return False
return recursive_check(L[0], L[1:], True)
print(has_repeats([1, 7, 8, 9, 2, 5, 6, 7]))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1 [7, 8, 9, 2, 5, 6, 7]
002 | 1 [8, 9, 2, 5, 6, 7]
003 | 1 [9, 2, 5, 6, 7]
004 | 1 [2, 5, 6, 7]
005 | 1 [5, 6, 7]
006 | 1 [6, 7]
007 | 1 [7]
008 | 6 [7]
009 | 5 [6, 7]
010 | 5 [7]
011 | 2 [5, 6, 7]
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/xutuquluzo.txt?noredirect
this only generates new branches from the first branch instead of making unnecessary ones on all calls
also if you were gona do memoization you might as well just use a set to get O(N) time instead of O(N^2)
yeah π
you can use the set both recursivley and iteratively btw so if you just need recursion you can still use it
first_branch is new -- that's to save extra calls?
yup
if you want I can draw a little diagram to show you what the difference between having it and not having it
although you gota give me like 30 mins eating rn lol
!e
def has_repeats(L: list):
"""
Returns `True` if any of the elements of `L` are not
unique; `False` otherwise.
"""
def recursive_check(num: int, L: list, first_branch: bool):
print(num, L)
if num == L[0]:
return True
elif len(L) < 2:
return False
if first_branch:
return recursive_check(num, L[1:], True) or recursive_check(L[0], L[1:], False)
else:
return recursive_check(num, L[1:], False)
if len(L) < 2:
return False
return recursive_check(L[0], L[1:], True)
print(has_repeats([1, 2, 3, 4]))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
001 | 1 [2, 3, 4]
002 | 1 [3, 4]
003 | 1 [4]
004 | 3 [4]
005 | 2 [3, 4]
006 | 2 [4]
007 | False
this is probably a much clearer case to see whats going on btw
yea thats really clear
i see exactly whats happening
kinda like bubble sort
Hey anyone able to help me I'm doing a deterministic quicksort recursive algorithm. But I'm trying to do a list of size 10000 that is sorted in the way 10000,9999,9998,.....,1 . I changed my recursion limit it to 10000, but I can only go up to a list of 2800 without having a mem leak. Anyone ever have this issue and be able to help?
hello folks am currenlty doing Ransom Note on leetcode
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
if len(ransomNote) > len(magazine): return False
dict = {}
for i in magazine:
if i in dict:
dict[i] += 1
else:
dict[i] = 1
for char in ransomNote:
if char not in dict:
return False
if dict[char] == 0:
return False
dict[char] -= 1
return True```
Why are we reducing the char we have seen already? `dict[char] -= 1`
I have no idea what the actual challenge is
but
just guessing from the name
and the algorithm
because you have a set number of each letter
i have a problem with the code
foo = 30
def bar():
exec('foo = 50')
return foo
print(foo)
print(bar())
output:
30
30
but expected output is:
30
50
how can i edit the program to get what i want? (there is a 'exec' command, i need it, so i can't remove this from function)
Do you have any code?
foo = 30
def bar():
d = {}
exec("foo=50", d)
return d['foo']
print(foo)
print(bar())
You can use like this to print 30 and 50 .
Hello, I came up with this Binary Search recursive structure, but it's returning None
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
if left > right or len(arr) == 0:
return "Target Not Found"
if midpoint == target:
return f"Target Found at index {midpoint}"
if target > arr[midpoint]:
return binary_search(arr[midpoint + 1:], target)
if target < arr[midpoint]:
return binary_search(arr[:(midpoint - 1)], target)
print(binary_search([1, 2, 3, 4, 5], 3))
```
is left always 0 btw?
shouldn't it be!
hi
if midpoint == target:
return f"Target Found at index {midpoint}"
did you mean to compare with arr[midpoint] here?
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
if left > right or len(arr) == 0:
return "Target Not Found"
if arr[midpoint] == target:
return f"Target Found at index {midpoint}"
if target > arr[midpoint]:
return binary_search(arr[midpoint + 1:], target)
if target < arr[midpoint]:
return binary_search(arr[:(midpoint - 1)], target)
then now, I noticed that the length of the original array was decreasing
soo it's not returning the actual index number
π
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
temp = arr
print(temp)
if left > right or len(arr) == 0:
return "Target Not Found"
if temp[midpoint] == target:
return f"Target Found at index {midpoint}"
if target > arr[midpoint]:
return binary_search(arr[midpoint + 1:], target)
if target < arr[midpoint]:
return binary_search(arr[:(midpoint - 1)], target)
I did this then noticcd
print(binary_search([1, 2, 3, 4, 5, 6, 7], 5))
[1, 2, 3, 4, 5, 6, 7]
[5, 6, 7]
[]
Target Not Found
notice that the index is offset only when target > arr[midpoint], and that its offset by midpoint + 1
so in that if, you can return midpoint + 1 + binary_search(arr[midpoint + 1:], target) instead
return midpoint + 1 + binary_search(arr[midpoint + 1:], target)
TypeError: unsupported operand type(s) for +: 'int' and 'str'
ah yeah, you should probably return just the index from the function, not a message
wait
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
temp = arr
print(temp)
if left > right or len(arr) == 0:
return "Target Not Found"
if temp[midpoint] == target:
return f"Target Found at index {midpoint}"
if target > arr[midpoint]:
return midpoint + 1 + binary_search(arr[midpoint + 1:], target)
if target < arr[midpoint]:
return binary_search(arr[:(midpoint - 1)], target)
where
where what?
isn't that not gonna effect the if statements
think you should do
if target > arr[midpoint]:
t = binary_search(arr[midpoint + 1:], target)
if t == -1:
return -1
return midpoint + 1 + t
It's crashinhg with even arrays
ooh bet
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
if left > right or len(arr) == 0:
return -1
if arr[midpoint] == target:
return f"Target Found at index {midpoint}"
if target > arr[midpoint]:
if target > arr[midpoint]:
t = binary_search(arr[midpoint + 1:], target)
if t == -1:
return -1
return midpoint + 1 + t
if target < arr[midpoint]:
return binary_search(arr[:(midpoint - 1)], target)
this
print(binary_search([1, 2], 2))
returns
return midpoint + 1 + t
TypeError: unsupported operand type(s) for +: 'int' and 'str'
but
you're returning a string when its found
return the index (midpoint)
also
if target > arr[midpoint]:
if target > arr[midpoint]:
is redundant
this
print(binary_search([1, 2, 3], 2))
returns
Target Found at index 1
you should return just the index
and this
print(binary_search([1, 2, 3, 4, 5], 2))
returns
-1
wait
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
print(arr)
if left > right or len(arr) == 0:
return -1
if arr[midpoint] == target:
return f"Target Found at index {midpoint}"
if target > arr[midpoint]:
t = binary_search(arr[midpoint + 1:], target)
if t == -1:
return -1
return midpoint + 1 + t
if target < arr[midpoint]:
return binary_search(arr[:(midpoint - 1)], target)
print(binary_search([1, 2, 3, 4, 5], 2))
[1, 2, 3, 4, 5]
[1]
[]
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
print(arr)
if left > right or len(arr) == 0:
return -1
if arr[midpoint] == target:
return 0
if target > arr[midpoint]:
t = binary_search(arr[midpoint + 1:], target)
if t == -1:
return -1
return midpoint + 1 + t
if target < arr[midpoint]:
return binary_search(arr[:(midpoint)], target)
this is working fine but hmm
if arr[midpoint] == target:
return 0
return midpoint
it's working π³
nice π
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
print(arr)
if left > right or len(arr) == 0:
return -1
if arr[midpoint] == target:
return midpoint
if target > arr[midpoint]:
t = binary_search(arr[midpoint + 1:], target)
if t == -1:
return -1
return midpoint + 1 + t
if target < arr[midpoint]:
return binary_search(arr[:midpoint], target)
if t == -1:
return -1
is this part necessary ?
yeah, if the thing is not found in the list then it shouldn't offset the -1
it's still returning -1 without it

yes
if its not found, it should return -1
it shouldnt return midpoint + 1 - 1
without that, if you searched for 4 in [1, 2, 3] it would return 1 + 1 + -1 or 0, implying that the first item in the list is 4
which is false
oooh
1 more thing
if left > right
I don't think there's any use of this in my code right?
instead I'll use:
if len(arr) == 0:
return -1
def binary_search(arr, target):
left = 0
right = len(arr) - 1
midpoint = (left + right) // 2
print(arr)
if len(arr) == 0:
return -1
if arr[midpoint] == target:
return midpoint
if target > arr[midpoint]:
t = binary_search(arr[midpoint + 1:], target)
if t == -1:
return -1
return midpoint + 1 + t
if target < arr[midpoint]:
return binary_search(arr[:midpoint], target)
the conditions left > right and len(arr) == 0 are equivalent
since left = 0 and right = len(arr) - 1, if left < right then len(arr) has to be 0
π 
btw, what is "t" like what exactly is my function returning there?
ooh wait
trying to process this again
why's recursion a bit complicated sometimes lol
hmmmmmmmm
ooooh so t becomes -1 inside one of the functions that has a length of 0
so we say when t becomes -1, it means that the length became 0
but how is it inside my if statement, that's whats confusing me
your function returns the index at which target is present in arr, or -1 if it is not present
aaah I see it now
thanks!
π
Does anyone know how to create a code that helps you write backwards?
!e
text = "abc"
print(text[::-1])
@feral hound :white_check_mark: Your eval job has completed with return code 0.
cba
do you mean something like this?
ty, dude, i I appreciate it
Happy to help! π .
When running this code I get a list with the same values but I don't understand why:
`lst = list()
years = 0 #initial year iterator
while years < 20:
i = 1.02
if (roi*(netincome - costi + initial)) < 50000:
lst.append(roi(netincome - costi + initial))
else:
lst.append(tax1(roi*(netincome - cost*i + initial)))
years += 1
i = i*i
`
I should get lst with different values
lst = list()
years = 0 #initial year iterator
i = 1.02
while years < 20:
if (roi*(netincome - cost*i + initial)) < 50000:
lst.append(roi*(netincome - cost*i + initial))
else:
lst.append(tax1*(roi*(netincome - cost*i + initial)))
years += 1
i = i*i
try this you had
i = 1.02
in the loop so it kept resetting its value instead of compounding as you probably wanted
am currently doing 542. 01 Matrix on leetcode
def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
m = len(mat)
n = len(mat[0])
q = []
for i in range(m):
for j in range(n):
if mat[i][j] == 0:
q.append((i,j))
else:
mat[i][j] = "#"
for row,column in q:
for dx,dy in (1,0),(-1,0),(0,1),(0,-1):
nr = row + dx
nc = column + dy
if 0 <= nr < m and 0 <= nc < n and mat[nr][nc] == "#":
mat[nr][nc] = mat[row][column] + 1
q.append((nr,nc))
return mat```
For this part
```py
for dx,dy in (1,0),(-1,0),(0,1),(0,-1):
nr = row + dx
nc = column + dy```
I know its checking all 4 directions but I don't understand why we are adding `dx` and `dy` to row and column
dx and dy are row and column offsets. The d stands for "difference". Although their use of variable names is slightly mixed here as they've called the row and column row and column respectively, rather than x and y.
The first offset, (1, 0) adds 1 to the row, and 0 to the column. So the coordinates (nr, nc) represent the cell immediately below the cell with coordinates (row, column).
How can I multiply 2 floats whose decimals get very small accurately? This code arrives at numbers too big for my pc
`lst = list()
years = 0
i = 1.02
while years<20:
lst.append(i)
i *= i
years += 1`
- Write a strategy to reach the goal node efficiently and quickly. Your logic/algorithm should be ideated while keeping in mind that you have prior knowledge of those black obstacles, but you only come to know about the grey obstacles once you reach a cell adjacent to it.
use decimal.Decimal instead of floats
I would think using an optimal path finding algorithm like BFS or A*, and then recalulating at each step to account for the gray walls when they can be seen is the way to go
Okay
btw you dont have to recalculate at each step just when you encounter the grey walls, and at that point you could either recalculate the shortest path again or first check first if your current path is blocked and then recalculate, either way all the methods should still work, this is just about efficiency
I cannot thank you enough
happy to help π
I've some sets of combinations of inequalities in form of [{(x>y),(y>x)},{(y>z),(z>y)},...] and I want to get all unique correct combinations.
One set can have more than 2 inequalities, but for simplification I'm omiting it now.
I'm looking for:
- Is there similar problem explained anywhere else?
- Implementation of check function.
- Implementation of get_all_correct_combinations that returns only unique results.
- [Optional] Some way to iterate from "greatest" to "lowest"(heuristics is ok)
- [Optional] Get count of orders that are correct for single combination with complexity <n!
@dataclass
class Greater:
"""Relationship like greater-than sign between two nodes
Irreflexivity: not a<a, i.e. no element is related to itself
Transitivity: if a<b and b<c then a<c
Asymmetry: if a<b then not b<a.
"""
base: int
destination: int
def check(combination: Tuple[Greater]):
"check if combination is correct"
raise NotImplementedError()
def get_all_correct_combinations(possibilities: list[list[Greater]]):
"yield all correct combination of inequalities"
for option in itertools.product(*possibilities):
if check(option):
yield option
# Example problem
my_options = [
[Greater(1, 2), Greater(2, 1)],
[Greater(2, 3), Greater(3, 2)],
[Greater(3, 4), Greater(4, 3)],
[Greater(4, 5), Greater(5, 4)],
[Greater(5, 6), Greater(6, 5)],
[Greater(6, 1), Greater(1, 6)],
]
for x in get_all_correct_combinations(my_options):
print(x)
Solutions:
Could return set[Greater], but to show solution indices of my_options are more readable
β 000000 1>6 & 6>1
β
000001 1>2 2>3 3>4 4>5 5>6 1>6
β
000010 1>2 2>3 3>4 4>5 6>5 6>1
β
000011 1>2 2>3 3>4 4>5 6>5 1>6
β
000100 1>2 2>3 3>4 5>4 5>6 6>1
β
000101 1>2 2>3 3>4 5>4 5>6 1>6
β
000110 1>2 2>3 3>4 5>4 6>5 6>1
β
000111 1>2 2>3 3>4 5>4 6>5 1>6
[...]
hey , currently working on LeetCode 21. Merge Two Sorted Lists
https://leetcode.com/problems/merge-two-sorted-lists/
Recursive Solution is as follows:
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
# Recursive
if not l1 and not l2:
# both l1 and l2 are empty list
return None
elif not l1:
# l1 is empty, directly return l2
return l2
elif not l2:
# l2 is empty, directly return l1
return l1
if l1.val < l2.val:
l1.next = self.mergeTwoLists(l1.next, l2)
return l1
else:
l2.next = self.mergeTwoLists(l1, l2.next)
return l2
I am having some difficulty understanding it - i was hoping someone might be able to break it down for me if possible, thanks. Im referring to the** final if else statement where the recursive calls are made**
(am supposing l1.next is l1 from the second element to the last one)
the "if l1.val < l2.val":
If the value of (the first element of) l1 is superior than l2, you know that the first element you'd need to return in the list is the first elemet of l1, and the rest is the sorted of l1 (without it's first element) and l2.
the "else" which translate into "l1.val >= l2.val"
Same as above, but for l2, by remplacing l1 by l2
(if I don't make sense, ask me, I'm not entirely sure if what I wrote is clear or not)
so, let's have two list, l1 = [1, 3, 7] and l2 = [2, 5]
let's try this alg
l1 not empty, l2 not empty, l1.val > l2.val, so
l1.next = self.margeTwoLists(l1.next, l2)
so, now, we have l1 = [3, 7] and l2 = [2, 5]
l1 and l2 not empty, l1.val !> v2.val, so we do
l2.next = self.margeTwoLists(l1, l2.next)
so, we have l1 = [3, 7] and l2 = [5]
l1 and l2 not empty, l1.val > l2.val, so
l1.next = self.mergTwoLists(l1.next, l2)
so we have l1 = [7] and l2 = [5]
l2.val > l1.val, so we have
l2.next = self.mergeTwoLists(l1, l2.next)
l2 is empty, so return l1 = [7]
l2.next = [7], so l2 = [5, 7]
return [5, 7]
so l1.next = [5, 7] so l1 = [3, 5, 7]
return [3, 5, 7]
so l2.next = [3, 5, 7], so l2 = [2, 3, 5, 7]
return [2, 3, 5, 7]
so l1.next = [2, 3, 5, 7], so l1 = [1, 2, 3, 5, 7]
return [1, 2, 3, 5, 7]
I'm not entirely sure to get what you need... 1. Idk
- I guess something like: (I don't know python really well, but that'll be the idea)
def check(combination: Tuple[Greater]):
for i in combination:
if !(i.a > i.b):
return False
return True
- use a set I guess: (again, try it on your own)
def get_all_correct_combination(possibilities: list[list[Greater]]):
for option in set(possibilities):
if check(option):
yield option
- how do you distinguish "higher" and "lower"??
(again, I don't use python much, and mostly, am a bit confused on what you need)
What I fount out:
- Partial order in math
- Check if result creates DAG:
def check(combination: Tuple[Greater]):
"""check if combination is correct"""
dag = nx.DiGraph()
for x in combination:
if dag.has_node(x.base) and x.destination in nx.ancestors(dag, x.base):
return False
dag.add_edge(x.base, x.destination)
return True
- Current solution, but can be improved by getting cartesian product with early rejection: https://stackoverflow.com/a/65918605
def get_all_correct_combinations(possibilities: list[list[Greater]]):
"""yield all correct combination of inequalities"""
for option in itertools.product(*possibilities): # use frozenset
if check(option):
yield option
- use topological sorting from networkx library
nx.topological_sort(graph)
- I haven't found out yet.
Answer (1 of 2): According to this StackExchange answer by Henning Makholm, this is a hard problem.
How many topological orderings exist for a graph?
The main way is to be systematic about your counting.
If you think about it, you can determine it for some cases to speed up your counting.
Her...
The Cartesian product is just itertools.product
check the pins
hello folks, am currently 21. Merge Two Sorted Lists on leetcode. This is my code
def mergeTwoLists(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
tail = dummy = ListNode()
while l1 and l2:
if l1.val < l2.val:
tail.next = l1
l1 = l1.next
else:
tail.next = l2
l2 = l2.next
tail = tail.next
if l1:
tail.next = l1
elif l2:
tail.next = l2
return dummy.next```
I dont fully understand `tail.next`. I know exactly what everything else is doing but its just that specific part I dont understand
this is an example of a linked list, where instead of storing all the values in memory right next to each other, you just have each value contain a reference to the next value. This way you can go through the list by continuously looking at the next value
so the next field of the tail variable should point to the next item in the list
Try following along with the algorithm manually to see how it is manipulating this field to merge the two input lists
Hey comrades! I need a bit explaining please.
What does the 'CheckRowClueR' function do here? Can anyone please help.
Here's the question: https://www.codewars.com/kata/5671d975d81d6c1c87000022
Anyone π
hey i have just started ds algo
got some knowledge of algorithm , it's all 3 possible cases , rules of a algo , basis of judgement
n then binary search nd linear search
now got into Big O notation n all
cant understand what r they
https://www.youtube.com/watch?v=8hly31xKli0&t=2399s watching this
In this course you will learn about algorithms and data structures, two of the fundamental topics in computer science. There are three main parts to this course: algorithms, data structures, and a deep dive into sorting and searching algorithms.
By the end, you will understand what algorithms and data structures are, how they are measured and e...
can any1 tell why big 0 notations ? what r they when needed
i just learned it defines the complexity of algo as a func of time
linear search-O(n)
binary search-o(log n)
n yeh explain me logarithm
plz
Decided to start looking into Algorithms & Data Structures. Already using AlgoExpert. Any books that explain the topic really well? (Considering buying a book on it in advance of learning it in class in about 3 months)
u r learning from which lang?
!code ?
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.
why this backticks are used?
In discord?
They just tell discord that text inside it needs to be formatted in a different way inside a code block
Can someone share any resources from where I can learn how to solve problems based on matrix like valid sudoku or finding sum of diagonals. I always have a hard time solving questions based on matrix.
Hey just inquiring if anyone here has a discord server dedicated to solving codewars or hackerrank on regular basis? Trying to find a social group of people who enjoy solving such challenges so that I can motivate myself to be regular π
All skill levels welcome btw
So if we have a string and we want to sort it as following:
string = "".join(sorted(string))
Then the time complexity will be O(n) + O(n log(n))
O(n) - for join
O(n log(n)) - for sorting the string
That would just be O(n log n), since that one is bigger
O(f(n)) gives an upper bound
hey
I am trying to replicate code for a game
the original is in javascript
however
when doing it in python
it gives an entirely different result
var seed = "a407ad70682db53dc93912dd3e30cc678f4e1e6015f56675c3f064010dc772e0"
var salt = "0000000000000000000fd438478cd50a858def3b606d43dfe12a22144f3a5f1b"
const nBits = 52;
const start = CryptoJS.enc.Hex.parse(seed)
console.log(start.toString(CryptoJS.enc.Hex))
const hmac = CryptoJS.HmacSHA256(start, salt);
seed = hmac.toString(CryptoJS.enc.Hex);
console.log(seed);
seed = seed.slice(0, nBits / 4);
const r = parseInt(seed, 16);
console.log(r);
let X = r / Math.pow(2, nBits);
console.log(X);
X = 99 / (1 - X);
console.log(X);
const result = Math.floor(X);
console.log(result);
console.log(Math.max(1, result / 100));
```this is the original js version
these are the outputs
anybody know at least how I can do the HMAC part in python? Whatever I do with hmac and hashlib just gives entirely different results, which leads to a different game result
Oh so whatever takes the longest we would use that?
What do you mean by O(f(n)), what is f?
A function of n
Sorry, I dont get it. What do you mean by, A function of n?
f(n) is some function f that takes some input n
O(f(n)) means the big O of the function f with input n
When you said O(f(n)) gives an upper bound, in this case f(n) is replacing O(n) + O(n log(n)), since we use the one that takes the longest time we will use O(n log(n)).
what your being told is that big O (O()) is concerned with the worst relationship between input size n and time/space
f(n) is replacing O(n) + O(n log(n))
almost
O(f(n)) is replacing O(n) + O(n log(n))
in this case that is
f can refer to any function but in this case its referring to your function
oh ok
like f(n) = n or f(n) = n*log(n) or f(n) = n^2, just some expression involving n
O(f(n)) == O(n) + O(n log(n)) == O(n + nlogn) == O(nlogn)
oh ok thank you!! I see what you mean.
Is there a word wrap algorithm that preserves columns of text while still wrapping paragraphs? For example here.
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
Id like the columns to be preserved but the paragraphs of text to be word wrapped.
if i feed this to pythons textwrap function it will wrap everything
i started to do something similar for another project but didn't finish it
but, yeah, python's built in text wrap will modify all the text
Though, I think I could do something hacky real quick
thatd be great. Ive been thinking few a while but cant come up with something.
sorry in case im misunderstanding but you just want this
The story had held us, round the fire, sufficiently breathless, but except the obvious remark that it was gruesome, as, on Christmas Eve in an old house, a strange tale should essentially be, I remember no comment uttered till somebody happened to say that it was the only case
to turn into this
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
the first one is all on the same line discord just wrapped it
am I correct?
!e
my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""
def word_wrap(text, line_length=100):
lines = text.splitlines()
i = 0
while i < len(lines):
line = lines[i]
i += 1
if len(line) <= line_length:
continue
truncated = [ ]
words = line.split()
while len(words) + sum(map(len, words)) > line_length:
truncated.insert(0, words.pop()) # could use a deque
lines[i - 1] = " ".join(words)
if i < len(lines):
lines[i] = f'{" ".join(truncated)} {lines[i]}'
else:
lines.append(" ".join(truncated))
return "\n".join(lines)
print(word_wrap(my_text, 50))
@stable pecan :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire,
008 | sufficiently breathless, but except the obvious
009 | remark that it was gruesome, as, on Christmas Eve
010 | in an old house, a strange tale should
011 | essentially be, I remember no comment uttered
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/rafuluwera.txt?noredirect
wow i didnt think it was possible.
!e
my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""
def word_wrap(text, line_length=100):
lines = my_text.splitlines()
i = 0
while i < len(lines):
line = lines[i]
i += 1
if len(line) <= line_length:
continue
truncated = [ ]
words = line.split()
while len(words) + sum(map(len, words)) > line_length:
truncated.insert(0, words.pop()) # could use a deque
lines[i - 1] = " ".join(words)
if i < len(lines):
lines[i] = f'{" ".join(truncated)} {lines[i]}'
else:
lines.append(" ".join(truncated))
return "\n".join(lines)
print(word_wrap(my_text, 90))
@fiery cosmos :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire, sufficiently breathless, but
008 | except the obvious remark that it was gruesome, as, on Christmas Eve in
009 | an old house, a strange tale should essentially be, I remember no
010 | comment uttered till somebody happened to say that it was the only case
ah i see
it will just skip the lines that are not past max
so it can only get smaller. It doesnt care if the columns go past its line length
so it wont try and fill
well anyways thanks
do you want it to be able to increase the word wrap limit as well?
ok will you paragraphs always be encased in
...
text
...
if that is the case its a lot easier since otherwise there is not real way of differentiating what is a paragraph
so how do you know what is a paragraph?
if you can figure out a rule for that its possible
yeah i think what im shooting for is not possible
i guess ill just try and see what most pdfs or text files conform to
and try and make an algorithm for that
and everything else will turn out sloppy
i accidentally used the variable name my_text in the function, should be changed to text
hmm it might be better to do something like this instead
i just adjust the margins to have the text centered
instead of filling the page
i think long lines of text are harder to read anyways instead of nice decent size width paragraphs
that does mean id have to get the longest line of text in the pdf or whatever
you can add to the function to increase line lengths too
i didn't know you wanted that
just grab words from the next lines.
in a similar type of while loop
yes but wouldnt this cuase a problem with the columns of text?
I have an idea instead of all this, are the paragraphs always guaranteed to have the longest line lengths?
im not sure.
if that is the case what you can do is set a minimum line length check all the lines in the file until you reach a line of a certain minimum length lets say 10
columns can be identified by being less than some line length and having no full stops
then keep appending those lines longer than 10 into a variable called text
use pythons text wrap on that variable and then just replace the lines where they need to be replaced
this way you set a min and a max value so that it only does wrapping on lines longer than the min value and wrap them to the width of the max value
lots of things to think about.
i think ill just make a random mad libs style text generator
becuase im still trying to build the app
pythons textwrap module can handle that
!e
import textwrap
my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""
def wrap(text, threshold, width):
start = []
middle = []
end = ""
for line in text.split("\n"):
if len(line) > threshold:
middle.append(line)
elif len(middle) == 0:
start.append(line)
else:
end += line
start = "\n".join(start)
start += "\n" + "\n".join(textwrap.wrap("\n".join(middle) ,width=width))
return start
print(wrap(my_text, 30 ,200))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire, sufficiently breathless, but except the obvious remark that it was gruesome, as, on Christmas Eve in an old house, a strange tale should essentially be, I
008 | remember no comment uttered till somebody happened to say that it was the only case
its not completed yet but I think this is more along the lines of what you want
@fiery cosmos
!e
import textwrap
my_text = """
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
THE TURN OF THE SCREW
I
II
III
...
The story had held us, round the fire, sufficiently breathless, but
except the obvious remark that it was gruesome, as, on Christmas Eve in
an old house, a strange tale should essentially be, I remember no
comment uttered till somebody happened to say that it was the only case
"""
def wrap(text, threshold, width):
start = []
middle = []
wrapped_text = []
for line in text.split("\n"):
if len(line) > threshold:
middle.append(line)
elif len(middle) == 0:
start.append(line)
else:
start = "\n".join(start)
start += "\n" + "\n".join(textwrap.wrap("\n".join(middle) ,width=width))
wrapped_text.append(start)
start = []
middle = []
return "\n".join(wrapped_text)
print(wrap(my_text, 30 ,200))
@feral hound :white_check_mark: Your eval job has completed with return code 0.
001 |
002 | THE TURN OF THE SCREW
003 | I
004 | II
005 | III
006 | ...
007 | The story had held us, round the fire, sufficiently breathless, but except the obvious remark that it was gruesome, as, on Christmas Eve in an old house, a strange tale should essentially be, I
008 | remember no comment uttered till somebody happened to say that it was the only case
009 | THE TURN OF THE SCREW
010 | I
011 | II
... (truncated - too many lines)
Full output: https://paste.pythondiscord.com/rayicayita.txt?noredirect
and its completed π
threshold is used to determine where a paragraph starts and ends
its not the best way to do it but its the best we got rn until you can figure out some pattern to identify paragraphs
yes im looking at free ebooks and finding patterns.
Like here for instance
i can word wrap the paragraphs that have the full stops.
i dont want continuation of word wrap on the bullet point lists though. they have full stops but are separated by newlines
so maybe i can use that
i think ill just do random words for right now
well depending on how general you want it to be you might have to do a lot check whats a paragraph and whats not
but as long as you can do that you can do something similar to what I did
in my code it just assumes that a paragraph is everything between a line longer (inclusive) than the threshold and a line shorter than the threshold (not inclusive)
Hello all!
I'm looking for help with an algorithmns question. It was originally for HW but the submission date passed and I still can't wrap my head around the solution. I got the other 3 in the problem set but couldn't get an algo to pass all test cases for this problem.
Alice has chosen n holiday gifts for her friends. Alice knows that each gift will be on sale during Black Friday. The Black Friday sale price of giftiwill begiftPrices[i].sale. Theprice of item i before Black Friday will be giftPrices[i].before; and the price of gift i after Black Friday is going to be giftPrices[i].after. Alice wants to plan when to buy each gift to minimize the total cost of all gifts. The challenge is that Alice can buy at most k gifts on BlackFriday. She, however, can buy any number of gifts before and after Black Friday. Design and implement an algorithm for finding the minimum total cost of all n gifts. Write the following function
MinCost(const std::vector<Price>& giftPrices, int k)
The parameters of this function are const std::vector<Price>& giftPrices β the list of prices and k β the maximum number of items Alice can buy on the Black Friday sale. Each element ofthe array/vector giftPrices contains three fields: sale, before, and after, as described above. Function MinCost should return the minimum possible total cost of all gifts. All numbers are integers
My original idea was to calculate the difference between Price.before and Price.after, Price.before and Price.sale. Then find the difference of those differences and choose the K largest difference of differences and for the rest swapping between before price and after price depending on which is less. This week was Greedy Algorithmns which I thought I had a good handle on from my AI course but clearly, I'm still struggling a bit.
I don't want a straight solution if possible, just some help finding the right steps. Thanks in advance.
I think the strategy would be as follows ```
- sort all the price items by their sale price
- go through that sorted list one at a time and add the min price per item (of sale, before, after) to total amount spent, if k is 0 you aren't allowed to use the sale price
- if the step 2 price was the sale one, decrement k```
for each gift, you can choose to either buy it before black friday, after, or on black friday. Since you can buy any number of gifts before black friday, and any number after, the cheapest thing is either to buy it on Black Friday (for up to k gifts) or at the cheaper of the before price and after price (for n - k gifts).
so you want to choose the k gifts with the biggest delta between sale and min(before, after) - those are the k gifts that you save the most by buying on black friday.
and for each remaining gift, you take it at the min(before, after) price.
oh I wasn't thinking about differences
my strat may be wrong
it never makes sense to buy a gift at the higher of the before price and the after price. So for each gift, you're choosing between buying it at min(before, after), and sale.
and since you can only buy k at sale, they should be the k where sale is most below min(before, after), because those are the k that you save the most by buying on black friday.
Yeah, taking the k gifts with the biggest abs(sale - min(before, after)) makes sense, then just min(before, after) after that
or that's not quite right 
I forgot to mention, I'm not sure this changes the solution, the sale price is not always less than the after and the before prices.
I think this is sort of similar to calculating the differences of differences and selecting on that, no? More straightforward but close to being the same metric? If the sale price could be more expensive that throws a wrench in this solution, I think.
I say that as a strong novice in algos
Sorting by min(before, after) - sale and taking the first k of those where the sale is chosen 
Also thank you so much for both of your responses
YouΕe right, the way I was calculating the heuristic was incorrect and this accounts for the sale price being greater
except, if the sale price isn't always the lowest, then you should buy fewer than k on black friday if the first k of them don't have a positive delta.
So I can still sort by the heuristic just if I approach a negative delta I can just select on min(before, after). That makes sense to me. If k = 3 but only the first item has a positive delta then just ignore the sale price for the rest of the items
right.
Thank you so much, both of you! I had gotten off the Greedy path and the solution ended up being less complex than I originally thought. I would've spun my wheels for hours on that.
Hello, i have a problem with list comprehension:
following code doesnt work, i basically wanna append 2 items into the list in one for loop.
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
listo = [nums[i],nums[i+n] for i in range(n)]
return listo
the code should do the following:
class Solution:
def shuffle(self, nums: List[int], n: int) -> List[int]:
listo = list()
for i in range(n):
listo.append(nums[i])
listo.append(nums[i+n])
return listo
!code
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.
[x, y for i in range(n)] returns list of tuples
It should be something like that
elements = [[nums[i], nums[i + n]] for i in range(n)]
elements = list(sum(elements, []))
!e
numbers = list(range(100))
n = 4
elements = [[numbers[i], numbers[i + n]] for i in range(n)]
elements = list(sum(elements, []))
print(elements)
@trim fiber :white_check_mark: Your eval job has completed with return code 0.
[0, 4, 1, 5, 2, 6, 3, 7]
ahhhhhh okay thanks a lot @trim fiber
Hi There, I am trying to add a column to a dataframe using a function to provide the values. I am trying to figure out why this doesn't work:
change_df['Change (%)'] = format_change(change_df['Change'])
In my head that should create a new column called "Change (%)" and populate it with the function "format_change" and pass the value in "Change".
The error juypter is spitting out is
ValueError: -1 is not in range
which looking further down suggests that it has an issue with this line of the function
if string[-1] == '%':
But I cannot understand why it's unhappy as all my rows have values, stored as objects and have a minimum length of 3.
OK so I stumbled on the answer and I think my issue is using SQL like code, this is going to be a problem.
The code should be:
change_df['Change (%)'] = change_df['Change'].apply(format_change)
Hi everyone! I am just starting out in Python and made a program to calculate prime numbers and then store them in a csv file. Everytime I start the program I want it to move on where it left off so I read the csv file (every prime has its own row) into a list in python but because I work with rows the list becomes a list of lists. primes = [[2][5][7][9][11][13]]. The problem with that is if I want to access them I need to double index it prime[3][0] and the primes that are read into the list from the csv are stored as strings, where the new primes added are stored as ints. I can not index an int and as a result I get an error. Can anyone help with this problem? (this description is a mess I know ask for more info if needed please)
Well, unpack the sublists once and get left with only one list.
something like primes = [row[0] for row in primes].
I tried that but im fairly sure I used wrong syntax. Right now I am trying to solve the problem at the beginning to just convert every element to an int before it gets read into my list. So all the items in the list primes are ints from the beginning and I never have to subscript
Hey fellas, simple slicing question.... If:
a = np.array([[1,2,3,4], [1,2,3,4]])
a[:, 1::4] = [[1], [1]],
how would I extract [1, 1] ?
.reshape(-1) would work, say.
any reason why this would stop working? lat_hla = hla[-1] #get last char from string
the input comes from hla = pytesseract.image_to_string(im_hla)
empty string?
for some reason the last char is blank now, so i had to change it to [-2], \n is being added to the end of the string by OCR, i need to figure how how to remove that first
!d str.strip
str.strip([chars])```
Return a copy of the string with the leading and trailing characters removed. The *chars* argument is a string specifying the set of characters to be removed. If omitted or `None`, the *chars* argument defaults to removing whitespace. The *chars* argument is not a prefix or suffix; rather, all combinations of its values are stripped:
```py
>>> ' spacious '.strip()
'spacious'
>>> 'www.example.com'.strip('cmowz.')
'example'
``` The outermost leading and trailing *chars* argument values are stripped from the string. Characters are removed from the leading end until reaching a string character that is not contained in the set of characters in *chars*. A similar action takes place on the trailing end. For example:
thanks that worked
Hello I Am Struggling With A Problem For Class:
Given two strings and a list of allowed "substitutions," return
whether one string can be converted into the other.
Example:
Input:
string 1: hello
string 2: helper
substitutions:
lo -> pa
pa -> per
Output:
true
This is true because "hello" => "helpa" => "helper."
you'd want to iterate over the string looking for match between the substring and the substitution
then iterate over the substitutions
?
That Only Shows If A Substitution Can Be Used?
What If You Need To Use More Than One?
iterate again would be the easiest
If The First Substitution Is h -> hh, Wont You Get Stuck On hello -> hhello -> hhhello?
Forever ?
Thanks For Your Help
i'm a bit confused about where you got this problem because it's not actually solvable
It should be solvable, it just seems arduous b/c you have to iterate over the substitutions multiple times
...or update the substitution list to include transitive substitutions, and avoid loops
my first instinct would be to use breadth first search
but that assumes its solvable and will search forever if not
it's a bit tricky to explain why, but this is undecidable
no algorithm can solve it in the general case
it feels reducible to the halting problem to me, but do you have a proof for it?
sure we can represent the state of a turing machine with some string s:
10101#stateA01010
would be tape 1010101010 in state A with the head at the third 1
and this is very loose but we can fairly easily construct some primatives right
eg.
1#stateA -> #stateA1
0#stateA -> #stateA0
would be moving our head to the left
we can come up with similar primitives for writing and stuff
maybe check out https://en.wikipedia.org/wiki/Markov_algorithm
Sounds complicated... if it's just a homework question, why not just iterate over all substrings
then look for mismatches
then substring(s) from 1 and iterate over the substitution list and look for matches
def main(string1: str, string2: str):
substitutions = {
"lo": "pa",
"pa": "per"
}
save_string_1 = string1
for key, value in substitutions.items():
for key2, value2 in substitutions.items():
for i in range( len(string1) ):
for start in range(0, len(string1), 1 ):
try:
if string1 == string2: return print(string1)
if key in string1[start:start+i]:
temp = string1[start: start+i].replace(key,value)
string1 = string1[0: start ] + temp + string1[start + i:]
if string1 == string2: return print(string1)
if key2 in string1[start:start+i]:
temp = string1[start: start+i].replace(key2,value2)
string1 = string1[0: start] + temp + string1[start + i:]
except:
break
return print("no")
if __name__ == '__main__':
main("hello", "helper")
I actually made something like this
not sure it properly works but it does for ur exampel
Does anyone know of some good resources for explaining memoization?
It just means caching the result of a computation so that it can be looked up in the future rather than recomputed
For example, if you want to write a function that tells you the n-th prime, you'll have to compute all the (n-1) primes first, so you might want to just save those results, in case you get asked to find another prime again.
if u copy the for start loop and add it after but with a descreasing loop, the code will work with only two syllabus in input/output. If u want more u need to find a way to nest for loop
Maybe not the best solution but i will work
For further optimisation you can detect all iterations of substitutions strings and iterate over them
can anyone please share the solution of how to calculate time complexity of this , with the mathematics involved also ,step by step
Please help
This isn't a Python code 
i calculated it is O(n^3) coming ,
i am wanting a detailed step by step solution for this problem
no the complexity should be O(n^2) because you used i in both loops
so your outer for loop actually only does one iteration
so the time complexity all comes from i<n*n; i++ which is n^2
also you should really think about how you style your code that looks disgusting with wrong/inconsistent indents and no spaces in the for loops
Hi , I have a problem
let's say the tuples are random rgb values
I want all the ones with a lot of red at the top
and all the ones with a high (yellow - blue) on the left
but i want to do it by sorting it into quadrants and then sorting the individual quadrants into quadrants etc
what are you sorting them into?
a 2d array
ok I think I get what you want now
(i have exactly 4**n tuples, btw)
btw do you mean green and blue?
yes, sry
and how would that work for the green and blue what rule would you use there?
or are you treating them equally?
basically lambda x: x[1]-x[2]
because if you want a nice gradient thats not what your gona get by sorting both on the left without some specific rule
you could do red on the top, green on the bottom and blue on the right if you want a nice gradient
I only used colors because i thought it would be easier to understand
no, i have a list of tuples that have nothing to do with colors other and i want to make them more or less binary searchable in two dimensions
it probably is easier to understand with colors so it was a good idea to phrase it like that, either way this applies to anything
hmm tbh I've never thought of binary search in 2 dimensions, not sure how that would work rn, will try a few things and get back to you if I figure something out, for now hopefully someone else has an idea
actually wait I have an idea
do you actually care about how they're stored or are you only doing it for the binary search
and do you care about their order, or is it again just for the binary search?
ahh I see so as long as its a 2d array you dont care?
well my question is because I want to change the definition of a similar tuple
you could just have it so that you sort it using the sum of the values in the tuple
that wouldn't work for me
why not?
you can achieve what you want but you need to first have a very clear definition of how to compare the tuples
wouldnt that still work?
I'm thinking of it now since your doing deltax + deltay if you sort them using x+y it should still work no?
I would reduce them to 1 dimension, which i don't want
you can first sort them in a 1byn array and then reorganise them into a 2d array
or maybe I'm not understanding you correctly