blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
462b9b76fe3b31d937eb8ead58f87802ef33dd3e
mabergerx/codesignal
/arcade/smoothSaling/reverseInParentheses.py
1,026
3.5625
4
def reverseInParentheses(inputString): if "(" not in inputString: return inputString else: last_opening_index = 0 corresponding_closing_index = 0 startIndex = None results = [] reversedString = "" for i, c in enumerate(inputString): if c == '(': last_opening_index = i for index in range(last_opening_index, len(inputString)): if inputString[index] == ')': corresponding_closing_index = index break string_between = inputString[last_opening_index+1:corresponding_closing_index] string_between_reversed = string_between[::-1] reversedString = inputString[:last_opening_index] + string_between_reversed + inputString[corresponding_closing_index+1:] return reverseInParentheses(reversedString)
ab1cc72aade05ec0df48420dcfca51ec1460e1cd
mabergerx/codesignal
/arcade/throughTheFog/depositProfit.py
337
3.59375
4
def solution(deposit, rate, threshold): def calculate_yearly_increase(amount): return amount * ((rate/100) + 1) amount = deposit years = 0 while True: amount = calculate_yearly_increase(amount) years += 1 print(amount) if amount >= threshold: return years
dda65cae00928850271f2534265e91f1499126d8
mabergerx/codesignal
/arcade/theJourneyBegins/checkPalindrome.py
693
3.84375
4
def checkPalindrome(inputString): middleIndex = int(len(inputString)/2) if len(inputString) % 2: return inputString[middleIndex+1:] == inputString[:middleIndex][::-1] else: return inputString[middleIndex:] == inputString[:middleIndex][::-1] print(checkPalindrome("aabaa")) #true print(checkPalindrome("abac")) #false print(checkPalindrome("a")) #true print(checkPalindrome("az")) #false print(checkPalindrome("abacaba")) #true print(checkPalindrome("z")) #true print(checkPalindrome("aaabaaaa")) #false print(checkPalindrome("zzzazzazz")) #false print(checkPalindrome("hlbeeykoqqqqokyeeblh")) #true print(checkPalindrome("hlbeeykoqqqokyeeblh")) #true
b409c4cdc092a1d161cc84fc4081183a8ba0bcec
mabergerx/codesignal
/arcade/darkWilderness/digitDegree.py
421
3.625
4
def solution(n): if n < 10: return 0 count = 0 def recursively_solve(number, count=count): count += 1 string_representation = str(number) sum_digits = sum([int(digit) for digit in string_representation]) if sum_digits > 9: return recursively_solve(sum_digits, count) else: return count return recursively_solve(n)
ac3a6fcb8237f80f54bd88856cc669d578ea08b5
kieranmcgregor/Python
/PythonForEverybody/Ch2/Ex2_prime_calc.py
2,439
4.125
4
import sys def prime_point_calc(numerator, denominator): # Returns a number if it is a prime number prime = True while denominator < numerator: if (numerator % denominator) == 0: prime = False break else: denominator += 1 if prime: return numerator def prime_list_calc(numerator_limit, denominator): # Returns list of prime numbers from 1 to user defined limit primes = [1, 2] numerator = 3 while numerator <= numerator_limit: prime = prime_point_calc(numerator, denominator) if prime != None: primes.append(prime) if denominator == numerator: denominator == 0 numerator += 1 return primes def prime_start_calc(start, denominator): # Returns next prime after given user input not_prime = True prime = 0 numerator = start while not_prime: prime = prime_point_calc(numerator, denominator) if prime != None: not_prime = False numerator += 1 return prime def main(): numerator_empty = True lps_empty = True denominator = 2 prime = None primes = None print ("\nThis program will calculate prime numbers.") while numerator_empty: numerator = input("Please enter an integer: ") try: numerator = int(numerator) numerator_empty = False except: print ("Invalid entry, not an integer.") while lps_empty: lps = input("Is this number a [l]imit, a [p]oint or a [s]tart? ") if lps != 'l' and lps != 'p' and lps != 's': print("Invalid entry, type 'l' for limit, 'p' for point or 's' for start.") else: lps_empty = False if numerator > sys.maxsize: numerator = sys.maxsize - 10 if lps[0].lower() == 'l': numerator_limit = numerator primes = prime_list_calc(numerator_limit, denominator) elif lps[0].lower() == 'p': prime = prime_point_calc(numerator, denominator) elif lps[0].lower() == 's': start = numerator prime = prime_start_calc(start, denominator) if prime != None: print ("{} is a prime number.".format(prime)) elif primes != None: print ("The following numbers are primes.\n{}".format(primes)) elif prime == None: print ("{} is not a prime number.".format(numerator)) main()
417d8c435205d3fd812b0ad86163226983e8e4c4
kieranmcgregor/Python
/PythonTinkering/Maze/maze.py
4,251
3.71875
4
import random ALL_TILES = ['0', '1', '2', '3', '01', '02', '03', '12', '13', '23', '012', '013', '023', '123'] ONE_SIDED = { '0' : [[1, 0], [0, -1], [-1, 0]], '1' : [[0, 1], [0, -1], [-1, 0]], '2' : [[0, 1], [1, 0], [-1, 0]], '3' : [[0, 1], [1, 0], [0, -1]] } TWO_SIDED = { '01' : [[0, -1], [-1, 0]], '02' : [[1, 0], [-1, 0]], '03' : [[1, 0], [0, -1]], '12' : [[0, 1], [-1, 0]], '13' : [[0, 1], [0, -1]], '23' : [[0, 1], [1, 0]] } def build_path(): path = {} THREE_SIDED = { '123' : [0, 1], '023' : [1, 0], '013' : [0, -1], '012' : [-1, 0] } level = input("What is your level? ") path_length = int(level) + 1 i = 0 current_pos = (0, 0) next_pos = [0, 0] last_tile = '' side_in = None side_out = None while (i < path_length): if (i == 0): start_tiles = [] j = 0 for side in ALL_TILES: if (len(side) == 3): start_tiles.append(side) start_tile_index = random.randrange(len(start_tiles)) tile_name = start_tiles[start_tile_index] path[current_pos] = tile_name next_pos[0] += THREE_SIDED[tile_name][0] next_pos[1] += THREE_SIDED[tile_name][1] current_pos = tuple(next_pos) last_tile = tile_name if (next_pos[1] > 0): side_out = 0 elif (next_pos[1] < 0): side_out = 2 if (next_pos[0] > 0): side_out = 1 elif (next_pos[0] < 0): side_out = 3 side_in = (side_out + 2) % 4 print("side_in {}".format(side_in)) elif ((i > 0) and (i < (path_length - 1))): j = 0 tiles = [] while (j < 4): tiles += check_tiles(j, last_tile, side_in, top = 2) j += 1 tile_index = random.randrange(len(tiles)) tile_name = tiles[tile_index] path[current_pos] = tile_name potential_pos = collision_check(path, current_pos, tile_name) last_pos = current_pos current_pos = potential_pos[random.randrange(len(potential_pos))] last_tile = tile_name next_pos[0] = current_pos[0] - last_pos[0] next_pos[1] = current_pos[1] - last_pos[1] if (next_pos[1] > 0): side_out = 0 elif (next_pos[1] < 0): side_out = 2 if (next_pos[0] > 0): side_out = 1 elif (next_pos[0] < 0): side_out = 3 side_in = (side_out + 2) % 4 print("side_in {}".format(side_in)) else: j = 0 end_tiles = [] while (j < 4): end_tiles += check_tiles(j, last_tile, side_in, iso = 3) j += 1 end_tile_index = random.randrange(len(end_tiles)) tile_name = end_tiles[end_tile_index] path[current_pos] = tile_name i += 1 return path def check_tiles(side, last_tile, side_in, iso = None, top = None): tiles = [] if (str(side) not in last_tile): for tile in ALL_TILES: if str(side_in) not in tile: if (iso == None): if (len(tile) <= top): if tile not in tiles: tiles.append(tile) else: if (len(tile) == iso): if tile not in tiles: tiles.append(tile) return tiles def collision_check(path, current_pos, tile_name): potential_openings = [] openings = [] if tile_name in ONE_SIDED: potential_openings += ONE_SIDED[tile_name] else: potential_openings += TWO_SIDED[tile_name] for potential_opening in potential_openings: potential_pos = ((current_pos[0] + potential_opening[0]), (current_pos[1] + potential_opening[1])) if potential_pos not in path: openings.append(potential_pos) return openings path = build_path() print(path)
58bfbf28aa758d222f0375e61b4ed2dc95c2c8da
kieranmcgregor/Python
/PythonForEverybody/Ch9/Ex2_Day_Sort.py
1,767
4.15625
4
def quit(): quit = "" no_answer = True while no_answer: answer = input("Would you like to quit? (y/n) ") try: quit = answer[0].lower() no_answer = False except: print ("Invalid entry please enter 'y' for yes and 'n' for no.") continue if quit == 'n': return True elif quit != 'y': print ("Neither 'y' nor 'n' found, exiting program") return False def open_file(fname): fpath = "../Files/" + fname try: fhand = open(fpath) except: print("Invalid file path, using default ../Files/mbox-short.txt") fpath = "../Files/mbox-short.txt" fhand = open(fpath) return fhand def search(days_of_week): search_on = True while search_on: search = input("Enter day of the week:\n").title() if search in days_of_week: print ("{} commits were done on {}".format(days_of_week[search], search)) else: print ("Your search was not found") answer = input("Would you like to continue searching? (y/n) ") if 'y' in answer.lower(): continue else: search_on = False no_quit = True days_of_week = {} while no_quit: fname = input("Please enter just the file name with extension:\n") fhand = open_file(fname) for line in fhand: if line.startswith("From "): words = line.split() if len(words) > 3: day_of_week = words[2] try: days_of_week[day_of_week] += 1 except: days_of_week[day_of_week] = 1 fhand.close() print (days_of_week) search(days_of_week) no_quit = quit()
0b24edf56290b00dbd374956e2204c4850f98f85
kieranmcgregor/Python
/ML4HB/linear_regression/line_reg.py
1,624
3.625
4
import numpy as npy import matplotlib.pyplot as plt import csv class LinearRegression(object): # Implements Linear Regression def __init__(self): self.w = 0 self.b = 0 self.rho = 0 def fit(self, X, y): mean_x = X.mean() mean_y = y.mean() errors_x = X - mean_x errors_y = y - mean_y errors_product_xy = npy.sum(npy.multiply(errors_x, errors_y) ) squared_errors_x = npy.sum(errors_x ** 2) self.w = errors_product_xy / squared_errors_x self.b = mean_y - self.w * mean_x N = len(X) std_x = X.std() std_y = y.std() covariance = errors_product_xy / N self.rho = covariance / (std_x * std_y) def predict(self, X): return self.w * X + self.b def visualize_solution(X, y, lin_reg): visualize_dataset(X, y) x = npy.arange(0, 800) y = lin_reg.predict(x) plt.plot(x, y, 'r--', label = 'r = %.2f' %lin_reg.rho) plt.legend() plt.show() def visualize_dataset(X, y): plt.xlabel('Number of shares') plt.ylabel('Number of likes') plt.scatter(X, y) # plt.show() def load_dataset(): num_rows = sum(1 for line in open('dataset_Facebook.csv')) - 1 X = npy.zeros( (num_rows, 1) ) y = npy.zeros( (num_rows, 1) ) with open('dataset_Facebook.csv') as f: reader = csv.DictReader(f, delimiter = ';') next(reader, None) for i, row in enumerate(reader): X[i] = int(row['share']) if (len(row['share']) ) > 0 else 0 y[i] = int(row['like']) if (len(row['like']) ) > 0 else 0 return X, y if __name__ == '__main__': X, y = load_dataset() # visualize_dataset(X, y) lin_reg = LinearRegression() lin_reg.fit(X, y) visualize_solution(X, y, lin_reg)
e00b1159d29bace8817dac03904b7b67a8530281
ahamed2408/Mind-Map
/Mindmap.py
2,684
3.75
4
class Mindmap: #initializing Variables def __init__(self): self.l=[] self.x=0 #Function to insert the values to the cards def insert(self): for i in range(self.x): m=[] for j in range(self.x): sm=[] name=input("Enter name") reveal=opencl=notim=0 sm.append(name) sm.append(opencl) sm.append(notim) sm.append(reveal) m.append(sm) self.l.append(m) print("The Matrix is: \n",self.l) #Function to Reveal the cards def reveal_card(self): rounds=0 counts=0 out=(self.x*2)//2 while True: if(counts==out): break rounds+=1 print("Round",rounds) a,b=map(int,input("User: ").split(",")) a-=1 b-=1 self.l[a][b][2]+=1 if(self.l[a][b][3]==1): print("Already Revealed") else: print("Output: Reveal",self.l[a][b][0]) # l[a][b][1]=1 c,d=map(int,input("User: ").split(",")) c-=1 d-=1 while(a==c and b==d): print("Can't open same card\n<Another chance for second card>") c,d=map(int,input("User: ").split(",")) c-=1 d-=1 if(self.l[c][d][3]==1): print("Already Revealed") else: print("Output: Reveal",self.l[c][d][0]) self.l[c][d][2]+=1 if(self.l[a][b][0]==self.l[c][d][0]): self.l[a][b][3]=1 self.l[c][d][3]=1 print("Output:Good Job!") counts+=1 if(counts==out): break else: print("Output: Closing both cards") if(self.l[a][b][2]==4 or self.l[c][d][2]==4 ): print("output:Game over") break print("\n") # Main Function # Object of the class Mindmap mindmap = Mindmap() while True: print("\nEnter the size of Matrix.Example Input: 2 2(for 2x2 matrix)") i,j=map(int,input().split(" ")) if(i==j and i%2==0): mindmap.x=i break else: print("Wrong Size Input") print("Next step") mindmap.insert() mindmap.reveal_card() print("End of program. Press any key to continue.") input()
7b968f91ccc95bccac27bcc823b3d6fd4fa8e8f7
tganderson0/class-info-master
/class-master.py
10,498
3.890625
4
import os class ClassInfo: def __init__(self, infoLine=""): self.className = "" self.instructor = "" self.contactInfo = "" self.whatToCallProf = "" self.classMainURL = "" self.applyInfo(infoLine) def formatForSaving(self) -> str: return f"{self.className}|{self.instructor}|{self.contactInfo}|{self.whatToCallProf}|{self.classMainURL}" def applyInfo(self, infoLine: str): if infoLine == "": print("This is a new class, please enter the following information: ") self.className = input("Please enter the class name: \n\t") self.instructor = input("Please enter the instructor's name: \n\t") self.contactInfo = input("Please enter the email to contact the instructor: \n\t") self.whatToCallProf = input("Please enter the preferred name of the professor (or . if unknown): \n\t") self.classMainURL = input("Please enter the URL for the class: \n\t") else: infoLine = infoLine.strip() splitInfo = infoLine.split("|") self.className = splitInfo[0] self.instructor = splitInfo[1] self.contactInfo = splitInfo[2] self.whatToCallProf = splitInfo[3] self.classMainURL = splitInfo[4] def modifyClassInfo(self): validInfo = ["class name", "instructor", "contact info", "professor preferred name", "class url", "stop"] while True: infoToModify = input( f"What would you like to change? (lowercase ok)\n\tClass Name: {self.className}\n\tInstructor: {self.instructor}\n\tContact Info: {self.instructor}\n\tProfessor Preferred Name: {self.whatToCallProf}\n\tClass URL: {self.classMainURL}\n\tStop").lower() if infoToModify in validInfo: if infoToModify == validInfo[0]: # changing class name self.className = input("Please type the new class name:\n\t") elif infoToModify == validInfo[1]: self.instructor = input("Please type the instructor name:\n\t") elif infoToModify == validInfo[2]: self.contactInfo = input("Please type the professor's email:\n\t") elif infoToModify == validInfo[3]: self.whatToCallProf = input("Please type the professor's preferred name:\n\t") elif infoToModify == validInfo[4]: self.classMainURL = input("Please type the class URL:\n\t") elif infoToModify == validInfo[5]: break os.system('cls') print("Value changed") else: os.system('cls') print("Invalid option, please select again") def printClassInfo(self): os.system('cls') print( f"Class Name: {self.className}\n\tInstructor: {self.instructor}\n\tContact Info: {self.instructor}\n\tProfessor Preferred Name: {self.whatToCallProf}\n\tClass URL: {self.classMainURL}") input("\nPress enter to continue") os.system('cls') class ClassAssignment: def __init__(self, infoLine=""): self.assignmentName = "" self.shortDescription = "" self.assignmentURL = "" self.className = "" self.dueDate = 0 self.applyInfo(infoLine) def formatForSaving(self) -> str: return f"{self.assignmentName}|{self.shortDescription}|{self.assignmentURL}|{self.className}|{self.dueDate}" def applyInfo(self, infoLine: str): if infoLine == "": print("This is a new assignment, please enter the following information: ") self.assignmentName = input("Please enter the assignment name: \n\t") self.shortDescription = input("Please enter a description: \n\t") self.assignmentURL = input("Please enter assignment URL: \n\t") self.className = input("Please enter the class this assignment is from: \n\t") self.dueDate = int(input("Please enter the day this assignment is due (ex: 23 for the 23rd): \n\t")) else: splitInfo = infoLine.split("|") self.assignmentName = splitInfo[0] self.shortDescription = splitInfo[1] self.assignmentURL = splitInfo[2] self.className = splitInfo[3] self.dueDate = int(splitInfo[4]) def printAssignmentInfo(self): os.system('cls') print("\n") if self.dueDate == 1 or self.dueDate == 21 or self.dueDate == 31: numberThing = "st" elif self.dueDate == 2 or self.dueDate == 22: numberThing = "nd" elif self.dueDate == 3 or self.dueDate == 23: numberThing = "rd" else: numberThing = "th" print(f"Name: {self.assignmentName}\n {self.shortDescription}\n\nUrl: {self.assignmentURL}\n\nClass: {self.className}\n\nDue on the {self.dueDate}{numberThing}") input("\nPress enter to continue") os.system('cls') class ClassMegaList: def __init__(self, classFile, assignmentFile): self.classFile = classFile self.assignmentFile = assignmentFile self.classList = self.addSavedClasses(classFile) self.assnList = self.addSavedAssignments(assignmentFile) def addSavedClasses(self, classInfo: str): allClasses = [] with open(classInfo) as clsMegaList: for classData in clsMegaList.readlines(): if classData[0] == "#" or len(classData) < 3: continue else: allClasses.append(ClassInfo(classData)) return allClasses def addNewClass(self): os.system('cls') print() self.classList.append(ClassInfo()) def addSavedAssignments(self, assignInfo: str): allAssn = [] with open(assignInfo) as assnInfo: for classData in assnInfo.readlines(): if classData[0] == "#": continue else: allAssn.append(ClassAssignment(classData)) return allAssn def addNewAssignment(self): os.system('cls') print() self.assnList.append(ClassAssignment()) def printAllAssignments(self): if len(self.assnList) == 0: print("No assignments right now!\n") else: print("Assignments coming up:\n") for assn in self.assnList: if assn.dueDate == 1 or assn.dueDate == 21 or assn.dueDate == 31: numberThing = "st" elif assn.dueDate == 2 or assn.dueDate == 22: numberThing = "nd" elif assn.dueDate == 3 or assn.dueDate == 23: numberThing = "rd" else: numberThing = "th" print(f"{assn.assignmentName} : Due on the {assn.dueDate}{numberThing}") def printAllClasses(self): if len(self.assnList) == 0: print("No classes yet!") else: print("Classes:") for cls in self.classList: print(f"{cls.className}") input("Press enter to continue") def removeAssignment(self): while True: os.system('cls') print(f"Please type the assignment you would like to remove: (or type stop)") self.printAllAssignments() chosenAssignment = input() if chosenAssignment == "stop": break else: for assn in self.assnList: if chosenAssignment == assn.assignmentName: self.assnList.remove(assn) def saveQuit(self): print("Saving...\n") with open(self.classFile, "w") as f: f.seek(0) f.truncate(0) for cls in self.classList: print(cls.formatForSaving(), file=f) with open(self.assignmentFile, "w") as f: f.seek(0) f.truncate(0) for assn in self.assnList: print(assn.formatForSaving(), file=f) input("Saved\nPress enter to close program") exit() def mainLoop(self): running = True validChoices = ["add class", "add assignment", "all classes", "all assignments", "class info", "assignment info", "remove assignment", "quit"] while running: print("\n") self.printAllAssignments() choice = input(f"\n\nPlease choose an option:\n\t{validChoices[0]}\n\t{validChoices[1]}\n\t{validChoices[2]}\n\t{validChoices[3]}\n\t{validChoices[4]}\n\t{validChoices[5]}\n\t{validChoices[6]}\n\t{validChoices[7]}\n").lower() if choice in validChoices: if choice == validChoices[0]: self.addNewClass() elif choice == validChoices[1]: self.addNewAssignment() elif choice == validChoices[2]: self.printAllClasses() elif choice == validChoices[3]: self.printAllAssignments() elif choice == validChoices[4]: os.system('cls') self.printAllClasses() chosenClass = input(f"\nPlease type the class name you want more info about:") validClass = False for cls in self.classList: if chosenClass == cls.className: cls.printClassInfo() validClass = True if not validClass: print("That class does not exist") elif choice == validChoices[5]: os.system('cls') print() self.printAllAssignments() chosenAssn = input(f"\nPlease type the assignment name you want more info about:\n") validAssn = False for assn in self.assnList: if chosenAssn == assn.assignmentName: assn.printAssignmentInfo() validAssn = True if not validAssn: print("That assignment does not exist") elif choice == validChoices[6]: self.removeAssignment() elif choice == validChoices[7]: self.saveQuit() else: os.system('cls') print("Invalid Choice\n") if __name__=="__main__": os.system('cls') classMaster = ClassMegaList("classes.txt", "assignments.txt") classMaster.mainLoop()
58fae696148c1558f5ccfce2c146b574b3d6368b
KennyReyesS/AirBnB_clone
/tests/test_models/test_city.py
1,716
3.5625
4
#!/usr/bin/python3 """ This module contains test cases for City """ import unittest from models.base_model import BaseModel from models.city import City import pep8 from datetime import datetime class TestCity(unittest.TestCase): """" Test cases class of City """ def test_pep8_city(self): """pep8 test. Makes sure the Python code is up to the pep8 standard. """ syntax = pep8.StyleGuide(quit=True) check = syntax.check_files(['models/city.py']) self.assertEqual( check.total_errors, 0, "Found code style errors (and warnings)." ) def test_attr_city(self): """ Test if City has attribute """ new_city = City() self.assertTrue(hasattr(new_city, "id")) self.assertTrue(hasattr(new_city, "created_at")) self.assertTrue(hasattr(new_city, "updated_at")) self.assertTrue(hasattr(new_city, "state_id")) self.assertTrue(hasattr(new_city, "name")) def test_type_city(self): """ Test if attribute is string """ new_city = City() self.assertIs(type(new_city.id), str) self.assertIs(type(new_city.created_at), datetime) self.assertIs(type(new_city.updated_at), datetime) self.assertIs(type(new_city.state_id), str) self.assertIs(type(new_city.name), str) def test_inherit_City(self): """ test inherit """ new_inherit = City() self.assertNotIsInstance(type(new_inherit), BaseModel) def test_cityisempty(self): """ Test if attribute is empty string """ new_city = City() self.assertEqual(new_city.state_id, "") self.assertEqual(new_city.name, "")
3f66236ecc851b7aec3243da3de85cc537dd6864
JDavid550/python_challenges
/calculator.py
1,141
3.765625
4
from math import sin,cos,tan,log print(""" Operations available [1]-sin [2]-cos [3]-tan [4]-ln """) epsilon=0.01 def apply_funtion(f,n): function={ 1:sin, 2:cos, 3:tan, 4:log } result = {} for i in range(1, n+1): result[i]=function[f](i) return result def calculate(): while True: f=input('Submit the operation to be carried out: ') try: f = int(f) if f > 4 or f < 0: print('You can only select one of the four operations above') calculate() break except ValueError: print('Please, submit a number according to the operations above') if int(f)<5: while True: n=input('Submit a number: ') try: n=int(n) break except ValueError: print('Please, submit a number') for i, j in apply_funtion(f,n).items(): print(i, round(j,2)) print('These results are in radians') if __name__ == "__main__": calculate()
6afe93b0bb66b817ba92c8d1eca2e40333552a39
AshishBora/challenge1
/thresholding.py
1,109
4
4
"""Find optimal threshold""" import numpy as np def find_best_threshold(arr0, arr1): """Find the best threshold seprating arr0 from arr1. We maximize the number of elements from arr0 that are less than or equal to the threshold plus the number of elements from arr1 that are greater than the threshold. :param arr0: list of numbers :param arr1: list of numbers :return thresh: Best separating threshold :return acc: Accuracy at the best threshold """ # Use -1 for arr0 and 1 for arr1 elems = [(num, -1) for num in arr0] + [(num, 1) for num in arr1] # Sort by original value elems.sort(key=lambda elem: elem[0]) # Cumulative sum of +1 and -1s cumsum = np.cumsum([elem[1] for elem in elems]) # best threshold = minimum cumulative sum # Averaging for finer estimation min_val = np.min(cumsum) min_pos = np.where(cumsum == min_val)[0] min_elems = [elems[pos][0] for pos in min_pos] thresh = np.mean(min_elems) # Compute accuracy acc = np.mean(list(arr0 <= thresh) + list(arr1 > thresh)) return thresh, acc
a5f51f2eea4347a3c6cd4947429d3e9186b0f6f1
Murdock135/TeachPython
/class4.py
559
4.03125
4
def two_sum(NumList): # listOfNums = [] listOfNums = NumList count = 0 # while count<5: # string_nums = input('Enter a digit: ') # nums = int(string_nums) #convert to int target = int(input('What\'s the target')) listLength = len(listOfNums) for m in range(0, listLength): for n in range(m+1, listLength): if listOfNums[m]==listOfNums[n]: continue elif listOfNums[m]+listOfNums[n]==target: print(m,n) answer = two_sum([3,2,4,5,11]) print(answer)
81567c5895ebec2009ffac7000a0dcb7db71387e
mrupesh/US-INR
/USD&INR.py
523
4.3125
4
print("Currency Converter(Only Dollars And Indian Rupees)") while True: currency = input("($)Dollars or (R)Rupees:") if currency == "$": amount = int(input('Enter the amount:')) Rupees = amount * 76.50 print(f"${amount} is equal to: ₹{Rupees}") elif currency.upper() == "R": amount = int(input('Enter the amount:')) Dollars = amount / 76.50 print(f"₹{amount} is equal to: ${Dollars}") else: print("Sorry! I don't understand that...") break
46155b03dab8165762e9ecedebc7efb6a719af9c
zhouchuang/pytest
/test10.py
355
4
4
""" 题目:暂停一秒输出,并格式化当前时间。 程序分析:无。 """ import time print(time.strftime("%y-%m-%d %H:%M:%S",time.localtime(time.time()))) time.sleep(1) print(time.strftime("%y-%m-%d %H:%M:%S",time.localtime(time.time()))) myD = {1:'A',2:'B'} for key ,value in dict.items(myD): print(key,value) time.sleep(1)
64585dcd3bd9861c4b2217e55115e56c443a96ea
zhouchuang/pytest
/yunsun.py
1,034
3.625
4
# coding=utf-8 def yunsuan(userA, userB, operate): '运算函数' try: A = int(userA) B = int(userB) operate_list = {'+': (A + B), '-': (A - B), '*': (A * B), '/': (A / B)} return operate_list[operate] except KeyError: return '%s 没有这个运算' % operate except ValueError: return '请给我个数字!' except ZeroDivisionError: return '%s 不能为除数!' % userB def squaresum(userA,userB): try: A = int(userA) B = int(userB) return A*A + B*B except ValueError: return '请输入正确的数字' def user_input(): '获取用户输入' userA = input('请输入数字A: ') userB = input('请输入数字B: ') operate = input('请选择运算符号(+、-、*、/):') return yunsuan(userA, userB, operate) def getsqusum(): userA = input('请输入数字A:') userB = input('请输入数字B:') return squaresum(userA,userB) print (user_input()) print (getsqusum())
d22e880532ea9e828118e8765c1bff7754330305
zhouchuang/pytest
/test5.py
723
3.734375
4
#题目:输入某年某月某日,判断这一天是这一年的第几天? #程序分析:以3月5日为例,应该先把前两个月的加起来,然后再加上5天即本年的第几天,特殊情况,闰年且输入月份大于2时需考虑多加一天: def addleap(year,month): if year % 4 ==0 and year%100!=0 and month > 2: return 1 else: return 0 def getdayth(): year = int(input('请输入年份')) month = int(input("请输入月份")) day = int(input("请输入日期")) sum=0 days = [31,30,28,30,31,30,31,31,30,31,30,31] for d in range(0,month-1): sum += days[d] sum += day sum += addleap(year,month) return sum print(getdayth())
a5c883f15941ca3dbe09b1909762f29a9a8d430c
Thandhan/CSE7ML
/Program_9/prg9.py
1,005
3.515625
4
from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier from sklearn import datasets iris = datasets.load_iris() print("Iris Data set loaded...\n\n") x_train,x_test,y_train,y_test = train_test_split(iris.data,iris.target,test_size =0.1) print("Dataset is split into training and testing..") print("Size of training data and its label",x_train.shape,y_train.shape) print("Size of training data and its label",x_test.shape,y_test.shape,"\n\n") for i in range(len(iris.target_names)): print("Label",i,"-",str(iris.target_names[i])) # Create object of KNN classifer classifier=KNeighborsClassifier(n_neighbors=1) classifier.fit(x_train,y_train) y_pred=classifier.predict(x_test) print("Result of Classifiation using K-nn with K=1") for r in range(0,len(x_test)): print("Sample:",str(x_test[r]),"Actual-label:",str(y_test[r]),"Predicted-l abel:",str(y_pred[r])) print("Classification Accuracy:",classifier.score(x_test,y_test))
86f91d794953d183366e9290564313d1dcaa594e
gmanacce/STUDENT-REGISTERATION
/looping.py
348
4.34375
4
###### 11 / 05 / 2019 ###### Author Geofrey Manacce ###### LOOPING PROGRAM ####CREATE A LIST months = ['january','february', 'match', 'april', 'may','june','july','august','september','october','november','december'] print(months) #####using For loop for month in months: print(month.title() + "\n") print("go for next month:") print("GOODBYE!!!!")
15b25ddb8ddd76c5e5923fa92c45760c5b92c0e1
DavidToca/_learn_python_the_hard_way
/ex12.py
655
3.8125
4
#our hero remains in the temple and is been asking for his training so far print "How are your skills with the math operators?" math_operations_skills = raw_input("skills: ") print "And what about your commenting ones?" commenting_skills = raw_input("skills: ") print "Why there isn't any more chapters between 6 and 11?" why_missing_chapters = raw_input("whyyy: ") print print "Ohhh ok, now I get it, it was because %s, mistery solved !" % why_missing_chapters print "Now back to your skills, your current status is:" print "*" * 10 print "math operations =", math_operations_skills print "*" * 10 print "commenting =", commenting_skills print "*" * 10
4407c72830681d2263c4882d39ab84070af61a77
Compileworx/Python
/De Cipher Text.py
348
4.34375
4
code = input("Please enter the coded text") distance = int(input("Please enter the distance value")) plainText = '' for ch in code: ordValue = ord(ch) cipherValue = ordValue - distance if(cipherValue < ord('a')): cipherValue = ord('z') - (distance - (ord('a') - ordValue + 1)) plainText += chr(cipherValue) print(plainText)
a61879f80699a457876f51b80db5a7a28227b733
caethan/CSE232
/problems/TOJ1297.py
1,155
3.90625
4
import sys S = sys.stdin.readline().strip() #Suffix tree implementation tree = {} END = 'END' def add_word(tree, word, terminator, marker): tree[marker] = True if not word: tree[END] = terminator return char = word[0] if not char in tree: tree[char] = {} add_word(tree[char], word[1:], terminator, marker) def add_suffixes(tree, S, marker): for i in range(len(S)): add_word(tree, S[i:], i, marker) #Build a suffix tree on both the forward and reversed strings, marking nodes by which string they're from add_suffixes(tree, S, 'forward') add_suffixes(tree, S[::-1], 'reverse') #N.B. doesn't get the first longest palindrome #Find the deepest shared node def find_shared(tree, char='', m1='forward', m2='reverse'): if not ((m1 in tree) and (m2 in tree)): #Not a shared node return '' shared = '' for key in tree.keys(): if key == m1 or key == m2 or key == END: continue deeper = find_shared(tree[key], key) if len(deeper) > len(shared): shared = deeper return char + shared print find_shared(tree)
adbd60fcb21c92970b7561225d0574300f958325
quangnguyendang/Reinforcement_Learning
/Chapter06_Temporal_Difference/Cliff_Walking_Q_Learning.py
8,666
3.75
4
# Example 6.6 page 108 in Reinforcement Learning: An Introduction Book # PhD Student: Nguyen Dang Quang, Computer Science Department, KyungHee University, Korea. # Q learning, Double Q Learning and SARSA Implementation import numpy as np import matplotlib.pyplot as plt # -------------- Set Constants ---------------- n_col = 12 n_row = 4 terminal = 47 goal = 47 start = 36 cliff_start = 37 cliff_end = 46 action_space = ['U', 'D', 'L', 'R'] action_index_effect = {'U': (-1 * n_col), 'D': n_col, 'L': -1, 'R': 1} action_index = {'U': 0, 'D': 1, 'L': 2, 'R': 3} state_space = range(0, n_col*n_row) # -------------- Utility Functions ---------------- def state_initialize(): # s = np.random.randint(0, n_row*n_col-1) # if s in range(cliff_start, cliff_end + 1): # s = start s = start return s def next_state(s, a): s_ = s + action_index_effect[a] row_s = int(s / n_col) col_s = s % n_col if (s_ not in range(0, n_col*n_row)) or \ ((row_s == 0) and (a == 'U')) or \ ((row_s == (n_row - 1)) and (a == 'D')) or \ ((col_s == 0) and (a == 'L')) or \ ((col_s == (n_col - 1)) and (a == 'R')): return -1 else: return s_ def take_action(s, a): row_s = int(s/n_col) col_s = s % n_col s_ = s + action_index_effect[a] r = -1000 if s_ in range(cliff_start, cliff_end + 1): s_ = start r = -100 elif (row_s == 0 and a == 'U') or \ ((row_s == n_row - 1) and a == 'D') or \ (col_s == 0 and a == 'L') or \ (col_s == (n_col - 1) and a == 'R'): s_ = -1 else: r = -1 return s_, r def epsilon_greedy(Q, s, epsilon): if np.random.rand() < epsilon: # Exploration a = action_space[np.random.randint(0, len(action_space))] while next_state(s, a) == -1: a = action_space[np.random.randint(0, len(action_space))] return a else: # Exploitation max_index = [] maxQ = -99999999 for i in range(0, len(action_space)): if (Q[s, i] > maxQ) and (next_state(s, action_space[i]) != -1): max_index = [i] maxQ = Q[s, i] elif (Q[s, i] == maxQ) and (next_state(s, action_space[i]) != -1): max_index.append(i) return action_space[max_index[np.random.randint(0, len(max_index))]] def print_policy(Q): print('\nOptimal Deterministic Policy:') for i in range(0, n_row): row_string = "" for j in range(0, n_col): s = i*n_col + j if s in range(cliff_start, cliff_end+1): row_string += '%12s' % "<-- " else: max_index = [] maxQ = -99999999 for a in range(0, len(action_space)): if Q[s, a] != 0: if (Q[s, a] > maxQ) and (next_state(s, action_space[a]) != -1): max_index = [action_space[a]] maxQ = Q[s, a] elif (Q[s, a] == maxQ) and (next_state(s, action_space[a]) != -1): max_index.append(action_space[a]) row_string += '%12s' % str(max_index) print(row_string) def print_Q(Q): print('\n', action_index) print('Q value table:') for i in range(0, n_row): row_string = "" for j in range(0, n_col): s = i*n_col + j row_string += str(np.round(Q[s, :], 1)) + "\t" print(row_string) # ------------------ RL ALGORITHMS ----------------------------- def Double_Q_Learning_Walking(Q1, Q2, alpha=0.1, gamma=0.99, epsilon=0.05, max_episode=500, display=True): i_episode = 0 return_eps = [] while i_episode < max_episode: if display: print("Episode {} ...".format(i_episode)) S = state_initialize() i_return = 0 i_trajectory = str(S) # t = 1 while S != terminal: # A = epsilon_greedy(Q1 + Q2, S, epsilon=1/t) A = epsilon_greedy(Q1 + Q2, S, epsilon) S_, R = take_action(S, A) if np.random.rand() <= 0.5: A_ = epsilon_greedy(Q1, S_, 0) Q1[S, action_index[A]] += alpha * (R + gamma * Q2[S_, action_index[A_]] - Q1[S, action_index[A]]) else: A_ = epsilon_greedy(Q2, S_, 0) Q2[S, action_index[A]] += alpha * (R + gamma * Q1[S_, action_index[A_]] - Q2[S, action_index[A]]) i_trajectory += ' > ' + str(S_) S = S_ i_return += R # t += 1 i_episode += 1 if display: print(' trajectory = {}'.format(i_trajectory)) print(' return = {}'.format(i_return)) return_eps.append(i_return) return return_eps def Q_Learning_Walking(Q, alpha=0.1, gamma=0.99, epsilon=0.05, max_episode=500, display=True): i_episode = 0 return_eps = [] while i_episode < max_episode: if display: print("Episode {} ...".format(i_episode)) S = state_initialize() i_return = 0 i_trajectory = str(S) # t = 1 while S != terminal: # A = epsilon_greedy(Q, S, epsilon=1/t) A = epsilon_greedy(Q, S, epsilon) S_, R = take_action(S, A) A_ = epsilon_greedy(Q, S_, 0) # Let epsilon=0 to choose A_max Q[S, action_index[A]] += alpha*(R + gamma*Q[S_, action_index[A_]] - Q[S, action_index[A]]) i_trajectory += ' > ' + str(S_) S = S_ i_return += R # t += 1 i_episode += 1 if display: print(' trajectory = {}'.format(i_trajectory)) print(' return = {}'.format(i_return)) return_eps.append(i_return) return return_eps def SARSA_Walking(Q, alpha=0.1, gamma=0.99, epsilon=0.05, max_episode=500, display=True): i_episode = 0 return_eps = [] while i_episode < max_episode: if display: print("Episode #{} ...".format(i_episode)) S = state_initialize() A = epsilon_greedy(Q, S, epsilon) i_return = 0 i_trajectory = str(S) # t = 1 while S != terminal: S_, R = take_action(S, A) # A_ = epsilon_greedy(Q, S_, epsilon=1/t) A_ = epsilon_greedy(Q, S_, epsilon) Q[S, action_index[A]] += alpha*(R + gamma*Q[S_, action_index[A_]] - Q[S, action_index[A]]) i_trajectory += ' > ' + str(S_) A = A_ S = S_ i_return += R # t += 1 i_episode += 1 if display: print(' trajectory = {}'.format(i_trajectory)) print(' return = {}'.format(i_return)) return_eps.append(i_return) return return_eps # -----------------MAIN PROGRAM--------------------- Q_Sarsa = np.zeros((len(state_space), len(action_space))) return_data_2 = SARSA_Walking(Q_Sarsa, alpha=0.1, gamma=0.99, epsilon=0.001, max_episode=5000, display=False) print_policy(Q_Sarsa) print_Q(Q_Sarsa) Q_Q = np.zeros((len(state_space), len(action_space))) return_data_1 = Q_Learning_Walking(Q_Q, alpha=0.1, gamma=0.99, epsilon=0.001, max_episode=5000, display=False) print_policy(Q_Q) print_Q(Q_Q) Q1 = np.zeros((len(state_space), len(action_space))) Q2 = np.zeros((len(state_space), len(action_space))) return_data_3 = Double_Q_Learning_Walking(Q1, Q2, alpha=0.1, gamma=0.99, epsilon=0.001, max_episode=5000, display=False) print_policy((Q1+Q2)/2) print_Q((Q1+Q2)/2) def on_moving_avg(data, window): iter = 0 data_new = [] on_moving_sum = 0 for x in data: iter += 1 on_moving_sum += x if iter % window == 0: data_new.append(on_moving_sum/window) on_moving_sum = 0 return data_new def plot_return(label1=None, label2=None, label3=None, data1=None, data2=None, data3=None): if data1 != None: plt.plot(on_moving_avg(data1, 20), label=label1) if data2 != None: plt.plot(on_moving_avg(data2, 20), label=label2) if data3 != None: plt.plot(on_moving_avg(data3, 20), label=label3) plt.xlabel('iteration') plt.ylabel('return') plt.legend(loc='best') plt.show() plot_return(label1='Q Learning', label2='SARSA Learning', label3='Double Q Learning', data1=return_data_1, data2=return_data_2, data3=return_data_3) # plot_return(label1='Q Learning', label2='SARSA Learning', data1=return_data_1, data2=return_data_2)
4e336ae145eaa3304a31d18f473b045fc19fc791
quangnguyendang/Reinforcement_Learning
/Chapter07_N-Step_Bootstrapping/Off_Policy_N_Step_SARSA.py
6,999
3.875
4
# Example 7.1 page 118 in Reinforcement Learning: An Introduction Book # PhD Student: Nguyen Dang Quang, Computer Science Department, KyungHee University, Korea. # n-step SARSA for estimating Q with importance sampling factor on 100-State Random Walk import numpy as np import gym import matplotlib.pyplot as plt class RandomWalkEnv: def __init__(self, n=19, action_range=1): self.n = n self.action_range = action_range self.action_space = gym.spaces.Discrete(2*self.action_range + 1) self.state_space = gym.spaces.Discrete(self.n) self.state = np.rint(self.n/2) def reset(self): self.state = int(self.n/2) def step(self, action): done = False if (not self.action_space.contains(action)) or (not self.state_space.contains(self.state + action - self.action_range)): print("Action {} is invalid at state {}".format(action, self.state)) reward = -1000 else: self.state = self.state + action - self.action_range reward = (-1) * (self.state == 0) + (1) *(self.state == self.n - 1) done = (self.state == self.n - 1) or (self.state == 0) return self.state, reward, done class NStepSARSAAgent: def __init__(self, n=19, action_range=1, environment=RandomWalkEnv()): self.n = n self.n_action = action_range * 2 + 1 self.action_space = gym.spaces.Discrete(self.n_action) self.state_space = gym.spaces.Discrete(self.n) self.state = np.rint(self.n / 2) self.Q = np.zeros((self.n, self.n_action)) self.terminals = [0, self.n - 1] self.env = environment self.env.reset() def reset(self): self.state = int(np.rint(self.n / 2)) self.env.reset() self.Q = np.zeros((self.n, self.n_action)) def next_state(self, s, a): real_action = a - int((self.n_action - 1)/2) if self.state_space.contains(int(s + real_action)): return s + real_action else: return -1 def policy_pi(self, state, epsilon=0): if np.random.rand() <= epsilon: # Exploration a = np.random.randint(0, self.n_action) while self.next_state(state, a) == -1: a = np.random.randint(0, self.n_action) return a else: # Exploitation max_a = [] maxQ = -np.inf for a in range(0, self.n_action): if self.next_state(state, a) != -1: if self.Q[state, a] > maxQ: max_a = [a] maxQ = self.Q[state, a] elif self.Q[state, a] == maxQ: max_a.append(a) return max_a[np.random.randint(0, len(max_a))] def number_action(self, state): action_count = 0 for a in range(0, self.n_action): if self.next_state(state, a) != -1: action_count += 1 return action_count def random_walk(self, n_episode=5000, learning_rate=0.001, gamma=0.99, epsilon=1, n=1): self.reset() i_episode = 0 while i_episode < n_episode: if i_episode % 5000 == 0: print("Episode #{} is run.".format(i_episode)) self.env.reset() S = [self.state] # Initialize and store S_0 # Terminal R = [0] A = [self.policy_pi(S[0], epsilon)] # Select and store action A according to behavior policy b(.|S_0) T = self.n ** 10 # Set T = infinity t = 0 t_update = 0 while t_update < T: if t < T: S_, R_t, _ = self.env.step(A[t]) # Take action A_t R.append(R_t) # Observe and store next reward as R_(t+1) S.append(int(S_)) # Observe and store next state as S_(t+1) if S[t+1] in self.terminals: T = t + 1 # If S_(t+1) is the terminal then set T = t + 1 (the end time of the current episode) else: # Select and store next action A_(t+1) according to behavior policy b(.|S_t+1) A.append(self.policy_pi(S[t+1], epsilon)) t_update = t - n + 1 if (t_update >= 0) and (S[t_update] not in self.terminals): G = 0 p = 1.0 # Calculate importance sampling factor for i in range(t_update + 1, np.minimum(t_update + n - 1, T - 1) + 1): p *= (self.Q[S[i], A[i]] == np.max(self.Q[S[i]])) / ((1 - epsilon) + (epsilon/self.number_action(S[i]))) # p *= 1.0 / ((1 - epsilon) + (epsilon / self.number_action(S[i]))) for i in range(t_update + 1, np.minimum(t_update + n, T) + 1): G = G + (gamma**(i-t_update-1))*R[i] if t_update + n < T: G = G + (gamma**n)*self.Q[int(S[t_update + n]), int(A[t_update + n])] self.Q[int(S[t_update]), int(A[t_update])] += learning_rate*p*(G - self.Q[int(S[t_update]), int(A[t_update])]) t += 1 i_episode += 1 def get_Q(self): return self.Q def get_v(self): V = [] for s in range(self.n): max_Q = -np.inf for a in range(self.n_action): if (max_Q < self.Q[s, a]) and (self.Q[s,a] != 0): max_Q = self.Q[s, a] V.append(max_Q) return V def get_target_policy(self): A = [] for s in range(self.n): max_Q = -np.inf max_A = [] for a in range(self.n_action): if (max_Q < self.Q[s, a]) and (self.Q[s, a] != 0): max_Q = self.Q[s, a] max_A = [a - int(np.rint(self.n_action / 2)) + 1] elif (max_Q == self.Q[s, a]) and (self.Q[s, a] != 0): max_A.append(a) A.append(max_A) return A def plot_v(self): plt.plot(self.get_v(), label="N_Step SARSA Estimation") plt.xlabel('state') plt.ylabel('value') plt.legend(loc='best') plt.show() env = RandomWalkEnv(20, 2) agent1 = NStepSARSAAgent(20, 2, env) agent1.random_walk(n_episode=1000, learning_rate=0.01, gamma=0.99, epsilon=1, n=3) print(agent1.get_Q()) print(agent1.get_target_policy()) agent1.plot_v() # v_1 = agent1.get_v() # agent1.random_walk(n_episode=10000, learning_rate=0.001, gamma=0.99, epsilon=1, n=10) # v_2 = agent1.get_v() # agent1.random_walk(n_episode=10000, learning_rate=0.001, gamma=0.99, epsilon=1, n=50) # v_3 = agent1.get_v() # plt.title("n-step TD Prediction for Value Function") # plt.plot(v_1, label="TD(0)") # plt.plot(v_2, label="TD(9)") # plt.plot(v_3, label="TD(49)") # plt.xlabel('state') # plt.ylabel('value') # plt.legend(loc='best') # plt.show()
5c8f903945c896c250cb23c7c9a29c355296b3c6
LuisReal/IPC2-2021-_Proyecto1_201313965
/Menu.py
1,828
3.5
4
from Archivo import Carga from MatrizOrtogonal import MatrizOrtogonal class Menu: def __init__(self): self.archivo = "" self.ruta = "" self.nombre_terreno = "" self.obj = "" self.obj_Lista = "" self.matriz = "" def menu(self): opcion = 0 while opcion != 6: print("\nMenu Principal: \n1.Cargar Archivo \n2.Procesar Archivo \n3.Escribir Archivo Salida" "\n4.Mostrar datos del estudiante" "\n5.Generar Grafica" "\n6.Salida") opcion = int(input("Ingrese una opcion \n")) if opcion == 1: self.ruta = input("Ingrese la ruta del archivo: ") print("\nSe cargo la ruta del archivo exitosamente\n") elif opcion == 2: print("el archivo se esta procesando\n") self.nombre_terreno = input("Ingrese el nombre del terreno a procesar: ") self.obj = Carga() self.obj.archivo(self.ruta, self.nombre_terreno) elif opcion == 3: print("va a escribir el archivo\n") elif opcion == 4: print("Luis Fernando Gonzalez Real \n201313965 \nIntroduccion a la Programacion y Computacion 2 seccion E" "\nIngenieria en Ciencias y Sistemas \n4to Semestre \n") elif opcion == 5: print("mostrar grafica \n") elif opcion == 6: print("salio") else: print("\nIngresa una opcion correcta \n") obj = Menu() obj.menu()
bd29943434b3033b2cb00d501b398a2426fef021
LuisReal/IPC2-2021-_Proyecto1_201313965
/ListaVertical.py
1,509
3.625
4
from NodoOrtogonal import Nodo class Lista_V: def __init__(self): self.primero = None self.ultimo = None self.size = 0 def vacia(self): return self.primero == None def insertar(self, dato, x, y): nodo_nuevo = Nodo(dato, x, y) if self.vacia() == True: self.primero = self.ultimo = nodo_nuevo elif nodo_nuevo.y < self.primero.y: self.agregar_inicio(dato, x, y) elif nodo_nuevo.y > self.ultimo.y: self.agregar_final(dato, x, y) #else: #print('Hello World') #self.agregar_medio() def agregar_inicio(self, dato, x, y): aux = Nodo(dato, x, y) self.primero.arriba = aux aux.abajo = self.primero self.primero = aux def agregar_final(self, dato, x, y): aux = Nodo(dato,x,y) self.ultimo.abajo = aux aux.arriba = self.ultimo self.ultimo = aux def recorrer_inicio(self): current = self.primero while current: # mientras que aux != None (mientras que el nodo no este vacio) print('(',current.dato, ' x:' ,current.x, ' y:' ,current.y,')', end = " => ") current = current.abajo def recorrer_fin(self): current = self.ultimo while current: # mientras que aux != None print('(',current.dato, ' x:' ,current.x, ' y:' ,current.y,')', end = " => ") current = current.arriba
67a9bd1a092034f593be8f146ba6c417a526d6d1
Aditya-kiran/AI-and-ML
/team_lecture/untitled.py
140
3.734375
4
while True: prompt = "%s words: " % 3 sentence = input(prompt) sentence = sentence.strip() words = sentence.split(' ') print(sentence)
10b5e6f0afaaf53fd5139ef91ea65db5ac20545d
TheS1lentArr0w/Milestone-Project-2
/blackjack.py
7,819
3.78125
4
''' BlackJack Card Game ''' # Imports import random # Global variables that will be useful throughout the code suits = ('Hearts', 'Diamonds', 'Spades', 'Clubs') ranks = ('Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'Jack', 'Queen', 'King', 'Ace') values = {'Two':2, 'Three':3, 'Four':4, 'Five':5, 'Six':6, 'Seven':7, 'Eight':8, 'Nine':9, 'Ten':10, 'Jack':10, 'Queen':10, 'King':10, 'Ace':11} ### Creation of required objects # Creation of Card class class Card: def __init__(self,suit,rank): self.suit = suit self.rank = rank self.value = values[rank] def __str__(self): return f"{self.rank} of {self.suit}" # Creation of Deck class class Deck: def __init__(self): self.all_cards = [] for suit in suits: for rank in ranks: # Create each card object and add it to the deck created_card = Card(suit,rank) self.all_cards.append(created_card) def shuffle(self): random.shuffle(self.all_cards) print("The deck has been shuffled!") def deal_one(self): return self.all_cards.pop() # Creation of Player class class Player: def __init__(self,bankroll): self.all_cards = [] self.bankroll = bankroll def remove_one(self): return self.all_cards.pop(0) def add_cards(self,new_cards): if type(new_cards) == type([]): # list of multiple Card objects # PROBABLY WON'T NEED THIS CASE BUT HANDY FOR NOW self.all_cards.extend(new_cards) else: # for a single Card object self.all_cards.append(new_cards) # Creation of Dealer class class Dealer(Player): def __init__(self): self.all_cards = [] # Due to inheritance, Dealer will also have 'remove_one' and 'add_cards' methods. # Redefining __init__ call as Dealer does not require a bankroll. ### Creation of required functions # Player input for bet # Check for errors e.g. has to be int, minimum 100, cannot exceed bankroll def player_bet(bankroll): choice = "WRONG" greater_than_min = False not_exceeding = False while choice.isdigit()==False or greater_than_min==False or not_exceeding==False: choice = input("How much will you bet? (Minimum bet = 100): ") # Digit check if choice.isdigit() == False: print("Sorry, that is not a digit!") # Greater than 100 check if choice.isdigit() == True: if int(choice) > 100: greater_than_min = True else: print("Sorry! The minimum bet is 100!") greater_than_min = False # Not exceeding bankroll check if choice.isdigit() == True: if greater_than_min == True: if int(choice )< bankroll: not_exceeding = True else: print("Sorry, that bet is more than what you have!") not_exceeding = False return int(choice) # Player input for hit or stay def player_choice(): choice = "WRONG" acceptable_values = ["hit","stay"] while choice not in acceptable_values: choice = input("Do you choose to hit or stay? (Please enter 'hit' or 'stay'): ") if choice not in acceptable_values: print("Sorry, I do not understand. Please enter 'hit' or 'stay'.") return choice # Player input for playing again def play_again(): choice = "WRONG" acceptable_values = ['y','n'] while choice not in acceptable_values: choice = input("Do you want to play again? ('y' or 'n'): ") if choice not in acceptable_values: print("Sorry, I do not understand. Please enter 'y' or 'n'.") return choice # Getting total value def get_total_value(all_cards): total_value = 0 aces = 0 for card in all_cards: total_value += card.value if card.rank == 'Ace': aces += 1 while aces > 0 and total_value > 21: total_value -= 10 aces -= 1 return total_value ##### MAIN GAME LOGIC playing = True ### Initiate game print("Welcome to Blackjack!") new_deck = Deck() # Shuffle deck new_deck.shuffle() # Player initiate new_player = Player(1000) # Dealer initiate new_dealer = Dealer() ### Main game loop while playing: # Display bankroll print(f"Your current bankroll is: {new_player.bankroll}") # Check if Player is broke if new_player.bankroll < 100: print("Sorry, you do not have enough money to play!") playing = False break # Ask for bet bet = player_bet(new_player.bankroll) # Deal cards, one each twice. for i in [1,2]: new_player.all_cards.append(new_deck.deal_one()) new_dealer.all_cards.append(new_deck.deal_one()) print("The cards have been dealt!") # Show 1 card from the dealer print("Dealer cards:") print(new_dealer.all_cards[0]) print("UNKNOWN") # Show both cards from the player print("Player cards:") for card in new_player.all_cards: print(card) # Loop for Player's turn bust = False while bust == False: # Ask for player choice choice = player_choice() if choice == "hit": new_player.all_cards.append(new_deck.deal_one()) else: # if player chose 'stay' break # Display cards again print("Player cards:") for card in new_player.all_cards: print(card) # Check for bust total_value = get_total_value(new_player.all_cards) if total_value > 21: print("Bust!") bust = True break # Loop for Dealer's turn dealer_bust = False while dealer_bust == False: # if total_value >= 17, stay. Else, hit. total_value = get_total_value(new_dealer.all_cards) if total_value < 17: # hit new_dealer.all_cards.append(new_deck.deal_one()) elif total_value >= 17 and total_value <= 21: # stay break else: # bust print("Dealer has bust!") dealer_bust = True break # Reveal cards print("The player and the dealer have ended their turn.") # Dealer cards print("Dealer cards:") for card in new_dealer.all_cards: print(card) print(f"The value of the dealer's hand = {get_total_value(new_dealer.all_cards)}") # Player cards print("Player cards:") for card in new_player.all_cards: print(card) print(f"The value of the player's hand = {get_total_value(new_player.all_cards)}") ### Checking game outcomes # Checking if player bust if bust == True: # Player bust # Player lose, subtract 2xbet from player bankroll new_player.bankroll -= 2*bet # Checking if dealer bust if bust == False and dealer_bust == True: # Dealer bust but player doesn't bust # Player win new_player.bankroll += 2*bet # Neither bust. Compare total_values player_total = get_total_value(new_player.all_cards) dealer_total = get_total_value(new_dealer.all_cards) if player_total > dealer_total: # Player win new_player.bankroll += 2*bet elif player_total < dealer_total: # Player lose new_player.bankroll -= 2*bet else: # Tie # No money lost or gained pass # Updated bankroll print(f"Your updated bankroll is: {new_player.bankroll}") # Play again? choice = play_again() if choice == 'y': pass else: playing = False break
9efd80a345662fcd6e8b4631d99d8f9d903a8fae
isaigm/leetcode
/search-insert-position/Accepted/3-16-2020, 1_10_28 PM/Solution.py
245
3.640625
4
// https://leetcode.com/problems/search-insert-position class Solution: def searchInsert(self, nums: List[int], target: int) -> int: for idx in range(len(nums)): if nums[idx] >= target : return idx return idx + 1
f240c65c8bd83da8bd36fe1c01a5ba0bb1ab4d19
isaigm/leetcode
/word-pattern/Wrong Answer/9-8-2020, 1_56_05 AM/Solution.py
411
3.578125
4
// https://leetcode.com/problems/word-pattern class Solution: def wordPattern(self, pattern: str, strr: str) -> bool: words = strr.split(' ') l1 = len(pattern) for i in range(l1 - 1): if pattern[i] == pattern[i + 1]: if words[i] != words[i + 1]: return False else: if words[i] == words[i + 1]: return False return True
326c1d3a8e1ce7610bbf26b92d0ee957a03e291a
isaigm/leetcode
/remove-nth-node-from-end-of-list/Accepted/3-17-2020, 4_29_10 PM/Solution.py
925
3.65625
4
// https://leetcode.com/problems/remove-nth-node-from-end-of-list # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode: size = 0 ptr = head while ptr != None: ptr = ptr.next size += 1 idx = 0 if size == n: next_node = head.next head = None head = next_node return head else: ptr = head prev = None while idx < (size - n): prev = ptr ptr = ptr.next idx += 1 if ptr.next == None: prev.next = None ptr = None else: prev.next = ptr.next ptr = None return head
38c3d2fe9e2e777e20a86dd6e19ece406bb05e50
isaigm/leetcode
/word-break/Wrong Answer/5-30-2021, 10_09_10 AM/Solution.py
244
3.671875
4
// https://leetcode.com/problems/word-break class Solution: def wordBreak(self, s: str, wordDict: List[str]) -> bool: large_string = "" for word in wordDict: large_string += word return s in large_string
d830adc3169ec263a5043079c99d8a8a65cda037
orrettb/python_fundamental_course
/02_basic_datatypes/2_strings/02_11_slicing.py
562
4.40625
4
''' Using string slicing, take in the user's name and print out their name translated to pig latin. For the purpose of this program, we will say that any word or name can be translated to pig latin by moving the first letter to the end, followed by "ay". For example: ryan -> yanray, caden -> adencay ''' #take the users name via input user_name = input("Enter your first name:") #select the first letter fist_letter = user_name[0] #add pig latin variable pig_value = "ay" pig_latin_ver = user_name[1:]+fist_letter+pig_value #print result print(pig_latin_ver)
fc9692fb7de66bc5a8ae7102e7b19325fb8eb88b
yywxenia/MachineLearningProj
/ML_Algorithms/RandomOptimi/ml2_code/optim_alg.py
4,017
3.9375
4
### Implement optimization algorithms: reference from Programming Collective Intelligence ### ============================================================================================= import random import math #----------------------------------------------------------------------------------------- # Hill climb def hill_climb(domain, cost_func): ## Generates a random list of numbers in the given domain to create the initial solution # Create a random solution sol = [random.randint(domain[idx][0], domain[idx][1]) for idx in range(len(domain))] # build a random pop # main loop while True: neighbors = [] for j in range( len(domain) ): if sol[j] > domain[j][0]: #print(sol[j],domain[j][0]) neighbors.append(sol[0:j] + [sol[j]-1] + sol[j+1:]) if sol[j] < domain[j][1]: neighbors.append(sol[0:j] + [sol[j]+1] + sol[j+1:]) # See what the best solution amongst the neighbors is current = cost_func(sol) best = current for j in range( len(neighbors) ): cost = cost_func( neighbors[j] ) if cost < best: best = cost sol = neighbors[j] # If there's no improvement, then we've reached the top if best == current: break return sol #----------------------------------------------------------------------------------------- # Simulated Annealing: def anneal_optim(domain, costfunc, T, cool, step): vec = [ random.randint(domain[i][0], domain[i][1]) for i in range(len(domain)) ] while T > 0.1: i = random.randint(0, len(domain)-1) dir = random.randint(-step, step) vecb = vec[:] vecb[i] += dir if vecb[i] < domain[i][0]: vecb[i] = domain[i][0] elif vecb[i] > domain[i][1]: vecb[i] = domain[i][1] ea = costfunc(vec) # lower cost eb = costfunc(vecb) # higher cost p = pow(math.e, (-eb - ea)/T) # The probability of a higher-cost solution being accepted: if (eb < ea or random.random() < p): vec = vecb T = T*cool # Decrease the temperature return vec #----------------------------------------------------------------------------------------- ## GA: def GA(domain, costfunc, popsize, step, mutprob, elite, maxiter=100): def mutate(vec): i = random.randint(0, len(domain)-1) if random.random() < 0.5 and vec[i] > domain[i][0]: return vec[0:i] + [vec[i] - step] + vec[i+1: ] elif vec[i] < domain[i][1]: return vec[0:i] + [vec[i] + step] + vec[i+1: ] else: return vec def crossover(r1, r2): i = random.randint(0, len(domain)-2) return r1[0:i] + r2[i:] # Initially create a set of random solutions known as the "population" pop = [] for i in range(popsize): vec = [ random.randint(domain[idx][0], domain[idx][1]) for idx in range(len(domain)) ] pop.append(vec) # How many winners from each generation topelite = int( elite * popsize) # Winner of every generation == wining rate * population size # main loop for i in range(maxiter): scores = [ (costfunc(v),v) for v in pop ] scores.sort() ranked = [ v for (s,v) in scores ] # Start with the pure winners pop = ranked[0:topelite] # Add mutated and bred forms of the winners while len(pop) < popsize: if random.random() < mutprob: # mutation idx = random.randint(0, topelite) pop.append( mutate(ranked[idx]) ) else: # crossover idx1 = random.randint(0, topelite) idx2 = random.randint(0, topelite) pop.append( crossover(ranked[idx1], ranked[idx2])) # #Print current best score # print scores[0][0] return scores[0][1]
ff3eab60580e342b83fa05e6bd111177cc5a53e5
ghiyaath/Error-handling
/main.py
1,453
3.71875
4
from tkinter import * from tkinter import messagebox # The info for the window window = Tk() window.title("Verify Form") window.geometry("540x340") window.resizable(False, False) window.config(bg="red") user_pass = {'Ghiyaath': 'Zaeemgee', 'Jaydenmay': 'jaydenmay', 'Shuaib': 'Biggun', 'Zoe': 'Foodislife'} entry1 = Label(window, text="Username", bg="violet") entry1.place(x=50, y=50) entry1 = Entry(window) entry1.place(x=200, y=50) entry2 = Label(window, text="Password", bg="violet") entry2.place(x=50, y=100) entry2 = Entry(window) entry2.place(x=200, y=100) def verification(): username = entry1.get() password = entry2.get() if username in user_pass: pw = user_pass.get(username) if pw == password: window.destroy() import main2 else: messagebox.showerror(message="Username and password does not match") else: messagebox.showerror(message="Username does not exist") def delete(): entry1.delete(0, 'end') entry2.config(state="normal") entry2.delete(0, END) verify = Button(window, text="verify", width=15, command=verification, bg="orange", borderwidth="5").place(x=40, y=200) clear = Button(window, text="Clear", width=15, command=delete, bg="aqua", borderwidth="5").place(x=200, y=200) quit = Button(window, text="Exit", width=15, command="exit", bg="blue", borderwidth="5").place(x=360, y=200) window.mainloop()
019115d2d0a51ab08b0a0ef0eb8e24dc31e98ecb
June-lizj/code-practice
/src/Offer-Python/Code006_Fibonacci.py
954
3.578125
4
# 大家都知道斐波那契数列,现在要求输入一个整数n, # 请你输出斐波那契数列的第n项(从0开始,第0项为0)。 # n<=39 class Solution: def Fibonacci(self, n): result = [0,1] if n < 2: return result[n] # for i in range(2,n+1): # result.append(result[i-1]+result[i-2]) while len(result) < n+1: result.append(result[-1]+result[-2]) return result[n] s = Solution() print(s.Fibonacci(6)) # class Solution: # def Fibonacci(self, n): # if n < 2: # return n # return self.Fibonacci(n - 1) + self.Fibonacci(n - 2) # Fibonacci(4) = Fibonacci(3) + Fibonacci(2); # = Fibonacci(2) + Fibonacci(1) + Fibonacci(1) + Fibonacci(0); # = Fibonacci(1) + Fibonacci(0) + Fibonacci(1) + Fibonacci(1) + Fibonacci(0); # 简单递归重复计算严重,n稍微大一点就会花很多时间
610caef7eb530369d1d5467b6d5d5f1e10456eec
June-lizj/code-practice
/src/Offer-Python/Code013_ReverseList.py
943
4.03125
4
# 输入一个链表,反转链表后,输出新链表的表头。 class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: # 返回ListNode def ReverseList(self, pHead): if pHead == None or pHead.next == None: return pHead pre = self.ReverseList(pHead.next) pHead.next.next = pHead pHead.next = None return pre a = ListNode(1) b = ListNode(2) c = ListNode(3) d = ListNode(4) e = ListNode(5) a.next = b b.next = c c.next = d d.next = e s = Solution() print(s.ReverseList(a).next.val) # class Solution: # # 返回ListNode # def ReverseList(self, pHead): # if pHead == None or pHead.next == None: # return pHead # pre = None # cur = pHead # while cur: # temp = cur.next # cur.next = pre # pre = cur # cur = temp # return pre
851ac765a242ede13f482b0a971793ccfd2fc403
luuuumen/algorithm013
/Week_04/jump_games.py
277
3.546875
4
# coding:utf-8 class Solution(object): def canJump(self, nums): """ :type nums: List[int] :rtype: bool """ ep = len(nums) - 1 for i in range(len(nums)-1,-1,-1): if nums[i] + i >= ep: ep = i return ep == 0
a3e375e0ff88ff9487a9ed5035949bcc83bf268d
SalmanStarneo/OOP-201920
/lab2_types_and_strings.py
3,123
4.25
4
#course: Object-oriented programming, year 2, semester 1 #academic year: 201920 #author: B. Schoen-Phelan #date: 29-09-2019 #purpose: Lab 2 class Types_and_Strings: def __init__(self): pass def play_with_strings(self): # working with strings message = input("Enter your name: ") print("\nOriginally entered: "+ message) print('\nfirst letter:'+message[:1]) print('\nlast letter:'+message[-1:]) # # print only first and last of the sentence # first = message[:1] print("\n\t1-He said \n \"that's fantastic \"") # last = message[-1:1] # print("The last character is:",last) # use slice notation print('\nthe amount of a in your name = ',message.count('a')) letter=input('\n now Enter the letter you want to look for within your name:') Value=message.find(letter) if(Value!=-1): print('\n The letter ',letter,' is found in position',(Value+1)) else: print('\n The letter ',letter,' does not exist in the name') # escaping a character print("\n The letters in your name adds up to:",len(message)," letters") Xletter=input('\n Enter a letter you want to replace a in your name:') nameExtra=message.replace('a',Xletter) print(nameExtra) # find all a's in the input word and count how many there are print('//////////////////////////////') for i in range(0,len(message),2): print(message[i]) print('////////////////////////////') # replace all occurences of the character a with the - sign # try this first by assignment of a location in a string and # observe what happens, then use replace() # printing only characters at even index positions def play_with_lists(self): message = input("Please enter a whole sentence: ") print("Originally entered: "+ message) # hand the input string to a list and print it out XList=message.split(' ') print("\n",XList) # append a new element to the list and print newitem=input("\n Please enter an item to the list:") XList.append(newitem) print('\n',XList) # remove from the list in 3 ways print('\nnow the item that just been added will be removed\n') print(XList.pop(),'\n',XList) # check if the word cake is in your input list #lent=len(XList) for i in XList: if any("cake" for i in XList): print('\n you seems to have found the stash of cake\n') break else: print('\nNo sweets for you \n') print(XList*3) X2List=XList X2List.reverse() print('\n',X2List) # reverse the items in the list and print # reverse the list with the slicing trick # print the list 3 times by using multiplication tas = Types_and_Strings() #tas.play_with_strings() tas.play_with_lists()
425e5fa45d638c81352a74191a76c7057810c2c0
Textualize/textual
/src/textual/_time.py
1,435
3.59375
4
import asyncio import platform from asyncio import sleep as asyncio_sleep from time import monotonic, perf_counter PLATFORM = platform.system() WINDOWS = PLATFORM == "Windows" if WINDOWS: time = perf_counter else: time = monotonic if WINDOWS: # sleep on windows as a resolution of 15ms # Python3.11 is somewhat better, but this home-grown version beats it # Deduced from practical experiments from ._win_sleep import sleep as win_sleep async def sleep(secs: float) -> None: """Sleep for a given number of seconds. Args: secs: Number of seconds to sleep for. """ await asyncio.create_task(win_sleep(secs)) else: async def sleep(secs: float) -> None: """Sleep for a given number of seconds. Args: secs: Number of seconds to sleep for. """ # From practical experiments, asyncio.sleep sleeps for at least half a millisecond too much # Presumably there is overhead asyncio itself which accounts for this # We will reduce the sleep to compensate, and also don't sleep at all for less than half a millisecond sleep_for = secs - 0.0005 if sleep_for > 0: await asyncio_sleep(sleep_for) get_time = time """Get the current wall clock (monotonic) time. Returns: The value (in fractional seconds) of a monotonic clock, i.e. a clock that cannot go backwards. """
acea5b1f940289d35ff1c7a2df77627eac7543ce
Textualize/textual
/src/textual/geometry.py
35,140
3.609375
4
""" Functions and classes to manage terminal geometry (anything involving coordinates or dimensions). """ from __future__ import annotations from functools import lru_cache from operator import attrgetter, itemgetter from typing import ( TYPE_CHECKING, Any, Collection, NamedTuple, Tuple, TypeVar, Union, cast, ) from typing_extensions import Final if TYPE_CHECKING: from typing_extensions import TypeAlias SpacingDimensions: TypeAlias = Union[ int, Tuple[int], Tuple[int, int], Tuple[int, int, int, int] ] """The valid ways in which you can specify spacing.""" T = TypeVar("T", int, float) def clamp(value: T, minimum: T, maximum: T) -> T: """Adjust a value so it is not less than a minimum and not greater than a maximum value. Args: value: A value. minimum: Minimum value. maximum: Maximum value. Returns: New value that is not less than the minimum or greater than the maximum. """ if minimum > maximum: maximum, minimum = minimum, maximum if value < minimum: return minimum elif value > maximum: return maximum else: return value class Offset(NamedTuple): """A cell offset defined by x and y coordinates. Offsets are typically relative to the top left of the terminal or other container. Textual prefers the names `x` and `y`, but you could consider `x` to be the _column_ and `y` to be the _row_. Offsets support addition, subtraction, multiplication, and negation. Example: ```python >>> from textual.geometry import Offset >>> offset = Offset(3, 2) >>> offset Offset(x=3, y=2) >>> offset += Offset(10, 0) >>> offset Offset(x=13, y=2) >>> -offset Offset(x=-13, y=-2) ``` """ x: int = 0 """Offset in the x-axis (horizontal)""" y: int = 0 """Offset in the y-axis (vertical)""" @property def is_origin(self) -> bool: """Is the offset at (0, 0)?""" return self == (0, 0) @property def clamped(self) -> Offset: """This offset with `x` and `y` restricted to values above zero.""" x, y = self return Offset(0 if x < 0 else x, 0 if y < 0 else y) def __bool__(self) -> bool: return self != (0, 0) def __add__(self, other: object) -> Offset: if isinstance(other, tuple): _x, _y = self x, y = other return Offset(_x + x, _y + y) return NotImplemented def __sub__(self, other: object) -> Offset: if isinstance(other, tuple): _x, _y = self x, y = other return Offset(_x - x, _y - y) return NotImplemented def __mul__(self, other: object) -> Offset: if isinstance(other, (float, int)): x, y = self return Offset(int(x * other), int(y * other)) return NotImplemented def __neg__(self) -> Offset: x, y = self return Offset(-x, -y) def blend(self, destination: Offset, factor: float) -> Offset: """Calculate a new offset on a line between this offset and a destination offset. Args: destination: Point where factor would be 1.0. factor: A value between 0 and 1.0. Returns: A new point on a line between self and destination. """ x1, y1 = self x2, y2 = destination return Offset( int(x1 + (x2 - x1) * factor), int(y1 + (y2 - y1) * factor), ) def get_distance_to(self, other: Offset) -> float: """Get the distance to another offset. Args: other: An offset. Returns: Distance to other offset. """ x1, y1 = self x2, y2 = other distance: float = ((x2 - x1) * (x2 - x1) + (y2 - y1) * (y2 - y1)) ** 0.5 return distance class Size(NamedTuple): """The dimensions (width and height) of a rectangular region. Example: ```python >>> from textual.geometry import Size >>> size = Size(2, 3) >>> size Size(width=2, height=3) >>> size.area 6 >>> size + Size(10, 20) Size(width=12, height=23) ``` """ width: int = 0 """The width in cells.""" height: int = 0 """The height in cells.""" def __bool__(self) -> bool: """A Size is Falsy if it has area 0.""" return self.width * self.height != 0 @property def area(self) -> int: """The area occupied by a region of this size.""" return self.width * self.height @property def region(self) -> Region: """A region of the same size, at the origin.""" width, height = self return Region(0, 0, width, height) @property def line_range(self) -> range: """A range object that covers values between 0 and `height`.""" return range(self.height) def __add__(self, other: object) -> Size: if isinstance(other, tuple): width, height = self width2, height2 = other return Size(max(0, width + width2), max(0, height + height2)) return NotImplemented def __sub__(self, other: object) -> Size: if isinstance(other, tuple): width, height = self width2, height2 = other return Size(max(0, width - width2), max(0, height - height2)) return NotImplemented def contains(self, x: int, y: int) -> bool: """Check if a point is in area defined by the size. Args: x: X coordinate. y: Y coordinate. Returns: True if the point is within the region. """ width, height = self return width > x >= 0 and height > y >= 0 def contains_point(self, point: tuple[int, int]) -> bool: """Check if a point is in the area defined by the size. Args: point: A tuple of x and y coordinates. Returns: True if the point is within the region. """ x, y = point width, height = self return width > x >= 0 and height > y >= 0 def __contains__(self, other: Any) -> bool: try: x: int y: int x, y = other except Exception: raise TypeError( "Dimensions.__contains__ requires an iterable of two integers" ) width, height = self return width > x >= 0 and height > y >= 0 class Region(NamedTuple): """Defines a rectangular region. A Region consists of a coordinate (x and y) and dimensions (width and height). ``` (x, y) ┌────────────────────┐ ▲ │ │ │ │ │ │ │ │ height │ │ │ │ │ │ └────────────────────┘ ▼ ◀─────── width ──────▶ ``` Example: ```python >>> from textual.geometry import Region >>> region = Region(4, 5, 20, 10) >>> region Region(x=4, y=5, width=20, height=10) >>> region.area 200 >>> region.size Size(width=20, height=10) >>> region.offset Offset(x=4, y=5) >>> region.contains(1, 2) False >>> region.contains(10, 8) True ``` """ x: int = 0 """Offset in the x-axis (horizontal).""" y: int = 0 """Offset in the y-axis (vertical).""" width: int = 0 """The width of the region.""" height: int = 0 """The height of the region.""" @classmethod def from_union(cls, regions: Collection[Region]) -> Region: """Create a Region from the union of other regions. Args: regions: One or more regions. Returns: A Region that encloses all other regions. """ if not regions: raise ValueError("At least one region expected") min_x = min(regions, key=itemgetter(0)).x max_x = max(regions, key=attrgetter("right")).right min_y = min(regions, key=itemgetter(1)).y max_y = max(regions, key=attrgetter("bottom")).bottom return cls(min_x, min_y, max_x - min_x, max_y - min_y) @classmethod def from_corners(cls, x1: int, y1: int, x2: int, y2: int) -> Region: """Construct a Region form the top left and bottom right corners. Args: x1: Top left x. y1: Top left y. x2: Bottom right x. y2: Bottom right y. Returns: A new region. """ return cls(x1, y1, x2 - x1, y2 - y1) @classmethod def from_offset(cls, offset: tuple[int, int], size: tuple[int, int]) -> Region: """Create a region from offset and size. Args: offset: Offset (top left point). size: Dimensions of region. Returns: A region instance. """ x, y = offset width, height = size return cls(x, y, width, height) @classmethod def get_scroll_to_visible( cls, window_region: Region, region: Region, *, top: bool = False ) -> Offset: """Calculate the smallest offset required to translate a window so that it contains another region. This method is used to calculate the required offset to scroll something in to view. Args: window_region: The window region. region: The region to move inside the window. top: Get offset to top of window. Returns: An offset required to add to region to move it inside window_region. """ if region in window_region and not top: # Region is already inside the window, so no need to move it. return NULL_OFFSET window_left, window_top, window_right, window_bottom = window_region.corners region = region.crop_size(window_region.size) left, top_, right, bottom = region.corners delta_x = delta_y = 0 if not ( (window_right > left >= window_left) and (window_right > right >= window_left) ): # The region does not fit # The window needs to scroll on the X axis to bring region in to view delta_x = min( left - window_left, left - (window_right - region.width), key=abs, ) if top: delta_y = top_ - window_top elif not ( (window_bottom > top_ >= window_top) and (window_bottom > bottom >= window_top) ): # The window needs to scroll on the Y axis to bring region in to view delta_y = min( top_ - window_top, top_ - (window_bottom - region.height), key=abs, ) return Offset(delta_x, delta_y) def __bool__(self) -> bool: """A Region is considered False when it has no area.""" _, _, width, height = self return width * height > 0 @property def column_span(self) -> tuple[int, int]: """A pair of integers for the start and end columns (x coordinates) in this region. The end value is *exclusive*. """ return (self.x, self.x + self.width) @property def line_span(self) -> tuple[int, int]: """A pair of integers for the start and end lines (y coordinates) in this region. The end value is *exclusive*. """ return (self.y, self.y + self.height) @property def right(self) -> int: """Maximum X value (non inclusive).""" return self.x + self.width @property def bottom(self) -> int: """Maximum Y value (non inclusive).""" return self.y + self.height @property def area(self) -> int: """The area under the region.""" return self.width * self.height @property def offset(self) -> Offset: """The top left corner of the region. Returns: An offset. """ return Offset(*self[:2]) @property def center(self) -> tuple[float, float]: """The center of the region. Note, that this does *not* return an `Offset`, because the center may not be an integer coordinate. Returns: Tuple of floats. """ x, y, width, height = self return (x + width / 2.0, y + height / 2.0) @property def bottom_left(self) -> Offset: """Bottom left offset of the region. Returns: An offset. """ x, y, _width, height = self return Offset(x, y + height) @property def top_right(self) -> Offset: """Top right offset of the region. Returns: An offset. """ x, y, width, _height = self return Offset(x + width, y) @property def bottom_right(self) -> Offset: """Bottom right offset of the region. Returns: An offset. """ x, y, width, height = self return Offset(x + width, y + height) @property def size(self) -> Size: """Get the size of the region.""" return Size(*self[2:]) @property def corners(self) -> tuple[int, int, int, int]: """The top left and bottom right coordinates as a tuple of four integers.""" x, y, width, height = self return x, y, x + width, y + height @property def column_range(self) -> range: """A range object for X coordinates.""" return range(self.x, self.x + self.width) @property def line_range(self) -> range: """A range object for Y coordinates.""" return range(self.y, self.y + self.height) @property def reset_offset(self) -> Region: """An region of the same size at (0, 0). Returns: A region at the origin. """ _, _, width, height = self return Region(0, 0, width, height) def __add__(self, other: object) -> Region: if isinstance(other, tuple): ox, oy = other x, y, width, height = self return Region(x + ox, y + oy, width, height) return NotImplemented def __sub__(self, other: object) -> Region: if isinstance(other, tuple): ox, oy = other x, y, width, height = self return Region(x - ox, y - oy, width, height) return NotImplemented def at_offset(self, offset: tuple[int, int]) -> Region: """Get a new Region with the same size at a given offset. Args: offset: An offset. Returns: New Region with adjusted offset. """ x, y = offset _x, _y, width, height = self return Region(x, y, width, height) def crop_size(self, size: tuple[int, int]) -> Region: """Get a region with the same offset, with a size no larger than `size`. Args: size: Maximum width and height (WIDTH, HEIGHT). Returns: New region that could fit within `size`. """ x, y, width1, height1 = self width2, height2 = size return Region(x, y, min(width1, width2), min(height1, height2)) def expand(self, size: tuple[int, int]) -> Region: """Increase the size of the region by adding a border. Args: size: Additional width and height. Returns: A new region. """ expand_width, expand_height = size x, y, width, height = self return Region( x - expand_width, y - expand_height, width + expand_width * 2, height + expand_height * 2, ) def clip_size(self, size: tuple[int, int]) -> Region: """Clip the size to fit within minimum values. Args: size: Maximum width and height. Returns: No region, not bigger than size. """ x, y, width, height = self max_width, max_height = size return Region(x, y, min(width, max_width), min(height, max_height)) @lru_cache(maxsize=1024) def overlaps(self, other: Region) -> bool: """Check if another region overlaps this region. Args: other: A Region. Returns: True if other region shares any cells with this region. """ x, y, x2, y2 = self.corners ox, oy, ox2, oy2 = other.corners return ((x2 > ox >= x) or (x2 > ox2 > x) or (ox < x and ox2 >= x2)) and ( (y2 > oy >= y) or (y2 > oy2 > y) or (oy < y and oy2 >= y2) ) def contains(self, x: int, y: int) -> bool: """Check if a point is in the region. Args: x: X coordinate. y: Y coordinate. Returns: True if the point is within the region. """ self_x, self_y, width, height = self return (self_x + width > x >= self_x) and (self_y + height > y >= self_y) def contains_point(self, point: tuple[int, int]) -> bool: """Check if a point is in the region. Args: point: A tuple of x and y coordinates. Returns: True if the point is within the region. """ x1, y1, x2, y2 = self.corners try: ox, oy = point except Exception: raise TypeError(f"a tuple of two integers is required, not {point!r}") return (x2 > ox >= x1) and (y2 > oy >= y1) @lru_cache(maxsize=1024) def contains_region(self, other: Region) -> bool: """Check if a region is entirely contained within this region. Args: other: A region. Returns: True if the other region fits perfectly within this region. """ x1, y1, x2, y2 = self.corners ox, oy, ox2, oy2 = other.corners return ( (x2 >= ox >= x1) and (y2 >= oy >= y1) and (x2 >= ox2 >= x1) and (y2 >= oy2 >= y1) ) @lru_cache(maxsize=1024) def translate(self, offset: tuple[int, int]) -> Region: """Move the offset of the Region. Args: offset: Offset to add to region. Returns: A new region shifted by (x, y) """ self_x, self_y, width, height = self offset_x, offset_y = offset return Region(self_x + offset_x, self_y + offset_y, width, height) @lru_cache(maxsize=4096) def __contains__(self, other: Any) -> bool: """Check if a point is in this region.""" if isinstance(other, Region): return self.contains_region(other) else: try: return self.contains_point(other) except TypeError: return False def clip(self, width: int, height: int) -> Region: """Clip this region to fit within width, height. Args: width: Width of bounds. height: Height of bounds. Returns: Clipped region. """ x1, y1, x2, y2 = self.corners _clamp = clamp new_region = Region.from_corners( _clamp(x1, 0, width), _clamp(y1, 0, height), _clamp(x2, 0, width), _clamp(y2, 0, height), ) return new_region @lru_cache(maxsize=4096) def grow(self, margin: tuple[int, int, int, int]) -> Region: """Grow a region by adding spacing. Args: margin: Grow space by `(<top>, <right>, <bottom>, <left>)`. Returns: New region. """ if not any(margin): return self top, right, bottom, left = margin x, y, width, height = self return Region( x=x - left, y=y - top, width=max(0, width + left + right), height=max(0, height + top + bottom), ) @lru_cache(maxsize=4096) def shrink(self, margin: tuple[int, int, int, int]) -> Region: """Shrink a region by subtracting spacing. Args: margin: Shrink space by `(<top>, <right>, <bottom>, <left>)`. Returns: The new, smaller region. """ if not any(margin): return self top, right, bottom, left = margin x, y, width, height = self return Region( x=x + left, y=y + top, width=max(0, width - (left + right)), height=max(0, height - (top + bottom)), ) @lru_cache(maxsize=4096) def intersection(self, region: Region) -> Region: """Get the overlapping portion of the two regions. Args: region: A region that overlaps this region. Returns: A new region that covers when the two regions overlap. """ # Unrolled because this method is used a lot x1, y1, w1, h1 = self cx1, cy1, w2, h2 = region x2 = x1 + w1 y2 = y1 + h1 cx2 = cx1 + w2 cy2 = cy1 + h2 rx1 = cx2 if x1 > cx2 else (cx1 if x1 < cx1 else x1) ry1 = cy2 if y1 > cy2 else (cy1 if y1 < cy1 else y1) rx2 = cx2 if x2 > cx2 else (cx1 if x2 < cx1 else x2) ry2 = cy2 if y2 > cy2 else (cy1 if y2 < cy1 else y2) return Region(rx1, ry1, rx2 - rx1, ry2 - ry1) @lru_cache(maxsize=4096) def union(self, region: Region) -> Region: """Get the smallest region that contains both regions. Args: region: Another region. Returns: An optimally sized region to cover both regions. """ x1, y1, x2, y2 = self.corners ox1, oy1, ox2, oy2 = region.corners union_region = self.from_corners( min(x1, ox1), min(y1, oy1), max(x2, ox2), max(y2, oy2) ) return union_region @lru_cache(maxsize=1024) def split(self, cut_x: int, cut_y: int) -> tuple[Region, Region, Region, Region]: """Split a region in to 4 from given x and y offsets (cuts). ``` cut_x ↓ ┌────────┐ ┌───┐ │ │ │ │ │ 0 │ │ 1 │ │ │ │ │ cut_y → └────────┘ └───┘ ┌────────┐ ┌───┐ │ 2 │ │ 3 │ └────────┘ └───┘ ``` Args: cut_x: Offset from self.x where the cut should be made. If negative, the cut is taken from the right edge. cut_y: Offset from self.y where the cut should be made. If negative, the cut is taken from the lower edge. Returns: Four new regions which add up to the original (self). """ x, y, width, height = self if cut_x < 0: cut_x = width + cut_x if cut_y < 0: cut_y = height + cut_y _Region = Region return ( _Region(x, y, cut_x, cut_y), _Region(x + cut_x, y, width - cut_x, cut_y), _Region(x, y + cut_y, cut_x, height - cut_y), _Region(x + cut_x, y + cut_y, width - cut_x, height - cut_y), ) @lru_cache(maxsize=1024) def split_vertical(self, cut: int) -> tuple[Region, Region]: """Split a region in to two, from a given x offset. ``` cut ↓ ┌────────┐┌───┐ │ 0 ││ 1 │ │ ││ │ └────────┘└───┘ ``` Args: cut: An offset from self.x where the cut should be made. If cut is negative, it is taken from the right edge. Returns: Two regions, which add up to the original (self). """ x, y, width, height = self if cut < 0: cut = width + cut return ( Region(x, y, cut, height), Region(x + cut, y, width - cut, height), ) @lru_cache(maxsize=1024) def split_horizontal(self, cut: int) -> tuple[Region, Region]: """Split a region in to two, from a given y offset. ``` ┌─────────┐ │ 0 │ │ │ cut → └─────────┘ ┌─────────┐ │ 1 │ └─────────┘ ``` Args: cut: An offset from self.y where the cut should be made. May be negative, for the offset to start from the lower edge. Returns: Two regions, which add up to the original (self). """ x, y, width, height = self if cut < 0: cut = height + cut return ( Region(x, y, width, cut), Region(x, y + cut, width, height - cut), ) def translate_inside( self, container: Region, x_axis: bool = True, y_axis: bool = True ) -> Region: """Translate this region, so it fits within a container. This will ensure that there is as little overlap as possible. The top left of the returned region is guaranteed to be within the container. ``` ┌──────────────────┐ ┌──────────────────┐ │ container │ │ container │ │ │ │ ┌─────────────┤ │ │ ──▶ │ │ return │ │ ┌──────────┴──┐ │ │ │ │ │ self │ │ │ │ └───────┤ │ └────┴─────────────┘ │ │ └─────────────┘ ``` Args: container: A container region. x_axis: Allow translation of X axis. y_axis: Allow translation of Y axis. Returns: A new region with same dimensions that fits with inside container. """ x1, y1, width1, height1 = container x2, y2, width2, height2 = self return Region( max(min(x2, x1 + width1 - width2), x1) if x_axis else x2, max(min(y2, y1 + height1 - height2), y1) if y_axis else y2, width2, height2, ) def inflect( self, x_axis: int = +1, y_axis: int = +1, margin: Spacing | None = None ) -> Region: """Inflect a region around one or both axis. The `x_axis` and `y_axis` parameters define which direction to move the region. A positive value will move the region right or down, a negative value will move the region left or up. A value of `0` will leave that axis unmodified. ``` ╔══════════╗ │ ║ ║ ║ Self ║ │ ║ ║ ╚══════════╝ │ ─ ─ ─ ─ ─ ─ ─ ─ ┼ ─ ─ ─ ─ ─ ─ ─ ─ │ ┌──────────┐ │ │ │ │ Result │ │ │ │ └──────────┘ ``` Args: x_axis: +1 to inflect in the positive direction, -1 to inflect in the negative direction. y_axis: +1 to inflect in the positive direction, -1 to inflect in the negative direction. margin: Additional margin. Returns: A new region. """ inflect_margin = NULL_SPACING if margin is None else margin x, y, width, height = self if x_axis: x += (width + inflect_margin.width) * x_axis if y_axis: y += (height + inflect_margin.height) * y_axis return Region(x, y, width, height) class Spacing(NamedTuple): """The spacing around a renderable, such as padding and border. Spacing is defined by four integers for the space at the top, right, bottom, and left of a region. ``` ┌ ─ ─ ─ ─ ─ ─ ─▲─ ─ ─ ─ ─ ─ ─ ─ ┐ │ top │ ┏━━━━━▼━━━━━━┓ │ ◀──────▶┃ ┃◀───────▶ │ left ┃ ┃ right │ ┃ ┃ │ ┗━━━━━▲━━━━━━┛ │ │ bottom └ ─ ─ ─ ─ ─ ─ ─▼─ ─ ─ ─ ─ ─ ─ ─ ┘ ``` Example: ```python >>> from textual.geometry import Region, Spacing >>> region = Region(2, 3, 20, 10) >>> spacing = Spacing(1, 2, 3, 4) >>> region.grow(spacing) Region(x=-2, y=2, width=26, height=14) >>> region.shrink(spacing) Region(x=6, y=4, width=14, height=6) >>> spacing.css '1 2 3 4' ``` """ top: int = 0 """Space from the top of a region.""" right: int = 0 """Space from the right of a region.""" bottom: int = 0 """Space from the bottom of a region.""" left: int = 0 """Space from the left of a region.""" def __bool__(self) -> bool: return self != (0, 0, 0, 0) @property def width(self) -> int: """Total space in the x axis.""" return self.left + self.right @property def height(self) -> int: """Total space in the y axis.""" return self.top + self.bottom @property def top_left(self) -> tuple[int, int]: """A pair of integers for the left, and top space.""" return (self.left, self.top) @property def bottom_right(self) -> tuple[int, int]: """A pair of integers for the right, and bottom space.""" return (self.right, self.bottom) @property def totals(self) -> tuple[int, int]: """A pair of integers for the total horizontal and vertical space.""" top, right, bottom, left = self return (left + right, top + bottom) @property def css(self) -> str: """A string containing the spacing in CSS format. For example: "1" or "2 4" or "4 2 8 2". """ top, right, bottom, left = self if top == right == bottom == left: return f"{top}" if (top, right) == (bottom, left): return f"{top} {right}" else: return f"{top} {right} {bottom} {left}" @classmethod def unpack(cls, pad: SpacingDimensions) -> Spacing: """Unpack padding specified in CSS style. Args: pad: An integer, or tuple of 1, 2, or 4 integers. Raises: ValueError: If `pad` is an invalid value. Returns: New Spacing object. """ if isinstance(pad, int): return cls(pad, pad, pad, pad) pad_len = len(pad) if pad_len == 1: _pad = pad[0] return cls(_pad, _pad, _pad, _pad) if pad_len == 2: pad_top, pad_right = cast(Tuple[int, int], pad) return cls(pad_top, pad_right, pad_top, pad_right) if pad_len == 4: top, right, bottom, left = cast(Tuple[int, int, int, int], pad) return cls(top, right, bottom, left) raise ValueError( f"1, 2 or 4 integers required for spacing properties; {pad_len} given" ) @classmethod def vertical(cls, amount: int) -> Spacing: """Construct a Spacing with a given amount of spacing on vertical edges, and no horizontal spacing. Args: amount: The magnitude of spacing to apply to vertical edges Returns: `Spacing(amount, 0, amount, 0)` """ return Spacing(amount, 0, amount, 0) @classmethod def horizontal(cls, amount: int) -> Spacing: """Construct a Spacing with a given amount of spacing on horizontal edges, and no vertical spacing. Args: amount: The magnitude of spacing to apply to horizontal edges Returns: `Spacing(0, amount, 0, amount)` """ return Spacing(0, amount, 0, amount) @classmethod def all(cls, amount: int) -> Spacing: """Construct a Spacing with a given amount of spacing on all edges. Args: amount: The magnitude of spacing to apply to all edges Returns: `Spacing(amount, amount, amount, amount)` """ return Spacing(amount, amount, amount, amount) def __add__(self, other: object) -> Spacing: if isinstance(other, tuple): top1, right1, bottom1, left1 = self top2, right2, bottom2, left2 = other return Spacing( top1 + top2, right1 + right2, bottom1 + bottom2, left1 + left2 ) return NotImplemented def __sub__(self, other: object) -> Spacing: if isinstance(other, tuple): top1, right1, bottom1, left1 = self top2, right2, bottom2, left2 = other return Spacing( top1 - top2, right1 - right2, bottom1 - bottom2, left1 - left2 ) return NotImplemented def grow_maximum(self, other: Spacing) -> Spacing: """Grow spacing with a maximum. Args: other: Spacing object. Returns: New spacing where the values are maximum of the two values. """ top, right, bottom, left = self other_top, other_right, other_bottom, other_left = other return Spacing( max(top, other_top), max(right, other_right), max(bottom, other_bottom), max(left, other_left), ) NULL_OFFSET: Final = Offset(0, 0) """An [offset][textual.geometry.Offset] constant for (0, 0).""" NULL_REGION: Final = Region(0, 0, 0, 0) """A [Region][textual.geometry.Region] constant for a null region (at the origin, with both width and height set to zero).""" NULL_SPACING: Final = Spacing(0, 0, 0, 0) """A [Spacing][textual.geometry.Spacing] constant for no space."""
166d7a098db4017ca41e6de9058c1c3d5e78451f
clay1996/SimpleSweep
/SimpleSweepPro
7,433
3.96875
4
#!/usr/bin/env python3 '''Open to enter IP(s) as a command line argument. An ARP scan is automatically performed on IP(s) entered and then prompted with the option to try to ping the IP(s) found during the ARP scan. If no IP is provided it will automatically perform an ARP scan on the network asking users for ports to be scanned then prompt users if they would also like to perform a ping on the IPs found during ARP scan.''' import os import sys; import time; from io import StringIO; import re; import argparse #Function to extract only the IP address from the 'arp -a' command def extractIPs(fileContent): pattern = r"((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)([ (\[]?(\.|dot)[ )\]]?(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3})" ips = [each[0] for each in re.findall(pattern, fileContent)] for item in ips: location = ips.index(item) ip = re.sub("[ ()\[\]]", "", item) ip = re.sub("dot", ".", ip) ips.remove(item) ips.insert(location, ip) return ips #Function to automatically socket scan IP addresses provided to it and print any open ports def portscannerauto(target): import sys import socket from datetime import datetime # Add Banner print("-" * 50) print("Scanning Target: " + target) print("Scanning started at:" + str(datetime.now())) print("-" * 50) try: # will scan ports user defines for port in range(1,100): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(1) # returns an error indicator result = s.connect_ex((target,port)) if result ==0: banner = os.popen('nmap '+ target + ' -p'+str(port)).read() banner= re.split('\n', banner) print("Port {} Is Open:".format(port) +' ' + banner[5]) s.close() print('End Of Open Ports') except KeyboardInterrupt: print("\n Exiting Program !!!!") sys.exit() except socket.gaierror: print("\n Hostname Could Not Be Resolved !!!!") sys.exit() except socket.error: print("\ Server Not Responding !!!!") sys.exit() #Funtion to scan ports a user provides and print any open ports def portscanner(target): import sys import socket from datetime import datetime # Add Banner print("-" * 50) print("Scanning Target: " + target) print("Scanning started at:" + str(datetime.now())) print("-" * 50) lowerport= int(input("What Port Would You Like To Start Scanning At?:")) upperport= int(input('What Port Would You Like To Finish Scanning At?:')) try: # will scan ports that the user defines for port in range(lowerport,upperport): s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) socket.setdefaulttimeout(1) # returns an error indicator result = s.connect_ex((target,port)) if result ==0: banner = os.popen('nmap '+ target + ' -p'+str(port)).read() banner= re.split('\n', banner) print("Port {} Is Open:".format(port) +' ' + banner[5]) s.close() print('End Of Open Ports') except KeyboardInterrupt: print("\n Exitting Program !!!!") sys.exit() except socket.gaierror: print("\n Hostname Could Not Be Resolved !!!!") sys.exit() except socket.error: print("\ Server Not Responding !!!!") sys.exit() ############################################################################### print('Welcome To SimpleSweepPro') print(''' ╔═══╗──────╔╗────╔═══╗──────────────╔═══╗ ║╔═╗║──────║║────║╔═╗║──────────────║╔═╗║ ║╚══╦╦╗╔╦══╣║╔══╗║╚══╦╗╔╗╔╦══╦══╦══╗║╚═╝╠═╦══╗ ╚══╗╠╣╚╝║╔╗║║║║═╣╚══╗║╚╝╚╝║║═╣║═╣╔╗║║╔══╣╔╣╔╗║ ║╚═╝║║║║║╚╝║╚╣║═╣║╚═╝╠╗╔╗╔╣║═╣║═╣╚╝║║║──║║║╚╝║ ╚═══╩╩╩╩╣╔═╩═╩══╝╚═══╝╚╝╚╝╚══╩══╣╔═╝╚╝──╚╝╚══╝ ────────║║──────────────────────║║ ────────╚╝──────────────────────╚╝ .-. | | |=| |=| | | | | | | | | |=| |=| |_| .=/I\=. ////V\\\\ |#######| ||||||||| ||||||||| |||||||||''') #Try block is entered if any command line arguments are entered try: # if len(sys.argv[1]) < 1: # sys.exit() # customIP = sys.argv[1:] #port scanner credit: (author unknown) #https://www.geeksforgeeks.org/simple-port-scanner-using-sockets-in-python/ #Pass every IP entered into automatic port scanner function parser = argparse.ArgumentParser(description='Port scanner and Ping sweep checker') parser.add_argument('-v4','--IPV4',type=str, metavar='', help='The IP version 4 Address to be scanned') args = parser.parse_args() customIP=args.IPV4.split(' ') print(customIP) for IP in customIP: portscannerauto(IP) pingresult = os.popen('ping -c 1 ' +IP).read() if "100.0%" in pingresult: print(IP +" DID NOT Respond To Ping") else: print(IP + " DID Respond To Ping") #Pass every IP entered into NMAP port scanner # print('\n scanning ' + IP + ' for ping response:') # for IP in customIP: # pingresult = os.popen('ping -c 1 ' +IP).read() # if "100.0%" in pingresult: # print(customIP +" DID NOT Respond To Ping") # else: # print(customIP + " DID Respond To Ping") print('Thank You For Using SimpleSweepPro') #Except block entered if no command line arguments provided except: # print('except block entered') scanresult = os.popen('arp -a').read() listofIPs= extractIPs(scanresult) print('IPs Found: ') print(listofIPs) counter=0 lenIPlist= len(listofIPs) for IP in listofIPs: portscanner(IP) counter = counter +1 if counter == lenIPlist: print("All Found Hosts Scanned.") usenmap = input('Would You Like To Continue Scanning The Hosts Found During The ARP Scan And Check For A Ping Response? Y/N?: ') if usenmap == 'Y': for IP in listofIPs: #print('\n scanning ' + IP +' for ping response:') pingresponce= os.popen('ping -c 1 ' +IP).read() if '100.0%' in pingresponce: print(IP + " DID NOT Respond To Ping") else: print(IP + " DID Respond To Ping") print("Thank You For Using SimpleSweepPro!") else: print('Thank You For Using SimpleSweepPro!')
5c36317240cb693d50674cef15ee3737592a09c1
Dimen61/leetcode
/python_solution/Array/56_MergeIntervals.py
737
3.78125
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def merge(self, intervals): """ :type intervals: List[Interval] :rtype: List[Interval] """ intervals.sort(key=lambda x: x.start) merged_intervals = [] for interval in intervals: if not merged_intervals: merged_intervals.append(interval) elif interval.start <= merged_intervals[-1].end: merged_intervals[-1].end = max(merged_intervals[-1].end, interval.end) else: merged_intervals.append(interval) return merged_intervals
64c3f597b0ca51f91b3216f93994989cac544fc6
Dimen61/leetcode
/python_solution/Array/57_InsertInterval.py
1,717
3.734375
4
# Definition for an interval. # class Interval(object): # def __init__(self, s=0, e=0): # self.start = s # self.end = e class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[Interval] :type newInterval: Interval :rtype: List[Interval] """ if not intervals: return [newInterval] elif newInterval.end < intervals[0].start: return [newInterval] + intervals elif newInterval.start > intervals[-1].end: return intervals + [newInterval] merged_intervals = [] index = 0 length = len(intervals) flag = False while index < length: if intervals[index].end < newInterval.start: merged_intervals.append(intervals[index]) index += 1 elif intervals[index].end >= newInterval.start and not flag: flag = True if intervals[index].start > newInterval.end: merged_intervals.append(newInterval) continue intervals[index].end = max(intervals[index].end, newInterval.end) intervals[index].start = min(intervals[index].start, newInterval.start) merged_intervals.append(intervals[index]) index += 1 while index < length and intervals[index].start <= merged_intervals[-1].end: merged_intervals[-1].end = max(merged_intervals[-1].end, intervals[index].end) index += 1 else: merged_intervals.append(intervals[index]) index += 1 return merged_intervals
6881ca029f3a708884433e4b26010075f3979404
Dimen61/leetcode
/python_solution/TwoPointers/209_MinimumSizeSubarraySum.py
818
3.609375
4
# The main idea is to main the proper window: # Consider that every window which ends position is # from 0 to len(nums)-1 and consider the start position # of each window. We notice that start positions are ascending # series. class Solution(object): def minSubArrayLen(self, s, nums): """ :type s: int :type nums: List[int] :rtype: int """ if not nums: return 0 left = right = 0 total = 0 min_len = 10 ** 8 for right in range(len(nums)): total += nums[right] while total >= s: min_len = min(min_len, right-left+1) total -= nums[left] left += 1 return 0 if min_len == 10 ** 8 else min_len
1ac11216ee3f43837c2fb2ea660a5c36c5d53b42
Dimen61/leetcode
/python_solution/Tree/235_LowestCommonAncestorOfABinarySearchTree.py
1,942
3.859375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ if not root: return None # Contains q or q. if root.val == p.val: return root elif root.val == q.val: return root # p or q on the right chil and left chil of the root. elif q.val < root.val < p.val or p.val < root.val < q.val: return root # p and q on the left chil elif q.val < root.val and p.val < root.val: return self.lowestCommonAncestor(root.left, p, q) elif q.val > root.val and p.val > root.val: return self.lowestCommonAncestor(root.right, p, q) # More elegant solution class Solution2(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ max_val = max(p.val, q.val) min_val = min(p.val, q.val) while root: if min_val <= root.val <= max_val: return root elif max_val < root.val: root = root.left else: root = root.right return root # The more more elegant solution class Solution3(object): def lowestCommonAncestor(self, root, p, q): """ :type root: TreeNode :type p: TreeNode :type q: TreeNode :rtype: TreeNode """ while (root.val-p.val)*(root.val-q.val) > 0: root = (root.left, root.right)[root.val < p.val] return root
8923618cc605f650005e9f9fca42acbc1a6e9edf
Dimen61/leetcode
/python_solution/Tree/112_PathSum.py
928
4
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if not root: return False # if root.val > sum: return False if not root.left and not root.right: return sum == root.val else: if root.left: if self.hasPathSum(root.left, sum-root.val): return True if root.right: if self.hasPathSum(root.right, sum-root.val): return True return False a = Solution() node0 = TreeNode(-2) node1 = TreeNode(-3) node0.right = node1 print(a.hasPathSum(node0, -5))
99c46397bbcd013e3fe7c25dd1a0ee70b0055b35
Dimen61/leetcode
/python_solution/Array/118_PascalTriangle.py
747
3.671875
4
class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ triangle = [] current_line = [] for i in range(numRows): if not current_line: current_line.append(1) triangle.append(current_line) else: next_line = [] for j in range(i+1): x = current_line[j-1] if j >= 1 else 0 y = current_line[j] if j < i else 0 next_line.append(x+y) triangle.append(next_line) current_line = next_line return triangle a = Solution() print(a.generate(3))
e0dca471d149615ebb6fce3f5011a80b609c5b73
Dimen61/leetcode
/python_solution/Combination/140_WordBreakII.py
1,943
3.625
4
class Solution(object): def wordBreak(self, s, wordDict): """ Basic dynamic programming :type s: str :type wordDict: Set[str] :rtype: List[str] """ # word_lst = list(wordDict) f = [[] for i in range(len(s)+1)] for i in range(len(s)): if f[i]: for word in wordDict: if s[i:i+len(word)] == word: f[i+len(word)].extend(map(lambda x: x+' '+word, f[i])) elif i == 0: for word in wordDict: if s[i:i+len(word)] == word: f[len(word)].append(word) for i, val in enumerate(f): print('f[{0}]: {1}'.format(i, val)) return f[len(s)] def wordBreak(self, s, wordDict): """ Dynamic programming with subsequent dealing. :type s: str :type wordDict: Set[str] :rtype: List[str] """ word_lst = list(wordDict) f = [[] for i in range(len(s)+1)] for i in range(len(s)): if i == 0 or f[i]: for index, word in enumerate(word_lst): if word == s[i:i+len(word)]: f[i+len(word)].append(index) res_lst = [] def dfs(index, sentence): '''Backtrack to construct possible sentences''' if index == 0: res_lst.append(sentence) return elif index < 0: return for i in f[index]: if not sentence: dfs(index-len(word_lst[i]), word_lst[i]) else: dfs(index-len(word_lst[i]), word_lst[i]+' '+sentence) dfs(len(s), '') return res_lst a = Solution() s = "catsanddog" dct = ["cat", "cats", "and", "sand", "dog"] print(a.wordBreak(s, dct))
56bcab76434dc7b088e92960488fcabfb9b8d941
Dimen61/leetcode
/python_solution/String/14.py
671
3.734375
4
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ res = '' if not strs: return res # Empty list strs for i in range(len(strs[0])): char = strs[0][i] flag = True for j in range(1, len(strs)): if i >= len(strs[j]) or strs[j][i] != char: flag = False break if not flag: return res else: res += char return res a = Solution() print(a.longestCommonPrefix(['abc', 'ab'])) print(a.longestCommonPrefix([]))
70585f8c7aed6a0045485f05ca49586a203a0f7f
Dimen61/leetcode
/python_solution/Tree/124_BinaryTreeMaximumPathSum.py
1,133
3.59375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxPathSum(self, root): """ Memorized search :type root: TreeNode :rtype: int """ if not root: return 0 self.max_num = -1000000000000 f = {} def memorized_search(root): if not root: return 0 if root in f: return f[root] f[root] = root.val + max(memorized_search(root.left), memorized_search(root.right), 0) return f[root] def dfs(root): if not root: return self.max_num = max(self.max_num, root.val) self.max_num = max(self.max_num, memorized_search(root)) self.max_num = max(self.max_num, memorized_search(root.left) + root.val + memorized_search(root.right)) dfs(root.left) dfs(root.right) dfs(root) return self.max_num
3d63b5d5b5844ef5d07dac492f2a50d63d7422e5
Dimen61/leetcode
/python_solution/BinarySearch/230_KthSmallestElementInABST.py
1,991
4.09375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def get_node_num(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 return self.get_node_num(root.left) + self.get_node_num(root.right) + 1 def kthSmallest(self, root, k): """ The main idea is binary search. :type root: TreeNode :type k: int :rtype: int """ left_num = self.get_node_num(root.left) if k <= left_num: return self.kthSmallest(root.left, k) elif k == left_num + 1: return root.val else: return self.kthSmallest(root.right, k-left_num-1) def kthSmallest(self, root, k): """ Use python generator to implement a binary tree in-order traversal. :type root: TreeNode :type k: int :rtype: int """ def helper(root): if root.left: for val in helper(root.left): yield val yield root.val if root.right: for val in helper(root.right): yield val i = 0 for val in helper(root): i += 1 if i == k: return val def kthSmallest(self, root, k): """ Use iteration to implement binary tree in-order traversal. :type root: TreeNode :type k: int :rtype: int """ i = 0 node_stack = [] while root or node_stack: if root: node_stack.append(root) root = root.left else: root = node_stack.pop() i += 1 if i == k: return root.val root = root.right
77b73fc141684968c1e1294e8013ba05b15550f4
Dimen61/leetcode
/python_solution/HashTable/274_H_Index.py
949
3.6875
4
# Use sorted array to implement a process intuitionly. class Solution(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ array = sorted(citations, reverse=True) index = citation = 0 for index, citation in enumerate(array): if citation < index + 1: return index return len(array) # Use some iterative trick class Solution2(object): def hIndex(self, citations): """ :type citations: List[int] :rtype: int """ length = len(citations) num = [0] * (length+1) for citation in citations: if citation > length: num[length] += 1 else: num[citation] += 1 total = 0 for i in range(length, -1, -1): total += num[i] if total >= i: return i return 0
c94dfa49fb341906f3915db5ee07ed88e855d7e5
kaifist/Rosalind_ex
/old_ex/k--mers_lexico_order.py
872
3.75
4
# Enumerating k-mers Lexicographically ##import itertools as it ## ##with open('rosalind_lexf.txt') as file: ## letras = file.readline().rstrip('\n').split() ## letras2 = ''.join(letras) ## print(letras2) ## n = int(file.readline()) ## ## print(letras) ## print(letras2) ## lista_perm = it.product(letras2, repeat=n) ## ## for i in lista_perm: ## print(''.join(i)) # los ordena directamente en orden alfabetico ## Ordering Strings of Varying Length Lexicographically # recursividad? letras = ['D', 'N', 'A'] def lex(l, n, m = ''): print(m) if n == 1: for i in l: m += i return(m) else: for i in l: lex(l, m+i, n-1) print(lex(letras, 1)) # letras = ('N', 'D', 'U', 'R', 'A', 'F', 'O', 'W', 'P', 'H') # for i in letras: # print(i) # for j in letras: # print(i+j) # for h in letras: # print(i+j+h) # for l in letras: # print(i+j+h+l)
b25543c9cefc8df363d0a792e920c3880d8aa6a0
BrandonMayU/Think-Like-A-Computer-Scientist-Homework
/6.13 Problems/6.13-4.py
380
3.546875
4
#Draw this pretty pattern. import turtle square = turtle.Turtle() wn = turtle.Screen() def drawSquare(turtle, size, totalSquares): rotationAngle = 360/totalSquares for i in range(totalSquares): square.right(rotationAngle) for i in range(4): square.forward(size) square.right(90) drawSquare(square,200,20) wn.exitonclick()
dbd0ed785c9af1889311a980ad5911e9d0ae6c88
BrandonMayU/Think-Like-A-Computer-Scientist-Homework
/6.13 Problems/6.13-14.py
499
3.6875
4
import math def mySqrt(n): initialGuess = n/2 for i in range(10): newGuess = (1/2)*(initialGuess + (n/initialGuess)) initialGuess = newGuess count = i + 1 print("Guess #", count,": ", newGuess) trueSQRT = math.sqrt(n) print("True Square root value = ", trueSQRT) print("Intilizing the function") value = int(input("Please enter value you want to find the square root of: ")) mySqrt(value) #Execute the function print() print("End of Program!")
482a4ab3e78e3f5e755ea3ff9b66fc48d3e5860f
BrandonMayU/Think-Like-A-Computer-Scientist-Homework
/7.10 Problems/5.6-17.py
367
4.1875
4
# Use a for statement to print 10 random numbers. # Repeat the above exercise but this time print 10 random numbers between 25 and 35, inclusive. import random count = 1 # This keeps track of how many times the for-loop has looped print("2") for i in range(10): number = random.randint(25,35) print("Loop: ",count," Random Number: ", number) count += 1
b0c51fbea5fd4b4d4aa85f7137cea006f7de4acc
BrandonMayU/Think-Like-A-Computer-Scientist-Homework
/4.11 Problems/4.11-4.py
516
4.03125
4
import turtle import math print("Two Questions:") print("A) Write a loop that prints each of the numbers on a new line. ") print("Here is my solution.... ") for i in [12, 10, 32, 3, 66, 17, 42, 99, 20]: print("Value is ", i) print("") print("B) Write a loop that prints each number and its square on a new line. ") print("Here is my solution") for i in [12, 10, 32, 3, 66, 17, 42, 99, 20]: sqr = float (i*i) print("For the value of ", i, " the value squared ", sqr) print("That is everything :)")
8478e33e1279a4135efdaf52e01e88ae3ca6d0b4
roma-vinn/Combinatorics
/Matrix Chain/matrix_chain_dynamic.py
2,195
4.03125
4
""" Created by Roman Polishchenko at 12/9/18 2 course, comp math Taras Shevchenko National University of Kyiv email: roma.vinn@gmail.com """ import time def matrix_chain_dynamic(dimensions, n): """ Dynamic Programming Python implementation of Matrix Chain Multiplication - build the worst sequence of brackets (it means that this sequence have the biggest number of elementary operations). :param dimensions: array of dimensions :param n: length of matrix sequence :return: array n x n of maximum amount of elementary operations for each pair i, j array n x n of right split of matrix chain """ m = [[-1 for _ in range(n)] for _ in range(n)] s = [[0 for _ in range(n)] for _ in range(n)] # multiplying matrix by itself for i in range(1, n): m[i][i] = 0 for length in range(2, n): for i in range(1, n - length + 1): j = i + length - 1 for k in range(i, j): cost = m[i][k] + m[k + 1][j] + dimensions[i - 1] * dimensions[k] * dimensions[j] if cost > m[i][j]: m[i][j] = cost # index if splitting s[i][j] = k return m, s def get_answer(s, i, j, res: list): """ Reconstruct the sequence of brackets and matrix that give the maximum number of operations :param s: array n x n of right split of matrix chain from matrix_chain_dynamic :param i: start of piece :param j: end of piece :param res: array of string from set {'(', ')', 'a[i]'} :return: None (array changes inside of function) """ if i == j: res.append('a[{}]'.format(i-1)) else: res.append('(') get_answer(s, i, s[i][j], res) get_answer(s, s[i][j]+1, j, res) res.append(')') def test(): arr = [1, 2, 3, 4, 5, 6] size = len(arr) res_m, res_s = matrix_chain_dynamic(arr, size) answer = [] get_answer(res_s, 1, size-1, answer) print("Maximal number of operations: {}".format(res_m[1][size-1])) print("Order: {}".format(''.join(answer))) if __name__ == '__main__': begin = time.time() test() print('Time:', time.time() - begin)
f3030a6ec17f2c79f004b68d360e2961d3e7b597
suraj-pawar/python
/bitwiseoperator/swapbitsbetween2no.py
459
4.0625
4
#!usr/bin/python/python2.7 def swapbits(no1,no2,pos,bits): x=no1 y=no2 mask=((2**bits)-1)<<(pos-bits) # pos=5,bits=4 ---> 0001 1110 xtemp= x & mask ytemp= y & mask x=x & (~ mask) y=y & (~ mask) x=x | ytemp y=y | xtemp return x,y def main(): no1=input("Enter the no1") no2=input("Enter the no2") pos=input("Enter the pos") bits=input("Enter the no of bits") print swapbits(no1,no2,pos,bits) if __name__ == "__main__": main()
fb4a92c1a68d2645a3ba5f157c82dfde411f8b64
suraj-pawar/python
/add10.py
307
3.9375
4
#!usr/bin/python/python2.7 #write a program to accept n no from user and add them def my_generator(): count=input("HOW MANY ") for x in range(count): i=input() yield i def add(*args): tot=0 for x in args: tot=tot+x print tot if __name__ == "__main__": it=my_generator() add(*it)
5edf56c07a4fd7ad27529f0b009745889594b045
TheProjecter/python-csv2pgsql
/csv2pgsql.py
15,393
3.75
4
""" Written by Cedric Boittin, 13/11/2013 A script for converting csv files to postgresql tables using python-psycopg2. It may be used to convert a single file, or every .csv file in a directory. Automatically creates a table with the corresponding columns, assuming that the csv file has a one-row header. The data types are automatically selected among text, double precision, or bigint. Assumes the database connection is managed by the user's settings, for example with a .pgpass file on linux. The null value may be automatically detected among the double quotes (""), the empty string or NA. usage: python csv2pgsql.py [-h] [--host HOST] [-u USERNAME] [-db DATABASE] [-n NULL] [--fixednull] [-v] [--autodrop] src positional arguments: src Directory containing the csv files optional arguments: -h, --help show this help message and exit --host HOST Host of the database -u USERNAME, --username USERNAME Name of the user who connects to the database -db DATABASE, --database DATABASE Name of the database -d DELIMITER, --delimiter DELIMITER Delimiter in the csv file -n NULL, --null NULL Null String in the CSV file --fixednull Do not check for the null string -v, --verbosity Increase output verbosity --autodrop Drop table if it already exists """ import csv import psycopg2 as pg import os.path import argparse import re from subprocess import call parser = argparse.ArgumentParser() parser.add_argument('src', help="Directory containing the csv files") parser.add_argument("--host", default="localhost", help='Host of the database') parser.add_argument('-u', "--username", default="YOUR_USERNAME_HERE", help='Name of the user who connects to the database') parser.add_argument('-db', "--database", default="YOUR_DB_HERE", help='Name of the database') parser.add_argument('-d', '--delimiter', default=',', help='Delimiter in the csv file') parser.add_argument('-n', '--null', default="\"\"", help='Null String in the csv file') parser.add_argument('--fixednull', action='store_true', help='Do not check for the null string') # parser.add_argument('--debug', action='store_true', help='Debug information on/off') parser.add_argument('-v', '--verbosity', action="count", help="Increase output verbosity") parser.add_argument('--autodrop', action='store_true', help='Drop table if it already exists') args = parser.parse_args() src = args.src dbname = args.database debug = args.verbosity userName = args.username hostName = args.host nullString = args.null autoDrop = args.autodrop fixedNullString = args.fixednull csvDelimiter = args.delimiter # Check presence of potential null strings hasNullString = {"NA":False, "\"\"":False, "":False} nRowsToParse = 10 systematicReading = True #The False flag remains to be managed nonnumericRegex = re.compile("[^\d\.]") startingZeroRegex = re.compile("^0[^\.]") def _buildRowInsertString(fields): """ Construct an adapted format string for quick use in an INSERT INTO sql statement """ elts = [] for field in fields: if field[1] == "text": elts.append('\'%s\'') continue elts.append('%s') return "(%s)" % ','.join(elts) def _dataType(data): """ Return a postgresql data type according to the given csv string """ # Set field to text if it is quoted, starts with 0, or contains a non-digit, # non-point character if data in ("", nullString): return "null" # No evidence elif data[0] in ('"', '\'') or nonnumericRegex.search(data) is not None or startingZeroRegex.search(data) is not None: if data == "NA": return "bigint" else: return "text" # Set field to double if it contains a point elif '.' in data: return "double precision" # Else, the field should only contain digits, set it to bigint else: return "bigint" def _mostGenericType(type1, type2): """ Return the most generic type among (text, double precision, bigint). Assume type1 is not "null" """ if type1 == "text": return "text" elif type2 == "text": return "text" elif type2 == "null": return type1 elif type1 == "double precision": return "double precision" return type2 def _checkAndSetNullString(candidate): """ If the null string has not been manually set, the script is in charge of finding the right one Return True if the null string has been modified.""" global nullString hasNullString[candidate]=True if hasNullString[candidate] == hasNullString["\"\""] == hasNullString[""] == True: print "File error : too many potential null Strings" import sys; sys.exit() if fixedNullString or nullString == candidate or candidate == "\"\"" or nullString == "NA": return False nullString = candidate #The other four cases if debug: if nullString == "": print "\n ***** New null string : [empty string] ***** \n" else: print "\n ***** New null string : " + nullString + " ***** \n" return True def _parseSomeFields(reader, fieldsCount, dataTypes): """ Parse all lines and return a list of datatypes for each column """ for i in range(nRowsToParse): #Read the line to check the data types try: line = reader.next() for i in range(fieldsCount): dataTypes[i].append(_dataType(line[i])) except Exception as e: if debug: print "EoF reached before reading " + str(nRowsToParse) + " lines." try: e.print_stack_trace() except Exception: pass break return dataTypes def _parseFields(filePath): """Return a list of (field type, field name) tuples. The field types are estimated """ reader = csv.reader(open(filePath, 'rb'), quoting=csv.QUOTE_NONE, delimiter=csvDelimiter) fieldNames = reader.next() fieldsCount = len(fieldNames) #Initialize data structures columns = [None]*fieldsCount dataTypes = [None]*fieldsCount for i in range(fieldsCount): dataTypes[i] = [] dataTypes = _parseSomeFields(reader, fieldsCount, dataTypes) #Parse the datatypes and select the most general one for i in range(fieldsCount): #Fix empty field names if fieldNames[i] in ("", "\"\"", "\'\'"): fieldNames[i] = "autoNull"+str(i) if "text" in dataTypes[i] or "null" in dataTypes[i]: columns[i] = (fieldNames[i], "text") elif "double precision" in dataTypes[i]: columns[i] = (fieldNames[i], "double precision") else: columns[i] = (fieldNames[i], "bigint") return columns def _reParseFields(data, fields): """ Fix the first incorrect field type according to the given data. Terminate python instance if no data type is modified """ n = len(data) fieldsCount = len(fields) for line in data: for j in range(fieldsCount): newType = _mostGenericType(fields[j][1], _dataType(line[j])) if newType != fields[j][1]: if debug: print "Found that " + str(fields[j]) + " should be of type " + newType fields[j] = (fields[j][0], newType) return (fields, fields[j][0], newType) # fields[j] = (fields[j][0], newType) # return fields print "\n***** Error : cannot find a proper data type. Terminating ..." import sys; sys.exit() def _reParseAndAlter(tableName, data, fields): """ Parse the fields again with to the given data, and modifies the table accordingly. """ (fields, column, newType) = _reParseFields(data, fields) colsString = [] command = "ALTER TABLE %s ALTER COLUMN %s SET DATA TYPE %s;" % (tableName, column, newType) if debug: print "\nExecuting postgresql command :\n" + command try: cursor.execute(command) connection.commit() if debug: print "... Successful" except Exception as e: try : print e.pgerror except Exception: try: e.print_stack_trace() except Exception: pass import sys; sys.exit() return fields def _parse(filePath): """ Parse the file """ # Verify file extension aFile = os.path.basename(filePath) source = aFile.split(".") fileShortName = source[0] if (len(source) != 2 or (source[1] != "csv" and source[1] != "CSV")): if debug: print "File " + aFile + " doesn't have the csv extension" return None # Get initial types for the fields fields = _parseFields(filePath) # Create a table with the corresponding rows commandString = "CREATE TABLE " + fileShortName + " (" commandString += fields[0][0] + " " + fields[0][1] for i in range(1, len(fields)): field = fields[i] commandString += ", " + field[0] + " " + field[1] commandString += ");" if debug >= 2: print "\nExecuting postgresql command :\n" + commandString try: cursor.execute(commandString) connection.commit() if debug: print "Successfully created table " + fileShortName except Exception as e: print "\n/!\\ Cannot create table " + fileShortName + ", it probably already exists" if autoDrop == True: command = "DROP TABLE %s;" % fileShortName print "Executing postgresql command : " + command try: connection.rollback() cursor.execute(command) connection.commit() except Exception as e: try: e.print_stack_trace() except Exception: pass if debug: print "Couldn't drop table. Terminating ..." import sys; sys.exit() try: cursor.execute(commandString) connection.commit() if debug: print "Successfully created table " + fileShortName except Exception as e: try: e.print_stack_trace() except Exception: pass if debug: print "Cannot create table. Terminating ..." import sys; sys.exit() try: e.print_stack_trace() except Exception: pass _doParse(fileShortName, fields, filePath) if debug >= 2: if nullString == "": print "Finished parsing %s, with [empty string] as null string\n" % aFile else: print "Finished parsing %s, with %s as null string\n" % (aFile, nullString) def _doParse(tableName, fields, filePath): """ Perform the parsing operations """ reader = csv.reader(open(filePath, 'rb'), quoting=csv.QUOTE_NONE, delimiter=csvDelimiter) reader.next() rowString = _buildRowInsertString(fields) # Insert data count = 0 dataBuffer = [None]*10000 for line in reader: dataBuffer[count] = line count += 1 #After 1000 lines, try sending data if count > 9999: count = 0 rowString = _sendData(tableName, fields, filePath, dataBuffer, rowString) if rowString is None: return if count > 0: _sendData(tableName, fields, filePath, [dataBuffer[i] for i in range(count)], rowString) def _sendData(tableName, fields, filePath, data, rowString): """ Send data to the connected database. Manage partially wrong table specification """ if data[len(data)-1] is None: #Incomplete batch newBuffer = [] for line in data: if line is not None: newBuffer.append(line) data = newBuffer success = _send(tableName, data, rowString) if success != 1: # While the row insertion fails, alter the table so it can store the data. # This will never cause an infinite loop because _reParseAndAlter requires that fields # are modified during its execution while success == -1: connection.rollback() fields = _reParseAndAlter(tableName, data, fields) rowString = _buildRowInsertString(fields) success = _send(tableName, data, rowString) if success == 0: #If the null string has to be changed, restart from the beginning _doParse(tableName, fields, filePath) return None try: connection.commit() except Exception as e: if debug: print "/!\ Error while committing changes. Terminating ..." try: e.print_stack_trace() except Exception: pass import sys; sys.exit() return rowString def _send(tableName, data, rowString): """ Send data to the connected database. Return 0 if an error occurred, -1 if the fields have to be reparsed, 1 otherwise """ cmd = [] for line in data: values = [] for elt in line: if elt in ("", "\"\"", "NA"): if _checkAndSetNullString(elt): #The null string has been changed, and the parsing must be done accordingly return 0 if elt == nullString: values.append('null') continue values.append(elt.replace("\'", "\'\'").replace("\"", "")) try: cmd.append(rowString % tuple(values)) except Exception as e: print values print rowString.count("%s") print len(values) try: e.print_stack_trace() except Exception: pass import sys; sys.exit() command = ("INSERT INTO %(table)s VALUES %(values)s;" % {"table":tableName, "values":",\n".join(cmd)}) if debug >= 3: print "\nExecuting postgresql command :\n" + command + "\n" try: cursor.execute(command) except Exception as e: if debug: print "\n/!\\ Error while inserting rows" try: print e.pgerror except Exception: pass finally: try: e.print_stack_trace() except Exception: pass return -1 return 1 def parseOneFile(): """ Read one csv file and parse it""" _parse(src) def parseAllFiles(): """ Read all .csv/.CSV files in src and parse them """ for aFile in os.listdir(src): filePath = os.path.join(src, aFile) if os.path.isdir(filePath): continue hasNullString = {"NA":False, "\"\"":False, "":False} global nullString nullString = args.null if debug >= 2 : if nullString == "": print "Back to [empty string] as null string" else: print "Back to " + nullString + " as null string" _parse(filePath) connection = None try: connection = pg.connect(database=dbname, user=userName, host=hostName) cursor = connection.cursor() except Exception as e: print "/!\\ Error : Cannot connect to the database. Terminating ..." import sys; sys.exit() if os.path.isdir(src): parseAllFiles() else: parseOneFile()
869965fd4ec4fd740c4d05f09d2064e5d13fcbc7
leeseulgi123/practice_python_coding
/Implementation_4.py
1,908
3.59375
4
# 구현 복습 print("지도의 크기를 입력하세요.(행,열) >") n,m = map(int, input().split()) print("현재 캐릭터의 위치(행,렬)와 방향을 입력하세요. >") x,y,d = map(int, input().split()) cnt = 1 turn_time = 0 # 경로 #(왼, 오, 상, 하) steps = [(0,-1),(0,1),(-1,0),(1,0)] # 방향 #(북, 동, 남, 서) directions = [(-1,0),(0,1),(1,0),(0,-1)] # 방문한 위치를 저장하는 2차원 리스트 my_path = [[0]*m for _ in range(n)] # 시작한 위치는 방문처리 my_path[x][y] = 1 # 맵의 행, 열의 정보를 담는 리스트 my_map = [] print(str(n)+"행의"+" 맵 정보를 입력하세요. >") for i in range(n): my_map.append(list(map(int, input().split()))) # 왼쪽으로 회전시켜주는 함수 # (d값이 -1되면 3으로 처리한다.) def turn_left(): global d d -= 1 if d==-1: d = 3 while True: # 우선적으로 왼쪽 회전을 수행. turn_left() nx = x+directions[d][0] ny = y+directions[d][1] # 정면에 가보지 않은 칸이 존재하면 이동. if my_path[nx][ny] == 0 and my_map[nx][ny] == 0: # 우선 방문처리. my_path[nx][ny] = 1 # 캐릭터의 현재 위치를 갱신한다. x,y = nx,ny # 이동 횟수 1 증가 cnt+=1 turn_time = 0 continue # 정면에 있는 공간에 방문한 적 있으면, else: # 한번 턴. turn_time+=1 # 만약 4 방향을 모두 가봤으면, if turn_time == 4: nx = x+directions[d][0] ny = y+directions[d][1] # 땅이면 이동 if my_map[nx][ny] == 0: x = nx y = ny # 바다이면 멈춤 else: break turn_time = 0 print("캐릭터는 총 "+str(cnt)+"칸을 방문했습니다.")
6d5b34e5951b7ab00184f7ab79c8b6f95fdad582
leeseulgi123/practice_python_coding
/23.py
1,037
3.78125
4
# 퀵 정렬(정통방식) array = [5,7,9,0,3,1,6,2,4,8] def quick_sort(array, start, end): # 원소가 1개인 경우 종료 if start>=end: return # 첫번째 원소를 pivot으로. pivot = start left = start+1 right = end while left<=right: # pivot보다 큰 데이터를 찾을 때까지 반복. while left<=end and array[left]<=array[pivot]: left+=1 # pivot보다 작은 데이터를 찾을 때까지 반복. while right>start and array[right]>=array[pivot]: right-=1 # 엇갈렸다면, if left>right: # 작은 데이터와 pivot을 스와프 array[right], array[pivot] = array[pivot], array[right] # 엇갈리지 않았다면, else: # 작은 데이터와 큰 데이터를 스와프 array[left], array[right] = array[right], array[left] quick_sort(array, start, right-1) quick_sort(array, right+1, end) quick_sort(array,0,len(array)-1) print(array)
a12ceb080ee0e74d55e9c692749d92e6abe150d4
leeseulgi123/practice_python_coding
/70.py
891
3.640625
4
# 크루스칼 알고리즘 def find_parent(parent, x): if parent[x]!=x: parent[x] = find_parent(parent, parent[x]) return parent[x] def union_parent(parent, a, b): a = find_parent(parent, a) b = find_parent(parent, b) if a<b: parent[b] = a else: parent[a] = b print("노드의 개수와 간선의 개수를 입력하세요. >") v,e = map(int, input().split()) parent = [0]*(v+1) # 모든 간선을 담을 리스트와 최종 비용 edges = [] result = 0 for i in range(1,v+1): parent[i] = i for _ in range(e): print("각 간선과 이에 대한 비용을 입력하세요. >") a,b,cost = map(int, input().split()) edges.append((cost, a, b)) edges.sort() for edge in edges: cost, a, b = edge if find_parent(parent, a)!=find_parent(parent, b): union_parent(parent, a, b) result+=cost print(result)
1f38fab51a8e374e89e2a501e07249ff03d6492f
leeseulgi123/practice_python_coding
/basic_adjacency_list.py
330
3.515625
4
graph = [[] for _ in range(3)] # 노드 0에 1번 노드가 거리 7로 연결 graph[0].append((1,7)) # 노드 0에 2번 노드가 거리 5로 연결 graph[0].append((2,5)) # 노드 1에 0번 노드가 거리 7로 연결 graph[1].append((0,7)) # 노드 2에 0번 노드가 거리 5로 연결 graph[2].append((0,5)) print(graph)
96bcb662bf3270dcc8c8f76f0aceab9d0671d542
Edmund-Lui98/SudokuCSP
/src/sudoku.py
2,503
3.75
4
""" ------------------------------------------------------- Sudoku class ------------------------------------------------------- Section: CP468 ------------------------------------------------------- """ import itertools rows = characters = "ABCDEFGHI" cols = numbers = "123456789" class sudoku: def __init__(self, board): self.variables = list() self.domains = dict() self.constraints = list() self.neighbors = dict() self.prepare(board) def prepare(self,board): game = list(board) self.variables = self.def_variables(rows,cols) self.domains = {v: list(range(1, 10)) if game[i] == '0' else [int(game[i])] for i, v in enumerate(self.variables)} self.def_constraints() self.def_neighors() def def_variables(self,a,b): var = [] for x in a: for i in b: var.append(x+i) return var def def_constraints(self): blocks = ( [self.combine(rows, number) for number in cols] + [self.combine(character, cols) for character in rows] + [self.combine(character, number) for character in ('ABC', 'DEF', 'GHI') for number in ('123', '456', '789')] ) for block in blocks: combinations = self.permutate(block) for combination in combinations: if [combination[0], combination[1]] not in self.constraints: self.constraints.append([combination[0], combination[1]]) def def_neighors(self): for x in self.variables: self.neighbors[x] = list() for c in self.constraints: if x == c[0]: self.neighbors[x].append(c[1]) def solved(self): solved = True for i in self.variables: if len(self.domains[i]) > 1: solved = False return solved #helper functions for the constraints @staticmethod def combine(alpha, beta): return [a + b for a in alpha for b in beta] @staticmethod def permutate(iterable): result = list() for L in range(0, len(iterable) + 1): if L == 2: for subset in itertools.permutations(iterable, L): result.append(subset) return result @staticmethod def constraint(xi, xj): return xi != xj
a311350bfa1104d209f64876457369db9c7caccd
vinitraj10/Python-Scrappers
/Image Downloader/image-downloader.py
270
3.59375
4
import random import urllib.request def download_image(url): name = random.randrange(1,100) file_name = str(name) + ".jpg" urllib.request.urlretrieve(url,file_name) print("Enter the URL:-") x = input() download_image(x) print("Image Downloaded Please Check Folder")
63d9e51100db4792259157df2e315f920b23f46f
Shashanksingh17/python-functional-program
/LeapYear.py
227
4.125
4
year = int(input("Enter Year")) if year < 1000 and year > 9999: print("Wrong Year") else: if year % 400 == 0 or (year % 4 == 0 and year % 100 != 0): print("Leap year") else: print("Not a Leap Year")
68d2b16d105b9ec4642c467b96bec518f14b9646
Shashanksingh17/python-functional-program
/PrimeFactor.py
365
3.890625
4
number = int(input("Enter Number")) def prime(num): count = 1 for i in range(1, num): if num % i == 0: count += 1 if count > 2: break if count == 2: return True return False def factor(x): for i in range(1, x+1): if x % i == 0 and prime(i): print(i,end=" ") factor(number)
b5c3a44e099edcc1974e5854b17e4b2475dc6a76
Appu13/RandomCodes
/DivideandConquer.py
678
4.1875
4
''' Given a mixed array of number and string representations of integers, add up the string integers and subtract this from the total of the non-string integers. Return as a number. ''' def div_con(x): # Variable to hold the string total strtot = 0 # Variable to hold the digit total digitot = 0 # Iterate through the list for ch in x: # Check if the current element is of type string if isinstance(ch, str): # Convert to integer and add to string total strtot += int(ch) # Else add to digit total else: digitot += ch # return the difference return digitot - strtot
f71b9304377348916257e65a8fbcc29d3ed3652e
socrates77-sh/learn
/IntroAlgorithms/part1.py
7,270
3.609375
4
import numpy as np from my_exception import * def instersion_sort(a_list): for j in range(1, len(a_list)): key = a_list[j] i = j-1 while i >= 0 and a_list[i] > key: a_list[i+1] = a_list[i] i = i-1 a_list[i+1] = key return a_list def selection_sort(a_list): for j in range(0, len(a_list)-1): smallest = j for i in range(j+1, len(a_list)): if a_list[i] < a_list[smallest]: smallest = i tmp = a_list[j] a_list[j] = a_list[smallest] a_list[smallest] = tmp return a_list def merge(left_list, right_list): merge_list = [] i = j = 0 for k in range(len(left_list)+len(right_list)+1): if left_list[i] <= right_list[j]: merge_list.append(left_list[i]) i += 1 if i >= len(left_list): merge_list += right_list[j:] break else: merge_list.append(right_list[j]) j += 1 if j >= len(right_list): merge_list += left_list[i:] break return merge_list def merge_sort(a_list): if len(a_list) <= 1: return a_list half_index = int(len(a_list)/2) left = a_list[:half_index] right = a_list[half_index:] left_sorted = merge_sort(left) right_sorted = merge_sort(right) return merge(left_sorted, right_sorted) def bubble_sort(a_list): for i in range(0, len(a_list)-1): for j in range(len(a_list)-1, i, -1): if a_list[j] < a_list[j-1]: tmp = a_list[j] a_list[j] = a_list[j-1] a_list[j-1] = tmp return a_list def find_max_crossing_subarray(a_list, low, mid, high): left_sum = sum = a_list[mid] max_left = mid for i in range(mid-1, low-1, -1): sum = sum+a_list[i] if sum > left_sum: left_sum = sum max_left = i right_sum = sum = a_list[mid+1] max_right = mid+1 for i in range(mid+2, high+1, 1): sum = sum+a_list[i] if sum > right_sum: right_sum = sum max_right = i return (max_left, max_right, left_sum+right_sum) def find_max_subarray(a_list, low, high): if(high == low): return (low, high, a_list[low]) else: mid = int((low+high)/2) (left_low, left_high, left_sum) = find_max_subarray(a_list, low, mid) (right_low, right_high, right_sum) = find_max_subarray(a_list, mid+1, high) (cross_low, cross_high, cross_sum) = find_max_crossing_subarray( a_list, low, mid, high) if left_sum >= right_sum and left_sum >= cross_sum: return (left_low, left_high, left_sum) if right_sum >= left_sum and right_sum >= cross_sum: return (right_low, right_high, right_sum) else: return (cross_low, cross_high, cross_sum) def square_matrix_multiply(a, b): if a.shape != b.shape: raise NotSameSizeError('two matrix are not same size') n = a.shape[0] m = a.shape[1] if not n == m: raise NotSquareError('matrix is not square') c = np.zeros(a.shape) for i in range(n): for j in range(n): c[i][j] = 0 for k in range(n): c[i][j] += a[i][k]*b[k][j] return c def square_matrix_multiply_recursive(a, b): if a.shape != b.shape: raise NotSameSizeError('two matrix are not same size') n = a.shape[0] m = a.shape[1] if not n == m: raise NotSquareError('matrix is not square') if n & (n-1) != 0: raise NotPowOfTwoError('matrix row/cloumn is not power of 2') c = np.zeros(a.shape) if n == 1: c = a*b return c else: h = int(n/2) a11 = a[:h, :h] a12 = a[:h, h:] a21 = a[h:, :h] a22 = a[h:, h:] b11 = b[:h, :h] b12 = b[:h, h:] b21 = b[h:, :h] b22 = b[h:, h:] c[:h, :h] = \ square_matrix_multiply_recursive(a11, b11) + \ square_matrix_multiply_recursive(a12, b21) c[:h, h:] = \ square_matrix_multiply_recursive(a11, b12) + \ square_matrix_multiply_recursive(a12, b22) c[h:, :h] = \ square_matrix_multiply_recursive(a21, b11) + \ square_matrix_multiply_recursive(a22, b21) c[h:, h:] = \ square_matrix_multiply_recursive(a21, b12) + \ square_matrix_multiply_recursive(a22, b22) return c def square_matrix_multiply_strassen(a, b): if a.shape != b.shape: raise NotSameSizeError('two matrix are not same size') n = a.shape[0] m = a.shape[1] if not n == m: raise NotSquareError('matrix is not square') if n & (n-1) != 0: raise NotPowOfTwoError('matrix row/cloumn is not power of 2') c = np.zeros(a.shape) if n == 1: c = a*b return c else: h = int(n/2) a11 = a[:h, :h] a12 = a[:h, h:] a21 = a[h:, :h] a22 = a[h:, h:] b11 = b[:h, :h] b12 = b[:h, h:] b21 = b[h:, :h] b22 = b[h:, h:] p1 = square_matrix_multiply_strassen(a11, b12) - \ square_matrix_multiply_strassen(a11, b22) p2 = square_matrix_multiply_strassen(a11, b22) + \ square_matrix_multiply_strassen(a12, b22) p3 = square_matrix_multiply_strassen(a21, b11) + \ square_matrix_multiply_strassen(a22, b11) p4 = square_matrix_multiply_strassen(a22, b21) - \ square_matrix_multiply_strassen(a22, b11) p5 = square_matrix_multiply_strassen(a11, b11) + \ square_matrix_multiply_strassen(a11, b22) + \ square_matrix_multiply_strassen(a22, b11) + \ square_matrix_multiply_strassen(a22, b22) p6 = square_matrix_multiply_strassen(a12, b21) + \ square_matrix_multiply_strassen(a12, b22) - \ square_matrix_multiply_strassen(a22, b21) - \ square_matrix_multiply_strassen(a22, b22) p7 = square_matrix_multiply_strassen(a11, b11) + \ square_matrix_multiply_strassen(a11, b12) - \ square_matrix_multiply_strassen(a21, b11) - \ square_matrix_multiply_strassen(a21, b12) c[:h, :h] = p5+p4-p2+p6 c[:h, h:] = p1+p2 c[h:, :h] = p3+p4 c[h:, h:] = p5+p1-p3-p7 return c def main(): m_size = (4, 4) a = np.random.randint(-100, 100, size=m_size) b = np.random.randint(-100, 100, size=m_size) c1 = square_matrix_multiply_strassen(a, b) c2 = square_matrix_multiply(a, b) print(a) print(b) print(c1) print(c2) # h = int(a.shape[0]/2) # print(a) # # print(b) # print('h=%d' % h) # a11 = a[:h, :h] # a12 = a[:h, h:] # a21 = a[h:, :h] # a22 = a[h:, h:] # print(a11) # print(a12) # print(a21) # print(a22) if __name__ == '__main__': main()
5a1793eadbe83d9a908e49dc320262c967cb2e13
molchiro/AtCoder
/old/ABC131/D.py
336
3.53125
4
def main(): N = int(input()) tasks = [] for i in range(N): tasks.append(list(map(int, input().split()))) tasks.sort(key=lambda x: x[1]) t = 0 for task in tasks: t += task[0] if t > task[1]: print('No') return print('Yes') if __name__ == "__main__": main()
f75b9ad9a002436828009a5589074e0d046cb09d
molchiro/AtCoder
/old/ABC196/B.py
84
3.515625
4
S = input() if '.' in S: ans, _ = S.split('.') print(ans) else: print(S)
e19bdfad1b2ec8290eeb59a1aaa33f5bab3b922a
molchiro/AtCoder
/ARC114/B.py
806
3.875
4
# UFして個数を数える # ループを持っているものが有効 # 2^n-1が答え class union_find: def __init__(self, N): self.par = [i for i in range(N)] def root(self, i): if self.par[i] == i: return i else: # 経路圧縮 self.par[i] = self.root(self.par[i]) return self.par[i] def same(self, a, b): return self.root(a) == self.root(b) def unite(self, a, b): if not self.same(a, b): self.par[self.root(a)] = self.root(b) N = int(input()) f_list = list(map(lambda x: int(x) - 1, input().split())) UF = union_find(N) for i, to in enumerate(f_list): UF.unite(i, to) roots = set() for i in range(N): roots.add(UF.root(i)) print((2**len(roots)-1)%998244353)
7a049ad9b04e1243ad1f440447d89fe112979633
Mvk122/misc
/CoinCounterInterviewQuestion.py
948
4.15625
4
""" Question: Find the amount of coins required to give the amount of cents given The second function gets the types of coins whereas the first one only gives the total amount. """ def coin_number(cents): coinlist = [25, 10, 5, 1] coinlist.sort(reverse=True) """ list must be in descending order """ cointotal = 0 while cents != 0: for coin in coinlist: if coin <= cents: cents -= coin cointotal += 1 break return cointotal def cointype(cents): coinlist = [25, 10, 5, 1] coinlist.sort(reverse=True) coincount = [[25,0], [10,0], [5,0], [1,0]] while cents != 0: for coin in coinlist: if coin <= cents: cents -= coin coincount[coinlist.index(coin)][1] += 1 break return coincount print(coin_number(50))
3214b2aee8eb0e99219132a7e53dd94fac966b6b
Mvk122/misc
/pisolver.py
317
3.84375
4
""" Solves for pi given random numbers between 0 and 1 """ from random import random def dist_from_origin(x,y): return (x**2 + y**2)**0.5 in_circle = 0 step = 100000 for i in range(step): x = random() y = random() if dist_from_origin(x,y) <= 1: in_circle += 1 print(4 * in_circle/step)
2af3d6bb8639cb85458007f533a0d416a9927718
Yusra04/Assignment-1
/yusra4.py
229
3.96875
4
newList = [12,35,9,56,34] def swapList(newList): size = len(newList) temp = newList[0] newList[0] = newList[size - 1] newList[size - 1] = temp return newList print("list after swapping:",swapList(newList))
c0e648e64683095d35d3b2989bd0ad57f00dbe64
yadhukrishnam/ProblemSolving
/Codeforces/1230A.py
162
3.546875
4
a,b,c,d = list(map(int, input().split())) print ("YES" if a+b+c == d or a+b+d==c or b+d+c == a or c+a+d == b or a+b == c+d or a+c == b+d or d+a == b+c else "NO" )
6abf0887385dbb4e5a113a319aaa99960f7d803a
yadhukrishnam/ProblemSolving
/Codeforces/339A.py
146
3.859375
4
math = input().split('+') math.sort() for i in range(len(math)): print (math[i], end='') if i!=len(math)-1: print ('+', end='')
08ee0fe594e47e38e12e85e95ea60c73f5bda6e3
Rxy-J/BilibiliLiveRecorderV2
/libs/parserSize.py
558
3.546875
4
def getSize(size): counter = 0 while size > 1024: counter += 1 size /= 1024 size = round(size, 2) if counter == 0: size = str(size)+"bytes" elif counter == 1: size = str(size)+"KB" elif counter == 2: size = str(size)+"MB" elif counter == 3: size = str(size)+"GB" elif counter == 4: size = str(size)+"TB" elif counter == 5: size = str(size)+"PB" elif counter == 6: size = str(size)+"ZB" else: size = "您太离谱了" return size
0fbadc167cbe38b93d0a964cb260fad9e22c5eb1
JackTJC/LeetCode
/Math/Divide.py
1,533
3.609375
4
# 29. 两数相除 # 给定两个整数,被除数 dividend 和除数 divisor。将两数相除,要求不使用乘法、除法和 mod 运算符。 # # 返回被除数 dividend 除以除数 divisor 得到的商。 # # 整数除法的结果应当截去(truncate)其小数部分,例如:truncate(8.345) = 8 以及 truncate(-2.7335) = -2 class Solution: def divide(self, dividend: int, divisor: int) -> int: def binary2decimal(binary): i = 1 sum = 0 for bit in binary[::-1]: sum += i if bit == '1' else 0 i <<= 1 return sum def binarySub(d1, d2): res = binary2decimal(d1) - binary2decimal(d2) return bin(res)[2:] # 二进制除法算法 if abs(dividend) < abs(divisor): return 0 sign1 = True if dividend < 0 else False sign2 = True if divisor < 0 else False b1 = str(bin(abs(dividend)))[2:] b2 = str(bin(abs(divisor)))[2:] headerBits = "" res = [] for bit in b1: headerBits += bit if int(headerBits) >= int(b2): res.append('1') headerBits = binarySub(headerBits, b2) else: res.append('0') strAns = ''.join(res) sign = sign1 ^ sign2 ans = binary2decimal(strAns) ans = -ans if sign else ans if -2 ** 31 <= ans <= 2 ** 31 - 1: return ans else: return 2 ** 31 - 1
c2369a92a6280ff7003dd8a8745fceed184b957e
zmh93/algorithm
/algorithm_py/main/quicksort.py
1,882
3.5
4
arr = [ 2, 4, 5, 5, 6, 7, 11, 11, 11, 12, 12, 13, 13, 13, 13, 14, 16, 18, 19, 19, 19, 22, 22, 23, 27, 29, 29, 30, 31, 33, 37, 38, 38, 38, 39, 39, 40, 40, 41, 42, 42, 43, 43, 46, 46, 50, 50, 52, 55, 57, 57, 57, 58, 59, 59, 59, 59, 59, 60, 62, 65, 65, 65, 67, 68, 68, 68, 68, 71, 73, 73, 73, 73, 73, 73, 74, 75, 76, 76, 80, 82, 82, 83, 83, 86, 87, 91, 93, 93, 93, 93, 94, 94, 94, 95, 96, 96, 96, 97, 98] def binary_search(arr, aim): sign = 0 ret = binary_recursion(arr, aim, 0, len(arr), sign) if ret.isalpha(): return ret return ret if ret < 0 else "数组中不存在此值" def binary_recursion(arr, aim, s, b, sign): sign += 1 if sign == 997: return "递归过深" mid = s + b >> 1 if s > b: return -1 if arr[mid] == aim: return mid elif arr[mid] > aim: return binary_recursion(arr, aim, s, mid, sign) elif arr[mid] < aim: return binary_recursion(arr, aim, mid, b, sign) def select_sort(arr): length = len(arr) min = 0 for i in range(0, length - 1): min = i for j in range(i + 1, length): if arr[min] > arr[j]: min = j temp = arr[i] arr[i] = arr[min] arr[min] = temp def insert_sort(arr): length = len(arr) for i in range(1, length): temp = arr[i] j = i - 1 while j >= 0 and arr[j] > temp: arr[j + 1] = arr[j] j -= 1 arr[j + 1] = temp def bubble_sort(arr): length = len(arr) for i in range(1, length): for j in range(i, length).__reversed__(): if arr[j] < arr[j - 1]: temp = arr[j] arr[j] = arr[j - 1] arr[j - 1] = temp # select_sort(arr) # insert_sort(arr) # bubble_sort(arr) ret = binary_search(arr, 32) print(ret) print(arr)
3659873714b860773c3ad625e98cff815afa6d24
ivvovk/homework1
/Main.py
2,089
3.8125
4
def step1(): print('Привет, '+uname+'. Я хочу сыграть с тобой в игру! ' 'Утка-маляр решила погулять.' 'Взять ей зонтик?') option='' options={'да': True, 'нет': False} while option not in options: print('Выберите: {}/{}'.format(*options)) option=input() if options[option]: return step2_umbrella() return step2_no_umbrella() def step2_umbrella(): print('Отличный выбор - ведь там сильный ливень. ' 'Теперь выбери, куда утке пойти гулять' ) option='' options={'кино': True, 'кофейня': False} while option not in options: print('Выберите: {}/{}'.format(*options)) option=input() if options[option]: return step3_movie() return step3_cafe() def step2_no_umbrella(): print('Там ливень, утка промокнет :(' 'Она возьмет такси или пойдет пешком?' ) option='' options={'такси': True, 'пешком': False} while option not in options: print('Выберите: {}/{}'.format(*options)) option=input() if options[option]: return step3_company() return step3_final() def step3_final(): print('Дождь и пешком? утка обиделась - game over') def step3_movie(): print('Но утка старая и плохо видит, она обиделась и остается дома.. ' 'game over' ) def step3_cafe(): print('Отлично! это именно то, о чем мечтала утка :)') def step3_company(): print('На такси можно и без зонта:)' ) return step2_umbrella() uname=input("Привет! как тебя зовут?" "") if __name__ == '__main__': step1()
66ef5fe01c8646a41fd47263baf6fb45a636e563
huqa/sudoku-solver
/solver.py
5,077
3.671875
4
# Simple brute force sudoku solver # # author: huqa (pikkuhukka@gmail.com) S_NUMBERS = [1,2,3,4,5,6,7,8,9] def change_zeroes_to_nones(grid): '''Changes zeroes to None in grid''' for i in range(0, len(grid)): for j in range(0, len(grid[i])): if grid[i][j] == 0: grid[i][j] = None return grid def bf_solution(grid_to_solve): '''A brute force solution for solving sudokus''' # spot is tuple with (y,x,number) spots = [] grid = list(grid_to_solve) last_spot = () nx = 0 ny = 0 while not is_solved(grid): if grid[ny][nx] == None or last_spot: is_good = False i = 1 if last_spot: i = last_spot[2] ny = last_spot[0] nx = last_spot[1] i += 1 while not is_good_candidate(nx, ny, i, grid): i += 1 if i > 9: grid[ny][nx] = None last_spot = spots.pop() break else: spots.append((ny,nx,i)) last_spot = () grid[ny][nx] = i is_good = True nx += 1 if nx >= 9: ny += 1 nx = 0 else: nx += 1 if nx >= 9: ny += 1 nx = 0 return grid def is_legal_for_row(num, y, grid): '''Checks if num is legal for the row''' for rx in range(0,9): if grid[y][rx] == num: return False return True def is_legal_for_column(num, x, grid): '''Checks if num is legal for the column''' for ry in range(0,9): if grid[ry][x] == num: return False return True def is_good_candidate(x, y, num, grid): '''Checks if num is a legal candidate for spot x,y''' sx, sy = find_zone(x,y) tbt = threebythree_candidates(sy, sx, grid) if num in tbt: if is_legal_for_column(num, x, grid) and is_legal_for_row(num, y, grid): return True else: return False else: return False def find_zone(x,y): '''Finds a zone (3x3) for a position''' spot_x = 0 spot_y = 0 if x >= 0 and x <= 2: spot_x = 1 elif x >= 3 and x <= 5: spot_x = 2 elif x >= 6 and x <= 8: spot_x = 3 if y >= 0 and y <= 2: spot_y = 1 elif y >= 3 and y <= 5: spot_y = 2 elif y >= 6 and y <= 8: spot_y = 3 return spot_x, spot_y def find_start_pos(sx,sy): '''Finds a starting position in the grid for a zone''' start_x = 0 start_y = 0 if sy == 1: start_y = 0 elif sy == 2: start_y = 3 elif sy == 3: start_y = 6 if sx == 1: start_x = 0 elif sx == 2: start_x = 3 elif sx == 3: start_x = 6 return start_x, start_y def threebythree_candidates(sy, sx, grid): '''Finds all legal candidates for a zone (3x3)''' start_x, start_y = find_start_pos(sx,sy) possible_numbers = [] for y in range(start_y, start_y+3): for x in range(start_x, start_x+3): if grid[y][x] != None: possible_numbers.append(grid[y][x]) return list(set(S_NUMBERS) - set(possible_numbers)) def is_solved(grid): '''Checks if a grid is solved completely''' if grid == None: return False for row in grid: if set(row) != set(S_NUMBERS): return False for row in range(0,9): column = [] for c in range(0,9): column.append(grid[row][c]) if set(column) != set(S_NUMBERS): return False for i in range(1,4): for j in range(1,4): sx, sy = find_start_pos(i,j) if threebythree_candidates(sy, sx, grid): return False return True def print_grid(grid): '''Ugly print given grid''' k = 1 l = 0 print("|===|===|===|===|===|===|===|===|===|") for i in grid: for j in i: if j == None: j = 0 if l % 3 == 0: print "# %d" % j, else: print "| %d" % j, l += 1 if l % 3 == 0: print "#" else: print "|" if k % 3 == 0: print("|===|===|===|===|===|===|===|===|===|") else: if l % 3 == 0: print("# | | # | | # | | #") else: print("| | | | | | | | | |") k += 1 print("") if __name__ == '__main__': sudoku = [[0,0,7,4,0,0,0,0,9], [3,9,0,0,8,0,0,4,1], [0,0,5,2,0,0,0,3,0], [0,0,4,6,2,3,0,0,0], [0,2,9,8,0,4,6,7,0], [0,0,0,9,7,1,8,0,0], [0,3,0,0,0,7,1,0,0], [9,7,0,0,6,0,0,5,8], [5,0,0,0,0,8,3,0,0]] print_grid(sudoku) sudoku = change_zeroes_to_nones(sudoku) print_grid(bf_solution(sudoku))
d25ac7c10ce42fed83f392ed9c5a02a3246eb146
Svanfridurjulia/FORRITUN-SJS-HR
/Verkefni í tímum/assignment 3 while/assignment3.6.py
222
4.125
4
a0 = int(input("Input a positive int: ")) # Do not change this line print(a0) while a0 != 1: if a0 % 2 == 0: a0 = a0/2 print(int(a0)) elif a0 % 2 != 0: a0 = 3*a0+1 print(int(a0))
594a8617abbfcd4175d45ff721b03d6f77425665
Svanfridurjulia/FORRITUN-SJS-HR
/Hlutapróf 2/babynames.3.py
3,394
4.28125
4
def open_file(filename): '''A function which tries to open the file and return it if the file is found. Otherwise it prints out error message''' try: opened_file = open(filename,"r") return opened_file except FileNotFoundError: print("File {} not found".format(filename)) def make_list(opened_file): '''A function which takes the opened file and makes lists within a list and returns that list''' baby_list = [] for lines in opened_file: line_list = lines.split("\t") baby_list.append(line_list) return baby_list def convert_to_int(baby_list): '''A function which converts the numbers to int and returns a list of lists containing both strings and ints''' final_list = [] for lists in baby_list: list1 = [] for elements in lists: try: list1.append(int(elements)) except ValueError: list1.append(elements) final_list.append(list1) return final_list def first_two(final_list): '''A function which creates a list with only the first two elements in final_list and returns it''' print_list = [] for lists in final_list: if len(print_list) < 2: print_list.append(lists) return print_list def first_five_list(final_list): '''A function which creates a list of the first five girl names and onether list of the first five boy names and returns both lists''' girl_list=[] boy_list = [] for lines in final_list: if len(girl_list) < 5: girl_list.append(lines[-2:]) if len(boy_list) < 5: boy_list.append(lines[1:3]) return girl_list, boy_list def list_frequencies(final_list): '''A function that makes two seperate lists, one with all the girl frequencies and the other with all the boy frequencies, and returns them''' b_list_frequencies = [] g_list_frequencies = [] #b stands for boys and g for girls for lines in final_list: b_list_frequencies.append(lines[2]) g_list_frequencies.append(lines[4]) return b_list_frequencies, g_list_frequencies def call_functions(opened_file): '''A function which calls other functions and returns nothing''' baby_list= make_list(opened_file) final_list = convert_to_int(baby_list) print_list = first_two(final_list) girl_list, boy_list = first_five_list(final_list) b_list_frequencies, g_list_frequencies = list_frequencies(final_list) frequency_boys, frequency_girls = find_frequency(b_list_frequencies,g_list_frequencies) print_func(print_list,boy_list,girl_list,frequency_boys,frequency_girls) def find_frequency(boy_list,girl_list): '''A function which finds the total frequency of all boy names and then of all the girl names and returns them ''' boy_frequency = sum(boy_list) girl_frequency = sum(girl_list) return boy_frequency, girl_frequency def print_func(list1,list2,list3,frequency_boys,frequency_girls): '''A Function which prints the output and returns nothing''' print(list1) print(list2) print(list3) print("Total frequency of boy names:",frequency_boys) print("Total frequency of girl names:",frequency_girls) #Main filename = input("Enter file name: ") opened_file = open_file(filename) if opened_file != None: call_functions(opened_file)
583bfced1f6e8059c86a80fb64cf757db6cdde6d
Svanfridurjulia/FORRITUN-SJS-HR
/Verkefni í tímum/assignment 10 listar/assignment10.3.1.py
489
4.03125
4
def add_word(): word = "" while word != "x": word = input("Enter word to be added to list: ") if word != "x": first_list.append(word) def word_list(): for word in first_list: if len(word) > 1: if word[0] == word[-1]: second_list.append(word) def print_second_list(): for word in second_list: print(word) first_list = [] second_list = [] add_word() print(first_list) word_list() print_second_list()
8ce075118b7aca2dd2dc8f54eb59146e8c4edaf4
Svanfridurjulia/FORRITUN-SJS-HR
/Hlutapróf 2/prófdæmi.py
1,553
4.3125
4
def sum_number(n): '''A function which finds the sum of 1..n and returns it''' sum_of_range = 0 for num in range (1,n+1): sum_of_range += num return sum_of_range def product(n): '''A function which finds the product of 1..n and returns it''' multi = 1 for num in range(1,n+1): multi = multi * num return multi def print_choices(): '''A function which prints the choices and gets the choice from the user and returns it''' print("""1: Compute the sum of 1..n 2: Compute the product of 1..n 9: Quit""") choice = input("Choice: ") return choice def choice_1(int_list): '''A function for the choice 1 which calls the sum function and prints out the sum, returns nothing''' sum_of_numbers = sum_number(int_list) print("The result is:",sum_of_numbers) def choice_2(int_list): '''A function for the choice 2 which calls the product function and prints out the product, returns nothing''' product_of_numbers = product(int_list) print("The result is:",product_of_numbers) def choices(choice, n): '''A function which calls other functions depending on what the user choice is and returns nothing''' if choice == "1": choice_1(n) elif choice == "2": choice_2(n) #Main choice = print_choices() while choice != "9": if choice == "1" or choice == "2": try: n = int(input("Enter value for n: ")) choices(choice, n) except ValueError: pass choice = print_choices()
7c041a0333ad9a58383c495981485c535f6aa8bd
Svanfridurjulia/FORRITUN-SJS-HR
/æfingapróf/dæmi2.py
878
4.21875
4
def open_file(filename): opened_file = open(filename,"r") return opened_file def make_list(opened_file): file_list = [] for lines in opened_file: split_lines = lines.split() file_list.append(split_lines) return file_list def count_words(file_list): word_count = 0 punctuation_count = 0 for lines in file_list: for element in lines: word_count += 1 for chr in element: if chr == "," or chr == "." or chr == "!" or chr == "?": punctuation_count += 1 return word_count + punctuation_count #main filename = input("Enter filename: ") try: opened_file = open_file(filename) file_list = make_list(opened_file) word_count = count_words(file_list) print(word_count) except FileNotFoundError: print("File {} not found!".format(filename))
a21a95fe8e825f0f09618cc3bcb6429dee540b70
Svanfridurjulia/FORRITUN-SJS-HR
/Verkefni í tímum/assignment 3 while/Assignment3.1.py
106
4.03125
4
num = int(input("Input an int: ")) # Do not change this line while num > 0: print(num) num -= 1
e96457e428d89fa70a8c586aeaf12921e84f2948
Svanfridurjulia/FORRITUN-SJS-HR
/Verkefni í tímum/assignment 9 files and exception/assignment9.1.py
274
3.890625
4
def remove_whitespaces(opened_file): for line in opened_file: print(line.strip().replace(" ", ""), end = "") return True file_name = input("Enter filename: ") opened_file = open("data.txt", "r") readfile = remove_whitespaces(opened_file) print(readfile)
9be417a8ba86044f1b8717d993f44660adfbf9cd
Svanfridurjulia/FORRITUN-SJS-HR
/æfing.py
1,056
4.3125
4
def find_and_replace(string,find_string,replace_string): if find_string in string: final_string = string.replace(find_string,replace_string) return final_string else: print("Invalid input!") def remove(string,remove_string): if remove_string in string: final2_string = string.replace(remove_string,"") return final2_string else: print("Invalid input!") first_string = input("Please enter a string: ") print("""\t1. Find and replace \t2. Find and remove \t3. Remove unnecessary spaces \t4. Encode \t5. Decode \tQ. Quit""") option = input("Enter one of the following: ") if option == "1": find_string = input("Please enter substring to find: ") replace_string = input("Please enter substring to replace with: ") final1_string = find_and_replace(first_string,find_string,replace_string) print(final1_string) elif option == "2": remove_string = input("Please enter substring to remove: ") final2_string = remove(first_string,remove_string) print(final2_string)
ad54a59bba32e1563975822c184df6cd0881b223
Svanfridurjulia/FORRITUN-SJS-HR
/Hlutapróf1/dog_age.py
790
4.09375
4
dog_age = int(input("Input dog's age: ")) # Do not change this line human = 16 if 0 < dog_age < 17: human_count = dog_age * human - (dog_age*dog_age*dog_age) print("Human age:", int(human_count)) else: print("Invalid age") if 1 < dog_age < 17: human_age = human + dog_age * 4 + 1 print("Human age:", human_age) elif dog_age == 1: print("Human age:", human) else: print("Invalid age") #1.User input #2.Create one variable outside the if statement #2a. One variable for the starting human age #3.Use if statement for when the dog_age is more than 1 but less than 17 #3a. calculate the human age #4.Use elif statement for when the dog_age is equal to 1 #4a.The calculations work after dog_age = 2 #5.Else is for when the dog_age is less than 0
f0d663cbc1f64b3d08e61927d47f451272dfd746
Hiradoras/Python-Exercies
/30-May/Valid Parentheses.py
1,180
4.375
4
''' Write a function that takes a string of parentheses, and determines if the order of the parentheses is valid. The function should return true if the string is valid, and false if it's invalid. Examples "()" => true ")(()))" => false "(" => false "(())((()())())" => true Constraints 0 <= input.length <= 100 Along with opening (() and closing ()) parenthesis, input may contain any valid ASCII characters. Furthermore, the input string may be empty and/or not contain any parentheses at all. Do not treat other forms of brackets as parentheses (e.g. [], {}, <>). ''' def valid_parentheses(string): is_valid = None cleared = "".join(i for i in string if i=="(" or i==")") uncompletes = [] for i in range(len(cleared)): if cleared[i]=="(": uncompletes.append(cleared[i]) elif cleared[i]==")": try: uncompletes.pop() except: return False if len(uncompletes) == 0: is_valid = True else: is_valid = False return is_valid print(valid_parentheses("()")) print(valid_parentheses("())")) print(valid_parentheses("((((()"))
cf9270abd93e8b59cdb717deeea731308bf5528d
Hiradoras/Python-Exercies
/29-May-2021/Reverse every other word in the string.py
895
4.25
4
''' Reverse every other word in a given string, then return the string. Throw away any leading or trailing whitespace, while ensuring there is exactly one space between each word. Punctuation marks should be treated as if they are a part of the word in this kata. ''' def reverse_alternate(string): words = string.split() new_words = [] for i in range(0,len(words)): if i % 2 == 0: new_words.append(words[i]) else: word = words[i] new_words.append(word[::-1]) return " ".join(new_words) print(reverse_alternate("Did it work?")) ############# Or ############### def shorter_reverse_alternative(string): return " ".join([element[::-1] if i % 2 else element for i,element in enumerate(string.split())]) print(shorter_reverse_alternative("Did it work?")) ### Same function but smarter and shorted with enumerate() method.
babfec5fcd6237914c59f824bddafcf2e737d7a9
wizardcalidad/Machine-Learning-Algorithms
/Logistic Regression/main.py
3,703
3.71875
4
import numpy as np import util import pdb def main(train_path, valid_path, save_path, save_img): """Problem: Logistic regression with Newton's Method. Args: train_path: Path to CSV file containing dataset for training. valid_path: Path to CSV file containing dataset for validation. save_path: Path to save predicted probabilities using np.savetxt(). save_img: Path to save plot classification. """ x_train, y_train = util.load_dataset(train_path, add_intercept=True) clf = LogisticRegression() clf.fit(x_train, y_train) x_eval, y_val = util.load_dataset(valid_path, add_intercept=True) predictions = clf.predict(x_eval) np.savetxt(save_path, predictions) print(clf.theta) util.plot(x_eval, y_val, clf.theta, save_img) class LogisticRegression: """Logistic regression with Newton's Method as the solver. Example usage: > clf = LogisticRegression() > clf.fit(x_train, y_train) > clf.predict(x_eval) """ def __init__(self, step_size=0.01, max_iter=1000000, eps=1e-5, theta_0=None, verbose=True): """ Args: step_size: Step size for iterative solvers only. max_iter: Maximum number of iterations for the solver. eps: Threshold for determining convergence. theta_0: Initial guess for theta. If None, use the zero vector. verbose: Print loss values during training. """ self.theta = theta_0 self.step_size = step_size self.max_iter = max_iter self.eps = eps self.verbose = verbose def fit(self, x, y): """Run Newton's Method to minimize J(theta) for logistic regression. Args: x: Training example inputs. Shape (n_examples, dim). y: Training example labels. Shape (n_examples,). """ # *** START CODE HERE *** if self.theta is None: self.theta = np.zeros(x.shape[1]) for _ in range(self.max_iter): temp_theta = self.theta log_likelihood = np.zeros(x.shape[1]) diagonal = [] for row_x, value_y in zip(x, y): gthetaX = 1.0/(1.0 + np.exp(-np.dot(self.theta.transpose(), row_x))) log_likelihood = log_likelihood + ((value_y - gthetaX)*row_x)/x.shape[0] diagonal.append(gthetaX*(1.0 - gthetaX)/x.shape[0]) D = np.diag(diagonal) H = np.dot(x.transpose(), D) #Hessian H = np.dot(H, x) #Inverse of The Hessian H_inverse = np.linalg.pinv(H) #Run Newton's Method to minimize J(theta) self.theta = self.theta - self.step_size*np.dot(H_inverse, -log_likelihood) diff = np.linalg.norm((self.theta - temp_theta), ord=1) #Threshold for determining convergence. if diff < self.eps: break def predict(self, x): """Return predicted probabilities given new inputs x. Args: x: Inputs of shape (n_examples, dim). Returns: Outputs of shape (n_examples,). """ predictions = [] for row_x in x: theta_x = np.dot(self.theta.transpose(), row_x) sigmoid = 1.0/(1.0 + np.exp(-theta_x)) predictions.append(sigmoid) return np.array(predictions) if __name__ == '__main__': main(train_path='ds1_train.csv', valid_path='ds1_valid.csv', save_path='logreg_pred_1.txt', save_img='logreg_pred_1.png') main(train_path='ds2_train.csv', valid_path='ds2_valid.csv', save_path='logreg_pred_2.txt', save_img='logreg_pred_2.png')
1f38b049d4a9e7f0b91ab23ce54fd3ecfa65c47a
viorato/compute_rational_links_genus
/continued_fractions.py
1,489
3.875
4
""" Continued fractions. """ from decimal import Decimal from fractions import Fraction class CFraction(list): """ A continued fraction, represented as a list of integer terms. """ def __init__(self, value, maxterms=15, cutoff=1e-10): if isinstance(value, (int, float, Decimal)): value = Decimal(value) remainder = int(value) self.append(remainder) while len(self) < maxterms: value -= remainder if value > cutoff: value = Decimal(1) / value remainder = int(value) self.append(remainder) else: break elif isinstance(value, (list, tuple)): self.extend(value) else: raise ValueError("CFraction requires number or list") def fraction(self, terms=None): "Convert to a Fraction." if terms is None or terms >= len(self): terms = len(self) - 1 while terms > 0 and self[terms] == 0: terms -= 2 if terms == 0: return Fraction(self[0],1) frac = Fraction(1,self[terms]) for t in reversed(self[1:terms]): frac = 1 / (frac + t) frac += self[0] return frac def __float__(self): return float(self.fraction()) def __str__(self): return "[%s]" % ", ".join([str(x) for x in self])
4768d84a53b7f0f91a47e43fd5764369cd1c8316
RickLicona/Algorithms_and_Data_structures
/Sorting_and_searching/quick_sort.py
1,770
3.984375
4
def quick_sort(a_list): quick_sort_helper(a_list, 0, len(a_list)-1) def quick_sort_helper(a_list, first, last): if first < last: split_point = partition(a_list, first, last) quick_sort_helper(a_list, first, split_point-1) quick_sort_helper(a_list, split_point+1, last) def partition(a_list, first, last): pivot_value = a_list[first] left_mark = first + 1 right_mark = last done = False while not done: while left_mark <= right_mark and a_list[left_mark] <= pivot_value: print("*******************") print("Left: ", left_mark) print("Right: ", right_mark) left_mark = left_mark + 1 print("C1") print(a_list) while a_list[right_mark] >= pivot_value and right_mark >= left_mark: print("*******************") print("Right:", right_mark) print("C2") right_mark = right_mark - 1 print(a_list) if right_mark < left_mark: print("*******************") print("Left: ", left_mark) print("Right: ", right_mark) done = True print("C3") print(a_list) else: print("*******************") print("Left: ", left_mark) print("Right: ", right_mark) temp = a_list[left_mark] a_list[left_mark] = a_list[right_mark] a_list[right_mark] = temp print("C4") print(a_list) print("C5") temp = a_list[first] a_list[first] = a_list[right_mark] a_list[right_mark] = temp return right_mark a_list = [54, 26, 93, 17, 77, 31, 44, 55, 20] quick_sort(a_list) print("\n \nFinal List:", a_list)