From 24d5068713f39619a23ce4e5059ae8f2b6585c0f Mon Sep 17 00:00:00 2001
From: Sourcery AI <>
Date: Thu, 29 Sep 2022 10:59:31 +0000
Subject: [PATCH] 'Refactored by Sourcery'
---
.../Deleting record in a binary file.py | 6 +-
.../Update a binary file.py | 39 +++--
.../Update a binary file2.py | 42 +++--
...on 1 (elegible for remedial, top marks).py | 83 +++++-----
.../search record in binary file.py | 25 ++-
.../input,output and error streams.py | 7 +-
.../special symbol after word.py | 27 ++--
A solution to project euler problem 3.py | 4 +-
AreaOfTriangle.py | 2 +-
Assembler/assembler.py | 7 +-
Automated Scheduled Call Reminders/caller.py | 2 +-
Base Converter Number system.py | 41 ++---
Battery_notifier.py | 5 +-
Binary Coefficients.py | 13 +-
Binary_search.py | 2 +-
BlackJack_game/blackjack.py | 26 ++-
BlackJack_game/blackjack_rr.py | 21 ++-
BlackJack_game/blackjack_simulate.py | 52 +++---
BoardGame-CLI/snakeLadder.py | 2 +-
BoardGame-CLI/uno.py | 55 +++----
BruteForce.py | 19 +--
CRC/crc.py | 6 +-
Caesar Cipher Encoder & Decoder.py | 31 ++--
Calculate resistance.py | 5 +-
Cat/cat.py | 7 +-
Checker_game_by_dz/modules/checker.py | 8 +-
Checker_game_by_dz/modules/checker_board.py | 27 +---
Classification_human_or_horse.py | 4 +-
Collatz-Conjecture.py | 2 +-
Colors/pixel_sort.py | 33 ++--
Colors/primary_colors.py | 142 +++++------------
Compression_Analysis/PSNR.py | 5 +-
Conversation.py | 7 +-
CountMillionCharacter.py | 9 +-
Credit_Card_Validator.py | 24 ++-
Cricket_score.py | 20 ++-
Day_of_week.py | 2 +-
Decimal_To_Binary.py | 14 +-
Delete_Linked_List.py | 7 +-
Detect_Remove_loop.py | 2 +-
Eight_Puzzle_Solver/eight_puzzle.py | 118 +++++---------
Emoji Dictionary/emoji_dictionary.py | 8 +-
EncryptionTool.py | 65 ++++----
.../mask_detection.py | 6 +-
Factorial.py | 6 +-
Fibonacci_sequence_recursive_sol.py | 5 +-
.../Background.py | 46 +++---
Flappy Bird - created with tkinter/Bird.py | 2 +-
.../Flappy Bird.py | 30 ++--
.../Settings.py | 27 ++--
Flappy Bird - created with tkinter/Tubes.py | 41 ++---
Google_Image_Downloader/image_grapper.py | 34 ++--
Gregorian_Calendar.py | 10 +-
GroupSms_Way2.py | 3 +-
Guessing_Game.py | 2 +-
.../hand_motion_recognizer.py | 22 +--
Hotel-Management.py | 96 +++++-------
ImageDownloader/img_downloader.py | 2 +-
Infix_to_Postfix.py | 11 +-
JARVIS/JARVIS.py | 9 +-
Job_scheduling.py | 12 +-
JustDialScrapperGUI/Justdial Scrapper GUI.py | 148 +++++++++---------
Koch Curve/koch curve.py | 2 +-
Letter_Counter.py | 2 +-
List.py | 3 +-
Luhn_Algorithm.py | 10 +-
Memory_game.py | 4 +-
MobiusFunction.py | 12 +-
Number reverse.py | 4 +-
Organise.py | 43 +++--
PDF/header_footer.py | 3 +-
PDF/images.py | 2 +-
PONG_GAME.py | 10 +-
Password Generator/pass_gen.py | 18 +--
Patterns/pattern1.py | 2 +-
Patterns/pattern2.py | 2 +-
Patterns/patterns.py | 8 +-
PongPong_Game/pong/load.py | 12 +-
Prime_number.py | 20 +--
Print_List_of_Even_Numbers.py | 7 +-
Print_List_of_Odd_Numbers.py | 4 +-
Program of Reverse of any number.py | 2 +-
...everse Linked List( Recursive solution).py | 4 +-
QR_code_generator/qrcode.py | 2 +-
QuadraticCalc.py | 6 +-
RandomNumberGame.py | 9 +-
Recursion Visulaizer/recursionVisualizer.py | 83 +++++-----
SOUNDEX.py | 9 +-
Shivaansh.py | 2 +-
Snake-Water-Gun-Game.py | 16 +-
Snake_water_gun/main.py | 6 +-
Sorting Algorithims/Bubble_sort.py | 4 +-
Sorting Algorithims/Count sort.py | 2 +-
Sorting Algorithims/Counting Sort.py | 4 +-
Sorting Algorithims/Counting-sort.py | 2 +-
Sorting Algorithims/Cycle Sort.py | 4 +-
Sorting Algorithims/Iterative Merge Sort.py | 8 +-
Sorting Algorithims/Merge Sort.py | 4 +-
Sorting Algorithims/Merge-sort.py | 14 +-
... values of first list using second list.py | 4 +-
Sorting Algorithims/Tim_sort.py | 6 +-
Sorting Algorithims/brickSort.py | 4 +-
Sorting Algorithims/bubblesortpgm.py | 6 +-
Sorting Algorithims/merge_sort.py | 39 +++--
Sorting Algorithims/selectionSort.py | 4 +-
Sorting Algorithims/sorting.py | 10 +-
Sorting Algorithims/stooge_sort.py | 2 +-
Sorting Algorithims/wave_sort.py | 2 +-
StringToBinary.py | 11 +-
Swap numbers.py | 14 +-
Test-Case-Generator/test_case.py | 27 ++--
TicTacToe.py | 103 +++++-------
Tic_Tac_Toe.py | 83 ++++------
Timetable_Operations.py | 10 +-
To print series 1,12,123,1234......py | 5 +-
.../find_Triplets_with_zero_sum.py | 2 +-
Tweet Pre-Processing.py | 7 +-
Type of angles of a triangle.py | 28 +---
Type_of_angles_of_triangle.py | 26 +--
.../VoiceAssistant_main.py | 18 +--
.../Project_Basic_struct/dictator.py | 2 +-
.../Project_Basic_struct/speakListen.py | 27 ++--
.../Project_Basic_struct/textRead.py | 79 +++++-----
.../Project_Basic_struct/websiteWork.py | 8 +-
VoiceRepeater/__main__.py | 4 +-
Weather Scrapper/weather.py | 2 +-
WeatherGUI.py | 2 +-
WikipediaModule.py | 9 +-
Windows_Wallpaper_Script/wallpaper_extract.py | 13 +-
Wordle/wordle.py | 24 +--
XORcipher/XOR_cipher.py | 32 +---
Youtube Downloader With GUI/main.py | 2 +-
addition.py | 2 +-
alexa_news_headlines.py | 4 +-
area_of_square.py | 2 +-
async_downloader/async_downloader.py | 24 +--
backup_automater_services.py | 3 +-
balance_parenthesis.py | 30 ++--
bank_managment_system/backend.py | 74 +++------
bank_managment_system/frontend.py | 3 +-
batch_file_rename.py | 4 +-
binary_search_tree.py | 132 ++++++++--------
binod.py | 7 +-
birthdays.py | 4 +-
blackJackGUI.py | 11 +-
blackjack.py | 26 ++-
bookstore_manangement_system.py | 20 +--
brickout-game/brickout-game.py | 37 ++---
calc_area.py | 14 +-
calculator-gui.py | 4 +-
calculator.py | 19 +--
changemac.py | 14 +-
chaos.py | 4 +-
check_file.py | 6 +-
check_for_sqlite_files.py | 12 +-
check_internet_con.py | 6 +-
check_prime.py | 20 +--
classicIndianCardMatch.py | 12 +-
consonant.py | 8 +-
conversion.py | 11 +-
convert_time.py | 5 +-
coronacases.py | 5 +-
currency converter/main.py | 2 +-
daily_checks.py | 2 +-
date-timeclient.py | 2 +-
date-timeserver.py | 2 +-
days_from_date.py | 2 +-
diceV2_dynamic.py | 20 ++-
diction.py | 2 +-
dir_test.py | 4 +-
divisors_of_a_number.py | 4 +-
email id dictionary/dict1.py | 4 +-
encrypter-decrypter-gui.py | 2 +-
encryptsys.py | 64 ++------
env_check.py | 6 +-
ex20.py | 27 ++--
facebook id hack.py | 4 +-
facebook-autologin-bot.py | 52 +++---
factor.py | 5 +-
factorial_perm_comp.py | 6 +-
factors.py | 2 +-
fibonacci.py | 2 +-
fileinfo.py | 6 +-
find_cube_root.py | 9 +-
find_prime.py | 5 +-
finding LCM.py | 6 +-
flappyBird_pygame/flappy_bird.py | 2 +-
floodfill/floodfill.py | 10 +-
folder_size.py | 7 +-
ftp_send_receive.py | 4 +-
gambler.py | 6 +-
game_of_life/game_o_life.py | 16 +-
gcd.py | 3 +-
get_crypto_price.py | 12 +-
get_info_remoute_srv.py | 5 +-
get_likes_on_FB.py | 27 +---
get_youtube_view.py | 5 +-
google.py | 10 +-
googlemaps.py | 13 +-
googleweb.py | 19 +--
happy_num.py | 37 +++--
image2pdf/image2pdf.py | 4 +-
input matrice,product any order!.py | 12 +-
insertion_sort.py | 6 +-
insta_monitering/insta_api.py | 18 +--
insta_monitering/insta_datafetcher.py | 52 +++---
insta_monitering/subpinsta.py | 2 +-
internet_connection_py3.py | 2 +-
invisible_clock.py | 2 +-
jee_result.py | 4 +-
kmp_str_search.py | 2 +-
lcm.py | 6 +-
length.py | 2 +-
levenshtein_distance.py | 22 +--
linear-algebra-python/src/lib.py | 120 ++++++--------
linear_search.py | 2 +-
loader.py | 2 +-
.../local_weighted_learning.py | 6 +-
logs.py | 8 +-
magic8ball.py | 2 +-
mapit.py | 2 +-
meme_maker.py | 6 +-
memorygame.py | 2 +-
merge.py | 4 +-
mobilePhoneSpecsScrapper.py | 18 +--
move_files_over_x_days.py | 11 +-
nasa_apod_with_requests/run.py | 10 +-
new.py | 11 +-
new_pattern.py | 2 +-
new_script.py | 29 ++--
news_articles__scraper.py | 7 +-
next_number.py | 9 +-
nmap_scan.py | 4 +-
notepad/notepad_support.py | 2 +-
nslookup_check.py | 4 +-
oneeven.py | 5 +-
other_pepole/get_ip_gui | 4 +-
passwordGen.py | 4 +-
password_checker.py | 4 +-
password_cracker.py | 10 +-
password_manager.py | 32 ++--
ph_email.py | 13 +-
ping_servers.py | 14 +-
ping_subnet.py | 16 +-
portscanner.py | 4 +-
powerdown_startup.py | 24 ++-
powerup_checks.py | 56 +++----
primelib/primelib.py | 52 ++----
prison_break_scrapper.py | 16 +-
pscheck.py | 2 +-
psunotify.py | 16 +-
puttylogs.py | 8 +-
pyauto.py | 2 +-
pythonVideoDownloader.py | 11 +-
python_sms.py | 4 +-
quote.py | 5 +-
random-sentences.py | 17 +-
random_file_move.py | 2 +-
randomloadingmessage.py | 2 +-
rangoli.py | 4 +-
rearrange-files/rearrange-files.py | 16 +-
recursive-fibonacci.py | 5 +-
recyclebin.py | 13 +-
rock_paper_scissor_game.py | 6 +-
rook.py | 7 +-
rotate_string.py | 8 +-
rotatelist.py | 11 +-
russian_roulette.py | 16 +-
scalg.py | 7 +-
scrap_file.py | 7 +-
script_count.py | 4 +-
sendemail.py | 14 +-
sensors_information.py | 9 +-
serial_scanner.py | 23 ++-
sha1.py | 7 +-
simulate_memory_cpu.py | 11 +-
singly_linked_list.py | 2 +-
snake.py | 26 ++-
socket-programming/client.py | 4 +-
socket-programming/server.py | 7 +-
soundex_algorithm.py | 14 +-
spiralmatrix.py | 7 +-
spotifyAccount.py | 25 ++-
sqlite_check.py | 6 +-
sqlite_table_check.py | 14 +-
stack.py | 14 +-
stackF_Harsh2255.py | 16 +-
stone_paper_scissor/main.py | 2 +-
stone_paper_scissor/utils.py | 19 +--
string_rotation.py | 6 +-
sudoku.py | 9 +-
swap.py | 14 +-
text_file_replace.py | 2 +-
tf_idf_generator.py | 54 +++----
.../mustache-add-on-face.py | 4 +-
.../utils.py | 4 +-
thread_signal.py | 5 +-
tic-tac-toe.py | 5 +-
tic_tak_toe.py | 34 +---
tik_tak.py | 5 +-
time_delta.py | 2 +-
translation_of_sizes_of_underwear_RU.py | 10 +-
tweeter.py | 28 ++--
ultimate-phone-book/contacts.py | 71 ++++-----
vowels.py | 5 +-
wiki_random.py | 2 +-
work_connect.py | 47 +++---
307 files changed, 1892 insertions(+), 2898 deletions(-)
diff --git a/1 File handle/File handle binary/Deleting record in a binary file.py b/1 File handle/File handle binary/Deleting record in a binary file.py
index dca55c2d140..41a5007b86c 100644
--- a/1 File handle/File handle binary/Deleting record in a binary file.py
+++ b/1 File handle/File handle binary/Deleting record in a binary file.py
@@ -10,11 +10,7 @@ def bdelete():
# Deleting the Roll no. entered by user
rno = int(input("Enter the Roll no. to be deleted: "))
with open("studrec.dat") as F:
- rec = []
- for i in stud:
- if i[0] == rno:
- continue
- rec.append(i)
+ rec = [i for i in stud if i[0] != rno]
pickle.dump(rec, F)
diff --git a/1 File handle/File handle binary/Update a binary file.py b/1 File handle/File handle binary/Update a binary file.py
index 19f16b955da..1f766cf6f0a 100644
--- a/1 File handle/File handle binary/Update a binary file.py
+++ b/1 File handle/File handle binary/Update a binary file.py
@@ -4,30 +4,27 @@
def update():
- F = open("class.dat", "rb+")
- S = pickle.load(F)
- found = 0
- rno = int(input("enter the roll number you want to update"))
- for i in S:
- if rno == i[0]:
- print("the currrent name is", i[1])
- i[1] = input("enter the new name")
- found = 1
- break
+ with open("class.dat", "rb+") as F:
+ S = pickle.load(F)
+ found = 0
+ rno = int(input("enter the roll number you want to update"))
+ for i in S:
+ if rno == i[0]:
+ print("the currrent name is", i[1])
+ i[1] = input("enter the new name")
+ found = 1
+ break
- if found == 0:
- print("Record not found")
+ if found == 0:
+ print("Record not found")
- else:
- F.seek(0)
- pickle.dump(S, F)
-
- F.close()
+ else:
+ F.seek(0)
+ pickle.dump(S, F)
update()
-F = open("class.dat", "rb")
-val = pickle.load(F)
-print(val)
-F.close()
+with open("class.dat", "rb") as F:
+ val = pickle.load(F)
+ print(val)
diff --git a/1 File handle/File handle binary/Update a binary file2.py b/1 File handle/File handle binary/Update a binary file2.py
index 26fb365e687..0f4f723e27a 100644
--- a/1 File handle/File handle binary/Update a binary file2.py
+++ b/1 File handle/File handle binary/Update a binary file2.py
@@ -4,28 +4,26 @@
def update():
- F = open("studrec.dat", "rb+")
- value = pickle.load(F)
- found = 0
- roll = int(input("Enter the roll number of the record"))
- for i in value:
- if roll == i[0]:
- print("current name", i[1])
- print("current marks", i[2])
- i[1] = input("Enter the new name")
- i[2] = int(input("Enter the new marks"))
- found = 1
-
- if found == 0:
- print("Record not found")
-
- else:
- pickle.dump(value, F)
- F.seek(0)
- newval = pickle.load(F)
- print(newval)
-
- F.close()
+ with open("studrec.dat", "rb+") as F:
+ value = pickle.load(F)
+ found = 0
+ roll = int(input("Enter the roll number of the record"))
+ for i in value:
+ if roll == i[0]:
+ print("current name", i[1])
+ print("current marks", i[2])
+ i[1] = input("Enter the new name")
+ i[2] = int(input("Enter the new marks"))
+ found = 1
+
+ if found == 0:
+ print("Record not found")
+
+ else:
+ pickle.dump(value, F)
+ F.seek(0)
+ newval = pickle.load(F)
+ print(newval)
update()
diff --git a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py
index 08ac16f3e32..68580d1985e 100644
--- a/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py
+++ b/1 File handle/File handle binary/question 1 (elegible for remedial, top marks).py
@@ -8,70 +8,67 @@
"""
+
# also find no. of children who got top marks
import pickle
-F = open("class.dat", "ab")
-list = [
- [1, "Ramya", 30],
- [2, "vaishnavi", 60],
- [3, "anuya", 40],
- [4, "kamala", 30],
- [5, "anuraag", 10],
- [6, "Reshi", 77],
- [7, "Biancaa.R", 100],
- [8, "sandhya", 65],
-]
+with open("class.dat", "ab") as F:
+ list = [
+ [1, "Ramya", 30],
+ [2, "vaishnavi", 60],
+ [3, "anuya", 40],
+ [4, "kamala", 30],
+ [5, "anuraag", 10],
+ [6, "Reshi", 77],
+ [7, "Biancaa.R", 100],
+ [8, "sandhya", 65],
+ ]
-pickle.dump(list, F)
-F.close()
+ pickle.dump(list, F)
def remcount():
- F = open("class.dat", "rb")
- val = pickle.load(F)
- count = 0
+ with open("class.dat", "rb") as F:
+ val = pickle.load(F)
+ count = 0
- for i in val:
- if i[2] <= 40:
- print(i, "eligible for remedial")
- count += 1
- print("the total number of students are", count)
- F.close()
+ for i in val:
+ if i[2] <= 40:
+ print(i, "eligible for remedial")
+ count += 1
+ print("the total number of students are", count)
remcount()
def firstmark():
- F = open("class.dat", "rb")
- val = pickle.load(F)
- main = []
- count = 0
+ with open("class.dat", "rb") as F:
+ val = pickle.load(F)
+ main = []
+ count = 0
- for i in val:
- data = i[2]
- main.append(data)
+ for i in val:
+ data = i[2]
+ main.append(data)
- top = max(main)
- print(top, "is the first mark")
+ top = max(main)
+ print(top, "is the first mark")
- F.seek(0)
- for i in val:
- if top == i[2]:
- print(i)
- print("congrats")
- count += 1
+ F.seek(0)
+ for i in val:
+ if top == i[2]:
+ print(i)
+ print("congrats")
+ count += 1
- print("the total number of students who secured top marks are", count)
- F.close()
+ print("the total number of students who secured top marks are", count)
firstmark()
-F = open("class.dat", "rb")
-val = pickle.load(F)
-print(val)
-F.close()
+with open("class.dat", "rb") as F:
+ val = pickle.load(F)
+ print(val)
diff --git a/1 File handle/File handle binary/search record in binary file.py b/1 File handle/File handle binary/search record in binary file.py
index fd58d246bb9..87855f1dbc4 100644
--- a/1 File handle/File handle binary/search record in binary file.py
+++ b/1 File handle/File handle binary/search record in binary file.py
@@ -4,21 +4,20 @@
def binary_search():
- F = open("studrec.dat", "rb")
- # your file path will be different
- value = pickle.load(F)
- search = 0
- rno = int(input("Enter the roll number of the student"))
+ with open("studrec.dat", "rb") as F:
+ # your file path will be different
+ value = pickle.load(F)
+ search = 0
+ rno = int(input("Enter the roll number of the student"))
- for i in value:
- if i[0] == rno:
- print("Record found successfully")
- print(i)
- search = 1
+ for i in value:
+ if i[0] == rno:
+ print("Record found successfully")
+ print(i)
+ search = 1
- if search == 0:
- print("Sorry! record not found")
- F.close()
+ if search == 0:
+ print("Sorry! record not found")
binary_search()
diff --git a/1 File handle/File handle text/input,output and error streams.py b/1 File handle/File handle text/input,output and error streams.py
index cecd268979b..e0a6008dcd5 100644
--- a/1 File handle/File handle text/input,output and error streams.py
+++ b/1 File handle/File handle text/input,output and error streams.py
@@ -8,9 +8,8 @@
while True:
ch = F.readlines()
- for (i) in ch: # ch is the whole file,for i in ch gives lines, for j in i gives letters,for j in i.split gives words
+ for i in ch:
print(i, end="")
- else:
- sys.stderr.write("End of file reached")
- break
+ sys.stderr.write("End of file reached")
+ break
diff --git a/1 File handle/File handle text/special symbol after word.py b/1 File handle/File handle text/special symbol after word.py
index 353a98cca87..7c92cd3bd7d 100644
--- a/1 File handle/File handle text/special symbol after word.py
+++ b/1 File handle/File handle text/special symbol after word.py
@@ -1,16 +1,15 @@
-F = open("happy.txt", "r")
-# method 1
-val = F.read()
-val = val.split()
-for i in val:
- print(i, "*", end="")
-print("\n")
+with open("happy.txt", "r") as F:
+ # method 1
+ val = F.read()
+ val = val.split()
+ for i in val:
+ print(i, "*", end="")
+ print("\n")
-# method 2
-F.seek(0)
-value = F.readlines()
-for line in value:
- for word in line.split():
- print(word, "*", end="")
-F.close()
+ # method 2
+ F.seek(0)
+ value = F.readlines()
+ for line in value:
+ for word in line.split():
+ print(word, "*", end="")
diff --git a/A solution to project euler problem 3.py b/A solution to project euler problem 3.py
index 3b34b655083..4c218f2be7e 100644
--- a/A solution to project euler problem 3.py
+++ b/A solution to project euler problem 3.py
@@ -36,7 +36,7 @@ def solution(n: int = 600851475143) -> int:
TypeError: Parameter n must be int or passive of cast to int.
"""
try:
- n = int(n)
+ n = n
except (TypeError, ValueError):
raise TypeError("Parameter n must be int or passive of cast to int.")
if n <= 0:
@@ -55,7 +55,7 @@ def solution(n: int = 600851475143) -> int:
ans = i
while n % i == 0:
- n = n / i
+ n /= i
i += 1
diff --git a/AreaOfTriangle.py b/AreaOfTriangle.py
index 9d866337e0b..1c454e885a3 100644
--- a/AreaOfTriangle.py
+++ b/AreaOfTriangle.py
@@ -14,4 +14,4 @@
# calculate the area
area = (s*(s-a)*(s-b)*(s-c)) ** 0.5
-print('The area of the triangle is: ' + area)
+print(f'The area of the triangle is: {area}')
diff --git a/Assembler/assembler.py b/Assembler/assembler.py
index c4773c583dd..3eacd708114 100644
--- a/Assembler/assembler.py
+++ b/Assembler/assembler.py
@@ -53,10 +53,9 @@ def loadFile(fileName):
loadFile: This function loads the file and reads its lines.
"""
global lines
- fo = open(fileName)
- for line in fo:
- lines.append(line)
- fo.close()
+ with open(fileName) as fo:
+ for line in fo:
+ lines.append(line)
def scanner(string):
diff --git a/Automated Scheduled Call Reminders/caller.py b/Automated Scheduled Call Reminders/caller.py
index 3082dbb7193..d351f223b64 100644
--- a/Automated Scheduled Call Reminders/caller.py
+++ b/Automated Scheduled Call Reminders/caller.py
@@ -42,7 +42,7 @@ def search():
timestamp = datetime.now().strftime("%H:%M")
five_minutes_prior = (timestamp + timedelta(minutes=5)).strftime("%H:%M")
for doc in list_of_docs:
- if doc["from"][0:5] == five_minutes_prior:
+ if doc["from"][:5] == five_minutes_prior:
phone_number = doc["phone"]
call = client.calls.create(
to=phone_number,
diff --git a/Base Converter Number system.py b/Base Converter Number system.py
index 9f36a6bd77f..b319dd410a5 100644
--- a/Base Converter Number system.py
+++ b/Base Converter Number system.py
@@ -1,36 +1,29 @@
def base_check(xnumber, xbase):
- for char in xnumber[len(xnumber ) -1]:
- if int(char) >= int(xbase):
- return False
- return True
+ return all(int(char) < int(xbase) for char in xnumber[len(xnumber ) -1])
def convert_from_10(xnumber, xbase, arr, ybase):
- if int(xbase) == 2 or int(xbase) == 4 or int(xbase) == 6 or int(xbase) == 8:
+ if int(xbase) in {2, 4, 6, 8}:
if xnumber == 0:
return arr
- else:
- quotient = int(xnumber) // int(xbase)
- remainder = int(xnumber) % int(xbase)
- arr.append(remainder)
- dividend = quotient
- convert_from_10(dividend, xbase, arr, base)
+ quotient, remainder = divmod(int(xnumber), int(xbase))
+ arr.append(remainder)
+ dividend = quotient
+ convert_from_10(dividend, xbase, arr, base)
elif int(xbase) == 16:
if int(xnumber) == 0:
return arr
- else:
- quotient = int(xnumber) // int(xbase)
- remainder = int(xnumber) % int(xbase)
- if remainder > 9:
- if remainder == 10: remainder = 'A'
- if remainder == 11: remainder = 'B'
- if remainder == 12: remainder = 'C'
- if remainder == 13: remainder = 'D'
- if remainder == 14: remainder = 'E'
- if remainder == 15: remainder = 'F'
- arr.append(remainder)
- dividend = quotient
- convert_from_10(dividend, xbase, arr, ybase)
+ quotient, remainder = divmod(int(xnumber), int(xbase))
+ if remainder > 9:
+ if remainder == 10: remainder = 'A'
+ if remainder == 11: remainder = 'B'
+ if remainder == 12: remainder = 'C'
+ if remainder == 13: remainder = 'D'
+ if remainder == 14: remainder = 'E'
+ if remainder == 15: remainder = 'F'
+ arr.append(remainder)
+ dividend = quotient
+ convert_from_10(dividend, xbase, arr, ybase)
def convert_to_10(xnumber, xbase, arr, ybase):
if int(xbase) == 10:
for char in xnumber:
diff --git a/Battery_notifier.py b/Battery_notifier.py
index 2f45301bc1e..dde55b19ae6 100644
--- a/Battery_notifier.py
+++ b/Battery_notifier.py
@@ -12,10 +12,7 @@
# notification to desktop
# help(Notification)
if charging:
- if percent == 100:
- charging_message = "Unplug your Charger"
- else:
- charging_message = "Charging"
+ charging_message = "Unplug your Charger" if percent == 100 else "Charging"
else:
charging_message = "Not Charging"
message = str(percent) + "% Charged\n" + charging_message
diff --git a/Binary Coefficients.py b/Binary Coefficients.py
index 3039858d55f..1735e29bae7 100644
--- a/Binary Coefficients.py
+++ b/Binary Coefficients.py
@@ -1,17 +1,12 @@
def pascal_triangle(lineNumber):
- list1 = list()
- list1.append([1])
+ list1 = [[1]]
i = 1
while i <= lineNumber:
- j = 1
- l = []
- l.append(1)
- while j < i:
- l.append(list1[i - 1][j] + list1[i - 1][j - 1])
- j = j + 1
+ l = [1]
+ l.extend(list1[i - 1][j] + list1[i - 1][j - 1] for j in range(1, i))
l.append(1)
list1.append(l)
- i = i + 1
+ i += 1
return list1
diff --git a/Binary_search.py b/Binary_search.py
index 118f4461bb0..93a0962cffe 100644
--- a/Binary_search.py
+++ b/Binary_search.py
@@ -37,6 +37,6 @@ def binary_search(arr, l, r, x):
# printing the output
if result != -1:
- print("Element is present at index {}".format(result))
+ print(f"Element is present at index {result}")
else:
print("Element is not present in array")
diff --git a/BlackJack_game/blackjack.py b/BlackJack_game/blackjack.py
index 858257ae39f..856bdd0b81e 100644
--- a/BlackJack_game/blackjack.py
+++ b/BlackJack_game/blackjack.py
@@ -60,9 +60,9 @@
print(f"{'*'*24}Dealer is the Winner !!{'*'*14}")
exit()
-if sum(d_cards) == 21 and sum(p_cards) == 21:
- print(f"{'*'*17}The match is tie !!{'*'*25}")
- exit()
+ if sum(p_cards) == 21:
+ print(f"{'*'*17}The match is tie !!{'*'*25}")
+ exit()
# function to show the dealer's choice
@@ -72,20 +72,17 @@ def dealer_choice():
random.shuffle(deck)
d_cards.append(deck.pop())
- print("Dealer has total " + str(sum(d_cards)) + "with the cards ", d_cards)
+ print(f"Dealer has total {str(sum(d_cards))}with the cards ", d_cards)
if sum(p_cards) == sum(d_cards):
print(f"{'*'*15}The match is tie !!{'*'*15}")
exit()
if sum(d_cards) == 21:
- if sum(p_cards) < 21:
+ if sum(p_cards) < 21 or sum(p_cards) != 21:
print(f"{'*'*23}Dealer is the Winner !!{'*'*18}")
- elif sum(p_cards) == 21:
- print(f"{'*'*20}There is tie !!{'*'*26}")
else:
- print(f"{'*'*23}Dealer is the Winner !!{'*'*18}")
-
+ print(f"{'*'*20}There is tie !!{'*'*26}")
elif sum(d_cards) < 21:
if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards):
print(f"{'*'*23}Dealer is the Winner !!{'*'*18}")
@@ -94,13 +91,10 @@ def dealer_choice():
if 21 > sum(p_cards) > sum(d_cards):
print(f"{'*'*22}Player is winner !!{'*'*22}")
+ elif sum(p_cards) < 21 or sum(p_cards) == 21:
+ print(f"{'*'*22}Player is winner !!{'*'*22}")
else:
- if sum(p_cards) < 21:
- print(f"{'*'*22}Player is winner !!{'*'*22}")
- elif sum(p_cards) == 21:
- print(f"{'*'*22}Player is winner !!{'*'*22}")
- else:
- print(f"{'*'*23}Dealer is the Winner !!{'*'*18}")
+ print(f"{'*'*23}Dealer is the Winner !!{'*'*18}")
while sum(p_cards) < 21:
@@ -110,7 +104,7 @@ def dealer_choice():
if k == 1:
random.shuffle(deck)
p_cards.append(deck.pop())
- print("You have a total of " + str(sum(p_cards)) + " with the cards ", p_cards)
+ print(f"You have a total of {str(sum(p_cards))} with the cards ", p_cards)
if sum(p_cards) > 21:
print(f'{"*"*13}You are BUSTED !{"*"*13}\n Dealer Wins !!')
if sum(p_cards) == 21:
diff --git a/BlackJack_game/blackjack_rr.py b/BlackJack_game/blackjack_rr.py
index d7c46b83cf6..903819f4214 100644
--- a/BlackJack_game/blackjack_rr.py
+++ b/BlackJack_game/blackjack_rr.py
@@ -9,11 +9,12 @@ class Colour:
suits = (
- Colour.RED + "Hearts" + Colour.END,
- Colour.RED + "Diamonds" + Colour.END,
- Colour.BLACK + "Spades" + Colour.END,
- Colour.BLACK + "Clubs" + Colour.END,
+ f"{Colour.RED}Hearts{Colour.END}",
+ f"{Colour.RED}Diamonds{Colour.END}",
+ f"{Colour.BLACK}Spades{Colour.END}",
+ f"{Colour.BLACK}Clubs{Colour.END}",
)
+
ranks = (
"Two",
"Three",
@@ -54,27 +55,23 @@ def __init__(self, suit, rank):
self.rank = rank
def __str__(self):
- return self.rank + " of " + self.suit
+ return f"{self.rank} of {self.suit}"
class Deck:
def __init__(self):
self.deck = []
for suit in suits:
- for rank in ranks:
- self.deck.append(Card(suit, rank))
+ self.deck.extend(Card(suit, rank) for rank in ranks)
def __str__(self):
- deck_comp = ""
- for card in self.deck:
- deck_comp += "\n " + card.__str__()
+ deck_comp = "".join("\n " + card.__str__() for card in self.deck)
def shuffle(self):
random.shuffle(self.deck)
def deal(self):
- single_card = self.deck.pop()
- return single_card
+ return self.deck.pop()
class Hand:
diff --git a/BlackJack_game/blackjack_simulate.py b/BlackJack_game/blackjack_simulate.py
index ae1706f6888..3bb6859f085 100644
--- a/BlackJack_game/blackjack_simulate.py
+++ b/BlackJack_game/blackjack_simulate.py
@@ -61,7 +61,7 @@ def __repr__(self):
return fmt_card.format(suit="*-Back-*", rank="*-Back-*")
def show(self):
- print(str(self))
+ print(self)
class Deck:
@@ -80,9 +80,9 @@ def __len__(self):
return len(self.cards)
def built(self):
+ suits = "Spades Heart Clubs Diamonds".split()
+ ranks = list(range(1, 14))
for _ in range(self.num):
- ranks = [x for x in range(1, 14)]
- suits = "Spades Heart Clubs Diamonds".split()
for suit in suits:
for rank in ranks:
card = Card(suit, rank)
@@ -144,7 +144,7 @@ def bet_amount(self):
@bet_amount.setter
def bet_amount(self, value):
type_tips = "Please give a integer"
- amount_tips = "Your chips should between 1 - " + str(self.amount) + " "
+ amount_tips = f"Your chips should between 1 - {str(self.amount)} "
try:
value = int(value)
except ValueError:
@@ -157,13 +157,10 @@ def bet_amount(self, value):
self._bet_amount = value
def double_bet(self):
- if self.can_double():
- self._bet_amount *= 2
- self.is_double = True
- else:
- over_tips = "Not enough chips || "
- cannot_double = "CAN'T DO DOUBLE"
- raise ValueError(Chips.get_tips(over_tips + cannot_double))
+ if not self.can_double():
+ raise ValueError(Chips.get_tips("Not enough chips || " + "CAN'T DO DOUBLE"))
+ self._bet_amount *= 2
+ self.is_double = True
@property
def insurance(self):
@@ -229,18 +226,16 @@ def unveil_card(self):
def calculate_point(self):
def _extract_rank():
raw_ranks = [card.rank for card in self.hand]
- cook_ranks = [10 if rank > 10 else rank for rank in raw_ranks]
+ cook_ranks = [min(rank, 10) for rank in raw_ranks]
return cook_ranks
def _sum_up(ranks):
rank_one = sum(ranks)
- rank_eleven = sum([11 if rank == 1 else rank for rank in ranks])
+ rank_eleven = sum(11 if rank == 1 else rank for rank in ranks)
# Over or has 2 Ace
if (ranks[::-1] == ranks) and (1 in ranks):
return 11 + len(ranks) - 1
- if rank_eleven <= BLACK_JACK:
- return rank_eleven
- return rank_one
+ return rank_eleven if rank_eleven <= BLACK_JACK else rank_one
points = _extract_rank()
self.point = _sum_up(points)
@@ -265,7 +260,7 @@ def showing(self):
def unveiling(self):
self.calculate_point()
- points_fmt = "My point is: {}".format(str(self.point))
+ points_fmt = f"My point is: {str(self.point)}"
self.speak(points_fmt)
self.unveil_card()
@@ -314,8 +309,8 @@ def select_choice(self, pattern):
}
enu_choice = enumerate((operation.get(p) for p in pattern), 1)
dict_choice = dict(enu_choice)
+ choice_fmt = "\t[{index}] {operation}"
for index, operator in dict_choice.items():
- choice_fmt = "\t[{index}] {operation}"
print(choice_fmt.format(index=index, operation=operator))
return dict_choice
@@ -429,7 +424,7 @@ def play(self):
if not self.bust:
self.is_surrender()
self.winner = self.get_winner()
- self.res = "Winner is " + self.winner
+ self.res = f"Winner is {self.winner}"
os.system("clear")
self.calculate_chips()
self.result_exhibit()
@@ -526,7 +521,7 @@ def get_select(select_max, prompt=">> ", general_err=""):
def chips_manage(self):
if self.choice == "Insurance":
- err = "The amount should under " + str(self.player.chips.current_amount())
+ err = f"The amount should under {str(self.player.chips.current_amount())}"
pay_ins = self.get_select(
self.player.chips.current_amount(),
prompt="Insurance amount >> ",
@@ -548,10 +543,9 @@ def card_manage(self):
self.player.obtain_card(self.deck)
if self.player.is_point(">", BLACK_JACK):
raise ValueError("Player BUST")
- else:
- self.dealer.strategy_trigger(self.deck)
- if self.dealer.is_point(">", BLACK_JACK):
- raise ValueError("Dealer BUST")
+ self.dealer.strategy_trigger(self.deck)
+ if self.dealer.is_point(">", BLACK_JACK):
+ raise ValueError("Dealer BUST")
elif self.choice != "Surrender":
if not self.player.chips.is_insurance:
self.dealer.strategy_trigger(self.deck)
@@ -574,17 +568,11 @@ def get_winner(self):
if self.choice == "Surrender":
return "Dealer"
elif self.choice == "Insurance":
- if self.player.is_point("==", BLACK_JACK):
- return "Dealer"
- return "Player"
-
+ return "Dealer" if self.player.is_point("==", BLACK_JACK) else "Player"
if self.choice in ("Double-down", "Stand"):
self.player.calculate_point()
self.dealer.calculate_point()
- if self.player.point > self.dealer.point:
- return "Player"
- return "Dealer"
-
+ return "Player" if self.player.point > self.dealer.point else "Dealer"
return "Both"
def calculate_chips(self):
diff --git a/BoardGame-CLI/snakeLadder.py b/BoardGame-CLI/snakeLadder.py
index 956f690d4be..e39efbd4b87 100644
--- a/BoardGame-CLI/snakeLadder.py
+++ b/BoardGame-CLI/snakeLadder.py
@@ -50,7 +50,7 @@ def play():
print("/"*20)
for i in players:
- n = input("{}'s turn: ".format(i)) or 1
+ n = input(f"{i}'s turn: ") or 1
n = int(n)
if players[i] < 100:
diff --git a/BoardGame-CLI/uno.py b/BoardGame-CLI/uno.py
index 4f36372a5f8..3ff1e62460d 100644
--- a/BoardGame-CLI/uno.py
+++ b/BoardGame-CLI/uno.py
@@ -16,13 +16,12 @@ def buildDeck():
wilds = ["Wild", "Wild Draw Four"]
for colour in colours:
for value in values:
- cardVal = "{} {}".format(colour, value)
+ cardVal = f"{colour} {value}"
deck.append(cardVal)
if value != 0:
deck.append(cardVal)
- for i in range(4):
- deck.append(wilds[0])
- deck.append(wilds[1])
+ for _ in range(4):
+ deck.extend((wilds[0], wilds[1]))
print(deck)
return deck
@@ -48,10 +47,7 @@ def shuffleDeck(deck):
def drawCards(numCards):
- cardsDrawn = []
- for x in range(numCards):
- cardsDrawn.append(unoDeck.pop(0))
- return cardsDrawn
+ return [unoDeck.pop(0) for _ in range(numCards)]
"""
@@ -62,13 +58,11 @@ def drawCards(numCards):
def showHand(player, playerHand):
- print("Player {}'s Turn".format(players_name[player]))
+ print(f"Player {players_name[player]}'s Turn")
print("Your Hand")
print("------------------")
- y = 1
- for card in playerHand:
- print("{}) {}".format(y, card))
- y += 1
+ for y, card in enumerate(playerHand, start=1):
+ print(f"{y}) {card}")
print("")
@@ -80,19 +74,15 @@ def showHand(player, playerHand):
def canPlay(colour, value, playerHand):
- for card in playerHand:
- if "Wild" in card:
- return True
- elif colour in card or value in card:
- return True
- return False
+ return any(
+ "Wild" in card or colour in card or value in card
+ for card in playerHand
+ )
unoDeck = buildDeck()
unoDeck = shuffleDeck(unoDeck)
unoDeck = shuffleDeck(unoDeck)
-discards = []
-
players_name = []
players = []
colours = ["Red", "Green", "Yellow", "Blue"]
@@ -101,30 +91,26 @@ def canPlay(colour, value, playerHand):
numPlayers = int(
input("Invalid. Please enter a number between 2-4.\nHow many players?"))
for player in range(numPlayers):
- players_name.append(input("Enter player {} name: ".format(player+1)))
+ players_name.append(input(f"Enter player {player + 1} name: "))
players.append(drawCards(5))
playerTurn = 0
playDirection = 1
playing = True
-discards.append(unoDeck.pop(0))
+discards = [unoDeck.pop(0)]
splitCard = discards[0].split(" ", 1)
currentColour = splitCard[0]
-if currentColour != "Wild":
- cardVal = splitCard[1]
-else:
- cardVal = "Any"
-
+cardVal = splitCard[1] if currentColour != "Wild" else "Any"
while playing:
showHand(playerTurn, players[playerTurn])
- print("Card on top of discard pile: {}".format(discards[-1]))
+ print(f"Card on top of discard pile: {discards[-1]}")
if canPlay(currentColour, cardVal, players[playerTurn]):
cardChosen = int(input("Which card do you want to play?"))
while not canPlay(currentColour, cardVal, [players[playerTurn][cardChosen-1]]):
cardChosen = int(
input("Not a valid card. Which card do you want to play?"))
- print("You played {}".format(players[playerTurn][cardChosen-1]))
+ print(f"You played {players[playerTurn][cardChosen - 1]}")
discards.append(players[playerTurn].pop(cardChosen-1))
# cheak if player won
@@ -136,13 +122,10 @@ def canPlay(colour, value, playerHand):
# cheak for special cards
splitCard = discards[-1].split(" ", 1)
currentColour = splitCard[0]
- if len(splitCard) == 1:
- cardVal = "Any"
- else:
- cardVal = splitCard[1]
+ cardVal = "Any" if len(splitCard) == 1 else splitCard[1]
if currentColour == "Wild":
for x in range(len(colours)):
- print("{}) {}".format(x+1, colours[x]))
+ print(f"{x + 1}) {colours[x]}")
newColour = int(
input("What colour would you like to choose? "))
while newColour < 1 or newColour > 4:
@@ -183,4 +166,4 @@ def canPlay(colour, value, playerHand):
playerTurn = numPlayers-1
print("Game Over")
-print("{} is the Winner!".format(winner))
+print(f"{winner} is the Winner!")
diff --git a/BruteForce.py b/BruteForce.py
index 46b17844e26..b6533d5b7ac 100644
--- a/BruteForce.py
+++ b/BruteForce.py
@@ -35,20 +35,12 @@ def getChars():
Método para obter uma lista contendo todas as
letras do alfabeto e números.
"""
- chars = []
-
- # Acrescenta à lista todas as letras maiúsculas
- for id_ in range(ord("A"), ord("Z") + 1):
- chars.append(chr(id_))
+ chars = [chr(id_) for id_ in range(ord("A"), ord("Z") + 1)]
# Acrescenta à lista todas as letras minúsculas
- for id_ in range(ord("a"), ord("z") + 1):
- chars.append(chr(id_))
-
+ chars.extend(chr(id_) for id_ in range(ord("a"), ord("z") + 1))
# Acrescenta à lista todos os números
- for number in range(10):
- chars.append(str(number))
-
+ chars.extend(str(number) for number in range(10))
return chars
@@ -66,10 +58,7 @@ def getChars():
def testFunction(password):
global pw
- if password == pw:
- return True
- else:
- return False
+ return password == pw
# Obtém os dígitos que uma senha pode ter
chars = getChars()
diff --git a/CRC/crc.py b/CRC/crc.py
index d3d302244b7..83c53de54d0 100644
--- a/CRC/crc.py
+++ b/CRC/crc.py
@@ -36,9 +36,7 @@ def crc_check(data, div):
original_data = data
data = data + ("0" * (len(div) - 1))
crc = crc_check(data, div)
- crc_str = ""
- for c in crc:
- crc_str += c
+ crc_str = "".join(crc)
print("Sent data: ", original_data + crc_str)
sent_data = original_data + crc_str
print(
@@ -49,7 +47,7 @@ def crc_check(data, div):
print("Receiver side remainder: ", remainder)
print("Continue [Y/N]:")
ch = input()
- if ch == "N" or ch == "n":
+ if ch in ["N", "n"]:
break
else:
continue
diff --git a/Caesar Cipher Encoder & Decoder.py b/Caesar Cipher Encoder & Decoder.py
index 7bd078e2849..e71c6044b8e 100644
--- a/Caesar Cipher Encoder & Decoder.py
+++ b/Caesar Cipher Encoder & Decoder.py
@@ -40,20 +40,14 @@ def encode():
text = text.upper()
for char in text:
ascii = ord(char)
- if ascii > 90:
+ if ascii <= 90 and ascii < 65 or ascii > 90:
new_ascii = ascii
else:
- if ascii < 65:
- new_ascii = ascii
- else:
- new_ascii = ascii + key
- if new_ascii > 90:
- new_ascii = new_ascii - 26
- else:
- new_ascii = new_ascii
+ new_ascii = ascii + key
+ new_ascii = new_ascii - 26 if new_ascii > 90 else new_ascii
encoded = chr(new_ascii)
encoded_cipher = encoded_cipher + encoded
- print("Encoded text: " + encoded_cipher)
+ print(f"Encoded text: {encoded_cipher}")
@@ -61,24 +55,17 @@ def decode():
cipher = input("\n[>] Enter your cipher text: ")
print("Posiblities of cipher text are: \n")
cipher = cipher.lower()
+ decoded = ""
for i in range(1, 26):
- decoded = ""
decoded_cipher = ""
for char in cipher:
ascii = ord(char)
- if ascii < 97:
+ if ascii >= 97 and ascii > 122 or ascii < 97:
new_ascii = ascii
else:
- if ascii > 122:
- new_ascii = ascii
- else:
- new_ascii = ascii - int(i)
- if new_ascii < 97:
- new_ascii = new_ascii + 26
- else:
- new_ascii = new_ascii
- decoded = chr(new_ascii)
- decoded_cipher = decoded_cipher + decoded
+ new_ascii = ascii - int(i)
+ new_ascii = new_ascii + 26 if new_ascii < 97 else new_ascii
+ decoded_cipher = decoded_cipher + chr(new_ascii)
print("\n" + decoded_cipher)
diff --git a/Calculate resistance.py b/Calculate resistance.py
index 10c7a5ad3e2..c21d8634435 100644
--- a/Calculate resistance.py
+++ b/Calculate resistance.py
@@ -1,9 +1,6 @@
def res(R1, R2):
sum = R1 + R2
- if (option =="series"):
- return sum
- else:
- return (R1 * R2)/(R1 + R2)
+ return sum if (option =="series") else (R1 * R2)/(R1 + R2)
Resistance1 = int(input("Enter R1 : "))
Resistance2 = int(input("Enter R2 : "))
option = str(input("Enter series or parallel :"))
diff --git a/Cat/cat.py b/Cat/cat.py
index 552ed6c1e7a..db77125448c 100644
--- a/Cat/cat.py
+++ b/Cat/cat.py
@@ -26,7 +26,7 @@ def with_files(files):
"""Executes when file(s) is/are specified."""
try:
# Read each file's contents and store them
- file_contents = [contents for contents in [open(file).read() for file in files]]
+ file_contents = [open(file).read() for file in files]
except OSError as err:
# This executes when there's an error (e.g. FileNotFoundError)
exit(print(f"cat: error reading files ({err})"))
@@ -41,10 +41,7 @@ def no_files():
# Get input, output the input, repeat
while True:
print(input())
- # Graceful exit for Ctrl + C, Ctrl + D
- except KeyboardInterrupt:
- exit()
- except EOFError:
+ except (KeyboardInterrupt, EOFError):
exit()
def main():
diff --git a/Checker_game_by_dz/modules/checker.py b/Checker_game_by_dz/modules/checker.py
index 8525435aef0..36f8985c14d 100644
--- a/Checker_game_by_dz/modules/checker.py
+++ b/Checker_game_by_dz/modules/checker.py
@@ -49,8 +49,7 @@ def _move(self, row, col):
piece = self.board.get_piece(row, col)
if (self.select) and (piece == 0) and (row, col) in self.valid_moves:
self.board.move(self.select, row, col)
- skip = self.valid_moves[(row, col)]
- if skip:
+ if skip := self.valid_moves[(row, col)]:
self.board.remove(skip)
self.chg_turn()
else:
@@ -71,7 +70,4 @@ def draw_moves(self, moves):
# for changing the turn
def chg_turn(self):
self.valid_moves = {}
- if self.turn == black:
- self.turn = white
- else:
- self.turn = black
+ self.turn = white if self.turn == black else black
diff --git a/Checker_game_by_dz/modules/checker_board.py b/Checker_game_by_dz/modules/checker_board.py
index b14df11b360..5830718e8a1 100644
--- a/Checker_game_by_dz/modules/checker_board.py
+++ b/Checker_game_by_dz/modules/checker_board.py
@@ -31,7 +31,7 @@ def move(self, piece, row, col):
self.board[piece.row][piece.col],
)
piece.move(row, col)
- if row == rows - 1 or row == 0:
+ if row in [rows - 1, 0]:
piece.make_king()
if piece.color == white:
self.white_k += 1
@@ -71,9 +71,7 @@ def get_valid_moves(self, piece):
row = piece.row
if piece.color == black or piece.king:
- moves.update(
- self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l)
- )
+ moves |= self._traverse_l(row - 1, max(row - 3, -1), -1, piece.color, l)
moves.update(
self._traverse_r(row - 1, max(row - 3, -1), -1, piece.color, r)
)
@@ -121,13 +119,8 @@ def _traverse_l(self, start, stop, step, color, l, skip=[]):
moves[(r, l)] = last
if last:
- if step == -1:
- row = max(r - 3, 0)
- else:
- row = min(r + 3, rows)
- moves.update(
- self._traverse_l(r + step, row, step, color, l - 1, skip=last)
- )
+ row = max(r - 3, 0) if step == -1 else min(r + 3, rows)
+ moves |= self._traverse_l(r + step, row, step, color, l - 1, skip=last)
moves.update(
self._traverse_r(r + step, row, step, color, l + 1, skip=last)
)
@@ -157,15 +150,11 @@ def _traverse_r(self, start, stop, step, color, right, skip=[]):
moves[(r, right)] = last
if last:
- if step == -1:
- row = max(r - 3, 0)
- else:
- row = min(r + 3, rows)
- moves.update(
- self._traverse_l(
- r + step, row, step, color, right - 1, skip=last
- )
+ row = max(r - 3, 0) if step == -1 else min(r + 3, rows)
+ moves |= self._traverse_l(
+ r + step, row, step, color, right - 1, skip=last
)
+
moves.update(
self._traverse_r(
r + step, row, step, color, right + 1, skip=last
diff --git a/Classification_human_or_horse.py b/Classification_human_or_horse.py
index 4aa069a855a..e4c65115f8a 100644
--- a/Classification_human_or_horse.py
+++ b/Classification_human_or_horse.py
@@ -49,6 +49,6 @@
classes = model.predict(images, batch_size=10)
print(classes[0])
if classes[0] > 0.5:
- print(filename + " is a human")
+ print(f"{filename} is a human")
else:
- print(filename + " is a horse")
+ print(f"{filename} is a horse")
diff --git a/Collatz-Conjecture.py b/Collatz-Conjecture.py
index bafea8c6d41..d1b96550a90 100644
--- a/Collatz-Conjecture.py
+++ b/Collatz-Conjecture.py
@@ -69,7 +69,7 @@ def sequence(number: float) -> float:
"""
modulo = number % 2 # The number modulo'd by 2
if modulo == 0: # If the result is 0,
- number = number / 2 # divide it by 2
+ number /= 2
else: # Otherwise,
number = 3 * number + 1 # multiply by 3 and add 1 (3x + 1)
return number
diff --git a/Colors/pixel_sort.py b/Colors/pixel_sort.py
index 3c3c06ea616..a846c81ad97 100644
--- a/Colors/pixel_sort.py
+++ b/Colors/pixel_sort.py
@@ -1,5 +1,6 @@
"""Pixel Sorting"""
+
# Importing Libraries
import cv2
import numpy as np
@@ -22,8 +23,8 @@
# the add_argument tells you what needs to be given as an input sp its help
args = parser.parse_args() # you take the arguments from command line
-os.makedirs("Image_sort/" + str(args.f))
-print(str(args.f).capitalize() + " directory is created.")
+os.makedirs(f"Image_sort/{str(args.f)}")
+print(f"{str(args.f).capitalize()} directory is created.")
# Defining all global variables
df = []
@@ -34,10 +35,9 @@
def createDataSet(val=0, data=[]):
global dict
dict[len(data)] = data
- if val != 0:
- if val == max(dict.keys()):
- final_df = pd.DataFrame(dict[val], columns=["Blue", "Green", "Red"])
- final_df.to_excel("Image_sort/" + str(args.f) + "/" + "output.xlsx")
+ if val != 0 and val == max(dict.keys()):
+ final_df = pd.DataFrame(dict[val], columns=["Blue", "Green", "Red"])
+ final_df.to_excel(f"Image_sort/{str(args.f)}/output.xlsx")
# Generating colors for each row of the frame
@@ -45,7 +45,7 @@ def generateColors(c_sorted, frame, row):
global df, img_list
height = 25
img = np.zeros((height, len(c_sorted), 3), np.uint8)
- for x in range(0, len(c_sorted)):
+ for x in range(len(c_sorted)):
r, g, b = c_sorted[x][0] * 255, c_sorted[x][1] * 255, c_sorted[x][2] * 255
c = [r, g, b]
df.append(c)
@@ -96,13 +96,14 @@ def findThreshold(lst, add):
def makeVideo():
out = cv2.VideoWriter(
- "Image_sort/" + str(args.f) + "/" + str(args.f) + ".mp4",
+ f"Image_sort/{str(args.f)}/{str(args.f)}.mp4",
cv2.VideoWriter_fourcc(*"mp4v"),
16,
(800, 500),
)
+
for count in tqdm(range(1, 500 + 1)):
- fileName = "Image_sort/" + str(args.f) + "/" + str(count) + ".jpg"
+ fileName = f"Image_sort/{str(args.f)}/{str(count)}.jpg"
img = cv2.imread(fileName)
out.write(img)
os.remove(fileName)
@@ -111,17 +112,17 @@ def makeVideo():
def main():
global img_list
- img = cv2.imread("Image/" + str(args.f) + ".jpg")
+ img = cv2.imread(f"Image/{str(args.f)}.jpg")
img = cv2.resize(img, (800, 500))
img_list.append(img)
height, width, _ = img.shape
print(">>> Row-wise Color sorting")
- for row in tqdm(range(0, height)):
+ for row in tqdm(range(height)):
color, color_n = [], []
add = []
- for col in range(0, width):
+ for col in range(width):
val = img[row][col].tolist()
# val includes all rgb values between the range of 0 to 1
@@ -141,7 +142,7 @@ def main():
# For the specific row , if any of the values are zero it gets sorted with color_n
if np.all(np.asarray(color)) == False:
- for ind, i in enumerate(color):
+ for i in color:
# Accessing every list within color
# Added to color_n if any of the element in the list is non-zero
# and their sum is less than threshold value
@@ -152,12 +153,10 @@ def main():
color_n.sort(key=lambda bgr: step(bgr, 8)) # step sorting
band, img = generateColors(color_n, img, row)
measure(len(color_n), row, col, height, width)
- cv2.imwrite("Image_sort/" + str(args.f) + "/" + str(row + 1) + ".jpg", img)
+ cv2.imwrite(f"Image_sort/{str(args.f)}/{str(row + 1)}.jpg", img)
# Writing down the final sorted image
- cv2.imwrite(
- "Image_sort/" + str(args.f) + "/" + str(args.f) + ".jpg", img
- ) # Displaying the final picture
+ cv2.imwrite(f"Image_sort/{str(args.f)}/{str(args.f)}.jpg", img)
print("\n>>> Formation of the Video progress of the pixel-sorted image")
makeVideo()
diff --git a/Colors/primary_colors.py b/Colors/primary_colors.py
index 107056fbd7d..31f6608d084 100644
--- a/Colors/primary_colors.py
+++ b/Colors/primary_colors.py
@@ -34,45 +34,25 @@ def simpleColor(r, g, b):
else:
return "CHOCOLATE"
- else: # Verde mas cerca de Rojo
- if rg > 60:
- return "NARANJA*"
- elif r > 125:
- return "AMARILLO"
- else:
- return "COCHOLATE"
+ elif rg > 60:
+ return "NARANJA*"
+ elif r > 125:
+ return "AMARILLO"
+ else:
+ return "COCHOLATE"
elif rg > rb: # Azul mayor que verde
- if bg < rb: # Verde mas cerca de Azul
- if gb < 60:
- if r > 150:
- return "ROJO 2"
- else:
- return "MARRON"
- elif g > 125:
- return "ROSADO"
- else:
- return "ROJO 3"
- else: # Verde mas cerca de Rojo
- if rb < 60:
- if r > 160:
- return "ROSADO*"
- else:
- return "ROJO"
- else:
- return "ROJO"
-
- else: # g y b iguales
- if rg > 20:
- if r >= 100 and b < 60:
- return "ROJO"
- elif r >= 100:
- return "ROJO"
- else:
- return "MARRON"
-
+ if bg >= rb:
+ return "ROSADO*" if rb < 60 and r > 160 else "ROJO"
+ if gb < 60:
+ return "ROJO 2" if r > 150 else "MARRON"
+ elif g > 125:
+ return "ROSADO"
else:
- return "GRIS"
- # VERDE ---------------------------------------------------
+ return "ROJO 3"
+ elif rg > 20:
+ return "ROJO" if r >= 100 and b < 60 or r >= 100 else "MARRON"
+ else:
+ return "GRIS"
elif g > r and g > b:
gb = diff(g, b) # distancia verde a azul
gr = diff(g, r) # distancia verde a rojo
@@ -82,33 +62,15 @@ def simpleColor(r, g, b):
rb = diff(r, b) # distancia de rojo a azul
- if r > b: # ROJO > AZUL
- if gr < gb: # Verde con Rojo
-
- if rb >= 150 and gr <= 20:
- return "AMARILLO"
- else:
- return "VERDE"
- else: # ...Verde
- return "VERDE"
-
- elif r < b: # AZUL > ROJO
- if gb < gr: # Verde con Azul
-
- if gb <= 20:
- return "TURQUESA"
- else:
- return "VERDE"
- else: # ...Verde
- return "VERDE"
-
- else: # r y b iguales
- if gb > 10:
- return "VERDE"
- else:
- return "GRIS"
+ if r <= b and r < b and gb < gr and gb <= 20:
+ return "TURQUESA"
+ elif r <= b and r < b or r <= b and gb > 10:
+ return "VERDE"
+ elif r <= b:
+ return "GRIS"
- # AZUL ------------------------------------------------------
+ else: # ROJO > AZUL
+ return "AMARILLO" if gr < gb and rb >= 150 and gr <= 20 else "VERDE"
elif b > r and b > g:
bg = diff(b, g) # distancia azul a verde
br = diff(b, r) # distancia azul a rojo
@@ -119,50 +81,28 @@ def simpleColor(r, g, b):
rg = diff(r, g) # distancia de rojo a verde
if g < r: # ROJO > VERDE
- if bg < rg: # Azul con Verde
- if bg <= 20:
- return "TURQUESA"
- else:
- return "CELESTE"
- else: # ...Azul
- if rg <= 20:
- if r >= 150:
- return "LILA"
- else:
- return "AZUL *************"
- else:
- return "AZUL"
+ if bg < rg:
+ return "TURQUESA" if bg <= 20 else "CELESTE"
+ if rg <= 20:
+ return "LILA" if r >= 150 else "AZUL *************"
+ else:
+ return "AZUL"
elif g > r: # VERDE > ROJO
if br < rg: # Azul con rojo
- if br <= 20:
- if r > 150 and g < 75:
- return "ROSADO FIUSHA"
- elif ir > 150:
- return "LILA"
- else:
- return "MORADO"
+ if br <= 20 and r > 150 and g < 75:
+ return "ROSADO FIUSHA"
+ elif br <= 20 and ir > 150:
+ return "LILA"
else:
return "MORADO"
+ elif rg <= 20:
+ return "GRIS" if bg <= 20 else "AZUL"
+ elif bg > 20:
+ return "ROJO" if r >= 100 and b < 60 or r >= 100 else "MARRON"
+ else:
+ return "GRIS"
- else: # ...Azul
- if rg <= 20:
- if bg <= 20:
- return "GRIS"
- else:
- return "AZUL"
- else: # r y g iguales
- if bg > 20:
- if r >= 100 and b < 60:
- return "ROJO"
- elif r >= 100:
- return "ROJO"
- else:
- return "MARRON"
- else:
- return "GRIS"
-
- # IGUALES---------------------------------------
else:
return "GRIS"
diff --git a/Compression_Analysis/PSNR.py b/Compression_Analysis/PSNR.py
index b3148c64c77..fc9b310d5ee 100644
--- a/Compression_Analysis/PSNR.py
+++ b/Compression_Analysis/PSNR.py
@@ -11,8 +11,7 @@ def Representational(r, g, b):
def calculate(img):
b, g, r = cv2.split(img)
- pixelAt = Representational(r, g, b)
- return pixelAt
+ return Representational(r, g, b)
def main():
@@ -34,7 +33,7 @@ def main():
# MSR = error_sum/(height*width)
PSNR = -(10 * math.log10(error / (255 * 255)))
- print("PSNR value is {}".format(PSNR))
+ print(f"PSNR value is {PSNR}")
if __name__ == "__main__":
diff --git a/Conversation.py b/Conversation.py
index 43f469ff56c..92189220bbb 100644
--- a/Conversation.py
+++ b/Conversation.py
@@ -5,7 +5,7 @@
# user puts in their name
name = getuser()
-name_check = input("Is your name " + name + "? → ")
+name_check = input(f"Is your name {name}? → ")
if name_check.lower().startswith("y"):
print("Okay.")
time.sleep(1)
@@ -16,10 +16,9 @@
# Python lists their name
userList = name
-# Python & user dialoge
-print("Hello", name + ", my name is Python.")
+print("Hello", userList + ", my name is Python.")
time.sleep(0.8)
-print("The first letter of your name is", userList[0] + ".")
+print("The first letter of your name is", f"{userList[0]}.")
time.sleep(0.8)
print("Nice to meet you. :)")
time.sleep(0.8)
diff --git a/CountMillionCharacter.py b/CountMillionCharacter.py
index c1aa7825a19..dc7c35de3ff 100644
--- a/CountMillionCharacter.py
+++ b/CountMillionCharacter.py
@@ -6,6 +6,7 @@
Credit to William J. Turkel and Adam Crymble for the word
frequency code used below. I just merged the two ideas.
"""
+
import re
pattern = re.compile("\W") # re is used to compile the expression more than once
@@ -308,7 +309,7 @@
wordlist.count(w) for w in wordlist
] # counts frequency of a letter in the given list
-print("String\n {} \n".format(wordstring))
-print("List\n {} \n".format(str(wordlist)))
-print("Frequencies\n {} \n".format(str(wordfreq)))
-print("Pairs\n {}".format(str(dict(zip(wordlist, wordfreq)))))
+print(f"String\n {wordstring} \n")
+print(f"List\n {wordlist} \n")
+print(f"Frequencies\n {wordfreq} \n")
+print(f"Pairs\n {dict(zip(wordlist, wordfreq))}")
diff --git a/Credit_Card_Validator.py b/Credit_Card_Validator.py
index 08100e781fd..00c8327288f 100644
--- a/Credit_Card_Validator.py
+++ b/Credit_Card_Validator.py
@@ -32,15 +32,14 @@ def company(self):
elif str(self.card_no).startswith("7"):
comp = "Gasoline Card"
- return "Company : " + comp
+ return f"Company : {comp}"
def first_check(self):
- if 13 <= len(self.card_no) <= 19:
- message = "First check : Valid in terms of length."
-
- else:
- message = "First check : Check Card number once again it must be of 13 or 16 digits long."
- return message
+ return (
+ "First check : Valid in terms of length."
+ if 13 <= len(self.card_no) <= 19
+ else "First check : Check Card number once again it must be of 13 or 16 digits long."
+ )
def validate(self):
# double every second digit from right to left
@@ -51,7 +50,7 @@ def validate(self):
double_it = int(crd_no[i]) * 2
if len(str(double_it)) == 2:
- sum_ += sum([eval(i) for i in str(double_it)])
+ sum_ += sum(eval(i) for i in str(double_it))
else:
sum_ += double_it
@@ -59,16 +58,11 @@ def validate(self):
else:
sum_ += int(crd_no[i])
- if sum_ % 10 == 0:
- response = "Valid Card"
- else:
- response = "Invalid Card"
-
- return response
+ return "Valid Card" if sum_ % 10 == 0 else "Invalid Card"
@property
def checksum(self):
- return "#CHECKSUM# : " + self.card_no[-1]
+ return f"#CHECKSUM# : {self.card_no[-1]}"
@classmethod
def set_card(cls, card_to_check):
diff --git a/Cricket_score.py b/Cricket_score.py
index 22b8f05e319..1ed6e37e3c7 100644
--- a/Cricket_score.py
+++ b/Cricket_score.py
@@ -14,13 +14,19 @@
sauce = request.urlopen(url).read()
soup = bs4.BeautifulSoup(sauce, "lxml")
-score = []
-results = []
-
-for div_tags in soup.find_all("div", attrs={"class": "cb-lv-scrs-col text-black"}):
- score.append(div_tags.text)
-for result in soup.find_all("div", attrs={"class": "cb-lv-scrs-col cb-text-complete"}):
- results.append(result.text)
+score = [
+ div_tags.text
+ for div_tags in soup.find_all(
+ "div", attrs={"class": "cb-lv-scrs-col text-black"}
+ )
+]
+
+results = [
+ result.text
+ for result in soup.find_all(
+ "div", attrs={"class": "cb-lv-scrs-col cb-text-complete"}
+ )
+]
engine = pyttsx3.init()
diff --git a/Day_of_week.py b/Day_of_week.py
index f0f9fd6f3b5..332739ea929 100644
--- a/Day_of_week.py
+++ b/Day_of_week.py
@@ -25,4 +25,4 @@ def find_day(date):
# To overcome those we have to process user input and make it standard to accept as defined by calender and time module
user_input = str(input("Enter date "))
date = process_date(user_input)
-print("Day on " + user_input + " is " + find_day(date))
+print(f"Day on {user_input} is {find_day(date)}")
diff --git a/Decimal_To_Binary.py b/Decimal_To_Binary.py
index a8e85097a14..842e8247eac 100644
--- a/Decimal_To_Binary.py
+++ b/Decimal_To_Binary.py
@@ -21,17 +21,13 @@ def dtbconverter(num):
while w_num != 0:
whole.append(w_num % 2)
- w_num = w_num // 2
+ w_num //= 2
whole.reverse()
- i = 0
- while i < len(whole):
- print(whole[i], end="")
- i += 1
- i = 0
- while i < len(fractional):
- print(fractional[i], end="")
- i += 1
+ for item_ in whole:
+ print(item_, end="")
+ for item in fractional:
+ print(item, end="")
number = float(input("Enter Any base-10 Number: "))
diff --git a/Delete_Linked_List.py b/Delete_Linked_List.py
index 263f69eb986..92f7f7cec7c 100644
--- a/Delete_Linked_List.py
+++ b/Delete_Linked_List.py
@@ -22,10 +22,9 @@ def Delete(self, key):
temp = self.head
if temp is None:
return "Can't Delete!"
- else:
- if temp.data == key:
- self.head = temp.next
- temp = None
+ if temp.data == key:
+ self.head = temp.next
+ temp = None
while temp is not None:
prev = temp
temp = temp.next
diff --git a/Detect_Remove_loop.py b/Detect_Remove_loop.py
index 6aad9f879b9..3e6c956ed70 100644
--- a/Detect_Remove_loop.py
+++ b/Detect_Remove_loop.py
@@ -33,7 +33,7 @@ def Remove_loop(self, Loop_node):
ptr1 = self.head
while 1:
ptr2 = Loop_node
- while ptr2.next != Loop_node and ptr2.next != ptr1:
+ while ptr2.next not in [ptr2, ptr1]:
ptr2 = ptr2.next
if ptr2.next == ptr1:
break
diff --git a/Eight_Puzzle_Solver/eight_puzzle.py b/Eight_Puzzle_Solver/eight_puzzle.py
index 703df00b3e6..336e9c4c909 100644
--- a/Eight_Puzzle_Solver/eight_puzzle.py
+++ b/Eight_Puzzle_Solver/eight_puzzle.py
@@ -25,10 +25,7 @@ def __init__(self, state, depth=0, moves=None, optimizer=0):
self.size = len(state)
self.depth = depth
self.optimizer = optimizer
- if moves is None:
- self.moves = list()
- else:
- self.moves = moves
+ self.moves = [] if moves is None else moves
def getAvailableActions(self):
"""
@@ -37,7 +34,7 @@ def getAvailableActions(self):
0 - Left 1 - Right 2 - Top 3 - Bottom
Restrictions: state is self.size x self.size Array
"""
- action = list()
+ action = []
for i in range(self.size):
for j in range(self.size):
if self.state[i][j] == 0:
@@ -121,7 +118,7 @@ def isGoalState(self):
"""
for i in range(self.size):
for j in range(self.size):
- if i == j and j == self.size - 1:
+ if i == j == self.size - 1:
continue
if self.state[i][j] != (i) * self.size + (j + 1):
return False
@@ -149,7 +146,7 @@ def getHammingDistance(self):
ans = 0
for i in range(self.size):
for j in range(self.size):
- if self.state[i][j] != 0 and self.state[i][j] != i * 3 + (j + 1):
+ if self.state[i][j] not in [0, i * 3 + (j + 1)]:
ans = ans + 1
return ans
@@ -160,107 +157,67 @@ def __hash__(self):
def __gt__(self, other):
if self.optimizer == 0:
- if self.getManhattanDistance() > other.getManhattanDistance():
- return True
- else:
- return False
+ return self.getManhattanDistance() > other.getManhattanDistance()
elif self.optimizer == 1:
- if self.getHammingDistance() > other.getHammingDistance():
- return True
- else:
- return False
+ return self.getHammingDistance() > other.getHammingDistance()
elif self.optimizer == 2:
- if (
+ return (
self.getHammingDistance() + self.getManhattanDistance()
> other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
+ )
+
return True
def __ge__(self, other):
if self.optimizer == 0:
- if self.getManhattanDistance() >= other.getManhattanDistance():
- return True
- else:
- return False
+ return self.getManhattanDistance() >= other.getManhattanDistance()
elif self.optimizer == 1:
- if self.getHammingDistance() >= other.getHammingDistance():
- return True
- else:
- return False
+ return self.getHammingDistance() >= other.getHammingDistance()
elif self.optimizer == 2:
- if (
+ return (
self.getHammingDistance() + self.getManhattanDistance()
>= other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
+ )
+
return True
def __lt__(self, other):
if self.optimizer == 0:
- if self.getManhattanDistance() < other.getManhattanDistance():
- return True
- else:
- return False
+ return self.getManhattanDistance() < other.getManhattanDistance()
elif self.optimizer == 1:
- if self.getHammingDistance() < other.getHammingDistance():
- return True
- else:
- return False
+ return self.getHammingDistance() < other.getHammingDistance()
elif self.optimizer == 2:
- if (
+ return (
self.getHammingDistance() + self.getManhattanDistance()
< other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
+ )
+
return True
def __le__(self, other):
if self.optimizer == 0:
- if self.getManhattanDistance() <= other.getManhattanDistance():
- return True
- else:
- return False
+ return self.getManhattanDistance() <= other.getManhattanDistance()
elif self.optimizer == 1:
- if self.getHammingDistance() <= other.getHammingDistance():
- return True
- else:
- return False
+ return self.getHammingDistance() <= other.getHammingDistance()
elif self.optimizer == 2:
- if (
+ return (
self.getHammingDistance() + self.getManhattanDistance()
<= other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
+ )
+
return True
def __eq__(self, other):
if self.optimizer == 0:
- if self.getManhattanDistance() == other.getManhattanDistance():
- return True
- else:
- return False
+ return self.getManhattanDistance() == other.getManhattanDistance()
elif self.optimizer == 1:
- if self.getHammingDistance() == other.getHammingDistance():
- return True
- else:
- return False
+ return self.getHammingDistance() == other.getHammingDistance()
elif self.optimizer == 2:
- if (
+ return (
self.getHammingDistance() + self.getManhattanDistance()
== other.getHammingDistance() + self.getManhattanDistance()
- ):
- return True
- else:
- return False
+ )
+
return True
@@ -293,7 +250,7 @@ def breadth_first_search(self):
if self.isSolvable() == False:
return (None, None)
- closed = list()
+ closed = []
q = deque()
q.append(Node(state=self.state, depth=0))
while q:
@@ -315,17 +272,18 @@ def depth_first_search(self):
"""
if self.isSolvable() == False:
return (None, None)
- closed = list()
- q = list()
- q.append(Node(state=self.state, depth=0))
+ closed = []
+ q = [Node(state=self.state, depth=0)]
while q:
node = q.pop()
if node.isGoalState():
return (node.moves, len(closed))
if node.state not in closed:
closed.append(node.state)
- for action in node.getAvailableActions():
- q.append(node.getResultFromAction(action))
+ q.extend(
+ node.getResultFromAction(action)
+ for action in node.getAvailableActions()
+ )
return (None, None)
@@ -336,7 +294,7 @@ def uniform_cost_search(self, optimizer=0):
"""
if self.isSolvable() == False:
return (None, None)
- closed = list()
+ closed = []
q = PriorityQueue()
q.put(Node(state=self.state, depth=0, optimizer=optimizer))
while q:
@@ -357,7 +315,7 @@ def a_star(self):
"""
if self.isSolvable() == False:
return (None, None)
- closed = dict()
+ closed = {}
q = PriorityQueue()
node = Node(state=self.state, depth=0)
q.put((node.getManhattanDistance(), node))
diff --git a/Emoji Dictionary/emoji_dictionary.py b/Emoji Dictionary/emoji_dictionary.py
index 04949946c9c..61c5131bdfc 100644
--- a/Emoji Dictionary/emoji_dictionary.py
+++ b/Emoji Dictionary/emoji_dictionary.py
@@ -187,14 +187,14 @@ def backspace(self):
def space(self):
if self.target:
text = self.get()
- text = text + " "
+ text = f"{text} "
self.clear()
self.append(text)
def tab(self): # 5 spaces
if self.target:
text = self.get()
- text = text + " "
+ text = f"{text} "
self.clear()
self.append(text)
@@ -202,7 +202,7 @@ def copy(self):
# TODO: copy to clipboad
if self.target:
self.memory = self.get()
- self.label["text"] = "memory: " + self.memory
+ self.label["text"] = f"memory: {self.memory}"
print(self.memory)
def paste(self):
@@ -234,7 +234,7 @@ def search_emoji():
outputtxt.insert(END, "You have entered no emoji.")
else:
means = emoji.demojize(word)
- outputtxt.insert(END, "Meaning of Emoji : " + str(word) + "\n\n" + means)
+ outputtxt.insert(END, f"Meaning of Emoji : {str(word)}" + "\n\n" + means)
# main window created
diff --git a/EncryptionTool.py b/EncryptionTool.py
index f6600752fa6..cb6245f3d4d 100644
--- a/EncryptionTool.py
+++ b/EncryptionTool.py
@@ -46,49 +46,45 @@ def decrypt(enc_text):
def readAndDecrypt(filename):
- file = open(filename, "r")
- data = file.read()
- datalistint = []
- actualdata = []
- datalist = data.split(" ")
- datalist.remove("")
- datalistint = [float(data) for data in datalist]
- for data in datalist:
- current1 = int(decryptChar(data))
- current1 = chr(current1)
- actualdata.append(current1)
- file.close()
+ with open(filename, "r") as file:
+ data = file.read()
+ datalistint = []
+ actualdata = []
+ datalist = data.split(" ")
+ datalist.remove("")
+ datalistint = [float(data) for data in datalist]
+ for data in datalist:
+ current1 = int(decryptChar(data))
+ current1 = chr(current1)
+ actualdata.append(current1)
return actualdata
def readAndEncrypt(filename):
- file = open(filename, "r")
- data = file.read()
- datalist = list(data)
- encrypted_list = list()
- encrypted_list_str = list()
- for data in datalist:
- current = ord(data)
- current = encryptChar(current)
- encrypted_list.append(current)
- file.close()
+ with open(filename, "r") as file:
+ data = file.read()
+ datalist = list(data)
+ encrypted_list = []
+ encrypted_list_str = []
+ for data in datalist:
+ current = ord(data)
+ current = encryptChar(current)
+ encrypted_list.append(current)
return encrypted_list
def readAndEncryptAndSave(inp_file, out_file):
enc_list = readAndEncrypt(inp_file)
- output = open(out_file, "w")
- for enc in enc_list:
- output.write(str(enc) + " ")
- output.close()
+ with open(out_file, "w") as output:
+ for enc in enc_list:
+ output.write(f"{str(enc)} ")
def readAndDecryptAndSave(inp_file, out_file):
dec_list = readAndDecrypt(inp_file)
- output = open(out_file, "w")
- for dec in dec_list:
- output.write(str(dec))
- output.close()
+ with open(out_file, "w") as output:
+ for dec in dec_list:
+ output.write(str(dec))
# encryption
@@ -104,11 +100,8 @@ def readAndDecryptAndSave(inp_file, out_file):
reverse.append(current)
print(reverse)
-# saves encrypted in txt file
-output = open("encrypted.txt", "w")
-for v in values:
- output.write(str(v) + " ")
-output.close()
-
+with open("encrypted.txt", "w") as output:
+ for v in values:
+ output.write(f"{str(v)} ")
# read and decrypts
print(readAndDecrypt("encrypted.txt"))
diff --git a/Face_Mask_detection (haarcascade)/mask_detection.py b/Face_Mask_detection (haarcascade)/mask_detection.py
index 9ba4c34734b..c44aa84a397 100644
--- a/Face_Mask_detection (haarcascade)/mask_detection.py
+++ b/Face_Mask_detection (haarcascade)/mask_detection.py
@@ -29,11 +29,7 @@
data[0] = normalized_image_array
prediction = model.predict(data)
print(prediction)
- if prediction[0][0] > prediction[0][1]:
- str = "Mask"
- else:
- str = "Without-mask"
-
+ str = "Mask" if prediction[0][0] > prediction[0][1] else "Without-mask"
cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
cv2.putText(img, str, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 150, 0), 1)
cv2.imshow("Result", img)
diff --git a/Factorial.py b/Factorial.py
index 572e928985a..8ac962000a1 100644
--- a/Factorial.py
+++ b/Factorial.py
@@ -2,11 +2,7 @@
def factorial(num: int):
- if num >= 1:
- return num * factorial(num - 1)
-
- else:
- return 1
+ return num * factorial(num - 1) if num >= 1 else 1
try:
diff --git a/Fibonacci_sequence_recursive_sol.py b/Fibonacci_sequence_recursive_sol.py
index 01a508518dc..00f2510022e 100644
--- a/Fibonacci_sequence_recursive_sol.py
+++ b/Fibonacci_sequence_recursive_sol.py
@@ -1,8 +1,5 @@
def fib(term):
- if term <= 1:
- return term
- else:
- return fib(term - 1) + fib(term - 2)
+ return term if term <= 1 else fib(term - 1) + fib(term - 2)
# Change this value to adjust the number of terms in the sequence.
diff --git a/Flappy Bird - created with tkinter/Background.py b/Flappy Bird - created with tkinter/Background.py
index 78dc415a9f4..d84fb75d9b1 100644
--- a/Flappy Bird - created with tkinter/Background.py
+++ b/Flappy Bird - created with tkinter/Background.py
@@ -150,29 +150,29 @@ def run(self):
"""
# Enquanto o atributo "stop" for False, a animação continuará em um loop infinito
- if not self.__stop:
-
- # Move as imagens de background na posição X
- self.move(self.__background[0], -10, 0)
- self.move(self.__background[1], -10, 0)
- self.tag_lower(self.__background[0])
- self.tag_lower(self.__background[1])
- self.tag_lower(self.__background_default)
-
- # Se a primeira imagem da lista tiver saído da área do widget, uma nova será criada depois da segunda imagem
- if self.bbox(self.__background[0])[2] <= 0:
- # Deleta a primeira imagem da lista (imagem que saiu da área do widget)
- self.delete(self.__background[0])
- self.__background.remove(self.__background[0])
-
- # Cria uma nova imagem a partir da última imagem da animação
- width = self.bbox(self.__background[0])[2] + self.__width // 2
- self.__background.append(
- self.create_image(width, self.__height // 2, image=self.__bg_image)
- )
-
- # Executa novamente o método depois de um certo tempo
- self.after(self.animation_speed, self.run)
+ if self.__stop:
+ return
+ # Move as imagens de background na posição X
+ self.move(self.__background[0], -10, 0)
+ self.move(self.__background[1], -10, 0)
+ self.tag_lower(self.__background[0])
+ self.tag_lower(self.__background[1])
+ self.tag_lower(self.__background_default)
+
+ # Se a primeira imagem da lista tiver saído da área do widget, uma nova será criada depois da segunda imagem
+ if self.bbox(self.__background[0])[2] <= 0:
+ # Deleta a primeira imagem da lista (imagem que saiu da área do widget)
+ self.delete(self.__background[0])
+ self.__background.remove(self.__background[0])
+
+ # Cria uma nova imagem a partir da última imagem da animação
+ width = self.bbox(self.__background[0])[2] + self.__width // 2
+ self.__background.append(
+ self.create_image(width, self.__height // 2, image=self.__bg_image)
+ )
+
+ # Executa novamente o método depois de um certo tempo
+ self.after(self.animation_speed, self.run)
def stop(self):
"""
diff --git a/Flappy Bird - created with tkinter/Bird.py b/Flappy Bird - created with tkinter/Bird.py
index 56fdcd1d31c..893a77d392c 100644
--- a/Flappy Bird - created with tkinter/Bird.py
+++ b/Flappy Bird - created with tkinter/Bird.py
@@ -125,7 +125,7 @@ def checkCollision(self):
continue
# Se houver alguma colisão o pássaro morre
- if len(possible_collisions) >= 1:
+ if possible_collisions:
self.__isAlive = False
return not self.__isAlive
diff --git a/Flappy Bird - created with tkinter/Flappy Bird.py b/Flappy Bird - created with tkinter/Flappy Bird.py
index 308a7c6ea70..a8a48dc2ec0 100644
--- a/Flappy Bird - created with tkinter/Flappy Bird.py
+++ b/Flappy Bird - created with tkinter/Flappy Bird.py
@@ -43,7 +43,7 @@ def __init__(self):
# Configura a janela do programa
self.title(self.window_name)
- self.geometry("{}x{}".format(self.__width, self.__height))
+ self.geometry(f"{self.__width}x{self.__height}")
self.resizable(*self.window_rz)
self.attributes("-fullscreen", self.window_fullscreen)
self["bg"] = "black"
@@ -51,9 +51,7 @@ def __init__(self):
# Verifica se existem as imagens do jogo
for file in self.images_fp:
if not os.path.exists(file):
- raise FileNotFoundError(
- "The following file was not found:\n{}".format(file)
- )
+ raise FileNotFoundError(f"The following file was not found:\n{file}")
# Carrega a imagem do botão para começar o jogo
self.__startButton_image = Background.getPhotoImage(
@@ -196,32 +194,32 @@ def createScoreBoard(self):
# Define a fonte dos textos
font = (self.text_font, int(0.02196 * self.__width + 0.5))
- # Cria a imagem do placar no background
- self.__background.create_image(x, y, image=self.__scoreboard_image)
-
+ self.__background.create_image(time_x, y, image=self.__scoreboard_image)
# Cria texto para mostrar o score do último jogo
self.__background.create_text(
score_x,
score_y,
- text="Score: %s" % self.__score,
+ text=f"Score: {self.__score}",
fill=self.text_fill,
font=font,
)
+
# Cria texto para mostrar a melhor pontuação do jogador
self.__background.create_text(
bestScore_x,
bestScore_y,
- text="Best Score: %s" % self.__bestScore,
+ text=f"Best Score: {self.__bestScore}",
fill=self.text_fill,
font=font,
)
+
# Cria texto para mostrar o tempo de jogo
self.__background.create_text(
time_x,
time_y,
- text="Time: %s" % self.__time,
+ text=f"Time: {self.__time}",
fill=self.text_fill,
font=font,
)
@@ -341,15 +339,11 @@ def loadScore(self):
# Tenta carregar o placar do usuário
try:
- file = open(self.score_fp)
- self.__bestScore = int(file.read(), 2)
- file.close()
-
- # Se não for possível, será criado um arquivo para guardar o placar
+ with open(self.score_fp) as file:
+ self.__bestScore = int(file.read(), 2)
except BaseException:
- file = open(self.score_fp, "w")
- file.write(bin(self.__bestScore))
- file.close()
+ with open(self.score_fp, "w") as file:
+ file.write(bin(self.__bestScore))
def saveScore(self):
"""
diff --git a/Flappy Bird - created with tkinter/Settings.py b/Flappy Bird - created with tkinter/Settings.py
index 33eb2c1da6f..6b545d48019 100644
--- a/Flappy Bird - created with tkinter/Settings.py
+++ b/Flappy Bird - created with tkinter/Settings.py
@@ -81,10 +81,8 @@ def setOptions(self):
# Tenta abrir o arquivo parar leitura
try:
- file = open(self.settings_fp, "r")
- data = loads(file.read())
- file.close()
-
+ with open(self.settings_fp, "r") as file:
+ data = loads(file.read())
# Define os atributos com os valores obtidos do arquivo desde que sejam
# referentes à eventos ou estejam na lista de atributos permitidos.
@@ -92,24 +90,19 @@ def setOptions(self):
if "event" in attr or attr in attributes:
setattr(Settings, attr, data[attr])
- # Caso não exista um arquivo para obter as configurações, ele será criado
except BaseException:
# Caso não exista o diretório, o mesmo será criado.
if not os.path.exists(os.path.split(self.settings_fp)[0]):
os.mkdir(os.path.split(self.settings_fp)[0])
- file = open(self.settings_fp, "w")
-
- data = dict()
+ with open(self.settings_fp, "w") as file:
+ data = {
+ attr: Settings.__dict__[attr]
+ for attr in Settings.__dict__
+ if "event" in attr or attr in attributes
+ }
- # Armazena no arquivo atributos com seus valores padrões desde que sejam
- # referentes à eventos ou estejam na lista de atributos permitidos.
-
- for attr in Settings.__dict__:
- if "event" in attr or attr in attributes:
- data[attr] = Settings.__dict__[attr]
- # Coloca as informações no arquivo e o fecha
- file.write(dumps(data, indent=2))
- file.close()
+ # Coloca as informações no arquivo e o fecha
+ file.write(dumps(data, indent=2))
diff --git a/Flappy Bird - created with tkinter/Tubes.py b/Flappy Bird - created with tkinter/Tubes.py
index a6021f69ef5..80875b424de 100644
--- a/Flappy Bird - created with tkinter/Tubes.py
+++ b/Flappy Bird - created with tkinter/Tubes.py
@@ -31,7 +31,7 @@ def __init__(
raise TypeError(
"The background argument must be an instance of Background."
)
- if not len(fp) == 2:
+ if len(fp) != 2:
raise TypeError(
"The parameter fp should be a sequence containing the path of the images of the tube body and the tube mouth."
)
@@ -99,9 +99,6 @@ def createNewTubes(self):
Método para criar 2 novos tubos (baixo e cima) numa mesma posição X
"""
- # Cria uma lista para armazenar as partes do corpo do tubo de cima
- tube1 = []
-
# Define a posição X que o tubo de cima aparecerá inicialmente no background
width = self.__width + (self.__imageWidth)
@@ -113,12 +110,11 @@ def createNewTubes(self):
self.__height - (self.__bird_h * 2) - self.__imageHeight,
)
- # Cria e adiciona à lista do corpo do tubo de cima, a boca do tubo
- tube1.append(
+ tube1 = [
self.__background.create_image(
width, height, image=self.__background.tubeImages[1]
)
- )
+ ]
# Cria uma nova imagem na lista de imagens com a altura sendo igual a posição Y do tubo de cima
self.__background.tubeImages[0].append(
@@ -141,21 +137,14 @@ def createNewTubes(self):
)
)
- ###############################################################################################################
- ###############################################################################################################
-
- # Cria uma lista para armazenar as partes do corpo do tubo de baixo
- tube2 = []
-
# A posição Y do tubo de baixo é calculada com base na posição do tubo de cima, mais o tamanho do pássaro
height = height + (self.__bird_h * 2) + self.__imageHeight - 1
- # Cria e adiciona à lista do corpo do tubo de baixo, a boca do tubo
- tube2.append(
+ tube2 = [
self.__background.create_image(
width, height, image=self.__background.tubeImages[1]
)
- )
+ ]
# Define a altura da imagem do corpo do tubo de baixo
height = self.__height - height
@@ -267,15 +256,17 @@ def move(self):
# Se a posição "x2" do tubo for menor que a posição "x1" do pássaro e se ainda não tiver sido
# pontuado este mesmo cano, o método para pontuar será chamado.
- if (self.__width / 2) - (self.__bird_w / 2) - self.__move < x2:
- if x2 <= (self.__width / 2) - (self.__bird_w / 2):
-
- # Verifica se o tubo está na lista de tubos passados
- if not tube[0] in self.__pastTubes:
- # Chama o método para pontuar e adiciona o tubo pontuado à lista de tubos passados
- self.__score_method()
- self.__pastTubes.append(tube[0])
- scored = True
+ if (self.__width / 2) - (
+ self.__bird_w / 2
+ ) - self.__move < x2 <= (self.__width / 2) - (
+ self.__bird_w / 2
+ ) and tube[
+ 0
+ ] not in self.__pastTubes:
+ # Chama o método para pontuar e adiciona o tubo pontuado à lista de tubos passados
+ self.__score_method()
+ self.__pastTubes.append(tube[0])
+ scored = True
# Move cada parte do copo do tubo no background
for body in tube:
diff --git a/Google_Image_Downloader/image_grapper.py b/Google_Image_Downloader/image_grapper.py
index a922894a8d0..cf2de5ae83f 100644
--- a/Google_Image_Downloader/image_grapper.py
+++ b/Google_Image_Downloader/image_grapper.py
@@ -63,7 +63,7 @@ def search_for_image():
counter = 0
for re in images:
rs = requests.get(re)
- with open("img" + str(counter) + ".jpg", "wb") as file:
+ with open(f"img{str(counter)}.jpg", "wb") as file:
file.write(rs.content)
# urlretrieve(re, 'img' + str(count) + '.jpg')
@@ -73,9 +73,6 @@ def search_for_image():
def download_wallpapers_1080p():
- cont = set() # Stores the links of images
- temp = set() # Refines the links to download images
-
print("Enter data to download wallpapers: ")
data = input()
search_query = {"q": data}
@@ -85,29 +82,24 @@ def download_wallpapers_1080p():
request = Request(g, headers=usr_agent)
r = urlopen(request).read()
sew = BeautifulSoup(r, "html.parser")
- count = 0
- for links in sew.find_all("a"):
- if "wallpaperscraft.com/download" in links.get("href"):
- cont.add(links.get("href"))
- for re in cont:
- # print all valid links
- # print('https://wallpaperscraft.com/image/' + re[31:-10] + '_' + re[-9:] + '.jpg')
-
- temp.add(
- "https://wallpaperscraft.com/image/" + re[31:-10] + "_" + re[-9:] + ".jpg"
- )
+ cont = {
+ links.get("href")
+ for links in sew.find_all("a")
+ if "wallpaperscraft.com/download" in links.get("href")
+ }
+
+ temp = {
+ f"https://wallpaperscraft.com/image/{re[31:-10]}_{re[-9:]}.jpg"
+ for re in cont
+ }
# Goes to Each link and downloads high resolution images
- for re in temp:
+ for count, re in enumerate(temp):
rs = requests.get(re)
- with open("img" + str(count) + ".jpg", "wb") as file:
+ with open(f"img{str(count)}.jpg", "wb") as file:
file.write(rs.content)
- # urlretrieve(re, 'img' + str(count) + '.jpg')
-
- count += 1
-
return True
diff --git a/Gregorian_Calendar.py b/Gregorian_Calendar.py
index 64c7d2a1a27..b2149e284f7 100644
--- a/Gregorian_Calendar.py
+++ b/Gregorian_Calendar.py
@@ -9,14 +9,10 @@
def is_leap(year):
- leap = False
if year % 4 == 0:
- leap = True
- if year % 100 == 0:
- leap = False
- if year % 400 == 0:
- leap = True
- return leap
+ return year % 400 == 0 if year % 100 == 0 else True
+ else:
+ return False
year = int(input("Enter the year here: "))
diff --git a/GroupSms_Way2.py b/GroupSms_Way2.py
index 04f9f562249..369f4cd9475 100644
--- a/GroupSms_Way2.py
+++ b/GroupSms_Way2.py
@@ -46,9 +46,10 @@
send_sms_url = "http://site24.way2sms.com/smstoss.action?"
opener.addheaders = [
- ("Referer", "http://site25.way2sms.com/sendSMS?Token=%s" % jession_id)
+ ("Referer", f"http://site25.way2sms.com/sendSMS?Token={jession_id}")
]
+
try:
for number in num:
send_sms_data = (
diff --git a/Guessing_Game.py b/Guessing_Game.py
index aaeb895384b..8448d9b5ddd 100644
--- a/Guessing_Game.py
+++ b/Guessing_Game.py
@@ -24,7 +24,7 @@ def guessing_game(GUESS_RANGE, GUESS_LIMIT):
ATTEMPTS_TOOK = ATTEMPTS_ALLOWED - GUESS_LIMIT
print(f"You nailed it! And it only took you {ATTEMPTS_TOOK} attempts.")
done = True
- if GUESS_LIMIT > 0 and not done:
+ if not done:
print(f"You still have {GUESS_LIMIT} chances left.\n")
GUESS = int(input("Try a new guess: "))
# Another input validation loop.
diff --git a/Hand-Motion-Detection/hand_motion_recognizer.py b/Hand-Motion-Detection/hand_motion_recognizer.py
index 9e9db13ce9e..a8615d037f1 100644
--- a/Hand-Motion-Detection/hand_motion_recognizer.py
+++ b/Hand-Motion-Detection/hand_motion_recognizer.py
@@ -12,37 +12,37 @@
with mp_hands.Hands(min_detection_confidence=0.8, min_tracking_confidence=0.5) as hands:
while cap.isOpened():
ret, frame = cap.read()
-
+
# BGR 2 RGB
image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
-
+
# Flip on horizontal
image = cv2.flip(image, 1)
-
+
# Set flag
image.flags.writeable = False
-
+
# Detections
results = hands.process(image)
-
+
# Set flag to true
image.flags.writeable = True
-
+
# RGB 2 BGR
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
-
+
# Detections
print(results)
-
+
# Rendering results
if results.multi_hand_landmarks:
- for num, hand in enumerate(results.multi_hand_landmarks):
+ for hand in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(image, hand, mp_hands.HAND_CONNECTIONS,
mp_drawing.DrawingSpec(color=(121, 22, 76), thickness=2, circle_radius=4),
mp_drawing.DrawingSpec(color=(250, 44, 250), thickness=2, circle_radius=2),
)
-
-
+
+
cv2.imshow('Hand Tracking', image)
if cv2.waitKey(10) & 0xFF == ord('q'):
diff --git a/Hotel-Management.py b/Hotel-Management.py
index b8e4cfcbfeb..0961b79c561 100644
--- a/Hotel-Management.py
+++ b/Hotel-Management.py
@@ -85,12 +85,10 @@ def add():
print("Online payment")
print("")
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
-
+ with open("Management.txt", "r") as File:
+ string = File.read()
+ string = string.replace("'", '"')
+ dictionary = json.loads(string)
if len(dictionary.get("Room")) == 0:
Room_num = "501"
else:
@@ -114,10 +112,8 @@ def add():
dictionary["Price"].append(Money)
dictionary["Room"].append(Room_num)
- File = open("Management.txt", "w", encoding="utf-8")
- File.write(str(dictionary))
- File.close()
-
+ with open("Management.txt", "w", encoding="utf-8") as File:
+ File.write(str(dictionary))
print("")
print("Your data has been successfully added to our database.")
@@ -129,37 +125,33 @@ def add():
filecheck = os.path.isfile("Management.txt")
if filecheck == False:
- File = open("Management.txt", "a", encoding="utf-8")
- temp1 = {
- "First_Name": [],
- "Last_Name": [],
- "Phone_num": [],
- "Room_Type": [],
- "Days": [],
- "Price": [],
- "Room": [],
- }
- File.write(str(temp1))
- File.close()
+ with open("Management.txt", "a", encoding="utf-8") as File:
+ temp1 = {
+ "First_Name": [],
+ "Last_Name": [],
+ "Phone_num": [],
+ "Room_Type": [],
+ "Days": [],
+ "Price": [],
+ "Room": [],
+ }
+ File.write(str(temp1))
def modify():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
-
+ with open("Management.txt", "r") as File:
+ string = File.read()
+ string = string.replace("'", '"')
+ dictionary = json.loads(string)
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
+ print("")
if dict_len == 0:
- print("")
print("There is no data in our database")
print("")
menu()
else:
- print("")
Room = input("Enter your Room Number: ")
listt = dictionary["Room"]
@@ -211,21 +203,18 @@ def modify():
def search():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
-
+ with open("Management.txt", "r") as File:
+ string = File.read()
+ string = string.replace("'", '"')
+ dictionary = json.loads(string)
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
+ print("")
if dict_len == 0:
- print("")
print("There is no data in our database")
print("")
menu()
else:
- print("")
Room = input("Enter your Room Number: ")
print("")
@@ -253,21 +242,18 @@ def search():
def remove():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
-
+ with open("Management.txt", "r") as File:
+ string = File.read()
+ string = string.replace("'", '"')
+ dictionary = json.loads(string)
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
+ print("")
if dict_len == 0:
- print("")
print("There is no data in our database")
print("")
menu()
else:
- print("")
Room = input("Enter your Room Number: ")
print("")
@@ -311,10 +297,8 @@ def remove():
dictionary["Room"] = None
dictionary["Room"] = listt_num
- file1 = open("Management.txt", "w", encoding="utf-8")
- file1.write(str(dictionary))
- file1.close()
-
+ with open("Management.txt", "w", encoding="utf-8") as file1:
+ file1.write(str(dictionary))
print("Details has been removed successfully")
exit_menu()
@@ -322,12 +306,10 @@ def remove():
def view():
- File = open("Management.txt", "r")
- string = File.read()
- string = string.replace("'", '"')
- dictionary = json.loads(string)
- File.close()
-
+ with open("Management.txt", "r") as File:
+ string = File.read()
+ string = string.replace("'", '"')
+ dictionary = json.loads(string)
dict_num = dictionary.get("Room")
dict_len = len(dict_num)
if dict_len == 0:
@@ -360,7 +342,7 @@ def view():
print("Room Number:", listt_num[index])
print("")
- index = index + 1
+ index += 1
exit_menu()
diff --git a/ImageDownloader/img_downloader.py b/ImageDownloader/img_downloader.py
index 70fea5fced6..61319a32db3 100644
--- a/ImageDownloader/img_downloader.py
+++ b/ImageDownloader/img_downloader.py
@@ -11,7 +11,7 @@ def ImageDownloader(url):
img_addrs = re.findall(p, text)
for i in img_addrs:
- os.system("wget {}".format(i))
+ os.system(f"wget {i}")
return "DONE"
diff --git a/Infix_to_Postfix.py b/Infix_to_Postfix.py
index bdffa82e63c..695a9415929 100644
--- a/Infix_to_Postfix.py
+++ b/Infix_to_Postfix.py
@@ -15,7 +15,7 @@ def __init__(self, capacity):
# check if the stack is empty
def isEmpty(self):
- return True if self.top == -1 else False
+ return self.top == -1
# Return the value of the top of the stack
def peek(self):
@@ -23,11 +23,10 @@ def peek(self):
# Pop the element from the stack
def pop(self):
- if not self.isEmpty():
- self.top -= 1
- return self.array.pop()
- else:
+ if self.isEmpty():
return "$"
+ self.top -= 1
+ return self.array.pop()
# Push the element to the stack
def push(self, op):
@@ -45,7 +44,7 @@ def notGreater(self, i):
try:
a = self.precedence[i]
b = self.precedence[self.peek()]
- return True if a <= b else False
+ return a <= b
except KeyError:
return False
diff --git a/JARVIS/JARVIS.py b/JARVIS/JARVIS.py
index 5135086c978..e4db8193b16 100644
--- a/JARVIS/JARVIS.py
+++ b/JARVIS/JARVIS.py
@@ -126,7 +126,7 @@ def on_press(key):
k = key.name # other keys
if k in ["1", "2", "left", "right"]: # keys of interest
# self.keys.append(k) # store it in global-like variable
- print("Key pressed: " + k)
+ print(f"Key pressed: {k}")
return False # stop listener; remove this if want more keys
@@ -215,7 +215,6 @@ def get_app(Q):
subprocess.call(["discord.exe"])
elif Q == "open browser":
subprocess.call(["C:\\Program Files\\Internet Explorer\\iexplore.exe"])
- # patch-1
elif Q == "open youtube":
webbrowser.open("https://www.youtube.com/") # open youtube
elif Q == "open google":
@@ -239,15 +238,11 @@ def get_app(Q):
except Exception as e:
print(e)
speak("Sorry, I can't send the email.")
- # =======
- # master
elif Q == "Take screenshot":
snapshot = ImageGrab.grab()
drive_letter = "C:\\"
- folder_name = r"downloaded-files"
folder_time = datetime.datetime.now().strftime("%Y-%m-%d_%I-%M-%S_%p")
- extention = ".jpg"
- folder_to_save_files = drive_letter + folder_name + folder_time + extention
+ folder_to_save_files = f"{drive_letter}downloaded-files{folder_time}.jpg"
snapshot.save(folder_to_save_files)
elif Q == "Jokes":
diff --git a/Job_scheduling.py b/Job_scheduling.py
index 6ac96c24abd..70d3180baae 100644
--- a/Job_scheduling.py
+++ b/Job_scheduling.py
@@ -72,10 +72,7 @@ def feasible(self, profit_jobs: List[int], deadline: List[int]) -> bool:
while k < len(self.tmp):
self.job = self.tmp[k]
- if self.job in self.jobs:
- self.jobindex = self.jobs.index(self.job)
- else:
- self.jobindex = 0
+ self.jobindex = self.jobs.index(self.job) if self.job in self.jobs else 0
self.dlineval = deadline[self.jobindex]
self.ftest = k + 1
k += 1
@@ -98,9 +95,8 @@ def main():
]
# midresult stores jobs in sorting order of deadline
midresult = []
- for i in range(len(jobs)):
- current_job = []
- current_job.extend((jobs[i].deadline, jobs[i].profit, jobs[i].job_id))
+ for job_ in jobs:
+ current_job = [job_.deadline, job_.profit, job_.job_id]
midresult.append(current_job)
midresult.sort(key=lambda k: (k[0], -k[1]))
(deadline, profit, jobs) = map(list, zip(*midresult))
@@ -112,7 +108,7 @@ def main():
finalprofit = []
finaldl = []
- for i, item in enumerate(scheduled_jobs):
+ for item in scheduled_jobs:
jobsindex = jobs.index(item)
finalprofit.append(profit[jobsindex])
finaldl.append(deadline[jobsindex])
diff --git a/JustDialScrapperGUI/Justdial Scrapper GUI.py b/JustDialScrapperGUI/Justdial Scrapper GUI.py
index 2dd4803f0bb..277a4bfa944 100644
--- a/JustDialScrapperGUI/Justdial Scrapper GUI.py
+++ b/JustDialScrapperGUI/Justdial Scrapper GUI.py
@@ -82,9 +82,7 @@ def get_rating(body):
def get_rating_count(body):
text = body.find("span", {"class": "rt_count"}).string
- # Get only digits
- rating_count = "".join(i for i in text if i.isdigit())
- return rating_count
+ return "".join(i for i in text if i.isdigit())
@staticmethod
def get_address(body):
@@ -100,7 +98,7 @@ def get_location(body):
latitude = text_list[3].strip().replace("'", "")
longitude = text_list[4].strip().replace("'", "")
- return latitude + ", " + longitude
+ return f"{latitude}, {longitude}"
def start_scrapping_logic(self):
page_number = 1
@@ -109,84 +107,82 @@ def start_scrapping_logic(self):
total_url = "https://www.justdial.com/{0}/{1}".format(self.location, self.query)
fields = ["Name", "Phone", "Rating", "Rating Count", "Address", "Location"]
- out_file = open("{0}.csv".format(self.file_name), "w")
- csvwriter = csv.DictWriter(out_file, delimiter=",", fieldnames=fields)
- csvwriter.writerow(
- {
- "Name": "Name", # Shows the name
- "Phone": "Phone", # shows the phone
- "Rating": "Rating", # shows the ratings
- "Rating Count": "Rating Count", # Shows the stars for ex: 4 stars
- "Address": "Address", # Shows the address of the place
- "Location": "Location", # shows the location
- }
- )
+ with open("{0}.csv".format(self.file_name), "w") as out_file:
+ csvwriter = csv.DictWriter(out_file, delimiter=",", fieldnames=fields)
+ csvwriter.writerow(
+ {
+ "Name": "Name", # Shows the name
+ "Phone": "Phone", # shows the phone
+ "Rating": "Rating", # shows the ratings
+ "Rating Count": "Rating Count", # Shows the stars for ex: 4 stars
+ "Address": "Address", # Shows the address of the place
+ "Location": "Location", # shows the location
+ }
+ )
- progress_value = 0
- while True:
- # Check if reached end of result
- if page_number > 50:
- progress_value = 100
- self.progressbar["value"] = progress_value
- break
+ progress_value = 0
+ while True:
+ # Check if reached end of result
+ if page_number > 50:
+ progress_value = 100
+ self.progressbar["value"] = progress_value
+ break
+
+ if progress_value != 0:
+ progress_value += 1
+ self.label_progress["text"] = "{0}{1}".format(progress_value, "%")
+ self.progressbar["value"] = progress_value
+
+ url = f"{total_url}/page-{page_number}"
+ print("{0} {1}, {2}".format("Scrapping page number: ", page_number, url))
+ req = urllib.request.Request(
+ url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"}
+ )
+ page = urllib.request.urlopen(req)
+
+ soup = BeautifulSoup(page.read(), "html.parser")
+ services = soup.find_all("li", {"class": "cntanr"})
+
+ # Iterate through the 10 results in the page
- if progress_value != 0:
progress_value += 1
self.label_progress["text"] = "{0}{1}".format(progress_value, "%")
self.progressbar["value"] = progress_value
- url = total_url + "/page-%s" % page_number
- print("{0} {1}, {2}".format("Scrapping page number: ", page_number, url))
- req = urllib.request.Request(
- url, headers={"User-Agent": "Mozilla/5.0 (Windows NT 6.1; Win64; x64)"}
- )
- page = urllib.request.urlopen(req)
-
- soup = BeautifulSoup(page.read(), "html.parser")
- services = soup.find_all("li", {"class": "cntanr"})
-
- # Iterate through the 10 results in the page
-
- progress_value += 1
- self.label_progress["text"] = "{0}{1}".format(progress_value, "%")
- self.progressbar["value"] = progress_value
-
- for service_html in services:
- try:
- # Parse HTML to fetch data
- dict_service = {}
- name = self.get_name(service_html)
- print(name)
- phone = self.get_phone_number(service_html)
- rating = self.get_rating(service_html)
- count = self.get_rating_count(service_html)
- address = self.get_address(service_html)
- location = self.get_location(service_html)
- if name is not None:
- dict_service["Name"] = name
- if phone is not None:
- print("getting phone number")
- dict_service["Phone"] = phone
- if rating is not None:
- dict_service["Rating"] = rating
- if count is not None:
- dict_service["Rating Count"] = count
- if address is not None:
- dict_service["Address"] = address
- if location is not None:
- dict_service["Address"] = location
-
- # Write row to CSV
- csvwriter.writerow(dict_service)
-
- print("#" + str(service_count) + " ", dict_service)
- service_count += 1
- except AttributeError:
- print("AttributeError Occurred 101")
-
- page_number += 1
-
- out_file.close()
+ for service_html in services:
+ try:
+ # Parse HTML to fetch data
+ dict_service = {}
+ name = self.get_name(service_html)
+ print(name)
+ phone = self.get_phone_number(service_html)
+ rating = self.get_rating(service_html)
+ count = self.get_rating_count(service_html)
+ address = self.get_address(service_html)
+ location = self.get_location(service_html)
+ if name is not None:
+ dict_service["Name"] = name
+ if phone is not None:
+ print("getting phone number")
+ dict_service["Phone"] = phone
+ if rating is not None:
+ dict_service["Rating"] = rating
+ if count is not None:
+ dict_service["Rating Count"] = count
+ if address is not None:
+ dict_service["Address"] = address
+ if location is not None:
+ dict_service["Address"] = location
+
+ # Write row to CSV
+ csvwriter.writerow(dict_service)
+
+ print(f"#{str(service_count)} ", dict_service)
+ service_count += 1
+ except AttributeError:
+ print("AttributeError Occurred 101")
+
+ page_number += 1
class JDScrapperGUI:
diff --git a/Koch Curve/koch curve.py b/Koch Curve/koch curve.py
index 77b31cc22f5..6b727c32b41 100644
--- a/Koch Curve/koch curve.py
+++ b/Koch Curve/koch curve.py
@@ -28,7 +28,7 @@ def snowflake(lengthSide, levels):
# Do not change the turtle’s heading.
t.backward(length / 2.0)
t.pendown()
- for i in range(3):
+ for _ in range(3):
# Pull the pen down – drawing when moving.
snowflake(length, 4)
t.right(120)
diff --git a/Letter_Counter.py b/Letter_Counter.py
index b900c72b4dc..e14168ad19f 100644
--- a/Letter_Counter.py
+++ b/Letter_Counter.py
@@ -15,7 +15,7 @@ def printt():
# Get the count and display results.
letter_count = message.count(letter)
- a = "your message has " + str(letter_count) + " " + letter + "'s in it."
+ a = f"your message has {str(letter_count)} {letter}" + "'s in it."
labl = tk.Label(root, text=a, font=("arial", 15), fg="black").place(x=10, y=220)
diff --git a/List.py b/List.py
index 34d29322069..40fc77e0c85 100644
--- a/List.py
+++ b/List.py
@@ -6,8 +6,7 @@
List.insert(0, 6)
print(List)
List.remove(6)
-List.append(9)
-List.append(1)
+List.extend((9, 1))
List.sort()
print(List)
List.pop()
diff --git a/Luhn_Algorithm.py b/Luhn_Algorithm.py
index 51eb03672aa..8a49e288397 100644
--- a/Luhn_Algorithm.py
+++ b/Luhn_Algorithm.py
@@ -18,6 +18,7 @@
David Costell (DontEatThemCookies on GitHub)
"""
+
# Input
CC = input("Enter number to validate (e.g. 7992739871): ")
if len(CC) < 10 or len(CC) > 10:
@@ -47,14 +48,15 @@
for i in tobedoubled:
if i > 9:
splitdigit = str(i)
- for index in range(0, len(splitdigit), 1):
- newdoubled.append(splitdigit[index : index + 1])
+ newdoubled.extend(
+ splitdigit[index : index + 1] for index in range(len(splitdigit))
+ )
+
tobedoubled.remove(i)
newdoubled = [int(i) for i in newdoubled]
# Unify all lists into one (luhnsum)
-luhnsum = []
-luhnsum.extend(tobedoubled)
+luhnsum = list(tobedoubled)
luhnsum.extend(newdoubled)
luhnsum.extend(remaining)
diff --git a/Memory_game.py b/Memory_game.py
index aca7f2fe81c..4a5ce49daff 100644
--- a/Memory_game.py
+++ b/Memory_game.py
@@ -23,7 +23,7 @@ def create(card):
random.shuffle(card1)
state = 0
exposed = []
- for i in range(0, 16, 1):
+ for i in range(16):
exposed.insert(i, False)
@@ -47,7 +47,7 @@ def mouseclick(pos):
def draw(canvas):
global card1
gap = 0
- for i in range(0, 16, 1):
+ for i in range(16):
if exposed[i] == False:
canvas.draw_polygon(
[[0 + gap, 0], [0 + gap, 100], [50 + gap, 100], [50 + gap, 0]],
diff --git a/MobiusFunction.py b/MobiusFunction.py
index ba1d3561658..64b2bb88a7d 100644
--- a/MobiusFunction.py
+++ b/MobiusFunction.py
@@ -3,10 +3,7 @@ def is_square_free(factors):
This functions takes a list of prime factors as input.
returns True if the factors are square free.
"""
- for i in factors:
- if factors.count(i) > 1:
- return False
- return True
+ return all(factors.count(i) <= 1 for i in factors)
def prime_factors(n):
@@ -15,7 +12,7 @@ def prime_factors(n):
"""
i = 2
factors = []
- while i * i <= n:
+ while i**2 <= n:
if n % i:
i += 1
else:
@@ -32,9 +29,6 @@ def mobius_function(n):
"""
factors = prime_factors(n)
if is_square_free(factors):
- if len(factors) % 2 == 0:
- return 1
- elif len(factors) % 2 != 0:
- return -1
+ return 1 if len(factors) % 2 == 0 else -1
else:
return 0
diff --git a/Number reverse.py b/Number reverse.py
index 1f84f917744..130d0656bc8 100644
--- a/Number reverse.py
+++ b/Number reverse.py
@@ -1,7 +1,7 @@
n=int(input("Enter number: "))
rev=0
-while(n>0):
+while (n>0):
dig=n%10
rev=rev*10+dig
- n=n//10
+ n //= 10
print("Reverse of the number:",rev)
diff --git a/Organise.py b/Organise.py
index 4133e4138fc..e7e3e05155a 100644
--- a/Organise.py
+++ b/Organise.py
@@ -64,15 +64,15 @@ def ChangeDirectory(dir):
def Organize(dirs, name):
try:
os.mkdir(name)
- print("{} Folder Created".format(name))
+ print(f"{name} Folder Created")
except WindowsError:
- print("{} Folder Exist".format(name))
+ print(f"{name} Folder Exist")
- src = "{}\\{}".format(destLocation, dirs)
- dest = "{}\{}".format(destLocation, name)
+ src = f"{destLocation}\\{dirs}"
+ dest = f"{destLocation}\{name}"
os.chdir(dest)
- shutil.move(src, "{}\\{}".format(dest, dirs))
+ shutil.move(src, f"{dest}\\{dirs}")
print(os.getcwd())
os.chdir(destLocation)
@@ -88,23 +88,18 @@ def Organize(dirs, name):
"Compressed",
]
for dirs in os.listdir(os.getcwd()):
- if 1:
- for name, extensions_list in zip(
- TYPES_LIST,
- [
- EXT_VIDEO_LIST,
- EXT_IMAGE_LIST,
- EXT_DOCUMENT_LIST,
- EXT_MUSIC_LIST,
- EXT_CODE_LIST,
- EXT_EXECUTABLE_LIST,
- EXT_COMPRESSED_LIST,
- ],
- ):
- if dirs.split(".")[-1].upper() in extensions_list:
- Organize(dirs, name)
- else:
- if dirs not in TYPES_LIST:
- Organize(dirs, "Folders")
-
+ for name, extensions_list in zip(
+ TYPES_LIST,
+ [
+ EXT_VIDEO_LIST,
+ EXT_IMAGE_LIST,
+ EXT_DOCUMENT_LIST,
+ EXT_MUSIC_LIST,
+ EXT_CODE_LIST,
+ EXT_EXECUTABLE_LIST,
+ EXT_COMPRESSED_LIST,
+ ],
+ ):
+ if dirs.split(".")[-1].upper() in extensions_list:
+ Organize(dirs, name)
print("Done Arranging Files and Folder in your specified directory")
diff --git a/PDF/header_footer.py b/PDF/header_footer.py
index f7b50037796..2afb4f12aa3 100644
--- a/PDF/header_footer.py
+++ b/PDF/header_footer.py
@@ -18,8 +18,7 @@ def footer(self):
# Arial italic 8
self.set_font("Arial", "I", 8)
# set Page number at the bottom
- self.cell(0, 10, "Page No {}".format(self.page_no()), 0, 0, "C")
- pass
+ self.cell(0, 10, f"Page No {self.page_no()}", 0, 0, "C")
pdf = MyPdf()
diff --git a/PDF/images.py b/PDF/images.py
index ad3c4033908..6b50707fa35 100644
--- a/PDF/images.py
+++ b/PDF/images.py
@@ -40,6 +40,6 @@
pdf.image("images\\" + filename, 0, 0, width, height)
except OSError:
- print("Skipped : " + filename)
+ print(f"Skipped : {filename}")
pdf.output("output.pdf", "F")
diff --git a/PONG_GAME.py b/PONG_GAME.py
index 8ddec6661de..53c08219342 100644
--- a/PONG_GAME.py
+++ b/PONG_GAME.py
@@ -99,17 +99,11 @@ def draw(canvas):
or ball_pos[1] >= (paddle1_pos + PAD_HEIGHT / 2 + HEIGHT / 2)
) and ball_pos[0] == (PAD_WIDTH + BALL_RADIUS):
score2 += 1
- else:
- pass
-
if (
ball_pos[1] <= (paddle2_pos + HEIGHT / 2 - PAD_HEIGHT / 2)
or ball_pos[1] >= (paddle2_pos + PAD_HEIGHT / 2 + HEIGHT / 2)
) and ball_pos[0] == (WIDTH - PAD_WIDTH - BALL_RADIUS):
score1 += 1
- else:
- pass
-
canvas.draw_text(str(score1), (250, 30), 40, "White")
canvas.draw_text(str(score2), (330, 30), 40, "White")
@@ -129,9 +123,9 @@ def keydown(key):
def keyup(key):
global paddle1_vel, paddle2_vel
- if key == simplegui.KEY_MAP["down"] or key == simplegui.KEY_MAP["up"]:
+ if key in [simplegui.KEY_MAP["down"], simplegui.KEY_MAP["up"]]:
paddle1_vel = 0
- if key == simplegui.KEY_MAP["w"] or key == simplegui.KEY_MAP["s"]:
+ if key in [simplegui.KEY_MAP["w"], simplegui.KEY_MAP["s"]]:
paddle2_vel = 0
diff --git a/Password Generator/pass_gen.py b/Password Generator/pass_gen.py
index 298f5931192..e26a6291a0c 100644
--- a/Password Generator/pass_gen.py
+++ b/Password Generator/pass_gen.py
@@ -14,18 +14,13 @@ def gen_sequence(
str.digits,
str.punctuation,
]
- sequence = ""
- for x in range(len(conditions)):
- if conditions[x]:
- sequence += possible_characters[x]
- else:
- pass
- return sequence
+ return "".join(
+ possible_characters[x] for x in range(len(conditions)) if conditions[x]
+ )
@staticmethod
def gen_password(sequence, passlength=8):
- password = "".join((secrets.choice(sequence) for i in range(passlength)))
- return password
+ return "".join(secrets.choice(sequence) for _ in range(passlength))
class Interface:
@@ -60,10 +55,7 @@ def generate_password(self, lenght):
def list_to_vertical_string(list):
- to_return = ""
- for member in list:
- to_return += f"{member}\n"
- return to_return
+ return "".join(f"{member}\n" for member in list)
class Run:
diff --git a/Patterns/pattern1.py b/Patterns/pattern1.py
index ac3869e064e..a15c2295d96 100644
--- a/Patterns/pattern1.py
+++ b/Patterns/pattern1.py
@@ -16,7 +16,7 @@ def pattern(lines):
for i in reversed(range(lines+1)):
t = ""
k = 1
- for m in range(i):
+ for _ in range(i):
if k == 10:
k = 0
t = str(t) + str(k)
diff --git a/Patterns/pattern2.py b/Patterns/pattern2.py
index 627f560de98..a58697b34fa 100644
--- a/Patterns/pattern2.py
+++ b/Patterns/pattern2.py
@@ -15,7 +15,7 @@ def main():
def pattern(lines):
t = 0
m = lines + 1
- for i in reversed(range(lines+1)):
+ for _ in reversed(range(lines+1)):
pattern = "@"*(m)
format = " "*t
t = t + 1
diff --git a/Patterns/patterns.py b/Patterns/patterns.py
index c074987e72f..18ad57a9807 100644
--- a/Patterns/patterns.py
+++ b/Patterns/patterns.py
@@ -7,10 +7,10 @@
# * * * * *
for i in range(1, 6):
- for j in range(0, i):
+ for _ in range(i):
print("*", end=" ")
- for j in range(1, (2 * (5 - i)) + 1):
+ for _ in range(1, (2 * (5 - i)) + 1):
print(" ", end="")
print("")
@@ -27,10 +27,10 @@
for i in range(1, 6):
- for j in range(0, (2 * (i - 1)) + 1):
+ for _ in range((2 * (i - 1)) + 1):
print(" ", end="")
- for j in range(0, 6 - i):
+ for _ in range(6 - i):
print("*", end=" ")
print("")
diff --git a/PongPong_Game/pong/load.py b/PongPong_Game/pong/load.py
index f06ff73da4e..1cc88b17eff 100644
--- a/PongPong_Game/pong/load.py
+++ b/PongPong_Game/pong/load.py
@@ -5,30 +5,25 @@
def load_balls(win_size: Tuple, radius: float, speed: Tuple, batch=None):
- balls = []
ball_x = win_size[0] / 2
ball_y = win_size[1] / 2
new_ball = ball.BallObject(x=ball_x, y=ball_y, radius=radius, batch=batch)
new_ball.velocity_x, new_ball.velocity_y = speed[0], speed[1]
- balls.append(new_ball)
- return balls
+ return [new_ball]
def load_paddles(
paddle_pos: Tuple, width: float, height: float, acc: Tuple, batch=None
):
- paddles = []
new_paddle = paddle.Paddle(
x=paddle_pos[0], y=paddle_pos[1], width=width, height=height, batch=batch
)
new_paddle.rightx = new_paddle.x + width
new_paddle.acc_left, new_paddle.acc_right = acc[0], acc[1]
- paddles.append(new_paddle)
- return paddles
+ return [new_paddle]
def load_rectangles(win_size: Tuple, border: float, batch=None):
- rectangles = []
top = rectangle.RectangleObject(
x=0, y=win_size[1] - border, width=win_size[0], height=border, batch=batch
)
@@ -38,5 +33,4 @@ def load_rectangles(win_size: Tuple, border: float, batch=None):
right = rectangle.RectangleObject(
x=win_size[0] - border, y=0, width=border, height=win_size[1], batch=batch
)
- rectangles.extend([left, top, right])
- return rectangles
+ return [left, top, right]
diff --git a/Prime_number.py b/Prime_number.py
index 1a345b5abe6..bc3c62ce44f 100644
--- a/Prime_number.py
+++ b/Prime_number.py
@@ -12,29 +12,19 @@ def is_prime_a(n):
if n < 2:
return False
sqrt_n = int(sqrt(n))
- for i in range(2, sqrt_n + 1):
- if n % i == 0:
- return False
- return True
+ return all(n % i != 0 for i in range(2, sqrt_n + 1))
def is_prime_b(n):
if n > 1:
- if n == 2:
- return True
- else:
+ if n != 2:
for i in range(2, n):
if n % i == 0:
return False
- return True
+ return True
return False
def is_prime_c(n):
- divisible = 0
- for i in range(1, n + 1):
- if n % i == 0:
- divisible += 1
- if divisible == 2:
- return True
- return False
+ divisible = sum(n % i == 0 for i in range(1, n + 1))
+ return divisible == 2
diff --git a/Print_List_of_Even_Numbers.py b/Print_List_of_Even_Numbers.py
index 5addb87407f..e6a5150a7eb 100644
--- a/Print_List_of_Even_Numbers.py
+++ b/Print_List_of_Even_Numbers.py
@@ -10,10 +10,5 @@
if n < 0:
print("Not a valid number, please enter a positive number!")
else:
- for i in range(0, n + 1):
- if i % 2 == 0:
- list.append(
- i
- ) # appending items to the initialised list getting from the 'if' statement
-
+ list.extend(i for i in range(n + 1) if i % 2 == 0)
print(list)
diff --git a/Print_List_of_Odd_Numbers.py b/Print_List_of_Odd_Numbers.py
index f032e035dee..6ad13ebe2f1 100644
--- a/Print_List_of_Odd_Numbers.py
+++ b/Print_List_of_Odd_Numbers.py
@@ -2,7 +2,7 @@
# Another best method to do this
n = map(list(int, input().split()))
-odd_list = list(i for i in n if i % 2 != 0)
+odd_list = [i for i in n if i % 2 != 0]
print(odd_list)
exit()
@@ -16,7 +16,7 @@
if n <= 0:
print("Invalid number, please enter a number greater than zero!")
else:
- odd_list = [i for i in range(1, n + 1, 2)] # creating string with number "i"
+ odd_list = list(range(1, n + 1, 2))
print(odd_list) # in range from 1 till "n".
diff --git a/Program of Reverse of any number.py b/Program of Reverse of any number.py
index 75edba98cc8..0d3750e8c16 100644
--- a/Program of Reverse of any number.py
+++ b/Program of Reverse of any number.py
@@ -2,7 +2,7 @@
rev = 0
while num > 0:
Rem = num % 10
- num = num // 10
+ num //= 10
rev = rev * 10 + Rem
print("The Reverse of the number", rev)
##################
diff --git a/Program to reverse Linked List( Recursive solution).py b/Program to reverse Linked List( Recursive solution).py
index 61a6165bab2..0b8ba618d82 100644
--- a/Program to reverse Linked List( Recursive solution).py
+++ b/Program to reverse Linked List( Recursive solution).py
@@ -34,11 +34,9 @@ def takeInput():
if head is None:
head = newNode
- tail = newNode
-
else:
tail.next = newNode
- tail = newNode
+ tail = newNode
i += 1
diff --git a/QR_code_generator/qrcode.py b/QR_code_generator/qrcode.py
index 753ec3ebf20..0aca13bf36d 100755
--- a/QR_code_generator/qrcode.py
+++ b/QR_code_generator/qrcode.py
@@ -9,7 +9,7 @@
print("Enter image name to save")
n = input(": ")
# Adding extension as .pnf
-d = n + ".png"
+d = f"{n}.png"
# Creating QR code
url = pyqrcode.create(s)
# Saving QR code as a png file
diff --git a/QuadraticCalc.py b/QuadraticCalc.py
index 305f7e1665a..ea9eb61ff0d 100644
--- a/QuadraticCalc.py
+++ b/QuadraticCalc.py
@@ -19,7 +19,7 @@ def findLinear(numbers): # find a & b of linear sequence
second_difference = []
for i in range(4): # input
term = str(i + 1)
- inp = int(input("Enter term " + term + ": "))
+ inp = int(input(f"Enter term {term}: "))
sequence.append(inp)
for i in range(3):
@@ -37,8 +37,6 @@ def findLinear(numbers): # find a & b of linear sequence
num = a * (n * n)
subs_diff.append((sequence[i]) - num)
b, c = findLinear(subs_diff)
- print(
- "Nth term: " + str(a) + "n^2 + " + str(b) + "n + " + str(c)
- ) # outputs nth term
+ print(f"Nth term: {str(a)}n^2 + {str(b)}n + {str(c)}")
else:
print("Sequence is not quadratic")
diff --git a/RandomNumberGame.py b/RandomNumberGame.py
index 8b3129234a6..e30ad8af68f 100644
--- a/RandomNumberGame.py
+++ b/RandomNumberGame.py
@@ -6,6 +6,7 @@
Thank you
"""
+
import os
import random
@@ -23,13 +24,13 @@
n = int(input("Enter number of players : "))
print()
-for i in range(0, n):
+for _ in range(n):
name = input("Enter name of player : ")
players.append(name)
os.system("cls")
-for i in range(0, n):
+for i in range(n):
orignum = random.randint(1, 100)
print(players[i], "your turn :", end="\n\n")
count = 0
@@ -49,11 +50,11 @@
score.append(count + 1)
os.system("cls")
print("players :\n")
-for i in range(0, n):
+for i in range(n):
print(players[i], "-", score[i])
print("\n\nwinner is :\n")
-for i in range(0, n):
+for i in range(n):
if score[i] == min(score):
print(players[i])
x = input()
diff --git a/Recursion Visulaizer/recursionVisualizer.py b/Recursion Visulaizer/recursionVisualizer.py
index 4ecc495e628..8ceede0aec0 100644
--- a/Recursion Visulaizer/recursionVisualizer.py
+++ b/Recursion Visulaizer/recursionVisualizer.py
@@ -11,60 +11,57 @@
def tree(i):
if i < 10:
return
- else:
- t.right(15)
- t.forward(15)
- t.left(20)
- t.backward(20)
- tree(2 * i / 5)
- t.left(2)
- tree(3 * i / 4)
- t.left(2)
- tree(i / 2)
- t.backward(num / 5)
- tree(random.randint(1, 100))
- tree(random.randint(1, num))
- tree(random.randint(1, num / 2))
- tree(random.randint(1, num / 3))
- tree(random.randint(1, num / 2))
- tree(random.randint(1, num))
- tree(random.randint(1, 100))
- t.forward(num / 5)
- t.right(2)
- tree(3 * i / 4)
- t.right(2)
- tree(2 * i / 5)
- t.right(2)
- t.left(10)
- t.backward(10)
- t.right(15)
- t.forward(15)
- print("tree execution complete")
+ t.right(15)
+ t.forward(15)
+ t.left(20)
+ t.backward(20)
+ tree(2 * i / 5)
+ t.left(2)
+ tree(3 * i / 4)
+ t.left(2)
+ tree(i / 2)
+ t.backward(num / 5)
+ tree(random.randint(1, 100))
+ tree(random.randint(1, num))
+ tree(random.randint(1, num / 2))
+ tree(random.randint(1, num / 3))
+ tree(random.randint(1, num / 2))
+ tree(random.randint(1, num))
+ tree(random.randint(1, 100))
+ t.forward(num / 5)
+ t.right(2)
+ tree(3 * i / 4)
+ t.right(2)
+ tree(2 * i / 5)
+ t.right(2)
+ t.left(10)
+ t.backward(10)
+ t.right(15)
+ t.forward(15)
+ print("tree execution complete")
def cycle(i):
if i < 10:
return
+ try:
+ tree(random.randint(1, i))
+ tree(random.randint(1, i * 2))
+ except:
+ print("An exception occured")
else:
- try:
- tree(random.randint(1, i))
- tree(random.randint(1, i * 2))
- except:
- print("An exception occured")
- else:
- print("No Exception occured")
- print("cycle loop complete")
+ print("No Exception occured")
+ print("cycle loop complete")
def fractal(i):
if i < 10:
return
- else:
- cycle(random.randint(1, i + 1))
- cycle(random.randint(1, i))
- cycle(random.randint(1, i - 1))
- cycle(random.randint(1, i - 2))
- print("fractal execution complete")
+ cycle(random.randint(1, i + 1))
+ cycle(random.randint(1, i))
+ cycle(random.randint(1, i - 1))
+ cycle(random.randint(1, i - 2))
+ print("fractal execution complete")
fractal(random.randint(1, 200))
diff --git a/SOUNDEX.py b/SOUNDEX.py
index 4d49ca8272e..eb561c26f1f 100644
--- a/SOUNDEX.py
+++ b/SOUNDEX.py
@@ -9,8 +9,6 @@ def SOUNDEX(TERM: str):
# List the Remove occurrences of A, E, I, O, U, Y, H, W.
Remove_List = ("A", "E", "I", "O", "U", "Y", "H", "W")
- # Save the first letter
- first_letter = TERM_LETTERS[0]
# Take the Other letters instead of First_Letter
Characters = TERM_LETTERS[1:]
# Remove items from Character using Remove_List
@@ -54,6 +52,8 @@ def SOUNDEX(TERM: str):
# If the saved Characters’s Number is the same the resulting First Letter,keep the First Letter AND remove the Number
if len(TERM_LETTERS) != 1:
+ # Save the first letter
+ first_letter = TERM_LETTERS[0]
if first_letter == TERM_LETTERS[1]:
Characters[0] = TERM[0]
else:
@@ -68,7 +68,6 @@ def SOUNDEX(TERM: str):
while len(Characters) < 4:
Characters.append(0)
if len(Characters) > 4:
- Characters = Characters[0:4]
+ Characters = Characters[:4]
- INDEX = "".join([str(C) for C in Characters])
- return INDEX
+ return "".join([str(C) for C in Characters])
diff --git a/Shivaansh.py b/Shivaansh.py
index deec715f10f..bbcd92e84e2 100644
--- a/Shivaansh.py
+++ b/Shivaansh.py
@@ -1,5 +1,5 @@
from __future__ import print_function
x = input("Enter a number: ")
-for i in range(1, 11, 1):
+for i in range(1, 11):
print(x, "x", i, "=", (x * i))
diff --git a/Snake-Water-Gun-Game.py b/Snake-Water-Gun-Game.py
index 54341645888..abe8b33b60f 100644
--- a/Snake-Water-Gun-Game.py
+++ b/Snake-Water-Gun-Game.py
@@ -6,6 +6,7 @@
And so on for other cases
"""
+
# you can use this code also, see this code is very short in compare to your code
# code starts here
"""
@@ -121,44 +122,35 @@
if user_choice == "w":
print("\n-------Mr. Computer won this round--------")
comp_point += 1
- x += 1
elif user_choice == "g":
print("\n-------You won this round-------")
user_point += 1
- x += 1
else:
print("\n-------Match draw-------")
match_draw += 1
- x += 1
-
+ x += 1
elif comp_rand == "w":
if user_choice == "g":
print("\n-------Mr. Computer won this round--------")
comp_point += 1
- x += 1
elif user_choice == "s":
print("\n-------You won this round-------")
user_point += 1
- x += 1
else:
print("\n-------Match draw-------")
match_draw += 1
- x += 1
-
+ x += 1
elif comp_rand == "g":
if user_choice == "s":
print("\n-------Mr. Computer won this round--------")
comp_point += 1
- x += 1
elif user_choice == "w":
print("\n-------You won this round-------")
user_point += 1
- x += 1
else:
print("\n-------Match draw-------")
match_draw += 1
- x += 1
-
+ x += 1
print("Here are final stats of the 10 matches : ")
print(f"Mr. Computer won : {comp_point} matches")
print(f"You won : {user_point} matches")
diff --git a/Snake_water_gun/main.py b/Snake_water_gun/main.py
index 5b13f549110..825d2b50ec6 100644
--- a/Snake_water_gun/main.py
+++ b/Snake_water_gun/main.py
@@ -33,7 +33,7 @@ class bcolors:
if b == "N":
run = False
print("Ok bubyeee! See you later")
-elif b == "Y" or b == "y":
+elif b in ["Y", "y"]:
print(
"There will be 10 matches, and the one who wins more matches will win. Let's start."
)
@@ -47,7 +47,7 @@ class bcolors:
user_choice = input("Type s for snake, w for water or g for gun: ").lower()
if user_choice == comp_choice:
- print(bcolors.HEADERS + "Game draws. Play again" + bcolors.ENDC)
+ print(f"{bcolors.HEADERS}Game draws. Play again{bcolors.ENDC}")
elif user_choice == "s" and comp_choice == "g":
print(bcolors.FAIL + "It's Snake v/s Gun You lose!" + bcolors.ENDC)
@@ -77,7 +77,7 @@ class bcolors:
i += 1
print(f"{10-i} matches left")
-if run == True:
+if run:
print(f"Your score is {score} and the final result is...")
time.sleep(3)
if score > 5:
diff --git a/Sorting Algorithims/Bubble_sort.py b/Sorting Algorithims/Bubble_sort.py
index b7dca090474..fc2f0b52b65 100644
--- a/Sorting Algorithims/Bubble_sort.py
+++ b/Sorting Algorithims/Bubble_sort.py
@@ -1,5 +1,5 @@
def bubble_sort(Lists):
- for i in range(len(Lists)):
+ for _ in range(len(Lists)):
for j in range(len(Lists) - 1):
# We check whether the adjecent number is greater or not
if Lists[j] > Lists[j + 1]:
@@ -11,7 +11,7 @@ def bubble_sort(Lists):
array_length = int(
input(print("Enter the number of elements of array or enter the length of array"))
)
-for i in range(array_length):
+for _ in range(array_length):
value = int(input(print("Enter the value in the array")))
array.append(value)
diff --git a/Sorting Algorithims/Count sort.py b/Sorting Algorithims/Count sort.py
index 6b689c226cd..55e1c516f11 100644
--- a/Sorting Algorithims/Count sort.py
+++ b/Sorting Algorithims/Count sort.py
@@ -7,7 +7,7 @@ def counting_sort(array1, max_val):
count[a] += 1
i = 0
for a in range(m):
- for c in range(count[a]):
+ for _ in range(count[a]):
array1[i] = a
i += 1
return array1
diff --git a/Sorting Algorithims/Counting Sort.py b/Sorting Algorithims/Counting Sort.py
index d4b790f6d03..c4587b9b6cc 100644
--- a/Sorting Algorithims/Counting Sort.py
+++ b/Sorting Algorithims/Counting Sort.py
@@ -9,7 +9,7 @@ def countingSort(array):
count = [0] * 10
# Store the count of each elements in count array
- for i in range(0, size):
+ for i in range(size):
count[array[i]] += 1
# Store the cummulative count
@@ -25,7 +25,7 @@ def countingSort(array):
i -= 1
# Copy the sorted elements into original array
- for i in range(0, size):
+ for i in range(size):
array[i] = output[i]
diff --git a/Sorting Algorithims/Counting-sort.py b/Sorting Algorithims/Counting-sort.py
index 09da6b6390b..1e2435b1672 100644
--- a/Sorting Algorithims/Counting-sort.py
+++ b/Sorting Algorithims/Counting-sort.py
@@ -24,7 +24,7 @@ def counting_sort(tlist, k, n):
count_list = [0] * (k + 1)
# iterate the tgt_list to put into count list
- for i in range(0, n):
+ for i in range(n):
count_list[tlist[i]] += 1
# Modify count list such that each index of count list is the combined sum of the previous counts
diff --git a/Sorting Algorithims/Cycle Sort.py b/Sorting Algorithims/Cycle Sort.py
index 20dca703907..b6fe17c0ea0 100644
--- a/Sorting Algorithims/Cycle Sort.py
+++ b/Sorting Algorithims/Cycle Sort.py
@@ -5,7 +5,7 @@ def cycleSort(array):
writes = 0
# Loop through the array to find cycles to rotate.
- for cycleStart in range(0, len(array) - 1):
+ for cycleStart in range(len(array) - 1):
item = array[cycleStart]
# Find where to put the item.
@@ -48,6 +48,6 @@ def cycleSort(array):
cycleSort(arr)
print("After sort : ")
-for i in range(0, n):
+for i in range(n):
print(arr[i], end=" ")
print() # Print a newline
diff --git a/Sorting Algorithims/Iterative Merge Sort.py b/Sorting Algorithims/Iterative Merge Sort.py
index 63173b6bf5c..3226ba538ee 100644
--- a/Sorting Algorithims/Iterative Merge Sort.py
+++ b/Sorting Algorithims/Iterative Merge Sort.py
@@ -32,11 +32,11 @@ def mergeSort(a):
# Merge call for each sub array
merge(a, left, mid, right)
- left = left + current_size * 2
+ left += current_size * 2
# Increasing sub array size by
# multiple of 2
- current_size = 2 * current_size
+ current_size *= 2
# Merge Function
@@ -45,9 +45,9 @@ def merge(a, l, m, r):
n2 = r - m
L = [0] * n1
R = [0] * n2
- for i in range(0, n1):
+ for i in range(n1):
L[i] = a[l + i]
- for i in range(0, n2):
+ for i in range(n2):
R[i] = a[m + i + 1]
i, j, k = 0, 0, l
diff --git a/Sorting Algorithims/Merge Sort.py b/Sorting Algorithims/Merge Sort.py
index 537b8b8857e..fce82fd5a22 100644
--- a/Sorting Algorithims/Merge Sort.py
+++ b/Sorting Algorithims/Merge Sort.py
@@ -14,10 +14,10 @@ def merge(arr, l, m, r):
R = [0] * (n2)
# Copy data to temp arrays L[] and R[]
- for i in range(0, n1):
+ for i in range(n1):
L[i] = arr[l + i]
- for j in range(0, n2):
+ for j in range(n2):
R[j] = arr[m + 1 + j]
# Merge the temp arrays back into arr[l..r]
diff --git a/Sorting Algorithims/Merge-sort.py b/Sorting Algorithims/Merge-sort.py
index e9d1167e5d3..57505425ad4 100644
--- a/Sorting Algorithims/Merge-sort.py
+++ b/Sorting Algorithims/Merge-sort.py
@@ -5,19 +5,17 @@
n = int(input("Enter number of elements in the list: ")) # taking value from user
for i in range(n):
- temp = int(input("Enter element" + str(i + 1) + ": "))
+ temp = int(input(f"Enter element{str(i + 1)}: "))
lst.append(temp)
def merge(ori_lst, left, mid, right):
L, R = [], [] # PREPARE TWO TEMPORARY LIST TO HOLD ELEMENTS
- for i in range(left, mid): # LOADING
- L.append(ori_lst[i])
- for i in range(mid, right): # LOADING
- R.append(ori_lst[i])
+ L.extend(ori_lst[i] for i in range(left, mid))
+ R.extend(ori_lst[i] for i in range(mid, right))
base = left # FILL ELEMENTS BACK TO ORIGINAL LIST START FROM INDEX LEFT
# EVERY LOOP CHOOSE A SMALLER ELEMENT FROM EITHER LIST
- while len(L) > 0 and len(R) > 0:
+ while L and R:
if L[0] < R[0]:
ori_lst[base] = L[0]
L.remove(L[0])
@@ -26,11 +24,11 @@ def merge(ori_lst, left, mid, right):
R.remove(R[0])
base += 1
# UNLOAD THE REMAINER
- while len(L) > 0:
+ while L:
ori_lst[base] = L[0]
L.remove(L[0])
base += 1
- while len(R) > 0:
+ while R:
ori_lst[base] = R[0]
R.remove(R[0])
base += 1
diff --git a/Sorting Algorithims/Sort the values of first list using second list.py b/Sorting Algorithims/Sort the values of first list using second list.py
index 61bfa9cad10..9233897f3d0 100644
--- a/Sorting Algorithims/Sort the values of first list using second list.py
+++ b/Sorting Algorithims/Sort the values of first list using second list.py
@@ -6,9 +6,7 @@ def sort_list(list1, list2):
zipped_pairs = zip(list2, list1)
- z = [x for _, x in sorted(zipped_pairs)]
-
- return z
+ return [x for _, x in sorted(zipped_pairs)]
# driver code
diff --git a/Sorting Algorithims/Tim_sort.py b/Sorting Algorithims/Tim_sort.py
index 9cbbb313e5d..ced031359d9 100644
--- a/Sorting Algorithims/Tim_sort.py
+++ b/Sorting Algorithims/Tim_sort.py
@@ -32,9 +32,9 @@ def merge(arr, l, m, r):
# left and right array
len1, len2 = m - l + 1, r - m
left, right = [], []
- for i in range(0, len1):
+ for i in range(len1):
left.append(arr[l + i])
- for i in range(0, len2):
+ for i in range(len2):
right.append(arr[m + 1 + i])
i, j, k = 0, 0, l
@@ -100,7 +100,7 @@ def timSort(arr, n):
# utility function to print the Array
def printArray(arr, n):
- for i in range(0, n):
+ for i in range(n):
print(arr[i], end=" ")
print()
diff --git a/Sorting Algorithims/brickSort.py b/Sorting Algorithims/brickSort.py
index 08308d05a5a..b427b201bd1 100644
--- a/Sorting Algorithims/brickSort.py
+++ b/Sorting Algorithims/brickSort.py
@@ -5,9 +5,9 @@
def oddEvenSort(arr, n):
# Initially array is unsorted
isSorted = 0
+ temp = 0
while isSorted == 0:
isSorted = 1
- temp = 0
for i in range(1, n - 1, 2):
if arr[i] > arr[i + 1]:
arr[i], arr[i + 1] = arr[i + 1], arr[i]
@@ -25,5 +25,5 @@ def oddEvenSort(arr, n):
n = len(arr)
oddEvenSort(arr, n)
-for i in range(0, n):
+for i in range(n):
print(arr[i], end=" ")
diff --git a/Sorting Algorithims/bubblesortpgm.py b/Sorting Algorithims/bubblesortpgm.py
index 2e51d9e5259..4e0c94e5a11 100644
--- a/Sorting Algorithims/bubblesortpgm.py
+++ b/Sorting Algorithims/bubblesortpgm.py
@@ -30,7 +30,7 @@ def bubbleSort(arr):
for i in range(n):
not_swap = True
# Last i elements are already in place
- for j in range(0, n - i - 1):
+ for j in range(n - i - 1):
# traverse the array from 0 to n-i-1
# Swap if the element found is greater
@@ -48,5 +48,5 @@ def bubbleSort(arr):
bubbleSort(arr)
print("Sorted array is:")
-for i in range(len(arr)):
- print("%d" % arr[i]),
+for item in arr:
+ (print("%d" % item), )
diff --git a/Sorting Algorithims/merge_sort.py b/Sorting Algorithims/merge_sort.py
index 005b4597509..28c9056b849 100644
--- a/Sorting Algorithims/merge_sort.py
+++ b/Sorting Algorithims/merge_sort.py
@@ -6,29 +6,26 @@ def merge(left_list, right_list):
left_list_length, right_list_length = len(left_list), len(right_list)
for _ in range(left_list_length + right_list_length):
- if left_list_index < left_list_length and right_list_index < right_list_length:
- # We check which value from the start of each list is smaller
- # If the item at the beginning of the left list is smaller, add it
- # to the sorted list
- if left_list[left_list_index] <= right_list[right_list_index]:
- sorted_list.append(left_list[left_list_index])
- left_list_index += 1
- # If the item at the beginning of the right list is smaller, add it
- # to the sorted list
- else:
- sorted_list.append(right_list[right_list_index])
- right_list_index += 1
-
- # If we've reached the end of the of the left list, add the elements
- # from the right list
- elif left_list_index == left_list_length:
- sorted_list.append(right_list[right_list_index])
- right_list_index += 1
- # If we've reached the end of the of the right list, add the elements
- # from the left list
- elif right_list_index == right_list_length:
+ if (
+ left_list_index < left_list_length
+ and right_list_index < right_list_length
+ and left_list[left_list_index] <= right_list[right_list_index]
+ or (
+ left_list_index >= left_list_length
+ or right_list_index >= right_list_length
+ )
+ and left_list_index != left_list_length
+ and right_list_index == right_list_length
+ ):
sorted_list.append(left_list[left_list_index])
left_list_index += 1
+ elif (
+ left_list_index < left_list_length
+ and right_list_index < right_list_length
+ or left_list_index == left_list_length
+ ):
+ sorted_list.append(right_list[right_list_index])
+ right_list_index += 1
return sorted_list
diff --git a/Sorting Algorithims/selectionSort.py b/Sorting Algorithims/selectionSort.py
index 75fbafcf79f..9eec1e51799 100644
--- a/Sorting Algorithims/selectionSort.py
+++ b/Sorting Algorithims/selectionSort.py
@@ -2,7 +2,7 @@
N = int(input("Enter The Size Of List"))
-for i in range(0, N):
+for _ in range(N):
a = int(input("Enter The number"))
list.append(a)
@@ -11,7 +11,7 @@
# Every time The Element Of List is fetched and the smallest element in remaining list is found and if it comes out
# to be smaller than the element fetched then it is swapped with smallest number.
-for i in range(0, len(list) - 1):
+for i in range(len(list) - 1):
smallest = list[i + 1]
k = 0
for j in range(i + 1, len(list)):
diff --git a/Sorting Algorithims/sorting.py b/Sorting Algorithims/sorting.py
index c56beca7375..c8325bb2548 100644
--- a/Sorting Algorithims/sorting.py
+++ b/Sorting Algorithims/sorting.py
@@ -2,10 +2,10 @@
temp = 0
print("Elements of original array: ")
-for i in range(0, len(arr)):
- print(arr[i], end=" ")
+for item in arr:
+ print(item, end=" ")
-for i in range(0, len(arr)):
+for i in range(len(arr)):
for j in range(i + 1, len(arr)):
if arr[i] > arr[j]:
temp = arr[i]
@@ -16,5 +16,5 @@
print("Elements of array sorted in ascending order: ")
-for i in range(0, len(arr)):
- print(arr[i], end=" ")
+for item_ in arr:
+ print(item_, end=" ")
diff --git a/Sorting Algorithims/stooge_sort.py b/Sorting Algorithims/stooge_sort.py
index ace9ba22038..00296bd69fa 100644
--- a/Sorting Algorithims/stooge_sort.py
+++ b/Sorting Algorithims/stooge_sort.py
@@ -14,7 +14,7 @@ def stooge_sort_(arr, l, h):
arr[h] = t
# If there are more than 2 elements in array
- if h - l + 1 > 2:
+ if h - l > 1:
t = (int)((h - l + 1) / 3)
# Recursively sort first 2 / 3 elements
diff --git a/Sorting Algorithims/wave_sort.py b/Sorting Algorithims/wave_sort.py
index cdaeb75afb2..81c6937ea07 100644
--- a/Sorting Algorithims/wave_sort.py
+++ b/Sorting Algorithims/wave_sort.py
@@ -7,5 +7,5 @@ def sortInWave(arr, n):
arr = []
arr = input("Enter the arr")
sortInWave(arr, len(arr))
-for i in range(0, len(arr)):
+for i in range(len(arr)):
print(arr[i], " ")
diff --git a/StringToBinary.py b/StringToBinary.py
index ebaabe2e152..c8e80ebdb5c 100644
--- a/StringToBinary.py
+++ b/StringToBinary.py
@@ -2,11 +2,8 @@
for chr in text:
bin = ""
- asciiVal = int(ord(chr))
+ asciiVal = ord(chr)
while asciiVal > 0:
- if asciiVal % 2 == 0:
- bin = bin + "0"
- else:
- bin = bin + "1"
- asciiVal = int(asciiVal / 2)
- print(bin + " : " + bin[::-1])
+ bin = f"{bin}0" if asciiVal % 2 == 0 else f"{bin}1"
+ asciiVal //= 2
+ print(f"{bin} : {bin[::-1]}")
diff --git a/Swap numbers.py b/Swap numbers.py
index 15fe20efc2e..753ab281ac2 100644
--- a/Swap numbers.py
+++ b/Swap numbers.py
@@ -3,20 +3,12 @@
x = 5
y = 10
-# To take inputs from the user
-#x = input('Enter value of x: ')
-#y = input('Enter value of y: ')
-
-# create a temporary variable and swap the values
-temp = x
-x = y
-y = temp
-
+x, y = y, x
# in python we can swap without using a third variablex
x,y = y,x
print(x,y)
# output is 10,5
-print('The value of x after swapping: {}'.format(x))
-print('The value of y after swapping: {}'.format(y))
+print(f'The value of x after swapping: {x}')
+print(f'The value of y after swapping: {y}')
diff --git a/Test-Case-Generator/test_case.py b/Test-Case-Generator/test_case.py
index 05c9e77d60a..03b905b0598 100644
--- a/Test-Case-Generator/test_case.py
+++ b/Test-Case-Generator/test_case.py
@@ -214,7 +214,6 @@ def done(self, output):
self.a = [0]
self.try_forget()
self.retrieve_home()
- pass
def display(self):
self.y_scroll = Scrollbar(gui)
@@ -506,9 +505,7 @@ def submit(self):
self.char_lis = list(self.char_list.get().split())
if self.char_lis[0] == "(Space":
return
- except IndexError:
- return
- except ValueError:
+ except (IndexError, ValueError):
return
except AttributeError:
pass
@@ -608,7 +605,7 @@ def generate(self): # Type 1
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.output.insert(END, self.n)
self.output.insert(END, "\n")
@@ -640,7 +637,7 @@ def generate(self): # Type 2
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.m = randint(self.m_min, self.m_max)
self.output.insert(END, self.n)
@@ -674,7 +671,7 @@ def generate(self): # Type 3
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.a = randint(self.a_min, self.a_max)
self.b = randint(self.b_min, self.b_max)
self.output.insert(END, self.a)
@@ -705,7 +702,7 @@ def generate(self): # Type 4
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.m = randint(self.m_min, self.m_max)
self.output.insert(END, self.n)
@@ -752,7 +749,7 @@ def generate(self): # Type 5
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.m = randint(self.m_min, self.m_max)
self.k = randint(self.k_min, self.k_max)
@@ -797,7 +794,7 @@ def generate(self): # Type 6
self.output.insert(END, " ")
self.output.insert(END, self.m)
self.output.insert(END, "\n")
- for i in range(self.n):
+ for _ in range(self.n):
self.a = [0] * self.m
for j in range(self.m):
self.a[j] = randint(self.a_min, self.a_max)
@@ -825,7 +822,7 @@ def generate(self): # Type 7
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.output.insert(END, self.n)
self.output.insert(END, "\n")
@@ -856,14 +853,14 @@ def generate(self): # Type 8
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.m = randint(self.m_min, self.m_max)
self.output.insert(END, self.n)
self.output.insert(END, " ")
self.output.insert(END, self.m)
self.output.insert(END, "\n")
- for j in range(self.m):
+ for _ in range(self.m):
self.a = randint(self.a_min, self.a_max)
self.b = randint(self.b_min, self.b_max)
self.output.insert(END, self.a)
@@ -892,7 +889,7 @@ def generate(self): # Type 9
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.a = choices(self.char_lis, k=self.n)
self.output.insert(END, "".join(self.a))
@@ -921,7 +918,7 @@ def generate(self): # Type 10
self.output.delete("1.0", END)
self.output.insert(END, self.t)
self.output.insert(END, "\n")
- for i in range(self.t):
+ for _ in range(self.t):
self.n = randint(self.n_min, self.n_max)
self.k = randint(self.k_min, self.k_max)
self.m = randint(self.m_min, self.m_max)
diff --git a/TicTacToe.py b/TicTacToe.py
index f1b61b80df9..074b199135e 100644
--- a/TicTacToe.py
+++ b/TicTacToe.py
@@ -1,16 +1,16 @@
def print_tic_tac_toe(values):
print("\n")
print("\t | |")
- print("\t {} | {} | {}".format(values[0], values[1], values[2]))
+ print(f"\t {values[0]} | {values[1]} | {values[2]}")
print('\t_____|_____|_____')
-
+
print("\t | |")
- print("\t {} | {} | {}".format(values[3], values[4], values[5]))
+ print(f"\t {values[3]} | {values[4]} | {values[5]}")
print('\t_____|_____|_____')
-
+
print("\t | |")
-
- print("\t {} | {} | {}".format(values[6], values[7], values[8]))
+
+ print(f"\t {values[6]} | {values[7]} | {values[8]}")
print("\t | |")
print("\n")
@@ -32,35 +32,26 @@ def check_win(player_pos, cur_player):
# All possible winning combinations
soln = [[1, 2, 3], [4, 5, 6], [7, 8, 9], [1, 4, 7], [2, 5, 8], [3, 6, 9], [1, 5, 9], [3, 5, 7]]
-
- # Loop to check if any winning combination is satisfied
- for x in soln:
- if all(y in player_pos[cur_player] for y in x):
-
- # Return True if any winning combination satisfies
- return True
- # Return False if no combination is satisfied
- return False
+
+ return any(all(y in player_pos[cur_player] for y in x) for x in soln)
# Function to check if the game is drawn
def check_draw(player_pos):
- if len(player_pos['X']) + len(player_pos['O']) == 9:
- return True
- return False
+ return len(player_pos['X']) + len(player_pos['O']) == 9
# Function for a single game of Tic Tac Toe
def single_game(cur_player):
# Represents the Tic Tac Toe
- values = [' ' for x in range(9)]
-
+ values = [' ' for _ in range(9)]
+
# Stores the positions occupied by X and O
player_pos = {'X':[], 'O':[]}
-
+
# Game Loop for a single game of Tic Tac Toe
while True:
print_tic_tac_toe(values)
-
+
# Try exception block for MOVE input
try:
print("Player ", cur_player, " turn. Which box? : ", end="")
@@ -68,119 +59,105 @@ def single_game(cur_player):
except ValueError:
print("Wrong Input!!! Try Again")
continue
-
+
# Sanity check for MOVE inout
if move < 1 or move > 9:
print("Wrong Input!!! Try Again")
continue
-
+
# Check if the box is not occupied already
if values[move-1] != ' ':
print("Place already filled. Try again!!")
continue
-
+
# Update game information
-
+
# Updating grid status
values[move-1] = cur_player
-
+
# Updating player positions
player_pos[cur_player].append(move)
-
+
# Function call for checking win
if check_win(player_pos, cur_player):
print_tic_tac_toe(values)
print("Player ", cur_player, " has won the game!!")
print("\n")
return cur_player
-
+
# Function call for checking draw game
if check_draw(player_pos):
print_tic_tac_toe(values)
print("Game Drawn")
print("\n")
return 'D'
-
+
# Switch player moves
- if cur_player == 'X':
- cur_player = 'O'
- else:
- cur_player = 'X'
+ cur_player = 'O' if cur_player == 'X' else 'X'
if __name__ == "__main__":
print("Player 1")
player1 = input("Enter the name : ")
print("\n")
-
+
print("Player 2")
player2 = input("Enter the name : ")
print("\n")
-
+
# Stores the player who chooses X and O
cur_player = player1
-
+
# Stores the choice of players
player_choice = {'X' : "", 'O' : ""}
-
+
# Stores the options
options = ['X', 'O']
-
+
# Stores the scoreboard
score_board = {player1: 0, player2: 0}
print_scoreboard(score_board)
-
+
# Game Loop for a series of Tic Tac Toe
- # The loop runs until the players quit
+ # The loop runs until the players quit
while True:
-
+
# Player choice Menu
print("Turn to choose for", cur_player)
print("Enter 1 for X")
print("Enter 2 for O")
print("Enter 3 to Quit")
-
+
# Try exception for CHOICE input
try:
choice = int(input())
except ValueError:
print("Wrong Input!!! Try Again\n")
continue
-
- # Conditions for player choice
+
+ # Conditions for player choice
if choice == 1:
player_choice['X'] = cur_player
- if cur_player == player1:
- player_choice['O'] = player2
- else:
- player_choice['O'] = player1
-
+ player_choice['O'] = player2 if cur_player == player1 else player1
elif choice == 2:
player_choice['O'] = cur_player
- if cur_player == player1:
- player_choice['X'] = player2
- else:
- player_choice['X'] = player1
-
+ player_choice['X'] = player2 if cur_player == player1 else player1
elif choice == 3:
print("Final Scores")
print_scoreboard(score_board)
break
-
+
else:
print("Wrong Choice!!!! Try Again\n")
-
+
# Stores the winner in a single game of Tic Tac Toe
winner = single_game(options[choice-1])
-
+
# Edits the scoreboard according to the winner
if winner != 'D' :
player_won = player_choice[winner]
score_board[player_won] = score_board[player_won] + 1
-
+
print_scoreboard(score_board)
# Switch player who chooses X or O
- if cur_player == player1:
- cur_player = player2
- else:
- cur_player = player1
+ cur_player = player2 if cur_player == player1 else player1
diff --git a/Tic_Tac_Toe.py b/Tic_Tac_Toe.py
index b71b5b1d290..ff003e28321 100644
--- a/Tic_Tac_Toe.py
+++ b/Tic_Tac_Toe.py
@@ -15,15 +15,15 @@ def introduction():
def draw_board(board):
print(" | |")
- print(" " + board[7] + " | " + board[8] + " | " + board[9])
+ print(f" {board[7]} | {board[8]} | {board[9]}")
print(" | |")
print("-------------")
print(" | |")
- print(" " + board[4] + " | " + board[5] + " | " + board[6])
+ print(f" {board[4]} | {board[5]} | {board[6]}")
print(" | |")
print("-------------")
print(" | |")
- print(" " + board[1] + " | " + board[2] + " | " + board[3])
+ print(f" {board[1]} | {board[2]} | {board[3]}")
print(" | |")
@@ -31,23 +31,17 @@ def input_player_letter():
# Lets the player type witch letter they want to be.
# Returns a list with the player's letter as the first item, and the computer's letter as the second.
letter = ""
- while not (letter == "X" or letter == "O"):
+ while letter not in {"X", "O"}:
print("Do you want to be X or O? ")
letter = input("> ").upper()
# the first element in the list is the player’s letter, the second is the computer's letter.
- if letter == "X":
- return ["X", "O"]
- else:
- return ["O", "X"]
+ return ["X", "O"] if letter == "X" else ["O", "X"]
def frist_player():
guess = random.randint(0, 1)
- if guess == 0:
- return "Computer"
- else:
- return "Player"
+ return "Computer" if guess == 0 else "Player"
def play_again():
@@ -75,10 +69,7 @@ def is_winner(bo, le):
def get_board_copy(board):
- dupe_board = []
- for i in board:
- dupe_board.append(i)
- return dupe_board
+ return list(board)
def is_space_free(board, move):
@@ -97,23 +88,12 @@ def get_player_move(board):
def choose_random_move_from_list(board, moveslist):
- possible_moves = []
- for i in moveslist:
- if is_space_free(board, i):
- possible_moves.append(i)
-
- if len(possible_moves) != 0:
- return random.choice(possible_moves)
- else:
- return None
+ possible_moves = [i for i in moveslist if is_space_free(board, i)]
+ return random.choice(possible_moves) if possible_moves else None
def get_computer_move(board, computer_letter):
- if computer_letter == "X":
- player_letter = "O"
- else:
- player_letter = "X"
-
+ player_letter = "O" if computer_letter == "X" else "X"
for i in range(1, 10):
copy = get_board_copy(board)
if is_space_free(copy, i):
@@ -129,20 +109,19 @@ def get_computer_move(board, computer_letter):
return i
move = choose_random_move_from_list(board, [1, 3, 7, 9])
- if move != None:
- return move
+ if move is None:
+ return (
+ 5
+ if is_space_free(board, 5)
+ else choose_random_move_from_list(board, [2, 4, 6, 8])
+ )
- if is_space_free(board, 5):
- return 5
-
- return choose_random_move_from_list(board, [2, 4, 6, 8])
+ else:
+ return move
def is_board_full(board):
- for i in range(1, 10):
- if is_space_free(board, i):
- return False
- return True
+ return not any(is_space_free(board, i) for i in range(1, 10))
print("Welcome To Tic Tac Toe!")
@@ -151,7 +130,7 @@ def is_board_full(board):
the_board = [" "] * 10
player_letter, computer_letter = input_player_letter()
turn = frist_player()
- print("The " + turn + " go frist.")
+ print(f"The {turn} go frist.")
game_is_playing = True
while game_is_playing:
@@ -165,13 +144,12 @@ def is_board_full(board):
draw_board(the_board)
print("Hoory! You have won the game!")
game_is_playing = False
+ elif is_board_full(the_board):
+ draw_board(the_board)
+ print("The game is tie!")
+ break
else:
- if is_board_full(the_board):
- draw_board(the_board)
- print("The game is tie!")
- break
- else:
- turn = "computer"
+ turn = "computer"
else:
# Computer's turn
move = get_computer_move(the_board, computer_letter)
@@ -181,12 +159,11 @@ def is_board_full(board):
draw_board(the_board)
print("The computer has beaten you! You Lose.")
game_is_playing = False
+ elif is_board_full(the_board):
+ draw_board(the_board)
+ print("The game is a tie!")
+ break
else:
- if is_board_full(the_board):
- draw_board(the_board)
- print("The game is a tie!")
- break
- else:
- turn = "player"
+ turn = "player"
if not play_again():
break
diff --git a/Timetable_Operations.py b/Timetable_Operations.py
index 0f75e59e516..2e445a96b93 100644
--- a/Timetable_Operations.py
+++ b/Timetable_Operations.py
@@ -37,16 +37,14 @@
# special condition below :
if Ht < 10:
- h = "0" + str(Ht)
+ h = f"0{str(Ht)}"
Ht = h
if Mt < 10:
- m = "0" + str(Mt)
+ m = f"0{str(Mt)}"
Mt = m
if St < 10:
- s = "0" + str(St)
+ s = f"0{str(St)}"
St = s
# add '0' to the empty spaces (caused by previous operations) in the final result!
-print(
- "final result is :", str(Ht) + ":" + str(Mt) + ":" + str(St)
-) # final result (formatted in clock)
+print("final result is :", f"{str(Ht)}:{str(Mt)}:{str(St)}")
diff --git a/To print series 1,12,123,1234......py b/To print series 1,12,123,1234......py
index 93adda5ee67..5a07a6c2cab 100644
--- a/To print series 1,12,123,1234......py
+++ b/To print series 1,12,123,1234......py
@@ -7,7 +7,7 @@ def num(a):
# outer loop to handle number of rows
- for i in range(0, a):
+ for i in range(a):
# re assigning num
@@ -17,8 +17,7 @@ def num(a):
# values changing acc. to outer loop
- for k in range(0, i + 1):
-
+ for _ in range(i + 1):
# printing number
print(num, end=" ")
diff --git a/Triplets with zero sum/find_Triplets_with_zero_sum.py b/Triplets with zero sum/find_Triplets_with_zero_sum.py
index 2a2d2b7688d..641208f2266 100644
--- a/Triplets with zero sum/find_Triplets_with_zero_sum.py
+++ b/Triplets with zero sum/find_Triplets_with_zero_sum.py
@@ -23,7 +23,7 @@ def find_Triplets_with_zero_sum(arr, num):
arr.sort()
# Run a loop until l is less than r, if the sum of array[l], array[r] is equal to zero then print the triplet and break the loop
- for index in range(0, num - 1):
+ for index in range(num - 1):
# initialize left and right
left = index + 1
diff --git a/Tweet Pre-Processing.py b/Tweet Pre-Processing.py
index 43d3e6c13b3..88301fa1e92 100644
--- a/Tweet Pre-Processing.py
+++ b/Tweet Pre-Processing.py
@@ -106,12 +106,7 @@
# In[24]:
-cleaned = []
-for i in tokens:
- if i not in stoper and i not in punct:
- cleaned.append(i)
-
-
+cleaned = [i for i in tokens if i not in stoper and i not in punct]
print(cleaned)
diff --git a/Type of angles of a triangle.py b/Type of angles of a triangle.py
index 3281f0d9980..7b6cac668be 100644
--- a/Type of angles of a triangle.py
+++ b/Type of angles of a triangle.py
@@ -1,8 +1,6 @@
# This program will return the type of the triangle.
# User has to enter the angles of the triangle in degrees.
def angle_type():
- angles = []
-
myDict = {
"All angles are less than 90°.": "Acute Angle Triangle",
"Has a right angle (90°)": "Right Angle Triangle",
@@ -12,44 +10,30 @@ def angle_type():
print("**************Enter the angles of your triangle to know it's type*********")
angle1 = int(input("Enter angle1 : "))
- if angle1 < 180 and angle1 > 0:
- angles.append(angle1)
- else:
+ if angle1 >= 180 or angle1 <= 0:
print("Please enter a value less than 180°")
angle1 = int(input())
- angles.append(angle1)
-
angle2 = int(input("Enter angle2 : "))
- if angle2 < 180 and angle2 > 0:
- angles.append(angle2)
- else:
+ if angle2 >= 180 or angle2 <= 0:
print("Please enter a value less than 180°")
angle2 = int(input())
- angles.append(angle2)
-
angle3 = int(input("Enter angle3 : "))
- if angle3 < 180 and angle3 > 0:
- angles.append(angle3)
- else:
+ if angle3 >= 180 or angle3 <= 0:
print("Please enter a value less than 180°")
angle3 = int(input())
- angles.append(angle3)
-
+ angles = [angle1, angle2, angle3]
sum_of_angles = angle1 + angle2 + angle3
if sum_of_angles > 180 or sum_of_angles < 180:
print("It is not a triangle!Please enter valid angles.")
return -1
- print("You have entered : " + str(angles))
+ print(f"You have entered : {angles}")
if angle1 >= 90 or angle2 >= 90 or angle3 >= 90:
print(myDict.get("Has a right angle (90°)"))
- elif angle1 < 90 and angle2 < 90 and angle3 < 90:
+ else:
print(myDict.get("All angles are less than 90°."))
- elif angle1 > 90 or angle2 > 90 or angle3 > 90:
- print(myDict.get("Has an angle more than 90°"))
-
angle_type()
diff --git a/Type_of_angles_of_triangle.py b/Type_of_angles_of_triangle.py
index 62978777f56..ca752ca39ad 100644
--- a/Type_of_angles_of_triangle.py
+++ b/Type_of_angles_of_triangle.py
@@ -3,8 +3,6 @@
def angle_type():
- angles = []
-
myDict = {
"All angles are less than 90°.": "Acute Angle Triangle",
"Has a right angle (90°)": "Right Angle Triangle",
@@ -17,38 +15,24 @@ def angle_type():
angle1 = int(input("Enter angle 1 : "))
- if angle1 < 180 and angle1 > 0:
- angles.append(angle1)
-
- else:
+ if angle1 >= 180 or angle1 <= 0:
print("Please enter a value less than 180°")
angle1 = int(input())
- angles.append(angle1)
-
# Taking Angle 2
angle2 = int(input("Enter angle2 : "))
- if angle2 < 180 and angle2 > 0:
- angles.append(angle2)
-
- else:
+ if angle2 >= 180 or angle2 <= 0:
print("Please enter a value less than 180°")
angle2 = int(input("Enter angle 2 :"))
- angles.append(angle2)
-
# Taking Angle 3
angle3 = int(input("Enter angle3 : "))
- if angle3 < 180 and angle3 > 0:
- angles.append(angle3)
-
- else:
+ if angle3 >= 180 or angle3 <= 0:
print("Please enter a value less than 180°")
angle3 = int(input("Enter angle3 : "))
- angles.append(angle3)
-
+ angles = [angle1, angle2, angle3]
# Answer
sum_of_angles = angle1 + angle2 + angle3
@@ -56,7 +40,7 @@ def angle_type():
print("It is not a triangle!Please enter valid angles.")
return -1
- print("You have entered : " + str(angles))
+ print(f"You have entered : {angles}")
if angle1 == 90 or angle2 == 90 or angle3 == 90:
print(myDict.get("Has a right angle (90°)"))
diff --git a/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py b/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py
index 1c2baf70897..eecaeefafd4 100644
--- a/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py
+++ b/VoiceAssistant/Project_Basic_struct/VoiceAssistant_main.py
@@ -14,7 +14,7 @@ def main():
print("\nSay \"Hello Python\" to activate the Voice Assistant!")
start += 1
while True:
-
+
q = short_hear().lower()
if "close" in q:
greet("end")
@@ -23,7 +23,7 @@ def main():
greet("start")
print_menu()
while True:
-
+
query = hear().lower()
if "close" in query:
greet("end")
@@ -32,32 +32,32 @@ def main():
elif "text to speech" in query:
tts()
time.sleep(4)
-
+
elif "search on google" in query or "search google" in query or "google" in query:
google_search()
time.sleep(10)
-
+
elif "search on wikipedia" in query or "search wikipedia" in query or "wikipedia" in query:
wiki_search()
time.sleep(10)
-
+
elif "word" in query:
ms_word()
time.sleep(5)
-
+
elif "book" in query:
pdf_read()
time.sleep(10)
-
+
elif "speech to text" in query:
big_text()
time.sleep(5)
-
+
else:
print("I could'nt understand what you just said!")
speak("I could'nt understand what you just said!")
-
+
print("\nDo you want to continue? if yes then say " + Fore.YELLOW + "\"YES\"" + Fore.WHITE + " else say " + Fore.YELLOW + "\"CLOSE PYTHON\"")
speak("Do you want to continue? if yes then say YES else say CLOSE PYTHON")
qry = hear().lower()
diff --git a/VoiceAssistant/Project_Basic_struct/dictator.py b/VoiceAssistant/Project_Basic_struct/dictator.py
index f5cb71fb014..1f57b85763c 100644
--- a/VoiceAssistant/Project_Basic_struct/dictator.py
+++ b/VoiceAssistant/Project_Basic_struct/dictator.py
@@ -7,7 +7,7 @@
def big_text():
print("By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?")
speak("By default, I will record your voice for 60 seconds.\nDo you want to change this default timing?")
- print(Fore.YELLOW + "Yes or No")
+ print(f"{Fore.YELLOW}Yes or No")
query = hear().lower()
duration_time = 0
diff --git a/VoiceAssistant/Project_Basic_struct/speakListen.py b/VoiceAssistant/Project_Basic_struct/speakListen.py
index e16db721abb..70755d13932 100644
--- a/VoiceAssistant/Project_Basic_struct/speakListen.py
+++ b/VoiceAssistant/Project_Basic_struct/speakListen.py
@@ -30,7 +30,7 @@ def greet(g):
Args:
g (str): To decide whether to say hello or good bye
"""
- if g == "start" or g == "s":
+ if g in ["start", "s"]:
h = datetime.datetime.now().hour
text = ''
if h > 12 and h < 17:
@@ -41,8 +41,8 @@ def greet(g):
text = "Hello! Good Evening "
text += " I am Python, How may i help you ?"
speak(text)
-
- elif g == "quit" or g == "end" or g == "over" or g == "e":
+
+ elif g in ["quit", "end", "over", "e"]:
text = 'Thank you!. Good Bye ! '
speak(text)
@@ -72,7 +72,7 @@ def hear():
recognizing()
speech = r.recognize_google(speech)
print(speech + "\n")
-
+
except Exception as exception:
print(exception)
return "None"
@@ -111,11 +111,11 @@ def long_hear(duration_time = 60):
#speech = r.listen(source)
# convert speech to text
try:
- print(Fore.RED +"Recognizing...")
+ print(f"{Fore.RED}Recognizing...")
#recognizing()
speech = r.recognize_google(speech)
- #print(speech + "\n")
-
+ #print(speech + "\n")
+
except Exception as exception:
print(exception)
return "None"
@@ -145,11 +145,11 @@ def short_hear(duration_time = 5):
#speech = r.listen(source)
# convert speech to text
try:
- print(Fore.RED +"Recognizing...")
+ print(f"{Fore.RED}Recognizing...")
#recognizing()
speech = r.recognize_google(speech)
- #print(speech + "\n")
-
+ #print(speech + "\n")
+
except Exception as exception:
print(exception)
return "None"
@@ -157,13 +157,6 @@ def short_hear(duration_time = 5):
-if __name__ == '__main__':
- # print("Enter your name")
- # name = hear()
- # speak("Hello " + name)
- # greet("s")
- # greet("e")
- pass
#hear()
#recognizing()
diff --git a/VoiceAssistant/Project_Basic_struct/textRead.py b/VoiceAssistant/Project_Basic_struct/textRead.py
index 030c78501f0..5dec893e8c5 100644
--- a/VoiceAssistant/Project_Basic_struct/textRead.py
+++ b/VoiceAssistant/Project_Basic_struct/textRead.py
@@ -14,13 +14,11 @@ def ms_word():
try:
speak("Enter the document's location - ")
location = input("Enter the document's location - ")
-
+
file_loc = doubleslash(location)
-
+
doc = docx.Document(file_loc)
- fullText = []
- for para in doc.paragraphs:
- fullText.append(para.text)
+ fullText = [para.text for para in doc.paragraphs]
#print(fullText)
doc_file = '\n'.join(fullText)
print(doc_file)
@@ -37,7 +35,7 @@ def pdf_read():
try:
speak("Enter the document's location - ")
location = input("Enter the document's location - ")
-
+
path = doubleslash(location)
pdf = fitz.open(path)
details = pdf.metadata # Stores the meta-data which generally includes Author name and Title of book/document.
@@ -47,32 +45,40 @@ def pdf_read():
print(f"ERROR - {exp}")
print(Fore.YELLOW + "I could'nt locate the file!\nIf you didn't specify the extension of the file, please specify it.")
return "None"
- try :
+ try:
""" 1. Author
2. Creator
3. Producer
4. Title """
-
+
author = details["author"]
#print("Author : ",author)
-
+
title = details["title"]
#print("Title : ",title)
-
+
#print(details)
#print("Total Pages : ",total_pages)
book_details(author, title, total_pages)
speak(f" Title {title}")
speak(f" Author {author}")
speak(f" Total Pages {total_pages}")
-
+
# TODO : Deal with the Index
toc = pdf.get_toc()
print("Say 1 or \"ONLY PRINT INDEX\" - if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'")
speak("Say 1 or only print index if you want me to print the book's index.\nSay 2 if you want me to print and make me speak out the book's index.\nSay any key if you don't want to print the index.'")
q = hear().lower()
- if "only print" in q or "1" in q or "one" in q or "vone" in q or 'only' in q or "index only" in q or 'only' in q or "print only" in q:
+ if (
+ "only print" in q
+ or "1" in q
+ or "one" in q
+ or "vone" in q
+ or 'only' in q
+ or "index only" in q
+ or "print only" in q
+ ):
print_index(toc)
time.sleep(15)
elif "speak" in q or "2" in q or 'two' in q:
@@ -84,18 +90,15 @@ def pdf_read():
time.sleep(4)
else:
time.sleep(4)
- pass
-
-
"""Allow the user to do the following
1. Read/speak a page
2. Read/speak a range of pages
3. Lesson
4. Read/speak a whole book
"""
-
+
#time.sleep(5)
-
+
print("____________________________________________________________________________________________________________")
print("1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book")
speak("1. Print/speak a single page\n2. Print/speak a range of pages\n3. Print/speak a Lesson\n4. Read/speak a whole book")
@@ -118,7 +121,7 @@ def pdf_read():
print(text.replace('\t',' '))
speak(text.replace('\t',' '))
-
+
elif 'range' in q or "multiple" in q:
try:
start_pg_no = int(input("Starting Page Number - "))
@@ -143,15 +146,7 @@ def pdf_read():
try:
key = input("Lesson name - ")
start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages)
- if start_pg_no != None and end_pg_no != None:
- start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages))
-
- for i in range(start_pg_no - 1, end_pg_no):
- page = pdf.load_page(i)
- text = page.get_text('text')
- print(text.replace('\t',' '))
- speak(text.replace('\t',' '))
- else:
+ if start_pg_no is None or end_pg_no is None:
print("Try Again.")
speak("Try Again.")
speak("Lesson name")
@@ -163,7 +158,15 @@ def pdf_read():
text = page.get_text('text')
print(text.replace('\t',' '))
speak(text.replace('\t',' '))
-
+
+ else:
+ start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages))
+
+ for i in range(start_pg_no - 1, end_pg_no):
+ page = pdf.load_page(i)
+ text = page.get_text('text')
+ print(text.replace('\t',' '))
+ speak(text.replace('\t',' '))
except Exception:
print("Try Again! Lesson could not be found.")
speak("Try Again.Lesson could not be found")
@@ -172,7 +175,7 @@ def pdf_read():
start_pg_no, end_pg_no = search_in_toc(toc, key, total_pages)
if start_pg_no != None and end_pg_no != None:
start_pg_no, end_pg_no = map(int,search_in_toc(toc, key, total_pages))
-
+
for i in range(start_pg_no - 1, end_pg_no):
page = pdf.load_page(i)
text = page.get_text('text')
@@ -197,7 +200,6 @@ def pdf_read():
time.sleep(5)
except Exception as e:
print(e)
- pass
pdf.close()
def doubleslash(text):
@@ -257,19 +259,18 @@ def search_in_toc(toc, key, totalpg):
"""
for i in range(len(toc) - 1):
topic = toc[i]
- if i != len(toc) - 2:
- if topic[1] == key:
- nexttopic = toc[i + 1]
- return (topic[2], nexttopic[2])
- elif topic[1].lower() == key:
- nexttopic = toc[i + 1]
- return (topic[2], nexttopic[2])
- else:
+ if i == len(toc) - 2:
if topic[1] == key:
return (topic[2], totalpg)
elif topic[1].lower() == key:
-
+
return (topic[2], totalpg)
+ elif topic[1] == key:
+ nexttopic = toc[i + 1]
+ return (topic[2], nexttopic[2])
+ elif topic[1].lower() == key:
+ nexttopic = toc[i + 1]
+ return (topic[2], nexttopic[2])
return None,None
def book_details(author, title, total_pages):
diff --git a/VoiceAssistant/Project_Basic_struct/websiteWork.py b/VoiceAssistant/Project_Basic_struct/websiteWork.py
index c20a2792791..853eb8c7317 100644
--- a/VoiceAssistant/Project_Basic_struct/websiteWork.py
+++ b/VoiceAssistant/Project_Basic_struct/websiteWork.py
@@ -13,16 +13,16 @@
def google_search():
"""[Goes to google and searches the website asked by the user]
"""
- google_search_link = "https://www.google.co.in/search?q="
google_search = "What do you want me to search on Google? "
print(google_search)
speak(google_search)
-
+
query = hear()
if query != "None":
+ google_search_link = "https://www.google.co.in/search?q="
webbrowser.open(google_search_link+query)
- elif query == "None":
+ else:
print("I could'nt understand what you just said!")
speak("I could'nt understand what you just said!")
@@ -31,7 +31,7 @@ def wiki_search():
"""
wiki_search = "What do you want me to search on Wikipedia? Please tell me the exact sentence or word to Search."
wiki_search_link = "https://en.wikipedia.org/wiki/"
-
+
print(wiki_search)
speak(wiki_search)
diff --git a/VoiceRepeater/__main__.py b/VoiceRepeater/__main__.py
index dc3e20a9739..6aedf3997a7 100644
--- a/VoiceRepeater/__main__.py
+++ b/VoiceRepeater/__main__.py
@@ -12,10 +12,10 @@
def callback(recognizer, audio):
- with open("spoken/" + str(len(speeches)) + ".wav", "wb") as file:
+ with open(f"spoken/{len(speeches)}.wav", "wb") as file:
file.write(audio.get_wav_data())
- playsound.playsound("spoken/" + str(len(speeches)) + ".wav")
+ playsound.playsound(f"spoken/{len(speeches)}.wav")
speeches.append(1)
print("____")
diff --git a/Weather Scrapper/weather.py b/Weather Scrapper/weather.py
index 55e8c59e4e7..0f327e0acaf 100644
--- a/Weather Scrapper/weather.py
+++ b/Weather Scrapper/weather.py
@@ -5,7 +5,7 @@
from bs4 import BeautifulSoup
city = input("Enter City")
-url = "https://www.wunderground.com/weather/in/" + city
+url = f"https://www.wunderground.com/weather/in/{city}"
try:
response = requests.get(url)
diff --git a/WeatherGUI.py b/WeatherGUI.py
index 19b42994b84..831817b4af0 100644
--- a/WeatherGUI.py
+++ b/WeatherGUI.py
@@ -22,7 +22,7 @@ def getWeather():
wind = soup.find("span", class_="_1Va1P undefined").text
pressure = soup.find("span", class_="_3olKd undefined").text
locationlabel.config(text=(location))
- templabel.config(text=temperature + "C")
+ templabel.config(text=f"{temperature}C")
WeatherText = (
"Sunrise : "
+ sunrise
diff --git a/WikipediaModule.py b/WikipediaModule.py
index dec5e2a5c0b..a98f2f543be 100644
--- a/WikipediaModule.py
+++ b/WikipediaModule.py
@@ -39,14 +39,10 @@ def wiki():
print("Page Id = ", pageId)
print(page.summary)
print("Page Link = ", url)
- # print "References : ",references
-
- pass
def fullPage(page):
- soup = BeautifulSoup(page.content, "lxml")
- return soup
+ return BeautifulSoup(page.content, "lxml")
def randomWiki():
@@ -80,9 +76,6 @@ def randomWiki():
print("Page Id = ", pageId)
print(page.summary)
print("Page Link = ", url)
- # print "References : ",references
-
- pass
# if __name__=="__main__":
diff --git a/Windows_Wallpaper_Script/wallpaper_extract.py b/Windows_Wallpaper_Script/wallpaper_extract.py
index 541462bdff4..4eef47444db 100644
--- a/Windows_Wallpaper_Script/wallpaper_extract.py
+++ b/Windows_Wallpaper_Script/wallpaper_extract.py
@@ -57,12 +57,11 @@ def change_ext():
# Look into all the files in the executing folder and change extension
for filename in os.listdir(w.file_urls["wall_dst"]):
base_file, ext = os.path.splitext(filename)
- if ext == "":
- if not os.path.isdir(w.file_urls["wall_dst"] + filename):
- os.rename(
- w.file_urls["wall_dst"] + filename,
- w.file_urls["wall_dst"] + filename + ".jpg",
- )
+ if ext == "" and not os.path.isdir(w.file_urls["wall_dst"] + filename):
+ os.rename(
+ w.file_urls["wall_dst"] + filename,
+ w.file_urls["wall_dst"] + filename + ".jpg",
+ )
# Remove all files Not having Wallpaper Resolution
@staticmethod
@@ -76,7 +75,7 @@ def extract_wall():
im = Image.open(w.file_urls["wall_dst"] + filename)
except IOError:
print("This isn't a picture.", filename)
- if list(im.size)[0] != 1920 and list(im.size)[0] != 1080:
+ if list(im.size)[0] not in [1920, 1080]:
im.close()
os.remove(w.file_urls["wall_dst"] + filename)
else:
diff --git a/Wordle/wordle.py b/Wordle/wordle.py
index ffed27a1838..3757a87cbca 100644
--- a/Wordle/wordle.py
+++ b/Wordle/wordle.py
@@ -22,6 +22,7 @@
new_dictionary.close()
"""
+
# import the library random
import random
@@ -37,10 +38,7 @@
dif_letters = list(set(word))
# Count how many times each letter occurs in the word
-count_letters = {}
-for i in dif_letters:
- count_letters[i] = word.count(i)
-
+count_letters = {i: word.count(i) for i in dif_letters}
# Set tries to 0
tries = 0
@@ -58,12 +56,12 @@
break
# Check if the word given by the user is 5 characters long
- if not len(user_inp) == 5:
+ if len(user_inp) != 5:
print("Your input must be 5 letters long")
continue
# Check if the word given by the user is in the dictionary
- if not user_inp in dictionary:
+ if user_inp not in dictionary:
print("Your word is not in the dictionary")
continue
@@ -104,13 +102,15 @@
# Check if letter is in the correct position
if user_inp[letter] == i:
return_answer += "G"
- else:
- if not user_inp[word.index(user_inp[letter])] == word[word.index(user_inp[letter])]:
- return_answer += "Y"
- else:
- answer_given = False
- do_not_add = True
+ elif (
+ user_inp[word.index(user_inp[letter])]
+ == word[word.index(user_inp[letter])]
+ ):
+ answer_given = False
+ do_not_add = True
+ else:
+ return_answer += "Y"
# Check if there has already been an answer returned
if not answer_given:
return_answer += "-"
diff --git a/XORcipher/XOR_cipher.py b/XORcipher/XOR_cipher.py
index 4d6bdb2190a..49d260fa335 100644
--- a/XORcipher/XOR_cipher.py
+++ b/XORcipher/XOR_cipher.py
@@ -45,13 +45,7 @@ def encrypt(self, content, key):
while key > 255:
key -= 255
- # This will be returned
- ans = []
-
- for ch in content:
- ans.append(chr(ord(ch) ^ key))
-
- return ans
+ return [chr(ord(ch) ^ key) for ch in content]
def decrypt(self, content, key):
"""
@@ -70,13 +64,7 @@ def decrypt(self, content, key):
while key > 255:
key -= 255
- # This will be returned
- ans = []
-
- for ch in content:
- ans.append(chr(ord(ch) ^ key))
-
- return ans
+ return [chr(ord(ch) ^ key) for ch in content]
def encrypt_string(self, content, key=0):
"""
@@ -95,13 +83,7 @@ def encrypt_string(self, content, key=0):
while key > 255:
key -= 255
- # This will be returned
- ans = ""
-
- for ch in content:
- ans += chr(ord(ch) ^ key)
-
- return ans
+ return "".join(chr(ord(ch) ^ key) for ch in content)
def decrypt_string(self, content, key=0):
"""
@@ -120,13 +102,7 @@ def decrypt_string(self, content, key=0):
while key > 255:
key -= 255
- # This will be returned
- ans = ""
-
- for ch in content:
- ans += chr(ord(ch) ^ key)
-
- return ans
+ return "".join(chr(ord(ch) ^ key) for ch in content)
def encrypt_file(self, file, key=0):
"""
diff --git a/Youtube Downloader With GUI/main.py b/Youtube Downloader With GUI/main.py
index 21d5c534ad5..7999318699d 100644
--- a/Youtube Downloader With GUI/main.py
+++ b/Youtube Downloader With GUI/main.py
@@ -36,7 +36,7 @@ def startDownload():
dfile_size = file_size
dfile_size /= 1000000
dfile_size = round(dfile_size, 2)
- label.config(text="Size: " + str(dfile_size) + " MB")
+ label.config(text=f"Size: {str(dfile_size)} MB")
label.pack(side=TOP, pady=10)
desc.config(
text=ob.title
diff --git a/addition.py b/addition.py
index 2a90bae31fb..38185b8823e 100644
--- a/addition.py
+++ b/addition.py
@@ -3,7 +3,7 @@
a = True
-while a == True:
+while a:
number1 = int(input("enter first number:"))
number2 = int(input("enter second number:"))
diff --git a/alexa_news_headlines.py b/alexa_news_headlines.py
index 7cb84b9fe09..2ac1b201fd9 100644
--- a/alexa_news_headlines.py
+++ b/alexa_news_headlines.py
@@ -23,7 +23,7 @@ def get_headlines():
unidecode.unidecode(listing["data"]["title"])
for listing in data["data"]["children"]
]
- titles = "... ".join([i for i in titles])
+ titles = "... ".join(list(titles))
return titles
@@ -41,7 +41,7 @@ def start_skill():
@ask.intent("YesIntent")
def share_headlines():
headlines = get_headlines()
- headline_msg = "The current world news headlines are {}".format(headlines)
+ headline_msg = f"The current world news headlines are {headlines}"
return statement(headline_msg)
diff --git a/area_of_square.py b/area_of_square.py
index 471e7c1cdb6..fb3e8402e1a 100644
--- a/area_of_square.py
+++ b/area_of_square.py
@@ -1,5 +1,5 @@
# Returns the area of the square with given sides
n = input("Enter the side of the square: ") # Side length should be given in input
side = float(n)
-area = side * side # calculate area
+area = side**2
print("Area of the given square is ", area)
diff --git a/async_downloader/async_downloader.py b/async_downloader/async_downloader.py
index 4f715048905..4aff1b937e8 100644
--- a/async_downloader/async_downloader.py
+++ b/async_downloader/async_downloader.py
@@ -71,19 +71,11 @@ async def download_file_by_url(url, session=None):
try:
async with session.get(url) as response:
if response.status == 404:
- print(
- "\t{} from {} : Failed : {}".format(
- file_name, url, "404 - Not found"
- )
- )
+ print(f"\t{file_name} from {url} : Failed : 404 - Not found")
return fail, url
- if not response.status == 200:
- print(
- "\t{} from {} : Failed : HTTP response {}".format(
- file_name, url, response.status
- )
- )
+ if response.status != 200:
+ print(f"\t{file_name} from {url} : Failed : HTTP response {response.status}")
return fail, url
data = await response.read()
@@ -92,17 +84,13 @@ async def download_file_by_url(url, session=None):
file.write(data)
except asyncio.TimeoutError:
- print("\t{} from {}: Failed : {}".format(file_name, url, "Timeout error"))
+ print(f"\t{file_name} from {url}: Failed : Timeout error")
except aiohttp.client_exceptions.ClientConnectionError:
- print(
- "\t{} from {}: Failed : {}".format(
- file_name, url, "Client connection error"
- )
- )
+ print(f"\t{file_name} from {url}: Failed : Client connection error")
else:
- print("\t{} from {} : Success".format(file_name, url))
+ print(f"\t{file_name} from {url} : Success")
fail = False
return fail, url
diff --git a/backup_automater_services.py b/backup_automater_services.py
index 21ec7aa0b62..f00e113ee9a 100644
--- a/backup_automater_services.py
+++ b/backup_automater_services.py
@@ -37,8 +37,7 @@
# the destination backup directory
for file_name in open(conffilename): # Walk through the configuration file
- fname = file_name.strip() # Strip out the blank lines from the configuration file
- if fname: # For the lines that are not blank
+ if fname := file_name.strip():
sourcefile = os.path.join(
sourcedir, fname
) # Get the name of the source files to backup
diff --git a/balance_parenthesis.py b/balance_parenthesis.py
index cd89ddcf6bd..e6e576a0b5b 100644
--- a/balance_parenthesis.py
+++ b/balance_parenthesis.py
@@ -19,14 +19,14 @@ def display(self):
def is_same(p1, p2):
- if p1 == "(" and p2 == ")":
- return True
- elif p1 == "[" and p2 == "]":
- return True
- elif p1 == "{" and p2 == "}":
- return True
- else:
- return False
+ return (
+ p1 == "("
+ and p2 == ")"
+ or p1 == "["
+ and p2 == "]"
+ or p1 == "{"
+ and p2 == "}"
+ )
def is_balanced(check_string):
@@ -37,19 +37,15 @@ def is_balanced(check_string):
paren = check_string[index]
if paren in "{[(":
s.push(paren)
+ elif s.is_empty():
+ is_bal = False
else:
- if s.is_empty():
+ top = s.pop()
+ if not is_same(top, paren):
is_bal = False
- else:
- top = s.pop()
- if not is_same(top, paren):
- is_bal = False
index += 1
- if s.is_empty() and is_bal:
- return True
- else:
- return False
+ return bool(s.is_empty() and is_bal)
print(is_balanced("[((())})]"))
diff --git a/bank_managment_system/backend.py b/bank_managment_system/backend.py
index e54027cf0a6..9b636fe2d13 100644
--- a/bank_managment_system/backend.py
+++ b/bank_managment_system/backend.py
@@ -21,10 +21,7 @@ def connect_database():
cur.execute("select acc_no from bank")
acc = cur.fetchall()
global acc_no
- if len(acc) == 0:
- acc_no = 1
- else:
- acc_no = int(acc[-1][0]) + 1
+ acc_no = 1 if len(acc) == 0 else int(acc[-1][0]) + 1
# check admin dtails in database
@@ -53,11 +50,9 @@ def check_employee(name, password):
print(data)
if len(data) == 0:
return False
- for i in range(len(data)):
- if data[i][0] == name and data[i][1] == password:
- return True
-
- return False
+ return any(
+ data[i][0] == name and data[i][1] == password for i in range(len(data))
+ )
# create customer details in database
@@ -77,10 +72,7 @@ def check_acc_no(acc_no):
cur.execute("select acc_no from bank")
list_acc_no = cur.fetchall()
- for i in range(len(list_acc_no)):
- if list_acc_no[i][0] == int(acc_no):
- return True
- return False
+ return any(list_acc_no[i][0] == int(acc_no) for i in range(len(list_acc_no)))
# get all details of a particular customer from database
@@ -121,12 +113,11 @@ def deduct_balance(new_money, acc_no):
bal = bal[0][0]
if bal < int(new_money):
return False
- else:
- new_bal = bal - int(new_money)
+ new_bal = bal - int(new_money)
- cur.execute("update bank set balance=? where acc_no=?", (new_bal, acc_no))
- conn.commit()
- return True
+ cur.execute("update bank set balance=? where acc_no=?", (new_bal, acc_no))
+ conn.commit()
+ return True
# gave balance of a particular account number from database
@@ -139,32 +130,28 @@ def check_balance(acc_no):
# update_name_in_bank_table
def update_name_in_bank_table(new_name, acc_no):
print(new_name)
- conn.execute("update bank set name='{}' where acc_no={}".format(new_name, acc_no))
+ conn.execute(f"update bank set name='{new_name}' where acc_no={acc_no}")
conn.commit()
# update_age_in_bank_table
def update_age_in_bank_table(new_name, acc_no):
print(new_name)
- conn.execute("update bank set age={} where acc_no={}".format(new_name, acc_no))
+ conn.execute(f"update bank set age={new_name} where acc_no={acc_no}")
conn.commit()
# update_address_in_bank_table
def update_address_in_bank_table(new_name, acc_no):
print(new_name)
- conn.execute(
- "update bank set address='{}' where acc_no={}".format(new_name, acc_no)
- )
+ conn.execute(f"update bank set address='{new_name}' where acc_no={acc_no}")
conn.commit()
# list of all customers in bank
def list_all_customers():
cur.execute("select * from bank")
- deatil = cur.fetchall()
-
- return deatil
+ return cur.fetchall()
# delete account from database
@@ -176,8 +163,7 @@ def delete_acc(acc_no):
# show employees detail from staff table
def show_employees():
cur.execute("select name, salary, position,pass from staff")
- detail = cur.fetchall()
- return detail
+ return cur.fetchall()
# return all money in bank
@@ -187,54 +173,47 @@ def all_money():
print(bal)
if len(bal) == 0:
return False
- else:
- total = 0
- for i in bal:
- total = total + i[0]
- return total
+ total = 0
+ for i in bal:
+ total = total + i[0]
+ return total
# return a list of all employees name
def show_employees_for_update():
cur.execute("select * from staff")
- detail = cur.fetchall()
- return detail
+ return cur.fetchall()
# update employee name from data base
def update_employee_name(new_name, old_name):
print(new_name, old_name)
- cur.execute("update staff set name='{}' where name='{}'".format(new_name, old_name))
+ cur.execute(f"update staff set name='{new_name}' where name='{old_name}'")
conn.commit()
def update_employee_password(new_pass, old_name):
print(new_pass, old_name)
- cur.execute("update staff set pass='{}' where name='{}'".format(new_pass, old_name))
+ cur.execute(f"update staff set pass='{new_pass}' where name='{old_name}'")
conn.commit()
def update_employee_salary(new_salary, old_name):
print(new_salary, old_name)
- cur.execute(
- "update staff set salary={} where name='{}'".format(new_salary, old_name)
- )
+ cur.execute(f"update staff set salary={new_salary} where name='{old_name}'")
conn.commit()
def update_employee_position(new_pos, old_name):
print(new_pos, old_name)
- cur.execute(
- "update staff set position='{}' where name='{}'".format(new_pos, old_name)
- )
+ cur.execute(f"update staff set position='{new_pos}' where name='{old_name}'")
conn.commit()
# get name and balance from bank of a particular account number
def get_detail(acc_no):
cur.execute("select name, balance from bank where acc_no=?", (acc_no))
- details = cur.fetchall()
- return details
+ return cur.fetchall()
def check_name_in_staff(name):
@@ -242,7 +221,4 @@ def check_name_in_staff(name):
cur.execute("select name from staff")
details = cur.fetchall()
- for i in details:
- if i[0] == name:
- return True
- return False
+ return any(i[0] == name for i in details)
diff --git a/bank_managment_system/frontend.py b/bank_managment_system/frontend.py
index c885c2b37c3..40652ee5be9 100644
--- a/bank_managment_system/frontend.py
+++ b/bank_managment_system/frontend.py
@@ -9,8 +9,7 @@
# A function for check that acc_no is integer or not
def check_string_in_account_no(check_acc_no):
- r = check_acc_no.isdigit()
- return r
+ return check_acc_no.isdigit()
# all buttons of page2
diff --git a/batch_file_rename.py b/batch_file_rename.py
index b3a4d75e6d5..24f2450cd40 100644
--- a/batch_file_rename.py
+++ b/batch_file_rename.py
@@ -69,11 +69,11 @@ def main():
# Set the variable old_ext with the second argument passed
old_ext = args["old_ext"][0]
if old_ext and old_ext[0] != ".":
- old_ext = "." + old_ext
+ old_ext = f".{old_ext}"
# Set the variable new_ext with the third argument passed
new_ext = args["new_ext"][0]
if new_ext and new_ext[0] != ".":
- new_ext = "." + new_ext
+ new_ext = f".{new_ext}"
batch_rename(work_dir, old_ext, new_ext)
diff --git a/binary_search_tree.py b/binary_search_tree.py
index 327c45c722d..ce5717f8294 100755
--- a/binary_search_tree.py
+++ b/binary_search_tree.py
@@ -57,9 +57,7 @@ def search(self, val, to_delete=False):
prev = current
current = current.right
elif current.info == val:
- if not to_delete:
- return "Match Found"
- return prev
+ return prev if to_delete else "Match Found"
else:
break
if not to_delete:
@@ -69,76 +67,70 @@ def search(self, val, to_delete=False):
def delete(self, val):
prev = self.search(val, True)
# Check if node exists
- if prev is not None:
- # Check if node is the Root node
- if prev == -1:
- temp = self.root.left
- prev2 = None
- while temp.right:
+ if prev is None:
+ print("Node doesn't exists")
+
+ elif prev == -1:
+ temp = self.root.left
+ prev2 = None
+ while temp.right:
+ prev2 = temp
+ temp = temp.right
+ if prev2 is None:
+ self.root.left = temp.left
+ else:
+ prev2.right = None
+ self.root.info = temp.info
+ print("Deleted Root ", val)
+ elif prev.left and prev.left.info == val:
+ # Check if node is leaf node
+ if prev.left.left is prev.left.right:
+ prev.left = None
+ print("Deleted Node ", val)
+ # Check if node has child at left and None at right
+ elif prev.left.left and prev.left.right is None:
+ prev.left = prev.left.left
+ print("Deleted Node ", val)
+ # Check if node has child at right and None at left
+ elif prev.left.left is None and prev.left.right:
+ prev.left = prev.left.right
+ print("Deleted Node ", val)
+ # Here node to be deleted has 2 children
+ elif prev.left.left and prev.left.right:
+ temp = prev.left
+ while temp.right is not None:
prev2 = temp
temp = temp.right
- if prev2 is None:
- self.root.left = temp.left
- self.root.info = temp.info
- else:
- prev2.right = None
- self.root.info = temp.info
- print("Deleted Root ", val)
- # Check if node is to left of its parent
- elif prev.left and prev.left.info == val:
- # Check if node is leaf node
- if prev.left.left is prev.left.right:
- prev.left = None
- print("Deleted Node ", val)
- # Check if node has child at left and None at right
- elif prev.left.left and prev.left.right is None:
- prev.left = prev.left.left
- print("Deleted Node ", val)
- # Check if node has child at right and None at left
- elif prev.left.left is None and prev.left.right:
- prev.left = prev.left.right
- print("Deleted Node ", val)
- # Here node to be deleted has 2 children
- elif prev.left.left and prev.left.right:
- temp = prev.left
- while temp.right is not None:
- prev2 = temp
- temp = temp.right
- prev2.right = None
- prev.left.info = temp.info
- print("Deleted Node ", val)
- else:
- print("Error Left")
-
- # Check if node is to right of its parent
- elif prev.right.info == val:
- flag = 0
- # Check is node is a leaf node
- if prev.right.left is prev.right.right:
- prev.right = None
- flag = 1
- print("Deleted Node ", val)
+ prev2.right = None
+ prev.left.info = temp.info
+ print("Deleted Node ", val)
+ else:
+ print("Error Left")
+
+ elif prev.right.info == val:
+ flag = 0
+ # Check is node is a leaf node
+ if prev.right.left is prev.right.right:
+ prev.right = None
+ flag = 1
+ print("Deleted Node ", val)
# Check if node has left child at None at right
- if prev.right and prev.right.left and prev.right.right is None:
- prev.right = prev.right.left
- print("Deleted Node ", val)
- # Check if node has right child at None at left
- elif prev.right and prev.right.left is None and prev.right.right:
- prev.right = prev.right.right
- print("Deleted Node ", val)
- elif prev.right and prev.right.left and prev.right.right:
- temp = prev.right
- while temp.left is not None:
- prev2 = temp
- temp = temp.left
- prev2.left = None
- prev.right.info = temp.info
- print("Deleted Node ", val)
- else:
- if flag == 0:
- print("Error")
- else:
- print("Node doesn't exists")
+ if prev.right and prev.right.left and prev.right.right is None:
+ prev.right = prev.right.left
+ print("Deleted Node ", val)
+ elif prev.right and prev.right.left is None and prev.right.right:
+ prev.right = prev.right.right
+ print("Deleted Node ", val)
+ elif prev.right and prev.right.left and prev.right.right:
+ temp = prev.right
+ while temp.left is not None:
+ prev2 = temp
+ temp = temp.left
+ prev2.left = None
+ prev.right.info = temp.info
+ print("Deleted Node ", val)
+ elif flag == 0:
+ print("Error")
def __str__(self):
return "Not able to print tree yet"
diff --git a/binod.py b/binod.py
index 2bee72de9d6..a81ac0c1faf 100644
--- a/binod.py
+++ b/binod.py
@@ -24,11 +24,10 @@ def checkBinod(file): # Trying to find Binod In File Insted Of Manohar Ka Kotha
with open(file, "r") as f:
# master
fileContent = f.read()
- if "binod" in fileContent.lower():
- print(f"**************Congratulations Binod found in {f}********************")
- return True
- else:
+ if "binod" not in fileContent.lower():
return False
+ print(f"**************Congratulations Binod found in {f}********************")
+ return True
if __name__ == "__main__":
diff --git a/birthdays.py b/birthdays.py
index 19ad2b001a2..13e38e550ab 100644
--- a/birthdays.py
+++ b/birthdays.py
@@ -6,9 +6,9 @@
if name == '':
break
if name in birthdays:
- print(birthdays[name] + ' is the birthday of ' + name)
+ print(f'{birthdays[name]} is the birthday of {name}')
else:
- print('I do not have birthday information for ' + name)
+ print(f'I do not have birthday information for {name}')
print('What is their birthday?')
bday = input()
birthdays[name] = bday
diff --git a/blackJackGUI.py b/blackJackGUI.py
index a67e6e06717..cd23811797d 100644
--- a/blackJackGUI.py
+++ b/blackJackGUI.py
@@ -65,9 +65,9 @@ def draw(self, canvas, pos):
def string_list_join(string, string_list):
- ans = string + " contains "
+ ans = f"{string} contains "
for i in range(len(string_list)):
- ans += str(string_list[i]) + " "
+ ans += f"{str(string_list[i])} "
return ans
@@ -91,10 +91,7 @@ def get_value(self):
var.append(card[1])
if "A" not in var:
return self.hand_value
- if self.hand_value + 10 <= 21:
- return self.hand_value + 10
- else:
- return self.hand_value
+ return self.hand_value + 10 if self.hand_value <= 11 else self.hand_value
def draw(self, canvas, pos):
for card in self.hand:
@@ -123,7 +120,7 @@ def deal():
player_card = Hand()
dealer_card = Hand()
deck = Deck()
- for i in range(2):
+ for _ in range(2):
player_card.add_card(deck.deal_card())
dealer_card.add_card(deck.deal_card())
diff --git a/blackjack.py b/blackjack.py
index 1cdac41bc43..6bee70b7ff7 100644
--- a/blackjack.py
+++ b/blackjack.py
@@ -47,9 +47,9 @@
print("***********************Dealer is the Winner !!******************")
exit()
-if sum(d_cards) == 21 and sum(p_cards) == 21:
- print("*****************The match is tie !!*************************")
- exit()
+ if sum(p_cards) == 21:
+ print("*****************The match is tie !!*************************")
+ exit()
def dealer_choice():
@@ -58,20 +58,17 @@ def dealer_choice():
random.shuffle(deck)
d_cards.append(deck.pop())
- print("Dealer has total " + str(sum(d_cards)) + "with the cards ", d_cards)
+ print(f"Dealer has total {str(sum(d_cards))}with the cards ", d_cards)
if sum(p_cards) == sum(d_cards):
print("***************The match is tie !!****************")
exit()
if sum(d_cards) == 21:
- if sum(p_cards) < 21:
+ if sum(p_cards) < 21 or sum(p_cards) != 21:
print("***********************Dealer is the Winner !!******************")
- elif sum(p_cards) == 21:
- print("********************There is tie !!**************************")
else:
- print("***********************Dealer is the Winner !!******************")
-
+ print("********************There is tie !!**************************")
elif sum(d_cards) < 21:
if sum(p_cards) < 21 and sum(p_cards) < sum(d_cards):
print("***********************Dealer is the Winner !!******************")
@@ -80,13 +77,10 @@ def dealer_choice():
if sum(p_cards) < 21 and sum(p_cards) > sum(d_cards):
print("**********************Player is winner !!**********************")
+ elif sum(p_cards) < 21 or sum(p_cards) == 21:
+ print("**********************Player is winner !!**********************")
else:
- if sum(p_cards) < 21:
- print("**********************Player is winner !!**********************")
- elif sum(p_cards) == 21:
- print("**********************Player is winner !!**********************")
- else:
- print("***********************Dealer is the Winner !!******************")
+ print("***********************Dealer is the Winner !!******************")
while sum(p_cards) < 21:
@@ -95,7 +89,7 @@ def dealer_choice():
if k == 1:
random.shuffle(deck)
p_cards.append(deck.pop())
- print("You have a total of " + str(sum(p_cards)) + " with the cards ", p_cards)
+ print(f"You have a total of {str(sum(p_cards))} with the cards ", p_cards)
if sum(p_cards) > 21:
print("*************You are BUSTED !*************\n Dealer Wins !!")
if sum(p_cards) == 21:
diff --git a/bookstore_manangement_system.py b/bookstore_manangement_system.py
index 7ae31cb195b..b7d93cd41f8 100644
--- a/bookstore_manangement_system.py
+++ b/bookstore_manangement_system.py
@@ -54,12 +54,7 @@ def login():
for y in data2:
- if y[1] == user_name and y[2] == passw:
-
- pass
-
- else:
-
+ if y[1] != user_name or y[2] != passw:
separator()
print(" Username or Password is Incorrect Try Again")
@@ -69,16 +64,11 @@ def login():
user_name = input(" USER NAME --- ")
passw = input(" PASSWORD --- ")
- if y[1] == user_name and y[2] == passw:
-
- pass
-
- else:
-
- separator()
+ if y[1] != user_name or y[2] != passw:
+ separator()
- print(" Username or Password is Again Incorrect")
- exit()
+ print(" Username or Password is Again Incorrect")
+ exit()
def ViewAll():
diff --git a/brickout-game/brickout-game.py b/brickout-game/brickout-game.py
index c212be6a634..5a314bbce36 100644
--- a/brickout-game/brickout-game.py
+++ b/brickout-game/brickout-game.py
@@ -199,16 +199,13 @@ def collide(self, ball):
ballXVel = ball.getXVel()
ballYVel = ball.getYVel()
- if (
+ return (
(ballX + ball._radius) >= brickX
and (ballX + ball._radius) <= (brickX + brickW)
) and (
(ballY - ball._radius) >= brickY
and (ballY - ball._radius) <= (brickY + brickH)
- ):
- return True
- else:
- return False
+ )
"""
@@ -228,8 +225,8 @@ def __init__(self, screen, x, y, width, height):
X = x
Y = y
- for i in range(3):
- for j in range(4):
+ for _ in range(3):
+ for _ in range(4):
self._bricks.append(Brick(screen, width, height, X, Y))
X += width + (width / 7.0)
Y += height + (height / 7.0)
@@ -279,10 +276,7 @@ def collide(self, ball):
check collisions between the ball and
any of the bricks.
"""
- for brick in self._bricks:
- if brick.collide(ball):
- return True
- return False
+ return any(brick.collide(ball) for brick in self._bricks)
# The game objects ball, paddle and brick wall
@@ -318,7 +312,7 @@ def collide(self, ball):
textsurfaceGameOver = mgGameOver.render("Game Over!", False, (0, 0, 0))
textsurfaceWin = mgWin.render("You win!", False, (0, 0, 0))
-textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0))
+textsurfaceScore = mgScore.render(f"score: {score}", False, (0, 0, 0))
# -------- Main Program Loop -----------
while not done:
@@ -352,7 +346,7 @@ def collide(self, ball):
# for counting and displaying the score
if brickWall.collide(ball):
score += 10
- textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0))
+ textsurfaceScore = mgScore.render(f"score: {str(score)}", False, (0, 0, 0))
screen.blit(textsurfaceScore, (300, 0))
# after scoring. because hit bricks are removed in the update-method
@@ -370,15 +364,14 @@ def collide(self, ball):
ball.draw()
- else: # game isn't running.
- if isGameOver: # player lose
- screen.blit(textsurfaceGameOver, (0, 0))
- textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0))
- screen.blit(textsurfaceScore, (300, 0))
- elif brickWall.hasWin(): # player win
- screen.blit(textsurfaceWin, (0, 0))
- textsurfaceScore = mgScore.render("score: " + str(score), False, (0, 0, 0))
- screen.blit(textsurfaceScore, (300, 0))
+ elif isGameOver: # player lose
+ screen.blit(textsurfaceGameOver, (0, 0))
+ textsurfaceScore = mgScore.render(f"score: {str(score)}", False, (0, 0, 0))
+ screen.blit(textsurfaceScore, (300, 0))
+ elif brickWall.hasWin(): # player win
+ screen.blit(textsurfaceWin, (0, 0))
+ textsurfaceScore = mgScore.render(f"score: {str(score)}", False, (0, 0, 0))
+ screen.blit(textsurfaceScore, (300, 0))
# --- Go ahead and update the screen with what we've drawn.
pygame.display.flip()
diff --git a/calc_area.py b/calc_area.py
index 7f35917c746..4439a5354b0 100644
--- a/calc_area.py
+++ b/calc_area.py
@@ -11,29 +11,29 @@ def main():
)
if shape == 1:
side = float(input("Enter length of side: "))
- print("Area of square = " + str(side ** 2))
+ print(f"Area of square = {str(side**2)}")
elif shape == 2:
l = float(input("Enter length: "))
b = float(input("Enter breadth: "))
- print("Area of rectangle = " + str(l * b))
+ print(f"Area of rectangle = {str(l * b)}")
elif shape == 3:
r = float(input("Enter radius: "))
- print("Area of circle = " + str(m.pi * r * r))
+ print(f"Area of circle = {str(m.pi * r * r)}")
elif shape == 4:
base = float(input("Enter base: "))
h = float(input("Enter height: "))
- print("Area of rectangle = " + str(0.5 * base * h))
+ print(f"Area of rectangle = {str(0.5 * base * h)}")
elif shape == 5:
r = float(input("Enter radius: "))
h = float(input("Enter height: "))
- print("Area of cylinder = " + str(m.pow(r, 2) * h * m.pi))
+ print(f"Area of cylinder = {str(m.pow(r, 2) * h * m.pi)}")
elif shape == 6:
r = float(input("Enter radius: "))
h = float(input("Enter height: "))
- print("Area of cone = " + str(m.pow(r, 2) * h * 1 / 3 * m.pi))
+ print(f"Area of cone = {str(m.pow(r, 2) * h * 1 / 3 * m.pi)}")
elif shape == 7:
r = float(input("Enter radius: "))
- print("Area of sphere = " + str(m.pow(r, 3) * 4 / 3 * m.pi))
+ print(f"Area of sphere = {str(m.pow(r, 3) * 4 / 3 * m.pi)}")
else:
print("You have selected wrong choice.")
diff --git a/calculator-gui.py b/calculator-gui.py
index e0a0ea5a28d..3a0c6b0ec6d 100755
--- a/calculator-gui.py
+++ b/calculator-gui.py
@@ -396,9 +396,7 @@ def geometry_settings(self):
_my_height = 350
_x = int(_com_width / 2 - _my_width / 2)
_y = int(_com_height / 2 - _my_height / 2)
- geo_string = (
- str(_my_width) + "x" + str(_my_height) + "+" + str(_x) + "+" + str(_y)
- )
+ geo_string = f"{_my_width}x{_my_height}+{_x}+{_y}"
# ----- Setting Now -----
self.geometry(geo_string)
self.resizable(width=False, height=False)
diff --git a/calculator.py b/calculator.py
index b12986aa7e6..87e616fe93e 100644
--- a/calculator.py
+++ b/calculator.py
@@ -66,7 +66,7 @@ def calc(term):
for func in functions:
if func in term:
- withmath = "math." + func
+ withmath = f"math.{func}"
term = term.replace(func, withmath)
try:
@@ -114,19 +114,14 @@ def main():
+ "- 12mod3\n\nEnter quit to exit"
)
- if sys.version_info.major >= 3:
- while True:
+ while True:
+ if sys.version_info.major >= 3:
k = input("\nWhat is ")
- if k == "quit":
- break
- result(k)
-
- else:
- while True:
+ else:
k = raw_input("\nWhat is ")
- if k == "quit":
- break
- result(k)
+ if k == "quit":
+ break
+ result(k)
if __name__ == "__main__":
diff --git a/changemac.py b/changemac.py
index b5e86ceae09..c020993c378 100644
--- a/changemac.py
+++ b/changemac.py
@@ -38,8 +38,8 @@ def retrandmac(mac):
infname = infname[:6]
infname = infname.decode("utf-8")
# GETTING MAC Address from /sys/class/net/wlan0/address directory
-cmdgetmac = "cat /sys/class/net/" + infname + "/address"
-crrntmac = cret("cat /sys/class/net/" + infname + "/address")
+cmdgetmac = f"cat /sys/class/net/{infname}/address"
+crrntmac = cret(f"cat /sys/class/net/{infname}/address")
crrntmac = crrntmac.decode("utf-8")
print(
"Your Current mac address = "
@@ -57,13 +57,13 @@ def retrandmac(mac):
# first turn off wifi
cret("nmcli radio wifi off")
- changemaccmd = "sudo ip link set dev " + infname + " address " + newmac
+ changemaccmd = f"sudo ip link set dev {infname} address {newmac}"
# executing command with new mac address
cret(changemaccmd)
# turning on wifi
cret("nmcli radio wifi on")
# GETTING MAC Address from /sys/class/net/wlan0/address directory
- cr = cret("cat /sys/class/net/" + infname + "/address")
+ cr = cret(f"cat /sys/class/net/{infname}/address")
cr = cr.decode("utf-8")
print("\nNow Your Current mac address = " + cr)
@@ -73,12 +73,12 @@ def retrandmac(mac):
genmac = retrandmac(randmac())
print("Please wait generating new mac address.....................")
cret("nmcli radio wifi off")
- changemaccmd = "sudo ip link set dev " + infname + " address " + genmac
+ changemaccmd = f"sudo ip link set dev {infname} address {genmac}"
cret(changemaccmd)
cret("nmcli radio wifi on")
- cr = cret("cat /sys/class/net/" + infname + "/address")
+ cr = cret(f"cat /sys/class/net/{infname}/address")
cr = cr.decode("utf-8")
- print("Now Your Current mac address = " + cr)
+ print(f"Now Your Current mac address = {cr}")
else:
print("You Have Selected wrong Option")
diff --git a/chaos.py b/chaos.py
index 520f3d44512..26ba7c55481 100644
--- a/chaos.py
+++ b/chaos.py
@@ -7,14 +7,14 @@ def main():
while True:
try:
x = float((input("Enter a number between 0 and 1: ")))
- if 0 < x and x < 1:
+ if 0 < x < 1:
break
else:
print("Please enter correct number")
except Exception as e:
print("Please enter correct number")
- for i in range(10):
+ for _ in range(10):
x = 3.9 * x * (1 - x)
print(x)
diff --git a/check_file.py b/check_file.py
index 65da90b2f17..d6138ffadd1 100644
--- a/check_file.py
+++ b/check_file.py
@@ -42,7 +42,7 @@ def main():
# Iterate for each filename passed in command line argument
for filename in filteredfilenames_1:
if not os.path.isfile(filename): # Check the File exists
- print("[-] " + filename + " does not exist.")
+ print(f"[-] {filename} does not exist.")
filteredfilenames_2.remove(
filename
) # remove non existing files from fileNames list
@@ -50,7 +50,7 @@ def main():
# Check you can read the file
if not os.access(filename, os.R_OK):
- print("[-] " + filename + " access denied")
+ print(f"[-] {filename} access denied")
# remove non readable fileNames
filteredfilenames_2.remove(filename)
continue
@@ -58,7 +58,7 @@ def main():
# Read the content of each file that both exists and is readable
for filename in filteredfilenames_2:
# Display Message and read the file contents
- print("[+] Reading from : " + filename)
+ print(f"[+] Reading from : {filename}")
readfile(filename)
else:
diff --git a/check_for_sqlite_files.py b/check_for_sqlite_files.py
index 556d348f8af..7cdbe97f701 100644
--- a/check_for_sqlite_files.py
+++ b/check_for_sqlite_files.py
@@ -18,17 +18,11 @@ def isSQLite3(filename):
if not isfile(filename):
return False
- if getsize(filename) < 100: # SQLite database file header is 100 bytes
+ if getsize(filename) < 100:
return False
- else:
- fd = open(filename, "rb")
+ with open(filename, "rb") as fd:
header = fd.read(100)
- fd.close()
-
- if header[0:16] == "SQLite format 3\000":
- return True
- else:
- return False
+ return header[:16] == "SQLite format 3\000"
log = open("sqlite_audit.txt", "w")
diff --git a/check_internet_con.py b/check_internet_con.py
index d6ab0a615db..66c965b6bf4 100644
--- a/check_internet_con.py
+++ b/check_internet_con.py
@@ -15,8 +15,8 @@ def checkInternetConnectivity():
print(url)
protocols = ["https://", "http://"]
if not any(x for x in protocols if x in url):
- url = "https://" + url
- print("URL:" + url)
+ url = f"https://{url}"
+ print(f"URL:{url}")
except BaseException:
url = "https://google.com"
try:
@@ -24,7 +24,7 @@ def checkInternetConnectivity():
print(f'Connection to "{url}" is working')
except URLError as E:
- print("Connection error:%s" % E.reason)
+ print(f"Connection error:{E.reason}")
checkInternetConnectivity()
diff --git a/check_prime.py b/check_prime.py
index 070ce9e2bff..e3809d2c1d9 100644
--- a/check_prime.py
+++ b/check_prime.py
@@ -12,29 +12,19 @@ def is_prime_a(n):
if n < 2:
return False
sqrt_n = int(sqrt(n))
- for i in range(2, sqrt_n + 1):
- if n % i == 0:
- return False
- return True
+ return all(n % i != 0 for i in range(2, sqrt_n + 1))
def is_prime_b(n):
if n > 1:
- if n == 2:
- return True
- else:
+ if n != 2:
for i in range(2, n):
if n % i == 0:
return False
- return True
+ return True
return False
def is_prime_c(n):
- divisible = 0
- for i in range(1, n + 1):
- if n % i == 0:
- divisible += 1
- if divisible == 2:
- return True
- return False
+ divisible = sum(n % i == 0 for i in range(1, n + 1))
+ return divisible == 2
diff --git a/classicIndianCardMatch.py b/classicIndianCardMatch.py
index 6c859fb8f4d..3d727bb009c 100644
--- a/classicIndianCardMatch.py
+++ b/classicIndianCardMatch.py
@@ -73,7 +73,7 @@ def __str__(self):
print("....decks have been combined and shuffled...\n")
print("------------------------------------------\n")
input("Enter a key to cut the deck..\n")
-player1 = combinedDeck[0:52]
+player1 = combinedDeck[:52]
player2 = combinedDeck[52:]
print(
"Deck has been split into two and Human get a half and computer gets the other...\n"
@@ -93,11 +93,11 @@ def __str__(self):
len(player1) != 0 and len(player2) != 0
): # this needs a fix as it goes on an infinite loop on a success.
switchPlayer = True
- while switchPlayer == True:
+ while switchPlayer:
for card in range(len(player1)):
input("Enter any key to place a card!!!\n")
currentPlayer1Card = player1[card].rank
- print("Your current card's rank: {}".format(currentPlayer1Card))
+ print(f"Your current card's rank: {currentPlayer1Card}")
centerPile.append(player1[card])
player1.pop(card)
switchPlayer = False
@@ -108,12 +108,12 @@ def __str__(self):
)
break
while switchPlayer == False:
+ switchPlayer = True
for card in range(len(player2)):
currentPlayer2Card = player2[card].rank
- print("Computer's current card's rank: {}".format(currentPlayer2Card))
+ print(f"Computer's current card's rank: {currentPlayer2Card}")
centerPile.append(player2[card])
player2.pop(card)
- switchPlayer = True
if currentPlayer1Card == currentPlayer2Card:
player2 = player2 + centerPile
print("Computer got a match and takes all the cards from center pile..")
@@ -121,4 +121,4 @@ def __str__(self):
print("GAME OVER!!!\n")
-print("Human has {} cards and computer has {}..".format(len(player1), len(player2)))
+print(f"Human has {len(player1)} cards and computer has {len(player2)}..")
diff --git a/consonant.py b/consonant.py
index 5138b47d1ca..2a33b65252d 100644
--- a/consonant.py
+++ b/consonant.py
@@ -14,13 +14,7 @@
def count_con(string):
- c = 0
- for i in range(len(string)):
- if (
- string[i] not in string_check
- ): # counter increases if the character is not vowel
- c += 1
- return c
+ return sum(string[i] not in string_check for i in range(len(string)))
counter = count_con(my_string)
diff --git a/conversion.py b/conversion.py
index 022035234f5..432b06ae435 100644
--- a/conversion.py
+++ b/conversion.py
@@ -3,15 +3,8 @@
def convert(s):
- # initialization of string to ""
- new = ""
-
- # traverse in the string
- for x in s:
- new += x
-
- # return string
- return new
+ # return string
+ return "".join(s)
# driver code
diff --git a/convert_time.py b/convert_time.py
index d7ff1c9f697..a9f4cfb7a0c 100644
--- a/convert_time.py
+++ b/convert_time.py
@@ -7,14 +7,11 @@ def convert_time(input_str):
# Checking if last two elements of time
# is AM and first two elements are 12
if input_str[-2:] == "AM" and input_str[:2] == "12":
- return "00" + input_str[2:-2]
+ return f"00{input_str[2:-2]}"
- # remove the AM
elif input_str[-2:] == "AM":
return input_str[:-2]
- # Checking if last two elements of time
- # is PM and first two elements are 12
elif input_str[-2:] == "PM" and input_str[:2] == "12":
return input_str[:-2]
diff --git a/coronacases.py b/coronacases.py
index b06d15ca97f..84f42d2f42a 100644
--- a/coronacases.py
+++ b/coronacases.py
@@ -84,14 +84,13 @@ def choices():
if choice == "1":
world()
sleep(1)
- choices()
elif choice == "2":
indiac()
sleep(1)
- choices()
else:
print("\nYou Have Entered Something Wrong, Please Enter Again")
- choices()
+
+ choices()
choices()
diff --git a/currency converter/main.py b/currency converter/main.py
index a75a047c724..306d4a15cb6 100644
--- a/currency converter/main.py
+++ b/currency converter/main.py
@@ -34,7 +34,7 @@ def getVal(cont1, cont2):
window.dropDown1.addItem("Select")
window.dropDown2.addItem("Select")
-for i in f.readlines():
+for i in f:
window.dropDown1.addItem(i)
window.dropDown2.addItem(i)
intOnly = QDoubleValidator()
diff --git a/daily_checks.py b/daily_checks.py
index 337f8d5aebe..672ce24e203 100644
--- a/daily_checks.py
+++ b/daily_checks.py
@@ -43,7 +43,7 @@ def putty_sessions(conffilename): # Function to load the putty sessions I need
# Open the file server_list.txt, loop through reading each line
# 1.1 -Changed - 1.3 Changed name to use variable conffilename
for server in open(conffilename):
- subprocess.Popen(("putty -load " + server)) # Open the PuTTY sessions - 1.1
+ subprocess.Popen(f"putty -load {server}")
def rdp_sessions():
diff --git a/date-timeclient.py b/date-timeclient.py
index 1e6f4c7b914..bc970b5c6f5 100644
--- a/date-timeclient.py
+++ b/date-timeclient.py
@@ -4,4 +4,4 @@
soc.connect((socket.gethostname(), 2905))
recmsg = soc.recv(1024)
soc.close()
-print("The time got from the server is %s" % recmsg.decode("ascii"))
+print(f'The time got from the server is {recmsg.decode("ascii")}')
diff --git a/date-timeserver.py b/date-timeserver.py
index c0d114c02f4..c316ff237d1 100644
--- a/date-timeserver.py
+++ b/date-timeserver.py
@@ -8,7 +8,7 @@
clientsocket, addr = soc.accept()
- print("estavlishes a connection from %s" % str(addr))
+ print(f"estavlishes a connection from {str(addr)}")
currentTime = time.ctime(time.time()) + "\r\n"
clientsocket.send(currentTime.encode("ascii"))
clientsocket.close()
diff --git a/days_from_date.py b/days_from_date.py
index 3a166679607..a062425afe3 100644
--- a/days_from_date.py
+++ b/days_from_date.py
@@ -29,7 +29,7 @@ def find_day(date):
def printt():
user_input = user_input1.get()
date = process_date(user_input)
- c = "Day on " + user_input + " is " + find_day(date)
+ c = f"Day on {user_input} is {find_day(date)}"
label2 = tk.Label(root, text=c, font=("Times new roman", 20), fg="black").place(
x=20, y=200
)
diff --git a/diceV2_dynamic.py b/diceV2_dynamic.py
index a0dcbcfbc61..44cf4589849 100644
--- a/diceV2_dynamic.py
+++ b/diceV2_dynamic.py
@@ -26,14 +26,13 @@ def roll(self):
# This implementation can be improved greatly of course.
def checkInput(sides):
try:
- if int(sides) != 0:
- if (
- float(sides) % int(sides) == 0
- ): # excludes the possibility of inputted floats being rounded.
- return int(sides)
- else:
+ if int(sides) == 0:
return int(sides)
+ if (
+ float(sides) % int(sides) == 0
+ ): # excludes the possibility of inputted floats being rounded.
+ return int(sides)
except ValueError:
print("Invalid input!")
return None
@@ -46,11 +45,10 @@ def pickNumber(item, question_string, lower_limit):
item = input(question_string)
item = checkInput(item)
if type(item) == int:
- if item <= lower_limit:
- print("Input too low!")
- continue
- else:
+ if item > lower_limit:
return item
+ print("Input too low!")
+ continue
# Main-function of the program that sets up the dices for the user as they want them.
@@ -66,7 +64,7 @@ def getDices():
diceAmount, "How many dices will do you want?: ", diceLowerLimit
)
- for i in range(0, diceAmount):
+ for _ in range(diceAmount):
d = Dice()
d.setSides(sides)
dices.append(d)
diff --git a/diction.py b/diction.py
index 8fc071cb6b8..83ec611eede 100644
--- a/diction.py
+++ b/diction.py
@@ -45,7 +45,7 @@ def translate(word):
speak(d)
elif len(get_close_matches(word, data.keys())) > 0:
x = get_close_matches(word, data.keys())[0]
- speak("Did you mean " + x + " instead, respond with Yes or No.")
+ speak(f"Did you mean {x} instead, respond with Yes or No.")
ans = takeCommand().lower()
if "yes" in ans:
speak("ok " + "It means.." + data[x])
diff --git a/dir_test.py b/dir_test.py
index 992d5924a88..38f468053d0 100644
--- a/dir_test.py
+++ b/dir_test.py
@@ -23,7 +23,7 @@ def main():
if os.path.exists(CheckDir): # Checks if the dir exists
print("The directory exists")
else:
- print("No directory found for " + CheckDir) # Output if no directory
+ print(f"No directory found for {CheckDir}")
print()
option = input("Would you like this directory create? y/n: ")
if option == "n":
@@ -31,7 +31,7 @@ def main():
exit()
if option == "y":
os.makedirs(CheckDir) # Creates a new dir for the given name
- print("Directory created for " + CheckDir)
+ print(f"Directory created for {CheckDir}")
else:
print("Not an option. Exiting")
exit()
diff --git a/divisors_of_a_number.py b/divisors_of_a_number.py
index 326378b177f..06b697ee639 100644
--- a/divisors_of_a_number.py
+++ b/divisors_of_a_number.py
@@ -16,5 +16,5 @@
print('\nthe number ' + number_to_divide + ' can be divided by:')
for item in list_number_divided :
print(f'{item}')
-if len(list_number_divided) <= 2 :
- print(number_to_divide + ' is a prime number')
\ No newline at end of file
+if len(list_number_divided) <= 2:
+ print(f'{number_to_divide} is a prime number')
\ No newline at end of file
diff --git a/email id dictionary/dict1.py b/email id dictionary/dict1.py
index 26c26be8d8d..746c7297bc9 100644
--- a/email id dictionary/dict1.py
+++ b/email id dictionary/dict1.py
@@ -1,7 +1,7 @@
#!/usr/bin/env python
-counts = dict()
-mails = list()
+counts = {}
+mails = []
fname = input("Enter file name:")
fh = open(fname)
for line in fh:
diff --git a/encrypter-decrypter-gui.py b/encrypter-decrypter-gui.py
index ea46ea95bb9..95b17a8c440 100644
--- a/encrypter-decrypter-gui.py
+++ b/encrypter-decrypter-gui.py
@@ -23,7 +23,7 @@ def geometry_settings(self):
# ----- Now Getting X and Y Coordinates
_x = int(_com_scr_w / 2 - _my_w / 2)
_y = int(_com_scr_h / 2 - _my_h / 2)
- _geo_string = str(_my_w) + "x" + str(_my_h) + "+" + str(_x) + "+" + str(_y)
+ _geo_string = f"{_my_w}x{_my_h}+{_x}+{_y}"
self.geometry(_geo_string)
# ----- Geometry Setting Completed Now Disabling Resize Screen Button -----
self.resizable(width=False, height=False)
diff --git a/encryptsys.py b/encryptsys.py
index 45daea14fd6..f8d6f5477ff 100644
--- a/encryptsys.py
+++ b/encryptsys.py
@@ -4,34 +4,18 @@
def decrypt():
texto = input("Input the text to decrypt : ").split(".")
- abecedario = string.printable + "áéíóúÁÉÍÚÓàèìòùÀÈÌÒÙäëïöüÄËÏÖÜñÑ´"
- abecedario2 = []
+ abecedario = f"{string.printable}áéíóúÁÉÍÚÓàèìòùÀÈÌÒÙäëïöüÄËÏÖÜñÑ´"
nummoves = int(texto[0])
- indexs = []
finalindexs = []
textode1 = texto[1]
- textode2 = []
-
- for l in range(0, len(abecedario)):
- abecedario2.append(abecedario[l])
-
- for letter in range(0, len(textode1)):
- textode2.append(textode1[letter])
-
- for index in range(0, len(textode1)):
- indexs.append(abecedario.index(textode1[index]))
-
- for move in range(nummoves, 0):
+ abecedario2 = [abecedario[l] for l in range(len(abecedario))]
+ textode2 = [textode1[letter] for letter in range(len(textode1))]
+ indexs = [abecedario.index(textode1[index]) for index in range(len(textode1))]
+ for _ in range(nummoves, 0):
abecedario2 += abecedario2.pop(27)
- for value in indexs:
- newval = value - nummoves
- finalindexs.append(newval)
-
- textofin = ""
-
- for i in range(0, len(finalindexs)):
- textofin += abecedario2[finalindexs[i]]
+ finalindexs.extend(value - nummoves for value in indexs)
+ textofin = "".join(abecedario2[finalindex] for finalindex in finalindexs)
print(textofin)
@@ -39,37 +23,21 @@ def decrypt():
def encrypt():
texto = input("Input the text to encrypt : ")
- abecedario = string.printable + "áéíóúÁÉÍÚÓàèìòùÀÈÌÒÙäëïöüÄËÏÖÜñÑ´"
- abecedario2 = []
+ abecedario = f"{string.printable}áéíóúÁÉÍÚÓàèìòùÀÈÌÒÙäëïöüÄËÏÖÜñÑ´"
nummoves = randint(1, len(abecedario))
- indexs = []
-
- texttoenc = []
-
- for l in range(0, len(abecedario)):
- abecedario2.append(abecedario[l])
-
- for let in range(0, len(texto)):
- texttoenc.append(texto[let])
-
- for letter in texto:
- indexs.append(abecedario2.index(letter))
-
- for move in range(0, nummoves):
+ abecedario2 = [abecedario[l] for l in range(len(abecedario))]
+ texttoenc = [texto[let] for let in range(len(texto))]
+ indexs = [abecedario2.index(letter) for letter in texto]
+ for _ in range(nummoves):
abecedario2 += abecedario2.pop(0)
texto = []
- for i in range(0, len(indexs)):
- texto.append(abecedario2[indexs[i]])
- texto.append(".")
-
- fintext = ""
-
- for letter2 in range(0, len(texto), 2):
- fintext += texto[letter2]
+ for index in indexs:
+ texto.extend((abecedario2[index], "."))
+ fintext = "".join(texto[letter2] for letter2 in range(0, len(texto), 2))
- fintext = str(nummoves) + "." + fintext
+ fintext = f"{str(nummoves)}.{fintext}"
print("\Encrypted text : " + fintext)
diff --git a/env_check.py b/env_check.py
index 7e7bc53e8cd..4f764694760 100644
--- a/env_check.py
+++ b/env_check.py
@@ -22,7 +22,7 @@
env_check = (
env_check.strip()
) # Set the variable as itself, but strip the extra text out
- print("[{}]".format(env_check)) # Format the Output to be in Square Brackets
+ print(f"[{env_check}]")
newenv = os.getenv(
env_check
) # Set the variable newenv to get the settings from the OS what is currently set for the settings out the configfile
@@ -30,6 +30,4 @@
if newenv is None: # If it doesn't exist
print(env_check, "is not set") # Print it is not set
else: # Else if it does exist
- print(
- "Current Setting for {}={}\n".format(env_check, newenv)
- ) # Print out the details
+ print(f"Current Setting for {env_check}={newenv}\n")
diff --git a/ex20.py b/ex20.py
index 78dc206831d..70def217424 100644
--- a/ex20.py
+++ b/ex20.py
@@ -16,22 +16,19 @@ def print_a_line(line_count, f):
print(line_count, f.readline())
-current_file = open(input_file)
+with open(input_file) as current_file:
+ print("First let's print the whole file:\n")
+ print_all(current_file)
-print("First let's print the whole file:\n")
-print_all(current_file)
+ print("Now let's rewind, kind of like a tape.")
+ rewind(current_file)
-print("Now let's rewind, kind of like a tape.")
-rewind(current_file)
+ print("Let's print three lines:")
+ current_line = 1
+ print_a_line(current_line, current_file)
-print("Let's print three lines:")
-current_line = 1
-print_a_line(current_line, current_file)
+ current_line += 1
+ print_a_line(current_line, current_file)
-current_line = current_line + 1
-print_a_line(current_line, current_file)
-
-current_line = current_line + 1
-print_a_line(current_line, current_file)
-
-current_file.close()
+ current_line += 1
+ print_a_line(current_line, current_file)
diff --git a/facebook id hack.py b/facebook id hack.py
index a7faa2bb225..65c2e4f84c7 100644
--- a/facebook id hack.py
+++ b/facebook id hack.py
@@ -27,7 +27,7 @@
def create_form():
- form = dict()
+ form = {}
cookie = {"fr": "0ZvhC3YwYm63ZZat1..Ba0Ipu.Io.AAA.0.0.Ba0Ipu.AWUPqDLy"}
data = requests.get(post_url, headers=headers)
@@ -67,6 +67,6 @@ def function(email, passw, i):
i += 1
if len(passw) < 6:
continue
- print(str(i) + " : ", passw)
+ print(f"{i} : ", passw)
if function(email, passw, i):
break
diff --git a/facebook-autologin-bot.py b/facebook-autologin-bot.py
index 261f02721d5..a15ccd659d2 100644
--- a/facebook-autologin-bot.py
+++ b/facebook-autologin-bot.py
@@ -38,31 +38,27 @@ def speak(text):
)
speak(text)
continue
- if "facebook" or "fb" in text:
- print("Opening Your Facebook Account")
- text = "Opening Your Facebook Account"
- speak(text)
- # your username and password here
- username = "your username"
- password = "yourpassword"
- # download webdriver of suitable version by link below
- # https://sites.google.com/a/chromium.org/chromedriver/downloads
- # locate your driver
- driver = webdriver.Chrome("C:\\Users\\AJAY\\Desktop\\chromedriver.exe")
- url = "https://www.facebook.com"
- print("Opening facebook...")
- driver.get(url)
- driver.find_element_by_id("email").send_keys(username)
- print("Entering Your Username...")
- time.sleep(1)
- driver.find_element_by_id("pass").send_keys(password)
- print("Entering Your password...")
- driver.find_element_by_name("login").click()
- time.sleep(4)
- print("Login Successful")
- text = "Login Successful Enjoy your day sir"
- speak(text)
- continue
- else:
- print("input valid statement")
- continue
+ print("Opening Your Facebook Account")
+ text = "Opening Your Facebook Account"
+ speak(text)
+ # your username and password here
+ username = "your username"
+ password = "yourpassword"
+ # download webdriver of suitable version by link below
+ # https://sites.google.com/a/chromium.org/chromedriver/downloads
+ # locate your driver
+ driver = webdriver.Chrome("C:\\Users\\AJAY\\Desktop\\chromedriver.exe")
+ url = "https://www.facebook.com"
+ print("Opening facebook...")
+ driver.get(url)
+ driver.find_element_by_id("email").send_keys(username)
+ print("Entering Your Username...")
+ time.sleep(1)
+ driver.find_element_by_id("pass").send_keys(password)
+ print("Entering Your password...")
+ driver.find_element_by_name("login").click()
+ time.sleep(4)
+ print("Login Successful")
+ text = "Login Successful Enjoy your day sir"
+ speak(text)
+ continue
diff --git a/factor.py b/factor.py
index 2e17bec367f..f99e627623d 100644
--- a/factor.py
+++ b/factor.py
@@ -1,8 +1,5 @@
def factorial(n):
- if n == 0:
- return 1
- else:
- return n * factorial(n - 1)
+ return 1 if n == 0 else n * factorial(n - 1)
n = int(input("Input a number to compute the factiorial : "))
diff --git a/factorial_perm_comp.py b/factorial_perm_comp.py
index f329eac3380..fae25a66a1c 100644
--- a/factorial_perm_comp.py
+++ b/factorial_perm_comp.py
@@ -39,7 +39,7 @@ def main():
while True:
try:
n = int(input("\n Enter Value for n "))
- print("Factorial of {} = {}".format(n, factorial(n)))
+ print(f"Factorial of {n} = {factorial(n)}")
break
except ValueError:
print("Invalid Value")
@@ -52,7 +52,7 @@ def main():
try:
n = int(input("\n Enter Value for n "))
r = int(input("\n Enter Value for r "))
- print("Permutation of {}P{} = {}".format(n, r, permutation(n, r)))
+ print(f"Permutation of {n}P{r} = {permutation(n, r)}")
break
except ValueError:
print("Invalid Value")
@@ -65,7 +65,7 @@ def main():
n = int(input("\n Enter Value for n "))
r = int(input("\n Enter Value for r "))
- print("Combination of {}C{} = {}".format(n, r, combination(n, r)))
+ print(f"Combination of {n}C{r} = {combination(n, r)}")
break
except ValueError:
diff --git a/factors.py b/factors.py
index 570534daf1e..a90d1d15231 100644
--- a/factors.py
+++ b/factors.py
@@ -6,5 +6,5 @@
while b <= math.sqrt(a):
if a % b == 0:
print("A factor of the number is ", b)
- print("A factor of the number is ", int(a / b))
+ print("A factor of the number is ", a // b)
b += 1
diff --git a/fibonacci.py b/fibonacci.py
index 15a98a66f03..c984d578a6d 100644
--- a/fibonacci.py
+++ b/fibonacci.py
@@ -41,7 +41,7 @@ def getFibonacciDynamic(n: int, fib: list) -> int:
Calculate the fibonacci number at position n using dynamic programming to improve runtime
"""
- if n == 0 or n == 1:
+ if n in {0, 1}:
return n
if fib[n] != -1:
return fib[n]
diff --git a/fileinfo.py b/fileinfo.py
index bc80dc4bc5a..a7965f99d37 100644
--- a/fileinfo.py
+++ b/fileinfo.py
@@ -26,16 +26,14 @@
try:
with open(file_name) as f:
# Source: https://stackoverflow.com/a/1019572
- count = sum(1 for line in f)
+ count = sum(1 for _ in f)
f.seek(0)
- t_char = sum([len(line) for line in f])
+ t_char = sum(len(line) for line in f)
except FileNotFoundError as e:
print(e)
sys.exit(1)
-# When open item is a directory (python2)
except IOError:
pass
-# When open item is a directory (python3)
except IsADirectoryError:
pass
diff --git a/find_cube_root.py b/find_cube_root.py
index cf315708a25..ad68a4320b0 100644
--- a/find_cube_root.py
+++ b/find_cube_root.py
@@ -6,15 +6,14 @@
def cubeRoot():
x = int(input("Enter an integer: "))
- for ans in range(0, abs(x) + 1):
+ for ans in range(abs(x) + 1):
if ans ** 3 == abs(x):
break
if ans ** 3 != abs(x):
print(x, "is not a perfect cube!")
- else:
- if x < 0:
- ans = -ans
- print("Cube root of " + str(x) + " is " + str(ans))
+ elif x < 0:
+ ans = -ans
+ print(f"Cube root of {x} is {str(ans)}")
cubeRoot()
diff --git a/find_prime.py b/find_prime.py
index d6d5a515bd2..2e297e2fe97 100644
--- a/find_prime.py
+++ b/find_prime.py
@@ -30,9 +30,8 @@
def find_prime(num):
res_list = []
for i in range(2, num + 1):
- if res_list != [] and any(i % l == 0 for l in res_list):
- continue
- res_list.append(i)
+ if not res_list or all(i % l != 0 for l in res_list):
+ res_list.append(i)
return res_list
diff --git a/finding LCM.py b/finding LCM.py
index e95feb45b47..d39727c19e3 100644
--- a/finding LCM.py
+++ b/finding LCM.py
@@ -4,11 +4,7 @@
def compute_lcm(x, y):
# choose the greater number
- if x > y:
- greater = x
- else:
- greater = y
-
+ greater = x if x > y else y
while(True):
if((greater % x == 0) and (greater % y == 0)):
lcm = greater
diff --git a/flappyBird_pygame/flappy_bird.py b/flappyBird_pygame/flappy_bird.py
index 34b3206b7e2..975b0fb258b 100644
--- a/flappyBird_pygame/flappy_bird.py
+++ b/flappyBird_pygame/flappy_bird.py
@@ -234,7 +234,7 @@ def main():
# check for collisions
pipe_collision = any(p.collides_with(bird) for p in pipes)
- if pipe_collision or 0 >= bird.y or bird.y >= W_HEIGHT - Bird.HEIGHT:
+ if pipe_collision or bird.y <= 0 or bird.y >= W_HEIGHT - Bird.HEIGHT:
done = True
for x in (0, W_WIDTH / 2):
diff --git a/floodfill/floodfill.py b/floodfill/floodfill.py
index b4c39735f23..09df1862c50 100644
--- a/floodfill/floodfill.py
+++ b/floodfill/floodfill.py
@@ -29,7 +29,7 @@ def generateClosedPolygons(self):
from random import randint, uniform
from math import pi, sin, cos
- for n in range(0, randint(0, 5)):
+ for _ in range(randint(0, 5)):
x = randint(50, self.window_width - 50)
y = randint(50, self.window_height - 50)
@@ -37,21 +37,19 @@ def generateClosedPolygons(self):
angle += uniform(0, 0.7)
vertices = []
- for i in range(0, randint(3, 7)):
+ for _ in range(randint(3, 7)):
dist = randint(10, 50)
vertices.append(
(int(x + cos(angle) * dist), int(y + sin(angle) * dist))
)
angle += uniform(0, pi / 2)
- for i in range(0, len(vertices) - 1):
+ for i in range(len(vertices) - 1):
pygame.draw.line(
self.surface, (255, 0, 0), vertices[i], vertices[i + 1]
)
- pygame.draw.line(
- self.surface, (255, 0, 0), vertices[len(vertices) - 1], vertices[0]
- )
+ pygame.draw.line(self.surface, (255, 0, 0), vertices[-1], vertices[0])
def run(self):
looping = True
diff --git a/folder_size.py b/folder_size.py
index 7410de8da36..9bd1117b222 100755
--- a/folder_size.py
+++ b/folder_size.py
@@ -35,8 +35,9 @@
) # Add the size of each file in the root dir to get the total size.
fsizeList = [
- str(round(fsizedicr[key] * dir_size, 2)) + " " + key for key in fsizedicr
-] # List of units
+ f"{str(round(fsizedicr[key] * dir_size, 2))} {key}" for key in fsizedicr
+]
+
if dir_size == 0:
print("File Empty") # Sanity check to eliminate corner-case of empty file.
@@ -44,4 +45,4 @@
for units in sorted(fsizeList)[
::-1
]: # Reverse sort list of units so smallest magnitude units print first.
- print("Folder Size: " + units)
+ print(f"Folder Size: {units}")
diff --git a/ftp_send_receive.py b/ftp_send_receive.py
index 691e0e8e899..d03ed1e418e 100644
--- a/ftp_send_receive.py
+++ b/ftp_send_receive.py
@@ -22,7 +22,7 @@
def receive_file(filename="example.txt"):
with open(filename, "wb") as out_file:
- ftp.retrbinary("RETR " + filename, out_file.write, 1024)
+ ftp.retrbinary(f"RETR {filename}", out_file.write, 1024)
ftp.quit()
@@ -34,5 +34,5 @@ def receive_file(filename="example.txt"):
def send_file(filename="example.txt"):
with open(filename, "rb") as in_file:
- ftp.storbinary("STOR " + filename, in_file)
+ ftp.storbinary(f"STOR {filename}", in_file)
ftp.quit()
diff --git a/gambler.py b/gambler.py
index e56d5dd65d1..362cd9c4f7e 100644
--- a/gambler.py
+++ b/gambler.py
@@ -8,7 +8,7 @@
wins = 0
bets = 0
-for i in range(trials):
+for _ in range(trials):
cash = stake
while cash > 0 and cash < goals:
bets += 1
@@ -18,5 +18,5 @@
cash -= 1
if cash == goals:
wins += 1
-print("Your won: " + str(100 * wins // trials) + "$")
-print("Your bets: " + str(bets // trials))
+print(f"Your won: {str(100 * wins // trials)}$")
+print(f"Your bets: {str(bets // trials)}")
diff --git a/game_of_life/game_o_life.py b/game_of_life/game_o_life.py
index 7d2ee832dcf..9709a5ce0f7 100644
--- a/game_of_life/game_o_life.py
+++ b/game_of_life/game_o_life.py
@@ -45,8 +45,7 @@
def create_canvas(size):
- canvas = [[False for i in range(size)] for j in range(size)]
- return canvas
+ return [[False for _ in range(size)] for _ in range(size)]
def seed(canvas):
@@ -98,16 +97,13 @@ def __judge_point(pt, neighbours):
# running the rules of game here.
state = pt
- if pt:
- if alive < 2:
- state = False
- elif alive == 2 or alive == 3:
- state = True
- elif alive > 3:
+ if state:
+ if alive < 2 or alive not in [2, 3] and alive > 3:
state = False
- else:
- if alive == 3:
+ elif alive in [2, 3]:
state = True
+ elif alive == 3:
+ state = True
return state
diff --git a/gcd.py b/gcd.py
index 0f10da082d7..83f27fe0748 100644
--- a/gcd.py
+++ b/gcd.py
@@ -2,6 +2,7 @@
although there is function to find gcd in python but this is the code which
takes two inputs and prints gcd of the two.
"""
+
a = int(input("Enter number 1 (a): "))
b = int(input("Enter number 2 (b): "))
@@ -9,6 +10,6 @@
while i <= a and i <= b:
if a % i == 0 and b % i == 0:
gcd = i
- i = i + 1
+ i += 1
print("\nGCD of {0} and {1} = {2}".format(a, b, gcd))
diff --git a/get_crypto_price.py b/get_crypto_price.py
index a263e4294b8..b1f4959f2b5 100644
--- a/get_crypto_price.py
+++ b/get_crypto_price.py
@@ -14,12 +14,12 @@ def getprice(symbol, exchange_id):
try:
v_price = exchange.fetch_ticker(symbol)
r_price = v_price["info"]["lastPrice"]
- if symbol_1[1] == "USD" or symbol_1[1] == "USDT":
- v_return = "{:.2f} {}".format(float(r_price), symbol_1[1])
- return v_return
- else:
- v_return = "{:.8f} {}".format(float(r_price), symbol_1[1])
- return v_return
+ return (
+ "{:.2f} {}".format(float(r_price), symbol_1[1])
+ if symbol_1[1] in ["USD", "USDT"]
+ else "{:.8f} {}".format(float(r_price), symbol_1[1])
+ )
+
except (ccxt.ExchangeError, ccxt.NetworkError) as error:
# add necessary handling or rethrow the exception
return "Got an error", type(error).__name__, error.args
diff --git a/get_info_remoute_srv.py b/get_info_remoute_srv.py
index eb08c2c9a95..ac91ccbd52b 100644
--- a/get_info_remoute_srv.py
+++ b/get_info_remoute_srv.py
@@ -18,13 +18,14 @@
result = []
for command in COMMANDS:
ssh = subprocess.Popen(
- ["ssh", "%s" % host, command],
+ ["ssh", f"{host}", command],
shell=False,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
+
result.append(ssh.stdout.readlines())
- print("--------------- " + host + " --------------- ")
+ print(f"--------------- {host} --------------- ")
for res in result:
if not res:
print(ssh.stderr.readlines())
diff --git a/get_likes_on_FB.py b/get_likes_on_FB.py
index cb999c76128..8588d76c954 100644
--- a/get_likes_on_FB.py
+++ b/get_likes_on_FB.py
@@ -4,37 +4,24 @@
import sys
import urllib
-accessToken = "TOKENVALUE" # YOUR ACCESS TOKEN GETS INSERTED HERE
userId = sys.argv[1] # USERID
limit = 100
-url = (
- "https://graph.facebook.com/"
- + userId
- + "/posts?access_token="
- + accessToken
- + "&limit="
- + str(limit)
-) # FB Link
+accessToken = "TOKENVALUE"
+url = f"https://graph.facebook.com/{userId}/posts?access_token={accessToken}&limit={limit}"
+
data = json.load(urllib.urlopen(url))
id = 0
-print(str(id))
+print(id)
for item in data["data"]:
time = item["created_time"][11:19]
date = item["created_time"][5:10]
- year = item["created_time"][0:4]
-
-if "shares" in item:
- num_share = item["shares"]["count"]
-else:
- num_share = 0
-if "likes" in item:
- num_like = item["likes"]["count"]
-else:
- num_like = 0
+ year = item["created_time"][:4]
+num_share = item["shares"]["count"] if "shares" in item else 0
+num_like = item["likes"]["count"] if "likes" in item else 0
id += 1
print(
diff --git a/get_youtube_view.py b/get_youtube_view.py
index 77f1b1a29b8..3d557fd16dc 100644
--- a/get_youtube_view.py
+++ b/get_youtube_view.py
@@ -2,6 +2,7 @@
Created on Thu Apr 27 16:28:36 2017
@author: barnabysandeford
"""
+
# Currently works for Safari, but just change to whichever
# browser you're using.
@@ -41,9 +42,9 @@
if url.startswith("https://"):
driver.get(url)
else:
- driver.get("https://" + url)
+ driver.get(f"https://{url}")
-for i in range(count):
+for _ in range(count):
# Sets the page to refresh at the refreshrate.
time.sleep(refreshrate)
driver.refresh()
diff --git a/google.py b/google.py
index 99a14b8c1c7..748fb15ff7b 100755
--- a/google.py
+++ b/google.py
@@ -16,14 +16,8 @@
def main():
- if len(sys.argv) > 1:
- keyword = " ".join(sys.argv[1:])
- else:
- # if no keyword is entered, the script would search for the keyword
- # copied in the clipboard
- keyword = pyperclip.paste()
-
- res = requests.get("http://google.com/search?q=" + keyword)
+ keyword = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else pyperclip.paste()
+ res = requests.get(f"http://google.com/search?q={keyword}")
res.raise_for_status()
soup = bs4.BeautifulSoup(res.text)
linkElems = soup.select(".r a")
diff --git a/googlemaps.py b/googlemaps.py
index afc55094c75..0588c1369f0 100644
--- a/googlemaps.py
+++ b/googlemaps.py
@@ -9,16 +9,11 @@
longi = g.latlng[1]
query = input("Enter the query")
-key = "your_api_key"
-url = (
- "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="
- + str(lat)
- + ","
- + str(longi)
- + "radius=1000"
-)
+url = f"https://maps.googleapis.com/maps/api/place/nearbysearch/json?location={str(lat)},{str(longi)}radius=1000"
+
-r = requests.get(url + "query=" + query + "&key=" + key)
+key = "your_api_key"
+r = requests.get(f"{url}query={query}&key={key}")
x = r.json()
y = x["results"]
diff --git a/googleweb.py b/googleweb.py
index 92fa989bad3..9f68a36ab58 100644
--- a/googleweb.py
+++ b/googleweb.py
@@ -16,8 +16,7 @@ def SearchResults():
for i in f:
singleLink=[]
singleRatio=[]
- singleWrite=[]
- singleWrite.append(i.strip("\n"))
+ singleWrite = [i.strip("\n")]
checkString=i.replace("+","")
searchString=i.replace("+","%2B")
searchString=searchString.replace(" ","+")
@@ -25,11 +24,10 @@ def SearchResults():
r = requests.get(searchString, headers=header)
soup = bs4.BeautifulSoup(r.text, features="html.parser")
elements = soup.select(".r a")
- for g in elements:
- lis.append(g.get("href"))
+ lis.extend(g.get("href") for g in elements)
for k in lis:
sentence=""
- if (k[0] != "#") and k[0] != "/":
+ if k[0] not in ["#", "/"]:
checker = k[8:16]
if (checker != "webcache"):
rr = requests.get(k, headers=header, verify=False)
@@ -41,25 +39,24 @@ def SearchResults():
if(ratio>80):
singleLink.append(k)
singleRatio.append(ratio)
- if(len(singleLink)>=4):
+ if (len(singleLink)>=4):
singleLink=np.array(singleLink)
singleRatio=np.array(singleRatio)
inds=singleRatio.argsort()
sortedLink=singleLink[inds]
sortedFinalList=list(sortedLink[::-1])
sortedFinalList=sortedFinalList[:4]
- FinalResult.append(singleWrite+sortedFinalList)
- elif(len(singleLink)<4) and len(singleLink)>0:
+ elif len(singleLink) > 0:
singleLink = np.array(singleLink)
singleRatio = np.array(singleRatio)
inds = singleRatio.argsort()
sortedLink = singleLink[inds]
sortedFinalList = list(sortedLink[::-1])
- sortedFinalList=sortedFinalList+(4-len(sortedFinalList))*[[" "]]
- FinalResult.append(singleWrite + sortedFinalList)
+ sortedFinalList += (4-len(sortedFinalList))*[[" "]]
else:
sortedFinalList=[[" "]]*4
- FinalResult.append(singleWrite+sortedFinalList)
+
+ FinalResult.append(singleWrite+sortedFinalList)
SearchResults()
diff --git a/happy_num.py b/happy_num.py
index a9740d0703b..cf8879b28e0 100644
--- a/happy_num.py
+++ b/happy_num.py
@@ -11,18 +11,17 @@ def isHappyNumber(num):
num = num//10;
return sum;
-num = 82;
+num = 82;
result = num;
-
-while(result != 1 and result != 4):
+
+while result not in [1, 4]:
result = isHappyNumber(result);
-
-#Happy number always ends with 1
-if(result == 1):
- print(str(num) + " is a happy number after apply way 1");
-#Unhappy number ends in a cycle of repeating numbers which contain 4
-elif(result == 4):
- print(str(num) + " is not a happy number after apply way 1");
+
+#Happy number always ends with 1
+if (result == 1):
+ print(f"{num} is a happy number after apply way 1");
+elif (result == 4):
+ print(f"{num} is not a happy number after apply way 1");
@@ -34,12 +33,12 @@ def isHappyNumber(num):
n=num
setData=set() #set datastructure for checking a number is repeated or not.
while 1:
- if n==1:
- print("{} is a happy number after apply way 2".format(num))
- break
- if n in setData:
- print("{} is Not a happy number after apply way 2".format(num))
- break
- else:
- setData.add(n) #adding into set if not inside set
- n=int(''.join(str(sum([int(i)**2 for i in str(n)])))) #Pythonic way
+ if n==1:
+ print(f"{num} is a happy number after apply way 2")
+ break
+ if n in setData:
+ print(f"{num} is Not a happy number after apply way 2")
+ break
+ else:
+ setData.add(n) #adding into set if not inside set
+ n = int(''.join(str(sum(int(i)**2 for i in str(n)))))
diff --git a/image2pdf/image2pdf.py b/image2pdf/image2pdf.py
index 7527836c7eb..4efc3462619 100644
--- a/image2pdf/image2pdf.py
+++ b/image2pdf/image2pdf.py
@@ -21,11 +21,11 @@ def getPictures(self):
if self.isEmpty(pictures):
print(" [Error] there are no pictrues in the directory ! ")
raise Exception(" [Error] there are no pictrues in the directory !")
- print("pictures are : \n {}".format(pictures))
+ print(f"pictures are : \n {pictures}")
return pictures
def isEmpty(self, items):
- return True if len(items) == 0 else False
+ return len(items) == 0
def convertPictures(self):
for picture in self.getPictures():
diff --git a/input matrice,product any order!.py b/input matrice,product any order!.py
index d0e3223e4c4..7967b749d59 100644
--- a/input matrice,product any order!.py
+++ b/input matrice,product any order!.py
@@ -7,8 +7,8 @@
matrice = []
rowan = []
-for i in range(0, rows):
- for j in range(0, coloumns):
+for _ in range(rows):
+ for _ in range(coloumns):
element = int(input("enter the element"))
rowan.append(element)
print("one row completed")
@@ -27,8 +27,8 @@
rowan = []
matrix = []
-for i in range(0, rows_):
- for j in range(0, coloumns_):
+for _ in range(rows_):
+ for _ in range(coloumns_):
element = int(input("enter the element"))
rowan.append(element)
print("one row completed")
@@ -44,8 +44,8 @@
# creating empty frame:
result = []
-for i in range(0, rows):
- for j in range(0, coloumns_):
+for _ in range(rows):
+ for _ in range(coloumns_):
rowan.append(0)
result.append(rowan)
rowan = []
diff --git a/insertion_sort.py b/insertion_sort.py
index 8ea77cb9552..0489cd2b6a9 100644
--- a/insertion_sort.py
+++ b/insertion_sort.py
@@ -7,7 +7,7 @@ def input_list():
# taking length and then values of list as input from user
n = int(input("Enter number of elements in the list: ")) # taking value from user
for i in range(n):
- temp = int(input("Enter element " + str(i + 1) + ": "))
+ temp = int(input(f"Enter element {str(i + 1)}: "))
list.append(temp)
@@ -22,7 +22,7 @@ def insertion_sort(list, n):
OUTPUT:
list of sorted values in assending order
"""
- for i in range(0, n):
+ for i in range(n):
key = list[i]
j = i - 1
# Swap elements witth key iff they are
@@ -45,7 +45,7 @@ def insertion_sort_desc(list, n):
OUTPUT:
list of sorted values in desending order
"""
- for i in range(0, n):
+ for i in range(n):
key = list[i]
j = i - 1
# Swap elements witth key iff they are
diff --git a/insta_monitering/insta_api.py b/insta_monitering/insta_api.py
index 957f240730d..5645bf4637a 100644
--- a/insta_monitering/insta_api.py
+++ b/insta_monitering/insta_api.py
@@ -37,11 +37,7 @@ def get(self):
if " " in q:
q = q.replace(" ", "")
self.background_task(user=user, tags=q, type=type, productId=productId)
- temp = {}
- temp["query"] = q
- temp["userId"] = user
- temp["status"] = True
- temp["productId"] = productId
+ temp = {"query": q, "userId": user, "status": True, "productId": productId}
print(
"{0}, {1}, {2}, {3}".format(
temp["userId"], temp["productId"], temp["query"], temp["status"]
@@ -61,11 +57,7 @@ def get(self):
self.send_error(400)
obj = InstaPorcessClass()
result = obj.deletProcess(tags=q, user=user, productId=productId)
- temp = {}
- temp["query"] = q
- temp["userId"] = user
- temp["productId"] = productId
- temp["status"] = result
+ temp = {"query": q, "userId": user, "productId": productId, "status": result}
print(
"{0}, {1}, {2}, {3}".format(
temp["userId"], temp["productId"], temp["query"], temp["status"]
@@ -85,11 +77,7 @@ def get(self):
self.send_error(400)
obj = InstaPorcessClass()
result = obj.statusCheck(tags=q, user=user, productId=productId)
- temp = {}
- temp["query"] = q
- temp["userId"] = user
- temp["status"] = result
- temp["productId"] = productId
+ temp = {"query": q, "userId": user, "status": result, "productId": productId}
print(
"{0}, {1}, {2}, {3}".format(
temp["userId"], temp["productId"], temp["query"], temp["status"]
diff --git a/insta_monitering/insta_datafetcher.py b/insta_monitering/insta_datafetcher.py
index 8c5ed78b902..a1a7b0bd9d0 100644
--- a/insta_monitering/insta_datafetcher.py
+++ b/insta_monitering/insta_datafetcher.py
@@ -26,7 +26,7 @@
class PorxyApplyingDecorator(object):
def __init__(self):
- filename = os.getcwd() + "/" + "ipList.txt"
+ filename = f"{os.getcwd()}/ipList.txt"
with open(filename, "r") as f:
ipdata = f.read()
self._IP = random.choice(ipdata.split(","))
@@ -71,7 +71,6 @@ async def dataprocess(htmldata):
maindict[i] = datadict[i]
except Exception as e:
print(e)
- pass
return maindict
@@ -107,12 +106,12 @@ def __init__(self, user, tags, type, productId):
try:
self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort)
- db = self.mon[productId + ":" + user + ":insta"]
+ db = self.mon[f"{productId}:{user}:insta"]
self._collection = db[tags]
if type == "hashtags":
- self._url = "https://www.instagram.com/explore/tags/" + tags + "/?__a=1"
- if type == "profile":
- self._url = "https://www.instagram.com/" + tags + "/?__a=1"
+ self._url = f"https://www.instagram.com/explore/tags/{tags}/?__a=1"
+ elif type == "profile":
+ self._url = f"https://www.instagram.com/{tags}/?__a=1"
except Exception as err:
print(f"exception {err}")
print("error::MointeringClass.__init__>>", sys.exc_info()[1])
@@ -129,9 +128,11 @@ def _dataProcessing(self, data):
print("top_post::", len(top_post))
futures = []
for i in media_post:
- tempdict = {}
- tempdict["url"] = "https://www.instagram.com/p/" + i["code"] + "/"
- tempdict["code"] = i["code"]
+ tempdict = {
+ "url": "https://www.instagram.com/p/" + i["code"] + "/",
+ "code": i["code"],
+ }
+
userdata.append(tempdict)
for i in top_post:
tempdict = {}
@@ -175,10 +176,9 @@ def _lastProcess(self, userdata, media_post, top_post):
tofind = ["owner", "location"]
for z in tofind:
try:
- tempdict[z + "data"] = i["data"][z]
+ tempdict[f"{z}data"] = i["data"][z]
except Exception as e:
print(f"exception : {e}")
- pass
mainlist.append(tempdict)
self._insertFunction(tempdict.copy())
for k in top_post:
@@ -187,10 +187,9 @@ def _lastProcess(self, userdata, media_post, top_post):
tofind = ["owner", "location"]
for z in tofind:
try:
- tempdict[z + "data"] = i["data"][z]
+ tempdict[f"{z}data"] = i["data"][z]
except Exception as err:
print(f"Exception :{err}")
- pass
mainlist.append(tempdict)
self._insertFunction(tempdict.copy())
except Exception as err:
@@ -272,10 +271,7 @@ def _dbProcessReader(self, user, tags, productId):
try:
db = mon["insta_process"]
collection = db["process"]
- temp = {}
- temp["user"] = user
- temp["tags"] = tags
- temp["productId"] = productId
+ temp = {"user": user, "tags": tags, "productId": productId}
records = collection.find(temp).count()
if records == 0:
raise Exception
@@ -293,10 +289,7 @@ def _processstart(self, user, tags, productId):
try:
db = mon["insta_process"]
collection = db["process"]
- temp = {}
- temp["user"] = user
- temp["tags"] = tags
- temp["productId"] = productId
+ temp = {"user": user, "tags": tags, "productId": productId}
collection.insert(temp)
except Exception as err:
print(f"execption : {err}\n")
@@ -326,10 +319,7 @@ def deletProcess(self, user, tags, productId):
try:
db = mon["insta_process"]
collection = db["process"]
- temp = {}
- temp["user"] = user
- temp["tags"] = tags
- temp["productId"] = productId
+ temp = {"user": user, "tags": tags, "productId": productId}
collection.delete_one(temp)
except Exception as err:
print(f"exception : {err}\n")
@@ -344,15 +334,9 @@ def statusCheck(self, user, tags, productId):
try:
db = mon["insta_process"]
collection = db["process"]
- temp = {}
- temp["user"] = user
- temp["tags"] = tags
- temp["productId"] = productId
+ temp = {"user": user, "tags": tags, "productId": productId}
records = collection.find(temp).count()
- if records == 0:
- result = False
- else:
- result = True
+ result = records != 0
except Exception as err:
print(f"exception : {err}\n")
print("error::dbProcessReader:>>", sys.exc_info()[1])
@@ -365,7 +349,7 @@ class DBDataFetcher:
def __init__(self, user, tags, type, productId):
try:
self.mon = pymongo.MongoClient(host=config.host, port=config.mongoPort)
- db = self.mon[productId + ":" + user + ":insta"]
+ db = self.mon[f"{productId}:{user}:insta"]
self._collection = db[tags]
except Exception as err:
print(f"exception : {err}\n")
diff --git a/insta_monitering/subpinsta.py b/insta_monitering/subpinsta.py
index 6e234063c75..a86cd8f2760 100644
--- a/insta_monitering/subpinsta.py
+++ b/insta_monitering/subpinsta.py
@@ -18,7 +18,7 @@ def instasubprocess(user, tags, type, productId):
+ " "
+ productId
)
- command = child_env + " " + file_pocessing
+ command = f"{child_env} {file_pocessing}"
result = subprocess.Popen(command, shell=True)
result.wait()
except:
diff --git a/internet_connection_py3.py b/internet_connection_py3.py
index 46ec09fdba9..c3ddeeb9e3c 100644
--- a/internet_connection_py3.py
+++ b/internet_connection_py3.py
@@ -26,5 +26,5 @@
browser = webdriver.Firefox()
browser.get(search)
os.system("cls") # os.system('clear') if Linux
-print("[+] Website " + search + " opened!")
+print(f"[+] Website {search} opened!")
browser.close()
diff --git a/invisible_clock.py b/invisible_clock.py
index 17f6d97b106..aaddd2b105f 100644
--- a/invisible_clock.py
+++ b/invisible_clock.py
@@ -14,7 +14,7 @@
background = 0
# capturing the background
-for i in range(30): # 30 times
+for _ in range(30):
ret, background = cap.read()
while cap.isOpened():
diff --git a/jee_result.py b/jee_result.py
index 7aa6046a50b..87f5b0ee25e 100644
--- a/jee_result.py
+++ b/jee_result.py
@@ -26,7 +26,7 @@
ct = 0
# print currentdate
yyyymmdd = currentdate.strftime("%Y/%m/%d")
- ddmmyyyy = yyyymmdd[8:] + "/" + yyyymmdd[5:7] + "/" + yyyymmdd[:4]
+ ddmmyyyy = f"{yyyymmdd[8:]}/{yyyymmdd[5:7]}/{yyyymmdd[:4]}"
print(ddmmyyyy)
b.open("http://cbseresults.nic.in/jee/jee_2015.htm")
b.select_form(nr=0)
@@ -37,7 +37,7 @@
# print(fd.read())
soup = BeautifulSoup(fd.read(), "html.parser")
- for writ in soup.find_all("table"):
+ for _ in soup.find_all("table"):
ct = ct + 1
# print (ct)
if ct == 6:
diff --git a/kmp_str_search.py b/kmp_str_search.py
index cae439949b9..e7ec0b8aa82 100644
--- a/kmp_str_search.py
+++ b/kmp_str_search.py
@@ -13,7 +13,7 @@ def kmp(pattern, text, len_p=None, len_t=None):
# 1) Construct the failure array
failure = [0]
i = 0
- for index, char in enumerate(pattern[1:]):
+ for char in pattern[1:]:
if pattern[i] == char:
i += 1
else:
diff --git a/lcm.py b/lcm.py
index c2d5b9731cc..da4ddbdce7a 100644
--- a/lcm.py
+++ b/lcm.py
@@ -29,11 +29,7 @@ def lcm(x, y):
if x <= 0 or y <= 0:
return -1
- if x > y:
- greater_number = x
- else:
- greater_number = y
-
+ greater_number = x if x > y else y
while True:
if (greater_number % x == 0) and (greater_number % y == 0):
lcm = greater_number
diff --git a/length.py b/length.py
index 257c62a4be7..d1deda4c1e8 100644
--- a/length.py
+++ b/length.py
@@ -3,6 +3,6 @@
# counter variable to count the character in a string
counter = 0
-for s in str:
+for _ in str:
counter = counter + 1
print("Length of the input string is:", counter)
diff --git a/levenshtein_distance.py b/levenshtein_distance.py
index 1dde234f490..3d8a54db25b 100644
--- a/levenshtein_distance.py
+++ b/levenshtein_distance.py
@@ -8,9 +8,6 @@ def levenshtein_dis(wordA, wordB):
length_B = len(wordB)
max_len = 0
diff = 0
- distances = []
- distance = 0
-
# check the difference of the word to decide how many letter should be delete or add
# also store that value in the 'diff' variable and get the max length of the user given words
if length_A > length_B:
@@ -23,26 +20,19 @@ def levenshtein_dis(wordA, wordB):
diff = 0
max_len = length_A
- # starting from the front of the words and compare the letters of the both user given words
- for x in range(max_len - diff):
- if wordA[x] != wordB[x]:
- distance += 1
-
- # add the 'distance' value to the 'distances' array
- distances.append(distance)
- distance = 0
+ distance = sum(wordA[x] != wordB[x] for x in range(max_len - diff))
+ distances = [distance]
+ distance = sum(
+ wordA[-(x + 1)] != wordB[-(x + 1)] for x in range(max_len - diff)
+ )
- # starting from the back of the words and compare the letters of the both user given words
- for x in range(max_len - diff):
- if wordA[-(x + 1)] != wordB[-(x + 1)]:
- distance += 1
# add the 'distance' value to the 'distances' array
distances.append(distance)
# get the minimun value of the 'distances' array and add it with the 'diff' values and
# store them in the 'diff' variable
- diff = diff + min(distances)
+ diff += min(distances)
# return the value
return diff
diff --git a/linear-algebra-python/src/lib.py b/linear-algebra-python/src/lib.py
index 9719d915bd2..d710502c1c7 100644
--- a/linear-algebra-python/src/lib.py
+++ b/linear-algebra-python/src/lib.py
@@ -71,9 +71,9 @@ def __str__(self):
length = len(self.__components)
for i in range(length):
if i != length - 1:
- ans += str(self.__components[i]) + ","
+ ans += f"{str(self.__components[i])},"
else:
- ans += str(self.__components[i]) + ")"
+ ans += f"{str(self.__components[i])})"
if len(ans) == 1:
ans += ")"
return ans
@@ -98,9 +98,7 @@ def eulidLength(self):
"""
returns the eulidean length of the vector
"""
- summe = 0
- for c in self.__components:
- summe += c ** 2
+ summe = sum(c ** 2 for c in self.__components)
return math.sqrt(summe)
def __add__(self, other):
@@ -110,12 +108,9 @@ def __add__(self, other):
returns a new vector that represents the sum.
"""
size = self.size()
- result = []
- if size == other.size():
- for i in range(size):
- result.append(self.__components[i] + other.component(i))
- else:
+ if size != other.size():
raise Exception("must have the same size")
+ result = [self.__components[i] + other.component(i) for i in range(size)]
return Vector(result)
def __sub__(self, other):
@@ -125,12 +120,9 @@ def __sub__(self, other):
returns a new vector that represents the differenz.
"""
size = self.size()
- result = []
- if size == other.size():
- for i in range(size):
- result.append(self.__components[i] - other.component(i))
- else: # error case
+ if size != other.size():
raise Exception("must have the same size")
+ result = [self.__components[i] - other.component(i) for i in range(size)]
return Vector(result)
def __mul__(self, other):
@@ -139,15 +131,11 @@ def __mul__(self, other):
and the dot-product
"""
ans = []
- if isinstance(other, float) or isinstance(other, int):
- for c in self.__components:
- ans.append(c * other)
+ if isinstance(other, (float, int)):
+ ans.extend(c * other for c in self.__components)
elif isinstance(other, Vector) and (self.size() == other.size()):
size = self.size()
- summe = 0
- for i in range(size):
- summe += self.__components[i] * other.component(i)
- return summe
+ return sum(self.__components[i] * other.component(i) for i in range(size))
else: # error case
raise Exception("invalide operand!")
return Vector(ans)
@@ -156,7 +144,7 @@ def copy(self):
"""
copies this vector and returns it.
"""
- components = [x for x in self.__components]
+ components = list(self.__components)
return Vector(components)
def changeComponent(self, pos, value):
@@ -201,9 +189,7 @@ def zeroVector(dimension):
"""
# precondition
assert isinstance(dimension, int)
- ans = []
- for i in range(dimension):
- ans.append(0)
+ ans = [0 for _ in range(dimension)]
return Vector(ans)
@@ -233,8 +219,9 @@ def axpy(scalar, x, y):
assert (
isinstance(x, Vector)
and (isinstance(y, Vector))
- and (isinstance(scalar, int) or isinstance(scalar, float))
+ and (isinstance(scalar, (int, float)))
)
+
return x * scalar + y
@@ -289,7 +276,7 @@ def __str__(self):
ans += "|"
for j in range(self.__width):
if j < self.__width - 1:
- ans += str(self.__matrix[i][j]) + ","
+ ans += f"{str(self.__matrix[i][j])},"
else:
ans += str(self.__matrix[i][j]) + "|\n"
return ans
@@ -330,26 +317,25 @@ def __mul__(self, other):
implements the matrix-scalar multiplication
"""
if isinstance(other, Vector): # vector-matrix
- if other.size() == self.__width:
- ans = zeroVector(self.__height)
- for i in range(self.__height):
- summe = 0
- for j in range(self.__width):
- summe += other.component(j) * self.__matrix[i][j]
- ans.changeComponent(i, summe)
- summe = 0
- return ans
- else:
+ if other.size() != self.__width:
raise Exception(
"vector must have the same size as the "
+ "number of columns of the matrix!"
)
- elif isinstance(other, int) or isinstance(other, float): # matrix-scalar
+ ans = zeroVector(self.__height)
+ for i in range(self.__height):
+ summe = sum(
+ other.component(j) * self.__matrix[i][j]
+ for j in range(self.__width)
+ )
+
+ ans.changeComponent(i, summe)
+ summe = 0
+ return ans
+ elif isinstance(other, (int, float)): # matrix-scalar
matrix = []
for i in range(self.__height):
- row = []
- for j in range(self.__width):
- row.append(self.__matrix[i][j] * other)
+ row = [self.__matrix[i][j] * other for j in range(self.__width)]
matrix.append(row)
return Matrix(matrix, self.__width, self.__height)
@@ -357,31 +343,33 @@ def __add__(self, other):
"""
implements the matrix-addition.
"""
- if self.__width == other.width() and self.__height == other.height():
- matrix = []
- for i in range(self.__height):
- row = []
- for j in range(self.__width):
- row.append(self.__matrix[i][j] + other.component(i, j))
- matrix.append(row)
- return Matrix(matrix, self.__width, self.__height)
- else:
+ if self.__width != other.width() or self.__height != other.height():
raise Exception("matrix must have the same dimension!")
+ matrix = []
+ for i in range(self.__height):
+ row = [
+ self.__matrix[i][j] + other.component(i, j)
+ for j in range(self.__width)
+ ]
+
+ matrix.append(row)
+ return Matrix(matrix, self.__width, self.__height)
def __sub__(self, other):
"""
implements the matrix-subtraction.
"""
- if self.__width == other.width() and self.__height == other.height():
- matrix = []
- for i in range(self.__height):
- row = []
- for j in range(self.__width):
- row.append(self.__matrix[i][j] - other.component(i, j))
- matrix.append(row)
- return Matrix(matrix, self.__width, self.__height)
- else:
+ if self.__width != other.width() or self.__height != other.height():
raise Exception("matrix must have the same dimension!")
+ matrix = []
+ for i in range(self.__height):
+ row = [
+ self.__matrix[i][j] - other.component(i, j)
+ for j in range(self.__width)
+ ]
+
+ matrix.append(row)
+ return Matrix(matrix, self.__width, self.__height)
def __eq__(self, other):
"""
@@ -404,10 +392,8 @@ def squareZeroMatrix(N):
returns a square zero-matrix of dimension NxN
"""
ans = []
- for i in range(N):
- row = []
- for j in range(N):
- row.append(0)
+ for _ in range(N):
+ row = [0 for _ in range(N)]
ans.append(row)
return Matrix(ans, N, N)
@@ -419,9 +405,7 @@ def randomMatrix(W, H, a, b):
"""
matrix = []
random.seed(None)
- for i in range(H):
- row = []
- for j in range(W):
- row.append(random.randint(a, b))
+ for _ in range(H):
+ row = [random.randint(a, b) for _ in range(W)]
matrix.append(row)
return Matrix(matrix, W, H)
diff --git a/linear_search.py b/linear_search.py
index d8776a12c09..ee4e11042a2 100644
--- a/linear_search.py
+++ b/linear_search.py
@@ -1,6 +1,6 @@
list = []
num = int(input("Enter size of list: \t"))
-for n in range(num):
+for _ in range(num):
numbers = int(input("Enter any number: \t"))
list.append(numbers)
diff --git a/loader.py b/loader.py
index 7ce80fef603..fe9a4784e3e 100644
--- a/loader.py
+++ b/loader.py
@@ -18,7 +18,7 @@ def animate(message="loading", endmessage="Done!"):
for c in itertools.cycle(["|", "/", "-", "\\"]):
if done:
break
- sys.stdout.write(f"\r {message}" + c)
+ sys.stdout.write(f"\r {message}{c}")
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write(f"\r {endmessage} ")
diff --git a/local_weighted_learning/local_weighted_learning.py b/local_weighted_learning/local_weighted_learning.py
index a3a911c4306..f91b4ba7057 100644
--- a/local_weighted_learning/local_weighted_learning.py
+++ b/local_weighted_learning/local_weighted_learning.py
@@ -32,10 +32,9 @@ def local_weight(
Return the weighted matrix.
"""
weight = weighted_matrix(point, training_data_x, bandwidth)
- W = (training_data.T * (weight * training_data)).I * (
+ return (training_data.T * (weight * training_data)).I * (
training_data.T * weight * training_data_y.T
)
- return W
def local_weight_regression(
@@ -81,8 +80,7 @@ def get_preds(training_data: np.mat, mcol_b: np.mat, tau: float) -> np.ndarray:
"""
Get predictions with minimum error for each training data
"""
- ypred = local_weight_regression(training_data, mcol_b, tau)
- return ypred
+ return local_weight_regression(training_data, mcol_b, tau)
def plot_preds(
diff --git a/logs.py b/logs.py
index 37519f55011..51fcb5efd4e 100644
--- a/logs.py
+++ b/logs.py
@@ -17,11 +17,7 @@
for files in os.listdir(logsdir): # Find all the files in the directory
if files.endswith(".log"): # Check to ensure the files in the directory end in .log
- files1 = (
- files + "." + strftime("%Y-%m-%d") + ".zip"
- ) # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension
+ files1 = f"{files}." + strftime("%Y-%m-%d") + ".zip"
os.chdir(logsdir) # Change directory to the logsdir
- os.system(
- zip_program + " " + files1 + " " + files
- ) # Zip the logs into dated zip files for each server. - 1.1
+ os.system(f"{zip_program} {files1} {files}")
os.remove(files) # Remove the original log files
diff --git a/magic8ball.py b/magic8ball.py
index 1ce9dc39a69..b117ae269a2 100644
--- a/magic8ball.py
+++ b/magic8ball.py
@@ -24,7 +24,7 @@
]
print("Hi! I am the magic 8 ball, what's your name?")
name = input()
-print("Hello!" + name)
+print(f"Hello!{name}")
def magic8Ball():
diff --git a/mapit.py b/mapit.py
index 53d0cd61014..7170870d840 100644
--- a/mapit.py
+++ b/mapit.py
@@ -7,4 +7,4 @@
address = pyperclip.paste()
else:
address = input("enter your palce")
-webbrowser.open("https://www.google.com/maps/place/" + address)
+webbrowser.open(f"https://www.google.com/maps/place/{address}")
diff --git a/meme_maker.py b/meme_maker.py
index 7cb4b550701..0c90db92f6f 100644
--- a/meme_maker.py
+++ b/meme_maker.py
@@ -11,12 +11,11 @@ def input_par():
print("Enter the color for the text(r, g, b): ")
color_value = [int(i) for i in input().split(" ")]
return text, size, color_value
- pass
def main():
path_to_image = sys.argv[1]
- image_file = Image.open(path_to_image + ".jpg")
+ image_file = Image.open(f"{path_to_image}.jpg")
image_file = image_file.convert("RGBA")
pixdata = image_file.load()
@@ -47,8 +46,7 @@ def main():
print("Enter the file name: ")
file_name = str(input())
- image_file.save(file_name + ".jpg")
- pass
+ image_file.save(f"{file_name}.jpg")
if __name__ == "__main__":
diff --git a/memorygame.py b/memorygame.py
index 9266a2cd54e..8223f3d6305 100644
--- a/memorygame.py
+++ b/memorygame.py
@@ -15,7 +15,7 @@ def square(x, y):
down()
color("black", "white")
begin_fill()
- for count in range(4):
+ for _ in range(4):
forward(50)
left(90)
end_fill()
diff --git a/merge.py b/merge.py
index 424cf1e0527..8e04f04a687 100644
--- a/merge.py
+++ b/merge.py
@@ -28,11 +28,11 @@ def merge():
with open(resultfile, "w") as writefile:
for csvfile in csvfiles:
with open(csvfile) as readfile:
- print("File {} readed.".format(csvfile))
+ print(f"File {csvfile} readed.")
# do the read and write
writefile.write(readfile.read() + "\n")
- print("\nFile {} wrote.".format(resultfile))
+ print(f"\nFile {resultfile} wrote.")
# the main program
diff --git a/mobilePhoneSpecsScrapper.py b/mobilePhoneSpecsScrapper.py
index 1578942f8dc..53d593cc1a9 100644
--- a/mobilePhoneSpecsScrapper.py
+++ b/mobilePhoneSpecsScrapper.py
@@ -18,7 +18,7 @@ def __init__(self):
# Folder name on which files going to save.
self.new_folder_name = "GSMArenaDataset"
# It create the absolute path of the GSMArenaDataset folder.
- self.absolute_path = os.getcwd().strip() + "/" + self.new_folder_name
+ self.absolute_path = f"{os.getcwd().strip()}/{self.new_folder_name}"
def crawl_html_page(self, sub_url):
@@ -27,9 +27,7 @@ def crawl_html_page(self, sub_url):
# Handing the connection error of the url.
try:
page = requests.get(url)
- # It parses the html data from requested url.
- soup = BeautifulSoup(page.text, "html.parser")
- return soup
+ return BeautifulSoup(page.text, "html.parser")
except ConnectionError as err:
print("Please check your network connection and re-run the script.")
@@ -42,13 +40,11 @@ def crawl_html_page(self, sub_url):
def crawl_phone_urls(self):
phones_urls = []
for i in range(1, 238): # Right now they have 237 page of phone data.
- print(self.url + "page/" + str(i))
- soup = self.crawl_html_page(self.url + "page/" + str(i))
+ print(f"{self.url}page/{str(i)}")
+ soup = self.crawl_html_page(f"{self.url}page/{str(i)}")
table = soup.findAll("div", {"class": "stream-item"})
table_a = [k.find("a") for k in table]
- for a in table_a:
- temp = a["href"]
- phones_urls.append(temp)
+ phones_urls.extend(a["href"] for a in table_a)
return phones_urls
def crawl_phones_models_specification(self, li):
@@ -88,7 +84,7 @@ def crawl_phones_models_specification(self, li):
"battery": battery,
"os": os,
}
- with open(obj.absolute_path + "-PhoneSpecs.json", "w+") as of:
+ with open(f"{obj.absolute_path}-PhoneSpecs.json", "w+") as of:
json.dump(phone_data, of)
except Exception as error:
print(f"Exception happened : {error}")
@@ -101,7 +97,7 @@ def crawl_phones_models_specification(self, li):
try:
# Step 1: Scrape links to all the individual phone specs page and save it so that we don't need to run it again.
phone_urls = obj.crawl_phone_urls()
- with open(obj.absolute_path + "-Phoneurls.json", "w") as of:
+ with open(f"{obj.absolute_path}-Phoneurls.json", "w") as of:
json.dump(phone_urls, of)
# Step 2: Iterate through all the links from the above execution and run the next command
diff --git a/move_files_over_x_days.py b/move_files_over_x_days.py
index 50b13762024..1abe50c902b 100644
--- a/move_files_over_x_days.py
+++ b/move_files_over_x_days.py
@@ -41,9 +41,7 @@
)
args = args_parser.parse_args()
-if args.days < 0:
- args.days = 0
-
+args.days = max(args.days, 0)
src = args.src # Set the source directory
dst = args.dst # Set the destination directory
days = args.days # Set the number of days
@@ -53,8 +51,5 @@
os.mkdir(dst)
for f in os.listdir(src): # Loop through all the files in the source directory
- if (
- os.stat(f).st_mtime < now - days * 86400
- ): # Work out how old they are, if they are older than 240 days old
- if os.path.isfile(f): # Check it's a file
- shutil.move(f, dst) # Move the files
+ if (os.stat(f).st_mtime < now - days * 86400) and os.path.isfile(f):
+ shutil.move(f, dst) # Move the files
diff --git a/nasa_apod_with_requests/run.py b/nasa_apod_with_requests/run.py
index 4d8048d022c..d100009554b 100644
--- a/nasa_apod_with_requests/run.py
+++ b/nasa_apod_with_requests/run.py
@@ -14,11 +14,11 @@
print(img_.headers["content-type"], img_.headers["content-length"])
content_type = img_.headers["content-type"]
-if img_.status_code == 200 and (
- content_type == "image/jpeg"
- or content_type == "image/gif"
- or content_type == "image/png"
-):
+if img_.status_code == 200 and content_type in [
+ "image/jpeg",
+ "image/gif",
+ "image/png",
+]:
ext = img_.headers["content-type"][6:]
if not os.path.exists("img/"):
os.mkdir("img/")
diff --git a/new.py b/new.py
index 9df00e5faaa..07f085bf594 100644
--- a/new.py
+++ b/new.py
@@ -37,7 +37,7 @@ def Times_of_India(userInput, ua):
bol = input("For more details ->(y) (y/n) :: ")
if bol == "y":
url += data1.get("href")
- print("%s" % url)
+ print(f"{url}")
webbrowser.open(url)
@@ -65,7 +65,7 @@ def india_today(userInput, ua):
k += 1
print(bold_start, data1[j].get_text(), bold_end)
bol = input("\nFor more details ->(y) (y/n) :: ")
- if bol == "y" or bol == "Y":
+ if bol in ["y", "Y"]:
data2 = data[i].find("a")
url = data2.get("href")
webbrowser.open(url)
@@ -126,12 +126,5 @@ def india_today(userInput, ua):
else:
print("\nThank you", "\U0001f600")
- elif say == 2:
- length = india_today(userInput, ua)
-
- if length == 0:
- print("Sorry No news")
- else:
- print("\nThank you", "\U0001f600")
else:
print("Sorry", "\N{expressionless face}")
diff --git a/new_pattern.py b/new_pattern.py
index e9ebc1c257c..7c90642a792 100644
--- a/new_pattern.py
+++ b/new_pattern.py
@@ -17,7 +17,7 @@ def pattern(lines):
for i in reversed(range(lines)):
nxt_pattern = "$"*t
pattern = "@"*(i+1)
- final_pattern = pattern + " n " + nxt_pattern
+ final_pattern = f"{pattern} n {nxt_pattern}"
print(final_pattern)
t = t +1
diff --git a/new_script.py b/new_script.py
index 7326bed8c4e..0e83d50eaf9 100644
--- a/new_script.py
+++ b/new_script.py
@@ -25,22 +25,21 @@
if "-h" in sys.argv or "--h" in sys.argv or "-help" in sys.argv or "--help" in sys.argv:
print(text)
sys.exit()
+elif "-python" in sys.argv[1]:
+ config_file = "python.cfg"
+ extension = ".py"
+elif "-bash" in sys.argv[1]:
+ config_file = "bash.cfg"
+ extension = ".bash"
+elif "-ksh" in sys.argv[1]:
+ config_file = "ksh.cfg"
+ extension = ".ksh"
+elif "-sql" in sys.argv[1]:
+ config_file = "sql.cfg"
+ extension = ".sql"
else:
- if "-python" in sys.argv[1]:
- config_file = "python.cfg"
- extension = ".py"
- elif "-bash" in sys.argv[1]:
- config_file = "bash.cfg"
- extension = ".bash"
- elif "-ksh" in sys.argv[1]:
- config_file = "ksh.cfg"
- extension = ".ksh"
- elif "-sql" in sys.argv[1]:
- config_file = "sql.cfg"
- extension = ".sql"
- else:
- print("Unknown option - " + text)
- sys.exit()
+ print(f"Unknown option - {text}")
+ sys.exit()
confdir = os.getenv("my_config")
scripts = os.getenv("scripts")
diff --git a/news_articles__scraper.py b/news_articles__scraper.py
index 6c6360460cf..0b500f2920b 100644
--- a/news_articles__scraper.py
+++ b/news_articles__scraper.py
@@ -9,6 +9,7 @@
***Uncomment the line to install newspaper3k first***
"""
+
# ! pip install newspaper3k
import pickle
@@ -26,7 +27,7 @@
# Extracting links for all the pages (1 to 158) of boomlive fake news section
fakearticle_links = []
for i in range(1, 159):
- url = "https://www.boomlive.in/fake-news/" + str(i)
+ url = f"https://www.boomlive.in/fake-news/{str(i)}"
try:
# this might throw an exception if something goes wrong.
page = requests.get(url)
@@ -100,8 +101,6 @@
article.nlp()
except Exception as error:
print(f"exception : {error}")
- pass
-
# Scrape the contents of article
title.append(article.title) # extracts the title of the article
text.append(article.text) # extracts the whole text of article
@@ -155,7 +154,7 @@
# Extracting links for all the pages (2 to 125) of boomlive fake news section
for i in range(2, 126):
- url = "https://timesofindia.indiatimes.com/news/" + str(i)
+ url = f"https://timesofindia.indiatimes.com/news/{str(i)}"
try:
# send requests
diff --git a/next_number.py b/next_number.py
index 30a935742b3..b5f9443fe24 100644
--- a/next_number.py
+++ b/next_number.py
@@ -1,6 +1,5 @@
-x, li, small, maxx, c = input(), list(), 0, 0, 1
-for i in range(len(x)):
- li.append(int(x[i]))
+x, li, small, maxx, c = input(), [], 0, 0, 1
+li.extend(int(x[i]) for i in range(len(x)))
for i in range(len(li) - 1, -1, -1):
if i == 0:
print("No Number Possible")
@@ -16,5 +15,5 @@
li[small], li[maxx] = li[maxx], li[small]
li = li[: small + 1] + sorted(li[small + 1 :])
if c:
- for i in range(len(li)):
- print(li[i], end="")
+ for item in li:
+ print(item, end="")
diff --git a/nmap_scan.py b/nmap_scan.py
index 72f4b078e96..716a1acb254 100644
--- a/nmap_scan.py
+++ b/nmap_scan.py
@@ -18,7 +18,7 @@ def nmapScan(tgtHost, tgtPort): # Create the function, this fucntion does the s
nmScan = nmap.PortScanner()
nmScan.scan(tgtHost, tgtPort)
state = nmScan[tgtHost]["tcp"][int(tgtPort)]["state"]
- print("[*] " + tgtHost + " tcp/" + tgtPort + " " + state)
+ print(f"[*] {tgtHost} tcp/{tgtPort} {state}")
def main(): # Main Program
@@ -31,7 +31,7 @@ def main(): # Main Program
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(",")
- if (tgtHost == None) | (tgtPorts[0] == None):
+ if (tgtHost is None) | (tgtPorts[0] is None):
print(parser.usage)
exit(0)
diff --git a/notepad/notepad_support.py b/notepad/notepad_support.py
index 7851ca9991a..0ffd8b920ea 100644
--- a/notepad/notepad_support.py
+++ b/notepad/notepad_support.py
@@ -123,7 +123,7 @@ def search_button(p1):
try:
cursor.execute(sql_command)
results = cursor.fetchall()
- w.errorOutput.configure(text=str(len(results)) + " results")
+ w.errorOutput.configure(text=f"{len(results)} results")
index = 0
if index >= 0 and index < len(results):
w.outputNotice.delete(1.0, END)
diff --git a/nslookup_check.py b/nslookup_check.py
index 4ae57f84cfc..3451e7de371 100644
--- a/nslookup_check.py
+++ b/nslookup_check.py
@@ -11,6 +11,4 @@
import subprocess # Import the subprocess module
for server in open("server_list.txt"): # Open the file and read each line
- subprocess.Popen(
- ("nslookup " + server)
- ) # Run the nslookup command for each server in the list
+ subprocess.Popen(f"nslookup {server}")
diff --git a/oneeven.py b/oneeven.py
index 0c0a8c52530..147ab8b702f 100644
--- a/oneeven.py
+++ b/oneeven.py
@@ -2,9 +2,6 @@
maximum = int(input(" Please Enter the Maximum Value : "))
-number = 1
-
-while number <= maximum:
+for number in range(1, maximum + 1):
if number % 2 == 0:
print("{0}".format(number))
- number = number + 1
diff --git a/other_pepole/get_ip_gui b/other_pepole/get_ip_gui
index 5728697ac5b..47dd3620cda 100755
--- a/other_pepole/get_ip_gui
+++ b/other_pepole/get_ip_gui
@@ -13,7 +13,7 @@ def get_wan_ip():
try:
# get ip from http://ipecho.net/plain as text
wan_ip = urlopen('http://ipecho.net/plain').read().decode('utf-8')
- res.configure(text='Wan IP is : ' + wan_ip, fg='#600')
+ res.configure(text=f'Wan IP is : {wan_ip}', fg='#600')
except:
res.configure(text='Problem in source : http://ipecho.net/plain', fg='red')
@@ -22,7 +22,7 @@ def get_wan_ip():
def get_local_ip():
try:
lan_ip = (socket.gethostbyname(socket.gethostname()))
- res.configure(text='Local IP is : ' + lan_ip, fg='#600')
+ res.configure(text=f'Local IP is : {lan_ip}', fg='#600')
except:
res.configure(text='Unkown Error', fg='#red')
# **************** about control button *****************#
diff --git a/passwordGen.py b/passwordGen.py
index 357c14619fc..7a49b1ddf79 100644
--- a/passwordGen.py
+++ b/passwordGen.py
@@ -8,10 +8,10 @@
passLen = 10 # actual generated password length will be this length + 1
myPass = ""
-for i in range(passLen):
+for _ in range(passLen):
while (len(myPass)) <= 2:
index = random.randrange(len(lChars))
- myPass = myPass + lChars[index]
+ myPass += lChars[index]
myPassLen = len(myPass)
while (len(myPass)) <= 5:
index = random.randrange(len(digits))
diff --git a/password_checker.py b/password_checker.py
index afc5f7203ba..e5b6203bbd7 100644
--- a/password_checker.py
+++ b/password_checker.py
@@ -3,14 +3,14 @@
def IInd_func():
count1=0
- for j in range(5):
+ for _ in range(5):
a=0
count=0
user_pwd = input("") #password you remember
for i in range(len(pwd)):
if user_pwd[i] == pwd[a]: #comparing remembered pwd with fixed pwd
a +=1
- count+=1
+ count+=1
if count==len(pwd):
print("correct pwd")
break
diff --git a/password_cracker.py b/password_cracker.py
index 3581fcc39f0..0e4bd9c01a6 100644
--- a/password_cracker.py
+++ b/password_cracker.py
@@ -22,13 +22,13 @@
def testPass(cryptPass): # Start the function
- salt = cryptPass[0:2]
+ salt = cryptPass[:2]
dictFile = open("dictionary.txt", "r") # Open the dictionary file
- for word in dictFile.readlines(): # Scan through the file
+ for word in dictFile:
word = word.strip("\n")
cryptWord = crypt.crypt(word, salt) # Check for password in the file
if cryptWord == cryptPass:
- print("[+] Found Password: " + word + "\n")
+ print(f"[+] Found Password: {word}" + "\n")
return
print("[-] Password Not Found.\n")
return
@@ -36,11 +36,11 @@ def testPass(cryptPass): # Start the function
def main():
passFile = open("passwords.txt") # Open the password file
- for line in passFile.readlines(): # Read through the file
+ for line in passFile:
if ":" in line:
user = line.split(":")[0]
cryptPass = line.split(":")[1].strip(" ") # Prepare the user name etc
- print("[*] Cracking Password For: " + user)
+ print(f"[*] Cracking Password For: {user}")
testPass(cryptPass) # Call it to crack the users password
diff --git a/password_manager.py b/password_manager.py
index cbbbcf87ef2..baac1aa24e7 100644
--- a/password_manager.py
+++ b/password_manager.py
@@ -48,14 +48,14 @@ def update_password(service_, password_):
)
conn.execute(command)
conn.commit()
- print(service_ + " password updated successfully.")
+ print(f"{service_} password updated successfully.")
def delete_service(service_):
command = 'DELETE from STORE where SERVICE = "' + service_ + '"'
conn.execute(command)
conn.commit()
- print(service_ + " deleted from the database successfully.")
+ print(f"{service_} deleted from the database successfully.")
def get_all():
@@ -74,11 +74,10 @@ def get_all():
def is_service_present(service_):
cursor_.execute("SELECT SERVICE from STORE where SERVICE = ?", (service_,))
data = cursor_.fetchall()
- if len(data) == 0:
- print("There is no service named %s" % service_)
- return False
- else:
+ if len(data) != 0:
return True
+ print(f"There is no service named {service_}")
+ return False
if connect == ADMIN_PASSWORD:
@@ -124,14 +123,13 @@ def is_service_present(service_):
add_password(service, username, password)
print("\n" + service.capitalize() + " password stored\n")
else:
- print("Service named {} already exists.".format(service))
+ print(f"Service named {service} already exists.")
elif input_ == "get":
service = input("What is the name of the service?\n")
- flag = is_service_present(service)
- if flag:
+ if flag := is_service_present(service):
username, password = get_password(service)
- print(service.capitalize() + " Details")
+ print(f"{service.capitalize()} Details")
print("Username : ", username)
print("Password : ", password)
@@ -139,20 +137,16 @@ def is_service_present(service_):
service = input("What is the name of the service?\n")
if service == "":
print("Service is not entered.")
- else:
- flag = is_service_present(service)
- if flag:
- password = getpass("Enter new password : ")
- update_password(service, password)
+ elif flag := is_service_present(service):
+ password = getpass("Enter new password : ")
+ update_password(service, password)
elif input_ == "delete":
service = input("What is the name of the service?\n")
if service == "":
print("Service is not entered.")
- else:
- flag = is_service_present(service)
- if flag:
- delete_service(service)
+ elif flag := is_service_present(service):
+ delete_service(service)
elif input_ == "getall":
get_all()
diff --git a/ph_email.py b/ph_email.py
index 8656d489ce2..7e05030f2f3 100755
--- a/ph_email.py
+++ b/ph_email.py
@@ -42,18 +42,9 @@
text = pyperclip.paste() # retrieve text from clipboard
-matches = [] # list to store numbers and emails
-
-# ph[1] means second item of the group-wise tuple
-# which is returned by findall function
-# same applies to email
-
-for ph in find_phone.findall(text):
- matches.append(ph[1])
-
-for em in find_email.findall(text):
- matches.append(em[0])
+matches = [ph[1] for ph in find_phone.findall(text)]
+matches.extend(em[0] for em in find_email.findall(text))
# display number of matches
print(f"{len(matches)} matches found")
diff --git a/ping_servers.py b/ping_servers.py
index bce734e45e9..78ce208b6e1 100644
--- a/ping_servers.py
+++ b/ping_servers.py
@@ -59,16 +59,14 @@
site = "bromley" # Set the variable site to bromley
logdir = os.getenv("logs") # Set the variable logdir by getting the OS environment logs
-logfile = (
- "ping_" + appgroup + "_" + site + ".log"
-) # Set the variable logfile, using the arguments passed to create the logfile
+logfile = f"ping_{appgroup}_{site}.log"
logfilename = os.path.join(
logdir, logfile
) # Set the variable logfilename by joining logdir and logfile together
confdir = os.getenv(
"my_config"
) # Set the variable confdir from the OS environment variable - 1.2
-conffile = appgroup + "_servers_" + site + ".txt" # Set the variable conffile - 1.2
+conffile = f"{appgroup}_servers_{site}.txt"
conffilename = os.path.join(
confdir, conffile
) # Set the variable conffilename by joining confdir and conffile together - 1.2
@@ -79,13 +77,9 @@
myping + server, shell=True, stdout=f, stderr=subprocess.STDOUT
) # Run the ping command for each server in the list.
if ret == 0: # Depending on the response
- f.write(
- server.strip() + " is alive" + "\n"
- ) # Write out that you can receive a reponse
+ f.write(f"{server.strip()} is alive" + "\n")
else:
- f.write(
- server.strip() + " did not respond" + "\n"
- ) # Write out you can't reach the box
+ f.write(f"{server.strip()} did not respond" + "\n")
print("\n\tYou can see the results in the logfile : " + logfilename)
# Show the location of the logfile
diff --git a/ping_subnet.py b/ping_subnet.py
index e8eb28d933f..56902a10bf7 100644
--- a/ping_subnet.py
+++ b/ping_subnet.py
@@ -30,19 +30,17 @@
len(sys.argv) < 2
): # If no arguments are passed then display the help and instructions on how to run the script
sys.exit(
- " You need to supply the first octets of the address Usage : "
- + filename
- + " 111.111.111"
+ f" You need to supply the first octets of the address Usage : {filename} 111.111.111"
)
- subnet = sys.argv[1] # Set the variable subnet as the three octets you pass it
if os.name == "posix": # Check the os, if it's linux then
myping = "ping -c 2 " # This is the ping command
elif os.name in ("nt", "dos", "ce"): # Check the os, if it's windows then
myping = "ping -n 2 " # This is the ping command
- f = open("ping_" + subnet + ".log", "w") # Open a logfile
+ subnet = sys.argv[1]
+ f = open(f"ping_{subnet}.log", "w")
for ip in range(2, 255): # Set the ip variable for the range of numbers
ret = subprocess.call(
myping + str(subnet) + "." + str(ip),
@@ -51,10 +49,6 @@
stderr=subprocess.STDOUT,
) # Run the command pinging the servers
if ret == 0: # Depending on the response
- f.write(
- subnet + "." + str(ip) + " is alive" + "\n"
- ) # Write out that you can receive a reponse
+ f.write(f"{subnet}.{str(ip)} is alive" + "\n")
else:
- f.write(
- subnet + "." + str(ip) + " did not respond" + "\n"
- ) # Write out you can't reach the box
+ f.write(f"{subnet}.{str(ip)} did not respond" + "\n")
diff --git a/portscanner.py b/portscanner.py
index 78fcde14a26..64b85bd8f0c 100644
--- a/portscanner.py
+++ b/portscanner.py
@@ -23,7 +23,7 @@ def connScan(tgtHost, tgtPort): # Start of the function
results = connSkt.recv(100)
screenLock.acquire() # Acquire the lock
print("[+] %d/tcp open" % tgtPort)
- print("[+] " + str(results))
+ print(f"[+] {str(results)}")
except:
screenLock.acquire()
print("[-] %d/tcp closed " % tgtPort)
@@ -61,7 +61,7 @@ def main():
(options, args) = parser.parse_args()
tgtHost = options.tgtHost
tgtPorts = str(options.tgtPort).split(",")
- if (tgtHost == None) | (tgtPorts[0] == None):
+ if (tgtHost is None) | (tgtPorts[0] is None):
print(parser.usage)
exit(0)
portScan(tgtHost, tgtPorts)
diff --git a/powerdown_startup.py b/powerdown_startup.py
index 7ce5f163c69..27e70e3105c 100644
--- a/powerdown_startup.py
+++ b/powerdown_startup.py
@@ -19,36 +19,34 @@ def windows(): # This is the function to run if it detects the OS is windows.
"startup_list.txt", "r"
): # Read the list of servers from the list
ret = subprocess.call(
- "ping -n 3 %s" % server,
+ f"ping -n 3 {server}",
shell=True,
stdout=open("NUL", "w"),
stderr=subprocess.STDOUT,
- ) # Ping the servers in turn
+ )
+
if ret == 0: # If you get a response.
- f.write(
- "%s: is alive, loading PuTTY session" % server.strip() + "\n"
- ) # Write out to the logfile
- subprocess.Popen(("putty -load " + server)) # Load the putty session
+ f.write(f"{server.strip()}: is alive, loading PuTTY session" + "\n")
+ subprocess.Popen(f"putty -load {server}")
else:
- f.write(
- "%s : did not respond" % server.strip() + "\n"
- ) # Write to the logfile if the server is down
+ f.write(f"{server.strip()} : did not respond" + "\n")
def linux():
f = open("server_startup_" + strftime("%Y-%m-%d") + ".log", "a") # Open the logfile
for server in open("startup_list.txt"): # Read the list of servers from the list
ret = subprocess.call(
- "ping -c 3 %s" % server,
+ f"ping -c 3 {server}",
shell=True,
stdout=open("/dev/null", "w"),
stderr=subprocess.STDOUT,
- ) # Ping the servers in turn
+ )
+
if ret == 0: # If you get a response.
- f.write("%s: is alive" % server.strip() + "\n") # Print a message
+ f.write(f"{server.strip()}: is alive" + "\n")
subprocess.Popen(["ssh", server.strip()])
else:
- f.write("%s: did not respond" % server.strip() + "\n")
+ f.write(f"{server.strip()}: did not respond" + "\n")
# End of the functions
diff --git a/powerup_checks.py b/powerup_checks.py
index b29cd43ba61..9725e56307f 100644
--- a/powerup_checks.py
+++ b/powerup_checks.py
@@ -45,37 +45,31 @@ def windows(): # This is the function to run if it detects the OS is windows.
for server in open(serverfile, "r"): # Read the list of servers from the list
# ret = subprocess.call("ping -n 3 %s" % server.strip(), shell=True,stdout=open('NUL', 'w'),stderr=subprocess.STDOUT) # Ping the servers in turn
ret = subprocess.call(
- "ping -n 3 %s" % server.strip(),
+ f"ping -n 3 {server.strip()}",
stdout=open("NUL", "w"),
stderr=subprocess.STDOUT,
- ) # Ping the servers in turn
+ )
+
if ret == 0: # Depending on the response
- f.write(
- "%s: is alive" % server.strip().ljust(15) + "\n"
- ) # Write out to the logfile is the server is up
+ f.write(f"{server.strip().ljust(15)}: is alive" + "\n")
else:
- f.write(
- "%s: did not respond" % server.strip().ljust(15) + "\n"
- ) # Write to the logfile if the server is down
+ f.write(f"{server.strip().ljust(15)}: did not respond" + "\n")
def linux(): # This is the function to run if it detects the OS is nix.
f = open("server_startup_" + strftime("%Y-%m-%d") + ".log", "a") # Open the logfile
for server in open(serverfile, "r"): # Read the list of servers from the list
ret = subprocess.call(
- "ping -c 3 %s" % server,
+ f"ping -c 3 {server}",
shell=True,
stdout=open("/dev/null", "w"),
stderr=subprocess.STDOUT,
- ) # Ping the servers in turn
+ )
+
if ret == 0: # Depending on the response
- f.write(
- "%s: is alive" % server.strip().ljust(15) + "\n"
- ) # Write out to the logfile is the server is up
+ f.write(f"{server.strip().ljust(15)}: is alive" + "\n")
else:
- f.write(
- "%s: did not respond" % server.strip().ljust(15) + "\n"
- ) # Write to the logfile if the server is down
+ f.write(f"{server.strip().ljust(15)}: did not respond" + "\n")
def get_servers(query): # Function to get the servers from the database
@@ -87,12 +81,11 @@ def get_servers(query): # Function to get the servers from the database
print("\nDisplaying Servers for : " + query + "\n")
while True: # While there are results
row = cursor.fetchone() # Return the results
- if row == None:
+ if row is None:
break
- f = open(serverfile, "a") # Open the serverfile
- f.write("%s\n" % str(row[0])) # Write the server out to the file
- print(row[0]) # Display the server to the screen
- f.close() # Close the file
+ with open(serverfile, "a") as f:
+ f.write("%s\n" % str(row[0])) # Write the server out to the file
+ print(row[0]) # Display the server to the screen
def main(): # Main Function
@@ -111,18 +104,17 @@ def main(): # Main Function
): # If the ask for help
print(text) # Display the help text if there isn't one passed
sys.exit(0) # Exit the script after displaying help
+ elif sys.argv[1].lower().startswith("-site1"): # If the argument is site1
+ query = "site1" # Set the variable to have the value site
+ elif (
+ sys.argv[1].lower().startswith("-site2")
+ ): # Else if the variable is bromley
+ query = "site2" # Set the variable to have the value bromley
else:
- if sys.argv[1].lower().startswith("-site1"): # If the argument is site1
- query = "site1" # Set the variable to have the value site
- elif (
- sys.argv[1].lower().startswith("-site2")
- ): # Else if the variable is bromley
- query = "site2" # Set the variable to have the value bromley
- else:
- print(
- "\n[-] Unknown option [-] " + text
- ) # If an unknown option is passed, let the user know
- sys.exit(0)
+ print(
+ "\n[-] Unknown option [-] " + text
+ ) # If an unknown option is passed, let the user know
+ sys.exit(0)
get_servers(query) # Call the get servers funtion, with the value from the argument
if os.name == "posix": # If the OS is linux.
diff --git a/primelib/primelib.py b/primelib/primelib.py
index 65856679561..7cf5243ede1 100644
--- a/primelib/primelib.py
+++ b/primelib/primelib.py
@@ -79,7 +79,7 @@ def isPrime(number):
return False
i = 5
- while i * i <= number:
+ while i**2 <= number:
if number % i == 0 or number % (i + 2) == 0:
return False
i += 6
@@ -104,7 +104,7 @@ def sieveEr(N):
# precondition
assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2"
- primes = [True for x in range(N + 1)]
+ primes = [True for _ in range(N + 1)]
for p in range(2, int(sqrt(N)) + 1):
if primes[p]:
@@ -112,12 +112,7 @@ def sieveEr(N):
primes[i] = False
primes[0] = False
primes[1] = False
- ret = []
- for p in range(N + 1):
- if primes[p]:
- ret.append(p)
-
- return ret
+ return [p for p in range(N + 1) if primes[p]]
# --------------------------------
@@ -133,14 +128,7 @@ def getPrimeNumbers(N):
# precondition
assert isinstance(N, int) and (N > 2), "'N' must been an int and > 2"
- ans = []
-
- # iterates over all numbers between 2 up to N+1
- # if a number is prime then appends to list 'ans'
- for number in range(2, N + 1):
-
- if isPrime(number):
- ans.append(number)
+ ans = [number for number in range(2, N + 1) if isPrime(number)]
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
@@ -168,12 +156,11 @@ def primeFactorization(number):
quotient = number
- if number == 0 or number == 1:
+ if number in [0, 1] or number not in [0, 1] and isPrime(number):
ans.append(number)
- # if 'number' not prime then builds the prime factorization of 'number'
- elif not isPrime(number):
+ else:
while quotient != 1:
@@ -183,9 +170,6 @@ def primeFactorization(number):
else:
factor += 1
- else:
- ans.append(number)
-
# precondition
assert isinstance(ans, list), "'ans' must been from type list"
@@ -314,9 +298,7 @@ def goldbach(number):
if primeNumbers[i] + primeNumbers[j] == number:
loop = False
- ans.append(primeNumbers[i])
- ans.append(primeNumbers[j])
-
+ ans.extend((primeNumbers[i], primeNumbers[j]))
j += 1
i += 1
@@ -414,14 +396,14 @@ def kgV(number1, number2):
count1 = primeFac1.count(n)
count2 = primeFac2.count(n)
- for i in range(max(count1, count2)):
+ for _ in range(max(count1, count2)):
ans *= n
else:
count1 = primeFac1.count(n)
- for i in range(count1):
+ for _ in range(count1):
ans *= n
done.append(n)
@@ -433,7 +415,7 @@ def kgV(number1, number2):
count2 = primeFac2.count(n)
- for i in range(count2):
+ for _ in range(count2):
ans *= n
done.append(n)
@@ -518,9 +500,10 @@ def getPrimesBetween(pNumber1, pNumber2):
# precondition
assert (
- isinstance(ans, list) and ans[0] != pNumber1 and ans[len(ans) - 1] != pNumber2
+ isinstance(ans, list) and ans[0] != pNumber1 and ans[-1] != pNumber2
), "'ans' must been a list without the arguments"
+
# 'ans' contains not 'pNumber1' and 'pNumber2' !
return ans
@@ -537,15 +520,10 @@ def getDivisors(n):
# precondition
assert isinstance(n, int) and (n >= 1), "'n' must been int and >= 1"
- ans = [] # will be returned.
-
- for divisor in range(1, n + 1):
-
- if n % divisor == 0:
- ans.append(divisor)
+ ans = [divisor for divisor in range(1, n + 1) if n % divisor == 0]
# precondition
- assert ans[0] == 1 and ans[len(ans) - 1] == n, "Error in function getDivisiors(...)"
+ assert ans[0] == 1 and ans[-1] == n, "Error in function getDivisiors(...)"
return ans
@@ -643,7 +621,7 @@ def fib(n):
fib1 = 1
ans = 1 # this will be return
- for i in range(n - 1):
+ for _ in range(n - 1):
tmp = ans
ans += fib1
fib1 = tmp
diff --git a/prison_break_scrapper.py b/prison_break_scrapper.py
index ad50636cd6a..f78d3098961 100644
--- a/prison_break_scrapper.py
+++ b/prison_break_scrapper.py
@@ -14,7 +14,7 @@
def download_files(links, idx):
for link in links:
subprocess.call(
- ["aria2c", "-s", "16", "-x", "16", "-d", "season" + str(idx), link]
+ ["aria2c", "-s", "16", "-x", "16", "-d", f"season{str(idx)}", link]
)
@@ -22,12 +22,14 @@ def main():
for i in range(1, 5):
r = req.get(BASE_URL + str(i) + "/1080/")
soup = bs(r.text, "html.parser")
- link_ = []
- for link in soup.find_all("a"):
- if ".mkv" in link.get("href"):
- link_.append(BASE_URL + str(i) + "/1080/" + link.get("href"))
- if not os.path.exists("season" + str(i)):
- os.makedirs("season" + str(i))
+ link_ = [
+ BASE_URL + str(i) + "/1080/" + link.get("href")
+ for link in soup.find_all("a")
+ if ".mkv" in link.get("href")
+ ]
+
+ if not os.path.exists(f"season{str(i)}"):
+ os.makedirs(f"season{str(i)}")
download_files(link_, i)
diff --git a/pscheck.py b/pscheck.py
index 36019a22b4d..5d5e57d7a97 100644
--- a/pscheck.py
+++ b/pscheck.py
@@ -24,7 +24,7 @@ def ps():
try:
# perform a ps command and assign results to a list
- output = commands.getoutput("ps -f|grep " + program)
+ output = commands.getoutput(f"ps -f|grep {program}")
proginfo = string.split(output)
# display results
diff --git a/psunotify.py b/psunotify.py
index 5e95769a916..aaaa04fc7ce 100644
--- a/psunotify.py
+++ b/psunotify.py
@@ -17,8 +17,9 @@
page = input("Enter Page No:")
# print type(page)
p = urllib2.Request(
- "https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start=" + page
+ f"https://www.google.co.in/search?q=gate+psu+2017+ext:pdf&start={page}"
)
+
ht = br.open(p)
text = '(.+?)'
patt = re.compile(text)
@@ -28,7 +29,7 @@
while int < len(urls):
urls[int] = urls[int].replace("", "")
urls[int] = urls[int].replace("", "")
- int = int + 1
+ int += 1
print(urls)
@@ -36,14 +37,9 @@
try:
temp = url.split("/")
q = temp[len(temp) - 1]
- if "http" in url:
- r = urllib2.urlopen(url)
- else:
- r = urllib2.urlopen("http://" + url)
- file = open("psu2" + q + ".pdf", "wb")
- file.write(r.read())
- file.close()
-
+ r = urllib2.urlopen(url) if "http" in url else urllib2.urlopen(f"http://{url}")
+ with open(f"psu2{q}.pdf", "wb") as file:
+ file.write(r.read())
print("Done")
except urllib2.URLError as e:
print(
diff --git a/puttylogs.py b/puttylogs.py
index 6e4c67a4784..5276181a36c 100644
--- a/puttylogs.py
+++ b/puttylogs.py
@@ -19,13 +19,9 @@
for files in os.listdir(logsdir): # Find all the files in the directory
if files.endswith(".log"): # Check to ensure the files in the directory end in .log
- files1 = (
- files + "." + strftime("%Y-%m-%d") + ".zip"
- ) # Create the Variable files1, this is the files in the directory, then we add a suffix with the date and the zip extension
+ files1 = f"{files}." + strftime("%Y-%m-%d") + ".zip"
os.chdir(logsdir) # Change directory to the logsdir
- os.system(
- zip_program + " " + files1 + " " + files
- ) # Zip the logs into dated zip files for each server. - 1.1
+ os.system(f"{zip_program} {files1} {files}")
shutil.move(
files1, zipdir
) # Move the zipped log files to the zipped_logs directory - 1.2
diff --git a/pyauto.py b/pyauto.py
index 7f9a19e0e77..2529f734cfa 100644
--- a/pyauto.py
+++ b/pyauto.py
@@ -18,7 +18,7 @@
while guess_password != password:
guess_password = random.choices(chars_list, k=len(password))
- print("<==================" + str(guess_password) + "==================>")
+ print(f"<=================={str(guess_password)}==================>")
if guess_password == list(password):
print("Your password is : " + "".join(guess_password))
diff --git a/pythonVideoDownloader.py b/pythonVideoDownloader.py
index 7bae8eac998..85a0b111d82 100644
--- a/pythonVideoDownloader.py
+++ b/pythonVideoDownloader.py
@@ -23,13 +23,12 @@ def get_video_links():
# find all links on web-page
links = soup.findAll("a")
- # filter the link sending with .mp4
- video_links = [
- archive_url + link["href"] for link in links if link["href"].endswith("mp4")
+ return [
+ archive_url + link["href"]
+ for link in links
+ if link["href"].endswith("mp4")
]
- return video_links
-
def download_video_series(video_links):
for link in video_links:
@@ -41,7 +40,7 @@ def download_video_series(video_links):
# last string
file_name = link.split("/")[-1]
- print("Downloading the file:%s" % file_name)
+ print(f"Downloading the file:{file_name}")
# create response object
r = requests.get(link, stream=True)
diff --git a/python_sms.py b/python_sms.py
index b5e578b3b86..ef456c72741 100644
--- a/python_sms.py
+++ b/python_sms.py
@@ -20,7 +20,7 @@
dbfile = "database/maindatabase.db"
master_db = os.path.join(dropbox, dbfile)
-f = open(scripts + "/output/student.txt", "a")
+f = open(f"{scripts}/output/student.txt", "a")
tdate = strftime("%d-%m")
@@ -30,7 +30,7 @@
cursor.execute(loc_stmt)
while True:
row = cursor.fetchone()
- if row == None:
+ if row is None:
break
sname = row[0]
snumber = row[1]
diff --git a/quote.py b/quote.py
index ed3b1b1317f..9ec497184bf 100644
--- a/quote.py
+++ b/quote.py
@@ -12,10 +12,7 @@
def return_quote():
response = requests.get("https://zenquotes.io/api/random")
json_data = loads(response.text)
- quote = (
- json_data[0]["q"] + " -" + json_data[0]["a"]
- ) # aligning the quote and it's author name in one string
- return quote
+ return json_data[0]["q"] + " -" + json_data[0]["a"]
quote = return_quote()
diff --git a/random-sentences.py b/random-sentences.py
index 3e6e8baacb7..c7c5bb58741 100644
--- a/random-sentences.py
+++ b/random-sentences.py
@@ -19,25 +19,16 @@ def random_int():
def random_sentence():
"""Creates random and return sentences."""
- return (
- "{} {} {} {} {} {}".format(
- article[random_int()],
- noun[random_int()],
- verb[random_int()],
- preposition[random_int()],
- article[random_int()],
- noun[random_int()],
- )
- ).capitalize()
+ return f"{article[random_int()]} {noun[random_int()]} {verb[random_int()]} {preposition[random_int()]} {article[random_int()]} {noun[random_int()]}".capitalize()
# prints random sentences
-for sentence in list(map(lambda x: random_sentence(), range(0, 20))):
+for sentence in list(map(lambda x: random_sentence(), range(20))):
print(sentence)
print("\n")
-story = (". ").join(list(map(lambda x: random_sentence(), range(0, 20))))
+story = (". ").join(list(map(lambda x: random_sentence(), range(20))))
# prints random sentences story
-print("{}".format(story))
+print(f"{story}")
diff --git a/random_file_move.py b/random_file_move.py
index f8a2af7704e..c44ac0df2a6 100644
--- a/random_file_move.py
+++ b/random_file_move.py
@@ -56,7 +56,7 @@ def check_ratio(x):
files = os.listdir(src)
size = int(ratio * len(files))
-print("Move {} files from {} to {} ? [y/n]".format(size, src, dest))
+print(f"Move {size} files from {src} to {dest} ? [y/n]")
if input().lower() == "y":
for f in random.sample(files, size):
try:
diff --git a/randomloadingmessage.py b/randomloadingmessage.py
index 71654d249b0..171a2b2b9a2 100644
--- a/randomloadingmessage.py
+++ b/randomloadingmessage.py
@@ -5,7 +5,7 @@
x = 1
-for i in range(x):
+for _ in range(x):
num = randint(1, 80)
if num == 1:
print("Reticulating splines...")
diff --git a/rangoli.py b/rangoli.py
index 75191e08546..2d2048245c4 100644
--- a/rangoli.py
+++ b/rangoli.py
@@ -12,7 +12,7 @@ def print_rangoli(n):
# Loop to print the rangoli
for i in range(1, n + 1):
- for j in range(0, i):
+ for j in range(i):
string += chr(96 + n - j)
if len(string) < width:
string += "-"
@@ -26,7 +26,7 @@ def print_rangoli(n):
string = ""
for i in range(n - 1, 0, -1):
- for j in range(0, i):
+ for j in range(i):
string += chr(96 + n - j)
if len(string) < width:
string += "-"
diff --git a/rearrange-files/rearrange-files.py b/rearrange-files/rearrange-files.py
index 5d12baec51f..91d5e732e43 100644
--- a/rearrange-files/rearrange-files.py
+++ b/rearrange-files/rearrange-files.py
@@ -12,11 +12,9 @@ def __init__(self):
self.list_of_all_files = os.listdir(self.folder_path)
def make_folder_and_return_name(self, foldername):
- if os.path.exists(foldername) is False:
- os.mkdir(foldername)
- else:
+ if os.path.exists(foldername) is not False:
foldername = foldername + str(2)
- os.mkdir(foldername)
+ os.mkdir(foldername)
return foldername
def check_folder_existance(self):
@@ -24,18 +22,20 @@ def check_folder_existance(self):
if self.list_of_all_files[i].endswith(".pdf"):
if os.path.exists("pdfs"):
shutil.move(
- self.folder_path + "/" + self.list_of_all_files[i],
- self.folder_path + "/pdfs",
+ f"{self.folder_path}/{self.list_of_all_files[i]}",
+ f"{self.folder_path}/pdfs",
)
+
else:
os.mkdir("pdfs")
elif self.list_of_all_files[i].endswith("jpg"):
if os.path.exists("jpgs"):
shutil.move(
- self.folder_path + "/" + self.list_of_all_files[i],
- self.folder_path + "/jpgs",
+ f"{self.folder_path}/{self.list_of_all_files[i]}",
+ f"{self.folder_path}/jpgs",
)
+
else:
os.mkdir("jpgs")
diff --git a/recursive-fibonacci.py b/recursive-fibonacci.py
index 5b769db6a70..2ef7daf714b 100644
--- a/recursive-fibonacci.py
+++ b/recursive-fibonacci.py
@@ -1,5 +1,2 @@
def fib(n):
- if n == 0 or n == 1:
- return n
- else:
- return fib(n - 1) + fib(n - 2)
+ return n if n in [0, 1] else fib(n - 1) + fib(n - 2)
diff --git a/recyclebin.py b/recyclebin.py
index 83222be716e..db317d43e3c 100644
--- a/recyclebin.py
+++ b/recyclebin.py
@@ -21,19 +21,16 @@ def sid2user(sid): # Start of the function to gather the user
"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" + "\\" + sid,
)
(value, type) = QueryValueEx(key, "ProfileImagePath")
- user = value.split("\\")[-1]
- return user
+ return value.split("\\")[-1]
except Exception:
return sid
def returnDir(): # Start of the function to search through the recyclebin
dirs = ["c:\\Recycler\\", "C:\\Recycled\\", "C:\\$RECYCLE.BIN\\"]
- # dirs=['c:\\$RECYCLE.BIN\\']
- for recycleDir in dirs:
- if os.path.isdir(recycleDir):
- return recycleDir
- return None
+ return next(
+ (recycleDir for recycleDir in dirs if os.path.isdir(recycleDir)), None
+ )
def findRecycled(
@@ -46,7 +43,7 @@ def findRecycled(
print("\n[*] Listing Files for User: " + str(user))
for file in files:
- print("[+] Found File: " + str(file))
+ print(f"[+] Found File: {str(file)}")
def main():
diff --git a/rock_paper_scissor_game.py b/rock_paper_scissor_game.py
index 21ab7c3ba50..d8046b5c6ed 100644
--- a/rock_paper_scissor_game.py
+++ b/rock_paper_scissor_game.py
@@ -37,13 +37,13 @@ def game(player_choice):
comp_choice = number_to_name(comp_number)
print(comp_choice)
- comp = -int(comp_number)
+ comp = -comp_number
play = int(number)
diff = (comp + play) % 5
- if diff == 1 or diff == 3:
+ if diff in [1, 3]:
print("you won!!!")
elif diff == 0:
print("draw")
- elif diff == 2 or diff == 4:
+ elif diff in [2, 4]:
print("you lose!!!")
diff --git a/rook.py b/rook.py
index 99b9b9cb6e9..649c47eb490 100644
--- a/rook.py
+++ b/rook.py
@@ -1,18 +1,17 @@
start = [0, 0]
end = [7, 7]
taken = [[1, 0], [1, 1], [1, 2], [1, 3]]
-queue = []
-queue.append([start[0], start[1], -1])
+queue = [[start[0], start[1], -1]]
visited = []
maze = []
-for i in range(8):
+for _ in range(8):
maze.append([".", ".", ".", ".", ".", ".", ".", "."])
visited.append([0, 0, 0, 0, 0, 0, 0, 0])
maze[start[0]][start[1]] = "S"
maze[end[0]][end[1]] = "E"
for i in taken:
maze[i[0]][i[1]] = "X"
-while len(queue) > 0:
+while queue:
point = queue.pop(0)
if end[0] == point[0] and end[1] == point[1]:
print(point[2] + 1)
diff --git a/rotate_string.py b/rotate_string.py
index ca1bc0babd0..c7e98c16033 100644
--- a/rotate_string.py
+++ b/rotate_string.py
@@ -1,22 +1,20 @@
def left_rotate(s, val):
- s1 = s[0:val]
+ s1 = s[:val]
s2 = s[val:]
return s2 + s1
def right_rotate(s, val):
- s1 = s[0 : len(s) - val]
+ s1 = s[:len(s) - val]
s2 = s[len(s) - val :]
return s2 + s1
def circular_rotate(s):
s = list(s)
- idx = 0
mid = len(s) // 2
- for i in reversed(range(mid, len(s))):
+ for idx, i in enumerate(reversed(range(mid, len(s)))):
s[idx], s[i] = s[i], s[idx]
- idx += 1
return s
diff --git a/rotatelist.py b/rotatelist.py
index 9603b0434a1..db7e9d4e09e 100644
--- a/rotatelist.py
+++ b/rotatelist.py
@@ -1,20 +1,13 @@
N = int(input("Enter The Size Of Array"))
list = []
-for i in range(0, N):
+for _ in range(N):
temp = int(input("Enter The Intger Numbers"))
list.append(temp)
-# Rotating Arrays Using Best Way:
-# Left Rotation Of The List.
-# Let's say we want to print list after its d number of rotations.
-
-finalList = []
d = int(input("Enter The Number Of Times You Want To Rotate The Array"))
-for i in range(0, N):
- finalList.append(list[(i + d) % N])
-
+finalList = [list[(i + d) % N] for i in range(N)]
print(finalList)
# This Method holds the timeComplexity of O(N) and Space Complexity of O(N)
diff --git a/russian_roulette.py b/russian_roulette.py
index 337f8be8a86..bb66f8a92b6 100644
--- a/russian_roulette.py
+++ b/russian_roulette.py
@@ -34,17 +34,13 @@ def main():
)
# check input
- while answer != "m" and answer != "p":
+ while answer not in ["m", "p"]:
answer = input("please enter again ('m' or 'p'): ")
# set turn
- if answer == 'm':
- turn = "player"
- else:
- turn = "pc"
-
+ turn = "player" if answer == 'm' else "pc"
# game starts
- while numOfRounds != 0 and (pc == False and player == False):
+ while numOfRounds != 0 and not pc and not player:
print(f"\nRound number {numOfRounds}/6")
time.sleep(1)
print("the gun is being loaded")
@@ -73,11 +69,7 @@ def main():
pc = True
else:
print("nothing happened phew!")
- if turn == "player": # flip the turn
- turn = "pc"
- else:
- turn = "player"
-
+ turn = "pc" if turn == "player" else "player"
time.sleep(2)
numOfRounds -= 1
diff --git a/scalg.py b/scalg.py
index d95ceb26117..11eb5e9a308 100644
--- a/scalg.py
+++ b/scalg.py
@@ -88,7 +88,7 @@ def score(source_data: list, weights: list, *args) -> list:
final_scores = [0 for i in range(len(score_lists[0]))]
# generate final scores
- for i, slist in enumerate(score_lists):
+ for slist in score_lists:
for j, ele in enumerate(slist):
final_scores[j] = final_scores[j] + ele
@@ -118,10 +118,7 @@ def score_columns(source_data: list, columns: list, weights: list) -> list:
list: Source data with the score of the set appended at as the last element.
"""
- temp_data = []
- for item in source_data:
- temp_data.append([item[c] for c in columns])
-
+ temp_data = [[item[c] for c in columns] for item in source_data]
if len(weights) > len(columns):
weights = [weights[item] for item in columns]
diff --git a/scrap_file.py b/scrap_file.py
index 7655e792cbe..ec584e6e812 100644
--- a/scrap_file.py
+++ b/scrap_file.py
@@ -10,11 +10,10 @@
def download(url):
- f = open(
+ with open(
"file_name.jpg", "wb"
- ) # opening file in write binary('wb') mode with file_name.ext ext=extension
- f.write(requests.get(url).content) # Writing File Content in file_name.jpg
- f.close()
+ ) as f:
+ f.write(requests.get(url).content) # Writing File Content in file_name.jpg
print("Succesfully Downloaded")
diff --git a/script_count.py b/script_count.py
index b7a2a0164b8..468274d11d8 100644
--- a/script_count.py
+++ b/script_count.py
@@ -52,7 +52,7 @@ def github(): # Start of the function just to count the files in the github dir
): # If the number of files is greater then 5, then print the following messages
print("\nYou have too many in here, start uploading !!!!!")
- print("You have: " + str(github_count) + " waiting to be uploaded to github!!")
+ print(f"You have: {str(github_count)} waiting to be uploaded to github!!")
elif github_count == 0: # Unless the count is 0, then print the following messages
print("\nGithub directory is all Clear")
else: # If it is any other number then print the following message, showing the number outstanding.
@@ -73,7 +73,7 @@ def development(): # Start of the function just to count the files in the devel
): # If the number of files is greater then 10, then print the following messages
print("\nYou have too many in here, finish them or delete them !!!!!")
- print("You have: " + str(dev_count) + " waiting to be finished!!")
+ print(f"You have: {str(dev_count)} waiting to be finished!!")
elif dev_count == 0: # Unless the count is 0, then print the following messages
print("\nDevelopment directory is all clear")
else:
diff --git a/sendemail.py b/sendemail.py
index 12a01080ee7..34e0372b1ed 100644
--- a/sendemail.py
+++ b/sendemail.py
@@ -32,7 +32,7 @@ def get_credentials():
flow.user_agent = APPLICATION_NAME
credentials = tools.run_flow(flow, store)
- print("Storing credentials to " + credential_path)
+ print(f"Storing credentials to {credential_path}")
return credentials
@@ -47,8 +47,7 @@ def SendMessage(sender, to, subject, msgHtml, msgPlain, attachmentFile=None):
)
else:
message1 = CreateMessageHtml(sender, to, subject, msgHtml, msgPlain)
- result = SendMessageInternal(service, "me", message1)
- return result
+ return SendMessageInternal(service, "me", message1)
def SendMessageInternal(service, user_id, message):
@@ -57,11 +56,11 @@ def SendMessageInternal(service, user_id, message):
service.users().messages().send(userId=user_id, body=message).execute()
)
- print("Message Id: %s" % message["id"])
+ print(f'Message Id: {message["id"]}')
return message
except errors.HttpError as error:
- print("An error occurred: %s" % error)
+ print(f"An error occurred: {error}")
return "Error"
return "OK"
@@ -103,20 +102,17 @@ def createMessageWithAttachment(sender, to, subject, msgHtml, msgPlain, attachme
if main_type == "text":
fp = open(attachmentFile, "rb")
msg = MIMEText(fp.read(), _subtype=sub_type)
- fp.close()
elif main_type == "image":
fp = open(attachmentFile, "rb")
msg = MIMEImage(fp.read(), _subtype=sub_type)
- fp.close()
elif main_type == "audio":
fp = open(attachmentFile, "rb")
msg = MIMEAudio(fp.read(), _subtype=sub_type)
- fp.close()
else:
fp = open(attachmentFile, "rb")
msg = MIMEBase(main_type, sub_type)
msg.set_payload(fp.read())
- fp.close()
+ fp.close()
filename = os.path.basename(attachmentFile)
msg.add_header("Content-Disposition", "attachment", filename=filename)
message.attach(msg)
diff --git a/sensors_information.py b/sensors_information.py
index 694dc302904..d9fa4dd25c7 100644
--- a/sensors_information.py
+++ b/sensors_information.py
@@ -12,10 +12,7 @@ def ip_addresses():
hostname = socket.gethostname()
addresses = socket.getaddrinfo(hostname, None)
- address_info = []
- for address in addresses:
- address_info.append((address[0].name, address[4][0]))
- return address_info
+ return [(address[0].name, address[4][0]) for address in addresses]
def cpu_load():
@@ -35,8 +32,8 @@ def show_sensors():
for address in ip_addresses():
print("IP Addresses: {0[1]} ({0[0]})".format(address))
print("CPU Load: {:.1f}".format(cpu_load()))
- print("RAM Available: {} MiB".format(ram_available() / 1024 ** 2))
- print("AC Connected: {}".format(ac_connected()))
+ print(f"RAM Available: {ram_available() / 1024**2} MiB")
+ print(f"AC Connected: {ac_connected()}")
def command_line(argv):
diff --git a/serial_scanner.py b/serial_scanner.py
index adf5ba1ee39..91f239eead7 100644
--- a/serial_scanner.py
+++ b/serial_scanner.py
@@ -20,35 +20,34 @@ def ListAvailablePorts():
# if there isn't available ports, returns an empty List
AvailablePorts = []
platform = sys.platform
- if platform == "win32":
+ if platform == "linux":
for i in range(255):
try:
- ser = serial.Serial(i, 9600)
+ ser = serial.Serial(f"/dev/ttyUSB{str(i)}")
except serial.serialutil.SerialException:
pass
else:
- AvailablePorts.append(ser.portstr)
+ AvailablePorts.append(f"/dev/ttyUSB{str(i)}")
ser.close()
-
- elif platform == "linux":
- for i in range(0, 255):
+ elif platform == "win32":
+ for i in range(255):
try:
- ser = serial.Serial("/dev/ttyUSB" + str(i))
+ ser = serial.Serial(i, 9600)
except serial.serialutil.SerialException:
pass
else:
- AvailablePorts.append("/dev/ttyUSB" + str(i))
+ AvailablePorts.append(ser.portstr)
ser.close()
+
else:
print(
"""This method was developed only for linux and windows
the current platform isn't recognised"""
)
- if len(AvailablePorts) == 0:
- print("NO port in use")
- return 0
- else:
+ if AvailablePorts:
return AvailablePorts
+ print("NO port in use")
+ return 0
# EXAMPLE OF HOW IT WORKS
diff --git a/sha1.py b/sha1.py
index 16a61e0ed75..b5aa4d8dd45 100644
--- a/sha1.py
+++ b/sha1.py
@@ -31,8 +31,7 @@ def padding(self):
Pads the input message with zeros so that padded_data has 64 bytes or 512 bits
"""
padding = b"\x80" + b"\x00" * (63 - (len(self.data) + 8) % 64)
- padded_data = self.data + padding + struct.pack(">Q", 8 * len(self.data))
- return padded_data
+ return self.data + padding + struct.pack(">Q", 8 * len(self.data))
def split_blocks(self):
"""
@@ -67,7 +66,7 @@ def final_hash(self):
for block in self.blocks:
expanded_block = self.expand_block(block)
a, b, c, d, e = self.h
- for i in range(0, 80):
+ for i in range(80):
if 0 <= i < 20:
f = (b & c) | ((~b) & d)
k = 0x5A827999
@@ -123,11 +122,11 @@ def main():
)
parser.add_argument("--file", dest="input_file", help="Hash contents of a file")
args = parser.parse_args()
- input_string = args.input_string
# In any case hash input should be a bytestring
if args.input_file:
hash_input = open(args.input_file, "rb").read()
else:
+ input_string = args.input_string
hash_input = bytes(input_string, "utf-8")
print(SHA1Hash(hash_input).final_hash())
diff --git a/simulate_memory_cpu.py b/simulate_memory_cpu.py
index 9a108fb89cc..0cd1c50794a 100644
--- a/simulate_memory_cpu.py
+++ b/simulate_memory_cpu.py
@@ -22,10 +22,9 @@ def print_help():
def mem():
pattern = re.compile('^(\d*)([M|G]B)$')
size = sys.argv[2].upper()
- match = pattern.match(size)
- if match:
- num = int(match.group(1))
- unit = match.group(2)
+ if match := pattern.match(size):
+ num = int(match[1])
+ unit = match[2]
if unit == 'MB':
s = ' ' * (num * 1024 * 1024)
else:
@@ -54,13 +53,13 @@ def cpu():
return
if cores > cpu_num:
- print("Invalid CPU Num(cpu_count="+str(cpu_num)+")")
+ print(f"Invalid CPU Num(cpu_count={str(cpu_num)})")
return
if cores is None or cores < 1:
cores = 1
- for i in range(cores):
+ for _ in range(cores):
Process(target=deadloop).start()
diff --git a/singly_linked_list.py b/singly_linked_list.py
index 500f30041e4..2fee90bb0dc 100644
--- a/singly_linked_list.py
+++ b/singly_linked_list.py
@@ -63,7 +63,7 @@ def delete_end(self):
curr = self.head
prev = None
while True:
- if curr.next == None:
+ if curr.next is None:
prev.next = None
del curr
break
diff --git a/snake.py b/snake.py
index 3c66cc599d4..88b0d033f88 100644
--- a/snake.py
+++ b/snake.py
@@ -25,9 +25,8 @@
x, y = win.getmaxyx()
key = KEY_DOWN # Initializing values
score = 0
- s = open(".snake_highscore.txt", "r")
- hscore = s.read()
- s.close()
+ with open(".snake_highscore.txt", "r") as s:
+ hscore = s.read()
snake = [[4, 10], [4, 9], [4, 8]] # Initial snake co-ordinates
food = [10, 20] # First food co-ordinates
@@ -35,9 +34,9 @@
while key != 27: # While Esc key is not pressed
win.border(0)
- win.addstr(0, 2, "Score : " + str(score) + " ") # Printing 'Score' and
+ win.addstr(0, 2, f"Score : {str(score)} ")
win.addstr(0, 27, " SNAKE ") # 'SNAKE' strings
- win.addstr(0, 37, "Highscore: " + str(hscore) + " ")
+ win.addstr(0, 37, f"Highscore: {str(hscore)} ")
win.timeout(
int(150 - (len(snake) / 5 + len(snake) / 10) % 120)
@@ -94,7 +93,7 @@
if snake[0] == food: # When snake eats the food
food = []
score += 1
- while food == []:
+ while not food:
food = [
randint(1, 18),
randint(1, 58),
@@ -110,15 +109,12 @@
except KeyboardInterrupt or EOFError:
curses.endwin()
- print("Score - " + str(score))
+ print(f"Score - {str(score)}")
if score > int(hscore):
- s = open(".snake_highscore.txt", "w")
- s.write(str(score))
- s.close()
-
+ with open(".snake_highscore.txt", "w") as s:
+ s.write(str(score))
curses.endwin()
if score > int(hscore):
- s = open(".snake_highscore.txt", "w")
- s.write(str(score))
- s.close()
-print("Score - " + str(score))
+ with open(".snake_highscore.txt", "w") as s:
+ s.write(str(score))
+print(f"Score - {str(score)}")
diff --git a/socket-programming/client.py b/socket-programming/client.py
index 851b74337fc..f337f6ffac9 100644
--- a/socket-programming/client.py
+++ b/socket-programming/client.py
@@ -10,7 +10,7 @@
s.connect((server, 12345))
# receive message from server connection successfully established
data = s.recv(1024).decode("utf-8")
-print(server + ": " + data)
+print(f"{server}: {data}")
while True:
# send message to server
@@ -18,7 +18,7 @@
s.sendall(new_data)
# receive message from server
data = s.recv(1024).decode("utf-8")
- print(server + ": " + data)
+ print(f"{server}: {data}")
# close connection
s.close()
diff --git a/socket-programming/server.py b/socket-programming/server.py
index 4986710ce9c..9631326fa7d 100644
--- a/socket-programming/server.py
+++ b/socket-programming/server.py
@@ -20,15 +20,14 @@
# show connected client
print("connected from", client_address)
# sending acknowledgement to client that you are connected
- connection.send(str("Now You are connected").encode("utf-8"))
+ connection.send("Now You are connected".encode("utf-8"))
# receiving the message
while True:
- data = connection.recv(1024).decode("utf-8")
- if data:
+ if data := connection.recv(1024).decode("utf-8"):
# message from client
print(list(client_address)[0], end="")
- print(": %s" % data)
+ print(f": {data}")
# Enter your message to send to client
new_data = str(input("You: ")).encode("utf-8")
connection.send(new_data)
diff --git a/soundex_algorithm.py b/soundex_algorithm.py
index 2be25a7477b..7bfc0c94acc 100644
--- a/soundex_algorithm.py
+++ b/soundex_algorithm.py
@@ -2,7 +2,7 @@ def soundex_al(word):
cap_word = word.upper() # convert the word to uppercase
return_val = ""
- return_val = "" + cap_word[0] # get the first letter of the word
+ return_val = f"{cap_word[0]}"
# dictonary to give values to the letters
code_dict = {"BFPV": "1", "CGJKQSXZ": "2", "DT": "3", "L": "4", "MN": "5", "R": "6"}
@@ -18,18 +18,16 @@ def soundex_al(word):
# get the values from the 'code_dict' and create the soundex code
for char in temp:
- for key in code_dict.keys():
- if char in key:
- code = code_dict[key]
- if code != return_val[-1]: # Remove all pairs of consecutive digits.
- return_val += code
+ for key, code in code_dict.items():
+ if char in key and code != return_val[-1]:
+ return_val += code
return_val = return_val[:4] # crop the word to 4 charactors
# if soundex code doen't contain 4 digits. fill it with zeros
if len(return_val) < 4:
- for x in range(len(return_val), 4):
- return_val = return_val + "0"
+ for _ in range(len(return_val), 4):
+ return_val = f"{return_val}0"
# return the value
return return_val
diff --git a/spiralmatrix.py b/spiralmatrix.py
index 806c82a68fa..0f0c03f1f18 100644
--- a/spiralmatrix.py
+++ b/spiralmatrix.py
@@ -2,11 +2,8 @@
t = 1
r = 0 # r stands for row
c = 0 # c stands for column
-matrix = [[0 for x in range(n)] for y in range(n)] # to initialise the matrix
-if n % 2 == 0:
- k = n // 2
-else:
- k = int((n / 2) + 1)
+matrix = [[0 for _ in range(n)] for _ in range(n)]
+k = n // 2 if n % 2 == 0 else int((n / 2) + 1)
for i in range(k):
while c < n:
matrix[r][c] = t
diff --git a/spotifyAccount.py b/spotifyAccount.py
index a585b6abb96..dc184069661 100644
--- a/spotifyAccount.py
+++ b/spotifyAccount.py
@@ -7,18 +7,15 @@
import requests
-if platform.system() == "Windows": # checking OS
- title = "windows"
-else:
- title = "linux"
+title = "windows" if platform.system() == "Windows" else "linux"
def randomName(size=10, chars=string.ascii_letters + string.digits):
- return "".join(random.choice(chars) for i in range(size))
+ return "".join(random.choice(chars) for _ in range(size))
def randomPassword(size=14, chars=string.ascii_letters + string.digits):
- return "".join(random.choice(chars) for i in range(size))
+ return "".join(random.choice(chars) for _ in range(size))
global maxi
@@ -42,12 +39,10 @@ def update(self):
time.sleep(600)
def get_proxy(self):
- random1 = random.choice(self.splited) # choose a random proxie
- return random1
+ return random.choice(self.splited)
def FormatProxy(self):
- proxyOutput = {"https": "socks4://" + self.get_proxy()}
- return proxyOutput
+ return {"https": f"socks4://{self.get_proxy()}"}
def __init__(self):
self.splited = []
@@ -78,7 +73,7 @@ def creator():
"displayname": "Josh",
"creation_point": "https://login.app.spotify.com?utm_source=spotify&utm_medium=desktop-win32&utm_campaign=organic",
"birth_month": "12",
- "email": email + "@gmail.com",
+ "email": f"{email}@gmail.com",
"password": password,
"creation_flow": "desktop",
"platform": "desktop",
@@ -91,6 +86,7 @@ def creator():
"referrer": "",
}
+
try:
r = s.post(
@@ -99,7 +95,7 @@ def creator():
proxies=proxy1.FormatProxy(),
)
if '{"status":1,"' in r.text:
- open("created.txt", "a+").write(email + "@gmail.com:" + password + "\n")
+ open("created.txt", "a+").write(f"{email}@gmail.com:{password}" + "\n")
created += 1
if title == "windows":
system(
@@ -115,8 +111,5 @@ def creator():
maxi = int(input("How many accounts do you want to create?\n"))
maxthreads = int(input("How many Threads?\n"))
-num = 0
-
-while num < maxthreads:
- num += 1
+for _ in range(maxthreads):
threading.Thread(target=creator).start() # Start Checking Thread
diff --git a/sqlite_check.py b/sqlite_check.py
index 74403b1a0bb..0776d4a274f 100644
--- a/sqlite_check.py
+++ b/sqlite_check.py
@@ -22,12 +22,12 @@
cur = con.cursor()
cur.execute("SELECT SQLITE_VERSION()")
data = cur.fetchone()
- print("SQLite version: %s" % data)
+ print(f"SQLite version: {data}")
except lite.Error as e:
- print("Error %s:" % e.args[0])
+ print(f"Error {e.args[0]}:")
sys.exit(1)
finally:
@@ -47,6 +47,6 @@
cur.execute("SELECT name FROM sqlite_master WHERE type='table'")
while True:
row = cur.fetchone()
- if row == None:
+ if row is None:
break
print(row[0])
diff --git a/sqlite_table_check.py b/sqlite_table_check.py
index 588b80e1c6e..ec7d62fe954 100644
--- a/sqlite_table_check.py
+++ b/sqlite_table_check.py
@@ -26,14 +26,20 @@
data = cursor.fetchone()
if str(data) == "(u'3.6.21',)":
- print("\nCurrently " + master_db + " is on SQLite version: %s" % data + " - OK -\n")
+ print(
+ "\nCurrently "
+ + master_db
+ + f" is on SQLite version: {data}"
+ + " - OK -\n"
+ )
+
else:
print("\nDB On different version than master version - !!!!! \n")
conn.close()
print("\nCheckling " + master_db + " against " + config_file + "\n")
-for table in tablelist.readlines():
+for table in tablelist:
conn = sqlite3.connect(master_db)
cursor = conn.cursor()
cursor.execute(
@@ -42,6 +48,6 @@
res = cursor.fetchone()
if res[0]:
- print("[+] Table : " + table.strip() + " exists [+]")
+ print(f"[+] Table : {table.strip()} exists [+]")
else:
- print("[-] Table : " + table.strip() + " does not exist [-]")
+ print(f"[-] Table : {table.strip()} does not exist [-]")
diff --git a/stack.py b/stack.py
index d90048ccf62..29ec3f69bf2 100644
--- a/stack.py
+++ b/stack.py
@@ -3,8 +3,7 @@
# Function to create an empty stack.
# It initializes size of stack as 0
def createStack():
- stack = []
- return stack
+ return []
# Function to determine the size of the stack
@@ -40,17 +39,12 @@ def reverse(string):
stack = createStack()
# Push all characters of string to stack
- for i in range(0, n, 1):
+ for i in range(n):
push(stack, string[i])
# Making the string empty since all
# characters are saved in stack
- string = ""
-
- # Pop all characters of string and
- # put them back to string
- for i in range(0, n, 1):
- string += pop(stack)
+ string = "".join(pop(stack) for _ in range(n))
return string
@@ -58,6 +52,6 @@ def reverse(string):
# Driver program to test above functions
string = "GeeksQuiz"
string = reverse(string)
-print("Reversed string is " + string)
+print(f"Reversed string is {string}")
# This code is contributed by Yash
diff --git a/stackF_Harsh2255.py b/stackF_Harsh2255.py
index b28bf9de77a..23746157565 100644
--- a/stackF_Harsh2255.py
+++ b/stackF_Harsh2255.py
@@ -6,8 +6,7 @@
# Function to create a stack. It initializes size of stack as 0
def createStack():
- stack = []
- return stack
+ return []
# Stack is empty when stack size is 0
@@ -18,22 +17,17 @@ def isEmpty(stack):
# Function to add an item to stack. It increases size by 1
def push(stack, item):
stack.append(item)
- print(item + " pushed to stack ")
+ print(f"{item} pushed to stack ")
# Function to remove an item from stack. It decreases size by 1
def pop(stack):
- if isEmpty(stack):
- return str(-maxsize - 1) # return minus infinite
-
- return stack.pop()
+ return str(-maxsize - 1) if isEmpty(stack) else stack.pop()
# Function to return the top from stack without removing it
def peek(stack):
- if isEmpty(stack):
- return str(-maxsize - 1) # return minus infinite
- return stack[len(stack) - 1]
+ return str(-maxsize - 1) if isEmpty(stack) else stack[len(stack) - 1]
# Driver program to test above functions
@@ -41,4 +35,4 @@ def peek(stack):
push(stack, str(10))
push(stack, str(20))
push(stack, str(30))
-print(pop(stack) + " popped from stack")
+print(f"{pop(stack)} popped from stack")
diff --git a/stone_paper_scissor/main.py b/stone_paper_scissor/main.py
index 2a2166f4f47..8711c92f0f7 100644
--- a/stone_paper_scissor/main.py
+++ b/stone_paper_scissor/main.py
@@ -26,6 +26,6 @@
utils.print_hand(computer_hand, "Computer")
result = utils.judge(player_hand, computer_hand)
- print("Result: " + result)
+ print(f"Result: {result}")
else:
print("Please enter a valid number")
diff --git a/stone_paper_scissor/utils.py b/stone_paper_scissor/utils.py
index 7acd1f61d36..3d2a0d17c73 100644
--- a/stone_paper_scissor/utils.py
+++ b/stone_paper_scissor/utils.py
@@ -1,22 +1,23 @@
def validate(hand):
- if hand < 0 or hand > 2:
- return False
- return True
+ return hand >= 0 and hand <= 2
def print_hand(hand, name="Guest"):
hands = ["Rock", "Paper", "Scissors"]
- print(name + " picked: " + hands[hand])
+ print(f"{name} picked: {hands[hand]}")
def judge(player, computer):
if player == computer:
return "Draw"
- elif player == 0 and computer == 1:
- return "Lose"
- elif player == 1 and computer == 2:
- return "Lose"
- elif player == 2 and computer == 0:
+ elif (
+ player == 0
+ and computer == 1
+ or player == 1
+ and computer == 2
+ or player == 2
+ and computer == 0
+ ):
return "Lose"
else:
return "Win"
diff --git a/string_rotation.py b/string_rotation.py
index 1b38bca0fd5..e092d4c25e9 100644
--- a/string_rotation.py
+++ b/string_rotation.py
@@ -6,11 +6,11 @@
def rotate(n):
a = list(n)
- if len(a) == 0:
+ if not a:
return print([])
l = []
- for i in range(1, len(a) + 1):
- a = [a[(i + 1) % (len(a))] for i in range(0, len(a))]
+ for _ in range(1, len(a) + 1):
+ a = [a[(i + 1) % (len(a))] for i in range(len(a))]
l += ["".join(a)]
print(l)
diff --git a/sudoku.py b/sudoku.py
index 688f164caff..57cf7a71bef 100644
--- a/sudoku.py
+++ b/sudoku.py
@@ -12,12 +12,11 @@
def solve(bo):
- find = find_empty(bo)
- if not find:
- return True
- else:
+ if find := find_empty(bo):
row, col = find
+ else:
+ return True
for i in range(1, 10):
if valid(bo, i, (row, col)):
bo[row][col] = i
@@ -65,7 +64,7 @@ def print_board(bo):
if j == 8:
print(bo[i][j])
else:
- print(str(bo[i][j]) + " ", end="")
+ print(f"{str(bo[i][j])} ", end="")
def find_empty(bo):
diff --git a/swap.py b/swap.py
index 2126a7e1ae5..5ddb1e00583 100644
--- a/swap.py
+++ b/swap.py
@@ -1,14 +1,6 @@
x = 5
y = 10
-# To take inputs from the user
-# x = input('Enter value of x: ')
-# y = input('Enter value of y: ')
-
-# create a temporary variable and swap the values
-temp = x
-x = y
-y = temp
-
-print("The value of x after swapping: {}".format(x))
-print("The value of y after swapping: {}".format(y))
+x, y = y, x
+print(f"The value of x after swapping: {x}")
+print(f"The value of y after swapping: {y}")
diff --git a/text_file_replace.py b/text_file_replace.py
index 216c5916537..16128e87c5c 100644
--- a/text_file_replace.py
+++ b/text_file_replace.py
@@ -19,7 +19,7 @@ def text_file_replace(file, encoding, old, new):
lines.append(line.replace(old, new))
with open(file=file, mode="w", encoding=encoding) as fd:
fd.writelines(lines)
- print('{} occurence(s) of "{}" have been replaced with "{}"'.format(cnt, old, new))
+ print(f'{cnt} occurence(s) of "{old}" have been replaced with "{new}"')
return cnt
diff --git a/tf_idf_generator.py b/tf_idf_generator.py
index 4e99e96ce64..6df716cd3c3 100644
--- a/tf_idf_generator.py
+++ b/tf_idf_generator.py
@@ -87,11 +87,10 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None):
"""
if file_names is None:
file_names = ["./../test/testdata"]
- tf_idf = (
- []
- ) # will hold a dict of word_count for every doc(line in a doc in this case)
idf = {}
+ tf_idf = []
+
# this statement is useful for altering existant tf-idf file and adding new docs in itself.(## memory is now the biggest issue)
if prev_file_path:
print(TAG, "modifying over exising file.. @", prev_file_path)
@@ -101,28 +100,25 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None):
for f in file_names:
- file1 = open(
+ with open(
f, "r"
- ) # never use 'rb' for textual data, it creates something like, {b'line-inside-the-doc'}
-
- # create word_count dict for all docs
- for line in file1:
- dict = {}
- # find the amount of doc a word is in
- for i in set(line.split()):
- if i in idf:
- idf[i] += 1
- else:
- idf[i] = 1
- for word in line.split():
- # find the count of all words in every doc
- if word not in dict:
- dict[word] = 1
- else:
- dict[word] += 1
- tf_idf.append(dict)
- file1.close()
-
+ ) as file1:
+ # create word_count dict for all docs
+ for line in file1:
+ dict = {}
+ # find the amount of doc a word is in
+ for i in set(line.split()):
+ if i in idf:
+ idf[i] += 1
+ else:
+ idf[i] = 1
+ for word in line.split():
+ # find the count of all words in every doc
+ if word not in dict:
+ dict[word] = 1
+ else:
+ dict[word] += 1
+ tf_idf.append(dict)
# calculating final TF-IDF values for all words in all docs(line in a doc in this case)
for doc in tf_idf:
for key in doc:
@@ -135,26 +131,28 @@ def find_tf_idf(file_names=None, prev_file_path=None, dump_path=None):
TAG,
"Total number of unique words in corpus",
len(idf),
- "( " + paint("++" + str(len(idf) - prev_doc_count), "g") + " )"
+ "( " + paint(f"++{str(len(idf) - prev_doc_count)}", "g") + " )"
if prev_file_path
else "",
)
+
print(
TAG,
"Total number of docs in corpus:",
len(tf_idf),
- "( " + paint("++" + str(len(tf_idf) - prev_corpus_length), "g") + " )"
+ "( " + paint(f"++{str(len(tf_idf) - prev_corpus_length)}", "g") + " )"
if prev_file_path
else "",
)
+
# dump if a dir-path is given
if dump_path:
if dump_path[-8:] != "tfidfpkl":
raise Exception(
- TAG
- + "Please provide a .tfidfpkl file_path, it is the standard format of this module."
+ f"{TAG}Please provide a .tfidfpkl file_path, it is the standard format of this module."
)
+
pickle.dump(
(idf, tf_idf), open(dump_path, "wb"), protocol=pickle.HIGHEST_PROTOCOL
)
diff --git a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py
index 0e30d89d195..9564584eed1 100644
--- a/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py
+++ b/thired-party-haarcascade-mustache-on-face/mustache-add-on-face.py
@@ -29,8 +29,8 @@
mustache2 = image_resize(mustache.copy(), width=nw)
mw, mh, mc = mustache2.shape
- for i in range(0, mw):
- for j in range(0, mh):
+ for i in range(mw):
+ for j in range(mh):
if mustache2[i, j][3] != 0: # alpha 0
roi_color[ny + int(nh / 2.0) + i, nx + j] = mustache2[i, j]
diff --git a/thired-party-haarcascade-mustache-on-face/utils.py b/thired-party-haarcascade-mustache-on-face/utils.py
index 832c2c3ff8e..068bd1b9c18 100644
--- a/thired-party-haarcascade-mustache-on-face/utils.py
+++ b/thired-party-haarcascade-mustache-on-face/utils.py
@@ -26,10 +26,8 @@ def image_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
r = width / float(w)
dim = (width, int(h * r))
- # resize the image
- resized = cv2.resize(image, dim, interpolation=inter)
# return the resized image
- return resized
+ return cv2.resize(image, dim, interpolation=inter)
class CFEVideoConf(object):
diff --git a/thread_signal.py b/thread_signal.py
index 902093517ab..bdf36b62d67 100644
--- a/thread_signal.py
+++ b/thread_signal.py
@@ -14,9 +14,8 @@ def run(self):
while self.event.is_set():
print("sub thread")
sleep(2)
- else:
- print("sub thread end")
- exit()
+ print("sub thread end")
+ exit()
def handler_thread(event):
diff --git a/tic-tac-toe.py b/tic-tac-toe.py
index 8956be21237..38453517cd8 100644
--- a/tic-tac-toe.py
+++ b/tic-tac-toe.py
@@ -25,10 +25,7 @@ def DrawBoard():
# This Function Checks position is empty or not
def CheckPosition(x):
- if board[x] == " ":
- return True
- else:
- return False
+ return board[x] == " "
# This Function Checks player has won or not
diff --git a/tic_tak_toe.py b/tic_tak_toe.py
index 3138057fea0..ef08ca5292e 100644
--- a/tic_tak_toe.py
+++ b/tic_tak_toe.py
@@ -16,10 +16,7 @@ def possibilities(board):
l = []
for i in range(len(board)):
- for j in range(len(board)):
-
- if board[i][j] == 0:
- l.append((i, j))
+ l.extend((i, j) for j in range(len(board)) if board[i][j] == 0)
return l
@@ -35,14 +32,8 @@ def random_place(board, player):
# of their marks in a horizontal row
def row_win(board, player):
for x in range(len(board)):
- win = True
-
- for y in range(len(board)):
- if board[x, y] != player:
- win = False
- continue
-
- if win == True:
+ win = all(board[x, y] == player for y in range(len(board)))
+ if win:
return win
return win
@@ -51,14 +42,8 @@ def row_win(board, player):
# of their marks in a vertical row
def col_win(board, player):
for x in range(len(board)):
- win = True
-
- for y in range(len(board)):
- if board[y][x] != player:
- win = False
- continue
-
- if win == True:
+ win = all(board[y][x] == player for y in range(len(board)))
+ if win:
return win
return win
@@ -66,11 +51,8 @@ def col_win(board, player):
# Checks whether the player has three
# of their marks in a diagonal row
def diag_win(board, player):
- win = True
y = 0
- for x in range(len(board)):
- if board[x, x] != player:
- win = False
+ win = all(board[x, x] == player for x in range(len(board)))
if win:
return win
win = True
@@ -106,7 +88,7 @@ def play_game():
while winner == 0:
for player in [1, 2]:
board = random_place(board, player)
- print("Board after " + str(counter) + " move")
+ print(f"Board after {str(counter)} move")
print(board)
sleep(2)
counter += 1
@@ -117,4 +99,4 @@ def play_game():
# Driver Code
-print("Winner is: " + str(play_game()))
+print(f"Winner is: {str(play_game())}")
diff --git a/tik_tak.py b/tik_tak.py
index fb4d11601cb..37c7cb06f04 100644
--- a/tik_tak.py
+++ b/tik_tak.py
@@ -26,10 +26,7 @@ def enter_number(p1_sign, p2_sign):
global switch
global j
k = 9
- while j:
- if k == 0:
- break
-
+ while j and k != 0:
if switch == "p1":
p1_input = int(input("\nplayer 1 :- "))
if p1_input <= 0:
diff --git a/time_delta.py b/time_delta.py
index 9b153fd9707..c2958c58706 100644
--- a/time_delta.py
+++ b/time_delta.py
@@ -53,7 +53,7 @@ def time_delta(t1, t2):
t = int(input())
- for itr_t in range(t):
+ for _ in range(t):
t1 = input()
t2 = input()
diff --git a/translation_of_sizes_of_underwear_RU.py b/translation_of_sizes_of_underwear_RU.py
index 63a64e9e34e..e4fa80528dc 100644
--- a/translation_of_sizes_of_underwear_RU.py
+++ b/translation_of_sizes_of_underwear_RU.py
@@ -10,11 +10,11 @@ def my_found(req):
"XXL": (12),
"XXXL": (14),
}
- if req[0] != "XXS":
- answ = my_dict["XXS"][req[1] - 1] + my_dict[req[0]]
- else:
- answ = my_dict["XXS"][req[1] - 1]
- return answ
+ return (
+ my_dict["XXS"][req[1] - 1] + my_dict[req[0]]
+ if req[0] != "XXS"
+ else my_dict["XXS"][req[1] - 1]
+ )
country = {1: "Россия", 2: "Германия", 3: "США", 4: "Франция", 5: "Великобритания"}
diff --git a/tweeter.py b/tweeter.py
index 73a7b3ce57a..5f9c2e1c928 100644
--- a/tweeter.py
+++ b/tweeter.py
@@ -21,28 +21,18 @@
def getStatus():
lines = []
while True:
- line = input()
- if line:
+ if line := input():
lines.append(line)
else:
break
- status = "\n".join(lines)
- return status
+ return "\n".join(lines)
def tweetthis(type):
- if type == "text":
- print("Enter your tweet " + user.name)
- tweet = getStatus()
- try:
- api.update_status(tweet)
- except Exception as e:
- print(e)
- return
- elif type == "pic":
- print("Enter pic path " + user.name)
+ if type == "pic":
+ print(f"Enter pic path {user.name}")
pic = os.path.abspath(input())
- print("Enter status " + user.name)
+ print(f"Enter status {user.name}")
title = getStatus()
try:
api.update_with_media(pic, status=title)
@@ -50,6 +40,14 @@ def tweetthis(type):
print(e)
return
+ elif type == "text":
+ print(f"Enter your tweet {user.name}")
+ tweet = getStatus()
+ try:
+ api.update_status(tweet)
+ except Exception as e:
+ print(e)
+ return
print("\n\nDONE!!")
diff --git a/ultimate-phone-book/contacts.py b/ultimate-phone-book/contacts.py
index 7c53bacb28e..af9f8514623 100644
--- a/ultimate-phone-book/contacts.py
+++ b/ultimate-phone-book/contacts.py
@@ -11,19 +11,15 @@
import pickle
import os
-# get array from pickle data
-infile = open('data/pickle-main', 'rb')
-# defining array
-array = pickle.load(infile)
-infile.close()
-
+with open('data/pickle-main', 'rb') as infile:
+ # defining array
+ array = pickle.load(infile)
# get key if path exists
keyacess = False
path = 'data/pickle-key'
if os.path.isfile('data/pickle-key'):
- pklekey = open('data/pickle-key', 'rb')
- key = pickle.load(pklekey)
- pklekey.close()
+ with open('data/pickle-key', 'rb') as pklekey:
+ key = pickle.load(pklekey)
if key == 'SKD0DW99SAMXI19#DJI9':
keyacess = True
print("key found & is correct")
@@ -70,18 +66,22 @@
arraylen = len(array[fname])
# if option 1 is selected
- if a == 1:
+ if a == 0:
+ print("Saving your Data ...")
+ with open('data/pickle-main', 'wb') as outfile:
+ pickle.dump(array, outfile)
+ print("YOUR DATA HAS BEEN SAVED SUCESSFULLY!")
+ loopvar += 1
+
+ elif a == 1:
print("")
print("== YOUR CONTACT LIST ==")
print("")
- i1 = 0
# print all names
- while i1 < arraylen:
+ for i1 in range(arraylen):
print(f"{array[fname][i1]} {array[lname][i1]}, {array[number][i1]} {array[email][i1]}")
- i1 += 1
print("=======================")
- # option 2 is selected
elif a == 2:
# get a new contact
array[fname].append(input("First Name: "))
@@ -90,7 +90,6 @@
array[email].append(input("email ID: "))
arraylen += 1
- # option 3
elif a == 3:
print("which contact would you like to delete? (enter first name)")
print("enter '\nSTOP' to STOP deleting contact")
@@ -105,28 +104,21 @@
# if no cotacts found
if tempvar == 0:
print("no cantact matches first name provided")
- # if only one contact is found
elif tempvar == 1:
print("DO YOU WANT TO DELETE CONTACT")
for i in range(4):
print(array[i][rmvar])
tempinp = input("y/n? ")
- if tempinp == 'y' or tempinp == 'Y':
+ if tempinp in ['y', 'Y']:
for i in range(4):
del array[i][rmvar]
print("contact REMOVED.")
else:
print("failed to REMOVE contact")
- # if more than one contact is found
else:
print("there are more than one contact with same name")
- # TODO
-
-
-
- # if option 4 is selected
elif a == 4:
- if keyacess == True:
+ if keyacess:
sortcounter = 1
while sortcounter != 0:
# reset counter
@@ -140,21 +132,22 @@
array[j][i + 1] = temp
# add one for changing values
sortcounter += 1
- if array[fname][i].upper() == array[fname][i + 1].upper():
- # if first name are same, compare last
- if array[lname][i].upper() > array[lname][i + 1].upper():
- for j in range(4):
- temp = array[j][i]
- array[j][i] = array[j][i + 1]
- array[j][i + 1] = temp
- # add one for changing values
- sortcounter += 1
+ if (
+ array[fname][i].upper() == array[fname][i + 1].upper()
+ and array[lname][i].upper()
+ > array[lname][i + 1].upper()
+ ):
+ for j in range(4):
+ temp = array[j][i]
+ array[j][i] = array[j][i + 1]
+ array[j][i + 1] = temp
+ # add one for changing values
+ sortcounter += 1
# if no values are swapped, sortcounter = 0; no next loop
print("CONTACTS ARE NOW SORTED")
else:
print("NEED CORRECT KEY TO ENABLE THIS FEATURE")
- # option 9
elif a == 9:
if keyacess:
# change prompt settings
@@ -168,16 +161,6 @@
print("NEED CORRECT KEY TO ENABLE THIS FEATURE")
- # if option 0 is selected
- elif a == 0:
- print("Saving your Data ...")
- outfile = open('data/pickle-main', 'wb')
- pickle.dump(array, outfile)
- outfile.close()
- print("YOUR DATA HAS BEEN SAVED SUCESSFULLY!")
- loopvar += 1
-
- # if no true option is selected
else:
print("!! PLEASE ENTER VALUE FROM GIVEN INTEGER")
diff --git a/vowels.py b/vowels.py
index c4cb540b286..4811c61c0fa 100644
--- a/vowels.py
+++ b/vowels.py
@@ -6,10 +6,7 @@
def checkVowels(letter):
- for i in range(len(vowels)):
- if letter == vowels[i]:
- return True
- return False
+ return any(letter == vowels[i] for i in range(len(vowels)))
for i in range(len(string)):
diff --git a/wiki_random.py b/wiki_random.py
index 3782ea60137..cf449770c1f 100644
--- a/wiki_random.py
+++ b/wiki_random.py
@@ -31,7 +31,7 @@ def load():
jsonData = response.json()["query"]["random"]
print("10 Random generted WIKI pages...")
for idx, j in enumerate(jsonData):
- print(str(idx) + ": ", j["title"])
+ print(f"{str(idx)}: ", j["title"])
i = input(
"Which page you want to see, enter index..[r: for retry,n: exit]?"
).lower()
diff --git a/work_connect.py b/work_connect.py
index bf3d4f9ed5a..6059d40e34d 100644
--- a/work_connect.py
+++ b/work_connect.py
@@ -37,29 +37,26 @@
): # Help Menu if called
print(text) # Print the text, stored in the text variable - 1.2
sys.exit(0) # Exit the program
-else:
- if sys.argv[1].lower().startswith("-c"): # If the first argument is -c then
- passwd = sys.argv[
- 2
- ] # Set the variable passwd as the second argument passed, in this case my login password
- subprocess.Popen(
- (
- r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p "
- + passwd
- )
- )
- subprocess.Popen((r"c:\geektools\puttycm.exe"))
- time.sleep(
- 15
- ) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc
- subprocess.Popen([remote, conffilename])
- elif (
- sys.argv[1].lower().startswith("-d")
- ): # If the first argument is -d then disconnect my checkpoint session.
- subprocess.Popen(
- (r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect ")
+elif sys.argv[1].lower().startswith("-c"): # If the first argument is -c then
+ passwd = sys.argv[
+ 2
+ ] # Set the variable passwd as the second argument passed, in this case my login password
+ subprocess.Popen(
+ (
+ r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe connect -u username -p "
+ + passwd
)
- else:
- print(
- "Unknown option - " + text
- ) # If any other option is passed, then print Unknown option and the text from above - 1.2
+ )
+ subprocess.Popen((r"c:\geektools\puttycm.exe"))
+ time.sleep(
+ 15
+ ) # Sleep for 15 seconds, so the checkpoint software can connect before opening mstsc
+ subprocess.Popen([remote, conffilename])
+elif (
+ sys.argv[1].lower().startswith("-d")
+): # If the first argument is -d then disconnect my checkpoint session.
+ subprocess.Popen(
+ (r"c:\Program Files\Checkpoint\Endpoint Connect\trac.exe disconnect ")
+ )
+else:
+ print(f"Unknown option - {text}")