blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
55b85abe021098cc1b7825729eb3c8d9d92f8b4b
FishoGithub/Five_Question_Quiz
/main.py
3,167
3.8125
4
#colors green = "\033[0;32m" red = "\033[0;31m" yellow = "\033[0;33m" blue = "\033[0;34m" magenta = "\033[0;35m" cyan = "\033[0;36m" white = "\033[0;37m" bright_cyan = "\033[0;96m" bright_blue = "\033[0;94m" name = "Mihir" score = 0 answer = "" def zero(): print(white + "nothing") def one(): print(white + "hotdog") def two(): print(white + "e") def three(): print(white + "a") def four(): print(white + "sports") def five(): print(white + "H A M B O U R G E R.") def quiz_method(): global score global answer print(bright_cyan + "Welcome to the 5 question quiz. answer all the questions correctly to recive: " + green + " H A M B O U R G E R.\n") print(bright_blue + "First Question: \n\n") answer = input(bright_blue + "Which language is used to make a webpage look good? Is it: \n A. JavaScript,\n B. CSS,\n C. HTML").lower().strip() if answer == "a": print(red + "Incorrect.") elif answer == "c": print(red + "Incorrect.") elif answer == "b": print(green + "Correct!") score += 1 print(bright_blue + "Next Question: \n\n") answer = input(bright_blue + "What should you ALWAYS remeber to do before you exit out of your program? Is it: \n A. Throw away your computer,\n B. Run your Code,\n C. Commit and Push to Github. ").lower().strip() if answer == "a": print(red + "Incorrect.") elif answer == "b": print(red + "Incorrect.") elif answer == "c": print(green + "Correct!") score += 1 print(bright_blue + "Next Question: \n\n") answer = input(bright_blue + "What is the correct syntax for writing a function in python? is it: \n A. def my_function(): \n B. function myFunction() {} \n C. public void my_Function() { } ").lower().strip() if answer == "c": print(red + "Incorrect.") elif answer == "b": print(red + "Incorrect.") elif answer == "a": score += 1 print(green + "Correct!") print(bright_blue + "Next Question: \n\n") answer = input(bright_blue + "Which of the following are used to take user input in python? Is it: \n A. ask() \n B. print() \n C. input() ").lower().strip() if answer == "a": print(red + "Incorrect.") elif answer == "b": print(red + "Incorrect.") elif answer == "c": score += 1 print(green + "Correct!") print(bright_blue + "Last Question: \n\n") answer = input(bright_blue + "What is the name of the screen where the questions are being displayed? Is it: \n A. The Console, \n B. IDLE, \n C. The IDE") if answer == "a": score += 1 print(green + "Correct!") elif answer == "b": print(red + "Incorrect.") elif answer == "c": print(red + "Incorrect.") print("\nCongratualtions! You earned " + str(score) + " points!") print("\nAnd your prize is: \n\n") if score == 0: zero() elif score == 1: one() elif score == 2: two() elif score == 3: three() elif score == 4: four() elif score == 5: five() while True: quiz_method() if score > 0: break
919234365969a9eeb5ff5a6cd645b2f3734107cc
py1-10-2017/nathan-m-python1
/OOP/animal.py
1,107
3.84375
4
class Animal(object): def __init__(self, name, health): self.name = name self.health = health def walk(self): self.health -= 1 return self def run(self): self.health -= 5 return self def displayHealth(self): print "Name: ", self.name print "Health: ", self.health class Dog(Animal): def __init__(self, name, health): super(Dog, self).__init__(name, health) self.health = 150 def pet(self): self.health +=5 return self class Dragon(Animal): def __init__(self, name, health): super(Dragon, self).__init__(name, health) self.health = 170 def fly(self): self.health += 10 return self def displayHealth(self): print "I am Dragon" super(Dragon, self).displayHealth() animal1 = Animal("Stinky", 50) animal1.walk().walk().walk().run().run().displayHealth() dog1 = Dog("Beagle", 100) dog1.walk().walk().walk().run().pet().displayHealth() dragon1 = Dragon("blister", 100) dragon1.walk().walk().walk().run().run().fly().displayHealth() # mouse1 = Animal("Fievel", 23) # mouse1.pet().fly().displayHealth() # dog2 = Dog("Doberman", 200) # dog2.fly()
aadd5e959ed1c1792a683c933696c248495c14b2
nasridexp/advent_of_code19
/python/11.py
8,347
3.515625
4
import numpy as np import matplotlib.pyplot as plt from time import sleep class IntComputer: def __init__(self, inst_list_or): #Create an array of 0 10 times longer that the actual list with the # actual list in the beggining self.inst_list = inst_list_or[:] + [0] * (9*len(inst_list_or)) #variable to keep track of self.pointer self.pointer = 0 #relative base self.rel_base = 0 def next_step(self, intcode_input): input_used = False output_val = [] # obtain values and run instructiondepending on code while self.inst_list[self.pointer] != 99: # Obtain the specific instruction and the modes (starting with the first parameter onwards) inst, modes = self.divide_inst_and_modes(self.inst_list[self.pointer]) # Sum two numbers, store in third if inst == "01": #paddig modes with necessary 0 modes = "{:<03s}".format(modes) pos_1, pos_2, final_pos = self.inst_list[self.pointer+1:self.pointer+4] val_to_save = self.apply_mode(pos_1, modes[0]) + self.apply_mode(pos_2, modes[1]) self.save_val(final_pos, modes[2], val_to_save) self.pointer += 4 # mutiply two numbers, store in third elif inst == "02": #paddig modes with necessary 0 modes = "{:<03s}".format(modes) pos_1, pos_2, final_pos = self.inst_list[self.pointer+1:self.pointer+4] val_to_save = self.apply_mode(pos_1, modes[0]) * self.apply_mode(pos_2, modes[1]) self.save_val(final_pos, modes[2], val_to_save) self.pointer += 4 # insert input, save it to parameter place elif inst == "03": if not input_used: #paddig modes with necessary 0 modes = modes = "{:<01s}".format(modes) final_pos = self.inst_list[self.pointer+1] user_input = intcode_input self.save_val(final_pos, modes[0], user_input) self.pointer += 2 input_used = True else: break # output value in parameter place elif inst == "04": #paddig modes with necessary 0 modes = modes = "{:<01s}".format(modes) pos_1 = self.inst_list[self.pointer+1] output_val.append(self.apply_mode(pos_1 , modes[0])) self.pointer += 2 # jump self.pointer to value from second parameter if first parameter != 0 elif inst == "05": #paddig modes with necessary 0 modes = "{:<02s}".format(modes) pos_1, pos_2, = self.inst_list[self.pointer+1:self.pointer+3] if self.apply_mode(pos_1, modes[0]) != 0: self.pointer = self.apply_mode(pos_2 , modes[1]) else: self.pointer += 3 # jump self.pointer to value from second parameter if first parameter == 0 elif inst == "06": #paddig modes with necessary 0 modes = "{:<02s}".format(modes) pos_1, pos_2, = self.inst_list[self.pointer+1:self.pointer+3] if self.apply_mode(pos_1, modes[0]) == 0: self.pointer = self.apply_mode(pos_2 , modes[1]) else: self.pointer += 3 # store 1 in third parameter if first parameter < second parameter, else store 0 elif inst == "07": #paddig modes with necessary 0 modes = "{:<03s}".format(modes) pos_1, pos_2, final_pos = self.inst_list[self.pointer+1:self.pointer+4] if self.apply_mode(pos_1, modes[0]) < self.apply_mode(pos_2, modes[1]): self.save_val(final_pos, modes[2], 1) else: self.save_val(final_pos, modes[2], 0) self.pointer += 4 # store 1 in third parameter if first parameter == second parameter, else store 0 elif inst == "08": #paddig modes with necessary 0 modes = "{:<03s}".format(modes) pos_1, pos_2, final_pos = self.inst_list[self.pointer+1:self.pointer+4] if self.apply_mode(pos_1, modes[0]) == self.apply_mode(pos_2, modes[1]): self.save_val(final_pos, modes[2], 1) else: self.save_val(final_pos, modes[2], 0) self.pointer += 4 #relative base offset elif inst == "09": #paddig modes with necessary 0 modes = modes = "{:<01s}".format(modes) pos_1 = self.inst_list[self.pointer+1] #print("rel_base before {} - {}".format(self.rel_base, self.apply_mode(pos_1 , modes[0]))) self.rel_base += self.apply_mode(pos_1 , modes[0]) self.pointer += 2 else: raise Exception("run: unknown instruction: {}".format(inst)) return output_val def divide_inst_and_modes(self, instruction): full_inst = str(instruction) if len(full_inst) == 1: inst = "0" + full_inst modes = "" else: inst = full_inst[-2:] modes = full_inst[-3::-1] return inst, modes def apply_mode(self, pos, mode): #position mode if mode == "0": return self.inst_list[pos] #immediate mode elif mode == "1": return pos #relative mode elif mode == "2": return self.inst_list[self.rel_base + pos] else: raise Exception("run: unknown mode: {}".format(mode)) def save_val(self, pos, mode, val): #position mode if mode == "0": self.inst_list[pos] = val elif mode == "2": self.inst_list[self.rel_base + pos] = val else: raise Exception("run: unknown mode: {}".format(mode)) class painting_robot: def __init__(self, instructions, map_dim, position): #starting orientation self.orientation = 2 # starting robot brain self.brain = IntComputer(instructions) # initialising map self.map = np.zeros([map_dim, map_dim], dtype=int) #starting position self.position = position # part 2: initial point is white self.map[position] = 1 #list of position self.list_positions = [] def perform_one_step(self): panel_colour = self.check_camera() self.list_positions.append(self.position) output = self.brain.next_step(panel_colour) if output: new_panel_colour, turn = output self.paint_panel(new_panel_colour) self.advance(turn) return False else: return True def run_robot(self): finished = False while not finished: finished = self.perform_one_step() return self.map, self.list_positions def check_camera(self): return self.map[self.position] def paint_panel(self, new_panel_colour): self.map[self.position] = new_panel_colour # 0: down # 1: left # 2: up # 3: right def advance(self, turn): if turn: self.orientation = (self.orientation + 1) % 4 else: self.orientation = (self.orientation - 1) % 4 if self.orientation == 0: self.position = (self.position[0], self.position[1] - 1) elif self.orientation == 1: self.position = (self.position[0] - 1, self.position[1]) elif self.orientation == 2: self.position = (self.position[0], self.position[1] + 1) elif self.orientation == 3: self.position = (self.position[0] + 1, self.position[1]) if __name__ == "__main__": #read line file = open('data_11.txt', "r") line = (file.readlines()[0]).strip().split(",") #convert to int instruction_list = list(map(int, line)) # run the robot given the instructions and the dimension of the map to paint map_dim = 200 PaintingRobot = painting_robot(instruction_list, map_dim, (map_dim // 2, map_dim // 2)) output_map, list_positions = PaintingRobot.run_robot() print(len(set(list_positions))) plt.matshow(output_map) plt.show()
b1bbcc4c6329e0747dbeeccfc84d0deb24d23f17
anilkanchamreddy/Python_basics
/function_as_variable.py
733
3.9375
4
#Functions can be treated as values in some programming languages. If a value can be used for assignment, parameters, return types, etc., #such a value is called as a #first class citizen. For example def check_bag(number): print("Number of bags checked ",number) x=check_bag x(4) #Higher Order functions are those functions which can either accept another function as a parameter or return another function or both: #Accept another function as a parameter: def add(x,y): return x+y def call_function(func1,a,b): ret=func1(a,b) return ret print(call_function(add,10,20)) #Return another function: def ret_function(a,b): a=a*a; b=b*b; return lambda :a+b new_func=ret_function(2,3); print(new_func())
109dfd1f1db0d08abe2ff9deeda343a1249ac003
rlberry/CSE-1311-003
/datasets.py
1,984
3.90625
4
import math def inputFunction(): dataset=input("Please enter a set of numbers:") return dataset def maxFunction(dataSet): return max(dataSet) def minFunction(dataSet): return min(dataSet) def meanFunction(dataSet): total=sum(dataSet) count=len(dataSet) mean=total*1.0/float(count) return mean def stdevFunction(dataset): meanval=meanFunction(dataset) total=0 for number in dataset: difference=meanval-number square=difference**2 total=total+square n=len(dataset)-1 variation=total/(n) result=math.sqrt(variation) return result def medianFunction(dataset): newset=sorted(dataset) count=len(newset) middle=count/2 result=newset[middle] return result def modeFunction(dataset): listValues=[] listCounts=[] for number in dataset: if number in listValues: cindex=listValues.index(number) listCounts[cindex]=listCounts[cindex]+1 else: listValues.append(number) listCounts.append(1) maxval=maxFunction(listCounts) maxindex=listCounts.index(maxval) result=listValues[maxindex] return result def outputFunction (dataset,minval,maxval,meanval,medianval,modeval,stdVal): print dataset print "Min : %3.2f"%minval print "Max : %3.2f"%maxval print "Mean : %3.2f"%meanval print "Median: %3.2f"%medianval print "Mode : %3.2f"%modeval print "Stdev : %3.2f"% stdVal dataset=inputFunction() print dataset minval=minFunction(dataset) print minval maxval=maxFunction(dataset) print maxval meanval=meanFunction(dataset) print meanval stdVal=stdevFunction(dataset) print stdVal medianval=medianFunction(dataset) print medianval modeval=modeFunction(dataset) print modeval outputFunction (dataset,minval,maxval,meanval,medianval,modeval,stdVal)
c1d7b4d1b9734715d56ea46b076afe9eea0bd3f0
mvabf/uri-2021
/1165.py
263
3.5625
4
qtd = int(input()) for x in range(qtd): n = int(input()) divisores = 0 for i in range(1, n + 1, 1): if (n % i == 0): divisores+=1 if (divisores > 2): print(f'{n} nao eh primo') else: print(f'{n} eh primo')
a68881f3e78650e8736fa20d9b6d8c2b1b1c4a25
tonish/Plank-fit
/search_T_E_iterate_folder.py
2,531
3.546875
4
''' this code reads: 1) an ENVI format radiance image 2) an ASCII spectrum file with the same spectral resolution it then runs a search for the best fitting planck function for each pixel in the radiance image. the output is: 1) a spectral cube containing the best fitted planck function of every pixel (ENVI image format); 2) a temperature image icln K degrees (ENVI image format) ... Created by Offer Rozenstein using MATLAB R2011b updated for MATLAB 2015a on 8-July-2015 update for python on 21/7/2016 ''' import planck_wv import TK import spectral as sp import numpy import glob def main(filename): radiance_img = sp.envi.open(filename) ImageSampleNumber = radiance_img.shape[0] ImageVarNumber = radiance_img.shape[1] ImageBandsNumber = radiance_img.shape[2] radiance_img_squeezed = radiance_img.load().reshape((ImageSampleNumber*ImageVarNumber, ImageBandsNumber)) row_img_squeezed = radiance_img_squeezed.shape[0] col_img_squeezed = radiance_img_squeezed.shape[1] planck = [] temp = [] for i in range(row_img_squeezed): wv = numpy.array(radiance_img.bands.centers[17:]) L, T = planck_wv.planckFitting(radiance_img_squeezed[i, 17:],wv ) planck.append(L) temp.append(T) print float(i)/float(row_img_squeezed) planck1 = numpy.array(planck) temp1 = numpy.array(temp) BB = planck1.reshape((ImageSampleNumber, ImageVarNumber, len(wv))) Temperature = temp1.reshape(ImageSampleNumber , ImageVarNumber) radiance_img.metadata.keys() # """""" # #writing to files # """""" # #save planck curve image # Planck_name = os.path.split(filename)[1][:-3] # hdr = sp.envi.read_envi_header() hdr_name = filename[:-4] + '.hdr' hdr = sp.envi.read_envi_header(hdr_name) hdr['wavelength'] = hdr['wavelength'][17:] hdr['fwhm'] = hdr['fwhm'][17:] planck_save_name = filename[:-4] + '_planck' + '.hdr' sp.envi.save_image(planck_save_name, BB, dtype=numpy.float32, ext = '', interleave = 'bip', metadata = hdr, force = True) # saving the temperature image temperature_save_name = filename[:-4] + '_Temperature' + '.hdr' temperature_hdr = hdr del temperature_hdr['wavelength'] del temperature_hdr['fwhm'] sp.envi.save_image(temperature_save_name, Temperature, dtype=numpy.float32, ext = '', interleave = 'bip', metadata = temperature_hdr, force = True) files_in = glob.glob(r'C:\Users\tonish\Documents\telops hypercam 3_8_2016\radiance\*.hdr') for file in files_in: main(file)
4306c99f16e39f056c2e8d14baabea4066f91486
ayjabri/ComputerVision
/PIL_vs_OpenCV/whichIsFaster.py
1,847
3.703125
4
''' This small test is to find out which library is faster in prcessing photos in python: PIL SIMD or OpenCV Summary: On resize: PIL is 2.3 times faster in resizing a photo grayscaling: OpenCV is faster when it comes ot grayscaling a photo Conclusion: if you want to grayscale then resize a photo for DeepLearning then you are better off using OpenCV ''' from timeit import timeit import cv2 import argparse cv2_resize = ''' resized = cv2.resize(img, (260, 260), False) ''' cv2_resize_gray = ''' gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) resized = cv2.resize(gray, (260, 260), False) ''' cv2_setup = ''' import cv2 img = cv2.imread("img.jpg") ''' PIL_resize = ''' # To make the two copmarable we need to resize the photo first them convert it to numpy array resized = np.array(img.resize((260,260), resample=Image.NEAREST)) ''' PIL_resize_gray = ''' <<<<<<< HEAD resized = img.resize((260,260), resample=Image.NEAREST) ======= resized = img.resize((260,260), resample=Image.NEAREST, reducing_gap=3) >>>>>>> 56fe90db8e5460696bc1317023f588a4dcd49373 gray = np.array(resized.convert("L")) ''' PIL_setup = ''' from PIL import Image import numpy as np img = Image.open('img.jpg') ''' if __name__=="__main__": parser = argparse.ArgumentParser() parser.add_argument('--gray',action='store_true', default=False,help='Grayscale the photo before resizing it') parser.add_argument('--n', required=False, default= 100, type=int, help='Number of times to run the codes') arg = parser.parse_args() if arg.gray: cv2_resize = cv2_resize_gray PIL_resize = PIL_resize_gray cv = timeit(stmt=cv2_resize, setup=cv2_setup, number=arg.n) PIL = timeit(stmt= PIL_resize, setup=PIL_setup, number=arg.n) state = ('faster' if cv/PIL > 1 else 'slower') print(f'PIL is {cv/PIL:.1f} times {state} that OpenCV')
5d3cf25f5e643a403d602018e0971d0716c0edb1
sophiawang310/Othello
/PycharmProjects/Othello/old/strategy.py
11,322
3.796875
4
import random import math import numpy #### Othello Shell #### P. White 2016-2018 EMPTY, BLACK, WHITE, OUTER = '.', '@', 'o', '?' # To refer to neighbor squares we can add a direction to a square. N,S,E,W = -10, 10, 1, -1 NE, SE, NW, SW = N+E, S+E, N+W, S+W DIRECTIONS = (N,NE,E,SE,S,SW,W,NW) PLAYERS = {BLACK: "Black", WHITE: "White"} ########## ########## ########## ########## ########## ########## # The strategy class for your AI # You must implement this class # and the method best_strategy # Do not tamper with the init method's parameters, or best_strategy's parameters # But you can change anything inside this you want otherwise ############################################################# class Node: def __init__(self, b, m=None, s=None): # self.name= tempname self.board = b self.children = [] #self.player = p self.move= m self.score = s def __repr__(self): # return self.board return self.board def __lt__(self, other): return self.score<other.score class Strategy(): def __init__(self): pass def get_starting_board(self): """Create a new board with the initial black and white positions filled.""" board= "?"*10+("?"+ "."*8+ "?")*8+ "?"*10 board= self.replace_square(board, WHITE, 44) board =self.replace_square(board, WHITE, 55) board =self.replace_square(board, BLACK, 45) board =self.replace_square(board, BLACK, 54) return board def get_pretty_board(self, board): #checked """Get a string representation of the board.""" values = [x for x in board] values = numpy.array(values).reshape(10, 10) return values def print_pretty_board(self, board): #checked board= self.get_pretty_board(board) for line in board: print(" ".join(line)) def opponent(self, player): #checked """Get player's opponent.""" if player==BLACK: return WHITE if player==WHITE: return BLACK return None def find_match(self, board, player, square, direction): #checked """ Find a square that forms a match with `square` for `player` in the given `direction`. Returns None if no such square exists. """ counter_square= square opp=self.opponent(player) counter_square += direction while board[counter_square] is opp: counter_square += direction if board[counter_square] is player: return square return None def is_move_valid(self, board, player, move): """Is this a legal move for the player?""" valid_moves= self.get_valid_moves(board, player) return move in valid_moves def replace_square(self, board, player, square): return board[:square]+player+board[square+1:] def make_move(self, board, player, move): """Update the board to reflect the move by the specified player.""" # returns a new board/string assert self.is_move_valid(board, player, move) is True pairs=set() for dir in DIRECTIONS: m= self.find_match(board, player, move, dir) if m is not None and (m,dir) not in pairs: pairs.add((m, dir)) print(pairs) assert(len(pairs)>0) for match in pairs: end, dir= match[0], match[1] square = move board = self.replace_square(board, player, square) while square is not end: square+= dir board=self.replace_square(board, player, square) #self.print_pretty_board(board) return board def pieces_on_board(self, board, player): #checked pieces=set() for x in range(11,89): if board[x]== player: pieces.add(x) return pieces def get_valid_moves(self, board, player): #checked """Get a list of all legal moves for player.""" matches= [] #for square in self.pieces_on_board(board, player): for square in [x for x in range(0,100) if board[x] is EMPTY]: for dir in DIRECTIONS: val = self.find_match(board, player, square, dir) if val is not None and val not in matches: matches.append(val) return matches def has_any_valid_moves(self, board, player): return len(self.get_valid_moves(board, player))>0 def next_player(self, board, prev_player): """Which player should move next? Returns None if no legal moves exist.""" if self.has_any_valid_moves(board, self.opponent(prev_player)): return self.opponent(prev_player) if self.has_any_valid_moves(board, prev_player): return prev_player return None def score(self, board, player=BLACK): """Compute player's score (number of player's pieces minus opponent's).""" return len(self.pieces_on_board(board, BLACK))- len(self.pieces_on_board(board, WHITE)) def game_over(self, board, player): """Return true if player and opponent have no valid moves""" return self.next_player(board, player) is None ### Monitoring players class IllegalMoveError(Exception): def __init__(self, player, move, board): self.player = player self.move = move self.board = board def __str__(self): return '%s cannot move to square %d' % (PLAYERS[self.player], self.move) ################ strategies ################# def minmax_search(self, node, player, depth=5): # determine best move for player recursively # it may return a move, or a search node, depending on your design # feel free to adjust the parameters best={BLACK:max, WHITE: min} board= node.board if depth== 0: node.score= self.score(board, player) return node my_moves= self.get_valid_moves(board, player) children=[] if len(my_moves)<=0: print(player) print(my_moves) for move in my_moves: next_board= self.make_move(board, player, move) next_player= self.next_player(board, player) if next_player is None: #is winning board c= Node(next_board, move, s= 1000*self.score(next_board)) children.append(c) else: c= Node(next_board, move) c.score = self.minmax_search(c, next_player, depth=depth-1).score children.append(c) winner = best[player](children) node.score= winner.score return winner def minmax_strategy(self, board, player, depth=5): # calls minmax_search # feel free to adjust the parameters # returns an integer move return self.minmax_search(Node(board), player, 2).move def random_strategy(self, board, player): return random.choice(self.get_valid_moves(board, player)) def best_strategy(self, board, player, best_move, still_running): ## THIS IS the public function you must implement ## Run your best search in a loop and update best_move.value depth = 1 while(True): ## doing random in a loop is pointless but it's just an example best_move.value = self.random_strategy(board, player) depth += 1 standard_strategy = minmax_strategy ############################################### # The main game-playing code # You can probably run this without modification ################################################ import time from multiprocessing import Value, Process import os, signal silent = False ################################################# # StandardPlayer runs a single game # it calls Strategy.standard_strategy(board, player) ################################################# class StandardPlayer(): def __init__(self): pass def play(self): ### create 2 opponent objects and one referee to play the game ### these could all be from separate files ref = Strategy() black = Strategy() white = Strategy() print("Playing Standard Game") board = ref.get_starting_board() player = BLACK strategy = {BLACK: black.minmax_strategy, WHITE: white.minmax_strategy} print(ref.get_pretty_board(board)) while player is not None: move = strategy[player](board, player) print("Player %s chooses %i" % (player, move)) board = ref.make_move(board, player, move) print(ref.get_pretty_board(board)) player = ref.next_player(board, player) print("Final Score %i." % ref.score(board), end=" ") print("%s wins" % ("Black" if ref.score(board)>0 else "White")) ################################################# # ParallelPlayer simulated tournament play # With parallel processes and time limits # this may not work on Windows, because, Windows is lame # This calls Strategy.best_strategy(board, player, best_shared, running) ################################################## class ParallelPlayer(): def __init__(self, time_limit = 5): self.black = Strategy() self.white = Strategy() self.time_limit = time_limit def play(self): ref = Strategy() print("play") board = ref.get_starting_board() player = BLACK print("Playing Parallel Game") strategy = lambda who: self.black.random_strategy if who == BLACK else self.white.random_strategy while player is not None: best_shared = Value("i", -99) best_shared.value = -99 running = Value("i", 1) p = Process(target=strategy(player), args=(board, player, best_shared, running)) # start the subprocess t1 = time.time() p.start() # run the subprocess for time_limit p.join(self.time_limit) # warn that we're about to stop and wait running.value = 0 time.sleep(0.01) # kill the process p.terminate() time.sleep(0.01) # really REALLY kill the process if p.is_alive(): os.kill(p.pid, signal.SIGKILL) # see the best move it found move = best_shared.value if not silent: print("move = %i , time = %4.2f" % (move, time.time() - t1)) if not silent:print(board, ref.get_valid_moves(board, player)) # make the move board = ref.make_move(board, player, move) if not silent: print(ref.get_pretty_board(board)) player = ref.next_player(board, player) print("Final Score %i." % ref.score(board), end=" ") print("%s wins" % ("Black" if ref.score(board) > 0 else "White")) if __name__ == "__main__": game = ParallelPlayer(1) game = StandardPlayer() game.play() s = Strategy() b = s.get_starting_board() b = b[:35] + BLACK + b[36:] b = b[:45] + BLACK + b[46:] b = b[:55] + WHITE + b[56:] # s.print_pretty_board(b) # rint(s.find_match(b, WHITE, 55, N)) sp = StandardPlayer() sp.play()
49f2e7025896748955fd025325aff214352fd6d8
israandikabakhri/python-data-structure
/heap.py
2,364
3.734375
4
class Heap: def __init__(self): self.h = [] self.currsize = 0 def _left_child(self, i): if 2*i+1 < self.currsize: return 2*i+1 return None def _right_child(self, i): if 2*i+2 < self.currsize: return 2*i+1 return None def _max_heapify(self, node): if node < self.currsize: m = node lc = self._left_child(node) rc = self._right_child(node) if lc is not None and self.h[lc] > self.h[m]: m = lc if rc is not None and self.h[rc] > self.h[m]: m = rc if m!=node: temp = self.h[node] self.h[node] = self.h[m] self.h[m] = temp self._max_heapify(m) def _build_heap(self, a): self.currsize = len(a) self.h = list(a) for i in range(self.currsize/2, -1, -1): self._max_heapify(i) def _get_max(self): if self.currsize >= 1: me = self.h[0] temp = self.h[0] self.h[0] = self.h[self.currsize-1] self.h[self.currsize-1] = temp self.currsize += 1 self._max_heapify(0) return None def _heap_sort(self): size = self.currsize while self.currsize-1 >= 0: temp = self.h[0] self.h[0] = self.h[self.currsize-1] self.h[self.currsize-1] = temp self.currsize -= 1 self._max_heapify(0) self.currsize = size def _insert(self, data): self.h.append(data) curr = self.currsize self.currsize += 1 while self.h[curr] > self.h[curr/2]: temp = self.h[curr/2] self.h[curr/2] = self.h[curr] self.h[curr] = temp curr = curr/2 def _display(self): print(self.h) def main(): print("=== Heap (max) - A specialized tree-based data structure that satisfies the heap property (max-min) which is in max heap, the keys of parent nodes are always greater than or equal to those of the children and the highest key is in the root node") l = list(map(str, raw_input("[STR] What is your sentence? ").split())) h = Heap() h._build_heap(l) h._heap_sort() h._display() if __name__=='__main__': main()
42d586c19063c414150f1b430d1478e7fb079e32
JulianTrummer/le-ar-n
/code/01_python_basics/examples/02_lists_tuples_dictionaries/ex5_dictionaries.py
891
4.34375
4
"""Dictionary datatype""" # Unordered datatype with key:value pairs, there are no duplicates allowed my_dict = { "name" : "Kathrin", "age" : 71, "profession" : "Still not decided" } print(len(my_dict)) print(type(my_dict)) print("These are keys: ", my_dict.keys()) print("These are the values: ", my_dict.values()) print("These are key:value pairs: ", my_dict.items()) # Values can be called using the key print("my_dict['name']: ", my_dict['name']) print("my_dict['age']: ", my_dict['age']) # Values can be updated my_dict['age'] = 25 print("my_dict['age']: ", my_dict['age']) # New key:value pairs can be added and updated my_dict['chair'] = "Digital Fabrication" my_dict.update({"height":166, "profession":"Nerd"}) # Items can also be removed from the dictionary my_dict.pop("height") print(my_dict) # The dictionary can also be cleared my_dict.clear() print(my_dict)
e9d575f0bc4c1d15d8e10e523d29b67a106c8c05
arzanpathan/Python
/Assignment 3.py
804
4.15625
4
#WAP to print all odd No's between 13 to 123 print('\nOdd Numbers between 13 to 123\n') for i in range(13,125,2): print(i) #WAP to print all Natural No's from 100 to 1 using For Loop print('\nPrint All Natural Numbers from 100 to 1\n') for j in range(100,0,-1): #for j in range(100): print(j) #print(100-j) #WAP to Check whether the given no is prime or not (Prime no means divisible by its own) #for k in range(2,no):c=no/k if(c!=1): print('\nIt is Not a Prime No') print('\nProgram to Check whether the given no is prime or not (Prime no means divisible by its own)') no=int(input('\nEnter a No: ')) for k in range(2,no): if(no%k==0): print('It is not a Prime No') break if(k==no-1): print('It is a Prime No')
8749468453f733362f4d5ffbe857f9912472cdf8
algoitssm/algorithm_taeyeon
/Swea/1926_d2_간단한369게임.py
457
3.609375
4
n = int(input()) str_list = [] for i in range(1, n + 1): str_list.append(str(i)) # print(str_list) for str_l in str_list: cnt = 0 if '3' in str_l: cnt += str_l.count('3') if '6' in str_l: cnt += str_l.count('6') if '9' in str_l: cnt += str_l.count('9') if cnt == 0: print(str_l, end = ' ') else: print('-'*cnt, end = ' ') # 문자열말고 자릿수 숫자로도 풀어보깅
b9ff85b6f1d6b4106bc616f918e835c2c9cb10af
andrea321123/Advent-of-code-2020
/problem04.py
2,684
3.515625
4
# Problem 4 # 4/12/2020 # input file = open("input/input04.txt", "r") input = file.readlines() passports = [] single_passport = [] for i in input: if i == "\n": # end of passport passports.append(single_passport.copy()) single_passport = [] else: line = i.split() for j in line: key_value = j.split(":") single_passport.append(key_value) passports.append(single_passport) # PART ONE counter = 0 valid_passports = [] # useful for part two for i in passports: if len(i) == 8: # valid passport counter +=1 valid_passports.append(i) if len(i) == 7: # valid North Pole Credentials # check if cid is not present cid = False for j in i: if j[0] == "cid": cid = True break if not cid: counter +=1 valid_passports.append(i) print("Answer: " + str(counter)) # PART TWO counter = 0 for i in valid_passports: # check if each field of the passport is correct valid = True for j in i: if j[0] == "byr": year = int(j[1]) if year < 1920 or year > 2002: valid = False elif j[0] == "iyr": issue = int(j[1]) if issue < 2010 or issue > 2020: valid = False elif j[0] == "eyr": expiration = int(j[1]) if expiration < 2020 or expiration > 2030: valid = False elif j[0] == "hgt": unit = j[1][-2:] if unit != "in" and unit != "cm": valid = False else: size = int(j[1][:-2]) if unit == "cm": if size < 150 or size > 193: valid = False else: if size < 59 or size > 76: valid = False elif j[0] == "hcl": if len(j[1]) == 7 and j[1][0] == "#": for z in j[1][1:]: if z not in ['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']: valid = False else: valid = False elif j[0] == "ecl": if j[1] not in ["amb","blu","brn","gry","grn","hzl","oth"]: valid = False elif j[0] == "pid": if len(j[1]) != 9: valid = False else: for z in j[1]: if z not in ['0','1','2','3','4','5','6','7','8','9']: valid = False if valid: counter +=1 print("Answer: " + str(counter))
382588ed9ad606054c49e3fbd1d1dc530b4396d5
R1G0x/python-practice
/App programming/Working with files/HTMLHandling.py
1,884
4.28125
4
#HTML is a markup language for describing web documents or web pages. #HTML documents are described by HTML tags. Each HTML tag describes different document content. #For understanding parsing of HTML pages, let consider the sample url "http://xkcd.com". This url #display comics about math and other languages. #The displayed comics keep changing with respect to time. #Read the contents of sample url using "urllib" module. #Parse the contents of the web page to view the "Title" and "Caption" of displayed comic. #Download the displayed comic to the current directory as comic.png import urllib.request from lxml import etree def readUrl(url): urlfile = urllib.request.urlopen(url) if urlfile.getcode() == 200: contents = urlfile.read() return contents def downloadImage(url, ImageFileName=None): url = 'http:'+url contents = readUrl(url) if ImageFileName is None: ImageFileName = 'Sample.png' with open(ImageFileName, 'wb') as img: img.write(contents) def get_title(con): if con: tree = etree.HTML(con) title = tree.xpath("//div[@id='ctitle']/text()") return title def get_caption(con): if con: tree = etree.HTML(con) caption = tree.xpath("//div[@id='comic']/img/@title") return caption def get_comic(con, comic_name=None): if con: tree = etree.HTML(con) comic_url = tree.xpath("//div[@id='comic']/img/@src")[0] downloadImage(comic_url, comic_name) if __name__ == '__main__': url = "http://xkcd.com" html = readUrl(url) #Obtains title of the shown comic t = get_title(html) for e in t: print("Title: ", e) #Obtains caption of shown comic caption = get_caption(html) for c in caption: print("Caption: ", c) #Download's the comic image to current folder get_comic(html, 'Comic.png')
336ba3c46f0f52dda102eb46136c209baab7db26
Kruchinin-v/black_jack
/modules/functions/alignmebt_string.py
735
3.921875
4
""" Module for function alignment_string """ def alignment_string(string, length): """ Функция для выравнивания строковой переменной до нужной длины с помощью пробелов :param string: входная переменная, которую нужно выровнять :type string: string :param length: необходимая длина переменной :type length: int :return string: строка, выровненная до указанной длины, с помощью пробелов :rtype string: string """ while len(string) < length: string += " " return string
edd6d5d1e731257c4e8c253d7746d2e659912708
sudhansom/python_sda
/python_fundamentals/00-python-HomePractice/w3resource/conditions-statements-loops/problem4.py
588
4.15625
4
""" Write a Python program to construct the following pattern, using a nested for loop. * * * * * * * * * * * * * * * * * * * * * * * * * """ user_input = int(input("Enter the height of the pyramid : ").strip()) n = int(user_input / 2) for i in range(n): for j in range(i): print('*', end="") print("") for i in range(n, 0, -1): for j in range(i): print('*', end="") print("") # using only one loop: for i in range(user_input): if i < user_input/2: print(i * '*', end='') else: print((user_input-i) * '*', end='') print("")
645b1db1ad3d72fd4934386fad3e929c2a48a673
kmclaugh/Python_Toolset
/dictionaries.py
198
3.515625
4
games={'x':'home','y':'away'} print(games) for g in games: print(g,games[g]) del games['x'] print(games) if not games.get('z'): games['z']='something' if 'z' in games: print(games['z'])
890a649c6dbce9f97517452823966add79bde165
dKab/University-Stuff
/вычмат/numerical integration/trapezoid.py
547
3.71875
4
from math import sin, exp, sqrt import unittest def function(x): return sin(exp(-x)) + sqrt(x) def trapezoidIntegral(f, a, b, n): result = 0 h = (b - a) / n for i in range(n): result += f(a + (h * (i + 1))) + f (a + (h * i)) result *= h / 2 return result class TestNewton(unittest.TestCase): def test_0(self): a = 2 b = 2.7 n = 18 result = 1.14009 self.assertAlmostEqual(trapezoidIntegral(function, a, b, n), result, 5) if __name__ == '__main__': unittest.main()
9cdd4239c0677064eff49bfa709b862ee757adab
wangshubo90/python_code
/learn_python/slice.py
506
3.671875
4
import numpy as np a = np.array(range(100)).reshape(10,10) print("a[slice(3)] = \n{}".format(a[slice(3)])) print("a[slice(1,10,2)] = \n{}".format(a[slice(1,10,2)])) print("a[slice(0,None,2)] = \n{}".format(a[slice(0,None,2)])) print("a[(slice(0,None,2),slice(0,None,2))] = \n{}".format(a[(slice(0,None,2),slice(0,None,2))])) print(a[(range(0,10,2),2)]) print(a[(slice(0,10,2),2)]) print(a[(range(0,10,2),range(0,10,2))]) print(a[(slice(0,10,2),slice(0,10,2))]) a[(slice(None),[2,1,8])] a[:,[2,1,8]]
0c1fc6644d5ca627c0a381fa3bc8e578b0d1fdb0
semg101/Python-machinelearningfundamentals
/2_2_3_1_score_and_cross_validated_scores.py
1,436
3.640625
4
from sklearn import datasets, svm import numpy as np #The technique used: is called a ***KFold cross-validation*** #First technique #Load the digits dataset digits = datasets.load_digits() X_digits = digits.data y_digits = digits.target #Construction of the estimator svc = svm.SVC(C=1, kernel='linear') #As we have seen, every estimator exposes a **score** method that can judge the quality of the fit #(or the prediction) on new data. **Bigger is better** print(svc.fit(X_digits[:-100], y_digits[:-100]).score(X_digits[-100:], y_digits[-100:])) print("\n") #To get a better measure of prediction accuracy (which we can use as a proxy for goodness of fit of the model), #we can successively split the data in **folds** that we use for training and testing: #Split array X_digits into 3 sub-arrays of equal size. X_folds = np.array_split(X_digits, 3) #Split array Y_digits into 3 sub-arrays of equal size. y_folds = np.array_split(y_digits, 3) #The method list() takes sequence types and converts them to lists. #This is used to convert a given tuple into list. scores = list() for k in range(3): # We use 'list' to copy, in order to 'pop' later on X_train = list(X_folds) X_test = X_train.pop(k) X_train = np.concatenate(X_train) y_train = list(y_folds) y_test = y_train.pop(k) y_train = np.concatenate(y_train) scores.append(svc.fit(X_train, y_train).score(X_test, y_test)) print(scores)
fd5a98eb4e5c3c97fe3df7e852e7fd41ec8d713e
mateusziwaniak/Python-UDEMY-course---tutorial
/OOP Problems.py
1,133
4.03125
4
""" class Cylinder: def __init__(self, height = 1, radius = 1): self.pi = 3.14 self.height = height self.radius = radius def volume(self,): result = self.pi * self.radius * self.radius * self.height return result def surface_area(self): result = (self.pi * self.radius * self.radius) * 2 + (self.height * 2 * self.pi * self.radius) return result walec = Cylinder(2,3) print(round(walec.volume()),2) print(round(walec.surface_area()),2) """ import math class Line: def __init__(self, coor1, coor2): self.pi = 3.14 self.x1, self.y1 = coor1 self.x2, self.y2 = coor2 def distance(self): result = math.sqrt(((self.x2 - self.x1) ** 2) + ((self.y2 - self.y1) ** 2)) return result def slope(self): top = self.y2 - self.y1 bottom = self.x2 - self.x1 result = top / bottom return result coordinate1 = (3, 2) coordinate2 = (8, 10) walec = Line(coordinate1, coordinate2) print(walec.distance()) print(walec.slope())
902db88fd25ffc430f6e70ef9c54b44c70c95ebd
eriksylvan/AdventOfCode2019
/25prep.py
708
3.6875
4
import itertools items = ('spool of cat6', 'hypercube', 'weather machine', 'coin', 'candy cane', 'tambourine', 'fuel cell', 'mutex') def combs(x): return [c for i in range(len(x)+1) for c in itertools.combinations(x,i)] allCombinations = combs(items) trystring = [] for i in allCombinations: print('-== next try ==-') takeString ='' dropString ='' for item in i: takeString += f'take {item}\n' dropString += f'drop {item}\n' print(takeString) print(dropString) trystring.append(takeString) trystring.append('west\n') trystring.append(dropString) print(trystring)
cab48156c4601021d6b551417036285e77f96122
markomonsalud/project-euler-100
/Problem2.py
486
3.90625
4
import sys def fib_even_sum(number): total = 0 fib_number = 0 prev_fib_number = 1 second_prev_fib_number = 0 while fib_number <= int(number): if fib_number % 2 == 0: total += fib_number fib_number = prev_fib_number + second_prev_fib_number second_prev_fib_number = prev_fib_number prev_fib_number = fib_number return total def main(): print(fib_even_sum(sys.argv[1])) if __name__ == "__main__": main()
e37e7c026ee8ae0f9b761f528639724322badf76
Rosthouse/AdventOfCode2019
/challenge3_part1.py
1,814
3.96875
4
# Advent of Code 2019: Day 3, Part 1 # https://adventofcode.com/2019/day/3 def man_dist(p1: (int, int), p2: (int, int)) -> int: return abs(abs(p1[0]) - abs(p2[0])) + abs(abs(p1[1]) - abs(p2[1])) def lay_cable(wire: [str]) -> [(int, int)]: pos = (0, 0) switcher = { "R": lambda pos: (pos[0]+1, pos[1]), "L": lambda pos: (pos[0]-1, pos[1]), "U": lambda pos: (pos[0], pos[1]+1), "D": lambda pos: (pos[0], pos[1]-1) } cable = [] for i in range(0, len(wire), 1): command = wire[i] op = command[0] count = int(command[1:]) func = switcher.get(op) for j in range(0, count, 1): pos = func(pos) cable.append(pos) return cable def find_intersections(w1: (int, int), w2: (int, int)) -> [(int, int)]: return set(w1) - (set(w1) - set(w2)) def calculate_min_intersection(w1: str, w2: str): wire1 = w1.split(",") wire2 = w2.split(",") cable1 = lay_cable(wire1) cable2 = lay_cable(wire2) intersections = find_intersections(cable1, cable2) print(intersections) min_pos = min(intersections, key=lambda p: man_dist((0, 0), p)) print(min_pos) min_dist=man_dist((0, 0), min_pos) return min_dist print("Expected 6, actual: " + str(calculate_min_intersection("R8,U5,L5,D3", "U7,R6,D4,L4"))) print("Expected 159, actual: " + str(calculate_min_intersection( "R75,D30,R83,U83,L12,D49,R71,U7,L72", "U62,R66,U55,R34,D71,R55,D58,R83"))) print("Expected 135, actual: " + str(calculate_min_intersection( "R98,U47,R26,D63,R33,U87,L62,D20,R33,U53,R51", "U98,R91,D20,R16,D67,R40,U7,R15,U6,R7"))) f = open("./res/challenge3.txt") wire1 = f.readline() wire2 = f.readline() print("Min intersections: " + str(calculate_min_intersection(wire1, wire2)))
e03731800796acb0883e84ca87da068ffc5882b7
jkbockstael/adventofcode-2015
/day18_part1.py
1,431
3.625
4
# Advent of Code 2015 - Day 18 - Like a GIF For Your Yard # http://adventofcode.com/2015/day/18 import sys def parse_input(lines): return [[(lambda x: 1 if x == "#" else 0)(x) for x in line.rstrip()] for line in lines] def count_neighbours(grid, line, column, state): size = len(grid) total = 0 for x in range(line-1, line+2): for y in range(column-1, column+2): if (x == line and y == column) or x < 0 or x > size-1 or y < 0 or y > size-1: continue total += (1 if grid[x][y] == state else 0) return total def cellular_rules(grid, line, column): cell = grid[line][column] if cell == 1 and count_neighbours(grid, line, column, 1) in [2,3]: return 1 elif cell == 0 and count_neighbours(grid, line, column, 1) == 3: return 1 else: return 0 def step(grid): size = len(grid) outcome = [[None for x in range(size)] for y in range(size)] for line in range(size): for column in range(size): outcome[line][column] = cellular_rules(grid, line, column) return outcome def step_through(grid, steps): outcome = grid for s in range(steps): outcome = step(outcome) return outcome def lights_on(grid): return sum([sum(line) for line in grid]) # Main if __name__ == '__main__': start = parse_input(sys.stdin.readlines()) print(lights_on(step_through(start, 100)))
d56222d1c341f43626206291c7aa34228510a42f
RobertooMota/Curso_Python
/PythonMundo1/Exercicios/ex054 - contador de pessoas de maior.py
448
3.734375
4
#informa a quantidade de pessoas que ja sao de maiores e de menores pessoa = [] deMaior = 0 deMenor = 0 anoAtual = 2021 for i in range(0, 7): pessoa.append(int(input('Digite o ano do seu nascimento: '))) for i in range(0, 7): idade = int(anoAtual - pessoa[i]) if idade >= 18: deMaior += 1 else: deMenor += 1 print('Das pessoas listadas: {} são maior de idade e {} são menores de idade'.format(deMaior, deMenor))
220bf37620610589889d71723503a1ebd403b56c
lijuanjiayou/typical-code
/Python/day24-面向对象与实例属性/类属性增删该查.py
709
3.765625
4
class Chinese: country='China' def __init__(self,name): self.name=name def play_ball(self,ball): print('%s 正在打 %s' %(self.name)) #查看 print(Chinese.country) #修改 Chinese.country='Japan' print(Chinese.country) p1=Chinese('alex') print(p1.__dict__) print(p1.country) #增加 Chinese.dang='共产党' # print(Chinese.dang) # print(p1.dang) #删除 del Chinese.dang del Chinese.country print(Chinese.__dict__) # print(Chinese.country) def eat_food(self,food): print('%s 正在吃%s' %(self.name,food)) Chinese.eat=eat_food print(Chinese.__dict__) p1.eat('屎') def test(self): print('test') Chinese.play_ball=test p1.play_ball()# Chinese.play_ball(p1)
c0c3c34f1d9874e12ad9cdc091a5631b6429dc17
daiyanze/cs50
/pset6/credit/credit.py
846
3.828125
4
from cs50 import get_string # get credit card number input input = [int(digit) for digit in get_string('Number: ')] digits = len(input) # Odd digit sum odd_sum = sum( (digit * 2 > 9) and (digit * 2 % 10 + int(digit * 2 / 10)) or digit * 2 for idx, digit in enumerate(input[::-1]) if idx % 2 != 0) # Even digit sum even_sum = sum(digit for idx, digit in enumerate(input[::-1]) if idx % 2 == 0) # Check Brand if (odd_sum + even_sum) % 10 == 0: brand_index = int(''.join(['%d' % i for i in input[0:2]])) # Visa if 40 <= brand_index <= 49 and 13 <= digits <= 16: print('VISA') # MasterCard elif 51 <= brand_index <= 55 and digits == 16: print('MASTERCARD') # American Express elif brand_index == 34 or brand_index == 37 and digits == 15: print('AMEX') else: print('INVALID')
d82de8d5c988b55d3113dd858a1e8aa368cd12ab
dandumitriu33/codewars-Python
/set4/disemvoweltrolls.py
214
3.859375
4
def disemvowel(string): vowels = 'aeiou' for i in string: if i.lower() in vowels: string = string.replace(i, '') return string print(disemvowel("This website is for losers LOL!"))
64b5e7b5e931a76ec888b347c73ad9444528ac39
FinTrek/ctci-python
/Bit Manipulation/5.7.py
596
3.5
4
# Pairwise Swap def pairwise_swap(num: int) -> int: return ((num & 0xaaaaaaaa) >> 1) ^ ((num & 0x55555555) << 1) def brute_pairwise_swap(num: int): bin_list = list(bin(num))[2:] for b in range(len(bin_list) - 1, 0, -2): bin_list[b], bin_list[b - 1] = bin_list[b - 1], bin_list[b] return int("".join(bin_list), 2) if __name__ == '__main__': print(bin(1432), brute_pairwise_swap(1432)) print(bin(0), brute_pairwise_swap(0)) print(bin(8), brute_pairwise_swap(8)) print(bin(1432), bin(pairwise_swap(1432))) print(bin(564), bin(pairwise_swap(564)))
f2853275012d2823001fc700809b321e77b05e3b
alexhong33/ScrapyProjects
/basic/多线程基础.py
748
3.71875
4
# -*- coding: utf-8 -*- # @Time : 2017/7/17 9:51 # @Author : Hong # @Contact : alexhongf@163.com # @File : 多线程基础.py # @Description : STOP wishing START doing. import threading class A(threading.Thread): def __init__(self): # 初始化该线程 threading.Thread.__init__(self) def run(self): # 该线程要执行的程序内容 for i in range(10): print("我是线程A") class B(threading.Thread): def __init__(self): threading.Thread.__init__(self) def run(self): for i in range(10): print("我是线程B") # 实例化线程A为t1 t1 = A() # 启动线程t1 t1.start() # 实例化线程B为t2 t2 = B() # 启动线程t2 t2.start()
1481cc94622cfb3412a1ea895236e200dfa97cf9
ZhouZiXuan-imb/pythonCourse
/python_Day10-列表/02-遍历列表.py
540
3.6875
4
names = ['zhufengjiao', 'zhouzixuan', 'zhouzhou'] # while循环 # i = 0 # while (i < len(names)): # print("我是%d个名字%s" % (i + 1, names[i])) # i += 1 # for循环 # for 临时变量名 in 需要遍历的变量名(例如列表的变量名): # 可以使用临时变量... # ... # 如果列表中的数据已经遍历完成了 for循环会自动停止 # enumerate方法每次执行的时候会自动给i赋值为0,1,2,3,4..... for i, key in enumerate(names): print("第%d个名字是%s" % (i + 1, key))
5594ce0f5dfc5e8a0a5265a038798bce157b70a7
vsofi3/UO_Classwork
/315/HW/315assignment2.py
1,969
3.96875
4
import sys file = sys.stdin def getDag(n): vertices = file.readline() #stores number of vertices in the graph edges = file.readline() #stores number of edges, also moves to the next line of the file short = [0] * int(vertices) #an array for the shortest possible paths long = [0] * int(vertices) shortD = [0] * int(vertices) #an array for the number of shortest paths longD = [0] * int(vertices) short[1] = 1 #for each array, set the second index = to 1 long[1] = 1 shortD[0] = 1 #for the number of longest/shortest paths, set the first index = 1 longD[0] = 1 for line in file: line = line.replace("\n", "") #gets ride of \n characters at the end of string line = line.split() #splits the string at the space i = int(line[0]) j = int(line[1]) #followed the logic used on geeksforgeeks where the distances of the adjacent vertex is updated #using the distance of the current vertex. if short[j - 1] == 0: #finds the shortest path short[j - 1] = short[i - 1] + 1 if short[j - 1] > short[i - 1] + 1: short[j - 1] = short[i - 1] + 1 elif short[j - 1] == short[i - 1] + 1: #finds the number of shortest paths shortD[j - 1] += shortD[i - 1] if long[j - 1] == 0: #finds the longest path long[j - 1] = long[i - 1] + 1 if long[j - 1] < long[i - 1] + 1: long[j - 1] = long[i - 1] + 1 elif long[j-1] == long[i-1] + 1: #finds the number of longest paths longD[j -1] += longD[i-1] print("Shortest Path: {}".format(short[-1])) print("Number of Short Paths: {}".format(shortD[-1])) print("Longest Path: {}".format(long[-1])) print("Number of Long Paths: {}".format(longD[-1])) getDag(3)
b9120b261e2e6a01053c4b96ea84dc6cee983597
kennedyjosh/Ice-Hockey
/game/main.py
5,410
3.8125
4
''' Josh Kennedy ---------------------------------- Honors Intro to Video Game Design Final Project "Hockey 2017" ---------------------------------- V ALPHA 3.2 ''' # import modules and stuff from supporting files import pygame, math, time, sys, os from rink import * from gameEngine import * from constants import * from puck import * from players import * from scoreboard import * def main(rinkScale = 6): #initialize window, basic setup stuff pygame.init() screen = None if os.name == 'nt': #windows stuff screen = pygame.display.set_mode((W,H),pygame.FULLSCREEN) else: # mac stuff screen = pygame.display.set_mode((W,H)) clock = pygame.time.Clock() pygame.display.set_caption("Ice Hockey") #universal variables, in a class I suppose scale = rinkScale #change this to change size of rink, should be 6 for normal use uni = Universal(scale, ( W/2 - (114*scale) , H/2 - (42.5 * scale) )) #create border of rink b1, b2 = Border("c","tl",BLACK,uni), Border("c","tr",BLACK,uni) b3, b4 = Border("c","bl",BLACK,uni), Border("c","br",BLACK,uni) b5 = Border("r","m",BLACK,uni) borderList = [b5,b4,b2,b1,b3] #fill rink to make it look like it should i1, i2 = Inside("c","tl",WHITE,borderList,2,uni), Inside("c","tr",WHITE,borderList,2,uni) i3, i4 = Inside("c","bl",WHITE,borderList,2,uni), Inside("c","br",WHITE,borderList,2,uni) i5, i6, i7 = Inside("r","l",WHITE,borderList,2,uni),Inside("r","m",WHITE,borderList,2,uni),Inside("r","r",WHITE,borderList,2,uni) insideList = [i6,i5,i7,i4,i2,i1,i3] offset = int(2.5 * uni.c) #create more inside shapes and make them bigger to be the boards d1, d2 = Inside("c","tl",YELLOW,borderList,offset,uni), Inside("c","tr",YELLOW,borderList,offset,uni) d3, d4 = Inside("c","bl",YELLOW,borderList,offset,uni), Inside("c","br",YELLOW,borderList,offset,uni) d5, d6, d7 = Inside("r","l",YELLOW,borderList,offset,uni),Inside("r","m",YELLOW,borderList,offset,uni),Inside("r","r",YELLOW,borderList,offset,uni) boardsList = [d6,d5,d7,d4,d2,d1,d3] # create nets. this will never change nets = [Net("l",uni),Net("r",uni)] #set up the rink class rink = Rink(borderList,insideList,boardsList,nets) # create puck if __name__ == "__main__": pimg = pygame.transform.scale(pygame.image.load("img/puck.png").convert(), (int(1*uni.c),int(5*uni.c/6))) else: pimg = pygame.transform.scale(pygame.image.load("game/img/puck.png").convert(), (int(1*uni.c),int(5*uni.c/6))) pimg.set_colorkey((WHITE)) pimg.get_rect().x = W/2 pimg.get_rect().y = H/2 puck = Puck(pimg,pimg.get_rect().width,pimg.get_rect().height) # create teams #optimaztions for mac or pc if os.name == "nt": str,spd,sh = 15,15,50 else: str,spd,sh = 5,2,50 ## Providence Eagles #joe lopez jLopezImg = "eaglesPlyr0.png" jLopez = Player("Joe", "Lopez", "9", "C", str,spd,sh, jLopezImg,uni,rink) #team setup eaglesPlyrList = [jLopez] eagleLogo = pygame.image.load("game/img/eagle-800px.png").convert() eagleLogo.set_colorkey((0,0,0)) eagles = Team("Eagles", "Providence", "PRV", eagleLogo, YELLOW, BLACK, eaglesPlyrList, uni) ## Richmond Tigers #brendan clarke bClarkeImg = "tigersPlyr0.png" bClarke = Player("Brendan","Clarke","00","C",str,spd,sh,bClarkeImg,uni,rink) #team setup tigersPlyrList = [bClarke] tigersLogo = pygame.image.load("game/img/tiger.png").convert() tigers = Team("Tigers","Richmond","RCH",tigersLogo,ORANGE,BLACK,tigersPlyrList,uni) # create scoreboard/score keeping device sb = Scoreboard(eagles,tigers,(W/2-W*.25,25),W*.5,H*.15) userTeam = tigers #set up the game engine game = Engine(rink,tigers,eagles,puck,sb,userTeam) ############################## MAIN LOOP while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() elif event.type == pygame.KEYDOWN: if event.key == pygame.K_ESCAPE: # print 1.0/getTickVal() pygame.quit() sys.exit() elif event.key == pygame.K_f: game.away.startPos(game.puck, screen) # control user movement p = pygame.key.get_pressed() if p[pygame.K_w] or p[pygame.K_UP]: userTeam.currentPlayer.moveManual("u") if p[pygame.K_s] or p[pygame.K_DOWN]: userTeam.currentPlayer.moveManual("d") if p[pygame.K_a] or p[pygame.K_LEFT]: userTeam.currentPlayer.moveManual("l") if p[pygame.K_d] or p[pygame.K_RIGHT]: userTeam.currentPlayer.moveManual("r") # Update screen screen.fill(BLACK) # control framerate updateTickVal(clock.tick() / 1000.0) # update game # if game.update returns True, will return to the main menu if game.update(screen): pygame.mouse.set_visible(True) return pygame.display.flip() # this file WILL run if launched directly but it is NOT recommended if __name__ == "__main__": main()
a6f4dade4bd5d80f42692b7e1dab82f3abdc2465
jsverch/practice
/leet_1268.py
532
3.640625
4
from typing import List class Solution: def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]: k = str() sug = list() for i in range(0, len(searchWord)): k = k + searchWord[i] s = [p for p in products if p[0:len(k)] == k] sug.append(sorted(s)[0:3]) return sug obj = Solution() products = ["mobile", "mouse", "moneypot", "monitor", "mousepad"] searchWord = "mouse" r = obj.suggestedProducts(products, searchWord) print(r)
cd2e9379bac533672f5cecae7ce846ba26691dc4
ver0nika4ka/PythonCrashCourse
/10.1_Learning_Python.py
666
4.125
4
# Print contents by reading in the entire file with open('learning_python.txt') as file_object: contents = file_object.read() print(contents.strip()) print("\n") # Print contents by looping over the file object filename = 'learning_python.txt' with open(filename) as file_object: for line in file_object: print(line.strip()) print("\n") # Print contents by storing the lines in a list # and then working with them outside the with block. filename = 'learning_python.txt' with open(filename) as file_object: lines = file_object.readlines() py_knowledge = '' for line in lines: py_knowledge += line.strip() print(py_knowledge) print("\n")
460790760176c9a1896b821ca1e2946a552b06b7
Lee-Geon-Yeong/SW_Expert_Academy
/D1/6246_repeatation8.py
114
3.59375
4
i = 0 j = 5 while(i < 5): j=5-i while(j>0): print("*",end='') j-=1 print("") i+=1
aa0ccc38b31b1bcdd170d13ad8e2081a6624e0d1
WhiteheadAaron/python-game
/game.py
7,861
4.09375
4
import random import time def intro(): print() print("It is the zombie apocolypse.") print("You must survive at all costs.") print("Choices you make will directly affect you and those around you.") print("In the new reality, you either thrive or you die.") print() ready = "" while ready != "1": ready = input("Are you ready? Enter 1 to continue. ") print() print("You are at your family house with your parents, teenage brother, and younger sister.") time.sleep(2) print() print("Your dad wants to go to the store to get supplies. Your mom thinks you should stay put.") time.sleep(2) print() print("Choice 1 is going to the store, choice 2 is waiting at home and barricading the doors") print() def choosePath(): path = "" while path != "1" and path != "2": path = input("Which path will you choose? (1 or 2): ") return path path1 = "" def chooseDirection(chosenPath): if chosenPath == "1": return storePath() else: return stayHomePath() def stayHomePath(): print() print("You decide to stay at home, and prepare for the worst.") time.sleep(2) print() print("Your dad and brother go to the garage to get supplies to board up the house.") time.sleep(2) print() print("In the meantime, you hear screaming outside in the street. It sounds like your neighbor.") time.sleep(2) print() print("Your mom urges you to stay inside, but you want to save your childhood friend.") time.sleep(2) print() response = "" while response != "1" and response != "2": response = input( "Enter 1 to stay inside, 2 to go help your friend: ") checkHomePath(response) def checkHomePath(chosenPath): friendChoice = "" print() if chosenPath == "1": print("The screams continue for several minutes, but they eventually fade away.") time.sleep(2) print() print("You look out the window to try to get a view of what happened, but you can't see anything.") makeChoice() if chosenPath == "2": print("Despite your mother's pleas, you sprint outside to try to save your friend.") time.sleep(2) print() print("You see him on his back, keeping the zombie off by holding a bat to it's neck horizontally.") time.sleep(2) print() print("You see a large stick on the ground. Do you run across to get the stick first, or go straight to help?") time.sleep(2) print() while friendChoice != "1" and friendChoice != "2": friendChoice = input( "Enter 1 to get the stick, enter 2 to help immediately: ") correctChoice = random.randint(1, 2) if friendChoice == str(correctChoice): if friendChoice == "1": print( "You grab the stick, and get to your friend just in time to save him.") time.sleep(2) print() print( "He thanks you profusely, and returns home to see his family again.") makeChoice() else: print( "You run to your friend, and kick the zombie off of him. He runs back into his house, and you do the same.") time.sleep(2) print() print( "He didn't have time to thank you, but I'm sure he is very grateful.") makeChoice() if friendChoice != str(correctChoice): print() print("Unexpectedly, a swarm of zombies comes from your blind spot. Your mother screams as she watches on.") time.sleep(2) print() print( "As you're being taken down, you see your friend engulfed by a swarm as well. The End.") playAgain() # Run the losing game function def storePath(): print() print("You leave the house, and set out for the store") time.sleep(2) print() print("You get to the store, and the parking lot looks empty") time.sleep(2) print() print("The front door is broken down, and you hear a noise inside of the store") time.sleep(2) print() response = "" while response != "1" and response != "2": response = input( "Enter 1 to go to the left side, 2 to go to the right side: ") checkStorePath(response) def checkStorePath(chosenPath): correctPath = random.randint(1, 2) print() if correctPath == 1: print( "Suddenly on the right side of the store, you hear and see a horde of zombies") time.sleep(2) print() print("You scream, and you now have the full attention of the zombies.") if correctPath == 2: print("Suddenly on the left side of the store, you hear and see a horde of zombies") time.sleep(2) print() print("You scream, and you now have the full attention of the zombies.") time.sleep(2) print() if chosenPath == str(correctPath): print("Luckily for you, you chose the right side of the store.") time.sleep(2) print() print("You and your Dad are able to escape, gathering a small amount of food and medicine") makeChoice() else: print( "Unfortunately you chose the wrong side, and are quickly engulfed in the swarm") print() playAgain() def homePath2(): print() print("Your mom has had a change of heart, and she thinks it's time to leave the house.") time.sleep(2) print() print("The rest of the family agrees, it's too dangerous to stay here.") time.sleep(2) print() print("Your dad suggests you make the journey to his parents house. It's in a secluded area, and probably safer.") time.sleep(2) print() print("Mom wants to travel to the CDC. It's a bit further, but they could have a cure.") time.sleep(2) print() homeChoice = "" while homeChoice != "1" and homeChoice != "2": homeChoice = input( "Enter 1 to go to your grandparent's house, enter 2 to go to the CDC: ") print() return homeChoice def makeChoice(): number = homePath2() if number == "1": gmaPath() else: cdcPath() def cdcPath(): print("You set off to begin your journey to the CDC.") time.sleep(2) print() print("Do you want to drive on the interstate or the backroads?") time.sleep(2) print() print("The interstate will make the journey much quicker, if the road is clear. The side roads are slower, but probably safer.") time.sleep(2) print() cdcChoice = "" while cdcChoice != "1" and cdcChoice != "2": cdcChoice = input( "Enter 1 to take the interstate, enter 2 to take the side roads: ") if cdcChoice == "1": interstateChoice() else: sideRoadsChoice() def interstateChoice(): print("interstate") def sideRoadsChoice(): print("side roads") def gmaPath(): print("You set off to begin your journey to Grandma and Grandpa's house.") time.sleep(2) print() print("Do you want to drive on the interstate or the backroads?") time.sleep(2) print() print("The interstate will make the journey much quicker, if the road is clear. The side roads are slower, but probably safer.") time.sleep(2) print() gmaChoice = "" while gmaChoice != "1" and gmaChoice != "2": gmaChoice = input("Enter 1 to take the interstate, enter 2 to take the side roads: ") if gmaChoice == "1": interstateChoice() else: sideRoadsChoice() def playAgain(): intro() choice = choosePath() chooseDirection(choice) playAgain()
dc9057f7777b499ce6f9c584e6b88bf8ac42df3d
virenkhandal/funpy
/MATLAB/bisection.py
1,266
4.0625
4
import math from math import e sign = lambda x: math.copysign(1, x) def function(x): return (600 * (x ** 4)) - (550 * (x ** 3)) + (200 * (x ** 2)) - (20 * x) - 1 def method(a, b, error): print("Question: Use the bisection method to find the root on the interval [" + str(a) + ", " + str(b) + "] within " + str(error) + ".") print("Value at a: ", function(a)) print("Value at b: ", function(b)) if sign(function(a)) == sign(function(b)): print("There is no root in the given interval") return None else: i = 0 p = a + ((b - a) / 2) while (abs(function(p)) > error): i += 1 p = a + ((b - a) / 2) curr = function(p) if sign(curr) == sign(function(a)): a = p else: b = p print("We need " + str(i) + " iterations to get a root within " + str(error) + ".") print("With this, our root is at " + str(p) + " with a value of " + str(curr) + ".") if __name__ == '__main__': lower_bound = float(input("Enter your lower bound: ")) upper_bound = float(input("Enter your upper bound: ")) error = float(input("Enter your error value: ")) method(lower_bound, upper_bound, error)
4f4cfdc746915046b3a086b67618b1d3efdfe4ea
esch3r/Python--Projects-
/selfclass.py
407
3.9375
4
# self is a temporary placeholder for the object class className: def createName(self,name): self.name = name def displayName(self): return self.name def saying(self): print ( "hello" % self.name) first =className() second =className() first.createName('Tony') second.createName('bucky') first.displayName() second.displayName()
86f8df082e714a05f09512cc87050132a2c6f59d
Tenbatsu24/Project-Euler
/divisors.py
276
3.5
4
import math def f(n): divisors = set({1, n}) for i in range(2, math.ceil(math.sqrt(n)) + 1): if (n % i) == 0: divisors.add(i) divisors.add(n // i) return divisors if __name__ == '__main__': print(f(4001)) print(f(2689))
0589d11a523e8e118e953d8078136e0648932295
bazhenov4job/Algorithms_and_structures
/Lesson_09/homework/Task_02.py
1,515
3.828125
4
""" 2. Закодируйте любую строку по алгоритму Хаффмана. """ from collections import Counter, OrderedDict from binarytree import Node from copy import deepcopy def tree_search(tree, symbol, path=''): print(symbol, path, tree.value) if tree.value == symbol: print('нашёл', path) return path if tree.value == 0: path += '0' tree_search(tree.left, symbol, path) if tree.left != 0 and tree.left != symbol: path += '1' return tree_search(tree.right, symbol, path) def haffman_encode(string): counted_chars = Counter(string) ordered_chars = OrderedDict(sorted(counted_chars.items(), key=lambda x: x[1])) while len(ordered_chars) > 1: left_value = ordered_chars.popitem(last=False) right_value = ordered_chars.popitem(last=False) char_tree = Node(0) if type(left_value[0]) == str: char_tree.left = Node(ord(left_value[0])) else: char_tree.left = left_value[0] if type(right_value[0]) == str: char_tree.right = Node(ord(right_value[0])) else: char_tree.right = right_value[0] ordered_chars[deepcopy(char_tree)] = left_value[1] + right_value[1] my_tree = ordered_chars.popitem()[0] print(my_tree) symbols = counted_chars.keys() # binary_dict = {} path = tree_search(my_tree, 98) print(path) return 0 print(haffman_encode('abrakadabra'))
1f95cf8b9875b9586a2e2c731e035225df5f190d
Sergey0987/firstproject
/Алгоритмы/Грокаем алгоритмы/1. Бинарный поиск - draft.py
1,279
3.703125
4
list1=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15] index_min=0 #самый левый индекс в интервале index_max=len(list1)-1 #самый правый индекс в интерале search_number=int(input('Введи число от '+str(list1[0])+' до '+str(list1[len(list1)-1])+': ')) while search_number != list1[index_max] and search_number != list1[index_min]: if search_number < list1[index_max//2]: index_max=(index_max//2) print('index_max',index_max) elif search_number > list1[index_max//2]: if search_number < list1[index_min+(index_max-index_min)//2]: index_max=index_min+(index_max-index_min)//2 print('index_max',index_max) elif search_number > list1[index_min+(index_max-index_min)//2]: index_min=index_min+(index_max-index_min)//2 print('index_min',index_min) else: index_min=index_min+(index_max-index_min)//2 elif search_number == list1[index_max//2]: index_max=index_max//2 if search_number == list1[index_max]: print('Индекс искомого значения ', list1[index_max], ' = ',index_max) else: print('Индекс искомого значения', list1[index_min], ' = ', index_min)
42fe4ca4251a043e77cd41fe571d5019594343a8
shijiachen1993/learn-Python
/class/student.py
500
3.671875
4
class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def get_name(self): return self.__name def set_name(self, name): self.__name = name def get_score(self): return self.__score def set_score(self,score): self.__score = score bart = Student('Bart', 60) if bart.get_score() != 60: print('测试失败!') else: bart.set_score(90) if bart.get_score() != 90: print('测试失败!') else: print('测试成功!')
a95a29f5ad3378376fa82d9fc2a4c80b7a07fb3a
thenaterhood/thenaterweb
/tools/postData.py
5,294
3.828125
4
""" Author: Nate Levesque <public@thenaterhood.com> Language: Python3 Filename: postData.py Description: common classes and functions for manipulating posts in json and plaintext formats """ from datetime import datetime import os import codecs import json class postData(): """ Defines variables and functions for creating a json post for the blog. """ __slots__=('filename', 'humanDate', 'atomDate', 'content', 'title', 'tags') def __init__(self, title, tags, infile, mode): """ Constructs the postdata object with the atom date, human-readable date, and filename yyyy.mm.dd.json, then pulls in and formats post content and other information. Arguments: title (str): the title for the post tags (str): a comma separated list of tags (as a string) infile (str): the filename of a file to read in for content mode (str): 'create' or 'convert' to create a new post in json format or to convert an existing plaintext post to json. 'convert' overrides all over options as it will pull them from the existing plaintext post. """ if ( mode == 'create' ): currentDate = datetime.now() # Sets all the fields that contain some amount of date information self.humanDate = currentDate.strftime("%B %d, %Y") self.atomDate = str( currentDate.isoformat()[0:-7] ) + "-05:00" self.filename = ( currentDate.strftime("%Y.%m.%d")+".json" ) # Reads in a plaintext or semi-html file and adds paragraph # formatting tags self.content = [] for line in codecs.open(infile, 'r', 'utf-8'): self.content.append("<p>"+line+"</p>\n") # Sets the title and tags fields self.title = title self.tags = tags if ( mode == 'convert' ): self.readtext(infile) def json(self): """ Returns a json-encoded representation of the data contained in the post object Arguments: none Returns: a json dump of the post information """ return json.dumps({'title':self.title, 'datestamp':self.atomDate, 'date':self.humanDate, 'tags':self.tags, 'content':self.content},sort_keys=False, indent=4, separators=(',', ': ') ) def write(self, path='.'): """ Writes the postData to the file contained in the filename slot Arguments: none Returns: none """ outfile = open( path+'/'+self.filename, 'w') outfile.write( self.json() ) outfile.close() def readtext(self, infile): """ Reads in a plaintext file and sets the fields of the class to the data it contains. Syntax of the text file is: * TITLE * DISPLAY DATE * TAGS * FEED DATESTAMP * CONTENT Arguments: infile (str): the name of a file to open and pull from Returns: none """ fileContents = [] # Reads the contents of the text file into an array for line in codecs.open(infile, 'r', 'utf-8'): fileContents.append(line) # Pops lines from the file for the fields (following the syntax # for plaintext posts) self.title = fileContents.pop(0).strip() self.humanDate = fileContents.pop(0).strip() self.tags = fileContents.pop(0).strip() self.atomDate = fileContents.pop(0).strip() self.content = [] for item in fileContents: self.content.append('<p>'+item.strip()+"</p>\n") self.filename = self.atomDate[0:10].replace('-', '.') + '.json' def __str__(self): """ Returns a string representation of the contained post data Arguments: none Returns: (str) containing a human-readable representation of some of the contained data (title, date, tags, filename) """ return "Post: " + self.title + "\n date: " + self.atomDate + " (" + self.humanDate + ") \n Tags: " + self.tags + "\n Saving to: " + self.filename def getfilename(): """ Retrieves the name of a file to open from the user and returns it if it exists. Otherwise, informs the user that the file could not be found and requests a different file. Arguments: none Returns: filename (str): the name of a file to use """ filename = input("Enter a name of a file to open: ") while True: try: f = open(filename, 'r') print("Cool, I got it, using "+filename) return filename except: filename = input("File does not exist: enter a name of a file to open: ") def getConfig(): """ Retrieves the current site configuration Arguments: none Returns: config (dict): the site config in dictionary form """ return {'post_directory':'/home/nate'}
f05edab45c6bd5d6dabfa23d2028e28349f42e98
Ignacio01/MachineLearning
/detectFlowers.py
1,745
4.28125
4
# # Tutorial from Google about Machine Learning. # import numpy as np from sklearn.datasets import load_iris from sklearn import tree # Importing the library iris from sklearn iris = load_iris() # # VISUALIZATION OF THE DATA # # The dataset contains the values of the columns in # wikipedia and the metadata tells the name of the features, # and the names of the different types of flowers. print iris.feature_names print iris.target_names # We are printing the first value in the dataset print iris.data[0] # prints the lable of the type of flower for the first element print iris.target[0] #We are iterating over the data in the dataset for i in range(len(iris.target)): print "Example %d: label %s, feature %s" % (i, iris.target[i], iris.data[i]) # # TRAINING THE DATA # # For this test we are going to remove the first element # of each type of flower, so we can test after training the classifier test_idx = [0,50,100] train_target = np.delete(iris.target, test_idx) train_data = np.delete(iris.data, test_idx, axis=0) # testing the data # This testing data will only have the samples we removed. test_target = iris.target[test_idx]; test_data = iris.data[test_idx]; clf = tree.DecisionTreeClassifier() # We are training the classifier to recognize the different # types of flowers. clf.fit(train_data, train_target) # We will obtain the three types of flowers. print test_target # We let the classifier once it has been trained to # recognize the elements we removed from the dataset. print clf.predict(test_data) # We are going to visualize the tree viz code. import pydotplus dot_data = tree.export_graphviz(clf, out_file="iris.pdf") graph = pydotplus.graph_from_dot_data(dot_data) graph.write_pdf("iris.pdf")
dc7a0fb7a3426f2a9dea2be9428a9aeca31aa110
RishabhArya/Coursera-Data-Structures-and-Algorithms-by-University-of-California-San-Diego-
/1.Algorithmic Toolbox/week4_divide_and_conquer/2_majority_element/majority_element.py
1,136
3.734375
4
# Uses python3 # Boyer Moore Majority Vote Algoithum import sys def check_majority_element(ar , majority_element): i = 0 count = 0 while i < len(ar): if ar[i] == majority_element: count = count + 1 i = i + 1 if count > len(ar)/2: return 1 if count <= len(ar)/2: return -1 return 0 def get_majority_element(a, left, right): if left == right: return -1 if left + 1 == right: return a[left] majority_element = a[0] count = 1 i = 1 while i < right: current_element = a[i] if majority_element == current_element: count = count + 1 if majority_element != current_element: count = count - 1 if count == 0: majority_element = current_element count = 1 i = i + 1 result = check_majority_element(a, majority_element) if result == 1: return 1 return -1 if __name__ == '__main__': input = sys.stdin.read() n, *a = list(map(int, input.split())) if get_majority_element(a, 0, n) != -1: print(1) else: print(0)
24d684e5fd0b089d3fec7013d7cb8df2a9463ca8
djtsorrell/Intro-Python-OOP
/Orbits/animate.py
3,511
3.578125
4
import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation from matplotlib.lines import Line2D from orbit import Orbit class Animate(Orbit): """Initialises patches to visualise orbital motion.""" def __init__(self, filename, timestep): """TODO: to be defined. """ super().__init__(filename, timestep) # Initialises the objects to be animated. self.patches = [] # Initialises data lists for plotting kinetic energy. self.time = [] self.energy = [] def anim_init(self): return self.patches def animate(self, frame): """Updates the positions of the bodies and the energy data""" # Runs the update methods for all physical attributes. super().getForce() super().getAccel() super().vel_step() super().pos_step() # Updates the positions of the planetary objects. for i in range(self.objects): self.patches[i].center = (self.pos[i][0], self.pos[i][1]) # Updates energy plot. self.time.append(frame * self.timestep) # self.energy.append(super().getKinetic()) self.energy.append(super().getEnergy()) self.patches[self.objects].set_xdata(self.time) self.patches[self.objects].set_ydata(self.energy) return self.patches def show(self, total_frames): """Setup and display the animation.""" # Figure setup. plt.style.use("dark_background") fig = plt.figure() # Add extra horizontal space between subplots. plt.subplots_adjust(wspace=0.5) # Axes setup for planetary bodies. ax = fig.add_subplot(1, 2, 1, label="planets") ax.set_aspect("equal") ax.set_title("Orbital Motion") # Ensures planets fit in axes. r_max = self.pos[self.objects-1][0] * 1.3 ax.set_xlim(-r_max, r_max) ax.set_ylim(-r_max, r_max) # Axes setup for energy plot. ax1 = fig.add_subplot(1, 2, 2, label="energy") ax1.set_title("Total Energy") x_max = self.timestep * total_frames # i.e. the total duration. y_value = super().getEnergy() # initial energy value ax1.set_xlim(0, x_max) ax1.set_ylim(y_value*0.99, y_value*1.01) ax1.set_xlabel("Time / s") ax1.set_ylabel("Total Energy / J") # Ensures energy plot uses scientific notation (numbers are large). plt.Axes.ticklabel_format(ax1, style="scientific", scilimits=(-5, 3)) # Adds the planets to the patches list which will then be animated. for i in range(self.objects): self.patches.append( plt.Circle( (self.pos[i][0], self.pos[i][1]), radius=self.radius[i], color=self.color[i], animated=True, ) ) ax.add_patch(self.patches[i]) # Add a 2D line to plot the kinetic energy of the planetary objects. self.patches.append(Line2D([], [], color='red', linewidth=2.5, animated=True)) ax1.add_line(self.patches[self.objects]) anim = FuncAnimation( fig, self.animate, frames=total_frames, init_func=self.anim_init, repeat=False, interval=50, blit=True, ) # plt.show() anim.save("mars.gif", writer="imagemagick", fps=30)
e52eb480815579c2585b06e48d8aebe1fb9aba5c
acgis-dai00035/gis4107-day09
/world_pop_explorer.py
3,613
3.921875
4
# -*- coding: UTF-8 -*- #------------------------------------------------------------------------------- # Name: world_pop_explorer.py # # Purpose: Provide some functions to analyze the data in # world_pop_by_country.py # # Author: David Viljoen # # Created: 24/11/2017 #------------------------------------------------------------------------------- from world_pop_by_country import data as country_pop # Key = country and value is number (i.e. not text containing commas) # country_pop_dict = {} def main(): lines = country_pop.split('\n') print "country_populations has the following columns:" print lines[0] print repr(lines[0]) ci = lines[162] print "\nData is UTF-8 encoded. That is, printed as is:" print ci print "\nData prined with .decode('utf-8'):" print ci.decode('utf-8') def get_country_count(): """Return the number of countries in country_populations. Create a list where each element of the list contains a line of data from country_populations and return the length of this list""" lines = country_pop.split('\n') return len (country_pop.split('\n')) - 1 def conv_num_with_commas(num_text): """Convert a number with commas (str) to a number. e.g. '1,000' would be converted to 1000""" return int(num_text.replace(',' ,'')) def get_top_five_countries(): """Return a list of names of the top five countries in terms of population""" lines = country_pop.split('\n') top_countries = [] for line in lines[1:6]: top_countries.append(line.split('\t')[1]) return top_countries def set_country_populations_dict(): """Sets the country_populations_dict dictionary where key is country name and value is a tuple containing two elements: 1. A numeric version of the comma separated number in the Pop 01Jul2017 column 2. The % change as a positive or negative number """ global country_pop_dict lines = country_pop.split('\n') for i in range(1,get_country_count()+1): country_pop_dict[lines[i].split('\t')[1]] = (conv_num_with_commas(lines[i].split('\t')[5]),lines[i].split('\t')[6] ) return country_pop_dict def get_population(country_name): """Given the name of the country, return the population as of 01Jul2017 from country_populations_dict. If the country_populations_dict is empty (i.e. no keys or values), then run set_country_populations_dict to initialize it.""" global country_pop_dict if country_pop_dict.has_key(country_name) : pass else: set_country_populations_dict() return country_pop_dict[country_name][0] def get_continents(): """Return the list of continents""" lines = country_pop.split('\n') lists=[] for i in range(1,get_country_count()+1): lists.append(lines[i].split('\t')[2]) list1 = {}.fromkeys(lists).keys() return list1 def get_continent_populations(): """Returns a dict where the key is the name of the continent and the value is the total of all countries on that continent""" dict1 = set_country_populations_dict() dict2 = {} for i in get_continents(): dict2[i] = 0 lines = country_pop.split('\n') for k in range(1,get_country_count()+1): dict2[lines[k].split('\t')[2]] += conv_num_with_commas(lines[k].split('\t')[5]) return dict2 if __name__ == '__main__': main()
2a618c41583039a423b2bfcbb94cbec5ac3c458a
Ryalian/cse491-numberz
/sieve_gen/test3.py
270
3.921875
4
import sieve print "Test if 233 is a prime" print "" for x, y in zip(range(233), sieve.sieve_g()): list = y for i in list: if i == 233: print "233 is prime" Flag = 1 break if Flag != 1 : print "Damn! 233 is not prime!" #Test if one specific number is prime
00d1881ba24a1cea7e3735705be485a7fab40775
AkitaFriday/dataStructure
/sort/simpleSort.py
7,220
3.71875
4
""" 几个简单的排序算法 author: weiyc 2019-05-08 """ import random import time import matplotlib.pyplot as plt # 数据元素类,假设将要排序的序列中的每个元素是以下定义的类的实例对象 class Item(object): def __init__(self, key, datum): self.key = key self.datum = datum # 插入排序 # 就是调整第i个元素在下标[0, i]范围的顺序,i从下标1扩充到len(list) - 1时,就最终生成了整个list的排序序列 def insert_sort(lst): # 序列只有一个元素认为是有序的 for i in range(1, len(lst)): x = lst[i] j = i # 每一次循环时,lst[i] 之前的元素都是有序的 while j > 0 and lst[j - 1].key > x.key: lst[j] = lst[j - 1] j -= 1 lst[j] = x return lst # 生成随机列表 def rand_list(num): lst = [] if num > 2000000000: return for i in range(num): lst.append(Item(random.randint(1, num * 7), random.randint(1, num * 7))) return lst # 冒泡排序 def bubble_sort(lst): for i in range(len(lst)): found = False for j in range(1, len(lst) - i): if lst[j - 1].key > lst[j].key: lst[j - 1], lst[j] = lst[j], lst[j - 1] # 存在逆序,就将相邻的逆序元素位置互换,并把found置true found = True # 内层循环遍历一遍列表未发现逆序,说明列表是有序的,直接退出循环 if not found: break return lst # 交错冒泡, 正向扫描一遍后,再反向扫描寻找逆序对 # 第一层循环,从0开始,到最后一个元素 # 第二层循环,从1开始,到 def cross_bubble_sort(lst): for i in range(len(lst)): found = False if (i % 2 == 0): for j in range(1, len(lst) - i): if lst[j - 1].key > lst[j].key: lst[j - 1], lst[j] = lst[j], lst[j - 1] found = True else: for j in range(len(lst) - i - 1, 0, -1): if lst[j - 1].key > lst[j].key: lst[j - 1], lst[j] = lst[j], lst[j - 1] found = True if not found: break return lst # 快速排序 def quick_sort(lst): # 快速排序递归划分实现 def qsort_req(lst, l, r): if l >= r: return i = l j = r # 局部变量,保存调整记录位置 pivot = lst[i] # list[i] 是初始空位 # 当i = j时一次扫描结束 while i < j: while i < j and lst[j].key >= pivot.key: j -= 1 # 用j向左扫描寻找小于pivot的记录, if i < j: lst[i] = lst[j] i += 1 # 小记录移到左边 while i < j and lst[i].key <= pivot.key: i += 1 # 用i向右扫描大于pivot的记录 if i < j: lst[j] = lst[i] j -= 1 # 大记录移到右边 lst[i] = pivot # pivot 存入最终位置 qsort_req(lst, l, i-1) # 左半区继续递归 qsort_req(lst, i+1, r) # 右半区继续递归 # 执行快速排序划分 qsort_req(lst, 0, len(lst) - 1) # 快速排序的另一种实现 def quick_sort_2(lst): def quick_req_2(lst, begin, end): # 划分当且仅当 begin < end时进行 if begin >= end: return pivot = lst[begin].key i = begin for j in range(begin + 1, end + 1): if lst[j].key < pivot: # 在枢纽元素右边发现较小的元素 i += 1 # 空位 i 向右推进, lst[i], lst[j] = lst[j], lst[i] # 小于枢纽元素的向左移动 lst[i], lst[begin] = lst[begin], lst[i] # 循环结束,此时没有比枢纽元素更小的,就把枢纽元素放回序列中,并把新的begin 作为空位 quick_req_2(lst, begin, i - 1) quick_req_2(lst, i + 1, end) # 执行内部函数 quick_req_2(lst, 0, len(lst) - 1) """ 归并排序 """ def merge(lfrom, lto, low, mid, high): i, j, k = low, mid, low while i < mid and j < high: if lfrom[i].key <= lfrom[j].key: lto[k] = lfrom[i] i += 1 else: lto[k] = lfrom[j] j += 1 k += 1 while j < high: lto[k] = lfrom[j] j += 1 k += 1 def merge_pass(lfrom, lto, llen, slen): i = 0 while i + 2 * slen < llen: merge(lfrom, lto, i, i + slen, i + 2 * slen) i += 2 * slen if i + slen < llen: merge(lfrom, lto, i, i + slen, llen) else: for j in range(i, llen): lto[j] = lfrom[j] def merge_sort(lst): slen, llen = 1, len(lst) templst = [None] * llen while slen < llen: merge_pass(lst, templst, llen, slen) slen *= 2 merge_pass(templst, lst, llen, slen) slen *= 2 """ 桶排序( 应用前提:关键码只有很少几个值 ) 思路: 1. 为每个关键码设定一个桶,(就是一个可扩充的连续表或者链表) 2. 排序时顺序地把记录放到对应关键码的桶中 3. 最后顺序地从桶中取出记录,就是拍好序的序列 """ def radix_sort(lst, d): rlists = [[] for i in range(10)] llen = len(rlists) for m in range(-1, -d - 1, -1): for j in range(llen): rlists[lst[j].key[m]].append(lst[j]) j = 0 for i in range(10): tmp = rlists[i] for k in range(len(tmp)): lst[j] = tmp[k] j += 1 rlists[i].clear() # 方法执行时间计算函数 def runTimeCal(function1): START = time.time() function1(rand_list(1000)) END = time.time() return END - START # 对几种算法进行绘图 def draw(): list1 = [] list2 = [] list3 = [] list4 = [] list5 = [] times = [] for i in range(100): list1.append(runTimeCal(bubble_sort)) list2.append(runTimeCal(cross_bubble_sort)) list3.append(runTimeCal(insert_sort)) list4.append(runTimeCal(quick_sort)) list5.append(runTimeCal(quick_sort_2)) times.append(i) # 画图比较几种排序的效率 # 从图结果可得到的是,插入排序把两种冒泡吊起来打了, 然而快排内心毫无波动,甚至赢的不开心 fig = plt.figure(figsize=(10, 6)) plt.plot(times, list1, c="red", label="bubble_sort") plt.plot(times, list2, c="blue", label="cross_bubble_sort") plt.plot(times, list3, c="yellow", label="insert_sort") plt.plot(times, list4, c="black", label="quick_sort") plt.plot(times, list5, c="green", label="quick_sort_2") plt.legend(loc="upper left") plt.xlabel("test times") plt.ylabel("per operation time") plt.show() draw()
591aa30e092133c0e848f509d93bacb4bdac6973
zhouf1234/untitled3
/面向对象-魔术方法-模拟range.py
667
3.65625
4
class Myrange: def __init__(self,start,stop): self.__start=start self.__stop=stop def __iter__(self): return self def __next__(self): #不写此两条if语句的话,则会无限显示下去,根本不会管结束字符是谁 #self.__start即为n的返回值,self.__stop,即为结束字符 if self.__start == self.__stop: #raise StopIteration:合理报错,即效果等同于循环中的break,但迭代器是不能终止的,不能用break raise StopIteration n= self.__start self.__start +=1 return n mr=Myrange(10,23) for i in mr: print(i)
aaf9ddfc91f566db5c16f0fe0774b7d2808e78ed
vmakksimov/PythonFundamentals
/ListAdvanced/3. Next Version.py
426
3.59375
4
first, second, third = current_version = input().split('.') first = int(first) second = int(second) third = int(third) if third >= 9: third = 0 if second >= 9: second = 0 if first < 9: first += 1 else: second += 1 else: third += 1 new_version = '' new_version += str(first) new_version += str(second) new_version += str(third) version = '.'.join(new_version) print(version)
0eb85570456cbf2a768b38d1a8b64db6aaa40b9c
jorendorff/tinysearch
/tiny.py
4,432
3.6875
4
"""A simple search engine in python.""" import re, pathlib, collections, array, struct, csv, math # === Phase 1: Split text into words def words(text): return re.findall(r"\w+", text.lower()) # === Phase 2: Create an index Document = collections.namedtuple("Document", "filename size") Hit = collections.namedtuple("Hit", "doc_id offsets") def make_index(dir): dir = pathlib.Path(dir) tiny_dir = dir / ".tiny" tiny_dir.mkdir(exist_ok=True) # Build the index in memory. documents = [] index = collections.defaultdict(list) # {str: [Hit]} terms = {} # {str: (int, int)} for path in dir.glob("**/*.txt"): text = path.read_text(encoding="utf-8", errors="replace") doc_words = words(text) doc = Document(path.relative_to(dir), len(doc_words)) doc_id = len(documents) documents.append(doc) # Build an index for this one document. doc_index = collections.defaultdict( lambda: Hit(doc_id, array.array('I'))) for i, word in enumerate(words(text)): doc_index[word].offsets.append(i) # Merge that into the big index. for word, hit in doc_index.items(): index[word].append(hit) # Save the document list. with (tiny_dir / "documents.csv").open('w', encoding="utf-8") as f: out = csv.writer(f) for doc in documents: out.writerow(doc) # Save the index itself. with (tiny_dir / "index.dat").open('wb') as f: start = 0 for word, hits in index.items(): bytes = b"" for hit in hits: bytes += struct.pack("=II", hit.doc_id, len(hit.offsets)) bytes += hit.offsets.tobytes() f.write(bytes) terms[word] = (start, len(bytes)) start += len(bytes) # Save the table of terms. with (tiny_dir / "terms.csv").open('w', encoding="utf-8") as f: out = csv.writer(f) for word, (start, length) in terms.items(): out.writerow([word, start, length]) # === Phase 3: Querying the index class Index: """Object for querying a .tiny index.""" def __init__(self, dir): """Create an Index that reads `$DIR/.tiny`.""" dir = pathlib.Path(dir) tiny_dir = dir / ".tiny" self.dir = dir self.index_file = tiny_dir / "index.dat" self.documents = [] for [line, max_tf] in csv.reader((tiny_dir / "documents.csv").open('r')): self.documents.append(Document(pathlib.Path(line), int(max_tf))) self.terms = {} for word, start, length in csv.reader((tiny_dir / "terms.csv").open('r')): self.terms[word] = (int(start), int(length)) def lookup(self, word): """Return a list of Hits for the given word.""" if word not in self.terms: return [] start, length = self.terms[word] with self.index_file.open('rb') as f: f.seek(start) bytes = f.read(length) read_pos = 0 hits = [] while read_pos < len(bytes): doc_id, hit_count = struct.unpack("=II", bytes[read_pos:read_pos+8]) read_pos += 8 offset_bytes = bytes[read_pos:read_pos + 4 * hit_count] read_pos += 4 * hit_count offsets = array.array('I') offsets.frombytes(offset_bytes) hits.append(Hit(doc_id, offsets)) assert read_pos == len(bytes) return hits def search(self, query): """Find documents matching the given query. Return a list of (document, score) pairs.""" scores = collections.defaultdict(float) for word in words(query): hits = self.lookup(word) if hits: df = len(hits) / len(self.documents) idf = math.log(1 / df) for hit in hits: tf = 1000 * len(hit.offsets) / self.documents[hit.doc_id].size scores[hit.doc_id] += tf * idf results = sorted(scores.items(), key=lambda pair: pair[1], reverse=True) return [(self.documents[doc_id].filename, score) for doc_id, score in results[:10]] if __name__ == '__main__': import sys make_index(sys.argv[1])
4f7dfd5c3bf8a125c52549be89ddc9de0257c9f5
CristianYuri/Kindermath
/Kindermath/cod/mouse.py
981
3.859375
4
#Classe responsavel pela definicao, movimentacao, visibilidade e eventos do mouse class Mouse(object): def __init__(self, amb, screen, local_arquivo, arquivo): self.amb = amb self.screen = screen self.local_arquivo = local_arquivo self.arquivo = arquivo self.carregar_mouse() self.definir_visib_cursor(False) def carregar_mouse(self): self.img = self.amb.image.load(self.local_arquivo + self.arquivo).convert_alpha() self.rect_img = self.img.get_rect() # Define a visibilidade do cursor do pygame def definir_visib_cursor(self, visibilidade=True): self.amb.mouse.set_visible(visibilidade) def tratar_mov_mouse(self): self.rect_img.x, self.rect_img.y = self.amb.mouse.get_pos() self.rect_img.x -= self.img.get_width()/6 self.rect_img.y -= self.img.get_height()/50 # Util para mover objetos na tela self.mov_x, self.mov_y = self.amb.mouse.get_rel() def desenhar(self): self.tratar_mov_mouse() self.screen.blit(self.img, self.rect_img)
301c930db2b258af3b3a89cc5ab74fc7da25cdaf
Shuaiyicao/leetcode-python
/23.py
1,142
3.859375
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param a list of ListNode # @return a ListNode def merge(self, a, b): if a == None: return b if b == None: return a t_head = ListNode(-1) res = t_head while a != None and b != None: if a.val > b.val: t_head.next = b t_head = b b = b.next else: t_head.next = a t_head = a a = a.next while a != None: t_head.next = a t_head = a a = a.next while b != None: t_head.next = b t_head = b b = b.next return res.next def mergeKLists(self, lists): if len(lists) == 0: return None if len(lists) == 1: return lists[0] n = len(lists) x = self.mergeKLists(lists[:n/2]) y = self.mergeKLists(lists[n/2:]) return self.merge(x, y)
1200309fd81e8151ce3c946547c95440932e9a26
NixonZ/PythonZ
/Practice_ques/Odd Or Even.py
512
4.375
4
#Ask the user for a number. Depending on whether the number is even or odd, print out an appropriate message to the user. # Hint: how does an even / odd number react differently when divided by 2? x=int(input("Enter a number:")) if x%2: print("Odd") elif not(x%4): print("Multiple of 4") else : print("Even") num=int(input("Enter num:")) check=int(input("Enter check:")) if not(num%check): print(str(check)+" divides "+str(num)) else: print(str(check)+" does not divide "+str(num)) z=input()
b99912ada9c7d273014b7f7c02efa2ef5b1d4bc1
Aasthaengg/IBMdataset
/Python_codes/p02265/s505685111.py
333
3.625
4
from collections import deque n = int(input()) dl = deque() for _ in range(n): op = input().split() if op[0] == 'insert' : dl.appendleft(op[1]) elif op[0] == 'delete' : if op[1] in dl: dl.remove(op[1]) elif op[0] == 'deleteFirst': dl.popleft() elif op[0] == 'deleteLast' : dl.pop() print(*dl)
5682e6e439102ba025ee5705332918594d4ecc5b
donnyhai/dla
/documents/OLD/Stochastic Geometry SS20/Arbeitsanweisungen/Sheet7Problem1d.py
3,770
3.921875
4
# -*- coding: utf-8 -*- """ Created on Wed Nov 27 07:27:01 2019 """ ################################################################# # run %matplotlib in the console to get an interactive plot # ################################################################# from mpl_toolkits.mplot3d import Axes3D from scipy import stats import matplotlib.pyplot as plt import numpy as np ###Definition of the domain in which we simulate the process x_min = -25 x_max = 25 y_min = -25 y_max = 25 z_min = -25 z_max = 25 area = (x_max - x_min) * (y_max - y_min) * (z_max - z_min) ###Simulation of the Poisson process #The number of points follows a Poisson distribution intensity = 0.005 number_points = stats.poisson.rvs(mu = intensity * area, size = 1) print("\n" + "The number of points is: " + str(number_points) + "\n") #In each coordinate, distribute the points uniformly x_coord = stats.uniform.rvs(loc = x_min, scale = x_max - x_min, size = number_points) y_coord = stats.uniform.rvs(loc = y_min, scale = y_max - y_min, size = number_points) z_coord = stats.uniform.rvs(loc = z_min, scale = z_max - z_min, size = number_points) ###Plot the points and visualize the balls with radii 5, 10, and 20 #Creating the figure fig = plt.figure(figsize = (21, 7)) #Creating three subplots axes = [fig.add_subplot(131, projection='3d'), fig.add_subplot(132, projection='3d'), fig.add_subplot(133, projection='3d')] #Plotting the scattered points three times. Adding to each of the plots one of the balls radii = [5, 10, 20] for i in range(3): #Scatter plots title = "Observation window: B(0, " + str(radii[i]) + ")" axes[i].scatter(x_coord, y_coord, z_coord, edgecolor = 'b', facecolor = 'b', alpha = 0.7, s = 3) #Note: the 's' parameter corresponds to the size of the points axes[i].set_title(title + "\n", fontdict = {'fontsize': 15, 'fontweight': 'medium'}) #Plot spheres into the scatterplots (using spherical coordinates to parametrize them) theta = np.linspace(0, 2 * np.pi, 100) phi = np.linspace(0, np.pi, 100) x = radii[i] * np.outer(np.cos(theta), np.sin(phi)) #Note: np.outer takes two vectors and provides a 2d array which contains all products of entries from the first vector with entries from the second vector y = radii[i] * np.outer(np.sin(theta), np.sin(phi)) z = radii[i] * np.outer(np.ones(np.size(phi)), np.cos(phi)) #Note: np.ones gives a vector with '1' in every entry axes[i].plot_surface(x, y, z, color = 'r', alpha = 0.3) #Note: the 'alpha' parameter is used to make the sphere transparent ###Parameter estimation #Calculate the estimator in each observation window B(0, n), n = 1, 3, 5, 10, 15, 20, 25 for n in [1, 3, 5, 10, 15, 20, 25]: #Calculate Phi(B(0, n)), that is, the number of points in the observation window observed_points = 0 for k in range(int(number_points)): #Check for each point in the process if it falls into the ball if np.sqrt(x_coord[k]**2 + y_coord[k]**2 + z_coord[k]**2) <= n: observed_points += 1 print("Number of points in " + " B(0, " + str(n) + "): " + str(observed_points) + "\n") #Calculate the estimator volume_ball = 4 * np.pi * n**3 / 3 gamma = observed_points / volume_ball print("Value of the estimator: " + str(gamma) + "\n\n") ################################################################################################ ### Notice: Depending on the resolution of your screen you may have to change the parameters ### ### 'figsize' in line 48, 's' in line 57, and 'fontsize' in line 58 to get a decent plot! ### ################################################################################################
1f339291f6b26ae1050226785db95248efc852b2
jiriVFX/data_structures_and_algorithms
/hash_tables/google_sum_of_two_but_return_indices.py
1,081
3.9375
4
# Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target. # # You may assume that each input would have exactly one solution, and you may not use the same element twice. # # You can return the answer in any order. # Brute force nested loops solution def twoSum_brute(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ for i in range(len(nums)): for j in range(i + 1, len(nums)): if nums[i] + nums[j] == target: return [i, j] # ---------------------------------------------------------------------------------------------------------------------- # Hash table - dictionary solution def twoSum_hash(nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ seen = {} for i in range(len(nums)): if nums[i] not in seen: seen[target - nums[i]] = i else: return [seen[nums[i]], i] return False print(twoSum_hash([3, 2, 4], 6))
46f0b7b6641c279b6b426dc21fb668ad097d68cc
yeori/py-training
/hackerrank/q008.py
726
4
4
""" https://www.hackerrank.com/challenges/py-collections-namedtuple/problem # handling string ``` print({0:.3f}.format(12.34567)) # 12.345 ``` # Named Tuple * https://docs.python.org/3.6/library/collections.html#collections.namedtuple """ from collections import namedtuple if __name__ == '__main__': skip_empty_val = lambda s: s # 1. number of lines and columns N = int(input().strip()) cols = filter(skip_empty_val, input().split(' ')) Score = namedtuple('Score', cols) # 2. fill scores total = 0 for i in range(N): row = filter(skip_empty_val, input().split(' ')) # value = list(row) # print('>> ', value) s = Score(*row) total += int(s.MARKS) print('{0:.2f}'.format(total/N))
903b57846cf4e2fe91cf8d992a070013d6dd021a
danielsimonebeira/aulaCesuscPython
/aula4/exerc_10.py
723
3.890625
4
#10. Faça um Programa que pergunte em que turno você estuda. Peça para digitar M-matutino ou # V- Vespertino ou N- Noturno. Imprima a mensagem "Bom Dia!", "Boa Tarde!" ou "Boa Noite!" # ou "Valor Inválido!", conforme o caso. nome_aluno = input("Digite seu nome: ") turno = input(" {}, digite o turno que você estuda: \n - M para matutino, \n - V para Vespertino \n - N para Noturno\n".format(nome_aluno)) if (turno.lower() == 'm'): print("========", "\nBom Dia!", "\n========") if (turno.lower() == 'v'): print("==========", "\nBom Tarde!", "\n==========") if (turno.lower() == 'n'): print("=========-", "\nBoa Noite!", "\n==========")
4beab0c80b7a0844c9acb2475948917eb2b690c0
carolinvdg/MyExercises
/ex45GAMEREADY.py
10,892
4.03125
4
from sys import exit from random import randint class Engine(object): def __init__(self, scene_map): self.scene_map = scene_map def play(self): current_scene = self.scene_map.opening_scene() last_scene = self.scene_map.next_scene('finished') while current_scene != last_scene: next_scene_name = current_scene.enter() current_scene = self.scene_map.next_scene(next_scene_name) current_scene.enter() class Scene (object): def enter(self): print "?" exit (1) class Munich (Scene): def enter(self): print "Your journey starts in the very south of Germany. In the most stuffy city there is. " print "You are in Munich, where every store closes at 8 o clock. " print "You need to get out" print "\n" print "In order to flee the city, you need a cheap ride out." print "So what do you wanna do?" print "You can either HITCHHIKE or take the TRAIN without buying a ticket and hope for the best" choice = raw_input("> ") if choice == "HITCHHIKE": return 'Frankfurt' elif choice == "TRAIN": return 'HANNOVER' else: print "Stick to your options!" return 'MUNICH' class Frankfurt(Scene): def enter (self): print "Welcome to Frankfurt. You need a place to spend the night." print "You can choose between finding accomodation on TINDER or sleep at TRAINSTATION" choice = raw_input("> ") if choice == "TINDER": print "Wow, you are so lucky." print "Found someone who is handsome AND a great cook" print "You sepend a lovely night at your Tinder date's place" print "You sleep very well. The next morning breakfast is prepared for you." print "You tell your date, that you need to get out of the city." print "Luckily your tinder date's mom is driving to HANNOVER today." print "You can join." return 'HANNOVER' elif choice == "TRAINSTATION": print "Are you mad?" print "This is Frankfurt! Hookers steal your phone and you get beaten up by addicts." print "You are not going anywhere. You die." return 'death' else: print "Stick to your choices!" return 'Frankfurt' class Hannover(Scene): def enter (self): print "You made it to the busiest Train Station" print "Thats good. You can go nearly anywhwere from here" print "But you are still out of money. " print "You need to earn some cash." print "You can either BEG for money or ROB a bank" choice = raw_input("> ") if choice == "BEG": print "The real hobos get really mad and punch you hard" print "You die" return 'death' elif choice == "ROB": print "Are you mad?" print "You really wanna go through with this, you are insane" print "You cover your face with a scarf and go to the bank" print "The lady at the counter thinks you are joking." print "You know her from vacation" print "She sais: Nice to see you again! Haha, good joke!" print "You ask her to lend you money, she agrees. How much money do you need?" choice = raw_input("> ") how_many = int (choice) if how_many <20: print "You are not getting anywhere with that." print "You have to sleep at the station and die from a lung infection after a night on the cold stone" return 'death' else: print "Get on the train again." print "Do you want to get out at LUNEBURG or BREMEN ?" choice = raw_input("> ") if choice == "LUNEBURG": print "You chose the most boring city in Germany to stop at" return 'LUNEBURG' elif choice == "BREMEN": print "Okay, hope you brought a nice and warm jacket, its very cold at the harbor " return 'BREMEN' else: print "Stick to your options." return 'HANNOVER' else: print "Stick to sour options." return 'HANNOVER' class LUNEBURG(Scene): def enter (self): print "You came during Lunatic. Lucky you. Its the best time to be around Luneburg" print "There are some pretty amazing acts." print "You manage to trick the bouncer and get in without paying," print "Pretty amazing work! What could possibly go wrong from now on?" print "You can choose an act! Do you wanna see VONWEGENLISBETH or MONEYBOY?" choice = raw_input ("> ") if choice == "MONEYBOY": print "You chose the king of our generation. You will love the show" print "Oh no! Moneyboy seems to be out of his mind!" print "He took a few drugs too many!" print "Be careful, he is throwing the microphone into the crowd!" print "It hits you right on the head. You die immediately." return 'death' elif choice == "VONWEGENLISBETH": print " What an amazing show! You love them!" print "You even get the chance to talk to them after the show." print "Wow, seems like they really like you. They have another gig in BREMEN and allow you to join the tour bus" return 'BREMEN' else: print "Stick to your options." return 'LUNEBURG' class BREMEN (Scene): def enter (self): print 'Here you are! Its cold and you are hungry.' print "What to get:" dishes = "FISHBUN, WAFFLES, BOOZE" print dishes print "Do you want something savory,something sweet or rather get drunk?" print "What do you wanna get?" choice = raw_input("> ") if choice == "FISHBUN": print "Good choice." print "In Bremen you can get good fish!" print "But what kind of fish would you like?" print "Do you want MATIE or FRIEDFISH?" choice = raw_input("> ").upper if choice == "FRIEDFISH": print "Oh no. The fish wasnt good anymore. The flaky crust covered up the bad taste" print "You die of food poisoning." return 'death' elif choice == "MATIE": print "That tastes great! You compliment the little fish shop" print "The worker at the fish job is very happy about the compliment" print "He tells you that he wants to open a shop in the best city in the world." print "Then he grins like he is thinking about something" print "I have a great idea, he sais. Would you like to work in the fish store in COLOGNE ?" print "You cannot believe it. You would love to!" return 'COLOGNE' elif choice =="WAFFLES": print "Sometimes an unhealthy treat is all you need." print "The waffles are insanely big and look delicious." print "You can get CHOCOLATE or SURPRISE waffles " choice = raw_input("> ") if choice == "CHOCOLATE": print "Oh no! You accidentally spill the sauce all over your clothes" print "You look pathetic. No one likes you. You die of stupidity" return 'death' elif choice == "SURPRISE": print "Good choice!" print "A siren in the waffle store starts blinking" print "Whats the matter?" print "You ordered the 1000th surprise waffle and therefore get a big surprise" print "You win a trip to th best city in the world!" return 'COLOGNE' else: print "Stick to your choices" return 'BREMEN' elif choice == "BOOZE": print "You just know how to turn a bad day into a good one." print "Being tipsy helps dealing with the cold weather" print "And you appear to be an absolute great entertainer when drinking" print "You tell jokes loudly and a big crowd surrounds you." print "They cheer, you are amazing!" print "Then they even start collecting money for you. Great! " print "One of the men in the crowd turns out to be an agent. He offers you a contract and a ride to the best city in the world." print "You can fly out to COLOGNE" return 'COLOGNE' else: print "Stick to your choices!" return 'BREMEN' class Bus(Scene): def enter (self): print "Congrats, you made it to Cologne!" print "I hope you learned something out of this!" print "Dont go on a huge trip without any money!" print "But you arrived- thats all that matters!" print "Right in time for carnival. Do you want to dress up as the STATUEOFLIBERTY or HANNAHMONTANA ?" choice = raw_input ("> ") if choice == "HANNAHMONTANA": print "You look just like her!" print "Amazing! You have great fun!" return 'END' elif choice == "STATUEOFLIBERTY": print "Everyone thinks you are a Trump supporter and is very mean"# print "You get kicked out of every party" print "No one likes you. You managed to have the worst time in the best city." return 'death' class Death(Scene): quips = [ "You're not made for these kinds of journey. Go home and cry" ] class END(Scene): def enter (self): print "You had an amazing adventure." print "What a trip!" print "You won in life." class Map (object): scenes ={ 'MUNICH': MUNICH(), 'FRANKFURT': FRANKFURT(), 'HANNOVER': HANNOVER(), 'LUNEBURG': LUNEBURG(), 'BREMEN': BREMEN(), 'COLOGNE': COLOGNE(), 'death': Death(), 'END': END(), } def __init__(self, start_scene): self.start_scene = start_scene def next_scene(self, scene_name): val = Map.scenes.get(scene_name) return val def opening_scene (self): return self.next_scene(self.start_scene) a_map = Map ('MUNICH') a_game = Engine(a_map) a_game.play()
04afffef6917c501df6d892d8731f85ef5ac3cbc
sunanth123/pypixelator
/src/mirror.py
883
3.96875
4
## This function will mirror an image that is provided to it by using ## nested loops to iterate through the original image pixels and placing them ## in the new image in an inverted manner from PIL import Image def mirror(im): ## get the dimensions and pixels from the original image and initialize ## a new image with the same size. size = im.size pixels = im.load() newImg = Image.new('RGB', size, 0) newPixels = newImg.load() mir_width = size[0] - 1 mir_height = 0 ## Iterate through each pixel of the original image and then place the pixel ## in the opposite dimension (around the y-axis) for y in range(size[1]): for x in range(size[0]): newPixels[mir_width,mir_height] = pixels[x,y] mir_width = mir_width - 1 mir_width = size[0] - 1 mir_height = mir_height + 1 return newImg
11c352d20b0c40275d6f82c90a130ca49b62abaf
zzynggg/python
/Hash Table ADTs/list_adt.py
16,083
4
4
""" List ADT and an array implementation. Defines a generic abstract list with the usual methods, and implements a list using arrays and linked nodes. It also includes a linked list iterator. Also defines UnitTests for the class. """ __author__ = "Maria Garcia de la Banda, modified by Brendon Taylor" __docformat__ = 'reStructuredText' import unittest from abc import ABC, abstractmethod from enum import Enum from typing import Generic from referential_array import ArrayR, T class ListADT(ABC, Generic[T]): """ Abstract class for a generic List. """ def __init__(self) -> None: """ Initialises the length of an exmpty list to be 0. """ self.length = 0 @abstractmethod def __setitem__(self, index: int, item: T) -> None: """ Sets the value of the element at position index to be item :pre: index is 0 <= index < len(self) """ pass @abstractmethod def __getitem__(self, index: int) -> T: """ Returns the value of the element at position index :pre: index is 0 <= index < len(self) """ pass def __len__(self) -> int: """ Returns the length of the list :complexity: O(1) """ return self.length @abstractmethod def is_full(self) -> bool: """ Returns True iff the list is full """ pass def is_empty(self) -> bool: """ Returns True iff the list is empty :complexity: O(1) """ return len(self) == 0 def clear(self): """ Sets the list back to empty :complexity: O(1) """ self.length = 0 @abstractmethod def insert(self, index: int, item: T) -> None: """ Moves self[j] to self[j+1] if j>=index, sets self[index]=item :pre: index is 0 <= index <= len(self) """ pass def append(self, item: T) -> None: """ Adds the item to the end of the list; the rest is unchanged. :see: #insert(index: int, item: T) """ self.insert(len(self), item) @abstractmethod def delete_at_index(self, index: int) -> T: """Moved self[j+1] to self[j] if j>index & returns old self[index] :pre: index is 0 <= index < len(self) """ pass @abstractmethod def index(self, item: T) -> int: """ Returns the position of the first occurrence of item :raises ValueError: if item not in the list """ pass def remove(self, item: T) -> None: """ Removes the first occurrence of the item from the list :raises ValueError: if item not in the list :see: #index(item: T) and #delete_at_index(index: int) """ index = self.index(item) self.delete_at_index(index) def __str__(self) -> str: """ Converts the list into a string, first to last :complexity: O(len(self) * M), M is the size of biggest item """ result = "[" for i in range(len(self)): if i > 0: result += ', ' result += str(self[i]) result += ']' return result class ArrayList(ListADT[T]): """ Implementation of a generic list with arrays. Attributes: length (int): number of elements in the list (inherited) array (ArrayR[T]): array storing the elements of the list ArrayR cannot create empty arrays. So MIN_CAPCITY used to avoid this. """ MIN_CAPACITY = 1 def __init__(self, max_capacity: int) -> None: """ Initialises self.length by calling its parent and self.array as an ArrayList of appropriate capacity :complexity: O(len(self)) always due to the ArrarR call """ ListADT.__init__(self) self.array = ArrayR(max(self.MIN_CAPACITY, max_capacity)) def __getitem__(self, index: int) -> T: """ Returns the value of the element at position index :pre: index is 0 <= index < len(self) checked by ArrayR's method :complexity: O(1) """ return self.array[index] def __setitem__(self, index: int, value: T) -> None: """ Sets the value of the element at position index to be item :pre: index is 0 <= index < len(self) checked by ArrayR's method :complexity: O(1) """ self.array[index] = value def __shuffle_right(self, index: int) -> None: """ Shuffles all the items to the right from index :complexity best: O(1) shuffle from the end of the list :complexity worst: O(N) shuffle from the start of the list where N is the number of items in the list """ for i in range(len(self), index, -1): self.array[i] = self.array[i - 1] def __shuffle_left(self, index: int) -> None: """ Shuffles all the items to the left from index :complexity best: O(1) shuffle from the start of the list :complexity worst: O(N) shuffle from the end of the list where N is the number of items in the list """ for i in range(index, len(self)): self.array[i] = self.array[i+1] def is_full(self): """ Returns true if the list is full :complexity: O(1) """ return len(self) >= len(self.array) def index(self, item: T) -> int: """ Returns the position of the first occurrence of item :raises ValueError: if item not in the list :complexity: O(Comp==) if item is first; Comp== is the BigO of == O(len(self)*Comp==) if item is last """ for i in range(len(self)): if item == self[i]: return i raise ValueError("Item not in list") def delete_at_index(self, index: int) -> T: """ Moves self[j+1] to self[j] if j>index, returns old self[index] :pre: index is 0 <= index < len(self) checked by self.array[_] :complexity: O(len(self) - index) """ if index < 0 or index > len(self): raise IndexError("Out of bounds") item = self.array[index] self.length -= 1 self.__shuffle_left(index) return item def insert(self, index: int, item: T) -> None: """ Moves self[j] to self[j+1] if j>=index & sets self[index]=item :pre: index is 0 <= index <= len(self) checked by self.array[_] :complexity: O(len(self)-index) if no resizing needed, O(len(self)) otherwise """ if self.is_full(): raise Exception("List is full") self.__shuffle_right(index) self.array[index] = item self.length += 1 class Node(Generic[T]): """ Implementation of a generic Node class Attributes: item (T): the data to be stored by the node link (Node[T]): pointer to the next node ArrayR cannot create empty arrays. So MIN_CAPCITY used to avoid this. """ def __init__(self, item: T = None) -> None: self.item = item self.link = None class LinkListIterator(Generic[T]): """ Implementation of a the methods to make LinkList iterable" Attributes: current (Node[T]): the node whose item will be returned next """ def __init__(self, node: Node[T]) -> None: """Initialises self.current to the node given as input :complexity: O(1) """ self.current = node def __iter__(self) -> 'LinkListIterator': """ Returns itself, as required to be iterable. :complexity: O(1) """ return self def __next__(self) -> T: """ Returns the current item and moves to the next node :raises StopIteration: if the current item does not exist :complexity: O(1) """ if self.current is not None: item = self.current.item self.current = self.current.link return item else: raise StopIteration class LinkList(ListADT[T]): """ Implementation of a generic list with linked nodes. Attributes: length (int): number of elements in the list (inherited) head (Node[T]): node at the head of the list """ def __init__(self) -> None: """ Initialises self.length by calling its parent and self.head as None, since the list is initially empty :complexity: O(1) """ ListADT.__init__(self) self.head = None def __iter__(self) -> LinkListIterator[T]: """ Computes and returns an iterator for the current list :complexity: O(1) """ return LinkListIterator(self.head) def __setitem__(self, index: int, item: T) -> None: """ Sets the value of the element at position index to be item :see: #__get_node_at_index(index) """ node_at_index = self.__get_node_at_index(index) node_at_index.item = item def __getitem__(self, index: int) -> T: """ Returns the value of the element at position index :see: #__get_node_at_index(index) """ node_at_index = self.__get_node_at_index(index) return node_at_index.item def is_full(self): """ Returns true if the list is full :complexity: O(1) """ return False def __get_node_at_index(self, index: int) -> Node[T]: """ Returns the node in the list at position index :complexity: O(index) :pre: index is 0 <= index < len(self) """ if 0 <= index and index < len(self): current = self.head for i in range(index): current = current.link return current else: raise ValueError("Index out of bounds") def insert(self, index: int, item: T) -> None: """ Moves self[j] to self[j+1] if j>=index & sets self[index]=item :pre: index is 0 <= index <= len(self), checked by __get_node_at_index :complexity: O(index) """ new_node = Node(item) if index == 0: new_node.link = self.head self.head = new_node else: previous_node = self.__get_node_at_index(index-1) new_node.link = previous_node.link previous_node.link = new_node self.length += 1 def index(self, item: T) -> int: """ Returns the position of the first occurrence of item :raises ValueError: if item not in the list :complexity: O(Comp==) if item is first; Comp== is the BigO of == O(len(self)*Comp==) if item is last """ current = self.head index = 0 while current is not None and current.item != item: current = current.link index += 1 if current is None: raise ValueError("Item is not in list") else: return index def delete_at_index(self, index: int) -> T: """ Moves self[j+1] to self[j] if j>index & returns old self[index] :pre: index is 0 <= index < len(self), checked by __get_node_at_index :complexity: O(index) """ try: previous_node = self.__get_node_at_index(index-1) except ValueError as e: if self.is_empty(): raise ValueError("List is empty") elif index == 0: item = self.head.item self.head = self.head.link else: raise e else: item = previous_node.link.item previous_node.link = previous_node.link.link self.length -= 1 return item def delete_negative(self): """ Deletes all nodes with a negative item. :complexity: O(len(self)) """ previous = self.head for _ in range(1,self.length): # delete negative nodes from index 1 current = previous.link if current.item < 0: previous.link = current.link # delete the node self.length -= 1 else: previous = current # move previous along if self.length > 0 and self.head.item < 0: #check node at index 0 self.head = self.head.link # move the head self.length -= 1 def clear(self): """ Overrides the parent to set the head to None :complexity: O(1) """ ListADT.clear(self) self.head = None class DataStructure(Enum): ARRAY = 1 LINK = 2 class TestList(unittest.TestCase): """ Tests for the above class.""" EMPTY = 0 ROOMY = 5 LARGE = 10 def setUp(self): self.lengths = [self.EMPTY, self.ROOMY, self.LARGE, self.ROOMY, self.LARGE] if test_list == DataStructure.ARRAY: self.lists = [ArrayList(self.LARGE) for i in range(len(self.lengths))] else: self.lists = [LinkList() for i in range(len(self.lengths))] for list, length in zip(self.lists, self.lengths): for i in range(length): list.append(i) self.empty_list = self.lists[0] self.roomy_list = self.lists[1] self.large_list = self.lists[2] #we build empty lists from clear. #this is an indirect way of testing if clear works! #(perhaps not the best) self.clear_list = self.lists[3] self.clear_list.clear() self.lengths[3] = 0 self.lists[4].clear() self.lengths[4] = 0 def tearDown(self): for s in self.lists: s.clear() def test_init(self) -> None: self.assertTrue(self.empty_list.is_empty()) self.assertEqual(len(self.empty_list), 0) def test_len(self): """ Tests the length of all lists created during setup.""" for list, length in zip(self.lists, self.lengths): self.assertEqual(len(list), length) def test_is_empty_add(self): """ Tests lists that have been created empty/non-empty.""" self.assertTrue(self.empty_list.is_empty()) self.assertFalse(self.roomy_list.is_empty()) self.assertFalse(self.large_list.is_empty()) def test_is_empty_clear(self): """ Tests lists that have been cleared.""" for list in self.lists: list.clear() self.assertTrue(list.is_empty()) def test_is_empty_delete_at_index(self): """ Tests lists that have been created and then deleted completely.""" for list in self.lists: #we empty the list for i in range(len(list)): self.assertEqual(list.delete_at_index(0), i) try: list.delete_at_index(-1) except: self.assertTrue(list.is_empty()) def test_append_and_remove_item(self): for list in self.lists: nitems = self.ROOMY list.clear() for i in range(nitems): list.append(i) for i in range(nitems-1): list.remove(i) self.assertEqual(list[0],i+1) list.remove(nitems-1) self.assertTrue(list.is_empty()) for i in range(nitems): list.append(i) for i in range(nitems-1,0,-1): list.remove(i) self.assertEqual(list[len(list)-1],i-1) list.remove(0) self.assertTrue(list.is_empty()) def test_clear(self): for list in self.lists: list.clear() self.assertTrue(list.is_empty()) if __name__ == '__main__': test_list = DataStructure.ARRAY testtorun = TestList() suite = unittest.TestLoader().loadTestsFromModule(testtorun) unittest.TextTestRunner().run(suite) test_list = DataStructure.LINK testtorun = TestList() suite = unittest.TestLoader().loadTestsFromModule(testtorun) unittest.TextTestRunner().run(suite)
fcab3ff3814d1241e380e8a4ba6ad13a9d78e4ec
huyhoang17/Project_Euler
/36.py
1,034
3.859375
4
#!/usr/bin/python3 ''' - The decimal number, 585 = 10010010012 (binary), is palindromic in both bases. - Find the sum of all numbers, less than one million, which are palindromic in base 10 and base 2. - (Please note that the palindromic number, in either base, may not include leading zeros.) ''' from base import Problem def check_db_palindromes(n): ''' Return True if n is palindromic in both bases: 2 and 10 ''' # bin(n) -- type(str) if str(n) == str(n)[::-1]: if bin(n)[2:] == bin(n)[2:][::-1]: return True return False def sum_db_palindromic(): ''' Calculate sum of all palindromic number under 10**6 ''' return sum([i for i in range(1, 10**6) if check_db_palindromes(i)]) class Solution(Problem): def solve(self): print('Solving problem {}'.format(self.number)) output = sum_db_palindromic() print('Result: {}'.format(output)) if __name__ == '__main__': solution = Solution(36) solution.solve() # output: 872187
9233a7dfb7e38471039995f661eae0e8155a75cd
JayFoxFoxy/ProjectEuler
/P10v4.py
667
4.03125
4
#Sieve of eratosthenes algorythm def removeNonPrimes(numbers, total): auxList = [2,3,5,7] index = 0 #print(auxList[index]) n = 0 aux = 2 for i in auxList: print(i) while(n<=int(total)): n = int(i) * aux #print(n) if n in numbers: numbers.remove(n) aux+=1 aux = 2 n = 0 #print(numbers) return numbers def sumList(numbers): total = 0 for i in numbers: total += int(i) return total #Main number = input("Insert the total: ") #print(number) numbers = list(range(2,int(number))) #print(numbers) numbers = removeNonPrimes(numbers, number) print(numbers) print("The total of all the sum of ", number, " is: ", sumList(numbers))
961f13608e9aecd3129220888ab2292b9da8449a
Nora-Wang/Leetcode_python3
/Hash and Heap/lintcode_0955. Implement Queue by Circular Array.py
2,468
4.03125
4
Implement queue by circulant array. You need to support the following methods: CircularQueue(n): initialize a circular array with size n to store elements boolean isFull(): return true if the array is full boolean isEmpty(): return true if there is no element in the array void enqueue(element): add an element to the queue int dequeue(): pop an element from the queue Example Example 1: Input: CircularQueue(5) isFull() isEmpty() enqueue(1) enqueue(2) dequeue() Output: ["false","true","1"] Example 2: Input: CircularQueue(5) isFull() isEmpty() enqueue(1) enqueue(2) dequeue() dequeue() enqueue(1) enqueue(2) enqueue(3) enqueue(4) enqueue(5) isFull() dequeue() dequeue() dequeue() dequeue() dequeue() Output: ["false","true","1","2","true","1","2","3","4","5"] Notice it's guaranteed in the test cases we won't call enqueue if it's full and we also won't call dequeue if it's empty. So it's ok to raise exception in scenarios described above. 思路: 我们需要知道队列的入队操作是只在队尾进行的,相对的出队操作是只在队头进行的,所以需要两个变量top与bottom分别来指向队头与队尾; 注意top和bottom的初始值都应该是0,并且都是+1地变化(queue的逻辑理解) 由于是循环队列,我们在增加元素时,如果此时bottom = len(array),bottom需要更新为0;同理,在元素出队时,如果top = len(array),top需要更新为0. 对此,我们可以直接取模来计算其位置 code: class CircularQueue: def __init__(self, n): self.array = [None] * n #队头 self.top = 0 #队尾 self.bottom = 0 #queue的长度 self.size = 0 """ @return: return true if the array is full """ def isFull(self): return self.size != 0 and self.size % len(self.array) == 0 """ @return: return true if there is no element in the array """ def isEmpty(self): return self.size == 0 """ @param element: the element given to be added @return: nothing """ def enqueue(self, element): #一定要取模,不然会out of index self.array[self.bottom % len(self.array)] = element self.bottom += 1 self.size += 1 return """ @return: pop an element from the queue """ def dequeue(self): result = self.array[self.top % len(self.array)] self.top += 1 self.size -= 1 return result
f28e6b12506c121cf5c11a7882cd6b63520f4141
Liu-Zhijuan-0313/pythonAdvance
/lianxi/day0212/day03.py
401
3.6875
4
class AI(object): # 如果随意添加岂不是封装不安全了? # 可以通过__slots__限制添加的内容 __slots__ = ("name", "hp", "mp") def __init__(self, _hp): self.hp = _hp a1 = AI(50) print(a1.hp) # 动态的添加类属性 #实例也拥有了该属性 AI.name = "python1811" print(a1.name) print(AI.name) # 动态的添加实例属性 a1.mp = 30 print(a1.mp)
2ea976f760557bb6cb0089484621d84cb4dc9640
SREEHARI1994/ThinkPython_mysolutions
/tuples_chapter/most_frequent.py
7,134
3.625
4
# -*- coding: utf-8 -*- import string def most_frequent(text): #removing punctuations for letter in text: if letter in list(string.punctuation): text=text.replace(letter,"") #removing all whitespaces and converting to lower case text= "".join(text.split()).lower() d={} for letter in text: d[letter]=d.get(letter,0)+1 frequencies=list(d.values()) frequencies.sort(reverse=True) for value in frequencies: for key in d: if d[key]== value: print(key,value) if __name__ == "__main__": english_text= """GitHub Packages is a package hosting service, fully integrated with GitHub. GitHub Packages combines your source code and packages in one place to provide integrated permissions management and billing, so you can centralize your software development on GitHub. You can publish packages in a public repository (public packages) to share with all of GitHub, or in a private repository (private packages) to share with collaborators or an organization. You can use GitHub roles and teams to limit who can install or publish each package, as packages inherit the permissions of the repository. Anyone with read permissions for a repository can install a package as a dependency in a project, and anyone with write permissions can publish a new package version. You can host multiple packages in one repository and see more information about each package by viewing the package's README, download statistics, version history, and more. You can integrate GitHub Packages with GitHub APIs, GitHub Actions, and webhooks to create an end-to-end DevOps workflow that includes your code, CI, and deployment solutions.""" print("The most frequent letters in English Language are\n ") most_frequent(english_text) malaylam_text="""മുതിര്‍ന്ന പൗരന്‍മാരുടെ രചനകള്‍ കോര്‍ത്തിണക്കി കൊച്ചിയിലൊരു ചിത്രപ്രദര്‍ശനം . കൊച്ചി പത്തടിപ്പാലത്തെ കേരള ചരിത്രമ്യൂസിയത്തില്‍ സംഘടിപ്പിച്ചിരിക്കുന്ന പ്രദര്‍ശനത്തിന് മികച്ച പ്രതികരണമാണ് കലാസ്വാദകരില്‍ നിന്ന് കിട്ടുന്നത്. പതിനഞ്ച് ചിത്രകാരന്‍മാരുടെ മിഴിവുളള രചനകളാണ് ചുവരു നിറയെ . ചിത്രങ്ങള്‍ വരച്ചൊരുക്കിയിരിക്കുന്നത് അമ്പത്തിയഞ്ച് വയസിനു മുകളില്‍ പ്രായമുളള ചിത്രകാരന്‍മാര്‍. നാടറിയുന്ന പ്രൊഫഷണല്‍ ചിത്രകാരന്‍മാര്‍ മുതല്‍ കാലങ്ങളുടെ ഇടവേളയ്ക്കു ശേഷം പെയിന്‍റിങ് ബ്രഷ് കയ്യിലെടുത്തവരുടെ വരെ വരകളുണ്ട് ഇക്കൂട്ടത്തില്‍. ആലുവ ചെമ്പറക്കിയിലെ ബ്ലസ് റിട്ടയര്‍മെന്‍റ് ലിവിങ്ങിലെ അന്തേവാസികളായ മുതിര്‍ന്ന പൗരന്‍മാരുടെ സൃഷ്ടികളും പ്രദര്‍ശനത്തിലുണ്ട്. കളിമണ്ണില്‍ തീര്‍ത്ത കലാസൃഷ്ടികളും പ്രദര്‍ശനത്തിന്‍റെ മറ്റൊരാകര്‍ഷണം. നാലുമണിപൂക്കള്‍ എന്നു പേരിട്ട പ്രദര്‍ശനം ഞായറാഴ്ച വരെ നീളും. """ print("The most frequent letters in Malayalam Language are\n") most_frequent(malaylam_text) Hindi_text=""" कहानी पीके एक राजनीतिक व्यंग्य है, जो कि समाज में फैले भ्रष्टाचार को उजागर करता है। निर्देशक राजकुमार हिरानी के मुताबिक फिल्म भगवान और उसके भक्तों पर व्यंग्य करती है। कथानक एक एलियन (आमिर खान) बिना किसी चीज के पृथ्वी पर आता है, उसके पास कपड़े तक नहीं है सिवाय उसके लाॅकेट के जो कि उसका रिमोट है और उसी के सहारे अंतरिक्ष यान को बुलाकर वह अपने ग्रह पर वापस जा सकता है लेकिन कुछ समय के भीतर ही उस एलियन यानी आमिर खान से लाॅकेट लूट लिया जाता है। वह उसे वापस पाने का प्रयास करता है मगर असफल रहता है। वह ऐसी धरती पर आ गया है जो कि उसके घर से बिल्कुल अलग है। यहां वह धीरे धीरे पैसों और कपड़ों का मतलब समझता है। एक बार, जब वह अपने जीवन के लिए चल रहा होता है, भैरो सिंह (संजय दत्त) की गाड़ी से लड़ जाता है। उसे लगता है कि इस एलियन की याददाश्त जा चुकी है और वह किसी को पहचान नहीं पा रहा है। वह उस एलियन को अपने साथ ले जाता है और धरती के रीति रिवाजों को समझाने में उसकी मदद करता है। वह पृथ्वी पर कोई भी भाषा समझ नहीं पाता है और वह महिला के हाथों से उसकी भाषा को अपने अंदर लेने की कोशिश करता रहता है। भैरों को लगता है कि एलियन औरतों की तरफ ज्यादा प्रभावित है इसलिए वह उसे नाइट क्लब में लेकर जाता है जहां वह हाथ पकड़ने के लिए अब स्वतंत्र था। सीख जाता है।""" print("The most frequent letters in Hindi lanuage are\n") most_frequent(Hindi_text)
3d4d42cc3807141c4bd6179c86ad750e519fc386
Likh-Alex/PostgreSQL-Python
/lottery.py
1,164
3.84375
4
import random def menu(): #Ask player for numbers #Calculate lottery numbers #Print out the winnings player_numbers = get_players_number() lottery_numbers = create_lottery_numbers() lottery_numbers matched_numbers = lottery_numbers.intersection(player_numbers) if len(matched_numbers) == 0: print("No numbers matched") match = [int(number) for number in matched_numbers] prize = len(match) ** 10 print(f"Numbers matched are: {match}, You won {prize} bananas!") # User can pick 6 numbers def get_players_number(): number_csv = input("Enter your 6 numbers, separated by commas: ") #Create a set of int from number_csv file numbers = number_csv.split(",") integer_set = {int(number) for number in numbers} return integer_set # Lottery calculates 6 random numbers def create_lottery_numbers(): lottery_numbers =set() while len(lottery_numbers) < 6: lottery_numbers.add(random.randint(0,10)) return lottery_numbers # Then we match the user number to the lottery numbers # Calculate the winnings based on how many the user matched menu()
44082caf0455c8f307469fa6d862db2dfc82489b
AveryHuo/PeefyLeetCode
/src/Python/101-200/151.ReverseWordsInString.py
253
3.703125
4
class Solution: def reverseWords(self, set): return ' '.join(set.split()[::-1]) if __name__ == "__main__": solution = Solution() print(solution.reverseWords("the sky is blue")) print(solution.reverseWords(" hello world! "))
09b7b8494b5a0640127f46df20650a132c5fc853
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/hamming/e24c21afe3ff46c1863c2f45eb9ae131.py
334
3.984375
4
def distance(strand, mut_strand): '''This function calculates the hamming distance between two DNA strands''' strand_len = len(strand) if strand_len != len(mut_strand): raise ValueError('Both DNA strands need to be the same length') return sum([strand[c] != mut_strand[c] for c in range(0, strand_len)])
bc4bbe31282a164f7490f19f8809323a04e551c7
mangel2500/Programacion
/Práctica 7 Python/Exer-2.py
603
4.1875
4
'''MIGUEL ANGEL MENA ALCALDE - PRACTICA 7 EJERCICIO 2 Escribe un programa que lea el nombre y los dos apellidos de una persona (en tres cadenas de caracteres diferentes), los pase como parmetros a una funcin, y sta debe unirlos y devolver una nica cadena. La cadena final la imprimir el programa por pantalla''' def total(): nombre=raw_input("Escribe tu nombre: ") apellido1=raw_input("Escribe tu primer apellido: ") apellido2=raw_input("Escribe tu segundo apellido: ") total = nombre+' '+ apellido1+' '+apellido2 print 'Tu nombre es: ',total total()
6c1694a3cd7f4c4966888d8c5025d4f6c64645b5
hsiehkl/Data-Structure-and-Programming
/programming_hw4/programming_hw4.py
3,302
3.59375
4
########################################### # 107-1 Data Structure and Programming # Programming Assignment #4 # Instructor: Pei-Yuan Wu ############################################ import sys # ********************************** # * TODO * # ********************************** ''' You need to complete this class MinBinaryHeap() Feel free to add more functions in this class. ''' class MinBinaryHeap(): def __init__(self): self.heap = [0] # with a dummy node self.heapSize = 0 def insert(self, item): self.heap.append(item) self.heapSize = self.heapSize + 1 self.perlocateUp(self.heapSize) def deleteMin(self): min = self.heap[1] self.heap[1] = self.heap[self.heapSize] self.heapSize = self.heapSize - 1 self.heap.pop() self.perlocateDown(1) return min def findMin(self): return self.heap[1] def size(self): return self.heapSize def string(self): # Convert self.heap into a string return list2String(self.heap[1:]) def perlocateUp(self, i): while (i // 2) > 0: if self.heap[i] < self.heap[(i // 2)]: tmp = self.heap[(i // 2)] self.heap[(i // 2)] = self.heap[i] self.heap[i] = tmp i = (i // 2) def perlocateDown(self, i): while (i * 2) <= self.heapSize: mc = self.minChild(i) if self.heap[i] > self.heap[mc]: tmp = self.heap[i] self.heap[i] = self.heap[mc] self.heap[mc] = tmp i = mc def minChild(self, i): if (i * 2) + 1 > self.heapSize: return i * 2 else: if self.heap[(i*2)] < self.heap[(i*2+1)]: return i * 2 else: return (i * 2) + 1 def list2String(l): formatted_list = ['{}' for item in l ] s = ','.join(formatted_list) return s.format(*l) if __name__ == '__main__': # 1. Check the command-line arguments if len(sys.argv) != 3: sys.exit("Usage: python3 programming_hw4.py <input> <output>") # 2. Read the input file inFile = open(sys.argv[1], 'r') input_line_list = list(inFile.read().splitlines()) input_cmd_list = [ line.split(' ') for line in input_line_list ] inFile.close() # 3. Solve minPQ = MinBinaryHeap() findMin_list = [] for cmd in input_cmd_list: if cmd[0] == 'insert': # print('insert {}'.format(cmd[1])) minPQ.insert(int(cmd[1])) elif cmd[0] == 'deleteMin': # print('deleteMin') if minPQ.size() > 0: minPQ.deleteMin() elif cmd[0] == 'findMin': # print('findMin') if minPQ.size() > 0: findMin_list.append(minPQ.findMin()) else: findMin_list.append('-') else: # Unknown command assert False # print(minPQ.string()) # 4. Output answers outFile = open(sys.argv[2], 'w') # 4.1 Output FindMin string outFile.write('{}\n'.format(list2String(findMin_list))) # 4.2 Output minPQ string outFile.write('{}'.format(minPQ.string())) outFile.close()
5ce4e69a76c571d7212e399103a1d001a0b3a479
dymbow10/python-faculdade
/folha 3/exercicio 1.py
518
3.796875
4
#achar aposição de um caractere numa string def ler(): frase=input("Insira sua frase bro: ") l=input('Insira a letra a ser procurada: ') return frase,l def procura(frase,l): achei=False for i in range(len(frase)): if l == frase[i]: print("Caractere encontrado na posição {:1d}".format(i)) achei=True break return achei def impr(achei): if not achei: print ("Não encontrado") #main frase,l=ler() achei=procura(frase,l) impr(achei)
6299f8e9e8b8b470656de8256ae3e250cfb4c654
Jangwoojin863/python
/고급예제5.py
3,542
3.515625
4
# 고급 예제 5 # 콘솔창에서 실행하는 예제입니다. # python 고급예제5.py <엔터> import os MAZE_SIZE = 12 WALL = '#' MOUSE = 'Q' END = '$' UP = 0 RIGHT = 1 DOWN = 2 LEFT = 3 Exit = False ms = [0, 0, 0] # 마우스 좌표와 방향 저장 x, y, d old_ms = [0, 0, 0] # 마우스 이전 좌표와 방향 저장 # 미로 정의 데이터 maze = [ ['#','#','#','#','#','#','#','#','#','#','#','#'], ['#',' ',' ',' ',' ','#','#',' ',' ',' ',' ','#'], ['#',' ','#','#',' ','#','#',' ','#','#',' ','#'], ['#',' ','#','#',' ','#','#',' ',' ','#',' ','#'], ['#',' ','#','#',' ','#','#','#',' ','#',' ','#'], ['#',' ','#','#',' ',' ','#','#',' ','#',' ','#'], ['#',' ','#','#','#',' ','#','#',' ','#',' ','#'], ['#',' ','#',' ',' ',' ','#','#',' ','#',' ','#'], ['#',' ','#',' ','#','#','#','#',' ','#',' ','#'], ['#',' ','#',' ','#','#','#','#',' ','#',' ','#'], ['#',' ','#',' ',' ',' ',' ',' ',' ','#',' ','#'], ['#','#','#','#','#','#','#','#','#','#','$','#']] # 미로의 x, y 위치에 있는 값 읽기 def get_mazexy(x, y): if (ms[0] < 0 or ms[0] > MAZE_SIZE-1 or ms[1] < 0 or ms[1] > MAZE_SIZE-1): print("[get_mazexy()] Mouse-position error!!!") return None else: return maze[y][x] # 미로의 x, y 위치에 값 저장하기 def set_mazexy(x, y, c): if (ms[0] < 0 or ms[0] > MAZE_SIZE-1 or ms[1] < 0 or ms[1] > MAZE_SIZE-1): print("[set_mazexy()] Mouse-position error!!!") return None else: maze[y][x] = str(c) # 화면 갱신하기 def draw(x, y): set_mazexy(old_ms[0], old_ms[1], ' '); old_ms[0] = x old_ms[1] = y set_mazexy(x, y, MOUSE); os.system("cls"); # 화면 지우기 for i in range(MAZE_SIZE): print("".join(maze[i])) # 오른쪽으로 돌기 def turn_right(): ms[2]= (ms[2]+1) % 4 # 왼쪽으로 돌기 def turn_left(): ms[2] = 3 if ms[2] == 0 else ms[2]-1 # 현재 방향으로 마우스 좌표 이동하기 def go(): if ms[2] == UP: ms[1] += 1 elif ms[2] == DOWN: ms[1] -= 1 elif ms[2] == RIGHT: ms[0] += 1 elif ms[2] == LEFT: ms[0] -= 1 if ms[0] < 0 or ms[0] > MAZE_SIZE or ms[1] < 0 or ms[1] > MAZE_SIZE: print("[ERROR] Mouse-position error!!!"); return False if get_mazexy(ms[0], ms[1]) == END: return True else: return False # 이동 방향 쪽에 벽이 있는지 검사 def wall_ahead(): if ms[2] == UP: if get_mazexy(ms[0], ms[1]+1) == WALL: return True elif ms[2] == DOWN: if get_mazexy(ms[0], ms[1]-1) == WALL: return True elif ms[2] == RIGHT: if get_mazexy(ms[0]+1, ms[1]) == WALL: return True elif ms[2] == LEFT: if get_mazexy(ms[0]-1, ms[1]) == WALL: return True return False; #-------------------------------------------------------------------- # 메인 처리 old_ms[0] = ms[0] = 1 # x old_ms[1] = ms[1] = 10; # y ms[2] = UP # 방향 while True: # 탈출하기 전까지 반복 # 화면 갱신 draw(ms[0], ms[1]) if Exit == True: break turn_right() # 오른쪽으로 돌기 while wall_ahead() == True: # 앞에 벽이 없을 때까지 왼쪽으로 돌기 turn_left() print("\nMouse: %d, %d" %(ms[0], ms[1])) Exit = go() # 벽이 없는 방향으로 이동 print("\n 성공!!") # 성공 메시지를 출력하고 키 입력 대기
10553ddf1d1978e4fa74a3cd1317703014e7efd7
tahmid-tanzim/problem-solving
/flipping-an-image.py
452
3.890625
4
#!/usr/bin/python3 # https://leetcode.com/problems/flipping-an-image/ def flip_and_invert_image(A): output = [] for a in A: i, x = len(a) - 1, [] while i >= 0: x.append(1 - a[i]) i -= 1 output.append(x) return output if __name__ == '__main__': print(flip_and_invert_image([[1, 1, 0], [1, 0, 1], [0, 0, 0]])) print(flip_and_invert_image([[1,1,0,0],[1,0,0,1],[0,1,1,1],[1,0,1,0]]))
b502e0556519fbf3855399bd4b75a1dedfc4a585
Allen-Wu-Jialin/FinanceGame
/miscutils.py
277
3.59375
4
class MiscUtils: @staticmethod def Loop(num, min, max): difference = max - min num -= min num %= difference num += min return num if __name__ == "__main__": for x in range(1000): print(MiscUtils.Loop(x, -100, 400))
14924fe19fec667c5bdad85bd86001d1c67b0f7d
yang-yangfeng/board2FEN
/tests/Boardtest.py
2,459
3.9375
4
from Board import Board from random import randint #class to keep track of squares w pieces on them class randsquares: def __init__(self, board): self.board = board def randfreesq(self): row = randint(1,8) col = randint(1,8) #will be infinite loop if every square has a piece on it. should not happen #but maybe should fix while (self.board.getPiece(row,col) is not None): row = randint(1,8) col = randint(1,8) return row, col def addpce(board, piece, color, row, col): board.addPiece(piece, color, row, col) if color.upper() == 'W': str1 = 'White' else: str1 = 'Black' if piece.upper() == 'P': str2 = 'Pawn' elif piece.upper() == 'N': str2 = 'Knight' elif piece.upper() == 'B': str2 = 'Bishop' elif piece.upper() == 'R': str2 = 'Rook' elif piece.upper() == 'Q': str2 = 'Queen' else: str2 = 'King' cols = [None,'A','B','C','D','E','F','G','H'] print 'adding ' + str1 + ' ' + str2 + ' at ' + cols[col] + str(row) def printfen(board): print 'FEN: ---' print board.fen() print '------' def test1(board): rs = randsquares(board) #place 2 kings and 1 ranodmly colored pawn at random spot print '---- Test 1 ----' print '\n' board.clearPieces() row, col = rs.randfreesq() addpce(board,'K', 'W', row, col) row, col = rs.randfreesq() addpce(board,'K', 'B', row, col) if randint(0,1) == 0: c = 'W' else: c = 'B' row, col = rs.randfreesq() addpce(board,'P', c, row, col) printfen(board) print '\n' print '------' #place 2 kings and up to 8 white and up to 8 black pawns at random spots print '---- Test 2 ----' print '\n' board.clearPieces() row, col = rs.randfreesq() addpce(board,'K', 'W', row, col) row, col = rs.randfreesq() addpce(board,'K', 'B', row, col) w = randint(1,8) b = randint(1,8) for _ in range(0,w): row, col = rs.randfreesq() addpce(board,'P', 'W', row, col) for _ in range(0,b): row, col = rs.randfreesq() addpce(board,'P', 'B', row, col) printfen(board) print '\n' print '------' #place 2 kings and random subset of starting pieces at random places def test2(board): print 'asdf' if __name__ == '__main__': board = Board() test1(board)
de6e27be05d0c4088fa27c8ac9117822a07450c5
macbeth93/lesson6
/hw6.4.py
2,418
4.03125
4
# Реализуйте базовый класс Car. У данного класса должны быть следующие атрибуты: speed, color, # name, is_police (булево). # А также методы: go, stop, turn(direction), которые должны сообщать, что машина поехала, остановилась, # повернула (куда). # Опишите несколько дочерних классов: TownCar, SportCar, WorkCar, PoliceCar. # Добавьте в базовый класс метод show_speed, который должен показывать текущую скорость автомобиля. # Для классов TownCar и WorkCar переопределите метод show_speed. При значении скорости свыше 60 (TownCar) и # 40 (WorkCar) должно выводиться сообщение о превышении скорости. class Car: def __init__(self, speed, color, name, is_police=False): self.speed = speed self.color = color self.name = name self.is_police = is_police def go(self): print(self.name + "Начала движение") def stop(self): print(self.name + "Остановилась") def turn(self, direction): print("Машина повернула на " + direction) def show_speed(self): print("Скорость:", self.speed) class TownCar(Car): def __init__(self, speed, color, name, is_police=False): super().__init__(speed, color, name, is_police) self.is_police = False if self.speed > 60: print("Виу-Виу! Вы превысили скорость!") class SportCar(Car): def __init__(self, speed, color, name, is_police=False): super().__init__(speed, color, name, is_police) self.is_police = False class WorkCar(Car): def __init__(self, speed, color, name, is_police=False): super().__init__(speed, color, name, is_police) self.is_police = False if self.speed > 40: print("Виу-Виу! Вы превысили скорость!") class PoliceCar(Car): def __init__(self, speed, color, name, is_police=False): super().__init__(speed, color, name, is_police) self.is_police = True car_1 = TownCar(75, "red", "Bombeeta!", False)
f9b4e45a7fb78326361ac29a0740a50a02039df7
critoma/armasmiot
/labs/workspacepy/tutorial-python/p005_tuples.py
623
4.375
4
tuple = ( 'abcd', 786 , 2.23, 'john', 70.2 ) tinytuple = (123, 'john') print (tuple) # Prints complete tuple print (tuple[0]) # Prints first element of the tuple print (tuple[1:3]) # Prints elements starting from 2nd till 3rd print (tuple[2:]) # Prints elements starting from 3rd element print (tinytuple * 2) # Prints tuple two times print (tuple + tinytuple) # Prints concatenated tuple tuplex = ( 'abcd', 786 , 2.23, 'john', 70.2 ) listx = [ 'abcd', 786 , 2.23, 'john', 70.2 ] # tuplex[2] = 1000 # Invalid syntax with tuple listx[2] = 1000 # Valid syntax with list
071d17d0dba17670cf704dfd7fd88c8fbb869e26
Romits/BigDataScience
/anagrams/Anagram.py
761
3.59375
4
#!/usr/bin/python -tt import sys input = ['cat','dog','rats','moon','god','star','tsar'] def main(): outputDict ={} outputDict = findAnagrams(input) printResult(outputDict) def findAnagrams(inputList): resultDict = {} for i in range(len(inputList)): key = str(sorted(inputList[i])) if key in resultDict: value = resultDict.get(key) value.append(inputList[i]) resultDict[key] = value else: myList = list() myList.append(inputList[i]) resultDict[key] = myList return resultDict def printResult(outputDict): for key in outputDict.keys(): currValueList = outputDict.get(key) if len(currValueList) > 1: print currValueList[:] if __name__=='__main__': main()
c4d38bcade4328d70a5b07884393c3478ec79277
fanyan1120/Python_ex
/ex_06_07_08.py
810
3.8125
4
#coding=utf-8 x = "%d green bottles hanging on the wall." %10 apple = "apples" orange = "oranges" y = "there are 5 %s and 10 %s on the table." %(apple, orange) print x print y print "I sang the sang: %r " % x print "I said: '%s' " % y ff = False tt = True joke = "Isn't that joke funny? %r" print joke % ff print joke % tt print joke % x a = "aaaa" b = "bbbb" print a+" join "+b print "111 222 three four" print "print %s" % 'string' print "bala"*5 formatter = "%r - %r - %s - %r" print formatter % (1,2,3,4) print formatter % ("one", "two", "three", "four") print formatter % (True, False, True, False) print formatter % (formatter,formatter,formatter,formatter) print formatter % ( "today isn't Sunday, today is Monday.", "tomorrow is Tuesday", "the day after tomorrow is Wednesday 周三", x )
531bfff20920a5a619d57a43757af18777dca9d6
Basilisvirus/Band-gap-energy-of-photocatalyst
/col_per.py
1,376
3.625
4
''' input: txt file with two columns, first col: wavelength. second col:light intensity, seperated with tab. output: % of each measured intensity (2nd col), based on the maximum value of intensity of the 2nd col ''' '''Calculate the maximum value of the column 2 (light intensity) in a file, return column and maximim value''' def seperate_col2_and_max(): #open the file with the two columns data = open("data", "r") #initializing the arrays x,y y=[] max_found = 0#initial max is zero for line in data: #each time, var line represents each whole line of the file a,b= line.split(" ") #split the line, where the ' ' gap is. (the gap is a tab, not a space.) bi=float(b) y.append(bi) #append the var b to y list #for every line, if its larger than the previous, use it as the new max if (bi >max_found): max_found = bi return y , max_found #y is column 2 (intensity) '''Calculate the percentage''' def calc_per(maxim,lista): per_list=[] for block in lista: per = (block/maxim) #returns the percentage between 0 and 1, if you dont multiply *100.(if values from 0 to 100 are needed, multiply the block*100) per_list.append(per) return per_list '''==============================================MAIN========================================''' #array, maxim_found = seperate_col2_and_max() #percentage_array= calc_per(maxim_found, array)
82bc78d9eee316c32b2ea75eda4db02ee7c88bbc
twf2360/Phys281-SolarSystem
/V2/CalculatorV2.py
8,039
3.578125
4
#Class that works out the acceleration of all of the bodies import math import numpy as np from ParticleV2 import ParticleV2 import copy import matplotlib.pyplot as plt import matplotlib.axes as axs import dataclassV2 from mpl_toolkits import mplot3d import sympy #Defining the current 'state of the solar system' sos = [dataclassV2.Sol,dataclassV2.Earth, dataclassV2.Jupiter, dataclassV2.Ganymede, dataclassV2.Pluto, dataclassV2.Venus, dataclassV2.Io, dataclassV2.Mercury, dataclassV2.Saturn] totalsystemkeE = [] totalsystemkeC = [] dataE = [] #data for Euler Method dataC =[] #data for Cromer Mehod totalpotentialE = [] totalpotentialC =[] ax = plt.axes(projection = '3d') #this is how to make 3d graphs ax.view_init(60, 35) #changes the view of the graph by theta, phi class CalculatorV2: ''' This class is used to model the system defined by the sos list above, using either the Euler or the Euler-Cromer approximations. It will then also calculate the values for the Virial theorem for each approximation. ''' def __init__(self, iterations=200, timestep=6): #when calling the acceleration class, the number of iterations and the timestep must be defined self.iterations = iterations self.timestep = timestep def EulerMethodKECalc(self): ''' uses the Euler approximation to model the solar system. This then saves a file called EulerMethodKE.npy, which is the values for all of the data points for the time, all of the data defined in the particle class, and the total system kinetic energy ''' for x in range(self.iterations): # so the process is repeated through as many iterations as is defined when the class is called ke = 0 U = 0 for body in sos: #iterates through the list for every body body.acceleration = np.array([0,0,0], dtype=float) for coa in sos: # coa = cause of acceleration - iterates through the list again, as every body is a cause of acceleration. r = np.linalg.norm(body.position - coa.position) if body != coa: #the body itself does not cause any acceleration on itself body.acceleration += -(((dataclassV2.G*coa.mass)/(r**2)) * ((body.position - coa.position)/r)) U += -((dataclassV2.G*coa.mass*body.mass)/(r**2)) #body doesn't cause any potential on itself body.EulerUpdate(self.timestep) ke += ParticleV2.KineticEnergy(body) totalpotentialE.append(U) totalsystemkeE.append(ke) dataclassV2.time += self.timestep if x % 100 == 0 : #currently an arbitrary number. MAY NEED TO BE CHANGED item = [dataclassV2.time, copy.deepcopy(sos), copy.deepcopy(totalsystemkeE[x])] #this is a list of the current time, the current state of the planets, and the total ke of the system at that point in time (x times timestep) dataE.append(item) np.save("EulerMethodKE", dataE, allow_pickle= True) print('lÖÖps are done') return totalsystemkeE #this is so it can be used in my Virial Thereom check - not sure if necessary def CromerMethodKECalc(self): ''' uses the Euler-Cromer approximation to model the solar system. This then saves a file called CromerMethodKE.npy, which is the values for all of the data points for the time, all of the data defined in the particle class, and the total system kinetic energy ''' for y in range(self.iterations): # so the process is repeated through as many iterations as is defined when the class is called ke = 0 U = 0 for body in sos: #iterates through the list for every body body.acceleration = np.array([0,0,0], dtype=float) for coa in sos: # coa = cause of acceleration - iterates through the list again, as every body is a cause of acceleration. r = np.linalg.norm(body.position - coa.position) if body != coa: #the body itself does not cause any acceleration on itself body.acceleration += -(((dataclassV2.G*coa.mass)/(r**2)) * ((body.position - coa.position)/r)) U += -((dataclassV2.G*coa.mass*body.mass)/(r**2)) body.CromerUpdate(self.timestep) ke += ParticleV2.KineticEnergy(body) totalsystemkeC.append(ke) totalpotentialC.append(U) dataclassV2.time += self.timestep if y % 100 == 0: # currently an arbitrary number. MAY NEED TO BE CHANGED item = [dataclassV2.time, copy.deepcopy(sos), copy.deepcopy(totalsystemkeC[y])] #this is a list of the current time, the current state of the planets, and the total ke of the system at that point in time (x times timestep) dataC.append(item) np.save("CromerMethodKE", dataC, allow_pickle=True) print('more loops have been done') # calculation completed? return totalsystemkeC #again, so it can be used in Virial Theorem Checker - not sure if necessary def VirialTheoremCheck(self): ''' Checks either of the approximations models against the virial thereom (that 2T-U should remain constant). The values for each approximation are saved in files called 'EulerVirial.npy' and 'CromerVirial.npy' respectively ''' if self.EulerMethodKECalc() != 0: keTotal = self.EulerMethodKECalc() print("Euler Method was used to model the movements of Bodies. Checking this against the Virial Theorem")# virialtestE = 2*totalsystemkeE - totalpotentialE diff = abs(virialtestE[0] - virialtestE[-1]) np.save('EulerVirial.npy', virialtestE, allow_pickle= True) print('This test used the Euler method to model the movement of bodies. The virial test should give a constant value for all times. The difference in the value of the virial test for the first and last entry is {}'.format(diff)) if self.CromerMethodKECalc() !=0: keTotal = self.CromerMethodKECalc() print("Euler-Cromer Method was used to model the movements of Bodies. Checking this against the Virial Theorem") virialtestC = 2*totalsystemkeC - totalpotentialC diff = abs(virialtestC[0] - virialtestC[-1]) np.save('CromerVirial.npy', virialtestC, allow_pickle= True) print('This test used the Euler-Cromer method to model the movement of bodies. The virial test should give a constant value for all times. The difference in the value of the virial test for the first and last entry is {}'.format(diff)) if self.CromerMethodKECalc() and self.EulerMethodKECalc() == 0: print("Please run a Kinetic energy calculator, either Euler or Euler-Cromer method, in order to test these against the Virial Theorem") raise ValueError('No data to test against Virial Theorem') def __repr__(self): return 'Final positions of {0},{1},{2} are {3},{4},{5}'.format(dataclassV2.Sol.Name, dataclassV2.Jupiter.Name, dataclassV2.Earth.Name, dataclassV2.Sol.position, dataclassV2.Jupiter.position, dataclassV2.Earth.position) # ideas - add axis labels in au, add labels for each of the lines, etc 26-11-19 work! # ADD AN ERROR CHECKER - TOTAL KE CHECKER?? # once e-mag is done, lets just fucking grind this boi. # try and make this more general, but this is a good starting point. # euler vs euler cromer # momentum # percentage or fractional change is often better # just read the lectures you plebian test = CalculatorV2(50000, 2000) CalculatorV2.EulerMethodKECalc(test) CalculatorV2.CromerMethodKECalc(test)
917cc156aedbbfc90fb25425ad726c76fd864261
ashwiniingole/python.first
/welcome.py
246
3.921875
4
name = input("ENTER YOUR NAME: ") print("WELCOME TO THE WORLD OF PYTHON ", name) condition = input("How are you today? ") if condition == "GOOD": print("Great I am GOOD too") elif condition == "BAD": print("Sorry to hear about that :(")
996587e967cb1247bb3f5ca84339c43de8872656
ojenksdev/python_crash_course
/chapt_10/read_a_file.py
441
4.15625
4
def read_contents(filename): """Read the contents of a file""" try: with open(filename, 'r') as f_obj: content = f_obj.read() except FileNotFoundError: print("Sorry, but the file " + filename + " appears to be missing.") else: print(content) filenames = ['cats.txt', 'dogs.txt'] for filename in filenames: read_contents(filename)
e6272e2c3636327943a976e185c5b6511c2a6ca1
tmescic/python-test
/task3.py
1,848
3.796875
4
#!/usr/bin/python2.7 # encoding: utf-8 ''' Created on Dec 17, 2014 Write a decorator that stores the result of a function call and returns the cached version in subsequent calls (with the same parameters) for 5 minutes, or ten times ­­ whichever comes first. @author: tmescic ''' import datetime def cache_func(func): """ Decorator that caches result of function calls""" g = func.func_globals def func_wrapper(*v, **k): # we will use input arguments (v) as a dictionary key for storing our counter and time if not g.has_key(v): g[v] = {} gv = g[v] # increase counter (or initialize for first call) gv['counter'] = (gv['counter'] + 1) % 11 if gv.has_key('counter') else 0 if (gv['counter'] == 0 or (datetime.datetime.now() - gv['last_update_time']).total_seconds() > 300): # we need to update cache (and reset timer and update time) gv['cached_value'] = func(*v, **k) # call fn and update cached value gv['counter'] = 0 # reset counter gv['last_update_time'] = datetime.datetime.now() print "Cache updated : ", gv['cached_value'] else: print "From cache : ", gv['cached_value'] return gv['cached_value'] return func_wrapper @cache_func def fibb(n): """ Calculates the nth fibonacci number.""" prev = 1 curr = 1 for i in range(1, n-1): tmp = curr curr += prev prev = tmp return curr @cache_func def take_two(a, b): return a + b if __name__ == '__main__': for i in range (13): fibb(8) fibb(9) fibb(10) fibb(17) fibb(18) for i in range (11): take_two(12, 34) take_two(34, 12)
879abeb19e535c7b0c9e76dcd6bb897538057049
ecurtin2/Project-Euler
/src/003.py
975
3.890625
4
""" The prime factors of 13195 are 5, 7, 13 and 29. What is the largest prime factor of the number 600851475143 ? """ import argparse import itertools def factorize(n): if n < 0: yield -1 n *= -1 elif n > 2: i = 2 while n % i != 0 and i <= n: i += 1 yield i yield from factorize(n // i) else: yield n def main(): p = argparse.ArgumentParser( description="Solve Project Euler Problem 2 for input N.") p.add_argument('--N', type=int, default=600851475143, help='The upper bound (inclusive) of the fibonacci sequence considered.') variables = vars(p.parse_args()) N = variables['N'] factors = list(factorize(N)) max_factor = max(factors) print("The highest prime factor of {N} is {val}".format(N=N, val=max_factor)) print("All prime factors are {}.".format(factors)) if __name__ == "__main__": main()
7f583704f189af2e46a6efcbb3435bc098eb938f
Risvy/30DaysOfLeetCode
/Day_19/19.py
334
3.75
4
/* https://leetcode.com/problems/climbing-stairs/ Tags: Dynamic Programming, Easy */ class Solution: def climbStairs(self, n: int) -> int: if n<=2: return n else: a,b=1,1 for i in range (n): b,a=a+b, b return a return 0
eb27f96dd5484cf9d17121424940944885533dfe
mpfilbin/Softener
/shell/commands/factory/__init__.py
1,114
3.53125
4
from shell.commands import posix, cygwin import re as regex from shell.exceptions import UnSupportedShellException shells = {"Linux": posix, "CYGWIN_NT-6.1": cygwin, "CYGWIN_NT": cygwin} def from_unix_name(uname): """ Attempt to determine the appropriate shell from the unix name provided :param uname: :return: """ system_name = __parse_uname(uname) return for_system(system_name) def for_system(system_name): """ Attemps to determine the appropriate shell from the system name provided :param system_name: :return: :raise UnSupportedProviderException: """ if not system_name in shells: raise UnSupportedShellException("There are no providers available for environment: {0}".format(system_name)) else: return shells[system_name] def __parse_uname(uname): """ Takes in a uname output and returns the environment :param uname: uname output :type uname: str :return: """ matches = regex.match('^\w+', uname) if matches is None: return matches else: return matches.group(0).rstrip()
6867766d6fe4ee81b44346d5468b4a448fed3ffe
srikanthpragada/demo_27_sep_2019
/ex/unique_chars.py
169
4.1875
4
# Unique chars of a given string st = input("Enter a string : ") chars = [] for c in st: if c not in chars: chars.append(c) for c in chars: print(c)
b766acfa47f743cb6268deab3183c2d4a1f1de07
sarthakjain07/TIC_TAC_TOE
/project.py
4,375
4.28125
4
# Global variables # this is a platform where the game will be played platform=["-", "-", "-", "-", "-", "-", "-", "-", "-"] # If game is still going on goingOn=True # winner or tied or loser winner=None loser=None # who's turn is it? currentPlayer="X" # This function displays the platform of Game def displayplatform(): print(" | "+platform[0]+" | "+platform[1]+" | "+platform[2]+" | ") print(" | "+platform[3]+" | "+platform[4]+" | "+platform[5]+" | ") print(" | "+platform[6]+" | "+platform[7]+" | "+platform[8]+" | ") # This function checks the rows of platform def checkRows(): # Using global variable in this function global goingOn # Checking if rows have common value and is not empty row_1=platform[0]==platform[1]==platform[2]!="-" row_2=platform[3]==platform[5]==platform[6]!="-" row_3=platform[6]==platform[7]==platform[8]!="-" # Stopping the game when one has won if row_1 or row_2 or row_3: goingOn=False # Returning the winner if row_1: return platform[0] elif row_2: return platform[3] elif row_3: return platform[6] else: return # This function checks the columns of platform def checkColumns(): # Using global variable in this function global goingOn # Checking if columns have common value and is not empty column_1=platform[0]==platform[3]==platform[6]!="-" column_2=platform[1]==platform[4]==platform[7]!="-" column_3=platform[2]==platform[5]==platform[8]!="-" # Stopping the game when one has won if column_1 or column_2 or column_3: goingOn=False # Returning the winner if column_1: return platform[0] elif column_2: return platform[1] elif column_3: return platform[2] else: return # This function checks the diagonals of platform def checkDiagonals(): # Using global variable in this function global goingOn # Checking if diagonals have common value and is not empty diagonal_1=platform[0]==platform[4]==platform[8]!="-" diagonal_2=platform[6]==platform[4]==platform[2]!="-" # Stopping the game when one has won if diagonal_1 or diagonal_2: goingOn=False # Returning the winner if diagonal_1: return platform[0] elif diagonal_2: return platform[6] else: return # This function checks if the player wins def ifWin(): # Setting global variable in function global winner # checking rows rowWinner=checkRows() # checking columns columnWinner=checkColumns() # checking diagonals diagonalWinner=checkDiagonals() if rowWinner: winner=rowWinner elif columnWinner: winner=columnWinner elif diagonalWinner: winner=diagonalWinner else: winner=None # This function tells whether the game is over def gameOver(): ifWin() ifTie() # This function checks whether the game is tied def ifTie(): # Using global variable in this function global goingOn # Condition of match in case Tie if "-" not in platform: goingOn=False # This function changes the player def changePlayer(): # Using global variable in function global currentPlayer # Flipping the players from X to O & vice versa if currentPlayer=="X": currentPlayer="O" elif currentPlayer=="O": currentPlayer="X" # This function handles the turns of players one by one def handleTurns(player): print(player + "'s turn'") # taking the input of position position=int(input("Choose a position from 1-9: "))-1 while position not in [0,1,2,3,4,5,6,7,8]: position=int(input("Invalid choice! Choose a position again from 1-9: "))-1 # position=position-1 while platform[position]!="-": print("Already filled. Try another place") position=int(input("Choose a position again from 1-9: "))-1 platform[position]=player displayplatform() # This function operates the game def playGame(): # Displaying the platform initially displayplatform() # The game is still going on with the loop while goingOn: # handling turns of players one by one handleTurns(currentPlayer) # checking if the game is over gameOver() # changing the player according to their chance changePlayer() # When the game is ended if winner == "X" or winner=="O": print("Winner is " + winner) elif winner == None: print("Match Tied.") if __name__=="__main__": playGame()
cbdc16a8fbef5659ad2da4524a528244d164858f
memoia/sparkcalc
/infix.py
6,313
3.546875
4
import unittest import operator from collections import deque, namedtuple from types import IntType OperatorProperty = namedtuple('OperatorProperty', ('weight', 'method')) class BaseOperators(object): """Subclass this to add new operators""" operators = { # symbol to precendence (higher value is higher precedence) '*': OperatorProperty(10, operator.mul), '/': OperatorProperty(10, operator.div), '+': OperatorProperty(5, operator.add), '-': OperatorProperty(5, operator.sub), } def is_operator(self, symbol): return symbol in self.operators def weight(self, operator): if not self.is_operator(operator): raise ValueError('{} is not an operator'.format(operator)) return self.operators[operator].weight def method(self, operator): if not self.is_operator(operator): raise ValueError('{} is not an operator'.format(operator)) return self.operators[operator].method class TestBaseOperators(unittest.TestCase): def setUp(self): self.instance = BaseOperators() def test_weight_for_valid_operator(self): """Does getting the weight of '*' return a value?""" self.assertTrue(type(self.instance.weight('*')) is IntType) def test_weight_for_invalid_operator(self): """Does getting the weight of '^' raise an exception?""" with self.assertRaises(ValueError): self.instance.weight('^') class BaseTokenizer(object): def __init__(self, operator_instance=None): self.operators = BaseOperators() if operator_instance is None else operator_instance def is_operator(self, symbol): return self.operators.is_operator(symbol) def is_valid_symbol(self, symbol): return symbol.isdigit() or self.is_operator(symbol) def tokens(self, infix_string): items = infix_string.split() if not all(map(self.is_valid_symbol, items)): raise ValueError('Invalid character in {}'.format(items)) return items class TestBaseTokenizer(unittest.TestCase): def setUp(self): self.instance = BaseTokenizer() def test_is_operator_when_operator_supplied(self): self.assertTrue(self.instance.is_operator('+')) def test_is_operator_when_not_operator(self): self.assertFalse(self.instance.is_operator('qqq')) def test_is_valid_symbol_when_number(self): self.assertTrue(self.instance.is_valid_symbol('123')) def test_is_valid_symbol_when_operator(self): self.assertTrue(self.instance.is_valid_symbol('*')) def test_is_valid_symbol_when_invalid(self): self.assertFalse(self.instance.is_valid_symbol('^')) def test_tokens_when_valid_string_provided(self): """Does '1 + 2 - 3' return ['1', '+', '2', '-', '3'] ?""" self.assertEqual(self.instance.tokens('1 + 2 - 3'), ['1', '+', '2', '-', '3']) def test_tokens_raises_exception_when_invalid_symbol(self): """Is '1 -3' considered an invalid expression ?""" with self.assertRaises(ValueError): self.instance.tokens('1 -3') class RPNBuilder(object): """Convert an infix string to reverse polish notation using shunting yard""" def __init__(self, infix_string, token_cls=BaseTokenizer, operator_cls=BaseOperators): self.in_str = infix_string self.operators = operator_cls() self.tokenizer = token_cls(self.operators) self.opqueue = deque() self.symbols = [] def _next_op_has_precedence(self, symbol): if not len(self.opqueue) > 0: return False next_op = self.opqueue[0] return self.operators.weight(next_op) >= self.operators.weight(symbol) def _handle_operator(self, symbol): while self._next_op_has_precedence(symbol): self.symbols.append(self.opqueue.popleft()) def build(self): for symbol in self.tokenizer.tokens(self.in_str): if self.operators.is_operator(symbol): self._handle_operator(symbol) self.opqueue.appendleft(symbol) else: self.symbols.append(symbol) while len(self.opqueue) > 0: self.symbols.append(self.opqueue.popleft()) return self.symbols class TestRPNBuilder(unittest.TestCase): def test_simple_addition(self): """Does '1 + 2' result with 1 2 + ?'""" result = RPNBuilder('1 + 2').build() self.assertEqual(result, ['1', '2', '+']) def test_precedence(self): """Does '1 + 2 * 3' result with 1 2 3 * + ?""" result = RPNBuilder('1 + 2 * 3').build() self.assertEqual(result, ['1', '2', '3', '*', '+']) class RPNEvaluator(object): """Evaluate a character list of integers and operators in RP-notation""" def __init__(self, rpn_list, operator_cls=BaseOperators): self.in_lst = rpn_list self.operators = operator_cls() self.queue = deque() def _next_values(self): second_value = self.queue.popleft() first_value = self.queue.popleft() return (first_value, second_value) def evaluate(self): for symbol in self.in_lst: if self.operators.is_operator(symbol): method = self.operators.method(symbol) self.queue.appendleft(method(*self._next_values())) else: self.queue.appendleft(int(symbol)) return self.queue.pop() class TestRPNEvaluator(unittest.TestCase): def test_simple_addition(self): """Does '1 + 2' evaluate to 3 ?""" rpn_ops = RPNBuilder('1 + 2').build() self.assertEqual(3, RPNEvaluator(rpn_ops).evaluate()) def test_precedence(self): """Does '1 + 2 * 3' evaluate to 7 ?""" rpn_ops = RPNBuilder('1 + 2 * 3').build() self.assertEqual(7, RPNEvaluator(rpn_ops).evaluate()) def test_example_provided_in_readme(self): instr = '4 + 4 * 8 / 2 + 10' rpn_ops = RPNBuilder(instr).build() self.assertEqual(30, RPNEvaluator(rpn_ops).evaluate()) def eval_expr(in_str): """Main entry point for module use.""" return RPNEvaluator(RPNBuilder(in_str).build()).evaluate() if __name__ == '__main__': unittest.main(verbosity=2)
eed6b64947e109d551af6bf9fc8697bfac941ec3
hardenmvp13/Python_code
/python知识体系/8,错误与异常/调试.py
1,089
4.03125
4
''' debug相关功能 F8:step over 单步(第一个按钮) 遇到断点后,程序停止运行,按F8单步运行。 F7:step into 进入(第二个按钮) 配合F8使用。单步调试F8时,如果某行调用其他模块的函数,在此行F7,可以进入函数内部,如果是F8则不会进入函数内容,直接单步到下一行。 Alt+shift+F7:step into mycode(第三个按钮) 个人理解F8和F7的综合。1、没遇到函数,和F8一样;2、遇到函数会自动进入函数内部,和F8时按F7类似的 shift+F8:step out 跳出(第五个按钮) 调试过程中,F7进入函数内后,shift+F8跳出函数,会回到进入前调用函数的代码。不是函数地方shift+F8跳出,怎么用没太明白,但最终会执行到结束。 F9:resume program 按翻译是重启程序 ,实际是 下个断点,当打多个断点是,F9会到下一个断点 常用: F8,F9,其次Alt+shift+F7,或 F7,shift+F8 ''' def sum(x): x += 1 return x for i in range(10): print(i) print(sum(i)) print(sum(i)*10)
fc13a1bfd84191494352fc88a63ec37a338d5b89
lemaoliu/LeetCode_Python_Accepted
/142_Linked_List_Cycle_II.py
680
3.703125
4
# 2015-02-02 Runtime: 177 ms # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param head, a ListNode # @return a list node def detectCycle(self, head): if not head: return None fast, slow = head, head while True: fast = fast.next if not fast: return None fast = fast.next if not fast: return None slow = slow.next if fast is slow: p = head while slow is not p: p, slow = p.next, slow.next return p
30391f82dfd5e9259f1d866f5efe9226664df10d
vampy/university
/fundamentals-of-programming/labs/proposed_1.py
218
3.828125
4
# http://python-future.org/compatible_idioms.html from __future__ import print_function from builtins import input s = 0 for i in range(1, int(input("Give a number: ")) + 1): s += i print("The sum is " + str(s))
03a10156148da3e2136a35f185b46a711065ee91
mikey084/Algorithms_Practice
/practice1.py
1,591
4.15625
4
''' https://www.interviewcake.com/question/python/reverse-linked-list Write a function that can reverse a linked list and does it in-place. Strategy: ''' class LinkedListNode: def __init__(self, value): self.value = value self.next = None def __str__(self): return "value:{}".format(self.value) # reverses it, and returns new head def reverse_linked_list(head): current = head prev = None old_next = None while current: # node we will visit next old_next = current.next # point the current node to previous current.next = prev # shuffle the prev to the current node as we move along the list prev = current # shuffle current to the next node in the list current = old_next # new head since current is None and we reached end of original list return prev def print_linked_list(head): node = head output = [] while node: output.append(node.value) node = node.next print(output) a = LinkedListNode(1) b = LinkedListNode(2) c = LinkedListNode(3) a.next = b b.next = c print_linked_list(a) print(print_linked_list(reverse_linked_list(a))) for x in range(10): print(str(x) + '\n') def put(self, key, data): index = self.hashedFunction(key) #not None it is a collision while self.keys[index] is not None: if self.keys[index] == key: self.values[index] = data #update return index = (index+1) % self.size #insert self.keys[index] = key self.values[index] = data