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 |
|---|---|---|---|---|---|---|
1020f3178cff29d565b3a44cc25b5aaa8fbd2edf | nitinkatyal1314/leetcode | /easy/14-longest_common_prefix.py | 800 | 3.71875 | 4 | class Solution:
def longestCommonPrefix(self, strs: List[str]) -> str:
sorted_items = sorted(strs, key=lambda s: len(s))
smallest_string = sorted_items[0]
# print(" Smallest : ",smallest_string )
for word in sorted_items[1:]:
# print("Comparing with ", word)
... |
9092164375af956b261eac82f220bc8508ac111e | hawkinsbl/05b-Exam1Practice | /src/problem0.py | 14,737 | 4.40625 | 4 | """
PRACTICE Exam 1, problem 0.
These problems illustrate concepts that previous problems have not emphasized:
-- determining whether a number is odd or even (Problem 0a)
-- returning True or False (Problem 0a)
-- is_prime (Problem 0b)
-- animation (Problem 0c)
Authors: David Mutchler, Vibha Alangar, Matt Bou... |
4230a836e2711181e084ffeff04f550fee85136e | throttlebot/hotrod-customer | /customer_unit_test.py | 446 | 3.5625 | 4 | import requests
"""
Checks that the server returns a valid response
"""
def test(host, port):
response = requests.get("http://" + host + ":" + str(port) + "/customer?customer=392")
assert response.status_code == 200, "Status code was {} instead of 200".format(response.status_code)
result = response.json()
assert r... |
e31a1a989c0866c8358b23e13ba4044bc00b390f | micdoug/mgb | /mgb/local_detection/neighbor.py | 2,150 | 3.84375 | 4 | """
Define the neighbor class.
Authors:
Michael D. Silva <micdoug.silva@gmail.com>
Created: Jan 2018
Modified: Jun 2018
"""
class Neighbor(object):
"""Encapsulate a neighbor tracked by a mobile device."""
# Class attributes
INACTIVE_THRESHOLD = 5
FRIEND_THRESHOLD = 10
def __init__(self, uid... |
19a5b67b06287045eee502d3f1d6aaab7d47eed5 | paweldrzal/python_codecademy | /two_list_join.py | 133 | 3.75 | 4 | #joining 2 lists
m = [1, 2, 3]
n = [4, 5, 6]
def join_lists(x,y):
return x+y
print join_lists(m, n)
#output [1, 2, 3, 4, 5, 6]
|
ed618371b3ca9cde94b3a6ca094cf8351ffa54f3 | himansh-23/PythonPractice | /util/utils.py | 3,105 | 3.703125 | 4 | import random
import time
def stringModify(str):
model = "Hello <<UserName>>, How are you?"
model = model.replace("<<UserName>>", str, 1)
return model
def headtail(count):
head = 0
tails = 0
for x in range(count):
number = random.randint(0, 1)
if number == 0:
head... |
859e72d791480403776ece43878f783083c49fde | eeezi/BaekJoon | /2292.py | 99 | 3.65625 | 4 | n = int(input())
num , room = 1, 1
while (n > num):
num += 6 * room
room += 1
print(room) |
00102f216a965140d2707bb7c3f01f95930fa08b | IceDerce/learn-python | /learning/function_varargs.py | 866 | 4.09375 | 4 | def total(a=5, *numbers, **phonebook):
"""
它是如何工作的。
当我们声明一个诸如 *param 的星号参数时,从此处开始直到结束的所有位置参数
(Positional Arguments)都将被收集并汇集成一个称为“param”的元组(Tuple)。
类似地,当我们声明一个诸如 **phonebook 的双星号参数时,从此处开始直至结束的所有关键字
参数都将被收集并汇集成一个名为 phonebook 的字典(Dictionary)。
"""
print('a', a)
# 遍历元组中的所有项目
for single_... |
1913b9339f91c30a8f77624a3a6b2b273002af91 | IceDerce/learn-python | /learning/str_format.py | 283 | 3.8125 | 4 | age = 20
name = 'litao'
print('{} is playing his balls when he is {} years old'.format(name, age))
print('Why {} is so stupid?'.format(name))
print('{0:0.7}'.format(1/3))
print('{0:_^20}'.format('fku'))
print('Why {name} is very {property}'.format(name='litao', property='stupid')) |
14389832de4c1e1317bd88f01b2686a83eb36017 | KeelyC0d3s/L3arning | /squareroot.py | 1,126 | 4.375 | 4 | # Keely's homework again.
# Please enter a positive number: 14.5
# The square root of 14.5 is approx. 3.8.
# Now, time to figure out how to get the square root of 14.5
#import math
#math.sqrt(14.5)
#print( "math.sqrt(14.5)", math.sqrt(14.5))
#Trying Newton Method.
#Found code here: https://tinyurl.com/v9ob6nm
# Fu... |
dad8ce6b3d20dff1ffcaef7146ecfbd88c3b54b0 | adarshk007/DATA-STURCTURES-and-ALGORITHMS | /DATA STRUCTURE/QUEUE/queue_all.py | 886 | 4.15625 | 4 | # QUEUE
#SUB TOPICS :
"""
1}Enqueue
2}Dequeue
3}Print: rear element
front element
"""
# ADARSH KUMAR
#__________________________________CODE________________________________________#
class queue:
def __init__(self):
self.new_queue=[]
self.size=0
self.f... |
0c6dacc0fddb1bf2d03a934a94a5c119311e9c9e | leesei/presentation-unicode-101 | /unicode.py | 341 | 3.65625 | 4 | #!/usr/bin/env python3
def encode(s, encoding):
coded = s.encode(encoding)
print('=>', encoding )
print(type(coded), coded.hex())
print()
s = '你好世界!'
print(type(s), s)
print([hex(ord(c)) for c in s])
print()
encode(s, 'utf-8')
encode(s, 'utf-16')
encode(s, 'utf-16le')
encode(s, 'utf-16be')
encode(s,... |
3ef7ec0a01587a13635a634271a160f67def4963 | himanshuhx/Python_Graphs | /venv/depthFirstTraversal.py | 765 | 3.6875 | 4 | from collections import defaultdict
class Graph:
def __init__(self):
self.graph=defaultdict(list)
def addEdge(self,u,v):
self.graph[u].append(v)
def DFSUtils(self,ele,visited):
visited[ele] = True
print(ele,end=' ')
for node in self.graph[ele]:
if not vis... |
d8198b9a360f1b63d5c7f32fe23d19d0b28ce879 | s1881079/weather-info-plotting | /task1_plenty.py | 2,057 | 3.546875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Tue Oct 9 15:44:05 2018
This is a program for reading file plenty.data as float
and do some data mapping
@author: Ananomous
"""
from matplotlib import pyplot
import os
def readPlenty(file_dir):
'''read plenty.data and convert to float'''
data =... |
84350a74b82b58bc2d77a4b319f53ef70d7ea472 | tuxar-uk/Turing-Machines | /SimpleTuM.py | 908 | 4.0625 | 4 | # Add unary numbers (e.g. 2+5)
#
# prog is indexed by the current tape symbol (0 or 1) and then by state
# (a kind of instruction pointer) to get an 'instruction' comprising:
# symbol to write on current tape position,
# head action (-1 = move left, +1 = move right)
# next state (like a goto jump).
prog=[[(1,+1,1),(0,... |
bea29fb3b2b9df15f6279e8778b5a1cfb35a8e36 | eubinecto/cs231n-assignments | /assignment1/cs231n/classifiers/k_nearest_neighbor/script.py | 12,220 | 3.625 | 4 | from builtins import range
from builtins import object
from typing import Optional
import numpy as np
import logging
import sys
logging.basicConfig(stream=sys.stdout, level=logging.INFO)
# from past.builtins import xrange # < -- what is xrange for?
class KNearestNeighbor(object):
""" a kNN classifier with L2 d... |
6c64d46c06e2b64418cd64d9038d4305e4d247ac | CosmicDisorder/blogz | /validate_email.py | 1,120 | 3.796875 | 4 | def is_email_valid(email):
is_valid=True
num_at = 0
num_dot = 0
for char in email:
if char == '@':
num_at += 1
if char == '.':
num_dot += 1
if num_at > 1 or num_dot > 1:
is_valid=False
if char == ' ':
is_valid=... |
578883934e9b49721a8d79f51e1012b0419d6cd0 | mslakshmi610/Assignments | /assignment9_mul_all_items.py | 78 | 3.609375 | 4 | def mul(i):
c=1
for x in i:
c*=x
return c
list=[2,5,7,9]
print(mul(list)) |
44ef3bfbb0e4ea0a1de17925b6e759daea55047f | mischaikow/advent_of_code | /day_9.py | 8,146 | 3.890625 | 4 | ## Day 9, we revisit the interpreter
import math
## Helper functions:
# Helper function to pull a specific digit from a number
def digit(number, n):
return number // 10**(n-1) % 10
# Helper function that recursitvely creates permutations
def permute(aList):
if len(aList) == 2:
return [[aList[0], aLi... |
cfe6e6829cd033c68f97661789d6f541e3816b1d | Shivam4819/python | /queue.py | 1,080 | 3.84375 | 4 | class Nodes:
def __init__(self, data1):
self.data = data1
self.next = None
class quque:
def __init__(self):
self.start = None
def enque(self, data):
new_node = Nodes(data)
if self.start is None:
self.start = new_node
else:
temp = sel... |
48f8f4a6deb753ea689abd4f193118429d1f2110 | amadriz/tareaPulperiaPython | /test_funciones.py | 835 | 3.65625 | 4 | from metodos import *
from tkinter import *
root = Tk()
def Calcular():
dias=int(edad.get())*365
mensaje=nombre.get()+ f' has vivido {dias} dias'
lblMensaje.config(text=mensaje)
nombre = StringVar()
edad = IntVar()
nombreLabel = Label(root, text="Nombre")
nombreLabel.grid(row=0, column=0, pady=5, padx=10... |
8aaf6cd5b8634dfdcd5a6e6923dbea448100b983 | carlanlinux/PythonBasics | /9/9.6_ClonningLists.py | 418 | 4.25 | 4 | '''
If we want to modify a list and also keep a copy of the original, we need to be able to make a copy of the
list itself, not just the reference. This process is sometimes called cloning, to avoid the ambiguity of
the word copy.
The easiest way to clone a list is to use the slice operator.
'''
a = [81,82,83]
... |
3647ccb28a579ebc1de9a78492f136558c6ba66d | carlanlinux/PythonBasics | /7_Iteration/7_1_ForString.py | 314 | 3.84375 | 4 | #puede usarse una variable delante del in que luego sustituirá dentro del loop.
#Este name es como el caso de i del for en java
for name in ["Joe", "Amy", "Brad", "Angelina", "Zuki", "Thandi", "Paris"]:
print("Hi ", name, " Please come to my party on Saturday!")
for achar in "Go Spot Go":
print(achar) |
5d58d8073a7bb39fb72cd38662a98c8db56fbebf | WojciechMula/toys | /itoa-divless/proof_single_digit.py | 1,142 | 3.984375 | 4 | def proof_carry():
for carry in [0, 1]: # carry from the previous position
for a in range(10):
for b in range(10):
# expected
S = a + b + carry
carry_expected = S // 10 # carry for the next position
# modified
... |
ce6d003646087f2bad846fad32eabeeccd7281f7 | WojciechMula/toys | /avx512-binomialcoef/python/factor.py | 2,630 | 3.796875 | 4 | def factor(x):
assert x > 0
k = 2
result = []
while x > 1:
if (x % k) == 0:
result.append(k)
x //= k
else:
if k == 2:
k = 3
else:
k += 2
return tuple(result)
class Primes:
def __ini... |
d235a60a0d9a2f85600cedcbfb8fadd3ed73aa77 | zhongbingchen/ichw | /py1/1700011738.py | 849 | 4.03125 | 4 | #!/usr/bin/env python3
"""Foobar.py: Description of what foobar does.
__author__ = "Zhong Bingchen"
__pkuid__ = "1700011738"
__email__ = "1700011738@pku.edu.cn"
"""
import math
import turtle
def planet(name, color, center, long, short):
name = turtle.Turtle()
name.speed(0)
name.shape("circle")
nam... |
fde237ca47db4923535865dc1e86a0a04580d577 | DorShaar/computer-vision-study | /FaceRecognition.py | 1,073 | 3.625 | 4 | import sys # for exit
import os # for file exist check
import cv2 # for image operations, face recognition
# Create a CascadeClassifier object.
face_cascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# Get image path from user.
# image_path = raw_input("Insert image path: ")
# if... |
fea07c801e6c1bc1e323246767310eb0da1e5a4a | ZeroDestru/meus-programas-em-python | /completo/av5biblio.py | 944 | 3.90625 | 4 | def insercao(a,b,cores):
cores
cores.append((a,b))
def consulta(cor,cores):
for codig in cores:
if(codig[1] == cor):
return codig[0]
return "cor não cadastrada"
def listagem(cores):
for i in range(len(cores)):
print(f'cor {cores[i][1]}: codigo {cor... |
53d1ddee25757f9cf65fc8859f7654383a04192e | ZeroDestru/meus-programas-em-python | /completo/avaliação 6 | 267 | 3.765625 | 4 | num = int(input())
so = 0
imp = 1
for i in range(1,num//2+1):
so += imp
imp += 2
if(so == num):
break
if(so == num):
print(f"{num} é quadrado perfeito")
else:
print(f"{num} não é quadrado perfeito") |
f2c18334ac24ad907b0a26eb9f454243e3b16d38 | haw230/linear-search | /linear_search/main.py | 442 | 3.96875 | 4 | def search(ls, num): #search function will take in a list (ls) and a number (num)
'''
This function will take in a list of numbers as ls, such as [1, 2, 3] and a number as num, such as 2.
The function should return the zero-based index of that number which would be 1 in this case.
Return -1 if the number could... |
c61927d7a37dae2b81e847334d7883523df14055 | Magnifis/Python-base | /Ustinov Andrey_Lesson1/task1_2.py | 1,262 | 3.90625 | 4 | # 2. Создать список, состоящий из кубов нечётных чисел от 0 до 1000:
# Вычислить сумму тех чисел из этого списка, сумма цифр которых делится нацело на 7.
# Например, число «19 ^ 3 = 6859» будем включать в сумму, так как 6 + 8 + 5 + 9 = 28 – делится нацело на 7.
# Внимание: использовать только арифметические операции!
#... |
a8bf8b4889893b1c47ae9258f194ff41c4ebbcc8 | MalteMagnussen/PythonProjects | /week2/webget.py | 976 | 3.78125 | 4 | import os
import urllib.request as req
from urllib.parse import urlparse
import checkFile
def download(url, to=None):
"""Download a remote file specified by a URL to a
local directory.
:param url: str
URL pointing to a remote file.
:param to: str
Local path, absolute or relative, wit... |
bef8d75fcc78789f6756049e29ba02d5702f296e | MalteMagnussen/PythonProjects | /week5/DateTime/Timedeltas.py | 1,136 | 3.9375 | 4 | from datetime import timedelta, datetime
print('smallest possible timedelta:\t', timedelta.min)
print('largest possible timedelta:\t', timedelta.max)
t = timedelta(weeks=1, days=2, hours=3,
minutes=4, seconds=5, microseconds=999)
# timedelta internally translates all to days,
# seconds and microseconds
p... |
ce9a774c06363afc1f03da671d9276d5ae11b758 | MalteMagnussen/PythonProjects | /week2/objectOriented/Book.py | 974 | 4.21875 | 4 | from PythonProjects.week2.objectOriented import Chapter
class Book():
"""A simple book model consisting of chapters, which in
turn consist of paragraphs."""
def __init__(self, title, author, chapters=[]):
"""Initialize title, the author, and the chapters."""
self.title = title
se... |
50f211e15312f81fd960ea1c0b332477bbdaa70d | MalteMagnussen/PythonProjects | /week4/numpy/fancyIndexing.py | 160 | 3.671875 | 4 | import numpy as np
# use one np array as indices for another
a = np.arange(0, 100, 10)
indices = np.array([1, 5, -1])
print(indices)
print(a)
print(a[indices])
|
eeb32b86f35a8343120dfeb28fb8f22e49f9ed83 | KowsalyaS18/task227 | /replace.py | 69 | 3.78125 | 4 | string=input("enter your string")
x=string.replace(",","|")
print(x)
|
a9d3de79037c925816be297de9f3755dab183ca2 | KowsalyaS18/task227 | /stringmatch.py | 184 | 3.546875 | 4 | str=input("enter your input")
file=open("c:Users/AMMA/myproject/Include/testfile.txt","r")
str1=file.read()
if str in str2:
print("matched")
else:
print("not matched")
file1.close()
|
0c209da23bd3717cad46e0bb0ad8d2e5401c177b | ReWKing/StarttoPython | /操作列表/创建数值列表/numbers.py | 208 | 4.34375 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Author:William Gin
# 使用函数range()
for value in range(1, 5):
print(value)
# 使用函数range()创建数字列表
numbers = list(range(1, 6))
print(numbers)
|
061d070b3ab2dbd762c7881c417277289d9ca0c3 | ReWKing/StarttoPython | /操作列表/创建数值列表/动手试一试/4-8 立方.py | 196 | 3.828125 | 4 | #!/usr/bin/python
# -*- coding:utf-8 -*-
# Author:William Gin
lifangs = []
for value in range(1, 11):
lifang = value ** 3
lifangs.append(lifang)
print(lifangs)
for i in lifangs:
print(i)
|
bf97c84e5ec9fd30990760633dd45a266100ec51 | ReWKing/StarttoPython | /下载数据/CSV文件格式/打印文件头及其位置/highs_lows.py | 632 | 3.625 | 4 | # author:K
# 导入csv模块
import csv
# 将要使用的文件存储到filename中
filename = 'sitka_weather_07-2014.csv'
# 打开这个文件,并将结果文件存储在f中
with open(filename) as f:
# 将前面存储的文件作为实参传递给它,创建一个与该文件相关联的阅读器(reader)对象,并将这个阅读器存储在reader中
reader = csv.reader(f)
# 调用一次next(),得到文件第一行,其中包含文件头,将返回的值存储在header_row中
header_row = next(reader)
... |
de847b7f5170c2a7b6525815360a9e556dabd851 | MrVineetPatil/unix | /8b.py | 590 | 4.03125 | 4 | from Area import *
while(1):
c = int(input(
"Enter 1 to find Area for circle\nEnter 2 to find Area for Rectangle\nEnter 3 to find Area for triangle\nEnter 4 to exit\n"))
print()
if c==1:
r=int(input("Enter radius:"))
print(area_cirle(r))
elif c==2:
x=int(input(... |
3e31f087d0703727310e782ad61f60682fc50d2a | tizziana/GrafoMundial | /pruebas/heap.py | 2,062 | 4.1875 | 4 |
# -------------------------------------------------------------------
# PRIMITIVAS DEL HEAP |
# -------------------------------------------------------------------
class Heap:
"""Representa un heap de min con operaciones de encolar, desencolar,
ver_maximo, cantidad y verificar si está vacio."""
def __... |
64034b97e527b66434bc822676ee43a59c26a97c | dmichaels19/Cracking-the-Coding-Interview | /davids_prep/davids_functions.py | 422 | 3.671875 | 4 | def new_range_iter(first, second=None, increment=1):
if second == None:
start = 0
end = first
else:
start = first
end = second
curr = start
while curr < end:
print(increment)
yield curr
curr += increment
def new_range_list(first, second=None, inc... |
6282de51d56d57dc268bd2daec959c93f2ea21c3 | dmichaels19/Cracking-the-Coding-Interview | /davids_prep/Interview Challenges/sets/set.py | 5,953 | 3.90625 | 4 | """
Please use Python 2.7. Call with:
$ your_input_text.txt | python set.py
"""
import sys
# Conversion mappings from attribute to value.
# The index of each attribute is its value
COLORS = ['blue', 'green', 'yellow']
SYMBOLS = ['aA@', 'sS$', 'hH#']
SHADINGS = ['ash','ASH', '@$#']
# Indices for the value of each att... |
a704d1acb1d18b4635baaf2ffb372a60be5d7ac4 | JohnEstebanAP/FundamentosProgramacionPython | /Sesión6/EjercicioPratico/sesion6.py | 3,958 | 3.96875 | 4 | # Diseñar 3 opciones:
#
# 1. Leer un número de 4 dígitos, mostrar el dígito mayor e
# informar si es par o impar.
# 2. Leer dos números de 3 dígitos cada uno, formar un tercer número
# con el mayor del primero y el menor del segundo.
# 3. Leer un número de 3 dígitos y formar el mayor número posi... |
c54aa8fdaa208f9107d7ec06a767e0430eac2124 | JohnEstebanAP/FundamentosProgramacionPython | /Reto 3/reto3.py | 3,174 | 3.59375 | 4 | #John Esteban Alvarez Piedrahita
#Número de identificacion: 1017272663
#esta función nos ayuda a determinar la alerta del promedio de la hemoglobina de los hombres
def alertaM(hemoglobina):
#Masculino
#print("el genero es Masculino",genero)
if hemoglobina < 13.2:
alerta = "Alerta 1"
elif hemo... |
875bc855207b37cedee6c9799951afcb63b2bf5f | JohnEstebanAP/FundamentosProgramacionPython | /Sesión1/sesion1.py | 1,894 | 4.46875 | 4 | #Instrucciones, Variables, y Operaciones Matemáticas
#Comencemos por lo más sencillo...
# Recuerda que programar significa
# darle instrucciones al computador
# para que haga lo que yo quiera.
# Podemos comenzar por pedirle que
# imprima algo para nosotros:
print("¡Hola soy john!")
print("\n")
# Para asignarle... |
fdde0b3b81e7987289e4134ff4a523f5b6544587 | saurabh-pandey/AlgoAndDS | /leetcode/binary_search/sqrt.py | 1,075 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/binary-search/125/template-i/950/
#Description
"""
Given a non-negative integer x, compute and return the square root of x.
Since the return type is an integer, the decimal digits are truncated, and only the integer part of
the result is returned.
Note: You are not allowed... |
4fc64b6ea76eae02f550506f35261fb470855e1c | saurabh-pandey/AlgoAndDS | /leetcode/queue_stack/problems/flood_fill.py | 2,482 | 3.984375 | 4 | #URL: https://leetcode.com/explore/learn/card/queue-stack/239/conclusion/1393/
"""
An image is represented by an m x n integer grid image where image[i][j] represents the pixel value
of the image.
You are also given three integers sr, sc, and newColor. You should perform a flood fill on the
image starting from the pi... |
37c3c8157412eb59392d73abc5dc4d4b79aa094c | saurabh-pandey/AlgoAndDS | /leetcode/binary_tree/preorder_traversal.py | 1,488 | 4 | 4 | #URL: https://leetcode.com/explore/learn/card/data-structure-tree/134/traverse-a-tree/928/
#Description
"""
Given the root of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = ... |
7ef38db4f1487764f52ab379c6d883cc261e7e0f | saurabh-pandey/AlgoAndDS | /myAttempts/heap/median_calc.py | 2,907 | 3.8125 | 4 | #Description
"""
Given a stream of numbers compute the running median.
NOTE: This problem was discussed in Tim's algo-1 course as an application of heap.
"""
from heap.heap import Heap
class MedianCalculator:
def __init__(self) -> None:
self.max_heap = Heap(False)
self.min_heap = Heap()
def ... |
b878068e14bbced944c4a6d9cc0bd86a2f6b3fce | saurabh-pandey/AlgoAndDS | /leetcode/binary_search/median_sorted_arrays.py | 3,578 | 3.984375 | 4 | #URL: https://leetcode.com/explore/learn/card/binary-search/146/more-practices-ii/1040/
#Description
"""
Given two sorted arrays nums1 and nums2 of size m and n respectively, return the median of the two
sorted arrays.
The overall run time complexity should be O(log (m+n)).
Example 1:
Input: nums1 = [1,3], nums2 = ... |
9374707c04d9255c7178b94a910276d5941f8798 | saurabh-pandey/AlgoAndDS | /leetcode/hash_table/top_k_frequent.py | 1,007 | 3.96875 | 4 | #URL: https://leetcode.com/explore/learn/card/hash-table/187/conclusion-hash-table/1133/
#Description
"""
Given an integer array nums and an integer k, return the k most frequent elements. You may return
the answer in any order.
Example 1:
Input: nums = [1,1,1,2,2,3], k = 2
Output: [1,2]
Example 2:
Input: nums =... |
e77bf1a504d076355f1b26af5e9dbf265bd67046 | saurabh-pandey/AlgoAndDS | /leetcode/binary_search/min_rotated_duplicate.py | 1,257 | 3.921875 | 4 | #URL: https://leetcode.com/explore/learn/card/binary-search/144/more-practices/1031/
#Description
"""
Suppose an array of length n sorted in ascending order is rotated between 1 and n times. For
example, the array nums = [0,1,4,4,5,6,7] might become:
[4,5,6,7,0,1,4] if it was rotated 4 times.
[0,1,4,4,5,6,7] if it was... |
36560d649954d5a1b7e2d1c1754e928a63646945 | saurabh-pandey/AlgoAndDS | /leetcode/trie/word_dictionary.py | 2,641 | 3.9375 | 4 | #URL: https://leetcode.com/explore/learn/card/trie/148/practical-application-i/1052/
#Description
"""
Design a data structure that supports adding new words and finding if a string matches any
previously added string.
Implement the WordDictionary class:
WordDictionary() Initializes the object.
void addWord(word) Adds ... |
958ecb786b8eba95c0108405c245901b436302f5 | saurabh-pandey/AlgoAndDS | /leetcode/dp/all_full_binary_tree.py | 2,243 | 3.9375 | 4 | #URL: https://leetcode.com/problems/all-possible-full-binary-trees/
#Description
"""
Given an integer n, return a list of all possible full binary trees with n nodes. Each node of each
tree in the answer must have Node.val == 0.
Each element of the answer is the root node of one possible tree. You may return the final... |
6787c40a50729832e9f0fdf851cfb129b0de31ce | saurabh-pandey/AlgoAndDS | /leetcode/array_and_string/string/reverse_words.py | 1,460 | 3.71875 | 4 | #URL: https://leetcode.com/explore/learn/card/array-and-string/204/conclusion/1165/
#Description
"""
Given a string s, reverse the order of characters in each word within a sentence while still
preserving whitespace and initial word order.
Example 1:
Input: s = "Let's take LeetCode contest"
Output: "s'teL ekat edoC... |
5c34f5b9a50d2615b703c22d2f29a96fe153cd5a | saurabh-pandey/AlgoAndDS | /leetcode/recursion_2/combinations.py | 948 | 4.09375 | 4 | #URL: https://leetcode.com/explore/learn/card/recursion-ii/472/backtracking/2798/
#Description
"""
Given two integers n and k, return all possible combinations of k numbers out of the range [1, n].
You may return the answer in any order.
Example 1:
Input: n = 4, k = 2
Output:
[
[2,4],
[3,4],
[2,3],
[1,2],
... |
a92f4917c59de273014c3aec97c484072912e9ff | saurabh-pandey/AlgoAndDS | /leetcode/hash_table/validate_sudoku.py | 3,023 | 3.859375 | 4 | #URL: https://leetcode.com/explore/learn/card/hash-table/185/hash_table_design_the_key/1126/
#Description
"""
Determine if a 9 x 9 Sudoku board is valid. Only the filled cells need to be validated according to
the following rules:
Each row must contain the digits 1-9 without repetition.
Each column must contain the di... |
dd293e196466918a0f6d70cd8db17dfd15a8e1dd | saurabh-pandey/AlgoAndDS | /leetcode/linkedList/singly_linked_list/SinglyLinkedList_a1.py | 3,045 | 3.765625 | 4 | #URL: https://leetcode.com/explore/learn/card/linked-list/209/singly-linked-list/1290/
# Description
"""
Design your implementation of the linked list. You can choose to use a singly or doubly linked list.
A node in a singly linked list should have two attributes: val and next. val is the value of the current node, and... |
d9a3ec31ab712b969bf2310cef052c9af042076d | saurabh-pandey/AlgoAndDS | /leetcode/linkedList/problems/add_two_nums.py | 2,257 | 4 | 4 | #URL: https://leetcode.com/explore/learn/card/linked-list/213/conclusion/1228/
#Description
"""
You are given two non-empty linked lists representing two non-negative integers. The digits are
stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and
return the sum as a linked l... |
e29aafec12e70059aeaa20d14ec71005b7ddb863 | saurabh-pandey/AlgoAndDS | /leetcode/binary_tree/deserialize.py | 1,769 | 3.984375 | 4 | #URL: https://leetcode.com/explore/learn/card/data-structure-tree/133/conclusion/995/
#Description
"""
Serialization is the process of converting a data structure or object into a sequence of bits so
that it can be stored in a file or memory buffer, or transmitted across a network connection link
to be reconstructed ... |
b44a022cd1fedc802f6be0f9b4124228906c3f4a | saurabh-pandey/AlgoAndDS | /leetcode/binary_search/find_peak.py | 1,947 | 3.9375 | 4 | #URL: https://leetcode.com/explore/learn/card/binary-search/126/template-ii/948/
#Description
"""
A peak element is an element that is strictly greater than its neighbors.
Given an integer array nums, find a peak element, and return its index. If the array contains
multiple peaks, return the index to any of the peaks.... |
fcbd02f154460b723edfb16fe71c34875ff7a524 | saurabh-pandey/AlgoAndDS | /leetcode/dp/max_sum_partition.py | 1,260 | 3.640625 | 4 | #URL: https://leetcode.com/problems/partition-array-for-maximum-sum/
#Description
"""
Given an integer array arr, partition the array into (contiguous) subarrays of length at most k.
After partitioning, each subarray has their values changed to become the maximum value of that
subarray.
Return the largest sum of the ... |
32cf60d49a9633e781b9add0b15dd50ce5bb54de | saurabh-pandey/AlgoAndDS | /leetcode/queue_stack/stack/min_stack.py | 2,188 | 3.90625 | 4 | #URL: https://leetcode.com/explore/learn/card/queue-stack/230/usage-stack/1360/
#Description
"""
Design a stack that supports push, pop, top, and retrieving the minimum element in constant time.
Implement the MinStack class:
MinStack() initializes the stack object.
void push(val) pushes the element val onto the stack... |
c49023ff5224e1af90c7b2a2674dea123f28e695 | saurabh-pandey/AlgoAndDS | /leetcode/array_and_string/array/plus_one.py | 1,690 | 3.984375 | 4 | #URL: https://leetcode.com/explore/learn/card/array-and-string/201/introduction-to-array/1148/
#Description
"""
Given a non-empty array of decimal digits representing a non-negative integer, increment one to the
integer.
The digits are stored such that the most significant digit is at the head of the list, and each
e... |
5422e9da5283fd21154013adc5b392cccccfc740 | saurabh-pandey/AlgoAndDS | /leetcode/recursion_1/search_bst.py | 962 | 3.875 | 4 | #URL: https://leetcode.com/explore/learn/card/recursion-i/251/scenario-i-recurrence-relation/3233/
#Description
"""
You are given the root of a binary search tree (BST) and an integer val.
Find the node in the BST that the node's value equals val and return the subtree rooted with that
node. If such a node does not ex... |
ba89d39559e72e5743200e694ed4cab235f8320d | saurabh-pandey/AlgoAndDS | /myAttempts/sorting/mergeSort.py | 477 | 3.796875 | 4 | def merge(A, B, C):
i = j = k = 0
while ( i < len(A)):
if ( (j < len(B)) and (k < len(C)) ):
if (B[j] < C[k]):
A[i] = B[j]
j += 1
else:
A[i] = C[k]
k += 1
i = i + 1
elif (j < len(B)):
A[i:] = B[j:]
i = len(A)
elif (k < len(C)):
A[i:] = ... |
19f33ae93453ea3af965342ea0aec53d2b167d05 | saurabh-pandey/AlgoAndDS | /leetcode/arrays/squares_sorted_array_a1.py | 1,753 | 4 | 4 | #URL: https://leetcode.com/explore/learn/card/fun-with-arrays/521/introduction/3240/
# Description
"""
Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Example 1:
Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: ... |
7ff689c4e4d6f95ad27413579ee15919eee29e15 | saurabh-pandey/AlgoAndDS | /leetcode/bst/sorted_arr_to_bst.py | 1,129 | 4.25 | 4 | #URL: https://leetcode.com/explore/learn/card/introduction-to-data-structure-binary-search-tree/143/appendix-height-balanced-bst/1015/
#Description
"""
Given an integer array nums where the elements are sorted in ascending order, convert it to a
height-balanced binary search tree.
A height-balanced binary tree is a bi... |
355892ad0355cf48021cecbdbc9ed2c73e45a09b | saurabh-pandey/AlgoAndDS | /leetcode/trie/replace_words.py | 3,401 | 4.09375 | 4 | #URL: https://leetcode.com/explore/learn/card/trie/148/practical-application-i/1053/
#Description
"""
In English, we have a concept called root, which can be followed by some other word to form another
longer word - let's call this word successor. For example, when the root "an" is followed by the
successor word "oth... |
e5db09c66f8e17621e1b5d5ec20d10f96b200e00 | saurabh-pandey/AlgoAndDS | /leetcode/dp/min_cost_climb.py | 1,188 | 3.90625 | 4 | #URL: https://leetcode.com/problems/min-cost-climbing-stairs/
#Description
"""
You are given an integer array cost where cost[i] is the cost of ith step on a staircase. Once you
pay the cost, you can either climb one or two steps.
You can either start from the step with index 0, or the step with index 1.
Return the mi... |
493d333914b713d43a9673579a4270b4c3c6e4aa | saurabh-pandey/AlgoAndDS | /leetcode/recursion_2/search_matrix.py | 4,628 | 3.953125 | 4 | #URL: https://leetcode.com/explore/learn/card/recursion-ii/470/divide-and-conquer/2872/
#Description
"""
Write an efficient algorithm that searches for a target value in an m x n integer matrix. The
matrix has the following properties:
Integers in each row are sorted in ascending from left to right.
Integers in each c... |
c5361ad406f3da27f7960150fb6afbd44bbae03e | saurabh-pandey/AlgoAndDS | /leetcode/queue_stack/stack/target_sum.py | 2,326 | 4.1875 | 4 | #URL: https://leetcode.com/explore/learn/card/queue-stack/232/practical-application-stack/1389/
#Description
"""
You are given an integer array nums and an integer target.
You want to build an expression out of nums by adding one of the symbols '+' and '-' before each
integer in nums and then concatenate all the integ... |
72d27e13ba30f9d65f0e0b4e105389f80d2fcd03 | loolu/python | /CharacterString.py | 830 | 4.15625 | 4 | #使用字符串
#字符串不可改变,不可给元素赋值,也不能切片赋值
website = 'http://www.python.org'
website[-3] = 'com'
#
format = "Hello, %s. %s enough for ya?"
values = ('world', 'hot')
print(format % values)
from string import Template
tmpl = Template("Hello, $who! $what enough for ya?")
print(tmpl.substitute(who='Mars', what='Dusty'))
print("{}... |
2d367a5c6c421c3bb18315107a153800b4dd8430 | sduch009/LearningPython | /ex43.py | 2,570 | 4.03125 | 4 | #ex43, Basic Object-Oriented Analysis nad Design
# Process for when you want to build something using python, specifically with object-oriented programming:
# 1. Write or draws about the problem.
# 2. Extract key concepts from 1 and research them.
# 3. Create class hierarchy and object map for the concepts.
# 4. C... |
2838508fa1a1f284f55f2d77f577fd79a76391e1 | fiedlr/matman | /plotter.py | 3,811 | 3.59375 | 4 | """ matman <github.com/fiedlr/matman> """
import numpy as np
import matplotlib.pyplot as plt
class Plotter:
""" Gives results a graphical interpretation """
def __init__(self, analyser):
self.__analyser = analyser
# Plt config
plt.grid(True)
def __autolabel(self, rects, ax, labels):
""" http://matplotlib.... |
de29077a7f294846b13b6af9c1c955ee2d80723c | canweriotnow/exercism | /python/bob/bob.py | 640 | 3.75 | 4 | #
# Skeleton file for the Python "Bob" exercise.
#
import re
def shoutp(what):
if re.search('[A-Z]', what) and what == what.upper():
return True
else:
return False
def questionp(what):
if re.match('.+\?\s*$', what):
return True
else:
return False
def silentp(what):
... |
2ad9bd49f4e7c8b48c3795de064e16a93aea9e8a | ironcpa/scaling_python_kor | /Chapter02/03_multithreading-worker.py | 848 | 3.640625 | 4 | # program desc
# - create 5 worker threads
# - each worker sum lots of numbers
# - and appends to results []
# - worker thread directly access collector obj(results)
# purpose
# - shows how to use workers
# - and collect results from worker
# how to run w/ time profiling
# $ /usr/bin/time -f "%Us user %... |
61bb1f7871db613627d1edd50128a7c5c88d0b4b | Stemist/BudCalc | /BudgetCalculatorCLI.py | 1,577 | 4.28125 | 4 | #!/usr/bin/env python3
people = []
class Person:
def __init__(self, name, income):
self._name = name
self._income = income
self.products = {}
def add_product():
try:
product = str(input("Enter product name: "))
cost = float(input("Enter product cost ($): "))
products[product] = price
except:... |
36d1d6f8060a6e7dcdf58b48b12bfea2396d6023 | joshrili/rili | /cpt_05.py | 1,662 | 4.15625 | 4 | '''
Description: python code, exercises of chapter 5, python crash course
Author: joshrili
Date: 2020-03-22
'''
cars = ['audi', 'bmw', 'subaru', 'toyota']
print(cars)
for car in cars :
if car == 'bmw' :
print(car.upper())
print('I like ' + car.upper() + '\n')
else :
print... |
4b67eb4c4a802e7980142f6a8ee644f1bda6d867 | huyilong/python-learning | /fibo_module.py | 720 | 4.25 | 4 | #fibonacci numbers module
#could directly input python3 on mac terminal to invoke version 3
def fib(n):
a, b = 0, 1
while b < n:
print( b),
#there is a trailing comma "," after the print to indicate not print output a new line
a, b = b, a+b
print #this is print out a empty line
#if you use print() then it... |
95731c7a7c4a014cebc004fdca3fa36d045919ac | akimoruzbaev/team_work | /tiif.py | 308 | 3.8125 | 4 | class Car:
def __init__(self, name, year, owner):
self.name = name
self.year = year
self.owner = owner
def get_info(self):
print(f"Автомобиль {self.name}")
print(f"Год выпуска {self.year}")
print(f"Владелец {self.owner}")
|
6d70e720d4424c0b948c20561fdec80afae21701 | gregxrenner/Data-Analysis | /Coding Challenges/newNumeralSystem.py | 1,752 | 4.46875 | 4 | # Your Informatics teacher at school likes coming up with new ways to help
# you understand the material. When you started studying numeral systems,
# he introduced his own numeral system, which he's convinced will help clarify
# things. His numeral system has base 26, and its digits are represented by
# English capita... |
51813f74b69d4bfe39415c2a323d48ce465351df | miguel-osuna/PS-Algos-and-DS-using-Python | /Section7_Trees/binary_heap/priority_queue.py | 1,298 | 3.5625 | 4 | # Local application imports
from binary_heap_max import BinaryHeapMax
class PriorityQueue:
"""
Front -> Rear implementation
Maintains the highest priority items on the front
"""
def __init__(self):
self.heap_items = BinaryHeapMax()
def __str__(self):
return str(self.heap_it... |
3db088fe5b7e8a7ae95961261f1419c7d5fdd5be | miguel-osuna/PS-Algos-and-DS-using-Python | /Section7_Trees/binary_heap/binary_heap_max.py | 2,727 | 3.625 | 4 | class BinaryHeapMax:
""" Binary Heap maximum order implementation """
def __init__(self):
self.heap_list = [0]
self.current_size = 0
def __str__(self):
return str(self.heap_list)
def __len__(self):
return self.current_size
def perc_up(self, i):
""" Percola... |
3368c218ef7be93ad0bfb2aa6efcb01f397697ae | miguel-osuna/PS-Algos-and-DS-using-Python | /Section7_Trees/binary_search_tree/balanced_binary_search_tree.py | 6,004 | 3.890625 | 4 | # Local application imports
from binary_search_tree import TreeNode, BinarySearchTree
class BalancedTreeNode(TreeNode):
""" Balanced Tree Node class """
def __init__(
self, key, value, left=None, right=None, parent=None, balance_factor=0
):
super().__init__(key, value, left, right, parent... |
2f74be1a461073ee407ec627e355281950a480a0 | miguel-osuna/PS-Algos-and-DS-using-Python | /Section6_Sorting_Searching/sorting/bubble_sort.py | 2,245 | 4.21875 | 4 | # Bubble Sort Algorithm
def bubble_sort(num_list):
""" Bubble Sort Algorithm """
for passnum in range(len(num_list) - 1, 0, -1):
for i in range(passnum):
# Exchanges items
if num_list[i] > num_list[i + 1]:
temp = num_list[i]
num_list[i] = num_list[... |
e239b3e81010c5c40e65a616cdf931c397cb43ac | miguel-osuna/PS-Algos-and-DS-using-Python | /Section5_Recursion/dynamic_programming/make_change.py | 3,304 | 4.21875 | 4 | def recursion_make_change(coin_value_list, change):
""" Recursive make change function"""
min_coins = change
# Base Case
if change in coin_value_list:
return 1
# Recursive Case
else:
# Iterates over coins that are smaller than the value of cents
for i in [coin for coin in... |
65d18a97c8ead84b581571e832a12ef49018be04 | vincenttuan/ntnu_python | /lesson2/StrDemo.py | 68 | 3.796875 | 4 | str = 'hello python 3.7'
print(str.find('th'))
print(str.find('ha')) |
cead807f8bd377eb882aa338c36f2d1d158e4c5c | vincenttuan/ntnu_python | /lesson1/OO_Demo.py | 545 | 3.796875 | 4 | class Account:
money = 0
def setName(self, name): # 戶名
self.name = name
def getName(self):
return self.name
def setMoney(self, money):
self.money = self.money + money
def getMoney(self):
return self.money
a = Account()
a.setName('Vincent')
a.setMoney(100)
a.setMoney(... |
15f165a254a6c2ae309cd85823db86a54aa12bc3 | vincenttuan/ntnu_python | /lesson6/Face_Recognition_Door.py | 2,374 | 3.640625 | 4 | # 匯入所需程式庫
import cv2
from lesson6 import Config
# 載入 Config.HAAR_FACES 指定的層疊分類器
haar_faces = cv2.CascadeClassifier(Config.HAAR_FACES)
if __name__ == '__main__':
s = input('是否要開門(y/n) ?')
if (s == 'n'):
exit(0)
# 取得攝像鏡頭位置
cap = cv2.VideoCapture(0)
# 設定攝像鏡頭捕捉區域
cap.set(cv2.CAP_PROP_FRAM... |
5466bfc838e83fe98c8fa57d88382fe1a48f8925 | vincenttuan/ntnu_python | /lesson2/ForLoop2.py | 276 | 3.96875 | 4 | names = ['John', 'Mary', 'Tom']
for name in names:
print(names.index(name), name)
if 'Tom' in names:
print('Yes')
else:
print('None')
employees = {'Tom':70000, 'Mary':80000, 'John':55000}
for key in employees:
print('%s 的薪資 %d' % (key, employees[key])) |
bcb7427eca9c4d4dff06454dab5a866bd1f165b7 | vincenttuan/ntnu_python | /lesson1/BMI.py | 441 | 3.703125 | 4 | w = 60
h = 170
bmi = w / ((h/100)*(h/100))
print(bmi)
bmi = w / ((h/100)**2)
print(h, w, bmi)
print("身高:" + str(h) + " 體重:" + str(w) + " BMI:" + str(bmi))
print("身高: %d 體重: %d BMI: %.2f" % (h, w, bmi))
print("身高: %06d 體重: %06d BMI: %06.2f" % (h, w, bmi))
result = "身高: {0} 體重: {1} BMI: {2}".format(h, w, bmi)
print(resul... |
e3f0c891f1f468000d52caedfa655862de173d83 | vincenttuan/ntnu_python | /lesson4/Win_TreeView_lotto.py | 849 | 3.515625 | 4 | import tkinter
import random
from tkinter import ttk # 匯入資源
def addRecord():
lottos = set()
while len(lottos) < 5:
lottos.add(random.randint(1, 39))
tree.insert('', '0', values=list(lottos)) # end 最後一筆,0 第一筆
tree.grid()
win.after(10, addRecord)
win = tkinter.Tk()
tree = ttk.Treeview(win... |
23de8de49110b4db71833b1b54041bd41fae2b43 | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-6.py | 436 | 4.3125 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates miles walked and calories lost for a specific day of the week.
dayWalked = input('Enter the day of the week you walked: ')
stepsTaken = int(input('Enter the number of steps taken that day: '))
milesWalked = (stepsTaken/2000)
caloriesL... |
7e281c681e942b6bb7ef1b06f9b9fcb663bc068c | jmobriencs/Intro-to-Python | /O'Brien_Lab11/Sum of Digits in a String.py | 1,204 | 4.09375 | 4 | # John-Michael O'Brien
# w1890922
# CISP 300
# 4/17/20
# This program allows a user to enter a series of single digit numbers and
# the program displays the sum of all the single digit numbers in the string.
# Chapter 12: Sum of Digits in a String
# the main function
def main():
endProgram = 'no'
... |
2c2cd04d5893ebb5e05d463729a999f80e55266c | jmobriencs/Intro-to-Python | /O'Brien_Lab1/Lab1-4.py | 580 | 4.1875 | 4 | #John-Michael O'Brien
#w1890922
#CISP 300
#1/31/20
#This program calculates how many credits are left until graduation.
studentName = input('Enter student name. ')
degreeName = input('Enter degree program name. ')
creditsDegree = int(input('Enter the number of credits needed for the degree. '))
creditsTaken =... |
b289eba680b79433efcc3eca9486b335a0254dc0 | XUANXUANXU/6-web-crawler | /09-day/第九天/进程.py | 739 | 3.96875 | 4 | #进程:资源是有CPU分配,是CPU资源分配的最小单元
#进程包含线程
# 如何创建进程?
from multiprocessing import Process
import os
def run():
print('子进程开启'+str(os.getpid()))
for i in range(1,300):
print(i)
print('子进程结束'+str(os.getpid()))
if __name__ == '__main__':
print('主进程开启'+str(os.getpid()))
#创建一个进程:
sub_pro... |
b954bf1fd82316d75850e07bb5177cdfcc3ab2e2 | kundaMwiza/dsAlgorithms | /source/peak_finder_linear.py | 530 | 3.8125 | 4 | def peak_finder_linear(L):
"""
input: list of integers L
output: peak element if it exists, else None
O(n) implementation for the peak finding problem on a one dimensional array
"""
for i in range(1,len(L)):
if i == 1 and L[0] >= L[1]:
return comp
elif i == len(L)-1:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.