Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 8 additions & 12 deletions Binary_tree/tree.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,22 +18,18 @@ def add(self, data):

def _add(self, data, node):
if data < node.data:
if node.left is not None:
self._add(data, node.left)
else:
if node.left is None:
node.left = Node(data)
else:
if node.right is not None:
self._add(data, node.right)
else:
node.right = Node(data)
self._add(data, node.left)
elif node.right is not None:
self._add(data, node.right)
else:
node.right = Node(data)
Comment on lines -21 to +28
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Tree._add refactored with the following changes:


# Method for find the data
def find(self, data):
if self.root is not None:
return self._find(data, self.root)
else:
return None
return self._find(data, self.root) if self.root is not None else None
Comment on lines -33 to +32
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Tree.find refactored with the following changes:


def _find(self, data, node):
if data == node.data:
Expand All @@ -55,6 +51,6 @@ def printTree(self):
def _printTree(self, node):
if node is not None:
self._printTree(node.left)
print(str(node.data) + ' ')
print(f'{str(node.data)} ')
Comment on lines -58 to +54
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function Tree._printTree refactored with the following changes:

self._printTree(node.right)

16 changes: 7 additions & 9 deletions Caesar_Cipher/Caesar_cipher.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,17 +25,15 @@ def encrypt_string(self) -> str:
return(output)

def decrypt_string(self, string: str) -> str:
output = ""
output = ""
string = string.lower()
string = string.strip()
if string == "":
if not (string := string.strip()):
return(self.blank_string)
else:
for c in string:
for k,v in self.key.items():
if v == c:
output += k

for c in string:
for k,v in self.key.items():
if v == c:
output += k

Comment on lines -28 to +36
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function main.decrypt_string refactored with the following changes:

return(output)

if __name__ == "__main__":
Expand Down
3 changes: 1 addition & 2 deletions Caterpillar_Game/Caterpillar.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,7 @@ def outside_window():
top_wall = t.window_height()/2
bottom_wall = -t.window_height()/2
(x,y) = caterpillar.pos()
outside = x < left_wall or x > right_Wall or y > top_wall or y < bottom_wall
return outside
return x < left_wall or x > right_Wall or y > top_wall or y < bottom_wall
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function outside_window refactored with the following changes:


def game_over():
caterpillar.color('yellow')
Expand Down
2 changes: 1 addition & 1 deletion Chinese_FlashCard/app/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ def create_dictionary(datalist=data_list()) -> dict:
""" slice every 4 items
return :: dict with sinograms as key
"""
sino_list = datalist[0::4]
sino_list = datalist[::4]
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function create_dictionary refactored with the following changes:

pinyin_list = datalist[1::4]
role_list = datalist[2::4]
def_list = datalist[3::4]
Expand Down
14 changes: 7 additions & 7 deletions Converter/converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,19 @@

while res.lower() != "q": #program loop
res = res.strip().split(" ")
try:

try:
if len(res) == 1:
print(options[res[0]]) #to display help menu

elif len(res) == 4:
for i in res[3].split(','):
value = round( eval( "{} * {}['{}'] / {}['{}']".format(res[2],res[0],i,res[0],res[1]) ) , 6 ) #calculating
print("{} \t : {}".format(i,value)) #displaying
value = round(eval(f"{res[2]} * {res[0]}['{i}'] / {res[0]}['{res[1]}']"), 6)
print(f"{i} \t : {value}")

else:
print("Invalid command")

Comment on lines -8 to +20
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 8-20 refactored with the following changes:

This removes the following comments ( why? ):

#displaying
#calculating

except:
print("Invalid command")

Expand Down
2 changes: 1 addition & 1 deletion Crud_in_flask/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -74,7 +74,7 @@ def delete(id):
conn.execute('DELETE FROM products WHERE id = ?', (id,))
conn.commit()
conn.close()
flash('"{}" was successfully deleted!'.format(products['title']))
flash(f""""{products['title']}" was successfully deleted!""")
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function delete refactored with the following changes:

return redirect(url_for('index'))


Expand Down
90 changes: 41 additions & 49 deletions Demerge_pdfs/demerging_pdfs.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,62 +2,54 @@
import re
def check_valid_filename(filename):
invalid_chars = r'[/\\:*?"<>|]'
if re.search(invalid_chars, filename):
print('A file name cannot contain any of these characters / \\ : * ? " < > |')
return False
else:
if not re.search(invalid_chars, filename):
return True
print('A file name cannot contain any of these characters / \\ : * ? " < > |')
return False
Comment on lines -5 to +8
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function check_valid_filename refactored with the following changes:


# Note: here instead of Python.pdf you should give the whole path to the pdf if the pdf is not present in the same directory where python program is present
merged_pdf = open('Python.pdf', mode='rb')


pdf = PyPDF2.PdfFileReader(merged_pdf)

(u, ctr, x) = tuple([0]*3)
for i in range(1, pdf.numPages+1):

if u >= pdf.numPages:
print("Successfully done!")
exit(0)

while True:
name = input("Enter the name of the pdf: ")
if check_valid_filename(name) == True:
break

while True:
ctr = input(f"Enter the number of pages for {name}: ")
try:
ctr = int(ctr)
if ctr > 0:
with open('Python.pdf', mode='rb') as merged_pdf:
pdf = PyPDF2.PdfFileReader(merged_pdf)

(u, ctr, x) = tuple([0]*3)
for _ in range(1, pdf.numPages+1):
if u >= pdf.numPages:
print("Successfully done!")
exit(0)

while True:
name = input("Enter the name of the pdf: ")
if check_valid_filename(name) == True:
break
else:
raise ValueError
except ValueError:
print("Page number must be a positive integer")

u += ctr
if u > pdf.numPages:
print('Limit exceeded! ')
break

# Note: In the braces you should give the desired path of where new files should be stored
base_path = '{}.pdf'
# If you want to store the new pdfs in the same directory, then leave the braces empty
path = base_path.format(name)
f = open(path, mode='wb')
pdf_writer = PyPDF2.PdfFileWriter()

for j in range(x, x+ctr):
page = pdf.getPage(j)
pdf_writer.addPage(page)
while True:
ctr = input(f"Enter the number of pages for {name}: ")
try:
ctr = int(ctr)
if ctr > 0:
break
else:
raise ValueError
except ValueError:
print("Page number must be a positive integer")

u += ctr
if u > pdf.numPages:
print('Limit exceeded! ')
break

x += ctr
# Note: In the braces you should give the desired path of where new files should be stored
base_path = '{}.pdf'
# If you want to store the new pdfs in the same directory, then leave the braces empty
path = base_path.format(name)
with open(path, mode='wb') as f:
pdf_writer = PyPDF2.PdfFileWriter()

pdf_writer.write(f)
f.close()
for j in range(x, x+ctr):
page = pdf.getPage(j)
pdf_writer.addPage(page)

x += ctr

merged_pdf.close()
pdf_writer.write(f)
Comment on lines -12 to +54
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 12-62 refactored with the following changes:

print("Successfully done!")
18 changes: 9 additions & 9 deletions Dice_Rolling_Stimulator/dice_stimulator.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,39 +12,39 @@
print("| |")
print("===========")

if number == 2:
elif number == 2:
print("===========")
print("| |")
print("| O O |")
print("| |")
print("===========")

if number == 3:
elif number == 3:
print("===========")
print("| O |")
print("| O |")
print("| O |")
print("===========")
if number == 4:

elif number == 4:
print("===========")
print("| O O |")
print("| |")
print("| O O |")
print("===========")
if number == 5:

elif number == 5:
print("===========")
print("| O O |")
print("| O |")
print("| O O |")
print("===========")
if number == 6:

elif number == 6:
print("===========")
print("| O O |")
print("| O O |")
print("| O O |")
print("===========")

Comment on lines -15 to +49
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 15-49 refactored with the following changes:

  • Simplify conditional into switch-like form (switch)

x = input("Press y to roll again ")
6 changes: 3 additions & 3 deletions Dictionary/dictionary.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,18 +7,18 @@ def translate(word):
if word in data:
return data[word]
elif word.title() in data:
return data[word.title()]
return data[word.title()]
elif word.upper() in data:
return data[word.upper()]
elif len(get_close_matches(word, data.keys())) > 0:
print("did you mean %s instead" %get_close_matches(word, data.keys())[0])
print(f"did you mean {get_close_matches(word, data.keys())[0]} instead")
decide = input("press y for yes or n for no: ")
if decide == "y":
return data[get_close_matches(word, data.keys())[0]]
elif decide == "n":
return("pugger your paw steps on working keys ")
else:
return("You have entered wrong input please enter just y or n")
return("You have entered wrong input please enter just y or n")
Comment on lines -10 to +21
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function translate refactored with the following changes:

else:
print("You have entered wrong keys. Try again")

Expand Down
17 changes: 8 additions & 9 deletions Diff_Utility/diff.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,11 @@
if orignal_contents[line] == changed_contents[line]:
# Ignore if the lines are same.
continue
else:
# Display the changes on the respective lines of the files.
print(f"[bold red][-] Line {line + 1}:[/bold red] {orignal_contents[line]}", end = "")
print(f"[bold green][+] Line {line + 1}:[/bold green] {changed_contents[line]}")

# Show the additions [+] or deletions [-] for the file that is the largest.
if line == len(smallest_sloc) - 1:
for new_line in range(line + 1, len(largest_sloc)):
print(f"{symbol} Line {new_line + 1}:[/bold {color}] {largest_sloc[new_line]}")
# Display the changes on the respective lines of the files.
print(f"[bold red][-] Line {line + 1}:[/bold red] {orignal_contents[line]}", end = "")
print(f"[bold green][+] Line {line + 1}:[/bold green] {changed_contents[line]}")

# Show the additions [+] or deletions [-] for the file that is the largest.
if line == len(smallest_sloc) - 1:
for new_line in range(line + 1, len(largest_sloc)):
print(f"{symbol} Line {new_line + 1}:[/bold {color}] {largest_sloc[new_line]}")
Comment on lines -40 to +47
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 40-48 refactored with the following changes:

24 changes: 19 additions & 5 deletions Egg_Catcher/eggcatcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,10 +30,24 @@
catcher = c.create_arc(catcher_start_x ,catcher_start_y ,catcher_start_x2,catcher_start_y2 , start=200 , extent = 140 , style='arc' , outline=catcher_color , width=3)

score = 0
score_text = c.create_text(10,10,anchor='nw' , font=('Arial',18,'bold'),fill='darkblue',text='Score : ' + str(score))
score_text = c.create_text(
10,
10,
anchor='nw',
font=('Arial', 18, 'bold'),
fill='darkblue',
text=f'Score : {score}',
)

lives_remaning = 3
lives_text = c.create_text(canvas_width-10,10,anchor='ne' , font=('Arial',18,'bold'),fill='darkblue',text='Lives : ' + str(lives_remaning))
lives_text = c.create_text(
canvas_width - 10,
10,
anchor='ne',
font=('Arial', 18, 'bold'),
fill='darkblue',
text=f'Lives : {lives_remaning}',
)
Comment on lines -33 to +50
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 33-36 refactored with the following changes:


eggs = []

Expand All @@ -57,13 +71,13 @@ def egg_dropped(egg):
c.delete(egg)
lose_a_life()
if lives_remaning == 0:
messagebox.showinfo('GAME OVER!' , 'Final Score : ' + str(score))
messagebox.showinfo('GAME OVER!', f'Final Score : {str(score)}')
Comment on lines -60 to +74
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function egg_dropped refactored with the following changes:

win.destroy()

def lose_a_life():
global lives_remaning
lives_remaning -= 1
c.itemconfigure(lives_text , text='Lives : ' + str(lives_remaning))
c.itemconfigure(lives_text, text=f'Lives : {lives_remaning}')
Comment on lines -66 to +80
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function lose_a_life refactored with the following changes:


def catch_check():
(catcher_x,catcher_y,catcher_x2,catcher_y2) = c.coords(catcher)
Expand All @@ -80,7 +94,7 @@ def increase_score(points):
score += points
egg_speed = int(egg_speed * difficulty_factor)
egg_interval = int(egg_interval * difficulty_factor)
c.itemconfigure(score_text , text='Score : ' + str(score))
c.itemconfigure(score_text, text=f'Score : {str(score)}')
Comment on lines -83 to +97
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function increase_score refactored with the following changes:


def move_left(event):
(x1,y1,x2,y2) = c.coords(catcher)
Expand Down
9 changes: 3 additions & 6 deletions Email Slicer/EmailSlicer.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,16 +4,13 @@ def isValidEmail(email):

# Regular expression for validating an Email
regex = r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'

if(re.fullmatch(regex, email)):
return True
else:
return False

return bool((re.fullmatch(regex, email)))
Comment on lines -7 to +8
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Function isValidEmail refactored with the following changes:


email = input("Enter your email id - ")

if isValidEmail(email):
username = email[0:email.index('@')]
username = email[:email.index('@')]
Comment on lines -16 to +13
Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Lines 16-16 refactored with the following changes:

domain = email[email.index('@')+1: ]
print("Username - ", username)
print("Domain - ", domain)
Expand Down
Loading