blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
8124f901f1650f94c89bdae1eaf3f837925effde
ravalrupalj/BrainTeasers
/Edabit/Balancing_Scales.py
944
4.5
4
#Balancing Scales #Given a list with an odd number of elements, return whether the scale will tip "left" or "right" based on the sum of the numbers. The scale will tip on the direction of the largest total. If both sides are equal, return "balanced". #The middle element will always be "I" so you can just ignore it. #Assume the numbers all represent the same unit. #Both sides will have the same number of elements. #There are no such things as negative weights in both real life and the tests! def scale_tip(lst): t=len(lst)//2 l= sum(lst[0:t]) r=sum(lst[t+1:]) if l>r: return 'left' elif l<r: return 'right' else: return 'balanced' print(scale_tip([0, 0, "I", 1, 1])) #➞ "right" # 0 < 2 so it will tip right print(scale_tip([1, 2, 3, "I", 4, 0, 0])) #➞ "left" # 6 > 4 so it will tip left print(scale_tip([5, 5, 5, 0, "I", 10, 2, 2, 1])) #➞ "balanced" # 15 = 15 so it will stay balanced
05209aa3f4105d4265090e6928e919d40186dc7d
j-scull/Python_Data_Structures
/priority_queue.py
7,890
4
4
from empty import Empty from positional_list import PositionalList class PriorityQueue: """ Abstract base class for priority queue implementations """ #------------------------------------------------------------------- class _Item: """ Composite design pattern - lightweight class stores access count _key: the access count _value: the value stored by the item """ __slots__ = '_key', '_value' def __init__(self, k, v): self._key = k self._value = v def __lt__(self, other): return self._key < other._key #------------------------------------------------------------------- def is_empty(self): """ return: True if the Priority Queue is empty, false otherwise """ return len(self) == 0 #------------------Concrete Implementations------------------------------ class UnsortedPriorityQueue(PriorityQueue): """ An implementstion of a PriorityQueue Store items in an unsorted list Requires searching the entire list when accessing items """ def __init__(self): """ Creates an empty PriorityQueue """ self._data = PositionalList() def __len__(self): """ returns: the number of items in the PriorityQueue """ return len(self._data) def add(self, key, value): """ Adds a key-value pair to the PriorityQueue """ self._data.add_last(self._Item(key, value)) def _find_min(self): """ Non-public utility method returns: the item with the minimum key """ if self.is_empty(): raise Empty('Priority Queue is empty') minimum = self._data.first() walk = self._data.after(minimum) while walk is not None: if walk.element() < minimum.element(): # __lt__ is implemented by the PriorityQueue class minimum = walk walk = self._data.after(walk) return minimum def min(self): """ returns: the (k,v) tuple with the minimum key, without removing it """ p = self._find_min() item = p.element() return (item._key, item._value) def remove_min(self): """ removes the minimum (k,v) tuple from the priority queue returns: the (k,v) tuple """ p = self._find_min() item = self._data.delete(p) # PositionalList removes and returns item return (item._key, item._value) #-------------------------------------------------------------------------------- class SortedPriorityQueue(PriorityQueue): """ Implementation of a PriorityQueue using a sorted PositionalList Adds items to the list in order """ def __init__(self): """ Creates an empty PriorityQueue """ self._data = PositionalList() def __len__(self): """ returns: the number of items in the PriorityQueue """ return len(self._data) def add(self, key, value): """ Adds a key-value pair to the PriorityQueue """ new_item = self._Item(key, value) walk = self._data.last() while walk is not None and new_item < walk.element(): walk = self._data.before(walk) if walk is not None: self._data.add_after(walk, new_item) else: self._data.add_first(new_item) def min(self): """ returns: the (k,v) tuple with the minimum key, without removing it """ if self.is_empty(): raise Empty('Priority Queue is empty') p = self._data.first() item = p.element() return (item._key, item._value) def remove_min(self): """ removes the minimum (k,v) tuple from the priority queue returns: the (k,v) tuple """ if self.is_empty(): raise Empty('Priority Queue is empty') p = self._data.first() item = self._data.delete(p) return (item._key, item._value) #---------------------------------------------------------------------------------- class HeapPriorityQueue(PriorityQueue): """ An implementation of a Priorrity Queue using an array based heap data structure ------------------------------------------------------------------------------- uses the _Item class from PriorityQueue """ #--------Non-Public methods------- # 0 # / \ # 1 2 # / \ / \ # 3 4 5 6 def _parent(self, i): return (i - 1) // 2 def _left(self, i): return i * 2 + 1 def _right(self, i): return i * 2 + 2 def _has_left(self, i): return self._left(i) < len(self._data) def _has_right(self, i): return self._right(i) < len(self._data) def _swap(self, i, j): """ Swaps the the elements stored at indexex i and j """ self._data[i], self._data[j] = self._data[j], self._data[i] def _upheap(self, i): """ Performed after inserting a new element into the heap Restores heap-order property """ parent = self._parent(i) if i > 0 and self._data[i] < self._data[parent]: self._swap(i, parent) self._upheap(parent) def _downheap(self, i): """ Performed after removing the minimum element from the heap Restores heap-order property """ if self._has_left(i): left = self._left(i) smallest = left if self._has_right(i): right = self._right(i) if self._data[right] < self._data[left]: smallest = right if self._data[smallest] < self._data[i]: self._swap(i, smallest) self._downheap(smallest) def _heapify(self): """ Performs bottom-up construction for a new heap """ # 0 0 X # / \ / \ / \ # 0 0 X X X X # / \ / \ / \ / \ / \ / \ # X X X X X X X X X X X X start = self._parent(len(self) - 1) # starts at the parent of the last leaf for i in range(start, -1, -1): self._downheap(i) #--------Public methods----------- def __init__(self, contents=()): """ Create an new Priority Queue If contents is given creates a heap using bottom up construction, otherwise creates an empty heap contents: an iterable sequence of (k,v) tuples """ self._data = [self._Item(k, v) for k, v in contents] if len(self._data) > 1: self._heapify() def __len__(self): """ returns: the number of elements in the priority queue """ return len(self._data) def add(self, key, value): """ Adds a key-value pair to te priority queue """ self._data.append(self._Item(key, value)) self._upheap(len(self._data) - 1) def min(self): """ returns: the key-value pair with the minimum key without removal """ if self.is_empty(): raise Empty('Priority Queue is empty') item = self._data[0] return (item._key, item._value) def remove_min(self): """ returns: the key-value pair with the minimal key removed from the priority queue """ if self.is_empty(): raise Empty('Priority Queue is empty') self._swap(0, len(self._data) - 1) item = self._data.pop() self._downheap(0) return (item._key, item._value)
d183ee49cc90ee2ede5a0d6383404edd9f08a4a8
nicolaespinu/LightHouse_Python
/spinic/Day14.py
1,572
4.15625
4
# Challenge # Dot's neighbour said that he only likes wine from Stellenbosch, Bordeaux, and the Okanagan Valley, # and that the sulfates can't be that high. The problem is, Dot can't really afford to spend tons # of money on the wine. Dot's conditions for searching for wine are: # # Sulfates cannot be higher than 0.6. # The price has to be less than $20. # Use the above conditions to filter the data for questions 2 and 3 below. # # Questions: # # 1. Where is Stellenbosch, anyway? How many wines from Stellenbosch are there in the entire dataset? # 2. After filtering with the 2 conditions, what is the average price of wine from the Bordeaux region? # 3. After filtering with the 2 conditions, what is the least expensive wine that's of the highest quality # from the Okanagan Valley? # # Stretch Question: # What is the average price of wine from Stellenbosch, according to the entire unfiltered dataset? # Note: Check the dataset to see if there are missing values; if there are, fill in missing values with the mean. import pandas as pd df = pd.read_csv('winequality-red_2.csv') df = df.drop(columns = ['Unnamed: 0']) df.head() print('Q1 of wines from Stellenbosch:',df[df['region'].str.contains('Stellenbosch')].shape[0]) filterDF = df[(df['sulphates']<=0.6) & (df['price']<20)] print("Q2 avg price of wines from Bordeaux: ",filterDF[filterDF['region']=='Bordeaux']['price'].mean()) print(filterDF[filterDF['region'].str.contains('Okanagan Valley')].sort_values(['quality','price'],ascending=[False,True])) # 1. 35 Wines # 2 .$11.30 # 3. Wine 1025
61a217a71284900e86f9453b52db9474189f4649
nicolaespinu/LightHouse_Python
/spinic/Day3.py
2,399
3.96875
4
# Challenge # Dot has some specific rules for what they want to change in the shopping list: # # They hate oak wood, and prefer maple. # They want to paint all the rooms blue except the kitchen, which they want to paint white. old_blueprint = { "Kitchen": ['Dirty', 'Oak', "Damaged", "Green"], "Dining Room": ['Dirty', 'Pine', 'Good Condition', 'Grey'], "Living Room": ['Dirty', 'Oak', 'Damaged', 'Red'], "Bedroom" : ["Clean", 'Mahogany', 'Good Condition', 'Green'], "Bathroom": ["Dirty", 'White Tile', 'Good Condition','White'], "Shed" : ['Dirty', "Cherry", "Damaged", "Un-painted"] } shopping_list = ['20 x Oak Plank', '20 x Oak Plank', '20 x Cherry Plank', 'White Paint', 'White Paint', 'White Paint'] # Note: The blueprint above is in a dictionary format and we won't be needing to work with dictionaries # in the challenge, use the blueprint as reference only. # # Use python's pop(), insert(), and append() list functions to change the shopping_list above so that it reflects # the right materials needed. # # The list should be ordered by wood types first, then paint types. example_shopping_list = ['wood type in room A', 'wood type in room b','paint type in room a','paint type in room b'] # Create a paint_list list from the new_shopping_list list using the built in python list indexing ability. shopping_list = ['20 x Oak plank', '20 x Oak Plank', '20 x Cherry Plank', 'White Paint', 'White Paint', 'White Paint'] #Solution new_shopping_list = shopping_list print(new_shopping_list) new_shopping_list.pop(-1) print(new_shopping_list) new_shopping_list.pop(-1) print(new_shopping_list) new_shopping_list.append('Blue Paint') print(new_shopping_list) new_shopping_list.append('Blue Paint') print(new_shopping_list) new_shopping_list.append('Blue Paint') print(new_shopping_list) new_shopping_list.append('Blue Paint') print(new_shopping_list) new_shopping_list.append('Blue Paint') print(new_shopping_list) new_shopping_list.pop(0) new_shopping_list.insert(0, "20 x Maple Plank") print(new_shopping_list) new_shopping_list.pop(1) new_shopping_list.insert(1, "20 x Maple Plank") print(new_shopping_list) new_shopping_list = ['20 x Maple Plank', '20 x Maple Plank', '20 x Cherry Plank', 'White Paint', 'Blue Paint','Blue Paint','Blue Paint','Blue Paint', 'Blue Paint'] # Solution paint_list = new_shopping_list[3:] print(paint_list)
3779b5ef15b56a4fb9df314e93335786abb5743e
xylo99/tic-tac-toe-program
/server/game/tttg.py
4,484
3.5
4
from game.tttg_menu_printer import mp_print_menu class TTTGame: def __init__(self): self.N = 3 self.CIRCLE = 1 self.EMPTY = 0 self.CROSS = 2 self.board = [[self.EMPTY for i in range(self.N)] for i in range(self.N)] self.AI_row = 0 self.AI_col = 0 def clear_board(self): for i in range(self.N): for j in range(self.N): self.board[i][j] = self.EMPTY def draw_border(self): boarder = " " * 14 for i in range(self.N): if i == self.N - 1: boarder += "---" else: boarder += "----" boarder += " \n" return boarder def make_move(self, row, col, seed): self.board[row][col] = seed def is_cell_empty(self, row, col): return self.board[row][col] == self.EMPTY def ai_move(self): found = False for i in range(self.N): for j in range(self.N): if self.board[i][j] == self.EMPTY: self.board[i][j] = self.CROSS self.AI_row = i self.AI_col = j found = True break if found: break def get_ai_row(self): return self.AI_row def get_ai_col(self): return self.AI_col def print_board(self, ): tab = " " * 15 # Draw columns for i in range(self.N): tab += str(i + 1) + " " tab += "\n" tab += self.draw_border() row_char = 'A' for i in range(self.N): tab += " " + row_char tab += " | " for j in range(self.N): if self.board[i][j] == self.CROSS: tab += "X" + " | " elif self.board[i][j] == self.EMPTY: tab += " " + " | " else: tab += "O" + " | " tab += "\n" row_char = chr(ord(row_char) + 1) # increase row char from A -> B -> C self.draw_border() tab += "" return tab def check_for_win(self, row, col, seed): # Return true if a row of 'seed' was played. counter = 0 for i in range(self.N): if self.board[row][i] == seed: counter += 1 if counter == 3: return True else: break # Return true if a column of 'seed' was played. counter = 0 for i in range(self.N): if self.board[i][col] == seed: counter += 1 if counter == 3: return True else: break # Return true if diagonal/anti-diagonal of 'seed' was played. counter = 0 win = True for i in range(self.N): for j in range(self.N): if i == j: if self.board[i][j] == seed: counter += 1 if counter == 3: return True else: win = False break if not win: break win = True counter = 0 for i in range(self.N): for j in range(self.N): if i + j == 2: if self.board[i][j] == seed: counter += 1 if counter == 3: return True else: win = False break if not win: break return win def is_valid_move(self, move): if len(move) != 2: return False if move[0] != 'a' and move[0] != 'b' and move[0] != 'c': return False if int(move[1]) > 3 or int(move[1]) < 1: return False # calculate row from the unicode equivalent of the row char used # Find the distance the desired row (move[0]) from the first row (A) # values are either 0, 1, or 2. if not self.is_cell_empty(ord(move[0]) - ord('a'), int(move[1]) - 1): return False return True @staticmethod def is_draw(move_num): return move_num == 6 @staticmethod def print_menu(client_start): return mp_print_menu(client_start)
c6fe659f4f5f7b6e01ef90ce5443eeed3e8d8ccb
Anagabsoares/AdaPrecourse
/variableIO.py
416
3.703125
4
# Variable and IO (input/ooutput) car = "lexus" # input anotherCar = input("What is your car name?") print(f"cool! My favorite car is {car} and yours is {anotherCar}") #CONSTANTS - a type of variable whose CANNOT be changed. - containers values that cannot be reassigned. #it is nor reinforced by Python.It is more like a style GRAVITY = 9.8 GRAVITY = input(f"gravity value:") print(f'gravity is {GRAVITY}')
166402e70525f0ab90d8fbef840293868153f8d2
Anagabsoares/AdaPrecourse
/snowman.py
2,731
4.0625
4
import random from wonderwords import RandomWord SNOWMAN_WRONG_GUESSES = 7 SNOWMAN_MAX_WORD_LENGTH = 8 SNOWMAN_MIN_WORD_LENGTH = 5 SNOWMAN_GRAPHIC = ['* * * ', ' * _ * ', ' _[_]_ * ', ' * (") ', ' \( : )/ *', '* (_ : _) ', '-----------'] def get_letter_from_user( wrong_guessed_list, snowman_dict): flag_one_letter = False letter_from_user = None while not flag_one_letter: letter_from_user = input('Enter a letter: ') if not letter_from_user.isalpha(): print("Invalid character, please enter a letter.") elif len(letter_from_user) > 1: print('You should input one single letter.') elif letter_from_user in wrong_guessed_list: print('You have already guessed that letter') elif letter_from_user in snowman_dict and snowman_dict[letter_from_user] == True : print(f'You have already guesses that letter {letter_from_user} and it is in the word') else: flag_one_letter = True return letter_from_user def snowman(): r = RandomWord() snowman_word = r.word( word_min_length = SNOWMAN_MIN_WORD_LENGTH, word_max_length = SNOWMAN_MAX_WORD_LENGTH) print(snowman_word) flag_correct_guess= False count_correct_guesses = 0 count_wrong_guesses = 0 wrong_guessed_list = [] snowman_dict = snowman_word_dict(snowman_word) while not flag_correct_guess and count_wrong_guesses < SNOWMAN_WRONG_GUESSES: letter = get_letter_from_user(wrong_guessed_list, snowman_dict) print(letter) if letter in snowman_dict: print(f"you guessed one letter that is in our word!") snowman_dict[letter] = True # correct_guessed_list.append(letter) # count_correct_guesses += 1 # if count_correct_guesses == SNOWMAN_WRONG_GUESSES: else: print(f"The letter {letter} is not in the word ") wrong_guessed_list.append(letter) count_wrong_guesses += 1 print(snowman_dict) draw_snowman(count_wrong_guesses) print(wrong_guessed_list) result = f"You made {count_correct_guesses} correct and {count_wrong_guesses} incorrect guesses" return result def draw_snowman(wrong_guesses_count): for i in range(SNOWMAN_WRONG_GUESSES - wrong_guesses_count, SNOWMAN_WRONG_GUESSES): print(SNOWMAN_GRAPHIC[i]) def snowman_word_dict(word): word_dict= {} for letter in word: if not letter in word_dict: word_dict[letter] = False print(word_dict) return word_dict snowman()
b7361409d72262f39071be3b831fe41185e38683
VictorMateu/practica2algoritmia
/dp_rec.py
4,260
3.75
4
''' Dynamic Programing recursivo ''' import sys import math import resource resource.setrlimit(resource.RLIMIT_STACK, (2**29,-1)) sys.setrecursionlimit(10**6) class Punto: ''' Clase para almacenar los puntos sobre la tierra ''' def __init__(self, n_points, height, alfa, beta): self.puntos = [] self.costes = {} self.n_points = n_points self.height = height self.alfa = alfa self.beta = beta def add_punto(self, punto_x, punto_y): ''' Añade un punto del terreno ''' self.puntos.append([punto_x, punto_y]) def add_coste(self, costes): ''' Añade el coste ''' self.costes += costes def ac_recursivo(puntos, k): ''' Función que realiza dynamic programing ''' costes = {} i = k if k < 0: return puntos.costes[0] if k == puntos.n_points-1: puntos.costes[k] = puntos.alfa*(puntos.height - puntos.puntos[k][1]) else: while k < puntos.n_points-1: coste_actual = calcular_coste(i, k+1 , puntos) if coste_actual > 0: costes[k] = coste_actual k += 1 if costes: puntos.costes[i] = min(costes.values()) else: puntos.costes[i] = -1 i -= 1 return ac_recursivo(puntos, i) def calcular_coste(i, k, puntos): ''' Función que calcula el coste ''' coste_actual = coste_columna(i, k, puntos) if coste_actual < 0 or puntos.costes[k] < 0: return -1 return coste_actual + puntos.costes[k] def coste_columna(i,k, puntos): ''' Función que calcula el coste de la columna y plataforma ''' diametro = puntos.puntos[k][0] - puntos.puntos[i][0] radio = float(diametro/2) altura_izq = puntos.height - puntos.puntos[i][1] altura_drc = puntos.height - puntos.puntos[k][1] if altura_izq < radio or altura_drc < radio or \ puntos.puntos[i][1] >= puntos.height or puntos.puntos[k][1] >= puntos.height: return -1 centro_x = puntos.puntos[i][0] + radio centro_y = puntos.height - radio for punto in range (i+1, k): result_y = math.sqrt(radio**2 - (puntos.puntos[punto][0] - centro_x)**2) + centro_y if puntos.puntos[punto][1] > result_y: return -1 return puntos.beta*(diametro**2) + puntos.alfa*(puntos.height - puntos.puntos[i][1]) def main(): ''' Función principal: Obtiene los datos ya sea por linea de comandos o a través de un fichero ''' if len(sys.argv) > 1: args = sys.argv[1:] with open(args[0], "r") as fichero: linea = fichero.readline() n_points, height, alfa, beta = linea.split() n_points = int(n_points) height = int(height) alfa = int(alfa) beta = int(beta) puntos = Punto(n_points,height,alfa,beta) for linea in range (0,n_points): linea = fichero.readline() punto_x, punto_y = linea.split() punto_x = int(punto_x) punto_y = int(punto_y) puntos.add_punto(punto_x, punto_y) k = puntos.n_points-1 coste_acueducto = ac_recursivo(puntos, k) if coste_acueducto < 0: print("impossible") else: print(coste_acueducto) else: linea = sys.stdin.readline() n_points, height, alfa, beta = linea.split() n_points = int(n_points) height = int(height) alfa = int(alfa) beta = int(beta) puntos = Punto(n_points,height,alfa,beta) for linea in range (0,n_points): linea = sys.stdin.readline() punto_x, punto_y = linea.split() punto_x = int(punto_x) punto_y = int(punto_y) puntos.add_punto(punto_x, punto_y) k = puntos.n_points-1 coste_acueducto = ac_recursivo(puntos, k) if coste_acueducto < 0: print("impossible") else: print(coste_acueducto) if __name__ == "__main__": main()
3a419523fb1fc6bbef5cf3da4ad3d07cc3d77b34
PranavDev/Sorting-Techniques
/RadixSort.py
803
4.15625
4
# Implementing Radix Sort using Python # Date: 01/04/2021 # Author: Pranav H. Deo import numpy as np def RadixSort(L, ord): Reloader_List = [] temp = [] for i in range(0, 10): Reloader_List.append([]) for i in range(0, ord): print('Iteration ', i, ' : ', L) for ele in L: n = int((ele / np.power(10, i)) % 10) Reloader_List[n].append(ele) for lst in Reloader_List: if len(lst) > 0: for e in lst: temp.append(e) L = temp temp = [] for k in range(0, 10): Reloader_List[k] = [] return L # MyList = [102, 209, 90, 1, 458, 923, 9, 48, 20] MyList = np.random.randint(0, 500, 100) order = 3 Final_List = RadixSort(MyList, order) print('\n', Final_List)
9a9e006411084d4e94f543e174788fec07664a3d
Diegox777/MAT156
/trapecio.py
968
3.796875
4
import matplotlib.pyplot as plt import numpy as np from sympy import symbols # importamos la libreria sympy from sympy import lambdify from sympy import sympify x = symbols('x') # establecemos a x como variable simbolica a = int(input('Introduzca a = ')) b = int(input('Introduzca b = ')) n = int(input('Introduzca n = ')) expr = input('Introduzca f(x) = ') expr = sympify(expr) #evaluamos la funcion f = lambda valor: expr.subs(x, valor).evalf() #def f(valor): # return expr.subs(x, valor).evalf() # valor = 2 # 2**2 # 4 h = (b - a) / n # I = (h/2)*(f(a)+ 2*sumatoria(f(xi)) + f(b)) s = 0 for i in range(1, n): print('i: ', i) s = s + f(a + h * i) I = (h / 2) * (f(a) + 2 * s + f(b)) print('El aproximado es: ', I) # Graficamos la funcion lam_x = lambdify(x, expr, modules=['numpy']) x_vals = np.linspace(a - 5, b + 5, 100) y_vals = lam_x(x_vals) plt.title(expr) plt.xlabel('x') plt.ylabel('y') plt.plot(x_vals, y_vals) plt.grid(True) plt.show()
07452465afd7fee553f055e810405fdeac934940
aki-nlp/AtCoder
/atcoder.jp/abc111/abc111_a/Main.py
123
3.6875
4
n = list(input()) for i in n: if i == '1': print(9, end='') elif i == '9': print(1, end='') print()
0eeedfe72aeac8b1571fdc5bb38f5b31124e4ddc
aki-nlp/AtCoder
/atcoder.jp/abc018/abc018_1/Main.py
139
3.53125
4
a = [int(input()) for _ in range(3)] l = sorted(a, reverse=True) print(l.index(a[0]) + 1) print(l.index(a[1]) + 1) print(l.index(a[2]) + 1)
9e71cb471cce4502135a3158848aa6b92d10657e
aki-nlp/AtCoder
/atcoder.jp/abc165/abc165_b/Main.py
136
3.5625
4
x = int(input()) money = 100 ans = 0 while True: money += int(money*0.01) ans += 1 if money >= x: break print(ans)
5bfa675cdca9c76ca073225a40e653093dc92d4d
fergusjproctor/Hangman
/Problems/The mean/task.py
178
3.671875
4
numberList = [] while True: newInt = input() if newInt == '.': break else: numberList.append(int(newInt)) print(sum(numberList) / len(numberList))
31fdb185e264674aff42c8cce47c2417cd69d6fe
pc-kong/Algorithms
/Python/Data Structures/Stacks and Queues/RestrictedList.py
3,501
3.75
4
""" Linear structures with restricted insertion, peeking and deletion operations """ from abc import ABCMeta, abstractmethod class RestrictedList: """ Implements the generic list that will later on serve for the Stack and Queue implementation. Attributes ---------- head: Node Head Node tail: Node Tail Node Methods ------- is_empty() insert(element) [abstract method] remove(element) peek() """ __metaclass__ = ABCMeta class Node: """ Node that contains the element. Attributes ---------- element: element The key value the node holds. next: Node A reference to the next node in the list. """ def __init__(self, element): """ Constructor for the nodes. Parameter -------- element: element The element to be stored in the node. """ self.element = element self.next = None def __init__(self): """ Restricted List constructor. """ self.head = None self.tail = None def __str__(self): """ Returns the string representation of the Restricted List by traversing it starting from the head and concatenating the string representation of each element. :return: The string representation of the list. :rtype: string """ current_node = self.head list_string = "[" while current_node != None: list_string += str(current_node.element) current_node = current_node.next if current_node != None: list_string += ", " list_string += "]" return list_string def __eq__(self, other): """ Checks it the list is the same as some other list. Parameter --------- other: RestrictedList The other object to be compared to this list. """ if other == None: return False node_a = self.head node_b = other.head while node_a != None and node_b != None: # Comparing the elements one by one. if node_a.element != node_b.element: return False node_a = node_a.next node_b = node_b.next return node_a is node_b def is_empty(self): """ Checks whether the list is empty or not. :return: True if is is empty, false otherwise. :rtype: boolean """ return self.head == None # Abstract method to be implemented by Stacks and Queues. @abstractmethod def insert(self, element): pass def remove(self): """ Deletes the element in the head of the list. :return: The element that was removed. :rtype: element """ if self.is_empty(): return None element = self.head.element if self.head == self.tail: self.head = None self.tail = None else: self.head = self.head.next return element def peek(self): """ Returns the element that is in the head of the list, without removing it. :return: The element stored in the head. :rtype: element """ if self.is_empty(): return None return self.head.element
b1c37e2364ec168e559ffdead2245b86d8fb6a4b
pc-kong/Algorithms
/Python/Data Structures/Lists/skip_list.py
5,440
3.90625
4
import random class SkipNode: """ elem : value contained in the node. next : level where the node appears (list of pointers to the next nodes). """ def __init__(self, height=0, elem=None): self.elem = elem self.next = [None]*height def __str__(self): string = "[" + str(self.elem) + "] " for node in reversed(self.next): if node != None: string += "[.] " else: string += "[.] " return string def __repr__(self): return str(self) class SkipList: """ head : current node. maxlevel : maximum level for the skip list. p : fraction of the nodes with level i references also having level i+1 references """ def __init__(self, maxlevel, p): self.head = SkipNode(maxlevel,-1) self.maxlevel = maxlevel self.level = 0 self.p = p """ Choose the level of the node randomly. """ def random_level(self): level = 1 while random.random() < self.p and level < self.maxlevel: level += 1 return level """ Returns a list of nodes in each level that contains the greatest value that is smaller than 'elem'. Start from the highest level. """ def updateList(self, elem): #List of nodes. update = [None] * self.maxlevel current = self.head for i in reversed(range(len(current.next))): #search for the greatest x that is smaller than elem. while current.next[i] and current.next[i].elem < elem: current = current.next[i] update[i] = current return update """ Search the node corresponding to the element. None if it is not present. [Used for search/insert/delete] """ def find(self, elem, update=None): if update == None: update = self.updateList(elem) if len(update) > 0 and update[0] != None: candidate = update[0].next[0] if candidate != None and candidate.elem == elem: return candidate return None """ Insert the new node in each of the levels up related to his height; the last one choosen with the randomHeight function. """ def insert(self, elem): level = self.random_level() snode = SkipNode(level, elem) update = self.updateList(elem) current = update[0].next[0] #If the element is not in the list. if current == None or current.elem != elem: #If the actual level of the list is smaller than the level of #the element to insert add reference to head. if level > self.level: for i in range(self.level+1,level): update[i] = self.head self.level = level #Add the new node to each level. for i in range(level): snode.next[i] = update[i].next[i] update[i].next[i] = snode """ Delete the node with value equal to elem; deletes it from all leves. """ def remove(self, elem): update = self.updateList(elem) x = self.find(elem, update) if x != None: for i in range(len(x.next)): update[i].next[i] = x.next[i] def str_aux(self,nodes,actual,prev): if actual.next[0] == None: nodes.append(str(actual)+"\n") return nodes n = self.str_aux(nodes,actual.next[0],actual) actual = n[len(n)-1] if prev: string = "" str_prev = str(prev) str_act = str(actual) string += str_prev if len(str_prev) < len(str_act): for i in range(len(str_prev), len(str_act)): if str_act[i] == "." or str_act[i] == "↓": string += "↓" else: string += " " nodes.append(string+"\n") return nodes def __str__(self): string = "" arrows = "\n" for l in range(self.level): string += " [.] " for l in range(self.level): arrows += " ↓ " string += arrows+"\n" actual = self.head.next[0] nodes = self.str_aux([],actual,None) for node in reversed(nodes): string += node return string """def __str__(self): string = "" arrows = "\n" for l in range(self.level): string += " [.] " for l in range(self.level): arrows += " ↓ " string += arrows+"\n" actual = self.head.next[0] while actual: str_act = str(actual) string += str_act actual = actual.next[0] str_next = str(actual) if len(str_act) < len(str_next): for i in range(len(str_act),len(str_next)): print(str_next[i]) if len(str_act) < i and str_next[i] == ".": string += "↓" else: string += " " string += "\n" return string""" def __repr__(self): return str(self) sl = SkipList(3,0.5) sl.insert(2) #print(sl) #print(sl) sl.insert(1) #print(sl) sl.insert(6) sl.insert(3) sl.insert(8) print(sl)
10f8dd868a9fae5feba391c56955f823dfe807ad
pc-kong/Algorithms
/Python/Data Structures/Stacks and Queues/Stack.py
794
4
4
""" Stack (LIFO) """ from RestrictedList import RestrictedList class Stack(RestrictedList): """ In stacks, the last element that was added is the first one to be removed. This class inherits from the RestrictedList class which already implements the removal method. """ def insert(self, element): """ Inserts an element into the Stack. Since the element removed in the RestrictedList is the one in the head of the list, then we need to insert those elements there. :param element: The element to be inserted. """ if element == None: return None new_node = self.Node(element) if self.is_empty(): self.tail = new_node else: new_node.next = self.head self.head = new_node
4a6f9ab97e98503908cde26c203ae490eb74ac7b
Srikrishnarajan/Fibonacci-Series.py
/Fibonacci_Series.py
190
4.09375
4
n = int(input("Enter the value of n: ")) a = 0 b = 1 c = 0 count = 1 print("Fibonacci Series: ", end = " ") while(count <= n): print(c, end = " ") count += 1 a = b b = c c = a + b
cf2cea50bae7be4d823e14763f3515184077a9f6
KrysVal/projetM2
/etc/duplicate_remover.py
1,169
3.5
4
from Bio import SeqIO, SeqRecord import argparse def duplicate_remover(file): d = {} duplicate = [] for record in SeqIO.parse(file, "fasta"): if record.seq in d.keys(): print("duplicate found : \n" + record.id) duplicate.append(record.id) d[record.seq] = record.description return d, duplicate def new_file_writer(file, d): with open(file, 'w') as f: for key in d.keys(): data = SeqRecord.SeqRecord(key, id=d[key]) SeqIO.write(data, f, "fasta") def duplicate_file_writer(file,duplicate_list): with open(file,'w') as f: for double in duplicate_list: f.write(double + "\n") if __name__ == '__main__': # Get argument and parse them parser = argparse.ArgumentParser() # file path : parser.add_argument("-f", "--filename", required=True) args = parser.parse_args() filename = args.filename d, duplicate = duplicate_remover(filename) o_filename = filename[:-3] + "2" + filename[-3:] d_filename = filename[:-3] + "_duplicate.txt" new_file_writer(o_filename, d) duplicate_file_writer(d_filename, duplicate)
cc550fea7bbdbf89ec7ec4ae96c84d7831864518
RonKand14/Python-War-card-game
/client.py
5,800
3.78125
4
import socket import time class Client: """ Client class: Fields: client's socket as s, host - server's Ip, port - server's port """ def __init__(self, host, port): self.host = host self.port = port self.s = None def read_input(self): """ read_input - read's and handles the input from the client to fit the game session If input is invalid - ask's again """ while True: try: bet = input("What is your'e next move:") if bet.lower() == 'log' or bet.lower() == 'war' or bet.lower() == 'log' or bet.lower() == 'yes' or bet.lower() == 'no' or bet.lower() == 'surrender' or bet.lower() == 'quit': return bet.lower() elif int(bet): return 'b' + str(bet) elif bet.lower() == 'info': self.print_info() else: print("Error: invalid input. read the following input rules:") self.print_info() except TypeError or ValueError: self.print_info() def print_info(self): """ When invalid input is given - print this msg """ return "Input info:\nBet: numbers only || Log request = log || Quit = quit || Accept war = war || Surrender war = surrender ||" def utf8_len(self, string): """ Made it but didnt used it - checks the length of the string given """ return len(string.encode('utf-8')) def making_connection(self): """ Create a socket for the client and connect's to the server's socket if accepted If game session is valid - send to handling_connection method to handle game session. """ self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) message = "I want to play WAR" while True: try: self.s.connect((self.host, self.port)) self.s.sendall(message.encode()) data = str(self.s.recv(4096).decode('utf-8')) if data.lower() == "request denied": print("Game request denied") break else: print("Hello! While playing Please select your action according to the following:\nBet: integers only.\nLog request = log.\nQuit = quit.\n" "Accepting War = war.\nSurrendering war = surrender.\nPlaying again(end game) = yes.\nDeclining to play again = no.\n") print(f"Your card is:{data[28:]}") self.handling_connection() break except OSError: print("OSError: connection lost") break # close the connection and process self.s.close() self.s = None time.sleep(5) exit("Client closed") def check_end(self, data): """ Check's if this msg given from server is an game_over msg - according to the header of it as 0. """ if data[0] == '0': return False else: return True def handling_connection(self): """ Handle a full game session including if the player want's to play again. """ playing = True while playing: msg = self.read_input() self.s.sendall(msg.encode('utf-8')) while True: data = str(self.s.recv(4096 * 2).decode('utf-8')) header = data[0] if header == '1' or header == '2': print(data[1:]) elif header == '6': print(data[1:]) msg = self.read_input() self.s.sendall(msg.encode()) elif header == '3': print(data[1:]) msg = input() # war or surrender while msg != "war" and msg != "surrender": print("Input Error: Type war or surrender") msg = input() self.s.sendall(msg.encode()) data = str(self.s.recv(4096).decode('utf-8')) print(data) elif header == '4': print(data[1:]) msg = self.read_input() self.s.sendall(msg.encode()) elif header == '5': print(data[1:]) playing = False break elif header == '0': print(data[1:]) msg = input() # yes or no only while msg != 'yes' and msg != 'no': print("Input Error: Type yes or no") msg = input() self.s.sendall(msg.encode()) if msg == 'yes': data = str(self.s.recv(4096 * 2).decode('utf-8')) print(f"Your card is:{data[28:]}") self.handling_connection() playing = False break else: data = str(self.s.recv(4096 * 2).decode('utf-8')) print(data) playing = False break def main(): my_name = socket.gethostname() my_host = socket.gethostbyname(my_name) server_port = 5555 client1 = Client(my_host, server_port) client1.making_connection() main()
9ce619cdfb7e082cd269c7349a538f13573e01ca
haffarmohammed/Aloha-async
/plot.py
371
3.859375
4
from matplotlib import pyplot as plt def generateGraphe(): # naming the x axis plt.xlabel('K') # naming the y axis plt.ylabel('paquets transmis') # giving a title to my graph plt.title('Asynchrone Aloha Statistics') # show a legend on the plot plt.legend() plt.savefig('graphe.png') # function to show the plot plt.show()
c5d5962687dba55ef6c7ea97b7ba1d499f152013
FranzTseng/practice
/python/OOP_bank_Project.py
942
3.78125
4
class Account(): def __init__(self, owner, balance): Account.owner = owner Account.balance = balance def __repr__(self): return f"owner:{self.owner}, balance:{self.balance}" def deposit(self, deposit): self.balance = self.balance + deposit print('Succeed') return self.balance def withdraw(self, withdraw): self.balance = self.balance - withdraw if self.balance < 0: return "Not enough balance in your account!!!" else: print('Succeed') return self.balance acct1 = Account('Jose',100) print(acct1) # Show the account owner attribute print(acct1.owner) # Show the account balance attribute print(acct1.balance) # Make a series of deposits and withdrawals print(acct1.deposit(50)) print(acct1.withdraw(75)) # Make a withdrawal that exceeds the available balance print(acct1.withdraw(500))
08f465020fda54f2161da24bc821125b5c6e9daa
Jack64ru/python
/while.py
78
3.75
4
i = int(input('number: ')) p = 1 while i >= p: print('*' * p) p = p+1
cf8cf0191e831307a5d78b27ae47cbc20c63db4d
KarthikeyanS27/Turtlebot-Navigation
/MPC Path Planning/devel/test.py
7,635
3.765625
4
import numpy as np import itertools from functions import * import matplotlib.pyplot as plt from matplotlib import animation # Inputs H_p = 2 # number of steps in prediction horizon H_c = 1 # number of steps in control horizon dt = 1 # seconds in one time step # positional coordinates x = [0] y = [0] v = [0] phi = [0] goal = [-5, -5] k = 0 # initialize time steps goalReached=False obstacles = [[0, 1], [2, 1]] min_buffer = 0.1 # The method that prints all # possible strings of length k. # It is mainly a wrapper over # recursive function printAllKLengthRec() # https://www.geeksforgeeks.org/print-all-combinations-of-given-length/ def printAllKLength(set, k): initialScore = 1e100 optimal = [""]*k optimal.append(initialScore) n = len(set) prefix = [] return printAllKLengthRec(set, prefix, n, k, optimal) # The main recursive method # to print all possible # strings of length k def printAllKLengthRec(set, prefix, n, k, optimal): score = optimal[-1] best = [1e100] # Base case: k is 0, # print prefix if (k == 0): newScore = calc_score(prefix, dt, H_c, x, y, k, goal, obstacles, min_buffer) if newScore < score: optimal = prefix.copy() optimal.append(newScore) return optimal # One by one add all characters # from set and recursively # call for k equals to k-1 for i in range(n): # Next character of input added newPrefix = prefix.copy() newPrefix.append(set[i]) # k is decreased, because # we have added a new character new = printAllKLengthRec(set, newPrefix, n, k - 1, optimal) if new[-1] < best[-1]: best = new return best combos = [[-5.0, -3.0], [-5.0, 3.0], [5.0, -3.0], [5.0, 3.0]] k = 2 #print(printAllKLength(combos, k)) # # First set up the figure, the axis, and the plot element we want to animate # fig = plt.figure() # ax = plt.axes(xlim=(0, 2), ylim=(-2, 2)) # line, = ax.plot([], [], lw=2) # # initialization function: plot the background of each frame # def init(): # line.set_data([], []) # return line, # # animation function. This is called sequentially # def animate(i): # #x = np.linspace(0, 2, 1000) # #y = np.sin(2 * np.pi * (x - 0.01 * i)) # x = 2 # y = x**2 # line.set_data(x, y) # return line, # call the animator. blit=True means only re-draw the parts that have changed. #anim = animation.FuncAnimation(fig, animate, init_func=init, frames=200, interval=20, blit=True) #plt.show() # x = np.arange(-10,10) # y = x**2 # fig = plt.figure() # ax = fig.add_subplot(111) # ax.plot(x,y) # coords = [] # def onclick(event): # global ix, iy # ix, iy = event.xdata, event.ydata # print ('x = %d, y = %d'%(ix, iy)) # global coords # coords.append((ix, iy)) # if len(coords) == 2: # fig.canvas.mpl_disconnect(cid) # return coords # cid = fig.canvas.mpl_connect('button_press_event', onclick) plt.show() # plt.figure("Jump Trajectory Lite") # plt.title("Drag the dots to the locations specified below:") # plt.xlabel("Red --> Jump Take-off, Blue --> Start of Jump, Green --> Drop Point") # ### Prompt user to place points 1, 2, and h_s # x1 = 0 # y1 = 0 # x2 = 0 # y2 = 0 # drop_height = 0 # class setLocations: # def __init__(self, rect, color): # self.rect = rect # self.press = None # self.color = color # def connect(self): # 'connect to all dots that are being clicked on' # self.cidpress = self.rect.figure.canvas.mpl_connect('button_press_event', self.on_press) # self.cidrelease = self.rect.figure.canvas.mpl_connect('button_release_event', self.on_release) # self.cidmotion = self.rect.figure.canvas.mpl_connect('motion_notify_event', self.on_motion) # def on_press(self, event): # 'when button is pressed, check if mouse is over a dot and store data' # if event.inaxes != self.rect.axes: return # contains, attrd = self.rect.contains(event) # print(contains) # if not contains: # print("test") # circle1 = plt.Circle((0.5,0.5), 0.2 , color='red') # plt.gcf().gca().add_artist(circle1) # dr = setLocations(circle1, 'red') # dr.connect() # drs.append(dr) # return # x0, y0 = self.rect.center # self.press = x0, y0, event.xdata, event.ydata # def on_motion(self, event): # 'if mouse is clicked and held over dot, move dot along with mouse' # if self.press is None: return # x0, y0, xpress, ypress = self.press # dx = event.xdata - xpress # distance moved in x direction # dy = event.ydata - ypress # distance moved in y direction # self.rect.center = x0+dx, y0+dy # def on_release(self, event): # 'on release, reset press data and keep object in most recent location' # self.press = None # self.rect.figure.canvas.draw() # def disconnect(self): # 'disconnect all stored connection ids' # self.rect.figure.canvas.mpl_disconnect(self.cidpress) # self.rect.figure.canvas.mpl_disconnect(self.cidrelease) # self.rect.figure.canvas.mpl_disconnect(self.cidmotion) # img_height = 300 # img_width = 400 # circle1 = plt.Circle((img_width*3/12,img_height/6), img_width/150,color='red') # plt.gcf().gca().add_artist(circle1) # drs = [] # dr = setLocations(circle1, 'blue') # dr.connect() # drs.append(dr) # plt.show() # # The main function that recursively prints all repeated # # permutations of the given string. It uses data[] to store # # all permutations one by one # # https://www.geeksforgeeks.org/print-all-permutations-with-repetition-of-characters/ # def allLexicographicRecur(string, data, last, index, optimal): # length = len(string) # hiScore = float(optimal[-1]) # # One by one fix all characters at the given index and # # recur for the subsequent indexes # for i in range(length): # # Fix the ith character at index and if this is not # # the last index then recursively call for higher # # indexes # data[index] = string[i] # # If this is the last index then print the string # # stored in data[] # if index==last: # score = calc_score(data, dt, H_c, x, y, k, goal, obstacles, min_buffer) # if score < hiScore: # optimal = data.copy() # optimal.append(score) # return optimal # else: # new = allLexicographicRecur(string, data, last, index+1, optimal) # if new[-1] < optimal[-1]: # optimal = new # return optimal # # This function sorts input string, allocate memory for data # # (needed for allLexicographicRecur()) and calls # # allLexicographicRecur() for printing all permutations # def allLexicographic(string): # length = len(string) # # Create a temp array that will be used by # # allLexicographicRecur() # data = [""] * (length) # optimal = [""] * (length) # optimal.append(100000000000000.0) # # Sort the input string so that we get all output strings in # # lexicographically sorted order # #string = sorted(string) # # Now print all # return allLexicographicRecur(string, data, length-1, 0, optimal) # # Find control sequence with lowest score # optimal_sequence = allLexicographic(combos)[:-1]
b79bb17bced0ae466ecf3821624e9273f6cbac6a
SewonShin/BLOCKCHAINSCHOOL
/Python Code 2/FastCampusPythonBasic/code04/main.py
722
3.875
4
# num_dict = {"m":"Moon", "s":"Seong"} # print(num_dict["m"]) # 가져오기 # keys(), values() # for k, v in num_dict.items(): # print(k,v) # num_dict["j"] = "Jae" # 키의 존재 유무 -> 추가, 수정 # del num_dict["m"] # 삭제 # print(num_dict.get("k")) # x = 10 # y = 10.1 # z = "문자열" # isBool = True # False # isNone = None # num_list = [1, 2, 3, 4, 5] # 인덱싱 0부터 시작 # print(num_list[0], num_list[-1]) # for i in num_list: # print(i) # 슬라이싱 (범위) 시작:끝-1 # print(num_list[0:3]) # print(num_list[1:]) # num_list.append(6) # num_list.append(7) # del num_list[len(num_list)-1] #삭제 # num_list[0] = 0 # 수정 # print(num_list)
8ccdc8d69acc0f784dbebdfe3c5618b268a01889
stevenwaldron/Sprint-Challenge--Data-Structures-Python
/reverse/reverse.py
1,522
4
4
class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next class LinkedList: def __init__(self): self.head = None def add_to_head(self, value): node = Node(value) if self.head is not None: node.set_next(self.head) self.head = node def contains(self, value): if not self.head: return False current = self.head while current: if current.get_value() == value: return True current = current.get_next() return False def view(self): values = [] currentnode = self.head while currentnode != None: values.append(str(currentnode.value)) currentnode = currentnode.next_node return '-->'.join(values) def reverse_list(self,node,prev): prev = None current = self.head while (current is not None): next = current.next_node current.next_node = prev prev = current current = next self.head = prev return self.view() LL = LinkedList() LL.add_to_head(6) LL.add_to_head(4) LL.add_to_head(2) print(LL.view()) print(LL.reverse_list(None,None))
d5a781cebe422e3b777ee772c1dbf79764664b23
humanwings/learngit
/python/basic/testStringFormat.py
957
3.75
4
import string # print(str("wujian")) # print(str("呉剣")) # print(ascii("wujian")) # print(ascii("呉剣")) # print(repr("wujian")) # print(repr("呉剣")) # str.format() print("============ str.format() ===============") print() s0 = "{} 's age is {}" s1 = "{0} 's age is {1}" s2 = "{0!a} 's age is {1}" print(s0) print(" --> ",s0.format("呉剣",40)) print(s1) print(" --> ",s1.format("呉剣",40)) print(s2) print(" --> ",s2.format("呉剣",40)) print() # % print("============ %d %s ===============") print() s0 = "%s 's age is %d" print(s0) print(" --> ",s0 % ("呉剣",40)) # string.Formatter print("============ string.Formatter ===============") print() fmt = string.Formatter() s0 = "{} 's age is {}" s1 = "{0} 's age is {1}" s2 = "{0!a} 's age is {1}" print(s0) print(" --> ",fmt.format(s0,"呉剣",40)) print(s1) print(" --> ",fmt.format(s1,"呉剣",40)) print(s2) print(" --> ",fmt.format(s2,"呉剣",40))
493be0686bb1d6a9bf2aae7a22372d5f61b1373c
humanwings/learngit
/python/coroutine/testCoroutine_yieldfrom02.py
3,405
3.84375
4
''' yield from 结构最简单的用法 委派生成器相当于管道,所以可以把任意数量的委派生成器连接在一起--- 一个委派生成器使用yield from 调用一个子生成器,而那个子生成器本身也是委派生成器,使用yield from调用另一个生成器。 最终以一个只是用yield表达式的生成器(或者任意可迭代对象)结束。 ''' #! -*- coding: utf-8 -*- from collections import namedtuple Result = namedtuple('Result', 'count average') # 子生成器 def averager(): print("averager begin ") total = 0.0 count = 0 average = None while True: # main 函数发送数据到这里 print("begin yield ...") term = yield print("term is ", term) if term is None: # 终止条件 break total += term count += 1 average = total/count return Result(count, average) # 返回的Result 会成为grouper函数中yield from表达式的值 # 委派生成器 def grouper(results, key): print("grouper begin ") # 这个循环每次都会新建一个averager 实例,每个实例都是作为协程使用的生成器对象 n = 0 # 如果不用while,那么grouper结束时会发生StopIteration,导致程序中止 # 有while在,grouper就不会结束,也就不会抛出StopIteration while True: # grouper 发送的每个值都会经由yield from 处理,通过管道传给averager 实例。grouper会在yield from表达式处暂停,等待averager实例处理客户端发来的值。 # averager实例运行完毕后,返回的值绑定到results[key] 上。 n += 1 print("before yield from ", n) results[key] = yield from averager() print("after yield from ", n) # 调用方 def main(data): results = {} for key, values in data.items(): # group 是调用grouper函数得到的生成器对象,传给grouper 函数的第一个参数是results,用于收集结果;第二个是某个键 print("------------ ", key, values) group = grouper(results, key) print("grouper OK") next(group) print("next OK") for value in values: # 把各个value传给grouper 传入的值最终到达averager函数中; # grouper并不知道传入的是什么,同时grouper实例在yield from处暂停 group.send(value) # 把None传入grouper,传入的值最终到达averager函数中,导致当前实例终止。然后继续创建下一个实例。 # 如果没有group.send(None),那么averager子生成器永远不会终止,委派生成器也永远不会在此激活,也就不会为result[key]赋值 group.send(None) # <- send(None) 以后, main已经处理完当前数据,结束本次循环了,但是旧的group还在生成新的averager,等待数据。 report(results) # 输出报告 def report(results): for key, result in sorted(results.items()): group, unit = key.split(';') print('{:2} {:5} averaging {:.2f}{}'.format(result.count, group, result.average, unit)) data = { 'girls;kg':[40, 41, 42, 43, 44, 54], 'girls;m': [1.5, 1.6, 1.8, 1.5, 1.45, 1.6], 'boys;kg':[50, 51, 62, 53, 54, 54], 'boys;m': [1.6, 1.8, 1.8, 1.7, 1.55, 1.6], } if __name__ == '__main__': main(data)
dc34b77a678caff2ce7b611f21ed210d55321225
humanwings/learngit
/python/coroutine/testCoroutine_01.py
894
4.25
4
''' 协程(Coroutine)测试 - 生产者和消费者模型 ''' def consumer(): r = '' # print('*' * 10, '1', '*' * 10) while True: # print('*' * 10, '2', '*' * 10) n = yield r if not n: # print('*' * 10, '3', '*' * 10) return # print('[CONSUMER] Consuming %s...' % n) r = '200 OK' def produce(c): # print('*' * 10, '4', '*' * 10) c.send(None) # 相当于 c.next() 不能send非none 因为是第一次调用,没有yield来接收数据 n = 0 # print('*' * 10, '5', '*' * 10) while n < 5: n = n + 1 print('[PRODUCER] Producing %s...' % n) r = c.send(n) print('[PRODUCER] Consumer return: %s' % r) #c.send(0) # 在这里加上send(0),可以出return前的log,但是会发生topIteration,为什么? c.close() c = consumer() produce(c)
64310b064ce3a0e2cc14f6e238ae8da215b44a83
Davidigbokwe/desktopapp
/Pythonapptkinter/script.py
475
3.859375
4
#python classes and object oriented programming #corey schafer #methods are functions associated with class class Employee: def __init__(self,first, last, pay): self.first =first self.last =last self.pay =pay self.email = first[0] + '.'+ last +"@hackmanmfb.com" def fullname(self): return '{} {}'.format(self.first, self.last) emp1 =Employee('david','igbokwe',50000) emp2 = Employee('Emeka', 'Victor',60000) #create a method with our class print(emp2.fullname())
f52b38bb4315682d54c1cd5b6062197f7a431c64
knksknsy/facial-reenactment
/utils/transforms.py
162
3.5
4
def normalize(data, mean, std): data = (data - mean) / std return data def denormalize(data, mean, std): data = (data * std) + mean return data
a58e7283130ce6309de6c28fcd5accdc55f96f88
janmachowski/breast_cancer_prediction
/main.py
4,483
3.546875
4
import pandas as pd import seaborn as sn import matplotlib.pyplot as plt from sklearn.metrics import accuracy_score # importing the dataset dataset = pd.read_csv('data.csv') X = dataset.iloc[:, 2:].values Y = dataset.iloc[:, 1].values print("Dataset dimensions : {}".format(dataset.shape)) # Visualization of data dataset.hist(bins = 10, figsize=(20, 15)) plt.show() dataset.isnull().sum() dataset.isna().sum() # Encoding categorical data values from sklearn.preprocessing import LabelEncoder labelencoder_Y = LabelEncoder() Y = labelencoder_Y.fit_transform(Y) # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X, Y, test_size=0.25, random_state=0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Logistic Regression Algorithm from sklearn.linear_model import LogisticRegression classifier = LogisticRegression(random_state=0) classifier.fit(X_train, Y_train) Y_pred1 = classifier.predict(X_test) print("Logistic Regression Classifier", accuracy_score(Y_test, Y_pred1) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred1, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 94.4 Accuracy # K-NN Algorithm from sklearn.neighbors import KNeighborsClassifier classifier = KNeighborsClassifier(n_neighbors=3, metric='minkowski', p=2) classifier.fit(X_train, Y_train) Y_pred2 = classifier.predict(X_test) print("3-Nearest Neighbors Classifier", accuracy_score(Y_test, Y_pred2) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred2, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 95.8 Accuracy # SVM from sklearn.svm import SVC classifier = SVC(kernel='linear', random_state=0) classifier.fit(X_train, Y_train) Y_pred3 = classifier.predict(X_test) print("Support Vector Classifier Linear Kernel", accuracy_score(Y_test, Y_pred3) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred3, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 96.5 Accuracy # K-SVM from sklearn.svm import SVC classifier = SVC(kernel='rbf', random_state=0) classifier.fit(X_train, Y_train) Y_pred4 = classifier.predict(X_test) print("Support Vector Classification RBF Kernel", accuracy_score(Y_test, Y_pred4) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred4, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 96.5 Accuracy # Naive Bayes from sklearn.naive_bayes import GaussianNB classifier = GaussianNB() classifier.fit(X_train, Y_train) Y_pred5 = classifier.predict(X_test) print("Gaussian Naive Bayes Classification", accuracy_score(Y_test, Y_pred5) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred5, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 92.3 Accuracy # Decision Tree Algorithm from sklearn.tree import DecisionTreeClassifier classifier = DecisionTreeClassifier(criterion='entropy', random_state=0) classifier.fit(X_train, Y_train) Y_pred6 = classifier.predict(X_test) print("Decision Tree Classifier", accuracy_score(Y_test, Y_pred6) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred6, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 95.1 Accuracy # Random Forest Classification Algorithm from sklearn.ensemble import RandomForestClassifier classifier = RandomForestClassifier(n_estimators=10, criterion='entropy', random_state=0) classifier.fit(X_train, Y_train) Y_pred7 = classifier.predict(X_test) print("Random Forest Classifier", accuracy_score(Y_test, Y_pred7) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred7, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 96.5 Accuracy # MLP from sklearn.neural_network import MLPClassifier classifier = MLPClassifier(solver='lbfgs', random_state=0, activation='logistic', hidden_layer_sizes=(15,)) classifier.fit(X_train, Y_train) Y_pred8 = classifier.predict(X_test) print("MLP Classifier", accuracy_score(Y_test, Y_pred8) * 100, "%") confusion_matrix = pd.crosstab(Y_test, Y_pred8, rownames=['Actual'], colnames=['Predicted']) sn.heatmap(confusion_matrix, annot=True) plt.show() # 96.5 Accuracy
13a66d537cddee11a8d927b15fb363d983d147a0
MengSunS/daily-leetcode
/sweeping_line/452.py
1,075
3.515625
4
# official solution, sort by ending points: class Solution: def findMinArrowShots(self, points: List[List[int]]) -> int: if not points: return 0 # sort by x_end points.sort(key = lambda x : x[1]) arrows = 1 first_end = points[0][1] for x_start, x_end in points: # if the current balloon starts after the end of another one, # one needs one more arrow if first_end < x_start: arrows += 1 first_end = x_end return arrows # my own: sort by starting points, find # of overlaps class Solution: def findMinArrowShots(self, A: List[List[int]]) -> int: if not A: return 0 A.sort() cnt = 1 n = len(A) prev = A[0] for i in range(n): start, end = A[i][0], A[i][1] if start > prev[1]: prev = A[i] cnt += 1 else: prev = [max(prev[0], start), min(prev[1], end)] return cnt
df4204941cbe8c6b45705ea839225afb9177bd11
MengSunS/daily-leetcode
/fb高频/92.py
748
3.875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, val=0, next=None): # self.val = val # self.next = next class Solution: def reverseBetween(self, head: ListNode, l: int, r: int) -> ListNode: if not head or l == r: return head dummy = prev = ListNode(0) dummy.next = head for _ in range(l - 1): prev = prev.next reverse = None cur = prev.next for _ in range(r - l + 1): tmp = cur.next cur.next = reverse reverse = cur cur = tmp prev.next.next = cur prev.next = reverse return dummy.next
4c71882a32a10c8157d62309ba2a25f537f63f03
MengSunS/daily-leetcode
/bfs/690.py
1,758
3.71875
4
# 第二遍做:recursion """ # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: emps = {e.id: e for e in employees} def dfs(id): return emps[id].importance + sum(dfs(sub_id) for sub_id in emps[id].subordinates) # sum() without [], it becomes a generator taking O(1) space in this step return dfs(id) # Method 1: bfs """ # Definition for Employee. class Employee: def __init__(self, id: int, importance: int, subordinates: List[int]): self.id = id self.importance = importance self.subordinates = subordinates """ class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: map= {} for e in employees: map[e.id]= e q= deque([id]) res= 0 while q: cur= q.popleft() res+= map[cur].importance for next in map[cur].subordinates: q.append(next) return res # Method 2: dfs recursion class Solution: def getImportance(self, employees: List['Employee'], id: int) -> int: table = {} for employee in employees: table[employee.id] = employee return self.helper(table, id) def helper(self, table, rootId): root = table[rootId] total = root.importance for subordinate in root.subordinates: total += self.helper(table, subordinate) return total
018c7f1ba42e50c46da8dd7112c56089af479027
MengSunS/daily-leetcode
/design/146.py
1,956
3.59375
4
# hashmap: {key: node} # doubleLinkedList: <->node<-> # node.val, node.key, node.before, node.after # two dummy nodes: self.head, self.tail class DLinkNode: def __init__(self): self.key = None self.val = None self.before = None self.after = None class LRUCache: def __init__(self, capacity: int): self.maxi = capacity self.size = 0 self.head = DLinkNode() self.tail = DLinkNode() self.head.after = self.tail self.tail.before = self.head self.dict = {} # {key: node} def get(self, key: int) -> int: node = self.dict.get(key, None) if not node: return -1 self.remove(node) self.insert(node) # self.dict[key] = node return node.val def put(self, key: int, value: int) -> None: #update node = self.dict.get(key, None) if not node: node = DLinkNode() self.size += 1 else: self.remove(node) self.dict[key] = node node.key = key node.val = value self.insert(node) if self.size > self.maxi: node = self.pop_tail() del self.dict[node.key] self.size -= 1 def remove(self, node): node.before.after = node.after node.after.before = node.before node.before = None node.after = None def insert(self, node): tmp = self.head.after self.head.after = node node.before = self.head node.after = tmp tmp.before = node def pop_tail(self): node = self.tail.before self.remove(node) return node # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
3eee307938420f7cc3a58ff6ebbd295652d134ed
MengSunS/daily-leetcode
/snap/342.py
647
3.609375
4
class Solution: def isPowerOfFour(self, num: int) -> bool: return num > 0 and num & (num-1) == 0 and 0b1010101010101010101010101010101 & num == num def isPowerOfFour(self, num: int) -> bool: if num < 0 : return False def helper(num): if num < 4: if num == 1: return True else: return False return helper(num/4) return helper(num) def isPowerOfFour(self, num: int) -> bool: if num < 0 : return False while num >= 4: num /= 4 return num == 1
437d0d9178abdbcf89042c35f1f94ebdc0912294
MengSunS/daily-leetcode
/binary_tree/tree/333.py
784
3.65625
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def largestBSTSubtree(self, root: TreeNode) -> int: def dfs(root): if not root: return 0, float('inf'), float('-inf') l_n, l_min, l_max = dfs(root.left) r_n, r_min, r_max = dfs(root.right) if l_max < root.val < r_min: return l_n + r_n + 1, min(l_min, root.val), max(r_max, root.val) else: return max(l_n, r_n), float('-inf'), float('inf') return dfs(root)[0]
86d20bc245deb7217a657286c19df842bab15d0d
MengSunS/daily-leetcode
/binary_tree/1644.py
864
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode': self.p_find, self.q_find= False, False res= self.dfs(root, p, q) return res if (self.p_find and self.q_find) else None def dfs(self, root, p, q): if not root: return left= self.dfs(root.left, p, q) right= self.dfs(root.right, p, q) if root==p: self.p_find= True return root if root==q: self.q_find= True return root if left and right: return root return left or right
c31c3e68fa40c14a7d943ffccbe98228a6d99c9a
MengSunS/daily-leetcode
/snap/146.py
1,556
3.765625
4
class Node: def __init__(self, key=None, val=None, before=None, after=None): self.key = key self.val = val self.before = before self.after = after class LRUCache: def __init__(self, capacity: int): self.cache = {} self.maxi = capacity self.head = Node() self.tail = Node() self.head.after = self.tail self.tail.before = self.head def get(self, key: int) -> int: node = self.cache.get(key, None) if node: self.remove(node) self.insert(node) return node.val else: return -1 def put(self, key: int, value: int) -> None: node = self.cache.get(key, None) if node: node.val = value self.remove(node) else: node = Node(key=key, val=value) self.insert(node) if len(self.cache) > self.maxi: self.remove(self.tail.before) def remove(self, node): node.before.after = node.after node.after.before = node.before node.before, node.after = None, None del self.cache[node.key] def insert(self, node): tmp = self.head.after self.head.after = node node.before = self.head node.after = tmp tmp.before = node self.cache[node.key] = node # Your LRUCache object will be instantiated and called as such: # obj = LRUCache(capacity) # param_1 = obj.get(key) # obj.put(key,value)
61b424ca8f98794de4d0b80f99a2e89bc587390e
ProProgrammer/udacity-cs253-L2andPSet2
/rot13_implementation.py
1,399
3.890625
4
ASCII_a = ord('a') # equals 97 ASCII_A = ord('A') # equals 65 ROTNum = 13 # requiredShift def rot13(user_input): outputList = [] if user_input: for i in user_input: if isLowerCaseChar(i): outputList.append(rotLowerCase(i, ROTNum)) elif isUpperCaseChar(i): outputList.append(rotUpperCase(i, ROTNum)) else: outputList.append(i) return ''.join(outputList) def rotLowerCase(inputChar, requiredShift): outputASCII = (((ord(inputChar) - ASCII_a) + requiredShift) % 26) + ASCII_a return chr(outputASCII) def rotUpperCase(inputChar, requiredShift): outputASCII = (((ord(inputChar) - ASCII_A) + requiredShift) % 26) + ASCII_A return chr(outputASCII) def isUpperCaseChar(c): if ord(c) >= ord('A') and ord(c) <= ord('Z'): return True else: return False def isLowerCaseChar(c): if ord(c) >= ord('a') and ord(c) <= ord('z'): return True else: return False print rot13('deep SukhwaniZZZ') """ # Experimenting before finalizing function for x in range(ord('a'), ord('z') + 1): print x, chr(x), (ord('z') + 13) % ord('z') requiredRot = 13 for x in range(ord('a'), ord('z') + 1): inputAscii = x outputAscii = x + requiredRot if (outputAscii > ord('z')) print x, chr(x), 'output:', chr(outputAscii) for x in range(97, 123): outputValue = (((x - 97) + 13) % 26) + 65 print x, chr(x), ':', outputValue, chr(outputValue) inputAscii outputAscii == inputAscii + 13 """
75a9d2a6c2d318f11c3257771c7c5ebd4ff8320e
sigmaticsMUC/neuralCar
/neuronalApp/netCar/simCar/Car.py
968
3.625
4
from neuronalApp.netCar.abstractNetCar.abstractVehicle import abstractVehicle class Car(abstractVehicle): color = (255, 0, 0) def __init__(self, xpos, ypos, velocity): self.velocity = velocity self.position = (xpos, ypos) # instance variable unique to each instance self.direction = (0, 0) # vector indicating directon of car def move(self): self.position = (self.position[0] + self.direction[0], self.position[1] + self.direction[1]) def get_next_pos(self): return self.position[0] + self.direction[0], self.position[1] + self.direction[1] def update_direction(self, dx, dy): self.direction = (dx, dy) def to_string(self): return "Car position at: " + str(self.position[0]) + ", " + str(self.position[1]) + "\n" + \ "Car direction: " + str(self.direction[0]) + ", " + str(self.direction[1]) + "\n" + \ "Car velocity: " + str(self.velocity)
bb735795b57903276b4cf8f9418d09e76f85a635
mateuszstompor/Rosalind
/AlgorithmicHeights/2sum/2sum.py
1,400
3.78125
4
import sys def two_sum(sequence): result = None for i in range(len(sequence)): for j in range(1, len(sequence)): if i != j and sequence[i] == -sequence[j]: result = i+1, j+1 if result is not None: return (result[0], result[1]) if result[0] < result[1] else (result[1], result[0]) def parse(file): array_count, elements_count = [int(x) for x in file.readline().split()] sequences = [sequence.split() for sequence in file.read().split('\n')] for i in range(len(sequences)): sequences[i] = list(map(lambda x: int(x), sequences[i]))[:elements_count] return sequences[:array_count] def print_two_sums(sequences): for sequence in sequences: indices = two_sum(sequence) if indices: print(indices[0], indices[1]) else: print(-1) if __name__ == "__main__": print("There is possibility of passing a path to file containing data as a first argument") if len(sys.argv) > 2: print('Wrong Invocation! Pass a path to file or do not pass anything') else: filename = sys.argv[1] if len(sys.argv) == 2 else 'rosalind_2sum.txt' try: with open(filename) as input_file: sequences = parse(input_file) print_two_sums(sequences) except IOError: print("Error while reading the file")
37886241a038e7e967bbe9b7d043f9b6f1d1773b
mateuszstompor/Rosalind
/PythonVillage/ini6/ini6.py
507
4
4
import sys def count_word_occurence(words): count = {} for word in words: count[word] = count.get(word, 0) + 1 return count if __name__ == "__main__": if len(sys.argv) != 2: print("Invoke the program passing a path to a file as an argument") else: with open(sys.argv[1]) as input_file: words = input_file.read().split() count = count_word_occurence(words) for key, value in count.items(): print(key, value)
ba2848ac2f71d60860dec842aa0356940112a583
mateuszstompor/Rosalind
/BioinformaticsStronghold/subs/subs.py
576
3.578125
4
import sys def motif_occurrence(dna, motif): result = [] for i in range(0, len(dna)): stripped = dna[i:i+len(motif)] index = stripped.find(motif) if index >= 0: result.append(index + i + 1) return result if __name__ == "__main__": if len(sys.argv) != 2: print("Invoke the program passing a path to a file as an argument") else: with open(sys.argv[1], 'r') as file: dna = file.readline().strip() motif = file.readline().strip() print(*motif_occurrence(dna, motif))
bdc289b3b5677c987a35aac212afdf63b4b94ac5
mateuszstompor/Rosalind
/AlgorithmicHeights/fibo/fibo.py
411
4.09375
4
import sys def fibonacci(n): if n == 0: return 0 elif n == 1: return 1 else: return fibonacci(n-1) + fibonacci(n-2) if __name__ == "__main__": if len(sys.argv) != 2: print("Invoke the program passing a path to a file as an argument") else: with open(sys.argv[1]) as file: number = int(file.read()) print(fibonacci(number))
489f07ddb56ccd352f2b13b39c9e47355ac1a650
Sanyab001/ProjectEuler
/task_6.py
1,034
3.828125
4
# Сумма квадратов первых десяти натуральных чисел равна # # 1**2 + 2**2 + ... + 10**2 = 385 # Квадрат суммы первых десяти натуральных чисел равен # # (1 + 2 + ... + 10)**2 = 55**2 = 3025 # Следовательно, разность между суммой квадратов и квадратом суммы первых десяти натуральных чисел составляет 3025 − 385 = 2640. # # Найдите разность между суммой квадратов и квадратом суммы первых ста натуральных чисел. def first_sum(d): """Функция поиска суммы квадратов""" s = 0 for i in range(d + 1): s += i ** 2 return s def second_sum(d): """Функция пойска квадрата суммы""" s = 0 for i in range(d + 1): s += i s **= 2 return s print(second_sum(100) - first_sum(100))
2d19f0e057fe87daae6821150999017903b7613d
Lixmna/wikidocs
/4.자료형/4.3_Tuple.py
169
3.625
4
p = (1,2,3) q = p[:1] + (5,) + p[2:] print(q) r = p[:1], 5, p[2:] print(r) # 튜플은 리스트와 달리 원소값을 직접 바꿀수 없기때문에 오려붙이기
0d9271a4ef2e01231c56ce2a52185d490841c041
DMWillie/AlgorithmAndDataStruct
/Sort/BubbleSort.py
208
3.828125
4
"""冒泡排序""" def bubbleSort(arr): for i in range(1,len(arr)): for j in range(0,len(arr)-i): if(arr[j]>arr[j+1]): arr[j],arr[j+1] = arr[j+1],arr[j] return arr
e00165de1a5665174275b66e5c8471e71a247a1b
kayev1/set05-1
/weather.py
1,689
3.984375
4
def get_weather_icon(pct_rain): """ Given the percent chance of rain as an integer (e.g. 75 is 75%), return the name of the icon to be displayed.""" if int(pct_rain) <= 10: return 'fullsun.ico' elif int(pct_rain) <= 20: return 'suncloud.ico' elif int(pct_rain) <= 85: return 'twodrops.ico' elif int(pct_rain) <= 50: return 'onedrop.ico' else: return 'pouring.ico' pct_rain=input('Enter percent chance of rain as an integer (e.g. 75 is 75%):') print(get_weather_icon(pct_rain)) # Q15: What icon name is returned if there is a: # • 15% chance of rain? # print(get_weather_icon(15)) # suncloud.ico # • 90% chance of rain? # print(get_weather_icon(90)) # pouring.ico # Q16: For what range of pct_rain values that will result in the icon fullsun.ico? # The range between 0 and 10. # Q17: Run the test below to confirm that it passes. Add additional tests that check that the proper icon is returned for: # • 15% chance of rain # • 75% chance of rain # • 95% chance of rain # Run your tests to confirm that they all pass. assert get_weather_icon(5)=='fullsun.ico', 'should be fully sunny' # Q18: Add another one that checks that the onedrop.ico is returned when there is a 45% chance of rain. assert get_weather_icon(45)=='onedrop.ico', 'should be onedrop' # Q19: One of your tests in Q18 should fail. How can you tell from the output which test has failed? # The error message states the value for pct_rain for which the assertion is incorrect. # Q20: Correct the bug so that all of the tests in Q18 pass. Note, that if you run the file each time you edit the function below you will be able to re-run the tests in Q18.
1b94be4ea421568eddcf9e2b0cf76448ac6409ae
PzanettiD/practice
/accum.py
222
3.546875
4
def accum(s): # your code text = [] for i in range(len(s)): temp = s[i] * (i + 1) text.append(temp.capitalize()) new_s = '-'.join(text) return new_s b = accum('abcd') print(b)
b577fd989558130c2c9a14161af9a049545bec91
PzanettiD/practice
/timeformat.py
615
3.609375
4
def timeformat(seconds): minutes = 0 hours = 0 if seconds / 60 >= 1: for i in range(0, seconds, 60): if seconds - 60 < 0: break else: minutes += 1 seconds -= 60 if minutes == 60: hours += 1 minutes = 0 s = [str(hours).zfill(2), str(minutes).zfill(2), str(seconds).zfill(2)] outpt = ':'.join(s) return outpt print(timeformat(86399)) print(timeformat(86399)) print(timeformat(86399)) print(timeformat(86399)) print(timeformat(86399))
94b9dea1cff4fa563dcf1701fb14b05e3f9ad7da
595849292/econometrics
/optimization/gradient_descent.py
1,693
3.640625
4
# it solve for unconstrained optimization problem # example f=x**2+Y**2 import time import numpy as np import sympy class GD(): def __init__(self): self.variant='x y z' self.inivalue=[1,2,3] self.fvalue=0 self.f=sympy.simplify('x**2+y**3+z') def fun1(self,x): variant=self.variant.split(' ') for i in range(0,len(x)): if i==0: self.fvalue=self.f.subs(variant[i],self.inivalue[i]) else: self.fvalue=self.fvalue.sub(variant[i],self.inivalue[i]) return self.fvalue def gradient(self,f): fvalue='' variant = self.variant.split(' ') for i in range(0, len(f)): if i == 0: fvalue = f.subs(variant[i], self.inivalue[i]) else: fvalue = fvalue.sub(variant[i], self.inivalue[i]) return fvalue def gradient_descent(self): variant=sympy.symbols(self.variant) f=sympy.simplify(self.f) #variant=self.variant.split(' ') diff=[sympy.diff(f,variant[i])for i in range(0,len(variant))] second_error=1000 second_y=self.fun1(self.inivalue) while True: direction=[self.gradient(f) for f in diff] self.inivalue=np.array(self.inivalue)-np.array(direction) first_error=second_error first_y=second_y second_y=self.fun1(self.inivalue) second_error=abs(second_y-first_y) if second_error>first_error or second_error<0.01: print(self.inivalue) print(second_error) print(first_error) break
3df0972f9d6da16a68009240f911454c25d1ed32
amnsr17/py_torch_lrn
/8-RNN.py
8,720
3.6875
4
# -------------- Text generation ---------------- # ---------- Character Level Encoding ----------- # -------------- Vanilla RNN ------------- # hidden(t) = tanh ( Weight(t) * hidden(t-1) + Weight(input) * Input(t) ) # output(t) = Weight(output) * hidden(t) # ------------ Implementation Steps ----------- # 1 creating vocab # 2 padding # 3 splitting into input/labels # 4 one-hot encoding # 5 model defining # 6 model training # 7 model evaluation import torch from torch import nn import numpy as np # 1 --------------------------------------------- text = ["hey how are you", "good i am fine", "have a nice day"] chars = set(" ".join(text)) # joining the documents and getting unique characters i.e. vocabulary int2char = dict(enumerate(chars)) # dictionary : mapping of character on an integer char2int = {} # dictionary: mapping of integers on a character for reversing the encoding for k,v in int2char.items(): char2int.update({v:k}) print(char2int) # 2 --------------------------------------------- # padding w.r.t the longest string longest = max(text, key=len) max_len = len(longest) for i in range(len(text)): # all documents in text while len(text[i])<max_len: # append whitespace at the end of the doc till it reaches max_len text[i] += " " print("After padding text: ",text) # 3 --------------------------------------------- # input: last character removed # label/ground truth: first character removed (one time-step ahead of input data) input_seq = [] label_seq = [] for i in range(len(text)): input_seq.append(text[i][:-1]) label_seq.append(text[i][1:]) print("Input: ",input_seq) print("Label: ",label_seq) # 4 --------------------------------------------- # First integer encoding then one-hot-encoding # integer encoding the input and label for i in range(len(text)): input_seq[i] = [char2int[character] for character in input_seq[i]] label_seq[i] = [char2int[character] for character in label_seq[i]] print(input_seq) print(label_seq) # dict_size : dictionary length - determines the length of one-hot vectors # seq_len : length of sequences being fed to the model which is fixed: maxlength-1 as last char got removed # batch_size: the number of sentences in one batch dict_size = len(char2int) # 17 seq_len = max_len-1 # 14 batch_size = len(text) # 3 def hot_encoder(input_sequence, batch_size, seq_len, dict_size): """ creates arrays of zeroes for each character in a sequence and replaces the corresponding character-index with 1 i.e. makes it "hot". """ # multi-dim array of zeros with desired output size # shape = 3,14,17 # every doc is 14 char long. Each char is a 17 items long one-hot vector as dict_size is 17 onehot_data = np.zeros(shape=(batch_size, seq_len, dict_size)) # replacing the 0 with 1 for each character to make its one-hot vector for batch_item in range(batch_size): for sequence_item in range(seq_len): onehot_data[batch_item, sequence_item, input_sequence[batch_item][sequence_item] ] = 1 print("Shape of one-hot encoded data: ", onehot_data.shape) return onehot_data input_seq = hot_encoder(input_seq,batch_size, seq_len, dict_size) print("Input data after being shaped and one-hot:\n",input_seq) # From np array Tensor input_seq = torch.from_numpy(input_seq) label_seq = torch.Tensor(label_seq) print(label_seq) # 5 --------------------------------------------- if torch.cuda.is_available(): device = torch.device("cpu") else: device = torch.device("cpu") # Model: 1 layer of RNN followed by a fully connected layer. # This fully connected layer is responsible for converting the RNN output to our desired output shape. # The forward function is executed sequentially, therefore we'll have to pass the inputs and zero-initialized hidden # state through the RNN layer first,before passing the RNN outputs to the fully connected layer. # init_hidden(): Initializes the hidden state. Creates a tensor of zeros in the shape of our hidden states. class RnnModel(nn.Module): def __init__(self, input_size, output_size, hidden_size, n_layers): super(RnnModel, self).__init__() # parameter/data-member defining self.hidden_size = hidden_size self.n_layers = n_layers # layer defining # RNN Layer self.rnn = nn.RNN(input_size, hidden_size, n_layers, batch_first=True) # Fully Connected Layer self.fc = nn.Linear(hidden_size, output_size) def forward(self, x): batch_size = x.size(0) # size of input batch along axis=0 # initializing the hidden state for first input using init_hidden method defined below hidden = self.init_hidden(batch_size) # Input + hidden_state to RNN to generate output out, hidden = self.rnn(x, hidden) # Reshaping the output so it can be fit to the fully connected layer # contiguous() -> returns a contiguous tensor. good for performance. # output and labels/targets both should be contiguous for computing the loss # view() cannot be applied to a dis-contiguous tensor out = out.contiguous().view(-1, self.hidden_size) out = self.fc(out) return out,hidden def init_hidden(self, batch_size): # Generates the first hidden layer of zeros to be used in the forward pass. # the tesor holding the hidden state will be sent to the device specified earlier hidden = torch.zeros(self.n_layers, batch_size, self.hidden_size) return hidden # Instantiating the Model model = RnnModel(input_size=dict_size, output_size=dict_size, hidden_size=12, n_layers=1) model.to(device) # Hyper-parameters n_epochs = 100 lr =0.01 # Loss, optimizer criterion = nn.CrossEntropyLoss() optimizer = torch.optim.Adam(model.parameters(), lr=lr) # 6 --------------------------------------------- # Training for epoch in range(1, n_epochs+1): optimizer.zero_grad() # clearing existing gradients from previous epoch input_seq.to(device) output, hidden = model(input_seq.float()) # Error: Expected object of scalar type float but got scalar type Double loss = criterion(output, label_seq.view(-1).long()) loss.backward() # backpropagation gradient calculation optimizer.step() # weights update if epoch%10 == 0: print('Epoch: {}/{}...............'.format(epoch, n_epochs), end=' ') print('Loss: {:.4f}'.format(loss.item())) # 7 --------------------------------------------- # Sample takes the string, makes one-hot tensor of each character using one_hotter_char, # and passes it to predict for next character prediction # one-hot for training is not working on the single character. So this one does it separately def one_hotter_char(char, batch_size, seq_len, dict_size): """makes a single input character one-hot-encoded and returns a tensor""" onehot_data = np.zeros(shape=(batch_size, seq_len, dict_size)) char = char2int[char] print("Integer Encoded Character is: ",char) onehot_data[0][0][char] = 1 print("One-hot Character is: ",onehot_data) print(onehot_data.shape) # making it a tensor onehot_data = torch.from_numpy(onehot_data).float() # .float() is required otherwise Error: Expected object of scalar type Double but got scalar type Float onehot_data.to('cpu') print(type(onehot_data)) return onehot_data def predict(model, char_tensor): """Takes model and a one-hot encoded tensor of a character, and predicts the next character and returns it along with the hidden state.""" out, hidden = model(char_tensor) probability = nn.functional.softmax(out[-1], dim=0).data # Taking the class having highest score from the output char = torch.max(probability, dim=0)[1].item() char = int2char[char] # converting from int to character return char, hidden def sample(model, out_len, batch_size, seq_len, dict_size, start_txt="hey"): """Takes the desired output length and input characters as input and returns the produced sentence.""" model.eval() # evaluation mode of the model start_txt = start_txt.lower() chars = [c for c in start_txt] size = out_len - len(chars) # assuming that output_length is always bigger than input characters for i in range(size): char_tensor = one_hotter_char(chars[i], batch_size, seq_len, dict_size) predicted_char, h = predict(model, char_tensor) chars.append(predicted_char) return ''.join(chars) one_hotter_char("g", batch_size=1, seq_len=1, dict_size=dict_size) generated_txt = sample(model, 15, batch_size=1, seq_len=1, dict_size=dict_size, start_txt="good") print(generated_txt)
1d909e4aa9e2c5fe73738292b640b34abb1f45a7
AnnaLara/smartninjacourse
/Homework_lesson_7/Guess the secret number.py
358
3.890625
4
#!/usr/local/bin/python # -*- coding: utf-8 -*- def main(): import random secret = random.randint(1,10) guess = int(raw_input("Guess a number from 1 to 10: ")) print "The secret numer was " + str(secret) if guess == secret: print "You won!" else: print "You lost... Try again!" if __name__ == "__main__": main()
0d185cc97d007f7a5651615bfe254f646bdefa43
AnnaLara/smartninjacourse
/Lesson_11_homework/Vehicle_manager_program/vehicle_manager.py
3,362
4.15625
4
#!/usr/local/bin/python # -*- coding: utf-8 -*- class Car: def __init__(self, brand, model, km, service_date): self.brand = brand self.model = model self.km = km self.service_date = service_date def see_vehicles(list): for x in list: print list.index(x)+1 print x.brand print x.model print x.km print x.service_date print "\n" if not list: print "You don't have any vehicles in your contact list." def add_new_vehicle(list): brand = raw_input("Please enter vehicle's brand: ") model = raw_input("Please enter vehicle's model: ") km = raw_input("Please enter vehicle's kilometers done so far: ") service_date = raw_input("Please enter vehicle's service date: ") new_vehicle = Car(brand = brand, model = model, km = km, service_date = service_date) list.append(new_vehicle) print "Success! New vehicle has been added." def edit_vehicle(list): see_vehicles(list) index = int(raw_input("Please, indicate the number of the vehicle that you wish to edit: ")) - 1 while True: element_to_edit = raw_input("What element you would like to edit: brand, model, kilometers, service date? To stop editing enter quit. ").lower() print element_to_edit if element_to_edit == "brand": list[index].brand = raw_input("Enter new brand: ") elif element_to_edit == "model": list[index].model = raw_input("Enter new model: ") elif element_to_edit == "kilometers": list[index].km = raw_input("Enter new number of kilometers: ") elif element_to_edit == "service date": list[index].service_date = raw_input("Enter new service date: ") elif element_to_edit == "quit": break else: print "The answer is not valid" answer = raw_input("Would you like to keep editing? yes/no ").lower() if answer == "no": break def update_vehicles_txt(file_name, list): txt_file = open(file_name, "w") for element in list: txt_file.write(element.brand + " ") txt_file.write(element.model + " ") txt_file.write(element.km + " ") txt_file.write(element.service_date) txt_file.write("\n") txt_file.close() def main(): vehicles_list = [] tesla = Car(brand="tesla", model="x", km="50000", service_date="12/12/18") vehicles_list.append(tesla) smart = Car(brand="smart", model="sm", km="1300", service_date="13/12/18") vehicles_list.append(smart) update_vehicles_txt("vehicles.txt", vehicles_list) while True: print "What would you like to do?" print "a) See the list of the vehicles" print "b) Edit vehicle" print "c) Add new vehicle" action = raw_input("Please, select a, b or c: ").lower() if action == "a": see_vehicles(vehicles_list) elif action == "b": edit_vehicle(vehicles_list) update_vehicles_txt("vehicles.txt", vehicles_list) elif action == "c": add_new_vehicle(vehicles_list) update_vehicles_txt("vehicles.txt", vehicles_list) else: print "The input is not valid. Please, select a, b or c: " if __name__ == "__main__": main()
afdf0666b5d24b145a7fee65bf489fd01c4baa8c
OaklandPeters/til
/til/python/copy_semantics.py
1,348
4.21875
4
# Copy Semantics # ------------------------- # Copy vs deep-copy, and what they do # In short: copy is a pointer, and deep-copy is an entirely seperate data structure. # BUT.... this behavior is inconsistent, because of the way that attribute # setters work in Python. # Thus, mutations of attributes is not shared with copies, but mutations # of items IS shared. # See example #1 VS #2 import copy # Example #1 # Item mutation DOES change copies, but not deep copies original = ["one", "two", ["three", "333"]] shallow = copy.copy(original) deep = copy.deepcopy(original) assert (original == shallow) assert (original == deep) assert (shallow == deep) original[2][0] = "four" assert (original == shallow) assert (original != deep) assert (shallow != deep) # Example #2 # Attribute mutation does not change copies, nor deep copies class Person: def __init__(self, name): self.name = name def __repr__(self): return "{0}({1})".format(self.__class__.__name__, self.name) def __eq__(self, other): return self.name == other.name original = Person("Ulysses") shallow = copy.copy(original) deep = copy.deepcopy(original) assert (original == shallow) assert (original == deep) assert (shallow == deep) original.name = "Grant" assert (original != shallow) assert (original != deep) assert (shallow == deep)
4a92290522b34d30c72a22c4060770cadee3b300
jebutton/flysimchk
/src/model.py
6,888
3.734375
4
"""Module containing classes that represent data objects. Copyright 2019 Jacqueline Button. """ from typing import List from typing import Dict class ChecklistStep(): """Contains the data used in each step. Right now it is limited to just the text of the step title and text. Attributes: step_number: The number of the step. step_title: The title of the step. step_text: the step of the text. Args: step_number (int): The number of the step. step_title (str): The title of the step. step_text (str): The title of the step. """ def __init__(self, step_number: int, step_title: str, step_text: str): """Class Constructor.""" self.step_number = step_number self.step_title = step_title self.step_text = step_text def __str__(self): """Turn class into a str. Returns: A str representation of the ChecklistStep. """ output = '{ step_number: ' + str(self.step_number) + ' | step_title: ' output += self.step_title + ' | step_text: ' + self.step_text + ' }' return output def __repr__(self): """Turn a class into a str for debugging purposes. Returns: A str representation of the Plane. """ output = '{ ChecklistStep Object: step_number: ' output += str(self.step_number) output += ' | step_title: ' + self.step_title output += ' | step_text: ' + self.step_text + ' }' return output class Checklist(): """This is a class to represent a checklist. Attributes: message (str): The message to use when displaying the checklist. name (str): The name of the checklist, also used as an ID in some operations. steps (list of ChecklistStep): The steps of the Checklist. Args: name: The name of the check list. Should be stored in the plane file. message: The message to use when displaying the checklist. Should be stored in the plane file. steps (Optional): The steps of the checklist. Should be stored in the plane file. """ def __init__(self, name: str, message: str, steps: List[ChecklistStep] = None): """Class constructor.""" self.message = message self.name = name self.steps = steps if self.steps is None: self.steps = [] def __str__(self): """Turn class into a str. Returns: A str representation of the Checklist. """ step_count = len(self.steps) counter = 1 output = '{ name: ' + self.name + ' | message: ' + self.message output += ' | steps: [' for step in self.steps: if counter < step_count: if step is not None: output += str(step) + ', ' counter += 1 else: output += str(step) + ']' output += ' }' return output def __repr__(self): """Turn a class into a str for debugging purposes. Returns: A str representation of the Checklist. """ step_count = len(self.steps) counter = 1 output = '{ Checklist Object: name: ' + self.name output += ' | message: ' + self.message output += ' | count_of_steps: ' + str(step_count) output += ' | step numbers: [' for step in self.steps: if counter < step_count: if step is not None: output += str(step.step_number) + ', ' counter += 1 else: output += str(step.step_number) + '] ' counter = 1 output += ' | steps: [' for step in self.steps: if counter < step_count: if step is not None: output += str(step) + ', ' counter += 1 else: output += str(step) + ']' output = output + ' }' return output def sort_checklist(self): """Sort the checklist.""" self.steps = sorted(self.steps, key=lambda step: step.step_number) class Plane(): """This is class to represent a plane and all of its data. Attributes: plane_name (str): The name of the plane. plane_info (List of str): The additional information used in the plane. It will be expanded in a future releas. checklists (list of Checklist): The list containing all of the checklists for the plane. Args: plane_name: The name of the plane. plane_info: The additional info from the plane. checklists: The list of Checklists for the plane. """ def __init__(self, plane_name: str, plane_info: List[Dict[str, str]] = None, checklists: List[Checklist] = None): """Class Constructor.""" self.plane_name = plane_name self.plane_info = plane_info self.checklists = checklists if self.plane_info is None: self.plane_info = [] if self.checklists is None: self.checklists = [] self.checklists.append(Checklist('blank_list', 'There are no checklists for ' 'this plane')) def __str__(self): """Turn class into a str. Returns: A str representation of the Plane. """ checklist_count = len(self.checklists) counter = 1 output = '{ plane_name: ' + self.plane_name + ' | plane_info: ' output += str(self.plane_info) output += ' | checklists: [' + '\n' for checklist in self.checklists: if counter < checklist_count: output += str(checklist) + ',\n' counter += 1 else: output += str(checklist) + '\n]' output += ' }' return output def __repr__(self): """Turn a class into a str for debugging purposes. Returns: A str representation of the Plane. """ checklist_count = len(self.checklists) plane_info_count = len(self.plane_info) counter = 1 output = '{ Plane Object: plane_name: ' + self.plane_name output += ' | # of Plane Info Pairs: ' + str(plane_info_count) output += ' | plane_info: ' + str(self.plane_info) output += ' | # of Checklists: ' + str(checklist_count) output += ' | checklists: [\n' for checklist in self.checklists: if counter < checklist_count: output += repr(checklist) + ',\n' counter += 1 else: output += repr(checklist) + '\n]' output += ' }' return output
1f6ef830d9b8da66932e33af5275fcfe7b12dde4
andrewmaltezthomas/rosalind
/3.Reverse_Complement/Reverse_Complement.py
1,313
4.09375
4
""" What this script does: Input: A DNA string s of length at most 1000 bp. Return: The reverse complement s**c of s. """ #Import Sequence File import os print user_path = raw_input("Enter sequence file location: ") path = os.chdir(user_path) print sequence_file_location = raw_input("Enter sequence file name: ") print sequence_file = open(sequence_file_location, "r") sequence_file = sequence_file.read() #Reverse the sequence print print "Sequence is:" print print sequence_file sequence_file_reversed = sequence_file[::-1] print "Reverse Sequence is:" print sequence_file_reversed #Complement the sequence dic = {'A': 't', 'T': 'a', 'C': 'g', 'G': 'c', 'N': 'n', 'I': 'i', 'U': 'a', 'Y': 'r', 'R': 'y', 'K': 'm', 'M': 'k', 'B': 'v', 'D': 'h', 'H': 'd', 'V': 'b', 'S': 'w', 'W': 's'} def complement(text, dic): #Complement for i, j in dic.iteritems(): text = text.replace(i, j) text = text.upper() return text sequence_file_rc = complement(sequence_file_reversed,dic) print print "Reverse Complement Sequence is:" print sequence_file_rc print #ROSALIND SOLUTION #input S #reverse S #for i = 1 to length of S # if S[i] = 'A' then S'[i] = 'T' # if S[i] = 'T' then S'[i] = 'A' # if S[i] = 'C' then S'[i] = 'G' # if S[i] = 'G' then S'[i] = 'C' # # #print S'
60d6bc5574a943948baae691e33f18103de719d3
andrewmaltezthomas/rosalind
/7.Mendels_First_Law/mendel.py
1,815
3.96875
4
homozygous_dominant = raw_input("Enter number of homozygous dominant organisms:") homozygous_dominant = float(homozygous_dominant) heterozygous = raw_input("Enter number of heterozygous organisms:") heterozygous = float(heterozygous) homozygous_recessive = raw_input("Enter number of homozygous recessive organisms:") homozygous_recessive = float(homozygous_recessive) total = homozygous_recessive + homozygous_dominant + heterozygous # There are fewer ways to get two recessive alleles, # So calculate that instead and then subtract the result from one to get the probability of a dominant allele # Probability of two recessive parents mating: prob_homozygous_recessive = (homozygous_recessive / total) * ((homozygous_recessive - 1) / (total - 1)) # Probability of two heterozygous parents mating: prob_heterozygous = (heterozygous / total) * ((heterozygous - 1) / (total - 1)) # Punnet square for heterozygous mating: # | | Y | y | # |---+----+----| # | Y | YY | Yy | # | y | Yy | yy | # Only 1/4 of those will be recessive so we take the probability of two heterozygous mating and multiply it by 1/4. # Probability of a heterozygous and a recessive parent mating: prob_heterozygous_homozgous_recessive = (heterozygous / total) * (homozygous_recessive / (total - 1)) + (homozygous_recessive / total) * (heterozygous / (total - 1)) # Punnet square for heterozygous & recessive mating: # | | Y | y | # |---+----+----| # | y | Yy | yy | # | y | Yy | yy | # In this case half the offspring have two recessive alleles so multiply the probability by 1/2. # Total probability of a recessive allele: prob_recessive = prob_homozygous_recessive + prob_heterozygous * 1/4 + prob_heterozygous_homozgous_recessive * 1/2 # Probability of a dominant allele: prob_dominant = 1 - prob_recessive print prob_dominant
a5c715a92c166274f665a37557c98f73e5caef2b
ottomattas/py
/class-example-geometry.py
3,948
4.5625
5
#!/usr/bin/env python """This is a simple class with some attributes to calculate area and circumference for a circle.""" __author__ = "Otto Mättas" __copyright__ = "Copyright 2021, The Python Problems" __license__ = "MIT" __version__ = "0.1" __maintainer__ = "Otto Mättas" __email__ = "otto.mattas@eesti.ee" __status__ = "Development" ##################### # CLASS DEFINITIONS # ##################### # DEFINE THE CIRCLE CLASS / OBJECT class Circle: # DEFINE CLASS ATTRIBUTES pi = 3.14 # CIRCLE IS INSTANTIATED (WITH A DEFAULT RADIUS) def __init__(self, radius=1): # DEFINE INSTANCE ATTRIBUTES self.radius = radius self.area = Circle.pi * radius ** 2 # DEFINE METHOD FOR RESETTING RADIUS def setRadius(self, new_radius): self.radius = new_radius self.area = Circle.pi * new_radius ** 2 # DEFINE METHOD FOR CALCULATING CIRCUMFERENCE def getCircumference(self): return 2 * Circle.pi * self.radius # DEFINE THE CYLINDER CLASS / OBJECT class Cylinder: # DEFINE CLASS ATTRIBUTES pi = 3.14 # CYLINDER IS INSTANTIATED (WITH A DEFAULT HEIGHT AND RADIUS) def __init__(self,height=1,radius=1): # DEFINE INSTANCE ATTRIBUTES self.height = height self.radius = radius # DEFINE METHOD FOR CALCULATING VOLUME def volume(self): return Cylinder.pi * self.radius ** 2 * self.height # DEFINE METHOD FOR CALCULATING SURFACE AREA def surface_area(self): return 2 * Cylinder.pi * self.radius * (self.height + self.radius) # DEFINE THE LINE CLASS / OBJECT class Line: # LINE IS INSTANTIATED (WITH TWO COORDINATES) def __init__(self,coor1,coor2): # DEFINE INSTANCE ATTRIBUTES self.coor1 = coordinate1 self.coor2 = coordinate2 # DEFINE METHOD FOR CALCULATING DISTANCE def distance(self): # DEFINE LINE COORDINATES x1,y1 = self.coor1 x2,y2 = self.coor2 # RETURN DISTANCE return ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5 # DEFINE METHOD FOR CALCULATING SLOPE def slope(self): # DEFINE LINE COORDINATES x1,y1 = self.coor1 x2,y2 = self.coor2 # RETURN SLOPE return (y2 - y1) / (x2 - x1) ###################################### # CREATE INSTANCES AND PRINT RESULTS # ###################################### ########## # CIRCLE # ########## # CREATE AN INSTANCE OF A CIRCLE THROUGH THE CIRCLE CLASS circle = Circle() # PRINT A SEPARATOR WITH A COMMENT print() print('-----------------------') print('Circle calculations') # PRINT VALUES print('Radius is: ',circle.radius) print('Area is: ',circle.area) print('Circumference is: ',circle.getCircumference()) # PRINT A SEPARATOR WITH A COMMENT print('-----------------------') print('Resetting the circle radius') # RESET THE RADIUS FOR THE INSTANCE circle.setRadius(2) # PRINT VALUES FOR THE RESET INSTANCE print('New radius is: ',circle.radius) print('New area is: ',circle.area) print('New circumference is: ',circle.getCircumference()) ############ # CYLINDER # ############ # CREATE AN INSTANCE OF A CYLINDER THROUGH THE CYLINDER CLASS cylinder = Cylinder(2,3) # PRINT A SEPARATOR WITH A COMMENT print() print('-----------------------') print('Cylinder calculations') # PRINT VALUES print('Height is: ',cylinder.height) print('Radius is: ',cylinder.radius) print('Volume is: ',cylinder.volume()) print('Surface area is: ',cylinder.surface_area()) ############ # LINE # ############ # CREATE AN INSTANCE OF A LINE THROUGH THE LINE CLASS coordinate1 = (3,2) coordinate2 = (8,10) line = Line(coordinate1,coordinate2) # PRINT A SEPARATOR WITH A COMMENT print() print('-----------------------') print('Line calculations') # PRINT VALUES print('Point 1 coordinates are: ',coordinate1) print('Point 2 coordinates are: ',coordinate2) print('Distance is: ',line.distance()) print('Slope is: ',line.slope(),'degrees')
454f068d4b88865db55d1a8ea9d9b72954d82026
rhlklwr/flappy_bird_game
/flappy_bird.py
8,242
3.515625
4
import pygame from pygame.locals import * import sys import random # Global variable for game FPS = 32 SCREENWIDTH = 289 SCREENHEIGHT = 511 SCREEN = pygame.display.set_mode((SCREENWIDTH, SCREENHEIGHT)) # initialising display for game GROUND_Y = SCREENHEIGHT * 0.8 GAME_SPRITES = {} # this is use to store images GAME_SOUNDS = {} # this is use to store sound PLAYER = 'gallery/sprites/bird.png' BACKGROUND = 'gallery/sprites/background.png' PIPE = 'gallery/sprites/pipe.png' def welcome_screen(): """ It will use to show images on initial screen """ # player_position_at_x = int(SCREENWIDTH/5) # player_position_at_y = int(SCREENHEIGHT - GAME_SPRITES['player'].get_height())/2 # (H-h)/2 message_screen_at_x = int(SCREENWIDTH - GAME_SPRITES['message'].get_height())/2+40 # 40 is offset value which I have set after running game message_screen_at_y = int(SCREENHEIGHT * 0.25) base_at_x = 0 while True: for event in pygame.event.get(): # if user clicks on cross button, close the game if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() # If the user presses space or up key, start the game for them elif event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_UP): return else: SCREEN.blit(GAME_SPRITES['background'], (0, 0)) # SCREEN.blit(GAME_SPRITES['player'], (player_position_at_x, player_position_at_y)) SCREEN.blit(GAME_SPRITES['message'], (message_screen_at_x, message_screen_at_y)) SCREEN.blit(GAME_SPRITES['base'], (base_at_x, GROUND_Y)) pygame.display.update() FPS_CLOCK.tick(FPS) def start_game(): score = 0 player_position_at_x = int(SCREENWIDTH/5) player_position_at_y = int(SCREENHEIGHT/2) base_position_at_x = 0 new_pipe1 = random_pipe() new_pipe2 = random_pipe() upper_pipes = [ {'x': SCREENWIDTH+200, 'y': new_pipe1[0]['y']}, {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y': new_pipe1[0]['y']} ] lower_pipes = [ {'x': SCREENWIDTH+200, 'y': new_pipe2[1]['y']}, {'x': SCREENWIDTH+200+(SCREENWIDTH/2), 'y': new_pipe2[1]['y']} ] pipe_velocity_at_x = -4 player_velocity_y = -9 player__max_velocity_y = 10 player_min_velocity_y = -8 player_acceleration_y = -1 player_flap_velocity = -8 is_player_flapped = False while True: for event in pygame.event.get(): if event.type == QUIT or (event.type == KEYDOWN and event.key == K_ESCAPE): pygame.quit() sys.exit() if event.type == KEYDOWN and (event.key == K_SPACE or event.key == K_LEFT): if player_position_at_y > 0: player_velocity_y = player_flap_velocity is_player_flapped = True GAME_SOUNDS['wing'].play() crash_test = is_collide(player_position_at_x, player_position_at_y, upper_pipes, lower_pipes) if crash_test: return # check for score player_mid_position = player_position_at_x + GAME_SPRITES['player'].get_width()/2 for pipe in upper_pipes: pipe_mid_pos = pipe['x'] + GAME_SPRITES['pipe'][0].get_width()/2 if pipe_mid_pos <= player_mid_position <pipe_mid_pos + 4: score += 1 print(f'your score is {score}') GAME_SOUNDS['point'].play() if player_velocity_y < player__max_velocity_y and not is_player_flapped: player_velocity_y += player_acceleration_y if is_player_flapped: is_player_flapped = False player_height = GAME_SPRITES['player'].get_height() player_position_at_y = player_position_at_y + min(player_velocity_y, GROUND_Y - player_position_at_y - player_height) for upper_pipe, lower_pipe in zip(upper_pipes, lower_pipes): upper_pipe['x'] += pipe_velocity_at_x lower_pipe['x'] += pipe_velocity_at_x # adding new pipe if 0 < upper_pipes[0]['x'] < 5: new_pipe = random_pipe() upper_pipes.append(new_pipe[0]) lower_pipes.append(new_pipe[1]) # Removing pipe when they are out of display if upper_pipes[0]['x'] < -GAME_SPRITES['pipe'][0].get_width(): upper_pipes.pop(0) lower_pipes.pop(0) SCREEN.blit(GAME_SPRITES['background'], (0, 0)) for upper_pipe, lower_pipe in zip(upper_pipes, lower_pipes): SCREEN.blit(GAME_SPRITES['pipe'][0], (upper_pipe['x'], upper_pipe['x'])) SCREEN.blit(GAME_SPRITES['pipe'][1], (lower_pipe['x'], lower_pipe['x'])) SCREEN.blit(GAME_SPRITES['base'], (base_position_at_x, GROUND_Y)) SCREEN.blit(GAME_SPRITES['player'], (player_position_at_x, player_position_at_y)) my_digits = [int(x) for x in list(str(score))] width = 0 for digit in my_digits: width += GAME_SPRITES['numbers'][digit].get_width() x_offset = (SCREENWIDTH - width)/2 for digit in my_digits: SCREEN.blit(GAME_SPRITES['numbers'][digit], (x_offset, SCREENWIDTH * 0.12)) x_offset += GAME_SPRITES['numbers'][digit].get_width() pygame.display.update() FPS_CLOCK.tick(FPS) def is_collide(player_position_at_x, player_position_at_y, upper_pipes, lower_pipes): return False def random_pipe(): """ Generate random position of pipe for upper and lower one's """ pipe_height = GAME_SPRITES['pipe'][0].get_height() offset = SCREENHEIGHT/3 position_for_lower_pipe_at_y = random.randrange(0, int(SCREENHEIGHT - GAME_SPRITES['base'].get_height() - 1.2 * offset)) pipe_x = SCREENWIDTH * 10 position_for_upper_pipe_at_y = pipe_height - position_for_lower_pipe_at_y + offset pipe = [ {'x': pipe_x, 'y': position_for_upper_pipe_at_y}, {'x': pipe_x, 'y': position_for_lower_pipe_at_y} ] return pipe if __name__ == '__main__': pygame.init() FPS_CLOCK = pygame.time.Clock() pygame.display.set_caption('Flappy Bird design by Rahul') # adding number into sprites to blit score on screen GAME_SPRITES['numbers'] = ( pygame.image.load('gallery/sprites/0.png').convert_alpha(), pygame.image.load('gallery/sprites/1.png').convert_alpha(), pygame.image.load('gallery/sprites/2.png').convert_alpha(), pygame.image.load('gallery/sprites/3.png').convert_alpha(), pygame.image.load('gallery/sprites/4.png').convert_alpha(), pygame.image.load('gallery/sprites/5.png').convert_alpha(), pygame.image.load('gallery/sprites/6.png').convert_alpha(), pygame.image.load('gallery/sprites/7.png').convert_alpha(), pygame.image.load('gallery/sprites/8.png').convert_alpha(), pygame.image.load('gallery/sprites/9.png').convert_alpha() ) # adding message image in sprite to blit on screen GAME_SPRITES['message'] = pygame.image.load('gallery/sprites/message.png').convert_alpha() GAME_SPRITES['base'] = pygame.image.load('gallery/sprites/base.png').convert_alpha() GAME_SPRITES['player'] = pygame.image.load(PLAYER).convert_alpha() GAME_SPRITES['background'] = pygame.image.load(BACKGROUND).convert() GAME_SPRITES['pipe'] = ( pygame.transform.rotate(pygame.image.load(PIPE).convert_alpha(), 180), pygame.image.load(PIPE).convert_alpha() ) # loading sound in dictionary GAME_SOUNDS['die'] = pygame.mixer.Sound('gallery/audio/die.wav') GAME_SOUNDS['hit'] = pygame.mixer.Sound('gallery/audio/hit.wav') GAME_SOUNDS['point'] = pygame.mixer.Sound('gallery/audio/point.wav') GAME_SOUNDS['swoosh'] = pygame.mixer.Sound('gallery/audio/swoosh.wav') GAME_SOUNDS['wing'] = pygame.mixer.Sound('gallery/audio/wing.wav') while True: welcome_screen() start_game()
4cbfb6c04bb9f888fb684b599d30c8a95dcbdfaf
parth2651/PythonLearningSample
/preprocessingdata.py
1,248
3.84375
4
import pandas as pd from sklearn.preprocessing import MinMaxScaler # Load training data set from CSV file training_data_df = pd.read_csv("Training.csv") # Load testing data set from CSV file test_data_df = pd.read_csv("Testing.csv") # Data needs to be scaled to a small range like 0 to 1 for the neural # network to work well. scaler = MinMaxScaler(feature_range=(0, 1)) # Scale both the training inputs and outputs scaled_training = scaler.fit_transform(training_data_df) scaled_testing = scaler.transform(test_data_df) # Print out the adjustment that the scaler applied to the total_earnings column of data print("Note: total_earnings values were scaled by multiplying by {:.10f} and adding {:.6f}".format(scaler.scale_[1], scaler.min_[1])) ##Note: total_earnings values were scaled by multiplying by 0.0039682540 and adding 0.000000 # Create new pandas DataFrame objects from the scaled data scaled_training_df = pd.DataFrame(scaled_training, columns=training_data_df.columns.values) scaled_testing_df = pd.DataFrame(scaled_testing, columns=test_data_df.columns.values) # Save scaled data dataframes to new CSV files scaled_training_df.to_csv("Training_scaled.csv", index=False) scaled_testing_df.to_csv("Testing_scaled.csv", index=False)
1030aacf43ea48c97a7f4f407a829429f4171929
wdfnst/StochasticGradientDescentNeuralNetwork
/two_layer_neural_network.py
1,126
4.09375
4
import sys import numpy as np # compute sigmoid nonlinearity def sigmoid(x): output = 1/(1+np.exp(-x)) return output # convert output of sigmoid function to its derivative def sigmoid_output_to_derivative(output): return output*(1-output) # input dataset X = np.array([ [0,1], [0,1], [1,0], [1,0] ]) # output dataset y = np.array([[0,0,1,1]]).T # seed random numbers to make calculation # deterministic (just a good practice) np.random.seed(1) # initialize weights randomly with mean 0 synapse_0 = 2*np.random.random((2,1)) - 1 for iter in xrange(10000): # forward propagation layer_0 = X layer_1 = sigmoid(np.dot(layer_0,synapse_0)) # how much did we miss? layer_1_error = layer_1 - y # multiply how much we missed by the # slope of the sigmoid at the values in l1 layer_1_delta = layer_1_error * sigmoid_output_to_derivative(layer_1) synapse_0_derivative = np.dot(layer_0.T,layer_1_delta) # update weights synapse_0 -= synapse_0_derivative print "Output After Training:" print layer_1
902623aa65a95e273af213f5144f40f50b96c1d9
hetzz/30DaysChallenge
/April/Day19/solution.py
587
3.75
4
def search(nums, target): low = 0 high = len(nums) - 1 while low <= high: mid = low + (high - low) // 2 if target == nums[mid]: return mid elif nums[mid] <= nums[high]: if( target > nums[mid]) & (target <= nums[high]): low = mid + 1 else: high = mid - 1 else: if (nums[low] <= target) & (target < nums[mid]): high = mid - 1 else: low = mid + 1 return -1 nums = [4,5,6,7,0,1,2] target = 0 print(search(nums,target))
162086004a87d73de9ea916be83dcb64d8551efb
hetzz/30DaysChallenge
/April/Day13/solution.py
791
3.625
4
def findMaxLength(nums): hash_map = {} curr_sum = 0 max_len = 0 ending_index = -1 n = len(nums) for i in range (0, n): if(nums[i] == 0): nums[i] = -1 for i in range (0, n): curr_sum = curr_sum + nums[i] if (curr_sum == 0): max_len = i + 1 ending_index = i if curr_sum in hash_map: if max_len < i - hash_map[curr_sum]: max_len = i - hash_map[curr_sum] ending_index = i else: hash_map[curr_sum] = i for i in range (0, n): if(nums[i] == -1): nums[i] = 0 else: nums[i] = 1 return max_len num = [1,0,1] print(findMaxLength(num))
a383876dd585215aa178a9d4c3b5ec9aee6c9494
omegadefender/Python-Exercises-and-Unit-Testing-Practice
/exercises/name_exercise.py
752
3.75
4
from itertools import dropwhile def id_consonants(x): return x not in 'aeiouy' def vowel(name): schop = ''.join(dropwhile(id_consonants, name)) if len(schop) > 1 and schop[0] == 'y' and schop[1] in 'aeiou': return schop[1:] elif len(name) > 0 and schop == '': return name elif name == '': return "noname" else: return schop def name_speller(n): n = input("\nYour name please: ").lower() ncap = n.capitalize() nchop = vowel(n) if nchop != "noname": return ( f"\n{ncap}?\n" f"{ncap} Fif{nchop} Stickal{nchop} Fif{nchop}\n" f"That's how you spell '{ncap}!'\n") else: return "\nDo you feel lucky?\nWell do you, punk?\n"
8faaf7e90939099218fe30068e6dd0f87970d0ea
jeanbcaron/course-material
/exercices/210/solution.py
305
3.640625
4
def is_prime(a): b = 0 for i in range(int(pow(a, 0.5))): if a % (i+2) == 0: if a != (i+2): b = 1 if b == 1 or a == 1: return False if b != 1: return True sol = 0 for j in range(1000): if is_prime(j): sol = sol + j print(sol)
63882b27e6281cf19c5c09307166dc8976eb3947
jeanbcaron/course-material
/exercices/200/solution.py
212
3.671875
4
def is_prime(a): b = 0 for i in range(int(pow(a, 0.5))): if a % (i+2) == 0: if a != (i+2): b = 1 if b == 1: return False if b != 1: return True
9e71ea1ce5ac93f533969630e9586799065740b1
SfundoMhlungu/Suicide-Checkers-py
/helpers.py
3,781
3.8125
4
# the functions below are helpers, the howmany left is for the minimax hearistic value # the nbo possible moves checks which player has won # virtual move original created for minimax to make a fake move on a board, until it minimax finds the most optimal one #####################attempt translation to cpp################################################### """ translation to cpp nothing is new in this file, howmany left function uses the exact same for loops as the board creation function, use it a reference, also the ValidBlack or red fuctions do the same nopossible moves functions also there is nothing new the interesing part is the returns, 1 if player has no moves == win else return 0 virtual move function, just makes a move in a boar, checks if it is an empty or a single jump then takes the coordinates and make a move """ def howmanyleft(board, player): #check how many pieces black has size = len(board[0]) left = 0 if player == 'Black': #how many pieces are left for black for z in range(0, size): for j in range(0, size): if board[z][j] == 'B': left += 1 else: for z in range(0, size): for j in range(0, size): if board[z][j] == 'R': left += 1 return left def nopossibleMoves(board, player, moves): if player == 'Black': if len(moves) == 0: return 1 else: return 0 else: if len(moves) == 0: return 1 else: return 0 def VirtualMove(board, player, Move): if player == 'Black': #single move if len(Move) == 3: board[Move['oldpos'][0]][Move['oldpos'][1]] = 'E' board[Move['enemy'][0]][Move['enemy'][1]] = 'E' board[Move['new'][0]][Move['new'][1]] = 'B' ################################################# NEW ####################################################################### elif len(Move) == 4: print('Black double move: ', Move) board[Move['oldpos'][0]][Move['oldpos'][1]] = 'E' board[Move['enemy1'][0]][Move['enemy1'][1]] = 'E' board[Move['enemy2'][0]][Move['enemy2'][1]] = 'E' board[Move['new'][0]][Move['new'][1]] = 'B' ############################################################################################################################ else: board[Move['oldpos'][0]][Move['oldpos'][1]] = 'E' board[Move['new'][0]][Move['new'][1]] = 'B' # for red player else: if len(Move) == 3: board[Move['oldpos'][0]][Move['oldpos'][1]] = 'E' board[Move['enemy'][0]][Move['enemy'][1]] = 'E' board[Move['new'][0]][Move['new'][1]] = 'R' #################################### NEW ################################################################## elif len(Move) == 4: board[Move['oldpos'][0]][Move['oldpos'][1]] = 'E' board[Move['enemy1'][0]][Move['enemy1'][1]] = 'E' board[Move['enemy2'][0]][Move['enemy2'][1]] = 'E' board[Move['new'][0]][Move['new'][1]] = 'R' ########################################################################################################### else: board[Move['oldpos'][0]][Move['oldpos'][1]] = 'E' board[Move['new'][0]][Move['new'][1]] = 'R'
3af51321a5e8cfa7f75ff8898713152e13fb660d
bootphon/word-count-estimator
/wce/word_count_estimation/rttm_processing.py
4,803
3.53125
4
"""Rttm processing Module to extract segments of speech from the original wavs by reading its related .rttm file and gather the results of the WCE on the segments that come from the same audio. The module contains the following functions: * extract_speech - extract speech for one file. * extract_speech_from_dir - extract speech for files in a directory. * retrieve_word_counts - write the gathered results per file to a .csv file. """ import os, sys, glob import csv import subprocess import shutil import numpy as np def extract_speech(audio_file, rttm_file, chunks_dir): """ Extract speech segments from an audio file. Parameters ---------- audio_file : str Path to the audio file. rttm_file : str Path to the corresponding rttm file. chunks_dir : str Path to the directory where to store the resulting wav chunks. Returns ------- wav_list : list List of the .wav files corresponding to the speech segments. onsets : List of the onsets of the speech segments. offsets : List of the offsets of the speech segments. """ wav_list = [] onsets = [] offsets = [] try: with open(rttm_file, 'r') as rttm: i = 0 for line in rttm: # Replace tabulations by spaces fields = line.replace('\t', ' ') # Remove several successive spaces fields = ' '.join(fields.split()) fields = fields.split(' ') onset, duration, activity = float(fields[3]), float(fields[4]), fields[7] if activity == 'speech': basename = os.path.basename(audio_file).split('.wav')[0] output = os.path.join(chunks_dir, '_'.join([basename, str(i)])+'.wav') cmd = ['sox', audio_file, output, 'trim', str(onset), str(duration)] subprocess.call(cmd) wav_list.append(output) onsets.append(onset) offsets.append(onset+duration) i += 1 except IOError: shutil.rmtree(chunks_dir) sys.exit("Issue when extracting speech segments from wav.") onsets = np.array(onsets) offsets = np.array(offsets) return wav_list, onsets, offsets def extract_speech_from_dir(audio_dir, rttm_dir, sad_name): """ Extract speech for files in a directory. Parameters ---------- audio_dir : str Path to the directory containing the audio files (.wav). rttm_dir : str Path to the directory containing the SAD files (.rttm). sad_name : str Name of the SAD algorithm used. Returns ------- wav_list : list List containing the path to the wav segments resulting from the trim. """ wav_list = [] audio_files = glob.glob(audio_dir + "/*.wav") if not audio_files: sys.exit(("speech_extractor.py : No audio files found in {}".format(audio_dir))) chunks_dir = os.path.join(audio_dir, "wav_chunks_predict") if not os.path.exists(chunks_dir): os.mkdir(chunks_dir) else: shutil.rmtree(chunks_dir) os.mkdir(chunks_dir) for audio_file in audio_files: rttm_filename = "{}_{}.rttm".format(sad_name, os.path.basename(audio_file)[:-4]) rttm_file = os.path.join(rttm_dir, rttm_filename) if not os.path.isfile(rttm_file): sys.exit("The SAD file %s has not been found." % rttm_file) wav_list.append(extract_speech(audio_file, rttm_file, chunks_dir)[0]) wav_list = np.concatenate(wav_list) return wav_list def retrieve_files_word_counts(word_counts, wav_chunks_list, output_path): """ Retrieve the word count for each file from the wav chunks' word counts. Parameters ---------- word_counts : list List of the word counts per wav chunk. wav_chunks_list : list List of paths to the wav chunks. output_path : str Path to the output_path file where to store the results. """ files = [] files_word_counts = [] for f in wav_chunks_list: filepath = '_'.join(f.split('_')[:-1]) filename = os.path.basename(filepath) if filename not in files: files.append(filename) for f in files: indices = [x for x, y in enumerate(wav_chunks_list) if f in y] wc = 0 for i in indices: wc += word_counts[i] files_word_counts.append((f, wc)) with open(output_path, 'w') as out: csvwriter = csv.writer(out, delimiter=';') for row in files_word_counts: csvwriter.writerow(row) print("Output saved at: {}.".format(output_path))
7e68241f8b3d58f5cd910f472dc9349080c5ab73
koukic/perceptron
/perceptron.py
3,244
3.578125
4
import numpy as np import matplotlib.pylab as plt # パーセプトロンクラス class PerceptronClassifier: def __init__(self, alpha, t , x): self.alpha = alpha self.weight = np.random.uniform(-1.0, 1.0, 3) # -1.0~1.0の乱数を3つ self.x = x self.t = t # 点を描画 self.plot_pixels() # 点を描画する def plot_pixels(self): # 点を画面に描画 for p,type in zip(self.x,self.t): #zip関数使っているよ print(p,":",type) if type == 1: plt.plot(p[0],p[1],"o",color="b") # 1は青い○p[0]とp[1]はx,y else: plt.plot(p[0],p[1],"x",color="r") # 0は赤い× # 学習 def learn(self): updated = True #更新が必要かどうか初期値 n = 0 while updated: #updateがtrueならずっと updated = False #一旦 for category, features in zip(self.t, self.x): predict = self.classify(features) # 点が上か下かを評価 if predict != category: # 線の描画 self.plot_line(n,False) # 重みの更新 t = 2 * (category - 0.5) # category0なら-1、category1なら1 self.weight = self.weight + self.alpha * t * np.append(features, 1) #重みの調整 updated = True n = n + 1 # 確定した線を描画する self.plot_line(n,True) # 線の表示 def plot_line(self,n,last): print(n,":",self.weight) plt.xlim([-0.1,1.1]) # Xの範囲は-0.1から1.1 plt.ylim([-0.1,1.1]) # yの範囲は-0.1から1.1 if self.weight[1] != 0: x = np.arange(-0.1,1.1,0.5) # xの値域(0, 1, 2, 3) y = -self.weight[0] / self.weight[1] * x - self.weight[2] / self.weight[1] elif self.weight[0] != 0: y = np.arrange(-0.1,1.1,0.1) x = self.weight[2] / self.weight[0] else: x = 0 y = 0 if last == True: plt.plot(x,y,"k-") # 黒の直線を引く else: plt.plot(x,y,"g-",linestyle="dotted") # 緑の直線を引く # 分類 def classify(self, features): score = np.dot(self.weight, np.append(features, 1)) # 関数による評価 # ステップ関数で分類 return self.f(score); # 活性化関数(ステップ関数) def f(self,x): if x > 0: return 1 else: return 0 # 処理結果の表示 def plot_show(self): plt.show() def main(): # 点の座標 x = np.array([[0, 0],[0,1],[1,0],[1,1]]) # 手の野種類(○:1 ×:0) 上のそれぞれの座標を評価 t = np.array([0,1,1,1]) # サイズを2にして、αを0,1二設定 classifier = PerceptronClassifier(0.05,t,x) # 学習フェーズ classifier.learn() # 結果の描画 classifier.plot_show() if __name__ == "__main__": main()
6289c503c8bcb4f018b0246ca7701e33e69b73f8
oorion/exercism
/python/word-count/wordcount.py
339
3.8125
4
import re def word_count(sentence): split_sentence = re.split(' +| *\n *|\t', sentence) output = {} for x in split_sentence: output[x] = count_word(x, split_sentence) return output def count_word(word, iterable): count = 0 for x in iterable: if x == word: count += 1 return count
d4d24193ecd8d87635579b434a0f36469de8a147
Keyurchaniyara/CompetitiveProgramming
/Interview Questions/04_Valid_Anagram.py
342
3.5
4
class Solution: def isAnagram(self, s: str, t: str) -> bool: if sorted(s) == sorted(t): if 1<=len(s)<=(5*pow(10,4)): return True else: if 1<=len(s)<=(5*pow(10,4)): return False s = Solution() s.isAnagram("anagram","nagaram")
429abba14b7125c258e394db7f1d27a6cde567dc
hmakinde/Python-Challenge-HM
/PyPoll/PyPoll_main.py
2,878
3.734375
4
import csv import os import numpy as np electionfile = os.path.join("Resources", "election_data.csv") candidates = [] votes = [] filetype = "main" #Creates dictionary to be used for candidate name and vote count. poll = {} #Sets variable, total votes, to zero for count. total_votes = 0 with open(electionfile, newline="") as csvfile: election = csv.reader(csvfile, delimiter=",") election_header = next(election) #creates dictionary from file using column 3 as keys, using each name only once. #counts votes for each candidate as entries #keeps a total vote count by counting up 1 for each loop (# of rows w/o header) for row in election: total_votes += 1 if row[2] in poll.keys(): poll[row[2]] = poll[row[2]] + 1 else: poll[row[2]] = 1 print(total_votes) #takes dictionary keys and values and, respectively, dumps them into the lists, # candidates and num_votes for key, value in poll.items(): candidates.append(key) votes.append(value) # creates vote percent list vote_percent = [] for n in votes: vote_percent.append(round(n/total_votes*100, 1)) # zips candidates, num_votes, vote_percent into tuples clean_data = list(zip(candidates, vote_percent, votes )) summaries =[] for row in clean_data: # print(row[0] + ":", str(row[1]) + "%", "(" + str(row[2]) + ")") summary = (row[0] + ": ", str(row[1]) + "%", " (" + str(row[2]) + ")") summaries.append(summary) print(summaries) for k in range(len(vote_percent)): if votes[k] > votes[k - 1]: winner = candidates[k] # #creates winner_list to put winners (even if there is a tie) # winner_list = [] # for name in clean_data: # if max(votes) == name[1]: # winner_list.append(name[0]) # # makes winner_list a str with the first entry # winner = winner_list[0] # #only runs if there is a tie and puts additional winners into a string separated by commas # if len(winner_list) > 1: # for w in range(1, len(winner_list)): # winner = winner + ", " + winner_list[w] #set output destination and write files output_dest = os.path.join('/Users/hmm794/Documents/Github/Python-Challenge-HM/PyPoll' + str(filetype) + '.txt') with open(output_dest, 'w') as writefile: writefile.writelines('Election Results\n') writefile.writelines('----------------------------' + '\n') writefile.writelines('Total Votes: ' + str(total_votes) + '\n') writefile.writelines('----------------------------' + '\n') writefile.writelines(str(summaries) + '\n') writefile.writelines('----------------------------' + '\n') writefile.writelines('Winner: ' + str(winner) + '\n') #writefile.writerows([ # #prints file to terminal # with open(output_file, 'r') as readfile: # print(readfile.read())
2c90b90bc91309e327def9cd93abe87e177a8626
WisdomDaPhoenix/Python
/Curse Words Program.py
791
3.84375
4
#Change all curse words to '****' within a string, simulating parental controls s = input('Enter a string: ') L = ['darn','dang','freakin','heck','shoot','Darn','Dang','Freakin','Heck','Shoot'] for i in range(len(s)): for t in L: if t in s: s = s.replace(t,len(t)*'*',-1) print(s) #OR s = input('Enter a string: ') s = s.lower() L = ['darn','dang','freakin','heck','shoot'] for i in L: if 'freakin' in s: s = s.replace('freakin','*******',-1) elif 'darn' in s: s = s.replace('darn','****',-1) elif 'shoot' in s: s = s.replace('shoot','*****',-1) elif 'heck' in s: s = s.replace('heck','****',-1) elif 'dang' in s: s = s.replace('dang','*****',-1) print(s)
e12b92bd3b8ba18d92db758aacfbae6a4c6abce0
Aparecida-Silva/Funcao-Split-e-len
/Média.py
467
3.9375
4
nota1 = eval(input("Digite a sua primeira nota: ")) nota2 = eval(input("Digite a sua segunda nota: ")) print("") if (nota1 <= 60 and nota2 <= 60): valor1 = nota1 * (100 / 100) print("O valor da sua primeira nota: ") print(valor1) valor2 = nota2 * (80 / 100) print("O valor da sua segunda nota: ") print(valor2) notafinal = valor1 + valor2 print("") print("Sua média final foi: ", notafinal) else: print("O valor da nota deve ser menor que 60!")
d2cc6c889ff35b1baba911fe72bb842af86d6d58
Cyvid7-Darus10/Codecademy
/Learn Complex Data Structures/HashMapsPython.py
2,025
3.5
4
class HashMap: def __init__(self, array_size: int): self.array_size = array_size self.array = [None for item in range(array_size)] def hashFunc(self, key, count_collisions: int = 0) -> int key_bytes = key.encode() hash_code = sum(key_bytes) return (hash_code + count_collisions) % self.array_size def assign(self, key: 'any type' , value: 'any type'): array_index = self.hashFunc(key) current_array_value = self.array[array_index] number_collisions = 0 while(current_array_value != None and current_array_value[0] != key): if number_collisions > self.array_size: #All array values are travelled print("Array is Full") return number_collisions += 1 array_index = self.hashFunc(key, number_collisions) current_array_value = self.array[array_index] self.array[array_index] = [key, value] def retrieve(self, key): array_index = self.hashFunc(key) possible_return_value = self.array[array_index] if possible_return_value == None: return None retrieval_collisions = 0 while (possible_return_value[0] != key): if retrieval_collisions > self.array_size: #All array values are travelled return None retrieval_collisions += 1 retrieving_array_index = self.hashFunc(key, retrieval_collisions) possible_return_value = self.array[retrieving_array_index] return possible_return_value[1] def main(): hash_map = HashMap(15) hash_map.assign("gabbro", "igneous") hash_map.assign("sandstone", "sedimentary") hash_map.assign("gneiss", "metamorphic") hash_map.assign("2gabbra", "2igneous") hash_map.assign("2sandsone", "2sedimentary") hash_map.assign("2gneis", "2metamorphic") hash_map.assign("1gabro", "1igneous") hash_map.assign("1sadstone", "1sedimentary") hash_map.assign("1geiss", "1metamorphic") print (hash_map.retrieve("gabbro")) print (hash_map.retrieve("sandstone")) print (hash_map.retrieve("2gneis")) if __name__ == "__main__": main()
4929c3e42fb811f577c1151575655f4da7a70294
aakankshamudgal/ML
/class.py
305
3.71875
4
class Calculator: def add(a,b): return a+b def sub(a,b): if(a>b): return a-b else: return b-a def mul(a,b): return a*b def div(a,b): return a/b def mod(a,b): return a%b x=add(4,5) print(x) y=sub(6,7) print(y) z=mul(3,2) print(z) c=div(4,2) print(c) d=mod(4,2) print(d)
aa0ab44c8775e6173887aad4251acf933ceaf4fc
Mitchellsuiter/Coding-projects-Junior-year
/Port_scanner.py
1,094
3.53125
4
import socket ip_address_list = ['31.13.74.36', '172.217.14.174', '40.97.142.194'] for ip in ip_address_list: print("Begin IP Scan on: " + ip + ".") try: for port in range(1,1000): #Create the Socket aSocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #Set the timeout to 2 seconds aSocket.settimeout(1) #Attempt to connect res = aSocket.connect_ex((ip, port)) if res == 0: #If res is 0, then the port is open. print("IP: " + str(ip) + " | Port Number " + str(port) + " is open.") else: #Otherwise, the port is considered closed print("IP: " + str(ip) + " | Port Number " + str(port) + " is closed.") #Close the socket aSocket.close() #Timeout exception except socket.timeout: print("Timeout has happened.") #Failure to connect to server exception except socket.error: print("Could not connect to the server.") print("I have finished scanning the ports.")
edb9dccf04443ff5c38694de85b8d63d5277cabd
NathanaelLeclercq/VSA-literate-waddlee
/scratches/scratch_2.py
305
3.8125
4
def myfunction(): print "I called My function" myfunction() def largest(x,y): ans = x if y > x: return ans largenum = largest(2,5) print largenum def getnum(prompt): ans = int(raw_input(prompt)) age = getnum("what is you age?") grade = getnum("what is your grade?")
6fd152a4821d311a934af8f894430e0775157083
Broges/brogesBrewApp
/core/menuSelect.py
2,265
3.734375
4
'''This file handles the menus; it prints out the users options and calls the methods required when the relevant option is chose. Essentially this is the 'control tower'. ''' from core.roundClass import user_round from core.dbManager import db from core.preferenceClass import pref from core.utils import clearScreen class Selection(): #class to manage menu choices def __init__(self): #constructor is passed as only one instance of pass #the class is required def selector(self): selection = input("\nEnter your selection here: ") print("\n") if selection == "1": db.print_db_person() #calls method which returns all people in database elif selection == "2": db.print_db_drinks() #calls method which returns all drinks in database elif selection == "3": db.insert_db_person() #calls method which inserts new person in database elif selection == "4": db.insert_db_drinks() #calls method which inserts new drink in database elif selection == "5": user_round.createRound() #calls method which creates a round elif selection == "6": user_round.isRoundActive() #calls method which checks if rounds are active elif selection == "7": pref.createPreferences() #calls method which creates a users preference elif selection == "8": pref.printPreferences() #calls method which prints users preferences elif selection == "9": exit() #exits the loop of printing user menu&selection, terminating the application def userMenu(self): print("Welcome to the Brew App! ") print("========================") print("\n[1] Output People Information") print("[2] Output Drink information") print("[3] Create New Person") print("[4] Create New Drink") print("[5] Create A Round") print("[6] Check Round Availability") print("[7] Create a preference") print("[8] Output saved preferences") print("[9] Exit") app = Selection() #creates instance of Selection object called app #this allows the methods to be called through app.<method>
f04517f886ac4216950a25cb0fa3ace817c4924d
Varobinson/python101
/print-a-square.py
102
3.71875
4
#Print a 5x5 square of * characters. square = 1 while square <= 5: print('*' * 5) square += 1
761768971347ca71abb29fcbbaccf6ef92d4df86
Varobinson/python101
/tip-calculator.py
998
4.28125
4
#Prompt the user for two things: #The total bill amount #The level of service, which can be one of the following: # good, fair, or bad #Calculate the tip amount and the total amount(bill amount + tip amount). # The tip percentage based on the level of service is based on: #good -> 20% #fair -> 15% # bad -> 10% try: #Ask user for total bill amount total_bill = int(input('What was your total? ')) #convert total to float #prompt user for service quality service = input('What was the service bad, fair, or good? ') #adding split feature #promt user for split amount split = input('How many people will be paying? ') except: print('error') #convert split to int split = int(split) tip = () service = service.lower() if service == 'bad': tip = total_bill * 0.1 elif service == 'fair': tip = total_bill * 0.15 elif service == 'good': tip = total_bill * 0.2 else: print("Cant't help you! ") #added split to total total = total_bill + tip / split print(total)
54fdcaea2dd283b21c319e22f23530b961161eee
Ryanj-code/Python-1-and-2
/Assignment/peer-programming.py
783
4.09375
4
#Ryan, Briana #Shipping Cost weight = float(input("what is the weight of the package in pounds?")) if weight <= 2: newWeight = weight * 1.50 print("you pay $ " + str(newWeight)) elif weight >2 and weight <=6: newWeight = weight * 3 print("you pay $ " + str(newWeight)) elif weight >6 and weight <=10: newWeight = weight * 4 print("you pay $ " + str(newWeight)) else: newWeight = weight * 4.75 print("you pay $ " + str(newWeight)) #Cookies Recipe amount = int(input("How many cookies?")) number = 48 fraction = float(amount / number) sugar = (1.5 * fraction) butter = (1 * fraction) flour = (2.75 * fraction) print("You need " + str(sugar) + " cups of sugar") print("You need " + str(butter) + " cups of butter") print("You need " + str(flour) + " cups of flour")
94bdd2d96de22c8911e7c22e46405558785fc25e
chhikara0007/intro-to-programming
/s2-code-your-own-quiz/my_code.py
1,211
4.46875
4
# Investigating adding and appending to lists # If you run the following four lines of codes, what are list1 and list2? list1 = [1,2,3,4] list2 = [1,2,3,4] list1 = list1 + [5] list2.append(5) # to check, you can print them out using the print statements below. print list1 print list2 # What is the difference between these two pieces of code? def proc(mylist): mylist = mylist + [6] def proc2(mylist): mylist.append(6) # Can you explain the results given by the four print statements below? Remove # the hashes # and run the code to check. print list1 proc(list1) print list1 print list2 proc2(list2) print list2 # Python has a special assignment syntax: +=. Here is an example: list3 = [1,2,3,4] list3 += [5] # Does this behave like list1 = list1 + [5] or list2.append(5)? Write a # procedure, proc3 similar to proc and proc2, but for +=. When you've done # that check your conclusion using the print-procedure call-print code as # above. def proc3(mylist): mylist += [5] print list3 proc3(list3) print list3 print list1 print list2 print list3 # What happens when you try: list1 = list1 + [7,8,9] list2.append([7,8,9]) list3 += [7,8,9] print list1 print list2 print list3
1e710775997e19734be2cb46470f80d70c8bf8e1
StefanKaeser/pybites
/157/accents.py
300
3.859375
4
import unicodedata def filter_accents(text): """Return a sequence of accented characters found in the passed in lowercased text string """ accents = [] for char in text: if "WITH" in unicodedata.name(char): accents.append(char.lower()) return accents
852fc5577d995bc8b08cd8f094362b7790c28949
StefanKaeser/pybites
/53/text2cols.py
921
3.875
4
import textwrap import itertools COL_WIDTH = 20 def _pad(string, width=COL_WIDTH): length = len(string) if length > width: raise ValueError return string + " " * (width - length) def _pad_list(lst, width=COL_WIDTH): return [_pad(line) for line in lst] def text_to_columns(text): """Split text (input arg) to columns, the amount of double newlines (\n\n) in text determines the amount of columns. Return a string with the column output like: line1\nline2\nline3\n ... etc ... See also the tests for more info.""" paragraphs = [paragraph.strip() for paragraph in text.split("\n\n")] rows = [textwrap.wrap(paragraph.strip(), COL_WIDTH) for paragraph in paragraphs] rows = [_pad_list(row) for row in rows] rows = [ "\t".join(row) for row in itertools.zip_longest(*rows, fillvalue=" " * COL_WIDTH) ] return "\n".join(rows)
24373fa1a842ccab6ed11851f7cb9ac19167b246
StefanKaeser/pybites
/170/mcdonalds.py
1,235
3.671875
4
import pandas as pd data = "https://s3.us-east-2.amazonaws.com/bites-data/menu.csv" # load the data in once, functions will use this module object df = pd.read_csv(data) pd.options.mode.chained_assignment = None # ignore warnings def get_food_most_calories(df=df): """Return the food "Item" string with most calories""" return df["Item"].loc[df["Calories"].idxmax()] def get_bodybuilder_friendly_foods(df=df, excl_drinks=False): """Calulate the Protein/Calories ratio of foods and return the 5 foods with the best ratio. This function has a excl_drinks switch which, when turned on, should exclude 'Coffee & Tea' and 'Beverages' from this top 5. You will probably need to filter out foods with 0 calories to get the right results. Return a list of the top 5 foot Item stings.""" df = df.copy() df = df[df["Calories"] != 0.0] if excl_drinks: df = df[df["Category"] != "Coffee & Tea"] df = df[df["Category"] != "Beverages"] df["Protein/Calories ratio"] = df.apply( lambda row: row["Protein"] / row["Calories"], axis=1 ) df = df.sort_values(by=["Protein/Calories ratio"], ascending=False) return list(df.head()["Item"])
8f0491dde7bb67ae7e44ba31e7444fe8524d4bd4
StefanKaeser/pybites
/208/combos.py
142
3.6875
4
import itertools def find_number_pairs(numbers, N=10): return [pair for pair in itertools.combinations(numbers, r=2) if sum(pair) == N]
549105f9a1329ae66e62f2130fae97545e1051fc
StefanKaeser/pybites
/7/logtimes.py
1,190
3.53125
4
from datetime import datetime import os import urllib.request SHUTDOWN_EVENT = "Shutdown initiated" # prep: read in the logfile logfile = os.path.join(os.getcwd(), "log") urllib.request.urlretrieve( "https://bites-data.s3.us-east-2.amazonaws.com/messages.log", logfile ) with open(logfile) as f: loglines = f.readlines() def convert_to_datetime(line): """TODO 1: Extract timestamp from logline and convert it to a datetime object. For example calling the function with: INFO 2014-07-03T23:27:51 supybot Shutdown complete. returns: datetime(2014, 7, 3, 23, 27, 51) """ date_str = line.split()[1] date = datetime.strptime(date_str, "%Y-%m-%dT%H:%M:%S") return date def time_between_shutdowns(loglines): """TODO 2: Extract shutdown events ("Shutdown initiated") from loglines and calculate the timedelta between the first and last one. Return this datetime.timedelta object. """ shutdown_loglines = [logline for logline in loglines if SHUTDOWN_EVENT in logline] shutdown_dts = [convert_to_datetime(logline) for logline in shutdown_loglines] return shutdown_dts[1] - shutdown_dts[0]
cfc7b9509d76c84061e8f77e4c0e37ff44c1c6f7
StefanKaeser/pybites
/79/community.py
792
3.546875
4
import csv import requests from collections import Counter CSV_URL = "https://bites-data.s3.us-east-2.amazonaws.com/community.csv" def get_csv(): """Use requests to download the csv and return the decoded content""" with requests.get(CSV_URL) as r: content = (line.decode("utf-8") for line in r.iter_lines()) return content def create_user_bar_chart(content): """Receives csv file (decoded) content and print a table of timezones and their corresponding member counts in pluses to standard output """ reader = csv.DictReader(content) timezones = [row["tz"] for row in reader] tz_ctr = Counter(timezones) string = "" for tz, num_members in tz_ctr.items(): string += f"{tz:<21}| {'+'*num_members}\n" print(string)
3616c18c64f87459c4219d8512aa24b7f80ea3cd
StefanKaeser/pybites
/51/miller.py
883
3.5625
4
from datetime import datetime, timedelta # https://pythonclock.org/ PY2_DEATH_DT = datetime(year=2020, month=1, day=1) BITE_CREATED_DT = datetime.strptime('2018-02-26 23:24:04', '%Y-%m-%d %H:%M:%S') def py2_earth_hours_left(start_date=BITE_CREATED_DT): """Return how many hours, rounded to 2 decimals, Python 2 has left on Planet Earth (calculated from start_date)""" time_left = PY2_DEATH_DT - start_date one_hour = timedelta(hours=1) return round(time_left / one_hour, 2) def py2_miller_min_left(start_date=BITE_CREATED_DT): """Return how many minutes, rounded to 2 decimals, Python 2 has left on Planet Miller (calculated from start_date)""" time_left = PY2_DEATH_DT - start_date earth_year = timedelta(days=365) miller_hour = 7 * earth_year miller_minute = miller_hour / 60 return round(time_left / miller_minute, 2)
592e186d9725f23f98eaf990116de6c572757063
Lobo2008/LeetCode
/581_Shortest_Unsorted_ContinuousSubarray.py
1,749
4.25
4
""" Given an integer array, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order, too. You need to find the shortest such subarray and output its length. Example 1: Input: [2, 6, 4, 8, 10, 9, 15] Output: 5 Explanation: You need to sort [6, 4, 8, 10, 9] in ascending order to make the whole array sorted in ascending order. Note: Then length of the input array is in range [1, 10,000]. The input array may contain duplicates, so ascending order here means <=. """ class Solution: def findUnsortedSubarray(self, nums): """ :type nums: List[int] :rtype: int """ """ 把数组看成折线图,折线图应该是上升或者平行的 两个指针head 和tail,同时从两边开始,当head指针的路劲下降的时候,找到了start,当tail指针的路径上坡了,找到了end,end-start就是长度 """ if len(nums) <= 1: return 0 sortnums = sorted(nums) head, tail = 0, len(nums)-1 headFind, tailFind = False, False while head <= tail: headRs = nums[head] ^ sortnums[head] == 0 tailRs = nums[tail] ^ sortnums[tail] == 0 if not headRs and not tailRs: return tail - head + 1 if headRs: #等于0的时候要继续比下一个 head += 1 if tailRs: tail -= 1 return 0 so = Solution() nums = [2, 6, 4, 8, 10, 9, 15]#5 # nums = [10,9,8,7,6,5] # nums = [] #0 # nums = [1] #0 # nums = [1,10] #0 # nums = [10,1] #2 # nums = [2,1,3,4,5] #2 nums = [2,3,4,5,1] #5 print(so.findUnsortedSubarray(nums))
ee897f18008dc3589302522ed41601a88c158c27
Lobo2008/LeetCode
/35_Search_Insert_Position.py
1,605
4
4
""" Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You may assume no duplicates in the array. Input: [1,3,5,6], 5 Output: 2 Input: [1,3,5,6], 7 Output: 4 Input: [1,3,5,6], 0 Output: 0 Input: [1,3,5,6], 7 Output: 4 12346789 5 """ class Solution(object): def searchInsert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ for index in range(len(nums)): if target <= nums[index]: return index return len(nums) def searchInsert_binary_search(self, nums, target): low = 0 high = len(nums) if target > nums[high-1]:return high while low <= high: mid = (low + high) // 2 # print('low=',low,',mid=',mid,',high=',high) if target == nums[mid] : # print('~~~~1') return mid elif target > nums[mid] : # print('~~~~2') low = mid + 1 index = mid + 1 flag = 'right' else:# target < nums[mid] # print('~~~~3') high = mid - 1 index = mid - 1 flag = 'left' # print(low,mid,high,'->',flag) return low so = Solution() nums = [1,3,5,6,7,9]; target = 3 # print(so.searchInsert_binary_search(nums,target)) for i in range(0,11): rs = so.searchInsert_binary_search(nums,i) print(i,'=>',rs)
efe54b9bf0d0a67475c24c0f15d02af1cc90192c
Lobo2008/LeetCode
/test14.py
99
3.75
4
dic = {} #f = "f" #dic[f] = 10 if dic[f]: print ('it is true') else: print ('it is false')
391adea82bbde9668280bfefc17c093da87a21c0
Lobo2008/LeetCode
/128_Longest_Consecutive_Sequence.py
2,734
3.890625
4
""" Given an unsorted array of integers, find the length of the longest consecutive elements sequence. Your algorithm should run in O(n) complexity. Example: Input: [100, 4, 200, 1, 3, 2] Output: 4 Explanation: The longest consecutive elements sequence is [1, 2, 3, 4]. Therefore its length is 4. """ class Solution: def longestConsecutive(self, nums): """ :type nums: List[int] :rtype: int """ """ 最直观的做法,就是先排序,然后遍历,记录最大的连续串,复杂度是nlgn 但是题目已经要求了是O(n),所以不能排序 例子:[8,2,3,4,5,9,12] 先统计出现的元素,设置为1 第一个: 8 找8-1=7是否在字典里并且7没用过 ,不ok,则长度不增加 找8+1=9是否在字典里并且9没用过,在,所以长度+1,长度变成2, 因为找到9了,所以继续从9找下去: 9-1是否在字典里并且8没用过,注意,因为刚才是从8 过来的,所以过来之前8应该标记为”已处理=>dic[8]=0 所以这个不成立,长度不变 9+1是否在字典里并且10没用过,不ok,所以长度不变 注意,找到以后才需要递归再找 。。。。。所以,以8来找,长度为2 第二个,2 找2-1是否在字典里且1没用过,不成立 +0 找2+1是否在字典里且3没用过,成立 +1,则将2标记为”已处理“,并从3开始再找下去 """ def rec(number): if not dic[number] or dic[number] == 0: return 0 else: dic[number] = 0 count = 1 count +=rec(number-1) count += rec(number+1) return count if not nums: return 0 from collections import Counter dic = Counter(nums) maxlen = 1 nowmax = 1 for n in nums: nowmax = rec(n) maxlen = max(nowmax,maxlen) return maxlen # """nlgn if not nums: return 0 maxlen = 1 newmax = 1 nums = list(set(nums)) nums.sort() for i in range(1,len(nums)): if nums[i] == nums[i-1]+1: newmax += 1 else: maxlen = max(maxlen,newmax) newmax = 1 return max(maxlen,newmax) # """ so = Solution() nums = [100, 4, 200, 1, 3, 2] nums = [1,3,5] nums = [1,2,3,5,7,8,9] nums = [2,3,4,5,9,12] print(so.longestConsecutive(nums))
ea2c7f0edc20071d14c98f3ac9fe25a888fc44f5
Lobo2008/LeetCode
/102_Binary_Tree_Level_Order_Traversal.py
2,191
4.03125
4
""" Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level). For example: Given binary tree [3,9,20,null,null,15,7], 3 / \ 9 20 / \ 15 7 return its level order traversal as: [ [3], [9,20], [15,7] ] """ # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def levelOrder(self, root): """ :type root: TreeNode :rtype: List[List[int]] """ """ 1 / \ 2 3 / \ / \ 4 5 6 7 1)第一层[1] (1)node=1, levelrs=[1], 1.left=2,1.right=2,一个node只有left和right两个节点 -> next=[2,3] rs=[[1]] 2)第二次[2,3] (1)node = 2, levelrs=[2], 2.left=4, 2.right=5 ->next=[4,5] (2)node = 3, levelrs=[3], 3.left=6, 3.right=7 ->next=[4,5,6,7] ->rs=[[1],[2,3]] 3)第三层[4,5,6,7] (1)node=4, levelrs=[4] 4.left=None,4.right=None ->next=[] (2)node=5.... ... ->levelrs=[4,5,6,7] ->rs=[[1],[,3],[4,5,6,7]] """ rs = [] if root == None: return rs thisLevel = [root] while thisLevel: levelrs = [] nextLevel = [] for node in thisLevel:#遍历当前层的所有节点 levelrs.append(node.val) if node.left: nextLevel.append(node.left) if node.right: nextLevel.append(node.right) rs.append(levelrs) thisLevel = nextLevel#新的遍历的集就是层遍历的下一层 return rs """ 1 / \ 2 3 / \ / \ 4 5 6 7 """ so = Solution() l1 = TreeNode(1) l2 = TreeNode(2) l3 = TreeNode(3) l4 = TreeNode(4) l5 = TreeNode(5) l6 = TreeNode(6) l7 = TreeNode(7) root = l1 l1.left = l2 l1.right = l3 l2.left = l4 l2.right = l5 l3.left = l6 l3.right = l7 print(so.levelOrder(root))
47a80668234357c9a895b6e1cafb240e5d2558db
Lobo2008/LeetCode
/210_Course_Schedule_II.py
4,310
4.34375
4
""" There are a total of n courses you have to take, labeled from 0 to n-1. Some courses may have prerequisites, for example to take course 0 you have to first take course 1, which is expressed as a pair: [0,1] Given the total number of courses and a list of prerequisite pairs, return the ordering of courses you should take to finish all courses. There may be multiple correct orders, you just need to return one of them. If it is impossible to finish all courses, return an empty array. Example 1: Input: 2, [[1,0]] Output: [0,1] Explanation: There are a total of 2 courses to take. To take course 1 you should have finished course 0. So the correct course order is [0,1] . Example 2: Input: 4, [[1,0],[2,0],[3,1],[3,2]] Output: [0,1,2,3] or [0,2,1,3] Explanation: There are a total of 4 courses to take. To take course 3 you should have finished both courses 1 and 2. Both courses 1 and 2 should be taken after you finished course 0. So one correct course order is [0,1,2,3]. Another correct ordering is [0,2,1,3] . """ class Solution(object): def findOrder(self, numCourses, prerequisites): """ :type numCourses: int :type prerequisites: List[List[int]] :rtype: List[int] """ """ 还是bfs,画出图就容易理解得多了,以第二个题目来画:[[1,0],[2,0],[3,1],[3,2]] 3->1->0 \>2/> 其中3->2 , 2->0 所以正确的选课方案就是, 最右边一层[0] 然后中间的一层[1,2] 最左边的一层[3] 同一层的多个节点,在同一层中可以以任意顺序出现,所以,所有的情况就是: [0]->[1,2]->[3] 第二次的[1.2]可互换,则有[0]->[2,1]->[3]共三种 注意注意,只需要返回一个正确的结果即可,无需返回所有情况 ref:https://leetcode.com/problems/course-schedule-ii/discuss/59321/Python-dfs-bfs-solutions-with-comments. """ from collections import defaultdict levels = defaultdict(lambda: [], {}) out_degree = {i:0 for i in range(numCourses)} for course, pre in prerequisites: out_degree[course] += 1 levels[pre].append(course) #levels = {0: [1, 2], 1: [3], 2: [3]} #out_degree= {0: 0, 1: 1, 2: 1, 3: 2} queue = [i for i in out_degree if out_degree[i]==0] #[0] # print(queue) rs = [] while queue: q = queue.pop() rs.append(q) #rs=[0] #找出与0相连的节点,把出度减一 for node in levels[q]:#[1,2] out_degree[node] -= 1 if out_degree[node] == 0:#出度减为零的时候,加入队列 queue.append(node) return rs if len(rs) == numCourses else [] # from collections import * def findOrder_bfs(self, numCourses, prerequisites): from collections import defaultdict,deque dic = {i: set() for i in range(numCourses)} neigh = defaultdict(set) for course, prereq in prerequisites: dic[course].add(prereq) neigh[prereq].add(course) #dic = {0: set(), 1: {0}, 2: {0}, 3: {1, 2}} 0没有先决,3的先决是1和2 #neigh= {0: {1, 2}, 1: {3}, 2: {3}} 0是1和2的先决 # print(dic, neigh) queue = deque([i for i in dic if not dic[i]])#将没有先决的节点放入队列 queue=[0] count, res = 0, [] while queue: node = queue.popleft() res.append(node)#res=[0] count += 1 for i in neigh[node]: #遍历neigh[0]=[1,2] dic[i].remove(node)#dic[1].remove(0) 遍历指向0的两个节点,并分别把这两个节点中指向0的节点数据删掉,删完以后,把节点放入队列,下次遍历 if not dic[i]: queue.append(i) return res if count == numCourses else [] so = Solution() numCourses = 4 prerequisites = [[1,0],[2,0],[3,1],[3,2]] # prerequisites = [[]] # numCourses = 2 # prerequisites = [[0,1],[1,0]] print(so.findOrder(numCourses, prerequisites)) print('+++++++') # print(so.findOrder_bfs(numCourses, prerequisites))
b2ba355049335f52c4304acf09b436bb471a97cb
Lobo2008/LeetCode
/213_House_Robber_II.py
4,827
3.8125
4
""" You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. All houses at this place are arranged in a circle. That means the first house is the neighbor of the last one. Meanwhile, adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Given a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police. Example 1: Input: [2,3,2] Output: 3 Explanation: You cannot rob house 1 (money = 2) and then rob house 3 (money = 2), because they are adjacent houses. Example 2: Input: [1,2,3,1] Output: 4 Explanation: Rob house 1 (money = 1) and then rob house 3 (money = 3). Total amount you can rob = 1 + 3 = 4. """ class Solution: def rob(self, nums): """ :type nums: List[int] :rtype: int """ """ 比第一代多了一个条件,那就是,rob了第一个house以后不能rob最后一个house [1,2,3,1] 所以其实可以这样? 如果rob了第一个,则nums其实是 [1,2,3] 否则,就是 [2,3,1] """ if not nums: return 0 if len(nums) <= 3: return max(nums) dp1 = [nums[0],nums[1]]+[0]*(len(nums)-3) dp2 = [nums[1],nums[2]]+[0]*(len(nums)-3) """ [6,6,4,8,4,3,3,10] nums1 = [6,6,4,8,4,3,3] nums2 = [6,4,8,4,3,3,10] l = 7 所以i = 2 3 4 5 6 i=2时 max(dp1[i-1])+nums1[2] => max(dp1[:i-1])+nums[2] 在i=len-1时,dp1应该停止 max(dp2[i-1])+nums2[2] => max(dp2[:i-1])+nums[3] i = 3时... ... i=5时 max(dp1[i-1])+nums1[5] => max(dp1[:i-1])+nums[5] max(dp2[i-1])+nums2[5] => max(dp2[:i-1])+nums[6] i=6时 max(dp1[i-1])+nums1[6] => max(dp1[:i-1])+nums[6] max(dp2[i-1])+nums2[6] => max(dp2[:i-1])+nums[7] """ for i in range(2,len(nums)-1): dp1[i] = max(dp1[:i-1])+nums[i] dp2[i] = max(dp2[:i-1])+nums[i+1] return max(max(dp1),max(dp2)) so = Solution() nums = [1,2,3,1] # nums = [6,6,4,8,4,3,3,10] # 27 print(so.rob(nums)) # method of robber I # dp,nothing to say if not nums: return 0 if len(nums) <= 2: return max(nums) dp = [nums[0],nums[1]]+[0]*(len(nums)-2) for i in range(2,len(nums)): dp[i] = max(dp[:i-1])+nums[i] return max(dp) #using nums = [6,6,4,8,4,3,3,10] as exaple # method of 1.39% # here , we can divide nums into nums1 and nums2,then # respectively implementing the Robber I method on nums1 and nums1 # nums1 = [6,6,4,8,4,3,3] -> max is 17 # nums2 = [6,4,8,4,3,3,10] -> max is 27 # thus the final result is 27 if not nums: return 0 if len(nums) <= 3: return max(nums) nums1, nums2 =[], [] nums1[:] = nums[:len(nums)-1] nums2[:] = nums[1:] dp1 = [nums1[0],nums1[1]]+[0]*(len(nums1)-2) dp2 = [nums2[0],nums2[1]]+[0]*(len(nums2)-2) for i in range(2,len(nums1)): dp1[i] = max(dp1[:i-1])+nums1[i] for j in range(2,len(nums2)): dp2[j] = max(dp2[:j-1])+nums2[j] return max(max(dp1),max(dp2)) # method of 13.6% # in method of 1.39%, we(I) NAIVELY using twice FOR X IN RANGE(xxx) # but actually, we can reduce to once if not nums: return 0 if len(nums) <= 3: return max(nums) nums1, nums2 =[], [] nums1[:] = nums[:len(nums)-1] nums2[:] = nums[1:] dp1 = [nums1[0],nums1[1]]+[0]*(len(nums1)-2) dp2 = [nums2[0],nums2[1]]+[0]*(len(nums2)-2) for i in range(2,len(nums1)): dp1[i] = max(dp1[:i-1])+nums1[i] dp2[i] = max(dp2[:i-1])+nums2[i] return max(max(dp1),max(dp2)) # method of 98.1% # in method of 13.6% and formmer, we used extra space nums1 and nums2 # but actually, using nums itself is enough # attention, nums2[i+1] = nums[i] ,so replace nums2 by nums # and, the length of the loop is len(nums)-1,not len(nums) if not nums: return 0 if len(nums) <= 3: return max(nums) dp1 = [nums[0],nums[1]]+[0]*(len(nums)-3) dp2 = [nums[1],nums[2]]+[0]*(len(nums)-3) for i in range(2,len(nums)-1): dp1[i] = max(dp1[:i-1])+nums[i] dp2[i] = max(dp2[:i-1])+nums[i+1] return max(max(dp1),max(dp2))