blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
88b776ce62e4f4a0c6aec9dfd349fc99929ecb07
krishnatiruveedula/ktrepository
/if_else.py
136
4.21875
4
num = int(input("Enter the number: ")) mod =num % 2 if mod > 0 : print("This is ODD numuber") else: print("This is EVEN number.")
d46c887b9ab5f7bb73d9d9741f4c44c5b9e5d8b1
yakshitgupta310/Patterns
/pattern-14(reverse-diamond).py
645
3.90625
4
n = 13 for i in range(n): if i <= (n // 2): for j in range((n // 2) - i + 1): print("*", end="\t") for k in range(i + 1): print("", end="\t") for l in range(i): print("", end="\t") for m in range((n // 2) + 1 - i): print("*", end="\t") else: for j in range(i - (n // 2) + 1): print("*", end="\t") for k in range(n - i): print("", end="\t") for l in range(n - i - 1): print("", end="\t") for m in range(i - (n // 2) + 1): print("*", end="\t") print()
95fbf27f30a05e613a017e17d12e88a4900892f3
DaHuO/Supergraph
/codes/CodeJamCrawler/CJ_16_1/16_1_1_Hamukichi_r1aa.py
438
3.859375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def compute_last_word(s): answer = s[0] for c in s[1:]: if answer[0] <= c: answer = c + answer else: answer += c return answer def main(): t = int(input()) for i in range(1, t + 1): s = input() print("Case #{}: {}".format(i, compute_last_word(s))) if __name__ == '__main__': main()
2f828f4c61fe447df40adebbc493897a653aeaec
songzi00/python
/Pro/基础/02数据类型/运算符与表达式续集.py
1,395
4.1875
4
""" 位运算符:按位运算符是把数字看做二进制来进行计算 """ # % 按位与运算符 #相应的二进制个位数都为1 ,则该位的结果为1,否则为0 print(5 % 7) """ 5 = 101 7 = 111 101 """ # \ 按位或运算符 #两个二进制位有一个为1时,结果为1 print(5 | 7) """ 5 = 101 7 = 111 111 """ #按位异或运算符 #二进制的两位相异时,结果为1 print(5 ^ 7) """ 101 111 010 """ # ~ 按位取反运算符 #每个二进制数据位取反,1变0,0变1 print(~5) # >> 左移动运算符 # 各二进制位全部移动若干位,由>>右侧的数字来决定 print(-13 >> 2) #1101 往后挪两位,成为0011,转换为十进制就是3 """ 关系运算符与关系运算表达式 == != > < >= <= 关系运算表达式 格式: 表达式1 关系运算符 表达式2 功能:计算“表达式1”和“表达式2”的值 值:如果关系成立,整个关系运算表达式的值是真。否则为假 """ """ 逻辑运算符 1 逻辑与 and 逻辑与运算表达式: 表达式1 and 表达式2 值:如果“表达式1”的值为真,那么“表达式2”也为真,整体逻辑表达式的值为真。有一个为假,均为假 """ num1 = 1 num2 = 20 if num1 and num2: print("张柏芝") else: print("谢霆锋")
f91af3d3ae12fbadce8ebebf99b3ebc44d6b9c31
amirfarhat/utilities
/types-and-algorithms/python/priorityqueue.py
4,360
3.59375
4
import random from collections import deque from heap import MaxHeap, MinHeap # ------------------------------------------ QUEUES class PriortyQueueABC: def __init__(self, heap_constructor): self.heap = heap_constructor() # inited by subclasses def __len__(self): return len(self.heap) def insert(self, element): self.heap.insert(element) def insert_all(self, elements): for e in elements: self.insert(e) def best(self): return self.heap.best() def pop_best(self): return self.heap.pop_best() def set(self, old_element, new_element): while old_element in self.heap.array: index_of_old_element = self.heap.array.index(old_element) self.heap.set(index_of_old_element, new_element) def __repr__(self): return repr(self.heap) def __str__(self): return str(self.heap) class MaxPriorityQueue(PriortyQueueABC): def __init__(self): PriortyQueueABC.__init__(self, MaxHeap) class MinPriorityQueue(PriortyQueueABC): def __init__(self): PriortyQueueABC.__init__(self, MinHeap) # ------------------------------------------ TEST def test_max_priority_queue(): # test insert, len, best, pop_best max_pq = MaxPriorityQueue() assert 0 == len(max_pq) max_pq.insert(-13) assert 1 == len(max_pq) assert -13 == max_pq.best() assert -13 == max_pq.pop_best() assert 0 == len(max_pq) max_pq.insert(1) max_pq.insert(2) max_pq.insert(3) assert 3 == len(max_pq) assert 3 == max_pq.best() assert 3 == max_pq.pop_best() # should pop 3 assert 2 == len(max_pq) assert 2 == max_pq.best() assert 2 == max_pq.pop_best() # should pop 2 assert 1 == len(max_pq) assert 1 == max_pq.best() assert 1 == max_pq.pop_best() # should pop 1 assert 0 == len(max_pq) # test set max_pq.insert(-10) assert 1 == len(max_pq) assert -10 == max_pq.best() max_pq.set(-10, 5) assert 1 == len(max_pq) assert 5 == max_pq.best() # should now be 5 assert 5 == max_pq.pop_best() assert 0 == len(max_pq) max_pq.insert(7) max_pq.insert(7) assert 2 == len(max_pq) max_pq.set(7, 11) assert 2 == len(max_pq) assert 11 == max_pq.best() assert 11 == max_pq.pop_best() # should pop the first 11 assert 1 == len(max_pq) assert 11 == max_pq.best() assert 11 == max_pq.pop_best() # should pop the last 11 assert 0 == len(max_pq) # test insert_all times = 10 for _ in range(times): count = 1000 nums = [random.randint(-10**6, 10**6) for _ in range(count)] qnums = deque() qnums.extend(sorted(nums)) max_pq = MaxPriorityQueue() max_pq.insert_all(qnums) for i in range(count): assert count - i == len(max_pq) assert qnums.pop() == max_pq.pop_best() assert count - i - 1 == len(max_pq) def test_min_priority_queue(): # test insert, len, best, pop_best min_pq = MinPriorityQueue() assert 0 == len(min_pq) min_pq.insert(1111) assert 1 == len(min_pq) assert 1111 == min_pq.best() assert 1111 == min_pq.pop_best() # should pop 1111 assert 0 == len(min_pq) min_pq.insert(5) min_pq.insert(2) min_pq.insert(10) assert 3 == len(min_pq) assert 2 == min_pq.best() assert 2 == min_pq.pop_best() # should pop 2 assert 2 == len(min_pq) assert 5 == min_pq.best() assert 5 == min_pq.pop_best() # should pop 5 assert 1 == len(min_pq) assert 10 == min_pq.best() assert 10 == min_pq.pop_best() # should pop 10 assert 0 == len(min_pq) # test set min_pq.insert(-16) min_pq.insert(15) min_pq.insert(14) assert 3 == len(min_pq) assert -16 == min_pq.best() min_pq.set(-16, -32) assert 3 == len(min_pq) assert -32 == min_pq.pop_best() # should pop -32 assert 2 == len(min_pq) assert 14 == min_pq.pop_best() # should pop 14 assert 1 == len(min_pq) assert 15 == min_pq.pop_best() # should pop 15 assert 0 == len(min_pq) # test insert_all times = 10 for _ in range(times): count = 1000 nums = [random.randint(-10**6, 10**6) for _ in range(count)] qnums = deque() qnums.extend(sorted(nums, reverse = True)) max_pq = MinPriorityQueue() max_pq.insert_all(qnums) for i in range(count): assert count - i == len(max_pq) assert qnums.pop() == max_pq.pop_best() assert count - i - 1 == len(max_pq) # ------------------------------------------ MAIN def main(): test_max_priority_queue() print("Max priority queue tests pass") test_min_priority_queue() print("Min priority queue tests pass") if __name__ == '__main__': main()
c1a599ba1603559e781182fd9b26b8559204c9aa
AngheloAlf/CIAC-Conglomerado-de-ejercicios
/ejercicios/03 condiciones y ciclos/07 - diferencias entre strings/Code/p2.py
276
3.625
4
A=raw_input('Ingrese A: ') B=raw_input('Ingrese B: ') cont=0 interseccion='' diferencia='' while cont<len(A): if A[cont] in B: interseccion+=A[cont] else: diferencia+=A[cont] cont+=1 print 'interseccion:',interseccion print 'diferencia:',diferencia
1edd0394957f216c7abf8a3dd0b41521f26a44e0
samineup0710/geneses_pythonassignment3rd
/harmonicseries.py
310
4.09375
4
inp =int(input("Enter the number of terms: ")) """set counter to store sum""" s = 0 for i in range(1,inp+1): s =s+(1/i) if i!=0: """to print harmonic series""" print("1/{} + ".format(i), end = " ") """ to print harmonic series sum""" print("\nThe sum of series is",round(s,3))
3af00d208849f6cfb92b1d2c4ffe3a895ababa03
Harris-Logic/Main_Arithmetic_Classifier
/code/Neural_Network_MLPClassifier.py
824
3.5
4
# -*- coding: utf-8 -*- """ Created on Thu Dec 20 19:29:11 2018 @author: yan MLPClassifier¶ """ import pandas as pd import numpy as np import matplotlib.pyplot as plt work_dir = "new.csv" bankdata = pd.read_csv(work_dir) droplist = ['class'] X = bankdata.drop(droplist, axis=1) y = bankdata['class'] from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.30) from sklearn.neural_network import MLPClassifier clf = MLPClassifier() #activation='logistic',solver='sgd',learning_rate='constant',learning_rate_init=0.001 clf.fit(X_train,y_train) y_pred = clf.predict(X_test) from sklearn.metrics import classification_report, confusion_matrix print(confusion_matrix(y_test, y_pred)) print(classification_report(y_test, y_pred))
fc41b26a6bc1b0b28d1ced7151e92a64b9048463
NUS-Projects-Amir/CS3243-Project-1
/manhattan_Final.py
7,102
3.875
4
## CS3243 Introduction to Artificial Intelligence # Project 1: k-Puzzle import os import sys import math from collections import deque from Queue import PriorityQueue import time #Class used for Priority Queue class PriorityEntry(object): def __init__(self, priority, data): self.data = data self.priority = priority def __lt__(self, other): return self.priority < other.priority class Node(object): #State: list of lists representing the configuration of the puzzle #Parent: reference to the state before the current state #Action: what you did in the previous state to reach the current state. #Location: Position of zero in the puzzle as a tuple def __init__(self, state, parent=None, action=None, location=None): self.state = state self.parent = parent self.dimension = len(state) self.action = action self.location = location self.string = str(state) self.pathCost = 0 #Get Manhattan Distance def getMD(self): totalDist = 0 size = len(self.state) for i in range(0, size): for j in range(0, size): num = self.state[i][j] if num != 0: actualRow = (num - 1) // size actualCol = (num - 1) % size rowDiff = abs(actualRow - i) colDiff = abs(actualCol - j) currDist = colDiff + rowDiff totalDist += currDist return totalDist #Find the blank/0 in a given state def findBlank(self): for i in range(self.dimension): for j in range(self.dimension): if self.state[i][j] == 0: return (i, j) #List all the neigihbours of a given node def move(self, xsrc, ysrc, xdest, ydest): output = [row[:] for row in self.state] output[xsrc][ysrc], output[xdest][ydest] = output[xdest][ydest], output[xsrc][ysrc] return output #Create the children/neighbours of a given node def get_neighbours(self): new_states = [] #Get coordinate of the blank if (self.location == None): (x, y) = self.findBlank() else: (x, y) = self.location #Tries to add the down movement if(y-1 >= 0): new_states.append( Node(self.move(x, y-1, x, y), self, "RIGHT", (x, y-1))) #Tries to add the up movement if(y+1 < self.dimension): new_states.append( Node(self.move(x, y+1, x, y), self, "LEFT", (x, y+1))) #Tries to add the left movement if(x+1 < self.dimension): new_states.append( Node(self.move(x+1, y, x, y), self, "UP", (x+1, y))) #Tries to add the right movement if(x-1 >= 0): new_states.append( Node(self.move(x-1, y, x, y), self, "DOWN", (x-1, y))) return new_states class Puzzle(object): def __init__(self, init_state, goal_state): self.init_state = init_state self.goal_state = goal_state self.visited_states = [init_state] self.goalstringhash = hash(str(goal_state)) self.set=set() #Check if a puzzle is solvable def isSolvable(self, state): inversions = 0 singleDim = [] (y, x) = (0, 0) #Calculate the number of inversions in a given state for i in range(0, len(state)): for j in range(0, len(state)): singleDim.append(state[i][j]) if state[i][j] == 0: (y, x) = (i, j) for i in range(0, len(singleDim)-1): for j in range(i+1, len(singleDim)): if singleDim[j] and singleDim[i] and singleDim[i] > singleDim[j]: inversions += 1 #If there is an odd no. of states if len(state) % 2 == 1: #Solvable if there is an even no. of inversions if (inversions % 2) == 0: return True else: return False #If there is an even no. of states else: #Solvable if blank is (1) on even row counting from bottom and inversions is odd or (2) odd row counting from bottom and inversions is even if (y % 2 == 0 and inversions % 2 == 1) or \ (y % 2 == 1 and inversions % 2 == 0): return True else: return False #Returns the list of actions once the goal state is found def terminate(self, node): output = [] while(node.parent != None): output.insert(0, node.action) node = node.parent return output #A* w/ Manhattan Distance Implementation def solve(self): if self.isSolvable(Node(self.init_state).state) == False: return ["UNSOLVABLE"] source = Node(self.init_state) if (hash(source.string)==self.goalstringhash): return None frontier = PriorityQueue() frontier.put(PriorityEntry(source.getMD(),source)) while (not frontier.empty()): node = frontier.get().data for neighbour in node.get_neighbours(): neighbour.pathCost = node.pathCost + 1 if (neighbour.string not in self.set): self.set.add(neighbour.string) if (hash(neighbour.string)==self.goalstringhash): return self.terminate(neighbour) f = neighbour.pathCost + neighbour.getMD() frontier.put(PriorityEntry(f, neighbour)) return ["UNSOLVABLE"] if __name__ == "__main__": # do NOT modify below # argv[0] represents the name of the file that is being executed # argv[1] represents name of input file # argv[2] represents name of destination output file if len(sys.argv) != 3: raise ValueError("Wrong number of arguments!") try: f = open(sys.argv[1], 'r') except IOError: raise IOError("Input file not found!") lines = f.readlines() # n = num rows in input file n = len(lines) # max_num = n to the power of 2 - 1 max_num = n ** 2 - 1 # Instantiate a 2D list of size n x n init_state = [[0 for i in range(n)] for j in range(n)] goal_state = [[0 for i in range(n)] for j in range(n)] i,j = 0, 0 for line in lines: for number in line.split(" "): if number == '': continue value = int(number , base = 10) if 0 <= value <= max_num: init_state[i][j] = value j += 1 if j == n: i += 1 j = 0 for i in range(1, max_num + 1): goal_state[(i-1)//n][(i-1)%n] = i goal_state[n - 1][n - 1] = 0 puzzle = Puzzle(init_state, goal_state) ans = puzzle.solve() with open(sys.argv[2], 'a') as f: for answer in ans: f.write(answer+'\n')
c15b7a0751ace59db58187f070dde7c763148c21
frkngny/sorting_algorithms
/merge_sort.py
1,026
3.78125
4
import random import math index = int(input("index: ")) lower = int(input("lower bound: ")) upper = int(input("upper bound: ")) random.seed(1) A = list() for ind in range(index): value = random.randint(lower, upper) A.append(value) org_list = A.copy() print('original list: ', org_list) r = len(A) - 1 def merge(A, p, q, r): n1 = q-p+1 n2 = r-q L = [0] * n1 R = [0] * n2 L.append(999999999) R.append(999999999) for i in range(n1): L[i] = A[p+i] for j in range(n2): R[j] = A[q+j+1] i = 0 j = 0 for k in range(p, r+1): if L[i] < R[j]: A[k] = L[i] i += 1 else: A[k] = R[j] j += 1 if len(A) == (n1+n2): print("merge sorted list: ", A) def merge_sort(A, p, r): if p < r: q = math.floor((p+r)/2) merge_sort(A, p, q) merge_sort(A, q+1, r) merge(A, p, q, r) merge_sort(A, 0, r)
0cb49bd7d4f56804062db55acfe826f31a41398b
CnrLwlss/ScientificPython
/Resources/mtDNA.py
1,568
3.875
4
# string package is for analysing text # urllib is for downloading data from the web import string, urllib # Text file derived from http://www.mitomap.org/MITOMAP/HumanMitoSeq URL="http://www.staff.ncl.ac.uk/conor.lawless/ScientificPython/Resources/mtDNA.txt" textfile=urllib.urlopen(URL) lines=textfile.readlines() textfile.close() mtDNA=string.join(lines,sep="") # Let's get rid of the newline caracters mtDNA=string.replace(mtDNA,"\n","") # Count the total number of bases nBases=len(mtDNA) print "Number of bases", nBases # Count the number of each base in the genome print "Guanine",string.count(mtDNA,"G") print "Adenine", string.count(mtDNA,"A") print "Thymine", string.count(mtDNA,"T") print "Cytosine", string.count(mtDNA,"C") # Count the number of times base sequences appear print "GATTACA", string.count(mtDNA,"GATTACA") print "CAT", string.count(mtDNA,"CAT") print "TAG", string.count(mtDNA,"TAG") # mtDNA is circular, so to emulate that, we join 3 copies together bigmtDNA=mtDNA+mtDNA+mtDNA bRange=500 query="CAT" results=[] # At every base, we count a range of positions centred at that base # and count the number of times the query string appears for x in xrange(nBases,2*nBases): xmin=x-bRange xmax=x+bRange results.append(string.count(bigmtDNA[xmin:xmax],query)) # Generate a report about the frequency of occurance of the query string print "Lowest frequency", float(min(results))/(1+2*bRange) print "Highest frequency", float(max(results))/(1+2*bRange) print "Average overall frequency", float(string.count(mtDNA,query))/nBases
b493065983c05d742c2261d9c298cb4956e1d987
Julienpir/sb7-pgz
/sweeper/sweeper.py
5,002
3.765625
4
# To run this game type the command pgzrun mines.py into the terminal whilst in this directory import random import math # Create the top tiles COVER = Actor('cover') FLAG = Actor('flag') # Create a dictionary that stores all the possible bottom tile types TILES = {0: Actor('blank'), 1: Actor('one'), 2: Actor('two'), 3: Actor('three'), 4: Actor('four'), 5: Actor('five'), 6: Actor('six'), 7: Actor('seven'), 8: Actor('eight'), 'M': Actor('mine'),} # Game Setup CELL_SIZE = 30 # Basic game parameters ROWS = 15 COLS = 15 MINES = 15 # Build a list of lists def build_grid(rows, cols, filler): grid = [] for r in range(rows): row = [] for c in range(cols): row.append(filler) grid.append(row) return grid # Add mines at random locations def place_mines(grid, mines): # Attempt to place n mines, if one already placed # try again, but only so many attempts # loop will alwasy exit. max_tries = len(grid) * len(grid[0]) * 2 while mines > 0 and max_tries > 0 : r = random.randint(0, len(grid) - 1) c = random.randint(0, len(grid[0]) - 1) if grid[r][c] != 'M' : grid[r][c] = 'M' mines -= 1 else: max_tries -= 1 continue # return True if all placed. return mines == 0 # Build a list of neighbors, omitting ones off the edge def list_of_neighbors(grid, r, c): neighbors = [] for rn in range(max(0,r-1), min(r+2,len(grid))): for cn in range(max(0,c-1), min(c+2,len(grid[0]))): if rn != r or cn != c : # Ignore the center, append all others neighbors.append((rn,cn)) return neighbors # For each cell if it is not a mine count how many mines are nearby def count_mines(grid): # For each cell that has a mine, increment the cells around it. # so long as they are not mines them selves. for r in range(len(grid)): for c in range(len(grid[0])): if grid[r][c] == 'M': inc_neighbors(grid, r, c) return # Increment all mine neighbors def inc_neighbors(grid, r, c): # Inc all cells next to the mine for r, c in list_of_neighbors(grid, r, c) : if grid[r][c] != 'M': grid[r][c] += 1 return # Update the board. def draw(): offset = -CELL_SIZE/2 xpos, ypos = offset, offset for row in range(len(top_grid)): ypos += CELL_SIZE xpos = offset for col in range(len(top_grid[0])): xpos += CELL_SIZE if top_grid[row][col] == 1: # Its still hidden COVER.pos = xpos, ypos COVER.draw() elif top_grid[row][col] == 'F': # Its a flag FLAG.pos = xpos, ypos FLAG.draw() else: # top is gone, show the base layer gridpos = base_grid[row][col] TILES[gridpos].pos = xpos, ypos TILES[gridpos].draw() return def on_mouse_down(pos, button): # map x y pixel location to row/col in grid r = math.floor(pos[1]/CELL_SIZE) c = math.floor(pos[0]/CELL_SIZE) if button == mouse.LEFT: # Left click tests cell if top_grid[r][c] != 'F': top_grid[r][c] = 0 if base_grid[r][c] == 0: flood_fill(base_grid, (r, c)) elif base_grid[r][c] == 'M' : print("sunk your battleship") # PLay a sound of a sin skip else: # Right/Center click adds flag if top_grid[r][c] == 1: top_grid[r][c] = 'F' elif top_grid[r][c] == 'F': top_grid[r][c] = 1 def flood_fill(grid, seedpos): # Make a queue of cleared cells to look at begining with # the seed point, visit neighbors and add to the queue zcells = [seedpos] for r, c in zcells: neighbors = list_of_neighbors(grid, r, c) for nr, nc in neighbors: if grid[nr][nc] == 0 and top_grid[nr][nc] == 1 : # If this cell has no near mines and # and it is still hidden, then.. if top_grid[nr][nc] != 'F': # Not a flag, remove cover top_grid[nr][nc] = 0 if (nr, nc) not in zcells: zcells.append((nr, nc)) elif top_grid[nr][nc] != 'F': # Show the count on the edge the area cleared top_grid[nr][nc] = 0 return # Pygamezero will set the the screen based on the globals WIDTH and HEIGHT HEIGHT = ((ROWS * CELL_SIZE) + 1) WIDTH = ((COLS * CELL_SIZE) + 1) # top_grid holds blanks or flags top_grid = build_grid(ROWS, COLS, 1) # base_grid holds mines/numeber of adjacent/or blanks # it is buil in three steps. base_grid = build_grid(ROWS, COLS, 0) place_mines(base_grid, MINES) count_mines(base_grid)
a71f489e041a547da81de9ef63eedce9588e7903
zouxiaohang/PythonicCodeSnippets
/PythonicCodeSnippets/PythonicCodeSnippets.py
425
3.671875
4
# -*- coding:utf-8 -*- #(1)获得正负无穷的float值 '''当涉及 > 和 < 运算时, 所有数都比-inf大, 所有数都比+inf小''' maxFloat = float('inf') minFloat = float('-inf') #(2)交换两个变量值 a, b = b, a #(3)字符串列表的连接 strList = ["Python", "is", "good"] res = ' '.join(strList) #Python is good res = ''.join(strList) #Pythonisgood if __name__ == "__main__": print("main")
90028b87b0375e67eefdb56ba0dfa07c647e044a
lucas-jsvd/python_crash_course_2nd
/python_work/salvar_nun_predileto.py
242
3.75
4
import json filename = "num_predileto.txt" try: numero = int(input("Qual o seu numero predileto? ")) except ValueError: print("Você digitou um valor incorreto.") else: with open(filename, "w") as f: json.dump(numero, f)
da23bd49d98c131157ca0fc520434e87c131e103
pulse-net/sockx
/sockx/receiver/tcp_message_receiver.py
1,181
3.5625
4
""" Server receiver of the file """ import socket from ..constants import * class TCPMessageReceiver: def __init__(self, port=PORT): self.__port = port def receive_message(self): # Create the server socket # TCP socket s = socket.socket(family=socket.AF_INET, type=socket.SOCK_STREAM) # Bind the socket to our local address s.bind((SERVER_HOST, self.__port)) # Enabling our server to accept connections # 5 here is the number of unaccepted connections that # the system will allow before refusing new connections s.listen(5) print(f"[*] Listening as {SERVER_HOST}:{self.__port}") # Accept connection if there is any client_socket, address = s.accept() # If below code is executed, that means the sender is connected print(f"[+] {address} is connected.") # Receive the message # Receive using client socket, not server socket received = client_socket.recv(BUFFER_SIZE).decode() # Close the client socket client_socket.close() # Close the server socket s.close() return received
7149a80bc074b3af8c7bbe524bc02f7ddd6a976f
Joel-Quintyn/Python-Learning
/Name Counter Loop.py
346
3.796875
4
""" SYNOPSIS: This Program Was Rewritten From C On My Learning Journey Of Python, It Is A Name Counter Using While Loop. """ i = 0 while True: name = str(input("Enter A Name: ")) i = i + 1 x = int(input("\nPress 1 To Enter Another Name\nPress 0 To Finish\n")) if x == 0: break print("You Entered {} Names".format(i))
5572433bd8203c2f11b1b73c680261c53254ed75
hsrambo07/AES_pyaes
/AES.py
3,346
4.03125
4
################################## """AES algorithm using python AES package""" ################################## #before running this file run install the requirements import ast from Crypto.Cipher import AES from Crypto.Random import get_random_bytes #encryption function def encrypt(key, msg): iv = get_random_bytes(16) #getting random bytes cipher = AES.new(key, AES.MODE_CFB, iv) #generating key encryption ciphertext = cipher.encrypt(msg) #encrypting plain text with the key given in input return iv + ciphertext #returing random bytes and ciphertext #decryption fuction def decrypt(key, ciphertext): try: iv = ciphertext[:16] ciphertext = ciphertext[16:] cipher = AES.new(key, AES.MODE_CFB, iv) smsg = cipher.decrypt(ciphertext) return smsg.decode("utf-8") except: print("=" * 60) return print('!!!!!Stopping Decryption process , maybe you entered a wrong key!!!!!') #initialising the main function if __name__ == "__main__": #Enter choice for encryption decryption as e or d ed = input("(e)ncrypt or (d)ecrypt: ") #ENCRYPTION if ed == "e": print("=" * 60) key = input("16 digit key: ") #enter your 16 digit key print("=" * 60) Nk=2 #if your key is smaller than 16 then it will fill 0s after that if len(key) < Nk * 8: print ("Key too short. Filling with \'0\'," "so the length is exactly {0} digits.".format(Nk * 8)) key += "0" * (Nk * 8 - len(key)) #input file name print("="*60) file_plain = input("Enter file name to decrypt: ") with open(file_plain) as file: msg = file.read() msg = encrypt( key, msg) # returns the encrpyt function #print('Your Plain Text: ',msg) f_plain = file_plain.split(".") #splits ur file name encrypted_file = (f_plain[0]) + '.' + f_plain[-1] + '.aes' #adding .aes extension to make it unreadable new_file = open( encrypted_file, mode = "wb") # creating new file with aes encrypted extension new_file.write(msg) new_file.close() print("=" * 60) print("Your file has been saved as: " , encrypted_file) #creates a new encrypted file in ur directory #DECRYPTION elif ed == "d": print("=" * 60) key = input("16 digit key: ") print("=" * 60) Nk=2 if len(key) < Nk * 8: print ("Key too short. Filling with \'0\'," "so the length is exactly {0} digits.".format(Nk * 8)) key += "0" * (Nk * 8 - len(key)) print("=" * 60) file_encrpyted = input("Enter file name to decrypt: ") with open(file_encrpyted,"rb") as fp: smsg = fp.read() msg=(decrypt(key,(smsg))) #send values to decrypt function f_encrypted = file_encrpyted.split(".") #splits ur file name decrypted_file = (f_encrypted[0]) + '.txt' #adding .aes extension to make it unreadable print("=" * 60) new_file=open("sample.txt",mode="w") new_file.write(msg) new_file.close() print("=" * 60) print("Your file has been saved as: " + decrypted_file) #Thank you
7df5ea92150bce1fe70015d86d30c3f6e7135e33
Hammad214508/Quarantine-Coding
/30-Day-LeetCoding-Challenge/April/Week3/21-LeftColWithAOne.py
2,465
4.21875
4
""" (This problem is an interactive problem.) A binary matrix means that all elements are 0 or 1. For each individual row of the matrix, this row is sorted in non-decreasing order. Given a row-sorted binary matrix binaryMatrix, return leftmost column index(0-indexed) with at least a 1 in it. If such index doesn't exist, return -1. You can't access the Binary Matrix directly. You may only access the matrix using a BinaryMatrix interface: BinaryMatrix.get(x, y) returns the element of the matrix at index (x, y) (0-indexed). BinaryMatrix.dimensions() returns a list of 2 elements [n, m], which means the matrix is n * m. Submissions making more than 1000 calls to BinaryMatrix.get will be judged Wrong Answer. Also, any solutions that attempt to circumvent the judge will result in disqualification. For custom testing purposes you're given the binary matrix mat as input in the following four examples. You will not have access the binary matrix directly. Example 1: Input: mat = [[0,0], [1,1]] Output: 0 Example 2: Input: mat = [[0,0], [0,1]] Output: 1 Example 3: Input: mat = [[0,0], [0,0]] Output: -1 Example 4: Input: mat = [[0,0,0,1], [0,0,1,1], [0,1,1,1]] Output: 1 """ """ This is BinaryMatrix's API interface. You should not implement it, or speculate about its implementation """ class BinaryMatrix(object): def __init__(self, matrix): self.matrix = matrix def get(self, x: int, y: int) -> int: return self.matrix[x][y] def dimensions(self) -> [int]: n = len(self.matrix) m = len(self.matrix[0]) return [n, m] # Imagine there is a pointer p(x, y) starting from top right corner. # p can only move left or down. If the value at p is 0, move down. # If the value at p is 1, move left. Try to figure out the correctness # and time complexity of this algorithm class Solution: def leftMostColumnWithOne(self, binaryMatrix: BinaryMatrix) -> int: rows, columns = binaryMatrix.dimensions() rows -= 1 columns -= 1 row = 0 col = columns while(row <= rows and col >= 0): if binaryMatrix.get(row, col) == 1: col -= 1 else: row += 1 if col != columns: return col+1 return -1 mat = [[0,0],[0,0]] matrix = BinaryMatrix(mat) solution = Solution() print(solution.leftMostColumnWithOne(matrix))
cece3fe8d0a63e9809dec27d423b33292e8750ae
Caqtus/pythonSelfExercise
/oddoreven.py
335
4.1875
4
def oddoreven(): myNumber = int(input('enter number and I will tel you if its odd or even')) if (myNumber % 2 == 0): print('Your number is even') print(f'{myNumber} % 2 - remainder is {myNumber % 2}') else: print('Your number is odd') print(f'{myNumber} % 2 - remainder is {myNumber % 2}')
3475914f56b952907a1acd5447a8966c855bae13
EugenenZhou/leetcode
/nowcoder/jzoffer/IsPopOrder.py
1,160
3.859375
4
# 栈的压入弹出顺序 # 输入两个整数序列,第一个序列表示栈的压入顺序, # 请判断第二个序列是否可能为该栈的弹出顺序。 # 假设压入栈的所有数字均不相等。 # 例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列, # 但4,3,5,1,2就不可能是该压栈序列的弹出序列。 # (注意:这两个序列的长度是相等的) ###################################################################### # -*- coding:utf-8 -*- class Solution: def IsPopOrder(self, pushV, popV): temp_stack = [] i = 0 while pushV: if not temp_stack or popV[i] != temp_stack[-1]: temp_stack.append(pushV.pop(0)) while temp_stack and popV[i] == temp_stack[-1]: temp_stack.pop() i = i + 1 if temp_stack: return False else: return True # write code here ###################################################################### push = [1,2,3,4,5] pop = [5,4,3,2,1] s = Solution() res = s.IsPopOrder(push,pop) print(res)
0c7983a45eb1887b13a33a2b0f6c79db96e48f9c
haru-256/ExpertPython3_Source
/chapter4/vector_as_dataclass.py
520
3.875
4
from dataclasses import dataclass @dataclass class Vector: x: int y: int def __add__(self, other): """+演算子を使ったベクトルの足し算""" return Vector( self.x + other.x, self.y + other.y, ) def __sub__(self, other): """-演算子を使ったベクトルの引き算""" return Vector( self.x - other.x, self.y - other.y, ) @dataclass(frozen=True) class FrozenVector: x: int y: int
087c3b3497da3d3098b97baa625dc4680e879609
arjun1321/BasicPython
/PythonModules/TurtleModule.py
428
3.6875
4
import turtle import time # Square # t = turtle.Pen() # t.forward(50) # t.left(90) # t.forward(50) # t.left(90) # t.forward(50) # t.left(90) # t.forward(50) # Octagon # t = turtle.Pen() # for i in range(0,8): # t.forward(50) # t.left(45) # Star # t = turtle.Pen() # for i in range(1,38): # t.forward(100) # t.left(175) t = turtle.Pen() for i in range (1,20): t.forward(100) t.left(95) time.sleep(3)
3bc96eed0104c3d501baa7fb7ef0a76f049461d1
daanjderuiter/oop_TN
/templates/solarsystem.py
1,793
3.734375
4
from math import sqrt import matplotlib.pyplot as plt from scipy.constants import G, au from vector import Vector class Universe: def __init__(self, dt=60*60*24): """Initialises an empty universe with default time steps of a day""" pass def add_body(self, planet): """Add a body to the universe""" pass def forces(self): """Computes the forces on all planets, and returns these forces as a collection of Vectors in a suitable format""" pass def update(self): """Updates positions and velocities to the next time point""" pass class Planet: def __init__(self, name, mass, position, velocity): self.name = name self.mass = mass self.position = Vector(*position) self.velocity = Vector(*velocity) def __repr__(self): return f'Name: {self.name}\nMass: {self.mass} kg\nPosition: ' + \ f'{tuple(self.position)}\nVelocity: {tuple(self.velocity)}' # Demo M_sun = 2e30 M_earth = 5.972e24 M_mars = 6.39e23 universe = Universe() earth = Planet('Earth', M_earth, (au, 0, 0), (0, 29780, 0)) sun = Planet('Sun', M_sun, (0, 0, 0), (0, 0, 0)) mars = Planet('Mars', M_mars, (1.524*au, 0, 0), (0, 24131, 0)) universe.add_body(earth) universe.add_body(sun) universe.add_body(mars) r_sun = [] r_earth = [] r_mars = [] for _ in range(700): r_sun.append(sun.position) r_earth.append(earth.position) r_mars.append(mars.position) universe.update() plt.figure() plt.plot([r.x for r in r_sun], [r.y for r in r_sun], 'o', label='Sun trajectory') plt.plot([r.x for r in r_earth], [r.y for r in r_earth], label='Earth trajectory') plt.plot([r.x for r in r_mars], [r.y for r in r_mars], label='Mars trajectory') plt.legend() plt.show()
fbb782563da941f0321d1101a2265e1c01404909
cristianlepore/python_exercises
/Lesson3/decimalToBinary.py
422
3.578125
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 8 12:09:59 2016 @author: ericgrimson """ num = 19 startingNum = num if num < 0: isNeg = True num = abs(num) else: isNeg = False result = '' if num == 0: result = '0' while num > 0: result = str(num % 2) + result num = num // 2 if isNeg: result = '-' + result print("The binary representation of", end=' ') print(startingNum, "is: ", result)
01549c2259aab221243a87c2b86a34d62f943a57
LArchCS/Handwritten-Equation-Recognition-Tensorflow
/processImage/testEqual.py
756
3.65625
4
import os import cv2 from PIL import Image ''' This class is used to seperate single symbol with equation according to its file name length ''' # This class is used to seperate single and equation from the annotated data class TestEqual: def getEqual(self): dataroot = os.getcwd() + "/data/annotated_train/" saveroot = os.getcwd() + "/data/train/" for f in os.listdir(dataroot): if f.endswith(".png"): ins = f.split('.')[0].split('_') if len(ins) > 3: # exclude the equation png only individual symbol im = Image.open(dataroot + f) im.save(saveroot + f) def main(): x = TestEqual() x.getEqual() if __name__ == "__main__": main()
ce3a509e547ece177ed7686ba38d574bac03f622
kolyaskink/python
/search_in_text/search_in_text.py
3,249
3.765625
4
import argparse import re class MyException(Exception): pass def get_config(): """ Parse config file and save data as a dictionary""" try: with open('config.txt') as f: settings = {} for line in f: line = line.strip() settings[(line.split('=')[0])] = (line.split('=')[1]) except IOError: raise MyException("Config file not found") return settings def get_params(): """ Take setting from the CLI parameters. Do the same what get_config does""" parser = argparse.ArgumentParser(description='Script to generate a CF template for Studios Jenkins.') parser.add_argument('--file_path', '-f', action='store', required=True, help="name of the file to search in") parser.add_argument('--case_sensitivity', '-c', action='store', required=False, help="Case sensitive search. Could be 'yes' or 'no'", default='no') parser.add_argument('--advanced_search', '-a', action='store', required=False, help="Split search pattern between lines", default='no') parser.add_argument('--search_pattern', '-s', action='store', required=True, help="String to search for") args = parser.parse_args() settings = {'file_path': args.file_path, 'case_sensitivity': args.case_sensitivity, 'search_pattern': args.search_pattern, 'advanced_search': args.advanced_search} return settings def parse_file_advanced(get_params): try: with open(get_params['file_path']) as f: s = "" for line in f: s = s + line.strip() for m in re.finditer(get_params['search_pattern'],s): print("'{0}':{1}-{2}".format( m.group(), m.start(), m.end() )) except IOError: raise MyException("Source file not found") def parse_file_simple(get_params): """ Load a file with text, verify it and save as a string Case non-sensitive """ try: with open(get_params['file_path']) as f: i = 0 for line in f: line = line.strip() if get_params['case_sensitivity'].lower() == 'no': if line.lower() == get_params['search_pattern'].lower(): print(line) i += 1 elif get_params['case_sensitivity'].lower() == 'yes': if line == get_params['search_pattern']: print(line) i += 1 else: print("case_sensitivity value could be yes or no") if i == 0: print("No match found") except IOError: raise MyException("Source file not found") except KeyError: raise MyException("Can't parse config file") def main(get_params): """ Find a string inside a file. Show the match""" if get_params['advanced_search'].lower() == 'yes': parse_file_advanced(get_params) elif get_params['advanced_search'].lower() == 'no': parse_file_simple(get_params) main(get_params())
ab0c189a14358c9a7e009b57402bc3ed30bcaf42
ganeshgirase/expression_parser
/lib/base_formatter.py
630
3.53125
4
#! /usr/bin/python # # Base class for all formatter. # class Formatter(object): # Base class for all formatter def __init__(self): # Initialization method # This method can be overriden to set up the value of # output and output_attributes instance variable pass @property def output(self): """ Get output value Args: None Returns: Returns class instance output variable """ return self._output @output.setter def output(self, value): """ Set output value Args: value: Value which is going to be associated with output """ self._output = value
a91721403c89dd28c110f88925b82278a4cb9ba2
LeiShi/Synthetic-Diagnostics-Platform
/src/python3/sdp/math/interpolation.py
8,629
4.3125
4
"""This module contains some useful interpolation methods """ import numpy as np from scipy.interpolate import BarycentricInterpolator class InterpolationError(Exception): def __init__(self,value): self.value = value def __str__(self): return repr(self.value) class OutofBoundError(InterpolationError, ValueError): def __init__(self, value): self.value = value def __str__(self): return repr(self.value) def linear_3d_3point(X,Y,Z,x,y,tol = 1e-8): """3D interpolation method Linearly interpolate the value of z for given x,y. By using 3 points data, the unknown value of z is assumed on the same plane. The method used here is the cross product method. From P(x1,y1,z1),Q(x2,y2,z2),and R(x3,y3,z3), construct 2 vectors on the plane, PQ(x2-x1,y2-y1,z2-z1) and PR(x3-x1,y3-y1,z3-z1). Then do the cross product, PQ*PR = N. This gives the normal vector of the plane. The plane's equation is then 'N dot X = d', where X is an arbitary point and d to be determined. d can be easily gotten from any one of the given points, say P. d = N dot P. Then the equation of the plane is found. The equation can be written as 'ax+by+cz = d', then z can be solved for given x and y. Arguments: x1,y1,z1: coordinates of the first point x2,y2,z2: the second point x3,y3,z3: the third point x,y: the x,y coordinates for the wanted return value: interpolated z value on given (x,y) """ x1,x2,x3 = X[0],X[1],X[2] y1,y2,y3 = Y[0],Y[1],Y[2] z0 = np.max(Z) z1,z2,z3 = Z[0]/z0,Z[1]/z0,Z[2]/z0 Nx = (y2-y1)*(z3-z1)-(y3-y1)*(z2-z1) Ny = (x3-x1)*(z2-z1)-(x2-x1)*(z3-z1) Nz = (x2-x1)*(y3-y1)-(x3-x1)*(y2-y1) z_base = (x2-x1)*(y3-y1) print(Nx,Ny,Nz,z_base) if(np.absolute(Nz/z_base) <= tol ): raise InterpolationError('3 points interpolation failed: given points are on a plane vertical to XY plane, no z value being able to interpolated.') d = Nx*x1 + Ny*y1 + Nz*z1 print(d, d-Nx*x-Ny*y) return (d - Nx*x - Ny*y)/float(Nz)*z0 def trilinear_interp(X,Y,Z,F,x, fill_value=0.0): """ Trilinear interpolation (3D) for 1 point on a cubic mesh See Wikipedia for a better description than the following: First choose a direction and interpolate all the corners along this direction (so 8pts -> 4pts) at the value of the wanted point. Choose a second direction and interpolate the 4pts at the wanted point (4pts -> 2pts). Finish with the interpolation along the last line Arguments: X -- 1D array containing the X coordinate of F Y -- 1D array containing the Y coordinate of F Z -- 1D array containing the Z coordinate of F F -- 3D array containing the data x -- position (3D) where the interpolation is wanted return value: interpolated z value on given (x,y) """ raise NameError('Does not work, should use RegularGridInterpolator') if len(x.shape) == 1: # if outside the box, put the value to fill_value if x[0] < X[0] or x[1] < Y[0] or x[2] < Z[0]\ or x[0] > X[-1] or x[1] > Y[-1] or x[2] > Z[-1]: return fill_value else: # First find the x,y,z coordinate of the corner of the cube indx = np.where(X < x[0])[0].max() indy = np.where(Y < x[1])[0].max() indz = np.where(Z < x[2])[0].max() # relative coordinates rx = (x[0]-X[indx])/(X[indx+1]-X[indx]) ry = (x[1]-Y[indy])/(Y[indy+1]-Y[indy]) rz = (x[2]-Z[indz])/(Z[indz+1]-Z[indz]) # compute the first linear interpolation temp = 1-rx c00 = F[indx,indy,indz]*temp + F[indx+1,indy,indz]*rx c10 = F[indx,indy+1,indz]*temp + F[indx+1,indy+1,indz]*rx c01 = F[indx,indy,indz+1]*temp + F[indx+1,indy,indz+1]*rx c11 = F[indx,indy+1,indz+1]*temp + F[indx+1,indy+1,indz+1]*rx # compute the second linear interpolation temp = 1-ry c0 = c00*temp + c10*ry c1 = c01*temp + c11*ry # compute the last linear interpolation return c0*(1-rz) + c1*rz elif len(x.shape) == 2: """this part is the same that before but with a mesh (not only one point). the comments will be only for trick due to the shape of the positions abd not on the method (look the first part for them) """ G = np.zeros(len(x[:,0])) # First find the x,y,z coordinate of the corner of the cube ind = ~((x[:,0] < X[0]) | (x[:,1] < Y[0]) | (x[:,2] < Z[0]) | (x[:,0] > X[-1]) | (x[:,1] > Y[-1]) | (x[:,2] > Z[-1])) G[~ind] = fill_value indx = np.where(X <= x[ind,0])[0].max() indy = np.where(Y <= x[ind,1])[0].max() indz = np.where(Z <= x[ind,2])[0].max() # relative coordinates rx = (x[ind,0]-X[indx])/(X[indx+1]-X[indx]) ry = (x[ind,1]-Y[indy])/(Y[indy+1]-Y[indy]) rz = (x[ind,2]-Z[indz])/(Z[indz+1]-Z[indz]) # compute the first linear interpolation temp = 1-rx c00 = F[indx,indy,indz]*temp + F[indx+1,indy,indz]*rx c10 = F[indx,indy+1,indz]*temp + F[indx+1,indy+1,indz]*rx c01 = F[indx,indy,indz+1]*temp + F[indx+1,indy,indz+1]*rx c11 = F[indx,indy+1,indz+1]*temp + F[indx+1,indy+1,indz+1]*rx # compute the second linear interpolation temp = 1-ry c0 = c00*temp + c10*ry c1 = c01*temp + c11*ry # compute the last linear interpolation G[ind] = c0*(1-rz) + c1*rz return G else: raise NameError('Error: wrong shape of the position to interpolate') # BarycentricInterpolator with boundary check class BoundaryWarnBarycentricInterpolator(BarycentricInterpolator): """Barycentric Interpolator with Boundary Check. Based on :py:class:`scipy.interpolate.BarycentricInterpolator`. The boundary is set as minimun x and maximum x. If called with x outside the available range, a OutofBoundError will be raised. __init__(xi, yi=None, axis=0, bound_error=True, fill_value=0) :param xi: x coordinates for interpolation :type xi: array of float :param yi: Optional, y values on each xi location. If not given, need to be provided later using :py:method`set_yi` method. :type yi: array of float :param int axis: the axis of yi along which the interpolator will be created. :param bool bound_error: If True, out of bound interpolation will result a OutofBoundError. Otherwise fill_value will be used . Default to be True :param float fill_value: If bound_error is False, out of bound values will be automatically filled with fill_value. see :py:class:`scipy.interpolate.BarycentricInterpolator` for further information. """ def __init__(self, xi, yi=None, axis=0, bound_error=True, fill_value=0): self._xmin = np.min(xi) self._xmax = np.max(xi) self._bound_error = bound_error self._fill_value = fill_value super(BoundaryWarnBarycentricInterpolator, self).__init__(xi, yi, axis) def __call__(self, x): if (self._bound_error): if np.any(x < self._xmin) or np.any(x > self._xmax): raise OutofBoundError('x out of bound! xmin: {}, xmax: {}'.\ format(self._xmin, self._xmax)) return super(BoundaryWarnBarycentricInterpolator, self).__call__(x) else: outbound_idx = np.logical_or(x < self._xmin, x > self._xmax) result = np.empty_like(x) result[~outbound_idx] = super(BoundaryWarnBarycentricInterpolator, self).__call__(x[~outbound_idx]) result[outbound_idx] = self._fill_value return result def add_xi(self, xi, yi=None): super(BoundaryWarnBarycentricInterpolator, self).add_xi(xi, yi) self._xmin = np.min( [np.min(xi), self._xmin] ) self._xmax = np.max( [np.max(xi), self._xmax] ) def set_yi(self, yi, axis=None): yi = np.array(yi) if not self._bound_error: assert yi.ndim == 1 super(BoundaryWarnBarycentricInterpolator, self).set_yi(yi, axis)
4ff22f39ef7273ec95649cf2036c31f48cdb2f5e
danvb112/introducaoPython
/revisãoDeTudo/exercicio 3.12.py
315
3.8125
4
print("Saiba quanto tempo sua viagem de carro irá durar!!") distancia = int(input(" Digite a distancia em Km que você irá percorrer: ")) velocidadeMedia = int(input("Digite a que velocidade média em Km/h que você irá percorrer: ")) tempo = distancia / velocidadeMedia print ("Seu tempo em horas é: " , tempo)
d6396e1980649d9fcfbe3e5a50f3fb6f37016731
aditya-sengupta/misc
/ProjectEuler/Q19.py
1,067
4.21875
4
"""You are given the following information, but you may prefer to do some research for yourself. 1 Jan 1900 was a Monday. Thirty days has September, April, June and November. All the rest have thirty-one, Saving February alone, Which has twenty-eight, rain or shine. And on leap years, twenty-nine. A leap year occurs on any year evenly divisible by 4, but not on a century unless it is divisible by 400. How many Sundays fell on the first of the month during the twentieth century (1 Jan 1901 to 31 Dec 2000)?""" def weekday_shift(month, year): if(month == 2): if(year%400 == 0 or (year%4 == 0 and year%100 != 0)): return 1 return 0 if(month in [4, 6, 9, 11]): return 2 return 3 def first_of_month(month, year): if(month == 2 and year == 1983): return 2 elif(month == 1 and year == 1900): return 1 elif(month > 1): return (weekday_shift(month - 1, year) + first_of_month(month - 1, year))%7 else: return (weekday_shift(12, year - 1) + first_of_month(12, year - 1))%7
bc8cf4f3f0c6d2a65eb8534c6b26e9c7d1196826
pkrucz00/ASD
/Gotowce/slowniki/spantree.py
2,768
3.53125
4
from math import inf class Node: def __init__(self, val, span): self.val = val self.span = span #(a,b) - przedzial, za ktory odpowiada dany wezel self.intervals = [] #przedzialy zawarte w wezle self.left = None self.right = None def spanTreeInit(data): def spanTreeAux(l, r, data): if len(data) == 0: return Node(None, (l,r)) mid = len(data)//2 root = Node(data[mid], (l,r)) root.left = spanTreeAux(l, root.val, data[:mid]) root.right = spanTreeAux(root.val, r, data[mid+1:]) return root return spanTreeAux(-inf, inf, data) def spanTreeInsert(root, interval): def spanTreeInsertAux(root, interval, aux): if root.span == aux: root.intervals.append(interval) return root else: a,b = root.span i,j= aux if a <= i and j <= root.val: root.left = spanTreeInsertAux(root.left, interval, (i, j)) elif root.val <= i and j <= b: root.right = spanTreeInsertAux(root.right, interval, (i,j)) else: root.left = spanTreeInsertAux(root.left, interval, (i, root.val)) root.right = spanTreeInsertAux(root.right, interval, (root.val, j)) return root return spanTreeInsertAux(root, interval, interval) def printIntervals(root, val): if root.val is None: return root.intervals result = root.intervals[:] if val <= root.val: tmp = printIntervals(root.left, val) if val >= root.val: tmp = printIntervals(root.right, val) for inter in tmp: result.append(inter) return result def removeInterval(root, interval): if root is not None: if interval in root.intervals: root.intervals.remove(interval) if root.val is None: return root i,j = interval a,b = root.span if a <= i and j <= root.val: root.left = removeInterval(root.left, interval) elif root.val <= i and j <= b: root.right = removeInterval(root.right, interval) else: root.left = removeInterval(root.left, interval) root.right = removeInterval(root.right, interval) return root def prepareData(data): n = len(data) aux = [data[i][j] for i in range(n) for j in range(2)] aux.sort() result = [aux[0]] for i in range(1, 2*n): if aux[i] != aux[i-1]: result.append(aux[i]) return result data = [(0, 10), (5, 20), (7, 12), (10, 15)] preparedData = prepareData(data) T = spanTreeInit(preparedData) for interval in data: T = spanTreeInsert(T, interval) print(printIntervals(T, 10))
7d610474f8178f1b3fee7e004c07c2707f9eb328
MrSyee/algorithm_practice
/math/can_you_eat_your_favorite_candy_on_your_favorite_day.py
4,500
3.90625
4
""" 1744. Can You Eat Your Favorite Candy on Your Favorite Day? (Medium) https://leetcode.com/problems/can-you-eat-your-favorite-candy-on-your-favorite-day/ You are given a (0-indexed) array of positive integers candiesCount where candiesCount[i] represents the number of candies of the ith type you have. You are also given a 2D array queries where queries[i] = [favoriteTypei, favoriteDayi, dailyCapi]. You play a game with the following rules: You start eating candies on day 0. You cannot eat any candy of type i unless you have eaten all candies of type i - 1. You must eat at least one candy per day until you have eaten all the candies. Construct a boolean array answer such that answer.length == queries.length and answer[i] is true if you can eat a candy of type favoriteTypei on day favoriteDayi without eating more than dailyCapi candies on any day, and false otherwise. Note that you can eat different types of candy on the same day, provided that you follow rule 2. Return the constructed array answer. Example 1: Input: candiesCount = [7,4,5,3,8], queries = [[0,2,2],[4,2,4],[2,13,1000000000]] Output: [true,false,true] Explanation: 1- If you eat 2 candies (type 0) on day 0 and 2 candies (type 0) on day 1, you will eat a candy of type 0 on day 2. 2- You can eat at most 4 candies each day. If you eat 4 candies every day, you will eat 4 candies (type 0) on day 0 and 4 candies (type 0 and type 1) on day 1. On day 2, you can only eat 4 candies (type 1 and type 2), so you cannot eat a candy of type 4 on day 2. 3- If you eat 1 candy each day, you will eat a candy of type 2 on day 13. Example 2: Input: candiesCount = [5,2,6,4,1], queries = [[3,1,2],[4,10,3],[3,10,100],[4,100,30],[1,3,1]] Output: [false,true,true,false,false] Constraints: 1 <= candiesCount.length <= 10^5 1 <= candiesCount[i] <= 10^5 1 <= queries.length <= 10^5 queries[i].length == 3 0 <= favoriteTypei < candiesCount.length 0 <= favoriteDayi <= 10^9 1 <= dailyCapi <= 10^9 """ # 하루에 먹을수 있는 개수를 한 가지 수로 고정했을 때만 구함 class Solution: def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]: ans = [] for query in queries: # O(queries) target_type, target_day, day_cap = query n_target = candiesCount[target_type] n_candies = sum(candiesCount[:target_type]) cap = 1 is_eat = False while cap <= day_cap: # O(queries * day_cap) n_eating = n_candies - ((target_day + 1) * cap) if n_eating > 0 and n_eating <= n_target: is_eat = True break cap += 1 ans.append(is_eat) return ans # 힌트 봄. 가능한 날짜의 최대 최소를 구하여 그 사이에 들어올 경우 통과. but, timelimit.. class Solution: def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]: ans = [] for target_type, target_day, day_cap in queries: # O(queries) n_target = candiesCount[target_type] n_smaller_candies = sum(candiesCount[:target_type]) # O(target_type) is_eat = False # eariest eariest_day = n_smaller_candies // day_cap # latest latest_day = n_smaller_candies + n_target if eariest_day <= target_day < latest_day: # latest day 등호 안됨 is_eat = True ans.append(is_eat) return ans # Discuss 봄. 누적합을 미리 계산해 두고 사용한다. Discuss에서는 accumulate 이용. class Solution: def canEat(self, candiesCount: List[int], queries: List[List[int]]) -> List[bool]: ans = [] accum = 0 accum_candies = [] for n_candies in candiesCount: # O(candiesCount) accum += n_candies accum_candies.append(accum) for target_type, target_day, day_cap in queries: # O(queries) is_eat = False # eariest if target_type > 0: eariest_day = accum_candies[target_type - 1] // day_cap else: eariest_day = 0 # latest latest_day = accum_candies[target_type] if eariest_day <= target_day < latest_day: is_eat = True ans.append(is_eat) return ans
97020f981f868efceb8004a0f470bb1bf72e0b60
santhoshkumar22101999/santhoshkumar
/factorial.py
82
3.671875
4
n=int(input("enter a number")) i=1 while(n>0): i=i*n n=n-1 print(i)
4aa227bf657f4b9d9befcca7558e26bf128e55c8
leogtzr/python_crash_course_book_code_snippets
/default_values1.py
540
3.78125
4
def describe_pet(pet_name, animal_type='dog'): """Display information about a pet.""" print(f"\nI have a {animal_type}.") print(f"My {animal_type}'s name is {pet_name.title()}.") def myf(name='Leo'): print(f"Hello, {name.title()}") describe_pet(pet_name='Willie') myf('Leonardo') myf() # NOTE # When you use default values, any parameter with a default value needs to be listed after all the # parameters that don’t have default values. This allows Python to continue interpreting positional arguments correctly.
22be17f5faf23cf6e1c8ef64d3e2f02e76719e82
chinmay232000/learning-python
/sallysshipping.py
1,028
3.84375
4
def cost_of_ground_shipping(weight): if weight>10: print((weight * 4.75 ) + 20) elif weight > 6: print((weight * 4.00 ) + 20) elif weight > 2: print((weight * 3.00 ) + 20) elif weight<=2: print((weight * 1.50 ) + 20) cost_of_premium_ground_shipping = 125 def cost_of_drone_shipping(weight): if weight > 10: print(weight * 14.25 ) elif weight > 6: print(weight * 12.00 ) elif weight > 2: print(weight * 9.00 ) elif weight<=2: print(weight * 4.50 ) def cheapest_shipping(weight): ground = cost_of_ground_shipping(weight) drone = cost_of_drone_shipping(weight) premium = cost_of_premium_ground_shipping if ground < premium and ground < drone: method = "standard ground" cost = ground elif premium < ground and premium < drone: method = "premium" cost = premium else: method = "drone" cost = drone print( "the cheapest option available is $%.2f with %s shipping." % (cost, method) ) cheapest_shipping(4.8) cheapest_shipping(41.5)
eb03dbf82808d2861f2b629bad1e3d45fe676fe0
shiwanibiradar/10days_python
/day2/while/average.py
251
4.40625
4
#Take 10 integers from keyboard using loop #and print their average value on the screen. print("Enter the 10 numbers for addition") i=10 add =0 while i > 0: a=float(input("")) add = add+a i = i-1 print('addition of your 10 numbers are',add/10)
d3234f95398e6e9582e7a2b0ceb320d8f0f62fe9
srikii/git_repocommits
/hw4a.py
1,269
3.53125
4
"""program to read the number od repositories in a given username and also the number of commits for each repository author: srikanth""" import urllib.request import urllib.parse import urllib.error import json import requests import ssl def git_repocommits(n): git_name=n git_url= "https://api.github.com/users/{}/repos".format(git_name) uh = urllib.request.urlopen(git_url) data = uh.read().decode() try: js = json.loads(data) except: js = None l1=list() for i in js: for key, val in i.items(): if key == "name": l1.append(val) l2=list() for i in l1: repo_url="https://api.github.com/repos/{}/{}/commits".format(git_name, i) uh2 = urllib.request.urlopen(repo_url) data2 = uh2.read().decode() try: js2 = json.loads(data2) except: js2 = None commits=len(js2) l2.append(commits) for i in range(len(l1)): print("Repo:", l1[i], "Number of commits: ", l2[i]) return(l1,l2) def main(): n=input("enter the GitHub user name: \n") g=git_repocommits(n) if __name__ == '__main__': main()
ea78927c476246b086cc17e642fa3e0f61819964
isw4/IntroSoftwareEng08_GoogleCalPart2
/meetings/timeslot.py
9,384
3.890625
4
""" Class to represent timeslots and perform some calculations """ import arrow, calc ASCENDING = 1 DESCENDING = -1 class TimeSlot: def __init__(self, contains, begin_datetime, end_datetime): """ TimeSlot object, used to represent time slots. Contains the following fields: contains: a list of dictionaries. Each dictionary contains information about the events that make up this timeslot. Fields of the dictionary are: summary: Description of the event begin_datetime: see below end_datetime: see below begin_datetime: isoformatted timedate string, about the date and time the merged event begins end_datetime: isoformatted timedate string, about the date and time the merged event ends """ assert arrow.get(begin_datetime) < arrow.get(end_datetime) self.begin_datetime = begin_datetime self.end_datetime = end_datetime if isinstance(contains, str): self.contains = [ { 'summary': contains, 'begin_datetime': begin_datetime, 'end_datetime': end_datetime } ] else: self.contains = contains def merge(self, other): """ Tries to merge two TimeSlot objects. Normally used to merge two busy times. Args: other: TimeSlot object, representing another busy time Returns: merged TimeSlot object, if it can be merged None, if it cannot be merged """ self_begin = arrow.get(self.begin_datetime) self_end = arrow.get(self.end_datetime) other_begin = arrow.get(other.begin_datetime) other_end = arrow.get(other.end_datetime) # Not Mergeable if self_end < other_begin or self_begin > other_end: return None # Mergable merged_contains = self.contains + other.contains if self_begin <= other_begin: merged_begin_datetime = self_begin.isoformat() else: merged_begin_datetime = other_begin.isoformat() if self_end >= other_end: merged_end_datetime = self_end.isoformat() else: merged_end_datetime = other_end.isoformat() return TimeSlot(merged_contains, merged_begin_datetime, merged_end_datetime) def find_freebusy_from(self, busylist): """ Finds a list of free times between the list of busy times. All busy times do not have to be merged. Args: self: TimeSlot object, representing a single slot of free time busylist: a list of TimeSlot objects, representing busy times Returns: a list of TimeSlot objects, representing free times """ ##### # There maybe are busy events ##### if busylist == []: # No busy events, entire free period is a free time return [ [self], [] ] ##### # There are some busy events. Are they in the free period? ##### free_begin = arrow.get(self.begin_datetime) free_end = arrow.get(self.end_datetime) # Eliminate events that end before or when the free period begins sorted_list = sort_by_end_time(busylist, DESCENDING) print('After first sort: {}'.format(sorted_list)) reduced_list = [] for busytime in sorted_list: if free_begin >= arrow.get(busytime.end_datetime): break # Append busy events that end after the free period begins reduced_list.append(busytime) if reduced_list == []: # All busy events end before the free period begins return [ [self], [] ] print('After first reduction: {}'.format(reduced_list)) # Eliminate events that begin after or when the free period ends sorted_list = sort_by_begin_time(reduced_list, ASCENDING) print('After second sort: {}'.format(sorted_list)) reduced_list = [] for busytime in sorted_list: if free_end <= arrow.get(busytime.begin_datetime): break # Append busy events that start after the free period ends reduced_list.append(busytime) if reduced_list == []: # No busy events in the free period return [ [self], [] ] print('After second reduction: {}'.format(reduced_list)) ##### # There are some busy events in the free period. Finding free and busy times ##### freetimes = [ ] busytimes = [ ] merged_list = calc.merge_single_list(reduced_list) print('Merged List: {}'.format(merged_list)) for busytime in merged_list: busy_begin = arrow.get(busytime.begin_datetime) busy_end = arrow.get(busytime.end_datetime) if freetimes == []: # First busy entry print("This is the first entry") if free_begin >= busy_begin and free_end <= busy_end: # Special case of when the free period is completely within a busy time return [ [], [busytime] ] if free_begin < busy_begin: # If there is a block of free time between the start of the free period # and the start of the busy time, first append a complete block before # appending a half block freetimes.append({ "begin_datetime": free_begin.isoformat(), "end_datetime": busy_begin.isoformat() }) print("Adding first entry. Free from {} to {}".format(free_begin.isoformat(), busy_begin.isoformat())) freetimes.append({ "begin_datetime": busy_end.isoformat(), "end_datetime": None }) print("Adding part of next entry. Free from {}".format(busy_end.isoformat())) else: # Otherwise, append a half block, waiting to be completed on next iteration freetimes.append({ "begin_datetime": busy_end.isoformat(), "end_datetime": None }) print("Adding part of first entry. Free from {}".format(busy_end.isoformat())) busytimes.append(busytime) continue # Subsequent entries. Finish the incomplete block from previous iteration, then # append another half block freetimes[len(freetimes)-1]["end_datetime"] = busy_begin.isoformat() print("to {}\n".format(busy_begin.isoformat())) freetimes.append({ "begin_datetime": busy_end.isoformat(), "end_datetime": None }) print("Adding part of next entry. Free from {}".format(busy_end.isoformat())) busytimes.append(busytime) # End for loop: finish loose ends # Busy time is after the free period, finish modifying free blocks of time if free_end > arrow.get(freetimes[len(freetimes)-1]["begin_datetime"]): # If the previous busy end time is before the free period end time, # then add the last block of free time freetimes[len(freetimes)-1]["end_datetime"] = free_end.isoformat() print("to {}(End)\n".format(free_end.isoformat())) else: # If not, there should not be another block of free time. Removes # the previously initiated block del freetimes[len(freetimes)-1] print("...Last entry cancelled") # Convert the list of free time dicts into list of TimeSlots fts = freetimes freetimes = [ ] for ft in fts: freetimes.append(TimeSlot('Free Time', ft['begin_datetime'], ft['end_datetime'])) return [freetimes, busytimes] def serialize(self): """ To convert the object into something that can be sent to browser """ return { 'contains': self.contains, 'begin_datetime': self.begin_datetime, 'end_datetime': self.end_datetime } def equals(self, other): """ To be able to easily compare objects """ if self.begin_datetime != other.begin_datetime \ or self.end_datetime != other.end_datetime \ or len(self.contains) != len(other.contains): return False for i in range(0, len(self.contains)): if self.contains[i]['summary'] != other.contains[i]['summary'] \ or self.contains[i]['begin_datetime'] != other.contains[i]['begin_datetime'] \ or self.contains[i]['end_datetime'] != other.contains[i]['end_datetime']: return False return True def __repr__(self): """ To be able to print object """ c = None for event in self.contains: next_c = "'summary': '{}', 'begin_datetime': '{}', 'end_datetime': '{}'".format(event['summary'], event['begin_datetime'], event['end_datetime']) if c == None: c = '[{'+next_c+'}' else: c = c+', {'+next_c+'}' c += ']' s = "'begin_datetime': '{}', 'end_datetime': '{}', ".format(self.begin_datetime, self.end_datetime) return '{'+s+c+'}' ################################################################################# # # Helper Functions # ################################################################################# def sort_by_begin_time(timeslot_list, order): """ Sorts a list of merged TimeSlot objects by their begin_datetime """ assert order == ASCENDING or order == DESCENDING if order == ASCENDING: return sorted(timeslot_list, key=lambda timeslot: int(timeslot.begin_datetime[:-6].replace('T','').replace('-','').replace(':',''))) else: return sorted(timeslot_list, key=lambda timeslot: int(timeslot.begin_datetime[:-6].replace('T','').replace('-','').replace(':','')), reverse=True) def sort_by_end_time(timeslot_list, order): """ Sorts a list of merged TimeSlot objects by their end_datetime """ assert order == ASCENDING or order == DESCENDING if order == ASCENDING: return sorted(timeslot_list, key=lambda timeslot: int(timeslot.end_datetime[:-6].replace('T','').replace('-','').replace(':',''))) else: return sorted(timeslot_list, key=lambda timeslot: int(timeslot.end_datetime[:-6].replace('T','').replace('-','').replace(':','')), reverse=True) def serialize_list(timeslot_list): return [ts.serialize() for ts in timeslot_list]
238f2949524b02f984ffc52fcb33a99a1442241d
Jeltorotik/snake-ai
/snake.py
3,506
3.65625
4
import pygame from collections import deque import random def draw_a_block(screen, x, y, type_of_block, color, size): #Scaling shell = size // 25 x *= size y *= size h, w = size, size if type_of_block == "horizontal": y += shell w -= shell*2 elif type_of_block == "vertical": x += shell h -= shell*2 elif type_of_block in ["empty","food"]: x += shell y += shell h -= shell*2 w -= shell*2 pygame.draw.rect(screen, color, [x, y, h, w]) def show_text(screen,text, x, y, font_size, color): myfont1 = pygame.font.SysFont('Comic Sans MS', font_size) myfont2 = pygame.font.SysFont('Comic Sans MS', font_size+2) textsurface1 = myfont1.render(text, False, color) textsurface2 = myfont2.render(text, False, (0,0,0)) screen.blit(textsurface2,(x+1,y+1)) screen.blit(textsurface1,(x,y)) class Snake(): def __init__(self, h, w): """ x, y - initial position of a snake h, w - height and width of the board Board: 0 - empty block 1 - snake block 2 - food block """ self.score = 0 self.h = h self.w = w x, y = random.randint(0, self.h-1), random.randint(0, self.w-1) self.body = deque([[x, y, "standing"]]) self.last_move = "right" self.next_move = "right" self.board = [[0] * h for _ in range(w)] self.board[x][y] = 1 self.spawn_food() self.moves = {"right": [1, 0, "horizontal"], "left": [-1, 0, "horizontal"], "up": [0, -1, "vertical"], "down": [0, 1, "vertical"]} def get_head(self): return self.body[0][0], self.body[0][1] def is_valid_move(self, move): if move not in self.moves.keys(): return False if move in ["up", "down"] and self.last_move in ["up", "down"]: return False if move in ["left", "right"] and self.last_move in ["left", "right"]: return False return True def move(self): """ moves snake's head, updates board and returns reward: 1) "Game over" (Out of border or ate itself) 2) "Food" (snake ate food) 3) None (snake just succesfully moves) """ self.last_move = self.next_move dx, dy, block = self.moves[self.next_move] x, y = self.get_head() if (0 <= x+dx < self.h) and (0 <= y+dy < self.w): self.body.appendleft([x+dx, y+dy, block]) #Poping tail x_tail, y_tail, _ = self.body[-1] self.board[x_tail][y_tail] = 0 if self.board[x+dx][y+dy] == 1: return "Game over" elif self.board[x+dx][y+dy] == 0: self.board[x+dx][y+dy] = 1 self.body.pop() return None else: self.board[x+dx][y+dy] = 1 self.board[x_tail][y_tail] = 1 self.score += 1 if self.score == self.h * self.w - 1: return "Game over" else: self.spawn_food() return "Food" else: return "Game over" def spawn_food(self): """ spawns food at random free block of board """ x = random.randint(0, self.h-1) y = random.randint(0, self.w-1) while self.board[x][y] != 0: x = random.randint(0, self.h-1) y = random.randint(0, self.w-1) self.board[x][y] = 2 self.food = [x, y] def draw(self, screen, size): """ Draws board, snake and food """ SNAKE_COLOR = (20, 255, 50) FOOD_COLOR = (200, 20, 40) screen.fill((255, 255, 255)) #Board for i in range(self.h): for j in range(self.w): draw_a_block(screen, i, j, "empty", (0,0,0), size) #Snake for block in self.body: draw_a_block(screen, *block, SNAKE_COLOR, size) draw_a_block(screen, *self.food, "food", FOOD_COLOR, size) show_text(screen, "score: " + str(self.score), 0, 0, 50, (255,255,255))
276db976128910aec53f1e27a09209936302b345
baieric/hackerRank
/algorithms/dynamicProgramming/candies.py
1,211
3.59375
4
# Solution to https://www.hackerrank.com/challenges/candies # Test Cases: # [1, 2, 3, 4] -> 10 # [4, 3, 2, 1] -> 10 # [1, 1, 1, 1] -> 4 # [1, 2, 3, 3, 3, 2, 1, 2] -> 15 # [1, 3, 2, 1] -> 7 n = int(input()) a = [] floor = None; for _ in range(n): i = int(input()) a.append(i) candies = 1 rating = a[0] total = 0 peakIndex = 0 peakCandies = 1 for i in range(n): if a[i] == rating: # peak must be the same as before, but reset candies candies = 1 peakIndex = i peakCandies = candies elif a[i] > rating: # found a new peak, update peakIndex and peakCandies # child must have one more candy than the previous child candies = candies + 1 peakIndex = i peakCandies = candies else: # lower rating, so reset candies to 1 # total must be increased for the downward slope (excluding the peak) # if this downward slope is longer than the previous upward slope, # the peak's candy count must increase candies = 1 total = total + i - peakIndex - 1 if i - peakIndex >= peakCandies: total = total + 1 rating = a[i] total = total + candies print(total)
b19e020a980763759dc51fdadb8dd36cacedb167
Hush14/Homeworks
/Pack4/4.3.py
5,247
3.625
4
import random from random import randint class animal(): pass class fish(animal): def __init__(self): self.t = 2 def __str__(self): return 'FISH' class bear(animal): def __init__(self): self.food = 0 self.t = 1 def __str__(self): return 'BEAR' class none(animal): def __init__(self): self.t = 0 def __str__(self): return 'NONE' class river(list): def __init__(self, n, time, f, b, dd): self.length = n self.l = [] self.new1 = [] self.new2 = [] self.time = time self.aa = 0 self.none = set() self.dd = dd self.extend([none()] * n) for i in range(self.length): self.none.add(i) self.new1.append(none()) self.new2.append(none()) for i in range(f): self.life(fish()) for i in range(b): self.life(bear()) def skra(self): s = "" for i in range(self.length): s += str(str(self[i])[0] + "-") print(s) def life(self, x): if (len(self.none) > 0): l1 = [] i = 0 while (len(self.none) > 0): l1.append(self.none.pop()) random.shuffle(l1) while (len(l1) > i): self.none.add(l1[i]) i += 1 kk = l1.pop() self.none.discard(kk) self[kk] = x else: return print("no place for new life") def check(self, x): if (x.food >= self.dd): return True else: return False def hod(self): self.lq = [] for i in range(self.length): self.none.add(i) self.new1[i] = none() self.new2[i] = none() for i in range(self.length): self.hod_otd(i) for i in range(self.length): if (str(self.new1[i]) != "NONE"): if (str(self.new2[i]) != "NONE"): if (str(self.new2[i]) == str(self.new1[i])): if (self.new1[i].t == 1): self.new1[i].food += 1 self.new2[i].food += 1 if (self.check(self.new1[i])): if (self.check(self.new2[i])): self.none.add(i) self[i] = none() else: self[i] = self.new2[i] else: if (self.check(self.new2[i])): self[i] = self.new1[i] else: self.none.add(i) self[i] = none() self.lq.append(i) if (self.new1[i].t == 2): self.none.add(i) self[i] = none() self.lq.append(i) else: if (self.new1[i].t == 1): self[i] = self.new1[i] self[i].food = 0 else: self[i] = self.new2[i] self[i].food = 0 else: if (self.new1[i].t == 1): self.new1[i].food += 1 if (self.check(self.new1[i])): self.none.add(i) self[i] = none() else: self[i] = self.new1[i] else: self[i] = self.new1[i] else: self[i] = none() while (self.lq != []): self.aa = self.lq.pop() self.life(self.new1[self.aa]) self.life(self.new2[self.aa]) if (self.new1[self.aa].t == 1): self.life(bear()) else: self.life(fish()) def anithype(self): self.hod() self.skra() def hod_otd(self, i): if (str(self[i]) != "NONE"): random.seed(version=2) k = random.randint(-1, 1) if (i == 0): k = (k + 1) // 2 if (i == self.length - 1): k = (k + 1) // 2 - 1 if (str(self.new1[i + k]) == "NONE"): self.new1[i + k] = self[i] self.none.discard(i + k) else: if (str(self.new2[i + k]) == "NONE"): self.new2[i + k] = self[i] else: self.hod_otd(i) def thuglife(self): print("RIVER") print("\n") self.skra() for i in range(self.time): print("\n") self.anithype() a = [] print("River's Length") n = int(input()) print("Amount of fish") n1 = int(input()) print("Amount of bears") n2 = int(input()) print("Amount of steps") time = int(input()) print("Days without food") dd = int(input()) b = river(n, time, n1, n2, dd) b.anithype()
dfc30e3fa0e11552f0c638ed26f1e1258ce8a05d
nascarsayan/lintcode
/428.py
572
3.640625
4
class Solution: def recurse(self, x, n, pows): if n == 0: pows[n] = 1 return pows[n] if n == 1: pows[n] = x return pows[n] if n == -1: pows[n] = 1 / x return pows[n] if n in pows: return pows[n] pows[n] = self.recurse(x, n // 2, pows) * self.recurse(x, n - n // 2, pows) return pows[n] """ @param x {float}: the base number @param n {int}: the power number @return {float}: the result """ def myPow(self, x, n): # write your code here pows = {} return self.recurse(x, n, pows)
dea2b61150dc56131e1a64e18d2ce4b0fe1bdbd4
Khushboo-09/DataStructureWithPython
/Doubly Linked List/RemoveAtEnd.py
2,775
3.515625
4
class _Node: __slots__= '_element','_next','_prev' def __init__(self,element,next,prev): self._element = element self._next = next self._prev = prev class DoublyLinkedList: def __init__(self): self._head = None self._tail = None self._size = 0 def __len__(self): return self._size def isempty(self): return self._size==0 def AddLast(self,e): newest = _Node(e,None,None) if self.isempty(): self._head = newest self._tail = newest else: self._tail._next = newest newest._prev = self._tail self._tail = newest self._size += 1 def AddAtBeginning(self,e): newest = _Node(e,None,None) if self.isempty(): self._head = newest self._tail = newest else: newest._next = self._head self._head._prev = newest self._head = newest self._size += 1 def AddAtAny(self,e,pos): newest = _Node(e,None,None) p = self._head i = 1 while i<pos-1: p = p._next i += 1 newest._next = p._next p._next._prev = newest p._next = newest newest._prev = p self._size += 1 def RemoveAtBeginning(self): if self.isempty(): print("The list is empty!!! Nothing to Delete.") return e = self._head._element self._head._next._prev = None self._head = self._head._next self._size -= 1 return e def RemoveAtEnd(self): if self.isempty(): print("Nothing to delete!!! The list is empty.") return e = self._tail._element self._tail._prev._next = None self._tail = self._tail._prev self._size -= 1 return e def display(self): p = self._head while p: print(p._element,end = " ") p = p._next print() def displayRev(self): p = self._tail while p: print(p._element,end = " ") p = p._prev print() d = DoublyLinkedList() d.AddLast(8) d.AddLast(2) d.AddLast(9) d.AddAtBeginning(4) d.AddLast(6) d.AddAtBeginning(7) d.AddAtAny(5,3) print("The original List is:") d.display() print("The list in reverse order is:") d.displayRev() print("The list after removing element from beginning which is:",d.RemoveAtBeginning()) d.display() print("The list in reverse order:") d.displayRev() print("The list after removing element at end which is:",d.RemoveAtEnd()) d.display() print("The list in reverse order:") d.displayRev() print("The size of the list is: ",d.__len__())
c7a586240101a69c7ef72ff30b1b0cb3187c26b3
gracemetzgar/New-Repo
/HW4.py
1,073
4.46875
4
# Author: Grace Metzgar # Date: 20210917 # Python for Data Analysis 101 ## Homework ### Instructor: Evelyn J. Boettcher, DiDacTex, LLC ### Week 1: Lecture 4 # Write a function that takes a single argument, prints the value of the argument, and returns the argument as a string. def str_function(x): print(x) return str(x) if type(str_function(10)) == str: print("string") else: print("not a string") # Write a function that takes a variable number of arguments and prints them all. def variable_function(*values): for x in values: print(x) variable_function(1, 2, 3, 4, 5) # Write a function that prints the names and values of keyword arguments passed to it. def key_function(**arguments): for key in arguments: print(key, arguments[key]) key_function(a = 1, b = 2, c = 3) # Write a python script (file) that prints your name as all lower case, upper case and proper capitalization. def name_function(my_name): print(my_name.upper()) print(my_name.lower()) print(my_name.title()) name_function("grace metzgar")
103c5395839ec916f3e00f8ad041e727baa2bc31
DanMeloso/python
/Exercicios/ex061.py
421
3.9375
4
#Exercício Python 061: Refaça o DESAFIO 051, lendo o primeiro termo e a razão de uma PA, #mostrando os 10 primeiros termos da progressão usando a estrutura while. termo = int(input('Informe o primeiro termo: ')) razao = int(input('Informe a Razão')) numero = 0 c = 0 while c < 10: if c == 0: numero = termo else: numero = numero + razao c += 1 print(numero, end=' → ') print('FIM')
89667726789ecba9ec269f9fbb177e20ec331679
jufecabrera/jf.cabreraMC
/csemana1/ex3.py
342
3.734375
4
a= 27 b= 83 #a es impar? if (a%2==0): print "%d es par" % (a) else: print "%d es impar" % (a) #divisres de a print "los dividores de a son:" for i in range(1,a+1): if (a%i == 0): print i #max comun divisor max_d=0 for j in range(1,a+1): if (a%j == 0 and b%j == 0): max_d=j print "El maximo comun divisor entre a y b es %d" % (max_d)
57160abed2c7701c35cc58bcb0cdd87cf00c92f6
shantanudwvd/PythonHackerrank
/CollectionsDeque.py
652
3.671875
4
from collections import deque deq = deque() digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", " "] queries = int(input()) for i in range(queries): my_string = input() string = "" number = "" for j in my_string: if j not in digits: string += j else: number += j if number != "": number = int(number) if string == "append": deq.append(number) elif string == "appendleft": deq.appendleft(number) elif string == "pop": deq.pop() elif string == "popleft": deq.popleft() for i in deq: print(i, end=" ")
78caa65847184ff5b184514ac88c478f451c3312
kjjeong104/MD_kjjeong
/py_development/data_process/math/NRsol.py
760
4.09375
4
#!/home/kjeong23/softwares/bin/python3.4 import math import numpy # Newton-Raphson method practice #Variables section thres=0.00001 #threshold target=0 #target value for the function guess=0 #initial guess clue for x dx=0.05 #increment of x to measure slope of f(x). search for both direction damp=1 #damping factor #solve equation f(x)=c, when c is the target. # for this case, let f(x)=x^3-2x+2 def f(x): value=0.002*x**2-0.007*x-0.0005 return value x=guess y=f(x) iter=0 while abs(y-target) > thres: iter+=1 slope = ( f(x+dx) - f(x-dx) ) / (2*dx) #find slope x = x - damp*(f(x)/slope) y=f(x) print ('Iteration {} x= {:8.4f}\n'.format(iter,x)) print ('final solution is x= {:8.4f}\n'.format(x)) print ('completed')
94e5caf4a11ccf9bd35a57f27d557ea32173ac7d
jessieharada6/Mini-Python-Projects
/Day-46-Create-a-Spotify-Playlist-using-the-Musical-Time-Machine/main.py
1,383
3.53125
4
from bs4 import BeautifulSoup import requests # import spotipy # from spotipy.oauth2 import SpotifyOAuth date = input("which year do you want to travel to? Type the date in this format YYYY-MM-DD \n") response = requests.get("https://www.billboard.com/charts/hot-100/2000-08-12") web_page_songs = response.text soup = BeautifulSoup(web_page_songs, "html.parser") songs_contents = soup.find_all(name="span", class_="chart-element__information__song text--truncate color--primary") songs_list = [song.getText() for song in songs_contents] year = date.split("-")[0] # spotify # sp = spotipy.Spotify( # auth_manager=SpotifyOAuth( # scope="playlist-modify-private", # redirect_uri="http://example.com", # client_id="YOUR UNIQUE CLIENT ID", # client_secret="YOUR UNIQUE CLIENT SECRET", # show_dialog=True, # cache_path="token.txt" # ) # ) # user_id = sp.current_user # song_uris = [] # for song in songs_list: # result = sp.search(q=f"track:{song} year:{year}", type="track") # try: # uri = result["tracks"]["items"][0]["uri"] # song_uris.append(uri) # except IndexError: # print(f"{song} does not exist in Spotify. Skipped.") # playlist = sp.user_playlist_create(user=user_id, name=f"{date} Billboard 100", public = False) # sp.playlist_add_items(playlist_id= playlist["id"], item=song_uris)
bd5e76f700a52d1e050d104f117615c8838b178b
chengbo/leetcode
/leetcode/binary_search_tree/convert_sorted_array_to_binary_search_tree.py
337
3.640625
4
from leetcode.binary_tree.tree_node import TreeNode def sorted_array_to_bst(nums): nums_len = len(nums) if nums_len == 0: return None middle = nums_len // 2 root = TreeNode(nums[middle]) root.left = sorted_array_to_bst(nums[:middle]) root.right = sorted_array_to_bst(nums[middle+1:]) return root
1c71f72a950253f9c3c7d11f84abaa83d15c38de
ca-sousa/py-guanabara
/exercicio/ex039.py
354
4.125
4
from datetime import date ano = int(input('Digite o ano de nascimento: ')) idade = date.today().year - ano if idade == 18: print('Esta na hora de se alistar') elif idade < 18: print('Ainda faltam {} anos para o seu alistamento'.format(18 - idade)) elif idade > 18: print('O prazo para alistamento passou ja faz {} anos'.format(idade - 18))
15730d8ea44a3075ce3927cbffd66e5be53e76e1
christaggart/openblock
/ebpub/ebpub/streets/name_utils.py
3,545
3.578125
4
""" Utility functions for munging address/block/street names. """ import re from ebpub.utils.text import smart_title, slugify def make_street_pretty_name(street, suffix): street_name = smart_title(street) if suffix: street_name += u' %s.' % smart_title(suffix) return street_name def make_block_number(left_from_num, left_to_num, right_from_num, right_to_num): lo_num, hi_num = make_block_numbers(left_from_num, left_to_num, right_from_num, right_to_num) if lo_num == hi_num: number = unicode(lo_num) elif lo_num and not hi_num: number = unicode(lo_num) elif hi_num and not lo_num: number = unicode(hi_num) else: number = u'%s-%s' % (lo_num, hi_num) return number def make_block_numbers(left_from_num, left_to_num, right_from_num, right_to_num): nums = [x for x in (left_from_num, left_to_num, right_from_num, right_to_num) if x is not None] if not nums: # This used to raise ValueError, maybe accidentally, because # min([]) does so. Preserving that for backward compatibility, # not sure if it matters. raise ValueError("No non-None addresses provided") lo_num = min(nums) hi_num = max(nums) return (lo_num, hi_num) def make_pretty_directional(directional): """ Returns a formatted directional. e.g.: N -> N. NW -> N.W. """ return "".join(u"%s." % c for c in directional) def make_pretty_name(left_from_num, left_to_num, right_from_num, right_to_num, predir, street, suffix, postdir=None): """ Returns a tuple of (street_pretty_name, block_pretty_name) for the given address bits. """ street_name = make_street_pretty_name(street, suffix) num_part = make_block_number(left_from_num, left_to_num, right_from_num, right_to_num) predir_part = predir and make_pretty_directional(predir) or u'' postdir_part = postdir and make_pretty_directional(postdir) or u'' block_name = u'%s %s %s %s' % (num_part, predir_part, street_name, postdir_part) block_name = re.sub(u'\s+', u' ', block_name).strip() return street_name, block_name def make_dir_street_name(block): """ Returns a street name from a block with the directional included. If the block has a ``predir``, the directional is prepended: "W. Diversey Ave." If the block has a ``postdir``, the directional is appended: "18th St. N.W." """ name = make_street_pretty_name(block.street, block.suffix) if block.predir: name = u"%s %s" % (make_pretty_directional(block.predir), name) if block.postdir: name = u"%s %s" % (name, make_pretty_directional(block.postdir)) return name def pretty_name_from_blocks(block_a, block_b): return u"%s & %s" % (make_dir_street_name(block_a), make_dir_street_name(block_b)) def slug_from_blocks(block_a, block_b): slug = u"%s-and-%s" % (slugify(make_dir_street_name(block_a)), slugify(make_dir_street_name(block_b))) # If it's too long for the slug field, drop the directionals if len(slug) > 64: slug = u"%s-and-%s" % (slugify(make_street_pretty_name(block_a.street, block_a.suffix)), slugify(make_street_pretty_name(block_b.street, block_b.suffix))) # If it's still too long, drop the suffixes if len(slug) > 64: slug = u"%s-and-%s" % (slugify(block_a.street), slugify(block_b.street)) return slug
b591b8fb098356b108500ba450080b2b13c6a1ce
huanglun1994/learn
/python编程从入门到实践/第五章/5-10.py
363
3.859375
4
# -*- coding: utf-8 -*- current_users = ['admin', 'huanglun', 'wangdi', 'xiaoming', 'xiaohong'] new_users = ['Huanglun', 'Wangdi', 'ranming', 'yandong', 'maning'] for new_user in new_users: if new_user.lower() in current_users: print('Sorry, you must choose another name again.') else: print("This name hasn't been used, you can make it.")
6a4be92b8cb4ee4f12b04a2204fc70a71dcf7295
Josh-Cruz/python-strings-and-list-prac
/multiple_sum_average_algos.py
787
4.5
4
# Multiples # Part I - Write code that prints all the odd numbers from 1 to 1000. # Use the for loop and don't use a list to do this exercise. # for x in range(1,1000): # if x % 2 != 0: # print x # Part II - Create another program that prints # all the multiples of 5 from 5 to 1,000,000. # for x in range(5, 1000000): # if x % 5 == 0: # print x # Sum List # Create a program that prints the # sum of all the values in the list: a = [1, 2, 5, 10, 255, 3]' # a = [1, 2, 5, 10, 255, 3] # sums = 0 # for x in a: # sums += x # print sums # Average List # Create a program that prints the average # of the values in the list: a = [1, 2, 5, 10, 255, 3] a = [1, 2, 5, 10, 255, 3] average = len(a) sums = 0 for x in a: sums += x print sums/ average
518cfae73e9e13d83dea1ee0a538496a72364bb7
Sampreet/numerical-techniques
/python/modules/root_finding/NewtonRaphson.py
4,452
3.71875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # Authors: Sampreet Kalita # Created: 2019-03-26 # Updated: 2020-01-12 """Module to find roots of a function using Newton-Raphson Method.""" # dependencies import numpy as np def find_root_uni(fn, df, xi, et=1e-6, imax=1e6): """ Find the (approximate) root of a given univariate function using Newton-Raphson Method. Parameters ---------- fn : function Given function of x. df : function Derivative of the given function of x. xi : float Initial point of selection. et : float (optional) Relative error threshold. imax : int (optional) Maximum number of iterations to consider. Returns ------- root, ic, msg : float, int, String The root and the iteration count with error string. """ # initialize values ic = 0 # check initial values if (fn(xi) == 0): return xi, ic, "Root found" # iterate till maximum iteration is reached or relative error reaches threshold while True: ic += 1 # check iteration threshold if (ic >= imax): return None, ic, "Maximum iterations reached" # no root if derivative is zero if df(xi) == 0: return None, ic, "Derivative is zero" # get intersection point xint = xi - fn(xi) / df(xi) # check relative error curr_diff = abs(xint - xi) max_diff = abs(xi) * et xi = xint if (curr_diff < max_diff): return xi, ic, "Approx. root found" # check value at xi if (fn(xi) == 0): return xi, ic, "Root found" return xi, ic, "Root found" def find_root_multi(Fn, Dn, X, em=1, imax=1e6): """ Find the (approximate) root of a given system of multivariate function using Newton-Raphson Method. Parameters ---------- Fn : list (function) Given set of equations. Dn : list (list (function)) Partial derivative equations of the given set. X : list (float) Initial point of selection. em : float (optional) Error margin. imax : int (optional) Maximum number of iterations to consider. Returns ------- root, ic, msg : float, int, String The root and the iteration count with error string. """ # initialize values ic = 0 # iterate till maximum error is reached or relative error reaches threshold while True: ic += 1 # check iteration threshold if (ic >= imax): return X, ic, "Maximum iteration reached" # check convergence is_converging = True for i in range(0, len(Dn)): if sum(list(map(lambda dn: dn(X), Dn[i]))) > em: is_converging = False break if (is_converging): return X, ic, None # obtain partial jacobian matrices for each variable Det_D = list(map(lambda index: get_jacobian_determinant(Fn, Dn, X, index), list(range(0, len(Fn) + 1)))) # check if denominator is zero if Det_D[0] == 0: return None, ic, "Denominator is zero" # update values for i in range(0, len(X)): X[i] = X[i] - Det_D[i+1]/Det_D[0] return X, ic, None def get_jacobian_determinant(Fn, Dn, X, index): """ Get the determinant of a partial Jacobian matrix of a given set of equations. Parameters ---------- Fn : list (function) Given set of equations. Dn : list (list (function)) Partial derivative equations of the given set. X : list (float) Initial point of selection. index : int Index of the variable for which the determinant is to be calculated. Returns ------- det: float Value of the determinant """ # initialize values mat = [] for i in range(0, len(Fn)): temp = [] for j in range(0, len(Fn)): # if the column is same, take the functional value if j == index - 1: temp.append(Fn[i](X)) # else take the partial derivate value else: temp.append(Dn[i][j](X)) mat.append(temp) # reconvert the array to numpy array mat = np.array(mat) # return determinant of matrix return np.linalg.det(mat)
32d8acb3c65622a65ab0e7c6b2cffd1e01313ed9
dinaramairambaeva/PP2_2021
/week 6/14.py
215
3.703125
4
# def panagram(a): # for i in range (97,123):if a.find(chr(i))==False:break # return True # print(panagram(input().lower())) a = input().lower() print(sum([i in a for i in 'abcdefghijklmnopqrstuvwxyz'])==26)
7fd8578347f284fa99f71fb9f4eff927a6484895
xieziwei99/py100days
/day01_15/multi/multiprocessDemo1.py
1,060
3.59375
4
""" Created on 2019/6/18 完成1~100000000求和的计算密集型任务 @author: xieziwei99 """ from multiprocessing import Queue, Process from time import time def main(): total = 0 number_list = [x for x in range(1, 10000001)] start = time() for number in number_list: total += number print(total) end = time() print('Execute time: %.3fs' % (end - start)) def task_handler(current_list, result_queue): total = 0 for num in current_list: total += num result_queue.put(total) def main1(): processes = [] num_list = [x for x in range(1, 10000001)] result_queue = Queue() index = 0 for _ in range(8): p = Process(target=task_handler, args=(num_list[index: index+1250000], result_queue)) index += 1250000 processes.append(p) p.start() start = time() for p in processes: p.join() total = 0 while not result_queue.empty(): total += result_queue.get() # get()会删除取得的元素 print(total) end = time() print('Execute time with 8 processes: %.3fs' % (end - start)) if __name__ == '__main__': main() main1()
ff1e263a8b941e42d90e0a104e40942bf9ac0db3
avidekar/python-assignments
/group_anagrams.py
645
4.3125
4
# Given an array of strings, group anagrams together. # # Example: # # Input: ["eat", "tea", "tan", "ate", "nat", "bat"], # Output: # [ # ["ate","eat","tea"], # ["nat","tan"], # ["bat"] # ] def group_anagrams(strs): result = [] grouped_dict = {} for word in strs: sorted_word = "".join(sorted(word)) if sorted_word not in grouped_dict: grouped_dict[sorted_word] = [word] else: grouped_dict[sorted_word].append(word) for key in grouped_dict: result.append(grouped_dict[key]) print(result) strs = ["eat", "tea", "tan", "ate", "nat", "bat"] group_anagrams(strs)
cc3e0fda5f4ea7f1b09c21f08e82dffc865ca0da
eduardorasgado/AlgorithmsX
/introduction/selection_sort.py
1,050
4.125
4
#!/usr/bin/env python3 def selection_sort(A, increasing=True): # clonning A B = A[:] # for 1 ... j-1 for j in range(len(B)-1): max_min_e = B[j+1] # to compare actual vs smallest(at the moment i) max_min_index = j+1 if increasing: # finding the smallest number in upper subarr for i in range(j+1, len(B)): if B[i] < max_min_e: max_min_e = B[i] max_min_index = i else: # findinf the greatest bumber in upper sub arr for i in range(j, len(B)): if B[i] > max_min_e: max_min_e = B[i] max_min_index = i # exchanging actual j for the smallest B[j], B[max_min_index] = B[max_min_index], B[j] return B list1 = [6,5,7,4,8,3,9,2,0,1] print(list1) print("Increasing sorting: ") list_inc = selection_sort(list1, True) print(list_inc) print("Decreasing sorting:") #print(list1) list_dec = selection_sort(list1, False) print(list_dec)
80c64c279c159e823befc5d576a46ebd509eb28b
soedjais/dodysw-hg
/ProjectEuler/Problem22.py
828
3.953125
4
""" Using names.txt (right click and 'Save Link/Target As...'), a 46K text file containing over five-thousand first names, begin by sorting it into alphabetical order. Then working out the alphabetical value for each name, multiply this value by its alphabetical position in the list to obtain a name score. For example, when the list is sorted into alphabetical order, COLIN, which is worth 3 + 15 + 12 + 9 + 14 = 53, is the 938th name in the list. So, COLIN would obtain a score of 938 x 53 = 49714. What is the total of all the name scores in the file? """ names = [name.replace('"','') for name in file("names.txt").readlines()[0].split(",")] names.sort() total_score = 0 for i,name in enumerate(names): score = sum([ord(c)-64 for c in name]) * (i+1) #print i, name, score total_score += score print total_score
fc5715c5e64d15e98079e050418b325e28e7ebe5
JavaRod/SP_Python220B_2019
/students/ramkumar_rajanbabu/lesson_09/assignment/test_database.py
2,321
3.578125
4
"""Module for testing database""" import unittest from unittest import TestCase import database as db class TestDatabase(TestCase): """Test Database""" def test_import_data(self): """Testing import data""" db.clear_database() actual = db.import_data("csv_files", "products.csv", "customers.csv", "rentals.csv") expected = ((5, 4, 5), (0, 0, 0)) self.assertEqual(actual, expected) def test_show_available_products(self): """Tetsing showing available products""" self.maxDiff = None db.clear_database() actual = db actual.import_data("csv_files", "products.csv", "customers.csv", "rentals.csv") expected = {"51": {"description": "TV", "product_type": "Electric", "quantity_available": "4"}, "325": {"description": "Laptop", "product_type": "Electric", "quantity_available": "112"}, "223": {"description": "Table", "product_type": "Furniture", "quantity_available": "25"}, "999": {"description": "Couch", "product_type": "Furniture", "quantity_available": "15"}} self.assertEqual(actual.show_available_products(), expected) def test_show_rentals(self): """Testing show rentals""" db.clear_database() actual = db actual.import_data("csv_files", "products.csv", "customers.csv", "rentals.csv") expected = {"200": {"name": "Iron Man", "address": "17801 International Blvd, Seattle, WA 98101", "phone_number": "206-787-5388", "email": "iron.man@gmail.com"}, "300": {"name": "Ramkumar Rajanbabu", "address": "7525 166th Ave NE, Redmond, WA 98052", "phone_number": "425-556-2900", "email": "ram.kumar@gmail.com"}} self.assertEqual(actual.show_rentals("999"), expected) if __name__ == "__main__": unittest.main()
fd4348a9770e79af8f1e93d1a313cc15280597b2
nltk/nltk
/nltk/lm/preprocessing.py
1,640
3.609375
4
# Natural Language Toolkit: Language Model Unit Tests # # Copyright (C) 2001-2023 NLTK Project # Author: Ilia Kurenkov <ilia.kurenkov@gmail.com> # URL: <https://www.nltk.org/> # For license information, see LICENSE.TXT from functools import partial from itertools import chain from nltk.util import everygrams, pad_sequence flatten = chain.from_iterable pad_both_ends = partial( pad_sequence, pad_left=True, left_pad_symbol="<s>", pad_right=True, right_pad_symbol="</s>", ) pad_both_ends.__doc__ = """Pads both ends of a sentence to length specified by ngram order. Following convention <s> pads the start of sentence </s> pads its end. """ def padded_everygrams(order, sentence): """Helper with some useful defaults. Applies pad_both_ends to sentence and follows it up with everygrams. """ return everygrams(list(pad_both_ends(sentence, n=order)), max_len=order) def padded_everygram_pipeline(order, text): """Default preprocessing for a sequence of sentences. Creates two iterators: - sentences padded and turned into sequences of `nltk.util.everygrams` - sentences padded as above and chained together for a flat stream of words :param order: Largest ngram length produced by `everygrams`. :param text: Text to iterate over. Expected to be an iterable of sentences. :type text: Iterable[Iterable[str]] :return: iterator over text as ngrams, iterator over text as vocabulary data """ padding_fn = partial(pad_both_ends, n=order) return ( (everygrams(list(padding_fn(sent)), max_len=order) for sent in text), flatten(map(padding_fn, text)), )
f52df76c041ebf79251391ed771e72bd88d231d2
Hellofafar/Leetcode
/Medium/427.py
2,469
4.125
4
# ------------------------------ # 427. Construct Quad Tree # # Description: # We want to use quad trees to store an N x N boolean grid. Each cell in the grid can only # be true or false. The root node represents the whole grid. For each node, it will be # subdivided into four children nodes until the values in the region it represents are all # the same. # # Each node has another two boolean attributes : isLeaf and val. isLeaf is true if and only # if the node is a leaf node. The val attribute for a leaf node contains the value of the # region it represents. # # Your task is to use a quad tree to represent a given grid. # (Check picture from https://leetcode.com/problems/construct-quad-tree/) # # Version: 1.0 # 10/11/19 by Jianfa # ------------------------------ """ # Definition for a QuadTree node. class Node: def __init__(self, val, isLeaf, topLeft, topRight, bottomLeft, bottomRight): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRight """ class Solution: def construct(self, grid: List[List[int]]) -> 'Node': if not grid or not grid[0]: return None n = len(grid) return self.dfs(grid, 0, 0, n-1, n-1) def dfs(self, grid, x1, y1, x2, y2): # x1, y1 is the coordinates of top left corner # x2, y2 is the coordinates of bottom right corner if x1 == x2 and y1 == y2: return Node(grid[x1][y1], True, None, None, None, None) # Be careful of the coordinates of each region topLeft = self.dfs(grid, x1, y1, (x1 + x2) // 2, (y1 + y2) // 2) topRight = self.dfs(grid, x1, (y1 + y2) // 2 + 1, (x1 + x2) // 2, y2) bottomLeft = self.dfs(grid, (x1 + x2) // 2 + 1, y1, x2, (y1 + y2) // 2) bottomRight = self.dfs(grid, (x1 + x2) // 2 + 1, (y1 + y2) // 2 + 1, x2, y2) if topLeft.isLeaf and topRight.isLeaf and bottomLeft.isLeaf and bottomRight.isLeaf \ and topLeft.val == topRight.val == bottomLeft.val == bottomRight.val: node = Node(topLeft.val, True, None, None, None, None) else: node = Node("*", False, topLeft, topRight, bottomLeft, bottomRight) return node # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # DFS solution
7f40dfbac1224a4e52599c3aabd14813d2c2a093
mohsindalvi87/bearsnacks
/computer-vision/anaglyphs/test.py
2,847
3.515625
4
#!/usr/bin/env python3 # https://en.wikipedia.org/wiki/Anaglyph_3D # https://github.com/miguelgrinberg/anaglyph.py/blob/master/anaglyph.py import numpy as np import cv2 # declare various color blending algorithms to mix te pixels # from different perspectives so that red/blue lens glasses # make the image look 3D mixMatrices = { 'true': [ [ 0.299, 0.587, 0.114, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 0, 0, 0.299, 0.587, 0.114 ] ], 'mono': [ [ 0.299, 0.587, 0.114, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0.299, 0.587, 0.114, 0.299, 0.587, 0.114 ] ], 'color': [ [ 1, 0, 0, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 1 ] ], 'halfcolor': [ [ 0.299, 0.587, 0.114, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 1 ] ], 'optimized': [ [ 0, 0.7, 0.3, 0, 0, 0, 0, 0, 0 ], [ 0, 0, 0, 0, 1, 0, 0, 0, 1 ] ], } # blends two RGB image pairs into a single image that will be perceived as # 3d when using red/blue glasses # inputs: # leftImage -- an image that corresponds to the left eye # rightImage -- an image that corresponds to the right eye # color -- a string that specifies a blending strategy by indexing into mixMatrices # returns: # anaglyph image def anaglyphBGR(leftImage, rightImage, color): # use the color argument to select a color separation formula from mixMatrices if color in mixMatrices: m = mixMatrices[color] else: print('invalid color mixMatrix: {}'.format(color)) return None h,w = leftImage.shape[:2] result = np.zeros((h,w,3), np.uint8) # split the left and right images into separate blue, green and red images lb,lg,lr = cv2.split(np.asarray(leftImage[:,:])) rb,rg,rr = cv2.split(np.asarray(rightImage[:,:])) resultArray = np.asarray(result[:,:]) resultArray[:,:,0] = lb*m[0][6] + lg*m[0][7] + lr*m[0][8] + rb*m[1][6] + rg*m[1][7] + rr*m[1][8] resultArray[:,:,1] = lb*m[0][3] + lg*m[0][4] + lr*m[0][5] + rb*m[1][3] + rg*m[1][4] + rr*m[1][5] resultArray[:,:,2] = lb*m[0][0] + lg*m[0][1] + lr*m[0][2] + rb*m[1][0] + rg*m[1][1] + rr*m[1][2] return result def main(): # read in the image and split out the left/right img = cv2.imread('../imgs3/image-0.png') if len(img.shape) > 2: img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) h,w = img.shape[:2] leftImage = img[:,:w//2] rightImage = img[:,w//2:] # make an anaglyph anaglyphImage = anaglyphBGR(leftImage, rightImage, color='color') if anaglyphImage is not None: # display the anaglyph image cv2.imshow("anaglyph",anaglyphImage) print("Press:\n [s] to save\n [anykey] to exit") char = cv2.waitKey() if char == ord('s'): # cv2.imwrite('anaglyph_sample.png', np.asarray(anaglyphImage[:,:])) cv2.imwrite('anaglyph_sample.png', anaglyphImage) if __name__=="__main__": main()
08a9c7da4f6a2c8cc1fb77f8fc539a10efcc3bfd
OlehPalka/First_semester_labs
/Lab work 8/numberssum.py
1,160
3.84375
4
""" This module counts to different lists and appends multiplication of i elements from both lists """ def narayana(number): """ This function returns list of numbers. A(i) = A(i-1) + A(i-3), де A(0) = A(1) = A(2) = 1 >>> narayana(12) [1, 1, 1, 2, 3, 4, 6, 9, 13, 19, 28, 41] """ result = [1, 1, 1] for element in range(3, number): result.append((result[element - 1]) + (result[element - 3])) return result def lucas(number): """ This function returns list of numbers. A(i) = A(i-1) + A(i-3), де A(0) = A(1) = A(2) = 1 >>> lucas(12) [2, 1, 3, 4, 7, 11, 18, 29, 47, 76, 123, 199] """ result = [2, 1] for element in range(2, number): result.append(result[element - 1] + result[element - 2]) return result def numberssum(number): """ This function returns multiplication of i element from naryanas() and from lucas() >>> numberssum(12) [2, 1, 3, 8, 21, 44, 108, 261, 611, 1444, 3444, 8159] """ result = list() for element in range(number): result.append(narayana(number)[element] * lucas(number)[element]) return result
c1bb060af581f07d8c10127cb9a9e7027bdf08cc
loganyang/Logviewer
/Components/EncryptionDecryption/WriteArchive/Test/Hexshow.py
389
3.53125
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # R.Wobst, @(#) Aug 02 2011, 19:13:36 # output file contents in hex form, at most 64 chars per line import sys, binascii sz = open(sys.argv[1]).read() hexout = binascii.b2a_hex(sz) if len(hexout) < 64: print '"%s"\n' % hexout print "crypt length:", len(sz) print while hexout: print '"%s"' % hexout[:64] hexout = hexout[64:]
35c9fe22dc529a3f8e5cdc91f491b387158fb9c2
cslarsen/project-euler
/e089/e89.py
3,305
3.765625
4
# -*- encoding: utf-8 -*- """ProjectEuler.net problem 89 Read and convert roman numerals. --> Slow but sure solution. By Christian Stigen Larsen, http://csl.sublevel3.org Public domain, 2012 The only rule you need to know: ***Numerals must be arranged in descending order of size.*** The law: Only I, X, and C can be used as the leading numeral in part of a subtractive pair. I can only be placed before V and X. X can only be placed before L and C. C can only be placed before D and M. Try to display numbers using minimum number of letters. """ import sys from itertools import permutations values = { 'I': 1, 'V': 5, 'X': 10, 'L': 50, 'C': 100, 'D': 500, 'M': 1000, } numerals = { 1: 'I', 5: 'V', 10: 'X', 50: 'L', 100: 'C', 500: 'D', 1000: 'M', } def value(char): global values return values[char.upper()] def from_string(s): """Convert roman numeral to integer. >>> from_string("MCMLXIV") 1964 >>> from_string("MCCCCCCVI") 1606 >>> from_string("MDCVI") 1606 """ ret = 0 s = s.translate(None, " ") # remove spaces num = list(reversed([value(c) for c in s])) prev = 0 for v in num: if v >= prev: ret += v prev = v else: ret -= prev ret += (prev-v) prev = v return ret def inverted(d): return dict(zip(d.values(), d.keys())) def to_string_bad(n): # note: this does not produce tightest output # start with biggest values s = "" while n: for (v, c) in reversed(sorted(inverted(values).iteritems())): if v <= n: n -= v s += c break return s """ Tenker sånn: 1964 = 1000+900+60+4 og = M CM LX IV = MCMLXIV Problemet er dette: 10004 = 10000 = 10*1000, så så lenge vi har verdi som er 1000 eller over, så kjør på """ def expand(n): "E.g. 1964 ==> [1000,900,60,4]" v = [] exp = len(str(n)) for ch in str(n): exp -= 1 v.append(int(ch)*10**exp) return v def to_char(n): "E.g. 1000 ==> M, 900 => CM, 60 => LX, 4 => IV" if n == 0: return "" NUMS = numerals.values() ret = [] # Brute-force: Try all four-letter combos for a in NUMS: for b in NUMS: for c in NUMS: for d in NUMS: if n == from_string(d): ret.append(d) if n == from_string(c+d): ret.append(c+d) if n == from_string(b+c+d): ret.append(b+c+d) if n == from_string(a+b+c+d): ret.append(a+b+c+d) return min([(len(s), s) for s in ret])[1] raise Exception("ERROR: Couldn't translate to_char: " + str(n)) #for a in numerals.values(): # num = from_string(a) # if num == n: # return a # for b in numerals.values(): # num = from_string(a+b) # if num == n: # return a+b def to_string(n): try: return "".join(map(to_char, expand(n))) except Exception, e: print "Error translating to string:", n print e sys.exit(0) saved_bytes = 0 n = 0 with open("roman.txt") as f: for line in f.readlines(): line = line.strip() num = from_string(line) if num == 0: print "Warning: 0 from", line new = to_string(num) if len(new) < len(line): saved_bytes += len(line)-len(new) n += 1 print n, "Input:", line, "==>", num, "==>", new, "diff: ", len(line)-len(new) print "Saved in total %d bytes" % saved_bytes
b1365138baae837056bd89bb165a1240179f8aaa
jacobbieker/NUR
/two_e.py
4,495
4
4
import numpy as np import matplotlib.pyplot as plt def two_e(rand_gen, A, a, b, c): def sat_equation(r, A, num_satallites=100): return A * num_satallites * (r / b) ** (a - 3) * np.exp(-(r / b) ** c) # Since we are integrating the sat_equation in 3D spherical integral, but only a dependence on r, integral # corresponds to sat_equation times dV, or the derivative of the volume of the sphere, so 4 * pi * r^2 def three_d_integral(r, A, num_sats): volume_of_sphere = 4 * np.pi * r ** 2 return volume_of_sphere * sat_equation(r, A, num_sats) def random_sample(func, xmin, xmax, ymin, ymax, num_samples): """ Generates random positions that follow the profile of equation 2 To sample the distribution, rejection sampling is used. The reason for this is the ease of implementing it for this problem, since only have to check if the random sample is less than the p(x) given in the handin p(x) in this case is n(x)*4*pi*x^2 dx / N_sat = (4*pi*A*b^3*(x/b)^a*exp(-(x/b)^c)*(a-c*(x/b)^c-1)/(x^2)) The N_sat cancels with the one in the n(x) :return: """ inputs = [] outputs = [] while len(outputs) < num_samples: # While the number of accepted values is less than the number of required samples x = next(rand_gen) * (xmax - xmin) + xmin # Generate random number for X y = next(rand_gen) * (ymax - ymin) + ymin # Generate random for Y as well if y <= func(x, A, 1): # The check for if y <= p(x), if not, its rejected, else, accepted inputs.append(x) outputs.append(y) return inputs, outputs # Now need to create random phi and theta for the given r values def create_halo(number_of_satallites): rand_sample_x = random_sample(three_d_integral, 0, 5, 0, 5, number_of_satallites)[0] # Now randomize the phi and thetas phi_sample = [] theta_sample = [] for _ in rand_sample_x: phi_sample.append((2 * np.pi * next(rand_gen))) # Since phi can be between 0 and 2pi radians theta_sample.append(np.pi * next(rand_gen)) # Since theta can be between 0 and pi radians return rand_sample_x, phi_sample, theta_sample # Given N(x) def n(x): return three_d_integral(x, A, 100) # Need to Generate 1000 Halos Now log_bins = np.logspace(-4, 0.69897000433, 21) # Need 21 for the end of the bins, goes from 1e-4 to 5 in logspace def create_haloes(number_of_haloes): """ Creates a set number of haloes with 100 satellites each :param number_of_haloes: :return: """ haloes = [] radii = [] for i in range(number_of_haloes): r, p, t = create_halo(100) haloes.append([r, p, t]) radii.append(r) radii = np.asarray(radii) radii = np.concatenate(radii) # This makes the radii a single length list, for ease of use with binning return haloes, radii def calc_avg_satellites_per_bin(bin_values, bins, num_haloes): """ Divide bin values by width of bins, then by number of haloes used to create it Gives average number of satellites per bin :param bin_values: :param bins: :return: """ new_averages = [] for index, element in enumerate(bin_values): avg_per_halo = element / num_haloes # Divide by number of haloes to get average per halo avg_per_bin_width = avg_per_halo / ( bins[index + 1] - bins[index]) # Divide by bin width to normalize for bin width new_averages.append(avg_per_bin_width) return np.asarray(new_averages) haloes, radii = create_haloes(1000) bin_values, bins, _ = plt.hist(radii, bins=log_bins) # Gets the bin values for the halo plt.cla() new_bin_values = calc_avg_satellites_per_bin(bin_values, bins, 1000) plt.title("Log-Log of N(x)") plt.xscale("log") plt.yscale("log") plt.ylabel("Log(Number of Satellites)") plt.xlabel("Log(X (R/R_vir))") plt.plot(np.arange(1e-4, 5, 0.001), n(np.arange(1e-4, 5, 0.001)), 'r', label='N(x)') plt.hist(np.logspace(-4, 0.69897000433, 20), weights=new_bin_values, bins=log_bins, label="Haloes") plt.legend(loc='best') plt.savefig("./plots/1000_haloes.png", dpi=300) plt.cla() return haloes, bin_values, log_bins
e0c85d445a0dafc70b7b31f961ccee0e3556797e
ruozhizhang/leetcode
/problems/sliding_window/Constrained_Subset_Sum.py
1,443
3.78125
4
''' https://leetcode.com/problems/constrained-subset-sum/ Given an integer array nums and an integer k, return the maximum sum of a non-empty subset of that array such that for every two consecutive integers in the subset, nums[i] and nums[j], where i < j, the condition j - i <= k is satisfied. A subset of an array is obtained by deleting some number of elements (can be zero) from the array, leaving the remaining elements in their original order. Example 1: Input: nums = [10,2,-10,5,20], k = 2 Output: 37 Explanation: The subset is [10, 2, 5, 20]. Example 2: Input: nums = [-1,-2,-3], k = 1 Output: -1 Explanation: The subset must be non-empty, so we choose the largest number. Example 3: Input: nums = [10,-2,-10,-5,20], k = 2 Output: 23 Explanation: The subset is [10, -2, -5, 20]. Constraints: 1 <= k <= nums.length <= 10^5 -10^4 <= nums[i] <= 10^4 ''' ''' Algorithm: similar idea to Sliding Window Maximum ''' from collections import deque class Solution: def constrainedSubsetSum(self, nums: List[int], k: int) -> int: res = float('-inf') q = deque() for i in range(len(nums) - 1, -1, -1): cur = nums[i] while q and q[0][0] > i + k: q.popleft() if q and q[0][1] > 0: cur += q[0][1] while q and q[-1][1] <= cur: q.pop() q.append((i, cur)) res = max(res, cur) return res
835b83e6aae42ed5a4e0175fe37686557325bee4
pvvishnu557/sum-of-the-digits-in-the-number
/sum of digits.py
127
3.9375
4
k=int(input("enter the number:")) sum=0 while(k>0): sum=sum+k%10 k=k//10 print("sum of the digits=",sum)
a44349e2fb7f0f29e05d6dffed3145503684e486
matthewelwell/adventofcode2020
/15.py
583
3.765625
4
import typing from utils.day15.game import Game def part1(data: str) -> typing.Union[str, int]: starting_numbers = list(int(number) for number in data.split(",")) game = Game(starting_numbers) results = game.play(to=2020) return list(results)[-1] def part2(data: str) -> typing.Union[str, int]: # TODO: there must be a more optimal way of doing this # - this code takes > 1m to run starting_numbers = list(int(number) for number in data.split(",")) game = Game(starting_numbers) results = game.play(to=30000000) return list(results)[-1]
cfb0cac2a3acc2caa3b1a63670b7f1e67ae03043
asen-krasimirov/Python-OOP-Course
/Graphic Timer/main.py
580
3.671875
4
from time import sleep from timer import Timer import os import pyfiglet # time format = hh.mm.ss/mm time = input('Enter time (in format hh.mm.ss or in mm): ') if time.count('.') == 0: timer = Timer.from_minutes(int(time)) else: timer = Timer.from_string(time) clear = os.system('cls') while True: if timer.is_finished(): os.system('cls') print(pyfiglet.figlet_format(" Time is up!", font="doh")) # Printing- 'The time is up!' input() break os.system('cls') timer.pass_one_second() print(timer.time) sleep(1)
d4d6fc20e95b50201e85ab2ffd39eebcdeadcb43
dburger4/PythonProgrammingExercises
/Homework 1/poundSignPrint.py
549
4.09375
4
################ # Author: Daniel Burger # Date: 2/23/2019 # This program draws a patter of pairs of pound signs that have # more spaces inbetween them the further down you go ################# NUM_LINES = 9 # number of lines the code will print for i in range(NUM_LINES): print('#', end='') #prints the first pound sign, always first charcter each line for j in range (i): print(' ', end='') #prints as many spaces as whatever row it is in (starting with row 0) print('#') #prints last pound sign, always last character on each line
6ccc88651f97f4db0aace1f18ebf1462a2b4c637
mitem9106/Algorithm-Practice
/linearSearch.py
421
3.953125
4
def linearSearch(array, x): for i in range(len(array)): if int(array[i]) == int(x): return i return -1 def main(): array = [88, 40, 10, 150, 34, 55, 20, 111] print("Search for: ") x = int(input()) result = linearSearch(array, x) if result == -1: print("Element x is not present in array[].") else: print("Element x is present at index %s" %(result))
540cfcf034daafcf70d03bdd974282e19e7a7d61
bysr/untitled
/Project/function/recursionFun.py
585
3.84375
4
# 递归函数,比如阶乘算法 import sys sys.setrecursionlimit(1500) # set the maximum depth as 1500 def fact(n): if n == 1: return 1 else: return n*fact(n-1) print(fact(1000)) def fact(n): return fact_item(n, 1) def fact_item(num, produce): if num == 1: return produce return fact_item(num-1, num*produce) print(fact(500)) def fact(n): return fact_iter(1, 1, n) def fact_iter(product, count, max): if count > max: return product return fact_iter(product * count, count + 1, max) print(fact(1000))
6af543ba08666861778bbf747b6e71d0bed132eb
johnklee/algprac
/hackerrank/implementation/medium/bigger-is-greater.py
1,629
3.5625
4
#!/usr/bin/env python3 import math import os import random import re import sys def swap(w, i, j): w[i], w[j] = w[j], w[i] # Complete the biggerIsGreater function below. def biggerIsGreater(w): #print('w={}'.format(w)) wi = list(map(lambda e: ord(e), w)) wi_len = len(wi) for i in range(1, wi_len): #print("Check i={}:{}".format(-i, w[-i])) for j in range(i+1, wi_len+1): #print("\tj={}:{}".format(-j, w[-j])) if wi[-j] < wi[-i]: swap(wi, -i, -j) bt_list = wi[-j+1:] hd_list = wi[:-j+1] #print('\tbt_list={}'.format(bt_list)) #print('\thd_list={}'.format(hd_list)) bt_list = sorted(bt_list) return ''.join(list(map(chr, hd_list+bt_list))) return 'no answer' def loadTC(n): tc_list = [] aw_list = [] pn = __file__.split('.')[0] with open('{}.t{}'.format(pn, n), 'r') as fh: fh.readline() for line in fh: line = line.strip() tc_list.append(line) with open('{}.a{}'.format(pn, n), 'r') as fh: for line in fh: line = line.strip() aw_list.append(line) return (tc_list, aw_list) # Test #print("{}".format(biggerIsGreater('dkhc'))) import unittest class FAT(unittest.TestCase): def setUp(self): pass def test_0(self): tc_list, aw_list = loadTC(0) for tc, aw in zip(tc_list, aw_list): rel = biggerIsGreater(tc) self.assertEqual(aw, rel, 'TC={}: Exp={}; Rel={}'.format(tc, aw, rel))
87fedbdd9642ba5bce5eadbec2cfef8c73000eb4
Andrew1707/Group-Adventure
/run.py
341
3.640625
4
from player import player from room import room from initialize import * tandrew = player("Tandrew", "Noob") caleb = player("Caleeb", "boss") kitchen.enter(caleb) def run(): resp = input("Where do you want to go? ") for room in caleb.location.adjacent: if resp == room.name: room.enter(caleb) run() run()
4172681fe102671deceed0f096e803668f49cf41
ash2osh/Algorithmic-Toolbox
/week2_algorithmic_warmup/6_last_digit_of_the_sum_of_fibonacci_numbers/fibonacci_sum_last_digit.py
1,212
3.875
4
# Uses python3 import sys def fibonacci_sum_naive(n): if n <= 1: return n previous = 0 current = 1 sum = 1 for _ in range(n - 1): previous, current = current, previous + current sum += current return sum % 10 def test_fibonacci_sum(n): for i in range(1, n + 1): print(i, '-->', fibonacci_sum_naive(i), ' === ', fibonacci_sum(i)) def calc_fib(n): if n <= 1: return n previous = 0 current = 1 for _ in range(n - 1): previous, current = current, previous + current return current def fibonacci_sum_slow(n): if n <= 1: return n total = 1 for i in range(2, n + 1): total += calc_fib(i % 60) % 10 return total % 10 # must calc this in less than 1 sec 832564823476 def fibonacci_sum(n): if n <= 1: return n total = 1 mod = n % 60 if mod == 0: return 0 for i in range(2, mod + 1): total += calc_fib(i) % 10 return total % 10 if __name__ == '__main__': # input = sys.stdin.read() n = int(input()) test_fibonacci_sum(n) # print(fibonacci_sum(n)) # print(fibonacci_sum_naive(n)) # print(fibonacci_sum(n))
cb9d147e0988a3684bd3b12f9ff92736a8bdaeee
wz1990911/w
/11day/01-for循环插入数.py
80
3.546875
4
list1 = [] for i in range(0,101): if i% 2 != 0: list1.append(i) print(list1)
e5fab826d23740f7c3d80f64de9a358cfa904662
Chidalu567/networking
/reverseshell/server.py
5,444
3.78125
4
import socket import sys import threading import queue '''First i need to create a thread that can preform two actions(listen&acceptingconnections,sending commands)''' number_of_jobs=2; #the number of actions i want to carry out job_to_do=[1,2]; #(1) is for listen and accept while (2) is for sending commands queue=queue.Queue(); all_connections=[]; #python list declration for storing connections all_addresses=[]; #python list declration for storing addresses #create the socket object def create_socket(): global s global port global host s=socket.socket(); #create a socket object port=9999; #port number host=''; #ip address of the system #bind address to one end of the socket and listen for connections def bind_socket(): print('Binding port number :> '+str(port)); s.bind((host,port)); #bind the address to the end of the socket s.listen(5); #listen for connections '''Here we accept connections from the client and also close connections if nthe server is been restarted''' #delete all existing address and connections is server.py file is restarted def accept_connections(): #here we delete connections if server is restarted for c in all_connections: c.close(); #close all connections if server is restarted del all_addresses[:]; #delete all address del all_connections[:]; #delete all connections while True: conn,address=s.accept(); #accept connection from client s.setblocking(1); #prevent connection timeout all_connections.append(conn); #append conn to list all_addresses.append(address); #append address to list print('Connections established :> '+str(address[0])); ''' We want to create a custom interactive shell named turtle that does thesecond thread functions 1)list all connections 2)select from various client 3)send commands ''' def start_mechatron(): while True: cmd = input('Mechatron:>'); # get user input if cmd=='list': list_connections(); #function call elif 'select' in cmd: conn=get_target(cmd); #function call to get selected client connection if conn is not None: #if connection is not false send_command_to_the_selected_user(conn); #function call to send commands to selected user else: print('Command is not recognized'); #This is where we list all active connections and delete in-active connections def list_connections(): results=' '; #this is where we store all id,address and port of a client for i,conn in enumerate(all_connections): #check for dead connections try: conn.send(str.encode('network testing')); #send byte format to remote system conn.recv(20000); #recieve message from client #if the client is in-active it then moves to th except action except: del all_connections[i]; #delete the connections del all_addresses[i]; #delete the in active address continue results=str(i)+' '+str(all_addresses[i][0]+' '+str(all_addresses[i][1])); print('-------Clients-------'+'\n'+results); #show this to the server when list_connections function is called #e.g #-------Clients------- #1 192.334.344 9999 #2 123.345.567 8888 def get_target(cmd): #function definition '''Here we are going to replace select with and emty string and return the selected connection''' try: target = cmd.replace('select',' '); # replace the select word with empty string leaving only the number id=int(target); #convert to integer conn = all_connections[id]; # slice for the selected connection print('You are connected to :' + str(all_addresses[id][0])); print(str(all_addresses[id][0]) + '::>', end=''); return conn; except: print('Selection is invalid '); return None; def send_command_to_the_selected_user(conn): #function definition while True: cmd=input(''); #get user input if cmd=='quit': conn.close(); #close connections s.close(); #close socket sys.exit() #exit cmd if len(str.encode(cmd))>0: conn.send(str.encode(cmd)); #send encoded command to the client client_response=conn.recv(20000).decode('utf-8'); #get client output print(client_response,end=''); #show client response #create workers def create_workers(): for _ in range(number_of_jobs): t=threading.Thread(target=work); #create a thread object t.daemon=True; #tells the thread to end when the program ends t.start(); #start thread def work(): while True: x=queue.get(); #get value in queue if x==1: create_socket(); #function call bind_socket(); #function call accept_connections(); #function call if x==2: start_mechatron(); #function call to start shell queue.task_done(); #end queue # create jobs for workers def create_jobs(): for x in job_to_do: queue.put(x); #add the value in list to the queue queue.join(); #join the values together if __name__=='__main__': create_workers(); create_jobs();
0f0c6b6f55233d0bed91142fadd87f965dc30633
code-harvey/MicroEarthQuake
/phasepapy/associator/func1D.py
1,464
3.515625
4
from .tt_stations_1D import * def tt_km(session, d_km): """ tt_km(session,d_km) Look up travel time from tt_table for the closest distance to entered value stored in the tt_table database. km_difference is the distance difference between the stored value returned in the lookup and the distance requested. session is the database connection Returns the TTtable_object,km_difference """ min = session.query(TTtable1D).filter(TTtable1D.d_km <= d_km).order_by(TTtable1D.d_km.desc()).first() # print min max = session.query(TTtable1D).filter(TTtable1D.d_km >= d_km).order_by(TTtable1D.d_km).first() # print max.d_km if abs(min.d_km - d_km) <= abs(max.d_km - d_km): return min, abs(min.d_km - d_km) else: return max, abs(max.d_km - d_km) def tt_s_p(session, s_p): """ tt_s_p(session,s_p) Look up the distance for an S-P travel time observation and return the closest value stored in the travel-time table Returns the closest tt_object,s_p_difference """ # print 's_p:',s_p min = session.query(TTtable1D).filter(TTtable1D.s_p <= s_p).order_by(TTtable1D.s_p.desc()).first() # print 'min.s_p:',min.s_p max = session.query(TTtable1D).filter(TTtable1D.s_p >= s_p).order_by(TTtable1D.s_p).first() # print 'max.s_p:',max.s_p if abs(min.s_p - s_p) <= abs(max.s_p - s_p): return min, abs(min.s_p - s_p) else: return max, abs(max.s_p - s_p)
d5e427fed5e731a562c70f2ca6b348e3a55c51a9
vaskocs/project
/2.py
398
3.65625
4
def convert(list,b1,b2): number=0 helyiertek=1 for i in range(len(list)-1,-1,-1): if list[i]>=b1: print("Nem jó szám") return None number+=list[i]*helyiertek helyiertek*=b1 list2=[] while number!=0: list2.append(number%b2) number//=b2 list2.reverse() return list2 print(convert([1,9],8,2))
e6209333c52a7830a10af07278980cf39af72bae
apri-me/python_class00
/Session6/assignment2.py
556
3.984375
4
import prettytable n = int ( input("Number of employees: ") ) employees = [] for i in range(n): emp = input("Emplyee number {}: ".format(i + 1)) employees.append(emp) hours = [] for i in range(n): h = float ( input("Work hours of Employee {}: ".format(i + 1))) hours.append(h) salary_per_hour = int ( input("How much you pay per hour? ") ) my_dict = dict (zip (employees, hours) ) pt = prettytable.PrettyTable( ["Name", "Hours", "Salary"] ) for name, h in my_dict.items(): pt.add_row( [name, h, h * salary_per_hour] ) print(pt)
d41eb4ec0708076a61561be19175d13bfd46d352
julia-neme/project-euler
/problem_5.py
1,195
3.65625
4
""" 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ def is_prime(N): i = 2 ans = True while i*i <= N: if N % i == 0: ans = False break else: i += 1 return ans def get_largest_exp(N_max, N): import numpy as np max_exp = int(np.log(N_max)/np.log(N)) return max_exp def eratosthenes_sieve(N_max): import numpy as np serie = np.arange(1, N_max + 1, 1) sieve = [True] * len(serie) i = 1 while i < len(serie): if sieve[i]: if is_prime(serie[i]): max_exp = get_largest_exp(np.max(serie), serie[i]) j = 2 while j <= max_exp: sieve[serie[i]**j - 1] = False j += 1 else: sieve[i] = False i += 1 return serie[1:][sieve[1:]] primos = eratosthenes_sieve(10) exp = [] for i in primos: exp.append(get_largest_exp(10, i)) primos_elevados = primos**exp ans = 1 for x in primos_elevados: ans = ans*x print("El menor nro. positivo multiplo de todos los nros. del 1 al 20 es {0}".format(ans))
e94c423add2747b54775629dfa3b5032dcd964b3
fabnonsoo/Matplotlib
/Analyzing_CSV_Data/csv_analysis1.py
804
3.671875
4
# Analyzing Data Loaded from CSV File: Using an 'import csv' module # NB: 'from collections import Counter' is used when a data is too large to loop through.... import csv import numpy as np from collections import Counter from matplotlib import pyplot as plt plt.style.use('fivethirtyeight') # Using csv: with open('sodata_19.csv') as csv_file: csv_reader = csv.DictReader(csv_file) row = next(csv_reader) # Prints only the first row of csv_reader print(row) # O/p the full dict values of the 1st row of the csv file print(row['LanguageWorkedWith']) # O/p only the 'LanguageWorkedWith' dict values of 1st row... print(row['LanguageWorkedWith'].split(';')) # Gives a Python list of the 'LanguageWorkedWith'
6c52aba1745a56128980a30f3d8871386e654193
blackhumdinger/LPTHW
/LPTHW_EXER/13.py
1,368
3.59375
4
# -*- coding: utf-8 -*- """ Created on Fri Feb 22 08:35:03 2019 @author: Pranav """ # EXERCISE 13 (PARAMETERS, UNPACKING AND VARIABLES #from sys import argv #script, first, second, third = argv #the line above unpacks the variables assigned rather than hoding the argumrnts #it gets assigned to four variables and "TAKE WHATEVERS IN THE ARGV AND UNPACK IT AND ASSIGN IT TO THE VARIABLES" #print"the script is called", script #print "this is your firt variable", first #print"your second variable is ", second #print"your third variable is ", third #the argv is the argument varibale you pass to tne #python script the argv is argument varibale a very standard name im programming thay you'll find in many languages #EXERCISE 14 PROMPTING AND PASSING from sys import argv script, user_name, ewww = argv prompt ='HUH?' print "Hi! %s thos is %s script" % (user_name,script) print "I'd like to ask you a few questions." print"DO you like me %s" % user_name likes = raw_input('prompt') print"where do you live %s, %s i judge you" % (user_name, ewww) lives = raw_input('prompt') print"what kinda rig do you have?" computer = raw_input(prompt) print """ Alright so now you've declared that %r abput liking me you live in %r. Not sure where that is, and you have a %r computer... naaaice!!! """% (likes, lives, computer)
5bc7cf74faa7c270117104fa2196b5fa8595b2ee
spudtrooper/photostitcher
/photostitcher.py
1,831
3.515625
4
"""Stitches a directory of images together into one image.""" import argparse import os import logging import math import sys from PIL import Image def Stitch(image_dir='images', output_image='output.jpg', images_per_row=6): images = [Image.open(os.path.join(image_dir, img)) for img in os.listdir(image_dir) if img != '.DS_Store' ] if not images_per_row: images_per_row = int(math.floor(math.sqrt(len(images)))) image_width = images[0].size[0] image_height = images[0].size[1] logging.info('Using image_width, image_height = (%d,%d)' % (image_width, image_height)) width = images_per_row * image_width height = (len(images) / images_per_row) * image_height logging.info('New image width, height = (%d,%d)' % (width,height)) new_im = Image.new('RGB', (width, height)) for i, im in enumerate(images): row = i / images_per_row col = i % images_per_row x = col * image_width y = row * image_height logging.info('row=%d col=%d x=%d y=%d', row, col, x ,y) new_im.paste(im, (x, y)) new_im.save(output_image) logging.info('Output to %s', output_image) def main(argv): logging.basicConfig(level=logging.INFO) parser = argparse.ArgumentParser() parser.add_argument('--images', help='Directory containing images') parser.add_argument('--output', help='Path of the output file') parser.add_argument('--images_per_row', default=0, nargs='?', type=int, help=('Set this to override the number of images per row. ' 'If not specified it defaults to ' 'floor(sqrt(len(images)))')) args = parser.parse_args() Stitch(args.images, args.output, args.images_per_row) if __name__ == '__main__': main(sys.argv)
5751ee6acd98c6cddb3d5217c9719e62f6c8dc15
qaswedf/test
/c_to_f.py
126
3.609375
4
c = input ("請輸入換算的溫度為攝式:") c = int(c) f = c * 9 / 5 + 32 print('你轉換出來的溫度為華式', f)
8b3006b08674d70cb7466fec085d4ff7b7e7b67a
jakehoare/leetcode
/python_1_to_1000/724_Find_Pivot_Index.py
1,163
4.03125
4
_author_ = 'jake' _project_ = 'leetcode' # https://leetcode.com/problems/find-pivot-index/ # Given an array of integers nums, write a method that returns the "pivot" index of this array. # We define the pivot index as the index where the sum of the numbers to the left of the index is equal to the sum of # the numbers to the right of the index. # If no such index exists, we should return -1. If there are multiple pivot indexes, you should return the left-most # pivot index. # Iterate over nums, maintaining sums of left and right sides relative to pivot. Remove num from right, then check # whether sides have equal sums, then add num to left. # Time - O(n) # Space - O(1) class Solution(object): def pivotIndex(self, nums): """ :type nums: List[int] :rtype: int """ left, right = 0, sum(nums) # sums of left and right arrays relative to pivot for i, num in enumerate(nums): right -= num if left == right: return i left += num # doing this last handles i == 0 better than adding previous before check return -1
1ca3c5bf9a9ee216c43d58ffaa52f4f5b1817442
masontmorrow/Data-Structures
/heap/heap.py
2,670
3.8125
4
from math import floor class Heap: def __init__(self): # storage starts with an unused 0 to make # integer division simpler later on self.storage = [0] self.size = 0 def insert(self, value): self.size += 1 self.storage.append(value) self._bubble_up(self.size) def delete(self): if self.size == 0: return elif self.size == 1: self.size -= 1 deleted = self.storage[1] self.storage.pop() return deleted elif self.size == 2: self.size -= 1 last_num = self.storage[-1] deleted = self.storage[1] self.storage = [0, last_num] self._sift_down(1) return deleted else: self.size -= 1 last_num = self.storage[-1] deleted = self.storage[1] self.storage = self.storage[:1] + [last_num] + self.storage[2:-1] self._sift_down(1) return deleted def get_max(self): if self.size > 0: return self.storage[1] else: return 0 def get_size(self): return self.size def _bubble_up(self, index): parent_index = floor(index/2) parent = self.storage[parent_index] child_index = index child = self.storage[child_index] if parent == 0: return if parent > child: return else: self.storage[parent_index] = child self.storage[child_index] = parent return self._bubble_up(parent_index) def _sift_down(self, index): parent_index = index parent = self.storage[parent_index] child_left_index = 2*index child_right_index = 2*index + 1 if child_left_index > self.size: #no children to test = end of heap return elif child_right_index > self.size: #left child to test only child_left = self.storage[child_left_index] if parent < child_left: self.storage[parent_index] = child_left self.storage[child_left_index] = parent return else: return else: #test both children child_left = self.storage[child_left_index] child_right = self.storage[child_right_index] if parent > child_left and parent > child_right: return else: if child_left > child_right: if parent < child_left: self.storage[parent_index] = child_left self.storage[child_left_index] = parent return self._sift_down(child_left_index) else: return else: if parent < child_right: self.storage[parent_index] = child_right self.storage[child_right_index] = parent return self._sift_down(child_right_index) else: return
b5c012032e037a35df29a9eec250cc5074b12b14
hrusikeshnandy/python
/if.py
231
4.09375
4
num1 = int(input("Enter the first number: ")) num2 = int(input("Enter teh second number: ")) if num1 > num2: print("number 1 is greater") elif num1==num2: print("numbers are equal") else: print("number 2 is greater")
66a33a1abcd607531b5461358db0d45f491d40f6
ageraldo1/Python-bootcamp
/regular_expressions/sample_re.py
1,337
3.875
4
import re print (re.search('ORA-', 'this is a sunny day')) patterns = ['term1', 'term2'] text = 'This is a string with term1, but not with the other term' for pattern in patterns: print (f"Searching for {pattern} in: \n {text}") # check for match if re.search(pattern, text): print ("\nMatch found\n") else: print ("\nMatch not found\n") match = re.search(patterns[0], text) print (match) print (match.start()) print (match.end()) #2 split_term = "@" phrase = "What is your email, is it hello@gmail.com?" print (re.split(split_term, phrase)) print (phrase.split(split_term)) #3 print (re.findall('match', 'Here is one match, here is anoter match')) #4 def multi_re_find(patterns, phrase): for pattern in patterns: print (f"Searching the phrase using the re-check {pattern}") print (re.findall(pattern, phrase)) print ("\n") test_phrase = 'sdsd..sssddd...sdddsddd...dsds...dsssss...sdddd' test_patterns = ['sd*', # s followed by zero or more d's 'sd+', # s followed by one or more d's 'sd?', # s followed by zero or one d's 'sd{3}', # s followed by three d's 'sd{2,3}', # s followed by two to three d's ] multi_re_find(test_patterns, test_phrase)
1a77ebcb3f67a9d0500d799e6e1112c2be5426ac
shanekang/pre-education
/quiz/pre_python_18.py
491
3.6875
4
"""18. 확장자가 포함된 파일 이름이 담긴 리스트에서 확장자를 제거하고 파일 이름만 추가 리스트에 저장하시오. file = ['exit.py',hi.py','playdata.hwp',intro.jpg'] 결과: file = ['exit',hi','playdata',intro'] 예시 <입력> print(new_list) <출력> ['exit', 'hi', 'playdata', 'intro'] """ file = ['exit.py','hi.py','playdata.hwp','intro.jpg'] new_list = file[0][0:4], file[1][0:2], file[2][0:8], file[3][0:5] print(new_list)
2ec5a6540e18f23f5e44c37c777e2a4c306f492b
tariksetia/Algx-Practice
/tree/node.py
456
3.5
4
from queue import Queue class Node: def __init__(self, data=None, left=None, right=None): self.data, self.left, self.right = data, left, right def __repr__(self): return str(self.data) def __str__(self): return str(self.data) def __bool__(self): return True if self.data is not None else False @property def leaf(self): return False if (self.right and self.left) else True
1c173a869c41bded6297c7287320283d605f695b
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/series/77379993a1cf4730a1d5b70daa8fa818.py
220
3.53125
4
def slices(numbers, length): if length == 0 or length > len(numbers): raise ValueError numbers = [int(number) for number in numbers] return [numbers[i:i+length] for i in range(len(numbers)-length+1)]
6028b5ba85e7261b0946051c1b10272886d8fd43
Macedo3/Curso-IME-USP-parte-1
/curso/quadrado.py
121
3.546875
4
l = int((input)('Qual é a medida do quadrado? ')) x = l * 4 y = l**2 print("perímetro: {} - área: {}".format(x, y))
1f5bb7f75412341343588bbaf215e56a6e430190
AdamZhouSE/pythonHomework
/Code/CodeRecords/2628/47937/306970.py
384
3.671875
4
a=input() b=input() c=input() d=input() #print(a) #print(b) #print(c) #print(d) if(a=="2" and b=="0 1" and c=="0 5" and d=="5 1"): print(6) print(1129) elif(a=="2" and b=="0 1" and c=="0 5" and d=="5 0"): print(6) print(1129) elif(a=="2" and b=="0 0" and c=="0 5" and d=="5 0"): print(6) print(1129) else: print(a) print(b) print(c) print(d)
1798e12359a6d675f6735e92af0f13f40312bcb0
spartantri/wafme
/tail.py
2,539
4.15625
4
#!/usr/bin/env python ''' Python-Tail - Unix tail follow implementation in Python. python-tail can be used to monitor changes to a file. Example: import tail # Create a tail instance t = tail.Tail('file-to-be-followed') # Register a callback function to be called when a new line is found in the followed file. # If no callback function is registerd, new lines would be printed to standard out. t.register_callback(callback_function) # Follow the file with 5 seconds as sleep time between iterations. # If sleep time is not provided 1 second is used as the default time. t.follow(s=5) ''' # Author - Kasun Herath <kasunh01 at gmail.com> # Source - https://github.com/kasun/python-tail import os import sys import time class Tail(object): ''' Represents a tail command. ''' def __init__(self, tailed_file): ''' Initiate a Tail instance. Check for file validity, assigns callback function to standard out. Arguments: tailed_file - File to be followed. ''' self.check_file_validity(tailed_file) self.tailed_file = tailed_file self.callback = sys.stdout.write def follow(self, s=1): ''' Do a tail follow. If a callback function is registered it is called with every new line. Else printed to standard out. Arguments: s - Number of seconds to wait between each iteration; Defaults to 1. ''' with open(self.tailed_file) as file_: # Go to the end of file file_.seek(0,2) while True: curr_position = file_.tell() line = file_.readline() if not line: file_.seek(curr_position) time.sleep(s) else: self.callback(line) def register_callback(self, func): ''' Overrides default callback function to provided function. ''' self.callback = func def check_file_validity(self, file_): ''' Check whether the a given file exists, readable and is a file ''' if not os.access(file_, os.F_OK): raise TailError("File '%s' does not exist" % (file_)) if not os.access(file_, os.R_OK): raise TailError("File '%s' not readable" % (file_)) if os.path.isdir(file_): raise TailError("File '%s' is a directory" % (file_)) class TailError(Exception): def __init__(self, msg): self.message = msg def __str__(self): return self.message
c19df0ce66369694ad43ba00806ebf24bf788189
ruohoruotsi/pyACA
/pyACA/ToolBlockAudio.py
888
3.59375
4
""" helper function: Creates blocks from given array. This method creates a block only if there is enough input data to fill the block. This means if there isn't enough data to fill the last block then that lst chunk of input data will be discarded. To avoid losing data, you should pad the input with zeros of at least iBlockLength length. Args: afAudioData: 1D np.array iBlockLength: block length iHopLength: hop length Returns: A 2D np.array containing the blocked data of shape (iNumOfBlocks, iBlockLength). """ import numpy as np def ToolBlockAudio(afAudioData, iBlockLength, iHopLength): iNumOfBlocks = np.floor((afAudioData.shape[0] - iBlockLength) / iHopLength + 1).astype(int) if iNumOfBlocks < 1: return np.array([]) return np.vstack([np.array(afAudioData[i*iHopLength:i*iHopLength+iBlockLength]) for i in range(iNumOfBlocks)])
3a6169bc13ec9a1619030133df4a6a1a833b4562
alanxing1122/workspaceU
/random_1225.py
450
4.09375
4
import random def jdstb_game(): computer = random.randint(1,3) player = input("1.剪刀、2.石头、3.布\t请输入对应的数字:") player = int(player) if(player not in [1,2,3]): print("请输入1、2、3") elif(computer == player): print("平局") elif((computer == 1 and player == 3)or(computer == 2 and player == 1)or(computer==3 and player==2)): print("电脑胜") else: print("玩家胜") while(1): jdstb_game()