From c781a8ba93967da04a7d8af861304d0a65818744 Mon Sep 17 00:00:00 2001 From: BhavKaran Date: Thu, 11 Oct 2018 17:41:22 +0530 Subject: [PATCH] Add files via upload --- CountMillionCharacters-2.0.py | 2 - Counting-sort.py | 16 +++-- Credit_Card_Validator.py | 14 ++--- Cricket_score.py | 4 +- EncryptionTool.py | 112 ++++++++++++++++++---------------- backup_automater_services.py | 32 +++++----- batch_file_rename.py | 6 +- calculator.py | 19 +++--- chaos.py | 2 +- check_file.py | 21 ++++--- check_for_sqlite_files.py | 14 ++--- check_input.py | 11 ++-- check_internet_con.py | 4 +- chicks_n_rabs.py | 6 +- create_dir_if_not_there.py | 14 ++--- cricket_live_score.py | 10 ++- daily_checks.py | 50 +++++++-------- dice.py | 1 + diceV2_dynamic.py | 14 ++--- dice_rolling_simulator.py | 39 +++++++----- dir_test.py | 4 +- env_check.py | 23 +++---- ex20.py | 21 +++++-- factorial_perm_comp.py | 112 +++++++++++++++++----------------- 24 files changed, 285 insertions(+), 266 deletions(-) diff --git a/CountMillionCharacters-2.0.py b/CountMillionCharacters-2.0.py index 460f096292b..0e9a7091155 100644 --- a/CountMillionCharacters-2.0.py +++ b/CountMillionCharacters-2.0.py @@ -1,4 +1,3 @@ - """Get the number of each character in any given text. Inputs: A txt file -- You will be asked for an input file. Simply input the name @@ -10,7 +9,6 @@ def main(): - file_input = input('File Name: ') try: with open(file_input, 'r') as info: diff --git a/Counting-sort.py b/Counting-sort.py index 0a1b148b84f..fb7d6f26f7a 100644 --- a/Counting-sort.py +++ b/Counting-sort.py @@ -1,4 +1,4 @@ -#counting sort +# counting sort l = [] @@ -7,17 +7,16 @@ highest = 0 for i in range(n): - temp = int(input("Enter element"+str(i+1)+': ')) + temp = int(input("Enter element" + str(i + 1) + ': ')) if temp > highest: highest = temp - - l += [temp] + l += [temp] -def counting_sort(l,h): - bookkeeping = [0 for i in range(h+1)] +def counting_sort(l, h): + bookkeeping = [0 for i in range(h + 1)] for i in l: bookkeeping[i] += 1 @@ -29,10 +28,9 @@ def counting_sort(l,h): if bookkeeping[i] > 0: for j in range(bookkeeping[i]): - L += [i] return L -print(counting_sort(l,highest)) - + +print(counting_sort(l, highest)) diff --git a/Credit_Card_Validator.py b/Credit_Card_Validator.py index 89bad20b76d..7c3da17d79a 100644 --- a/Credit_Card_Validator.py +++ b/Credit_Card_Validator.py @@ -2,7 +2,7 @@ class CreditCard: - def __init__(self,card_no): + def __init__(self, card_no): self.card_no = card_no @property @@ -10,7 +10,7 @@ def company(self): comp = None if str(self.card_no).startswith('4'): comp = 'Visa Card' - elif str(self.card_no).startswith(('50', '67', '58','63',)): + elif str(self.card_no).startswith(('50', '67', '58', '63',)): comp = 'Maestro Card' elif str(self.card_no).startswith('5'): comp = 'Master Card' @@ -25,7 +25,7 @@ def company(self): elif str(self.card_no).startswith('7'): comp = 'Gasoline Card' - return 'Company : '+comp + return 'Company : ' + comp def first_check(self): if 13 <= len(self.card_no) <= 19: @@ -41,7 +41,7 @@ def validate(self): crd_no = self.card_no[::-1] for i in range(len(crd_no)): if i % 2 == 1: - double_it = int(crd_no[i])*2 + double_it = int(crd_no[i]) * 2 if len(str(double_it)) == 2: sum_ += sum([eval(i) for i in str(double_it)]) @@ -61,10 +61,10 @@ def validate(self): @property def checksum(self): - return '#CHECKSUM# : '+self.card_no[-1] + return '#CHECKSUM# : ' + self.card_no[-1] @classmethod - def set_card(cls,card_to_check): + def set_card(cls, card_to_check): return cls(card_to_check) @@ -76,8 +76,6 @@ def set_card(cls,card_to_check): print(card.checksum) print(card.validate()) - # 79927398713 # 4388576018402626 # 379354508162306 - diff --git a/Cricket_score.py b/Cricket_score.py index 75b6d30758b..57f22489a73 100644 --- a/Cricket_score.py +++ b/Cricket_score.py @@ -1,6 +1,6 @@ import bs4 as bs from urllib import request -from win10toast import ToastNotifier +from win10toast import ToastNotifier toaster = ToastNotifier() @@ -17,7 +17,5 @@ for result in soup.find_all('div', attrs={"class": "cb-lv-scrs-col cb-text-complete"}): results.append(result.text) - print(score[0], results[0]) toaster.show_toast(title=score[0], msg=results[0]) - diff --git a/EncryptionTool.py b/EncryptionTool.py index e562969e4b7..bd53fcc35b6 100644 --- a/EncryptionTool.py +++ b/EncryptionTool.py @@ -1,7 +1,7 @@ -#GGearing -#Simple encryption script for text -#This was one my first versions of this script -#09/07/2017 +# GGearing +# Simple encryption script for text +# This was one my first versions of this script +# 09/07/2017 from __future__ import print_function import math import sys @@ -15,97 +15,105 @@ else: input_fun = raw_input -text=input_fun("Enter text: ") -values= [] -reverse= [] +text = input_fun("Enter text: ") +values = [] +reverse = [] + + def encryptChar(target): - #encrytion algorithm - target=(((target+42) * key) -449) + # encrytion algorithm + target = (((target + 42) * key) - 449) return target + def decryptChar(target): - target=(((target+449) / key) -42) + target = (((target + 449) / key) - 42) return target + def encrypt(input_text): - col_values= [] - for i in range (len(input_text)): - current=ord(input_text[i]) - current=encryptChar(current) + col_values = [] + for i in range(len(input_text)): + current = ord(input_text[i]) + current = encryptChar(current) col_values.append(current) return col_values + def decrypt(enc_text): col_values = [] - for i in range (len(enc_text)): - current=int(decryptChar(enc_text[i])) - current=chr(current) + for i in range(len(enc_text)): + current = int(decryptChar(enc_text[i])) + current = chr(current) col_values.append(current) return col_values + def readAndDecrypt(filename): - file=open(filename,"r") - data=file.read() - datalistint= [] - actualdata= [] - datalist=data.split(" ") + file = open(filename, "r") + data = file.read() + datalistint = [] + actualdata = [] + datalist = data.split(" ") datalist.remove('') for i in range(len(datalist)): datalistint.append(float(datalist[i])) for i in range(len(datalist)): - current1=int(decryptChar(datalistint[i])) - current1=chr(current1) + current1 = int(decryptChar(datalistint[i])) + current1 = chr(current1) actualdata.append(current1) file.close() return actualdata + def readAndEncrypt(filename): - file=open(filename,"r") - data=file.read() - datalist=list(data) - encrypted_list=list() - encrypted_list_str=list() + file = open(filename, "r") + data = file.read() + datalist = list(data) + encrypted_list = list() + encrypted_list_str = list() for i in range(len(datalist)): - current=ord(datalist[i]) - current=encryptChar(current) + current = ord(datalist[i]) + current = encryptChar(current) encrypted_list.append(current) file.close() return encrypted_list -def readAndEncryptAndSave(inp_file,out_file): - enc_list=readAndEncrypt(inp_file) - output=open(out_file,"w") + +def readAndEncryptAndSave(inp_file, out_file): + enc_list = readAndEncrypt(inp_file) + output = open(out_file, "w") for i in range(len(enc_list)): - output.write(str(enc_list[i])+" ") + output.write(str(enc_list[i]) + " ") output.close() -def readAndDecryptAndSave(inp_file,out_file): - dec_list=readAndDecrypt(inp_file) - output=open(out_file,"w") + +def readAndDecryptAndSave(inp_file, out_file): + dec_list = readAndDecrypt(inp_file) + output = open(out_file, "w") for i in range(len(dec_list)): output.write(str(dec_list[i])) output.close() -#encryption -for i in range (len(text)): - current=ord(text[i]) - current=encryptChar(current) + +# encryption +for i in range(len(text)): + current = ord(text[i]) + current = encryptChar(current) values.append(current) -#decryption -for i in range (len(text)): - current=int(decryptChar(values[i])) - current=chr(current) +# decryption +for i in range(len(text)): + current = int(decryptChar(values[i])) + current = chr(current) reverse.append(current) print(reverse) -#saves encrypted in txt file -output=open("encrypted.txt","w") +# saves encrypted in txt file +output = open("encrypted.txt", "w") for i in range(len(values)): - output.write(str(values[i])+" ") + output.write(str(values[i]) + " ") output.close() -#read and decrypts +# read and decrypts print(readAndDecrypt("encrypted.txt")) - - diff --git a/backup_automater_services.py b/backup_automater_services.py index 0addf2ce257..d2afe4f1f82 100644 --- a/backup_automater_services.py +++ b/backup_automater_services.py @@ -8,25 +8,25 @@ # Description : This will go through and backup all my automator services workflows -import datetime # Load the library module -import os # Load the library module -import shutil # Load the library module +import datetime # Load the library module +import os # Load the library module +import shutil # Load the library module -today = datetime.date.today() # Get Today's date -todaystr = today.isoformat() # Format it so we can use the format to create the directory +today = datetime.date.today() # Get Today's date +todaystr = today.isoformat() # Format it so we can use the format to create the directory -confdir = os.getenv("my_config") # Set the variable by getting the value from the OS setting -dropbox = os.getenv("dropbox") # Set the variable by getting the value from the OS setting -conffile = 'services.conf' # Set the variable as the name of the configuration file -conffilename = os.path.join(confdir, conffile) # Set the variable by combining the path and the file name -sourcedir = os.path.expanduser('~/Library/Services/') # Source directory of where the scripts are located +confdir = os.getenv("my_config") # Set the variable by getting the value from the OS setting +dropbox = os.getenv("dropbox") # Set the variable by getting the value from the OS setting +conffile = 'services.conf' # Set the variable as the name of the configuration file +conffilename = os.path.join(confdir, conffile) # Set the variable by combining the path and the file name +sourcedir = os.path.expanduser('~/Library/Services/') # Source directory of where the scripts are located # Combine several settings to create destdir = os.path.join(dropbox, "My_backups" + "/" + "Automater_services" + todaystr + "/") # 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 - sourcefile = os.path.join(sourcedir, fname) # Get the name of the source files to backup - destfile = os.path.join(destdir, fname) # Get the name of the destination file names - shutil.copytree(sourcefile, destfile) # Copy the directories +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 + sourcefile = os.path.join(sourcedir, fname) # Get the name of the source files to backup + destfile = os.path.join(destdir, fname) # Get the name of the destination file names + shutil.copytree(sourcefile, destfile) # Copy the directories diff --git a/batch_file_rename.py b/batch_file_rename.py index c540a687a87..cae8d274c92 100644 --- a/batch_file_rename.py +++ b/batch_file_rename.py @@ -6,7 +6,6 @@ once you pass the current and new extensions """ - # just checking __author__ = 'Craig Richards' __version__ = '1.0' @@ -28,7 +27,7 @@ def batch_rename(work_dir, old_ext, new_ext): # Start of the logic to check the file extensions, if old_ext = file_ext if old_ext == file_ext: # Returns changed name of the file with new extention - newfile = split_file[0] + new_ext + newfile = split_file[0] + new_ext # Write the files os.rename( @@ -39,7 +38,8 @@ def batch_rename(work_dir, old_ext, new_ext): def get_parser(): parser = argparse.ArgumentParser(description='change extension of files in a working directory') - parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, help='the directory where to change extension') + parser.add_argument('work_dir', metavar='WORK_DIR', type=str, nargs=1, + help='the directory where to change extension') parser.add_argument('old_ext', metavar='OLD_EXT', type=str, nargs=1, help='old extension') parser.add_argument('new_ext', metavar='NEW_EXT', type=str, nargs=1, help='new extension') return parser diff --git a/calculator.py b/calculator.py index 81f5709710b..62122f6a5b6 100644 --- a/calculator.py +++ b/calculator.py @@ -22,9 +22,10 @@ convert degrees to radians : rad(deg) """ -import math import sys +from fileinfo import raw_input + def calc(term): """ @@ -32,7 +33,7 @@ def calc(term): output: returns the result of the computed term. purpose: This function is the actual calculator and the heart of the application """ - + # This part is for reading and converting arithmetic terms. term = term.replace(' ', '') term = term.replace('^', '**') @@ -42,11 +43,11 @@ def calc(term): term = term.replace('rad', 'radians') term = term.replace('mod', '%') - functions = ['sin', 'cos', 'tan','pow', 'cosh', 'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e'] + functions = ['sin', 'cos', 'tan', 'pow', 'cosh', 'sinh', 'tanh', 'sqrt', 'pi', 'radians', 'e'] # This part is for reading and converting function expressions. term = term.lower() - + for func in functions: if func in term: withmath = 'math.' + func @@ -69,9 +70,9 @@ def calc(term): except AttributeError: print('Please check usage method and try again.') - except TypeError : - print ("please enter inputs of correct datatype ") - + except TypeError: + print("please enter inputs of correct datatype ") + return term @@ -91,8 +92,8 @@ def main(): purpose: handles user input and prints information to the console. """ - - print("\nScientific Calculator\n\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)"+\ + + print("\nScientific Calculator\n\nFor Example: sin(rad(90)) + 50% * (sqrt(16)) + round(1.42^2)" + "- 12mod3\n\nEnter quit to exit") if sys.version_info.major >= 3: diff --git a/chaos.py b/chaos.py index 727ff46eafc..6e7a5a526c9 100644 --- a/chaos.py +++ b/chaos.py @@ -15,7 +15,7 @@ def main(): print("Please enter correct number") for i in range(10): - x = 3.9 * x * (1-x) + x = 3.9 * x * (1 - x) print(x) diff --git a/check_file.py b/check_file.py index 7d3152180ff..ba72215214a 100644 --- a/check_file.py +++ b/check_file.py @@ -9,8 +9,9 @@ # Description : Check a file exists and that we can read the file from __future__ import print_function -import sys # Import the Modules -import os # Import the Modules +import sys # Import the Modules +import os # Import the Modules + # Prints usage if not appropriate length of arguments are provided @@ -21,25 +22,25 @@ def usage(): # Readfile Functions which open the file that is passed to the script def readfile(filename): - with open(filename, 'r') as f: # Ensure file is correctly closed under - read_file = f.read() # all circumstances + with open(filename, 'r') as f: # Ensure file is correctly closed under + read_file = f.read() # all circumstances print(read_file) print() - print('#'*80) + print('#' * 80) print() def main(): # Check the arguments passed to the script if len(sys.argv) >= 2: - filenames = sys.argv[1:] - filteredfilenames_1 = list(filenames) # To counter changing in the same list which you are iterating - filteredfilenames_2 = list(filenames) + file_names = sys.argv[1:] + filteredfilenames_1 = list(file_names) # To counter changing in the same list which you are iterating + filteredfilenames_2 = list(file_names) # Iterate for each filename passed in command line argument for filename in filteredfilenames_1: - if not os.path.isfile(filename): # Check the File exists + if not os.path.isfile(filename): # Check the File exists print('[-] ' + filename + ' does not exist.') - filteredfilenames_2.remove(filename) # remove non existing files from fileNames list + filteredfilenames_2.remove(filename) # remove non existing files from fileNames list continue # Check you can read the file diff --git a/check_for_sqlite_files.py b/check_for_sqlite_files.py index fe09b3c86d0..5aa472af11c 100644 --- a/check_for_sqlite_files.py +++ b/check_for_sqlite_files.py @@ -17,26 +17,26 @@ def isSQLite3(filename): if not isfile(filename): return False - if getsize(filename) < 100: # SQLite database file header is 100 bytes + if getsize(filename) < 100: # SQLite database file header is 100 bytes return False else: fd = open(filename, 'rb') - Header = fd.read(100) + header = fd.read(100) fd.close() - if Header[0:16] == 'SQLite format 3\000': + if header[0:16] == 'SQLite format 3\000': return True else: return False -log = open('sqlite_audit.txt','w') +log = open('sqlite_audit.txt', 'w') for r, d, f in os.walk(r'.'): for files in f: if isSQLite3(files): print(files) print("[+] '%s' **** is a SQLITE database file **** " % os.path.join(r, files)) - log.write("[+] '%s' **** is a SQLITE database file **** " % files+'\n') + log.write("[+] '%s' **** is a SQLITE database file **** " % files + '\n') else: - log.write("[-] '%s' is NOT a sqlite database file" % os.path.join(r, files)+'\n') - log.write("[-] '%s' is NOT a sqlite database file" % files+'\n') + log.write("[-] '%s' is NOT a sqlite database file" % os.path.join(r, files) + '\n') + log.write("[-] '%s' is NOT a sqlite database file" % files + '\n') diff --git a/check_input.py b/check_input.py index 1eb19d9eb0d..758f8ed742f 100644 --- a/check_input.py +++ b/check_input.py @@ -1,5 +1,4 @@ -def get_user_input(start,end): - +def get_user_input(start, end): """ input: two integer values lower limit 'start' and maximum 'end' @@ -29,17 +28,17 @@ def get_user_input(start,end): else: # valid case - loop = False # aborts while-loop + loop = False # aborts while-loop except ValueError: # error case - print("Please try again. Only numbers") + print("Please try again. Only numbers") return user_input - -x = get_user_input(1,6) + +x = get_user_input(1, 6) print(x) # Asks user to enter something, ie. a number option from a menu. # While type != interger, and not in the given range, diff --git a/check_internet_con.py b/check_internet_con.py index e5e2545d487..073d828f5fd 100644 --- a/check_internet_con.py +++ b/check_internet_con.py @@ -1,12 +1,14 @@ #!/usr/bin/python3 import urllib2 + def checkInternetConnectivity(): try: urllib2.urlopen("http://google.com", timeout=2) print("Working connection") except urllib2.URLError as E: - print("Connection error:%s"%E.reason) + print("Connection error:%s" % E.reason) + checkInternetConnectivity() diff --git a/chicks_n_rabs.py b/chicks_n_rabs.py index 046c637f598..559eabd43f7 100644 --- a/chicks_n_rabs.py +++ b/chicks_n_rabs.py @@ -10,9 +10,9 @@ def solve(num_heads, num_legs): ns = 'No solutions!' - for i in range(num_heads+1): - j = num_heads-i - if 2*i+4*j == num_legs: + for i in range(num_heads + 1): + j = num_heads - i + if 2 * i + 4 * j == num_legs: return i, j return ns, ns diff --git a/create_dir_if_not_there.py b/create_dir_if_not_there.py index a24e01f5ab1..07ad8159c4e 100644 --- a/create_dir_if_not_there.py +++ b/create_dir_if_not_there.py @@ -8,17 +8,17 @@ # # Description : Checks to see if a directory exists in the users home directory, if not then create it -import os # Import the OS module +import os # Import the OS module + MESSAGE = 'The directory already exists.' TESTDIR = 'testdir' try: - home = os.path.expanduser("~") # Set the variable home by expanding the user's set home directory - print(home) # Print the location - - if not os.path.exists(os.path.join(home, TESTDIR)): # os.path.join() for making a full path safely - os.makedirs(os.path.join(home, TESTDIR)) # If not create the directory, inside their home directory + home = os.path.expanduser("~") # Set the variable home by expanding the user's set home directory + print(home) # Print the location + + if not os.path.exists(os.path.join(home, TESTDIR)): # os.path.join() for making a full path safely + os.makedirs(os.path.join(home, TESTDIR)) # If not create the directory, inside their home directory else: print(MESSAGE) except Exception as e: print(e) - diff --git a/cricket_live_score.py b/cricket_live_score.py index 7bdc85f31ea..9f29600ede2 100644 --- a/cricket_live_score.py +++ b/cricket_live_score.py @@ -8,14 +8,12 @@ html_page = Client.read() Client.close() - -soup_page = soup(html_page,"html.parser") - +soup_page = soup(html_page, "html.parser") score_box = soup_page.findAll("div", {"class": "cb-col cb-col-25 cb-mtch-blk"}) score_box_len = len(score_box) print(score_box_len) for i in range(score_box_len): - print(score_box[i].a["title"]) - print(score_box[i].a.text) - print() + print(score_box[i].a["title"]) + print(score_box[i].a.text) + print() diff --git a/daily_checks.py b/daily_checks.py index 8ab0e6ea3ed..bcb85aa5ccb 100644 --- a/daily_checks.py +++ b/daily_checks.py @@ -12,66 +12,68 @@ Description : This simple script loads everything I need to carry out the daily checks for our systems. """ -import platform # Load Modules +import platform # Load Modules import os import subprocess import sys -from time import strftime # Load just the strftime Module from Time +from time import strftime # Load just the strftime Module from Time -def clear_screen(): # Function to clear the screen - if os.name == "posix": # Unix/Linux/MacOS/BSD/etc - os.system('clear') # Clear the Screen - elif os.name in ("nt", "dos", "ce"): # DOS/Windows - os.system('CLS') # Clear the Screen +def clear_screen(): # Function to clear the screen + if os.name == "posix": # Unix/Linux/MacOS/BSD/etc + os.system('clear') # Clear the Screen + elif os.name in ("nt", "dos", "ce"): # DOS/Windows + os.system('CLS') # Clear the Screen -def print_docs(): # Function to print the daily checks automatically - print ("Printing Daily Check Sheets:") +def print_docs(): # Function to print the daily checks automatically + print("Printing Daily Check Sheets:") # The command below passes the command line string to open word, open the document, print it then close word down subprocess.Popen(["C:\\Program Files (x86)\Microsoft Office\Office14\winword.exe", "P:\\\\Documentation\\Daily Docs\\Back office Daily Checks.doc", "/mFilePrintDefault", "/mFileExit"]).communicate() -def putty_sessions(conffilename): # Function to load the putty sessions I need +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(('putty -load ' + server)) # Open the PuTTY sessions - 1.1 def rdp_sessions(): - print ("Loading RDP Sessions:") - subprocess.Popen("mstsc eclr.rdp") # Open up a terminal session connection and load the euroclear session + print("Loading RDP Sessions:") + subprocess.Popen("mstsc eclr.rdp") # Open up a terminal session connection and load the euroclear session def euroclear_docs(): # The command below opens IE and loads the Euroclear password document - subprocess.Popen('"C:\\Program Files\\Internet Explorer\\iexplore.exe"' '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"') + subprocess.Popen( + '"C:\\Program Files\\Internet Explorer\\iexplore.exe"' '"file://fs1\pub_b\Pub_Admin\Documentation\Settlements_Files\PWD\Eclr.doc"') + # End of the functions # Start of the Main Program def main(): - filename = sys.argv[0] # Create the variable filename - confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.3 - conffile = 'daily_checks_servers.conf' # Set the variable conffile - 1.3 + filename = sys.argv[0] # Create the variable filename + confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable - 1.3 + conffile = 'daily_checks_servers.conf' # Set the variable conffile - 1.3 # Set the variable conffilename by joining confdir and conffile together - 1.3 conffilename = os.path.join(confdir, conffile) - clear_screen() # Call the clear screen function + clear_screen() # Call the clear screen function # The command below prints a little welcome message, as well as the script name, # the date and time and where it was run from. - print ("Good Morning " + os.getenv('USERNAME') + ", "+ - filename, "ran at", strftime("%Y-%m-%d %H:%M:%S"), "on",platform.node(), "run from",os.getcwd()) + print("Good Morning " + os.getenv('USERNAME') + ", " + + filename, "ran at", strftime("%Y-%m-%d %H:%M:%S"), "on", platform.node(), "run from", os.getcwd()) - print_docs() # Call the print_docs function - putty_sessions(conffilename) # Call the putty_session function - rdp_sessions() # Call the rdp_sessions function - euroclear_docs() # Call the euroclear_docs function + print_docs() # Call the print_docs function + putty_sessions(conffilename) # Call the putty_session function + rdp_sessions() # Call the rdp_sessions function + euroclear_docs() # Call the euroclear_docs function if __name__ == "__main__": diff --git a/dice.py b/dice.py index 5e7a8a62b5e..a2e5c12f99b 100644 --- a/dice.py +++ b/dice.py @@ -22,6 +22,7 @@ def __init__(self): So use this method to give it a judgement when you need to change the instance attributes. """ + def set_sides(self, sides_change): if sides_change >= 4: if sides_change != 6: diff --git a/diceV2_dynamic.py b/diceV2_dynamic.py index 8fcb66e74a7..313d4353f7e 100644 --- a/diceV2_dynamic.py +++ b/diceV2_dynamic.py @@ -4,15 +4,15 @@ # Class that that holds dice-functions. You can set the amount of sides and roll with each dice object. class Dice: def __init__(self): - self.sideCount=6 - + self.sideCount = 6 + def setSides(self, sides): if sides > 3: self.sides = sides else: print("This absolutely shouldn't ever happen. The programmer sucks or someone " "has tweaked with code they weren't supposed to touch!") - + def roll(self): return random.randint(1, self.sides) @@ -29,7 +29,7 @@ def checkInput(sides): return int(sides) else: return int(sides) - + except: print("Invalid input!") return None @@ -50,7 +50,7 @@ def pickNumber(item, question_string, lower_limit): # Main-function of the program that sets up the dices for the user as they want them. -def getDices(): +def getDices(): dices = [] sides = None diceAmount = None @@ -63,7 +63,7 @@ def getDices(): for i in range(0, diceAmount): d = Dice() d.setSides(sides) - dices.append(d) + dices.append(d) return dices @@ -79,4 +79,4 @@ def getDices(): rollOutput = rollOutput + str(dice.roll()) + ", " rollOutput = rollOutput[:-2] -print (rollOutput) +print(rollOutput) diff --git a/dice_rolling_simulator.py b/dice_rolling_simulator.py index e3f6fa237b1..3967b4bda44 100644 --- a/dice_rolling_simulator.py +++ b/dice_rolling_simulator.py @@ -10,32 +10,35 @@ global user_exit_checker user_exit_checker = "exit" + # Our start function (What the user will first see when starting the program) def start(): - print "Welcome to dice rolling simulator: \nPress Enter to proceed" + print + "Welcome to dice rolling simulator: \nPress Enter to proceed" raw_input(">") - + # Starting our result function (The dice picker function) result() # Our exit function (What the user will see when choosing to exit the program) def bye(): - print "Thanks for using the Dice Rolling Simulator! Have a great day! =)" + print + "Thanks for using the Dice Rolling Simulator! Have a great day! =)" # Result function which is our dice chooser function def result(): - # user_dice_chooser No idea how this got in here, thanks EroMonsterSanji. - print "\r\nGreat! Begin by choosing a die! [6] [8] [12]?\r\n" + print + "\r\nGreat! Begin by choosing a die! [6] [8] [12]?\r\n" user_dice_chooser = raw_input(">") user_dice_chooser = int(user_dice_chooser) - + # Below is the references to our dice functions (Below), when the user chooses a dice. if user_dice_chooser == 6: dice6() @@ -45,32 +48,36 @@ def result(): elif user_dice_chooser == 12: dice12() - + # If the user doesn't choose an applicable option else: - print "\r\nPlease choose one of the applicable options!\r\n" + print + "\r\nPlease choose one of the applicable options!\r\n" result() # Below are our dice functions. def dice6(): # Getting a random number between 1 and 6 and printing it. - dice_6 = random.randint(1,6) - print "\r\nYou rolled a " + str(dice_6) + "!\r\n" + dice_6 = random.randint(1, 6) + print + "\r\nYou rolled a " + str(dice_6) + "!\r\n" user_exit_checker() - + def dice8(): - dice_8 = random.randint(1,8) - print "\r\nYou rolled a " + str(dice_8) + "!" + dice_8 = random.randint(1, 8) + print + "\r\nYou rolled a " + str(dice_8) + "!" user_exit_checker() def dice12(): - dice_12 = random.randint(1,12) - print "\r\nYou rolled a " + str(dice_12) + "!" + dice_12 = random.randint(1, 12) + print + "\r\nYou rolled a " + str(dice_12) + "!" user_exit_checker() @@ -84,6 +91,6 @@ def user_exit_checker(): else: bye() - + # Actually starting the program now. start() diff --git a/dir_test.py b/dir_test.py index 52d14c853ad..02c71a9e885 100644 --- a/dir_test.py +++ b/dir_test.py @@ -12,8 +12,8 @@ def main(): - if sys.version_info.major >= 3: # if the interpreter version is 3.X, use 'input', - input_func = input # otherwise use 'raw_input' + if sys.version_info.major >= 3: # if the interpreter version is 3.X, use 'input', + input_func = input # otherwise use 'raw_input' else: input_func = raw_input diff --git a/env_check.py b/env_check.py index 91ad1cc8d2b..542b1c9e142 100644 --- a/env_check.py +++ b/env_check.py @@ -10,16 +10,17 @@ import os -confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable -conffile = 'env_check.conf' # Set the variable conffile +confdir = os.getenv("my_config") # Set the variable confdir from the OS environment variable +conffile = 'env_check.conf' # Set the variable conffile conffilename = os.path.join(confdir, conffile) # Set the variable conffilename by joining confdir and conffile together -for env_check in open(conffilename): # Open the config file and read all the settings - 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 - 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 - - 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) +for env_check in open(conffilename): # Open the config file and read all the settings + 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 + 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 + + 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) diff --git a/ex20.py b/ex20.py index 6065af4fea8..43a3381e97d 100644 --- a/ex20.py +++ b/ex20.py @@ -2,25 +2,34 @@ script, input_file = argv + def print_all(f): - print f.read() + print + f.read() + # seek(n) to read a file's content from byte-n def rewind(f): - f.seek(0) + f.seek(0) + def print_a_line(line_count, f): - print line_count, f.readline() + print + line_count, f.readline() + current_file = open(input_file) -print "First let's print the whole file:\n" +print +"First let's print the whole file:\n" print_all(current_file) -print "Now let's rewind, kind of like a tape." +print +"Now let's rewind, kind of like a tape." rewind(current_file) -print "Let's print three lines:" +print +"Let's print three lines:" current_line = 1 print_a_line(current_line, current_file) diff --git a/factorial_perm_comp.py b/factorial_perm_comp.py index 57fbcf6ee26..25f6f872079 100644 --- a/factorial_perm_comp.py +++ b/factorial_perm_comp.py @@ -9,71 +9,69 @@ # Description : Find Factorial, Permutation and Combination of a Number -def factorial(n): - fact = 1 - while(n >= 1 ): - fact = fact * n - n = n - 1 +def factorial(n): + fact = 1 + while n >= 1: + fact = fact * n + n = n - 1 - return fact + return fact -def permutation(n,r): - return factorial(n)/factorial(n-r) +def permutation(n, r): + return factorial(n) / factorial(n - r) - -def combination(n,r): - return permutation(n,r)/factorial(r) +def combination(n, r): + return permutation(n, r) / factorial(r) def main(): - print('choose between operator 1,2,3') - print('1) Factorial') - print('2) Permutation') - print('3) Combination') - - operation = input('\n') - - if(operation == '1'): - print('Factorial Computation\n') - while(True): - try: - n = int(input('\n Enter Value for n ')) - print('Factorial of {} = {}'.format(n,factorial(n))) - break - except(ValueError): - print('Invalid Value') - continue - - elif(operation == '2'): - print('Permutation Computation\n') - - while(True): - 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))) - break - except(ValueError): - print('Invalid Value') - continue - - - elif(operation == '3'): - print('Combination Computation\n') - while(True): - try: - 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))) - break - - except(ValueError): - print('Invalid Value') - continue + print('choose between operator 1,2,3') + print('1) Factorial') + print('2) Permutation') + print('3) Combination') + + operation = input('\n') + + if operation == '1': + print('Factorial Computation\n') + while True: + try: + n = int(input('\n Enter Value for n ')) + print('Factorial of {} = {}'.format(n, factorial(n))) + break + except ValueError: + print('Invalid Value') + continue + + elif operation == '2': + print('Permutation Computation\n') + + while True: + 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))) + break + except ValueError: + print('Invalid Value') + continue + + elif operation == '3': + print('Combination Computation\n') + while True: + try: + 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))) + break + + except ValueError: + print('Invalid Value') + continue if __name__ == '__main__': - main() + main()