blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
9a339e0d6d33c70e036f8916a14d6fc9c87119e0
Jovamih/PythonProyectos
/Numpy/CalculoMatrices/operadoresBoleanos.py
479
3.65625
4
# /usr/bin/env python3 import numpy as np import sys def operator_boolean(n0=0,n1=0): a=np.random.randint(1,80,size=(9,9)) mul6y7= (np.mod(a,n0)==0 )& (np.mod(a,n1)==0) #enmascaramiento b=a[mul6y7] print(a) if mul6y7.any(): print("Existe al menos un valor multiplo de {} y {}".format(n0,...
9897c3ff8d18c01d6508ced1edc9fefe9c1a3d68
Jovamih/PythonProyectos
/Matplotlib/graficos-dispersion-simples.py
1,112
3.921875
4
#/usr/bin/env python3 import matplotlib.pyplot as plt import numpy as np def dispersion(): x=np.linspace(-20,20,100) y=np.sin(x) plt.plot(x,y,'-^',color='black') #podemos especificar '-ok' #la estrcutura del 3er argumento de la declaracion de plot() es 'linea de separacion|disperso|color' #lo...
61f3afa3ba794a9d0b314652ba2b6ae720fafcb8
Jovamih/PythonProyectos
/Pandas/Data Sciensist/data-missing.py
1,885
3.90625
4
#/usr/bin7env python3 import numpy as np import pandas as pd def missing(): #manejo de dato faltante en python. con pandas #incorpora el modelo centinela mediante los objetos None(Nativo) y NaN #None: objeto nativo en python que representa la ausencia de datos en el codigo a=pd.Series([n**2 for n in r...
fc051c335436b48832e0f31c49d47f507faf4a81
Jovamih/PythonProyectos
/Pandas/Data Sciensist/Indizacion-seleccion-de-datos.py
3,554
3.625
4
#usr/bin/env python import numpy as np import pandas as pd def indizacion(): #usamos el operador IN para indicar si existe una clave (index)en la serie data= pd.Series([12,34,45],index=['Hola','Adios','Visto']) print(data) val = 'Hola' in data #Usamos Keys(), index, items() print("Se encuentra ...
b809cd6e2593797c8be6dd156060a0c630f52469
Jovamih/PythonProyectos
/Numpy/Arrays/atributos.py
625
3.5
4
# /usr/bin/env python3 import numpy as np import sys def atributos(): np.random.seed(0) x1= np.random.randint(2,10,size=6) x2=np.random.randint(2,10,size=(3,5)) x3=np.random.randint(2,10,size=(3,4,5)) #ndim= Numero de dimesiones #shape=Retorna el tamaño de las dimensiones (a,b) #size= El tama...
9bdbf9e5067f9ea8d854846d36b9aaebe4f733ff
dinaklal/PyBot
/scripts/greeting.py
380
3.75
4
import random # Sentences we'll respond with if the user greeted us GREETING_KEYWORDS = ("hello", "hi", "greetings", "sup", "what's up",) GREETING_RESPONSES = ["'sup bro", "hey", "*nods*", "hey you get my snap?"] def check_for_greeting(sentence): if sentence.lower() in GREETING_KEYWORDS: retur...
80f49e48a17c8efb5a686f48f9e5596c6e26206b
alexandermadams/BIS-397-497-AdamsAlexander
/Assignment 3/Assignment 3 - Exercise 6.5.py
535
3.953125
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 8 13:53:08 2020 @author: alexa """ text = 'This is a sentence that repeats itself a few times within the times of this sentence' text = text.lower() word_counts = {} for word in text.split(): if word in word_counts: word_counts[word]+=1 ...
a37993a70f838e51cc0957394d8a209b7bcd1963
Emman-Lopez-Oso/UrbanDisplacementStudio2020
/Sydney/twitter/scripts/summary_stats.py
3,082
3.5
4
import pandas import geopandas as gpd from .clean_tweets import geometrize_tweets from .home_location import assign_home_location def summary_stats(data): """ Analyze the following: - Number of tweets (printed output) - Number of unique users (printed output) - Median number of tweets/u...
13d5b80cc3c56ccfc37624e19cd4cecf2c91529c
klaferr/PHYS410
/kris/nbody.py
7,989
3.53125
4
# This code uses initial conditions from a data file and other parameters # given by the user and integrates the system using second-order # Leapfrog (LF2) until something "interesting" happens # By Ben Flaggs, Vivian Carvajal, Kris Laferriere # 11/18/18 import numpy as np import matplotlib.pyplot as plt fro...
8322c6ce357d6dd5b1242bb67c42e6fee7eb46da
patrycjagrantze/Kryptografia
/Zadanie1_GrupaD.py
17,845
3.859375
4
#-*- coding: utf-8 -*- import os #Zadanie numer 1 #Patrycja Grantze, Jonatan Bresa #funkcja odczytyjąca z pliku txt def open_file (): f = open (nazwa_pliku , "r" , encoding='utf8') plain = "" for i in f : plain = plain + i g = f. read () print("Plik otwarty pomyślnie.") ...
65ccbe14fc6adeaff8614823b0d92826405886b6
Madhav2008/Introduction-To-Python
/File1.py
220
3.640625
4
f = open("File1.txt") f.read() filelines = f.readlines() #print(wordCount) for i in filelines: print(filelines) intro = 'Madhav' intro.split() def Hello(intro): print('Hello'+' '+intro) Hello(intro)
864d0c93264da52d34c8b9e4fe263ca63b7efdda
daimessdn/py-incubator
/exercise list (py)/sorting/bubble.py
820
4.125
4
# Bubble Short list = [] for i in range(0,25): x = float(input("")) list.append(x) # swap the elements to arrange in order # ascending for iter_num in range(len(list)-1, 0, -1): for index in range(iter_num): if (list[index] > list[index+1]): temp = list[index] list[index] = list[index+1] list[index+1] ...
d6184aaf783b476ecbe4c26667f218237821f963
daimessdn/py-incubator
/exercise list (py)/praktikum/prokom28-9/newtonraphson.py
448
3.65625
4
from math import * def f(x): return exp(x) - 5 * (x**2) def f_aksen(x): return exp(x) - 10 * x epsilon1 = 0.0000001 epsilon2 = 0.000001 x = float(input("Masukan nilai x: ")) i = 0 x_sebelumnya = 0 # print(f(a), f(b), f(c)) while (abs(x-x_sebelumnya) > epsilon1): x_sebelumnya = x x = x - (f(x)/f_aksen(x)) ...
2947935f616998f81097793ac6fde8d158f78ad3
daimessdn/py-incubator
/exercise list (py)/gabut/num.py
286
3.890625
4
# Doraemon's pocket things = ["everywhere door", "real 3d glasses", "appartment tree"] print("Put the things in Doraemon's pocket") x = str(input("")) while (x != "finish"): things.append(x) x = str(input("")) print("Let see the things inside...") for i in things: print("- " + i)
630d45582204c4a2becdd2f45ff5647cfe4eff38
shalinihenna/QAP_metaheuristica
/GA.py
8,709
3.734375
4
import random from random import randint import matplotlib.pyplot as plt import numpy as np import time """ La poblacion se define como una lista que contiene un diccionario entonces population[0] = { 'solucion': [1,2,3,5,6], 'valor_objetivo': 12 } """ def swap(p0,p1,solution): temp =...
2a037a4ec58e7582963997c07a0928f4740a269e
xtawfnhdx/PythonInterview
/PythonInterview/DesigPattern/StructuralModel/Flyweight.py
2,177
3.609375
4
""" 享元模式 """ import json from typing import Dict class Flyweight(): def __init__(self, shared_start: str) -> None: self.shared_start = shared_start def operation(self, unique_start: str) -> None: s = json.dumps(self.shared_start) u = json.dumps(unique_start) print(f"Flyweight:...
aca8d04a6c25e469d0e561b0a0339ec1061827b4
xtawfnhdx/PythonInterview
/PythonInterview/DesigPattern/BehaviorPattern/Command.py
1,900
3.859375
4
""" 命令模式 """ from __future__ import annotations from abc import ABC, abstractmethod class Comand(ABC): @abstractmethod def execute(self) -> None: pass class SimpleCommand(Comand): def __init__(self, payload: str) -> None: self._payload = payload def execute(self) -> None: pr...
5ddd09236902a0fddc1ebfc1a6bc78db1767aa22
tranthang96/Python_OPP
/Class/test.py
181
3.671875
4
while 1: try: dtb = float(input("nhap diem:")) break; except Exception: print("Ban da nhap sai, xin moi nhap lai:") if dtb>=5: print("ban da dau") else: print("ban truot")
b34dd71fa9436dff22c6eb7de812951dbc388cc3
tranthang96/Python_OPP
/Class/class_hd.py
8,439
3.78125
4
Nếu hỏi một bạn đã biết về lập trình hướng đối tượng (bất kể ngôn ngữ nào) rằng bạn nghĩ tới từ nào đầu tiên khi nói về OOP có lẽ hầu hết câu trả lời nhận được sẽ là: class (Hay tiếng Việt là lớp). Vậy, class là gì? Nói đơn giản nó giống như là một bản mẫu, một khuôn mẫu. Ở đó ta khai báo các thuộc tính (attri...
fe01520adb278914122aeadd10a11982176dd917
ecerami/fastapi_essentials
/essentials/chapter9/unpack_example.py
529
3.515625
4
from pydantic import BaseModel class Person(BaseModel): first: str last: str zip_code: str def __str__(self): return "%s %s: %s" % (self.first, self.last, self.zip_code) person = Person(first="Bruce", last="Wayne", zip_code="10021") print(person) person_dict = {"first": "Bruce", "last": "W...
40f44be75faa0e2c4f6bc0b4fbfb97787b229ea0
rohitpaul23/k-mean
/kmean.py
6,204
3.734375
4
''' K-Means Algorithm ----------------- ''' import csv import random import math import pygal def read_csv_fieldnames(filename, separator): """ Inputs: filename - name of CSV file separator - character that separates fields Ouput: A dictionary of tuple consist ...
a485eda0fa37663718f8c086b6ac030805f6c2b6
JuanAvila900/CSE
/Juan Avila - Items.py
4,318
3.5625
4
class Item(object): def __init__(self, name): self.name = name def name(self): print("You got a %s" % self.name) class Weapon(Item): def __init__(self, name, Weight, skill, description): super(Weapon, self).__init__(name) self.Weight = Weight self.skill = skill ...
d81d75ccf8fb6410a933d22682175e1695d6457f
nnnangni/algorithm2
/0219/4839-binarysearch.py
577
3.515625
4
T = int(input()) for tc in range(1,T+1): P, A, B = map(int, input().split()) def search(start,end,final): count = 0 middle = 0 while middle != final: middle = int((start + end) / 2) if final < middle: end = middle else: ...
8d179e65bdc2db68c9057933cddd136a509e39e5
nnnangni/algorithm2
/0221/fibo.py
403
3.859375
4
def f(n): if n>=2 and memo[n]==0: memo[n] = f(n-1) + f(n-2) return memo[n] # if문이 끝날때마다 memo리스트에 쌓아주는건지? N = 10 # fibo 10 구하기 memo = [0]*(N+1) # 인덱스로 N만큼 있어야됨 memo[0] = 0 memo[1] = 1 print(f(N)) print(memo) # 피보나치 DP적용 F = [0] * (N+1) F[0] = 0 F[1] = 0 for n in range(2, N+1): F[n] = F[n-1] + F[n+...
6f84990bc9e9854537e02a942bf33ad997f94bbd
nnnangni/algorithm2
/0905/recursion.py
534
3.640625
4
# 멱집합 {1,2,3} - 모든 부분집합 구하기 select=[False,False,False] def powerset(select,depth): print(select,depth) print() if depth==len(select): # 여기서 원하는 부분집합을 구하게 됨 print("내 부분집합",select,depth) print() return select[depth] = True # 해당 숫자를 집합에 사용하겠다. powerset(select,depth+1) ...
a8e4ec9295d85dcf79d83799d0aa83b2340f27e0
nnnangni/algorithm2
/0218/search.py
307
3.765625
4
def search(arr, n, key): i = 0 while i<n and arr[i]!=key: i += 1 if i<n: return i else: return -1 def find(arr, n ,key): for i in range(n): if arr[i] == key: return i return -1 key = 4 A = [7,2,4] print(search(A,3,4)) print(find(A,3,8))
85e00852fa00fb628d831c057f7f0b44672eb250
ZKsenia/ZhdanovaKseniya
/PythonApplication14.py
1,813
3.796875
4
#14.1 print('Введите значения A и B, A<B') a = int(input()) b = int(input()) if (a<b): for i in range(a,b+1): for n in range(1,i+1): print('ответ =', i, sep=' ') else: print('Введите значениия, удовлетворяющие условию') #14.2 print('Введите значения A и B, A>B') a = int(input()) b = int(inp...
4105df8008063eecea2d001ed75b218f88f5d4a6
HwangYoungHa/Coala
/Crawling/2주차/hw1.py
497
3.78125
4
print("일반계산기 프로그램입니다!") a = int(input("계산할 첫번째 값을 입력해주세요 : ")) b = int(input("계산할 두번째 값을 입력해주세요 : ")) print("\n두 개의 값 : %d와 %d"%(a, b)) print("더하기 값 (a + b) : %d"%(a+b)) print("빼기 값 (a - b) : %d"%(a-b)) print("곱하기 값 (a * b) : %d"%(a*b)) print("정수 나누기 값 (a // b) : %d"%(a//b)) print("실수 나누기 값 (a / b) : %.2f"%(a/b)) prin...
5f67ee8f5004c18c64ded878fb3dbd769d80c725
jordi2224/DQNavigator
/controller/GPIOdefinitions.py
2,291
3.640625
4
import RPi.GPIO as GPIO """ Definitions and functions for using the RPi's GPIOs Using miss-timing in H-bridge control pins will cause damage to bridge, motors and/or RPi Some of this function should never ever be called asynchronously """ # Right track pins RT_F = 12 RT_R = 35 RTH1 = 38 RTH2 = 40 # Left track pins L...
9b538721a98f96c260f54f8d58cac3b02667dcbb
renglard/python_L01
/ex5.py
92
3.515625
4
space = 9 for i in range(1,10,2): print((" " * space) + (i * '*')) space = space - 1
b9513943785438b1084a89ba90dc6610c66551aa
jparedes17/ejercicios
/grade-school/grade_school.py
460
3.5625
4
from typing import List class School: def __init__(self): self.students: List[[int, str]] = [] def add_student(self, name: str, grade: int): self.students.append([grade, name]) def roster(self) -> List[str]: self.students.sort() return [i[1] for i in self.students] d...
2fb640ca926f9769d4ee6f9c0de68e1de8b5729c
organisciak/field-exam
/stoplisting/__init__.py
1,421
4.1875
4
''' Python code Example of word frequencies with and without stopwords. Uses Natural Language Toolkit (NLTK) - Bird et al. 2009 bush.txt is from http://www.bartleby.com/124/pres66.html obama.txt is from http://www.whitehouse.gov/blog/inaugural-address ''' from nltk import word_tokenize from nltk.probability import ...
6d315993b7fe772ac2d2fe290db19438efad581e
sumittal/coding-practice
/python/print_anagram_together.py
1,368
4.375
4
# A Python program to print all anagarms together #structure for each word of duplicate array class Word(): def __init__(self, string, index): self.string = string self.index = index # create a duplicate array object that contains an array of Words def create_dup_array(string, size): ...
f4e471fd724900ae215aae4f8a22f08608845f41
sumittal/coding-practice
/python/intersection_of_dict.py
929
3.75
4
def intersection_dict(a1, a2): res = {} k1 = set(a1.keys()) k2 = set(a2.keys()) common_k = list(k1 & k2) for key in common_k: val1 = a1[key] val2 = a2[key] if isinstance(val1, dict) and isinstance(val2, dict): res[key] = get_common(val1, val2) eli...
a9c2da95b60a92e08a8047f7639d0e0c5759e406
sumittal/coding-practice
/python/find_equilibrium.py
1,556
3.734375
4
""" Equilibrium index of an array Equilibrium index of an array is an index such that the sum of elements at lower indexes is equal to the sum of elements at higher indexes. For example, in an arrya A: A[0] = -7, A[1] = 1, A[2] = 5, A[3] = 2, A[4] = -4, A[5] = 3, A[6]=0 3 is an equilibrium index, because: A[0] + A[1]...
3d6251f05849dc49caae345bcc9372b0b55fdd15
sumittal/coding-practice
/python/magic_number.py
705
3.96875
4
''' Write function that should return true if the target integer can be obtained by placing addition or subtraction operations in the list ''' def getWays(magic_number, numbers): if (util(numbers, 0, magic_number) > 0): return True return False def util(numbers, i, magic_number): n = len(numbers) ...
39ac1ff3e0e7a78438a9015f83708fc95fdcf1b4
sumittal/coding-practice
/python/trees/diameter.py
930
4.1875
4
""" Diameter of a Binary Tree The diameter of a tree (sometimes called the width) is the number of nodes on the longest path between two end nodes. """ class Node: def __init__(self,val): self.data = val self.left = None self.right = None def height(root): if ...
00c32b861584b6a7adfc41fcffecc9947b347efb
sumittal/coding-practice
/python/Tictactoe/TicTacToe.py
2,296
4.09375
4
class TicTacToe: """Management of a Tic - Tac - Toe game(does not do strategy).""" def __init__(self): """Start a new game.""" self.board = [[' '] * 3 for j in range(3)] self.player = X def mark(self, i, j): """Put an X or O mark at position(i, j) for next player s turn.""...
d908fd0d883037158c1aa9c226c9136e116744ea
sumittal/coding-practice
/python/search/jump_search.py
1,325
4.09375
4
""" * works only on sorted arrays * the optimal size of block to be jumped is O(root n). This makes the time complexity of Jump search O(root n). * The time complexity of Jump Search is between Linear Search and Binary Search * Binary Search is better than Jump Search, but Jump search has an advantage that we traverse ...
61f3a8e5d32469e7949ae084e0b28131aa96b53d
sumittal/coding-practice
/python/Tictactoe/tictactoe.py
305
3.71875
4
import TicTacToe game = TicTacToe() # X moves: game.mark(1, 1) game.mark(2, 2) game.mark(0, 1) game.mark(1, 2) game.mark(2, 0) # O moves: game.mark(0, 2) game.mark(0, 0) game.mark(2, 1) game.mark(1, 0) print(game) winner = game.winner() if winner is None: print(Tie) else: print(winner, wins)
007ea54a91ffd6a691cec69c6f244f670b9e4ef4
sumittal/coding-practice
/python/triangles/num_pyramid.py
188
3.8125
4
def pyr(n): num = 1 for i in range(1,n+1): #num = 1 for n in range(1,i+1): print(num, end= " ") num = num + 1 print("\r") pyr(10)
0b8ff8440a92dc738daefb082f248debb2a5c3de
sumittal/coding-practice
/python/sort/quick.py
1,021
4.0625
4
# This function takes last element as pivot, places # the pivot element at its correct position in sorted # array, and places all smaller (smaller than pivot) # to left of pivot and all greater elements to right # of pivot def partition(arr, low, high): i = low - 1 p = arr[high] for j in range(low, high): ...
4f69aad05e4ba9e525d25a47efb19419c3c9314e
anthony-chang/machine-learning-playground
/officePrices.py
866
3.5
4
# https: // www.hackerrank.com/challenges/predicting-office-space-price/problem from sklearn import linear_model from sklearn.preprocessing import PolynomialFeatures import numpy as np features, N = (int(n) for n in input().split()) x_train = [] y_train = [] x_test = [] x_train = [0 for i in range(N)] for i in range...
d080cff2b0a7ddd01143a8b6a83e1c0c2761db2f
jmetz93/daily-interview-pro
/Problems/FloorCeilingBinaryTree.py
645
4.03125
4
# Given an integer k and a binary search tree, find the floor (less than or equal to) of k, and the ceiling (larger than or equal to) of k. If either does not exist, then print them as None. # Here is the definition of a node for the tree. class Node: def __init__(self, value): self.left = None self.right =...
62791f9531a748eb06da277e1f58b48d5c655de2
kiddos/model-zoo
/kaggle/league-of-legends/extra_data.py
2,140
3.5
4
import pandas as pd import sqlite3 connection = sqlite3.connect('league.sqlite3') cursor = connection.cursor() dataframe = pd.read_csv('./data/matchinfo.csv') for c in dataframe: print c champs_col = [ 'blueTopChamp', 'blueJungleChamp', 'blueMiddleChamp', 'blueADCChamp', 'blueSupportChamp', 'redTopCha...
9779bda686c7c074f0c8fb8504dd291a3418b934
VIJAYAYERUVA/CS5590-0001-Python-Programming
/Sourcecode/LAB3/ICE/2. New List.py
80
3.5
4
a = [5, 10, 15, 20, 25] f= a[0] l= a[-1] n = [] n.append(f) n.append(l) print(n)
6089699c510ee7e1a1f216a8c3a5a06412d482e3
Velythyl/ML-perso
/dev0/solution.py
1,059
3.59375
4
import numpy as np def make_array_from_list(some_list): return np.array(some_list) def make_array_from_number(num): return np.array([num]) class NumpyBasics: def add_arrays(self, a, b): return np.add(a, b) def add_array_number(self, a, num): return a + num def multiply_elemen...
087cd1aaa247313e9da401bf0bdcc5348fb1772e
Nikoletazl/Advanced-Python
/exercises/multidimensional_lists/diagonal_diff.py
291
3.59375
4
size = int(input()) matrix = [] for _ in range(size): matrix.append([int(x) for x in input().split(" ")]) primary = 0 secondary = 0 for row in range(size): primary += (matrix[row][row]) secondary += (matrix[row][size - 1 - row]) print(abs(primary - secondary))
f9e9b2d3200e1ec79e86ecd3e462b12f3afe9784
Nikoletazl/Advanced-Python
/exercises/functions/even_odd.py
327
3.9375
4
def even_odd(*args): command = args[-1] result = [] parity = 0 if command == "even" else 1 for num in args[:len(args) - 1]: if num % 2 == parity: result.append(num) return result print(even_odd(1, 2, 3, 4, 5, 6, "even")) print(even_odd(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...
d86cdb49810cd9a6c2699795ca0279c100af05b0
Nikoletazl/Advanced-Python
/exercises/multidimensional_lists/flatten_lists.py
177
3.6875
4
sublist = input().split("|") result = [] for idx in range(len(sublist) -1, -1, -1): elements = sublist[idx].split() result += elements print(" ".join(result))
855d350c1a5eac947f5c0ca8b8f522ac5491b50e
Nikoletazl/Advanced-Python
/labs/lists_as_stacks_queues/water_dispenser.py
756
3.765625
4
from collections import deque water_quantity = int(input()) people_queue = deque() while True: command = input() if command == "Start": break people_queue.appendleft(command) while True: command = input() if command == "End": break if command.startswith("ref...
0e8552a7750d18ee58218fa8296697b6c4c01fd0
Nikoletazl/Advanced-Python
/exercises/multidimensional_lists/alice_wonderland.py
1,302
4.09375
4
def is_outside(row, col, size): if row < 0 or col < 0 or row >= size or col >= size: return True return False def get_next_position(direction, r, c): if direction == "up": return r - 1, c if direction == "down": return r + 1, c if direction == "left": re...
4619fb945968010ddeb5a3c5e9f6802445c702d6
Nikoletazl/Advanced-Python
/exercises/lists_as_stacks_queues/fashion_boutique.py
341
3.6875
4
clothes = [int(x) for x in input().split()] rack_capacity = int(input()) used_racks = 1 current_rack = rack_capacity while clothes: cloth = clothes[-1] if cloth > current_rack: used_racks += 1 current_rack = rack_capacity else: current_rack -= cloth clothes.pop()...
4057478b07e6184d461b803537eb74245de87d04
Nikoletazl/Advanced-Python
/labs/multidimensional_lists/square_max_sum.py
908
3.734375
4
def read_matrix(): (n, m) = [int(x) for x in input().split(", ")] matrix = [] for _ in range(n): row = [int(x) for x in input().split(", ")] matrix.append(row) return matrix matrix = read_matrix() sums = [] n = len(matrix) m = len(matrix[0]) for r in range(n - 1): ...
a5b9ba81e2167b89a3bc071b13c804025eeb3c91
Nikoletazl/Advanced-Python
/exercises/lists_as_stacks_queues/balanced_parentheses.py
466
3.65625
4
expression = input() stack = [] balanced = True pair = { "{": "}", "[": "]", "(": ")", } for ch in expression: if ch in "{[(": stack.append(ch) else: if len(stack) == 0: balanced = False last_opening_bracket = stack.pop() if pair[last_open...
147f321a5f8130fd346956473fbb31de248ad6e6
w321-mk/APaG
/checkSpelling.py
519
3.828125
4
import enchant from fileOpen import fileOpen def checkSpelling(text: str): text = text.split() checkifEnglish = enchant.Dict("en_US") score = 0 outOf = 0 for word in text: outOf += 1 if checkifEnglish.check(word): score += 1 return score, outOf def grade(file: str):...
898328fec0d22e522c021c7693e6fc639aa7cbb8
Tao4free/Python
/multiprocessing/sharelist/sharelist_01.py
511
3.78125
4
# https://stackoverflow.com/questions/23623195/multiprocessing-of-shared-list from multiprocessing import Process, Manager def worker(x, i, *args): sub_l = manager.list(x[i]) ch = chr(ord('A') + i) sub_l.append(ch) x[i] = sub_l if __name__ == '__main__': manager = Manager() x = manager.list(...
dde206697a3b356ebfb65202f57d9eae19d7d182
aaronalerander/Various-Programs-In-Python
/expertmachine.py
4,452
4.1875
4
instructions = input("would you like instructions? (yes or no) ").upper() if instructions == ("YES"): print("\nPick a movie from the list below\n\nCHRISTMAS FILMS\nHome Alone 2\tThe Polar Express\tElf\tHow The Grinch Stole Christmas\tA Christmas Carol\nJingle All The Way\tFrosty The Snow Man\tA Charlie Brown Ch...
c2bed85e4f87d1ca12c22acc9ec0bd48ea1f64b5
afreeliu/CrazyPythonLearn
/main/Chapter/13_数据库编程/13.2.4执行查询.py
1,263
3.828125
4
import sqlite3 if __name__ == '__main__': # 1 打开或者创建数据库 conn = sqlite3.connect('first.db') # 2 获取游标 c = conn.cursor() # 3 执行查询语句 c.execute('select * from user_tb where _id > 2') print('查询返回的记录数:', c.rowcount) # 4 通过游标的 description 属性获取列信息 print(c.description) for col in (c.des...
3b96f8c82e640c9d0bc940fc8f8813943ec9f4ca
Mnbee33/self_taught_python
/chapter7.py
823
3.75
4
print("--No.1--") channels = ["walking dead", "entrage", "the soprano", "vampire diaries"] for channel in channels: print(channel) print("--No.2--") for i in range(25, 51): print(i) print("--No.3--") for i, channel in enumerate(channels): print("{}: {}".format(i, channel)) print("--No.4--") corrects = [1...
2a1fa742df96133e4758a56e33c60b623b53694d
Mnbee33/self_taught_python
/chapter22/SequentialSearch.py
321
3.765625
4
def sequential_search(number_list, n): found = False for i in number_list: if i in number_list: if i == n: found = True break return found numbers = range(0, 100) s1 = sequential_search(numbers, 2) print(s1) s2 = sequential_search(numbers, 202) print(s2)...
6e23030423be57a6dedb861a73f823524637678f
Yetz/Cinta-roja
/Udemy/StringsAndEscapeSequences.py
77
3.8125
4
name = input ("please enter your name") print("yor name is" + "%s" % (name))
89d65094d6f370135edf560efd5eed601b38124f
harrygg/FishForCinema
/FishForCinema/db.py
947
3.734375
4
import sqlite3 from film import * from utils import log db_file = "movies.db" def get_last_id(): try: conn = sqlite3.connect(db_file) with conn: cursor = conn.cursor() sql_command = "SELECT MAX(id) FROM movies;" cursor.execute(sql_command) last = cursor.fetchone()[0] return las...
58840050d3c75db5a86715c55e6d881785deee6b
cyzhang9999/leet_code
/link_2num_sum.py
3,454
3.625
4
#!/usr/bin/env python # encoding: utf-8 """ @version: ?? @author: Chunyu Zhang @license: @file: link_2num_sum.py @time: 18/5/29 下午8:15 """ ''' 给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。 你可以假设除了数字 0 之外,这两个数字都不会以零开头。 示例: 输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807 ''' ''' 本题比较...
0b6eaf6f099c3b7197101b2d8892e3529f2f0c75
FabioOJacob/instruct_test
/main.py
2,136
4.1875
4
import math class Point(): """ A two-dimensional Point with an x and an y value >>> Point(0.0, 0.0) Point(0.0, 0.0) >>> Point(1.0, 0.0).x 1.0 >>> Point(0.0, 2.0).y 2.0 >>> Point(y = 3.0, x = 1.0).y 3.0 >>> Point(1, 2) Traceback (most recent call last): ... V...
4a034a926362d8708cb26008a09cf789ce1d49ac
shekharproject2014/Git_Practice_Pro
/all_transfer_statements.py
209
3.5625
4
# Number Break '''for i in range(10): if i==7: print("it's enough") break print(i)''' #Age Break age = [3,10,38,37,40,78,74,50,56] for i in age: if i > 40: break print(i)
b28e7dbe710cc85c33add597713b4568e2fbf502
aspnetcs/viz
/viz/geom.py
3,513
3.5
4
import numpy as np from . import terminal from .stats import normalize from .text import format_float def hist(xs, range=None, margin=10, width=None): """ xs: array of numbers, preferably an np.array, can contain nans, infinities range: (minimum, maximum) tuple of numbers (defaults to (min, max) of xs) ...
f77201c4a88ffd62ef600f5cd59cf5bdc876b123
crisp-k/python_crash_course
/chapter4/exercise6.py
74
3.578125
4
odd_numbers = list(range(1, 21, 2)) for odd in odd_numbers: print(odd)
e511e579a738f3cee80500f4bbe4ba6c5eb4bd7e
crisp-k/python_crash_course
/chapter2/exercise2.py
175
3.734375
4
message = "I am printing a different message" print(message) message = "I wonder why python immediately puts a newline into my output. What if I dont want it?" print(message)
3dc9c1d21163bd71260598e48ebc9b0e4be14918
Jegs03/claculadora-de-ley-de-coseno
/main.py
2,119
3.96875
4
import math # ley de coseno tipo = input("angulo o lado?") if tipo == "l": a = input("primer lado?") b = input("segundo lado?") C = input("angulo?") ang = input("deg o rad?") a = float(a) b = float(b) C = float(C) if ang == "r": c = math.sqrt((pow(a, 2) + pow(b,...
9ab354c2972b01495167cceb33e08eb0eda2e613
joaomxavier/TEC
/joao_xavier.py
4,650
3.734375
4
# Trabalho final TEC # Disciplina: Teoria da Computação # Aluno: João Marcelo Specki Xavier # Professora: Karina Roggia import os # Função que lê o arquivo de entrada def lendo_arquivo(nome): entrada = list() ref_arquivo = open(caminho_arquivo + "\\" + nome, "r") for linha in ref_arquivo: valores =...
323478d7855f8e198e883f9dbc9f08fd5f7d4ea7
tiry/RoboMaster-Playground
/test_vector.py
1,111
3.53125
4
import unittest from vector import Vector class TestVectors(unittest.TestCase): def test_accessXYZ(self): v1 = Vector(1,2,3) self.assertEqual(1, v1.x) self.assertEqual(1, v1[0]) self.assertEqual(2, v1.y) self.assertEqual(2, v1[1]) self.assertEqual(3, v1.z) ...
e297e65dd2a30a256885732ba0af914b89595189
binchen15/leet-python
/linkedlist/prob445.py
859
3.90625
4
# represent integers as singly linked list # add two numbers, and return the result as a list class Solution(object): def addTwoNumbers(self, l1, l2): """ :type l1: ListNode :type l2: ListNode :rtype: ListNode """ n1 = self.list_to_number(l1) n2 = self.list_to...
64552b00d0e1ff6ca97bf781d35917da9125bfd7
binchen15/leet-python
/greedy/prob1974.py
709
3.59375
4
class Solution: def minTimeToType(self, word: str) -> int: curr = "a" # current letter pointed at seconds = 0 def dist(c1, c2): """calculate distance between two letters on the typerwriter""" # n1, n2 = ord(c1)-ord('a'), ord(c2)-ord('a') ...
a3f3feadb711c2dd4bc70c7116d3f4e5d8996903
binchen15/leet-python
/tree/traversal/prob637.py
1,150
3.734375
4
# 637 average of levels of binary tree # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def averageOfLevels(self, root): """ :type root: TreeNode ...
b1174e38a8afaec011c3ef1f30e0e1e8327e7ded
binchen15/leet-python
/math/prob1518.py
366
3.546875
4
class Solution: def numWaterBottles(self, numBottles: int, numExchange: int) -> int: full = numBottles empty = 0 ans = 0 while full > 0 or empty >= numExchange: ans += full # drink water empty += full full, empty = divmod(empty,...
f13d75aa5c2755d6bcff6a74c006a072b689fbb6
binchen15/leet-python
/recursion/prob536.py
1,126
3.96875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def str2tree(self, s: str) -> Optional[TreeNode]: if not s: return None elif "(...
aa1053827ae90c68b89afda3b8fe5caa7a705eaa
binchen15/leet-python
/arrays/prob1389.py
332
3.578125
4
# 1389 Creat Target Array in given order class Solution(object): def createTargetArray(self, nums, index): """ :type nums: List[int] :type index: List[int] :rtype: List[int] """ ans = [] for i, j in enumerate(index): ans.insert(j, nums[i]) ...
9ed8991297b4b37555d94275f3fbc0a792154e0a
binchen15/leet-python
/arrays/prob867.py
359
3.6875
4
# 867 Transpose Matrix class Solution(object): def transpose(self, A): """ :type A: List[List[int]] :rtype: List[List[int]] """ B = [] nr = len(A) nc = len(A[0]) for c in range(nc): row = [A[r][c] for r in range(nr)] B.append(...
dae9307432e2f1b1561d6d150323174eb7640a8f
binchen15/leet-python
/backtracking/prob257.py
852
3.890625
4
# 257 Binary tree paths class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ if not root: return [] results = [] parts = [str(root.val)] self.traverse(parts, root, results) ...
355444411ee94dce8462005d25474d1128b4677b
binchen15/leet-python
/arrays/prob1002.py
657
3.515625
4
# 1002 Find Common Characters class Solution(object): def commonChars(self, A): """ :type A: List[str] :rtype: List[str] """ counts = [] for s in A: tmp = [0] * 26 for c in s: tmp[ord(c)-ord('a')] += 1 counts.append...
93b081194ec86d7d0c8dfad68d78634741bac0aa
binchen15/leet-python
/interview/prob57.py
1,287
3.8125
4
# 57 Insert Intervals class Solution(object): def insert(self, intervals, newInterval): """ :type intervals: List[List[int]] :type newInterval: List[int] :rtype: List[List[int]] """ m = len(intervals) if not m: intervals.append(newInterva...
28a0e138847a26dae69fa52248f71e002c2e5454
binchen15/leet-python
/tree/prob617.py
510
3.90625
4
#617. Merge two binary trees class Solution(object): def mergeTrees(self, t1, t2): """ :type t1: TreeNode :type t2: TreeNode :rtype: TreeNode """ if not t1: return t2 if not t2: return t1 t1.val += t2.val # combine the root ...
ece006920db4388d52ed29a8bd006bcf620d36d4
binchen15/leet-python
/tree/prob101.py
622
3.734375
4
# symmetric trees class Solution(object): def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ if not root: return True return self.isMirror(root.left, root.right) def isMirror(self, s, t): """test if tree s and t ar...
09515ffe8a859620775c8175493d48b33a6fdc67
binchen15/leet-python
/linkedlist/prob142.py
1,058
3.890625
4
class Solution: def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]: if not head: return None def hasCycle(head): if not head: return False cur1 = head cur2 = head.next if not cur2: ...
4bf3a7ced71143dff890e3cf83be5df1516250b7
binchen15/leet-python
/tree/traversal/prob257.py
631
3.859375
4
class Solution: def binaryTreePaths(self, root: Optional[TreeNode]) -> List[str]: ans = [] def walk(path, node): if not node: return if path: path += f"->{node.val}" else: path = f"{nod...
038b3ca406e9eec801d5fb24116615cf58bd1956
binchen15/leet-python
/interview/prob406.py
1,456
3.703125
4
# 406 Queue Reconstruction by Height class Solution(object): def reconstructQueue(self, people): """ :type people: List[List[int]] :rtype: List[List[int]] """ m = len(people) if m <= 1: return people people.sort() ans = [0] * m ...
5891e0a7cce6b762cc813d13322b9cd9df9ab4d8
binchen15/leet-python
/arrays/prob1260.py
736
3.5625
4
# 1260 shift 2D grid class Solution(object): def shiftGrid(self, grid, k): """ :type grid: List[List[int]] :type k: int :rtype: List[List[int]] """ for _ in range(k): self.shift(grid) return grid def shift(self, grid): ...
5c576c2112833b5e8e1fad4f29cfdd139d379812
binchen15/leet-python
/linkedlist/prob206.py
2,653
3.953125
4
class Solution(object): """5% recursion solution.""" def reverseList(self, head): """ :type head: ListNode :rtype: ListNode """ if head == None or head.next == None: return head # a shorter list reverse = self.reverseList(head.next) ...
13c6c710b2358125b07daf9aecd70da38a968afb
binchen15/leet-python
/greedy/ex605.py
1,092
3.984375
4
class Solution(object): """flower bed""" def canPlaceFlowers(self, flowerbed, n): """ :type flowerbed: List[int] :type n: int :rtype: bool """ # n <= m m = len(flowerbed) if n == 0: return True if m == 0: return True...
60ead47795b4882bf5c6dfb763432366f71660a2
binchen15/leet-python
/search/dfs/prob133.py
2,056
3.65625
4
# 133 clone graph # DFS algorithm """ # Definition for a Node. class Node(object): def __init__(self, val = 0, neighbors = None): self.val = val self.neighbors = neighbors if neighbors is not None else [] """ class Solution(object): def cloneGraph(self, node): """ :type node: N...
0d9310cc9205060d3fcff2e197ae6767391ca3f9
binchen15/leet-python
/tree/prob112.py
1,748
3.671875
4
# prob. 112 Path sum # sum of node values along a radius equals to the sum class Solution(object): def hasPathSum(self, root, sum): """ :type root: TreeNode :type sum: int :rtype: bool """ if not root: # not sure return False if not root.left ...
73e9ce08e3adf8fc11e1ff598491963b4d134fc3
binchen15/leet-python
/sorting/ex215.py
645
3.546875
4
class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort(reverse=True) return nums[k-1] class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int]...
3163500fcd552517863a01960a094f4c9f1e722b
binchen15/leet-python
/arrays/prob1275.py
1,521
3.78125
4
# 1275 Tic Tac Toe class Solution(object): def tictactoe(self, moves): """ :type moves: List[List[int]] :rtype: str """ board = [ [" "," "," "] for _ in range(3)] for i, move in enumerate(moves): x, y = move if i & 1: board[x...
3affd99b90bc6b6cb9a0298b684b205a2a3bbfb1
binchen15/leet-python
/hashtable/prob719.py
877
3.546875
4
class Solution(object): def smallestDistancePair(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ nums.sort() m = len(nums) # bisecting the min and max possible distance l, h = 0, nums[-1] - nums[0] while l < h: ...
1bf6f5cbf6a326de1ec845adc6d8cb7807e34860
binchen15/leet-python
/tree/prob1325.py
667
3.6875
4
class Solution: def removeLeafNodes(self, root: Optional[TreeNode], target: int) -> Optional[TreeNode]: if not root: return None if root.val == target and self.isLeaf(root): return None root.left = self.removeLeafNodes(root.left, target) ...
a2df6569fb7553f72667c03ae67ace637b9b9dbb
akaliutau/cs-problems-python
/problems/sort/Solution406.py
1,615
4.125
4
""" You are given an array of people, people, which are the attributes of some people in a queue (not necessarily in order). Each people[i] = [hi, ki] represents the ith person of height hi with exactly ki other people in front who have a height greater than or equal to hi. Reconstruct and return the queu...
2328fba53c5419f763aa07929142ef58ce56939a
akaliutau/cs-problems-python
/problems/dp/Solution1647.py
1,572
3.59375
4
""" A string s is called good if there are no two different characters in s that have the same frequency. Given a string s, return the minimum number of characters you need to delete to make s good. The frequency of a character in a string is the number of times it appears in the string. For ex...
359f2db50e522e3adca68057d7965828ac4d7d09
akaliutau/cs-problems-python
/problems/binarysearch/Solution81.py
398
4.03125
4
""" Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. (i.e., [0,0,1,2,2,5,6] might become [2,5,6,0,0,1,2]). You are given a target value to search. If found in the array return true, otherwise return false. Example 1: Input: nums = [2,...
657280e2cf8fbbc26b59ed7830b342713cac502b
akaliutau/cs-problems-python
/problems/hashtable/Solution957.py
1,240
4.15625
4
""" There are 8 prison cells in a row, and each cell is either occupied or vacant. Each day, whether the cell is occupied or vacant changes according to the following rules: If a cell has two adjacent neighbors that are both occupied or both vacant, then the cell becomes occupied. Otherwise, it...