blob_id stringlengths 40 40 | repo_name stringlengths 5 127 | path stringlengths 2 523 | length_bytes int64 22 545k | score float64 3.5 5.34 | int_score int64 4 5 | text stringlengths 22 545k |
|---|---|---|---|---|---|---|
6fadccdbc4e934881abac49a979eeacbef7eac7f | xstast24/utils | /enumeration.py | 3,328 | 4.0625 | 4 | class Enumeration:
"""
Helps to make (lightweight) work with custom enum classes easier.
This class is intended to be subclassed by custom enum classes. Example: class WorkDays(Enumeration)
Enum values in custom subclass should be defined as class variables, e.g.:
var1 = "Monday", var2 = 500, var3 =... |
561a5ed5f7cff3ea4a7f2fbbcc3aaab799548bb6 | Paiet/Tech-Journal-for-Everything | /python-for-security/TCPSniffer/Object-Oriented Python/extending/books.py | 2,706 | 3.765625 | 4 | # #
# # class Book:
# # def __init__(self, title, author):
# # self.title = title
# # self.author = author
# #
# # def __str__(self):
# # return '<Book: {} by {}>'.format(self.title, self.author)
# #
# # class TextBook(Book):
# # def __init__(self, title, author, edition):
# # ... |
43728b9faa264f4a971c1c6bb7f3d5df462fa3ed | Skylord0071/Stock-Screener-python | /Just.py | 1,198 | 3.765625 | 4 | import datetime as dt
import matplotlib.pyplot as plt
from matplotlib import style
import pandas as pd
import pandas_datareader.data as web
while True:
print("Hello World")
mm = input("Enter the company name : ")
print("Year,month,date format")
ya = int(input("start year : "))
ma = int(input("start... |
6040cb61d813b7b9396104a1eb2700464383147b | marcio-pg/Code-Abbey | /Problem 02 - Sum in loop.py | 873 | 3.828125 | 4 | # Problem #2 - Sum in Loop http://www.codeabbey.com/index/task_view/sum-in-loop
# Submission by MPadilla - 15/Jun/2015
suma=0 #Inicializa la variable suma.
N=int(input('How many numbers are you gonna sum?\n')) #Pregunta la primera linea de input, cuantos numeros se sumaran
num=input('Paste the numbers you\'re... |
5ba07b1de22df771d3d3ae2ada33a7f80fdf788f | marcio-pg/Code-Abbey | /Problem 43 - Dice Rolling.py | 567 | 4 | 4 | # Problem #43 - Dice Rolling http://www.codeabbey.com/index/task_view/dice-rolling
# Submission by MPadilla - 01/Aug/2015
from math import floor
print("In the first line, input the amount of dice rolls you will calculate. In the following ones, input the random numbers:")
entr=[float(input()) for x in range(int... |
c9a92a3801645eba6257bb50179596a408d73f7c | marcio-pg/Code-Abbey | /Problem 18 - Square Root.py | 932 | 3.984375 | 4 | # Problem #18 - Square Root http://www.codeabbey.com/index/task_view/square-root
# Submission by MPadilla - 25/Jun/2015
def heron(value):
global V, entr, i, R, d, T
for t in range(T): #Calcula la aproximacion segun el método de Heron, pero sin usar tolerancia
R=(R+d)/2
d=V/R
entr[i... |
7b8025e81eaadece75189eef57a518e560fa2e59 | marcio-pg/Code-Abbey | /Problem 52 - Pythagorean Theorem.py | 708 | 3.796875 | 4 | # Problem #52 - Pythagorean Theorem Dice http://www.codeabbey.com/index/task_view/pythagorean-theorem
# Submission by MPadilla - 08/Aug/2015
from math import sqrt
def pyth(a,b):
global c
c=int("{:.0f}".format(sqrt(a**2+b**2)))
return(c)
print("Input number of triangles in the first line and tri... |
37aa3ee478c914308aff64f69654286d37ae8c0d | marcio-pg/Code-Abbey | /Problem 08 - Arithmetic Progression.py | 1,379 | 3.703125 | 4 | # Problem #8 - Arithmetic Progression http://www.codeabbey.com/index/task_view/arithmetic-progression
# Submission by MPadilla - 21/Jun/2015
def arith(prog):#Función para calcular progresión arirmética
global i,entr
A=entr[i][0]
B=entr[i][1]
C=entr[i][2] #Selecciona de cada tripleta los parámet... |
3b582f75705736982841af1acc369baa26287f05 | ethomas1541/Treehouse-Python-Techdegree-Project-1 | /guessing_game.py | 2,919 | 4.15625 | 4 | """
Treehouse Python Techdegree
Project 1 - Number Guessing Game
Elijah Thomas
/2020
"""
"""
Tried to make my code a bit fancy. I have a bit of knowledge beyond what's been taught to me thus
far in the techdegree, and I plan to use it to streamline the program as much as I can.
"""
#Also, fair warning, I ... |
7e8e5cd20755bc9967dc6800b3614fdc9c8cc8d3 | Sheax045/SWDV660 | /Week1/week-1-review-Sheax045/temp_converter.py | 371 | 4.375 | 4 | # Please modify the following program to now convert from input Fahrenheit
# to Celsius
def doConversion():
tempInFAsString = input('Enter the temperature in Fahrenheit: ')
tempInF = float( tempInFAsString )
tempInC = ( tempInF - 32 ) / 1.8
print('The temperature in Celsius is', tempInC, 'degrees')
fo... |
f376bbaa60f9220807648aceefb3298411c39ae1 | a-k-r-a-k-r/color_theme_maker | /color.py | 9,457 | 3.59375 | 4 | '''
Program: Color Theme Maker
Author : akr
GitHub : https://github.com/a-k-r-a-k-r
Blog : https://a-k-r-a-k-r.blogspot.com
'''
#Color Theme Maker
import tkinter
from tkinter import BOTH, IntVar, DISABLED, filedialog
#Define window
root = tkinter.Tk()
root.title('Color Theme Maker')
root.iconbitma... |
3e8d8473c3ab5be30048eafdf16d7a04581e045d | sammy412/Project-Euler-Python- | /Problem 3- Largest Prime Factor.py | 412 | 3.6875 | 4 | import math
def primeFactors(n):
while n % 2 == 0:
primelist.append(2)
n = n / 2
for i in range(3,int(math.sqrt(n))+1,2):
while n % i== 0:
primelist.append(i)
n = n / i
if n > 2:
primelist.append(n)
t=int(input())
for _ in range(t):... |
bfedde77485709d9f372b5f6e92f0cbde80c2e9a | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/FindUnionListofTwoBST.py | 1,071 | 3.546875 | 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 getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:
listA = []
def v... |
03423218015102fa03c41678dd587bb24c56b038 | Swagat-Kumar/Competitive_Codes_Python | /Arrays/CheckPossiblity.py | 559 | 3.609375 | 4 | class Solution:
def checkPossibility(self, nums) -> bool:
def check(listA):
for i in range(len(listA)-1):
if listA[i+1] < listA[i]:
return False
return True
for i in range(len(nums)-1):
if nums[i+1] < nums[i]:
li... |
45442e0e975496bd4cdceb66ecb0bc27e4ea900c | Swagat-Kumar/Competitive_Codes_Python | /Arrays/SortDiagonally.py | 740 | 3.5 | 4 | class Solution:
def diagonalSort(self, mat):
listA = []
aux = []
def visit(x, y):
if x >= len(mat) or y >= len(mat[0]):
return
listA.append((x, y))
aux.append(mat[x][y])
visit(x+1, y+1)
for c in range(len(mat[0])):
... |
a6cef09b5136497d570e48dd085cb640fdd799f8 | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/BinarySearchTree.py | 851 | 4.03125 | 4 | class Node:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def insert(root, val):
if root == None:
return Node(val)
if root.val == val:
return root
elif val < root.val:
root.left = insert(root.left, v... |
dd5c8a906b4389c003afdf2e81b59467446b19ff | Swagat-Kumar/Competitive_Codes_Python | /APAS/PartitionList.py | 617 | 3.703125 | 4 | # Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def partition(self, head: ListNode, x: int) -> ListNode:
temp = head
low = ListNode()
l = low
high = ListNode()
h =... |
36af7634eba1cff56f26cfa67e800ba66f5c63fb | Swagat-Kumar/Competitive_Codes_Python | /BasicsOfStringManipulation/UpUp.py | 475 | 3.765625 | 4 | st = list(input())
ans = ''
word = ''
for s in st:
if s.isalpha() or s == '[':
word += s
else:
if len(word) != 0:
if len(word) != 1:
word = word[0].upper()+word[1:]
else:
word = word[0].upper()
ans += word
word = ''
... |
f2b4da2338a2c9aa1906ae8b0e36d6962f043ebe | Swagat-Kumar/Competitive_Codes_Python | /BasicsOfStringManipulation/PrintVertically.py | 479 | 3.59375 | 4 | class Solution:
def printVertically(self, s: str):
ans = []
words = s.split()
lenn = 0
for w in words:
if len(w) > lenn:
lenn = len(w)
for i in range(lenn):
temp = ''
for w in words:
if len(w) <= i:
... |
1fe1975f3f80821cafd9223087cff9712b5b4223 | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/2DTree.py | 1,562 | 3.953125 | 4 | class Node:
def __init__(self, x=0, y=0, left=None, right=None) -> None:
self.x = x
self.y = y
self.left = left
self.right = right
def insert(root, x, y, level=0):
if root == None:
return Node(x, y)
if level % 2 == 0:
if x < root.x:
root.left = i... |
33515cd7b800725bd0f8c8442dbd1d64928e70bf | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/BSTFromPreorderTravel.py | 612 | 3.796875 | 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 bstFromPreorder(self, preorder) -> TreeNode:
self.i = 0
def visit(low=0, high=10**9):
... |
8f5d2ff9bb785411d8ecba06b49306810380bf2f | Swagat-Kumar/Competitive_Codes_Python | /FloodFill/micro_maze.py | 804 | 3.515625 | 4 | def dfs(visited, matrix, x, y):
if x == n-1 and y == m-1:
return True
if x < 0 or x > m-1:
return False
if y < 0 or y > n-1:
return False
if matrix[x][y] == 1:
if visited[x][y]:
return False
visited[x][y] = True
if(dfs(visited, matrix, x-1, y))... |
be11ee92fbf9b6b295db6855f96651bc0724e0e7 | Swagat-Kumar/Competitive_Codes_Python | /BasicsOfStringManipulation/Capicua.py | 193 | 3.796875 | 4 | t = int(input())
ans = []
for i in range(t):
s = input()
reverse = s[::-1]
if(s == reverse):
ans.append("YES")
else:
ans.append("NO")
for a in ans:
print(a)
|
7eb1d69027915bc3e154b3e56d020c19d5bcb27d | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/ZigZagLevelTraversal.py | 839 | 3.6875 | 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 zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:
listA = []
def depth(node)... |
3f8f8c4001b82fc43133b4f1cd924da71e8463fe | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/LongestZigZagPathInBST.py | 802 | 3.765625 | 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 longestZigZag(self, root: TreeNode) -> int:
self.lp = 0
def solve(node, path=0, prev=... |
1e1e4ace795f10f96251deed7d5481fe6efa5197 | Swagat-Kumar/Competitive_Codes_Python | /Arrays/averageSalaryexcludingmaxxmin.py | 341 | 3.546875 | 4 | class Solution:
def average(self, salary: List[int]) -> float:
minn = 10**7
maxx = 10
Total = 0
for s in salary:
if s > maxx:
maxx = s
if s < minn:
minn = s
Total += s
Total = Total-minn-maxx
return T... |
f9ba29e611e0bcd4ed8d34051cd0117044d6ff8a | Swagat-Kumar/Competitive_Codes_Python | /APAS/DivideTwoIntegers.py | 708 | 3.5 | 4 | class Solution:
def divide(self, dividend: int, divisor: int) -> int:
if divisor == 0:
return 2**31-1
if dividend == 0:
return 0
if divisor == 1:
return dividend
if divisor == -1:
return 2**31-1 if dividend == -2**31 else -dividend
... |
acfde3bb315c81d8ff44c708b5f391a6b7f600b8 | Swagat-Kumar/Competitive_Codes_Python | /HashMap/KeyboardRow.py | 589 | 3.734375 | 4 | class Solution:
def findWords(self, words):
listA = []
aux = {0: 'QWERTYUIOP', 1: 'ASDFGHJKL', 2: 'ZXCVBNM'}
def contains(c, i):
return c in aux[i] or chr(ord(c)-32) in aux[i]
for w in words:
z = 0
add = True
i = 0
for i in... |
a49929d27b649cdc490ee4de8fa5c992f7fffc21 | Swagat-Kumar/Competitive_Codes_Python | /APAS/IsValidSoduku.py | 1,058 | 3.59375 | 4 | class Solution:
def isValidSudoku(self, board) -> bool:
for r in range(len(board)):
temp = []
for c in range(len(board[0])):
if board[r][c] == '.':
continue
if board[r][c] in temp:
return False
te... |
d598580591c8899c5c87ac51dc66b50ff076e2c1 | Swagat-Kumar/Competitive_Codes_Python | /BasicMaths/ComplimentOfNumber.py | 589 | 3.546875 | 4 | class Solution:
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
def toBinary(num):
aux = ''
while num != 0:
aux = str(num % 2)+aux
num = num//2
return aux
binary = toBinary(N)
aux = ''
... |
033af25a5c1aa64c9d3000688f180545b2fa2460 | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/UnivaluedBT.py | 528 | 3.828125 | 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 isUnivalTree(self, root: TreeNode) -> bool:
self.value = root.val
def visit(node):
... |
cad55d13a565520f3a85ab68ef828c70f6c210c7 | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/SmallestLexographicallyLeaf.py | 803 | 3.75 | 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 smallestFromLeaf(self, root: TreeNode) -> str:
self.ans = ''
def visit(node, st=''):
... |
051f4e0fc51f51533dff5a6ee8b344ac5db9bb87 | Swagat-Kumar/Competitive_Codes_Python | /APAS/SortColors.py | 513 | 3.546875 | 4 | class Solution:
def sortColors(self, nums) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
whiteEnd = 0
redEnd = 0
for i in range(len(nums)):
save = nums[i]
nums[i] = 2
if save == 0:
nums[white... |
72a11e836ac2185cf9acca399467fe89c3510f54 | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/pathSum.py | 708 | 3.6875 | 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 hasPathSum(self, root: TreeNode, sum: int) -> bool:
if root == None:
return False
... |
aaf2ce681d1e3e3411a22efc09f938101dba3c97 | Swagat-Kumar/Competitive_Codes_Python | /BinarySearchTree/AverageOfLevels.py | 834 | 3.609375 | 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 averageOfLevels(self, root: TreeNode) -> List[float]:
listA = []
nodes = [root]
... |
6a727e3407a1e95fbbeb3aa69a81f4d1d7080a07 | PowellET816/backup | /idk.py | 1,362 | 4.03125 | 4 | # Ethan Powell
# period 6
# variable Declaration and assignment
myVariable = "Ethan" # string variable]
myNumber = 12 # int variable
myDecimal = 12.6 # float variable
# make a variable of type string
myVariable = "hi"
# while loops
x = 1
while x <= 10:
print(x)
x += 1
# challenge: make a while ... |
995d7556b4753b233cdf9f735774c39ebb729fa5 | RoMalms10/AirBnB_clone_v2 | /web_flask/6-number_odd_or_even.py | 2,574 | 4.03125 | 4 | #!/usr/bin/python3
""" This module will import flask for a web application.
Web application needs to be waiting on 0.0.0.0 and port 5000.
- One route is / and will call a function that displays "Hello HBNB!".
- One route is /hbnb and will call a function that displays "HBNB".
- One route is /c/<text> an... |
f4a50e3fff071af11de6d0c1d70cca6db0d0fc6f | JavierEsteban/TodoPython | /Ejercicios/DesdeCero/10.- Modulos Paquetes Archivos/3.-Paquetes/paquete/herramientas.py | 150 | 3.53125 | 4 | from datetime import datetime
def fecha():
nombrefecha = datetime.now().strftime("%Y-%m-%d")
print("La fecha es {}".format(nombrefecha))
|
d07e8872a37eaf9eee70600595eb94d4dd6d7e9d | JavierEsteban/TodoPython | /Ejercicios/DesdeCero/1.- Variables y Tipos de Datos/1.- Numeros.py | 257 | 3.703125 | 4 | def main():
##Declaración de valores númericos
a = 20 #Números enteros
b = 2.2 #Números Flotantes
print("El número {} es {}".format(a, type(a)))
print("El número {} es {}".format(b, type(b)))
if __name__=="__main__":
main()
|
66ed0026c9f5b50f5b41e7e65547bb054fa3b55c | JavierEsteban/TodoPython | /Ejercicios/OperadoresBasicos/Python -Ojala/Clase 3.py | 1,268 | 3.984375 | 4 | # Manejo de archivos con python
from datetime import date
def Escritura_Archivo(valor = "Defecto",NumeroRepeticiones = 2):
nombreArchivo = "Archivo" + str(date.today()).replace("-","") +".Txt"
archivo = open(nombreArchivo,"w+")
for i in range(0,NumeroRepeticiones):
archivo.write("El valor ingresad... |
72e99be26206ee4fefa8154ca8ee53403f01ae6d | JavierEsteban/TodoPython | /Ejercicios/DesdeCero/1.- Variables y Tipos de Datos/3.- Ejercicios.py | 1,580 | 4.28125 | 4 | ## Hallar el promedio de notas con los pesos enviados
def main():
nota_1 = 10
nota_2 = 7
nota_3 = 4
notafinal = 10*0.15 + 7*0.35 + 4*0.5
print(notafinal)
# Completa el ejercicio aquí
if __name__ =='__main__':
main()
#Ejercicio que cada ultimo registro de la matriz sume los 3 primeros.
def ... |
9e62ba08fa01e6a2d0e3c9aecf93e43c0600992e | hemiaoio/learn-python | /lesson-01/currency_converter_v4.0.py | 573 | 4.25 | 4 |
def convert_currency(in_money,exchange_rate):
out_money = in_money * exchange_rate
return out_money
USD_VS_RMB = 6.77
currency_str_value = input("请输入带单位的货币:")
# 获取货币单位
unit = currency_str_value[-3:]
if unit == 'CNY':
exchange_rate = 1/USD_VS_RMB
elif unit == 'USD':
exchange_rate = USD_VS_RMB
else:... |
46792872a04fbac8ee6ff8469dc0e4d1c147fb4f | hemiaoio/learn-python | /lesson-09/aqi_v3.0.py | 959 | 3.765625 | 4 | """
日期:2018/09/06
功能:AQI计算
版本:3.0
CSV 库操作
# 先从 filestream 取得 writer
writer = csv.writer(f)
# 按行写数据
writer.writerow(rowdata)
# 读数据
data_list = writer.reader()
"""
import csv
import json
def process_json_file(filepath):
"""
解码json文件
"""
f = open(filepath... |
50ce226f3741c7a1a8b5a6b327fc179f007704ee | hemiaoio/learn-python | /lesson-04/bmr_v1.0.py | 607 | 3.859375 | 4 | """
功能:BMR计算器
版本:v1.0
日期:2018/8/20
"""
def main():
# 性别
gender = '男'
# 体重(kg)
weight = 70
# 身高(cm)
height = 175
# 年龄
age = 25
if (gender == '男'):
# 男性
bmr = 13.7 * weight + 5.0 * height - 6.8 * age + 66
elif (gender == '女'):
# 女性
... |
7f5a62963e620a00f8e30baf529d82007c1d9076 | hemiaoio/learn-python | /lesson-01/currency_converter_v2.0.py | 522 | 4.1875 | 4 | USD_VS_RMB = 6.77
currency_str_value = input("请输入带单位的货币:")
# 获取货币单位
unit = currency_str_value[-3:]
if unit == 'CNY':
rmb_str_value = currency_str_value[:-3]
rmb_value = eval(rmb_str_value)
usd_value = rmb_value / USD_VS_RMB
print('CNY to USD :', usd_value)
elif unit == 'USD':
usd_str_value = curr... |
5c63852000078a365438713b93bf076a3ada8f43 | SEJUNHONG/Multicampus | /Python0803_1.py | 367 | 3.671875 | 4 | gravity=[7, 4, 2, 0, 0, 6, 0, 7, 0]
height=[0, 0, 0, 0, 0, 0, 0, 0, 0]
max_height=0
for i in reversed(range (9)):
h=0
for j in reversed(range(i, 9)):
if gravity[i]>gravity[j]:
h+=1
else:
j=8
height[i]=h
for i in range(9):
if height[i]>max_height:
... |
be1be3d9712e8f4036c2c57d9e4960cde2674bf8 | MarcusBlaisdell/ParallelProgramming | /Programming_Assignments/Programming Assignment 2/parser.py | 599 | 3.71875 | 4 | ###
getList = open("thelist.txt", "r")
line = getList.readline()
line = line[:-1]
myMax = 0
while line:
readFile = open(line, "r")
line2 = readFile.readline()
#line2 = line2[:1]
while line2:
line3 = line2.split()
#print ("line3[1]: ", line3[1], " - myMax: ", myMax)
if int(line3[1]) > myMax:
... |
0745de33ce263d7af2d1dc7fa490e5f1330625be | littlenightingale3/gittest | /robot/Kulka.py | 1,118 | 3.5625 | 4 | #! /usr/bin/env python
# -*- coding: utf-8 -*-
import rg
class Robot:
def act(self, game): #dzialania robota
#ilu_wrogow = 0
lista_wrogow = []
# jeżeli obok są przeciwnicy, atakuj
# wersja z pętlą przeglądającą wszystkie pola zajęte przez roboty
for poz, robot in game.rob... |
f1c33d5a000f7f70691e10da2bad54de62fc9a8d | sugia/leetcode | /Integer Break.py | 648 | 4.125 | 4 | '''
Given a positive integer n, break it into the sum of at least two positive integers and maximize the product of those integers. Return the maximum product you can get.
Example 1:
Input: 2
Output: 1
Explanation: 2 = 1 + 1, 1 × 1 = 1.
Example 2:
Input: 10
Output: 36
Explanation: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36.
Not... |
55493da433cbde632e697a1ab4f9466320ee66b5 | sugia/leetcode | /Rearrange String k Distance Apart.py | 1,846 | 3.84375 | 4 | '''
Given a non-empty string s and an integer k, rearrange the string such that the same characters are at least distance k from each other.
All input strings are given in lowercase letters. If it is not possible to rearrange the string, return an empty string "".
Example 1:
Input: s = "aabbcc", k = 3
Output: "abcab... |
dd2e7ccdbc664f32515b0a730e0ced3822d23c83 | sugia/leetcode | /Minimum Genetic Mutation.py | 3,381 | 4.3125 | 4 | '''
A gene string can be represented by an 8-character long string, with choices from "A", "C", "G", "T".
Suppose we need to investigate about a mutation (mutation from "start" to "end"), where ONE mutation is defined as ONE single character changed in the gene string.
For example, "AACCGGTT" -> "AACCGGTA" is 1 mutat... |
3bd738055fa2eda583deaa1ff2e7980d15ac5dc0 | sugia/leetcode | /Shortest Word Distance.py | 1,257 | 4.0625 | 4 | '''
Given a list of words and two words word1 and word2, return the shortest distance between these two words in the list.
Example:
Assume that words = ["practice", "makes", "perfect", "coding", "makes"].
Input: word1 = “coding”, word2 = “practice”
Output: 3
Input: word1 = "makes", word2 = "coding"
Output: 1
Note:
Yo... |
fd2da8ba26c83bc02b1bc370c68d8c04df46079d | sugia/leetcode | /Combination Sum IV.py | 1,246 | 4.09375 | 4 | '''
Given an integer array with all positive numbers and no duplicates, find the number of possible combinations that add up to a positive integer target.
Example:
nums = [1, 2, 3]
target = 4
The possible combination ways are:
(1, 1, 1, 1)
(1, 1, 2)
(1, 2, 1)
(1, 3)
(2, 1, 1)
(2, 2)
(3, 1)
Note that different sequ... |
a3fc906021f03ed53ad43fbc133d253f74e56daa | sugia/leetcode | /Valid Palindrome.py | 697 | 4.15625 | 4 | '''
Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.
Note: For the purpose of this problem, we define empty string as valid palindrome.
Example 1:
Input: "A man, a plan, a canal: Panama"
Output: true
Example 2:
Input: "race a car"
Output: false
'''
class... |
175cecc66411afc5a07d6c8faad0bd086897a88d | sugia/leetcode | /valid-parentheses.py | 602 | 3.953125 | 4 | class Solution:
#given a string
#return a bool
def isValid(self, s):
stack = []
for x in s:
if x in '([{':
stack.append(x)
else:
if len(stack) == 0:
return False
if stack[-1] == '(' and x == ')':
... |
bef2db4fef1a748c4a33dd387b6af401f393c64c | sugia/leetcode | /Image Smoother.py | 1,504 | 3.796875 | 4 | '''
Given a 2D integer matrix M representing the gray scale of an image, you need to design a smoother to make the gray scale of each cell becomes the average gray scale (rounding down) of all the 8 surrounding cells and itself. If a cell has less than 8 surrounding cells, then use as many as you can.
Example 1:
Input... |
57ed599703fa2c68a24e0b77f32968344a3c2b34 | sugia/leetcode | /Largest Plus Sign.py | 3,075 | 4.03125 | 4 | '''
In a 2D grid from (0, 0) to (N-1, N-1), every cell contains a 1, except those cells in the given list mines which are 0. What is the largest axis-aligned plus sign of 1s contained in the grid? Return the order of the plus sign. If there is none, return 0.
An "axis-aligned plus sign of 1s of order k" has some cent... |
6051a070da52615d8bbcae7c659ac8e320049305 | sugia/leetcode | /merge-k-sorted-lists.py | 579 | 3.75 | 4 | '''
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
'''
class Solution:
#given a list of list node
#return a list node
def mergeKLists(self, lists):
heap = []
for x in lists:
if x:
heapq.heappush(heap, [x.val, x])
d... |
396253f9798266c4b6b291f272aa7b79c6fa0a0a | sugia/leetcode | /Power of Two.py | 498 | 4.125 | 4 | '''
Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Example 2:
Input: 16
Output: true
Example 3:
Input: 218
Output: false
'''
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
... |
8415d6adbfcbb8590890d930704d1ab3096a0034 | sugia/leetcode | /Contiguous Array.py | 939 | 4.0625 | 4 | '''
Given a binary array, find the maximum length of a contiguous subarray with equal number of 0 and 1.
Example 1:
Input: [0,1]
Output: 2
Explanation: [0, 1] is the longest contiguous subarray with equal number of 0 and 1.
Example 2:
Input: [0,1,0]
Output: 2
Explanation: [0, 1] (or [1, 0]) is a longest contiguous ... |
f3b56fe9724ad96e32ebf718e0b9d03f8599325b | sugia/leetcode | /Android Unlock Patterns.py | 2,089 | 3.765625 | 4 | '''
Given an Android 3x3 key lock screen and two integers m and n, where 1 ≤ m ≤ n ≤ 9, count the total number of unlock patterns of the Android lock screen, which consist of minimum of m keys and maximum n keys.
Rules for a valid pattern:
Each pattern must connect at least m keys and at most n keys.
All the keys mus... |
054f74da31326efd84c334bce81fba8c8993b847 | sugia/leetcode | /Reverse Bits.py | 741 | 4.0625 | 4 | '''
Reverse bits of a given 32 bits unsigned integer.
Example:
Input: 43261596
Output: 964176192
Explanation: 43261596 represented in binary as 00000010100101000001111010011100,
return 964176192 represented in binary as 00111001011110000010100101000000.
Follow up:
If this function is called many times,... |
c89f865232fac2a3ba999a48de9f48c0430a0dae | sugia/leetcode | /Best Time to Buy and Sell Stock with Cooldown.py | 1,412 | 3.859375 | 4 | '''
Say you have an array for which the ith element is the price of a given stock on day i.
Design an algorithm to find the maximum profit. You may complete as many transactions as you like (ie, buy one and sell one share of the stock multiple times) with the following restrictions:
You may not engage in multiple... |
4ea6e28f72e677046c82e365a70e6abae94cb828 | sugia/leetcode | /Remove Invalid Parentheses.py | 1,412 | 4 | 4 | '''
Remove the minimum number of invalid parentheses in order to make the input string valid. Return all possible results.
Note: The input string may contain letters other than the parentheses ( and ).
Example 1:
Input: "()())()"
Output: ["()()()", "(())()"]
Example 2:
Input: "(a)())()"
Output: ["(a)()()", "(a())(... |
77207dc2ba26332d9ff071fffc232398beb1e454 | sugia/leetcode | /Valid Square.py | 1,180 | 3.71875 | 4 | '''
Given the coordinates of four points in 2D space, return whether the four points could construct a square.
The coordinate (x,y) of a point is represented by an integer array with two integers.
Example:
Input: p1 = [0,0], p2 = [1,1], p3 = [1,0], p4 = [0,1]
Output: True
Note:
All the input integers are in the rang... |
1c59ace51e212ef319a09a5703d88b878ca494e8 | sugia/leetcode | /Group Shifted Strings.py | 1,102 | 4.15625 | 4 | '''
Given a string, we can "shift" each of its letter to its successive letter, for example: "abc" -> "bcd". We can keep "shifting" which forms the sequence:
"abc" -> "bcd" -> ... -> "xyz"
Given a list of strings which contains only lowercase alphabets, group all strings that belong to the same shifting sequence.
Exa... |
234b271b7b3aa9a7bd7e91a8334568c7d61c9e16 | sugia/leetcode | /Department Top Three Salaries.py | 1,519 | 3.515625 | 4 | '''
The Employee table holds all employees. Every employee has an Id, and there is also a column for the department Id.
+----+-------+--------+--------------+
| Id | Name | Salary | DepartmentId |
+----+-------+--------+--------------+
| 1 | Joe | 70000 | 1 |
| 2 | Henry | 80000 | 2 |
| 3 ... |
cd46ca9292716451523c2fb59813627274928af3 | sugia/leetcode | /Strobogrammatic Number II.py | 1,197 | 4.15625 | 4 | '''
A strobogrammatic number is a number that looks the same when rotated 180 degrees (looked at upside down).
Find all strobogrammatic numbers that are of length = n.
Example:
Input: n = 2
Output: ["11","69","88","96"]
'''
class Solution(object):
def findStrobogrammatic(self, n):
"""
:type n... |
ad637c71cab2b115660b7fc86fc45ca380fd0a1c | sugia/leetcode | /Median of Two Sorted Arrays.py | 1,406 | 4 | 4 | '''
There are two sorted arrays nums1 and nums2 of size m and n respectively.
Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).
You may assume nums1 and nums2 cannot be both empty.
Example 1:
nums1 = [1, 3]
nums2 = [2]
The median is 2.0
Example 2:
nums1 = [1, 2]... |
0b8cecee54fb63680c6a855f95ee2bbb130ed87b | sugia/leetcode | /Coin Change.py | 1,590 | 3.9375 | 4 | '''
You are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.
Example 1:
Input: coins = [1, 2, 5], amount = 11
Out... |
a313738667701cf179a8dc73e9a915b2eb8982db | sugia/leetcode | /Keyboard Row.py | 951 | 4.09375 | 4 | '''
Given a List of words, return the words that can be typed using letters of alphabet on only one row's of American keyboard like the image below.
American keyboard
Example 1:
Input: ["Hello", "Alaska", "Dad", "Peace"]
Output: ["Alaska", "Dad"]
'''
class Solution(object):
def findWords(self, words):
... |
3cd4fa22e6eae89b71d54a079f08d2a77016437f | sugia/leetcode | /Sort List.py | 1,347 | 4 | 4 | '''
Sort a linked list in O(n log n) time using constant space complexity.
Example 1:
Input: 4->2->1->3
Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0
Output: -1->0->3->4->5
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.nex... |
3390c91dcae4cbceb3e827edbf332857aba2fa4c | sugia/leetcode | /Ugly Number II.py | 891 | 4 | 4 | '''
Write a program to find the n-th ugly number.
Ugly numbers are positive numbers whose prime factors only include 2, 3, 5.
Example:
Input: n = 10
Output: 12
Explanation: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12 is the sequence of the first 10 ugly numbers.
Note:
1 is typically treated as an ugly number.
n does not exce... |
b3e2af17f2f7e8950c12e21835eb3d10dd016aeb | sugia/leetcode | /Longest Substring with At Most K Distinct Characters.py | 994 | 3.671875 | 4 | '''
Given a string, find the length of the longest substring T that contains at most k distinct characters.
Example 1:
Input: s = "eceba", k = 2
Output: 3
Explanation: T is "ece" which its length is 3.
Example 2:
Input: s = "aa", k = 1
Output: 2
Explanation: T is "aa" which its length is 2.
'''
class Solution(ob... |
2b71360af858b4bef0d6656885147b18a55a4d12 | sugia/leetcode | /Largest Divisible Subset.py | 845 | 3.875 | 4 | '''
Given a set of distinct positive integers, find the largest subset such that every pair (Si, Sj) of elements in this subset satisfies:
Si % Sj = 0 or Sj % Si = 0.
If there are multiple solutions, return any subset is fine.
Example 1:
Input: [1,2,3]
Output: [1,2] (of course, [1,3] will also be ok)
Example 2:
In... |
e0e326f07a8f166d9e424ddd646e563b5e817da9 | sugia/leetcode | /Solve the Equation.py | 2,867 | 4.3125 | 4 | '''
Solve a given equation and return the value of x in the form of string "x=#value". The equation contains only '+', '-' operation, the variable x and its coefficient.
If there is no solution for the equation, return "No solution".
If there are infinite solutions for the equation, return "Infinite solutions".
If t... |
8c3ae2289cd214e6288ede5de4a2e296f5d3983b | sugia/leetcode | /Largest Triangle Area.py | 1,047 | 4.15625 | 4 | '''
You have a list of points in the plane. Return the area of the largest triangle that can be formed by any 3 of the points.
Example:
Input: points = [[0,0],[0,1],[1,0],[0,2],[2,0]]
Output: 2
Explanation:
The five points are show in the figure below. The red triangle is the largest.
Notes:
3 <= points.length <=... |
92be21be36099dfcbac1b41e9e893dbef8f32643 | sugia/leetcode | /Clone Graph.py | 1,786 | 3.9375 | 4 | '''
Clone an undirected graph. Each node in the graph contains a label and a list of its neighbors.
OJ's undirected graph serialization:
Nodes are labeled uniquely.
We use # as a separator for each node, and , as a separator for node label and each neighbor of the node.
As an example, consider the serialized graph ... |
9d3e0787365be7c3f794b6bdaa4c20c8aa902d59 | sugia/leetcode | /Walls and Gates.py | 1,583 | 3.984375 | 4 | '''
You are given a m x n 2D grid initialized with these three possible values.
-1 - A wall or an obstacle.
0 - A gate.
INF - Infinity means an empty room. We use the value 231 - 1 = 2147483647 to represent INF as you may assume that the distance to a gate is less than 2147483647.
Fill each empty room wit... |
e98a262e88b26b329f9baa13ee4e785b82af8faa | sugia/leetcode | /Inorder Successor in BST.py | 938 | 3.921875 | 4 | '''
Given a binary search tree and a node in it, find the in-order successor of that node in the BST.
Note: If the given node has no in-order successor in the tree, return null.
Example 1:
Input: root = [2,1,3], p = 1
2
/ \
1 3
Output: 2
Example 2:
Input: root = [5,3,6,2,4,null,null,1], p = 6
5
... |
60e19d0f67fae2558a45d75d71100048d3221454 | sugia/leetcode | /Word Search II.py | 1,374 | 3.9375 | 4 | '''
Given a 2D board and a list of words from the dictionary, find all words in the board.
Each word must be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.
Example:
Input: ... |
648bbe2a485946f33f6bb61c1a069583addc8d80 | sugia/leetcode | /search-in-rotated-sorted-array.py | 698 | 3.6875 | 4 | class Solution:
#given a list of integers and an integer
#return an integer
def search(self, A, target):
left = 0
right = len(A) - 1
while left + 1 < right:
mid = (left + right) >> 1
if A[left] <= A[mid]:
if A[left] <= target <= A[mid]:
... |
bd503bda1274a4325ece9b50c408ee72bd1964d5 | sugia/leetcode | /4sum.py | 1,342 | 3.765625 | 4 | '''
Given an array nums of n integers and an integer target, are there elements a, b, c, and d in nums such that a + b + c + d = target? Find all unique quadruplets in the array which gives the sum of target.
Note:
The solution set must not contain duplicate quadruplets.
Example:
Given array nums = [1, 0, -1, 0, -2... |
78a20c5cd096d37af8f12326f23fafde84b72ca6 | sugia/leetcode | /Friend Circles.py | 2,086 | 4.03125 | 4 | '''
There are N students in a class. Some of them are friends, while some are not. Their friendship is transitive in nature. For example, if A is a direct friend of B, and B is a direct friend of C, then A is an indirect friend of C. And we defined a friend circle is a group of students who are direct or indirect frien... |
1c2c88084958236536e7a184d30f436a3abffed7 | zy041225/python_bin | /tabTools/calculate_tab.py | 1,617 | 3.5 | 4 | #!/usr/bin/python3
def parameter_parser(argv):
para_lst = []
tmp = argv.split(',')
for i in tmp:
if '-' in i:
bg, ed = i.split('-')[:]
bg = int(bg)-1
ed = int(ed)
for j in range(bg, ed):
para_lst.append(j)
else:
i = int(i)-1
para_lst.append(int(i))
return sorted(para_lst)
def calculate(... |
e0e34e7381733942fc5b722c0fcd099061f168e6 | nurfaizherlambang/cs50problemsets | /Python, SQL, HTML, CSS, Flask, Javascript/pset7/problems-2020-x-houses/import.py | 861 | 3.859375 | 4 | from cs50 import SQL
import csv
import sys
db = SQL("sqlite:///students.db")
if len(sys.argv) < 2:
print("Usage: python import.py characters.csv")
sys.exit()
with open(sys.argv[1], 'r') as csvfile:
reader = csv.reader(csvfile, delimiter=',')
for row in reader:
if len(row[0].split()) < 2:
... |
ff568d32a99ee45eb6a7b8535a49e9e49047d1a7 | Behnam1111/The-Hirst-Painting | /Turtle_race/Warming_up.py | 401 | 3.84375 | 4 | from turtle import Turtle, Screen
import random
timmy = Turtle()
timmy.shape("turtle")
colours = ["red", "green", "yellow", "blue", "black", "purple", "orange", "gray"]
timmy.pensize(10)
timmy.speed(9)
for i in range(0, 3000):
angle = random.choice([0, 90, 180, 270])
timmy.pencolor(random.choice(colours))
... |
366c58e4274034a7e704f39343a2a8b84d04f5d8 | GuidoRavasi/mastercobra | /hangman.py | 2,540 | 3.890625 | 4 |
# -*- coding: utf-8 -*-
__project__ = 'mastercobra'
__author__ = 'Alfio Ferrara'
__email__ = 'alfio.ferrara@unimi.it'
__institution__ = 'Università degli Studi di Milano'
__date__ = '20 nov 2020'
__comment__ = '''
Implementing the hangman game
'''
from typing import List, Dict
import numpy as np
class Hangma... |
20f76d1b1cc24c1b625e6369f046bb6b8a0a110e | gerty/advent-of-code-2016 | /Day 10 - Balance Bots/AoC_Day10.py | 4,275 | 3.890625 | 4 | # Code written by @gerty
# Input from Day 10, Problem 1 (and 2) of Advent of Code 2016
# Input files in same directory
# My input: in file D10input.txt
class Bot:
"""Common robot with high/low destination tracking"""
def __init__(self):
self.chiplow = 0 # these slots hold the number of the chi... |
55926ff3a2bebfaad166335cff41c9edc9aba9a6 | joseph-palermo/ICS3U-Assignment-02B-Python | /assignment_two.py | 527 | 4.34375 | 4 | #!/usr/bin/env python3
# Created by: Joseph Palermo
# Created on: October 2019
# This program calculates the area of a sector of a circle
import math
def main():
# This function calculates the area of a sector of a circle
# input
radius = int(input("Enter the radius: "))
angle_θ = int(input("Enter ... |
3e4e9060ebb9113631139e5468d89a3f8d49eab1 | kolacx/ITEA | /lesson6/main2.py | 492 | 3.59375 | 4 | import random
class Randomizer:
def __init__(self, steps):
self._steps = steps
self._current_step = 0
self._value = 0
def __iter__(self):
return self
def __next__(self):
if self._current_step <= self._steps:
self._value += random.random()
... |
9a3a711d7447a991a720fe82d25f6a0e28d86381 | kolacx/ITEA | /lesson4/home/task2.py | 2,430 | 3.59375 | 4 | class Registrations():
_users = {}
def validation_password(password):
if not any(char.isdigit() for char in password):
return True
def if_login_exist(login):
if login in Registrations.get_all_users():
return True
def get_all_users():
return R... |
db345389c5d67ef0adb1601887a97a67c5f989df | kolacx/ITEA | /lesson6/struct/my_list.py | 1,407 | 3.609375 | 4 | class MyList:
def __init__(self, *args):
self._my_list = [*args]
self._steps = len(args)
self._current_step = 0
def clear(self):
self._my_list = []
return self._my_list
def pop(self):
last_item = self._my_list[-1]
del self._my_list[-1]
retur... |
3a59cec44e38cb384e93ce3511752d43f2318997 | top-on/covid-plz | /covid_plz/main.py | 1,210 | 3.5625 | 4 | """CLI for requesting COVID-19 incidence number for given German ZIP code."""
import re
import requests
import typer
from bs4 import BeautifulSoup
PATTERN = r"pro 100.000 Einwohner in den letzten 7 Tagen</td>\n<td>([\d.]+)[\d,]*</td>"
app = typer.Typer(
help="CLI for requesting COVID-19 incidence number for giv... |
288c4e4c45bc565928d4bd755a15b14567e886ad | HenriBranken/ML_Raschka | /henris_coding/chapter_08_latest/b_words_to_feature_vectors.py | 482 | 3.5 | 4 | import numpy as np
from sklearn.feature_extraction.text import CountVectorizer
count = CountVectorizer()
docs = np.array([
"The sun is shining",
"The weather is sweet",
"The sun is shining, the weather is sweet, and one and one is two"
])
bag = count.fit_transform(docs)
# Print the contents of the vocabu... |
dd1b84054afb9c381a66c3e02919d88ac3081a55 | HenriBranken/ML_Raschka | /henris_coding/chapter_04/n_select_from_model.py | 1,612 | 3.546875 | 4 | from sklearn.feature_selection import SelectFromModel
import pandas as pd
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
df_wine = pd.read_csv("./wine_data.txt", header=None)
df_wine.columns = ["class_label", "alcohol", "malic_acid", "ash",... |
32ee95b31d484312ce6cae63b0986e3bc09f9209 | pythongus/metabob | /test/test_string_format.py | 369 | 3.984375 | 4 | def print_formatted(number):
spaces = len(bin(number)) - 2
format_string = (f'{{:>{spaces}}} {{:>{spaces}}} '
f'{{:>{spaces}}} {{:>{spaces}}}')
for n in range(1, number + 1):
print(format_string.format(str(n), oct(n)[2:], hex(n)[2:].upper(), bin(n)[2:]))
if __name__ == '__main... |
db3ee8a9d1701384f5decaef8ff3f904bf8b7c2a | pythongus/metabob | /hackerrank/binary_tree.py | 795 | 3.765625 | 4 | """
Binary Tree Module
"""
from hackerrank.node import Node
class Tree:
def __init__(self, root: Node):
self.root = root
self.height = 2 if any([root.left, root.right]) else 1
@property
def height(self) -> int:
return self._height
@height.setter
def height(self, height: ... |
3fc7882bdd9f13e847b1dc377091ae5224ea6da2 | SiaH319/420-LCU-05 | /classCalculator-v2.0.py | 6,162 | 3.796875 | 4 | #Sia Ham (1730812)
#420-LCU Computer Programming , Section 3
#S. Hilal , instructor
#Assignment 3
class Student:
'Base class for all students'
Count = 0
CountA =0
CountB =0
CountC =0
CountF =0
def __init__(self,p_name, p_id, p_t1, p_t2, p_a1, p_a2, p_a3, p_a4):
'''Constructor... |
e8b51b79913227ce3b5ac4d4db9a4d1212644b1e | vincentpanqi/PythonLearning | /BasicAdvance/function6.py | 708 | 3.84375 | 4 | #!/usr/local/python
# coding=utf-8
# Created by Ferris on 2016/11/14
# 多类型传值
# 冗余参数
def fun(x, y):
print x + y
t = (1, 2)
fun(*t)
# 多类型传值传一个元组进入函数需要在元组前加*
def fun1(x, y, z):
print x + y + z
t1 = (2, 3, 4)
fun1(*t1)
fun1(*(1, 2, 3))
fun1(1,*t)
# *t只能放在命名参数后边不能放在命名参数前边
dic = {'x':1, 'y':3, 'z':5}
# dic = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.