Skip to content

Commit 0fdbcbc

Browse files
author
majid shahbaz
committed
1. DSA
2. Sorting 3. Searching 4. Stack 5. Linked List
1 parent 34539dc commit 0fdbcbc

File tree

17 files changed

+1366
-4
lines changed

17 files changed

+1366
-4
lines changed

README.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -210,6 +210,7 @@
210210
4.5.7.2. Intersection Operator (&)
211211
4.5.7.3. Difference Operator (-)
212212
4.5.7.4. Symmetric Difference Operator (^)
213+
213214
#### [4.6. Conditional Statements](https://github.com/Majid460/python_practice_part1/blob/main/src/basic/conditional)
214215
4.6.1. Python Logical Conditions
215216
4.6.1.1. Comparison Operators (==, !=, <, <=, >, >=)
Lines changed: 162 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,162 @@
1+
"""
2+
File handling is an important part of any web application.
3+
4+
Python has several functions for creating, reading, updating, and deleting files.
5+
6+
File Handling
7+
The key function for working with files in Python is the open() function.
8+
The open() function takes two parameters; filename, and mode.
9+
There are four different methods (modes) for opening a file:
10+
11+
"r" - Read - Default value. Opens a file for reading, error if the file does not exist
12+
"a" - Append - Opens a file for appending, creates the file if it does not exist
13+
"w" - Write - Opens a file for writing, creates the file if it does not exist
14+
"x" - Create - Creates the specified file, returns an error if the file exists
15+
16+
In addition you can specify if the file should be handled as binary or text mode
17+
"t" - Text - Default value. Text mode
18+
"b" - Binary - Binary mode (e.g. images)
19+
20+
21+
"""
22+
# 1. To open a file use open()
23+
file = open("test.txt","rt") # Because "r" for read, and "t" for text are the default values, you do not need to specify them.
24+
print(file.read())
25+
file.close()
26+
"""
27+
Q. What is life?
28+
A. Life is temporary environment to execute certain tasks.
29+
"""
30+
# 2. Open with "with"
31+
"""
32+
Then you do not have to worry about closing your files, the with statement takes care of that.
33+
"""
34+
with open("test.txt","rt") as f:
35+
print(f.read())
36+
37+
"""
38+
Q. What is life?
39+
A. Life is temporary environment to execute certain tasks.
40+
"""
41+
"""
42+
Note: You should always close your files. In some cases, due to buffering, changes made to a file may not show until you close the file.
43+
"""
44+
45+
# 3. Read Only Parts of the File
46+
"""
47+
48+
By default the read() method returns the whole text, but you can also specify how many characters you want to return:
49+
"""
50+
with open("test.txt","rt") as f:
51+
print(f.read(5))
52+
# Reads first 5 characters
53+
# Q. Wh
54+
55+
# 4. Read lines
56+
with open("test.txt","rt") as f:
57+
print(f.readline()) # Reads first line
58+
59+
#By calling readline() two times, you can read the two first lines:
60+
61+
"""Example
62+
Read two lines of the file:
63+
"""
64+
65+
with open("test.txt") as f:
66+
print(f.readline())
67+
print(f.readline())
68+
69+
#By looping through the lines of the file, you can read the whole file, line by line:
70+
71+
"""Example
72+
Loop through the file line by line:"""
73+
74+
with open("test.txt") as f:
75+
for x in f:
76+
print(x)
77+
78+
# Read second line
79+
with open("test.txt") as f:
80+
lines = f.readlines()
81+
if len(lines)>=2:
82+
print(f"second line:: {lines[1]}")
83+
# second line:: A. Life is temporary environment to execute certain tasks.
84+
85+
# Read last line
86+
with open("test.txt") as f:
87+
lines = f.readlines()
88+
print(f"last line:: {lines[len(lines)-1]}")
89+
# second line:: Q. How?
90+
91+
### Write to file
92+
print("-------------------Write in file------------------")
93+
"""
94+
Write to an Existing File
95+
To write to an existing file, you must add a parameter to the open() function:
96+
97+
"a" - Append - will append to the end of the file
98+
99+
"w" - Write - will overwrite any existing content
100+
"""
101+
# with open("test.txt","w") as f:
102+
# f.write("Because life is harsh")
103+
# #open and read the file after the appending:
104+
# with open("test.txt") as f:
105+
# print(f.read())
106+
107+
# with open("test.txt","a") as f:
108+
# f.write("A. Because life is harsh.\n")
109+
# #open and read the file after the appending:
110+
# with open("test.txt") as f:
111+
# print(f.read())
112+
113+
114+
print("-------------------Create a new file------------------")
115+
116+
# with open("newfile.txt","x") as f:
117+
# f.write("Hey new file is created \n")
118+
119+
# Remove a file
120+
import os
121+
# os.remove("newfile.txt")
122+
123+
# if os.path.exists("newfile.txt"):
124+
# os.remove("newfile.txt")
125+
# else:
126+
# print("The file does not exist")
127+
128+
print("------------------- Json Handling ------------------")
129+
"""
130+
JSON (JavaScript Object Notation)
131+
132+
- A standard data interchange format supported in Python via the json module.
133+
- Serialization = converting Python objects → JSON string.
134+
- Deserialization = converting JSON string → Python object.
135+
- JSON is widely used for data exchange and is interoperable across languages.
136+
"""
137+
138+
import json
139+
140+
# To convert a dict to json use dumps
141+
142+
x = {
143+
"name":"Test",
144+
"age":20
145+
}
146+
"""The json.dumps() method has parameters to order the keys in the result:
147+
148+
Example
149+
Use the sort_keys parameter to specify if the result should be sorted or not:"""
150+
151+
y = json.dumps(x, indent=4, sort_keys=True)
152+
print(y)
153+
"""
154+
{
155+
"age": 20,
156+
"name": "Test"
157+
}
158+
"""
159+
160+
# Convert json to dict
161+
js = json.loads(y)
162+
print(js)

src/basic/filehandling/newfile.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Hey new file is created

src/basic/filehandling/test.txt

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
Q. What is life?
2+
A. Life is temporary environment to execute certain tasks.
3+
Q. How?
4+
A. Because life is harsh.
5+
A. Because life is harsh.
6+
A. Because life is harsh.

src/basic/functions/functions.py

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -129,19 +129,18 @@ def myfunction():
129129
def cal_area(length,width,/):
130130
return length*width
131131

132-
#area = cal_area(lenght = 10,width = 20)
132+
#area = cal_area(length = 10,width = 20)
133133
#print(f"Area is :: {area}")
134134

135135
# We will get error because we have to pass positional arguments just not any keyword argument
136136
"""
137-
area = cal_area(lenght = 10,width = 20)
137+
area = cal_area(length = 10,width = 20)
138138
Error:
139139
Traceback (most recent call last):
140140
File "/Users/macbookpro/Documents/Python Practice/python_practice_part1/src/basic/functions/functions.py", line 132, in <module>
141-
area = cal_area(lenght = 10,width = 20)
141+
area = cal_area(length = 10,width = 20)
142142
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
143143
TypeError: cal_area() got some positional-only arguments passed as keyword arguments: 'width'
144-
145144
"""
146145

147146
# To fix it we need to pass only positional because we have used forward slash (/) right after the end of arguments

src/basic/functions/lambda.py

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
"""
2+
A lambda function is a small anonymous function.
3+
4+
A lambda function can take any number of arguments, but can only have one expression.
5+
6+
lambda arguments : expression
7+
"""
8+
# a represents the arguments
9+
10+
x= lambda a:a+4
11+
print(x(2))
12+
13+
# 6
14+
15+
def add(a):
16+
return lambda y:y+a
17+
18+
lam = add(2) # It returns the inner lambda function
19+
20+
print(lam(2))
21+
# 4
22+
Lines changed: 137 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,137 @@
1+
"""
2+
A Linked List is, as the word implies, a list where the nodes are linked together. Each node contains data and a pointer.
3+
The way they are linked together is that each node points to where in the memory the next node is placed.
4+
5+
6+
Linked Lists
7+
A linked list consists of nodes with some sort of data, and a pointer, or link, to the next node.
8+
9+
[data|next] -> [data|next] -> [data|next] -> [data|next] -> null
10+
11+
A singly linked list.
12+
A big benefit with using linked lists is that nodes are stored wherever there is free space in memory, the nodes do not have to be stored contiguously right after each other like elements are stored in arrays. Another nice thing with linked lists is that when adding or removing nodes, the rest of the nodes in the list do not have to be shifted.
13+
"""
14+
from src.basic.datatypes.casting.casting import height
15+
16+
17+
# Singly linklist
18+
class Node:
19+
def __init__(self, data):
20+
self.data = data
21+
self.next = None
22+
self.prev = None # Only for doubly
23+
24+
25+
class LinkList:
26+
def __init__(self):
27+
self.head = None
28+
29+
def add_node(self, data):
30+
new_node = Node(data)
31+
32+
if self.head is None:
33+
self.head = new_node
34+
return
35+
current_node = self.head
36+
while current_node.next is not None:
37+
current_node = current_node.next
38+
current_node.next = new_node
39+
40+
def display(self):
41+
current_node = self.head
42+
while current_node is not None:
43+
print(current_node.data, end=" -> ")
44+
current_node = current_node.next
45+
print("null")
46+
47+
48+
# Doubly linklist
49+
class DoublyLinkList:
50+
51+
def __init__(self):
52+
self.head = None
53+
self.tail = None
54+
55+
def add_node(self, data):
56+
new_node = Node(data)
57+
58+
if self.head is None:
59+
self.head = self.tail = new_node
60+
return
61+
self.tail.next = new_node
62+
new_node.prev = self.tail
63+
self.tail = new_node
64+
65+
def print_forward(self):
66+
current = self.head
67+
while current:
68+
print(current.data, end=" -> ")
69+
current = current.next
70+
print("None")
71+
72+
def print_backward(self):
73+
current = self.tail
74+
while current:
75+
print(current.data, end=" -> ")
76+
current = current.prev
77+
print("None")
78+
79+
80+
# Circular Single linklist
81+
class CircularLinkList:
82+
def __init__(self):
83+
self.head = None
84+
85+
def add_node(self, data):
86+
new_node = Node(data)
87+
88+
if self.head is None:
89+
self.head = new_node
90+
new_node.next = self.head
91+
return
92+
current = self.head
93+
while current.next is not self.head:
94+
current = current.next
95+
current.next = new_node
96+
new_node.next = self.head
97+
98+
def display(self, count):
99+
if not self.head:
100+
print("List is empty")
101+
return
102+
current = self.head
103+
i = 0
104+
lowest = current.data
105+
while i < count:
106+
if current.data < lowest:
107+
lowest = current.data
108+
print(current.data, end=" -> ")
109+
current = current.next
110+
i += 1
111+
print("None", end=" \n")
112+
print(f"Lowest value is: {lowest}", end="\n")
113+
114+
115+
if __name__ == '__main__':
116+
# Singly
117+
print("---------------------- Singly ------------------------", end="\n")
118+
linkList = LinkList()
119+
linkList.add_node(1)
120+
linkList.add_node(2)
121+
linkList.add_node(3)
122+
linkList.display()
123+
# Doubly
124+
print("---------------------- Doubly ------------------------", end="\n")
125+
doubly = DoublyLinkList()
126+
doubly.add_node(11)
127+
doubly.add_node(12)
128+
doubly.add_node(13)
129+
doubly.print_forward()
130+
doubly.print_backward()
131+
# Circular
132+
print("---------------------- Circular ------------------------", end="\n")
133+
circular = CircularLinkList()
134+
circular.add_node(111)
135+
circular.add_node(112)
136+
circular.add_node(113)
137+
circular.display(4)

0 commit comments

Comments
 (0)