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
56ea49400b82ee1982b4103e4f34c9bee7b5e650
mekdeshub123/cap_lab_5
/five_days_forcast.py
1,191
3.59375
4
#the data request is limited to USA cities only import os import requests from datetime import datetime #retrieve key that stored in envromental variable key = os.environ.get('WEATHER_KEY') #print(key) print('----------------------------------------------') print('\nTHE DATA REQUEST IS LIMITED TO US CITIES ONLY') print('----------------------------------------------\n') city_name = input('Enter city: ')#user imputs for the name parameter city = city_name + ', us'# concatnates the user imput with value, us. query = {'q': city, 'units': 'imperial', 'appid':key}#parameter in query url = 'http://api.openweathermap.org/data/2.5/forecast' try: data = requests.get(url, params=query).json()# Fetch data using get method and put it into json file print(data) forecast_items = data['list']#storing data into list print('\n') for forecast in forecast_items:#loop through the list timestamp = forecast['dt'] date =datetime.fromtimestamp(timestamp)#convert to a readable date and time format temp = forecast['main']['temp'] print(f'at {date}temprature is {temp}')# put it to format string except: print('city cannot be found!')
b1da56330aaed2070bd2a2cf71e7905f800f11db
LaytonAvery/DigitalCraftsWeek1
/Day4/todolist.py
1,089
4.21875
4
choice = "" task = {} def add_task(choice): task = [{"title": name, "priority": priority}] task.append("") for key, value in task.append(""): print(key, value) # print(task) def delete_task(choice): del task def view_all(): for key, value in task.items(): print(key, value) choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) while True: choice = input(""" Welcome to your TODO app! Press 1 to 'Add Task'. Press 2 to 'Delete Task'. Press 3 to 'View All Tasks'. Press q to QUIT.""") print(choice) if choice == "1": name = input("Enter a task: ") priority = input("Enter task priority: ") add_task(choice) elif choice == "2": for items in task(): print(items) deletion = input("What would you like deleted? ") delete_task(choice) elif choice == "3": view_all() elif choice == "q": break
00aec8932d5749f9f5af478ebb9dbeff183a5c11
krizo/checkio
/quests/singleton.py
874
4.125
4
''' https://py.checkio.org/en/mission/capital-city/ You are an active traveler who have visited a lot of countries. The main city in the every country is its capital and each country can have only one capital city. So your task is to create the class Capital which has some special properties: the first created instance of this class will be unique and single, and all of the other instances should be the same as the very first one. Also you should add the name() method which returns the name of the capital. In this mission you should use the Singleton design pattern. ''' class Capital(object): __instance = None def __new__(cls, city): if Capital.__instance is None: Capital.__instance = object.__new__(cls) Capital.__instance.city = city return Capital.__instance def name(self): return self.city
a4267b4bc3cc1901c8f717b192af77f9feec37b3
yinglingwang07238422/csv2txt
/csv2txt/cmd.py
1,080
3.734375
4
#!/usr/bin/env python # encoding=utf-8 import os import argparse import csv2txt def convert_by_cmd(): # 参数定义 parser = argparse.ArgumentParser(description="Convert a csv file to token separator txt file") parser.add_argument('--version', '-v', action='version', version='%(prog)s version : v'+csv2txt.getVersion(), help='show the version') parser.add_argument('--separator', '-s', metavar='"\\t"', default= "\t", help='The separator between column, default is TAB(\\t)') parser.add_argument("csv", type=argparse.FileType('r'), help='input csv file path to convert') parser.add_argument("txt", type=argparse.FileType('w'), help='ouput txt file path') # 解析参数 args = parser.parse_args() csvPath=os.path.abspath(args.csv.name) txtPath=os.path.abspath(args.txt.name) separator=csv2txt.escapeSeparatorFlipDict.get(args.separator, args.separator); escapeSeparator= csv2txt.escapeSeparator(separator); print(u'Convert '+csvPath+' to ' +txtPath+ ' with separator '+ escapeSeparator) # 执行转换 csv2txt.convertByFile(args.csv, args.txt, separator);
ef657e61a2dfdac5e44aaa1187aa11c6f6713017
niraj36/test
/fizz_buzz.py
410
3.75
4
def fizz_buzz(start_value, end_value, fizz_value, buzz_value): count = start_value message = count while count <= end_value: if count % fizz_value == 0: message = 'Fizz' if count % buzz_value == 0: message += ' Buzz' elif count % buzz_value == 0: message = 'Buzz' print(message) count += 1 message = count
d8f3097c5b0dc01d85ee0b72006d1fdb8b6431e1
VioletM/student-python-graphics
/1.py
744
4
4
from tkinter import * ## Размеры холста: W = 600 # ширина H = 400 # высота ## Диаметр мячика: D = 10 ## Начальное положение мячика: X_START = 150 Y_START = 100 Win=Tk() c = Canvas(Win, width=W, height=H, bg='black') c.pack() ## Отрисовка поля: c.create_rectangle(30, 30, W - 30, H - 30, outline='white', width=8) c.create_line(W / 2, 30, W / 2, H - 30, fill='white', width=8, dash=(100, 10)) ## Ракетки и мячик: c.create_rectangle(X_START, Y_START, X_START + D, Y_START + D, fill='red') c.create_line(50, 150, 50, 200, fill='white', width=10) c.create_line(W - 50, 150, W - 50, 200, fill='white', width=10) Win.mainloop()
96d924eb36cf0b3e23c5a71d555ee6cd24970c11
Ola752/load-shed
/loadshed/utils/timing.py
2,509
4.03125
4
import timeit import datetime start_time = 0 lap_time = 0 # level 1 lap_time2 = 0 # level 2 def start(): """ Start timing :return: nothing """ global start_time global lap_time global lap_time2 start_time = lap_time = lap_time2 = timeit.default_timer() time_now = datetime.datetime.now() print(f'Started at {time_now.strftime("%I:%M%p")}') def lap(is_print_out=False): """ Calc the elapsed time from the previous lap (i.e. lap_time). :return: int """ global lap_time current_time = timeit.default_timer() s_out = time2str(current_time - lap_time) lap_time = current_time if is_print_out: print(s_out) return s_out def lap2(is_print_out=False): """ Calc the elapsed time from the previous lap (i.e. lap_time). :return: int """ global lap_time2 current_time = timeit.default_timer() s_out = time2str(current_time - lap_time2) lap_time2 = current_time if is_print_out: print(s_out) return s_out def stop(is_print_out=True): """ Print out the elapsed time from the start time (i.e. start_time). :return: nothing """ global start_time current_time = timeit.default_timer() time_now = datetime.datetime.now() s_out = 'Stopped at {}, total: {}'.format(time_now.strftime('%I:%M%p '), time2str(current_time - start_time)) if is_print_out: print(s_out) return s_out def stop_full(is_print_out=False): """ Print out the elapsed time from the start time (i.e. start_time). :return: nothing """ global start_time current_time = timeit.default_timer() time_now = datetime.datetime.now() s_out = 'Stopped at {} in {}'.format(time_now.strftime('%I:%M%p %d/%m/%Y'), time2str(current_time - start_time)) if is_print_out: print(s_out) return s_out def stop_inline(): """ Print out the elapsed time from the start time (i.e. start_time). :return: nothing """ global start_time current_time = timeit.default_timer() s_out = '[{}]'.format(time2str(current_time - start_time)) print(s_out) def time2str(seconds): """ Convert number of elapsed time (in seconds, a float number) to a string. :param seconds: e.g. 62.15 :return: e.g. 1m 2.15s """ if seconds < 60: s_out = '{:.2f}s'.format(seconds) else: mins = int(seconds / 60) seconds -= 60 * mins # float s_out = '{}m {:.2f}s'.format(mins, seconds) return s_out
81e3eb880ccd149f93bfe2a4bc6c48f86ad745b7
Diogo-Ferreira/astar_he_arc
/City.py
1,079
3.5625
4
""" Ferreira Venancio Diogo IA Class HE-ARC 2016 Class city """ class City(object): def __init__(self, name, x_pos, y_pos): self.name = name self.x_pos = float(x_pos) self.y_pos = float(y_pos) self.connections = {} self.gx = 0 self.parent = None def add_connection_to(self, to, distance): self.connections[to] = float(distance) def __str__(self): return self.name def __getitem__(self, item): """Allows to get the connection like: sourceCity['targetCity'] """ if item in self.connections: return self.connections[item] else: return 0 def __hash__(self): return str(self.name).__hash__() def __iter__(self): """Allows to iterate each connections""" return self.connections.items().__iter__() def __eq__(self, other): if isinstance(other, str): return self.name == other elif isinstance(other, City): return self.name == other.name else: return super.__eq__(other)
05c34a6a177cd48e5c8e1f2b05ef5413e2ec9b41
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/saymyname.py
206
3.90625
4
# ask the user for their name name = input('What is your name? ') # print their name 100 times for x in range(100): # print their name followed by a space,not a new line print(name,end = ' rules, ')
f5c9eb271fbd7da172fa9af87960faff1bd5f675
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/fibfunctions.py
267
4.15625
4
def fibonacci(num): print("printing fibonacci numbers till ", num) v = 1 v1 = 1 v2 = v + v1 print(v) print(v1) while v2 < num: print(v2) v = v1 v1 = v2 v2 = v + v1 fibonacci(10) fibonacci(20) fibonacci(500)
b85eddbab124941dcffd5c4918478fc3f9b8837b
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/Click-And-Smile.py
843
3.53125
4
# ClickAndSmile.py import random import turtle def draw_smiley(x, y): pen.penup() pen.setpos(x, y) pen.pendown() # Face pen.pencolor("yellow") pen.fillcolor("yellow") pen.begin_fill() pen.circle(50) pen.end_fill() # Left eye pen.setpos(x-15, y+60) pen.fillcolor("blue") pen.begin_fill() pen.circle(10) pen.end_fill() # Right eye pen.setpos(x+15, y+60) pen.begin_fill() pen.circle(10) pen.end_fill() # Mouth pen.setpos(x-25, y+40) pen.pencolor("black") pen.width(10) pen.goto(x-10, y+20) pen.goto(x+10, y+20) pen.goto(x+25, y+40) pen.width(1) pen = turtle.Pen() pen.speed(0) pen.hideturtle() turtle.bgcolor("black") turtle.onscreenclick(draw_smiley) turtle.getscreen()._root.mainloop()
b77b996655f2c3a53acf170a6b4b7f78fc9051ac
abhishektzr/sangini
/learning-python_Teach-Your-Kids-to Code/circlescolour.py
350
3.875
4
import turtle t = turtle.Pen() colours = ["red", "yellow", "blue", "green","orange", "purple", "white", "gray",'pink','light blue','brown', 'light green'] t.speed(20) for x in range(12): t.fillcolor(colours[x % colours.__sizeof__()]) t.begin_fill() t.circle(100) t.end_fill() t.left(30) turtle.textinput("Enter your name", "Done")
68e086044625f54a75bf362a4dd6d63c4632cff6
NALM98/Homework-Course-1
/HW3/HW1.py
1,689
4.125
4
print("Введите, пожалуйста,три любых числа") a = int(input()) b = int(input()) c = int(input()) #1. a и b в сумме дают c #2. a умножить на b равно c #3. a даёт остаток c при делении на b #4. c является решением линейного уравнения ax + b = 0 #5. a разделить на b равно c #6. a в степени b равно c. #1 if a+b == c: print("Сумма чисел a и b равна числу c") else: print("Сумма чисел a и b не равна числу c") #2 if a*b == c: print("Произведение чисел a и b равно числу c") else: print("Произведение чисел a и b не равно числу c") #3 if a%b == c: print ("Число a даёт остаток, равный числу c при делении на число b") else: print ("Число a не даёт остаток, равный числу c при делении на число b") #4 if -1*b/a == c: print("Число c является решением линейного уравнения ax+b") else: print("Число c не является решением линейного уравнения ax+b") #5 if a/b == c: print("Частное от деления числа a на число b равно числу c") else: print("Частное от деления числа a на число b не равно числу c") #6 if a**b == c: print("Число a в степени b равно числу с") else: print("Число a в степени b не равно числу c")
c1820b939c67c0a7587026e6434419e4f7e5667d
filipmihal/ml-coursera-python-coursework
/regression/linear.py
2,071
4.03125
4
import os from abstract import AbstractRegression import numpy as np from matplotlib import pyplot from scipy import optimize class LinearRegression(AbstractRegression): """Linear regression class""" def plot_data(self): index = 0 for feature in self.get_features().transpose(): index += 1 pyplot.plot(feature, self.labels, 'ro', ms=10, mec='k') pyplot.ylabel('labels') pyplot.xlabel('features ' + str(index)) pyplot.show() def cost_function(self, theta: np.ndarray) -> np.ndarray: """ Compute cost for linear regression. Computes the cost of using theta as the parameter for linear regression to fit the data points in X and y. :param theta :return: """ matrix = np.subtract(np.dot(self.features, theta), self.labels) J = np.dot(matrix.transpose(), matrix) / (2 * self.labels.size) return J def gradient(self, theta: np.ndarray, alpha: float) -> np.ndarray: # compute gradient for the constants # compute the rest of gradients for all features output = np.zeros(self.features.shape[1]) #add to the first row of the output k = 0 output[k] = alpha * np.sum(np.dot(self.features, theta) - self.labels) / self.labels.size for feature in self.get_features().transpose(): k += 1 output[k] = alpha * np.dot(np.dot(self.features, theta) - self.labels, feature) / self.labels.size return output def minimize_cost(self, theta: np.ndarray): # number of iterations output = optimize.minimize(self.cost_function, theta, jac=True, method='TNC', options={'maxiter': 400}) return output.x def predict(self, theta: np.ndarray): print("ahoj") data = np.loadtxt(os.path.join('../Exercise1/Data', 'ex1data1.txt'), delimiter=',') X, y = data[:, 0], data[:, 1] linear_regression = LinearRegression(X.T, y) linear_regression.plot_data() linear_regression.gradient(np.array([0, 0]), 0.01)
5e92cdb5639fdf7277da9808d00f3acddcf7c8f6
SwethaGullapalli/PythonTasks
/FolderComparision.py
1,358
3.796875
4
import os import shutil Folderpath1=raw_input("please enter first folder name : ") Folderpath2=raw_input("please enter second folder name : ") needmatchedfiles=raw_input("do you want matched files? ") needmatchedfiles=needmatchedfiles=="yes" donotneedmatchedfiles=raw_input("do you want unmatched files? ") donotneedmatchedfiles=donotneedmatchedfiles=="yes" print needmatchedfiles print donotneedmatchedfiles list1=[] list2=[] matchedlist=[] unmatchedlist=[] if os.path.isdir(Folderpath1): print "This is a folder1" Folderfiles1=os.listdir(Folderpath1) print Folderfiles1 if os.path.isdir(Folderpath2): print "This is a folder2" Folderfiles2=os.listdir(Folderpath2) print Folderfiles2 for Filename1 in Folderfiles1: if os.path.isfile(Folderpath1 +'\\'+ Filename1): list1.append(Filename1) for Filename2 in Folderfiles2: if os.path.isfile(Folderpath2 + "\\"+ Filename2): list2.append(Filename2) for i in list1:#a.txt,b.txt for j in list2:#c.txt,d.txt,a.txt if needmatchedfiles: if i==j: matchedlist.append(i) else: if i not in unmatchedlist : unmatchedlist.append(i) if j not in unmatchedlist : unmatchedlist.append(j) if needmatchedfiles: print "List is Matched and the matched list is %s"%matchedlist if donotneedmatchedfiles: print"List is not matched and the unmatched list is %s"%unmatchedlist
2c4041af39e9c050adb9f1aa6352a6b9c25c8436
SwethaGullapalli/PythonTasks
/PrintFileNameHavingPy.py
866
4.375
4
#program to print the file extension having py """give input as list of file names iterate each file name in file names list declare one variable for holding file extension declare variables for index and dot index iterate each character in the file name increment the index by 1 if Character is equal to "." assign index to dot index if index is greater than or equal to dot index concatenate the character to file extension variable if .py== file extension variable print file name""" FileNameList = ["blue.py","black.txt","orange.log","red.py"] for FileName in FileNameList: FileExtension="" Index =0 DotIndex = -1 for Character in FileName: if Character == ".": DotIndex = Index if Index>=DotIndex and DotIndex!=-1: FileExtension=FileExtension+Character Index+=1 if".py" == FileExtension: print FileName
a3649f42792c2945eccc395db2b53e2a5beeaec1
berkio3x/pyray3d
/vector.py
1,451
3.5
4
import math class Vec3: def __init__(self, x, y, z): self.x = x self.y = y self.z = z def __str__(self): return f'Vec3({self.x},{self.y},{self.z})' def __sub__(self, other): return Vec3(self.x - other.x , self.y - other.y , self.z - other.z) def __add__(self, other): return Vec3(self.x + other.x , self.y + other.y , self.z + other.z) def mag(self): return math.sqrt(self.x**2 + self.y**2 + self.z**2) def __div__(self, other): return Vec3(self.x/other, self.y/other , self.z/other) def __rmul__(self, other): return Vec3(self.x*other, self.y*other , self.z*other) def __mul__(self, other): return Vec3(self.x*other, self.y*other , self.z*other) def __neg__(self,other): return Vec3(-1*self.x, -1*self.y, -1*self.z) def __truediv__(self, other): return Vec3(self.x/other, self.y/other , self.z/other) def dot(self, other): if isinstance(other, Vec3): return self.x * other.x + self.y * other.y + self.z * other.z raise Exception('this should recieve an arfument of type Vec3') def cross(self, other): if isinstance(other, Vec3): return Vec3( self.y* other.z - self.x* other.y, self.z* other.x - self.x* other.z , self.x * self.y - self.y * self.x) raise Exception('this should recieve an arfument of type Vec3')
51b40c1df3d52d3b1089dc01438022dbd506133c
stevenhvtran/Maze-Generator
/listMaze.py
6,337
3.78125
4
from pprint import pprint import random import numpy as np #Generates the grid needed to start a maze def gridGen(x): if x%2 != 0: #Creates the grid being used grid = [[0 for i in range(0,x)] for i in range(0,x)] grid = walls(walls(grid, x), x) return(list(map(list, grid))) else: #Forces an odd number for dimensions of grid gridGen(x+1) #Creates the walls of the maze def walls(grid, x): grid[::2] = [[i+1 for i in grid[i]] for i in range(0,int((x+1)/2))] grid = list(zip(*grid)) return grid #Sets the starting point of the maze to a random co-ordinate on the edge of the grid def start(grid): randCoord = [1, 2*random.randint(0, (len(grid)-3)/2)+1] #Randomizing a point in first row grid[0][randCoord[1]] = 4 #Sets starting point to 3 grid[1][randCoord[1]] = 3 #Sets predetermined first step to 3 too #Randomly reflects grid across diagonal to change starting edge if random.getrandbits(1) == 0: grid = transpose(grid) randCoord = transposeC(randCoord) #Randomly reflects the grid across the horizontal to change starting edge if random.getrandbits(1) == 0: grid = reverse(grid) randCoord = reverseC(randCoord, grid) return [grid, randCoord] #Reflects a square array across its diagonal (top left to bottom right) def transpose(grid): return list(map(list, zip(*grid))) #Changes co-ordinate of a point on a transposed array to match transformation def transposeC(coord): return [coord[1], coord[0]] #Reflects an array across its horizontal def reverse(grid): return grid[::-1] #Changes co-ordinate of a point on a reflected array to match transformation def reverseC(coord, grid): return [len(grid) - 1 - coord[0], coord[1]] #Picks a random direction for the maze's path to go on def goto(grid, invDir, squigFactor): #Picks directions that aren't already flagged as being 'invalid' previously direction = random.choice([dir for dir in ['n','s','e','w'] if dir not in invDir]) #Direction randomizer length = random.randint(0, int(np.sqrt(len(grid))/squigFactor))*2 return [length, direction] #Checks to see if path is clear and if so, moves current position to a new one as determined #by goto function def go(pos, grid, length, direction): #Moves the current position to the new place turning all those in path to 3's global invDir ''' Creates the path For every input from the goto randomizer... Transform the grid so that Easterly movement on the transformed grid is equivalent to the input direction. Then move the path to the east in accordance to goto randomizer if path is valid, if not add compass direction to invDir list. Then transform the grid back to its original form and return the grid and the new active co-ordinate. ''' if direction == 'n': grid = transpose(reverse(grid)) pos = transposeC(reverseC(pos, grid)) if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('n') grid = reverse(transpose(grid)) pos = reverseC(transposeC(pos), grid) if direction == 'e': if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('e') if direction == 's': grid = transpose(grid) pos = transposeC(pos) if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('s') grid = transpose(grid) pos = transposeC(pos) if direction == 'w': grid = transpose(reverse(transpose(grid))) pos = transposeC(reverseC(transposeC(pos), grid)) if isClear(grid, pos , length) == True: for i in range(1, length+1): grid[pos[0]][pos[1]+i] = 3 pos[1] += length else: invDir.append('w') grid = transpose(reverse(transpose(grid))) pos = transposeC(reverseC(transposeC(pos), grid)) return [grid, pos, invDir] def isClear(grid, pos, length): global invDir if sum(grid[pos[0]][pos[1]:pos[1]+length+1]) == (length/2)+3 and pos[1]+length < len(grid): invDir = [] return True else: return False invDir = [] def mazeGen(x): global invDir result = start(gridGen(x)) grid, pos = result[0], result[1] hist = [] return createPath(x, grid, pos, hist) def createPath(x, grid, pos, hist): global invDir #6-2 is best configuration so far for speed and no gaps squigFactor = 6 #Medium effect on time, increasing will increase density of maze and reduce gaps retries = 2 #IDK effect on time but increasing value decreases black gaps while True: for i in range(0, 8): #Optimally only needs to loop 4 times to get all compass directions #If all moves in every direction are invalid retries with smaller path #Breaks after all retries are used up if len(invDir) == 4: invDir = [] if retries > 0: retries -= 1 continue if retries == 0: retries += 2 #SHOULD BE THE SAME AS RETRIES STARTING VALUE hist.remove(pos) if len(hist) < 2: break pos = random.choice(hist) step = goto(grid, invDir, squigFactor) grid, pos, invDir = go(pos, grid, step[0], step[1]) if pos not in hist: hist.append(pos) invDir = [] if len(hist) < 2: break #Re-use the start function to pick an endpoint for the maze return start(grid)[0]
3cd1af446a478f64466a9761c16b7f4d21b834d7
tonyw0527/Python-algorithm-notes
/Implementation/combinationsAndPrimeNumber.py
609
3.828125
4
# 리스트C3 의 조합의 경우의 수를 담은 리스트를 얻는다. # 각 원소의 합이 소수인 것들의 수만 더한다. from itertools import combinations from math import sqrt def isPrime(num): if num < 2: return False for n in range(2, int(sqrt(num)) + 1): if num % n == 0: return False return True def solution(nums): answer = 0 cases = list(combinations(nums, 3)) for c in cases: summedNum = sum(c) if isPrime(summedNum): print(summedNum, ' is prime number') answer += 1 return answer
2d9d781b6bc8ccb022ce86d4ed6f58fadcd2788b
paulan94/CTCIPaul
/4_8_find_common_ancs.py
793
3.890625
4
class Node(): def __init__(self,val): self.val = val self.right = None self.left = None def node_exists(root,node): if root == node: return True if not root: return None else: return node_exists(root.left,node) or node_exists(root.right,node) return False def find_ca(root,A,B): if not root: return None if not A and not B: return root if (node_exists(root.right,A) and node_exists(root.left,B)) or (node_exists(root.right,B) and node_exists(root.left,A)): return root else: return find_ca(root.left,A,B) or find_ca(root.right,A,B) root = Node(2) root.left = Node(1) root.left.left = Node(5) root.left.right = Node(6) root.right = Node(3) print (find_ca(root,root.left.left, root).val)
327c06d09a8423799688e23faeafdde1468b8ebc
paulan94/CTCIPaul
/AddOrMultiplyRuntimes.py
615
3.75
4
def addRunTimeAlgorithm(arrayA, arrayB): # O(A+B) for a in arrayA: print (a) for b in arrayB: print (b) def multiplyRunTimeAlgorithm(arrayA, arrayB): # O(AB) for a in arrayA: for b in arrayB: print (str(a) + "," + str(b)) if __name__ == "__main__": arrayA = ["a","b","c"] arrayB = [1,2,3,4] print ("Running add runtimes function!") addRunTimeAlgorithm(arrayA, arrayB) print ("End add runtimes function\nStarting multiply runtimes function!") multiplyRunTimeAlgorithm(arrayA, arrayB) print ("End multiply runtimes function!")
78d35c7dc69601404fa656ca6991b8586eb71a7f
paulan94/CTCIPaul
/get_len_arr.py
1,140
4.03125
4
# Given a list of n words, the task is to check if two same words come next to each other. # Then remove the pair and print the number of words left in the list after this pairwise # removal is done until no other pairs are present. # # Examples: # # Input : [ba bb bb bcd xy] # Output : 3 # As [bb, bb] cancel each other so, [ba bcd xy] is the new list. # # Input : [laurel hardy hardy laurel] # Output : 0 # As first both [hardy] will cancel each other. # Then the list will be [laurel, laurel] which also remove # each other. So, the final list doesn't contain any # word. #assumptions: can be more than 1 pair, new pairs can come from deletions of pairs def get_len_arr(arr): stack = [] if len(arr) <= 1: return len(arr) for ele in arr: if len(stack) == 0: stack.append(ele) else: popped = stack.pop() if ele != popped: stack.append(popped) stack.append(ele) return len(stack) a = ['laurel', 'hardy', 'hardy', 'laurel'] a2 = ['bc', 'bb', 'bb', 'bcd', 'xy'] print (get_len_arr(a)) print (get_len_arr(a2))
21cc678347d34d1ca41120c9bec17f757cbf6b06
paulan94/CTCIPaul
/4_5_validate_bst.py
483
3.734375
4
class Node(): def __init__(self, val): self.val = val self.left = None self.right = None def validate_bst(mn, mx, root): if not root: return True elif root.val < mn or root.val > mx: return False return validate_bst(mn,root.val,root.left) and validate_bst(root.val,mx,root.right) rt = Node(6) rt.left = Node(5) rt.left.right = Node(8) rt.left.left = Node(1) rt.right = Node(9) rt.right.right = Node(11) print (validate_bst(-100,100,rt))
41daacddca3128116a92c6a6bd83b0f197444c96
paulan94/CTCIPaul
/binsearch2.py
713
3.96875
4
def bin_search(arr,key,start,end): #we need to check if the end index is greater than 0 because #we need to ensure that end is within the bounds of [0:len(a)-1] if (start <= end): #mid will be start + (end-start)//2 #the first start keeps track of where our lower bound is #and we move to the right (end-start)//2 times mid = start + (end-start)//2 if (arr[mid] == key): return mid elif (arr[mid] > key): return bin_search(arr,key,start,mid-1) else: return bin_search(arr,key,mid+1,end) return -1 # 0 1 2 3 4 5 a=[2,5,7,9,11,20] print (bin_search(a,20,0,len(a)-1)) ##print (bin_search_iterative(a,9))
34e8dded051c178bc946de223e5ed459837bed4a
paulan94/CTCIPaul
/node.py
840
3.6875
4
class Node: def __init__(self,val): self.val = val self.left = None self.right = None rt = Node(5) rt.left = Node(2) rt.right = Node(6) rt.left.left = Node(1) rt.left.right = Node(3) def contains(root,node): if not root: return False if root == node: return True elif root.left == node or root.right == node: return True return contains(root.left, node) or contains(root.right, node) def lowestCommonAncestor(root, p, q): if not root: return None if p == q: return p.val if (contains(root.left,p) and contains(root.right,q)) or (contains(root.left,q) and self.contains(root.right,p)): return root.val return lowestCommonAncestor(root.left,p,q) or lowestCommonAncestor(root.right,p,q)
d9efef45642933fbdc520bac6a2e4b3785ae26dd
paulan94/CTCIPaul
/4_1_route_nodes.py
515
3.828125
4
class Node: def __init__(self,val): self.val = val self.children = [] def route_exists(a,b): if a.val == b.val: return True elif (not a and b) or (not b and a): return False else: for c in a.children: if route_exists(c,b): return True return False a = Node(5) b = Node(6) c = Node(7) d = Node(8) e = Node(10) f = Node(11) a.children += [b,c,d] d.children.append(e) print (route_exists(a,e)) print (route_exists(a,f))
cd2c876ba236ef81aaf268f832eeb2de7fa66f71
paulan94/CTCIPaul
/8_9_parens.py
398
3.515625
4
def get_parens(n): if n == 0: return [''] else: p_list = [] parens = get_parens(n-1) for each in parens: p_list.append('()' + each) p_list.append('(' + each + ')') p_list.append(each + '()') return set(p_list) print (get_parens(4)) print (get_parens(3)) print (get_parens(2)) print (get_parens(1)) print (get_parens(0))
dc71001743d53cc6ebc0488cc4e4d3bf975a7d79
paulan94/CTCIPaul
/My HackerRank Solutions/binary_tree_BST.py
953
3.953125
4
#Paul An #is this binary tree a BST? #This program creates an array based on an in-order traversal of the given Binary Tree. #It compares the sum starting at 0. 0 with 1, 2 with 3, up to n-1 with n to see if the sequence is ordered correctly. """ Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def checkBST(root): inorder_array = [] inorder_array = create_array(root, inorder_array) return parse_array(inorder_array) def create_array(node, inorder_array): if (node.left != None): create_array(node.left, inorder_array) inorder_array.append(node.data) if (node.right != None): create_array(node.right, inorder_array) return inorder_array def parse_array(inorder_array): for i in range(len(inorder_array)-1): if ((inorder_array[i] - inorder_array[i+1])!= -1): return False return True
4a80711d999e08b07361e0891f348ba6a29a3591
paulan94/CTCIPaul
/4_2_create_bst_min_height.py
719
3.703125
4
class Node(): def __init__(self,val): self.val = val self.left = None self.right = None def create_bst_min_height(arr,start, end): if not arr or len(arr) == 0 or end < start: return None else: mid = (start + end)//2 node = Node(arr[mid]) print (node.val) node.left = create_bst_min_height(arr,start,mid-1) node.right = create_bst_min_height(arr,mid+1,end) return node arr = [1,2,3] arr2 = [1,2,3,4,5,6,7,8] x1 = create_bst_min_height(arr,0,len(arr)-1) x2 = create_bst_min_height(arr2,0,len(arr2)-1) print (x1.val, x1.left.val, x1.right.val) print (x2.val, x2.left.val, x2.right.val, x2.left.left.val, x2.right.right.val )
394f3dafa486af4e54f0097d4c407d9678e48bce
alekseidrumov/HOMEWORK_PYTHON_ADVANCED_NUM_4
/1.py
893
3.875
4
def registration(): login = input("login: ") password = input("password: ") name = input('name: ') with open('file.txt','a') as f: f.write(login+' login '+password+' password '+name+' name ') def login(dict): dict = dict print(dict) login = input("login: ") password = input("password: ") if login in dict and password in dict: for key,value in dict.items(): if value == 'name': print('Hello',key) else: print("Try again!") while True: ans = int(input("Choose 1 - login, 2 - registration, 3 - exit: ")) if ans == 1: with open('file.txt','r') as f: str = f.read() list = str.split() dict = dict(zip(list[::2], list[1::2])) login(dict) elif ans == 2: registration() elif ans == 3: break
7af10a743dbf3690644d938655353f87a802c16c
JaLeeKi/data-python
/data_presenter.py
1,067
3.921875
4
# Create a new file called data_presenter.py. # Open the CupcakeInvoices.csv. open_file = open('CupcakeInvoices.csv') # Loop through all the data and print each row. for line in open_file: print(line) # Loop through all the data and print the type of cupcakes purchased. for line in open_file: values = line.split(',') print(values[2]) # Loop through all the data and print out the total for each invoice (Note: this data is not provided by the csv, you will need to calculate it. Also, keep in mind the data from the csv comes back as a string, you will need to convert it to a float. Research how to do this.). for line in open_file: values = line.split(',') quantity = int(values[3]) price = float(values[4]) total = quantity * price print(total) # Loop through all the data, and print out the total for all invoices combined. total = 0 for line in open_file: values = line.split(',') quantity = int(values[3]) price = float(values[4]) total = total + (quantity * price) print(total) # Close your open file. open_file.close()
3857e9ecf09d236e3e03425c3cfe37b29ab8ad99
AntonioGetsemani/EjercicioDePruebaRecursividad
/Ejercicio1Recursividad.py
198
3.5
4
author = 'Antonio Getsemani' def ConvertirNumero(num): if num == 0: return "" else: return str(num % 2) + ConvertirNumero(num//2) print(ConvertirNumero(8))
7bbf7e4294d9f9a4e6ee7ab9c66f73c67a7a5909
georgePopaEv/python-exercise
/Day2P.py
576
3.765625
4
bani = float(input("Cati bani ai in total? :")) # trecem suma de bani # alegem dobanda dintre 10, 12 sau 15 # vedem la cati o umprumuta sau a cata parte # Calculam cat tre sa plateasca fiecare persoana inapoi dobanda = int(input("Cat este dobanda la care imprumuti?10, 12 sau 15? ")) split = int(input("La cati oameni se imparte banca?")) back = round(bani / split * (1+dobanda/100) , 2) if (dobanda == 10) | (dobanda == 12) | (dobanda == 15): print(f"fiecare persoana trebuie sa plateasca : ${back} ") else: print("Eroare de introducere a dobanzii!")
5e687cca74958a11a30f7b38e0f148898296e314
georgePopaEv/python-exercise
/P9DAY.py
626
3.5625
4
import art print(art.logo) def maxim_from_dictionar(dictionar): max = 0 for i in dictionar: if dictionar[i] > max: max = pers[i] winner = i print(f"Castigatorul este {winner} care a licitat cu {max}") run = True pers = {} while run: name = input("Numele cu care liciteaza: ") suma = int(input("Suma = $")) pers[name] = suma again = input("Vrea cineva sa mai liciteze ? DA/NU").lower() if again == 'da': run = True # print('\n' * 50) elif again == 'nu': run = False maxim_from_dictionar(pers)
fe13a07aade0381d220e30fb2f3eb344a7f63405
saileshchauhan/PythonProgram
/DataStructure/Strings/1_WordFrequency.py
1,730
3.9375
4
''' @Author:Sailesh Chauhan @Date:2021-06-11 @Last Modified by:Sailesh Chauhan @Last Modified time:2021-06-11 @Title: Get length of string count each alphabet frequency and char replacement. ''' #Importing logConfig for error logging import logconfig import logging,re def create_word(): ''' Description: Parameters: Returns: ''' try: userValue=validation(input("You can enter any word\n")) return userValue except Exception as ex: logging.error(ex) def validation(stringValue): ''' Description: Provides validation for userinput. Parameters: stringValue it is userinput. Returns: correctString after validation. ''' try: regexName="^[a-zA-Z0-9.]{3,}[a-zA-Z]+$" if(re.match(regexName,stringValue)): return stringValue print("String Lenght must be more than 3") except Exception as ex: logging.critical(ex) def char_frequency(word): ''' Description: Parameters: Returns: ''' try: charFrequency={} for char in word: count=0 for index in range(len(word)): if(char==word[index]): count+=1 charFrequency.update({char:count}) return charFrequency except Exception as ex: logging.critical(ex) def char_replacement(word): ''' Description: Parameters: Returns: ''' try: char = word[0] word = word.replace(char, '$') word = char + word[1:] return word except Exception as ex: logging.critical(ex) word=create_word() print(char_replacement(word)) print("word frequency dictionary",char_frequency(word))
61cb6e042e6b49bf4dea1b95335989c5c66bdcd4
saileshchauhan/PythonProgram
/DataStructure/Lists/3_CopyList_RemoveDuplicates.py
1,944
3.90625
4
''' @Author:Sailesh Chauhan @Date:2021-06-10 @Last Modified by:Sailesh Chauhan @Last Modified time:2021-06-10 @Title: Copy list and remove duplicate element from list. ''' import logconfig import logging,copy def create_list(): ''' Description: Parameters: Returns: ''' try: defaultList=[] choice='' print("You can enter any value in set") while(choice.lower()!='q'): userValue=input("Enter value to add in set\n") defaultList.append(userValue) print("Do you want to add more values \nPress C to continue\nQ to stop\n") choice=input("Enter choice\n") return defaultList except Exception as ex: logging.error(ex) def copy_list(list): ''' Description: Parameters: Returns: ''' try: copyList=[] for item in list: copyList.append(item) return copyList except Exception as ex: logging.critical(ex) def deep_copy_list(list): ''' Description: Parameters: Returns: ''' try: deepCopy=copy.deepcopy(list) return deepCopy except Exception as ex: logging.critical(ex) list=create_list() print("New copy of list using For Loop ",copy_list(list)) print("New copy of list using Deep Copy method of Copy module ",deep_copy_list(list)) def remove_duplicates(list): ''' Description: Parameters: Returns: ''' try: index=0 end=len(list) while(index<end): count=index+1 while(count<end): if(list[index]==list[count]): list.remove(list[index]) end-=1 count-=1 count+=1 index+=1 return list except Exception as ex: logging.critical(ex) noDuplicateList=remove_duplicates(list) print("List after removing elements ",noDuplicateList)
af00f452c536b5503c79a34286fd1b78b91ddc8e
saileshchauhan/PythonProgram
/DataStructure/Lists/7_CommonItem_From2List.py
1,343
3.53125
4
''' @Author:Sailesh Chauhan @Date:2021-06-10 @Last Modified by:Sailesh Chauhan @Last Modified time:2021-06-10 @Title: Find out common item in both list. ''' #Importing logConfig for error logging import logconfig import logging,re def create_list(): ''' Description: Parameters: Returns: ''' try: defaultList=[] choice='' print("You can enter any value in list") while(choice.lower()!='q'): userValue=validation(input("Enter value to add in list\n")) defaultList.append(userValue) print("Do you want to add more values \nPress C to continue\nQ to stop\n") choice=input("Enter choice\n") return defaultList except Exception as ex: logging.error(ex) def validation(stringValue): ''' Description: Provides validation for userinput. Parameters: stringValue it is userinput. Returns: correctString after converting it to int validation. ''' try: regexName="^[0-9a-zA-Z]{1,}$" if(re.match(regexName,stringValue)): return (stringValue) print("Invalid Input") except Exception as ex: logging.critical(ex) setOne=set(create_list()) setTwo=set(create_list()) setOne.intersection_update(setTwo) print("The list of element common ",list(setOne))
012065e8a85e1ac86c2e563e5df3d7feab87101a
Exodus76/aoc19
/day1.py
759
4.125
4
#day 1 part 1 #find the fuel required for a module, take its mass, divide by three, round down, and subtract 2 #part1 function def fuel_required(mass): if(mass < 0): return 0 else: return (mass/3 - 2) #part2 fucntion def total_fuel(mass): total = 0 while(fuel_required(mass) >= 0): total += fuel_required(mass) mass = fuel_required(mass) return total input_file = open('input.txt','r') total_fuel_1 = 0 total_fuel_requirement = 0 list_of_masses = input_file.readlines() for i in list_of_masses: total_fuel_1 += fuel_required(int(i)) print("part1 = " + str(total_fuel_1)) for i in list_of_masses: total_fuel_requirement += total_fuel(int(i)) print("part2 = " + str(total_fuel_requirement))
e40fbf76d88da16cb8c9ab18b276cf1595aa8198
yz9527-1/1YZ
/pycharm/Practice/python 3自学/12-读取csv文件.py
626
3.765625
4
# -*-coding:UTF-8 -*- """ import csv with open(r'E:\YZ\data\data1.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') for row in readCSV: #print(row) #print(row[0]) print(row[0], row[1]) """ import csv with open(r'E:\YZ\data\data1.csv') as csvfile: readCSV = csv.reader(csvfile, delimiter=',') citys = [] password = [] days = [] for row in readCSV: city = row[0] paword = row[1] day = row[2] citys.append(city) password.append(paword) days.append(day) print(citys) print(password) print(days)
380f71e1a17b74229526deb208804f1707dafbb3
llubu/AI
/Project 3/BayesianNet/question3_solver.py
3,782
3.703125
4
class Question3_Solver: def __init__(self, cpt): self.cpt = cpt; self.skip1 = self.createTable1() self.skip2 = self.createTable2() ##################################### # ADD YOUR CODE HERE # Pr(x|y) = self.cpt.conditional_prob(x, y); # A word begins with "`" and ends with "`". # For example, the probability of word "ab": # Pr("ab") = \ # self.cpt.conditional_prob("a", "`") * \ # self.cpt.conditional_prob("b", "a") * \ # self.cpt.conditional_prob("`", "b"); # query example: # query: "qu--_--n"; # return "t"; def solve(self, query): """ This function solves the given querry and returns the letter which is most suitable. """ query = '`' + query + '`' # Adding string end delimiters uS = query.index('_') # index of the underscore in the query string tmp = query.split('_') #print tmp prevDash = tmp[0].count('-') # Count of dashes before the underScore afterDash = tmp[1].count('-') # Count of dashes after the underScore #print prevDash, afterDash if 0 != (uS - prevDash): leftch = query[uS-prevDash -1] # Index of valid character before leftmost dash else: leftch = query[uS-prevDash] if len(query) != (uS + afterDash): rtch = query[uS+afterDash +1] # Index of valid character after rightmost dash else: rtch = query[uS+afterDash] #print leftch, rtch leftsum = 0 # Sum of probalities for left dashes rtsum = 0 # Sum of probabilities for right dashes maxSum = -1 # Max sum for a particular letter in the loop maxChar = '?' # The character with maxSum for i in range(0, 26): if (0 == prevDash): leftsum = self.cpt.conditional_prob(chr(97+i) ,leftch) if (1 == prevDash): leftsum = self.skip1[chr(97+i), leftch] if (2 == prevDash): leftsum = self.skip2[chr(97+i), leftch] if (0 == afterDash): rtsum = self.cpt.conditional_prob(rtch, chr(97+i)) if (1 == afterDash): rtsum = self.skip1[rtch, chr(97+i)] if (2 == afterDash): rtsum = self.skip2[rtch, chr(97+i)] fiSum = leftsum*rtsum if ( maxSum < fiSum ): maxSum = fiSum maxChar = chr(97+i) return maxChar; def createTable1(self): """ Creates the lookup table to help eliminate hidden var 1 """ table= dict() for i in range(0,27): prev = chr(96+i) for j in range(0, 27): sum = 0 cur = chr(96+j) for k in range(0, 27): sum += self.cpt.conditional_prob(chr(96+k), prev) * self.cpt.conditional_prob(cur, chr(96+k)) table[prev,cur] = sum return table def createTable2(self): """ Creates the lookup table to help eliminate hidden var 2 """ table = dict() for i in range(0, 27): prev = chr(96+i) for j in range(0, 27): sum = 0 cur = chr(96+j) for k in range(0, 27): sum += self.skip1[chr(96+k), prev] * self.cpt.conditional_prob(cur, chr(96+k)) table[prev, cur] = sum return table
91f7b60a8fd8f7b3518b40755a12b2cdf3038e5e
llubu/AI
/Project 4/machine_learning/question3_solver.py
2,047
3.859375
4
import math class Question3_Solver: def __init__(self): return; # Add your code here. # Return the centroids of clusters. # You must use [(30, 30), (150, 30), (90, 130)] as initial centroids #[(30, 60), (150, 60), (90, 130)] def solve(self, points): centroids = [(30, 30), (150, 30), (90, 130)] #centroids = [(30, 60), (150, 60), (90, 130)] while(1): final = [[],[],[]] centroid1 = [(), (), ()] minIndex = -1 #Get distance from each current centroid for point in points: d1 = self.getDistance(centroids[0], point) d2 = self.getDistance(centroids[1], point) d3 = self.getDistance(centroids[2], point) #Find closest centroid if d1 < d2: minIndex = 0 if d3 < d1: minIndex = 2 elif d3 < d2: minIndex = 2 else: minIndex = 1 final[minIndex].append(point) #Compute new centroid for i in range(0,3): xsum = 0 ysum = 0 for item in final[i]: xsum += item[0] ysum += item[1] centroid1[i] = (xsum/len(final[i]), ysum/len(final[i])) #If centroids don't change, terminate if ( centroid1[0] == centroids[0] and centroid1[1] == centroids[1] and centroid1[2] == centroids[2]): break else: centroids = centroid1 centroid1 = [(), (), ()] return centroids; def getDistance(self, p1, p2): """ Helper function to get the distance between two points p1 and p2 """ dis = math.pow( math.pow (( p2[0] - p1[0]), 2) + math.pow (( p2[1] - p1[1]), 2), 0.5) return dis
6b72e1414ffa164e5753a0d701ca7b29098fa82c
ChengBinJin/Tensorflow-SungKim
/src/ML_lab_03.py
899
3.6875
4
import tensorflow as tf # import matplotlib.pyplot as plt x_data = [1., 2., 3.] y_data = [1., 2., 3.] W = tf.Variable(tf.random_normal([1]), name='weight') X = tf.placeholder(tf.float32) Y = tf.placeholder(tf.float32) # Our hypothesis for linear model X * W hypothesis = X * W # cost/loss function cost = tf.reduce_mean(tf.square(hypothesis - Y)) # Minimize: Gradient Descent using derivate: W -= learning_rate * derivative learning_rate = 0.1 gradient = tf.reduce_mean((W * X - Y) * X) descent = W - learning_rate * gradient update = W.assign(descent) # Launch the graph in a session. sess = tf.Session() # Initializes global variables in the graph. sess.run(tf.global_variables_initializer()) for step in range(21): sess.run(update, feed_dict={X: x_data, Y: y_data}) print('Step: {}'.format(step), 'cost: {}, W: {}'.format(sess.run(cost, feed_dict={X: x_data, Y: y_data}), sess.run(W)))
83a4be2a2ac283fafb84d62420c65d8d118383ab
yanolsh/dev-sprint2
/chap7.py
613
4.0625
4
# Enter your answrs for chapter 7 here # Name: # Ex. 7.5 import math def fact(k): if k == 0: return 1 else: rec = fact(k-1) result = k * rec return result def estimate_pi(): t = 0 k = 0 factor = 2 * math.sqrt(2) / 9801 while True: num = fact(4*k) * (1103 + 26390*k) den = fact(k)**4 * 396**(4*k) term = factor * num / den t += term if abs(term) < 1e-15: break k += 1 print k return 1 / t print estimate_pi() # How many iterations does it take to converge? # it takes 2 iterations.
954577d721fc5226cec27b13688bf039cc253360
aiqiliu/algoprep
/15.py
3,761
3.671875
4
# 3sum: # 1. get len # return [] if len<3 # split the list into <= 0 and > 0 # recursion, for every num1 in l1, pair up with num2 in l2. # if (0 - num1 - num2) in num1 or in num2, append the [num1, num2, 0-num1-num2] in result # first iteration: problem - have duplicates class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] l1 = [num1 for num1 in nums if num1 <= 0] l2 = [num2 for num2 in nums if num2 > 0] for num1 in l1: for num2 in l2: curr = [num1, num2] num3 = 0 - num1 - num2 if num3 in l1 or num3 in l2: curr.append(num3) result.append(curr) return result # second iteration: add a dict to indicate if num1 has occured before class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] dict = {} l1 = [num1 for num1 in nums if num1 <= 0] l2 = [num2 for num2 in nums if num2 > 0] for num1 in l1: if num1 not in dict: dict[num1] = 1 for num2 in l2: curr = [num1, num2] num3 = 0 - num1 - num2 if num3 in nums: if num3 in curr and nums.count(num3) > 1: curr.append(num3) result.append(curr) result = [sorted(l) for l in result] result = set(tuple(x) for x in result) result = [list(x) for x in result] return result # third iteration: ignored that all elements may be 0 # second iteration: add a dict to indicate if num1 has occured before class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] dict = {} if all(x == 0 for x in nums): return [[0,0,0]] l1 = [num1 for num1 in nums if num1 <= 0] l2 = [num2 for num2 in nums if num2 > 0] if l1.count(0) >= 3: result.append([0,0,0]) for num1 in l1: if num1 not in dict and num1 != 0: dict[num1] = 1 for num2 in l2: curr = [num1, num2] num3 = 0 - num1 - num2 if num3 in nums: if num3 in curr and nums.count(num3) > 1 or num3 not in curr and nums.count(num3) > 0: curr.append(num3) result.append(curr) result = [sorted(l) for l in result] result = set(tuple(x) for x in result) result = [list(x) for x in result] return result # fourth iteration # neater solution, with O(N^2) complexity class Solution(object): def threeSum(self, nums): """ :type nums: List[int] :rtype: List[List[int]] """ m = len(nums) if m < 3: return [] result = [] for i in range(0, m-2): if i > 0 and nums[i] == nums[i-1]: continue j, k = i + 1, m - 1 target = 0 - nums[i] while j < k: if j > i + 1 and nums[j] == nums[j-1]: j += 1 continue if nums[j] + nums[k] == target: result.append([nums[i], nums[j], nums[k]]) j += 1 k -= 1 elif nums[j] + nums[k] < target: j += 1 else: k -= 1 return result
c1705f2e61d5dc83e340aa1c9452e0731a669174
varinder-singh/EVA4
/S11/drawCyclicCurve.py
1,714
3.5
4
class PlotTheCurve(): def __init__(self, cycle_count, lr_min, lr_max, step_size): self.cycle_count = cycle_count self.lr_min = lr_min self.lr_max = lr_max self.step_size = step_size def setX(self,cycle,cycle_count): list1 = [] mincycleval, maxcycleval = cycle step_size = maxcycleval-mincycleval minim = mincycleval for i in range(mincycleval,(step_size * self.cycle_count)+1): if i-minim==step_size: list1.append(i) minim = i list1.append(i) return list1[:step_size*self.cycle_count] def setY(self,minval, maxval, cycle, step_size): list2 = [] for i in range(cycle): list2.append(minval) list2.append(maxval) list2.append(minval) return list2[:cycle*step_size] def plot(self): import matplotlib.pyplot as plt cycle_count=self.cycle_count # x axis values x = self.setX((1,3),cycle_count) #print("X ", x) # Set the minimum and maximum values of LR lr_min = self.lr_min lr_max = self.lr_max step_size = self.step_size # corresponding y axis values y = self.setY(lr_min,lr_max,cycle_count,step_size) #print("Y ", y) # plotting the points plt.plot(x, y, color='green') # naming the x axis plt.xlabel('Iterations (10e4)') # naming the y axis plt.ylabel('LR Range') # giving a title to my graph plt.title('Triangular schedule') # function to show the plot plt.show()
c7befa66246c186a74d3b744cefc83914b3f8dea
Binovizer/Python-Beginning
/TheBeginning/Demos/GuessTheNumber.py
322
3.875
4
from random import randint x = randint(1,100) print("Here We Go...") n = int(input("Guess the number: ")) while(True): if(x == n): print("Yippeee! You Guessed It Right.") break elif(x > n): print("Too Low") else: print("Too High") n = int(input("Guess Again: "))
41aa6417fa2caa63e1be5277d7da7c4be451715a
Binovizer/Python-Beginning
/GUIDemo/CreatingDropDownMenu.py
1,721
3.84375
4
from tkinter import * def doNothing(): print("This started Working") root = Tk() menu = Menu(root, tearoff = False) root.config(menu = menu) submenu = Menu(menu, tearoff = False) menu.add_cascade(label='File', menu = submenu) submenu.add_command(label='New Project', command = doNothing) submenu.add_command(label='New...', command=doNothing) submenu.add_separator() submenu.add_command(label='Quit', command=root.destroy) editMenu = Menu(menu, tearoff = False) menu.add_cascade(label='Edit', menu=editMenu) editMenu.add_command(label="Redo", command=doNothing) root.mainloop() # from tkinter import * # # def doNothing(): # print("Ok, ok I won't!") # # root = Tk() # # menu = Menu(root, tearoff = False) # Creates menu object # root.config(menu = menu) # Configuring menu object to be a menu # # subMenu = Menu(menu, tearoff = False) # Creating a menu inside a menu # # menu.add_cascade(label = "File", # menu = subMenu) # Creates file button with dropdown, sub menu is the drop # # subMenu.add_command(label = "New project", # command = doNothing) # subMenu.add_command(label = "New...", # command = doNothing) # 2 commands in the sub menu now # # subMenu.add_separator() # Creates seperator in the drop # # subMenu.add_command(label = "Exit", # command = root.destroy) # Another sub menu item # # editMenu = Menu(menu, tearoff = False) # Create another item in main menu # # menu.add_cascade(label = "Edit", # menu = editMenu) # # editMenu.add_command(label = "Redo", # command = doNothing) # # root.mainloop()
eb78d593489b33d1a5cd3cb14268aef27b553962
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/50.py
897
4.1875
4
import re student_id = input("Enter student id : ") if(re.search("[^0-9]", student_id)): print("Sorry! Student ID can only contains digit") else: student_name = input("Enter student name : ") if re.search("[^a-zA-Z]", student_name): print("Name can only contain alphabets") else: print("Hello",student_name.capitalize()) fees_amount = input("Enter Fees Amount : ") if re.search("^\d+(\.\d{1,2})?$", fees_amount): college_name = "akgec" email_id = student_name.lower()+"@"+college_name+".com" print("\nStudent ID : ",student_id) print("Student Name : ",student_name) print("Student Fees : ",fees_amount) print("Student Email ID : ",email_id) else: print("Sorry! Only two digits are allowed after decimal point")
67372b5d84a298c77462a0979c9e52eafaffe948
Binovizer/Python-Beginning
/TheBeginning/Demos/DateNTimeDemo.py
327
3.546875
4
import time import datetime print(time.clock()) print(time.gmtime()) print(time.localtime()) print(time.time()) print(time.daylight) print(datetime.datetime.now()) print(datetime.datetime.now()+datetime.timedelta()) print("Current Time : "+time.strftime("%c")) print(time.strftime("%x")) print(time.strftime("%X"))
a54f5599368ec0d5a7a425a7cba6efa0795e67ff
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/32.py
359
3.875
4
a = [int(x) for(x) in input("Enter numbers : ").split(sep=' ')] #Taking list as an input print("List before sorting : ",a) #Bubble Sort for i in range(0,len(a)) : for j in range(0,len(a)-i-1) : if (a[j] < a[j+1]): temp = a[j]; a[j] = a[j+1]; a[j+1] = temp print("List after sorting : ",a)
e9a65f7f1552fb9dc8b79e7f6d8147b7f148874d
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/17.py
101
3.84375
4
counter = 1 while (counter <= 3): print(counter) counter += 1 print("End of program")
2edf97fc3e08b52cbe3646a770eacc4800fec38d
Binovizer/Python-Beginning
/GUIDemo/FittingWidgets.py
288
3.9375
4
from tkinter import * root = Tk() one = Label(root, text='One', fg='black', bg="red") two = Label(root, text='Two', fg='red', bg='yellow') three = Label(root, text='Three', fg='red', bg='blue') one.pack() two.pack(fill=X) three.pack(fill=BOTH, expand=TRUE) root.mainloop()
f1ec84bd827159d3638ce26957379c9a20d5ed2b
Binovizer/Python-Beginning
/TheBeginning/py_basics_assignments/33.py
708
4.09375
4
furniture_list = [("SofaSet",20000),("Dining Table",8500),("TV stand",4599),("Cupboard",13920)] fur_name = input("Enter the Name of furniture You want to buy : ").strip() for fur_tuple in furniture_list: if (fur_tuple[0].lower() == fur_name.lower()): price = fur_tuple[1] print("\nFurniture Name : ",fur_tuple[0],", Price : ",price) no = int(input("\nEnter Quantity : ").strip()) bill_amount = price * no; print("\nFurniture Name : ",fur_tuple[0],", Price : ",price) print("Quantity : ",no) print("Bill Amount : ",bill_amount) print("Thank You for Shopping With Us ;)") break; else: print("No Results Found")
1055bc0e42e910b94362ab9eca8562dd189a4ad7
bocchini/py_todo
/view/add_to_do.py
522
3.6875
4
from controllers.to_do_controller import add_to_do def add(): print('*' * 30, '-' * 4, ' Adicionar uma tarefa ', '-' * 4, '*' * 30) save = False while not save: title = input('Digite o titulo da tarefa: ').capitalize() to_do = input('Digite a tarefa: ').capitalize() want_to_save = input('Salvar a tarefa? (s/n) ') if want_to_save.lower() == 's': save = True do = add_to_do(title, to_do) print('Tarefa adicionada') print(do)
ae49e7d82f3936422004eea0e1f73d0f58feb126
messophet/Google
/Algorithms/CTCI/Chapter 1 - Arrays and Strings/35.py
432
3.90625
4
class Stack: def __init__(self): self.items=[] def push(self,item): self.items.append(item) def pop(self): return self.items.pop() def size(self): return len(self.items) def isEmpty(self): return self.items==[] class MyQueue: def __init__(self): self.queue = [] #3 2 1 -stack-> 3 2 1 (LIFO) -stack-> 1 2 3 | push 4 onto s1 -> 4, s2 = 1 2 3 | s1 = 4 3 2 1... now pop and it's in FIFO #3 2 1 -queue-> 1 2 3 (FIFO)
fae008a799fc1d985d61d7801a196a802ad4f49b
messophet/Google
/Algorithms/CTCI/Chapter 1 - Arrays and Strings/graphs.py
816
3.890625
4
graph = {'A':['B','D'],'B':['C'],'C':['E','F'],'D':[],'E':[],'F':[]} def find_path(graph,start,end,path=[]): path = path + [start] if(start==end): return path if(not graph.has_key(start)): return None #shortestPath = None for node in graph[start]: if node not in path: newpath = find_path(graph,node,end,path) if newpath: return newpath return None print(find_path(graph,'A','F')) def find_shortest_path(graph,start,end,path=[]): path=path+[start] if(start==end): return path if(not graph.has_key(start)): return None shortestPath = None for node in graph[start]: if node not in path: newpath = find_shortest_path(graph,node,end,path) if newpath: if(not shortest or len(newpath) < len(path)): shortestPath = newpath return shortestPath print(find_path(graph,'A','F'))
e21fb99cb9d35f6ee1b5d7bc0b846d7479ed5b20
jiafulow/emtf-nnet
/emtf_nnet/architecture/endless_utils.py
1,615
4.03125
4
"""Architecture utils.""" import numpy as np def gather_indices_by_values(arr, max_value=None): """Gather indices by values. Instead of gathering values by indices, this function gathers indices by (non-negative integer) values in an array. The result is a nested list, which can be addressed by content from the original array. Negative values in the array are ignored. Example: >>> arr = [0, 1, 1, 2, 2, 2, 4] >>> gather_indices_by_values(arr) [[0], [1, 2], [3, 4, 5], [], [6]] """ arr = np.asarray(arr) if not (arr.dtype in (np.int64, np.int32) and arr.ndim == 1): raise TypeError('arr must be a 1-D int32 or int64 numpy array') if max_value is None: max_value = np.max(arr) return [ [i for (i, x_i) in enumerate(arr) if x_i == y_j] for y_j in range(max_value + 1) ] def gather_inputs_by_outputs(arr, default_value=-99, padding_value=-99): """Gather inputs by outputs. Assume a 2-D array that is used to map multiple inputs to a smaller number of outputs. If two or more inputs are mapped to the same output, the one with the highest priority is used as the output. """ arr = np.asarray(arr) if not (arr.dtype in (np.int64, np.int32) and arr.ndim == 2): raise TypeError('arr must be a 2-D int32 or int64 numpy array') max_value = np.max(arr) matrix_shape = (max_value + 1, len(arr)) matrix = np.full(matrix_shape, default_value, dtype=np.int32) for i, x_i in enumerate(arr): for j, x_j in enumerate(x_i): if x_j != padding_value: priority = len(x_i) - 1 - j matrix[x_j, i] = priority return matrix
1c68f6f4f392e6e800af406002a42e343b8811f0
alixoallen/todos.py
/import random.py
367
3.90625
4
import random nome=(input('digite um nome :')) nome2=(input('digite um segundo nome :')) nome3=(input('digite um terceiro nome:')) nome4=(input('digite um quarto nome :')) lista=[nome,nome2,nome3,nome4] nme=random.choice(lista) print("o nome sorteado foi {}".format(nme)) #quase fiz sozinho, nao havia colocado a lista pois nao passava na minha cabeça, dor dor dor
b09f322540e7bbeaec6e9e07238e09374110fbc8
alixoallen/todos.py
/dobro triplo e raiz.py
162
4.03125
4
n=int(input('digite um numero :')) dobro= n*2 triplo= n*3 raiz= n**(1/2) print('o dobro de {} é {}, o triplo é {} , e a raiz é {}'.format(n,dobro,triplo,raiz))
0af2fe8c20ab0c3cd1b7c9282387577f64babe72
alixoallen/todos.py
/conversor de metros, centimetros e milimetros.py
196
3.8125
4
medida=float(input('quantos metros quer converter ?')) cm= medida*100 mm=medida*1000 print('segundo a metragem que escolheu, os centimetros correspondem a {}, e os milimetros a {}'.format(cm,mm ))
50807cca27c1d9b15e8a43d36a3fe2249529c96c
alixoallen/todos.py
/adivinhação.py
327
4.15625
4
from random import randint computer=randint(0,5) print('pensei no numero{}'.format(computer))#gera um numero aleatorio, ou faz o computador """"""pensar""""""""""""""" escolha=int(input('digite um numero:')) if escolha == computer: print('parabens voce acertou!') else: print('ora ora voce é meio pessimo nisso!')
23ffb890a15d4de9ec5686c12cc2476f78c4810c
yupei0318cs/ScrapyWebCrawler
/douban_book/douban_book/utils/threadsafe_queue.py
888
3.640625
4
import queue import threading q = queue.Queue() for i in range(5): q.put(i) while not q.empty(): print (q.get()) q = queue.LifoQueue() for i in range(5): q.put(i) while not q.empty(): print (q.get()) class Task: def __init__(self, priority, description): self.priority = priority self.description = description def __lt__(self, other): return self.priority < other.priority q = queue.PriorityQueue() q.put(Task(1, 'Important Task\n')) q.put(Task(10, 'Normal Task\n')) q.put(Task(100, 'Lazy Task\n')) def job(q): while True: task = q.get() print ('Task: ', task.description) q.task_done() threads = [threading.Thread(target= job, args= (q,)), threading.Thread(target=job, args=(q,))] for t in threads: t.setDaemon(True) t.start() q.join()
ce951ed88517fc810a94b560b2c96e86395874f7
lalluz/movie_trailer_website
/media.py
1,239
3.8125
4
import webbrowser class Movie: """ This class provides a way to store movie related information. Attributes: title (str): the movie title storyline (str): a short description of the movie box_art_url (str): a url to a poster image trailer_url (str): a url to a youtube trailer video production_company (str): the production company name director (str): the director full name duration (str): the duration in minutes box_office (str): the amount of money raised by ticket sales in dollars year (str): the release year """ def __init__(self, title, storyline, box_art_url, trailer_url, production_company, director, duration, box_office, year): """ Init Movie class """ self.title = title self.storyline = storyline self.box_art_url = box_art_url self.trailer_url = trailer_url self.production_company = production_company self.director = director self.duration = duration self.box_office = box_office self.year = year def show_trailer(self): """ Open the browser at the youtube trailer url. """ webbrowser.open(self.trailer_url)
d1e7bdef1bfbdee75db0888035cbee70ddf5875c
nedraki/gym_explorer
/deep_q_network.py
1,979
3.53125
4
import tensorflow as tf from tensorflow import keras from keras.models import Model, Sequential, load_model from keras.layers import Input, Dense, Dropout from keras.optimizers import Adam, RMSprop # Neural Network model for Deep Q Learning """Deep Q-Learning As an agent takes actions and moves through an environment, it learns to map the observed state of the environment to an action. An agent will choose an action in a given state based on a "Q-value", which is a weighted reward based on the expected highest long-term reward. A Q-Learning Agent learns to perform its task such that the recommended action maximizes the potential future rewards. This method is considered an "Off-Policy" method, meaning its Q values are updated assuming that the best action was chosen, even if the best action was not chosen.""" def create_q_model(input_shape: int, num_actions: int): """A model of Dense layers (fully connected layers) to train an agent using reinforcement learning. input_shape: Comes from observation of the environment. `env.observation_space.shape[0]` num_actions: Number of available actions that can be taken by the agent. `env.action_space.n` For more specific NN, you can find research of Deep Mind research at: [docs](https://keras.io/examples/rl/deep_q_network_breakout/) """ model = Sequential() model.add(Dense(512, activation='relu', input_shape=(input_shape,))) #model.add(Dropout(0.1)) model.add(Dense(256, activation='relu')) model.add(Dense(64, activation='relu')) #model.add(Dropout(0.1)) model.add(Dense(num_actions, activation='softmax')) # model = Model(inputs=X_input, outputs=model, name='trained_model') # In the Deepmind paper they use RMSProp however then Adam optimizer # improves training time model.compile(loss="mse", optimizer=Adam( learning_rate=0.001, epsilon=1e-07), metrics=["accuracy"]) model.summary() return model
39f15cc411cd352495194da5849953befe4edb07
Recky-krec/Python-BS4
/youtube-searcher-master/youtube-searcher.py
1,365
3.578125
4
#!/usr/bin/python3 import bs4 as bs import urllib.request import re import os def webRequest(url): """Creates a request based in the url""" headers = {"User-Agent":"Mozilla/5.0 (X11; Linux i686) AppleWebKit/537.17 (KHTML, like Gecko) Chrome/24.0.1312.27 Safari/537.17"} req = urllib.request.Request(url, headers=headers) #Creating a request raw_sauce = urllib.request.urlopen(req) #Opening url with created request sauce = raw_sauce.read() #Source code soup = bs.BeautifulSoup(sauce, features="lxml") #Creating BS4 object return soup def youtubeSearch(): """Use user input for retrieving desired background""" query = input("Insert query: ") #this is a trivial input method, consider changing it ;) query_keywords = query.split(" ") print("+".join(query_keywords)) url = 'https://www.youtube.com/results?search_query=' + "+".join(query_keywords) return url def writeToFile(url_list): with open("found_urls.txt", "w") as f: for url in url_list: f.write("www.youtube.com{url}\n".format(url=url)) def parse(): url_list = [] url = youtubeSearch() source = webRequest(url) pattern = r'/watch' for link in source.find_all('a'): link = link.get('href') if re.match(pattern, link): url_list.append(link) return url_list if __name__ == "__main__": url_list = parse() writeToFile(url_list)
ac1615321ed322852494f2d9e039a2756c8b6a55
mansiagnihotrii/Data-Structures-in-python
/Strings/5_single_edit.py
852
3.8125
4
''' Check whether the strings entered are one or zero edit away. Edits performed are: insert a character, remove a character, or replace a character ''' def single_edit(s1, s2): if s1 == s2: return True if abs(len(s1) - len(s2)) > 1: return False short_str = s1 if len(s1) < len(s2) else s2 long_str = s1 if len(s1) > len(s2) else s2 len_short_str = len(short_str) len_long_str = len(long_str) index1, index2 = 0, 0 found = False while index2< len_long_str and index1 < len_short_str: if short_str[index1] != long_str[index2]: if found: return False found =True if len_short_str == len_long_str: index1 += 1 else: index1 += 1 index2 += 1 return True s1 = input("Enter first string: ") s2 = input("Enter second string: ") print(single_edit(s1, s2))
9eb137a3f310eeb8c6d006bfd72fce5e035e06b2
mansiagnihotrii/Data-Structures-in-python
/Linked List/4_linkedlist_partition.py
851
4.125
4
''' Given a linked list and an element , say 'x'. Divide the same list so that the left part of the list has all the elements less that 'x' and right part has all elements greater than or equal to 'x'. ''' #!/usr/bin/env python3 import linkedlist from linkedlist import LinkedList,Node def partition_list(head,element): start = head new = LinkedList() new.head = Node(start.data) start = start.next while start: if start.data >= element: linkedlist.insert_end(new.head,start.data) else: new.head = linkedlist.insert_beg(new.head,start.data) start = start.next return new.head list1 = LinkedList() head = linkedlist.create_list(list1) element = input("Enter partition element: ") if head is None: print("List is empty") else: new_head = partition_list(head,element) linkedlist.printlist(new_head)
af7a3b336d50ddea1a8c4ec76a767f3143fdc44f
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/greedy/largest_permutation.py
2,068
4.09375
4
def largest_permutation(k, arr): """Hackerrank Problem: https://www.hackerrank.com/challenges/largest-permutation/problem You are given an unordered array of unique integers incrementing from 1. You can swap any two elements a limited number of times. Determine the largest lexicographical value array that can be created by executing no more than the limited number of swaps. For example, if arr = [1, 2, 3, 4] and the maximum swaps k = 1, the following arrays can be formed by swapping the 1 with the other elements: [2,1,3,4] [3,2,1,4] [4,2,3,1] The highest value of the four (including the original) is [4, 2, 3, 1]. If k >= 2, we can swap to the highest possible value: [4, 3, 2, 1]. Solve: We store the values in a dictionary so we can access the position of each value in O(1) speed. We then iterate through the list starting at the highest value, and swap it IF it isn't already in the correct position. We then update the dictionary with the swapped values, and then proceed to the next value to swap. Args: k (int): Number of swaps to perform arr (list): List of numbers where 1 <= arr[i] <= n Returns: list containing the largest lexicographical value array after k swaps """ sorted_array = sorted(arr, reverse=True) vals = {v: idx for idx, v in enumerate(arr)} c = 0 m = len(arr) while k > 0 and c < len(arr): if arr[c] != sorted_array[c]: # Swap the current highest value swap = arr[c] arr[c] = m arr[vals[m]] = swap # Update dictionary prev = vals[m] vals[m] = c vals[swap] = prev k -= 1 m -= 1 c += 1 return arr if __name__ == "__main__": print(largest_permutation(1, [4, 2, 3, 5, 1])) print(largest_permutation(2, [4, 2, 3, 5, 1])) print(largest_permutation(2, [4, 3, 2, 5, 1])) print(largest_permutation(1, [2, 1, 3])) print(largest_permutation(1, [2, 1]))
c696a2980ffe52412000a0f0deda444cea00badf
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/funny_string.py
1,059
4.34375
4
def funny_string(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/funny-string/problem In this challenge, you will determine whether a string is funny or not. To determine whether a string is funny, create a copy of the string in reverse e.g. abc -> cba. Iterating through each string, compare the absolute difference in the ascii values of the characters at positions 0 and 1, 1 and 2 and so on to the end. If the list of absolute differences is the same for both strings, they are funny. Determine whether a give string is funny. If it is, return Funny, otherwise return Not Funny. Args: s (str): String to check Returns: str: Returns "Funny" or "Not Funny" based on the results of the string """ for i in range(len(s)//2): if abs(ord(s[i]) - ord(s[i+1])) != abs(ord(s[len(s)-i-1]) - ord(s[len(s)-i-2])): return "Not Funny" return "Funny" if __name__ == "__main__": assert funny_string("acxz") == "Funny" assert funny_string("bcxz") == "Not Funny"
131e45b4fcdb5a3ef8a9efa3580a1ac03bda66f6
kcc3/hackerrank-solutions
/python/numpy/min_and_max.py
432
3.9375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/np-min-and-max/problem Task You are given a 2-D array with dimensions N x M. Your task is to perform the min function over axis 1 and then find the max of that. """ import numpy n, m = map(int, input().split(' ')) array = [] for _ in range(n): a = list(map(int, input().split(' '))) array.append(a) min_array = numpy.min(array, axis=1) print(max(min_array))
0562ecb6074ee2c8d62d863db65a1c5a5325fd66
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/strings/mars_exploration.py
919
4.34375
4
def mars_exploration(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/mars-exploration/problem Sami's spaceship crashed on Mars! She sends a series of SOS messages to Earth for help. Letters in some of the SOS messages are altered by cosmic radiation during transmission. Given the signal received by Earth as a string, s, determine how many letters of Sami's SOS have been changed by radiation. For example, Earth receives SOSTOT. Sami's original message was SOSSOS. Two of the message characters were changed in transit. Args: s (str): string to compare with SOS message (must be divisible by 3) Returns: int: the number of characters that differ between the message and "SOS" """ sos = int(len(s)/3) * "SOS" return sum(sos[i] != s[i] for i in range(len(s))) if __name__ == "__main__": assert mars_exploration("SOSSPSSQSSOR") == 3
ff2f6d4c31e79e2249438839b9e85049e4f2c4e0
kcc3/hackerrank-solutions
/python/python_functionals/validating_email_addresses_with_filter.py
1,146
4.15625
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/validate-list-of-email-address-with-filter/problem""" def fun(s): """Determine if the passed in email address is valid based on the following rules: It must have the username@websitename.extension format type. The username can only contain letters, digits, dashes and underscores [a-z], [A-Z], [0-9], [_-]. The website name can only have letters and digits [a-z][A-Z][0-9] The extension can only contain letters [a-z][A-Z]. The maximum length of the extension is 3. Args: s (str): Email address to check Returns: (bool): Whether email is valid or not """ if s.count("@") == 1: if s.count(".") == 1: user, domain = s.split("@") website, extension = domain.split(".") if user.replace("-", "").replace("_", "").isalnum(): if website.isalnum(): if extension.isalnum(): if len(extension) <= 3: return True return False if __name__ == "__main__": test = "itsallcrap" print(fun(test))
10a395af6ac6efa71d38074c2d88adff4665435e
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/bit_manipulation/maximizing_xor.py
932
4.3125
4
def maximizing_xor(l, r): """Hackerrank Problem: https://www.hackerrank.com/challenges/maximizing-xor/problem Given two integers, l and r, find the maximal value of a xor b, written a @ b, where a and b satisfy the following condition: l <= a <= b <= r Solve: We XOR the l and r bound and find the length of that integer in binary form. That gives us the binary from which we can create the highest value of a xor b, because that falls within l and r. Args: l (int): an integer, the lower bound inclusive r (int): an integer, the upper bound inclusive Returns: int: maximum value of the xor operations for all permutations of the integers from l to r inclusive """ xor = l ^ r xor_binary = "{0:b}".format(xor) return pow(2, len(xor_binary)) - 1 if __name__ == "__main__": print(maximizing_xor(10, 15)) print(maximizing_xor(11, 100))
5dada4e2c555cf79880499431e25a16d8a441ad3
kcc3/hackerrank-solutions
/python/numpy/zeros_and_ones.py
617
3.96875
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/np-zeros-and-ones/problem Task You are given the shape of the array in the form of space-separated integers, each integer representing the size of different dimensions, your task is to print an array of the given shape and integer type using the tools numpy.zeros and numpy.ones. """ import numpy # Read in the number of lines to parse dimensions = list(map(int, input().split(' '))) # Convert array to a bumpy array and print out transpose and flatten print(numpy.zeros(dimensions, dtype=numpy.int32)) print(numpy.ones(dimensions, dtype=numpy.int32))
6d15fcd0279049189d9a54c882f0b27a46034a59
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/the_grid_search.py
2,824
4.21875
4
def grid_search(g, p): """Hackerrank Problem: https://www.hackerrank.com/challenges/the-grid-search/problem Given a 2D array of digits or grid, try to find the occurrence of a given 2D pattern of digits. For example: Grid ---------- 1234567890 0987654321 1111111111 1111111111 2222222222 Pattern ------ 876543 111111 111111 The 2D pattern begins at the second row and the third column of the grid. The pattern is said to be present in the grid. Args: g (list): The grid to search, an array of strings p (list): The pattern to search for, an array of strings Returns: str: "YES" or "NO" depending on whether the pattern is found or not """ for i in range(len(g)-len(p)+1): # If we find a match for the first line, store the indices to search for match = [x for x in range(len(g[i])) if g[i].startswith(p[0], x)] if match: # Iterate through the list of indices where the first line of the pattern matched for j in match: found = True # Now see if the rest of the pattern matches within the same column / index for k in range(1, len(p)): if p[k] == g[i+k][j:j+len(p[k])]: continue else: found = False break if found: return "YES" return "NO" if __name__ == "__main__": g = ["7283455864", "6731158619", "8988242643", "3830589324", "2229505813", "5633845374", "6473530293", "7053106601", "0834282956", "4607924137"] p = ["9505", "3845", "3530"] assert grid_search(g, p) == "YES" g2 = ["7652157548860692421022503", "9283597467877865303553675", "4160389485250089289309493", "2583470721457150497569300", "3220130778636571709490905", "3588873017660047694725749", "9288991387848870159567061", "4840101673383478700737237", "8430916536880190158229898", "8986106490042260460547150", "2591460395957631878779378", "1816190871689680423501920", "0704047294563387014281341", "8544774664056811258209321", "9609294756392563447060526", "0170173859593369054590795", "6088985673796975810221577", "7738800757919472437622349", "5474120045253009653348388", "3930491401877849249410013", "1486477041403746396925337", "2955579022827592919878713", "2625547961868100985291514", "3673299809851325174555652", "4533398973801647859680907"] p2 = ["5250", "1457", "8636", "7660", "7848"] assert grid_search(g2, p2) == "YES" g3 = ["111111111111111", "111111111111111", "111111011111111", "111111111111111", "111111111111111"] p3 = ["11111", "11111", "11110"] assert grid_search(g3, p3) == "YES"
24ea0ea11b64dd814811282faa67c89274005133
kcc3/hackerrank-solutions
/python/numpy/transpose_and_flatten.py
735
4.0625
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/np-transpose-and-flatten/problem Task You are given a X integer array matrix with space separated elements ( = rows and = columns). Your task is to print the transpose and flatten results. """ import numpy # Initialize array array = [] # Read in the number of lines to parse n, m = input().split(' ') # Iterate through each line and add to the array array = [] for _ in range(int(n)): line = input() array_map = map(int, line.split(' ')) cur_array = numpy.array(list(array_map)) array.append(cur_array) # Convert array to a bumpy array and print out transpose and flatten array = numpy.array(array) print(numpy.transpose(array)) print(array.flatten())
6eba8809d2c6d10aadc221ea78cf0d08d458d967
kcc3/hackerrank-solutions
/data_structures/python/stacks/maximum_element.py
1,176
4.34375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/maximum-element/problem You have an empty sequence, and you will be given queries. Each query is one of these three types: 1 x -Push the element x into the stack. 2 -Delete the element present at the top of the stack. 3 -Print the maximum element in the stack. """ # Enter your code here. Read input from STDIN. Print output to STDOUT # Setup the list which will act as our stack stack = [-1] # Read in the total number of commands num_commands = int(input()) # For each command, append, pop, or return the max value as specified. When we push to the stack, we can compare # with the current highest value so that the stack always has the max value at the tail of the list, and because when # we pop, we are removing the last added item, so it is either the last added value, or a copy of the last max value # when it was added for _ in range(num_commands): query = input().split(" ") if query[0] == "1": stack.append(max(int(query[1]), stack[-1])) elif query[0] == "2": stack.pop() elif query[0] == "3": print(stack[-1]) else: print("Unknown command")
54e29a17af6dfcb36c102bba527a588a533d29f3
kcc3/hackerrank-solutions
/python/built_ins/any_or_all.py
548
4.15625
4
""" Hackerrank Problem: https://www.hackerrank.com/challenges/any-or-all/problem Given a space separated list of integers, check to see if all the integers are positive, and if so, check if any integer is a palindromic integer. """ n = int(input()) ints = list(input().split(" ")) # Check to see if all integers in the list are positive if all(int(i) >= 0 for i in ints): # Check if any of the integers are a palindrome - where the digit number is the same if digits are reversed print(any(j == j[-1] for j in ints)) else: print(False)
3cc86ea1557ecd260202121ce31df104a83d1b09
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/taum_and_bday.py
1,606
4.09375
4
def taum_bday(b, w, bc, wc, z): """Hackerrank Problem: https://www.hackerrank.com/challenges/taum-and-bday/problem Taum is planning to celebrate the birthday of his friend, Diksha. There are two types of gifts that Diksha wants from Taum: one is black and the other is white. To make her happy, Taum has to buy b black gifts and w white gifts. - The cost of each black gift is bc units. - The cost of every white gift is wc units. - The cost of converting each black gift into white gift or vice versa is z units. Help Taum by deducing the minimum amount he needs to spend on Diksha's gifts. For example, if Taum wants to buy b = 3 black gifts and w = 5 white gifts at a cost of bc = 3, wc = 4 and conversion cost z = 1, we see that he can buy a black gift for 3 and convert it to a white gift for 1, making the total cost of each white gift 4. That matches the cost of a white gift, so he can do that or just buy black gifts and white gifts. Either way, the overall cost is 3 * 3 + 5 * 4 = 29. Args: b (int): The number of black presents to purchase w: (int): The number of white presents to purchase bc (int): The cost of each black present wc (int): The cost of each white present z (int): The cost to switch between the present types Returns: int: the optimized cost to buy the specified presents """ return b * min(bc, wc + z) + w * min(wc, bc + z) if __name__ == "__main__": print taum_bday(3, 5, 3, 4, 1) print taum_bday(10, 10, 1, 1 , 1) print taum_bday(5, 9, 2, 3, 4)
048f4a1843a7cb34f846a62ff3cc70225a74c763
kcc3/hackerrank-solutions
/data_structures/python/stacks/balanced_brackets.py
2,594
4.40625
4
def is_balanced(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/balanced-brackets/problem A bracket is considered to be any one of the following characters: (, ), {, }, [, or ]. Two brackets are considered to be a matched pair if the an opening bracket (i.e., (, [, or {) occurs to the left of a closing bracket (i.e., ), ], or }) of the exact same type. There are three types of matched pairs of brackets: [], {}, and (). A matching pair of brackets is not balanced if the set of brackets it encloses are not matched. For example, {[(])} is not balanced because the contents in between { and } are not balanced. The pair of square brackets encloses a single, unbalanced opening bracket, (, and the pair of parentheses encloses a single, unbalanced closing square bracket, ]. By this logic, we say a sequence of brackets is balanced if the following conditions are met: - It contains no unmatched brackets. - The subset of brackets enclosed within the confines of a matched pair of brackets is also a matched pair of brackets. Given n strings of brackets, determine whether each sequence of brackets is balanced. If a string is balanced, return YES. Otherwise, return NO. Args: s (str): The string to compare Returns: (str): "YES" or "NO" based on whether the brackets in the string are balanced """ open_closed = {"(": ")", "[": "]", "{": "}"} balanced = [] for i in s: if i in open_closed.keys(): balanced.append(i) else: # If the stack is empty, we have a closed bracket without any corresponding open bracket so not balanced if len(balanced) == 0: return "NO" # Compare the brackets to see if they correspond, and if not, not balanced if i != open_closed[balanced.pop()]: return "NO" # If the stack is empty, every open bracket has been closed with a corresponding closed bracket if not balanced: return "YES" # If there's still something in the stack, then return NO because it's not balanced return "NO" if __name__ == "__main__": assert is_balanced("}}}") == "NO" assert is_balanced("{[()]}") == "YES" assert is_balanced("{[(])}") == "NO" assert is_balanced("{{[[(())]]}}") == "YES" assert is_balanced("{{([])}}") == "YES" assert is_balanced("{{)[](}}") == "NO" assert is_balanced("{(([])[])[]}") == "YES" assert is_balanced("{(([])[])[]]}") == "NO" assert is_balanced("{(([])[])[]}[]") == "YES"
64029718781f0f862fed1741ef8c28bea8d80233
kcc3/hackerrank-solutions
/data_structures/python/linked_lists/insert_node_at_specific_position_in_linked_list.py
2,513
4.09375
4
"""Hackerrank Problem: https://www.hackerrank.com/challenges/insert-a-node-at-a-specific-position-in-a-linked-list/problem Given the pointer to the head node of a linked list and an integer to insert at a certain position, create a new node with the given integer as its data attribute, insert this node at the desired position and return the head node. A position of 0 indicates head, a position of 1 indicates one node away from the head and so on. The head pointer given may be null meaning that the initial list is empty. """ import math import os import random import re import sys class SinglyLinkedListNode: def __init__(self, node_data): self.data = node_data self.next = None class SinglyLinkedList: def __init__(self): self.head = None self.tail = None def insert_node(self, node_data): node = SinglyLinkedListNode(node_data) if not self.head: self.head = node else: self.tail.next = node self.tail = node def print_singly_linked_list(node, sep, fptr): while node: fptr.write(str(node.data)) node = node.next if node: fptr.write(sep) # Complete the insertNodeAtPosition function below. # # For your reference: # # SinglyLinkedListNode: # int data # SinglyLinkedListNode next # # def insertNodeAtPosition(head, data, position): """Function to insert a new node into a linked list at the specified index position Args: head (SinglyLinkedListNode): Head of the linked list data (int): Data to store in the linked list position (int): The position to store the new node Returns: head (SinglyLinkedListNode): Head of the new linked list with the added node """ if position == 0: return SinglyLinkedListNode(data) traverse = head for i in range(position - 1): traverse = traverse.next new_node = SinglyLinkedListNode(data) new_node.next = traverse.next traverse.next = new_node return head if __name__ == '__main__': fptr = open(os.environ['OUTPUT_PATH'], 'w') llist_count = int(input()) llist = SinglyLinkedList() for _ in range(llist_count): llist_item = int(input()) llist.insert_node(llist_item) data = int(input()) position = int(input()) llist_head = insertNodeAtPosition(llist.head, data, position) print_singly_linked_list(llist_head, ' ', fptr) fptr.write('\n') fptr.close()
93d2c4f2eb3485d73051a93cfa531070aa46a563
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/bigger_is_greater.py
1,021
4.28125
4
def bigger_is_greater(w): """Hackerrank Problem: https://www.hackerrank.com/challenges/bigger-is-greater/problem Given a word, create a new word by swapping some or all of its characters. This new word must meet two criteria: - It must be greater than the original word - It must be the smallest word that meets the first condition Args: w (str): The word to swap Returns: str: Return the next highest lexicographical word or "no answer" """ # Find non-increasing suffix arr = [c for c in w] i = len(arr) - 1 while i > 0 and arr[i - 1] >= arr[i]: i -= 1 if i <= 0: return "no answer" # Find successor to pivot j = len(arr) - 1 while arr[j] <= arr[i - 1]: j -= 1 arr[i - 1], arr[j] = arr[j], arr[i - 1] # Reverse suffix arr[i:] = arr[len(arr) - 1: i - 1: -1] return "".join(arr) if __name__ == "__main__": print(bigger_is_greater("zzzayybbaa")) print(bigger_is_greater("zyyxwwtrrnmlggfeb"))
fcb4d9bc984884d587811ceb50aa624e520e709d
kcc3/hackerrank-solutions
/python/itertools/itertools_combinations_with_replacements.py
303
3.578125
4
""" Hackerrank Problem: https://www.hackerrank.com/challenges/itertools-combinations-with-replacement/problem """ from itertools import combinations_with_replacement string, k = input().split(" ") for combination in combinations_with_replacement(sorted(string), int(k)): print("".join(combination))
ef1ff7bf8a43249a3848049ae41e3506578d44ab
kcc3/hackerrank-solutions
/problem_solving/python/algorithms/implementation/encryption.py
653
3.953125
4
import math def encryption(s): """Hackerrank Problem: https://www.hackerrank.com/challenges/encryption/problem Encryption function based on the specifics as provided in the challenge. Args: s (str): The string to encrypt Returns: str: The string after passing through specified encryption """ string = s.replace(" ", "") columns = math.ceil(math.sqrt(len(string))) line = "" for i in range(columns): line += string[i::columns] + " " return line if __name__ == "__main__": print(encryption("have a nice day")) print(encryption("feedthedog")) print(encryption("chillout"))
8e6a005a4c9160c79ac341f317dedb5c6f04d9cb
cisquo/cours_python_hepia
/ex50.py
1,803
3.53125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #s = input ("Entrez une valeur: ") def longueur(l1): nb = 0 for x in l1: nb += 1 return nb def moyenne(l1): total = 0 for x in l1: total = total + x return total / longueur(l1) if l1 else 0 def plus_grand_ou_egal (l1, n): res = [] for x in l1: if x >= n : res.append(x) return res def plus_petit_ou_egal (l1, n): res = [] for x in l1: if x <= n : res.append(x) return res def minimum (l1): res = l1[0] for x in l1: if x < res : res = x return res def positive (l1): return plus_grand_ou_egal(l1,0) def dans(l1, n): return True if (set(l1) & set({n})) == {n} else False def binaire(l1): res = 0 for i, elem in enumerate(reversed(l1)): # print(i,':',elem) # print(elem*(2**i)) res += int(elem)*(2**i) return(res) def and_lst(lst): for elem in lst: if not elem: return False return True def zip(l1, l2): l3 = [] if len(l1) == len(l2): for i in range(len(l1)): l3.append((l1[i], l2[i])) return l3 return l3 # [(A,B]] -> ([A],[B]) def unzip(l1): l3 = [] l2 = [] for i, j in l1: l3.append(i) l2.append(j) return l2, l3 def f(x): return 2*x+2 def transform(lst,f): l2 = [] for elem in lst: l2.append( f(elem) ) return l2 def majeur(age): return age >= 18 def mineur(age): return age < 18 def filter(lst,f): l2 = [] for elem in lst: if f(elem): l2.append( (elem) ) return l2 def remove_duplicates(lst): l2 = [] for elem in lst: if f(elem) l2.append( (elem) ) return l2
72aa1573e269adc097e788feba4bec118353f114
cisquo/cours_python_hepia
/ex512.py
513
4.03125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #s = input ("Entrez une valeur: ") def add(dic,k,v): dic.append((k,v)) def index(dic,val): for k,v in dic: if v == val: return k def lenght(dic): return len(dic) def is_in(dic, cle): for k,v in dic: if k == cle: return True return False def val(dic): print (dic) def key(dic): for k,v in dic: print (k) def reverse(dic): for k,v in dic: print (v,k) try: res =
49f4e08c38d8f2429e77d4af1d29e4010c381208
archeranimesh/pythonFundamentals
/code/pyworkshop/02_list/list_sort.py
556
4.21875
4
# Two ways to sort a list. lottery_numbers = [1, 3, 345, 123, 789, 12341] # 1st method does not modify the original list, # returns a shallow copy of original list. print("sorted list: ", sorted(lottery_numbers)) # reverse the list. print("reverse list: ", sorted(lottery_numbers, reverse=True)) x = sorted(lottery_numbers) # returns a list. print("x = ", x, "\ntypeof(x): ", type(x)) # In place list sorting. lottery_numbers.sort() print("list sort: ", lottery_numbers) # reverse lottery_numbers.reverse() print("list reverse: ", lottery_numbers)
d7b87d4a7e4d87be392508d92cd10d2ff1e033e5
archeranimesh/pythonFundamentals
/code/pyworkshop/07_loops_if/05_break_continue_return.py
645
3.828125
4
# Break, stops the execution of loop and jumps to end of loop. # Continue, doesn't continue the following loop statement, but jump to start of loop. names = ["Jimmy", "Rose", "Max", "Nina", "Phillip"] for name in names: if len(name) != 4: continue # Start new iteration when len is not 4 print(f"Hello, {name}") if name == "Nina": break # Exit from loop when condition is met print("Done") # In nested loop, break exit from the loop it is part of i = 1 j = 1 while i < 10: while j < 10: print(f"{i} : {j}") j += 1 if j == 4: break # breaks from inner loop i += 1
63a6c50f451fd165eeff0b514a9c5e87b44b531d
michalecki/codewars
/sum_of_intervals.py
1,528
4.1875
4
''' Write a function called sumIntervals/sum_intervals() that accepts an array of intervals, and returns the sum of all the interval lengths. Overlapping intervals should only be counted once. Intervals are represented by a pair of integers in the form of an array. The first value of the interval will always be less than the second value. Interval example: [1, 5] is an interval from 1 to 5. The length of this interval is 4. List containing overlapping intervals: [ [1,4], [7, 10], [3, 5] ] The sum of the lengths of these intervals is 7. Since [1, 4] and [3, 5] overlap, we can treat the interval as [1, 5], which has a length of 4. ''' def sum_intervals(inp_arr): ''' :param array: array of intervals :return: sum of lengths of the intervals ''' # sort the intervals over the first digit inp_arr.sort() # loop and merge if overlap i = 0 while i < len(inp_arr) - 1: while inp_arr[i][1] >= inp_arr[i + 1][0]: inp_arr[i] = [inp_arr[i][0], max(inp_arr[i + 1][1], inp_arr[i][1])] del inp_arr[i + 1] if i == len(inp_arr) - 1: break i += 1 # calculate the sum total = sum([inp_arr[x][1] - inp_arr[x][0] for x in range(len(inp_arr))]) return total # testing sum_intervals([ [1, 2], [6, 10], [11, 15] ]) # \; // => 9 sum_intervals([ [1, 4], [7, 10], [3, 5] ]) # ; // => 7 sum_intervals([ [1, 5], [10, 20], [1, 6], [16, 19], [5, 11] ]) # ; // => 19
aa970b317af5316d42807008efbc5b41e8347486
michalecki/codewars
/sum_of_numbers.py
582
4.34375
4
def get_sum(a,b): ''' Given two integers a and b, which can be positive or negative, find the sum of all the numbers between including them too and return it. If the two numbers are equal return a or b. Note: a and b are not ordered! :param a: int :param b: int :return: int ''' if a == b: return a ab = [a, b] ab.sort() return sum(range(ab[0],ab[1]+1)) #testing print(get_sum(0,1)) # ok print(get_sum(4,4)) # ok print(get_sum(0,-1)) print(get_sum(-2,0)) print(get_sum(-3,-2)) print(get_sum(4,2)) print(get_sum(-3,5))#ok
67c080061bd2de6a136ca201be47f659b7770fa3
oostlab/python-pen-web
/bruteforce/postgress_brute.py
3,582
3.53125
4
#!/usr/bin/python3 ''' Postgress bruteforce script. A script for bruteforcing postgress Test with the following commandline python3 postgress_brute.py 192.168.2.5 users.txt passwords.txt ''' import psycopg2 import sys from time import sleep def execute_scan(host, userfile, passwordfile, port, connect_timeout, ssl): '''Execute the bruteforce scan :param str host: hosts (IP addresses, hostnames) comma separated :param str userfile: filename with usernames :param str passwordfile: filename with passwords :param int port : port number :param bool ssl: bool to set ssl :param bool use_subset: bool for subset of lists and slow connection ''' # connect_timeout = 2 # read_timeout = 2 try: # exceptions with files # open the Userfile in users list users = [] with open(userfile) as file: for line in file: users.append(line.strip()) passwords = [] with open(passwordfile) as file: for line in file: passwords.append(line.strip()) except Exception as FileError: print(FileError) login_postgress(host, users, passwords, port, connect_timeout, ssl) def check_postgress(host, port, connect_timeout): """Function for checking if there is postgress database running.""" try: # connect to the PostgreSQL server conn = psycopg2.connect(host="192.168.2.8", user="postgres", password="postgress", port=5432, connect_timeout=1) if conn is not None: conn.close() return True except (Exception, psycopg2.DatabaseError) as error: # print(error) if 'password authentication failed' in str(error): return True else: return False def login_postgress(host, users, passwords, port, connect_timeout, ssl): """Function for logging in to postgress.""" for user in users: for password in passwords: sleep(1) try: # connect to the PostgreSQL server # print('Connecting to the PostgreSQL database...') print(f'Trying with {user}:{password} on {host}') conn = psycopg2.connect(host=host, user=user, password=password, port=port, connect_timeout=connect_timeout) # conn = psycopg2.connect(host="192.168.2.8", port=5432, connect_timeout=1) if conn is not None: print(f'connected with {user}:{password} on {host}') conn.close() except (Exception, psycopg2.DatabaseError) as error: # print(error) if 'password authentication failed' in str(error): print('wrong userid and password') elif 'Connection refused' in str(error): print('Connection refused') break else: print(error) break else: continue break if len(sys.argv) != 4: print("Not enough arguments:\n" + 'Usage: postgress_brute.py target userfile passfile') else: host = sys.argv[1] users = sys.argv[2] passw = sys.argv[3] ssl = False if check_postgress(host, 5432, 3): print('postgress available continue with bruteforcing') execute_scan(host, users, passw, 5432, 1, ssl) else: print('No postgress server available')
791406611128204f4689899bf23292904e7e1c7d
trandaniel/project-euler-solutions
/python/problem004.py
393
4.03125
4
# A palindromic number reads the same both ways. The largest palindrome made from # the product of two 2-digit numbers is 9009 = 91 x 99. # # Find the largest palindrome made from the product of two 3-digit numbers. largest = 0 for i in xrange(100, 1000): for j in xrange(100, 1000): if (i * j > largest) and (str(i*j) == str(i*j)[::-1]): largest = i*j print largest
7e3dbd35ab956465da78d9d923a7ffe37f9005bc
makcg/HomeWork
/HW5/Lesson 5 Prictice task 3.py
635
4.0625
4
# Вспоминаем работу с файлом. Есть файл, в котором много англоязычных текстовых строк. # Считаем частоту встретившихся слов в файле, но через функции и map, без единого цикла! from collections import Counter file = open('text_for_ practice_task_3.py', 'r') def lower(a): return a.lower() def counter(f): list_split = list(map(str, f.split())) list_split = map(lower, list_split) counter = Counter(list_split) return counter print(list(map(counter, file))) file.close()
6f4909312fd87ec11a1e4c74c70a2e05fca8a840
makcg/HomeWork
/HW5/Lesson 5 Task 3.py
311
4.03125
4
from itertools import zip_longest s = [1, 2, 3, 4] u = ['q', 'w', 'e', 'r', 't'] y = [5, 6, 7, 8] def zip_func(a, b, c): """ input: three random lists combines three lists (including different lengths) return: one list """ return list(zip_longest(a, b, c)) print(zip_func(s, u, y))
23d50115da2e3217dfde2bd62ff14039ca1044f2
MayaYosef/Synthetic-Digits-Classification
/python/makegraphs.py
3,332
3.984375
4
""" this python file is responsible for making and saving graphs of the training process """ import matplotlib matplotlib.use( 'tkagg' ) import matplotlib.pyplot as plt import numpy as np import os import printmessage def graphs(H, plot_path, epoches): """ responsible for making, saving and presenting the graphs of the training process & printing a message with the location of the plots in the computer. param plot_path: the directory in which the graphs will be saved param epoches: the number of epochs- The number of times the images ran on the model for learning purposes """ os.mkdir(plot_path) plotpath1 = plot_path + r"\plot1.png" plotpath2 = plot_path + r"\plot2.png" plotpath3 = plot_path + r"\plot3.png" graph1(H, plotpath1, epoches) graph2(H, plotpath2) graph3(H, plotpath3) printmessage.printProcess("Graphs of the training process are in " + plot_path) def graph1(H, plot_path1, epoches): """ Creates a png image file in which it draws the learning graph of the model, saving it and showing it at the end of the training. (traning & validation accuracy & loss) param H: the history of the model training param plot_path1: the directory in which graphs 1 will be saved param epochs: the number of times the images ran on the model for learning purpose """ plt.style.use("ggplot") plt.figure() N = epoches plt.plot(np.arange(0, N), H.history["loss"], label="train_loss") plt.plot(np.arange(0, N), H.history["val_loss"], label="val_loss") plt.plot(np.arange(0, N), H.history["accuracy"], label="train_acc") plt.plot(np.arange(0, N), H.history["val_accuracy"], label="val_acc") plt.title("Training Loss and Accuracy") plt.xlabel("Epoch #") plt.ylabel("Loss/Accuracy") plt.legend(loc="upper left") plt.savefig(plot_path1) #save plot to file plt.show() def graph2(H, plot_path2): """ Creates a png image file in which it draws the learning graph of the model, saving it and showing it after the user closed the first plot. (traning & validation cross entropy loss) param H: the history of the model training param plot_path2: the directory in which graphs 2 will be saved """ plt.style.use("ggplot") plt.figure() plt.title('Cross Entropy Loss') plt.plot(H.history['loss'], color='blue', label='train') plt.plot(H.history['val_loss'], color='orange', label='val') plt.legend(loc="upper left") plt.savefig(plot_path2) plt.show() def graph3(H, plot_path3): """ Creates a png image file in which it draws the learning graph of the model, saving it and showing it after the user closed the second plot. (traning & validation classification accuracy) param H: the history of the model training param plot_path3: the directory in which graphs 3 will be saved """ plt.style.use("ggplot") plt.figure() plt.title('Classification Accuracy') plt.plot(H.history['accuracy'], color='blue', label='train') plt.plot(H.history['val_accuracy'], color='orange', label='val') plt.legend(loc="upper left") plt.savefig(plot_path3) plt.show()
81e3bc5134fd6998b582378871194a42a9373528
melissawm/rse2017
/examples/example 1/IDEB.py
8,455
4.0625
4
# coding: utf-8 # # Example: IDEB Analysis # We are going to analyse data corresponding to the IDEB (Basic Education Development Index) for brazilian cities. The data comes from the file # In[1]: ideb_file = "IDEB por Município Rede Federal Séries Finais (5ª a 8ª).xml" # which was obtained from the main brazilian government open data site <a href="http://dados.gov.br">dados.gov.br</a> # Since we have an .xml file, we'll use the *xml.etree.ElementTree* module to parse its contents. For simplicity, we'll call this module *ET*. # In[2]: import xml.etree.ElementTree as ET # ### The ElementTree (ET) module # # An XML file is a hierarchical set of data, so the most intuitive way to represent this data is by a tree. To do this, the ET module implements two classes: the ElementTree class represents the whole XML file as a tree, and the Element class represents one node of this tree. All interactions that occurr with the whole file (like reading and writing to this file) are done through the ElementTree class; on the other hand, every interaction with an isolated element of the XML and its subelements are done through the Element class. # # By reading the docs, we learn that the *ET.parse* methods returns an *ElementTree* from a file. # In[3]: tree = ET.parse(ideb_file) # The *ElementTree* class has the following structure: # In[4]: dir(tree) # According to the documentation for this module, we access the ElementTree via its *root* node, which is an *Element* class instance. To see the root element, we use the *getroot* method: # In[5]: root = tree.getroot() # As an *Element*, the root object has the *tag* and *attrib* properties, and *attrib* is a dictionary of its attributes. Let's see what are these values: # In[6]: # root.tag # In[7]: # root.attrib # To access each child node of the root element, we iterate on these nodes (which are also *Elements*): # In[8]: # for child in root: # print(child.tag, child.attrib) # We can see that our XML comes with a lot of data. Next, we will try to get a subset of this data. # ### Selecting the data # Now that we have a better idea of the document's structure, let's build a pandas *DataFrame* with what we need. First, we can see that we only need the last node of the root element, "valores" (which stands for "values" in Portuguese); the other nodes are in fact just the header for the XML file. Let's explore this node. # In[9]: IDEBvalues = root.find('valores') # Note that there is one more layer of data here: # In[10]: # IDEBvalues # In[11]: # IDEBvalues[0] # Now, we can explore the grandchildren of the root node: # In[12]: # for child in IDEBvalues: # for grandchild in child: # print(grandchild.tag, grandchild.attrib) # Now, let's extract the data we are interested in: # In[13]: data = [] for child in IDEBvalues: data.append([float(child[0].text), child[1].text, child[2].text]) # In[14]: # data # Since <a href="http://pandas.pydata.org/">Pandas</a> seems to be fashionable right now ;) let's use it to store and treat this data. We'll give it a shorter name though, pd. # In[15]: import pandas as pd # Now, we create our DataFrame from the preexisting data. # In[16]: IDEBTable = pd.DataFrame(data, columns = ["Valor", "Municipio", "Ano"]) # In[17]: # IDEBTable # You can see there are two sets of data here, one for 2007 and another for 2009. We'll only use the most recent data for our "analysis". # In[18]: IDEBTable = IDEBTable.loc[0:19] # ### Identifying the city codes # # In our IDEBTable, cities are identified by their so called "IBGE Code", which is a code issued to each locality by the Brazilian Institute for Geography and Statistics (IBGE). In order to make this more user friendly, we'll read the most recent Excel file with the list of cities and their respective 7 digit codes (from 2014; these codes include a final verification digit). For this, we'll use the xlrd module, which must be manually installed; see <a href="https://pypi.python.org/pypi/xlrd">this</a>. # In[19]: localCodesIBGE = pd.read_excel("DTB_2014_Municipio.xls") # Now we can inspect the data by using the pandas *head* method for DataFrames: # In[20]: # localCodesIBGE.head() # The columns we are interested in are just "Nome_UF", "Cod Municipio Completo" and "Nome_Município", which stand for State (or Province), Complete City Code and City Name, respectively. # In[21]: localCodesIBGE = localCodesIBGE[["Nome_UF", "Cod Municipio Completo", "Nome_Município"]] # Now, we have two DataFrames: **IDEBTable**, containing the complete IDEB data corresponding to city names, and **localCodesIBGE**, containing the corresponding city codes. We must select from the complete **localCodesIBGE** table only the rows corresponding to cities for which we have the IDEB value. For this, we will extract from both DataFrames the columns corresponding to the city codes (remember that in the **localCodesIBGE** table, codes have an extra verification code which we will not use): # In[42]: IDEBCities = IDEBTable["Municipio"] cities = localCodesIBGE["Cod Municipio Completo"].map(lambda x: str(x)[0:6]) # Note that we have used *map* to transform numerical data into strings, removing the last digit. # # Now, both **IDEBCities** and **cities** are pandas Series objects. To get the indices of cities for which we have IDEB data, first we will identify which codes are **not** in **IDEBCities**: # In[43]: citiesToRemove = cities[~cities.isin(IDEBCities)] # We remove the corresponding rows from the localCodesIBGE table: # In[45]: newTable = localCodesIBGE.drop(citiesToRemove.index).reset_index(drop=True) # Finally, we will create a new DataFrame joining city name and IDEB value: # In[46]: finalData = pd.concat([newTable, IDEBTable], axis=1) # This gives # In[47]: finalData # ## Finishing up: a pretty figure # # In order to include graphics in notebooks, usually the first cell in the notebook contains the code # # % matplotlib inline # # or # # % matplotlib notebook # # Since we don't want to sacrifice the legibility of our *article* by starting it with some misterious command, we can use the **init_cell** nbextension so that a later cell is executed first on our notebook ([More details](#about_initcell)). # # First, let's import the pyplot sublibrary of the matplotlib library and call it plt: # In[48]: import matplotlib.pyplot as plt # We'll do a very simple plot, but for this it would be nice to use the city names instead of the numerical indices in the finalData table: # In[49]: finalData.set_index(["Nome_Município"], inplace=True) # Now, we will select the column with the values ("Valor") for the IDEB by city in the finalData table (note that the result of this operation is a Series): # In[50]: finalData["Valor"] # We are ready for our pretty (yet irrelevant) picture. # In[52]: finalData["Valor"].plot(kind='barh') plt.title("IDEB by city (Data from 2009)") # ## Comments about automatic documentation and script generation # # To convert this notebook to a regular Python .py script, use #jupyter-nbconvert --to python 'IDEB.ipynb' --template=removeextracode.tpl # The removeextracode.tpl has the following content: #{% extends 'python.tpl'%} #{% block input %} #{% if 'codecomment' in cell['metadata'].get('tags', []) %} # {{ cell.source | comment_lines }} #{% else %} # {{ cell.source | ipython2python }} #{% endif %} #{% endblock input %} # This means that we will include all notebook cells tagged with **codecomment** as comments on our script. This is to avoid generating a unusable script including our inspection of objects and attempts at solving a problem. # # For more details on templates and the nbconvert extension, check <a href="https://jupyter-contrib-nbextensions.readthedocs.io/en/latest/">this page</a>, for example. # ## Initialization cell <a id='about_initcell'></a> # # Through the "init_cell" extension (also from nbextensions), it is possible to alter the order of execution of notebook cells. If we look at the metadata of the cell below, we can see that it is marked to be executed before all other cells, and so we obtain the desired result when we run all cells in the notebook. (This command allows us to see inline graphics inside our notebook). # In[53]: # %matplotlib inline
a013fb32d1e0ffc470c56a9f7ec6fefc8daf831c
NgoHarrison/CodingPractice
/7. Graphs/employee_inheritance.py
675
3.75
4
""" # Employee info class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): # It's the unique id of each node. # unique id of this employee self.id = id # the importance value of this employee self.importance = importance # the id of direct subordinates self.subordinates = subordinates """ class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: mapping = {i.id: i for i in employees} def dfs(emp): cur = mapping[emp] return cur.importance + (sum(dfs(emp) for emp in cur.subordinates)) return dfs(id)
ee9eacd0237b3283f840b5b6b3ef338e2bc53cd4
NgoHarrison/CodingPractice
/3. Arrays/Longest_Mountain_In_Array.py
1,232
3.84375
4
def longestMountain(A): print(A) left = 0 right = len(A)-1 while left < right: #print(A[left:right+1]) middle = (right+left)//2 print(left,middle,right) temp = sorted(A[left:middle+1])+sorted(A[middle+1:right+1],reverse=True) if len(temp) < 3: return 0 if temp == A[left:middle]+A[middle:right+1] and len(temp)==(len(set(temp[0:middle]))+len(set(temp[middle:len(temp)]))): if temp[len(temp)//2] > temp[(len(temp)//2)-1] and temp[len(temp)//2] > temp[(len(temp)//2)+1]: return right-left+1 if A[left+1] <= A[left] and A[right] < A[right-1]: left+=1 elif A[left+1] > A[left] and A[right] >= A[right-1]: right-=1 else: left+=1 right-=1 return 0 arr=[0,1,2,3,4,5,4,3,2,1,0] arr2=[2,2,2] arr3=[2,1,4,7,3,2,5] arr4=[0,1,2,3,4,5,6,7,8,9,10,8,7,6,5,4,3,2,1,0] arr5=[0,1,2,3,4,5,6,7,8,9] arr6=[0,1,0,2,2] arr7=[4,2,9,8,0] print(longestMountain(arr7)) #print(arr[0:2]+arr[2:4]) #print('-------') #middle = 3 #print(sorted(arr[0:middle]+arr[middle:len(arr)])) #temp = sorted(arr,reverse=True) #print(arr) #print(temp) #print(arr==temp[0:len(temp)])
e000295cea431c02d05cc166379d0c564f0c7f1b
ShreyanGoswami/coding-contests
/Leetcode weekly contest 188/array_with_stack_ops.py
1,263
3.890625
4
''' Given an array target and an integer n. In each iteration, you will read a number from list = {1,2,3..., n}. Build the target array using the following operations: Push: Read a new element from the beginning list, and push it in the array. Pop: delete the last element of the array. If the target array is already built, stop reading more elements. You are guaranteed that the target array is strictly increasing, only containing numbers between 1 to n inclusive. Return the operations to build the target array. You are guaranteed that the answer is unique. ''' from typing import List def buildArray(self, target: List[int], n: int) -> List[str]: ''' Time complexity: O(n) Space complexity: O(n) ''' res = [] s = set(target) prefixSum = [0, 1] for i in range(2, n+1): if i in s: prefixSum.append(prefixSum[i-1] + i) else: prefixSum.append(prefixSum[i-1]) for i in range(1, n+1): if i in s: res.append('Push') else: if prefixSum[n] - prefixSum[i] == 0: break res.append('Push') res.append('Pop') return res
a72af4074104f47c32f8714796c4a1f6948bc8d1
ShreyanGoswami/coding-contests
/Leetcode weekly contest 189/rearrange_words_in_sentence.py
860
4.25
4
''' Given a sentence text (A sentence is a string of space-separated words) in the following format: First letter is in upper case. Each word in text are separated by a single space. Your task is to rearrange the words in text such that all words are rearranged in an increasing order of their lengths. If two words have the same length, arrange them in their original order. Return the new text following the format shown above. ''' class Solution: def arrangeWords(self, text: str) -> str: ''' Time complexity: O(nlogn) Space complexity: O(n*m) where n is the number of words and m is the maximum number of letters in a word ''' words = text.split() words[0] = words[0].lower() words.sort(key = lambda x: len(x)) words[0] = words[0].capitalize() return " ".join(x for x in words)