#algos-and-data-structs
1 messages · Page 102 of 1
Well, a tree is a very fundamental data structure in computing. Not just in computing, but in real life as well.
uhhh
I mean you didn't use classes or anything
no, don't see anything OO here
It's just:
a) an empty list
b) a pair of: an element and another linked list
You can implement linked lists with classes or tuples or anything you want really
you can have another linked list in a linked list?
well yeah same way you can have a dictionary in a dictionary
or a list inside of a list
no, I meant a different thing
hang on I will re read the Grokking chapter
None -- empty list
(1, None) -- head of the list is 1, the rest of the list is None
(2, (1, None)) -- head of the list is 2, the rest of the list is (1, None)
yeah, maybe that
I feel doing this in haskell would be better, but maybe not
Haskell lists are linked lists and they have builtin function for head, tail, inits, etc
I'm still confused tho aren't arrays just lists in python
an array means that everything is stored next to each other in memory
Python lists are arrays under the hood
Well almost
"It’s like going to a movie with your friends and finding a place to sit— but another friend joins you, and there’s no place for them. You have to move to a new spot where you all fit. In this case, you need to ask your computer for a different chunk of memory that can fit four tasks. Then you need to move all your tasks there."
this is what Grokking says about arrays
Sounds ok tbh
so I think he's trying to say insertion is not that great for arrays?
Yea because you have to reallocate space for the array
got it
he also says you can "hold seats"
like hold chunks of memory
if you want to read everything in a linked list at once
but if you want to go from one node to another node that's far away you can't
you should be using a linked list bc you can just insert stuff
right?
you don't need to move anything around just insert stuff
You should make a distinction of inserting at the tail or the middle
Inserting at the tail is called appending
i forgot what it's called inserting at the head
Thats called prepending
oh ok
Just know that theyre different because they have different costs
got it
Also depending on how you implement the linked list appending could be O(1) or O(n)
ok and when you insert stuff in a list
you change what the node/previous element points to
but when you use arrays you shift everything down in memory
same w deletion too
when you delete stuff from a linked list you just change what the previous element was pointing to
yeah, you'd care about insertions and pops here
a linked list has O(1) time for insertion and O(1) time for deletion
so a linked-list-based queue
bc when stuff gets inserted the nodes can just switch to where they point
and same when it gets deleted too
the only bad thing about a linked list is lookups of a specific element
what if they screwed up and wanted to look at something in the middle of the queue?
or is that just a dumb question
bc then an array would be better
Queues dont generally have items skip ahead
@old rover that scenario is unlikely within the context of the problem
ok
uhhhhh
# Node class
class Node:
# Function to initialize the node object
def __init__(self, data):
self.data = data # Assign data
self.next = None # Initialize next as null
# Linked List class
class LinkedList:
# Function to initialize the Linked List object
def __init__(self):
self.head = None
ok how do you do this without classes?
you don't really make data structures without classes
you don't need inheritance, but you will want to learn classes if you want to make data structures in python
it helps a lot
ok will do
don't be heapq
a what?
heapq is a python module which implements a heap
where should I look to learn it?
it's List Cosplay Day 🙂
Learn what heaps are first
but instead of it being a class, it just runs it on top of some sequences.
https://realpython.com/python3-object-oriented-programming/ this is probably useful
you can skip the section on inheritance
is a heap another data structure
yes
Its a tree with some constraints
so I mean does Grokking just expect that I already know OOP?
probably
you should be fine, inheritance tends to be the part that gets people
yeah it got me when I was doing Scala
great language
😂
one of my favourites
typeclasses are beautiful
🥴
so am I just gonna have to flat out memorize how to create a linked list?
that doesn't sound fun
no you should understand it
Once you know what a linked list is, it's easy to make one. There's really no memorization involved.
but I do know what a linked list is
it's a list that has nodes that point to each other w pointers
ok, make one
without looking at the code
then, what's the problem? A simple singly linked list is basically just:
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
n1 = Node("c")
n2 = Node("b", n1)
n3 = Node("a", n2)
then what is up with this dude's implementation
it's java-esque. He uses setters and getters for something that could just be attributes.
but that's mostly just stylistic. It's the same structure as what I wrote off the top of my head.
am noob sorry
wrong channel
all good
the author then takes the Node class, which is essentially what I wrote (and is the actual linked list), and created a LinkedList class that wraps it and provides algorithms on top of it.
but I don't want to memorize entire functions
so... don't...
there's no memorization involved here. If you want to find the length of a linked list, you walk it until you find a node without a next. If you want to remove a specific node from a list, you set the previous node's next to the node you're removing's next.
maybe try understanding the functions then
to insert an element after a specific node, set the new node's next to the next of the node you're inserting after, and then set the node you're inserting after's next to the new node.
the functions are showing you implementations of an algorithm. You just need to understand the algorithm - once you know the algorithm, it's easy to implement it.
I do understand the algorithm
then I don't understand the problem. If you understand the algorithm for finding the size of a linked list, the size() function there is trivial
great thanks this was very helpful
I'm not sure if that was sarcastic. If it was, perhaps try describing the problem and I'll see if I can be more specific.
I do understand the data structure I just don't know how to code it from scratch
and every guide I look at is so long
If you understand the data structure and the algorithm, then you don't need to bother with the guide. Take the simple linked list I made:
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
n1 = Node("c")
n2 = Node("b", n1)
n3 = Node("a", n2)
Take that and walk it. Find its length. Insert an extra element between a and b. Delete b.
And if you don't know how to do any of those steps - is it that you don't understand the algorithm, or you don't know how to implement the algorithm?
I make my implementations have a node class and a linked list class with the usual methods
Instead of manually connecting nodes like that
I've seen that in a lot of tutorials and i dont understand why
it's easier to understand than manually connecting nodes ¯_(ツ)_/¯
having a LinkedList class instead of just Node allows you to represent an empty list - that can't be done as easily with only Node
you need to assign a special meaning to a specific head node, or something.
Its also easier to compare to the python list and its methods
yep. But at the same time, it's one extra level of indirection, and obscures the algorithms a little. Seeing how nodes manually connect is slightly easier IMHO.
I still don’t get it
in a real world implementation I'd have a class that wraps the collection of nodes, though, most likely.
The bad thing is I can’t just google how to make a linked list during an interview
what, specifically?
I just don’t know how to write out the code without looking at someone else’s implementation of it
which code? The class(es) representing the data structure itself? The methods representing algorithms on it, like getting its length, or inserting or removing elements?
no the code from the website
This stuff
OK - what's a specific example of a class or method from that website that you wouldn't be able to implement on your own?
There's 2 different data structures and 4 different algorithms shown there, depending on how you count.
I mean
Idk what to write for insertion, search, and deleting things without looking back at it
are you familiar with the algorithm?
Yes
You start with the first node and you iterate through until you find the node you want bc all the nodes aren’t close together in memory like they are in an array
do you know how to insert a node?
i don't understand how you can be familiar with an algorithm and not be able to implement it
I don’t bc grokking algorithms shows no coding snippets w data structures
I’ll look at CLRS tomorrow and see if it does
huhh? it doesn't show pseudocode?
no it doesn’t
can you show me the page where it describes how to search for a node?
it just goes to another sorting algorithm in the next chapter
like a screenshot or something
that's still talking about arrays, that first page
probably the next page
wow
it seems that book is not meant for learning the implementation, just the application
so maybe it would be better to read CLRS for that specific section
to get more than a surface level understanding of a linked list
idk about clrs, you seem to have bad experiences with that book ¯_(ツ)_/¯
then idk what to do dude
gotta try something
what kind of book doesn't even teach the actual implementation of the damn data structure?
a book concerned about applications
i didn't write the book ¯_(ツ)_/¯
The "grokking algorithms" one seems to be an ELI5 type of thing.
a what?
"explain it like I'm 5"
oh I didn't know that acronym
if I were trying to explain a linked list to an elementary school student, my explanation would be like that one.
yeah that's true
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class SLinkedList:
def __init__(self):
self.headval = None
list1 = SLinkedList()
list1.headval = Node("Mon")
e2 = Node("Tue")
e3 = Node("Wed")
# Link first Node to second node
list1.headval.nextval = e2
# Link second Node to third node
e2.nextval = e3
here's some code I found from https://www.tutorialspoint.com/python_data_structure/python_linked_lists.htm#:~:text=Advertisements,lists in its standard library.
Python - Linked Lists - A linked list is a sequence of data elements, which are connected together via links. Each data element contains a connection to another data element in form of
that first class Node actually does what you did in your code before
Is that book Grokking algorithm?
correct
still I'm sure a 5th grader could understand the implementation in psuedocode
It doesnt show the actual code?
nope
not for a linked list
for a binary search algo it does
I remember reading somewhere that the intent of the book is to give an overview of what different data structures are.
It's not intended for step by step break down of what each algorithm does.
and how to do it.
each
ngl, linked lists are actually terrible
lmao
they're good for a certain purpose
not really
why do you say that?
Do you?
I know how they work I just don't know how to implement them in code
as someone (probably knuth or something) said that one time, "talk is cheap, show me code"
ah, linus torvalds
Agreed.
ok here's the new plan not that anyone really cares
use Grokking to get base level knowledge of stuff
then use CLRS to solidify what you already know
Wait werent you learning big O?
yeah
I have seen CLRS being highly regarded.
well it's a tough book to read cover to cover for me at least
probably for anyone
extremely long detailed paragraphs make it something you want to refer to
Yeah, that's also true. I have heard that its pretty hard.
it is very rigorous, in the sense that everything is fleshed out
I mean
I'm gonna need to get a bit rigorous w the material
if I really want to learn it
growth mindset or what not
I also like how these questions are very code based rather than concept based
of course. if you can't code it, who cares if you "know how to do it"
is this CLRS?
yes
it seems you've found it
Are you also still learning big O? Or are you diverting your focus to implementing data structures?
nah I spent like 3-4 days on big O
I am not staying in big O hell
Grokking algorithms says big O is just how fast an algorithm runs
hahahaha
I'm gonna steal that "big O hell"
hahaha
I mean
what do you want me to do? spend a whole month on just big O?
ain't nobody got time fo dat
No, i personally think you are doing the right thing by implementing them.
yeah a lot of the people on pydis said you're supposed to be learning data structures and algorithms along w big O
of course, you can't learn big O in isolation, that's just useless
not seperately
yes, exactly
Actually I think at UB they taught linked lists even before they taught big O
but that doesn't really make sense to me
at where
university at Buffalo
but I think their CS curriculum was pretty garbage anyways
so uh I'm gonna watch some netflix and then go to bed
it's been a very long day
Thanks guys for helping me I really appreciate it
I'm trying to write a json response to a local file, then later access the file. I can write the response locally but I'm having a hard time accessing the data locally, if that makes any sense). Could anyone help?
Does it have to do w algos/DS?
json would be something you would get when you make a request to a server/api
You make a request and you get a response, that format of the response depends on who designed it, but in most cases it's json.
Yeah the only time I heard of JSON was web related stuff
Yeah, currently I get the response and dump it into a local file, but it seems I can't access/print parts of it locally. I realize I should probably just open a help channel for this though
What do you mean, "seems I can't access/print parts of it locally"?
when I try something like
print(tempFile['48hours'][1]['moving_avg'])
I get an error about
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)```
printing just the tempFile gives me the same error
then there's something wrong with your tempFile, probably the way you are reading your json and storing it inside tempFile
how are you reading your json?
with open('data.json', 'w') as outfile:
json.dump(requests.get(("https://api.warframe.market/v1/items/{}_prime_{}/statistics").format("ash","blueprint")).json()['payload']['statistics_live'], outfile)
with open('data.json') as json_data:
d = json.load(json_data)
print(d)
this prints the entire json
So you are able to print the entire json, but not part of it?
Yeah, basically it wont let me access it like a json
Thought as far as I understand json.load should fix that
Then that has to do with your query
Something is not correct here, data['48hours'][1]['moving_avg']
I replaced that section of the code, the entirely of my code is what I put in chat now. Heres what the json looks like just for reference
It should be 0 instead of 1.
wait my bad.
Even ignoring the [1] and only putting ['48hours'] errors. However I'm trying to access it is incorrect, I just cant figure out why
can you paste your json here?
If it's not sensitive data and you are comfortable.
Someone just helped me figure it out. I just needed to change how I'm printing
print(d['48hours'][1])
so can you do print(d['48hours'][1]["moving_avg"])?
I was trying to change what part of the json d would be equal to, but since d becomes a dict I guess I can just access the separate sections
I can print that yeah
Then what was wrong?
The way I was trying to print. I was trying to do ```py
d = json.load(json_data['48hours'])
print(d)
instead of
```py
d = json.load(json_data)
print(d['48hours'])
Oh ok yeah you have to pass the whole file when you load, and then afterwards you can access specific part of it.
Anyway, thank you
your file is still called rich.py
so python is importing that instead of the rich module
Do we really need to split array recurcivesly in mergesort?
when we can just split them in half and sort them using two pointers?
no, both approaches work and one of them doesn't require copying the array
Im trying to make a defined algorithmic function that can determine if an inputed word is a palindrome or not (a word that is the same backwards, like racecar). are there any ways i could do this? This is for an assignment, so dont just give me the answer. All i need for now is a method i can build off of.
So far im thinking a loop and a list of some sort
sure, have you written any code?
yeah
print ("Welcome to the PALINDROMATIC 5000!")
print("Please do not input numbers, symbols, individual letters, or special characters. (such as: A $ 5 ♡.)")
def checkPalindrome(str):
str = input("Please input a word: ")
reversedword = []
characterindex = len(str)
while characterindex > 0:
reversedword += str[characterindex - 1]
characterindex = characterindex - 1
return reversedword
reversedword = ''
if str == reversedword:
print("Yes")
else:
print("Naw")
print(checkPalindrome(str))
return reversedword will stop the function
right
also, you take str as an argument, but instantly override it
yeah, i fixed that
that isn't a bug, just weird code.
print ("Welcome to the PALINDROMATIC 5000!")
print("Please do not input numbers, symbols, individual letters, or special characters. (such as: A $ 5 ♡.)")
def checkPalindrome():
str = input("Please input a word: ")
reversedword = []
characterindex = len(str)
while characterindex > 0:
reversedword += str[characterindex - 1]
characterindex = characterindex - 1
return reversedword
if str == reversedword:
print("Yes")
else:
print("Naw")
print(checkPalindrome())
What can I say, im a relatively new python user
I also mostly learn by trial and error but i dont have time for that, it takes too long
at least your reversing logic seems to work correctly
Cause i looked up how to reverse a string but yeah
at the very least i can understand the reversing loop
but now I need to convert the list it outputs back into a string
str.join(iterable)```
Return a string which is the concatenation of the strings in *iterable*. A [`TypeError`](exceptions.html#TypeError "TypeError") will be raised if there are any non-string values in *iterable*, including [`bytes`](#bytes "bytes") objects. The separator between elements is the string providing this method.
is that understandable to you?
yeah
hey I got a question
why is it that CLRS shows the psuedocode for searching stuff in a linked list, inserting stuff into a linked list, and deleting stuff from a linked list
but it never actually shows how to create the linked list??
I guess it just assumes that you already know how to make one???
def checkPalindrome():
str = input("Please input a word: ")
reversedword = []
characterindex = len(str)
while characterindex > 0:
reversedword += str[characterindex - 1]
characterindex = characterindex - 1
reversedword = str.join(reversedword)
return reversedword
print(checkPalindrome())
``` Okay, oi added the join method, and it works but it prints multiple of the reversed characters. Like, if i input "racecar" it outputs "rracecararacecarcracecareracecarcracecararacecarr"
how you create a linked list depends on the language
it does describe it
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
n1 = Node("c")
n2 = Node("b", n1)
n3 = Node("a", n2)
yeah but it doesn't show an implementation of it in psuedocode
it's right there
what ami doing wrong
I know the difference between a linked list and a doubly linked list
where?
I don't see any psuedocode there
if i describe an algorithm to you in english, that's pseudocode
@inland iron the way you use str.join is like separator.join, so you want to write ''.join to join with no separator
it is the opposite order from what you would expect
it says:
each element of a doubly linked list L is an object with a key field
and two other pointer fields: next and prev
@old rover
the reason it went wrong as it did is because your parameter str
so you were joining reversedword with the original input as separator
what's a key field?
it's a variable, which stores a "key"
class Node:
def __init__(self, data, next=None):
self.data = data
self.next = next
n1 = Node("c")
n2 = Node("b", n1)
n3 = Node("a", n2)
so then what is the key field here?
self.data
I get what's happening up till the n1 = Node("c")
that's the first node
and then it goes to node B, and the reference is back to node 1?
ok
also this is for a doubly linked list
pointing to the other node
someone told me that there are no pointers in python
just references
that's correct
and references are just addresses in memory
sure
Okay, now i have another assignment, but its the same as the one i just did. i just have to refactor my code: ```py
print ("Welcome to the PALINDROMATIC 5000!")
print("Please do not input numbers, symbols, individual letters, or special characters. (such as: A $ 5 ♡.)")
str = input("Please input a word: ")
def checkPalindrome():
reversedword = []
characterindex = len(str)
while characterindex > 0:
reversedword += str[characterindex - 1]
characterindex = characterindex - 1
reversedword = ''.join(reversedword)
if reversedword == str:
print("This word is a palindrome.")
return True
else:
print("This word is not a palindrome.")
return False
print(checkPalindrome())
do you have any ideas about how you would go about solving that?
None
I mean, i refactored the code: ```py
def checkPalindrome(word):
reversedword = []
characterindex = len(str)
while characterindex > 0:
reversedword += str[characterindex - 1]
characterindex = characterindex - 1
reversedword = ''.join(reversedword)
if reversedword == str:
return True
else:
return False
print(checkPalindrome("racecar"))
print(checkPalindrome("banana"))
class linkedListNode:
def__init__(self, value, nextNode = None):
self.value = value
self.nextNode = nextNode
node1 = linkedListNode("3")
node2 = linkedListNode("7")
node3 = linkedListNode("10")
node1.nextNode = node2
node2.nextNode = node3
can someone explain why the colon after linkedListNode is being underlined in red?
is that the entire file?
yes
so one more to the right?
in between def and __init__
oh yeah I was wondering why it didn't get highlighted
thanks dude
Last Video: https://www.youtube.com/watch?v=W-9hyTm1syc
How to code a linked list in 2 separate ways.
This is video #2 in my Linked List series.
From student to software engineer: Build your career at www.theforge.ca
yeah I really like this video for linked lists
it's in python 2.7 but who cares
you like snake case more?
so if this was a doubly linked list
wouldn't you just be using the .nextNode thing more?
so it's really not that bad
and CLRS has functions you can add to your linked list to make it do stuff
CLRS has functions that can make your linked list do stuff?
like insertion, deletion, searching
yeah...
ok?
time to add those
You need a linked list class for those
damn why doesn't it say that in CLRS
because you don't actually need a linked list class for those
but he just said
ok then thanks
It would make sense that those functions are part of a linked list class and not top level or part of the node class
it would, but it's not necessary
especially if you're unfamiliar with the oop concepts
also, afaik clrs tends to not give the overall structure of the code, only the individual functions
class linkedListNode:
def __init__(self, value, nextNode = None):
self.value = value
self.nextNode = nextNode
node1 = linkedListNode("3")
node2 = linkedListNode("7")
node3 = linkedListNode("10")
node1.nextNode = node2
node2.nextNode = node3
def listSearch(List, node):
x = List.head()
while x != None and x.node !=node:
x = x.nextNode
return x
ok I don't think there's any such thing as x.next
I think they mean next node?
yes
yes
it says so in the text
it probably says what x.next is before bc I don't see it in that paragraph
that's correct
It would be a good idea to read the paragraphs carefully
I am not reading this book cover to cover
I am reading the paragraphs that come w the functions
def listSearch(List, node):
x = List.head()
while x != None and x.node !=node:
x = x.nextNode
return x
you don't have a head method defined anywhere
I actually don't know how to write the head method of the linked list
sure, but it'd certainly be useful to read the entire linked list section, since yuo're learning aobut linked lists
do you want that List to be head
you don't need .head() you need a list head variable
to be pass into the function
I need an extra paramater?
I'd suggest you read the book, but implement the idea yourself
I did read the chapter
Then you should know how it works
def listSearch(List, node): The List is already head of the list
ok
def listSearch(aList, node):
x = aList
while x != None and x.node !=node:
x = x.nextNode
return x
so is this correct then?
does it work?
I don't even know how to test it
create some nodes, connect them together, and use your function on it
create some random lists, make them into linked lists, and test that your function returns the same position as .find on the original list
class linkedListNode:
def __init__(self, value, nextNode = None):
self.value = value
self.nextNode = nextNode
node1 = linkedListNode("3")
node2 = linkedListNode("7")
node3 = linkedListNode("10")
node1.nextNode = node2
node2.nextNode = node3
I have some nodes over here that I connected into a linked list
ok great, now try searching for one of them
that makes sense
later, I suggest you make a enlist function which will convert a list to a linked list
that exists????
it would if you make one
yep
in some way, every function one can think of exists 😉
some don't
for example
def contains_infite_loop(program):
...
wdym?
Bro focus on this one
focus on what??
ye, write the search
The search thing
the conversion is harder
node = linkedListNode("3",
linkedListNode("7",
linkedListNode("10")))
so that's the entire linked list
yep
# This Function checks whether the value
# x present in the linked list
def search(self, x):
# Initialize current to head
current = self.head
# loop till current not equal to None
while current != None:
if current.data == x:
return True # data found
current = current.next
return False # Data Not found
I found this code on geeksforgeeks
yeah
so it's __contains__, basically.
magic word
uhhh
This method is how you'd implement the __contains__ magic method, which would allow in checks
Have you written your own classes before?
You've never used in?
I used in
lol
that's why - you need to know the magic methods when implementing your own classes with operators
It's a good goal to make your LinkedList one - you'll learn how to implement in, +, .extend (like on lists), how to do classmethods (to implement enlist)...
yeah
I'm just struggling
no two people implement a linked list the same
class linkedListNode:
def __init__(self, value, nextNode = None):
self.value = value
self.nextNode = nextNode
node1 = linkedListNode("3")
node2 = linkedListNode("7")
node3 = linkedListNode("10")
node1.nextNode = node2
node2.nextNode = node3
this part mostly stays the same
# This Function checks whether the value
# x present in the linked list
def search(self, x):
# Initialize current to head
current = self.head
# loop till current not equal to None
while current != None:
if current.data == x:
return True # data found
current = current.next
return False # Data Not found
what do they mean by current here?
it's the node you're currently checking
that's your "key"
sigh
is there a reason you're not using the pseudocode in clrs?
I have been using the psuedocode in CLRS for the past hour at least
and I haven't gotten anywhere
do you know what's giving you problems?
hi hi : )
I understand the psuedocode
I just don't know how to write it in actual code
.head is a method in python right?
no, it's an attribute
it doesn't even show how they even create .head
because it's different for every language
it's just an attribute they make the node-object have
seems like it's their linked list class
class SingleLinkedList:
def __init__(self):
"constructor to initiate this object"
self.head = None
self.tail = None
return
I googled how to find the head of a linked list and this is what I found
ok
I just wish the book didn't assume I just knew how they did .head
but wishing won't change anything
Its just a method that gets the first item in the list
how do you post code?
You dont even need it
it does say in the introduction of the book, that it is not an introductory text for people who don't know how to program
it assumes familiarity with basic language concepts
class Solution(object):
def twoSum(self, nums, target):
self.nums = nums
self.target = target
self.indicies = []
for i in nums:
if target - i in nums:
x = nums.index(i)
self.indicies.append(x)
print(self.indicies)
im not sure why im getting the first 0 when outputted?
oh boy I asked in my college's coding server and now they're saying to do it in C++
it is probably a better language for dsa
but python
The language doesnt matter and anyone telling otherwise is a dumbass
what is a constructor?
Try thinking about it logically; you know what the head of a list is, right? so when the user creates the head of the list, you can set self.head to that node
I kinda forgot the definition
i'm not saying you can't learn dsa, but you must have a handle on programming in your language of choice before tackling them
a constructor creates and initializes an object
If you end up doing it in another language, there's an entire guide on Rust based on implementing tons of shitty linked lists 🙂
https://rust-unofficial.github.io/too-many-lists/index.html
Learning Rust With Entirely Too Many Linked Lists
i love that tutorial
(even with a rant at the beginning about why linked lists are horrible and why no one should ever use them for anything except educational purposes)
(thats the same explanation as why you have to learn freudian psychology in every intro to psych class)

"here are all of freudians theories. also they are all wrong"
"but learn them anyways bc hes the father of psychology"
because Freudian psychology, despite being an outdated pseudoscience, happens to be exactly as effective as fancy modern psychotherapy methods? 😛
💀
sounds like the people who worshipped Siraj Rival
I just realised this isn't offtopic.
when all the channels merge together
Yeah, cache locality = dead
Although streams (infinite lists) are kinda useful, and they're sort of like linked lists
linked lists are still good for merging and inserting near the center
although, that is quite rare
def add_list_item(self, item):
"add an item at the end of the list"
if not isinstance(item, ListNode):
item = ListNode(item)
if self.head is None:
self.head = item
else:
self.tail.next = item
self.tail = item
return
so isInstance returns a boolean
if it matches the data type in the second paramater?
class SingleLinkedList:
def __init__(self):
"constructor to initiate this object"
self.head = None
self.tail = None
return
this is how they create the .head method
is that how CLRS wants me to do it?
head isnt a method there
is a stack another data structure?
yes
oh well F in the chat for me ig
I'm looking at this book and it doesn't implement a linked list on its own
well, in a way
only w a stack
stacks can be implemented via linked lists
it depends on what methods you attach to your linked list, basically
stacks can also be implemented via arrays
true
searching a linked list
didn't you make a working method for that?
Pretty much:
- Take the head as the current node
- Until you find a node that has the right value or hit a node without a
.next(the tail), take the current node's.nextas the new current node.
but I can't even take the head of the current node
bc I don't know how to write the function to take the head
Of the linked list, you mean? Why?
The head is the first node
I think you don't quite get how linked lists work
yeah I know the head is the first node
Ok then whats the problem
I don't know how to write the code for it
There are two ways to implemnet a linked list, basically:
- Only have the Node class. It has a certain
.nextand a value, and that's it. To hold a reference to the linked list, you hold a reference to its head node. The problem with that approach is that you can't really truly modify the list in a way that changes it head - you'd need to somehow tell every other function/whatever that has a reference to the first node "hey, the head is changed now"
- Have a
Nodeclass, and also have aLinkedListclass. The latter would have a reference to itshead, a reference to itstail, maybe also itslength, and have all the methods for working with linked lists.
With the second approach, the problem of the first one vanishes - one only holds the reference to the linked list itself, and the list's head can be updated however you want.
It seems to me that you're confused because you're trying to use the former approach and so are confused what head is supposed to be.
So use the second one - you need another class.
@vocal gorge im here now 🙂
also, regarding the constant M
Let
T(n)andf(n)be two positive functions. We writeT(n) ∊ O(f(n)), and say thatT(n)has order off(n), if there are positive constantsMandn₀such thatT(n) ≤ M·f(n)for alln ≥ n₀.
there's the M... idk what's its purpose lol
ah, I see. Yeah, it's the definition.
Because what that means is that, say, n^2 is not O(n). Why? Because no matter what M you choose, even 10**100, the statement n^2 < M n will stop being true for sufficiently big n.
But 48101203213 n is O(n) (pick any M bigger that 48101203213)
OHHHH I GET IT NOW!
so the M is there to signify this sort of... transcendence almost
yeah
essentially, this is necessary for the definition to be invariant with regards to multiplication by a constant. The O-notation is about, basically, making a hierarchy of functions that asymptotically exceed each other.
linked lists! love 'em
Any function that's O(n log n) will eventually exceed a function that's asymptotically O(n), and they will exceed the O(sqrt(n)) ones, and so on
but I know that bc it's hard coded in there that it's 3
yeah
how do I find the head if I'm not creating the node myself?
yep thx so much! i understand
you can't go linkedList[0] bc there's no index since they're far apart in memory
wait... this means that AFTER FOUR FKING ATTEMPTS I FINALLY COMPLETELY UNDERSTOOD THE DEFINITION OF BIG O
YESSSSSSSSSSSSSSSSSSSSSSSSSSS
With approach 1, the head is the node that's passed to you, always (there's nothing special about the head with approach1, so that's the only way you can know what the head is).
With approach 2, make a LinkedList class - you're still lacking it.
ok so I created a linkedList class
is that camelCase i see in a class name??
PascalCase pls
your linked list is basically a "wrapper" around the chain of nodes inside
idk what Pascalcase is dude
LinkedList instead of linkedList
like camelCase but you capitalize the first word as well
but whatever
it should have a head attribute, a tail attribute, maybe a length attribute, and of course, that's what you'll attach all the methods to.
head and tail will be references to Node instances. A LinkedList always has a head and a tail unless it's empty.
(if it's length 1, they are the same Node).
class LinkedList:
def __init__(self, head, tail, length):
self.head = head
self.tail = tail
self.length = length
like that?
mmm, it'd be pretty annoying to create the list like that
because it'd mean you have to manually build the list like you were doing before you can wrap it in a LinkedList
instead, I'd suggest just:
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
and then start attaching methods, starting with push (append a node to the tail) and pushleft (append a node before the head)
is that self.head = None the same thing as putting head = None
in the def init paramater?
def init(self, head= None)
like that?
No, in my case the init accepts no arguments.
After you implement these two methods, you'll be able to build your lists pretty easily.
depends on whether you need to
if I wanted to do search through the linked list
I'd implement building it first.
a bit difficult to search through something you don't have
Since I get the impression you don't quite get why this should be done this way, still, and implementing a working LinkedList will probably make it clearer.
So make a list you can add elements to, then bother with searching.
the idea behind push is basically:
- if the list is empty, just make the new Node the new head and new tail.
- If it's not, take the current
tail, and set the new Node as its.next. - In both cases, increment
.length.
start with that.
oh, and step 0) wrap the value you need to add in a Node
oh lord what have I gotten myself into
...linked lists? 😛
why is all the code for linked lists I look at manually coding the linked list
but not building the linked list with an input
interesting
why does the book even start with linked lists?
don't they all
no lol
I would hope not
when in procedural programming do you even see a linked list
compile time macros creating traces
I dunno
the first ds in almost all the resources I've ever come across is linked list
I guess an array is too simple
you'd think, but start with a vector then 😔
idk what those are yet
a binary search tree <> binary search
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
self.last_node = None
def append(self, data):
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
def display(self):
current = self.head
while current is not None:
print(current.data, end = ' ')
current = current.next
a_llist = LinkedList()
n = int(input('How many elements would you like to add? '))
for i in range(n):
data = int(input('Enter data item: '))
a_llist.append(data)
print('The linked list: ', end = '')
a_llist.display()
i thought it meant isomorphic
It can mean a lot of things
so is that append function how you build a linked list?
it is very flexible
the code?
fair enough ¯_(ツ)_/¯
god knows I haven't even tried it
is the reason why they're setting last_Node = None bc it doesn't exist yet?
ye, the constructor should create an empty linked list
ok
...why did you change tail to last_node?..
i think you need to just stop looking up code, and start producing your own
I would if I knew what to write
it also doesn't do what I described. Rather, your append is what I described above as pushleft - it appends to the beginning of the list.
review your resources until you are able to produce a linked list on your own
dude
I have been staring at CLRS for the past 2 hours
and Grokking too
and the other book I have
or start even simpler than a linked list. Try making a box. It holds a single value and has get and set methods
get returns the value in the box, set sets the value in the box
if you're not able to do it on your own, maybe you're not ready to do it yet.
Well, see my message above:
the idea behind
pushis basically:
- if the list is empty, just make the new Node the new head and new tail.
- If it's not, take the current
tail, and set the new Node as its.next.- In both cases, increment
.length.
So:
def push(self, val):
node = LinkedListNode(val) # wrap the value in a node
if self.length == 0: # if the list was empty, make it the head and the tail
self.head = self.tail = node
else: # otherwise, append to the tail and make the node the new tail
self.tail.next = node
self.tail = node
self.length += 1
damn dude maybe you should try never learning anything that you have a hard time w initially
if self.last_node is None:
self.head = Node(data)
self.last_node = self.head
else:
self.last_node.next = Node(data)
self.last_node = self.last_node.next
``` that looks about the same as this, expect not storing an internal length
Consider now how to do pushleft (or whatever the common way to call that method is). It'll be very similar, but you need to set the head to the new node, and make sure the new node's next is set to the old head.
I am serious, try making a box. Maybe learning classes and data structures and algorithms is too much at once for you. That is fine
take it step by step
there is nowhere to rush to
I don't want to make a box
...well that's not good learning attitude
if you have no idea where to really go with a linked list, you need more practice with simpler classes. That is perfectly fine. Keep in mind textbooks are supposed to have a highly competent teacher along with them explaining everything, not be used alone. Which is why they start so harshly a lot of the time
sorry, i didn't mean that you should just give up, but sometimes it's better to wait until you have more experience. i remember a couple months ago i got really confused whenever i looked at anything oop-related, but now i'm able to understand much better because i have more experience
I'm not waiting for another couple of months
I'm doing it and I'm doing it now
I understand helping a complete beginner to DS/algos is frustrating
especially when you're like how do they not understand this concept? I learnt it in one day
that is not the issue here. I just think you would have an easier time if you started with something simpler and worked your way. If you bash your head against a wall long enough, it will work, but there are better ways to learn.
this is one of the simplest data structures
well if you go through hell keep going
I have no idea why they are so common, they are really only used for flow control with recursion and some obscure places
clrs starts with stacks, right? maybe try that and go in order of the textbook
stacks are a useful data structure
Nah I like Grokking more
I don't like the gigantic paragraphs with every miniscule detail involved
even now I still don't get entirely what CLRS is saying after reading the chapter multiple times
very well, lets get back to bashing heads against the wall
welcome to daspecito land
how far did you get with writing a linked list yourself?
hey at least I'm not trying to do leetcode questions without knowing any ds/algos
I created a linked list manually
but I didn't know how to create it w someone else's input
ah, I remember now
alright, an easier operation than append or push is just prepend
where you take a linked list, a value and create a new linked list which starts with that value
make that function
what actually the proper name for this that isn't cons
I found a GitHub repo
that actually does all off the adding and searching in a couple of lines
I will check it out after lunch
@mint jewel it you want to look at it
that's a doubly linked list
ok then that’s just one thing to change
a doubly linked list just has the pointers from a node pointing to the previous one and the one ahead
If you think looking at a complete implementation of a linked list would help you, I could write one.
yes please
class Node :
def __init__( self, data ) :
self.data = data
self.next = None
self.prev = None
class LinkedList :
def __init__( self ) :
self.head = None
def add( self, data ) :
node = Node( data )
if self.head == None :
self.head = node
else :
node.next = self.head
node.next.prev = node
self.head = node
def search( self, k ) :
p = self.head
if p != None :
while p.next != None :
if ( p.data == k ) :
return p
p = p.next
if ( p.data == k ) :
return p
return None
def remove( self, p ) :
tmp = p.prev
p.prev.next = p.next
p.prev = tmp
def __str__( self ) :
s = ""
p = self.head
if p != None :
while p.next != None :
s += p.data
p = p.next
s += p.data
return s
so like how do you tell that this is a doubly linked list?
every node has a self.next and a self.prev
every Node has a prev and a next reference
Pasting large amounts of code
If your code is too long to fit in a codeblock in discord, you can paste your code here:
https://paste.pydis.com/
After pasting your code, save it by clicking the floppy disk icon in the top right, or by typing ctrl + S. After doing that, the URL should change. Copy the URL and post it here so others can see it.
also
they just use .head exactly like how the textbook does
but no one ever shows how they defined head
The code that you just posted defines head.
.
I thought you guys wanted me to write a function for head
https://paste.pythondiscord.com/ekakakafew.rb there ya go. Ran some unit tests, so it should be correct at least, feel free to ask if you have questions (no idea why it indents with tabs, in the file its with spaces.)
this is great thanks
class Node:
def __init__(self, head, tail):
self.head = head
self.tail = tail
def __repr__(self):
return f'({self.head!r} {self.tail!r})'
so you can't call .head without this?
I thought it was just a property
class LL_Node: # class of linked list node objects
def __init__(self, data, next=None):
self.data = data
self.next = next
def update_data(self, new_data):
self.data = new_data
def update_next(self, new_next):
self.next = new_next
class LL: # actual linked list
def __init__(self, base_list=[]):
self.head = None
for elem in base_list:
self.head = LL_Node(elem, self.head)
... # other linked list functions
like here's some code that just uses .head
most of the lists you will find do this silly thing where they use self.head on the list itself to be the top node
and then self.head of the node is the value at that node
what's that !r?
oh, nice, never seen that before
so a list of strings would print with quotes
return f'({self.head!r} {self.tail!r})'
ok
don't worry about how this works too much, it was more to help pytest give sensible output than to be part of the example
when you say this is more or less entirely wrong are you referring to the code I sent?
head of a linked list is always a single value
you can see how head is implemented in my case
def head(self):
try:
return self.value.head
except AttributeError:
raise ValueError("head of empty list")
it just returns the head of the top node
in a doubly linked list
it was in response to
ahh
ah, I should've made pop_left
howcome
because now you have two things the head of a list means
and what it actually make sense to mean is the first value of the list
since tail then becomes the second node
first node is just the list itself
hmm
most linked lists don't cache the last elements, that is only really useful for linked list backed queue
what would you call the first node then
data LinkedList a = Node a (LinkedList a) | Nil
the only reason to have separate class from the node itself is if you want a queue
which my example isn't, since I have no poll
ah
the way we defined linked lists in gurklang was literally just 2 long tuples
(head, (element, (next_element, None)))
``` with absolutely no classes
damn why doesn't python do that
because most of the time, you don't need linked lists in python
that is true
and advent of code :P
what's advent of code?
when did you need a linked list for that?
I can't think of too many real algos where that is used
series of short algo problems throughout december, one per day like an advent calender
err i think it was one of the later days, it probably involved inserting in the middle of a list or something? i kind of forget
that seems like a case for a finger tree
though a linked list is probably easier to implement
but the input was large enough that using other things would take way too long
yeah, maybe
I still don't know how linked lists got such a special treatment
a trie is arguably more useful, but most programmers aren't expected to know how to make one
you ever heard of that joke
reversing a linked list
or something like that
I think the other one is like inverting a binary tree or something
class Node(object):
# Each node has its data and a pointer that points to next node in the Linked List
def __init__(self, data, next = None):
self.data = data;
self.next = next;
# function to set data
def setData(self, data):
self.data = data;
whoms't
what does setData even do?
that is just bad code
so skip that ig
you won't get anywhere googling around for a perfect linked list implementation
well, start by making a node class. You saw several already, but write one yourself, actually typing out all the characters
just a basic head tail one
uhhhh
you know what lakmatiol?
what I was looking back at I don't think this person even knows python
class Node(object):
# Each node has its data and a pointer that points to next node in the Linked List
def __init__(self, data, next = None):
self.data = data;
self.next = next;
semi colons after everything????
sus
you could tell from the fact they made a setData function
no competent python programmer makes a setter function
guess you shouldn't just randomly look at someone's github repo for implementations when they don't even know the language
most of the code on the internet is quite bad
wack
so you will find it in older code
are there any alternatives
what do you mean alternatives?
was semi colons after everything ever needed in python?
like things you can put other than option
fuck
things you can put other than object
lmao
that is where you put parent classes, and optionally a metaclass, as well as kwargs for __init_subclass__
what's kwargs....
it is nice if a function has a lot of arguments
yeah it's like type hints but w paramaters
interesting
class Node :
def __init__( self, data ) :
self.data = data
self.next = None
self.prev = None
class LinkedList :
def __init__( self ) :
self.head = None
def add( self, data ) :
node = Node( data )
if self.head == None :
self.head = node
else :
node.next = self.head
node.next.prev = node
self.head = node
ignoring the fact that it's a doubly linked list
what do you guys think of this code?
this is how insertion is written in pseudocode in CLRS
I don't get what they mean by x.next
the next node?
are subclasses just classes below classes?
x.next isn't really explained
I don't get what they mean by x.next
They mean the attributenextofx😛
which for Nodes is a reference to the next node or None
WDYM by that?
what's a field?
mmm, all of this terminology is somewhat hard to explain in Python because it doesn't really have fields like structs in C-like languages do. Basically, by field I mean "attribute that is a value (not a method)"
so yeah, property, field, attribute - basically interchangable.
Of LinkedList instances, yes.
damn so that helper was wrong then
hmm?