blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
1f1720189686223a6d8c6dc0a93ea768a6ddbe81
zhaogaofeng/pythonTest
/函数/高级特性.py
598
3.546875
4
from collections import Iterable L = ('Michael', 'Sarah', 'Tracy', 'Bob', 'Jack') print(L[-2:]) L = list(range(100)) print(L[:2:5]) print(isinstance("fd", Iterable)) for i, value in enumerate(L): print(i, value) for x, y in [(2, 3), (4, 5)]: print(x, y) print(range(10)) L = list(range(1, 11)) L = (x * x for x in range(1, 11)) print(L) for l in L: print(l) L1 = ['Hello', 'World', 18, 'Apple', None] L2 = [x.lower() for x in L1 if isinstance(x, str)] print(L2) def fib(max): n,a,b=0,0,1 while n<max: yield b a,b=b,a+b n=n+1 return "done" print(fib(5))
2864b9433004e306bef0ccaa1b3315d330410932
GeorgOhneH/WerbeSkip
/deepnet/layers/activations/leaky_relu.py
603
3.75
4
from deepnet.layers import Layer import numpywrapper as np class LReLU(Layer): """ Leaky ReLU is an activation function It behaves like a layer The shape of the input is the same as the output """ def __init__(self, alpha=0.01): self.z = None self.alpha = alpha def forward(self, z): z[z < 0] *= self.alpha return z def forward_backpropagation(self, z): self.z = z return self.forward(z) def make_delta(self, delta): dz = np.ones_like(self.z) dz[self.z < 0] = self.alpha return delta * dz
236bba6660dbca2eaa34a161b84f14b3260975f5
GeorgOhneH/WerbeSkip
/deepnet/layers/core/fullyconnected.py
2,653
3.828125
4
from deepnet.layers import Layer import numpywrapper as np class FullyConnectedLayer(Layer): """ after https://sudeepraja.github.io/Neural/ weight initializer after http://neuralnetworksanddeeplearning.com/chap3.html The FullyConnectedLayer saves the weights and biases of the layer As the name says it is fully connected, this means that every neuron from the previous layer is connect with every neuron of this layer The biases are from the neurons, which are after the weight connected """ def __init__(self, neurons): """ :param neurons: unsigned int """ self.neurons = neurons self.optimizer = None self.biases = None self.weights = None self.nabla_b = None self.nabla_w = None self.a = None def __str__(self): return "{}: neurons: {}".format(super(FullyConnectedLayer, self).__str__(), self.neurons) def init(self, neurons_before, optimizer): """ Initial the layer Uses Gaussian random variables with a mean of 0 and a standard deviation of 1 :param neurons_before: unsigned int :param optimizer: optimiser of the Optimizer class :return: neurons of layer: unsigned int """ self.biases = np.random.randn(1, self.neurons).astype(dtype="float32") self.weights = np.random.randn(int(neurons_before), self.neurons).astype(dtype="float32") / np.sqrt(int(neurons_before)).astype(dtype="float32") self.optimizer = optimizer return self.neurons def forward(self, a): """Applies a matrix multiplication of the weights and adds the biases """ return a @ self.weights + self.biases def forward_backpropagation(self, a): """ Applies a matrix multiplication of the weights and adds the biases and saves the value for the backpropagation """ self.a = a return self.forward(a) def make_delta(self, delta): """Calculates error and the derivative of the parameters""" self.nabla_b = np.sum(delta, axis=0) self.nabla_w = self.a.T @ delta return delta @ self.weights.T def adjust_parameters(self, mini_batch_size): """Changes the weights and biases after the optimizer calculates the change""" change_w, change_b = self.optimizer.calculate_change(self.nabla_w, self.nabla_b) self.weights -= change_w/mini_batch_size self.biases -= change_b/mini_batch_size def save(self): return [self.weights, self.biases] def load(self, array): self.weights, self.biases = array
044bcaf6563c135f8e58b75cd25ba2e18312dc78
GeorgOhneH/WerbeSkip
/deepnet/layers/activations/tanh.py
528
3.65625
4
from deepnet.layers import Layer import numpywrapper as np class TanH(Layer): """ TanH is an activation function It behaves like a layer The shape of the input is the same as the output """ def __init__(self): self.z = None def forward(self, z): return np.tanh(z) def forward_backpropagation(self, z): self.z = z return self.forward(z) def make_delta(self, delta): z = 1 - self.forward(self.z) ** 2 delta = delta * z return delta
8740ac9f9857af67eda3e8feb4e46919c7b0565a
iiiramal/python-challenge
/PyPoll/.ipynb_checkpoints/main-checkpoint.py
2,525
3.578125
4
# import os import csv #Declare CVS Path csvpath = os.path.join(os.getcwd(),'Python Challenge', 'PyPoll','Resources','election_data.csv') printpath = os.path.join(os.getcwd(),'Python Challenge','PyPoll','Analysis','PollAnalysis.text') with open(csvpath) as csvfile: # CSV reader specifies delimiter and variable that holds contents csvreader = csv.reader(csvfile, delimiter=',') print(csvreader) #print(csvreader) # Read the header row first (skip this step if there is now header) csv_header = next(csvreader) #print(f"CSV Header: {csv_header}") #Declare Variables: Votes to tally totals, candidates as list, Tally as list to count individual candidate votes, and Tally Dictionary to calc Max. Votes = 0 Candidates = [] Tally = [] TallyDict = {} #Loop through csv file to tally votes and create candidate list. for row in csvreader: #Total = Total + int(row[1]) Votes = Votes + 1 Tally.append(row[2]) if row[2] not in Candidates: Candidates.append(row[2]) #declare new variables TallyLoopList = len(Candidates) TallyLoop = len(Tally) printlist = [] #loop through candidate list, looping through tally list to count individual votes for i in range(TallyLoopList): TallyCount = 0 for j in range(TallyLoop): if Tally[j] == Candidates[i]: TallyCount = TallyCount + 1 #Calculate Percent of votes each candidate earned. TallyPercent = "{:.2%}".format(TallyCount/Votes) #Add Candidate, Tally % and Tally Count to list for future printing printlist.append(f'{Candidates[i]}: {TallyPercent} ({TallyCount})') TallyDict[Candidates[i]] = [TallyCount] #Calculate winner and assigning name winnervote = max(TallyDict.items(), key=lambda x : x[1]) winner = winnervote[0] #Print to Terminal print(f'Election Results \n------------------------- \nTotal Votes: {Votes} \n-------------------------') for i in range (len(printlist)): print(printlist[i]) print(f'------------------------- \nWinner: {winner} \n-------------------------') #Print to .text f = open(printpath, 'w') f.write(f'Election Results \n------------------------- \nTotal Votes: {Votes} \n-------------------------') for i in range (len(printlist)): f.write(f'\n{printlist[i]}') f.write(f'\n------------------------- \nWinner: {winner} \n-------------------------')
dadac8975af6f547ec524245aa1e77e941390c76
phramos07/taskminer
/tests/temp/rubens/ldp/utils/graph-generator-narytree.py
601
3.828125
4
#!/usr/bin/python from sys import argv, exit from random import randint if len(argv) != 3: print("%s <arity:int> <height:int>" % (argv[0])) exit() N = int(argv[1]) height = int(argv[2]) count = 0 edges = [] stack = [(0, 0)] while stack: (label, index) = stack[-1] if index == N: stack.pop(); continue count += 1 edges.append((label, count)) stack[-1] = (label, index + 1) if len(stack) < height: stack.append((count, 0)) # Printing number of vertices, of edges, and edges print(count + 1) print(len(edges)) for (u, v) in sorted(edges): print("%d\t%d\t%d" % (u, v, randint(0, 100)))
87470701bf7ac97e3edd933477be0b63e696f424
Kirank8502/typingspeed
/typingspeed.py
3,263
3.5
4
from tkinter import * import random from tkinter import messagebox ##############Root########################### root = Tk() root.geometry('800x600+400+100') root.configure(bg='powder blue') root.title('Typing speed game') words = ['Apple','Time','Really','service','order','Little','small','fight','italian'] ###############functions ##############3 def labelSlider(): global count,sliderwords text = 'Welcome to typing Increaser Game' if(count >= len(text)): count = 0 sliderwords = '' sliderwords += text[count] count += 1 fontLabel.configure(text=sliderwords) fontLabel.after(150,labelSlider) def startGame(event): global score,miss if(timeleft == 60): time() gamePlayDetailLabel.configure(text='') if(wordEntry.get() == wordLabel['text']): score += 1 scoreLabelCount.configure(text=score) #print("score ",score) else: miss += 1 #print("miss ",miss) random.shuffle(words) wordLabel.configure(text=words[0]) #print(wordEntry.get()) wordEntry.delete(0,END) def time(): global timeleft,score,miss if(timeleft>0): timeleft -= 1 timeLabelCount.configure(text=timeleft) timeLabelCount.after(1000,time) else: gamePlayDetailLabel.configure(text='Hit = {} | Miss = {} | Total score = {}'.format(score,miss,score-miss)) dk = messagebox.askretrycancel('notification','For Play Again Click Retry Button') if(dk == True): score = 0 miss = 0 timeleft = 60 timeLabelCount.configure(text=timeleft) wordLabel.configure(text=words[0]) scoreLabelCount.configure(text=score) else: root.destroy() ################# Variables ######################3 score = 0 timeleft = 60 count = 0 sliderwords = '' miss = 0 ##############################Label ################################ fontLabel = Label(root,text='Welcome to typing speed increaser game',font=('times',25,'italic bold'),bg='powder blue',width=40) fontLabel.place(x=10,y=10) labelSlider() random.shuffle(words) wordLabel = Label(root,text=words[0],font=('times',40,'italic bold'),bg='powder blue') wordLabel.place(x=350,y=200) scoreLabel = Label(root,text='Your score : ',font=('times',25,'italic bold'),bg='powder blue') scoreLabel.place(x=10,y=100) scoreLabelCount = Label(root,text=score,font=('times',25,'italic bold'),bg='powder blue') scoreLabelCount.place(x=80,y=170) timerLabel = Label(root,text='Time left : ',font=('times',25,'italic bold'),bg='powder blue') timerLabel.place(x=600,y=100) timeLabelCount = Label(root,text=timeleft,font=('times',25,'italic bold'),bg='powder blue') timeLabelCount.place(x=650,y=170) gamePlayDetailLabel = Label(root,text='Type Word And Hit Enter Button',font=('times',30,'italic bold'),bg='powder blue') gamePlayDetailLabel.place(x=120,y=450) ######################## Entry ####################################### wordEntry = Entry(root,font=('times',25,'bold'),bd=10,justify='center') wordEntry.place(x=250,y=300) wordEntry.focus_set() root.bind('<Return>',startGame) root.mainloop()
4de7a69cc3d91d2145bdc663fe9613cb622064eb
nadjet/keras-bert
/utils/df_utils.py
555
3.671875
4
from pandas import DataFrame import pandas as pd pd.set_option('mode.chained_assignment', None) def one_to_many(df : DataFrame, column_name): columns = sorted(list(set(df[column_name].tolist()))) for column in columns: df[column] = 0 df[column] = df[column].astype(int) for i, row in df.iterrows(): for column in columns: if column == row[column_name]: df.loc[i,column] = 1 return df def get_values(df: DataFrame, column_name): return sorted(list(set(df[column_name].tolist())))
4b5e4c6e23a66cd5510accd02b012d7e5fc6ab25
Kwon1995-2/BC_Python
/chapter3/problem4.py
870
4.0625
4
"""사용자로부터 현재 시간을 나타내는 1~12의 숫자를 입력받는다. 또 "am" 혹은 "pm"을 입력받고 경과 시간을 나타내는 값을 입력 받는다. 이로부터 최종 시간이 몇 시인지 출력하는 프로그램 작성 """ c_hour = int(input("Enter the hour : ")) daynight = str(input("'am' or 'pm' : ")) plus_hour = int(input("How many hours ahead? ")) new_hour = c_hour + plus_hour if daynight == 'am' : if c_hour + plus_hour >= 12 : new_hour -= 12 print('pm '+ str(new_hour)) else : print(daynight+str(new_hour)) elif daynight == 'pm' : if c_hour + plus_hour >= 12 : new_hour -= 12 print('am '+ str(new_hour)) else : print(daynight+" "+str(new_hour)) else : print("Must Input 'am' or 'pm'! Retry") #print(daynight+" "+str(c_hour))
b9e6f248199d58f6f185160a24febe997becf9e0
Kwon1995-2/BC_Python
/chapter4/problem3.py
564
4.46875
4
"""3명 이상의 친구 이름 리스트를 작성하고 insert()로 맨 앞에 새로운 친구 추가 insert()로 3번째 위치에 새로운 친구 추가 append()로 마지막에 친구추가 """ friend = ["A","B","C"] friend.insert(0,"D") # friend.insert(3,"E") print(friend) friend.insert(100, "X") #append와 비슷한 기능 friend.append('a') print(friend) # numli = [1,2,3] # numli.insert(1,17) # print(numli) # numli.append(4) # numli.append(5) # numli.append(6) # numli.insert(3,25) # del(numli[0]) # numli.pop(0) # print(numli)
e2d3b918735e9376cc3e6e71b6c09e2c251afffd
Kwon1995-2/BC_Python
/chapter3/problem10.py
732
3.828125
4
"""반복문과 조건문을 사용해 점수를 계속 입력 받아 90점 이상이면, A 80이상이면 B, 60점 이상이면 C, 40점이상이면 D, 39점 이하이면 F 출력 입력받는 점수가 음수일 때 종료""" while 1: score = int(input("Input the score : ")) if score >= 0 : if score >= 90 : print("A") continue elif score >= 80 : print("B") continue elif score >= 60 : print("C") continue elif score >= 40 : print("D") continue else : print("F") continue else : print("Enter the Positive!") break
238000878a26755b076e7034d6fdf4bda21066d7
Kwon1995-2/BC_Python
/chapter4/problem.4.1.11.py
162
3.859375
4
str1 = str(input("Input the string : ")) for i in range(0, len(str1)): if str1[i] == 'a': print('e',end='') else : print(str1[i],end='') print("\n")
8edcb34c53ab2479656e589eff5e75ba3d463cbc
Kwon1995-2/BC_Python
/chapter5/example5.1.py
2,694
3.953125
4
# def welcome(): # print("hello, everybody!") # welcome() ################################## # def prtStr(str): # print("%s"%str) # str = "Welcome to Python" # prtStr(str) ################################## # def squareArea(s): # # area = s*s # # return area # return s*s # a = squareArea(5) # b = squareArea(7) # print("한변의 길이가 %d인 정사각형의 넓이는 %d"%(5,a)) # print("한변의 길이가 %d인 정사각형의 넓이는 %d"%(7,b)) ################################## # def sum(n): # nsum = 0 # for i in range(1,n+1): # nsum += i # return nsum # a = sum(50) # b = sum(1000) # print(a,b) ################################## # def func1(): # v=10 # print("func1()의 v = %d"%v) # def func2(): # global v # v = 30 # #v=20 # print("func2()의 v = %d"%v) # v = 20 # func1() # func2() ################################## # def prtMesg(message,count=1): # print(message*count) # prtMesg('default') # prtMesg('Hi!',5) # def greet(name, msg="Nothing new?"): # print("Hi! ",name+', '+msg) # greet("Abe") # greet("Bob","Good Morning!") ################################## # def func(a,b=2,c=3): # print('a=',a,'b=',b,'c=',c) # return a+b+c # print(func(4,5)) # print(func(5, c=7)) # print(func(c=10,a=27)) ################################## # def total(*numbers): # sum = 0 # for n in numbers: # sum += n # return sum # print(total(1,2,3)) # print(total(1,2,3,4,5)) ################################## # def dicPresident(**keywords): # for i in keywords.keys(): # print("%s : %d-th president"%(i, keywords[i])) # dicPresident(Kennedy=35, Obama=44, Trump=45) ################################## # def f(arg): # pass # print(help()) ################################## # sum = lambda x, y : x+y # print("정수의 합 : ",sum(10,20)) # print("정수의 합 : ",sum(20,20)) # _sum = lambda x,y : (x+y,x*y) # print(_sum(10,20)) ################################## # def move(n,a,b,c): # if n>0: # move(n-1,a,c,b) # print("Move a disk from %s to %s"%(a,c)) # move(n-1,b,a,c) # move(3,'a','b','c') ################################## # def factorial(n): # if n == 0: return 1 # return n*factorial(n-1) # print(factorial(5)) ################################## print(abs(-2),round(1.4),round(1.5)) print(all([1,-2,3]),all([1,-2,0]),any([1,-1,-5]),any([0,0,0])) print(bin(12),oct(9),hex(125)) print(chr(0x41),ord('A'),eval('1+2*3')) print(enumerate('abc'), list(enumerate('abc')), dict(enumerate('abc'))) print(list(filter(lambda x:len(x)>2,['this','is','a','test']))) a = map(str.upper,'abc') print(list(a)) print(max([1,3,9]), min([1,3,9])) print(repr(b'0011'),repr(11)+"개") a = zip('abc',(1,2,3)) print(a, list(a))
8fe8a7e6c41cd6010b927577beebb0bd78faefef
Kwon1995-2/BC_Python
/chapter4/problem.4.2.1.py
312
3.828125
4
friend = ['A','B',"C"] friend.insert(0,'D') friend.insert(2,"E") friend.append("F") print(friend) num_list = [1,2,3] num_list.insert(1, 17) print(num_list) num_list.append(4) num_list.append(5) num_list.append(6) print(num_list) del(num_list[0]) print(num_list) num_list.sort() num_list[3] = 25 print(num_list)
83dc8cec0c931dc505aa1db24a3c72968e2baafd
Kwon1995-2/BC_Python
/chapter2/[Ex]2_3.py
986
3.796875
4
#부울형 # aVar = True # bVar = False # print(type(aVar)) # a = 1 # b = 2 # c = a > b # print(c) # d= a < b # print(d) #정수형 # intVar = 0 # print(type(intVar)) # intVar = 0b110010 # print(type(intVar)) # intVar = 0o1 # print(type(intVar)) # intVar = 0x1 # print(type(intVar)) #실수형 # fVar = 1.0 # print(type(fVar)) # fVar = 1e0 # print(type(fVar)) # print(100_000.000_0001, 0x_FF_FF, 0o7_777, 0b_1010_1010) #정수표현 # print(0.00_10_27) #실수표현 #복소수형 # a = 1+1j # b=1-1J # print(a+b, a-b, a*b, type(a)) # print(a.real, a.imag, b.real, b.imag) #문자열 # strVar = "test" # print(type(strVar)) # str1 = "single quote ' inside string" # print(str1) # str2 = 'double quote " inside string' # print(str2) # str3 = "double quote \" insdie string" # print(str3) # str4 = "not very long string \ # that spans two lines" # print(str4) # str5 = """ # line1 # line2 # line3 # """ # print(str5) #type error # age=23 # message = "Happy "+age+"rd Birdthday!"
d690cb88233e7814d0f84b3d328ab239139702f0
schiob/OnlineJudges
/hackerrank/algorithms/implementation/sherlock_and_squares.py
253
3.5
4
from math import ceil from math import sqrt t = int(input()) for _ in range(t): x, y = list(map(int, input().split())) bot_root = ceil(sqrt(x)) count = 0 while bot_root**2 <= y: count += 1 bot_root += 1 print(count)
c82702ec10d3658cf6351e71d23074e94c6fdda0
schiob/OnlineJudges
/COJ/python/2382.py
158
3.609375
4
# coding: utf-8 # In[11]: num = input().split(" ") # In[16]: print('YES') if int(num[0], int(num[1])) % int(num[2]) == 0 else print('NO') # In[ ]:
f2bc72233bc9e5f0bd3fd0064707dda8b481b17a
schiob/OnlineJudges
/COJ/python/2699.py
92
3.53125
4
sum = 0 for x in xrange(30): sum += int(raw_input()) print('%.3f') % (sum / 30.0 + sum)
7e3829e573eff90fed0992032bc737f4bcd79dbc
aveusalex/OBI
/Acelerador.py
244
3.921875
4
distancia_percorrida = int(input()) while distancia_percorrida > 8: distancia_percorrida -= 8 if distancia_percorrida == 8: print(3) elif distancia_percorrida == 7: print(2) elif distancia_percorrida == 6: print(1)
1a49fc913e65610488f7f497b635b45129023f72
ryvengray/algorithm_learning
/python/linked_list/merge-k-sorted-lists.py
1,037
4
4
from python.commons.node import ListNode, generate_list_node, print_list_node from queue import PriorityQueue # leetcode [23] class Solution: # 两数相加 @staticmethod def merge_k_list(lists: [ListNode]) -> ListNode: # 傀儡 dummy = ListNode(0) current = dummy p = PriorityQueue() import itertools counter = itertools.count(1) def put(li_node): p.put((li_node.val, next(counter), li_node)) for li in lists: if li: put(li) while not p.empty(): val, priority, node = p.get() current.next = node current = node node = node.next if node: put(node) return dummy.next if __name__ == '__main__': # Iteration n1 = generate_list_node([2, 4, 8]) n2 = generate_list_node([1, 2, 2, 3, 8, 9]) n3 = generate_list_node([2, 5]) print('Merge:') h = Solution.merge_k_list([n1, n2, n3]) print_list_node(h)
1a4f54d3720a86864288b258f1e976e5d4ec3157
c-elliott96/fall_20_ai
/a01/a01q02/main.py
759
3.828125
4
def move(direction = None, m = None): space_val = m.index(" ") n = m[:] if direction == 'right': if space_val == len(n) - 1: return n else: temp = n[space_val + 1] n[space_val + 1] = n[space_val] n[space_val] = temp return n elif direction == 'left': if space_val == 0: return n else: temp = n[space_val - 1] n[space_val - 1] = n[space_val] n[space_val] = temp return n else: raise ValueError("ERROR in move: invald direction %s" % direction) if __name__ == '__main__': direction = raw_input() s = raw_input() m = list(s) print move(direction = direction, m = m)
63886ae23df34a323359c48f73db96cf125177e5
c-elliott96/fall_20_ai
/othello-project/testing/test.py
3,184
4.5
4
## Author: Kevin Weston ## This program will simulate a game of othello in the console ## In order to use it, you need to: ## 1. Import code for your AIs. ## 2. You also need to import a function which applies an action to the board state, ## and replace my function call (main.get_action(...)) within the while loop. ## 3. Your AIs must have a get_move() function. Assign these functions to ## white_get_move and black_get_move. ## 4. Create an initial board state to be played on ## Replace these imports with the file(s) that contain your ai(s) # import main import '../' import '../' def get_winner(board_state): black_score = 0 white_score = 0 for row in board_state: for col in row: if col == 'W': white_score += 1 elif col == 'B': black_score += 1 if black_score > white_score: winner = 'B' elif white_score > black_score: winner = 'W' else: winner = None return (winner, white_score, black_score) def prepare_next_turn(turn, white_get_move, black_get_move): next_turn = 'W' if turn == 'B' else 'B' next_move_function = white_get_move if next_turn == 'W' else black_get_move return next_turn, next_move_function def print_board(board_state): for row in board_state: print row def simulate_game(board_state, board_size, white_get_move, black_get_move): player_blocked = False turn = 'B' get_move = black_get_move print_board(board_state) while True: ## GET ACTION ## next_action = get_move(board_size=board_size, board_state=board_state, turn=turn, time_left=0, opponent_time_left=0) print "turn: ", turn, "next action: ", next_action _ = raw_input() ## CHECK FOR BLOCKED PLAYER ## if next_action is None: if player_blocked: print "Both players blocked!" break else: player_blocked = True turn, get_move = prepare_next_turn(turn, white_get_move, black_get_move) continue else: player_blocked = False ## APPLY ACTION ## ## Replace this function with your own apply function board_state = main.apply_action(board_state=board_state, action=next_action, turn=turn) print_board(board_state) turn, get_move = prepare_next_turn(turn, white_get_move, black_get_move) winner, white_score, black_score = get_winner(board_state) print "Winner: ", winner print "White score: ", white_score print "Black score: ", black_score if __name__ == "__main__": ## Replace with whatever board size you want to run on board_state = [[' ', ' ', ' ', ' '], [' ', 'W', 'B', ' '], [' ', 'B', 'W', ' '], [' ', ' ', ' ', ' ']] board_size = 4 ## Give these the get_move functions from whatever ais you want to test white_get_move = Rando.get_move black_get_move = MiniMaximus.get_move simulate_game(board_state, board_size, white_get_move, black_get_move)
ec45b798cbfb0053bc23464485d4a38efae8b894
carlmcateer/lpthw2
/ex45/Boxing/make_object.py
1,963
3.78125
4
import random import time wait_time = .5 class Boxer(object): def __init__(self, name = '', life = 0, stamina = 0): self.name = name self.life = life self.stamina = stamina def print_stats(self): print "name: "+self.name print "life: "+str(self.life) print "stamina: "+str(self.stamina) class Player(Boxer): pass class Enemy(Boxer): pass def choose_name(): print "Whats your name kid?" user_input = raw_input("> ") print "%s? I hope you are tougher then you sound..." % user_input time.sleep(wait_time) print "Lets see who you are up agenst." time.sleep(wait_time) print ".." time.sleep(wait_time) return str(user_input) def choose_enemy(): bad_guy_names = [ "Mohammed Ali", "Floyd Mayweather Jr.", "Sugar Ray Robinson", "Mike Tyson", "Joe Louis", "Manny Pacquiao", "Joe Frazier", "Rocky Marciano", "Vasyl Lomachenko" ] chosen_name = bad_guy_names[random.randint(0,len(bad_guy_names)-1)] print "Well if it aint none other than %s" % chosen_name time.sleep(wait_time) #dificulty options return str(chosen_name) player_name = choose_name() enemy_name = choose_enemy() enemy_life = random.randint(5,15) player = Player(name = player_name, life = 0, stamina = 2) enemy = Enemy(name = enemy_name, life = enemy_life, stamina = 4) print vars(player) print vars(enemy) print player.print_stats() print enemy.print_stats() # def game_loop(): # print "Type play or pass" # while player.life > 0 and enemy.life > 0 # user_input = raw_input("> ") # # if "play" in user_input: # player.print_stats() # elif "pass" in user_input: # enemy.print_stats() # else: # print "Try again..." # time.sleep(wait_time) # game_loop() # # game_loop()
797cdc5d2c7d19a64045bc0fc1864fcefe0633b4
carlmcateer/lpthw2
/ex4.py
1,065
4.25
4
# The variable "car" is set to the int 100. cars = 100 # The variable "space_in_a_car" is set to the float 4.0. space_in_a_car = 4 # The variable "drivers" is set to the int 30. drivers = 30 # The variable "passengers" is set to the int 90. passengers = 90 # The variable cars_not_driven is set to the result of "cars" minus "drivers" cars_not_driven = cars - drivers # The variable "cars_driven" is set to the variable "drivers" cars_driven = drivers # The variable "carpool_capacity" is set to "cars_driven" times "space_in_a_car" carpool_capacity = cars_driven * space_in_a_car # The variable "average_passengers_per_car" is set to "passengers" devided by "cars_driven" average_passengers_per_car = passengers / cars_driven print "There are", cars, "cars avaiable." print "There are only", drivers, "drivers avaiable." print "There will be", cars_not_driven, "empty cars today." print "We can transport", carpool_capacity, "people today." print "We have", passengers, "to carpool today." print "We need to put about", average_passengers_per_car, "in each car."
41da391efc2d5e51686e56d9f3bb7034670ef74a
gsnelson/censor-dispenser-project
/censor_dispenser.py
4,127
3.90625
4
# These are the emails you will be censoring. The open() function is opening the text file that the emails are contained in and the .read() method is allowing us to save their contexts to the following variables: email_one = open("email_one.txt", "r").read() email_two = open("email_two.txt", "r").read() email_three = open("email_three.txt", "r").read() email_four = open("email_four.txt", "r").read() # task 2 def find_replace(text, censored_term): ''' Difference between my function & the solution: the solution doesn't redact if spaces occur in the search term while mine does. Also, the solution performed the search term replacement letter-by-letter and mine performed it as a whole. ''' redacted_text = text.replace(censored_term, len(censored_term) * '*') return redacted_text # print(find_replace(email_one, 'learning algorithm')) # task 3 proprietary_terms = ["she", "personality matrix", "sense of self", "self-preservation", "learning algorithm", "her", "herself", "Helena"] def multi_find_replace(text, censored_terms): ''' Difference between my function & the solution: same as task 2 above - accounting for spaces in the search terms and searching letter-by-letter rather than singly ''' for term in censored_terms: text = text.replace(term, len(term) * '*') return text # print(multi_find_replace(email_two, proprietary_terms)) # task 4 negative_words = ["concerned", "behind", "danger", "dangerous", "alarming", "alarmed", "out of control", "help", "unhappy", "bad", "upset", "awful", "broken", "damage", "damaging", "dismal", "distressed", "distressing", "concerning", "horrible", "horribly", "questionable"] def negative_find_replace(text, negative_terms): ''' Difference between my function & the solution: the solution converted the text string to a list before the search and then joined the list to convert it back to a whole string. I dealt with the string throughout the function. The solution removes carriage returns (new lines) and punctuation, presumably to improve the search for keywords. However, the text that is returned from the function is unformatted while my function returns the email text as it originally appears. The solution, when performing the searches, looks for each word from the text in the keyword lists. My function does the opposite; it looks for each keyword in the text since there are fewer keywords than words in the text (i.e. fewer cycles through a for loop. The solution rebuilt the code created in task 3 in this function while mine just called the function already created ''' neg_count = 0 for term in negative_terms: neg_count += text.count(term) if neg_count >= 2: text = text.replace(term, len(term) * '*') return text # print(negative_find_replace(multi_find_replace(email_three, proprietary_terms), negative_words)) # task 5 all_words = proprietary_terms + negative_words print(all_words) def fore_aft_find_replace(text, search_terms): ''' Difference between my function & the solution: Same as task four as regards carriage returns (new lines) and punctuation. My function converted the text to a list like the solution did in this task as well as task 4. ''' email_list = list(text.split(' ')) index = 0 for term in search_terms: if term in email_list: count = email_list.count(term) for i in range(count): index = email_list.index(term) email_list[index] = len(term) * '*' email_list[index - 1] = len(term) * '*' email_list[index + 1] = len(term) * '*' listToStr = ' '.join([str(elem) for elem in email_list]) return listToStr print(fore_aft_find_replace(email_four, all_words)) # I give myself a B grade on this project. The solution addressed details # that mine didn't. Overall, my project reproduced the desired results # with far fewer lines of code than the solution.
6574d794c152f0cc7a8f7c2193af7483014690a7
gaochenchao/test
/test.py
2,403
3.671875
4
# -*- coding: utf-8 -*- class Person(object): def __init__(self, name, age): self.name = name self.age = age def __cmp__(self, other): if self.age > other.age: return 1 elif self.age < other.age: return -1 else: return 0 def __repr__(self): return "[person] %s age: %s" %(self.name, self.age) class ListNode(object): def __init__(self, v, next): self.v = v self.next = next def __repr__(self): return "[v] %s [next] %s" % (self.v, self.next.v) class MiniLink(object): # head = ListNode(None, None) def __init__(self): self.head = ListNode(None, None) def printList(self): p = self.head.next while p.next: print p p = p.next print "==============================" def listToLink(self, arr): p = self.head for i in arr: node = ListNode(i, None) p.next = node p = node def insert(self, index, v): p = self.head i = 0 while i <= index: p = p.next i += 1 node = ListNode(v, None) node.next = p.next p.next = node def remove(self, index): p = self.head i = 0 while i < index: p = p.next i += 1 nx = p.next if nx: p.next = nx.next else: p.next = None def recurse(self, node): if node.next: self.recurse(node.next) print node else: print "[v] %s [next] None" % node.v def reversePrint(self): self.recurse(self.head) def getMax(self): p = self.head.next max = p while p.next: p = p.next max = max if p.v <= max.v else p return max.v if __name__ == '__main__': link = MiniLink() # arr = [1, 2, 3, 4, 5] # link.listToLink(arr) # link.reversePrint() # link.insert(2, 9) # link.printList() # link.remove(0) # link.printList() p1 = Person('a', 29) p2 = Person('b', 30) p3 = Person('bc', 181) p4 = Person('bd', 34) p5 = Person('bg', 30) # arr = [p1, p2, p3, p4, p5] arr = [1, 2, 3, 4, 5] link.listToLink(arr) link.reverseLink() link.printList() # print link.getMax()
23a0df7b971e178b0fcf59d993247a3b97a3ae96
gaochenchao/test
/single_list.py
3,701
3.59375
4
# -*- coding: utf-8 -*- __author__ = 'gaochenchao' class ListNode(object): def __init__(self, value, next): self.value = value self.next = next def __repr__(self): return "[ListNode] %s" % self.value class LnTool(object): def __init__(self): self.head = ListNode(None, None) def arrToList(self, arr): if not arr or len(arr) == 0: return self.head p = self.head for i in arr: ln = ListNode(i, None) p.next = ln p = p.next return self.head def printList(self): p = self.head while p: if p.value: print p.value p = p.next def getLen(self): p = self.head if not p.next: return 0 count = 0 while p: count += 1 p = p.next return count - 1 def getBackN(self, n): p = self.head if not p.next: return self.head ln_len = self.getLen() m = ln_len - n if n > ln_len: m = ln_len for i in range(0, m+1): p = p.next return p def getBackN2(self, n): p0 = self.head p1 = self.head i = 1 while i <= n: p1 = p1.next i += 1 while p1: p0 = p0.next p1 = p1.next return p0 def delBackN(self, n): p0 = self.head p1 = self.head if not p0.next: return for i in range(n+1): p1 = p1.next while p1: p0 = p0.next p1 = p1.next p0.next = p0.next.next def removeNode(self, val): if not self.head.next: return self.head newHead = ListNode(None, self.head) pre = newHead p = self.head while p: if p.value == val: pre.next = p.next p = p.next else: pre = p p = p.next return newHead.next def removeDuplicate(self): pre = self.head p = self.head.next while p: if pre.value == p.value: while p and pre.value == p.value: p = p.next pre.next = p else: pre = p p = p.next def removeAllDuplicate(self): if not self.head or not self.head.next: return self.head newHead = ListNode(None, self.head) pre = newHead p = self.head next = None while p and p.next: next = p.next if p.value == next.value: while p and next and p.value == next.value: next = next.next pre.next = next p = next else: pre = p p = p.next def reverseBetween(self, m, n): newHead = ListNode(None, self.head) if m == n: return k = 0 front = newHead while k < m: front = front.next k += 1 pre = front.next p = pre.next next = None tail = pre while k < n: next = p.next p.next = pre pre = p p = next k += 1 tail.next = p front.next = pre self.head = newHead.next lnt = LnTool() # arr = [1, 2, 3, 4, 5, 6] # lnt.arrToList(arr) # arr = [1, 2, 6, 4, 5, 6, 2] arr = [1, 2, 3, 4, 5, 6, 7] lnt.arrToList(arr) # lnt.printList() # lnt.removeAllDuplicate() lnt.printList() lnt.reverseBetween(3, 6) lnt.printList()
c5a4f56e243b17df1ae3f76c63171b99fb6d8ccd
vincemaling/Full-Stack-Web-Dev-P1
/movies/media.py
922
4.0625
4
class Movie(): """This class builds movie information to be displayed in a web browser""" # Initalizes an instance of Movie def __init__(self, movie_title, movie_storyline, poster_image, trailer_youtube, imdb_rating, cast): self.title = movie_title self.storyline = movie_storyline self.poster_image_url = poster_image self.trailer_youtube_url = trailer_youtube self.imdb_rating = imdb_rating self.cast = cast # Sets the storyline of a Movie instance def set_storyline(self, storyline): self.storyline = storyline # Sets the poster url of a Movie instance def set_poster(self, poster): self.poster_image_url = poster # Sets the IMDB rating of a Movie instance def set_imdb(self, imdb): self.imdb_rating = imdb # Sets the cast of a Movie instance def set_cast(self, actors): self.cast = actors
325fcf8ad719e1f728dd4f4b4681e6c6980ef07d
Interligo/tetrika-school-tasks
/task3_appearance_intervals.py
5,490
3.984375
4
import time def len_is_even(element: list) -> bool: """Службная функция для проверки интервалов на четность.""" return len(element) % 2 == 0 def data_is_correct(data: dict) -> bool: """Службная функция для проверки переданных данных на корректность.""" if len(data) != 3: return False for element in data: if not len_is_even(data[element]): return False return True def split_intervals_list(intervals: list) -> list: """Служебная функция для разделения списка интервалов на пары.""" return [interval for interval in range(len(intervals)) if interval % 2 == 0] def attendance_in_lesson_time(lesson_start_time: int, lesson_end_time: int, intervals: list) -> list: """Функция проверяет интервалы присутствия и корректирует/отбрасывает интервалы вне времени урока.""" attendance_intervals = [] arrival_intervals = split_intervals_list(intervals) for interval in arrival_intervals: start_of_interval = intervals[interval] end_of_interval = intervals[interval + 1] if lesson_start_time <= lesson_end_time: if start_of_interval <= lesson_start_time < end_of_interval: attendance_intervals.append(lesson_start_time) elif lesson_start_time <= start_of_interval <= lesson_end_time: attendance_intervals.append(start_of_interval) if lesson_end_time >= end_of_interval > lesson_start_time: attendance_intervals.append(end_of_interval) elif end_of_interval > lesson_end_time > start_of_interval >= lesson_start_time: attendance_intervals.append(lesson_end_time) else: raise SystemExit(f'Некорректное время урока: время начала урока ({time.ctime(lesson_start_time)}) позже, ' f'чем время завершения урока ({time.ctime(lesson_end_time)}).') return attendance_intervals def count_time_in_border(start_border: int, end_border: int, intervals_to_count: list) -> int: """Вспомогательная функция для поиска и сложения совпадающих интервалов присутствия.""" total_time = 0 arrival_intervals = split_intervals_list(intervals_to_count) for interval in arrival_intervals: start_of_interval = intervals_to_count[interval] end_of_interval = intervals_to_count[interval + 1] start_of_interval_to_count = 0 end_of_interval_to_count = 0 if start_of_interval <= start_border < end_of_interval: start_of_interval_to_count = start_border elif start_border <= start_of_interval <= end_border: start_of_interval_to_count = start_of_interval if end_border >= end_of_interval > start_border: end_of_interval_to_count = end_of_interval elif end_of_interval > end_border > start_of_interval >= start_border: end_of_interval_to_count = end_border total_time += (end_of_interval_to_count - start_of_interval_to_count) return total_time def total_time_of_attendance_counter(pupil_intervals: list, tutor_intervals: list) -> int: """Функция подсчитывает общее время присутствия ученика и преподавателя.""" total_time_of_attendance = 0 tutor_intervals_index = split_intervals_list(tutor_intervals) for interval in tutor_intervals_index: tutor_start_of_interval = tutor_intervals[interval] tutor_end_of_interval = tutor_intervals[interval + 1] total_time_of_attendance += count_time_in_border( start_border=tutor_start_of_interval, end_border=tutor_end_of_interval, intervals_to_count=pupil_intervals ) return total_time_of_attendance def appearance(intervals: dict) -> int: """Функция-агрегатор принимает данные и возвращает общее время присутствия ученика и преподавателя в секундах.""" if not data_is_correct(intervals): raise SystemExit('Переданные данные некорректны.') lesson_start_time = intervals['lesson'][0] lesson_end_time = intervals['lesson'][1] pupil_intervals = attendance_in_lesson_time( lesson_start_time=lesson_start_time, lesson_end_time=lesson_end_time, intervals=intervals['pupil'] ) tutor_intervals = attendance_in_lesson_time( lesson_start_time=lesson_start_time, lesson_end_time=lesson_end_time, intervals=intervals['tutor'] ) total_time_of_attendance = total_time_of_attendance_counter( pupil_intervals=pupil_intervals, tutor_intervals=tutor_intervals ) return total_time_of_attendance if __name__ == '__main__': data = { 'lesson': [1594663200, 1594666800], 'pupil': [1594663000, 1594663199, 1594663340, 1594663389, 1594663390, 1594663395, 1594663396, 1594666472], 'tutor': [1594663290, 1594663430, 1594663443, 1594666473, 1594666890, 1594666990] } print(appearance(data))
0bdde125872c900b739a8f3dfe4a692a4bb374e2
Rahkeen/Hyperbolic-Time-Chamber
/CTCI/Arrays-Strings/1-7.py
486
3.828125
4
def matrix_rc_zero(matrix): rows = set() cols = set() for col in xrange(len(matrix)): for row in xrange(len(matrix[0])): if matrix[col][row] == 0: rows.add(row) cols.add(col) for col in xrange(len(matrix)): for row in xrange(len(matrix[0])): if row in rows or col in cols: matrix[col][row] = 0 matrix = [[1,1,1],[1,0,1],[1,1,1]] print matrix matrix_rc_zero(matrix) print matrix
6c81cc65adb9651088c975a02cfab4b304bf6187
INDAPlus20/oskhen-task-15
/dataguess.py
1,931
3.78125
4
#!/usr/bin/env python3 # Types: stack/queue/prio/not sure/impossible while True: try: n = input() except: exit() if n == "": exit() n = int(n) stack_bag = list() queue_bag = list() prio_bag = list() bagtype = [True]*3 for _ in range(n): line = list(map(int, input().split(" "))) prio_bag.sort() if line[0] == 1: stack_bag.append(line[1]) queue_bag.append(line[1]) prio_bag.append(line[1]) elif line[0] == 2: # Check Stack if bagtype[0] != False: if len(stack_bag) == 0: bagtype[0] = False else: if line[1] != stack_bag[-1]: bagtype[0] = False else: stack_bag.pop() # Check Queue if bagtype[1] != False: if len(queue_bag) == 0: bagtype[1] = False else: if line[1] != queue_bag[0]: bagtype[1] = False else: queue_bag.pop(0) # Check Prio if bagtype[2] != False: if len(prio_bag) == 0: bagtype[2] = False else: if line[1] != prio_bag[-1]: bagtype[2] = False else: prio_bag.pop() if sum(bagtype) > 1: print("not sure") elif sum(bagtype) == 0: print("impossible") elif bagtype == [True, False, False]: print("stack") elif bagtype == [False, True, False]: print("queue") elif bagtype == [False, False, True]: print("priority queue")
796e6b1fd24d439e7e29aa2bd6d9bb895f5a316f
manasjainp/BScIT-Python-Practical
/5c.py
391
4.03125
4
""" Youtube Video Link :- https://youtu.be/AB4S9uMpFKY Write a Python program to sum all the items in a dictionary. Save File as 5c.py Run :- python 5c.py """ #Method2 dic2 = {'python':90, 'cpp':100, 'java':80, 'php':50} print("sum is ") print(sum(dic2.values())) print() #Method1 dic1 = {'python':90, 'cpp':100, 'java':80, 'php':50} sum=0 for i in dic1.values(): sum=sum+i print(sum)
093233f29bfc50e37eb316fdffdf3a934aa5cea3
manasjainp/BScIT-Python-Practical
/7c.py
1,470
4.40625
4
""" Youtube Video Link :- https://youtu.be/bZKs65uK1Eg Create a class called Numbers, which has a single class attribute called MULTIPLIER, and a constructor which takes the parameters x and y (these should all be numbers). i. Write a method called add which returns the sum of the attributes x and y. ii. Write a class method called multiply, which takes a single number parameter a and returns the product of a and MULTIPLIER. iii. Write a static method called subtract, which takes two number parameters, b and c, and returns b - c. iv. Write a method called value which returns a tuple containing the values of x and y. Make this method into a property, and write a setter and a deleter for manipulating the values of x and y. Save File as 7c.py Run :- python 7c.py """ class Numbers: MULTIPLIER=5 def __init__(self,x,y): self.x=x self.y=y #subpart-1 def add(self): return self.x + self.y #subpart-2 @classmethod def multiply(cls,a): return cls.MULTIPLIER * a #subpart-3 @staticmethod def substract(b,c): return b-c #subpart-4 @property def value(self): return(self.x, self.y) @value.setter def value(self, t): self.x = t[0] self.y = t[1] @value.deleter def value(self): self.x=None self.y=None ob=Numbers(10,20) print("Add :- ",ob.add()) print("Multiply :- ", Numbers.multiply(10)) print("Substract :- ", Numbers.substract(20,10)) ob.value=(100,200) print("Add :- ", ob.add()) del ob.value print("Values :- ",ob.value)
ea5f8250e93c2b98745db0ed964e5dbfb0bcca48
jimi79/cistercian_clock
/clock.py
3,257
3.625
4
#!/usr/bin/python3 import random import time import datetime class Printer: def __init__(self): self.initValues() def initValues(self): self.values = [] value = []; # 0 value.append(' ') value.append(' ') self.values.append(value) value = []; # 1 value.append(' ') value.append('¯ ') self.values.append(value) value = []; # 2 value.append(' ') value.append('_ ') self.values.append(value) value = []; # 3 value.append(' ') value.append('\ ') self.values.append(value) value = []; # 4 value.append(' ') value.append('/ ') self.values.append(value) value = []; # 5 value.append('_ ') value.append('/ ') self.values.append(value) value = []; # 6 value.append(' ') value.append(' |') self.values.append(value) value = []; # 7 value.append('_ ') value.append(' |') self.values.append(value) value = []; # 8 value.append(' ') value.append('_|') self.values.append(value) value = []; # 9 value.append('_ ') value.append('_|') self.values.append(value) def mirrorVert(self, text): newtext = [] for line in text: newline = "" for letter in line: newletter = letter if letter == "\\": newletter = "/" if letter == "/": newletter = "\\" newline = newletter + newline line = newline newtext.append(line) return newtext def mirrorHorz(self, text): newtext = [] for line in text: newline = "" for letter in line: newletter = letter if letter == "\\": newletter = "/" if letter == "/": newletter = "\\" if letter == "_": newletter = "¯" if letter == "¯": newletter = "_" newline = newline + newletter line = newline newtext.append(line) newtext.reverse() return newtext def generateValue(self, value): draw = [] svalue = str(value) svalue = svalue.zfill(4) arts = [] arts.append(self.values[int(svalue[3])]) arts.append(self.values[int(svalue[2])]) arts[1] = self.mirrorVert(arts[1]) arts.append(self.values[int(svalue[1])]) arts[2] = self.mirrorHorz(arts[2]) arts.append(self.values[int(svalue[0])]) arts[3] = self.mirrorHorz(self.mirrorVert(arts[3])) draw.append(arts[1][0] + " " + arts[0][0]) draw.append(arts[1][1] + "|" + arts[0][1]) draw.append(" | ") draw.append(arts[3][0] + "|" + arts[2][0]) draw.append(arts[3][1] + " " + arts[2][1]) return draw def test(): c = Printer() for i in range(0, 10): a = c.values[i] print('\n'.join(a)) print("====") print('\n'.join(c.mirrorHorz(a))) print("====") print('\n'.join(c.mirrorVert(a))) def test2(): c = Printer() val = random.randrange(0, 10000) c.generateValue(val) print(val) class Clock(): def __init__(self): self.printer = Printer() def run(self, format_, delay, verbose): while True: val = datetime.datetime.now().strftime(format_) sval = self.printer.generateValue(val) print("\n".join(sval)) if verbose: print(val) time.sleep(delay) def runClassic(self): self.run("%H%M", 60, False) def runWithMinutesAndSeconds(self): self.run("%M%S", 1, True) def runWithSecondsAndMinutes(self): self.run("%S%M", 1, True) c = Clock() #c.runWithMinutesAndSeconds() #c.runWithSecondsAndMinutes() c.runClassic()
6c5ef2ab95ad0bff6989ef33222d174381182bf4
CameronSCarlin/acute-commute
/QueryMaps.py
1,753
3.578125
4
from datetime import datetime import googlemaps import keys import pprint from Trip import Trip class QueryMaps(Trip): """ Provides access to Google Maps API. """ def __init__(self, start, end, mode, departure_time=None, arrival_time=None): """ :param start (str or dict): Start location of trip :param end (str or dict): End location of trip :param mode (str): The mode of travel for the trip :param departure_time (str): Time of departure :param arrival_time (str): Time of arrival """ Trip.__init__(self, start, end, mode, departure_time, arrival_time) self._gmaps = googlemaps.Client(keys.gmaps) self._pprinter = pprint.PrettyPrinter(indent=4) self._dir_result = None self.update_query(start, end, mode, departure_time, arrival_time) def get_directions_result(self): return self._dir_result def print_directions(self): self._pprinter.pprint(self._dir_result) def update_query(self, start, end, mode, departure_time=None, arrival_time=None): """ This method calls Google Maps to perform the search. Used in the constructor or as a public method to update the query without instantiating a new QueryMaps object. :param start: Start location of trip :param end: End location of trip :param mode: The mode of travel for the trip :param departure_time: Time of departure :param arrival_time: Time of arrival :return: """ if departure_time is None and arrival_time is None: departure_time = datetime.now() self._dir_result = self._gmaps.directions(start, end, mode, departure_time=departure_time)[0]
5da49d4c685b6a9a0cbdab2a985bf40a6b4e072c
jdavisrader/dealerRater
/review.py
1,618
3.703125
4
class Review(object): score = 0 def __init__(self, title, rating, review): self.title = title self.rating = int(rating) self.review = review def score_review(self): self.score = (self.review.count("wonderful") * 3) + (self.review.count("painless") * 2) + (self.review.count("fantastic") * 3) + (self.review.count("thank you") * 4) + (self.review.count("perfect") * 4) + (self.review.count("hassle free") * 2) + (self.review.count("pleasure") * 3) + (self.review.count("appreciate") * 4) + (self.review.count("knowledgable") * 3) + (self.review.count("patient") * 2) + (self.review.count("excellent") * 3) positiveWordCount = self.review.count("painless") + self.review.count("fantastic") + self.review.count("thank you") + self.review.count("perfect") + self.review.count("hassle free") + self.review.count("pleasure") + self.review.count("appreciate") + self.review.count("knowledgable") + self.review.count("patient") + self.review.count("excellent") ratio = int(float(positiveWordCount)/float(len(self.review.split())) * 1000) if ratio > 50: self.score += 5 elif ratio > 40: self.score += 4 elif ratio > 30: self.score += 3 elif ratio > 10: self.score += 1 else: self.score += 0 if self.rating > 30: self.score += 0 elif self.rating < 41: self.score += 1 elif self.rating < 46: self.score += 4 elif self.rating < 48: self.score += 5 else: self.score += 7
4e1d6e98e53fd8cabfe87651e40ac430f09dde88
pouerietwilmary/202010451
/Ejercicio 4.py
230
3.9375
4
# 4 Crear un programa que muestre las letras de la Z (mayúscula) a la A (mayúscula, descendiendo). import string def listAlphabet(): return list(string.ascii_uppercase) print('alfabeto en mayuscula') print(listAlphabet())
e5c32e02bee32823803cbd24ecd90ecd8c39da9f
510404494/test4
/booktest/testwo.py
1,157
3.90625
4
def quick_sort(L): return q_sort(L, 0, len(L) - 1) def q_sort(L, left, right): if left < right: pivot = Partition(L, left, right) q_sort(L, left, pivot - 1) q_sort(L, pivot + 1, right) return L def Partition(L, left, right): pivotkey = L[left] while left < right: while left < right and L[right] >= pivotkey: right -= 1 L[left] = L[right] while left < right and L[left] <= pivotkey: left += 1 L[right] = L[left] L[left] = pivotkey print("left:"+str(left)) return left def quicksort(nums): if len(nums) <= 1:return nums # 左子数组,右子数组 less , greater= [],[] # 基准数 --pop默认最后一个 base = nums.pop() # 对原数组进行划分 for x in nums: if x < base: less.append(x) else: greater.append(x) print(less) print(greater) print(base) # 递归调用 return quicksort(less) + [base] + quicksort(greater) if __name__ == '__main__': myList = [49, 38, 65, 97, 76, 13, 27, 49] print(myList) print(quicksort(myList))
c71d7f8ce9996471b72e084a237929a7eed0bf18
abhisheks008/Data-Structure-and-Algorithm-Week-12
/Week 12 Q5.py
486
3.734375
4
def enqueue (x,y): global k if (int(y)>int(k)): l.append(x) k = y elif (int(y)<int(k)): l.insert(0,x) k = y def display(): for j in range (0,len(l)): print ('{}|{}'.format(l[j],j+1),end = " ") if (j<(len(l)-1)): print ("->",end = " ") i = 0 l = [] k = 0 count = int(input()) while (i<count): a = input() if (a[0]=='1'): enqueue (a[2],a[4]) elif (a[0]=='3'): display() i = i+1
c19eeeacd474a323bf38154200bc8a7e73004415
kimtree/algorithms-and-data-structures
/181003-codeplus/codeplus4.py
328
3.671875
4
import itertools numbers = [1, 2, 3, 4, 5] answer = 8 result = set() combinations = itertools.combinations(numbers, 3) for c in combinations: if sum(c) == answer: result.add(c) if not result: print("NO") else: result = list(result) result.sort() for r in result: print(r[0], r[1], r[2])
f38eea4820e785ac951f08b86581d2ab82bcdcfe
ikita123/list-python
/even.py
232
3.921875
4
element=[23,14,56,12,19,9,15,25,31,42,43] i=0 even_count=0 odd_count=0 while i<len(element): if i%2==0: even_count+=1 else: odd_count+=1 i=i+1 print("even number",even_count) print("odd number",odd_count)
b98ae22ff3666f3ce22bc8cc57b3f343a6c8f17b
ZakirQamar/gems
/src/python_structures_tricks/python_structures_tricks.py
1,169
4.09375
4
def unpacking_a_sequence_into_variables(): """ Any sequence (or iterable) can be unpacked into variables using a simple assignment operation. The only requirement is that the number of the variables and structures match the sequence. Example: >>> p = (5, 6) >>> x, y = p >>> x 5 >>> y 6 Also works with structures. Example: >>> data = [ 'ACME', 50, 91.1, (2012, 12, 21)] >>> name, shares, price, date = data >>> name 'ACME' >>> shares 50 >>> price 91.1 >>> date (2012, 12, 21) """ pass def unpacking_elements_from_iterables_of_arbitrary_length(): """ You can use Python star expression. >>> record = ('John', 'john@doe.com', '555-343-7272', '555-553-1212', 'blue') >>> name, email, *phones, eyes = record >>> name 'John' >>> email 'john@doe.com' >>> phones ('555-343-7272', '555-553-1212') >>> eyes 'blue' """ pass if __name__ == '__main__': import doctest doctest.testmod( verbose=True)
d916840b3ec5c3efbb4ee0b1c1aea1ad42844d66
omushpapa/minor-python-tests
/Large of three/large_ofThree.py
778
4.40625
4
#!/usr/bin/env python2 #encoding: UTF-8 # Define a function max_of_three() # that takes three numbers as arguments # and returns the largest of them. def max_of_three(num1, num2, num3): if type(num1) is not int or type(num2) is not int or type(num3) is not int: return False num_list = [num1, num2, num3] temp = 0 if num1 == num2 == num3: return num3 for i in range(len(num_list) - 1): if num_list[i] < num_list[i + 1]: temp = num_list[i + 1] return temp def main(): value1 = input("Enter first value: ") value2 = input("Enter second value: ") value3 = input("Enter third value: ") print max_of_three(value1, value2, value3) if __name__ == "__main__": print "Hello World"
e6134ced3a1fc1b67264040e64eba2af21ce8e1d
omushpapa/minor-python-tests
/List Control/list_controls.py
900
4.15625
4
#!/usr/bin/env python2 #encoding: UTF-8 # Define a function sum() and a function multiply() # that sums and multiplies (respectively) all the numbers in a list of numbers. # For example, sum([1, 2, 3, 4]) should return 10, and # multiply([1, 2, 3, 4]) should return 24. def sum(value): if type(value) is not list: return False summation = 0 for i in value: if type(i) is not int: return False summation = summation + i return summation def multiply(value): if type(value) is not list: return False result = 1 for i in value: if type(i) is not int: return False result = result * i return result def main(): ans = input("Enter values in list: ") print sum(ans) print multiply(ans) if __name__ == "__main__": main()
6c58ca9f940f7ab15d3b99f27217b3bd485b01f9
omushpapa/minor-python-tests
/Operate List/operate_list.py
1,301
4.1875
4
# Define a function sum() and a function multiply() # that sums and multiplies (respectively) all the numbers in a list of numbers. # For example, sum([1, 2, 3, 4]) should return 10, # and multiply([1, 2, 3, 4]) should return 24. def check_list(num_list): """Check if input is list""" if num_list is None: return False if len(num_list) == 0: return False new_list = [] for i in num_list: if i!='[' and i!=']' and i!=',': new_list.append(i) for x in new_list: if type(x) != int: return False return True def sum(num_list): """Compute sum of list values""" if check_list(num_list): final_sum = 0 for i in num_list: final_sum = final_sum + i return final_sum else: return False def multiply(num_list): """Multiply list values""" if check_list(num_list): final_sum = 1 for i in num_list: final_sum = final_sum * i return final_sum else: return False def main(): get_list = input("Enter list: ") operations = [sum, multiply] print map(lambda x: x(get_list), operations) if __name__ == "__main__": main()
a193124758fc5b01168757d0f98cf67f9b98c664
omushpapa/minor-python-tests
/Map/maps.py
388
4.25
4
# Write a program that maps a list of words # into a list of integers representing the lengths of the correponding words. def main(): word_list = input("Enter a list of strings: ") if type(word_list) != list or len(word_list) == 0 or word_list is None: print False else: print map(lambda x: len(x), word_list) if __name__ == "__main__": main()
b0956c92848ea9087b83181d0dfcd360e45bdade
hubieva-a/lab4
/1.py
718
4.4375
4
# Дано число. Вывести на экран название дня недели, который соответствует # этому номеру. #!/usr/bin/env python3 # -*- coding: utf-8 -*- import sys if __name__ == '__main__': n = input("Number of the day of the week") n = int(n) if n == 1: print("Monday") elif n== 2: print("Tuesday") elif n == 3: print("Wednesday") elif n == 4: print("Thursday") elif n == 5: print("Friday") elif n == 6: print("Saturday") elif n == 7: print("Sunday") else: print("Please choose a number in range from 1 to 7") exit(1)
21587730b4d4ee204bb42c9c44a469c6d7c00c04
endokazuki/deep_leaning
/perceptron/perceptron.py
1,934
3.84375
4
import numpy as np x1 = input('Enter 0 or 1 in x1: ') # Enter x1 x1=int(x1) x2 = input('Enter 0 or 1 in x2: ') x2=int(x2) # Enter x2 selected_gate =input('Enter gate(and,or,nand,xor): ') class perceptron: #liner--直線で表現が可能(XORは曲線) #def __init__(self,x1,x2): # self.x1=x1 # self.x2=x2 #def AND(self,x1,x2): #ANDゲート(簡易型) # w1,w2,theta=0.5,0.5,0.2 # tmp=x1*w1+x2*w2 # if tmp <= theta: # return 0 # elif tmp > theta: # return 1 def AND(self,x1,x2): #ANDゲート x=np.array([x1,x2]) w=np.array([0.5,0.5]) bias=-0.7 tmp=np.sum(w*x)+bias if tmp <= 0: return 0 else: return 1 def NAND(self,x1,x2): #NANDゲート x=np.array([x1,x2]) w=np.array([-0.5,-0.5]) bias=0.7 tmp=np.sum(w*x)+bias if tmp <= 0: return 0 else: return 1 def OR(self,x1,x2): #ORゲート x=np.array([x1,x2]) w=np.array([0.5,0.5]) bias=-0.1 tmp=np.sum(w*x)+bias if tmp <= 0: return 0 else: return 1 def XOR(self,x1,x2): #XORゲート s1=self.NAND(x1,x2) #自身のクラス内の関数を呼び出す s2=self.OR(x1,x2) y=self.AND(s1,s2) return y if selected_gate == "and": p=perceptron() output_date=p.AND(x1,x2) print(output_date) elif selected_gate == "nand": p=perceptron() output_date=p.NAND(x1,x2) print(output_date) elif selected_gate == "or": p=perceptron() output_date=p.OR(x1,x2) print(output_date) elif selected_gate == 'xor': p=perceptron() output_date=p.XOR(x1,x2) print(output_date) else: print("NO SELECTED!!")
50923882ada4e539df923241e35ec0f2aa3984ad
isabelgaldamez/linked_list
/SLL.py
1,210
3.75
4
import list mylist = list.SList() # instantiating the class of SLL mylist.add_to_back(10) mylist.add_to_back(1) mylist.add_to_back(8) mylist.add_to_back(11) mylist.add_to_back(22) mylist.print_list() print("******") mylist.add_to_front(2) mylist.print_list() print("******") mylist.insert_after_node(2, 4) mylist.insert_after_node(1, 5) mylist.print_list() print("******") # mylist.delete_node(2) # mylist.print_list() print("******") mylist.delete_node(1) mylist.print_list() print("******") # mylist.delete_node(5) # mylist.print_list() mylist.delete_at_index(4) mylist.print_list() print("******") mylist.reverse() mylist.print_list() print("********") mylist.find_nth_to_last(3) # print("******") # mylist.list_length_iterative() # print("******") # print(mylist.list_length_recursive(mylist.head)) # print("******") # mylist.swap_nodes(5, 10) # mylist.print_list() # print("******") # mylist.swap_nodes(22, 11) # mylist.print_list() myPalindrome = list.SList() # instantiating the class of SLL myPalindrome.add_to_back('S') myPalindrome.add_to_back('O') myPalindrome.add_to_back('L') # myPalindrome.add_to_back('A') # myPalindrome.add_to_back('R') print("******") print(myPalindrome.isPalindrome())
897b41cb4fe3e3562afc2236bc3be3eae93be49f
jch427/directed-study
/CH_3_EX_3_7.py
2,561
3.53125
4
dinner_gusset = ['erica', 'alexis', 'mando', 'yoda', 'stan lee'] dinner_gusset.append('ducky') message = f'Heloo, {dinner_gusset[0].title()} would you care to join me for dinner this evening?' message_1 = f'Heloo, {dinner_gusset[1].title()} would you care to join me for dinner this evening?' message_2 = f'Heloo, {dinner_gusset[2].title()} would you care to join me for dinner this evening?' message_3 = f'Heloo, {dinner_gusset[3].title()} would you care to join me for dinner this evening?' message_4 = f'Heloo, {dinner_gusset[4].title()} would you care to join me for dinner this evening?' print(message) print(message_1) print(message_2) print(message_3) print(message_4) popped_dinner_gusset = dinner_gusset.pop(3) message_5 = f'unforchentily {popped_dinner_gusset} is unable to make it but we will be joined by {dinner_gusset[4]}' print(message_5) message_6 = f'Heloo, {dinner_gusset[4].title()} would you care to join me for dinner this evening?' print(message_6) dinner_gusset.insert(0, 'tony') dinner_gusset.insert(5, 'fred') dinner_gusset.append('sam') message_7 = f'Heloo, {dinner_gusset[0].title()} would you care to join me for dinner this evening?' print(message_7) message_8 = f'Heloo, {dinner_gusset[5].title()} would you care to join me for dinner this evening?' print(message_8) message_9 = f'Heloo, {dinner_gusset[7].title()} would you care to join me for dinner this evening?' print(message_9) message_10 = 'Unfortunately the diner table will be unavailable in time, so I will only be able to invite two people to the party.' print(message_10) dinner_gusset_0 = dinner_gusset.pop(0) message_11 = f'{dinner_gusset_0.title()} you are uninvited' print(message_11) dinner_gusset_1 = dinner_gusset.pop(2) message_12 = f'{dinner_gusset_1.title()} you are uninvited' print(message_12) dinner_gusset_2 = dinner_gusset.pop(2) message_13 = f'{dinner_gusset_2.title()} you are uninvited' print(message_13) dinner_gusset_3 = dinner_gusset.pop(2) message_14 =f'{dinner_gusset_3.title()} you are uninvited' print(message_14) dinner_gusset_4 = dinner_gusset.pop(2) message_15 = f'{dinner_gusset_4.title()} you are uninvited' print(message_15) dinner_gusset_5 = dinner_gusset.pop(2) message_16 = f'{dinner_gusset_5.title()} you are uninvited' print(message_16) message_17 = f'{dinner_gusset[0]} you are still invited to dinner.' print(message_17) del dinner_gusset[0] message_18 = f'{dinner_gusset[0]} you are still invited to dinner.' print(message_18) del dinner_gusset[0] print(dinner_gusset)
80cb3ef92cec41b4ff72e5c980ef05f7a0830a40
jch427/directed-study
/CH_3_EX_3_8.py
433
3.625
4
vacation_spots = ['tokyo', 'pairs', 'austen', 'singapore', 'japan'] print(vacation_spots) print(sorted(vacation_spots)) print(vacation_spots) print(sorted(vacation_spots, reverse=True)) print(vacation_spots) vacation_spots.sort(reverse=True) print(vacation_spots) vacation_spots.sort(reverse=False) print(vacation_spots) vacation_spots.sort() print(vacation_spots) vacation_spots.sort(reverse=True) print(vacation_spots)
bc6ffe075520ed7f6b1feebb383833335cf20799
jch427/directed-study
/CH_4_EX_4_1.py
176
3.953125
4
pizza = ['pepperoni', 'ham', 'BBQ'] for pizza in pizza: print(f"{pizza} is one of my favorite types of pizza") print(f"pizza is one of the foods i could eat every day.")
41ac9a3fd5d3c74de4f73aa4e7451b94f43d46c8
jonathancohen1/extracting_data_y_net
/Article.py
3,028
3.578125
4
import csv from TextFromURL import TextFromURL class Article: #TODO Create a Class for "PAGE" #TODO Class will include the following attributes: ''' 1. page address - link 2. location of the scraped data file 3. article's basic data: #date #name of writer/reporter #section #Title ''' ''' def __init__(self,link , title = None, author = None, date = None, section = None): self.link = link self.title = title self.author = author self.date = date self.section = section self.path_to_file = "/home/jonathan/Documents/Gathering Data Proj/webdata/"+str(self.title)+".csv" self.linked_articles = [] ''' def __init__(self,link): self.link = link self.title = None self.author = None self.date = None self.section = None self.path_to_file = None self.linked_articles = [] def get_data(self): url= TextFromURL(self.link) raw_article_data = url.get_text_list(return_type = "list") self.title = raw_article_data[0] self.path_to_file = "/home/jonathan/Documents/Gathering Data Proj/webdata/"+str(self.title)+".csv" self.set_section_date(raw_article_data[1:]) return raw_article_data[1:] def create_dict(self): raw_article_data = self.get_data() dictionary = {"title":self.title ,"author":self.author, "date":self.date, "section":self.section,"article data":raw_article_data} return dictionary def create_file(self): dictionary = self.create_dict() with open(self.path_to_file, "w") as csv_file: writer = csv.writer(csv_file,delimiter=':') for key, value in dictionary.items(): writer.writerow([key, value]) def set_section_date(self,raw_article_data): section = None date = None for i in range(len(raw_article_data)) : if "אתר נגיש" in raw_article_data[i] and section == None: section = i if "פורסם" in raw_article_data[i] and date == None: date = i section = raw_article_data[section] section = section.split(" ")[1][4:] date = raw_article_data[date].split(" ") for i in range(len(date)): if "פורסם" in date[i]: pos = i for i in range(pos,len(date)): if "." in date[i]: self.date = date[i] self.section = section def get_data_as_dict(self): with open(self.path_to_file, 'r') as csv_file: reader = csv.reader(csv_file,delimiter=':') return dict(reader) def add_linked_article(self,linked_article): if type(linked_article) == "Article": self.linked_articles.append(linked_article) else: return "Error: given input type is NOT $Article$ "
298a63d6370e9e6179194e26aa46d7ef0de913d4
weixinCaishang/pyspider
/练习/pachong.py
4,021
3.609375
4
# -*- coding: UTF-8 -*- #http请求模块 import re import requests #HTML解析的工具包 from bs4 import BeautifulSoup def qiushibaike(): content = requests.get("http://www.qiushibaike.com").content soup = BeautifulSoup(content, "html.parser") #class:content是根据html中我们想要的格式来进行匹配的 for div in soup.find_all('div', {'class': 'content'}): print div.text.strip() + '\n' def demo_string(): #类似Java,有增加额外方法 stra = 'hello' print stra.capitalize() print stra.replace('he', 'ha') strb = ' \n \rget \r \n ' print(1, strb.rstrip()) print(2 , strb.lstrip()) print(3, stra.startswith('h')) print(4, stra.endswith('h')) print(5, stra + strb) print(6, stra, len(stra), len(strb)) print(7, '-'.join(['a','b','c'])) strc = 'hello world' print(strc.split(' ')) print(strc.find('a')) def demo_operation(): print 1, 1 + 2, 5 / 2, 5 * 2, 5 - 2 print 1, 1 + 2, 5 / 2.0, 5 * 2, 5 - 2 print(2, True, not True, False) print(1 << 2, 88 >> 2) print(5 | 3, 2 & 4, 6 ^ 2) def demo_function(): max([1]) len('1') range(1,10,2) print(dir(list)) x = 2 #如果x是个对象,可以用eval直接使用,可以用于写java语言 print(6,eval('x*2 + 5 + 3')) print(chr(66), ord('a')) print(divmod(11, 3)) #控制流略 #list def demo_list(): list1 = [1, 'a', 5.0, 23, 76] list2 = [1, 'a', 5.0, 23, 1212] print(list1) for i in list1: print(i) print(list1.extend(list2)) print(1 in list2) #操作符重载,两个相连 list2 = list2 + list1 print(list2) list2.insert(0, 'dasdasda') list2.pop(1) print(list2) list2.sort() print(list2) list2.reverse() print(list2.count(1)) #tuple不可变 t = (1, 2, 3) print(t) def add(a, b): return a + b def demo_dict(): dict = {'a' : 1, 'b': "a"} print(dict) print(dict.keys(), dict.values()) for key, value in dict.items(): print(key, value) for key in dict.keys(): print(key) print(dict.has_key(1)) a = add print(a(1, 2)) class User: def __init__(self, name, uid): self.name = name self.uid = uid def __repr__(self): return "i am a guest" + self.name + str(self.uid) class Admin(User): def __init__(self, name, uid, group): User.__init__(self, name, uid) self.group = group def __repr__(self): return "i am a guest" + self.name + str(self.uid) + self.group def demo_object(): user = User('jim', 1) print(user) admin = Admin('xiangyu', 1, 'a') print(admin) def demo_exception(): try: print(2/1) raise Exception("dasdas") except Exception as e: print(e) finally: print('final') #随机数略 #正则表达式 def demo_regex(): str = 'abc123def12gh15' #\d是digit数字 \w是字符串和数字 \s是空格 +代表匹配多次 #[]就是用来把一个式子包起来,和数学的()类似 p1 = re.compile('[\d]+') p2 = re.compile('\d') p3 = re.compile('[\d]') print(1, p1.findall(str)) print(2, p2.findall(str)) print(3, p3.findall(str)) str = 'a@163.com,b@google.com,c@qq.com,d@163.com' #.是正则表达式中的特殊字符,需要用\转义 p4 = re.compile('[\w]+@[163|qq|google]+\.com') print(p4.findall(str)) str = '<html><h>title</h><body>content</body></html>' # ^<说明首字符必须是< p5 = re.compile('<h>[^<]+</h>') print(p5.findall(str)) p5 = re.compile('<h>[^<]+</h><body>[^<]+</body>') print(p5.findall(str)) str = 'xx2016-08-20zzz,xx2016-7-20zzz' p6 = re.compile('\d{4}-\d{2}-\d{2}') print(p6.findall(str)) if __name__ == '__main__': #qiushibaike() #demo_string() #demo_operation() #demo_function() #demo_list() #demo_dict() #demo_object() #demo_exception() demo_regex()
f2ea73f7c80f873f8405eb2c3930439b57eb11ce
hlane6/biotracker
/tracker/models/target_manager.py
4,204
3.53125
4
from collections import namedtuple from .associate import associate from .tracker import Tracker, Target import csv import cv2 class TargetManager: """ A TargetManager is responsible for generating Targets for a given video. This is a three step process: 1. Using a Tracker, perform an initial first pass of the video. After this step, the targets will contain information about their x, y, width, height, and theta, but will not have associated ids, and there can be many mistakes dealing with sequential frames combining multiple targets into one larger target. 2. Post process the generated tracklets by attempting to remove some of the mistakes previously made. After this step, multiple targets will ideally not be combining into one bigger target if they get close together. 3. Using an Associator, associate the targets. After this step, the targets should have all have corresponding ids and are ready to be written to a csv file. """ FRAME_NUM = 0 TARGET_ID = 1 POS_X = 2 POS_Y = 3 WIDTH = 4 HEIGHT = 5 THETA = 6 def __init__(self, video_path: str, background_path: str=None) -> None: """ Initializes the TrackerManager. A TrackerManger has the following instance variables: targets: list[list[Target]] - All of the targets for a given video. At each index contains a list of all Targets corresponding to the frame number with the index for its value video: cv2.VideoCapture - a reference to the video it is analyzing """ self.targets = [] self.video_path = video_path if background_path is None: self.background_path = video_path.split('.mp4')[0] + '_background.jpg' else: self.background_path = background_path def identify_targets(self) -> None: """ Using a Tracker, will perform an initial pass of the video. self.targets will now contain Targets with valid frame_num, x, y, width, height, and theta, but they will have invalid ids and there can be mistakes between consequtive frames of Targets disappearing. """ tracker = Tracker(self.video_path, self.background_path) self.targets = tracker.process_video() def post_process_targets(self) -> None: """ Using a Tracker, will perform a second pass through the targets in an attempt to remove inconsistances between consequtive frames. self.targest should now contain Targets with valid frame_num, x, y, width, height, and theta and are ready to be associated to unique ids. """ pass def associate_targets(self): """ Using an associator, will perform a final pass through the targets an attempt to assign unique ids to targets throughout the video. """ self.targets = associate(self.targets) def write_csv_file(self, csv_file_name: str) -> None: """ Converts data to a csv file. Targets will be ordered by ascending frame number. """ with open(csv_file_name, 'w') as csv_file: writer = csv.writer(csv_file) writer.writerow(Target.FIELDS) for frame_targets in self.targets: for target in frame_targets: writer.writerow(tuple(target)) def load_data(self, csv_file: str): """ Loads data from a csv file """ with open(csv_file, 'r') as file_data: reader = csv.reader(file_data, delimiter=',') next(reader, None) # skip header for row in reader: target = self.__read_row(row) self.targets.append(self.target) def __read_row(self, row: list): """ Reads in a row from csv file into a Target """ return Target( target_id=int(row[TARGET_ID]), frame_num=int(row[FRAME_NUM]), x=int(row[POS_X]), y=int(row[POS_Y]), width=int(row[WIDTH]), height=int(row[HEIGHT]), theta=float(row[THETA]) )
54c2ac0456ebb81e141570e3d80cca21277c2d78
LiuyajingMelody/vscode_learning
/dichotomy.py
386
3.609375
4
import math def binary(list, item): low = 0 high = len(list)-1 while low <= high: mid = math.floor((low+high)/2) guess = list[mid] if guess == item: return mid if guess <= item: low = mid+1 else: high = mid+1 return None my_listing = [1, 2, 3, 4, 5, 6, 7] print(binary(my_listing, 4))
506198b6c9182bc55b941b8aa678b884ac441d35
Porkwaffle/Christmas-Bingo-PC
/ChristmasBingo.py
4,184
3.546875
4
#! python3 # ChristmasBingo.py import random from tkinter import * words = ['Mary', 'Joseph', 'Jesus', 'Frosty', 'Manger', 'Presents', 'Snow', 'Chimney', 'Fireplace', 'Star', 'Garland', 'Ornaments', 'Tinsel', 'Mistletoe', 'Church', 'Carols', 'Santa', 'Candy Cane', 'Sledding', 'Elf', 'North Pole', 'Rudolph', 'Hot Cocoa', 'Wise Men', 'Nativity', 'Bethlehem', 'Stockings', 'Gingerbread', 'Egg Nog', 'Lights', 'Donkey', 'Wreath', 'Nice List', 'Sprinkles', 'Cookies', 'Noel', 'Angel', 'Mittens', 'Silver Bells', 'Holly', 'Gift Wrap', 'Grinch', 'Drummer Boy', 'Icicles', 'Marshmallows', 'Nutcracker', 'Frankincense', 'Silent Night', 'Chestnuts'] def CreateCard(): global text card = random.sample(words, 24) text.insert(END, '\n\n') text.insert(END, card[0] + ' | ' + card[1] + ' | ' + card[2] + ' | ' + card[3] + ' | ' + card[4] + '\n') text.insert(END, '--------------------------------------------------------------\n') text.insert(END, card[5] + ' | ' + card[6] + ' | ' + card[7] + ' | ' + card[8] + ' | ' + card[9] + '\n') text.insert(END, '--------------------------------------------------------------\n') text.insert(END, card[10] + ' | ' + card[11] + ' | FREE SPACE | ' + card[12] + ' | ' + card[13] + '\n') text.insert(END, '--------------------------------------------------------------\n') text.insert(END, card[14] + ' | ' + card[15] + ' | ' + card[16] + ' | ' + card[17] + ' | ' + card[18] + '\n') text.insert(END, '--------------------------------------------------------------\n') text.insert(END, card[19] + ' | ' + card[20] + ' | ' + card[21] + ' | ' + card[22] + ' | ' + card[23] + '\n\n') text.yview(END) def draw(): global text if len(words) == 0: text.insert(END, 'All Words have been drawn!\n') text.yview(END) else: drawn = random.choice(words) words.remove(drawn) text.insert(END, drawn + '\n') text.yview(END) def reset(): global words global text words = ['Mary', 'Joseph', 'Jesus', 'Frosty', 'Manger', 'Presents', 'Snow', 'Chimney', 'Fireplace', 'Star', 'Garland', 'Ornaments', 'Tinsel', 'Mistletoe', 'Church', 'Carols', 'Santa', 'Candy Cane', 'Sledding', 'Elf', 'North Pole', 'Rudolph', 'Hot Cocoa', 'Wise Men', 'Nativity', 'Bethlehem', 'Stockings', 'Gingerbread', 'Egg Nog', 'Lights', 'Donkey', 'Wreath', 'Nice List', 'Sprinkles', 'Cookies', 'Noel', 'Angel', 'Mittens', 'Silver Bells', 'Holly', 'Gift Wrap', 'Grinch', 'Drummer Boy', 'Icicles', 'Marshmallows', 'Nutcracker', 'Frankincense', 'Silent Night', 'Chestnuts'] random.shuffle(words) text.insert(END, 'New Round: Clear your Boards!\n') text.insert(END, '---------------------------------------\n') text.yview(END) root = Tk() root.title('Christmas Bingo') root.geometry('650x500') #TextBox text = Text(root, background='#101010', foreground='#D6D6D6', borderwidth=18, relief='sunken', width=20, height=15, wrap=WORD, font=('Purisa', 15)) text.insert(END, "Welcome to Christmas Bingo!\n\n") text.grid(row=0, column=0, columnspan=6, padx=5, pady=5, sticky=N+S+E+W) #TextBox Tags text.tag_add("alignment", "1.0", "end") text.tag_configure("alignment", justify=CENTER) text.tag_add("title", "1.0", "1.27") text.tag_configure("title", foreground="red", underline=1) #Stretch to fit root.columnconfigure(0, weight=1) root.columnconfigure(1, weight=1) root.columnconfigure(2, weight=1) root.columnconfigure(3, weight=1) root.rowconfigure(0, weight=1) root.rowconfigure(1, weight=1) root.rowconfigure(2, weight=1) root.rowconfigure(3, weight=1) #Buttons Button(root, text = 'Draw', fg = 'green', command = draw).grid(row = 3, column = 0, sticky=N+S+E+W) Button(root, text = 'Reset', fg = 'orange', command = reset).grid(row = 3, column = 1, sticky= N+S+E+W) Button(root, text = 'Create Card', fg = 'Blue', command = CreateCard).grid(row = 3, column = 2, sticky= N+S+E+W) Button(root, text = 'Quit', fg = 'red', command = quit).grid(row = 3, column = 3, sticky= N+S+E+W) root.mainloop()
897d2858ebbcd23487e8b63241decd66f557ef30
simhaonline/ERP-2
/hr/hr.py
3,582
3.828125
4
""" Human resources module Data table structure: * id (string): Unique and random generated identifier at least 2 special characters (except: ';'), 2 number, 2 lower and 2 upper case letters) * name (string) * birth_year (number) """ # everything you'll need is imported: # User interface module import ui # data manager module import data_manager # common module import common file_name = "hr/persons.csv" table = data_manager.get_table_from_file(file_name) def start_module(): """ Starts this module and displays its menu. * User can access default special features from here. * User can go back to main menu from here. Returns: None """ while True: # List of available option list_options = ['Show list of employees', 'Add new employee', 'Remove employee', 'Update employee', 'Get oldest employee', 'Get employee with age closest to average'] # printing menu ui.print_menu("Human resources manager", list_options, "(0) Main menu") # Dict of available option to start equal function dic_function = {'1': show_table, '2': add, '3': remove, '4': update, '5': get_oldest_person, '6': get_persons_closest_to_average, '0': exit} # Start option common.choose_by_dic(dic_function, table) # your code def show_table(table): """ Display a table Args: table (list): list of lists to be displayed. Returns: None """ title_list = ['ID', 'Name', 'Year of birth'] ui.print_table(table, ('ID', 'Name', 'Year of birth')) def add(table): """ Asks user for input and adds it into the table. Args: table (list): table to add new record to Returns: list: Table with a new record """ global file_name employee_id = generate_random(table) employee_name = input('Enter the new employee\'s full name: ') employee_year = input('Enter the new employee\'s year of birth: ') table.append([employee_id, employee_name, employee_year]) write_table_to_file(file_name, table) return table def remove(table, id_): """ Remove a record with a given id from the table. Args: table (list): table to remove a record from id_ (str): id of a record to be removed Returns: list: Table without specified record. """ # your code return table def update(table, id_): """ Updates specified record in the table. Ask users for new data. Args: table (list): list in which record should be updated id_ (str): id of a record to update Returns: list: table with updated record """ # your code return table # special functions: # ------------------ def get_oldest_person(table): """ Question: Who is the oldest person? Args: table (list): data table to work on Returns: list: A list of strings (name or names if there are two more with the same value) """ # your code def get_persons_closest_to_average(table): """ Question: Who is the closest to the average age? Args: table (list): data table to work on Returns: list: list of strings (name or names if there are two more with the same value) """ # your code
96f5fbe27bf7bd62b365d50f0266ce8297042094
amanotk/pyspedas
/pyspedas/dates.py
1,592
4.15625
4
# -*- coding: utf-8 -*- """ File: dates.py Description: Date functions. """ import datetime import dateutil.parser def validate_date(date_text): # Checks if date_text is an acceptable format try: return dateutil.parser.parse(date_text) except ValueError: raise ValueError("Incorrect data format, should be yyyy-mm-dd: '" + date_text + "'") def get_date_list(date_start, date_end): """Returns a list of dates between start and end dates""" d1 = datetime.date(int(date_start[0:4]), int(date_start[5:7]), int(date_start[8:10])) d2 = datetime.date(int(date_end[0:4]), int(date_end[5:7]), int(date_end[8:10])) delta = d2 - d1 ans_list = [] for i in range(delta.days + 1): ans_list.append(str(d1 + datetime.timedelta(days=i))) return ans_list def get_dates(dates): """Returns a list of dates date format: yyyy-mm-dd input can be a single date or a list of two (start and end date) """ ans_list = [] if not isinstance(dates, (list, tuple)): dates = [dates] if len(dates) == 1: try: validate_date(dates[0]) ans_list = dates except ValueError as e: print(e) ans_list = [] elif len(dates) == 2: try: validate_date(dates[0]) validate_date(dates[1]) ans_list = get_date_list(dates[0], dates[1]) except ValueError as e: print(e) ans_list = [] return ans_list
5b083920802fc4b757b8bf06445afdbd9222fd38
VictorDMe/FitnessFunction-with-ComplexNumbers
/Program.py
594
3.578125
4
import cmath for x in range(0, 11): a = x / 10 for y in range(-10, 11): b = y / 10 numero = complex(a, b) conta = (-(pow(numero, 3)) + 4 * (pow(numero, 2)) - 6 * numero + 4) / 5 modulo = cmath.sqrt(conta.imag**2 + conta.real**2) if modulo.real > 0.90: print("\033[34m" + "Número complexo:" + "\033[0;0m" + f" {numero}") #print(f"Resultado da função polinomial: {conta}") print("\033[34m" + "A porcentagem de conveniência é de:" + "\033[0;0m" f" {round((modulo.real * 100), 2)}%") print("")
d5d65042a3159b4490e540d752e7191d37b44fda
veera789/project1
/practice1.py
135
3.765625
4
def func(arg): """ :param arg: taking args :return: returning square """ x = arg*arg return x print(func(20))
5e0ca56488a3cda328eb88bd0a1fdd7ba6cb2bb8
sreckovicvladimir/hexocin
/sqlite_utils.py
1,702
4.125
4
import sqlite3 from sqlite3 import Error def create_connection(db_file): """ create a database connection to the SQLite database specified by db_file :param db_file: database file :return: Connection object or None """ conn = None try: conn = sqlite3.connect(db_file) return conn except Error as e: print(e) return conn def create_table(conn): """ create a table from the create_table_sql statement :param conn: Connection object :param create_table_sql: a CREATE TABLE statement :return: """ sql = """ CREATE TABLE IF NOT EXISTS data_points ( n integer NOT NULL, p integer NOT NULL, data text NOT NULL ); """ try: c = conn.cursor() c.execute(sql) except Error as e: print(e) def populate_table(conn, row): """ Create a new project into the projects table :param conn: :param project: :return: project id """ sql = ''' INSERT INTO data_points(n,p,data) VALUES(?,?,?) ''' cur = conn.cursor() cur.execute(sql, row) conn.commit() return cur.lastrowid def select_row(conn, n, p): """ Return single row from data_points table :param conn: the Connection object :return: """ cur = conn.cursor() cur.execute("SELECT data FROM data_points where n=%d and p=%d" % (n, p)) query = cur.fetchone() if query == None: raise ValueError("Something went wrong, probably arguments out of range or the db isn't properly populated") return query[0]
729de941fa2acf25946f792a079ea801a691e229
JhoplaINC/randomnumb
/randomnumb.py
267
3.859375
4
# -*- coding: utf-8 -*- print("\nIngrese el número del cual quiera saber cuantas combinaciones posibles tiene:") num=int(input()) print("\n**************") num=(num-1)*num print("La cantidad de combinaciones posibles es: "+str(num)) print("**************")
ca6f4a332a7d24905318f6744a92d376d9e9727c
nishi-ai/adventure_game
/adventure_game2.py
1,733
4.09375
4
import time import random def print_pause(message_to_print): print(message_to_print) time.sleep(0.3) def intro(): print_pause("""You find yourself standing in an open field, filled with grass and yellow wildflowers.""") print_pause("""Rumor has it that a wicked fairie is somewhere around here, and has been terrifying the nearby village.""") print_pause("In front of you is a house.") print_pause("To your right is a dark cave.") def cave(items): print_pause("You find an item.") items_list = ["lighter", "candle", "a box of match", "cigarette"] c = random.choice(items_list) if c == "cigarette": print_pause("yay :D") print_pause(c) items.append(c) choose_number(items) def house(items): print_pause("You meet a old man.") print_pause("Talk to him") if items.count("cigarette") < 5: print_pause("He is saying, not enough cigarettes!!!") else: print_pause("He is saying, you won!") choose_number(items) def choose_number(items): print_pause("Enter 1 to knock on the door of the house.") print_pause("Enter 2 to peer into the cave.") print_pause("Enter 0 to quit.") print_pause("What would you like to do?") response = input("Please enter 1 or 2.\n") while response > "0" and response <= "2": print_pause("Please enter 1 or 2") response = input("Please enter 1 or 2.\n") if response == "1": house(items) break elif response == "2": cave(items) break elif response == "0": print_pause("bye") quit() def play_game(): items = [] intro() choose_number(items) play_game()
9676010d8ebd0abd607591d4a983e1d624c2cde4
rundongwen/Connect-4-1
/main.py
2,751
3.9375
4
width = 7 height = 6 board = [] for i in range(height): board.append([" "] * width) def get_move(): column = int(input("Which column do you want? (1-7) ")) if (column > 7 or column < 1): print("ERROR CHARACTER OUT OF RANGE") column = get_move() column -= 1 column_full = False for i in range(height): if board[i][column] == "O": column_full = True break if column_full: print("COLUMN IS FULL") column = get_move() return column def make_move(col, player): row = 0 for i in range(height): if board[i][col] == " ": row = i else: break board[row][col] = player return board def draw_board(board): print("1,2,3,4,5,6,7") for i in board: print("|".join(i)) draw_board(board) def check_win(): #check Horizontal for row in range(width - 1): for col in range(height - 1): if board[row][col] != " ": if board[row][col] == board[row][col + 1] == board[row][ col + 2] == board[row][col + 3]: return board[row][col] #checks Vertical for row in range(width - 1): for col in range(height - 1): if board[row][col] != " ": if board[row][col] == board[row - 1][col] == board[ row - 2][col] == board[row - 3][col]: return board[row][col] #checks Diagonal (top-left to bottom-right) for col in range(height - 3): for row in range(width - 3): if board[row][col] == board[row - 1][col + 1] == board[row - 2][ col + 2] == board[row - 3][col + 3]: return board[row][col] #checks Diagonal (bottom-left to top-right) for col in range(height - 1, height - 3): for row in range(width - 3): if board[row][col] == board[row - 1][col - 1] == board[row - 2][ col - 2] == board[row - 3][col - 3]: return board[row][col] #cat's game/tie full = True for col in range(height): for row in range(width): if board[col][row] == " ": full = False break if full: return "Cat" def main(): winner = " " player = "O" while winner == " ": col = get_move() board2 = make_move(col, player) if player == "O": player = "X" elif player == "X": player = "O" draw_board(board2) winner = check_win() print(check_win()) if winner == "Cat": print("It's a Tie!") else: print("{} is the winner".format(winner)) main()
d0d2fa19d12568cc791210027b37317a9c1d3a93
sxlijin/copenhagent
/lib/logger.py
2,816
3.890625
4
#! /usr/bin/env python """Provides methods to log information to the console and process logs.""" import time, traceback LOG_STR = '[ %10.6f ] %12.12s : %s' def log(event, message=''): """ Logs to console in specific format: [time] event : message. Returns time.clock() at which log() was called. """ t = time.clock() TRIM_LENGTH = 50 if len(message) <= TRIM_LENGTH: print LOG_STR % (t, event, message) else: while len(message) > TRIM_LENGTH: split_index = message.rfind(' ', TRIM_LENGTH-10, TRIM_LENGTH) + 1 if split_index == 0: split_index = TRIM_LENGTH print LOG_STR % (t, event, message[:split_index]) event = '' message = message[split_index:] print LOG_STR % (t, '', message[:split_index]) return t def log_runtime_of(function): """ Runs $function and logs its start, end, and runtime. Tip: use lambda to run functions which take parameters, like so: log_runtime_of(lambda: f(arg1, arg2)) Returns runtime of $function. """ f_name = function.__name__ f_event_str = '%-10.s %s' % (function.__name__, '%9.9s') start = log(f_event_str % '<start>') function_output = function() end = log(f_event_str % '<end>') runtime = end-start log(f_event_str % '<runtime>', '%10.10s() runtime was %10.8f' % (f_name, runtime)) return (runtime, function_output) def log_error(e, event=''): """ Logs an error as [time] error.type : error.value If $event specified, instead logs as [time] $event : error.type -> error.value """ if event == '': log(type(e).__name__, e.message) else: log(event, '%s -> %s' % (type(e).__name__, e.message)) traceback.print_exc() def parse_runtimes(fnames): """ Takes a list of filenames corresponding to files containing logs with runtimes, and writes to STDOUT summaries of the runtime information in said files (what runtimes were logged, average, and number of trials in file). """ runtime_sum = {} runtime_count = {} for fname in fnames: f = open(fname, 'rU') for line in f: if 'runtime' not in line: continue line = line.split(' : ')[1].split() (fxn, runtime) = (line[0], float(line[-1])) if fxn not in runtime_sum: runtime_sum[fxn] = 0.0 runtime_count[fxn] = 0 runtime_sum[fxn] += runtime runtime_count[fxn] += 1 for fxn in runtime_sum: print '%10.10s : %15.15s had average runtime %12.8f ms (%4d trials)' % ( fname, fxn, runtime_sum[fxn]/runtime_count[fxn], runtime_count[fxn])
d5c9916bbc6ae82b54e17f804d24914f8fb89e7e
yudantoanas/PTI
/H02-16518332/H02-16518332-03.py
1,244
3.5625
4
# NIM/Nama : 16518332/Dhafin Rayhan Ahmad # Tanggal : 22 September 2018 # Deskripsi : Membuat segitiga dari 3 lidi # Input y = int(input("Masukkan banyaknya stik Tuan Yon: ")) print("Masukkan panjang stik Tuan Yon:") sy = [0 for i in range(y)] # list panjang stik-stik Tuan Yon for i in range(y): sy[i] = int(input()) # input panjang stik ke-(i+1) milik Tuan Yon r = int(input("Masukkan banyaknya stik Nyai Rin: ")) print("Masukkan panjang stik Nyai Rin:") sr = [0 for i in range(r)] # list panjang stik-stik Nyai Rin for i in range(r): sr[i] = int(input()) # input panjang stik ke-(i+1) milik Nyai Rin m = int(input("Masukkan banyaknya stik Tuan Mi: ")) print("Masukkan panjang stik Tuan Mi:") sm = [0 for i in range(m)] # list panjang stik-stik Tuan Mi for i in range(m): sm[i] = int(input()) # input panjang stik ke-(i+1) milik Tuan Mi # Output print("Daftar segitiga yang dapat dibuat:") # Mencari segitiga yang dapat dibuat for i in range(y): for j in range(r): for k in range(m): if sy[i] + sr[j] > sm[k] and sr[j] + sm[k] > sy[i] and sm[k] + sy[i] > sr[j]: print(str(sy[i]) + " " + str(sr[j]) + " " + str(sm[k])) # output stik-stik yang bisa dibuat segitiga
886597d6b011d22ad5b9dfc4caca918a73096c5a
yudantoanas/PTI
/P02-16518332/P02-16518332-01.py
1,312
3.65625
4
# NIM/Nama : 16518332/Dhafin Rayhan Ahmad # Tanggal : 19 September 2018 # Deskripsi : Menjodohkan laki-laki dan perempuan berdasarkan tingkat kegantengan dan kecantikan # Meminta input data laki-laki N = int(input("Masukkan jumlah laki-laki: ")) # banyaknya laki-laki G = [0 for i in range(N)] # declare array tingkat kegantengan for i in range(N): # input kegantengan G[i] = int(input("Masukkan tingkat kegantengan " + str(i+1) + ": ")) # input kegantengan laki-laki ke-(i+1) # Meminta input data perempuan M = int(input("Masukkan jumlah perempuan: ")) # banyaknya perempuan C = [0 for i in range(M)] # declare array tingkat kecantikan for i in range(M): # input kecantikan C[i] = int(input("Masukkan tingkat kecantikan " + str(i+1) + ": ")) # input kecantikan perempuan ke-(i+1) # Input tolak ukur jodoh (X) X = int(input("Masukkan nilai X: ")) pasangan = 0 # pasangan jodoh yang ditemukan sementara 0 (belum dicari) # Cek jodoh for i in range(N): # Mengecek apakah laki-laki ke-(i+1) memiliki jodoh for j in range(M): # Mengecek apakah perempuan ke-(j+1) adalah jodoh dari laki-laki ke-(i+1) if G[i] + C[j] == X: # jika memenuhi syarat jodoh pasangan += 1 # ditemukan pasangan jodoh, sehingga jumlah pasangan sementara ditambah satu # Output print("Jumlah pasangan yang jodoh ada " + str(pasangan) + ".")
a16fe06da38ea6187da8abddebe261036b5d534b
stjordanis/Activaiton-Funciton-form-Scratch
/tanH/tanH.py
568
3.59375
4
from matplotlib import pylab import pylab as plt import numpy as np #sigmoid = lambda x: 1 / (1 + np.exp(-x)) def sigmoid(x): return (1 / (1 + np.exp(-x))) def tanh(x): return (2/(1+np.exp(-2*x)))-1 x_axis = plt.linspace(-10,10) y_axis = plt.linspace(-1,1) x = plt.linspace(-10,10,100) black = (0,0,0) plt.plot(x, sigmoid(x), 'b', label='Sigmoid') plt.plot(x, tanh(x), 'r', label='Tanh') plt.grid() plt.title('tanH v/s Sigmoid Function') plt.legend(loc='lower right') plt.xlabel('X Axis') plt.ylabel('Y Axis') plt.show()
2583173e3cd813e909c5cc267eadda53088acf5c
airlivered/python_homework
/laboratory3/task1/WordReplace/separator.py
253
3.6875
4
def separate(sentence, character): """ :param sentence: string :param character: string char :return: """ words = sentence.split(character) return words if __name__ == "__main__": print(separate("Oh my"," "))
1578548e1b5a7e37e2ca0dcfdd610cbdb8e491c8
Summersummer3/LeetCodeInPython
/com/example/cipher/gcd.py
470
3.625
4
# -*- coding: utf-8 -*- # __author__ = 'summer' def gcd_1(x, y): if x < 0: x = -x if y < 0: y = -y if x < y: return gcd_1(y, x) else: if y % x == 0: return x else: return gcd_1(y, x - y) def gcd(x, y): if x < 0: x = - x if y < 0: y = - y if x < y: return gcd(y, x) res = x % y if not res: return y else: return gcd(y, res)
1787ce826a6d13c27631aefad09e6def1698ecfb
Summersummer3/LeetCodeInPython
/com/example/LeetCode/luckyString.py
793
3.5
4
# -*- coding: utf-8 -*- # __author__ = 'summer' def luckyString(str): """ Microsoft coding test :param str: :return: """ res = [] fb = [1, 1] while fb[-1] < 26: fb.append(fb[-1] + fb[-2]) for i in xrange(len(str)): j = i while j <= len(str): count = 0 last = "" for s in str[i:j]: if not s in last: count += 1 last += s if count in fb and str[i:j] not in res: res.append(str[i:j]) j += 1 res.sort() for p in res: print p def input_test(): n = int(raw_input()) return n if __name__ == '__main__': for i in range(input_test()): s = raw_input().strip().strip()
95d1ceac57777490313fbc3f6024c1fb93edbcfb
Summersummer3/LeetCodeInPython
/com/example/LeetCode/MinSubstring.py
634
3.625
4
# -*- coding: utf-8 -*- # __author__ = 'summer' """ any two chars in str2 should not be identical. """ def minSubtring(str1, str2): lst = list(str2) pos = [-1] * len(str2) length, s, t = 0, 0, 0 for i, c in enumerate(str1): if c in lst: pos[lst.index(c)] = i if -1 not in pos and (not length or length > max(pos) - min(pos)): s = min(pos) t = max(pos) length = t - s if length: return str1[s: t + 1] else: return "no" if __name__ == '__main__': str1 = raw_input() str2 = raw_input() print minSubtring(str1, str2)
c11dea262eb49ade8ffdd84256c1831f976ce74a
Summersummer3/LeetCodeInPython
/com/example/sort/quickSort.py
1,698
4.03125
4
import random def quicksort(arr,begin,end): if begin < end: middle = partition(arr, begin, end) quicksort(arr, begin, middle-1) quicksort(arr, middle+1, end) def partition(arr,begin,end): position = end para = arr[end] while begin < end: if arr[begin] > para: if arr[end-1] < para: temp = arr[begin] arr[begin] = arr[end-1] arr[end-1] = temp begin += 1 end -= 1 else: end -= 1 else: begin += 1 temp = arr[begin] arr[begin] = arr[position] arr[position] = temp return begin def randomized_quicksort(arr, begin, end): if begin < end: middle = partition(arr, begin, end) randomized_quicksort(arr, begin, middle-1) randomized_quicksort(arr, middle+1, end) def randomized_partition(arr, begin, end): position = random.randint(begin, end) para = arr[position] temp_1 = arr[end] arr[end] = para arr[position] = temp_1 position = end while begin < end: if arr[begin] > para: if arr[end-1] < para: temp = arr[begin] arr[begin] = arr[end-1] arr[end-1] = temp begin += 1 end -= 1 else: end -= 1 else: begin += 1 temp_2 = arr[begin] arr[begin] = arr[position] arr[position] = temp_2 return begin if __name__ == '__main__': a = [] for each in range(0,50): a.append(random.randint(0,100)) print a randomized_quicksort(a, 0, len(a)-1) print a
03a9338b9bac7b896e2550a539c99e7ae93ccaca
Summersummer3/LeetCodeInPython
/com/example/LeetCode/climbStairs.py
272
3.65625
4
__author__ = 'summer' def climbStairs(n): """ :type n: int :rtype: int """ dp =[1, 2] index = 2 while len(dp) < n: dp.append(dp[index - 1] + dp[index - 2]) index += 1 return dp[0] if n == 1 else dp[-1] print climbStairs(3)
04da350a513c7cc103b948765a1a24b9864686e1
JayHennessy/Stack-Skill-Course
/Python_Intro/pandas_tutorial.py
631
4.28125
4
# Python Pandas tutorial (stackSkill) import pandas as pd import matplotlib.pyplot as plt from matplotlib import style data = pd.read_csv('C:/Users/JAY/Desktop/Machine_Learning_Course/KaggleCompetions/titanic_comp/data/test.csv') # shows data on screen print(data.head()) data.tail() #print the number of rows (incldues the header) print(len(data.index)) # return rows that meet a certain condition # here we get the date value for all the days that have rain in the event column rainy_days = data['Date'][df['Events']=='Rain'] # plot the results with matplotlib style.use('classic') data['Max.TemperatureC'].plot() plt.show()
5a4c3d746a52616fc62d93a90f15e44f2ef8dd74
Kstyle0710/KOR_NLP
/test.py
567
3.578125
4
# a = "abd cdf ede kdof diknd" # print(type(a)) # # b = [x for x in a.split(" ")[:-1]] # print(b) # print(type(b)) # # k = "my home" # # print(f"제가 있는 장소는 {k}") ## 단어간 동일성 비교 테스트 print("절단"=="절단") print("절단"=="절단기") print("절단"in"절단") print("절단"in"절단기") print("-"*30) target = ["절단기", "절단장비"] def including_check(k): if k in [x for x in target][0]: print("Included") else: print("Not Included") including_check("절단기") including_check("절단")
f62bd2ec440e3929c5aee99d0b90fd726e3f3eff
aniket0106/pdf_designer
/rotatePages.py
2,557
4.375
4
from PyPDF2 import PdfFileReader,PdfFileWriter # rotate_pages.py """ rotate_pages() -> takes three arguements 1. pdf_path : in this we have to pass the user pdf path 2. no_of_pages : in this we have to pass the number of pages we want to rotate if all then by default it takes zero then we re-intialize it to total number of pages 3. clockwise : it is default args which take boolean value if its value is True then it will right rotate by given angle if it is false then it will rotate towards the left by given angle getNumPages() : is the function present in the PyPDF2 which is used to get the total number of page present inside the inputted pdf getPage(i) : is the function which return the particular page for the specified pdf rotateClockwise(angle) : is the function which rotate the specified page by given angle towards to right rotateCounterClockwise(angle) : is the function which rotate the specified page by given angle towards the left """ def rotate_pages(pdf_path,no_of_pages=0,clockwise=True): # creating the instance of PdfFileWriter we have already initialize it with our output file pdf_writer = PdfFileWriter() pdf_reader = PdfFileReader(pdf_path) total_pages = pdf_reader.getNumPages() if no_of_pages == 0: no_of_pages = total_pages if clockwise: for i in range(no_of_pages): page = pdf_reader.getPage(i).rotateClockwise(90) pdf_writer.addPage(page) with open('rotate_pages.pdf', 'wb') as fh: pdf_writer.write(fh) for i in range(no_of_pages,total_pages): page = pdf_reader.getPage(i) pdf_writer.addPage(page) with open('rotate_pages.pdf', 'wb') as fh: pdf_writer.write(fh) else: for i in range(no_of_pages): page = pdf_reader.getPage(i).rotateCounterClockwise(90) pdf_writer.addPage(page) with open('rotate_pages.pdf', 'wb') as fh: pdf_writer.write(fh) for i in range(no_of_pages,total_pages): page = pdf_reader.getPage(i) pdf_writer.addPage(page) with open('rotate_pages.pdf', 'wb') as fh: pdf_writer.write(fh) """ f=FileWriter("rotate_pages.pdf","wb") pdf_writer = PdfWriter(f) pdf_writer.write() """ if __name__ == '__main__': path = 'F:\pdf\ex1.pdf' rotate_pages(path,no_of_pages=10,clockwise=True)
6dfb27bd2d23c7523d8566fc4aa82301c7072e0f
vikashsingh3/Python_3.7_Codewars
/mexican_wave_codewars_com.py
1,921
4.09375
4
# Title: Mexican Wave # Source: codewars.com # Site: https://www.codewars.com/kata/58f5c63f1e26ecda7e000029 # Code by: Vikash Singh # # Description: # Introduction # The wave (known as the Mexican wave in the English-speaking world outside North America) is an example of metachronal # rhythm achieved in a packed stadium when successive groups of spectators briefly stand, yell, and raise their arms. # Immediately upon stretching to full height, the spectator returns to the usual seated position. # The result is a wave of standing spectators that travels through the crowd, even though individual spectators # never move away from their seats. In many large arenas the crowd is seated in a contiguous circuit all the way # around the sport field, and so the wave is able to travel continuously around the arena; in discontiguous seating # arrangements, the wave can instead reflect back and forth through the crowd. When the gap in seating is narrow, # the wave can sometimes pass through it. Usually only one wave crest will be present at any given time in an arena, # although simultaneous, counter-rotating waves have been produced. (Source Wikipedia) # # Task # In this simple Kata your task is to create a function that turns a string into a Mexican Wave. You will be # passed a string and you must return that string in an array where an uppercase letter is a person standing up. # Rules # 1. The input string will always be lower case but maybe empty. # 2. If the character in the string is whitespace then pass over it as if it was an empty seat. # Example # wave("hello") => ["Hello", "hEllo", "heLlo", "helLo", "hellO"] def wave(message): final_message = [] for num in range(len(message)): if message[num].strip() != "": final_message.append(message[0:num].lower() + message[num].upper() + message[num+1:].lower()) return final_message
94ddb075e4106f14c1c445b7164c3b6cffd93d57
amigo7777/-Pyhton-2
/Фильтр.py
193
3.609375
4
n = int(input()) lst =[] for i in range(n): s = input() if s.startswith('%%'): s = s[2:-1] if not s.startswith('####'): lst.append(s) print(*lst, sep='\n')
18e6cbf32704a4a009fff77d18aaf6e8e5417615
rishabhsagar123/PYTHON-PROJECTS
/Dictionary.py
1,373
3.84375
4
from tkinter import * window=Tk() window.title("First Application of Tkinter") def click(): entered_text=textentry.get() output.delete(0.0,END) try: defination=my_compdictionery[entered_text] Label(window,text="Yes in dictionery Check Console",fg="yellow",bg="red").grid(row=10,column=0) print(defination) except: defination="sorry there is no word in it please try again" output.insert(END,defination) def close_window(): window.destroy() exit() photo1=PhotoImage(file="C:\\Users\\hp\\Desktop\\panda copy.png") Label(window,image=photo1,bg="black").grid(row=0,column=0) Label(window,text="rishabh",fg="white",bg="black",font="none 12 bold").grid(row=1,column=0) textentry=Entry(window,width=20,bg="white") textentry.grid(row=2,column=0) Button(window,text="SELECT",width=6,command=click).grid(row=3,column=0) output=Text(window,width=75,height=6,wrap=WORD,background="white") output.grid(row=5,column=0,columnspan=2,sticky=W) my_compdictionery = { 'algorithm' : 'A piece of code is called algorithm', 'bug' : 'Any Problem in a program' } Label(window,text="Click To Exit:",bg="black",fg="white",font="none 12 bold").grid(row=6,column=0) Button(window,text="CLOSE",width=6,command=close_window).grid(row=7,column=0) window.mainloop()
25c7f9ba79d68d3c30cbd4ceb1bee12105a24ea0
abhayycs/BlockChain
/others/key_generation.py
1,108
3.5625
4
from Crypto.PublicKey import RSA from Crypto import Random random_generator = Random.new().read # ARGUMENTS: 1) KEY_LENGTH, 2) RANDOM NUMBER GENERATOR key = RSA.generate(1024, random_generator) print('key:\t',key) # WRITE DOWN PUBLIC AND PRIVATE KEY IN A FILE with open('mykey.pem','wb') as file: file.write(key.exportKey('PEM')) # private key file.write(b"\n") # new line in binary form file.write(key.publickey().exportKey('PEM')) # PUBLIC KEY #Public Key can be changed after each transaction print('public key:\t',key.publickey().exportKey('PEM')) # A matching RSA public key. public_key = key.publickey() # Size of the RSA modulus in bits # print("Size of key:\t", key.size_in_bits()) # The minimal amount of bytes that can hold the RSA modulus. # print("Size:\t", key.size_in_bytes()) print("key.can_encrypt",key.can_encrypt()) print("key.can_sign",key.can_sign()) # Whether this is an RSA private key print("key.has_private",key.has_private()) enc_data = public_key.encrypt('This is great!', 32) print("Encrypted data is : ",enc_data) print("Decrypted data is ",key.decrypt(enc_data))
10fd4011d6f775bbb9a5cad35e2e267ea43ade18
Gabriel-f-r-bojikian/RPN-calculator
/calculadoraRPN.py
1,952
3.828125
4
#Calculadora implementada como uma classe. As operações aritméticas básicas e potenciação foram implementadas import operacoes import entrada class calculadoraRPN: def __init__(self): self.operadoresAceitos = operacoes.operadoresAceitos self.pilhaDeNumeros = [] self.pilhaDeOperacoes = [] self.fluxoEntrada = entrada.inputStream(self.operadoresAceitos) def recebeInputDoUsuario(self): self.fluxoEntrada.recebeStreamEntrada() numeros, operadores = self.fluxoEntrada.separaNumeroDeOperador() return numeros, operadores def montaPilhaNumeros(self, listaDeNumeros): for numero in listaDeNumeros: self.pilhaDeNumeros.append(numero) def montaPilhaOperacoes(self,listaDeOperacoes): for operacao in listaDeOperacoes: self.pilhaDeOperacoes.append(operacao) def fazContas(self): valorDireito = 0 valorEsquerdo = 0 while len(self.pilhaDeOperacoes) > 0: if not len(self.pilhaDeOperacoes) == 0: operacao = self.pilhaDeOperacoes.pop(0) else: break if not len(self.pilhaDeNumeros) == 0: valorDireito = self.pilhaDeNumeros.pop() else: print("Erro: Pilha vazia") break if not len(self.pilhaDeNumeros) == 0: valorEsquerdo = self.pilhaDeNumeros.pop() else: print("Erro: Numero insuficiente de argumentos") self.pilhaDeNumeros.append(valorDireito) break resultado = operacoes.fazContaIndividual(valorEsquerdo, valorDireito, operacao) self.pilhaDeNumeros.append(resultado) print("") print("\t= ", resultado, "\n") def loopPrincipal(self): while True: print(self.pilhaDeNumeros) numeros, operadores = self.recebeInputDoUsuario() self.montaPilhaNumeros(numeros) self.montaPilhaOperacoes(operadores) self.fazContas() if __name__ == '__main__': calc = calculadoraRPN() calc.loopPrincipal()
d1a5ff40143e7adbbb8dd7c7928c389488701a3a
ardulat/deep-learning
/amaratkhan_assignment1.py
3,375
4.0625
4
import numpy as np import matplotlib.pyplot as plt from random import randint def partition(A, start, end): pivot = A[end] partitionIndex = start for i in range(start, end): if (A[i] < pivot): A[i], A[partitionIndex] = A[partitionIndex], A[i] partitionIndex += 1 A[end], A[partitionIndex] = A[partitionIndex], A[end] return partitionIndex def quickSortHelper(A, start, end): if (start < end): pivotIndex = partition(A, start, end) quickSortHelper(A, start, pivotIndex-1) quickSortHelper(A, pivotIndex+1, end) def quickSort(A): start = 0 end = len(A) quickSortHelper(A, start, end-1) def binarySearch(A, x): """A - array, x - element to search""" low = 0 high = len(A)-1 mid = 0 comparisons = 0 while (low <= high): mid = int((low+high)/2) comparisons += 1 if(A[mid] < x): # look on the right half low = mid+1 elif(A[mid] > x): # look on the left half high = mid-1 else: # we found it # print("WE FOUND IT!") return comparisons # print("THERE IS NO SUCH ELEMENT!") return comparisons def exhaustiveSearch(A, x): comparisons = 0 for i in range(0, len(A)): comparisons += 1 if (A[i] == x): # print("WE FOUND IT!") return comparisons # print("THERE IS NO SUCH ELEMENT!") return comparisons if __name__ == "__main__": # uncomment if you want to make the output of random function the same each time # np.random.seed(42) # generating random array to check if sort and search works A = np.random.randint(0, 100, 10) quickSort(A) print(A) x = binarySearch(A, 51) x = exhaustiveSearch(A, 72) # compute execution times for BINARY SEARCH binarySearchResults = [] binarySearchX = [] for i in range(0, 1001, 10): binarySearchX.append(i) t = 10 # number of times to calculate total_comparisons = 0 for j in range(0, t): A = np.random.randint(0, 100, i) # generate random array with size = i quickSort(A) x = randint(0, 100) # generate random integer to search comparisons = binarySearch(A, x) total_comparisons += comparisons avg_comparisons = total_comparisons / t binarySearchResults.append(avg_comparisons) # compute execution times for EXHAUSTIVE SEARCH exhaustiveSearchResults = [] exhaustiveSearchX = [] for i in range(0, 1001, 10): exhaustiveSearchX.append(i) t = 10 # number of times to calculate total_comparisons = 0 for j in range(0, t): A = np.random.randint(0, 100, i) # generate random array with size = i quickSort(A) x = randint(0, 100) # generate random integer to search comparisons = exhaustiveSearch(A, x) total_comparisons += comparisons avg_comparisons = total_comparisons / t exhaustiveSearchResults.append(avg_comparisons) print(binarySearchX) print(binarySearchResults) print() print(exhaustiveSearchX) print(exhaustiveSearchResults) plt.plot(binarySearchX, binarySearchResults, exhaustiveSearchX, exhaustiveSearchResults, 'r') plt.show()
dde08f772720d8f6935ed1f2a200eb65d1406f0a
JRJurman/persistent-number-generator
/functions/mapListToBase.py
374
3.703125
4
from functions.toBaseN import toBaseN def originalAndStringOfBaseN(base): def originalAndString(number): return (number, toBaseN(base)(number)) return originalAndString def mapListToBase(numbers, base = 10): """ convert numpy array into integer of base only use for printing """ return list(map(originalAndStringOfBaseN(base), list(map(int, numbers))))
4e39f38eee0b84dcd74e15281ae99759faa53362
liorkesten/Data-Structures-and-Algorithms
/Algorithms/Sorting_Algorithms/Linear_Sorting/BinSort.py
748
4.0625
4
def binSort(A, m): """ Bin Sorting_Algorithms - algorithm: gets an array of int numbers, find the maximum value (m) in the array, than create an list of [0,1,...,m] and than increase the counter of the A array. Put the amount of each index in ret array and return ret :param m: :param A: array of int nums :return: new Array that is sorted. """ # Define bins in len m+1 because m is the max value so bins[0]=0, # bins[m+1]=m bins = [0] * (m + 1) for index in A: bins[index] += 1 # Init the return value arr ret = [0] * len(A) j = 0 # Index of ret Array for i in range(m + 1): for k in range(bins[i]): ret[j] = i j += 1 return ret
e340d8b94dc7c2f32e6591d847d8778ed5b5378b
liorkesten/Data-Structures-and-Algorithms
/Algorithms/Arrays_Algorithms/isArithmeticProgression.py
666
4.3125
4
def is_arithmetic_progression(lst): """ Check if there is a 3 numbers that are arithmetic_progression. for example - [9,4,1,2] return False because there is not a sequence. [4,2,7,1] return True because there is 1,4,7 are sequence. :param lst: lst of diff integers :return: True or False if there is a 3 sequence in the lst. """ set_of_values = set(lst) # Check if there is 3 monotony for i in range(len(lst)): for j in range(i + 1, len(lst)): third_num = abs(lst[i] - lst[j]) + max(lst[i], lst[j]) if third_num in set_of_values: return True return False
ab37c638cb42eea91065d8280e4f5ae74539a56a
liorkesten/Data-Structures-and-Algorithms
/Algorithms/BinaryRep_Algorithms/BinaryRepresantion.py
2,081
4.03125
4
from Data_Structures.my_doubly_linked_list import * def binaryRep(n): """ Function that gets an int number and return a linked list the represent the number in binary representation Time complexity: log(n) :param n: integer number :return: linked list - binary representation of n """ # Create list of k pows of 2 s.t 2^k>n len_span = 0 # Edge case # if len_span == 0: # len_span = 1 while 2 ** len_span <= n: len_span += 1 span = [2 ** i for i in range(len_span)] # Add to linked list the binary rep of n bin_rep = MyLinkedList() for i in range(len(span) - 1, -1, -1): if n >= span[i]: n -= span[i] bin_rep.push(1) else: bin_rep.push(0) return bin_rep def addOne(L): """ Gets a linked list the represent num and increase the num by one Time complexity : Log(n) :param L: Linked list the represent a num :return: None - change the current Linked list """ cur = L.tail while cur: if cur.data == 1: cur.data = 0 else: # Cur.data = 0 cur.data = 1 break cur = cur.prev else: L.push(1) def decreaseOne(L): """ Gets a linked list the represent num and decrease the num by one :param L: Linked list the represent a num :return: None - change the current Linked list """ cur = L.tail while cur: if cur.data == 0: cur.data = 1 else: # Cur.data = 1 cur.data = 0 break cur = cur.prev # In case that we have to delete the last pow. # For ex decrease 8 - 1,0,0,0 --> 0,1,1,1 --> 1,1,1 if L.head.data == 0: L.head = L.head.next L.len -= 1 def createRepByAddOne(n): """ Function that create a binary representation by adding one to linked list: Time complexity: O(n) :param n: :return: """ l = binaryRep(0) for i in range(n): addOne(l) return l
6101f3df70700db06073fd8e3723dba00a02e9d9
liorkesten/Data-Structures-and-Algorithms
/Algorithms/Arrays_Algorithms/BinarySearch.py
577
4.21875
4
def binary_search_array(lst, x): """ Get a sorted list in search if x is in the array - return true or false. Time Complexity O(log(n)) :param lst: Sorted lst :param x: item to find :return: True or False if x is in the array """ if not lst: return False if len(lst) == 1: return x == lst[0] mid = len(lst) // 2 if lst[mid] == x: return True elif lst[mid] < x: return binary_search_array(lst[mid + 1:], x) elif lst[mid] > x: return binary_search_array(lst[:mid], x)
4ad8813ec4be6393f4e8900885e900db9ddb7b32
liorkesten/Data-Structures-and-Algorithms
/Algorithms/Sorting_Algorithms/QuickSort.py
735
4
4
from Algorithms.Arrays_Algorithms.Partition import rand_partition # _____________________________Random sorting_________________________________ def quick_sort(lst, s=0, e=-1): """ Quick Sorting_Algorithms - Random pivot. Time complexity - n*log(n) in the avg case. n^2 in the worst case. :param a: array :param s: start index :param e: end index :return: None - change the origin array. """ # change e to the len of a. if e == -1: e = len(lst) - 1 if s >= e: return p = rand_partition(lst, s, e) # Recursive calls quick_sort(lst, p + 1, e) # Recursive right quick_sort(lst, s, p - 1) # Recursive left
ffbf1e335934e537f4d29e1391595edc49761389
patpiet/Projects_Learning
/clock_timer/countdown_clock.py
1,885
3.9375
4
import time from tkinter import * from tkinter import messagebox root = Tk() root.title("Countdown App") root.geometry("300x250") # Create count variables hour = StringVar() minute = StringVar() second = StringVar() title = StringVar() hour.set("00") minute.set("00") second.set("00") # Create Labels hour_label = Label(root, text="HOUR") hour_label.place(x=80, y=10) minute_label = Label(root, text="MINUTE") minute_label.place(x=126, y=10) second_label = Label(root, text="SECOND") second_label.place(x=176, y=10) title_label = Label(root, text="Alarm title:") title_label.place(x=120, y=120) # Create Entries hourEntry = Entry(root, width=3, font=("Arial", 18, ""), textvariable=hour) hourEntry.place(x=80, y=30) minuteEntry = Entry(root, width=3, font=("Arial", 18, ""), textvariable=minute) minuteEntry.place(x=130,y=30) minuteEntry = Entry(root, width=3, font=("Arial", 18, ""), textvariable=second) minuteEntry.place(x=180,y=30) titleEntry = Entry(root, width=40, font=("Arial", 9, ""), textvariable=title) titleEntry.place(x=10, y=140) def submit(): title_inside = titleEntry.get() try: # Input provided by user = temp temp = int(hour.get())*3600 + int(minute.get())*60 + int(second.get()) except: error_label = Label(root, text="Please enter the right value!") error_label.place(x=76, y=60) while temp > -1: mins, secs = divmod(temp, 60) hours = 0 if mins > 60: hours, mins = divmod(mins, 60) hour.set("{0:2d}".format(hours)) minute.set("{0:2d}".format(mins)) second.set("{0:2d}".format(secs)) root.update() time.sleep(1) if temp == 0: messagebox.showinfo("Time Countdown!", title_inside) temp -= 1 btn = Button(root, text='Set Time Countdown', bd='5', command = submit) btn.place(x = 87,y = 200) root.mainloop()
fe8691af8e917efb28d2311a0ee093d1edb34787
samanthaWest/Python_Scripts
/HackerRank/MinMaxSum.py
450
3.515625
4
#!/bin/python3 import math import os import random import re import sys # # Complete the 'miniMaxSum' function below. # # The function accepts INTEGER_ARRAY arr as parameter. # def miniMaxSum(arr): arr_length = len(arr) sorted_arr = sorted(arr) print(sum(sorted_arr[:4]), sum(sorted_arr[arr_length - 4:])) if __name__ == '__main__': arr = list(map(int, input().rstrip().split())) miniMaxSum(arr)
bc575d9e0b25e519b50e9b22c038975fc85aeef8
samanthaWest/Python_Scripts
/DataStructsAndAlgorithms/Searching/JumpSearch.py
1,888
4.03125
4
# Jump Search # https://www.geeksforgeeks.org/jump-search/ # Alg for sorted arrays, check fewer elements then linear # search by jumping ahead by fixed steps or skipping some eements in place of searching all ele # Binar ysearch is better then jump search but jump searches advantage is being able to traverse back only once, where the # smallest element of the smaller group. So in a system where binary search is costly we do a jump search. # https://www.youtube.com/watch?v=63kS6ZkMpkA&ab_channel=GeeksforGeeks # Jump the amuont of steps until you find something gret then or ewqual to x then do a linear search backwards # https://www.youtube.com/watch?v=wNOoyZ45SmQ&ab_channel=TECHDOSE import math def jumpSearch(arr, x, n): # finding size of block to be jumped step = math.sqrt(n) prev = 0 # finding block where ele is present while arr[int(min(step, n) -1)] < x: # Min number between step and n - 1 value in the array is it greater then the target valyue print('-------') print(int(min(step, n) -1)) print(arr[int(min(step, n) -1)]) print(x) prev = step step += math.sqrt(n) # go up another 4 steps print(step) if prev >= n: return -1 # Doing a linear search for x in # block beginning with prev. print(prev) while arr[int(prev)] < x: prev += 1 # If we reached next block or end # of array, element is not present. if prev == min(step, n): return -1 # If element is found if arr[int(prev)] == x: return prev return -1 # Driver code to test function arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610 ] x = 55 n = len(arr) # Find the index of 'x' using Jump Search print(jumpSearch(arr, x, n))
d37d608744317b4e7957d53a77ce52f3483161ce
samanthaWest/Python_Scripts
/DataStructsAndAlgorithms/Stack/QueueUsingStacks.py
2,043
4.0625
4
# Costly enque operation # Enqueing from the left and dequing from the right class Queue: def __init__(self): self.s1 = [] self.s2 = [] def enQueue(self, x): # TC: O(n) # Emptying list one into list 2 from the end of list 2 # List 1 : 1 , 2 , 3 # After Changign to list 2 # List 2 : 3 , 2 , 1 while len(self.s1) != 0: self.s2.append(self.s1[-1]) # Taking last element in the list with [-1] self.s2.pop() self.s1.append(x) # Adding new data value to the top of the list # List 1 : 5 # List 2 : 3, 2 , 1 # New List 1: 5 , 1 , 2 , 3 while len(self.s2) != 0: # Loading all elements back into origonal list after new value insertion self.s1.append(self.s2[-1]) self.s2.pop() def deQueue(self): # TC: O(1) if len(self.s1) == 0: print("Empty Q") # Return top of self.1 x = self.s1[-1] self.s1.pop() return x # Costly deque operation # Enquing from the left and dequing from the right class Queue2: def __init__(self): self.s1 = [] self.s2 = [] def enQueue(self, x): # TC: O(1) self.s1.append(x) def deQueue(self): # TC: O(n) if len(self.s1) == 0 and len(self.s2) == 0: print("Q is Empty") return # List 1 = 1 ,2 , 3 # List 2 = [] # After # List 1 = [] # List 2 = 3 , 2 , 1 # Remove top element from list 2 and return # List 1 = [] # List 2 = 3, 2 elif len(self.s2) == 0 and len(self.s1) > 0: while len(self.s1): # Push everything from stack 1 to stack to and now the list has the top element at the end, pop return temp = self.s1.pop() self.s2.append(temp) return self.s2.pop() else: return self.s2.pop()
a0e52ed563d1f26e274ef1aece01794cce581323
samanthaWest/Python_Scripts
/DataStructsAndAlgorithms/TwoPointersTechnique.py
784
4.3125
4
# Two Pointers # https://www.geeksforgeeks.org/two-pointers-technique/ # Used for searching for pairs in a sorted array # We take two pointers one representing the first element and the other representing the last element # we add the values kept at both pointers, if their sum is smaller then target we shift left pointer to the # right. If sum is larger then target we shift right pointer to the left till be get closer to the sum. def isPairSum(arr, lenghtArray, target): l = 0 # first pointer r = lenghtArray - 1 # second pointer while l < r: curSum = numbers[l] + numbers[r] if curSum > target: r -= 1 elif curSum < target: l += 1 else: return [l + 1, r + 1]
68c804bf7acf9572256e553810571de3f10f151f
samanthaWest/Python_Scripts
/DesignPatterns/design_pattern_observer_weather_app.py
2,400
3.578125
4
from abc import ABC, abstractmethod ############## # Interfaces # ############## # Observer Interface class Observer(ABC): @abstractmethod def update(self): pass # Display Element Interface class DisplayElement(ABC): @abstractmethod def display(self): pass # Subject Interface class Subject(ABC): @abstractmethod def registerObserver(self, o: Observer): pass @abstractmethod def removeObserver(self, o: Observer): pass @abstractmethod def notifyObservers(self): pass ################## # Implementation # ################## class WeatherData(Subject): def __init__(self): self._observers = [] self._tempature = 0 self._humidity = 0 self._pressure = 0 def registerObserver(self, o: Observer): self._observers.append(o) def removeObserver(self, o: Observer): self._observers.remove(o) def notifyObservers(self): for o in self._observers: o.update() def getTempature(self): return self._tempature def getHumidity(self): return self._humidity def getPressure(self): return self._pressure def measurementsChanged(self): self.notifyObservers() def setMeasurements(self, temp: int, humidity: int, pressure: int): self._tempature = temp self._humidity = humidity self._pressure = pressure self.measurementsChanged() class CurrentConditionDisplay(Observer, DisplayElement): def __init__(self, weatherData: WeatherData): self._tempature = 0 self._humidity = 0 self._pressure = 0 self._weatherData = weatherData self._weatherData.registerObserver(self) def update(self): self._tempature = self._weatherData.getTempature() self._humidity = self._weatherData.getHumidity() self._pressure = self._weatherData.getPressure() self.display() def display(self): print("Current Conditions " + str(self._tempature) + "F " + str(self._humidity) + "%") if __name__ == '__main__': weatherData = WeatherData() currentDisplay = CurrentConditionDisplay(weatherData) weatherData.setMeasurements(80, 65, 30.4) weatherData.setMeasurements(90, 61, 30.4)
6686c069121b9b4d384c0f2ec5fb3293dee4d8a9
samanthaWest/Python_Scripts
/HackerRank/Trees/Insertion.py
373
3.78125
4
class newNode(): def __init__(self, data): self.key = data self.left = None self.right = None def insert(temp, key): if not temp: root = newNode(key) q = [] q.append(temp) while (len(q)): # Take no from the queue to search through temp = q[0] q.pop(0)
c98020ca384a60af1a0e53dc6369e3eee5867884
Fahien/pyspot
/test/script/map-test.py
228
3.515625
4
import pyspot def create_week(): week = pyspot.test.Week() if week.days[1] == "monday": return week else: return None def modify_monday( week ): days = week.days days[1] = "tuesday" week.days = days
e965acf456da9568da5112a120d9d7d3bec34132
animan123/inference
/input.py
2,313
3.765625
4
from term import term def get_operator (op): if op == '=': return 'imply' if op == '|': return 'or' if op == '&': return 'and' raise Exception ("Invalid operator " + op) def isUpper (x): return x>='A' and x<='Z' def get_pred_dict (pred_string): first_bracket = pred_string.index('(') pred_name = pred_string[:first_bracket] pred_args = pred_string[first_bracket+1:-1].split(',') pred_args = [x.replace('(','') for x in pred_args] pred_args = [x.replace(')','') for x in pred_args] return { "name": pred_name, "args": pred_args } def preprocess (s): s = s.replace ('=>', '=') s = s.replace (' ', '') t = '' i = 0 while i < len(s): if isUpper (s[i]) and s[i-1] != '~' and not isUpper(s[i-1]): j = s.index(')', i+1) x = '(' + s[i:j+1] + ')' t += x i = j+1 else: t += s[i] i += 1 return t def process (s): s = s[1:-1] #print len(s), s if (s[0]=='~' and isUpper(s[1])) or (isUpper(s[0])): #print "part 1" if s[0] == '~': s = s[1:] truth = False else: truth = True return term(truth=truth, pred=get_pred_dict (s)) elif s[0]=='~': #print "part 2" return term(truth=False, args=[process(s[1:])]) else: #print "part 3" substring = '' args = [] count = 0 op = None for c in s: if c in ['&', '|', '='] and count == 0: op = c else: substring += c if c == '(': count += 1 if c == ')': count -= 1 if count == 0: if (c == ')' and op is not None) or c in ['&', '|', '=']: #print "Sending substring: ", substring args.append (process(substring)) substring = '' return term(op=get_operator(op), args=args) def get_cnf (s): s = preprocess (s) t = process(s) t.simplify () return t.get_cnf () if __name__ == '__main__': #s = '((AA(x, y)|(~BB(p, q)))=>(CC(x)|DD(p)))' #s = '(~(~(~(~(~A(x))))))' #s = '((A(x)=>B(x))=>C(x))' #s = 'Q(Alice, Bob)' #s = '((~(Parent(x,y) & Ancestor(y,z))) | Ancestor(x,z))' #s = '(~(Parent(x,y) & Ancestor(y,z)))' #s = '(~(Dog(y) => Loves(x,y)))' #s = '((Travel(Santa, Christmas) => Child(x)) & (Present(y) & Give(Santa, y, x)))' s = '(Travel(Santa, Christmas) => (Child(x) & (Present(y) & Give(Santa, y, x))))' s = preprocess (s) t = process (s) #t.show () t.simplify () t.show () ''' cnf = t.get_cnf () for x in cnf: print x '''
fb876f79260e8f65d452ad3674b2fbe5a8bd174a
priscila-rocha/Python
/Curso em video/ex007.py
129
3.8125
4
n1 = int(input('Digite sua 1ª nota: ')) n2 = int(input('Digite sua 2ª nota: ')) print('Sua média foi: {}'.format((n1+n2)/2))