blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
59206867d7a35e131a214486f7b12621876b1ad5
microsoft/pybryt
/pybryt/annotations/complexity/complexities.py
8,817
4.09375
4
"""Complexity classes for complexity annotations""" import numpy as np from abc import ABC, abstractmethod from dataclasses import dataclass from typing import Any, Dict, List, Union @dataclass class ComplexityClassResult: """ A container class for the results of complexity checks. """ complexity_class: "complexity" """the complexity class associated with this result""" residual: float """the residual from the least-squares fit""" class complexity(ABC): """ Abstract base class for a complexity. Subclassses should implement the ``transform_n`` method, which transforms the input lengths array so that least squares can be used. If needed, the ``transform_t`` method can also be overwritten to transform the step counter values. The architecture for these and the algorithm for determining the optimal complexity is borrowed from https://github.com/pberkes/big_O. """ def __or__(self, other: Any) -> "ComplexityUnion": """ Create a complexity union through use of the ``|`` operator. Args: other (any): the other object in the union Returns: :py:class:`ComplexityUnion`: the union """ return ComplexityUnion.from_or(self, other) def __call__(self, complexity_data: Dict[int, int]) -> ComplexityClassResult: """ Return the sum of residuals by performing least squares on the input length data and timings. Uses ``transform_n`` and ``transform_t`` to transform the data from ``complexity_data``, which is a dictionary mapping input lengths to step counts. Performs least squares on the resulting arrays and returns the sum of residuals. Args: complexity_data (``dict[int, int]``): the complexity information Returns: ``float``: the sum of residuals from least squares """ ns, ts = [], [] for n, t in complexity_data.items(): ns.append(n) ts.append(t) n = np.array(ns, dtype=int) t = np.array(ts, dtype=int) try: n = self.transform_n(n) t = self.transform_t(t) _, resid, _, _ = np.linalg.lstsq(n, t, rcond=-1) if len(resid) == 0: return ComplexityClassResult(self, np.inf) return ComplexityClassResult(self, resid[0]) except: return ComplexityClassResult(self, np.inf) @staticmethod @abstractmethod def transform_n(n: np.ndarray) -> np.ndarray: """ Transforms the array of input lengths for performing least squares. Args: n (``np.ndarray``): the array of input lengths Returns: ``np.ndarray``: the transformed array of input lengths """ ... # pragma: no cover @staticmethod def transform_t(t: np.ndarray) -> np.ndarray: """ Transforms the array of timings for performing least squares. Args: n (``np.ndarray``): the array of timings Returns: ``np.ndarray``: the transformed array of timings """ return t class _constant(complexity): """ Complexity class for constant time: :math:`\\mathcal{O}(1)` """ @staticmethod def transform_n(n: np.ndarray) -> np.ndarray: return np.ones((len(n), 1)) # complexity classes are singletons constant = _constant() class _logarithmic(complexity): """ Complexity class for logarithmic time: :math:`\\mathcal{O}(\\log n)` """ @staticmethod def transform_n(n: np.ndarray) -> np.ndarray: return np.vstack((np.ones(len(n)), np.log2(n))).T logarithmic = _logarithmic() class _linear(complexity): """ Complexity class for linear time: :math:`\\mathcal{O}(n)` """ @staticmethod def transform_n(n: np.ndarray) -> np.ndarray: return np.vstack((np.ones(len(n)), n)).T linear = _linear() class _linearithmic(complexity): """ Complexity class for linearithmic time: :math:`\\mathcal{O}(n \\log n)` """ @staticmethod def transform_n(n: np.ndarray) -> np.ndarray: return np.vstack((np.ones(len(n)), n * np.log2(n))).T linearithmic = _linearithmic() class _quadratic(complexity): """ Complexity class for quadratic time: :math:`\\mathcal{O}(n^2)` """ @staticmethod def transform_n(n: np.ndarray) -> np.ndarray: return np.vstack((np.ones(len(n)), n * n)).T quadratic = _quadratic() class _cubic(complexity): """ Complexity class for cubic time: :math:`\\mathcal{O}(n^3)` """ @staticmethod def transform_n(n: np.ndarray) -> np.ndarray: return np.vstack((np.ones(len(n)), n * n * n)).T cubic = _cubic() class _exponential(complexity): """ Complexity class for exponential time: :math:`\\mathcal{O}(2^n)` """ @staticmethod def transform_n(n: np.ndarray) -> np.ndarray: return np.vstack((np.ones(len(n)), n)).T @staticmethod def transform_t(t: np.ndarray) -> np.ndarray: return np.log2(t) exponential = _exponential() complexity_classes = [constant, logarithmic, linear, linearithmic, quadratic, cubic]#, exponential] class ComplexityUnion: """ A complexity class that represents a union of multiple complexity classes. Complexity unions can be used to write annotations but cannot be used as classes to determine the complexity of a block of code; they are simply collections of acceptable complexity classes. This class does not ensure the uniqueness of the complexity classes it tracks; that is, if the same complexity class is added twice, it will be tracked twice. Args: *complexity_classes (:py:class:`complexity`): the complexity classes in the union """ _complexity_classes = List[complexity] """the complexity classes contained in the union""" def __init__(self, *complexity_classes: complexity): self._complexity_classes = list(complexity_classes) def __or__(self, other: Any) -> "ComplexityUnion": """ Create a complexity union through use of the ``|`` operator. Args: other (any): the other object in the union Returns: :py:class:`ComplexityUnion`: the union """ return self.from_or(self, other) @classmethod def from_or( cls, left: Union[complexity, "ComplexityUnion"], right: Union[complexity, "ComplexityUnion"], ) -> "ComplexityUnion": """ Create a complexity union from two operands. Args: left (:py:class:`complexity` or :py:class:`ComplexityUnion`): the left operand right (:py:class:`complexity` or :py:class:`ComplexityUnion`): the right operand Returns: :py:class:`ComplexityUnion`: the union containing both operands Raises: ``TypeError``: if either operand is not a complexity class or complexity union """ if not isinstance(left, (complexity, cls)): raise TypeError(f"Attempted to combine a complexity class with an object of type {type(left)}") if not isinstance(right, (complexity, cls)): raise TypeError(f"Attempted to combine a complexity class with an object of type {type(right)}") if isinstance(left, cls): right_complexities = [right] if isinstance(right, cls): right_complexities = right.get_complexities() return cls(*left.get_complexities(), *right_complexities) elif isinstance(right, cls): return cls(left, *right.get_complexities()) return cls(left, right) def add_complexity(self, complexity_class: complexity) -> None: """ Add another complexity class to this union. Args: complexity_class (:py:class:`complexity`): the complexity class to add """ self._complexity_classes.append(complexity_class) def get_complexities(self) -> List[complexity]: """ Return a list of the complexity classes in this union. Returns: ``list[complexity]``: the complexity classes """ return [*self._complexity_classes] def __eq__(self, other: Any) -> bool: """ Determine whether another object is equal to this complexity union. An object is equal to a complexity union if it is also a complexity union and contains the same complexity classes. Returns: ``bool``: whether the other object is equal to this one """ return isinstance(other, type(self)) and \ set(self.get_complexities()) == set(other.get_complexities())
e004fbf44a1c54030e467abb7825724e9d1ba249
vesran/GraphIT
/graphit/induced_bipartite_subgraph.py
4,714
3.875
4
from graphit.graphcore import Graph def _count_bipartite_edges(G, X, Y): """ Counts the number of edges in G which starts has an endpoints in X and Y. :param G: Graph :param X: Vertex set from G :param Y: Vertex set from G :return: Integer """ cpt = 0 for edge in G.edges: v1 = edge.v1 v2 = edge.v2 if (X.__contains__(v1) and Y.__contains__(v2)) or (X.__contains__(v2) and Y.__contains__(v1)): cpt += 1 return cpt def _extract_bipartite_edges(G, X, Y): """ Extracts edges which have an endpoints in X and in Y. :param G: Graph :param X: Vertex set from G :param Y: Vertex set from G :return: List of edges extracted from G """ bipartite_edges = [] for edge in G.edges: v1 = edge.v1 v2 = edge.v2 if (X.__contains__(v1) and Y.__contains__(v2)) or (X.__contains__(v2) and Y.__contains__(v1)): bipartite_edges.append(edge) return bipartite_edges def _count_subset_neighbors(v, X): """ Counts the number of neighbors of vertex v which are in X. :param v: A vertex :param X: Vertex set :return: Integer """ return len(set(v.neighbors).intersection(X)) def extract_bipartite_subgraph(graph, verbose=False): """ Extracts a bipartite subgraph of the given graph with at least e(G)/2 edges. :param graph: Graph to extract the subgraph from. :param verbose: Boolean to display messages :return: tuple (subgraph, partite set X, partite set Y) """ edge_threshold = int(graph.edges.__len__() / 2) + 1 X = graph.vertices[:int(len(graph.vertices)/2)] Y = graph.vertices[int(len(graph.vertices)/2):] i = 1 while _count_bipartite_edges(graph, X, Y) < edge_threshold: print(f"================ Iteration {i} ===================") if verbose else 0 i += 1 print("X", X) if verbose else 0 print("Y", Y) if verbose else 0 print(_count_bipartite_edges(graph, X, Y)) if verbose else 0 # Find in X and Ythe best vertex to move best_vertex_X, best_vertex_Y = X[0], Y[0] best_score_X, best_score_Y = -10000, -10000 for vertex in X: score = _count_subset_neighbors(vertex, X) - _count_subset_neighbors(vertex, Y) if score > best_score_X: best_score_X, best_vertex_X = score, vertex for vertex in Y: score = _count_subset_neighbors(vertex, Y) - _count_subset_neighbors(vertex, X) if score > best_score_Y: best_score_Y, best_vertex_Y = score, vertex # Move best vertex print(f"Edge gains X -> Y : {best_score_X} - {best_vertex_X}") if verbose else 0 print(f"Edge gains Y -> X: {best_score_Y} - {best_vertex_Y}") if verbose else 0 if best_score_X > best_score_Y: # Move X vertex to Y X.remove(best_vertex_X) Y.append(best_vertex_X) else: # Move vertex Y to X Y.remove(best_vertex_Y) X.append(best_vertex_Y) # Extract bipartite subgraph print("X", X) if verbose else 0 print("Y", Y) if verbose else 0 H = Graph() H.edges = _extract_bipartite_edges(graph, X, Y) H.vertices = X + Y return H, X, Y def export2tex_bipartite_subgraph(pathname, dest_name='./out.tex', verbose=False): """ Extracts a bipartite subgraph from the graph described in the given file and export the same graph to a new file with the subgraph in red. Graph must be loopless, otherwise the algorithm stops. :param pathname: Initial graph file :param dest_name: Output file :param verbose: Boolean to display messages :return: None """ g = Graph() g.read_dat(pathname) # Check if the given graph is loopless if any(edge.v1.id == edge.v2.id for edge in g.edges): print('The specified graph is not loopless. It might not contains a bipartite subgraph with e(G)/2 edges.') return # Extract bipartite graph H, X, Y = extract_bipartite_subgraph(g) print("Partite set X :", X) if verbose else 0 print("Partite set Y :", Y) if verbose else 0 print(f'Ratio of marked edges : {_count_bipartite_edges(g, X, Y)}/{g.num_edges}') print("File created :", dest_name) g.exportbipartite2tex(H, dest_name=dest_name) if __name__ == '__main__': pathname = './resources/hexa.dat' g = Graph() g.read_dat(pathname) # g.random_init(6, 4, loop=False, multiple_edges=True) H, X, Y = extract_bipartite_subgraph(g) # g.exportbipartite2tex(H, './resources/bipartite_test.tex') export2tex_bipartite_subgraph(pathname, dest_name='./resources/out.tex', verbose=True)
47fdae9fb8f95a64a34518088a443a3e8cf3f25e
francosbenitez/unsam
/07-plt-especificacion-y-documentacion/05-especificacion/documentacion.py
2,305
4.09375
4
""" Ejercicio 7.8: Funciones y documentación Para cada una de las siguientes funciones: Pensá cuál es el contrato de la función. Agregale la documentación adecuada. Comentá el código si te parece que aporta. Detectá si hay invariantes de ciclo y comentalo al final de la función Guardá estos códigos con tus modificaciones en el archivo documentacion.py. def valor_absoluto(n): if n >= 0: return n else: return -n def suma_pares(l): res = 0 for e in l: if e % 2 ==0: res += e else: res += 0 return res def veces(a, b): res = 0 nb = b while nb != 0: #print(nb * a + res) res += a nb -= 1 return res def collatz(n): res = 1 while n!=1: if n % 2 == 0: n = n//2 else: n = 3 * n + 1 res += 1 return res """ def valor_absoluto(n): ''' Devuelve valor absoluto de n => f(n) = |n| Precondicion: valor n real Poscondicion: valor n positivo ''' if n >= 0: return n else: return -n def suma_pares(l): ''' Devuelve la suma de numeros pares de una lista Precondicion: valores reales en la lista Poscondicion: si el elemento es par, hago la suma res += e si el elemento es impar, sumo 0 ''' res = 0 for e in l: if e % 2 ==0: res += e else: res += 0 return res # La invariante es que res debe comenzar en 0 para sumar def veces(a, b): ''' Realizo la multiplicacion entre a y b ------------ Precondicion: valor a real, valor b entero Poscondicion: producto entre a y b ''' res = 0 nb = b while nb != 0: res += a nb -= 1 return res # La invariante es que res debe comenzar en 0 para sumar def collatz(n): ''' Funcion de conjetura de Collatz Precondicion: valor n entero positivo Poscondicion: si el n es par, se divide entre 2 si el n es impar, devuelve 3*n+1 ''' res = 1 while n!=1: if n % 2 == 0: n = n//2 else: n = 3 * n + 1 res += 1 return res # La invariante es que res debe empezar en 1 # si el usuario coloca un n = 1
ce6e06a0bd0994743e886b39c801b469753083eb
dk-yoon/Algorithm
/Software Expert Academy/Difficulty (1)/SWEA2056.py
867
3.96875
4
''' 연월일 순으로 구성된 8자리의 날짜가 입력으로 주어진다. 해당 날짜의 유효성을 판단한 후, 날짜가 유효하다면 ”YYYY/MM/DD”형식으로 출력하고, 날짜가 유효하지 않을 경우, -1 을 출력하는 프로그램을 작성하라. ''' t = int(input()) thirtyone = ['01','03','05','07','08','10','12'] thirty = ['04','06','09','11'] twentyeight = ['02'] for t in range (1,t+1): date = str(input()) year = (date[0:4]) month = str(date[4:6]) day = int(date[6:8]) strday = str(date[6:8]) if (month in thirtyone and day < 32): print(f'#{t} {year}/{month}/{strday}') elif (month in thirty and day < 31): print(f'#{t} {year}/{month}/{strday}') elif (month in twentyeight) and day < 29: print(f'#{t} {year}/{month}/{strday}') else: print(f'#{t} -1')
f74dde0261038d46e3ada75c994c31d62ee9dba1
rugbyprof/2143-ObjectOrientedProgramming
/ClassLectures/day01.py
2,090
4.59375
5
import random # simple print! print("hello world") # create a list a = [] # prints the entire list print(a) # adds to the end of the list a.append(3) print(a) # adds to the end of the list a.append(5) print(a) # adds to the end of the list, and python doesn't care # what a list holds. It can a mixture of all types. a.append("mcdonalds") print(a) # I can also append alist to a list. # Lists of lists is how we represent multi-dimensional data (like 2D arrays) a.append([1,2,3,'a','b']) print(a) s = "hello " t = "world" st = s + t # python 'overloads' the `+` sign to perform a concetenation # when adding strings. print(st) # simple loop that loops 10 times # the 'range' function returns a 'list' in this case # the list = [0,1,2,3,4,5,6,7,8,9] for i in range(10): # appand a random integer between 0 and 100 a.append(random.randint(0,100)) # This loop 'iterates' over the 'container' 'a' placing # subsequent values in x for x in a: print(x) # Another way of looping over a container (list). # This has a more traditional c++ 'feel' to it. for j in range(len(a)): print(a[j]) print() # print the last element in a list print(a[len(a)-1]) # print the last element in a list (cooler way) print(a[-1]) # Prints a "slice" of the list. In this case 2,3,4 (not 5). print(a[2:5]) # Loop and jump by two's. Remember the range function takes different param numbers. # 1. param = size of list to return # 2. params = starting value, ending value that list will contain # 3. params = same as 2. but adds an 'increment by' value as the third param for i in range(0,len(a),2): print(a[i]) print(a) #Insert a value into a position in the list, without overwriting another value a.insert(7,'dont jack my list') # This would overwrite value at a[7] # Or error if index did not exist a[7] = 'dont jack my list' print(a) # Just like appending to the list a.insert(len(a),'please work') print(a) # Should error, but defaults to appending to end of list a.insert(len(a)+3,'hmmmm') # prints second to last item print(a[-2]) # errors a[len(a)+2] = '999999'
680824ae02e990a20dda4600a0c150299fe6d5d1
BalaTheAtom/Begginer_solo
/pract1.py
788
3.671875
4
st="APPLE" def findOccurences(s, ch): return [i for i, letter in enumerate(s) if letter == ch] d=len(st) times=0 l=[] b=[0 for x in range(d)] while(True): letter_entered=input("Please enter a char : ").upper() times=times+1 a=list(findOccurences(st,letter_entered)) for i in range(d): if(i in a and not i in l): b[i]=st[i] l.append(i) elif(i not in l): b[i]='_' if (st == "".join(b)): print("you WON !! and the word is {}".format(st)) print("number of trials: {}".format(times)) length=len(set(st)) yourLucK=int((length/times)*100) print("your Luck percentage : {}%".format(yourLucK)) break else: for i in range(d): print(b[i],end='')
2c2e0cc6c45e8436e570cff352546e4b9c533ecd
nkuryad/KodeNoteBook
/src/list-sum.py
502
3.75
4
""" @docStart ### List Sum @docEnd """ # @codeStart from functools import reduce # sum of all parameters def sumAll(*x): res = 0 for a in x: res += a return res print(sumAll(2, 3, 4, 5)) # 14 # sum of no. of given list def listSum(x): res = 0 for i in x: res += i return res print(listSum([2, 3, 4, 5])) # 14 # One liner using reduce and lambda def listSumO(x): return reduce(lambda a, b: a+b, x, 0) print(listSumO(range(1, 11))) # 55 # @codeEnd
85d336a4cb86757906dfdbab4eddc3f0833d00d6
yoursc/adventofcode
/2015/07/2015-07-part_2.py
2,274
3.5
4
#!/usr/bin/python # -*- coding: utf-8 -*- """ @Author : Ven @Date : 2020/1/19 """ cmd_dic = {} num_dic = {} def write_cmd_dic(command: str): command_split = command.split(" -> ") if command_split.__len__() != 2: return inter: str = command_split[0] outer: str = command_split[1] cmd_dic[outer] = inter def f_and(value: str): value_split = value.split("AND") a: str = value_split[0].strip() b: str = value_split[1].strip() result: int = int(get_value(a)) & int(get_value(b)) return str(result) def f_or(value: str): value_split = value.split("OR") a: str = get_value(value_split[0].strip()) b: str = get_value(value_split[1].strip()) result: int = int(a) | int(b) return str(result) def f_not(value: str): value_n: str = value.replace("NOT", "") a: str = get_value(value_n.strip()) result: int = 65536 + ~int(a) return str(result) def f_shift(value: str): if "LSHIFT" in value: value_split = value.split("LSHIFT") a: str = get_value(value_split[0].strip()) b: str = get_value(value_split[1].strip()) result: int = int(a) << int(b) return str(result) elif "RSHIFT" in value: value_split = value.split("RSHIFT") a: str = get_value(value_split[0].strip()) b: str = get_value(value_split[1].strip()) result: int = int(a) >> int(b) return str(result) else: print("Error!!") exit(1) def get_value(key: str): try: a = int(key) return key except Exception: if key in num_dic: return num_dic[key] cmd = cmd_dic[key] print(f'{key}=[{cmd}]') if "AND" in cmd: result = f_and(cmd) elif "OR" in cmd: result = f_or(cmd) elif "NOT" in cmd: result = f_not(cmd) elif "SHIFT" in cmd: result = f_shift(cmd) else: result = get_value(cmd) num_dic[key] = result return result with open("2015-07.data", 'r', encoding='utf8') as file: file_str = file.read() cmd_list = file_str.split("\n") for command in cmd_list: write_cmd_dic(command) cmd_dic["b"] = "46065" print(f'The value of a is {get_value("a")}')
4ed85238537222b17177ac114b7b79ae6730c79b
franzigrkn/WISB256
/Euler Challenge/Multiples_3_5.py
311
3.953125
4
multiples=[] number=int(input()) getallen=list(range(0, number+1)) print(getallen) for i in range(3,number, 3): multiples.append(getallen[i]) for i in range(5, number, 5): if getallen[i] not in multiples: multiples.append(getallen[i]) print(multiples) answer=sum(multiples) print(answer)
3e782341426e65808ed55d9ed62bc1ddaa977f3c
nadeem1306/Q3_NADEEMCHAUDHARY-
/Q3_Nadeem.py
690
3.90625
4
def minChar(n,s): special=0 digit=0 up=0 lp=0 print("Password contains:") for i in s: if i.islower(): lp+=1 elif i.isdigit(): digit+=1 elif i.isupper(): up+=1 else: special+=1 print("Digits=" + str(digit)) print("Special character=" + str(special)) print("Uppercase Alphabet=" + str(up)) print("Lowercase Alphabet=" + str(lp)) if n>7 and digit>0 and special>0 and up>0 and lp>0: print("Strong Password. Good to go") else: print(str(8-n)+" more characters should be added") n=int(input()) s=str(input()) minChar(n,s)
041c28c1af90e7097d58e328139e85cf7e3d0687
linadatascience/MSCS
/Practice_of_Computer_Program/Project_Poker_Game/Deck.py
686
3.59375
4
from Card import * from random import shuffle class Deck: def __init__(self): self.deck = [] suit = "spades" for x in range (1,14): self.deck.append(Card(suit,x)) suit = "clubs" for x in range (1,14): self.deck.append(Card(suit,x)) suit = "hearts" for x in range (1,14): self.deck.append(Card(suit,x)) suit = "diamonds" for x in range (1,14): self.deck.append(Card(suit,x)) def shuffle(self): shuffle(self.deck)
5522c757bfa1df5d3b4469da0a1f586af5647123
solavrov/imaginedNums
/funs.py
760
3.53125
4
from IndexSet import IndexSet def create_unique_index_set(size, dim): s = [] x = IndexSet(size, dim) s.append(x.get_sorted_tuple()) while True: if x.next(): s.append(x.get_sorted_tuple()) else: break return list(set(s)) def sum_given_size(x, size): r = [] dim = len(x) s = create_unique_index_set(size, dim) for e in s: r.append(sum([x[i] for i in e])) return r def sum_all_sizes(x): r = [] for size in range(1, len(x) + 1): r += sum_given_size(x, size) return r def sum_all_sizes_no_duplicates_sorted(x): r = sum_all_sizes(x) r = list(set(r)) r.sort() return r y = [1, 3, 5] print(sum_all_sizes_no_duplicates_sorted(y))
bc959cf3fd78611a404cd333297742d775541671
bhrigu123/interview_prep_python
/longest_valid_brackets.py
984
3.5625
4
def get_longest_length(arr): stack = [] start_index = 0 end_index = 0 max_length = 0 while end_index < len(arr): if is_opening(arr[end_index]): stack.append(arr[end_index]) end_index+=1 else: if len(stack) > 0: popped_bracket = stack.pop() if corresponding_opening_bracker(arr[end_index]) == popped_bracket: end_index += 1 else: max_length = max(max_length, (end_index - start_index)) start_index = end_index +1 end_index += 1 max_length = max(max_length, (end_index - start_index)) return max_length def is_opening(bracket): openin_brackets = set(['(','[','{']) if bracket in openin_brackets: return True return False def corresponding_opening_bracker(closing_bracket): bracket_map = {')':'('} return bracket_map[closing_bracket] print get_longest_length('(')
40437c8b41eeb844522e59a6841566ddfa67e1bf
dominicprice/pyeliza
/eliza/syn.py
1,219
3.71875
4
import eliza.EString as EString from eliza.word import WordList from typing import List class SynList(list): "Collection of synonyms" def add(self, words): "Add a WordList of synonyms to the list" self.append(words) def pprint(self, indent): for elem in self: print(' ' * indent, end='') elem.pprint(indent) def find(self, s: str) -> WordList: "Find a word list containing `s` , or None if none exist" for elem in self: if elem.find(s): return elem return None def match_decomp(self, s: str, pat: str, lines: List[str]) -> bool: """ Decomposition match: if decomp has no synonyms, do a regular match, otherwise try all synonyms """ if not EString.match(pat, "*@* *", lines): return EString.match(s, pat, lines) first = lines[0] syn_word = lines[1] the_rest = " " + lines[2] syn = self.find(syn_word) if syn is None: print("Could not find syn list for " + syn_word) return False for elem in syn: pat = first + elem + the_rest if EString.match(s, pat, lines): n = EString.count(first, '*') for j in range(len(lines)-2, n-1, -1): lines[j+1] = lines[j]; lines[n] = elem return True return False __all__ = [ "SynList" ]
ae0ed592ffd47e1092f3e27185f77013f1405ee5
wsh123456/arithmetic
/leetcode/211_add-and-search-word-data-structure-design.py
1,508
3.875
4
# 添加与搜索单词-数据结构设计 # 设计一个支持以下两种操作的数据结构: # void addWord(word) # bool search(word) # search(word) 可以搜索文字或正则表达式字符串,字符串只包含字母 . 或 a-z 。 . 可以表示任何一个字母。 # 示例: # addWord("bad") # addWord("dad") # addWord("mad") # search("pad") -> false # search("bad") -> true # search(".ad") -> true # search("b..") -> true # 说明: # 你可以假设所有单词都是由小写字母 a-z 组成的 class WordDictionary: class __Node(): def __init__(self, isword = False): self.isword = isword self.next = dict() def __init__(self): self.__root = self.__Node() def addWord(self, word): cur = self.__root for char in word: if char not in cur.next: cur.next[char] = self.__Node() cur = cur.next[char] cur.isword = True def search(self, word): return self.__match(self.__root, word, 0) def __match(self, node, word, index): if index == len(word): return node.isword char = word[index] if char != ".": if char not in node.next: return False return self.__match(node.next[char], word, index + 1) else: for nextkey in node.next.keys(): if self.__match(node.next[nextkey], word, index + 1): return True return False
390b0408991d84b88a271de629b20408b9d98eb9
hughian/OJ
/LeetCode/Python/M98. Validate Binary Search Tree.py
1,488
3.546875
4
class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None def isValidBST(root) -> bool: if not root: return True def pre(root): if not root: return True, float('inf'), -float('inf') if root: t = True minl, minr = float('inf'), float('inf') maxl, maxr = -float('inf'), -float('inf') if root.left: tt, minl, maxl = pre(root.left) t = t and tt and maxl < root.val if root.right: tt, minr, maxr = pre(root.right) t = t and tt and minr > root.val print(root.val, minl, maxl, minr, maxr) return t, min(minl, minr, root.val), max(maxl, maxr, root.val) return pre(root)[0] def isValidBST(root): tmp = [] def inorder(root, tmp): if root: inorder(root.left, tmp) tmp +=[root.val] inorder(root.right, tmp) inorder(root, tmp) print(tmp) return tmp == sorted(list(set(tmp))) root = TreeNode(3) root.right = TreeNode(30) root.right.left = TreeNode(10) root.right.left.right = TreeNode(15) root.right.left.right.right = TreeNode(45) r = isValidBST(root) print(r) T = TreeNode(5) T.left = TreeNode(1) T.right = TreeNode(4) T.right.left = TreeNode(3) T.right.right = TreeNode(6) def ino(root): if root: ino(root.left) print(root.val, end=' ') ino(root.right) ino(T)
0fa4a8af2f87b8156221536e06e21726b7c9524d
harounixo/GOMYCODE
/project-2.py
389
3.59375
4
def remove_match_char(list1, list2): for i in range(len(list1)) : for j in range(len(list2)) : if list1[i] == list2[j] : c = list1[i] list1.remove(c) list2.remove(c) list3 = list1 + [""] + list2 return [list3, True] list3 = list1 + [""] + list2 return [list1, list2]
5ac57123e6615e33946e07d28dda4f91b7ac92bd
adit-sinha/Solutions-to-Practice-Python
/(7) List Comprehensions.py
137
3.875
4
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100] for even in a: if even%2==0: print(even, "is an even number in the given list.")
63cb3807d9d675e89126629bd4b69a673995a4d2
amisha1garg/Arrays_In_Python
/SearchAnElement.py
1,046
4.15625
4
# Given an integer array and another integer element. The task is to find if the given element is present in array or not. # # Example 1: # # Input: # n = 4 # arr[] = {1,2,3,4} # x = 3 # Output: 2 # Explanation: There is one test case # with array as {1, 2, 3 4} and element # to be searched as 3. Since 3 is # present at index 2, output is 2. # User function Template for python3 class Solution: # Complete the below function def search(self, arr, N, X): # Your code here for i in range(0, N): if X in arr: return arr.index(X) else: return -1 # { # Driver Code Starts # Initial Template for Python 3 import math def main(): T = int(input()) while (T > 0): N = int(input()) A = [int(x) for x in input().strip().split()] x = int(input()) ob = Solution() print(ob.search(A, N, x)) T -= 1 if __name__ == "__main__": main() # } Driver Code Ends
1b254db1f4c2ffe870cc48724c88c18d031fd186
tachang/OAuthTool
/ConnectHTTPHandler.py
4,665
3.546875
4
import urllib2 import urllib import httplib import socket import ssl import sys import base64 class ConnectBasedProxyHTTPConnection(httplib.HTTPConnection): # Variable to store the protocol being requested protocol = None # Initialization def __init__(self, host, port=None, strict=None, timeout=socket._GLOBAL_DEFAULT_TIMEOUT, ): print host httplib.HTTPConnection.__init__(self, host, port) def request(self, method, url, body=None, headers={}): # Dissect the url to determine the protocol. Store it in the instance variable. self.protocol, stuffAfterProtocol = urllib.splittype(url) # Check to make sure we got some kind of protocol if self.protocol is None: raise ValueError, "Unknown protocol type in " + url # Parse out the host from the URL resource. host should be something like www.example.com or www.example.com:8888 # and resourceString should be something like /example.html host, resourceString = urllib.splithost(stuffAfterProtocol) # Parse out the port from the host host, port = urllib.splitport(host) # It is possible that port is not defined. In that case we go by the protocol if port is None: # List of common protocol to port mappings protocolToPortMapping = {'http' : 80, 'https' : 443} # Check if the protocol is in the list if self.protocol in protocolToPortMapping: protocolToPortMapping[self.protocol] self._real_port = protocolToPortMapping[self.protocol] else: raise ValueError, "Unknown port for protocol " + str(self.protocol) else: self._real_port = port self._real_host = host httplib.HTTPConnection.request(self, method, url, body, headers) def connect(self): # Call the connect() method of httplib.HTTPConnection httplib.HTTPConnection.connect(self) # At this point I am connected to the proxy server so I can send the CONNECT request connectCommand = "CONNECT " + str(self._real_host) + ":" + str(self._real_port) + " HTTP/1.0\r\n\r\n" self.send(connectCommand) # Expect a HTTP/1.0 200 Connection established response = self.response_class(self.sock, strict=self.strict, method=self._method) (version, code, message) = response._read_status() # Probably here we can handle auth requests... # 407 Proxy Authentication Required if (code == 407): # Obtain the list of proxies using a call to urllib.getproxies() proxyDictionary = urllib.getproxies() # Base the proxy string on what protocol was requested desiredProxy = proxyDictionary[self.protocol] # Parse out the proxy string for the username and password proxy_type, user, password, hostport = urllib2._parse_proxy(desiredProxy) proxyAuthorizationString = 'Proxy-Authorization: Basic %s\r\n\r\n' % base64.b64encode('%s:%s' % (user, password)) connectCommand = "CONNECT " + str(self._real_host) + ":" + str(self._real_port) + " HTTP/1.0\r\n" httplib.HTTPConnection.connect(self) self.send(connectCommand) self.send(proxyAuthorizationString) # Proxy returned something other than 407 or 200 elif (code != 200): self.close() raise socket.error, "Proxy connection failed: %d %s" % (code, message.strip()) # Eat up header block from proxy.... while True: # Note to investigate using "fp" directly and performing a readline(). line = response.fp.readline() if line == '\r\n': break # Determine if we are trying to do an SSL connection. If we are # we need to make sure we do the SSL handshake if (self.protocol == 'https'): newSSLSocket = ssl.wrap_socket(self.sock, keyfile=None, certfile=None) self.sock = newSSLSocket # ConnectHTTPHandler class that does multiple inheritance # This will override both urllib2.HTTPHandler and urllib2.HTTPSHandler class ConnectHTTPHandler(urllib2.HTTPHandler, urllib2.HTTPSHandler): # This method returns a urllib.addinfourl object. The "addinfourl" object contains headers, an http return code # the url, and a socket reference def do_open(self, http_class, req): # The response object returned is of type urllib.addinfourl responseObject = urllib2.HTTPHandler.do_open(self, ConnectBasedProxyHTTPConnection, req) return responseObject if __name__ == '__main__': opener = urllib2.build_opener(ConnectHTTPHandler) urllib2.install_opener(opener) req = urllib2.Request(url='https://login.yahoo.com/config/mail?.intl=us') #req = urllib2.Request(url='http://www.bing.com/') f = urllib2.urlopen(req) print f.read()
a1f302c36a5df438238163b38e2469a1046e5c1a
TylerAlsop/Graphs
/lecture-notes/day-2-word-ladder1.py
4,058
3.859375
4
# Given two words (begin_word and end_word), and a dictionary's word list, # return the shortest transformation sequence from begin_word to end_word, such that: # Only one letter can be changed at a time. # Each transformed word must exist in the word list. Note that begin_word is not a transformed word. # Note: # Return None if there is no such transformation sequence. # All words contain only lowercase alphabetic characters. # You may assume no duplicates in the word list. # You may assume begin_word and end_word are non-empty and are not the same. # Sample: # begin_word = "hit" # end_word = "cog" # return: ['hit', 'hot', 'cot', 'cog'] # begin_word = "sail" # end_word = "boat" # ['sail', 'bail', 'boil', 'boll', 'bolt', 'boat'] # beginWord = "hungry" # endWord = "happy" # None ################### Could start by building the graph first (seen below) ################### # word_graph = { # 'hit': {'hat', 'hot'}, # 'hat': {'cat', 'hot', 'hit'}, # 'cat': {'cot', 'hat'}, # 'hot': {'hit', 'hat', 'cot'}, # 'cog': {'cot'}, # 'cot': {'cog'} # } ################### Or we could start by building the structure first (seen below) ################### # Access the file of words import os import sys with open(os.path.join(sys.path[0], 'words.txt'), 'r') as f: words = f.read().split("\n") # word_file = open('words.txt', 'r') # words = word_file.read().split("\n") # word_file.close() # Put our words in a set for O(1) lookup word_set = set() for word in words: word_set.add(word.lower()) def get_neighbors(word): letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'] neighbors = set() # A neighbor is any word that's different by one letter and is inside of the word_list string_word = list(word) # Take each letter of the alphabet (all 26 of them) and generate EVERY combination of characters where just one letter is different for i in range(len(string_word)): # swap each character with a character from the letters list for letter in letters: new_word = list(string_word) # place new letter at current position in the word new_word[i] = letter # convert the word back to a string new_word_string = "".join(new_word) # Check that the word exists in the word_list (if yes then it is a neighbor) if new_word_string != word and new_word_string in word_set: neighbors.add(new_word_string) # Return all neighbors return neighbors class Queue(): def __init__(self): self.queue = [] def enqueue(self, value): self.queue.append(value) def dequeue(self): if self.size() > 0: return self.queue.pop(0) else: return None def size(self): return len(self.queue) def find_word_path(begin_word, end_word): # Do BFS # Create a queue queue = Queue() # Create a visited set visited = set() # Add a start word to queue (like a path) queue.enqueue([begin_word]) # While the queue is not empty: while queue.size() > 0: # Pop the current word off of the queue current_path = queue.dequeue() current_word = current_path[-1] # If the word has not been visited: if current_word not in visited: # If the current word is the end word: if current_word == end_word: # Return path return current_path # Add current word to visited set visited.add(current_word) # Add neighbors of current word to queue (like a path) for neighbor_word in get_neighbors(current_word): # Make a copy new_path = list(current_path) new_path.append(neighbor_word) queue.enqueue(new_path) print(find_word_path('ants', 'diet')) print(find_word_path('plane', 'stove')) print(find_word_path('lambda', 'google'))
e1aa51e544d816a3b2ff44cc7bee030c96a2d5ec
q2806060/python-note
/a-T-biji/day19/student_project/student_info.py
3,587
3.625
4
from student import Student def input_student(): L = [] # 先创建一个空列表.准备放学生信息的字典 while True: n = input("请输入学生姓名: ") if not n: # 如果姓名为空,结束输入 break try: a = int(input("请输入学生年龄: ")) s = int(input("请输入学生成绩: ")) except ValueError: print("您的输入有误,请按回车键重新输入:") input() continue d = Student(n, a, s) # 创建新对象 L.append(d) return L def output_student(L): print("+---------------+----------+----------+") print("| 姓名 | 年龄 | 成绩 |") print("+---------------+----------+----------+") for d in L: n, a, s = d.get_infos() a = str(a) s = str(s) # 将整数转为字符串 print("|%s|%s|%s|" % (n.center(15), a.center(10), s.center(10))) print("+---------------+----------+----------+") def delete_student_info(L): '''L绑定的是列表对象''' n = input("请输入要删除的学生姓名: ") for i in range(len(L)): # i代表索引 d = L[i] if d.get_name() == n: del L[i] # 根据索引来删除 或 L.pop(i) print("删除", n, "成功") return print("删除失败!") def modify_student_score(L): n = input("请输入要修改的学生的姓名: ") for i in range(len(L)): d = L[i] if d.get_name() == n: # 修改学生成绩 s = int(input("请输入要修改的新成绩: ")) # d.score = s d.set_score(s) print("成功修改", n, '的成绩为:', s) # 返回 return print(n, "这个学生不存在") def output_student_by_score_desc(L): # 先对L进行降度排序, 生成一个新列表L2 def get_score(d): # d用来绑定列表里的字典 return d.get_score() L2 = sorted(L, key=get_score, reverse=True) output_student(L2) def output_student_by_score_asc(L): L2 = sorted(L, key=lambda d: d.get_score()) output_student(L2) def output_student_by_age_desc(L): L2 = sorted(L, key=lambda d: d.get_age(), reverse=True) output_student(L2) def output_student_by_age_asc(L): L2 = sorted(L, key=lambda d: d.get_age()) output_student(L2) def read_from_file(): L = [] # 从si.txt 中读取数据 try: fr = open('si.txt') try: for line in fr: line = line.rstrip() # 去掉左侧的'\n' n, a, s = line.split(',') # ['xiaozhang', '20', '100'] a = int(a) s = int(s) # 转为整数 L.append(Student(n, a, s)) finally: fr.close() print("读取数据成功!") except OSError: print("读取数据失败") return L def save_to_file(L): # 文件数据到文件 si.txt 中 try: fw = open('si.txt', 'w') try: for d in L: # 方法1 # fw.write(d.get_name()) # fw.write(',') # fw.write(str(d.get_age())) # fw.write(',') # fw.write(str(d.get_score())) # fw.write('\n') # 方法2 d.write_to_file(fw) finally: fw.close() print("保存成功!") except OSError: print("保存失败!")
f3ac9194450d7ee69a8fc4e8c20e84c38e11c3cd
sarkondelo/pyladies
/8ho/7.py
706
3.75
4
birth_number = input('Zadej svoje rodné číslo, prosím. ') #fce analytující formát rč def format(birth_number): intak = int(birth_number[:6]) intak2 = int(birth_number[-4:]) if len(str(intak)) == 6 and birth_number[6] == '/' and len(str(intak2)) == 4: return True else: return False print(format(birth_number)) #dělitelné jedenácti def eleven(birth_number): if birth_number % 11 == 0: return True else: return False #vrátí datum narození ve formátu třech čísel - 08, 07, 97 #def date_of_birth(birth_number): # day = birth_number[4:5] # month = int(birth_number[2:3]) # year = int(birth_number[0:1]) # return date_of_birth(birth_number) #print(date_of_birth(birth_number))
e24bd9cad4b75ebf7953ce4be3ce8c9950beee13
Parth731/Python-Tutorial
/pythontut/8_String_Datatype.py
784
3.984375
4
mystr = "Harry is a good boy" print(mystr) #index is start 0 print(mystr[4]) # 4 is excluding print(mystr[0:4]) # length count start from 0 print(len(mystr)) # positive index # print(mystr[0:19]) # print(mystr[0:5:2]) # print(mystr[0::2]) # print(mystr[:5]) # print(mystr[0:]) # print(mystr[:]) # print(mystr[::]) # print(mystr[0:19:1]) #negative index # mystr = "Harry is a good boy" print(mystr[-1:0]) print(mystr[-4:]) print(mystr[-4:-1]) print(mystr[15:18]) print(mystr[::-1]) #reverse string print(mystr[::-2]) #string function print(mystr.isalnum()) print(mystr.isalpha()) print(mystr.endswith("boy")) print(mystr.endswith("bboy")) print(mystr.count("o")) print(mystr.capitalize()) print(mystr.find("is")) print(mystr.lower()) print(mystr.upper()) print(mystr.replace("is","are"))
d7dee45350afc55ad323584fb513c0c7c31bfa88
AravindVasudev/datastructures-and-algorithms
/problems/leetcode/valid_sudoku.py
1,213
3.59375
4
# https://leetcode.com/problems/valid-sudoku/ class Solution: def isValidSudoku(self, board: List[List[str]]) -> bool: for i in range(9): rowSet, colSet = set(), set() for j in range(9): if board[i][j] != '.': if board[i][j] in rowSet: return False rowSet.add(board[i][j]) if board[j][i] != '.': if board[j][i] in colSet: return False colSet.add(board[j][i]) for gridI in range(3): for gridJ in range(3): offsetI = gridI * 3 offsetJ = gridJ * 3 gridSet = set() for i in range(offsetI, offsetI + 3): for j in range(offsetJ, offsetJ + 3): if board[i][j] != '.': if board[i][j] in gridSet: return False gridSet.add(board[i][j]) return True
ecd5c2714193628b34cd985b9f6933ac985cda4c
ra-hul/Baby-Names
/math.py
260
4.125
4
import math; x1= int(input("Enter x1--->")) y1= int(input("Enter y1-->")) x2= int(input("Enter x2--->")) y2=int(input("Enter y2--->")) d1 = (x2 - x1) * (x2 - x1); d2 = (y2 - y1) * (y2 - y1); res = math.sqrt(d1+d2) print("Distance between two points:",res);
e409d609dee5910eb6d6231e20bbf0d2cdb90262
gongjunhuang/Spider
/DMProject/train_test/test.py
740
3.796875
4
def mcnuggets(n): """ Determine if it's possible to buy exactly n McNuggets with packages of 6, 9 and 20 McNuggets. The solution is a Diophantine equation with 3 variables (ax+by+cz=n). Calculate z=(n-ax-by)/c for all x,y. The time complexity is O(n^2). """ packs = {'6': 0, '9': 0, '20': 0} r1 = n // 6 + 1 r2 = n // 9 + 1 for x in range(r1): for y in range(r2): z, remainder = divmod(n - 6 * x - 9 * y, 20) if remainder > 0 or z < 0: continue else: #return {'6': x, '9': y, '20': z} return True return False numbers = [50, 51, 52, 53, 54, 55, 7] for n in numbers: print(n, mcnuggets(n))
6ada036e4fbb9f47a03ac723bc5b879405355131
AntonUden/ProjectEuler
/Python/Project Euler 1 (Python)/Project Euler 1.py
86
3.71875
4
sum = 0 for i in range(1, 1000): if (i%3 == 0) or (i%5 == 0): sum += i print(sum)
e7708c87d8b01fd86be7f2857044a5b54cb4e868
David1874/algorithm
/HW6/Dijkstra_05131011.py
2,886
3.609375
4
class Graph(): def __init__(self, vertices): self.V = vertices self.graph = [] self.graph_matrix = [[0 for column in range(vertices)] for row in range(vertices)] def addEdge(self,u,v,w): pass def get_min(self,X,a) -> int: b=[] for i in range(len(X)): if (X[i] != 0) & (i not in a): b.append(X[i]) min=b[0] for i in b: if i < min: min=i return min def Dijkstra(self, s): #s起始值 a=[s] self.graph_matrix[0] = self.graph[s] for x in range(self.V-1): # for的i跑index i=0 while len(a) < (x+2): # 當最小值=你最新graph matrix的某項時 if i not in a: if self.get_min(self.graph_matrix[len(a)-1],a) == self.graph_matrix[len(a)-1][i]: a.append(i) i+=1 for i in range(self.V): # 都不等於0 取小 if (self.graph[a[-1]][i] != 0) & (self.graph_matrix[len(a)-2][i] != 0): self.graph_matrix[len(a)-1][i] = min(self.graph_matrix[len(a)-2][a[-1]]+self.graph[a[-1]][i],self.graph_matrix[len(a)-2][i]) elif (self.graph[a[-1]][i] != 0) & (self.graph_matrix[len(a)-2][i] == 0): if i not in a: self.graph_matrix[len(a)-1][i] = self.graph[a[-1]][i] + self.graph_matrix[len(a)-2][a[-1]] elif (self.graph[a[-1]][i] == 0) & (self.graph_matrix[len(a)-2][i] != 0): self.graph_matrix[len(a)-1][i] = self.graph_matrix[len(a)-2][i] D = dict((str(i),self.graph_matrix[-1][i]) for i in range(self.V)) return D def Kruskal(self): pass g=Graph(9) g.graph = [[0,4,0,0,0,0,0,8,0], [4,0,8,0,0,0,0,11,0], [0,8,0,7,0,4,0,0,2], [0,0,7,0,9,14,0,0,0], [0,0,0,9,0,10,0,0,0], [0,0,4,14,10,0,2,0,0], [0,0,0,0,0,2,0,1,6], [8,11,0,0,0,0,1,0,7], [0,0,2,0,0,0,6,7,0] ] # g = Graph(7) # g.graph = [[0,7,0,0,0,0,0], # [7,0,10,8,0,0,0], # [0,10,0,12,0,1,0], # [0,8,12,0,8,4,0], # [0,0,6,8,0,10,5], # [0,0,1,4,10,0,6], # [0,0,0,0,5,6,0], # ]; # g = Graph(6) # g.graph = [[0,8,0,0,0,1], # [3,0,1,0,0,0], # [5,0,0,2,2,0], # [0,4,6,0,7,3], # [0,0,0,0,0,0], # [0,0,0,2,8,0]] # g = Graph(6) # g.graph = [[0,5,0,0,0,0], # [0,0,6,0,-4,0], # [0,0,0,0,-3,-2], # [0,0,4,0,0,0], # [0,0,0,1,0,6], # [3,7,0,0,0,0]] print("Dijkstra",g.Dijkstra(1))
bf0806faa67dfa7553469fef01aaffc3d5e16245
RinaticState/python-work
/Chapter 9/privileges.py
2,241
3.984375
4
# -*- coding: utf-8 -*- """ Created on Fri Jan 05 15:54:19 2018 @author: Ayami """ class User(object): """Gives summary of user information.""" def __init__(self, first_name, last_name, username, email, location): """Initialises the first name and last name attributes.""" self.first_name = first_name self.last_name = last_name self.username = username self.email = email self.location = location self.login_attempt = 0 def describe_user(self): """Prints a summary of the user info.""" print("\nUser info: ") print("\nName: " + self.first_name.title() + " " + self.last_name.title() ) print("Username: " + self.username) print("Email: " + self.email) print("Location: " + self.location.title()) def greet_user(self): """Greets the user.""" print("\nGood day, " + self.username + " !") def login_attempts(self): print("\nLogin Attempts: " + str(self.login_attempt) ) def increment_login_attempts(self): self.login_attempt += 1 def reset_login_attempts(self): if self.login_attempt >= 1: self.login_attempt = 0 print("Resetting login attempts..") else: print("The number of attempts is already 0 !") class Privilege(object): """presents the privileges available for an admin.""" def __init__(self): self.privileges = [] def show_privileges(self): """prints a list of the admin's privileges""" print("\n What would you like to do ?") for privilege in self.privileges: print("- " + privilege) class Admin(User): """makes a unique admin user with its own privileges""" def __init__(self, first_name, last_name, username, email, location): super(Admin, self).__init__(first_name, last_name, username, email, location) self.privilege = Privilege() user_admin = Admin('rina', 'takahashi', 'rtakahashi', '[email protected]', 'shibuya') user_admin.describe_user() user_admin.privilege.privileges = ['add post', 'remove post', 'ban user'] user_admin.privilege.show_privileges()
1c41cafb2511ea5c50fcf0a5d051766c1ab8ad77
ratchanon-dev/solution_py
/max.py
2,500
4.125
4
"""PlanCDEFGHIJKLMNOPQRSTUVWXYZ""" def main(): """io function""" text = input() num1 = float(input()) num2 = float(input()) num3 = float(input()) if text == "Descend": print("%.2f, %.2f, %.2f"% (checkhigh(num1, num2, num3), \ checkmid(num1, num2, num3), checklow(num1, num2, num3))) if text == 'Ascend': print("%.2f, %.2f, %.2f"% (checklow(num1, num2, num3), \ checkmid(num1, num2, num3), checkhigh(num1, num2, num3))) if text == "A" and num1 == num2 == num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) if text == "A" and num1 == num2 == num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) if text == "A" and num1 == num2 > num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) elif text == "B" and num1 == num2 < num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) elif text == "B" and num1 < num2 == num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) elif text == "B" and num1 > num2 == num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) elif text == "C" and num1 == num2 > num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) elif text == "C" and num1 == num2 < num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) elif text == "C" and num1 < num2 == num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) elif text == "C" and num1 > num2 == num3: print("%.2f, %.2f, %.2f"% (num1, num2, num3)) def checkhigh(high, mid, low): """check high""" if high >= mid >= low: return high if mid >= low >= high: return mid if low >= high >= mid: return low if high >= low >= mid: return high if mid >= high >= low: return mid if low >= mid >= high: return low def checkmid(high, mid, low): """check mid""" if high >= mid >= low: return mid if mid >= low >= high: return low if low >= high >= mid: return high if high >= low >= mid: return low if mid >= high >= low: return high if low >= mid >= high: return mid def checklow(high, mid, low): """check low""" if high >= mid >= low: return low if mid >= low >= high: return high if low >= high >= mid: return mid if high >= low >= mid: return mid if mid >= high >= low: return low if low >= mid >= high: return high main()
7d361940ad31a7c266f639361c9b401acb732b4a
itenabler-python/PythonDay2
/chart/chart_02.py
668
3.5625
4
import matplotlib.pyplot as plt from matplotlib.ticker import FuncFormatter def value_format(value, position): return '$ {}M'.format(int(value)) # set up values VALUES = [100,150,125,170] POS = [0,1,2,3] LABELS = ['Q1 2018','Q2 2018','Q3 2018','Q4 2018'] # set up the chart # Colors can be specified in multiple formats, as # described in https://matplotlib.org/api/colors_api.html # https://xkcd.com/color/rgb/ plt.bar(POS,VALUES, color='xkcd:moss green') plt.xticks(POS, LABELS) plt.ylabel('Sales') # retreive the current axes and apply formatter axes = plt.gca() axes.yaxis.set_major_formatter(FuncFormatter(value_format)) # to display the chart plt.show()
4d56e41a4ea60e0ab3a0fe596beb1cbaa7f46ae3
jorge-alvarado-revata/code_educa
/python/week3/ejercicios10a.py
240
3.828125
4
# Verifica si un año es bisiesto es_bisiesto = False year = int(input('ingrese el año: ')) es_bisiesto = (year % 4 == 0) es_bisiesto = es_bisiesto and (year % 100 != 0) es_bisiesto = es_bisiesto or (year % 400 == 0) print(es_bisiesto)
d36f797e4df40b9398793818ac4fbebe4bd6c11f
meloun/ew_aplikace
/Aplikace_1_0/Source/libs/test/hex.py
280
3.796875
4
''' Created on 11.11.2013 @author: Meloun ''' s = "abcd" print "{:}".format((12,13)) s2 = s.encode('hex') print s2, type(s2) for c in s: print c print c.encode('hex') print (",".join(c.encode('hex') for c in s)) print ":".join(c.encode('hex') for c in s)
46b0e8d098b974ae897fa28cdc374b1590be5951
PaulMDavid/ml_qs
/Day21/old/RNN_BitCoin.py
2,616
3.625
4
# Importing the Libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Reading CSV file from train set training_set = pd.read_csv('BitCoin_Data.csv') training_set.head() #Selecting the second column [for prediction] training_set = training_set.iloc[:,2:3] training_set.head() # Converting into 2D array training_set = training_set.values training_set # Scaling of Data [Normalization] from sklearn.preprocessing import MinMaxScaler sc = MinMaxScaler() training_set = sc.fit_transform(training_set) training_set = sc.fit_transform(training_set) training_set # Lenth of the Data set len(training_set) 898 X_train = training_set[0:897] Y_train = training_set[1:898] # X_train must be equal to Y_train len(X_train) 897 len(Y_train) 897 #Reshaping for Keras [reshape into 3 dimensions, [batch_size, timesteps, input_dim] X_train = np.reshape(X_train, (897, 1, 1)) X_train #-------------------------Need to be have Keras and TensorFlow backend--------------------------- #RNN Layers from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM regressor = Sequential() # Adding the input layer and the LSTM layer regressor.add(LSTM(units = 4, activation = 'sigmoid', input_shape = (None, 1))) # Adding the output layer regressor.add(Dense(units = 1)) # Compiling the Recurrent Neural Network regressor.compile(optimizer = 'adam', loss = 'mean_squared_error') # Fitting the Recurrent Neural Network [epoches is a kindoff number of iteration] regressor.fit(X_train, Y_train, batch_size = 32, epochs = 20) # Reading CSV file from test set test_set = pd.read_csv('BitCoin_Data.csv') test_set.head() #selecting the second column from test data real_btc_price = test_set.iloc[:,2:3] print(real_btc_price) # Coverting into 2D array real_btc_price = real_btc_price.values #getting the predicted BTC value of the first week of Dec 2017 inputs = real_btc_price inputs = sc.transform(inputs) #Reshaping for Keras [reshape into 3 dimensions, [batch_size, timesteps, input_dim] inputs = real_btc_price[1:109] inputs = np.reshape(inputs, (108, 1, 1)) predicted_btc_price = regressor.predict(inputs) predicted_btc_price = sc.inverse_transform(predicted_btc_price) #Graphs for predicted values plt.plot(real_btc_price, color = 'red', label = 'Real BTC Value') plt.plot(predicted_btc_price, color = 'blue', label = 'Predicted BTC Value') plt.title('BTC Value Prediction') plt.xlabel('Days') plt.ylabel('BTC Value') plt.legend() plt.show()
064b74e4ebb8bc64c71e47a97367d6898a22bbb2
AdamZhouSE/pythonHomework
/Code/CodeRecords/2976/39021/312998.py
201
3.625
4
import re str = input() re.compile res = [] while True: s=input() res.append(s.repalce(str,'')) else: res.append(s) if not s: break for i in res: print(i)
dddb15eeede80a2ba43849566f350048445dd549
olgarozhdestvina/pands-problems-2020
/Problem Set/weekday.py
249
4.34375
4
# Olga Rozhdestvina # The program that outputs whether or not today is a weekday. from datetime import datetime today = datetime.today() if today.weekday() <= 4: print("Yes, unfortunately today is a weekday.") else: print("It is the weekend, yay!")
fd02d127ec7eeb2dd6f2cd53bb35a49387f53925
ctaboy/SpringProjects21
/Language_Modeling/Part 2 Anagram decoder/decode.py
2,790
3.59375
4
#!/usr/bin/env python """Anagram decoder.""" import collections from typing import DefaultDict, List import pynini import argparse KeyTable = DefaultDict[str, List[int]] def get_key(s: str) -> str: """Computes the "key" for a given token.""" return "".join(sorted(s)) def make_key_table(sym: pynini.SymbolTable) -> KeyTable: """Creates the key table. The key table is a dictionary mapping keys to the index of words which have that key. """ table: KeyTable = collections.defaultdict(list) for (index, token) in sym: key = get_key(token) table[key].append(index) return table def make_lattice(tokens: List[str], key_table: KeyTable) -> pynini.Fst: """Creates a lattice from a list of tokens. The lattice is an unweighted FSA. """ lattice = pynini.Fst() # A "string FSA" needs n + 1 states. lattice.add_states(len(tokens) + 1) lattice.set_start(0) lattice.set_final(len(tokens)) for (src, token) in enumerate(tokens): key = get_key(token) # Each element in `indices` is the index of an in-vocabulary word that # represents a possible unscrambling of `token`. indices = key_table[key] assert indices, f"no anagrams found for {token}" for index in indices: # This adds an unweighted arc labeled `index` from the current # state `src` to the next state `src + 1`. lattice.add_arc(src, pynini.Arc(index, index, 0, src + 1)) return lattice def decode_lattice( lattice: pynini.Fst, lm: pynini.Fst, sym: pynini.SymbolTable ) -> str: """Decodes the lattice.""" lattice = pynini.compose(lattice, lm) assert lattice.start() != pynini.NO_STATE_ID, "composition failure" # Pynini can join the string for us. return pynini.shortestpath(lattice).string(sym) def main(args: argparse.Namespace) -> None: lm = pynini.Fst.read(args.lm) sym = lm.input_symbols() assert sym, "no input symbol table found" key_table = make_key_table(sym) with open(args.input, "r") as source: with open(args.output, "w") as sink: for line in source: tokens_list = line.split() lattice = make_lattice(tokens_list, key_table) shortest_path_str = decode_lattice(lattice, lm, sym) print(shortest_path_str, file=sink) if __name__ == "__main__": parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "input", help="Enter an input file path (e.g. data/test.ana)" ) parser.add_argument( "output", help="Enter an output file path (e.g. data/test.hyp)" ) parser.add_argument("--lm", help="Enter a language model file path") main(parser.parse_args())
ef67d287757457892bcb55c57c4d861c2d962d4a
uhrzel/ph-guide-to-prog
/arrays/python/no-lists.py
476
4.03125
4
# Get collection of items: item1 = input() item2 = input() item3 = input() item4 = input() item5 = input() # Our position, or "index": position = int( input() ) # Get our item at position: if (position == 1): our_item = item1 elif (position == 2): our_item = item2 elif (position == 3): our_item = item3 elif (position == 4): our_item = item4 elif (position == 5): our_item = item5 else: our_item = "Item not found!" # Print our item print(our_item)
5bf0ef5baac7616c5c2cbc1cda0a94c959246e3a
HaileeKim/Data-Structure
/DoublyLinkedList.py
2,316
3.953125
4
class DList: class Node: def __init__(self, item, prev, link): self.item = item self.prev = prev self.next = link def __init__(self): self.head = self.Node(None,None,None) self.tail = self.Node(None,self.head,None) self.head.next = self.tail self.size = 0 def __sizeof__(self): return self.size def is_empty(self): return self.size == 0 def insert_before(self,p,item): t = p.prev n = self.Node(item,t,p) p.prev = n t.next = n self.size += 1 def insert_after(self,p,item): t = p.next n = self.Node(item,p,t) t.prev = n p.next = n self.size += 1 def delete(self,x): x.prev.next = x.next x.next.prev = x.prev self.size -= 1 return x.item def search(self, target): p = self.head for k in range(self.size): if target == p.item: return k p = p.next return 0 def print_list(self): if self.is_empty(): print('리스트 비어있음') else: p = self.head.next while p != self.tail: if p.next != self.tail: print(p.item, ' <=> ', end = '') else: print(p.item) p = p.next class EmptyError(Exception): pass if __name__ == '__main__': s = DList() s.insert_after(s.head,'apple') s.insert_before(s.tail,'orange') s.insert_before(s.tail, 'cherry') s.insert_after(s.head.next,'pear') print(s.__sizeof__()) s.print_list() #apple <=> pear <=> orange <=> cherry print('마지막 노드 삭제 후 : \t', end = '') s.delete(s.tail.prev) s.print_list() #apple <=> pear <=> orange print('맨 끝에 포도 삽입 후 : \t', end = '') s.insert_before(s.tail,'grape') s.print_list() #apple <=> pear <=> orange <=> grape print('첫 노드 삭제 후 : \t', end = '') s.delete(s.head.next) s.print_list() #pear <=> oragne <=> grape print('첫 노드 삭제 후 : \t', end = '') s.delete(s.head.next) s.print_list() #orange <=> grapge print('첫 노드 삭제 후 : \t', end = '') s.delete(s.head.next)
f6e30d6af7d7c7d180ae0f810f9dc95545ff1b06
rwylie/python-exercises
/Turtle_Exercises/shapes.py
775
3.609375
4
from turtle import * def circle(): circle(50) def star(size): for i in range(5): forward(size) right(144) def square(): for i in range(4): forward(50) right(90) def pentagon(): for i in range(5): forward(200) right(72) def octagon(): for i in range(8): forward(100) right(45) def hexagon(): for i in range(6): forward(100) right(60) def triangle(): for i in range(3): forward(175) right(120) def diamond(): for i in range(2): forward(100) right(110) forward(75) right(70) def full_star(size): for side in range(5): forward(size) left(36) forward(size) right(108)
dbb500c610ecaa8d2aacd32e0016169a6032104c
daniel-reich/ubiquitous-fiesta
/yXekCk3qRWYR5AHif_24.py
151
3.796875
4
def vow_replace(word, vowel): lst=["a","e","i","o","u"] for char in word: if char in lst: word=word.replace(char, vowel) return word
8ceff93c8bda0482caa2f730e0e142385843ede8
MartrixG/CODES
/NAS/任务/data_process/test.py
210
3.546875
4
import Dataset as data import numpy as np #data.view_detail('cifar100', show_image=True) a = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9]) print(a.reshape(3, 3, 3))
495fdb44d87aaa50df4c8ef7e5c5872ac4f58c82
Astrosysman/lessons_of_python
/lesson3_dz_5_fibonacci_number.py
396
4.25
4
#!/usr/bin/env python3 # Возвращает число Фибоначчи на ведёному пользователю номеру # Автор Вазинский Виталий def fibonacci_number(number): if number == 1 or number == 2: return 1 return fibonacci_number(number - 2) + fibonacci_number(number - 1) def main(): number = int(input('Введите число: ')) print(fibonacci_number(number)) main()
1c324c7964c9918ca783608c94359e2e400dc3d2
kharithomas/LeetCode-Solutions
/two_pointers/two-sum-ii-input-array-is-sorted.py
539
3.515625
4
from typing import List # TC : O(N) # SC : O(1) class Solution: def twoSum(self, numbers: List[int], target: int) -> List[int]: start, end = 0, len(numbers) - 1 while start < end: sum = numbers[start] + numbers[end] if sum == target: return [start + 1, end + 1] elif sum > target: end -= 1 else: start += 1 s = Solution() print(s.twoSum([2, 7, 11, 15], 9)) print(s.twoSum([2, 3, 4], 6)) print(s.twoSum([-1, 0], -1))
9f364aa3baf62debfa9a80ccbcad298a2a0a61f7
moontree/leetcode
/version1/81_Search_In_Rotated_Sorted_Array_II.py
2,166
4.1875
4
""" Follow up for "Search in Rotated Sorted Array": What if duplicates are allowed? Would this affect the run-time complexity? How and why? the relation between mid, left, and right Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). Write a function to determine if a given target is in the array. The array may contain duplicates. """ def search(nums, target): """ :type nums: List[int] :type target: int :rtype: int """ count = len(nums) left = 0 right = count - 1 while left <= right: mid = (left + right) / 2 if nums[mid] == target: return True while nums[left] == nums[mid]: left += 1 if nums[mid] > nums[right]: if nums[left] <= target < nums[mid]: right = mid - 1 else: left = mid + 1 elif nums[mid] < nums[right]: if nums[mid] < target <= nums[right]: left = mid + 1 else: right = mid - 1 else: right -= 1 return False examples = [ { "input": { "nums": [4, 4, 4, 6, 7, 4, 4, 4], "target": 6 }, "output": True }, { "input": { "nums": [4, 4, 4, 4, 7, 0, 4, 4], "target": 1 }, "output": False }, { "input": { "nums": [1, 1, 3, 1], "target": 3 }, "output": True }, { "input": { "nums": [1, 3, 1, 1, 1], "target": 3 }, "output": True }, { "input": { "nums": [3, 1, 2, 2, 2], "target": 1 }, "output": True }, { "input": { "nums": [3, 5, 1], "target": 3 }, "output": True }, ] for example in examples: print "----- testing -----" print example res = search(example["input"]["nums"], example["input"]["target"]) print res == example["output"], "res = ", res, "expected = ", example["output"]
b47489c921441c6c77012aff1a0580770be1368d
Grommash9/python_24_skillbox
/24_zadacha_8/card.py
824
3.640625
4
cards_list = [] def new_cards_list(): suit_list = [' ♣️', ' ♦️', ' ♥️', ' ♠️'] cards = { 'Двойка': 2, 'Тройка': 3, 'Четверка': 4, 'Пять': 5, 'Шестерка': 6, 'Семерка': 7, 'Восьмерка': 8, 'Девятка': 9, 'Десятка': 10, 'Валет': 10, 'Дама': 10, 'Король': 10, 'Туз': 11 } for name, value in cards.items(): for suit in suit_list: cards_list.append([name + suit, value]) def cards_left(): return len(cards_list) - 1 class Card: def __init__(self, number): self.name = cards_list[number][0] self.value = cards_list[number][1] del cards_list[number]
18984e579823fed4235b31bf94232379291918f2
ajeet214/Web-Scrapping
/youtube_channel_30_videos.py
2,798
3.640625
4
""" Project : YouTube Channel videos Author : Ajeet Date : July 27, 2023 """ import re from bs4 import BeautifulSoup as bs from urllib.request import urlopen import json youtube_search = "https://www.youtube.com/@PW-Foundation/videos" # Open the URL and read the content of the page url_search = urlopen(youtube_search) youtube_page = url_search.read() # Parse the HTML content of the page using BeautifulSoup youtube_html = bs(youtube_page, "html.parser") # # Define a regular expression pattern to extract the JSON data from the script tag pattern = r'<script nonce="[-\w]+">\n\s+var ytInitialData = (.+)' script_data = re.search(pattern=pattern, string=youtube_html.prettify())[1].replace(';', '') # Load the JSON data into a Python dictionary json_data = json.loads(script_data) # Extract the list of videos from the JSON data and store it in the 'videos_container' variable videos_container = json_data['contents']['twoColumnBrowseResultsRenderer']['tabs'][1]['tabRenderer']['content']['richGridRenderer']['contents'] print(f"Total videos: {len(videos_container)-1}") # Loop through the video list and print the URLs of the videos for video in videos_container[:-1]: # print(video) video_id = video['richItemRenderer']['content']['videoRenderer']['videoId'] video_url = f"https://www.youtube.com/watch?v={video_id}" print(video_url) """ output: Total videos: 30 https://www.youtube.com/watch?v=LuTONVLzESM https://www.youtube.com/watch?v=KWXKegvNa-I https://www.youtube.com/watch?v=dArUpCasmnE https://www.youtube.com/watch?v=HqG2QchBw8Y https://www.youtube.com/watch?v=1izKrQHyx9M https://www.youtube.com/watch?v=jXAb1evxaJc https://www.youtube.com/watch?v=2dn7XMxRtPE https://www.youtube.com/watch?v=Fks4dVnTb5M https://www.youtube.com/watch?v=nIuGXeISbSo https://www.youtube.com/watch?v=L5G-0FbyAsc https://www.youtube.com/watch?v=uqDX6hcRf2I https://www.youtube.com/watch?v=9ZVfDuqKIQM https://www.youtube.com/watch?v=1wMGzlQTyeM https://www.youtube.com/watch?v=ivS0xPAbVUs https://www.youtube.com/watch?v=UJb799ZLCwQ https://www.youtube.com/watch?v=RPCHRtdO9hg https://www.youtube.com/watch?v=iN2UWJW3lzo https://www.youtube.com/watch?v=lRle7Jzciq8 https://www.youtube.com/watch?v=CPmcBN2xoxI https://www.youtube.com/watch?v=mdZ4g2o7v9g https://www.youtube.com/watch?v=z3ko4cUOYO0 https://www.youtube.com/watch?v=ZLgLCNKQwFw https://www.youtube.com/watch?v=J7hFajBOmBo https://www.youtube.com/watch?v=PXb-jcA2TGA https://www.youtube.com/watch?v=LxHAzwur8cI https://www.youtube.com/watch?v=sBXHecS1S1w https://www.youtube.com/watch?v=l6ZY90YnMy0 https://www.youtube.com/watch?v=33onjejJLDs https://www.youtube.com/watch?v=o3eOj-jhhfI https://www.youtube.com/watch?v=ecGcmstmnGA """
10a021b4293873be8ae55dc1365c56da94c9bb9e
jbell69/python-challenge
/PyBank/main.py
2,312
3.8125
4
# install modules import csv import os #declare variables total_months = 0 net_amount = 0 previous_revenue = 0 monthly_change = 0 m_change_list = [] total_change = [] months = [] # Set path for file csvpath = os.path.join("..", "Data", "budget_data.csv") with open(csvpath, newline='') as bank_csv_file: bank_csvreader = csv.reader(bank_csv_file, delimiter=',') bank_header = next(bank_csvreader) for row in bank_csvreader: # defining data groups months.append(row[0]) revenue = int(row[1]) # total number of months total_months = total_months + 1 # sum all profit/losses net_amount = net_amount + revenue # change in revenue if total_months > 1: monthly_change = revenue - previous_revenue m_change_list.append(monthly_change) previous_revenue = revenue # calculation for output total_change = sum(m_change_list) average_change = total_change / (total_months - 1) great_inc_profit = max(m_change_list) great_dec_profit = min(m_change_list) max_month_index = m_change_list.index(great_inc_profit) min_month_index = m_change_list.index(great_dec_profit) max_month = months[max_month_index] min_month = months[min_month_index] # print out results print ("Financial Analysis") print ("------------------------------") print (f"Total Months: {str(total_months)}") print (f"Total: ${str(net_amount)}") print (f"Average Change: ${str(round(average_change,2))}") print (f"Greatest Increase in Profits: {str(max_month)} ${str(great_inc_profit)}") print (f"Greatest Decrease in Profits: {str(min_month)} ${str(great_dec_profit)}") # exporting results to txt file PyBank_export = open("PyBank.txt", "w") PyBank_export.write ("Financial Analysis\n") PyBank_export.write ("------------------------------\n") PyBank_export.write (f"Total Months: {str(total_months)}\n") PyBank_export.write (f"Total: ${str(net_amount)}\n") PyBank_export.write (f"Average Change: ${str(round(average_change,2))}\n") PyBank_export.write (f"Greatest Increase in Profits: {str(max_month)} ${str(great_inc_profit)}\n") PyBank_export.write (f"Greatest Decrease in Profits: {str(min_month)} ${str(great_dec_profit)}\n") PyBank_export.close()
287361df635003364ab44c8ca9cf099390e36ab2
kellybreedlove/proj6
/Graph.py
3,538
4.03125
4
import sys import Queue """ A class to model a vertex in a graph. """ class Vertex(object): """ idVal The id or value stored at this vertex adjs The vertices that are adjacent to this vertex """ def __init__(self, idVal, adjs): self._id = idVal self._adjacents = adjs """ An accessor for this vertex's id """ def id(self): return self._id """ An accessor for this vertex's adjacent vertices """ def adj(self): return self._adjacents """ A mutator for this vertex's adjacent vertices """ def addAdj(self, adj): self._adjacents += [adj] """ A contains method for adjacents v The vertex in question """ def isAdjacent(self, v): for u in self._adjacents: if u.id() == v.id(): return True return False """ A class to model a graph. """ class Graph(object): """ v All of the vertices in this graph """ def __init__(self, v): self._vertices = v """ Print this graph """ def printGraph(self): for v in self._vertices: for a in v.adj(): print "%s -> %s" % (v.id(), a.id()) """ "Private" Helper Find the vertex that corresponds to the given id return The vertex object that corresponds to the given id """ def getV(self, v): for u in self._vertices: if u.id() == v: return u return None """ Contains v The id of the vertex in question return True if n is in this graph, False otherwise """ def hasVertex(self, v): for u in self._vertices: if u.id() == v: return True return False """ Find the adjacent vertices to this vertex in the graph return The id of adjacent vertices """ def getAdj(self, v): raw = set() for u in self._vertices: if u.id() == v: for a in u.adj(): raw.add(a.id()) adj = [i for i in raw] adj.sort() return adj return ["None"] """ Find the vertex with the most adjacent vertices in this graph return The id of vertex with the most adjacent vertices """ def vertexWithMostAdj(self): maxAdj = self._vertices[0] for v in self._vertices: if len(v.adj()) > len(maxAdj.adj()): maxAdj = v return maxAdj.id() """ Find a path, if any, from vertex s to vertex v in this graph. Do so using depth first search. path The paths from s to each vertex s The id of the starting vertex v The id of the ending vertex return The path from s to v """ def findPath(self, sID, vID = ""): if not self.hasVertex(sID) or not self.hasVertex(vID): return ["These artists are not connected"] s = self.getV(sID) v = self.getV(vID) # vertex : parent paths = {} worklist = [] worklist.append(s) while worklist: x = worklist.pop() for u in x.adj(): if u.id() not in paths: paths[u.id()] = x.id() worklist.append(u) path = [vID] curr = vID while curr != sID: curr = paths[curr] path.append(curr) path.reverse() return path
6f54531db1a486b7549b04fc10dbf5cbc7b6c9fb
mnincao/4linux-520-7938
/aula1/aula1.py
283
3.59375
4
nome = input("Digite o seu nome completo:") cpf = input("Digite seu CPF:") idade = input("Digite sua idade:") print('-------------------------') print('Confirmação de cadastro: ') print(f'Nome:{nome}') print(f'CPF:{cpf}') print(f'Idade:{idade}') print('-------------------------')
0128aa02bef82c5ee9e31d5ee9e736d27f36ba90
Patricksxj/p_scripts
/计算95%置信区间.py
689
3.5625
4
# 使用该方法,计算的是95%CI # 计算95%CI时,网上有人设置 alpha=0.05, 不正确 # 注意:scale不是标注差,是标准误差 # 在查 Z 表的時候,首先要先看檢定是單尾檢定還是雙尾檢定 。如果是求信賴區間的話就是雙尾檢定 。 import numpy as np from scipy.stats import * data=np.random.normal(0,1,10000) confidence=0.95 result=t.interval(confidence,df=len(data) - 1,loc=data.mean(),scale=sem(data)) mean=data.mean() std=data.std() a=mean-1.96*std/np.sqrt(len(data)) b=mean+1.96*std/np.sqrt(len(data)) print("用公式计算出的置信区间:",result) print("手工计算结果,下限",a) print("手工计算结果,上限",b)
8caa03ee484c43ba411299a7614db721a0b1bd91
hornsbym/WarGame
/Connector.py
3,553
3.59375
4
""" Author: Mitchell Hornsby File: Connector.py Purpose: Creates a socket that constantly runs. It waits for players to connect and then pairs them up in a new GameServer. """ from GameServer import GameServer import socket import pickle class Connector (object): def __init__(self): """ Starts the server. """ # Socket info here: # self.HOST = "142.93.118.50" # On the server self.HOST = "127.0.0.1" # For testing self.PORT = 4999 self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) # Creates socket self.socket.bind((self.HOST,self.PORT)) # Binds socket to local port print("CONNECTOR: listening at port", self.PORT) # Keeps track of existing games here (only allow 10 for testing): self.activePort = 5000 self.connected = 0 self.waitingList = [] self.activeGames = [] self.start() def start(self): """ Begins the primary loop for the server.""" outboundData = { "gameServer host": None, "gameServer port": None } counter = 0 while True: # Each time a person joins, iterates over the current list of active games. # If any of the games has finished, removes that game and re-opens the port. for thread in self.activeGames: if thread.isAlive() == False: self.activeGames.remove(thread) print("CONNECTOR: Active port number is", self.activePort, "Iteration", counter) counter += 1 print('CONNECTOR: Trying to recieve data...') inboundData = self.socket.recvfrom(1024) # Gets bundle of data from clients data = inboundData[0] # Separates data from address address = inboundData[1] # Separates address from data data = pickle.loads(data) # Unpickles data back into a python dict print("CONNECTOR: Message:", data, "From:",address) self.waitingList.append(address) # Creates a new Game server here if len(self.waitingList) >= 2: print("CONNECTOR: Someone wants to play, creating a game...") g = GameServer(self.activePort) # Creates game print(g.start()) # Starts game self.activeGames.append(g) # Adds the game a list # Tells the first person to start the game where it's being hosted outboundData["gameServer host"] = self.HOST outboundData["gameServer port"] = self.activePort # Keeps track of how many people have successfully connected self.connected += 1 print("CONNECTOR: Keeping track of the number of people who have connected:", self.connected) # Connects players to the new game for x in range(2): address = self.waitingList[x] # Packages up data and sends it back to the player out = pickle.dumps(outboundData) self.socket.sendto(out, address) print("CONNECTOR: Sent data out to", address) self.waitingList = self.waitingList[2:] # Removes players from waiting list once they're in a game Connector()
e3bcd374e1d0c14019f507c3c67e1883aee024e2
brulogatti/ApprendeCoderAvecPython
/Exercicios_module3.py
7,361
4
4
''' a=int(input()) b=int(input()) c=int(input()) if a==b: print(a) elif a==c: print(a) elif b==c: print(b) temperature=int(input()) if temperature>0: if temperature<=10: print("Il va faire frais.") else: print("Il va faire froid.") a=int(input()) b=int(input()) c=int(input()) if c==1: print(a+b) elif c==2: print(a-b) elif c==3: print(a*b) elif c==4: print(a**2+a*b) else: print("Erreur") nombre=int(input()) if nombre%2==0: print(True) else: print(False) a=int(input()) b=int(input()) if a%b==0: print(False) elif b%a==0: print(False) else: print(True) a=float(input()) b=float(input()) if a<0: print("Erreur") elif b<0: print("Erreur") else: print((a*b)**0.5) nombre1=int(input()) nombre2=int(input()) if nombre1==nombre2: print(12*10) elif nombre2==0: if nombre1==13: print(2*10) else: print(0) elif nombre2%2==0: if nombre2==12: if nombre1==15: print(2*10) else: print(0) elif nombre1==13 or nombre1==16: print(2*10) else: print (0) else: if nombre2==11: if nombre1==16: print(2*10) else: print(0) elif nombre1==14 or nombre1==15: print(2*10) else: print(0) lettre=input() a=float(input()) cube = a**3 if lettre=="T": print(((2**0.5)/12)*cube) elif lettre=="C": print(cube) elif lettre=="O": print(((2**0.5)/3)*cube) elif lettre=="D": print(((15+(7*(5**0.5)))/4)*cube) elif lettre=="I": print(((15+(5*(5**0.5)))/12)*cube) else: print("Polyèdre non connu") n = int(input('valeur du nombre n dont on veut tester la conjecture')) while n != 1: print(n) if n % 2 == 0 : n = n // 2 else: n = 3*n + 1 print(n) import turtle n = int(input()) for i in range(n): turtle.forward(100) turtle.left(360/n) turtle.done() import turtle n = int(input()) for i in range(n): turtle.forward(100) turtle.left(((n-1)*180)/n) turtle.done() import turtle from math import gcd # fonction du module math qui calcule le pgcd de 2 nombres LONGUEUR = 100 # taille de chaque segment de l'étoile n = int(input("Combien de branches désirez-vous ? :")) inc = (n-1) // 2 while gcd(n, inc) > 1: inc = inc - 1 if inc == 1 : print("Impossible de dessiner une étoile à", n, "branches en un tenant") else: angle = 180 - (n - 2 * inc) * 180 / n for i in range(n): turtle.forward(LONGUEUR) turtle.left(angle) turtle.done() for x in range(5): for y in range(4): print(x, y) import turtle for i in range(3): # à chaque itération, trace un losange angle = 120 for j in range(4): # à chaque itération, trace un segment turtle.forward(100) turtle.left(angle) angle = 180 - angle turtle.right(120) turtle.hideturtle() turtle.done() DISTANCE = 3844.0e5 nombre_pliages = 0 epaisseur = 0.0001 while epaisseur < DISTANCE : epaisseur = 2 * epaisseur nombre_pliages = nombre_pliages + 1 response = int(input("Combien de plis sont-ils nécessaires pour se rendre sur la Lune ? : ")) while response!=nombre_pliages: print("Mauvaise réponse.") response = int(input("Combien de plis sont-ils nécessaires pour se rendre sur la Lune ? : ")) print("Bravo !") flag=False cont=0 soma=0 while flag==False: numero=float(input()) if(numero==-1): flag=True else: soma=numero+soma cont=cont+1 print(soma/cont) nombre=int(input()) lado=nombre espaco=0 for i in range(nombre): print(espaco*" " + lado*"X", end="\n") lado=lado-1 espaco=espaco+1 cont=int(input()) soma=0 flag=0 if cont>=0: for i in range(cont): numero=int(input()) soma=soma+numero print(soma) else: while flag!=1: entrada=input() if entrada=="F": print(soma) flag =1 else: numero = int(entrada) soma=soma+numero import random NB_ESSAIS_MAX = 6 secret = random.randint(0, 100) chance=1 flag=0 nombre=int(input()) while chance<=NB_ESSAIS_MAX and flag==0: if nombre==secret: print("Gagné en", chance, "essai(s) !") flag=1 elif nombre>secret and chance!=6: print("Trop grand") nombre=int(input()) chance=chance+1 elif nombre<secret and chance!=6: print("Trop petit") nombre=int(input()) chance=chance+1 else: chance=chance+1 if flag==0: print("Perdu ! Le secret était", secret) saut=int(input()) position_cible=int(input()) position_courante=0 flag=0 proxima = 0 while position_courante!=position_cible and flag==0: proxima = position_courante + saut if proxima<100 and proxima!=0: position_courante=proxima if(position_courante!=position_cible): print(position_courante) elif proxima>100: position_courante=proxima-100 if position_courante!=0 and position_courante!=position_cible: print(position_courante) elif position_courante==position_cible: flag=0 else: flag=1 else: flag=1 if flag==0: print("Cible atteinte") else: print(0) print("Pas trouvée") n = int(input()) for i in range(1,n+1): for j in range(1,n+1): print(i*j, end = " ") print() sin=float(input()) resultado = sin sub=3 soma=5 flag=0 operacao=0 fatorial=1 modulo=0 while flag==0: for i in range(1,sub+1): fatorial = fatorial*i operacao=(sin**sub)/fatorial if operacao<0: modulo=operacao*(-1) else: modulo = operacao if modulo<10e-6: flag=1 resultado = resultado - operacao fatorial=1 sub = sub + 4 for j in range(1,soma+1): fatorial=fatorial*j operacao=(sin**soma)/fatorial if operacao<0: modulo=operacao*(-1) else: modulo=operacao if modulo<10e-6: flag=1 resultado = resultado + operacao fatorial = 1 soma = soma+4 print(resultado) ''' tamanho=int(input()) CONTADOR1=1 contador2=1 contador3=0 numero=0 flag=0 while flag==0: numero=contador2 contador3 = contador3 + 1 if contador2<CONTADOR1: for i in range(contador2,CONTADOR1+1): print(numero, end = "") if numero+1<10: numero = numero+1 else: numero = 0 numero = CONTADOR1 for i in range(contador2+1, CONTADOR1+1): if numero - 1 > 0: numero = numero - 1 else: numero = 0 print(numero, end="") print() else: for i in range(contador2,CONTADOR1+1): print(numero, end = "") if numero+1<10: numero = numero+1 else: numero = 0 numero = CONTADOR1 for i in range(contador2+1, CONTADOR1+1): if numero - 1 > 0: numero = numero - 1 else: numero = 0 print(numero, end="") print() if CONTADOR1+2<10: CONTADOR1=CONTADOR1+2 else: CONTADOR1=CONTADOR1-8 if contador2+1<10: contador2=contador2+1 else: contador2=0 if contador3==tamanho: flag=1#Terminar, exercício 3.18
2794b2cf9308ca912d482f9bb4dbdbcb651631fb
aadilkhhan/Advance-Python-1
/13_pr_03.py
98
3.8125
4
num = int(input("Enter your number : ")) table = [num*i for i in range(1 , 11)] print(table)
2f05f6af584a8ce65670549e60dc5885920ce550
shashankvmaiya/Algorithms-Data-Structures
/LeetCode_python/src/heap/median_dataStream_H.py
2,088
3.65625
4
''' 295. Find Median from Data Stream Question: Design a data structure that supports the following two operations: void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far. E.g., addNum(1) addNum(2) findMedian() -> 1.5 addNum(3) findMedian() -> 2 Solution: - Maintain 2 heaps: a max_heap and a min_heap - max_heap consists of the lower N/2 elements and min_heap consists of the top N/2 elements - whenever size of one of the heaps, for example min_heap > size of max_heap +1, then pop the min element from min_heap and push it to the max_heap - median = either min_heap[0] or max_heap[0] or the mean of the two Created on May 25, 2019 @author: smaiya ''' import heapq class MedianFinder: def __init__(self): """ initialize your data structure here. """ self.min_heap = [] self.max_heap = [] self.size_max, self.size_min = 0, 0 def addNum(self, num: int): if not self.max_heap or num<-self.max_heap[0]: heapq.heappush(self.max_heap, -num) self.size_max+=1 else: heapq.heappush(self.min_heap, num) self.size_min+=1 if self.size_max-self.size_min>1: heapq.heappush(self.min_heap, -heapq.heappop(self.max_heap)) self.size_max-=1 self.size_min+=1 elif self.size_min-self.size_max>1: heapq.heappush(self.max_heap, -heapq.heappop(self.min_heap)) self.size_min-=1 self.size_max+=1 def findMedian(self): if not self.max_heap: median = 0 elif self.size_min==self.size_max: median = (self.min_heap[0]-self.max_heap[0])/2 elif self.size_min<self.size_max: median = -self.max_heap[0] else: median = self.min_heap[0] return median # Your MedianFinder object will be instantiated and called as such: obj = MedianFinder() obj.addNum(2) param_2 = obj.findMedian()
6f60f063e044540992a2212cdfa772afe987469e
tots0tater/scheduler
/tkcalendar.py
3,999
4.625
5
from tkinter import Frame, Button, Label import calendar, datetime class TkCalendar(Frame): """ A tkinter calendar that displays a month. All days on the calendar are buttons that when pressed return a date object to the designated callback function. Required arguments: master -- the parent which TkCalendar will belong to. This is primarily used for drawing. Keyword arguments: date_callback -- a callback function that all dates on a calendar subscribe to when clicked on. The returned function handles the returned date object today_color -- color if the day on the calendar is today current_month_color -- color if day lies within current month. (default 'white') other_month_color -- color if day lies outside current month. (default 'gray93') year -- the year our calendar is initialized to (default datetime.date.today().year) month -- the month our calendar is initialized to (default datetime.date.today().month) """ def __init__( self, master, date_callback=lambda date: print(date), today_color='light cyan', current_month_color='white', other_month_color='gray93', year=datetime.date.today().year, month=datetime.date.today().month): self.master = master super().__init__(self.master) # Where we'll draw the calendar self.calendar_frame = Frame(self) # The date callback function used for when a user clicks on self.date_callback = date_callback # Information to default our calendar month to self.today = datetime.date.today() self.year = year self.month = month # Colors for our calendar self.today_color = today_color self.current_month_color = current_month_color self.other_month_color = other_month_color # Internal calendar for getting a month date calendar self.c = calendar.Calendar() self.header = Label(self, text='', width=20) self.previous_month = Button( self, text="<== previous", command=self.__prev_month, width=10 ) self.next_month = Button( self, text="next ==>", command=self.__next_month, width=10 ) self.__get_calendar() def __prev_month(self): self.month -= 1 if 0 == self.month: self.month = 12 self.year -= 1 self.__get_calendar() def __next_month(self): self.month += 1 if 13 == self.month: self.month = 1 self.year += 1 self.__get_calendar() def set_year(self, year): self.year = year self.__get_calendar() def set_month(self, month): self.month = month self.__get_calendar() def __get_calendar(self, width=5): # Remove all of our internal widgets for our calendar # This is because we're updating our buttons for widget in self.calendar_frame.winfo_children(): widget.destroy() # Update our header self.header.config(text="{} {}".format(calendar.month_name[self.month], self.year)) self.header.grid(row=0, column=3) self.previous_month.grid(row=0, column=0) self.next_month.grid(row=0, column=6) # Draw our day names for col, name in enumerate(calendar.day_name): Label(self.calendar_frame, text=name[:3], width=width).grid(row=0, column=col) # Get our iterable month calendar_month = self.c.monthdatescalendar(self.year, self.month) for row, week in enumerate(calendar_month): for col, day in enumerate(week): # The function our button will go to when pressed def date_handler(day=day): self.date_callback(day) background = None if self.today == day: background = self.today_color elif day.month == self.month: background = self.current_month_color else: background = self.other_month_color # A button for the current day in our calendar. # When pressed, it will pass the date object # to the initialized date_callback function Button( self.calendar_frame, text=str(day.day), width=width, background=background, borderwidth=0, command=date_handler, ).grid(row=row + 1, column=col) self.calendar_frame.grid(row=1, column=0, columnspan=7)
c9f86f1072e7ed7731b164bb3a8f4d19642fe4a3
MNJetter/aly_python_study
/ex3.py
1,165
4.40625
4
# Writes a statement. print "I will now count my chickens:" # Writes a statement followed by the restuls of a math equation. print "Hens", 25.00 + 30.00 / 6.00 # Writes a statement followed by the results of a math equation. print "Roosters", 100.00 - 25.00 * 3.00 % 4.00 # Writes a statement. print "Now I will count the eggs:" # Writes the results of a math equation. print 3.00 + 2.00 + 1.00 - 5.00 + 4.00 % 2.00 - 1.00 / 4.00 + 6.00 # Writes a question. print "Is it true that 3 + 2 < 5 - 7?" # Calculates the answer to that question (t/f). print 3.00 + 2.00 < 5.00 - 7.00 # Prints a question and the results of a math equation. print "What is 3 + 2?", 3.00 + 2.00 # Prints a question and the results of a math equation. print "What is 5 - 7?", 5.00 - 7.00 # Prints a statement. print "Oh, that's why it's False." # Prints a statement. print "How about some more." # Prints a question and calculates the answer (t/f). print "Is it greater?", 5.00 > -2.00 # Prints a question and calculates the answer (t/f). print "Is it greater or equal?", 5.00 >= -2.00 # Prints a question and calculates the answer (t/f). print "Is it less or equal?", 5.00 <= -2.00
6725b82267c0589e3e195787bb466d3540e6057c
mwong33/leet-code-practice
/easy/can_place_flowers.py
1,650
3.828125
4
class Solution: # O(n) time O(1) space def canPlaceFlowers(self, flowerbed: List[int], n: int) -> bool: # Greedy Algorithm # Iterate through the flowerbed # 1) Check if current plot is 0 if it is not just increment to the next plot # 2) If it is 0 check plot in front to see if it is 0 and check plot after to see if it is 0 # 3) If the checks above are true, decrement n and plant the plot with a flower (change it to 1) # 4) If the checks above are false increment to the next plot # 5) Check is n is 0 if it is 0 return True otherwise return False if n == 0: return True if len(flowerbed) == 1: if flowerbed[0] == 1: return False elif n > 1: return False else: return True flowers_remaining = n for i in range(len(flowerbed)): if flowerbed[i] == 0: if i > 0 and i < len(flowerbed) - 1: if flowerbed[i-1] == 0 and flowerbed[i+1] == 0: flowerbed[i] = 1 flowers_remaining -= 1 elif i == 0: if flowerbed[i+1] == 0: flowerbed[i] = 1 flowers_remaining -= 1 elif i == len(flowerbed) - 1: if flowerbed[i-1] == 0: flowerbed[i] = 1 flowers_remaining -= 1 if flowers_remaining == 0: return True return False
7fdcf69c2ad116a4e59b0659620693c2f5b42046
trendsetter37/HackerRank
/Sherlock and the Beast/satb.py
1,033
3.84375
4
#!/usr/bin/python3.4 ''' Sherlock and the Beast on HackerRank ''' import sys from colorama import Back, Style, Fore def decent(n): n = int(n) if n == 1: return -1 else: if n % 3 == 0: return '5' * n else: for i in range(n, -1, -5): # This should return the largest if i % 3 == 0 and (n-i) % 5 == 0: return '5'*i + '3'*(n-i) else: return -1 if __name__ == '__main__': if len(sys.argv) < 2: # Will use sample testcases by default f = open('sample_testcase.txt', 'r') # testnumber case was stripped input_lines = f.readlines()[1::] # Each line is in a list g = open('sample_testcase_answers.txt', 'r') output_lines = g.readlines() for i in range(len(input_lines)): result = decent(input_lines[i]) if int(result) == int(output_lines[i]): print(Fore.GREEN + "Testcase {} passed".format(i+1) + Style.RESET_ALL) else: print(Fore.RED + "Testcase {} failed -- Correct: {}\tActual: {}".format(i+1,\ output_lines[i], result) + Style.RESET_ALL) f.close, g.close()
a59ec0a71b6fe9319f2f3253b5ce94e5e39d9892
J0/Kattis
/python/farming/character.py
106
3.8125
4
x = input() x = int(x) if x == 1 : print(0) elif x == 2: print(1) else: sum = 2**x - x -1 print(sum)
2ad52c36492224f9566ad122a6e77fd495f03098
novicelch/python-study
/python-spider/base/python_base.py
1,291
3.921875
4
# 这是python基础练习 # -*- coding: utf-8 -*- __author__ = "liuchenhu"; import re, math; print(__author__); a = "world"; b = "liuchenhu"; c = 22; print(a); print("hello world"); print("hello", "world", "lch"); print("hello %s"%a); print("hello %s"%(a,)); print("hello %s - %s"%(a, b)); print("%s is %s years ord"%(b, c)); # 数据类型 a = 22; print("a = %s,数据类型: %s"%(a, type(a))); a = 22.12; print("a = %s,数据类型: %s"%(a, type(a))); a = "awsd"; print("a = %s,数据类型: %s"%(a, type(a))); a = 1 > 2; print("a = %s,数据类型: %s"%(a, type(a))); a = ['aaa', 123, 12.3]; print("a = %s,数据类型: %s"%(a, type(a))); a = ("wasd", 34, 33.3); print("a = %s,数据类型: %s"%(a, type(a))); a = {"name":"liuchenhu","age":66} print("a = %s,数据类型: %s"%(a, type(a))); a = None; print("a = %s,数据类型: %s"%(a, type(a))); a = True and False; print("a = %s,数据类型: %s"%(a, type(a))); a = set(["wasd", True, None, 212, 22.3]); print("a = %s,数据类型: %s"%(a, type(a))); # 运算符 print(123//2); print(23%2); print(3**2); # 字符串 print(u"刘陈虎"); print(r"刘白"); print(b"liubai"); # ASCII码 print("98-->%s;a-->%s"%(chr(98),ord('a'))); print("刘陈虎".encode("utf8")); print(b'\xe5\x88\x98\xe9\x99\x88\xe8\x99\x8e'.decode("utf-8"));
6b6601ec96f13f16f338715e32bd5a0487df6462
kizs3515/shingu_1
/0922_4.py
410
3.875
4
for looper in["K","O","R","E","A"]: print "hello", print " " print " " for looper in[1,2,3,4,5]: print "hello" print " " for looper in["AS","AD","AC"]: print "\nhello" print " " for looper in range(0,10): print "hello" for i in 'abcdefg': print i, print " " print " " for i in range(1,10,2): print i, print " " print " " for i in range(10,1,-1): print i, print " " print " "
08e20effcc8c0003c89e4a87116e61b263ada70e
GHs1b1/weatherF
/WeatherF.py
1,246
3.84375
4
# Application that interact with webservice to obtain data. import requests location: str = input("Enter the city name: ") try: print(location) except: print('invalid city, please re-enter') def main(): # website: "https://api.openweathermap.org/data/2.5/weather?q={city name},{state code},{country code}&appid={API # key}" url: str = "http://api.openweathermap.org/data/2.5/weather?q=Stroudsburg,pa,us&units=imperial&APPID=e4e38cc148c3f9ba2ed55980157cd226" res = requests.get(url) data = res.json() print(res.text) print(data) if data['cod'] == '404': print("Invalid data:{}, please check data and re-enter information") else: print(res.json()) temperature = data['main']['temp'] weather_description = data['weather'][0]['description'] humdt = data['main']['humidity'] wind_speed = data['wind']['speed'] print("-----------------------------------------") print("-------------------------------------------") print('temperature: ', temperature) print('wind_speed: {}', format(wind_speed)) print('humidity: ', humdt, '%') print('weather_description: {}', format(weather_description)) main()
cb0c0e475c40dac8f007242ab580906119606c35
patni11/Nand2Tetris
/Downloaded/nand2tetris/projects/06/Instructions.py
7,984
3.6875
4
#Our class to convert each line of assembly language to relevant binary code class Assembly_Binary: def __init__(self, input_array): self.input_array = input_array self.final_array = [] #To store the final 16bit binary lines of the output self.binary_array = [] #To store temporary output #Dictionary for computation self.c_operation_dict = {"0": "0 1 0 1 0 1 0", "1": "0 1 1 1 1 1 1", "-1": "0 1 1 1 0 1 0", "D": "0 0 0 1 1 0 0", "A": "0 1 1 0 0 0 0", "!D": "0 0 0 1 1 0 1", "!A": "0 1 1 0 0 0 1", "-D": "0 0 0 1 1 1 1", "-A": "0 1 1 0 0 1 1", "D+1": "0 0 1 1 1 1 1", "A+1": "0 1 1 0 1 1 1", "D-1": "0 0 0 1 1 1 0", "A-1": "0 1 1 0 0 1 0", "D+A": "0 0 0 0 0 1 0", "D-A": "0 0 1 0 0 1 1", "A-D": "0 0 0 0 1 1 1", "D&A": "0 0 0 0 0 0 0", "D|A": "0 0 1 0 1 0 1", "M": "1 1 1 0 0 0 0", "!M": "1 1 1 0 0 0 1", "-M": "1 1 1 0 0 1 1", "M+1": "1 1 1 0 1 1 1", "M-1": "1 1 1 0 0 1 0", "D+M": "1 0 0 0 0 1 0", "D-M": "1 0 1 0 0 1 1", "M-D": "1 0 0 0 1 1 1", "D&M": "1 0 0 0 0 0 0", "D|M": "1 0 1 0 1 0 1"} #Dictionary for Destination self.destination_dict = {"M": "0 0 1", "D": "0 1 0", "MD": "0 1 1", "A": "1 0 0", "AM": "1 0 1", "AD": "1 1 0", "AMD": "1 1 1"} #Dictionary for Jump self.jump_dict = {"JGT": "0 0 1", "JEQ": "0 1 0", "JGE": "0 1 1", "JLT": "1 0 0", "JNE": "1 0 1", "JLE": "1 1 0", "JMP": "1 1 1"} #Dictionary for Symbols self.symbols_dict = {"R0": "0", "R1": "1", "R2": "2", "R3": "3", "R4": "4", "R5": "5", "R6": "6", "R7": "7", "R8": "9", "R10": "10", "R11": "11", "R12": "12", "R13": "13", "R14": "14", "R15": "15", "SCREEN": "16384", "KBD": "24576", "SP": "0", "LCL": "1", "ARG": "2", "THIS": "3", "THAT": "4"} #To keep tracck of variables enountered so far self.variable_counter = 16 #main function to implement other operations def main(self): initial_array = self.input_array self.first_pass(initial_array) #First Pass self.second_pass(initial_array) #Second pass for each in initial_array: instruction = self.AorC(each) #Check if it is A or C instruction if instruction == "A": self.final_array.append(self.handle_A_instruction(each)) #Perform A operation and store result in final array elif instruction == "C": self.handle_C_instruction(each) #Perform C operation and self.final_array.append(self.binary_array) #store result in final array self.binary_array = [] #Reset the temporary binary array, which stores the calculation for each input array value return self.final_array #Final output with all the lines converted to binary # TO HANDLE LABELS def first_pass(self,initial_array): counter = 0 #To keep track of line numbers for each in initial_array: if "(" in each: string = each.replace('(', "") string = string.replace(')', "") if string not in self.symbols_dict.keys(): self.symbols_dict[string] = counter #Add the label to symbols dictionary with value as the counter. Do this if the line starts with "(" else: counter += 1 #Increase the counter by 1 if we did not encoutner the label. THis is because labels are not counterd as lines in binary # TO HANDLE VARIABLES def second_pass(self,initial_array): for each in initial_array: if "@" in each: new_string = each.replace("@","") # Try to convert it into a integer, if it dosen't work, that means it is a variable try: number = int(new_string) except: if new_string not in self.symbols_dict.keys(): self.symbols_dict[new_string] = str(self.variable_counter) #Storing variable in the symbols dictionary with value as our varible counter self.variable_counter += 1 #increment variable counter by 1 # TO HANDLE C INSTRUCTIONS def handle_C_instruction(self, each): self.binary_array = [1, 1, 1] #Set binary array to 111 because C instructions start with it #We split the array to two parts before "=" and after "=". Handles arugments like D=M-D;JLE if "=" in each: array = each.split("=") #There is a chance that we have a jump condition. We can split using ";" and handle it if ";" in array[1]: second_array = array[1].split(";") self.c_operation(second_array[0]) #Perfrom computation self.destination(array[0]) #Perfrom destination self.jump(second_array[1]) #Perfrom jump return else: self.c_operation(array[1]) self.destination(array[0]) self.binary_array.append(0) self.binary_array.append(0) self.binary_array.append(0) return #We split the array to two parts before ";" and after ";". Handles arugments like D;JLE. We need this in case there is no "="" if ";" in each: array = each.split(";") self.c_operation(array[0]) self.binary_array.append(0) self.binary_array.append(0) self.binary_array.append(0) self.jump(array[1]) return #Handles computation def c_operation(self, array): for each in self.c_operation_dict[array].split(" "): self.binary_array.append(int(each)) #Handles Destination def destination(self, array): for each in self.destination_dict[array].split(" "): self.binary_array.append(int(each)) #Handles Jump def jump(self, array): for each in self.jump_dict[array].split(" "): self.binary_array.append(int(each)) #HANDLES A INSTRUCTION def handle_A_instruction(self, each): if isinstance(each, str): new_str = each.replace('@', '') # if variable, get the value from symbol dictionary else convert the string to integer if new_str in self.symbols_dict.keys(): number = int(self.symbols_dict[new_str]) else: number = int(new_str) self.convert_to_binary(number) #Converts the number to binary #Add zeros if the length of array is less than 16, we need this because of register size while len(self.binary_array) < 16: self.binary_array.append(0) #Flip the binary array because it stores value in the opposite order new_array = [] for i in range(len(self.binary_array)-1, -1, -1): new_array.append(self.binary_array[i]) self.binary_array = [] #rseset binary array return new_array #CONVERTS THE NUMBER TO BINARY def convert_to_binary(self, number): if number == 1: self.binary_array.append(1) return elif number == 0: self.binary_array.append(0) return self.binary_array.append(number % 2) self.convert_to_binary(number // 2) # CHECK IF WE HAVE A 'C' OR 'A' INSTRUCTION def AorC(self, each): if each[0] == "@": return "A" elif each[0] == "(": return "IGNORE" else: return "C"
36653d214911bc0e98acef8fa542d471814b0029
nguyenkims/projecteuler-python
/src/p85.py
1,049
3.65625
4
def f(m,n): '''return the number of rectangles that a m x n contains''' s=0 for a in range(1,m+1): for b in range(1,n+1): s+= (m-a+1)*(n-b+1) return s print f(1,1),f(2,4), f(3,3) def g(m,n): ''' the same as f(m,n) except g(m,n) is calculated recursively''' if m==0: return 0 elif m == 1 : return n * (n+1) /2 else: return 2* g(m-1,n) - g(m-2,n) + n*(n+1)/2 print g(1,1), g(2,1), g(2,3), g(3,3) limit = 2 * 10 **6 M=200 N=2000 L={} # L contains (m,n,f(m,n)) def fillL(): for m in range(0,M): for n in range(0,N): if m==0: L[(m,n)]=0 elif m == 1 : L[(m,n)] = (n * (n+1)) /2 else: L[(m,n)] = 2* L[(m-1,n)] - L[(m-2,n)] + n*(n+1)/2 fillL() print 'L is filled' # print L[(3,3)], L[(2,3)], L[(100,100)], L[(20,200)] , L[(672,854)] def main() : mimumum = 10 ** 6 for m in range(1,M): for n in range(1, N): if m*n + n*(n+1) + m*(m+1)> 3*limit: pass else: t = L[(m,n)] # t= g(m,n) if abs(t - limit) < mimumum: mimumum = abs(t - limit) print m,n,t, m*n main()
10608e1d4bf19495d84af3a84aea9bcec0dbe815
bkrmalick/uni
/Data Strucutres (Python + Java)/CW2/asdasd.py
336
3.75
4
def subarray(subarray, array): for i in range(0,len(subarray)) found=False for j in range(0, len(array)) if(B[i]==A[j]): found=True break if(!found): return False return True A=[4,2,1,3] B=[2,3,1] print(subarray(B, A))
ddeaec9c7a7d0ea2852de9c55ab4ef29fb30453f
gatlinL/csce204
/Exercises/March8th/functions2.py
1,048
3.90625
4
# Author: Gatlin Lawson import turtle import random turtle.setup(575,575) pen = turtle.Turtle() pen.speed(0) pen.pensize(2) pen.hideturtle() def draw_square(): length = 50 x = random.randint(-int(turtle.window_width()/2), int(turtle.window_width()/2 - length)) y = random.randint(-int(turtle.window_height()/2), int(turtle.window_height()/2 - length)) pen.up() pen.setpos(x,y) pen.down() for i in range(4): pen.forward(length) pen.left(90) def draw_triangle(): length = 50 x = random.randint(-int(turtle.window_width()/2), int(turtle.window_width()/2 - length)) y = random.randint(-int(turtle.window_height()/2), int(turtle.window_height()/2 - length)) pen.up() pen.setpos(x,y) pen.down() pen.setheading(0) for i in range(3): pen.forward(length) pen.left(120) for i in range(10): choice = random.randint(0,1) if choice == 0: draw_triangle() else: draw_square() turtle.done()
fb8f66f7a4c46f15c65115aa6b808ccf90fd8608
mikeckennedy/python-jumpstart-course-demos
/apps/09_real_estate_analyzer/final/concept_dicts.py
1,040
4.34375
4
lookup = {} lookup = dict() lookup = {'age': 42, 'loc': 'Italy'} lookup = dict(age=42, loc='Italy') class Wizard: def __init__(self, name, level): self.level = level self.name = name gandolf = Wizard("Gladolf", 42) print(gandolf.__dict__) print(lookup) print(lookup['loc']) lookup['cat'] = 'Fun code demos' if 'cat' in lookup: print(lookup['cat']) # Suppose these came from a data source, e.g. database, web service, etc # And we want to randomly access them import collections User = collections.namedtuple('User', 'id, name, email') users = [ User(1, 'user1', '[email protected]'), User(2, 'user2', '[email protected]'), User(3, 'user3', '[email protected]'), User(4, 'user4', '[email protected]'), ] lookup = dict() for u in users: lookup[u.email] = u print(lookup['[email protected]']) # LAMBDAS def find_significant_numbers(nums, predicate): for n in nums: if predicate(n): yield n numbers = [1, 1, 2, 3, 5, 8, 13, 21, 34] sig = find_significant_numbers(numbers, lambda x: x % 2 == 1) print(list(sig))
5d96b384841e54f2a3edd88bd35741e6e4915a2b
luciasalar/lyrics-money-project
/merge_datasets.py
3,000
3.578125
4
import pandas as pd import glob """Here we create dataset 1 and dataset 2""" # Dataset1 contains: #1. hiphop songs from billboard top 100 hip hop songs (weekly charts from 70s to 2020) #2. top 500 songs with keywords "rap money", "hip hop money" # one problem is that youtube song titles are messy, Genuis lyrics won't have an exact match of these songs, so we need to consider only using YouTube dataset to study comments #Dataset 2 contains dataset 1.1 with "money" in lyrics class CleanData: def __init__(self): '''define the main path''' self.input_path = '/disk/data/share/s1690903/Lyrics_project/data/lyrics_hothp/' self.output_path = '/disk/data/share/s1690903/Lyrics_project/data/billboard_hothp_all.csv' def read_all_files(self) -> pd.DataFrame: """ Read all the billboard files. """ all_files = [] for file in glob.glob(self.input_path + "*.csv"): file_pd = pd.read_csv(file) all_files.append(file_pd) all_files_pd = pd.concat(all_files) all_files_pd.to_csv(self.output_path, encoding='utf-8-sig') return all_files_pd def clean_data(self, lyricsfile): """We only retain songs with publication year.""" file = lyricsfile.dropna(subset=['year']) clean_file = file.dropna(subset=['lyrics']) return clean_file class FilterKeywords: """Here we want to filter lyrics containing money.""" def __init__(self, file): '''define the main path''' self.path = '/disk/data/share/s1690903/Lyrics_project/data/' self.file = pd.read_csv(self.path + file, encoding='utf-8-sig') self.filter_path = '/disk/data/share/s1690903/Lyrics_project/data/filter_lyrics/' self.output_path = '/disk/data/share/s1690903/Lyrics_project/data/filtered_lyrics.csv' def filter_lyrics(self, keywords): '''filter song lyrics according to list of keywords''' for k in keywords.split(','): fil_songs = self.file[self.file['lyrics'].str.contains(k)] fil_songs.to_csv(self.filter_path + 'filter_{}.csv'.format(k)) return fil_songs def read_all_files(self) -> pd.DataFrame: """ Read all the billboard files. """ all_files = [] for file in glob.glob(self.filter_path + "*.csv"): file_pd = pd.read_csv(file) all_files.append(file_pd) all_files_pd = pd.concat(all_files) all_files_pd.to_csv(self.output_path, encoding='utf-8-sig') return all_files_pd #dataset 1.1 #cle = CleanData() #allfiles = cle.read_all_files() # cleaned = cle.clean_data(allfiles) #dataset 1.2 f = FilterKeywords('billboard_hothp_all.csv') money_songs = f.filter_lyrics('money, cash, paperbacks') all_filtered = f.read_all_files() titles = all_filtered[['title','artist','year']] titles.to_csv('/disk/data/share/s1690903/Lyrics_project/data/filtered_lyrics_title.csv') #all_filtered.
0fac2b104e9dedc3661fdd82f7483d55b8d83eb6
Shraddh-Arutwar/Python
/2.1. sum_and_largest_no_of_array.py
322
3.8125
4
# use *range() --> for unpacking the range function output a = [*range(1,11)] sum = 0 print("list is: ", a) for x in range(0, len(a)): sum = sum + int(a[x]) print("sum of array no: ", sum) # Largest number in arrays n = 0 for i in range(0, len(a)): if a[i] > n: n = a[i] print ("largest number is:", n)
97c8405b0753a8618e218760d84ea421ef05a97e
RoanPaulS/Functions_Python
/palindrome_function.py
214
4.3125
4
word = input("Enter any word : "); def palindrome(word): return word == word[::-1]; if palindrome(word): print("Given word is Palindrome"); else: print("Given word is not a Palindrome");
9b02776b64925880c256a548881369336ce74807
Jamiil92/Machine-Learning-by-Andrew-Ng
/code/ml-ex2/ex2.py
4,628
3.859375
4
from __future__ import division, absolute_import, print_function import time import numpy as np import matplotlib from matplotlib import pyplot as plt from matplotlib import * from numpy import * import scipy as sc from scipy.optimize import fmin_ncg from plotData import plotData from sigmoid import sigmoid from costFunction import costFunction from costFunction import gradFunction from plotDecisionBoundary import plotDecisionBoundary from predict import predict ## Logistic Regression plt.clf() ; plt.close('all') # Load data # The first two columns contains the exam scores # and the third column contains the label data = np.loadtxt("C:\\Python37\\Data\\ex2data1.txt", delimiter =",") X = data[:,0:2] ; y = data[:,2]; #### Part 1 : Plotting # We start the exercise by first plotting the data to understand the problem # we are working with . print("Plotting data with + indicating (y=1) examples and o indicating (y=0) examples.\n") plotData(X,y) # Put some labels plt.xlabel("Exam 1 score") plt.ylabel("Exam 2 score") plt.axis([30, 105, 30, 105]) # Specified in plot order plt.legend(["Admitted", "Not admitted"], loc = 'best') plt.show() print("\nProgram paused. Press enter to continue.\n") time.sleep(2) #### Part 2 : Compute Cost and Gradient # In this part of the exercise, we implement the cost and gradient # for logistic regression. # Setup the data matrix appropriatel, and add ones for the intercept term m,n = X.shape # Add intercept term to x and X_test X = np.c_[np.ones((m,)), X] # Initialize fitting parameters initial_theta = np.zeros((n+1,)) # Compute and display initial cost and gradient cost = costFunction (initial_theta, X, y) grad = gradFunction (initial_theta, X, y) print("Cost at initial thata (zeros) : %f\n" %cost) print("Expected cost (approx) : 0.693\n") print("Gradient and initial theta (zeros): \n", grad) print("\nExpected gradients (approx):\n -0.1000\n -12.0092\n -11.2628\n") # Compute and display cost and gradient with non-zero theta test_theta = [-24, 0.2, 0.2] cost = costFunction(test_theta, X, y) grad = gradFunction(test_theta, X, y) print("\nCost at test_theta: %f\n"%cost) print("Expected cost (approx): 0.218\n") print("Gradient at test theta: \n", grad) print("Expected gradients (approx): \n 0.043\n 2.566\n 2.647\n") print("\nProgram paused. Press enter to continue.\n") time.sleep(2) #### Part 3 : Optimizing using fmin_ncg opts = {'disp': disp} theta, cost, u, v, w ,x = fmin_ncg(f = costFunction, x0= initial_theta, fprime= gradFunction, args = (X, y), maxiter = 400, full_output = 1 ) # from the guide # u = fcalls : int # Number of function calls made. # v = gcalls : int # Number of gradient calls made. # w = hcalls : int # Number of hessian calls made. # x = warnflag : int # Warnings generated by the algorithm. # 1 : Maximum number of iterations exceeded. # Print theta to screen print("\nCost at theta found by fmin_ncg: %f\n" %cost) print("Expected cost (approx): 0.203\n") print("theta: \n", theta) print("\nExpected theta (approx):") print("-25.161\n 0.206\n 0.201\n") # Plot Boundary plotDecisionBoundary(theta, X, y) # Labels and legend plt.xlabel("Exam 1 score") plt.ylabel("Exam 2 score") # Specified in plot order plt.legend(['Admitted', 'Not admitted'], loc='best') plt.show() print("\nProgram paused. Press enter to continue.\n") time.sleep(2) #### Part 4: Predict and Accuracies # After learning the parameters, you'll like to use it to predict the outcomes # on unseen datta. In this part, you will use the logistic regression model # to predict the probability that a student with score 45 on exam 1 and # score 85 on exam 2 will be admitted. # Furthermore, you will compute the training and test set accuracies of our # model. # Predict probability for a student with score 45 on exam 1 # and score 85 on exam 2 prob = sigmoid((array([1, 45, 85]).dot(theta))) print("For a student with scores 45 and 85, we predict an admission probability of \n%f" %prob) print("\nExpected value : 0.775 +/- 0.002 \n\n ") # Compute accuracy on our training set p = predict(theta, X) print("Train accuracy: %f\n" %(np.mean(p == y) * 100)) print("Expected accuracy (approx): 89.0\n") print("\n")
2718e8b9d95acf72e433d12f384b0dc5460b7f9e
zumaad/pyrver
/event_loop/event_loop.py
5,663
3.546875
4
import selectors from typing import Callable, Union, Generator import datetime import socket class ResourceTask: """ A resource task is a task that is dependent on a file like object (socket or actual file for example) to be readable or writable. A coroutine will yield this type of task so that it can be resumed by the event loop when the file like object is readable or writable. For example, lets say that you have a coroutine that is making a server request and needs to wait for the response The server could take a long time to send the response, and you want to be able to do other things during that time. So, the function just has to yield event_loop.resource_task(socket_that_communicates_with_server, 'readable'). The coroutine will then be paused and the event loop will run other coroutines. When the event loop notices that the 'socket_that_communicates_with_server' is readable (meaning it has data in it), then the couroutine associated with the task will be resumed. This ResourceTask class is never called explicitly by the coroutines, the coroutines use the 'resource_task' method on the EventLoop class to create a ResourceTask which they then yield. """ EVENT_TO_SELECTORS_EVENT = { #selectors.EVENT_WRITE and EVENT_READ are just ints, but its better to use the variable names. 'writable':selectors.EVENT_WRITE, 'readable':selectors.EVENT_READ } def __init__(self, resource, event: str): """ a event such as writable or readable along with a resource such as a socket or a file is provided. The resource is registered with the event loop so that the event loop can store it in a Selector which it uses to monitor which resources are ready to give back to the coroutine that yielded them. """ self.resource = resource try: self.event = self.EVENT_TO_SELECTORS_EVENT[event] except KeyError: raise KeyError(f"you did not provide a valid event associated with this resource task. Valid events are {self.EVENT_TO_SELECTORS_EVENT}") def __str__(self): return str(vars(self)) class TimedTask: """ A TimedTask is simply used to pause a coroutine for the given delay. The coroutine that yielded the TimedTask will be resumed after the timedtask is complete. """ def __init__(self, delay: int): self.delay = delay self.delay_time = datetime.timedelta(seconds=delay) self.start_time = datetime.datetime.now() self.end_time = self.start_time + self.delay_time def __str__(self): return str(vars(self)) class EventLoop: """ The great event loop. This class is responsible for running coroutines, getting tasks from them, checking whether the tasks are complete, and then resuming the coroutines and passing in any resources the coroutines may need. """ def __init__(self): self.task_to_coroutine = {} self.ready_resources = set() self.resource_selector = selectors.DefaultSelector() def register_resource(self, resource, event: int): self.resource_selector.register(resource, event) def deregister_resource(self, resource) -> None: for task in self.task_to_coroutine: if task.resource == resource: del self.task_to_coroutine[task] break def run_coroutine(self, func: Callable, *func_args): coroutine = func(*func_args) task = next(coroutine) if task: self.task_to_coroutine[task] = coroutine if isinstance(task, ResourceTask): self.register_resource(task.resource, task.event) def is_complete(self, task) -> bool: if isinstance(task, ResourceTask): return self.is_resource_task_complete(task) elif isinstance(task, TimedTask): return self.is_timed_task_complete(task) else: raise ValueError(f"task has to be either a resource task or a timed task, got {str(task)}") def is_resource_task_complete(self, resource_task: ResourceTask) -> bool: return resource_task.resource in self.ready_resources def is_timed_task_complete(self, timed_task: TimedTask) -> bool: return datetime.datetime.now() > timed_task.end_time def get_new_task(self, coroutine: Generator, task): if isinstance(task, ResourceTask): self.resource_selector.unregister(task.resource) try: new_task = coroutine.send(True) return new_task except StopIteration: return None def loop(self): """ This is the meat of the event loop. """ self.ready_resources = set(self.resource_selector.select(-1)) while True: for task, coroutine in list(self.task_to_coroutine.items()): if self.is_complete(task): new_task = self.get_new_task(coroutine, task) del self.task_to_coroutine[task] if new_task: self.task_to_coroutine[new_task] = coroutine if isinstance(task, ResourceTask): self.register_resource(new_task.resource, new_task.event) if not self.task_to_coroutine: print("all tasks are over, exiting the loop") break self.ready_resources = set(resource_wrapper.fileobj for resource_wrapper, event in self.resource_selector.select(-1))
5c1b01b00b25bf6bea7cfad2a719994754fd0fd6
mauricio004/datafiles2
/python_mit_2/exhaustiveenumeration.py
510
3.96875
4
def squareroot(x): epsilon = 0.01 step = epsilon ** 2 numguesses = 0 ans = 0.0 while abs(ans ** 2 - x) >= epsilon and ans * ans <= x: ans += step numguesses += 1 print('numguesses = ' + str(numguesses)) print('ans : ' + str(ans)) if abs(ans ** 2 - x) >= epsilon: print('Failed on square root of', str(x)) else: print(str(ans) + ' is close to square root of ' + str(x)) def main(): squareroot(0.5) if __name__ == '__main__': main()
b204aec72eaea78a54989f29063a33c859c33e1b
garra0123/dlex
/preview/diff.py
173
3.578125
4
from sympy import * # 定义函数变量x x = Symbol('x') # 函数sin(x**2)*x 对x求导 d = diff(sin(x ** 2) * x, x) print("函数sin(x**2)*x 对x求导: \n%s" % d)
45176319fafdc2a666507a575985705a71739f8f
de-ritchie/dsa
/Data Structures/week1_basic_datastructures/tree_height/tree_height.py
1,702
3.90625
4
# python3 import sys import threading class Node: def __init__(self, val): self.val = val self.children = [] def createTree(nodes) : root = None for node in nodes : if node.val == -1: root = node else : nodes[node.val].children.append(node) return root def compute_height(n, parents): # Replace this code with a faster implementation max_height = 0 nodes = [] for i in parents : nodes.append(Node(i)) root = createTree(nodes) # queue = [root] # while len(queue) > 0 : # node = queue.pop(0) # if len(node.children) > 0 : # queue.extend(node.children) # print(node.val) if root == None : return max_height else : queue = [0, root] prev = 0 while len(queue) > 0 : node = queue.pop(0) if isinstance(node, Node) : if len(node.children) > 0: queue.extend(node.children) else : max_height = max(max_height, prev) prev = node + 1 if len(queue) > 0: queue.append(prev) return max_height def main(): n = int(input()) parents = list(map(int, input().split())) print(compute_height(n, parents)) # In Python, the default limit on recursion depth is rather low, # so raise it here for this problem. Note that to take advantage # of bigger stack, we have to launch the computation in a new thread. sys.setrecursionlimit(10**7) # max depth of recursion threading.stack_size(2**27) # new thread will get stack of such size threading.Thread(target=main).start()
73793a70c5a22a1eefee0fb1dcf8036f8b839510
DenisenkoA/2nd-home-task
/str_op.py
423
3.96875
4
s="У лукоморья 123 дуб зеленый 456" #1 if s: if s.count("я")!=0: print(s.index('я')) else: print("буква ""я"" не была представлена") #2 print(s.count("y")) #3 if s: if s.isupper ==True: print(s.isupper()) else: print(s.upper()) #4 print(len(s)) if s: if len(s)>4: print(s.lower()) #5 print('О'+s[1:])
4f756673e56f9e864859fa19e25daac2b3d37de2
inwk6312winter2019/week4labsubmissions-parth801736
/Lab5task2.py
877
3.765625
4
from Lab5task1 import point import copy class rectangle: def __init__(self): self.width = 0 self.height = 0 self.corner = 0 def find_center(r): c = point() c.x = r.corner.x + r.width/2.0 c.y = r.corner.y + r.height/2.0 return c def move_rectangle(r, dx, dy): r.corner.x += dx r.corner.y += dy def new_move(r, dx, dy): res = copy.deepcopy(r) move_rectangle(res, dx, dy) return res rect = rectangle() rect.width = 40.0 rect.height = 80.0 rect.corner = point() rect.corner.x = 0.0 rect.corner.y = 0.0 print('Center') c = find_center(rect) print('(%g, %g)' % (c.x,c.y)) print('') print('(%g, %g)' % (rect.corner.x, rect.corner.y)) print('move') move_rectangle(rect, 200, 100) print('(%g, %g)' % (rect.corner.x, rect.corner.y)) print('') print('New move') n_rect = new_move(rect, 80, 160) print('(%g, %g)' % (n_rect.corner.x, n_rect.corner.y))
eee63537d879c66d4f2d2601dd70500f959838ad
joelcurl/finna
/statements/util.py
365
3.859375
4
def is_current_date(key, past_dates, today): if key not in past_dates: past_dates[key] = today return True else: if past_dates[key] < today: past_dates[key] = today return True return False def is_date_between(date, start, end): if start <= date and date <= end: return True return False
460b294d8d4ac2f27a724d8bd65cdb20087829d2
thegrafico/coding-challenges
/python_challenge/dummy_coding/test.py
308
3.828125
4
ar = [ [1,2,3], [4,6,8], [10,20,30] ] #vertical normalr for row in range( len(ar) ): for col in range( len(ar[0]) ): print(ar[row][col], end=',') #Vertical reversed for row in range( len(ar) ): for col in range( len(ar) - 1, -1, -1 ): print(ar[row][col], end=',')
a85e57997203e91abf2effaf83561e9c4ecf9cb6
oneyuan/CodeforFun
/PythonCode/src/138.copy-list-with-random-pointer.py
1,289
3.59375
4
# # @lc app=leetcode id=138 lang=python3 # # [138] Copy List with Random Pointer # import collections """ # Definition for a Node. class Node: def __init__(self, val, next, random): self.val = val self.next = next self.random = random """ class Solution: def copyRandomList(self, head: 'Node') -> 'Node': dic = collections.defaultdict(lambda: Node(0, None, None)) dic[None] = None n = head while n: dic[n].val = n.val dic[n].next = dic[n.next] dic[n].random = dic[n.random] n = n.next return dic[head] def copyRandomList0(self, head: 'Node') -> 'Node': if not head: return None hashMap = {} newHead = Node(head.val, None, None) hashMap[head] = newHead u, v = head, newHead while u: v.random = u.random if u.next: v.next = Node(u.next.val, None, None) hashMap[u.next] = v.next else: v.next = None u = u.next v = v.next node = newHead while node: if node.random: node.random = hashMap[node.random] node = node.next return newHead
d2f675e265034581b1775b8a4ea18a5994a1c0f7
albertosanfer/MOOC_python_UPV
/Módulo 3/Práctica3_1.py
462
4.09375
4
# A continuación tenemos un input en el que le pediremos un número al usuario y # lo guardaremos en la variable entrada. Después, deberemos guardar en la # variable mayorQueTres el valor True si ese número es mayor que tres y False # en caso contrario. # Nota, acordaros de realizar la conversión de tipos en el input entrada = int(input('Introduce un número:')) if entrada > 3: mayorQueTres = True else: mayorQueTres = False print(mayorQueTres)
dffb264a1cc4f0aca5acb36b12d67b4ab123e627
alyzatuchler/project-euler
/eulerP5.py
678
3.75
4
# -*- coding: utf-8 -*- """ Created on Mon Sep 18 15:36:03 2017 @author: alexa 2520 is the smallest number that can be divided by each of the numbers from 1 to 10 without any remainder. What is the smallest positive number that is evenly divisible by all of the numbers from 1 to 20? """ num_int = 40 #starts at 40 since the smallest # for starting has to be divisible by 20 ans_int = 0 tracker_bool = True iter_int = 0 while(tracker_bool): isDivisible_bool = True for x in range(1, 21): if num_int % x != 0: isDivisible_bool = False if isDivisible_bool: ans_int = num_int tracker_bool = False num_int += 2 print(ans_int)
ee70ef92423123e00cecec5d6bd900c0e0942956
wenjiaaa/Leetcode
/P0001_P0500/0080-remove-duplicates-from-sorted-array-ii.py
1,299
4.03125
4
""" https://leetcode.com/problems/remove-duplicates-from-sorted-array-ii/ \Given a sorted array nums, remove the duplicates in-place such that duplicates appeared at most twice and return the new length. Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory. Example 1: Given nums = [1,1,1,2,2,3], Your function should return length = 5, with the first five elements of nums being 1, 1, 2, 2 and 3 respectively. It doesn't matter what you leave beyond the returned length. Example 2: Given nums = [0,0,1,1,1,1,2,3,3], Your function should return length = 7, with the first seven elements of nums being modified to 0, 0, 1, 1, 2, 3 and 3 respectively. It doesn't matter what values are set beyond the returned length. """ class Solution(object): def removeDuplicates(self, nums): """ :type nums: List[int] :rtype: int """ if len(nums) < 3: return len(nums) l = 1 for i in range(2, len(nums)): if nums[i] != nums[l] or nums[i] == nums[l] and nums[i] != nums[l-1]: l += 1 nums[l] = nums[i] return l+1 S = Solution() nums = [1, 1, 1, 2, 2, 3] res = S.removeDuplicates(nums) print(res, nums)
eef9021d9c043720cca8603679746b1b74b48e23
wayneshun/LPTHW
/spider/函数.py
213
3.609375
4
# -*- coding: utf-8 -*- """ Created on Thu Jul 10 22:37:58 2014 @author: shunxu """ def sum(i1, i2): result= 0 for i in range(i1, i2 + 1): result = result + i return result print sum(1, 100)
db71b3b17f59af1177fcb54d3f3ca0a15bef17ec
kiaev/python
/Lec10/main2.py
374
4.21875
4
""" Сравнение строк. В Python все строки - Unicode. """ print("A > a:", "A" > "a") print("A is:", ord("A")) print("a is:", ord("a")) print("66 is:", chr(66)) print("98 is:", chr(98)) print("ABCD" < "ABCE") """ 'ABCD' VS 'a' Лексико-графический порядок сравнения (как в словарь) """ print("ABCD" < "a")
543d43951d475f80f1fc46af4d8c56e403d9b411
Sakura-Yamada/nandemo
/raspberrypi/motor.py
1,384
3.6875
4
# -*- coding: utf-8 -*- import RPi.GPIO as GPIO import time import sys #参考文献 #https://tool-lab.com/raspberrypi-startup-26/ #https://github.com/CamJam-EduKit/EduKit3/tree/master/CamJam%20Edukit%203%20-%20RPi.GPIO/Code #set GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) #Pin Assignment r1 = 9 r2 = 10 l1 = 8 l2 = 7 #Set in out GPIO.setup(r1, GPIO.OUT) GPIO.setup(r2, GPIO.OUT) GPIO.setup(l1, GPIO.OUT) GPIO.setup(l2, GPIO.OUT) #関数の定義 #motor_OO( number ) で、モーター制御ができる(はず) def forward(wait_time): GPIO.output(r1, 1) GPIO.output(r2, 0) GPIO.output(l1, 1) GPIO.output(l2, 0) print("forward") time.sleep(wait_time) def back(wait_time): GPIO.output(r1, 0) GPIO.output(r2, 1) GPIO.output(l1, 0) GPIO.output(l2, 1) print("back") time.sleep(wait_time) def right(wait_time): GPIO.output(r1, 1) GPIO.output(r2, 0) GPIO.output(l1, 0) GPIO.output(l2, 1) print("right") time.sleep(wait_time) def left(wait_time): GPIO.output(r1, 0) GPIO.output(r2, 1) GPIO.output(l1, 1) GPIO.output(l2, 0) print("left") time.sleep(wait_time) def stop(wait_time): GPIO.output(r1, 0) GPIO.output(r2, 0) GPIO.output(l1, 0) GPIO.output(l2, 0) print("stop") time.sleep(wait_time) #テスト forward(2) stop(0.5) back(2) stop(0.5) right(2) stop(0.5) left(2) stop(0.5) stop(2) GPIO.cleanup()
04f74fb4ab6a0481c0ef340cf9ead35812fb9825
gil9red/SimplePyScripts
/html_parsing/www.sports.ru_epl_table.py
709
3.734375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = "ipetrash" from bs4 import BeautifulSoup def parse(html): soup = BeautifulSoup(html, "lxml") teams = [] for row in soup.select("tbody > tr"): cols = row.select("td") teams.append({ "Место": cols[0].text, "Команда": [name.text for name in row.select("a[class=name]")], "Матчи": cols[2].text, }) return teams if __name__ == "__main__": url = "https://www.sports.ru/epl/table/" import urllib.request with urllib.request.urlopen(url) as rs: html = rs.read() teams = parse(html) for team in teams: print(team)
e25cf215e64025e7c763c4b42631c408bce86191
Ra8/CP
/Python/numbertheory/gcd.py
393
3.78125
4
def gcd(a, b): while a > 1 and b > 1: a, b = max(a, b), min(a, b) a, b = b, a % b if a == 1 or b == 1: return 1 if a == 0: return b if b == 0: return a def test(): assert gcd(5, 10) == 5 assert gcd(2, 3) == 1 assert gcd(5, 8) == 1 assert gcd(6, 8) == 2 assert gcd(30, 70) == 10 if __name__ == "__main__": test()
07e79f7094dbbd4a5054031493eecc00ececfd01
DevepProd/holbertonschool-higher_level_programming-1
/0x03-python-data_structures/6-print_matrix_integer.py
265
3.921875
4
#!/usr/bin/python3 def print_matrix_integer(matrix=[[]]): for i, row in enumerate(matrix): for x, number in enumerate(row): print("{:d}".format(number), end="") if x < len(row) - 1: print(end=" ") print()
e3fcbca9648afb3761ee687bad5dfd16fe98a46b
sourcery-ai-bot/Estudos
/PYTHON/Python-Atividades/modulo_user.py
1,636
4.125
4
"""Uma classe que pode usada para representar um usuário.""" class Usuário(): """Modelar dados base de um usuário.""" def __init__(self, nome, sobrenome, idade, sexo, escolaridade, origem ): """Inicializando os atributos do método.""" self.nome = nome self.sobrenome = sobrenome self.idade = idade self.sexo = sexo self.escolaridade = escolaridade self.origem = origem self.login_tentativas = 0 def apresentar(self): """Exibe o nome do usuário de forma estilizada.""" print("\nOlá, " + self.nome.title() + " " + self.sobrenome.title() + ". Bem vindo ao mundo da programação.") def descrição(self): """Exibe os dados obtidos do usuário.""" print("\nAqui estão os dados fornecidos até então:") print("Nome: " + self.nome.title()) print("Sobrenome: " + self.sobrenome.title()) print("Idade: " + str(self.idade)) print("Sexo: " + self.sexo.title()) print("Escolaridade: " + self.escolaridade.title()) print("Origem: " + self.origem.title()) def incrementando_login_tentativas(self, somar_login): """ Soma a quantidade de logins ao valor atual de tentativas de login. """ self.login_tentativas += somar_login def resetar_login_tentativas(self): """Reseta o número de logins a 0.""" self.login_tentativas = 0 def ver_login_tentativas(self): """Exibe o número de logins do dia.""" print("Tentativas de login: " + str(self.login_tentativas))
de5ceff4a4c66b9a1571888a41b34608b55a4b55
ys1106/Baekjoon
/Baek_12820/venv/Lib/site-packages/nester.py
865
4.09375
4
"""这是“nester.py"模块,提供了一个名为print_lol()的函数,这个函数的作用是用来打印列表,其中有可能包含(也可能不包含)嵌套列表""" def print_lol(the_list,indent=False,level=1): """这个函数取一个位置参数,名为"the_list",这可以是任何python列表(也可以是包含嵌套列表的列表)。所指定的列表中的每个数据项会(递归的)输到屏幕上,各数据项各占一行。""" for each_flick in the_list: if isinstance(each_flick,list): print_lol(each_flick,indent,level+1) else: if indent: for tab_stop in range(level): print("\t",end=' ') print(each_flick)
e944ae9137500d848f3d517e8caf16a9d213d89f
shenlinli3/python_learn
/second_stage/day_04/demo_02_基础数据类型-集合.py
1,028
3.9375
4
# -*- coding: utf-8 -*- """ @Time : 2021/5/13 15:14 @Author : zero """ # 集合 set # 集合是无序的 # 集合中的对象具有唯一性 # 集合的初始化 # 1. set01 = {1, 2, 3, 4} print(type(set01)) print(set01) # 2. # set02 = set("hello") # str\list\tuple # set02 = set([1, 2, 3, 3, 4, 2]) # str\list\tuple set02 = set((1, 2, 3, 3, 4, 2)) # str\list\tuple print(type(set02)) print(set02) # 集合的操作 set03 = {1, 2, 3, 4} set04 = {3, 4, 5, 6, 7} # 交集 print(set03 & set04) # {3, 4} # 并集 print(set03 | set04) # {1, 2, 3, 4, 5, 6, 7} # 差集 print(set03 - set04) # {1, 2} print(set04 - set03) # {5, 6, 7} # 并集 - 交集 = 对称差集 print(set03 ^ set04) # {1, 2, 5, 6, 7} # 集合添加一个对象 set03.add(666) set03.remove(4) print(set03) # 计算长度 print(len({1, 2, 3})) # 3 # 成员运算 print(1 in {1, 2, 3}) # True # 列表、字符串、元组 去重 list01 = [1, 2, 2, 3, 4, 4] list01 = list(set(list01)) print(list01)
3191da3faa0032effb5f78da8c3711e4596fe916
oppenheimera/euler
/601.py
737
3.828125
4
from itertools import count def streak(n): """ Returns the divisibility streak of n 13 is divisible by 1 14 is divisible by 2 15 is divisible by 3 16 is divisible by 4 17 is NOT divisible by 5 So streak(13)=4. >>> streak(13) 4 """ for i in count(0): if (n+i) % (i+1) != 0 or (i+1) > n: return i def P(s, N): """ The number of integers n, 1 < n < N, for which streak(n) = s. >>> P(3,14) 1 >>> P(6,10**6) 14286 """ count = 0 for n in range(1, N+1): if streak(n) == s: count += 1 return count def get_ans(): count = 0 for i in range(1, 32): count += P(i, 4**i) return count print(get_ans())
cafc89d0019f391457ac72a2d98acd4cfce049c4
nashit-mashkoor/Coding-Work-First-Phase-
/practice-pandas/.ipynb_checkpoints/CAPM MODEL-checkpoint.py
1,192
3.515625
4
# -*- coding: utf-8 -*- """ Created on Sun Dec 9 21:08:49 2018 @author: MMOHTASHIM """ import pandas as pd import matplotlib.pyplot as plt import quandl from statistics import mean import numpy as np from IPython import get_ipython api_key="fwwt3dyY_pF8LyZqpNsa" def get_data_company(company_name): df=quandl.get("EURONEXT/"+str(company_name),authtoken=api_key) df=pd.DataFrame(df["Last"]) df.rename(columns={"Last":"Price"},inplace=True) df_2=df.resample("M").mean() return df_2 def get_data_euronext(): df_2=pd.read_csv("EuroNext 100 Historical Data.csv") df_2=df_2.loc[0:6, :] df_2=pd.DataFrame(df_2[["Date","Price"]]) return df_2 def calculate_beta(company_name): df=get_data_euronext() df_2=get_data_company(company_name) xs=np.array((df["Price"])) ys=np.array(df_2["Price"]) m = (((mean(xs)*mean(ys)) - mean(xs*ys)) / ((mean(xs)*mean(xs)) - mean(xs*xs))) b = mean(ys) - m*mean(xs) get_ipython().run_line_magic('matplotlib', 'qt') print("Your Beta is"+ str(m)) regression_line = [(m*x)+b for x in xs] plt.scatter(xs,ys,color='#003F72') plt.plot(xs, regression_line) plt.show() return m, b
e3fb0787aa4a1f0b14f45ac019d7c5745923062e
here0009/LeetCode
/Python/285_InorderSuccessorinBST.py
2,111
3.75
4
""" Given a binary search tree and a node in it, find the in-order successor of that node in the BST. The successor of a node p is the node with the smallest key greater than p.val.   Example 1: Input: root = [2,1,3], p = 1 Output: 2 Explanation: 1's in-order successor node is 2. Note that both p and the return value is of TreeNode type. Example 2: Input: root = [5,3,6,2,4,null,null,1], p = 6 Output: null Explanation: There is no in-order successor of the current node, so the answer is null.   Note: If the given node has no in-order successor in the tree, return null. It's guaranteed that the values of the tree are unique. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/inorder-successor-in-bst 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': def inorder(node): if node: inorder(node.left) res.append(node) inorder(node.right) res = [] inorder(root) res.append(None) index = 0 while res[index] != p: index += 1 return res[index+1] class Solution: def inorderSuccessor(self, root: 'TreeNode', p: 'TreeNode') -> 'TreeNode': curr = root stack = [] while curr: if curr.val > p.val: stack.append(curr) curr = curr.left elif curr.val < p.val: curr = curr.right else: if curr.right: tmp = curr.right while tmp.left: tmp = tmp.left return tmp else: if stack: return stack.pop() else: return None return None
50df3f25025ee0728140414d68057558fd021369
Aasthaengg/IBMdataset
/Python_codes/p03777/s578788663.py
82
3.671875
4
a,b = input().split() if (a == 'H') ^ (b == 'H'): print('D') else: print('H')
ab7aa11d4e9a02ee648a45c5709f2b9d02f9f0cc
Reidddddd/leetcode
/src/leetcode/python/TopKFrequentElements_347.py
512
3.671875
4
class TopKFrequentElements(object): def topKFrequent(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] use counter to count the frequency then sort the counter with value(reverse means descending order) then return the top k """ from collections import Counter counter = Counter(nums) counter = sorted(counter.items(), key=lambda x: x[1], reverse=True) return [x[0] for x in counter[:k]]
d5b99576034d7f75f4ad966785f0d7598be55755
ekocibelli/Special-Topics-in-SE
/HW05_Test_Ejona_Kocibelli.py
2,174
3.5
4
""" Author: Ejona Kocibelli Project Description: Testing functions reverse, rev_enumerate, find_second, get_lines. """ import unittest from HW05_Ejona_Kocibelli import reverse, rev_enumerate, find_second, get_lines class TestString(unittest.TestCase): def test_reverse(self): """ verify that the function reverses the strings properly.""" self.assertEqual((reverse("ALBI AND EJONA")), "ANOJE DNA IBLA") self.assertEqual(reverse("Hello"), "olleH") self.assertEqual(reverse(""), "") def test_rev_enumerate(self): """ verify that the function reverses the sequence and the offset correctly.""" expected = [(4, 'a'), (3, 'n'), (2, 'o'), (1, 'j'), (0, 'e')] result = list(rev_enumerate("ejona")) self.assertEqual(list(rev_enumerate("ejona")), list(reversed(list(enumerate("ejona"))))) self.assertEqual(list(rev_enumerate([3, 33, 11, 44, 67])), list(reversed(list(enumerate([3, 33, 11, 44, 67]))))) self.assertNotEqual(list(rev_enumerate(["ejona"])), list(reversed(list(enumerate("ejonaejona"))))) self.assertEqual(list(rev_enumerate("")), list(reversed(list(enumerate(""))))) self.assertEqual(result, expected) def test_find_second(self): """ verify that the function the second appearance of a substring in a string properly.""" self.assertTrue(find_second('iss', 'Mississippi') == 4) self.assertTrue(find_second('abba', 'abbabba') == 3) self.assertTrue(find_second('ab', 'Eabjona') == -1) self.assertTrue(find_second('ab', 'Ejona') == -1) self.assertTrue(find_second('ab', 'abEjonabjab') == 6) def test_get_lines(self): """ verify that the function reads and yields the information of the file properly""" self.file_path = 'text.txt' expect = ['<line0>', '<line1>', '<line2>', '<line3.1 line3.2 line3.3>', '<line4.1 line4.2>', '<line5>', '<line6>'] result = list(get_lines('text.txt')) self.assertEqual(result, expect) if __name__ == '__main__': unittest.main(exit=False, verbosity=2)