homepage at https://joeyajames.github.io
joeyajames / python Goto Github PK
View Code? Open in Web Editor NEWPython code for YouTube videos.
License: MIT License
Python code for YouTube videos.
License: MIT License
homepage at https://joeyajames.github.io
Function and Variable Naming: Changed function names and variable names to follow Python's naming conventions (snake_case).
Input Parsing: Changed eval to float for parsing input to ensure safer evaluation of user input.
Output Formatting: Used f-strings for cleaner and more readable output formatting.
Choice Comparison: Changed the comparison to strings ('1', '2', '3') instead of integers to match the input type.
Exit Condition: Changed the exit condition to compare the choice with a string '3' instead of an integer 3.
Main Guard: Added if name == "main": guard to ensure that main() function is executed only when the script is run directly, not when it's imported elsewhere. This is a common best practice in Python.
Line 18 in ba3e6e6
It is directly checked as if lst[1].
This will give error if index does not exist in lst.
Instead, we need to check if len(lst) >= 2 i.e. whether 1st element exists or not.
Python/LinkedLists/LinkedList0.py
Line 24 in ba3e6e6
User is given flexibility to either create linked list with root as None or with a root node given by them.
i.e. size could be 0 or 1
If applicable:
User can also pass root that already has more next nodes.
i.e. size could be n
But, initial size is always set as 0 instead of calculating and setting it as per above logic
Choice Function: Replaced sample with choice for selecting a single random item from a sequence. This simplifies the code when only one random choice is needed.
Pen State Functions: Corrected the function names from pu and pd to penup and pendown, respectively, for clarity and consistency.
Position Copy: Used the copy() method to create a copy of the position vector before modifying it. This prevents unintended changes to the original position vector.
Distance Calculation: Replaced abs(tt.pos() - start_position) with tt.distance(start_position) to calculate the distance between two points more accurately.
Indentation and Formatting: Ensured consistent indentation and formatting throughout the code for readability and maintainability.
Thank you very much for your video and code!
But I actually have one question about your codes time complexity. The following two lines of codes showing that you are using Python slicing to construct the left half and right half:
L = A[first:middle+1]
R = A[middle+1:last+1]
Since the slicing operator is O(k), my question is does the time complexity of the merge sort still be O(nlogn) if we use the Python list slicing in our codes?
Thank you very much!
Is this the right approach ?
class node:
def getHeight(self):
if self is None:
return -1
return 1 + max(self.leftChild.getHeight(), self.rightChild.getHeight())
class Tree:
def getHeight(self):
if self.root:
return self.root.getHeight()
else:
return -1
Either threshold related condition should be removed or threshold should be defined somewhere.
Presentation about OOP concepts is very short and incomplete for someone who wants to learn it.
Hi,
I am starting to get in touch with linked lists and other data structures types,
A part ";" errors I found in the code, the problem is in the newlist [type List] there will be references of objects "nodes" of previous linked lists and not the "data", so I propose to you to use get_data() function which will simplify the code as:
def sort_list(self, reverse_list = True):
if self.size > 1:
temp_list = []
current = self.root
temp_list.append(current.get_data())
while current.has_next_node():
current = current.get_next()
temp_list.append(current.get_data())
temp_list = sorted(temp_list, reverse = reverse_list)
sorted_Linked_List = LinkedList()
for element in temp_list:
sorted_Linked_List.add_node(element)
return sorted_Linked_List
return self
I'n not an expert but i would like to know if there wasn't better to type the init method like this:
class Shape:
def init(self, color=None):
if color == None:
self.color = ""
else:
self.color = color
since the input for color is expected to be a string type
@joeyajames i want to add some new snippets on OOPs
In this project, if the user inputs a text with alpabetic characters as the choice variable, it gives an error. Even if the choice is 1 or 2, if the user inputs a alphabetic string, it gives an error as well. So, we need to check the user's answer and respond accordingly, so that it doesn't give an error.
Thanks for your notebook and YT video's. Now a days I believe you need a key for accessing the api. Maybe use another website as example
Line 52 in ba3e6e6
It is going to each hash location, checking if pairs exist and returning the 0th pairs.
It needs to go to each hash location, check if pairs exist and loop over each pair and return their 0th element i.e. the keys.
I am making one text file for contributing file for those who intend to contribute to this repository.
Hi,
I am experiencing delay in transferring files from one USB drive to another USB drive using python code.
Initially transferring of files from the USB drive takes place very fast and gradually slow down to 10 kbps.
Is there any way to slowing down the file transfer process.
My python code is given below
import os
import shutil
directory = "name of the new directory"
dir_create = "Path of the destination directory" #destination directory
path = os.path.join(dir_create, directory)
os.mkdir(path) # create a new directory
dir_dst = "Path of the new destination directory"
dir_src = "Path of the Source directory" # .csv data file source directory
for filename in os.listdir(dir_src):
if filename.endswith('.csv'):
shutil.copy(dir_src + filename, dir_dst)
Hello,
How can I call the added list (created list)?
high_temps = []
for row in rows:
tds = row.find_all('td')
for i in range(1,7):
high_temps.append(tds[i].text)
print(high_temps)
IndexError Traceback (most recent call last)
in ()
8 tds = row.find_all('td')
9 for i in range(1,7):
---> 10 high_temps.append(tds[i].text)
11 print(high_temps)
IndexError: list index out of range
I don't believe the else statement self.root = this_node
in the below remove
function is correct. If there is no previous node, that means you are at the root; and the root should be set to next
not this_node
def remove (self, d):
this_node = self.root
while this_node:
if this_node.get_data() == d:
next = this_node.get_next()
prev = this_node.get_prev()
if next:
next.set_prev(prev)
if prev:
prev.set_next(next)
else:
self.root = this_node
self.size -= 1
return True # data removed
else:
this_node = this_node.get_next()
return False # data not found
In Sorting Algorithms/quick_sort.py
Please consider changing arguments names to meet the snake case rolls and also do not use names like A
due to the Shadows name 'A' from outer scope
Hi,
I am starting to get in touch with linked lists and other data structures types,
A part ";" errors I found in the code, the problem is in the newlist [type List] there will be references of objects "nodes" of previous linked lists and not the "data", so I propose to you to use get_data() function which will simplify the code as:
def sort_list(self, reverse_list = True):
if self.size > 1:
temp_list = []
current = self.root
temp_list.append(current.get_data())
while current.has_next_node():
current = current.get_next()
temp_list.append(current.get_data())
temp_list = sorted(temp_list, reverse = reverse_list)
sorted_Linked_List = LinkedList()
for element in temp_list:
sorted_Linked_List.add_node(element)
return sorted_Linked_List
return self
@joeyajames The code of matplotlib library as well as pandas library is not executing since there is a typo mistake in code . Please assign me this issue .
Naming Conventions: Renamed private methods to follow Python's naming conventions (snake_case).
Returning None: Changed the return value of peek and pop methods to None instead of False for clarity. In Python, None is typically used to indicate the absence of a value.
Use of Dummy Element: Initialized the heap with a dummy element at index 0 to simplify index calculations. This helps in avoiding special cases in the code.
Output Formatting: Changed the output printing to exclude the dummy element when printing the heap elements.
The reason for the error is that the key 'avg_high' can't be found because it has been changed to 'av_hi'.
Here is the link to the file:
https://github.com/joeyajames/Python/blob/master/Pandas/pandas_weather.py
Here is the output:
--------------------------------------------------
[ 11. iterate rows of df with a for loop ]
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
4409 try:
-> 4410 return libindex.get_value_at(s, key)
4411 except IndexError:
pandas/_libs/index.pyx in pandas._libs.index.get_value_at()
pandas/_libs/index.pyx in pandas._libs.index.get_value_at()
pandas/_libs/util.pxd in pandas._libs.util.get_value_at()
pandas/_libs/util.pxd in pandas._libs.util.validate_indexer()
TypeError: 'str' object cannot be interpreted as an integer
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-14-1fc7b7226e62> in <module>
2 header("11. iterate rows of df with a for loop")
3 for index, row in df.iterrows():
----> 4 print (index, row["month"], row["avg_high"])
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/series.py in __getitem__(self, key)
869 key = com.apply_if_callable(key, self)
870 try:
--> 871 result = self.index.get_value(self, key)
872
873 if not is_scalar(result):
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
4416 raise InvalidIndexError(key)
4417 else:
-> 4418 raise e1
4419 except Exception:
4420 raise e1
~/opt/anaconda3/lib/python3.7/site-packages/pandas/core/indexes/base.py in get_value(self, series, key)
4402 k = self._convert_scalar_indexer(k, kind="getitem")
4403 try:
-> 4404 return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
4405 except KeyError as e1:
4406 if len(self) > 0 and (self.holds_integer() or self.is_boolean()):
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_value()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'avg_high'
Hi,
I am starting to get in touch with linked lists and other data structures types,
A part ";" errors I found in the code, the problem is in the newlist [type List] there will be references of objects "nodes" of previous linked lists and not the "data", so I propose to you to use get_data() function when appending data to the temporary list instead of node object references which will simplify the code as below:
def sort_list(self, reverse_list = True):
if self.size > 1:
temp_list = []
current = self.root
temp_list.append(current.get_data())
while current.has_next_node():
current = current.get_next()
temp_list.append(current.get_data())
temp_list = sorted(temp_list, reverse = reverse_list)
sorted_Linked_List = LinkedList()
for element in temp_list:
sorted_Linked_List.add_node(element)
return sorted_Linked_List
return self
Can you consider change the position of
self.edges.append([0] * (len(self.edges)+1))
after this line
self.vertices[vertex.name] = vertex
Since
self.edges.append([0] * (len(self.edges)+1))
is for initializing the matrix to zeros. Especially, adding the first edge, it is not easy to understand. Because when this line changes position it follows the initializing, appending new initialized edges, fill the weight number logic. That will be more easy for comprehension.
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.