blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
e9f780995200a10c7fe117f01a283f5f95325f73
wmackowiak/Zadania
/Zajecia04/dom2.py
387
3.8125
4
# Utwórz dowolną tablicę n x n zawierającą dowolny znak, a następnie wyświetl jej elementy w formie tabeli n x n. # Elementy powinny być oddzielone spacją # wejście: # n = 3 # # tab = [['-', '-', '-'] # ['-', '-', '-'], # ['-', '-', '-']] # wyjście: # - - - # - - - # - - - # tablica = [[0] * cols] * rows tablica = [['-'] * 3] * 3 for x in tablica: print(x)
7d3d64976ba2bc6670ccbc2bb65dbecf20513e40
wmackowiak/Zadania
/Dodatkowe/zad11.py
240
3.71875
4
# Zwykle odliczanie wsteczne kojarzy nam się ze startem rakiety. Proszę o wygenerowanie liczb od 10 do zera i na końcu # będzie komunikat: „ Rakieta startuje!!!”. i=10 while i>=0: print(i) i=i-1 print("Rakieta startuje!!!")
71fb6862027166ebec778612f6acc48f47d51914
MatePaulinovic/thesis
/thesis/utils/array_util.py
1,202
3.515625
4
from typing import List import numpy as np def save_np_ndarray(string_format: str, string_args: List[str], destination_dir: str, array: np.ndarray ) -> None: """Saves numpy arrays with the specified format name to the output dir. Args: string_format (str): filename format the file should have string_args (List[str]): list of parameters to be inserted to the format destination_dir (str): directory where the file should be saved array (np.ndarray): the array that should be saved """ np.save((destination_dir + string_format).format(*string_args), array) def cut_np_2D_ndarray(array: np.ndarray, start_offset: int, end_offset: int ) -> np.ndarray: #TODO: add documentation return array[:, max(0, start_offset) : min(end_offset, array.shape[1])] def cut_np_1D_ndarray(array: np.ndarray, start_offset: int, end_offset: int ) -> np.ndarray: #TODO: add documentation return array[max(0, start_offset) : min(end_offset, len(array))]
70c18e3e9d4773c08f755826779661164264932c
atulmishr/Dtypes-work
/datatypes.py
608
3.953125
4
#python strings Atul="Welcome into the world of Bollywood" print(Atul) print(Atul*2) print(Atul[1:10]) print(Atul[9:]) print(Atul + "Atul Mishra with Sanjay Kapoor") #python Lists Heros = ['Aamir','Salman','Ranveer','Shahid','Akshay'] print(Heros) print(Heros[1:2]) print(Heros[2:]) Heroiens= ['Dyna','Katreena','Karishma','kareena','kirti'] print(Heros + Heroiens) #list operations Heros.append('Rajkumar Rao') print(Heros) Heroiens.insert(3,'Aalia') print(Heroiens) Heros.extend('Sonu sood') print(Heros) #deleting players=['Ronaldo,Messi','Dhoni','jadeja','Raina'] print(players) del players([1:3]) print(players)
a72b702f794d518d17e9fb30f29425b6253ffae0
MingjunGuo/bdt_5002
/assign1/A1_mguoaf_20527755_Q2_code.py
9,220
3.625
4
# -*-coding:utf-8-*- import csv import time def loadDataDict(filename): """ load data from file :param filename: filename :return: Dataset is a dict{(transcation):count,...} """ filename = filename # load data from given file,type is list with open(filename) as f: DataSet = csv.reader(f) # transform the datatype to dict DataDict = {} for transaction in DataSet: if frozenset(transaction) in DataDict.keys(): DataDict[frozenset(transaction)] += 1 else: DataDict[frozenset(transaction)] = 1 return DataDict # define a tree,and save every node class treeNode: """ define a class, every node will have some attributes: name:the name of node count: the number of node occurance ParentNode : the ParentNode ChildrenNode: the ChildrenNode, the type is dict NodeLink: the similar node in different transaction, The default is None and some function: inc: plus the numOccurance disp: print the tree """ def __init__(self, name, numOccur, ParentNode): self.name = name self.count = numOccur self.ParentNode = ParentNode self.ChildrenNode = {} self.NodeLink = None def inc(self, numOccur): self.count += numOccur def updateHeader(originalNode, targetNode): """ connecting the similar treeNode together :param originalNode: the treeNode :param targetNode: the treeNode that should be connected :return: """ while(originalNode.NodeLink != None): originalNode = originalNode.NodeLink originalNode.NodeLink = targetNode def updateTree(items, intree, headerTable, count): """ Update Tree with every transaction, updating process can be split into three steps: (1) if the items[0] has already been the childrenNode of intree, then update the numOccur of Items[0] (2) else: construct the new treeNode,and update the headerTable (3) loop step(1) and step(2) until there is no item in items :param items: one transaction after filtering by minSup :param intree: the items[0]'s parentNode :param headerTable: headerTable:{item:[count, header of NodeLink],...} :param count: the count of this transaction :return: """ # Step1: if items[0] in intree.ChildrenNode: intree.ChildrenNode[items[0]].inc(count) # Step2: else: intree.ChildrenNode[items[0]] = treeNode(items[0], count, intree) if headerTable[items[0]][1] == None: headerTable[items[0]][1] = intree.ChildrenNode[items[0]] else: updateHeader(headerTable[items[0]][1], intree.ChildrenNode[items[0]]) # Step3: if len(items) > 1: updateTree(items[1:], intree.ChildrenNode[items[0]], headerTable, count) def createTree(DataDict, minSup=300): """ creating FP-Tree can be split into three steps: (1) Traverse the DataSet, count the number of occurrences of each item, create a header-table (2) Remove items in the headerTable that do not meet the minSup (3) Traverse the DataSet again, create the FP-tree :param DataSet: dict{(transaction):count,...} :param minSup: minimum support :return:rootTree, headerTable """ # Step 1: headerTable = {} for transaction in DataDict: for item in transaction: headerTable[item] = headerTable.get(item, 0) + DataDict[transaction] # del item whose value is Nan: key_set = set(headerTable.keys()) for key in key_set: if key is '': del(headerTable[key]) # Step 2: key_set = set(headerTable.keys()) for key in key_set: if headerTable[key] < minSup: del(headerTable[key]) # if the headerTable is None, then return None, None freqItemSet = set(headerTable.keys()) if len(freqItemSet) == 0: return None, None # plus one value for the item to save the NodeLink for key in headerTable: headerTable[key] = [headerTable[key], None] # Instantiate the root node rootTree = treeNode('Null Set', 1, None) # Step 3: for transaction, count in DataDict.items(): localID = {} for item in transaction: if item in freqItemSet: localID[item] = headerTable[item][0] if len(localID) > 0: orderedItems = [v[0] for v in sorted(localID.items(), key=lambda p: p[1], reverse=True)] updateTree(orderedItems, rootTree, headerTable, count) return rootTree, headerTable def ascendTree(leafNode, prefixPath): """ Treat every transaction as a line, connecting from leafnode to rootnode :param leafNode: leafnode :param prefixPath: path ending with leafnode :return: """ if leafNode.ParentNode != None: prefixPath.append(leafNode.name) ascendTree(leafNode.ParentNode, prefixPath) def findPrefixPath(baseitem, treeNode): """ find conditional pattern base(collection of paths ending with baseitem being looked up) for every frequent item :param baseitem: frequent item :param treeNode: the header of NodeLink in headerTable :return: condPats:conditional pattern base """ condPats = {} while treeNode != None: prefixPath = [] ascendTree(treeNode, prefixPath) if len(prefixPath) > 1: condPats[frozenset(prefixPath[1:])] = treeNode.count treeNode = treeNode.NodeLink return condPats def mineTree(inTree, headerTable, minSup, prefix, freqItemList): """ after constructing the FP-Tree and conditional FP-tree, loop for look for frequent ItemSets :param inTree: the dataset created by createTree :param headerTable: the FP-Tree :param minSup: the minimum support :param prefix: used to save current prefix, should be pass set([]) at first :param freqItemList: used to save frequent itemsets, should be pass list[] at first :return: """ items = [v[0] for v in sorted(headerTable.items(), key=lambda p:p[1][0])] for baseitem in items: newFreqSet = prefix.copy() newFreqSet.append(baseitem) freqItemList.append(newFreqSet) condPats = findPrefixPath(baseitem, headerTable[baseitem][1]) myCondTree, myHeadTable = createTree(condPats, minSup) if myHeadTable != None: mineTree(myCondTree, myHeadTable, minSup, newFreqSet, freqItemList) def from_Itemset(freqItems, rootTree, headerTable, minSup): """ Based on the result of frequent Itemset, print out those FP-conditional trees whose height is larger than 1 :param freqItems: the result of finding frequent Itemset :return: the FP-conditional trees , put in one list """ # Step1: find all the items that the FP-conditional trees whose height is larger than 1 FP_items = [] for items in freqItems: if len(items) > 1: FP_items.append(items[0]) # Step2: Remove duplicates FP_items = list(set(FP_items)) # Step3: find the conditional-tree of every item lst_all = [] for baseitem in FP_items: condPats = findPrefixPath(baseitem, headerTable[baseitem][1]) myCondTree, myHeadTable = createTree(condPats, minSup) lst = from_node(myCondTree) lst_all.append(lst) return lst_all def from_node(node): """ from every node whose conditional tree is higher than 1, print the conditional tree into list :param node: :return: """ lst = [] combination = node.name + ' ' + str(node.count) lst.append(combination) if node.ChildrenNode: lst_children = [] Item_set = set(node.ChildrenNode.keys()) for Item in Item_set: node_new = node.ChildrenNode[Item] lst_new = from_node(node_new) lst_children.append(lst_new) lst.append(lst_children) if len(lst) == 1: lst = lst[0] return lst def fpTree(DataDict, minSup=300): """ package all the function into the main function :param DataDict: the input file :param minSup: the minimum support :return: freqItems\FP-conditional trees """ rootTree, headerTable = createTree(DataDict, minSup) freqItems = [] prefix = [] mineTree(rootTree, headerTable, minSup=300, prefix=prefix, freqItemList=freqItems) lst_all = from_Itemset(freqItems, rootTree, headerTable, minSup=300) # print_fp_all = print_fp(rootTree, headerTable, minSup=300) return freqItems, lst_all def data_write_csv(filename, datas): with open(filename, 'w', newline='') as f: writer = csv.writer(f) for data in datas: writer.writerow([data]) print('save file successfully') if __name__ == '__main__': start = time.clock() DataDict = loadDataDict('groceries.csv') freqItems, lst_all = fpTree(DataDict) data_write_csv('submission_2.1.csv', freqItems) data_write_csv('submission_2.2.csv', lst_all) elapsed_1 = time.clock() - start print("Running time is:", elapsed_1) print(freqItems) print(len(freqItems)) print(len(lst_all)) print(lst_all)
3bee7286fcbfd406dea12509209bb2ac292541eb
jhoneal/Python-class
/pythag.py
99
3.546875
4
from math import sqrt def calc(a,b): c = sqrt(a^2 + b^2) print('{:.3f}'.format(c)) calc(4,9)
0fd4177666e9d395da20b8dfbfae9a300e53f873
jhoneal/Python-class
/pin.py
589
4.25
4
"""Basic Loops 1. PIN Number Create an integer named [pin] and set it to a 4-digit number. Welcome the user to your application and ask them to enter their pin. If they get it wrong, print out "INCORRECT PIN. PLEASE TRY AGAIN" Keep asking them to enter their pin until they get it right. Finally, print "PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE.""" pin = 9999 num = int(input("Welcome to this application. Please enter your pin: ")) while num != pin: num = int(input("INCORRECT PIN. PLEASE TRY AGAIN: ")) print("PIN ACCEPTED. YOU HAVE $0.00 IN YOUR ACCOUNT. GOODBYE.")
d64d13bb882c7b211d77803e00f968eb8ea3f81d
jhoneal/Python-class
/add.py
187
3.71875
4
import random def a1(): a = random.randint(0,9) b = random.randint(0,9) print("What is {} + {}?".format(a,b)) answer = int(input("Enter number:")) print(answer==a+b) a1()
3bb04e461f84949712738592c61f4080abb5a733
Coopelia/LeetCode-Solution
/py/384.py
593
3.796875
4
''' 打乱数组 ''' import random from typing import List class Solution: def __init__(self, nums: List[int]): self.original = nums def reset(self) -> List[int]: """ Resets the array to its original configuration and return it. """ return self.original def shuffle(self) -> List[int]: """ Returns a random shuffling of the array. """ tmplist = self.original.copy() res = [] while tmplist: res.append(tmplist.pop(random.randint(0, len(tmplist) - 1))) return res
ad525b6f818470b79566d0cbb092e53602d03f7b
MichaelDeutschCoding/Python_Baby_Projects
/animal_classes.py
1,378
3.875
4
class Pet: def __init__(self, name, weight, species): self.name = name self.weight = weight self.species = species self.alive = True self.offspring = [] print(f'{self.name} successfully initiated.') def __repr__(self): if self.offspring: return f'Meet {self.name}. A {self.species} that weighs {self.weight} kg. {self.name} is alive: {self.alive} and has {len(self.offspring)} children, named {", ".join(self.offspring)}' else: return f'Meet {self.name}. A {self.species} that weighs {self.weight} kg. {self.name} is alive: {self.alive}' def birth(self, baby_name): self.offspring.append(baby_name) print(f'Congratulations to {self.name} on the birth of a new baby {self.species} named {baby_name}!') class Dog(Pet): def __init__(self, name, weight, howls): Pet.__init__(self, name, weight, 'dog') self.howls = howls def __repr__(self): return super().__repr__() + f". Does {self.name} howl? " + str(self.howls) billy = Pet('Billy', 22, 'goat') rover = Pet('Rover', 13, 'dog') rover.birth('Spot') rover.birth('Samantha') chewy = Dog('Chewie', 15, True) chewy.birth('Chewbacca Jr') print(billy) print(rover) print(chewy) print(chewy.offspring) billy.alive = False print(billy)
f9f29d0d9f2a06e069ee1b2972053d436d786f29
MichaelDeutschCoding/Python_Baby_Projects
/connect4.py
632
3.84375
4
ROW_COUNT = 6 COLUMN_COUNT = 7 def create_board(): board = [] for row in..... return board def drop_piece(board, row, col, piece): pass def valid_location(board, col): return board[5][col] == 0 def next_open_row(board, col): for r in range(ROW_COUNT): if board[r][col] == 0: return r def printer(board): pass #for row in board[::-1]: print(row) #print column numbers board = create_board() game_over = False turn = 0 while not game_over: if turn == 0: col = int(input("Player One, choose a column: ") if valid_location(board, col):
96cc50582d0ec13cdec24e10c67d210e828cfb9b
MichaelDeutschCoding/Python_Baby_Projects
/Battleship.py
3,607
4.1875
4
from random import randrange, choice from string import digits # TO DOs # multiple ships # various sized ships # define class (ship) # two players # merge board coordinates into a tuple instead of separate components of row/col def battleship(): print() print("\t \t Let's Play Battleship!") print("You may press 'Q' at any time to quit.") sz = 5 global again again = "" board = [] for x in range(sz): board.append(["O"] * sz) def print_board(board): num = 65 print(" " + " ".join(digits[1:sz + 1])) for row in board: print(chr(num), " ".join(row)) num +=1 print_board(board) ship_row = randrange(sz) ship_col = randrange(sz) #hide a ship of length 3 directions = [] if ship_row >= 2: directions.append("up") if ship_row <= (sz - 3): directions.append("down") if ship_col >= 2: directions.append("left") if ship_col <= (sz - 3): directions.append("right") direction = choice(directions) print(directions) #### print(direction) #### if direction == "up": ship2_row = ship_row - 1 ship3_row = ship_row - 2 ship2_col = ship_col ship3_col = ship_col if direction == "down": ship2_row = ship_row + 1 ship3_row = ship_row + 2 ship2_col = ship_col ship3_col = ship_col else: pass if direction == "left": ship2_col = ship_col -1 ship3_col = ship_col -2 ship2_row = ship_row ship3_row = ship_row else: pass if direction == "right": ship2_col = ship_col + 1 ship3_col = ship_col + 2 ship2_row = ship_row ship3_row = ship_row else: pass print("ship row:", ship_row) print("ship col:", ship_col) print("ship2:", ship2_row, ship2_col) print(ship3_row, ship3_col) t = 0 #turn counter while True: print() print("\tTurn", t+1) guess = (input("Guess a Coordinate (letter first): ")).upper() if guess == "Q": print("Sorry to see you go.") return elif not len(guess) == 2 or not guess[0].isalpha() or not guess[1].isdigit(): #should it be If not len(guess) == 2 print("Invalid Entry.") continue guess_row = ord(guess[0]) - 65 guess_col = int(guess[1]) - 1 if guess_row < 0 or guess_row > sz - 1 or guess_col < 0 or guess_col > sz -1: print("Oops, that's not even in the ocean!") continue elif board[guess_row][guess_col] == "X" or board[guess_row][guess_col] == "#": print("You've already guessed that spot.") continue if ((guess_row == ship_row and guess_col == ship_col) or (guess_row == ship2_row and guess_col == ship2_col) or (guess_row == ship3_row and guess_col == ship3_col)): board[guess_row][guess_col] = "#" print("Hit!") print_board(board) if (board[ship_row][ship_col] == "#" and board[ship2_row][ship2_col] == "#" and board[ship3_row][ship3_col] == "#"): print("You sunk my battleship!!") print("Congratulations, you won!".center(75, '*')) break else: t +=1 continue else: print("You missed my battleship.") board[guess_row][guess_col] = "X" t +=1 print_board(board) again = input("Do you want to play again? type 'Y' for yes: ").upper() def play(): battleship() while again == "Y": print() battleship() else: print("Thanks for playing. Goodbye.") play() blah = input("MD")
56562d9c21637289ec49096572dd5297f9b0261c
rgb-24bit/scripts
/py/prime.py
654
3.921875
4
# -*- coding: utf-8 -*- """ Obtaining a prime number within the numerical range is designated ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: (c) 2019 by rgb-24bit. :license: MIT, see LICENSE for more details. """ import sys def eratosthenes(n): is_prime = [True] * (n + 1) is_prime[1] = False for i in range(2, int(n ** 0.5) + 1): if is_prime[i]: for j in range(i * i, n + 1, i): is_prime[j] = False return [x for x in range(2, n + 1) if is_prime[x]] if __name__ == '__main__': prog, *args = sys.argv for arg in args: print(eratosthenes(int(arg)))
51d409c780d13e35d3a4626a10273ef0d32e03a6
Raivias/assimilation
/old/vector.py
1,173
4.25
4
class Vector: """ Class to use of pose, speed, and accelertation. Generally anything that has three directional components """ def __init__(self, a, b, c): """ The three parts of the set :param a: x, i, alpha :param b: y, j, beta :param c: z, k, gamma """ self.a = a self.b = b self.c = c def __add__(self, other): a = self.a + other.a b = self.b + other.b c = self.c + other.c return Vector(a, b, c) def __sub__(self, other): a = self.a - other.a b = self.b - other.b c = self.c - other.c return Vector(a, b, c) def __mul__(self, other): if other is Vector: return self.cross_mul(other) def cross_mul(self, other): """ Cross multiply :param other: Another Vector :return: Cross multiple of two matices """ a = (self.b * other.c) - (self.c * other.b) b = (self.c * other.a) - (self.a * other.c) c = (self.a * other.b) - (self.b * other.a) return Vector(a, b, c) def scalar_mul(self, other): pass
f3b74c75bfa4ad15798649420d2ed7aec23bd441
shangsuru/machine-learning
/sml/hw4/1a.py
9,046
3.796875
4
import numpy as np from matplotlib import pyplot as plt """ # Backpropagation dL = (-error)@np.reshape(np.insert(a[-1], 0, 1), (1, -1)) self.weights[-1] += learning_rate * dL for i in range(1, len(self.weights) - 1): prod = None for k in range(i, len(self.weights) - 1): val = ( self.weights[k+1] @ np.insert(self.activation_func_df[k](z[k]), 0, 1) ) prod = val if prod is None else prod @ val dL = - ( (np.reshape(prod, (-1, 1)) @ error) @ np.reshape(np.insert(a[i], 0, 1), (1, -1)) ) self.weights[i] += learning_rate * dL """ class NeuralNetworkold: """Represents a neural network. Args: layers: An array of numbers specifying the neurons per layer. activation_func: An array of activation functions corresponding to each layer of the neural network except the first. actionvation_func_df: An array of the derivatives of the respective activation functions. Attributes: activation_func: The activation functions for each layer of the network. weights: A numpy array of weights. """ def __init__(self, layers, activation_func, activation_func_df, penalty_func, penalty_func_df, feature_func): self.dim = layers self.activation_func = activation_func self.activation_func_df = activation_func_df self.penalty_func = penalty_func self.penalty_func_df = penalty_func_df self.feature_func = feature_func self.weights = [np.random.random((layers[i + 1], layers[i] + 1)) for i in range(len(layers) - 1)] def predict(self, x): """Predicts the value of a data point. Args: X: The input vector to predict an output value for. Returns: The predicted value(s). """ a = x z = None for i, weight in enumerate(self.weights[:-1]): z = weight@np.insert(a, 0, 1) a = self.activation_func[i](z) y = self.weights[-1]@np.insert(a, 0, 1) return np.argsort(y)[-1] def train(self, x, y, learning_rate=.1): """Trains the neural network on a single data point. Args: X: The input vector. Y: The output value corresponding to the input vectors. """ # Forwardpropagation: build up prediction matrix z = [] a = [x] for i, weight in enumerate(self.weights[:-1]): z.append(weight@self.feature_func(a[-1])) a.append(self.activation_func[i](z[-1])) pred_y = (self.weights[-1]@self.feature_func(a[-1])).reshape(-1, 1) K = len(self.weights) d = [None] * K d[-1] = (pred_y - y).reshape(-1, 1)@a[-1].reshape(1, -1) for i in range(1, K): k = K - i - 1 d[k] = d[k+1]@(self.weights[k + 1]@np.append(self.activation_func_df[k](z[k]),1)) for i in range(K): self.weights[i] -= learning_rate * (d[i]@x[i]) class NeuralNetwork: """Represents a neural network. Args: layers: An array of numbers specifying the neurons per layer. activation_func: An array of activation functions corresponding to each layer of the neural network except the first. actionvation_func_df: An array of the derivatives of the respective activation functions. Attributes: activation_func: The activation functions for each layer of the network. weights: A numpy array of weights. """ def __init__(self, layers, activation_func, activation_func_df, penalty_func, penalty_func_df, feature_func): self.dim = layers self.activation_func = activation_func self.activation_func_df = activation_func_df self.penalty_func = penalty_func self.penalty_func_df = penalty_func_df self.feature_func = feature_func self.weights = [np.random.random((layers[i + 1], layers[i])) * 1e-4 for i in range(len(layers) - 1)] self.bias = [np.random.random((layers[i + 1],)) * 1e-4 for i in range(len(layers) - 1)] def predict(self, x): """Predicts the value of a data point. Args: X: The input vector to predict an output value for. Returns: The predicted value(s). """ a = x z = None for i, weight in enumerate(self.weights): z = weight@a + self.bias[i] a = self.activation_func[i](z) y = a return np.argsort(y)[-1] def train(self, x, y, learning_rate=.01): """Trains the neural network on a single data point. Args: X: The input vector. Y: The output value corresponding to the input vectors. """ # forward propagate def fp(): h = [x] a = [] for i in range(len(self.weights)): a.append(self.bias[i] + self.weights[i]@h[i]) h.append(self.activation_func[i](a[i])) return h, a h, a = fp() pred_y = h[-1] g = self.penalty_func_df(pred_y, y).reshape(-1, 1) K = len(self.weights) delta_b = [None] * K delta_W = [None] * K for i in range(K): k = K - i - 1 g = g * self.activation_func_df[k](a[k]).reshape(-1, 1) delta_b[k] = g delta_W[k] = g@h[k].reshape(1, -1) g = self.weights[k].T@g for i in range(K): self.weights[i] = self.weights[i] - learning_rate * delta_W[i] self.bias[i] = self.bias[i] - learning_rate * delta_b[i].reshape(-1) def gradientAtPoint(self, x, y): def fp(): h = [x] a = [] for i in range(len(self.weights)): a.append(self.bias[i] + self.weights[i]@h[i]) h.append(self.activation_func[i](a[i])) return h, a h, a = fp() pred_y = h[-1] g = self.penalty_func_df(y, pred_y).reshape(-1, 1) K = len(self.weights) delta_b = [None] * K delta_W = [None] * K for i in range(K): k = K - i - 1 g = g * self.activation_func_df[k](a[k]).reshape(-1, 1) delta_b[k] = g delta_W[k] = g@h[k].reshape(1, -1) g = self.weights[k].T@g return delta_W, delta_b def onehot(self, y): ret = [0] * self.dim[-1] ret[int(y)] = 1 return np.array(ret).reshape(1,-1) def gradientDescent(self, X, Y, epoch=10, learning_rate=1): for j in range(epoch): print(j) dw_total = None db_total = None for i in range(len(X)): dw, db = self.gradientAtPoint(X[i], self.onehot(Y[i])) dw_total = dw if dw_total is None else dw_total + dw db_total = db if db_total is None else db_total + db for i in range(len(self.weights)): self.weights[i] = self.weights[i] - learning_rate * dw_total[i] / len(X) self.bias[i] = self.bias[i] - learning_rate * db_total[i].reshape(-1) / len(X) def onehot(y): ret = [0] * 10 ret[int(y)] = 1 return np.array(ret).reshape(1,-1) def error(nn, X, Y): error = 0 for i, x in enumerate(X): y = Y[i] y_ = nn.predict(x) error += 1 if y != y_ else 0 return error / len(X) def main(): # Prepare data X_train = np.loadtxt('./dataSets/mnist_small_train_in.txt', delimiter=",") Y_train = np.loadtxt('./dataSets/mnist_small_train_out.txt', delimiter=",") X_test = np.loadtxt('./dataSets/mnist_small_test_in.txt', delimiter=",") Y_test = np.loadtxt('./dataSets/mnist_small_test_out.txt', delimiter=",") D = X_train[0].shape[0] # Create and train neural network def act_func(x): return 1 / (1 + np.exp(-x)) def act_func_df(x): return act_func(x) * (1- act_func(x)) def pen_func(x, y): return .5*(x - y)**2 def pen_func_df(x, y): return (x - y) ff = lambda x: np.append(x, 1) layers = [D, 200, 10] nn = NeuralNetwork( layers, [act_func] * (len(layers) - 1), [act_func_df] * (len(layers) - 1), pen_func, pen_func_df, ff ) print("Pre-Training:") print("Training Error: {}".format(error(nn, X_train, Y_train))) print("Test Error: {}".format(error(nn, X_test, Y_test))) nn.gradientDescent(X_train, Y_train) print("Post-Training:") print("Training Error: {}".format(error(nn, X_train, Y_train))) print("Test Error: {}".format(error(nn, X_test, Y_test))) if __name__ == "__main__": main()
277907f7ebb91a70565ba791fe9131058135a351
dafydds/adventofcode2018
/day1.py
662
3.5
4
with open('data/day1_input.txt', 'r') as fp: lines = fp.readlines() vals = [int(x) for x in lines] print(sum(vals)) def get_repeated_value(vals): counts = {} current_value = 0 counts[current_value] = 1 break_while = False while True: for val in vals: current_value += val previous_counts = counts.get(current_value, 0) if (previous_counts > 0): return current_value break_while = True break counts[current_value] = 1 if break_while: break answer2 = get_repeated_value(vals) print(answer2)
ae13cecbf688c569880bb932bb4a5b4e7ae09e14
andyshen55/MITx6.0001
/ps1/ps1c.py
1,782
4.0625
4
def guessRate(begin, end): #finds midpoint of the given search range and returns it as a decimal guess = ((begin + end) / 2) / 10000.0 return guess def findSaveRate(starting_salary): #program constants portion_down_payment = 0.25 total_cost = 1000000 down = total_cost * portion_down_payment r = 0.04 semi_annual_raise = .07 months = 36 #search counter, search boundaries searches = 0 begin = 0 end = 10000 #continue until there are no more valid save rate guesses. while (end - begin) > 1: searches += 1 currentGuess = guessRate(begin, end) #reinitialize variables for new iteration current_savings = 0.0 month = 1 annual_salary = starting_salary while month <= months: current_savings *= 1 + (r / 12) current_savings += (annual_salary / 12) * currentGuess #increases salary semi-annually after every 6th month if (not (month % 6)): annual_salary *= 1 + semi_annual_raise month += 1 #checks if savings are within 100 dollars of required down payment costDiff = current_savings - down #updates upper/lower bounds if costDiff > 100: end = currentGuess * 10000 elif costDiff < 0: begin = currentGuess * 10000 else: print("Best savings rate:", str(currentGuess)) print("Steps in bisection search:", str(searches)) return #if impossible to save for down payment within 36 months print("It is not possible to pay the down payment in three years.") if __name__ == "__main__": findSaveRate(float(input("Enter the starting salary: ")))
904e4fdfd5cbbf3b0071e26be2d49f42ab9796b0
vgomesdcc/UJ_TeoCompPYTHON
/p3.py
253
3.875
4
print("Insira as notas das provas e do trabalho") prova1 = int(input()) prova2 = int(input()) trabalho = int(input()) prova1 = prova1*3 prova2 = prova2*3 if (prova1+prova2+trabalho)/7 >= 7: print("Aprovado") else: print("Reprovado")
f1feb135f8c763fcf9c8bf51d0456d143b08c984
chouqin/test-code
/pytest/test_func.py
381
3.734375
4
import datetime def add_date(day): day += datetime.timedelta(days=1) return day def append_list(li): li.append(1) return li def two_return(): return 1, 2 if __name__ == "__main__": d1 = datetime.date(2012, 3, 14) d2 = add_date(d1) print d1, d2 l1 = [2, 3] l2 = append_list(l1) print l1, l2 a, b = two_return() print a, b
b3626a37d0b7cd47b4dcdebb19334ee43c3381d8
IvanPLebedev/TasksForBeginer
/Task22.py
637
3.984375
4
''' Задача 22 Напишите программу, которая принимает текст и выводит два слова: наиболее часто встречающееся и самое длинное. ''' import collections text = 'Напишите программу и которая принимает текст и выводит два слова наиболее часто встречающееся и самое длинное' words = text.split() counter = collections.Counter(words) common, occurrences = counter.most_common()[0] longest = max(words, key=len) print(occurrences) print(common, longest)
7907574293ccefef00b3a19517699f3b97caf46c
IvanPLebedev/TasksForBeginer
/Task8.py
480
3.953125
4
''' Напишите проверку на то, является ли строка палиндромом. Палиндром — это слово или фраза, которые одинаково читаются слева направо и справа налево ''' def polindrom(string): return string == string[::-1] a = 'asdfdsa' b = 'reewer' for x in [a,b]: if polindrom(x): print(x,': polindrom') else: print(x,': don,t polindrom')
e804e54379de9827b7a521ef0627afbc270982bd
agin0634/my-leetcode
/solution-python/1000-1499/1013-partition-array-into-three-parts-with-equal-sum.py
412
3.5
4
class Solution(object): def canThreePartsEqualSum(self, A): """ :type A: List[int] :rtype: bool """ target = sum(A)/3 temp,part = 0,0 for a in A: temp += a if temp == target: temp = 0 part += 1 if part >= 3: return True else: return False
b8a84b7f2c8fa026b8004ae443a465e6e12cb8e4
agin0634/my-leetcode
/solution-python/0000-0499/0143-reorder-list.py
958
3.890625
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def reorderList(self, head): """ :type head: ListNode :rtype: None Do not return anything, modify head in-place instead. """ if not head or not head.next: return head stack = [] while head.next.next: stack.append(head.next.val) head.next = head.next.next r = temp = ListNode(0) c = 0 while stack: if c == 0: n = stack[0] del stack[0] temp.next = ListNode(n) temp = temp.next c = 1 else: n = stack.pop() temp.next = ListNode(n) temp = temp.next c = 0 head.next.next = r.next
4ace81cf22287a59177ccc3b70b5bb1a258115d3
agin0634/my-leetcode
/solution-python/0000-0499/0019-remove-nth-node-from-end-of-list.py
624
3.71875
4
# Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def removeNthFromEnd(self, head, n): """ :type head: ListNode :type n: int :rtype: ListNode """ temp, size = head, 0 while temp: size += 1 temp = temp.next l = size - n if l == 0: return head.next res = head for i in range(1,l): head = head.next head.next = head.next.next return res
62e43748e944ce09643e3c4c943e3efe88e9e92b
agin0634/my-leetcode
/solution-python/0500-0999/0500-keyboard-row.py
387
3.5
4
class Solution(object): def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ roa, res = [set('qwertyuiop'), set('asdfghjkl'), set('zxcvbnm')], [] for w in words: word = set(w.lower()) for i in roa: if word.issubset(i): res.append(w) return res
4e5399de763865da945d2157ec2ab5737e104a9e
agin0634/my-leetcode
/solution-python/0000-0499/0113-path-sum-ii.py
761
3.75
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def pathSum(self, root, s): """ :type root: TreeNode :type sum: int :rtype: List[List[int]] """ res = [] def helper(node, tmp): if not node: return if not node.left and not node.right: tmp += [node.val] if sum(tmp) == s: res.append(tmp) return helper(node.left, tmp + [node.val]) helper(node.right, tmp + [node.val]) helper(root, []) return res
bf92d64a05ccf277b13dd50b1e21f261c5bba43c
NikitaBoers/improved-octo-sniffle
/averagewordlength.py
356
4.15625
4
sentence=input('Write a sentence of at least 10 words: ') wordlist= sentence.strip().split(' ') for i in wordlist: print(i) totallength= 0 for i in wordlist : totallength =totallength+len(i) averagelength=totallength/ len(wordlist) combined_string= "The average length of the words in this sentence is "+str(averagelength) print(combined_string)
0de13dc0bcc711f7dbc68efdfd0aee2cdbaf94af
NikitaBoers/improved-octo-sniffle
/studentsdictionary2.py
618
3.546875
4
import json filename = 'students (1).csv' students= {} with open(filename) as file: file.readline() for line in file: split= line.strip().split(',') other= {} other['LastName']=split [1] other['Adjective']=split[0] other['Email']=split [3] students[split[2]] = other print(students) with open ('studentdictionary.json', 'w' ) as file: json.dump(students, file, indent=4) #adjective, last_name, first_name, email=line.split(',') #students[first_name.strip()]= #other={} #other['LastName']=last_name #other[Adjective]=adjective #other['email']=email
ca820fc2d0a2ee0dee559ca8185ef4ede2620c65
maximrufed/Mirrows
/geoma.py
3,820
3.765625
4
import math eps = 1e-7 class point: x: float y: float def __init__(self, x_init, y_init): self.x = x_init self.y = y_init def set(self, x, y): self.x = x self.y = y def len(self): return math.sqrt(self.x * self.x + self.y * self.y) def normalize(self, len): tek_len = self.len() self.x = self.x / tek_len * len self.y = self.y / tek_len * len def to_arr(self): return [round(self.x), round(self.y)] def rotate(self, angle): x1 = self.x y1 = self.y self.x = x1 * math.cos(angle) - y1 * math.sin(angle) self.y = x1 * math.sin(angle) + y1 * math.cos(angle) def __add__(self, other): return point(self.x + other.x, self.y + other.y) def __sub__(self, other): return point(self.x - other.x, self.y - other.y) def show(self): print("x: " + str(self.x) + " y: " + str(self.y)) def scal(a: point, b: point): # cos return a.x * b.x + a.y * b.y def vect(a: point, b: point): # sin return a.x * b.y - a.y * b.x class otr: def __init__(self, a: point, b: point): self.a = a self.b = b def set(self, a: point, b: point): self.a = a; self.b = b; def to_vec(self): return self.b - self.a class line: def set(self, a, b, c): self.a = a self.b = b self.c = c def __init__(self, p1: point, p2: point): self.a = p2.y - p1.y self.b = p1.x - p2.x self.c = p1.x * (p1.y - p2.y) + p1.y * (p2.x - p1.x) def show(self): print("a: " + str(self.a)) print("b: " + str(self.b)) print("c: " + str(self.c)) def get_angle(a: point, b: point): return math.atan2(vect(a, b), scal(a, b)) def rotate_vector_vector(a: point, b: point): # start_len = b.len() angle = get_angle(a, b) * 2 print("angle: " + str(angle)) a.show() a.rotate(angle) a.show() # b.normalize(start_len) return a def sign(a): if (a < 0): return -1 if (a > 0): return 1 return 0 def check_inter_ray_otr(ray: otr, mir: otr): a = ray.a - mir.a; b = mir.b - mir.a c = ray.b - mir.a return ((vect(a, b) * vect(a, c)) > 0) and (sign(vect(ray.to_vec(), mir.a - ray.a)) != sign(vect(ray.to_vec(), mir.b - ray.a))) def len_pt_line(p: point, o: otr): l = line(o.a, o.b) return ((l.a * p.x + l.b * p.y + l.c) / math.sqrt(l.a * l.a + l.b * l.b)) def inter_point(ray: otr, mir: otr): if not(check_inter_ray_otr(ray, mir)): return -1 else: d1 = len_pt_line(ray.a, mir) d2 = len_pt_line(ray.b, mir) tek_vec = ray.b - ray.a # check for div fo zero tek_vec.normalize(tek_vec.len() * d1 / (d1 - d2)) ray.b = ray.a + tek_vec; return ray def dist_pt_otr(p: point, o: otr): ab = o.b - o.a ba = o.a - o.b ap = p - o.a bp = p - o.b if ((scal(ab, ap) >= 0) and (scal(ba, bp) >= 0)): return abs(len_pt_line(p, o)) else: return min(ap.len(), bp.len()) def inside_pt_otr(p: point, o: otr): ab = o.b - o.a ba = o.a - o.b ap = p - o.a bp = p - o.b if ((scal(ab, ap) >= 0) and (scal(ba, bp) >= 0)): return 0 else: if (ap.len() < bp.len()): return 1 else: return 2 def pt_to_line(a: point, o: otr): return (vect(o.a - a, o.b - a) == 0) def otr_inter(a: otr, b: otr): if (pt_to_line(a.a, b) and pt_to_line(a.b, b)): if (((max(a.a.x, a.b.x) < min(b.a.x, b.b.x)) or ((min(a.a.x, a.b.x) > max(b.a.x, b.b.x)))) or ((max(a.a.y, a.b.y) < min(b.a.y, b.b.y)) or ((min(a.a.y, a.b.y) > max(b.a.y, b.b.y))))): return 0 else: return 1 t = a.b - a.a t2 = b.b - b.a return (sign(vect(t, b.a - a.b)) != sign(vect(t, b.b - a.b))) and (sign(vect(t2, a.a - b.a)) != sign(vect(t2, a.b - b.a))) def line_inter(l1: line, l2: line): return point((l1.b * l2.c - l2.b * l1.c) / (l1.a * l2.b - l2.a * l1.b), (l1.a * l2.c - l2.a * l1.c) / (l2.a * l1.b - l1.a * l2.b)) def perp_line_pt(l: line, p: point): a = line(point(0, 0), point(0, 0)) a.set(-l.b, l.a, -(p.x * -l.b + p.y * l.a)) return a
292ad196eaee7aab34dea95ac5fe622281b1a845
LJ1234com/Pandas-Study
/06-Function_Application.py
969
4.21875
4
import pandas as pd import numpy as np ''' pipe(): Table wise Function Application apply(): Row or Column Wise Function Application applymap(): Element wise Function Application on DataFrame map(): Element wise Function Application on Series ''' ############### Table-wise Function Application ############### def adder(ele1, ele2): return ele1 + ele2 df = pd.DataFrame(np.random.randn(5,3),columns=['col1','col2','col3']) print(df) df2 = df.pipe(adder, 2) print(df2) ############### Row or Column Wise Function Application ############### print(df.apply(np.mean)) # By default, the operation performs column wise print(df.mean()) print(df.apply(np.mean,axis=1)) # operations can be performed row wise print(df.mean(1)) df2 = df.apply(lambda x: x - x.min()) print(df2) ############### Element wise Function Application ############### df['col1'] = df['col1'].map(lambda x: x * 100) print(df) df = df.applymap(lambda x:x*100) print(df)
e45c11a712bf5cd1283f1130184340c4a8280d13
LJ1234com/Pandas-Study
/21-Timedelta.py
642
4.125
4
import pandas as pd ''' -String: By passing a string literal, we can create a timedelta object. -Integer: By passing an integer value with the unit, an argument creates a Timedelta object. ''' print(pd.Timedelta('2 days 2 hours 15 minutes 30 seconds')) print(pd.Timedelta(6,unit='h')) print(pd.Timedelta(days=2)) ################## Operations ################## s = pd.Series(pd.date_range('2012-1-1', periods=3, freq='D')) td = pd.Series([ pd.Timedelta(days=i) for i in range(3) ]) df = pd.DataFrame(dict(A = s, B = td)) print(df) ## Addition df['C']=df['A'] + df['B'] print(df) ## Subtraction df['D']=df['C']-df['B'] print(df)
3d9b7186764bfd5dd51a24a6e23769f229b8b9e8
LJ1234com/Pandas-Study
/01-Series.py
1,531
4.03125
4
import pandas as pd import numpy as np ''' Series is a one-dimensional labeled array capable of holding data of any type. The axis labels are collectively called index. A pandas Series can be created using the following constructor: pandas.Series( data, index, dtype, copy) - data: data takes various forms like ndarray, list, constants - index: Index values must be unique and hashable, same length as data. Default np.arrange(n) if no index is passed. - dtype: dtype is for data type. If None, data type will be inferred - copy: Copy data. Default False ''' ################### Create Series ################### # Create an Empty Series s = pd.Series() print(s) # Create a Series from ndarray data = np.array(['a', 'b', 'c', 'd']) s = pd.Series(data) print(s) s = pd.Series(data, index=[10, 11, 12, 13]) print(s) # Create a Series from dict data = {'a': 1, 'b': 2, 'c': 3, 'd': 4} s = pd.Series(data) # Dict keys are used to construct index. print(s) data = {'a': 0., 'b': 1., 'c': 2.} s = pd.Series(data,index=['b','c','d','a']) # Index order is persisted and the missing element is filled with NaN print(s) # Create a Series from Scalar s = pd.Series(5, index=[0, 1, 2, 3]) print(s) ################### Accessing Series ################### # Accessing Data from Series with Position s = pd.Series([1, 2, 3, 4, 5], index=['a','b','c','d', 'e']) print(s) print(s[0]) print(s[[0, 2, 4]]) print(s[:3]) print(s[-3:]) # Accessing Data Using Label (Index) print(s['a']) print(s[['a', 'c', 'd']])
4c4d5e88fde9f486210ef5bd1595775e0adce53c
aiworld2020/pythonprojects
/number_99.py
1,433
4.125
4
answer = int(input("I am a magician and I know what the answer will be: ")) while (True): if answer < 10 or answer > 49: print("The number chosen is not between 10 and 49") answer = int(input("I am choosing a number from 10-49, which is: ")) continue else: break factor = 99 - answer print("Now I subtracted my answer from 99, which is " + str(factor)) friend_guess = int(input("Now you have to chose a number from 50-99, which is: ")) while (True): if friend_guess < 50 or friend_guess > 99: print("The number chosen is not between 50 and 99") friend_guess = int(input("Now you have to chose a number from 50-99, which is: ")) continue else: break three_digit_num = factor + friend_guess print("Now I added " + str(factor) + " and " + str(friend_guess) + " to get " + str(three_digit_num)) one_digit_num = three_digit_num//100 two_digit_num = three_digit_num - 100 almost_there = two_digit_num + one_digit_num print("Now I added the hundreds digit of " + str(three_digit_num) + " to the tens and ones digit of " + str(three_digit_num) + " to get " + str(almost_there)) final_answer = friend_guess - almost_there print("Now I subtracted your number, " + str(friend_guess) + " from " + str(almost_there) + " to get " + str(final_answer)) print("The final answer, " + str(final_answer) + " is equal to my answer from the beginning, " + str(answer))
6f240b1f578b18a0e3572187fa31e2bf5d48f772
a1a1a2a4/100knock
/otani/python/1/05.py
285
3.71875
4
from pprint import pprint def Ngram(string, num): ngram = [0 for i in range(len(string) - num + 1)] # 初期化 for i in range(len(string) - num + 1): ngram[i] = string[i:(i + num)] return ngram string = "ketsugenokamisama" ngram = Ngram(string, 3) pprint(ngram)
d8e1ab0778a17030a2ee03eccba776743384747f
Bolodeoku1/PET328_2021_Class
/group 6 project new.py
503
3.625
4
B_comp = float (input('What is the bit cost?')) CR_comp = float (input('What is the rig cost per hour?')) t_comp = float (input('What is the drilling time?')) T_comp = float (input('What is the round trip time?')) F_comp = float (input('What is the footage drill per bit?')) # convert inputs to numerals # the formula for drilling cost per foot drilling_cost_per_foot =(B_comp + CR_comp * (t_comp + T_comp))/(F_comp) print('The drilling cost per foot is {0:.2f} $' .format (drilling_cost_per_foot))
de46cb4081b386006c47ad7f16849cd0c95d4e30
lamolivier/EPFL-MLBD-Project
/notebooks/helper_functions.py
743
4
4
import pickle def save_to_pickle(var, filename, path_write_data): """ Parameters ---------- var : any python variable variable to be saved filename : string Name of the pickle we will create path_write_data : string Path to the folder where we write and keep intermediate results """ with open(path_write_data + filename + '.pickle', 'wb') as f: pickle.dump(var, f) f.close() def load_pickle(path_data): """ Parameters: ---------- path_data : string Path to the file to be loaded Returns ---------- var : The loaded object """ with open(path_data, 'rb') as f: var = pickle.load(f) f.close() return var
a71c9875f51651370970f8c61280d7305bfad02f
klaundal/lompe
/lompe/model/data.py
12,751
4.03125
4
""" Lompe Data class The data input to the Lompe inversion should be given as lompe.Data objects. The Data class is defined here. """ import numpy as np import warnings class ShapeError(Exception): pass class ArgumentError(Exception): pass class Data(object): def __init__(self, values, coordinates = None, LOS = None, components = 'all', datatype = 'none', label = None, scale = None, iweight = None, error = 0): """ Initialize Data object that can be passed to the Emodel.add_data function. All data should be given in SI units. The data should be given as arrays with shape (M, N), where M is the number of dimensions and N is the number of data points. For example, for 3D vector valued data, M is 3, and the rows correspond to the east, north, and up (ENU) components of the measurements, in that order. See documentation on specific data types for details. The coordinates should be given as arrays with shape (M, N) where M is the number of dimensions and N is the number of data points. For example, ground magnetometer data can be provided with a (2, N) coordinate array with N values for the longitude and latitude, in degrees in the two rows. The order of coordinates is: longitude [degrees], latitude [degrees], radius [m]. See documentation on specific data types for details. You must specify the data type. Acceptable types are: 'ground_mag': Magnetic field perturbations on ground. Unless the components keyword is used, values should be given as (3, N) arrays, with eastward, northward and upward components of the magnetic field perturbation in the three rows, in Tesla. The coordinates can be given as (2, N) arrays of the magnetometers' longitudes and latitudes in the two rows (the radius is then assumed to be Earth's radius), OR the coordinates can be given as (3, N) arrays where the last row contains the geocentric radii of the magnetometers. An error (measurement uncertainty) can be given as an N-element array, or as a scalar if the uncertainty is the same for all data points in the dataset. An alternative way of specifying 'ground_mag', if you do not have full 3D measurements, is to provide it as (M, N) values, where M < 3, and the rows correspond to the directions that are measured. Specify which directions using the components keyword (see documentation for that keyword for details). 'space_mag_fac': Magnetic field perturbations in space associated with field-aligned currents. Unless the components keyword is used, values should be given as (3, N) arrays, with eastward, northward and upward components of the magnetic field perturbation in the three rows, in Tesla. Note that the upward component is not used for this parameter, since field-lines are assumed to be radial and FACs therefore have no vertical field (it must still be given). The coordinates should be given as (3, N) arrays with the longitudes, latitudes, and radii of the measurements in the three rows. 'space_mag_full': Magnetic field perturbations in space associated with field-aligned currents and horizontal divergence-free currents below the satellite. This is useful for low-flying satellites with accurate magnetometers (e.g., Swarm, CHAMP). The format is the same as for 'space_mag_fac'. 'convection': Ionospheric convection velocity perpendicular to the magnetic field, mapped to the ionospheric radius. The values should be given as (2, N) arrays, where the two rows correspond to eastward and northward components in m/s. The coordinates should be given as (2, N) arrays where the rows are longnitude and latitude in degrees. For line-of-sight measurements, the values parameters should be an N element array with velocities in the line-of-sight direction. The line-of-sight direction must be specified as a (2, N) array using the LOS keyword. The (2, N) LOS parameter should contain the eastward and northward components of the line-of-sight vector in the two rows. 'Efield': Ionospheric convection electric field, perpendicular to B and mapped to the ionospheric radius. The values should be given in [V/m], with the same format as for 'convection'. The LOS keyword can be used for this parameter also, if only one component of the electric field is known. 'fac': Field-aligned electric current density in A/m^2. It must be provided as a K_J*K_J element array, where the elements correspond to the field-aligned current density at the Lompe inner grid points, in the order that they will have after a flatten/ravel operation. Values passed to coordinates will be ignored. This parameter is only meant to be used with large-scale datasets or simulation output that can be interpolated to the Lompe model grid. This is different from all the other datatypes used in Lompe. Note ---- One purpose of this class is to collect all data sanity checks in one place, and to make sure that the data which is passed to Lompe has the correct shape, valid values etc. We're not quite there yet, so be careful! :) Parameters ---------- values: array array of values in SI units - see specific data type for details coordinates: array array of coordinates - see specific data types for details datatype: string datatype should indicate which type of data it is. They can be: 'ground_mag' - ground magnetic field perturbation (no main field) data 'space_mag_full' - space magnetic field perturbation with both FAC and divergence-free current signal 'space_mag_fac' - space magnetic field perturbation with only FAC signal 'convection' - F-region plasma convection data - mapped to R 'Efield' - electric field - mapped to R label: string, optional A name for the dataset. If not set, the name will be the same as the datatype. Setting a label can be useful for distinguishing datasets of the same type from different sources (e.g. DMSP and SuperDARN) LOS: array, optional if the data is line-of-sight (LOS), indicate the line-of-sight using a (2, N) array of east, north directions for the N unit vectors pointing in the LOS directions. By default, data is assumed to not be line-of-sight. Note that LOS is only supported for Efield and convection, which are 2D data types. components: int(s), optional indicate which components are included in the dataset. If 'all' (default), all components are included. If only one component is included, set to 0, 1, or 2 to specify which one: 0 is east, 1 is north, and 2 is up. If two components are included, set to a list of ints (e.g. [0, 2] for east and up). NOTE: If LOS is set, this keyword is ignored scale: float, optional DEPRECATED. Use iweight and error instead. Previous description: set to a typical scale for the data, in SI units. For example, convection could be typically 100 [m/s], and magnetic field 100e-9 [T]. If not set, a default value is used for each dataset. iweight: float, optional importance weight of the data ranging from 0 to 1. For example, since ground magnetometer measurements can only indirectly influence the calculation of ionospheric convection via conductance, one might set iweight=0.3 for ground magnetometer data and iweight=1.0 for ionospheric convection measurements. Keep in mind that this weight is directly applied to the a priori inverse data covariance matrix, so the data error is effectively increased by a factor of 1/sqrt(iweight). error: array of same length as values, or float, optional Measurement error. Used to calculate the data covariance matrix. Use SI units. """ self.isvalid = False datatype = datatype.lower() if datatype not in ['ground_mag', 'space_mag_full', 'space_mag_fac', 'convection', 'efield', 'fac']: raise ArgumentError(f'datatype not recognized: {datatype}') return(None) errors = {'ground_mag':10e-9, 'space_mag_full':30e-9, 'space_mag_fac':30e-9, 'convection':50, 'efield':3e-3, 'fac':1e-6} iweights = {'ground_mag':0.5, 'space_mag_full':0.5, 'space_mag_fac':0.5, 'convection':1.0, 'efield':1.0, 'fac':1.0} assert scale is None,"'scale' keyword is deprecated! Please use 'iweight' (\"importance weight\") instead" if error == 0: error = errors[datatype] warnings.warn(f"'error' keyword not set for datatype '{datatype}'! Using error={error}", UserWarning) if iweight is None: iweight = iweights[datatype] warnings.warn(f"'iweight' keyword not set for datatype '{datatype}'! Using iweight={iweight}", UserWarning) self.label = datatype if label is None else label self.datatype = datatype self.values = values if coordinates is not None: if datatype.lower() == 'fac': warnings.warn('Warning: FAC data must be defined on the whole Emodel.grid_J, but this is not checked.', UserWarning) if coordinates.shape[0] == 2: self.coords = {'lon':coordinates[0], 'lat':coordinates[1]} if coordinates.shape[0] == 3: self.coords = {'lon':coordinates[0], 'lat':coordinates[1], 'r':coordinates[2]} else: self.coords = {} assert datatype.lower() == 'fac', "coordinates must be provided for all datatypes that are not 'fac'" self.isvalid = True if np.ndim(self.values) == 2: self.N = self.values.shape[1] # number of data points if np.ndim(self.values) == 1: self.N = self.values.size if (LOS is not None) & (datatype in ['convection', 'efield']): self.los = LOS # should be (2, N) east, north components of line of sight vectors self.components = [0,1] #2021-10-29: jreistad added this to work with how components is used in model.py. Could avoid this slightly non-inututuve value by modifying model.py instead. else: self.los = None if type(components) == str and components == 'all': self.components = [0, 1, 2] else: # components is specified as an int or a list of ints self.components = np.sort(np.array(components).flatten()) assert np.all([i in [0, 1, 2] for i in self.components]), 'component(s) must be in [0, 1, 2]' # make data error: if np.array(error).size == 1: self.error = np.full(self.N, error) else: self.error = error # assign importance weight self.iweight = iweight # check that number of data points and coordinates match: if self.coords['lat'].size != np.array(self.values, ndmin = 2).shape[1]: raise ShapeError('not the same number of coordinates and data points') # remove nans from the dataset: iii = np.isfinite(self.values) if iii.ndim > 1: iii = np.all(iii, axis = 0) self.subset(iii) def subset(self, indices): """ modify the dataset so that it only contains data points given by the passed indices. The indices are 1D, so if the dataset is vector-valued, indices refer to the column index; it selects entire vectors, you can not select only specific components """ self.values = np.array(self.values , ndmin = 2)[:, indices].squeeze() self.error = self.error[indices] for key in self.coords.keys(): self.coords[key] = self.coords[key][indices] if self.los is not None: self.los = self.los[:, indices] # update number of data points: if np.ndim(self.values) == 2: self.N = self.values.shape[1] if np.ndim(self.values) == 1: self.N = self.values.size return self def __str__(self): return(self.datatype + ': ' + str(self.values)) def __repr__(self): return(str(self))
d65ac8ccbf22813eb3be92d127b316cb3b735e9d
tammytdo/SP2018-Python220-Accelerated
/Student/tammyd_Py220/Py220_lesson09/concurrency.py
1,014
4.0625
4
import threading import time import random # simple threading def func(n): for i in range(n): print("hello from thread %s" % threading.current_thread().name) time.sleep(random.random() * 2) # run a bunch of fuctions at the same time threads = [] for i in range(3): thread = threading.Thread(target=func, args=(i+2)) thread.start() threads.append(thread) # start and append thread. for thread in threads: print("Joining thread: ", thread.name) thread.join() # to know when it is done print("all threads finished.") func(10) # ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~` # # race conditions # import threading # import time # class shared: # val = 1 # def func(): # y = shared.val # time.sleep(0.001) # y += 1 # shared.val = y # threads = [] # for i in range(100): # thread = threading.Thread(target=func) # threads.append(thread) # thread.start() # for thread in threads: # thread.join() # print(shared.val)
4c118860c69f31cc8d10182c9f7bb3027c5942be
tammytdo/SP2018-Python220-Accelerated
/Student/tammyd_Py220/Py220_lesson07/assignment7/mailroom_model.py
1,821
4
4
""" Simple database example with Peewee ORM, sqlite and Python Here we define the schema Use logging for messages so they can be turned off """ import logging from peewee import * logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) logger.info("One off program to build the classes from the model in the database") logger.info("Here we define our data (the schema)") logger.info("First name and connect to a database (sqlite here)") logger.info("The next 3 lines of code are the only database specific code") database = SqliteDatabase("mailroom.db") database.connect() database.execute_sql("PRAGMA foregn_keys = ON") # needed for sqlite only logger.info("Connected to database") class BaseModel(Model): class Meta: database = database class Donors(BaseModel): """ this class defines Donor, which maintains details of someone who has made a donation """ logger.info("Donors class model created") donor_id = CharField(primary_key = True, max_length = 10) #primary_key = True means every person has to have a unique name donor_name = CharField(max_length = 40) donor_city = CharField(max_length = 40, null = True) #donor may have no city donor_phone = CharField(max_length= 13, null = True) #donor may not have/give contact info logger.info("Successfully logged Donors") class Donations(BaseModel): """ this class defines Donations, which maintains details of someone's donation """ logger.info("Donations class model created") donation_amount = DecimalField(decimal_places = 2) donation_date = DateField(formats = "YYYY-MM-DD") donation__donor_id = ForeignKeyField(Donor) logger.info("Successfully logged Donations") database.create_tables([ Donors, Donations, ]) database.close()
053294e9f40e9d67b652c013c84cc443106a6187
obryana/data-science-projects
/Google FooBar/google_fuel_injection.py
975
3.625
4
def peek(num_pellets): operations_peek = 1 while num_pellets % 2 == 0: num_pellets /= 2 operations_peek += 1 return (operations_peek, num_pellets) def answer(num_pellets): num_pellets = int(num_pellets) operations = 0 while num_pellets > 1: if num_pellets % 2 == 0: num_pellets /= 2 operations += 1 else: peek_add = peek(num_pellets+1) peek_sub = peek(num_pellets-1) if peek_add[1] == peek_sub[1]: operations += min(peek_add[0],peek_sub[0]) num_pellets = peek_add[1] else: if peek_add[0] > peek_sub[0]: operations += peek_add[0] num_pellets = peek_add[1] else: operations += peek_sub[0] num_pellets = peek_sub[1] return operations print(answer(47)) print(answer(4)) print(answer(15))
5608d39b85560dc2ea91e943d60716901f5fe88b
longroad41377/selection
/months.py
337
4.4375
4
monthnames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"] month = int(input("Enter month number: ")) if month > 0 and month < 13: print("Month name: {}".format(monthnames[month-1])) else: print("Month number must be between 1 and 12")
b84a8ac32b9e866639fdf804a1acc3f561863339
artem-chyrkov/hist-detector
/base/ring_list.py
922
3.609375
4
class RingList: def __init__(self): self._max_size = 0 self._ring_list = [] self._index_to_replace = -1 def init(self, max_size): self._max_size = max_size self.clear() def add(self, x): # TODO optimize if len(self._ring_list) < self._max_size: # usual adding self._ring_list.append(x) else: # len(self._ring_list) == self._max_size --> ring-style adding self._index_to_replace += 1 if self._index_to_replace >= self._max_size: self._index_to_replace = 0 self._ring_list[self._index_to_replace] = x def clear(self): self._ring_list.clear() self._index_to_replace = -1 def get(self): return self._ring_list def get_actual_size(self): return len(self._ring_list) def get_index_to_replace(self): return self._index_to_replace
21219f7ddb8f074e9f811f4c5d3bcdb34712a761
da1x/cs50-2018
/pset6/mario/mario.py
535
3.921875
4
from cs50 import get_int while True: # prompt user height = get_int("Height: ") # Make sure the number is more then 0 and less then 24 if height < 24 and height >= 0: break # Print for i in range(height): # First part for j in range(height - i - 1): print(" ", end="") for k in range(i + 1): print("#", end="") # Middle two spaces for l in range(2): print(" ", end="") # End part for m in range(i + 1): print("#", end="") print("\n", end="")
182e95b294e0c4341a8e6dc9fb90b61885bf2022
ccsourcecode/python-data-analysis
/00原始代码【无笔记纯享版】/00-01-3pandas常用内容速成简记/demo04筛选DataFrame中的数据/demo04-4布尔索引:补充示例/example布尔索引-04-4-1筛最高评分中的最低价格/example布尔索引-04-4-1.py
876
3.59375
4
import pandas as pd from pandas import DataFrame resourceFile = "bestsellers.csv" # 取出表数据 data = pd.read_csv(filepath_or_buffer=resourceFile) # Index(['书名', '作者', '评分', '被查看次数', '价格', '年份', '体裁'], dtype='object') # print(data.columns) # 最高评分“中”的最低价格(基于最高评分接着细粒度筛,千万注意这里不是重新筛) # 筛选数据结果result从原始data开始。深拷贝,不是浅拷贝。 result = data # 筛出最高评分 result = result[result["评分"] == result["评分"].max()] # 在最高评分的基础上,筛出最低价格 result = result[result["价格"] == result["价格"].min()] # 下面这样做是不对的,看似可以实际报错 # result = result[result["评分"] == result["评分"].max()][result["价格"] == result["价格"].min()] # 输出结果 print(result)
f8679f7a1aa887cbd492d94ffdcc54bbc1c05fc1
ccsourcecode/python-data-analysis
/00原始代码【无笔记纯享版】/00-09线性回归预测分析/补充案例/00-09-1单一自变量线性回归预测分析/demo_singleLR1-自热火锅价格销量相关性分析/demo_singleLR1.py
402
3.515625
4
import pandas as pd from pandas import DataFrame # 探究价格与销量的关联系数 # 读取文件 df = pd.read_excel(io="自热火锅.xlsx", sheet_name=0) # type: DataFrame # print(df.columns) # Index(['category', 'goods_name', 'shop_name', 'price', 'purchase_num', 'location'], dtype='object') # 计算相关系数 corrPriceNum = df["price"].corr(other=df["purchase_num"]) print(corrPriceNum)
4adb4a10b451e7c7e41c85d5f59d7ab0732f56ef
Letthemknow/school
/Stanford/CS109/cs109_pset3.py
3,303
3.5
4
# Name: # Stanford email: ########### CS109 Problem Set 3, Question 1 ############## """ ************************IMPORTANT************************ For all parts, do NOT modify the names of the functions. Do not add or remove parameters to them either. Moreover, make sure your return value is exactly as described in the PDF handout and in the provided function comments. Remember that your code is being autograded. You are free to write helper functions if you so desire. Do NOT rename this file. ************************IMPORTANT************************ """ # Do not add import statements. # Do not remove this import statement either. from numpy.random import rand # part (a) - completed for you def simulate_bernoulli(p=0.4): if rand() < p: return 1 return 0 # part (b) def simulate_binomial(n=20, p=0.4): count = 0 for _ in range(n): if rand() < p: count += 1 return count # part (c) def simulate_geometric(p=0.03): num_trials = 1 r = rand() while r >= p: num_trials += 1 r = rand() return num_trials # part (d) def simulate_neg_binomial(r=5, p=0.03): count = 0 successes = 0 while successes <= r: count += 1 if rand() < p: successes += 1 return count # Note for parts (e) and (f): # Since `lambda` is a reserved word in Python, we've used # the variable name `lamb` instead. Do NOT use the word # `lambda` in your code. It won't do what you want! # part (e) def simulate_poisson(lamb=3.1): time_increments = 60000 prob = lamb / time_increments count = 0 for _ in range(time_increments): if rand() < prob: count += 1 return count # part (f) def simulate_exponential(lamb=3.1): time_increments = 60000 prob = lamb / time_increments r = rand() time_steps = 1 while r >= prob: time_steps += 1 r = rand() return time_steps / time_increments def main(): """ We've provided this for convenience. Feel free to modify this function however you like. We won't grade anything in this function. """ print("Bernoulli:", simulate_bernoulli()) ########### CS109 Problem Set 3, Question 13 ############## """ *********** Article submission ********** If you choose to submit an article for extra credit, it should be in a function named article_ec: - this function should take 0 arguments - edit the string variable sunetid to be your SUNetID, e.g., "yanlisa" - edit the string variable title to be your article title, e.g., "10 Reasons Why Probability Is Great" - edit the string variable url to be a URL to your article, e.g., "http://cs109.stanford.edu/" - you should not modify the return value """ def article_ec(): sunetid = "agalczak" # your sunet id here. title = "Carnival Probability of Bankruptcy" # your article title here url = "https://www.macroaxis.com/invest/ratio/CCL--Probability-Of-Bankruptcy" # a link to your article here return sunetid, title, url ############################################################ # This if-condition is True if this file was executed directly. # It's False if this file was executed indirectly, e.g. as part # of an import statement. if __name__ == "__main__": main()
d0df4da84b7a6d75240e62c41569c4b471b2699e
Letthemknow/school
/Stanford/CS109/cs109_pset5_coursera.py
7,343
3.703125
4
# Do NOT add any other import statements. # Don't remove these import statements. import numpy as np import copy import os # Name: # Stanford email: ########### CS109 Problem Set 5, Question 8 ############## def get_filepath(filename): """ filename is the name of a data file, e.g., "learningOutcomes.csv". You can call this helper function in all parts of your code. Return a full path to the data file, located in the directory datasets, e.g., "datasets/learningOutcomes.csv" """ return os.path.join("datasets", filename) """ Assembled by Lisa Yan and Past CS109 TA Anand Shankar *************************IMPORTANT************************* For part_a and part_b, do NOT modify the name of the functions. Do not add or remove parameters to them either. Moreover, make sure your return value is exactly as described in the PDF handout and in the provided function comments. Remember that your code is being autograded. You are free to write helper functions if you so desire. Do NOT rename this file. *************************IMPORTANT************************* """ def part_a(filename): """ filename is the name of a data file, e.g. "learningOutcomes.csv". You must use the filename variable. Do NOT alter the filename variable, and do NOT hard-code a filepath; if you do, you'll likely fail the autograder. You can use the helper function defined above, get_filepath(). Return the difference in sample means (float) as described in the handout. """ data = np.genfromtxt(get_filepath(filename), names = ['id', 'activity', 'score'], dtype=[('id', np.int32), ('activity', np.dtype('U9')), ('score', np.int32)], delimiter=',') activity1, activity2 = data[data['activity'] == "activity1"], data[data['activity'] == "activity2"] a1_scores, a2_scores = [row[2] for row in activity1], [row[2] for row in activity2] return abs(np.mean(a1_scores) - np.mean(a2_scores)) def part_b(filename, seed=109): """ filename is the name of a data file, e.g. "learningOutcomes.csv". You must use the filename variable. Do NOT alter the filename variable, and do NOT hard-code a filepath; if you do, you'll likely fail the autograder. You MUST use np.random.choice with replace=True to draw random samples. You may NOT use any other function to draw random samples. See assignment handout for details. Return the p-value (float) as described in the handout. """ np.random.seed(seed) # DO NOT ALTER OR DELETE THIS LINE ### BEGIN YOUR CODE FOR PART (B) ### data = np.genfromtxt(get_filepath(filename), names = ['id', 'activity', 'score'], dtype=[('id', np.int32), ('activity', np.dtype('U9')), ('score', np.int32)], delimiter=',') activity1, activity2 = data[data['activity'] == "activity1"], data[data['activity'] == "activity2"] a1_scores, a2_scores = [row[2] for row in activity1], [row[2] for row in activity2] true_diff = part_a(filename) # 1. Create universal sample with two samples. universal_sample = a1_scores + a2_scores # 2. Repeat bootstrapping procedure 10000 times. num_greater_diffs = 0 iters = 10000 for i in range(iters): resample1 = resample(universal_sample, len(a1_scores)) resample2 = resample(universal_sample, len(a2_scores)) diff = abs(np.mean(resample1) - np.mean(resample2)) if diff > true_diff: num_greater_diffs += 1 p_val = num_greater_diffs / iters return p_val ### END YOUR CODE FOR PART (B) ### def resample(data, n): return np.random.choice(data, n, replace=True) def optional_function(): """ We won't autograde anything you write in this function. But we've included this function here for convenience. It will get called by our provided main method. Feel free to do whatever you want here, including leaving this function blank. We won't read or grade it. """ np.random.seed(109) data_scores = np.genfromtxt(get_filepath('learningOutcomes.csv'), names=['id', 'activity', 'score'], dtype=[('id', np.int32), ('activity', np.dtype('U9')), ('score', np.int32)], delimiter=',') data_back = np.genfromtxt(get_filepath('background.csv'), names=['id', 'background'], dtype=[('id', np.int32), ('background', np.dtype('U7'))], delimiter=',') activity1, activity2 = data_scores[data_scores['activity'] == "activity1"], data_scores[data_scores['activity'] == "activity2"] a1_scores, a2_scores = [row[2] for row in activity1], [row[2] for row in activity2] back_less, back_avg, back_more = data_back[data_back['background'] == 'less'], data_back[data_back['background'] == 'average'], data_back[data_back['background'] == 'more'] backs = [back_less, back_avg, back_more] # Loop over all the backgrounds and get a difference in means between act1 and act2. Similar to part a. for back in backs: act1_scores = [] act2_scores = [] for row in back: id = row['id'] score_row = data_scores[data_scores['id'] == id] score = score_row['score'] if score_row['activity'] == "activity1": act1_scores.append(score) else: act2_scores.append(score) back_mean = abs(np.mean(act1_scores) - np.mean(act2_scores)) # Calculate p-val, exact same code as in part_b universal_sample = (act1_scores + act2_scores) # This returns a list of arrays for some reason. Need to flatten it. universal_sample = [element for sublist in universal_sample for element in sublist] num_greater_diffs = 0 iters = 10000 for i in range(iters): resample1 = resample(universal_sample, len(act1_scores)) resample2 = resample(universal_sample, len(act2_scores)) diff = abs(np.mean(resample1) - np.mean(resample2)) if diff > back_mean: num_greater_diffs += 1 p_val = num_greater_diffs / iters print("Background: {} mean: {:.2f} p-value: {}".format(back[0]['background'], back_mean, p_val)) def main(): """ We've provided this for convenience, simply to call the functions above. Feel free to modify this function however you like. We won't grade anything in this function. """ print("****************************************************") print("Calling part_a with filename 'learningOutcomes.csv':") print("\tReturn value was:", part_a('learningOutcomes.csv')) print("****************************************************") print("****************************************************") print("Calling part_b with filename 'learningOutcomes.csv':") print("\tReturn value was:", part_b('learningOutcomes.csv')) print("****************************************************") print("****************************************************") print("Calling optional_function:") print("\tReturn value was:", optional_function()) print("****************************************************") print("Done!") # This if-condition is True if this file was executed directly. # It's False if this file was executed indirectly, e.g. as part # of an import statement. if __name__ == "__main__": main()
718944b33bc36198a7942be3db1204adec0b47ac
joseluisquisan/hello-world
/devnet/devnet/data_estructures.py
485
3.53125
4
def legalAges(): lifeEvent = { "drivingAge": 16, "votingAge": 18, "drinkingAge": 21, "retirementAge": 65 } print("The legal driving age is " + str(lifeEvent["drivingAge"]) + ".") print("The legal voting age is " + str(lifeEvent["votingAge"]) + ".") print("The legal drinking age is " + str(lifeEvent["drinkingAge"]) + ".") print("The legal retirement age is " + str(lifeEvent["retirementAge"]) + ".") legalAges()
e821232eb26f19e46699cec48e7165e461f14578
joseluisquisan/hello-world
/python_basico/disccionarios.py
636
3.90625
4
def run(): mi_diccionario = { 'llave1': 1, 'llave2': 2, 'llave3': 3, } # print(mi_diccionario['llave1']) # print(mi_diccionario['llave2']) # print(mi_diccionario['llave3']) población_paises = { 'Argentina': 44_938_712, 'Brasil': 210_147_125, 'Colombia': 50_372_424 } # print(población_paises['Argentina']) # print(población_paises['Bolivia']) # for pais in población_paises.values(): # print(pais) for pais,poblacion in población_paises.items(): print(pais, 'tiene', poblacion, "habitantes") if __name__ == '__main__': run()
65280e232d355a12c8bbb7122a17a0be72f381fd
joseluisquisan/hello-world
/codigocurso/bohemian.py
336
3.9375
4
# def run(): # for i in range(6): # if i == 3: # print("Figarooo") # continue # print("Galileo") def run(): for contador in range(101): if contador % 2 != 0: print("Impar") continue print("Par ", contador, "") if __name__ == '__main__': run()
c56b0a62664f03485da1fb9bd35f119e26dfe008
rajeshwerkushwaha/python_learning
/file_readwrite/file_readwrite.py
720
3.75
4
# read all at one shot f = open('sample.txt', 'r') print(f.read()) # read line by line when file is small f = open('sample.txt', 'r') for line in f: print(line) # read line by line when file is big f = open('sample.txt', 'r') while True: line = f.readline() print(line) if ("" == line): break; # new file create move f = open('sample1.txt', 'x') f.write('This msg writes through f.write()') f = open('sample1.txt', 'r') print(f.read()) # append mode f = open('sample.txt', 'a') f.write('\nThis line written by f.write() in append mode') # write mode f = open('sample2.txt', 'w') f.write('\nThis line written by f.write() in wite mode (overwrite mode)') # delete a file import os os.remove('sample1.txt')
4ca20b2b026a7985dbb4e0fe140c458d87625132
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D8_NeedRevision/Convert_BST_to_Greater_Tree_NeedRevision/Solution_naive.py
1,186
3.859375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from Y2017.TreeNode import TreeNode class Solution(object): #TLEed. Passed 211/212 test cases. #A naive method that wasted the feature of BST. def convertBST(self, root): list=[] self.getAllNode(root,list) list=sorted(list,reverse=True) self.convertTree(root,list) return root """ :type root: TreeNode :rtype: TreeNode """ def getAllNode(self,root,list): if root: list.append(root.val) self.getAllNode(root.left,list) self.getAllNode(root.right,list) def convertTree(self,root,list): if root: val=root.val for num in list: if num>val: root.val+=num if num<=val: break self.convertTree(root.left, list) self.convertTree(root.right, list) t1=TreeNode(5) t2=TreeNode(2) t3=TreeNode(13) t1.left=t2 t1.right=t3 obj=Solution() print(obj.convertBST(t1))
6f8546778e855972ede401231ae059607e306ca2
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D11/Find_Mode_in_Binary_Search_Tree_NeedRevision/Solution_improved_dict.py
887
3.640625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from Y2017.TreeNode import TreeNode class Solution(object): # Runtime: 108ms Beats or equals to 40% (Fastest) def findMode(self, root): if not root: return [] dict = {} self.traverse(root) modeCount = max(dict.values()) return [k for k, v in dict.iteritems() if v==modeCount] def traverse(self, root): if root: dict[root.val] = dict.get(root.val, 0) + 1 self.traverse(root.left) self.traverse(root.right) """ :type root: TreeNode :rtype: List[int] """ # Runtime: ms Beats or equals to % t = TreeNode(2147483647) solution = Solution() print(solution.findMode(t))
0950827093e06c37a71d0b016c73b174b787ce79
AllanWong94/PythonLeetcodeSolution
/Y2017/M9/D5/Increasing_Triplet_Subsequence/Solution.py
875
3.515625
4
# Runtime: 39ms Beats or equals to 55% class Solution(object): def increasingTriplet(self, nums): val1=[] val2=None for i in nums: if not val1 or i>val1[-1]: val1.append(i) if len(val1)==3: return True elif val1: if len(val1)==1: val1[0]=i else: if val1[0]<i<val1[1]: val1[1]=i else: if not val2 or val2>i: val2=i else: val1=[val2,i] val2=None return False """ :type nums: List[int] :rtype: bool """ solution = Solution() print(solution.increasingTriplet([5,1,5,5,2,5,4]))
6d814302839f5517aeb31a243085f1ecf451d1cf
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D19_NeedRevision/Subtree_of_Another_Tree/Solution_naive.py
541
3.546875
4
# Runtime: 442ms Beats or equals to 32% # Reference: https://discuss.leetcode.com/topic/88520/python-straightforward-with-explanation-o-st-and-o-s-t-approaches class Solution(object): def isMatch(self, s, t): if not (s and t): return s is t return s.val == t.val and self.isMatch(s.left, t.left) and self.isMatch(s.right, t.right) def isSubtree(self, s, t): if self.isMatch(s, t): return True if not s: return False return self.isSubtree(s.left, t) or self.isSubtree(s.right, t)
bb101b61facff7835475f521e96043e58ccbcf11
AllanWong94/PythonLeetcodeSolution
/Y2017/M8/D19_NeedRevision/Subtree_of_Another_Tree/Solution.py
1,408
3.890625
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from Y2017.TreeNode import TreeNode #TLEed. class Solution(object): def isSubtree(self, s, t): return self.helper(s,t,False,t) def helper(self,s,t,root_found,origin_t): if root_found: if s and s.val==origin_t.val: if self.helper(s.left,origin_t.left, True, origin_t) and self.helper(s.right,origin_t.right, True, origin_t): return True if (not s and t) or (s and not t): return False if (not s and not t): return True return self.helper(s.left,t.left, True, origin_t) and self.helper(s.right,t.right, True, origin_t) else: if not s or not t: return False if s.val==t.val: return self.helper(s.left, t.left, True, origin_t) and self.helper(s.right, t.right, True, origin_t) return self.helper(s.left, t, False, origin_t) or self.helper(s.right, t, False, origin_t) """ :type s: TreeNode :type t: TreeNode :rtype: bool """ # Runtime: ms Beats or equals to % t1=TreeNode(1) t2=TreeNode(1) t3=TreeNode(1) t1.left=t2 solution = Solution() print(solution.isSubtree(t1,t3))
087a85027a5afa03407fed80ccb82e466c4f46ed
ch-bby/R-2
/ME499/Lab_1/volumes.py
2,231
4.21875
4
#!\usr\bin\env python3 """ME 499 Lab 1 Part 1-3 Samuel J. Stumbo This script "builds" on last week's volume calculator by placing it within the context of a function""" from math import pi # This function calculates the volumes of a cylinder def cylinder_volume(r, h): if type(r) == int and type(h) == int: float(r) float(h) if r < 0 or h < 0: return None # print('you may have entered a negative number') else: volume = pi * r ** 2 * h return volume elif type(r) == float and type(h) == float: if r < 0 or h < 0: return None else: volume = pi * r ** 2 * h return volume else: # print("You must have entered a string!") return None # This function calculates the volume of a torus def volume_tor(inner_radius, outer_radius): if type(inner_radius) == int and type(outer_radius) == int: float(inner_radius) float(outer_radius) if inner_radius < 0 or outer_radius < 0: return None else: if inner_radius > outer_radius: return None elif inner_radius == outer_radius: return None else: r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section volume = (pi * r_circle ** 2) * (2 * pi * r_mid) return volume elif type(inner_radius) == float and type(outer_radius) == float: if r < 0 and h < 0: return None else: if inner_radius > outer_radius: return None elif inner_radius == outer_radius: return None else: r_mid = (inner_radius + outer_radius) / 2 # Average radius of torus r_circle = (outer_radius - inner_radius) / 2 # Radius of donut cross-section volume = (pi * r_circle ** 2) * (2 * pi * r_mid) return volume else: return None if __name__ == '__main__': print(cylinder_volume(3, 1)) print(volume_tor(-2, 7))
c2c12efe187c133fee08b987e911772b0054fcbd
ch-bby/R-2
/ME499/Lab_1/words.py
461
3.765625
4
#!\usr\bin\env python3 """ME 499 Lab 1 Part 5 Samuel J. Stumbo 13 April 2018""" def letter_count(string_1, string_2): count = 0 string_1 = str(string_1).lower() string_2 = str(string_2).lower() for i in string_1: #print(i) # Print for debugging purposes if i == string_2: count += 1 return count if __name__ == '__main__': print(letter_count('supercalafragalisticexpialidocious', 1))
39bebab706b7e5bccee7fe7ae212831fe5279e5e
ch-bby/R-2
/ME499/lab2/filters.py
1,312
3.921875
4
#!/usr/bin/env python3 """ ME 499: Lab 2 Samuel J. Stumbo 20 April 2018 Filters Function This function reads in random data (or any data, really) and normalizes it """ from sensor import * import numpy as np import matplotlib.pyplot as plt def mean_filter(l1, width = 3): unfiltered = [] w = width // 2 for n in l1: unfiltered.append(n) filtered = [] for i in range(w, len(l1)-w): filtered.append(sum(unfiltered[i - w : i + w + 1]) / width) return unfiltered, filtered def median_filter(l1, width=3): filtered = [] w = width for i in range(len(l1) - w + 1): filtered.append(np.median(unfiltered[i: i + w])) return filtered if __name__ == '__main__': data = generate_sensor_data() width = 5 l1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] unfiltered, mean = mean_filter(data, width) median = median_filter(data,width) print_sensor_data(unfiltered, 'unfiltered.txt') print_sensor_data(mean, 'mean.txt') print_sensor_data(median, 'median.txt') # red dashes, blue squares and green triangles plt.plot(range(len(mean)), mean, 'r--', range(len(median)), median, 'g', range(len(data)), data) plt.show() # print(filtered) # print(median_filter(l1, n)) # fin = open('words.txt') # print(fin.readline())
d571d28325d7278964d45a25a4777cf8f121f0ce
ch-bby/R-2
/ME499/Lab4/shapes.py
1,430
4.46875
4
#!/usr/bin/env python3# # -*- coding: utf-8 -*- """ **************************** ME 499 Spring 2018 Lab_4 Part 1 3 May 2018 Samuel J. Stumbo **************************** """ from math import pi class Circle: """ The circle class defines perimeter, diameter and area of a circle given the radius, r. """ def __init__(self, r): if r <= 0: raise 'The radius must be greater than 0!' self.r = r def __str__(self): return 'Circle, radius {0}'.format(self.r) def area(self): return pi * self.r ** 2 def diameter(self): return 2 * self.r def perimeter(self): return 2 * pi * self.r class Rectangle: """ The rectangle class has attributes of a rectangle, perimeter and area """ def __init__(self, length, width): if length <= 0 or width <= 0: raise 'The length and width must both be positive values.' self.length = length self.width = width def __str__(self): return 'Rectangle, length {0} and width {1}'.format(self.length, self.width) def area(self): return self.length * self.width def perimeter(self): return self.length * 2 + self.width * 2 if __name__ == '__main__': c = Circle(1) r = Rectangle(2, 4) shapes = [c, r] for s in shapes: print('{0}: {1}, {2}'.format(s, s.area(), s.perimeter()))
fbe33499711988c0d0f888d1dfc6626fe90c017a
yvvyoon/learn-python
/multi_pro1.py
239
3.640625
4
import time start_time = time.time() def count(name): for i in range(1, 200001): print(f'{name}: {i}') num_list = ['p1', 'p2', 'p3', 'p4'] for num in num_list: count(num) print(f'*** {time.time() - start_time} ***')
79531c1658c717a945851ef9bf19bca4d70d6118
yvvyoon/learn-python
/team-study/generator/generator04.py
988
3.96875
4
class Tree(object): def __init__(self, data=None, left=None, right=None): self.data = data self.left = left self.right = right def inorder(self): if self.left: for x in self.left.inorder(): yield x yield self if self.right: for x in self.right.inorder(): yield x def __iter__(self): return self.inorder() def __repr__(self, level=0, indent=' '): s = level * indent + self.data if self.left: s = f'{s}\n{self.left.__repr__(level+1, indent)}' if self.right: s = f'{s}\n{self.right.__repr__(level+1, indent)}' return s def tree(List): n = len(List) if n == 0: return None i = n / 2 return Tree(List[i], tree(List[:i]), tree(List[i + 1:])) if __name__ == '__main__': t = tree('abcdef') print(t) print() for el in t.inorder(): print(el.data)
9c9ae4a120558d23b1f70f1e581b08cb5112f6cc
soja-soja/LearningHTML
/Python/Session-1.py
565
3.890625
4
print('\n============ Output ===========') # condition if-else a = int(input('please enter A:')) b = int(input('please enter B:')) c = input('enter the operator:') if c == '+': # b == 0 b<0 b>0 b<=0 b>=0 b!=0 print('A+B is: {} '.format(a+b) ) else: print('A-B is: {} '.format(a-b) ) # a = 1 # integer # a = 2 # a = 3 # a = 1.5 # float # a = 'SOJA.ir' # string # a = 'S' # character - char # ctrl + / ---> to commend out a line # '100' 100 # int --> str # 100 --> '100' # str(100) --> '100' # str --> int # '100' --> 100 # int('100') --> 100
b47ed30acdcc89e7fca0545648aca5e0511f9585
xychen1015/leetcode
/offer/27.py
1,014
3.859375
4
# -*- coding: utf-8 -*- # @Time : 2020/9/24 上午11:36 # @Author : cxy # @File : 27.py # @desc: """ 方法一:递归。不需要使用额外的变量存储结果,直接就地进行翻转。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def mirrorTree(self, root: TreeNode) -> TreeNode: if not root: return None root.left,root.right=self.mirrorTree(root.right),self.mirrorTree(root.left) return root """ 方法二:使用栈.先把cur的左右子节点放入到栈中,然后交换cur的左右子节点 """ class Solution: def mirrorTree(self, root: TreeNode) -> TreeNode: if not root: return None stack=[root] while stack: cur=stack.pop() if cur.right: stack.append(cur.right) if cur.left: stack.append(cur.left) cur.left,cur.right=cur.right,cur.left return root
486253055276e69f69bc83f3180f7339908d0c75
xychen1015/leetcode
/offer/59.py
1,469
3.75
4
# -*- coding: utf-8 -*- # @Time : 2020/9/3 下午3:13 # @Author : cxy # @File : 59.py # @desc: """ 由于题目要求max_value、push_back 和 pop_front 的均摊时间复杂度都是O(1)。因此不能直接使用max方法,需要使用一个暂存数组来存放当前元素之后的最大元素的值 """ class MaxQueue: def __init__(self): from collections import deque self.q = deque() self.mx = deque() def max_value(self) -> int: return self.mx[0] if self.mx else -1 """ 依次插入[2,5,3,4,6,6] q:[2], mx:[2] q:[2,5], mx:[5],弹出2并插入5 q:[2,5,3], mx:[5,3],不弹出并插入3 q:[2,5,3,4], mx:[5,4],弹出3并插入4 q:[2,5,3,4,6], mx:[6],弹出4 5并插入6 q:[2,5,3,4,6,6], mx:[6,6],不弹出并插入6,因为6<=6 """ def push_back(self, value: int) -> None: self.q.append(value) while self.mx and self.mx[-1]<value: self.mx.pop() # 当新插入的元素大于暂存数组中的末端元素时,则弹出末端 self.mx.append(value) # 直到大于等于value,则插入到暂存数组中 def pop_front(self) -> int: if not self.q: return -1 ans = self.q.popleft() if ans == self.mx[0]: self.mx.popleft() return ans # Your MaxQueue object will be instantiated and called as such: # obj = MaxQueue() # param_1 = obj.max_value() # obj.push_back(value) # param_3 = obj.pop_front()
3a6a87ea881449029996ce4d5603be93a85854bf
subin97/python_basic
/exercise/gugudan.py
310
3.703125
4
while True: print('구구단 몇 단을 계산할까요(1~9)?') num = int(input()) if num not in range(1, 10): print('구구단 게임을 종료합니다.') break print(f'구구단 {num}단을 계산합니다.') for i in range(1, 10): print(f'{num} X {i} = {num*i}')
8497d12e91e7e5964459332a8cc28ace8e101980
subin97/python_basic
/mycode/10_pythonic/list_comprehension.py
173
3.640625
4
result = [x for x in range(10) if x%2 == 0] print(result) my_str1 = "Hello" my_str2 = "World" result = [i+j for i in my_str1 for j in my_str2 if not (i==j)] print(result)
ea3348c0dd35ba8c60d8dc3b75f04703501931d2
retropleinad/Chess
/pieces/knight.py
1,697
3.828125
4
from pieces.piece import Piece class Knight(Piece): # Inherited constructor # Update the piece value def __init__(self, color, column, row, picture): super().__init__(color, column, row, picture) self.val = 3 # Is the square in a 2 by 3 or a 3 by 2? # Is there a friendly piece in that square? # Otherwise, it can move. def can_move(self, board, column, row): if column >= len(board) or row >= len(board) or column < 0 or row < 0 or \ (board[column][row] is not None and board[column][row].color == self.color): return False elif (self.column + 2 == column and self.row + 1 == row) or \ (self.column + 2 == column and self.row - 1 == row) or \ (self.column - 2 == column and self.row + 1 == row) or \ (self.column - 2 == column and self.row - 1 == row) or \ (self.column + 1 == column and self.row + 2 == row) or \ (self.column + 1 == column and self.row - 2 == row) or \ (self.column - 1 == column and self.row + 2 == row) or \ (self.column - 1 == column and self.row - 2 == row): return True return False # Returns a list of available moves that a piece may make, given a particular board def available_moves(self, board): moves = [] i = 2 while i > -3: j = 2 while j > -3: if self.can_move(board, self.column + i, self.row + j): moves.append((self.column + i, self.row + j)) j -= 1 i -= 1 return moves
4211efe86175e8a6425c117f4869ca5239b15727
ytxka/nowcode-codes
/二叉搜索树的后序遍历序列.py
1,256
3.546875
4
# -*- coding:utf-8 -*- class Solution: def VerifySquenceOfBST(self, sequence): # 二叉搜索树的后序遍历,最后一个元素为root,前面必可以分为两部分 # 一部分(左子树)小于root,一部分(右子树)大于root # 递归判断左右子树 if not sequence: return False if len(sequence) == 1: return True root = sequence[-1] index = 0 while sequence[index] < root: index += 1 # 下面这种for循环写法有误,上述while循环正确 # 问题在于:假设只有左子树,则剩余元素均大于最后一个,则index=0,意为没有左子树,显然不对 # for i in sequence[:-1]: # if i > root: # index = sequence.index(i) # break left = sequence[:index] right = sequence[index:-1] leftIs = True rightIs = True for j in right: if j < root: return False if left: leftIs = self.VerifySquenceOfBST(left) if right: rightIs = self.VerifySquenceOfBST(right) return leftIs and rightIs
82d094ce4f9018cd3f2b6777e68ce691a2436c3e
ytxka/nowcode-codes
/二叉搜索树的第k个结点.py
608
3.765625
4
# -*- coding:utf-8 -*- # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: # 返回对应节点TreeNode def KthNode(self, pRoot, k): # write code here self.res = [] self.MidSearch(pRoot) if 0 < k <= len(self.res): return self.res[k - 1] else: return None def MidSearch(self, root): if not root: return self.MidSearch(root.left) self.res.append(root) self.MidSearch(root.right)
13238ec3b96e2c1297fa1548f14d19860fbe222d
GeeB01/Codigos_guppe
/objetos.py
1,007
4.3125
4
""" Objetos -> São instancias das classe, ou seja, após o mapeamento do objeto do mundo real para a sua representação computacional, devemos poder criar quantos objetos forem necessarios. Podemos pensar nos objetos/instancia de uma classe como variaveis do tipo definido na classe """ class Lampada: def __init__(self, cor, voltagem, luminosidade): self.__cor = cor self.__voltagem = voltagem self.__luminosidade = luminosidade def mostra_cor(self): print(self.__cor) class ContaCorrente: contador = 1234 def __init__(self, limite, saldo): self.__numero = ContaCorrente.contador + 1 self.__limite = limite self.__saldo = saldo ContaCorrente.contador = self.__numero class Usuario: def __init__(self, nome, sobrenome, email, senha): self.__nome = nome self.__sobrenome = sobrenome self.__email = email self.__senha = senha lamp1 = Lampada('qazu', '110', 'aaa') lamp1.mostra_cor()
94c0aa3a85162c6642450b3eb51fbf258b9a2f64
GeeB01/Codigos_guppe
/sistema_de_arquivos_manipulação.py
874
3.578125
4
""" Sistema de Arquivo - manipulação # Descobrindo se um arquivo ou diretorio existe #paths relativos print(os.path.exists('texto.txt')) print(os.path.exists('gb')) print(os.path.exists('gb/gabriel1.py')) #paths absolutos print(os.path.exists('C:\\Users\\Gabriel')) # criando arquivo # forma 1 open('aruivo_teste.txt', 'w').close() # forma 2 open('arquivo2.txt', 'a').close() # forma 3 with open('arquivo3.txt', 'w') as arquivo: pass # criando arquivo os.mknod('aruivo_teste2.txt') os.mknod('C:\\Users\\Gabriel\\PycharmProjects\\guppe\\arquivo_teste3.txt') # criando diretorio os.mkdir('novo') # a função cira um diretorio se este nao existir. Caso exista, teremos FileExistsError # criando multi diretorios os.makedirs('outro/mais/um') """ import os os.rename('frutas2.txt', 'frutas3.txt') os.rename('outro/mais/um/teste.txt', 'outro/mais/um/teste2.txt')
a99fc4de820a1c0ac22c88be6b3ee4317a9234e7
GeeB01/Codigos_guppe
/leitura_de_arquivos.py
561
4.0625
4
""" Leitura de arquivos para ler o conteúdo de um arquivo em Python, utilizamos a função integrada open(), que literalmente significa abrir open() -> Na forma mais simples de utilização nos passamos apenas um parametro de entrada, que neste caso é o caminho para o arquivo à ser lido. Essa função retorna um _io.TextIOWrapper e é com ele que trabalhamos então # Por padrao a função open(), abre o arquivo para leitura. Este arquivo deve existir, ou entao teremos o erro FileNotFoundError """ arquivo = open('pacotes.py') print(arquivo.read())
a5a1bd8efaf5d8bbed35197d34a402acb5a46084
GeeB01/Codigos_guppe
/len_abs_sum_round.py
698
4
4
""" len, abs, sum, round #len len() retorna o tamanho(ou seja, o numeor de itens) de um iteravel print(len('Gabriel')) #abs ela retorna o valor absoluto de um numero inteiro ou real, de forma basica , seria o seu valor real sem o sinal print(abs(-5)) print(abs(3.53)) #sum recebe como parametro um iteravel podendo receber um valor inical e retorna a soma total dos elementos incluindo o valor inicial print(sum([1, 2, 3, 4, 5])) print(sum([1, 2, 3, 4, 5], 10)) #round retorna um numero arredondado para n digito de precisao apos a casa decimal se a precisao nao for informada retrona o inteiro mais proximo da entrada """ print(round(12.123124)) print(round(5.789)) print(round(7.97561254125))
219a68a96463790053489586c1714b7a27f66388
Reiji-A/python_package
/正規表現re/test.py
1,321
3.625
4
import re regex = r"ab+" text = "abbabbabaaabb" pattern = re.compile(regex) matchObj = pattern.match(text) matchObj matchObj = re.match(regex,text) matchObj # matchのサンプルコード data = "abcdefghijklmn" # パターン式の定義(aで始まりcで終わる最短の文字列) pattern = re.compile(r"a.*?c") match_data = pattern.match(data) print(match_data.group()) # searchのサンプルコード # パターン式の定義(dで始まりgで終わる最短の文字列) pattern = re.compile(r"d.*?g") match_data = pattern.search(data) # 一致したデータ print(match_data.group()) # 一致した開始位置 print(match_data.start()) # 一致した終了位置 print(match_data.end()) # 一致した位置を表示 print(match_data.span()) # findallのサンプルコード # パターン式の定義(dで始まりgで終わる最短の文字列) pattern = re.compile(r"d.*?g") match_data = pattern.findall(data) print(match_data) # finditerのサンプルコード # パターン式の定義(dで始まりgで終わる最短の文字列) data = "abcdefghijklmnabcdefghijklmn" pattern = re.compile(r"d.*?g") match_datas = pattern.finditer(data) print(match_datas) for match in match_datas: print(match.group()) print(match.start()) print(match.end()) print(match.span())
2ccfacec48b1716f13ca9bd75dd39008c749b0f4
aryanguptaSG/Data_Structure
/data_structures/dequeue/dequeue_using_array.py
839
3.953125
4
class dequeue(): """docstring for dequeue""" def __init__(self, size=5): self.size = size self.front = self.rear = -1 self.array = size*[None] def pushfront(self,value): if(self.front-1==self.rear): print("dequeue is full") return 0; elif(self.front ==-1): self.front=self.size-1 else: self.front-=1 self.array[self.front]=value print(value," is added in dequeue") print("front is : ",self.front) def pushback(self,value): if(self.rear+1==self.front or self.rear==self.size-1): print("dequeue is full") return 0; else: self.rear+=1 self.array[self.rear]=value print(value," is added in dequeue") print("rear is : ",self.rear) dequ = dequeue() dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10) dequ.pushback(10)
d8e32ee5aed3b8c943bbaf05545f547e2f27d464
AnnKuz1993/Python
/lesson_02/example_03.py
1,893
4.25
4
# Пользователь вводит месяц в виде целого числа от 1 до 12. # Сообщить к какому времени года относится месяц (зима, весна, лето, осень). # Напишите решения через list и через dict. month_list = ['зима', 'весна', 'лето', 'осень'] month_dict = {1: 'зима', 2: 'весна', 3: 'лето', 4: 'осень'} num_month = int(input("Введите номер месяца от 1 до 12 >>> ")) if num_month == 1 or num_month == 2 or num_month == 12: print("Время года для этого месца >>> ", month_dict.get(1)) elif num_month == 3 or num_month == 4 or num_month == 5: print("Время года для этого месца >>> ", month_dict.get(2)) elif num_month == 6 or num_month == 7 or num_month == 8: print("Время года для этого месца >>> ", month_dict.get(3)) elif num_month == 9 or num_month == 10 or num_month == 11: print("Время года для этого месца >>> ", month_dict.get(4)) else: print("Ввели неверное число! Такого месяца не существует!") if num_month == 1 or num_month == 2 or num_month == 12: print("Время года для этого месца >>> ", month_list[0]) elif num_month == 3 or num_month == 4 or num_month == 5: print("Время года для этого месца >>> ", month_list[1]) elif num_month == 6 or num_month == 7 or num_month == 8: print("Время года для этого месца >>> ", month_list[2]) elif num_month == 9 or num_month == 10 or num_month == 11: print("Время года для этого месца >>> ", month_list[3]) else: print("Ввели неверное число! Такого месяца не существует!")
62e23d990a25f1115e87984698d4af54ab11b3e1
AnnKuz1993/Python
/lesson_04/example_06.py
465
3.875
4
# итератор, генерирующий целые числа, начиная с указанного from itertools import count for el in count (3): if el > 10: break else: print(el) # итератор, повторяющий элементы некоторого списка, определенного заранее from itertools import cycle c = 0 for el in cycle("ABBY"): if c > 7: break print(el) c += 1
96cd937cfe7734c8fae5348b53517271e3c59321
AnnKuz1993/Python
/lesson_03/example_01.py
791
4.125
4
# Реализовать функцию, принимающую два числа (позиционные аргументы) и выполняющую их деление. # Числа запрашивать у пользователя, предусмотреть обработку ситуации деления на ноль. def num_division(): try: a = int(input("Введите первое число: ")) b = int(input("Введите второе число: ")) return print("Результат деления первого числа на второе →",a / b) except ZeroDivisionError: return "На 0 делить нельзя!" except ValueError: return "Ввели неверное значение!" num_division()
3bb991b7c0d7cd43ff00f35c15e114792246bc8e
AnnKuz1993/Python
/lesson_01/example_06.py
324
3.953125
4
a = float(input("Введи результат пробежки в 1-ый день: ")) b = float(input("Введи желаемый результат пробежки: ")) day = 0 while a < b: a = a * 1.1 day += 1 print("Ты достигнешь желаемого результата на ",day,"-й день")
1bba11b294f8ab6e4c63481028eeb7ed4ad69f92
AreebaKhalid/ComputerVisionPractis
/Program7Rotations.py
715
3.59375
4
import cv2 import numpy as np image = cv2.imread('./images/input.jpg') height, width = image.shape[:2] #cv2.getRotationMatrix2D(rotation_center_x, rotation_center_y,angle_of_rotation,scale) #angle is anti clockwise #image is cropped by putting scale = 1 #put = .5 it will not crop rotation_matrix = cv2.getRotationMatrix2D((width/2,height/2),90,.5) #new width and height in warp_affine function rotated_image = cv2.warpAffine(image, rotation_matrix,(width,height)) cv2.imshow("Rotated Image",rotated_image) #method-2 image = cv2.imread('./images/input.jpg') rotated_image = cv2.transpose(image) cv2.imshow("Rotated Image - Method 2",rotated_image) cv2.waitKey() cv2.destroyAllWindows()
1d519743918f89d13492af1c920356e056787ddd
pythonclaire/pythonpractice
/financing_assistant.py
3,514
3.625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from sys import exit #终值计算器 def finalassets(): print("信息输入样式举例") print(""" 请输入本金<元>:10000 请输入年化收益率<如5%>:5% 请输入每月追加投入金额<元>:1000 请输入投资年限:30 """) A=int(input("请输入本金<元>:")) r=input("请输入年化收益率<如5%>:") m=int(input("请输入每月追加投入金额<元>:")) n=int(input("请输入投资年限:")) for i in range(1,12*n+1): A=int((A+m)*(1+float(r.strip('%'))/100/12)) if i%12==0: print(f"第{int(i/12)}年总资产:{A}") #达到目标的最低年化收益率 def yield_rate(): print("年化收益率以0.05%递增") print("信息输入样式举例") print(""" 请输入理财目标<万元>:100 请输入本金<元>:10000 请输入每月追加投入金额<元>:1000 请输入投资年限:30 """) g=int(input("请输入理财目标<万元>:")) AA=int(input("请输入本金<元>:")) m=int(input("请输入每月追加投入金额<元>:")) n=int(input("请输入投资年限:")) r=0.005 A=AA while A<g*10000: A=AA for i in range(1,12*n+1): A=int((A+m)*(1+r/12)) r=r+0.005 print(f"最终总资产:{A}") print(f"最低年化收益率:{round((r-0.005)*100,1)}%") #达到目标的最低月投入金额 def monthly_invest(): print("月投入金额以100元递增") print("信息输入样式举例") print(""" 请输入理财目标<万元>:100 请输入本金<元>:10000 请输入年化收益率<如5%>:5% 请输入投资年限:30 """) g=int(input("请输入理财目标<万元>:")) AA=int(input("请输入本金<元>:")) r=input("请输入年化收益率<如5%>:") n=int(input("请输入投资年限:")) m=100 A=AA while A<g*10000: A=AA for i in range(1,12*n+1): A=int((A+m)*(1+float(r.strip('%'))/100/12)) m=m+100 print(f"最终总资产:{A}") print(f"最低月投入金额:{m-100}") def expenditure(): income=int(input("请输入您的月可支配收入: ")) exp={} n=int(input("请输入支出项目数量: ")) print("\n请逐个输入项目及权重(权重之和如超过1,将按占比重新分配)") print(""" 举例: 项目1:投资 权重1:0.4 """) for i in range(1,n+1): item=input(f"项目{i}: ") weight=float(input(f"权重{i}: ")) exp[item]=weight print("\n以下为您各项支出及权重") print(exp) sum=0 for value in exp.values(): sum=sum+value print("\n以下为您各项支出的分配金额:") for key in exp: print(f"{key}:{int(exp[key]/sum*income)}") print("\n") def start(): print("欢迎使用理财小助手!") print("希望能够帮助您达成理财目标,优化支出结构,实现财务自由!") print(""" 理财小助手能够帮助您: 1. 计算固定投资下,最终获得的总资产 2. 计算达成既定理财目标,每月需要的最低投入的金额 3. 计算达成既定理财目标,需要的最低年化收益率 4. 按既定权重,分配月可支配收入 """ ) while True: print("请输入您想咨询的问题编号,输入其他任意内容退出") q=input("> ") if q=='1': finalassets() elif q=='2': monthly_invest() elif q=='3': yield_rate() elif q=='4': expenditure() else: exit(0) start()
393dffa71a0fdb1a5ed69433973afd7d6c73d9ff
neelismail01/common-algorithms
/insertion-sort.py
239
4.15625
4
def insertionSort(array): # Write your code here. for i in range(1, len(array)): temp = i while temp > 0 and array[temp] < array[temp - 1]: array[temp], array[temp - 1] = array[temp - 1], array[temp] temp -= 1 return array
0e81f90bd31a9a378d2d4923176d4705d9d0f84a
jpecci/algorithms
/graphs/bfs.py
1,454
3.734375
4
from collections import deque from sets import Set def bfs(graph, start): explored={} #store the distance queue=deque() queue.append(start) explored[start]=0 while len(queue)>0: tail=queue.popleft() #print "%s -> "%(tail), for head, edge in graph.outBounds(tail).items(): if head not in explored: queue.append(head) explored[head]=explored[tail]+1 return explored def connected_components(graph): count_components=0 components={} visited=Set() # this is across all the bfs calls for node in graph: if node not in visited: # start a new bfs in this component count_components+=1 components[count_components]=1 queue=Queue() queue.put(node) visited.add(node) while not queue.empty(): v=queue.get() for w in graph[v]: if w not in visited: queue.put(w) visited.add(w) components[count_components]+=1 return components if __name__=='__main__': from graph import Graph, Edge, Vertex g=Graph() g.addEdge(Edge(Vertex('s'),Vertex('a')),False) g.addEdge(Edge(Vertex('b'), Vertex('s')),False) g.addEdge(Edge(Vertex('b'), Vertex('c')),False) g.addEdge(Edge(Vertex('c'), Vertex('a')),False) g.addEdge(Edge(Vertex('c'), Vertex('d')),False) print "graph: \n",g start=Vertex('s') dist=bfs(g, start) print "dists:" for to in sorted(dist.items(), key=lambda p:p[1]): print "%s->%s: dist= %d"%(start,to[0],to[1]) #print "components ",connected_components(g)
da3e119bb80133d329bedf3cde0cae09f12d4866
jpecci/algorithms
/graphs/dfs.py
827
3.75
4
from Queue import Queue from sets import Set def dfs(graph, start): explored=set() #store the distance stack=[] stack.append(start) explored.add(start) while len(stack)>0: tail=stack.pop() #print "%s -> "%(tail), for head, edge in graph.outBounds(tail).items(): if head not in explored: stack.append(head) explored.add(head) return explored if __name__=='__main__': from graph import Graph, Edge, Vertex g=Graph() g.addEdge(Edge(Vertex('s'),Vertex('a')),False) g.addEdge(Edge(Vertex('b'), Vertex('s')),False) g.addEdge(Edge(Vertex('b'), Vertex('c')),False) g.addEdge(Edge(Vertex('c'), Vertex('a')),False) g.addEdge(Edge(Vertex('c'), Vertex('d')),False) g.addEdge(Edge(Vertex('e'),Vertex('d')),False) print "graph: \n",g start=Vertex('s') explored=dfs(g, start) print explored
dc1116924017c9359798f1bb89e5f12424d21a93
jpecci/algorithms
/sorting/bubblesort.py
309
4
4
def swap(a,i,j): temp=a[i] a[i]=a[j] a[j]=temp def bubble_sort(a): for i in range(len(a)): swapped=False for j in range(1, len(a)-i): if a[j-1]>a[j]: swap(a, j-1, j) swapped=True #print a if not swapped: break if __name__=="__main__": v=[0,5,2,8,3,4,1] bubble_sort(v) print v
4af657b9bc471f8e6750e3c263e1a4ec43c5086a
vonkoper/pp3
/zadania domowe/trojkat.py
807
3.84375
4
''' Napisać program który sprawdzi czy z podanych przez użytkownika długości boków jest możliwość stworzenia trójkąta i oblicza jego pole. ''' a=float(input("Podaj dlugosc pierwszego boku trojkata: ")) b=float(input("Podaj dlugosc drugiego boku: ")) c=float(input("Podaj dlugosc trzeciego boku: ")) dlugosci_bokow = [a, b, c] x=max(dlugosci_bokow) dlugosci_bokow.remove(x) print(dlugosci_bokow) if sum(dlugosci_bokow) > x: answer=input("Z takich odcinkow da sie zbudowac trojkat, czy chcesz policzyc jego powierzchnie? (y/n) ") if answer == "y": ob=0.5*(a+b+c) pole=(ob*(ob-a)*(ob-b)*(ob-c))**0.5 print("Pole trojkata wynosi: ", pole) if answer == "n": print("Koniec") else: print("Z takich odcinkow nie da sie zbudowac trojkata.")
1862fd92995dbb1f72b17543ba52fa53c1c65e82
Czarne-Jagodki/labs
/lab1/ex1.py
4,802
4.4375
4
def print_matrix(matrix): """ Function shows a matrix of neighbourhood of graph. :param list: it's a not empty array of arrays :return: None """ i = 0 for row in matrix: i = i + 1 print(i, end='. ') print(row) def print_list(list): """ Function shows a list of neighbourhood of graph. It show appropriate vertex and other vertexes connected with it :param list: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge :return: None """ for key, value in list.items(): print(key, end=' -> ') print(value) neighbour_list = { 1 : [2, 5], 2 : [1, 3, 5], 3 : [2, 4], 4 : [3, 5], 5 : [1, 2, 4] } def from_list_to_matrix_neighbour(list): """ Function converts neighbourhood list to neighbourhood matrix :param list: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge :return: array of arrays which represents graph """ matrix = [] length = len(list) for elements in list.values(): row = [] for i in range(1, length + 1): if i in elements: row.append(1) else : row.append(0) matrix.append(row) print_matrix(matrix) return matrix #from_list_to_matrix_neighbour(neighbour_list) def from_matrix_neighbour_to_list(matrix): """ Function converts neighbourhood matrix to neighbourhood list :param matrix: not empty array of arrays which represents graph :return: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge """ list = {} i = 0 for row in matrix: i += 1 row_list = [] lenght = len(row) for j in range(lenght): if row[j] == 1: row_list.append(j + 1) list[i] = row_list return list #from_matrix_neighbour_to_list(from_list_to_matrix_neighbour(neighbour_list)) def transpone_matrix(matrix): """ Function to transpone matrix It's needed, beceuse functions associated with incidence returned not appropriate results :param matrix: not empty array of arrays :return: array of arrays but transponed """ import numpy as np n = np.matrix(matrix) n = n.transpose() length = len(n) new_matrix = [] n = np.array(n) for row in n: new_matrix.append(row) return new_matrix def from_list_to_incidence_matrix(list): """ Function converts list of neighbourhood to incidence matrix :param list: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge :return: it's a array of arrays which represents incidence matrix of graph """ matrix = [] for key, value in list.items(): ranger = key #ranger check if we do not use element used # in previous iterations to prevent from doubling same row for elem in value: if ranger < elem: row = [0] * len(list) row[key - 1] = 1 row[elem - 1] = 1 matrix.append(row) #print_matrix(matrix) matrix = transpone_matrix(matrix) return matrix print_matrix(from_list_to_incidence_matrix(neighbour_list)) def from_incidence_matrix_to_list(matrix): """ Function converts incidence matrix to list of neighbourhood :param matrix: it's a not empty array of arrays represents incidence matrix of graph, the matrix must be transponed on the input if it does not become from functions from this module The best way to do it is by our previous function :return: it's a dictionary: keys are numbers of graph vertex and values are lists of other vertexes connected with them by edge """ matrix = transpone_matrix(matrix) list = {} for row in matrix: i = -1 j = -1 for k in range(len(row)): if row[k] == 1: if i != -1: j = k + 1 else: i = k + 1 if i in list: list[i].append(j) else: list[i] = [j] if j in list: list[j].append(i) else: list[j] = [i] l = {} for key in sorted(list): l[key] = list[key] list = l return list print_list(from_incidence_matrix_to_list(from_list_to_incidence_matrix(neighbour_list)))
39012923982f1cca9660d1cea01faac7cef24257
cw02048/python-numpy-pandas
/test4.py
368
3.96875
4
# -*- coding: utf-8 -*- """ Created on Thu Nov 21 19:19:18 2019 @author: cw020 """ def main(): n_list = [] n = int(input()) i = 0 while i < n: tmp = input() n_list.append(tmp[0:len(tmp)-3]) i += 1 for n in sorted(n_list): print(n) main()
3b087e39202ceefc8516e889161b06de68fd45d3
Anastasijap91/RTR105
/test20191010.py
307
3.8125
4
inp = raw_input("Enter a number between 0.0 and 1.0:") score = float(inp) if (score >=1.0): print("Jus nepildat instrukcijas:") exit() elif (score >=0.9): print("A") elif (score >=0.8): print("B") elif (score >=0.7): print("C") elif (score>=0.6): print("D") else: print("F")
a57688d3afbc2a044eae489a2a475db55bddbfe3
orcl/coding
/algorithm/Stack/queueWithStack/queueWithStack.py
670
3.828125
4
class Queue: #initialize your data structure here. def __init__(self): self.inbox = [] self.outbox = [] #@param x, an integer #@return nothing def push(self,x): self.inbox.append(x) #@return nothing def pop(self): if len(self.outbox) == 0: while len(self.inbox) > 0: self.outbox.append(self.inbox.pop()) self.outbox.pop() #@return an integer def peek(self): if len(self.outbox) == 0: while len(self.inbox) > 0: self.outbox.append(self.inbox.pop()) return self.outbox[len(self.outbox)-1] #@return an boolean def empty(self): return len(self.inbox) == 0 and len(self.outbox) == 0
5b9f9de8f78a512a5a023539fbe770e54c0679e6
orcl/coding
/algorithm/Stack/stackWithQueue/stackWithQueues.py
1,805
3.96875
4
#!/usr/bin/python # # class Stack: #initialize your data structure here. def __init__(self): self.queue1 = [] self.queue2 = [] #@param x, an integer #@return nothing def push(self,x): if not self.queue1: self.queue2.append(x) else: self.queue1.append(x) #@return nothing def pop(self): size = 0 if not self.queue1: #queue1 is empty, shift queue2 to queue1, remove the last from queue2 tmp = 0 size = len(self.queue2) while tmp < size - 1: self.queue1.append(self.queue2.pop(0)) tmp = tmp + 1 self.queue2.pop(0) else: #queue2 is empty, shift queue1 to queue2, remove the last from queue1 tmp = 0 size = len(self.queue1) while tmp < size - 1: self.queue2.append(self.queue1.pop(0)) tmp = tmp + 1 self.queue1.pop(0) #@return an integer def top(self): result = 0 size = 0 if not self.queue1: #queue1 is empty, shift queue2 to queue1, remove the last from queue2 tmp = 0 size = len(self.queue2) while tmp < size - 1: self.queue1.append(self.queue2[0]) self.queue2.pop(0) tmp = tmp + 1 result = self.queue2[0] self.queue2.pop(0) self.queue1.append(result) else: #queue2 is empty, shift queue1 to queue2, remove the last from queue1 tmp = 0 size = len(self.queue1) while tmp < size -1: self.queue2.append(self.queue1[0]) self.queue1.pop(0) tmp = tmp + 1 result = self.queue[0] self.queue1.pop(0) self.queue2.append(result) return result #@return an boolean def empty(self): return len(self.queue1) == 0 and len(self.queue2) == 0 def main(): print "hello" if __name__ == "__main__": main()
730901965676d61fb26179be80b1e8ab0a6bbcc9
ryankapler/Statbook
/Rando.py
355
3.875
4
#Random number generator #to be done amount = raw_input("How many random numbers do you need: ") Num_max = raw_input("What is the max value you need: ") Num_min = raw_input("What is the min value you need: ") num_list = [] from random import randint for i in range(int(amount)): num_list.append(randint(int(Num_min), int(Num_max))) print num_list
81bf34bd0e8841eb9dba5da8b1c2cfc8005cfb24
vagerasimov-ozn/python18
/Lessons/lesson 6/class_testing/AninimSurvey.py
738
3.53125
4
class AnonimSurvey: """Собирает анонимные ответы на опросник""" def __init__(self,question): """Содержит вопрос, и подготавливает список для ответа""" self.question = question self.responses = [] def show_question(self): """Показать вопрос""" print(self.question) def store_response(self, new_response): """Сохраняет у нас ответ""" self.responses.append(new_response) def show_results(self): print("результаты нашего опроса следующие:") for response in self.responses: print(f"- {response}")
5b550f916aa21eb985c444582751b57c3baf9ec6
vagerasimov-ozn/python18
/test.py
149
3.515625
4
spi = ['volvo','suzuki','bmv'] #for i in range(5): # print(barsuk) #for i in range(len(spi)): # print(spi[i]) for car in spi: print(car)
fa021815ff156a454f6f8a2c18fa7720aa536d95
vagerasimov-ozn/python18
/rusruletka.py
624
3.640625
4
# Давайте напишем программу русской рулетки import random amount_of_bullets = int(input("Сколько патронов? ")) baraban = [0,0,0,0,0,0] # 0 - пустое гнездо # 1 - гнездо с патроном for i in range(amount_of_bullets): baraban[i] = 1 print("Посмотрите на барабан", baraban) how_much = int(input("сколько раз вы собираетесь нажать на курок? ")) for i in range(how_much): random.shuffle(baraban) if baraban[0] == 1: print("бабах") else: print("щелк")
3530861eb47f9b665eb10a3ddc24f65c886f7288
rihu897/study-03-desktop-01-master
/search.py
1,072
3.578125
4
import pandas as pd import eel ### デスクトップアプリ作成課題 ### 課題6:CSV保存先をHTML画面から指定可能にする def kimetsu_search(word, csv): # トランザクション開始 try : # 検索対象取得 df=pd.read_csv("./" + csv) source=list(df["name"]) # 検索結果 result = "" # 検索 if word in source: result = "『{}』はあります".format(word) else: result = "『{}』はありません".format(word) # 追加 #add_flg=input("追加登録しますか?(0:しない 1:する) >> ") #if add_flg=="1": source.append(word) # 検索結果をコンソールに出力 print(result) # CSV書き込み df=pd.DataFrame(source,columns=["name"]) df.to_csv("./" + csv,encoding="utf_8-sig") print(source) except : result = "ERROR:CSVファイルが見つかりません" # 検索結果を返却 return result
4e50b816c598d0e1b226da7a067cf5cd7cd0764e
ijekel2/projects
/StoneQuest/StoneQuest/scenes/Introduction.py
921
3.75
4
from sys import exit class Introduction(object): def enter(self): ## ## Print the game title and description. print("\n\n\n\n\n\n\n\n\n\n") print(" *****************") print(" ** STONE QUEST **") print(" *****************") print("----------------------------------------------------------------------") print("In this thrilling adventure, you will guide Harry, Ron, and Hermione") print("through several deadly challenges in a quest to save the Sorcerer's") print("Stone from the clutches of the evil and power-hungry Severus Snape.") print("----------------------------------------------------------------------\n") ## ## Ask the user if they want to play the game. print("Would you like to play?") answer = input("[y/n]> ") if answer == "y": return 'Fluffy' else: print("Goodbye!") exit(1)
b56b3f5d3c9b9ffd5aaee009288e30f908045249
ijekel2/projects
/StoneQuest/StoneQuest/scenes/MirrorOfErised.py
5,185
3.75
4
class MirrorOfErised(object): def enter(self): ## ## Print the introductory narrative for Level 6 print("\n") print(" *************************************") print(" ** LEVEL SIX: THE MIRROR OF ERISED **") print(" *************************************") print("----------------------------------------------------------------------") print("You, Harry, having passed through the flames, find yourself standing") print("at the top a staircase that runs around the small chamber as if ") print("cajoling all potentional occupants to descend into the center of the ") print("room and toward the dangers that await. Indeed at the foot of the") print("stairs you see the profile of a full grown man standing transfixed") print("before a beautiful yet terrible full length mirror. However, moving") print("forward, you observe not the greasy visage of the long-expected Snape,") print("but the lanky form of Professor Quirrel, his eyes staring madly into") print("the mirror, and his turban quivering with frustration. \n") print("\"Ah! The ever-meddlesome Potter has arrived at last! Just as you") print("predicted, my master. But now... how to obtain the stone?!\"\n") print("You are not sure who Quirrell is talking to, but you are filled with") print("righteous indignation upon discoving the true identity of your enemy.\n") print("\"QUIRREL! You murderous snake,\" you begin as you descend the steps.") print("\"How I have desired to meet you face to face, to be the instrument ") print("of your comeuppance! Too long have you oppressed the weak and gorged") print("yourself on the fear of the powerless! Too long have you sipped the") print("blood of unicorns and wiped your lips with the lush velvet of your") print("sinister turban! TODAY THIS ENDS!\"\n") input("Press Enter to continue...") print("") print("Quirrell is temporarily stunned by your hitherto unsuspected fiery") print("eloquence. You take the opportunity to push him aside and plant") print("yourself firmly in front of the mirror.\n") print("You recognize this mirror from your previous nighttime jaunts around") print("the castle. It is the Mirror of Erised, and to those who gaze into") print("its depths it reflects visions of their hearts' deepest desires.") print("As you position yourself in front of the mirror, you see a reflected") print("Harry placing the Sorcerer's Stone into his pocket. You feel an") print("object in your own pocket that certainly was not there a moment") print("before.\n") print("Quirrell's face changes slowly from surprise to cunning curiosity.") print("You realize that you have obtained the stone, but now you must invent") print("a convincing lie to tell Quirrell when he asks you what you have seen.") print("Luckily, Dumbledore forsaw that the savior of the stone would need to") print("furnish a quality fib. You see writing appear in the mirror:\n") print(" LSMFYE OLEOWN FOAI COSSK HKCIT ESE LONGHDI IRAP\n") print("\"What do you see in the mirror, boy?\"") print("----------------------------------------------------------------------\n") ## ## Get the user's input in response to Quirrell's question.' print("Respond to Quirrell with a convincing lie. Make sure to use correct") print("punctuation so as not to arouse suspicion.") lie = input("[fib]>") if lie == "I see myself holding a pair of thick, woolen socks.": print("----------------------------------------------------------------------") print("Quirrell is entirely convinced, but suddenly you hear a high, cold") print("voice emanating from his turban.\n") print("\"He liieeeesss!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'Voldemort' elif "," not in lie: print("----------------------------------------------------------------------") print("Quirrell is a stickler for punctuation, and your missing comma rouses") print("his suspicion.\n") print("\"Turn out your pockets, Potter!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'DeathToChess' elif "." not in lie: print("----------------------------------------------------------------------") print("Quirrell is a stickler for punctuation, and your missing period rouses") print("his suspicion.\n") print("\"Turn out your pockets, Potter!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'DeathToChess' else: print("----------------------------------------------------------------------") print("Quirrell does not find your lie plausible and his suspicion is roused.\n") print("\"Turn out your pockets, Potter!\"") print("----------------------------------------------------------------------\n") input("Press Enter to continue...") return 'DeathToChess'
ffc720c4cc661893ee61c92899e255f3a093ef24
DimmeGz/green_lantern
/lantern/tdd/lonely_robot.py
4,943
3.765625
4
class Asteroid: def __init__(self, x, y): self.x = x self.y = y class Robot: compass = ['N', 'E', 'S', 'W'] def __init__(self, x, y, asteroid, direction, obstacle): self.x = x self.y = y self.asteroid = asteroid self.direction = direction self.obstacle = obstacle self.health = 100 self.battery = 100 if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise MissAsteroidError('The robot flew beside asteroid') if self.x == obstacle.x and self.y == obstacle.y: raise ObstacleCrashError('The robot crashed into an obstacle') def turn_left(self): if self.direction in self.compass: self.battery -= 1 self.battery_check() self.direction = self.compass[self.compass.index(self.direction) - 1] def turn_right(self): if self.direction in self.compass: self.battery -= 1 self.battery_check() self.direction = self.compass[(self.compass.index(self.direction) + 1) % 4] def battery_check(self): if self.battery == 0: raise LowBatteryError('Battery is empty') def move_forward(self): move_ffwd_dict = {'W': (self.x - 1, self.y), 'E': (self.x + 1, self.y), 'S': (self.x, self.y - 1), 'N': (self.x, self.y + 1)} self.x, self.y = move_ffwd_dict[self.direction] self.battery -= 1 self.battery_check() if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise RobotCrashError('The robot fell down from the asteroid') if self.x == self.obstacle.x and self.y == self.obstacle.y: self.health -= 10 if self.health == 0: raise RobotCrashError('Robot is destroyed') self.move_backward() self.forward_detour() def forward_detour(self): if (self.direction == 'N' and self.x != self.asteroid.x) or \ (self.direction == 'E' and self.y != 0) or \ (self.direction == 'S' and self.x != 0) or \ (self.direction == 'W' and self.y != self.asteroid.y): self.turn_right() self.move_forward() self.turn_left() for _ in range(2): self.move_forward() self.turn_left() self.move_forward() self.turn_right() else: self.turn_left() self.move_forward() self.turn_right() for _ in range(2): self.move_forward() self.turn_right() self.move_forward() self.turn_left() def move_backward(self): move_back_dict = {'W': (self.x + 1, self.y), 'E': (self.x - 1, self.y), 'S': (self.x, self.y + 1), 'N': (self.x, self.y - 1)} self.x, self.y = move_back_dict[self.direction] self.battery -= 1 self.battery_check() if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise RobotCrashError('The robot fell down from the asteroid') if self.x == self.obstacle.x and self.y == self.obstacle.y: self.health -= 10 if self.health == 0: raise RobotCrashError('Robot is destroyed') self.move_forward() self.backward_detour() def backward_detour(self): if (self.direction == 'N' and self.x != 0) or \ (self.direction == 'E' and self.y != self.asteroid.y) or \ (self.direction == 'S' and self.x != self.asteroid.x) or \ (self.direction == 'W' and self.y != 0): self.turn_right() self.move_backward() self.turn_left() for _ in range(2): self.move_backward() self.turn_left() self.move_backward() self.turn_right() else: self.turn_left() self.move_backward() self.turn_right() for _ in range(2): self.move_backward() self.turn_right() self.move_backward() self.turn_left() def self_destroy(self): del self try: self except NameError: raise RobotCrashError('Robot is self destroyed') class Obstacle: def __init__(self, x, y, asteroid): self.x = x self.y = y self.asteroid = asteroid if self.x > self.asteroid.x or self.y > self.asteroid.y or self.x < 0 or self.y < 0: raise MissAsteroidError('Obstracle is not on asteroid') class MissAsteroidError(Exception): pass class RobotCrashError(Exception): pass class ObstacleCrashError(Exception): pass class LowBatteryError(Exception): pass