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 |
|---|---|---|---|---|---|---|
e4617c7da4f6dcd3cfcfcad00ca4672e8f891491 | jerede/Desenvolvimento-Python | /ExecicioJorge/Ex01Q1.py | 396 | 3.953125 | 4 | #1) Faça um Programa que peça as 4 notas bimestrais e mostre a média.
print ('Avaliação do Aluno')
nota1 = float(input('Digite a primeira Nota: '))
nota2 = float(input('Digite a segunda Nota: '))
nota3 = float(input('Digite a terceira Nota: '))
nota4 = float(input('Digite a quarta Nota: '))
media = (nota1 ... |
818d8383004fd4057a5046e41c9088bacbd54758 | marejak023/leibniz-series | /main.py | 2,214 | 3.671875 | 4 | #Author: marejak023
#Contact: marejak023@gmail.com, marejak023.wz.cz
#Date: 06/02/2021
import matplotlib.pyplot as plt
import numpy as np
import math
#code for computing Leibniz series
k = 1 # denominator
s = 0 # sum
# x and y array for storing plot values
y = np.array([])
x = np.array([])
PI_CONST_LI... |
9a1b268386b4652bf50af0365892ef7338329727 | ellenfb/EE381 | /Prj_5_HypothesisTesting/Project5_Part2_EllenBurger.py | 933 | 3.6875 | 4 | #header
import matplotlib.pyplot as pmf
import random
p = 0.5 # Probablility of success for original system
n = 18 # Number of trials
Y = [] # Contains binomial RVs
b = [0] * (n+1) # List of n + 1 zeroes
N = 100 # Number of experiments performed
for j in range(N):
# Bernoulli random variable
for i in ra... |
f86364ba2cb64e69ee22736009ae72f4d8bbdfd3 | newmancodes/python_exercises_for_tony | /string_sequences.py | 376 | 3.953125 | 4 | string_values = list(input('Enter a comma separated list of strings: ').split(','))
max_found = ''
for start in range(len(string_values[0])):
for end in range(len(string_values[0][start:])):
look_for = string_values[0][start:start+end+1]
if len(look_for) > len(max_found) and look_for in string_value... |
4ddc77618d10ad035872e94afdb90d41383685f9 | BrianASpencer/CSC310Homework | /Homework-1/Hw1.py | 3,775 | 4.28125 | 4 | # Name: Brian Spencer
# Date: 1/27/19
# Course: CSC 310
# Project: Homework 1
# Function to determine if there is at least one distinct pair of
# elements in an array whose product is odd.
# An array is the only required input.
def isOdds(a):
n = len(a)
for i in range(0, n): #iterate over array twice... |
6604766302b7fb15c5cb38cea1724f43a7a61f28 | piri07/PythonPractice | /DSA/Bellman.py | 1,328 | 4.03125 | 4 | class Graph:
def __init__(self,vertices):
self.V = vertices
self.graph=[]
def addEdge(self,u,v,w):
self.graph.append([u,v,w])
#prints the solution
def printArr(self,dist):
print("vertex distance from Source")
for i in range(self.V):
... |
7ef715dd78c6282a3a8d337a8ba69c96e4c3607f | piri07/PythonPractice | /DSA/binomialcoeff.py | 1,509 | 3.8125 | 4 | # A Dynamic Programming based Python Program that uses table C[][]
# to calculate the Binomial Coefficient
# Returns value of Binomial Coefficient C(n, k)
def binomialCoef(n, k):
C = [[0 for x in range(k+1)] for x in range(n+1)]
# Calculate value of Binomial Coefficient in bottom up manner
for i in r... |
f9886344b8c61878d322680525f4f4afe8220042 | abbi163/MachineLearning_Classification | /KNN Algorithms/CustomerCategory/teleCust_plots.py | 873 | 4.125 | 4 | import matplotlib.pyplot as plt
import pandas as pd
df = pd.read_csv('E:\Pythoncode\Coursera\Classification_Algorithms\KNN Algorithms\CustomerCategory/teleCust1000t.csv')
# print(df.head())
# value_counts() function is used to count different value separately in column custcat
# eg.
# 3 281
# 1 ... |
29809d1ff13e65e1873762eff4292736dc8357aa | jordanyoumbi/Python | /function/function_arg_multiple.py | 531 | 3.703125 | 4 | # function qui prend 2 arguments en parametres
def clean_string(string, change_string):
replacement_string = ""
cleaned_string = string.replace(change_string, replacement_string)
return(cleaned_string)
goal = clean_string("Goal!!!!!!!", "!")
print(goal)
# function qui prend 3 arguments en parametres
def... |
b90611898fc38198839e38527a00826a340ff727 | jordanyoumbi/Python | /liste/Comprehension_liste.py | 712 | 4.03125 | 4 | # reduction du calcul à partir de fonction dejà defini
# exemple ci-dessous comment calculer la longueur des elements d' une liste
animals = ["Chien", "Tigre", "Lion", "vache", "Panda"]
animals_lengths = []
for animal in animals:
animals_lengths.append(len(animal))
print(animals_lengths)
# le code ci-dessous fai... |
8bf38aa84c4fa743e1e62de5dc82a7e78f59ef4f | jordanyoumbi/Python | /liste/Training_liste.py | 547 | 3.53125 | 4 | # exercice sur les comprehensions de listes
# pourcourir une liste et identifier ses colonnes
name_counts = {}
jules = open("legislators.csv", "r", encoding="utf-8")
legislators = jules.read()
for row in legislators:
gender = row[3]
year = row[7]
if gender =="F" and year > 1950:
name = row [1]
... |
b653a7f40d3d18f90733053a18d55b8bac940b39 | jordanyoumbi/Python | /les_dates/time.py | 1,455 | 3.828125 | 4 | # tout d' abord il faut recuperer le mudule time
# l' exemple ci-dessous affiche le nombre de seconde depuis 1970. date à le quelle les comptes ont commencé
import time
current_time = time.time()
print(current_time)
# utilisation de function gmtime() pour connaitre l' heure GMT
current_struct_time = time.gmtime(current... |
423d82d0f6248deff3e501763b90eee365757e17 | JimmyLamothe/chess_age | /get_html.py | 1,415 | 3.515625 | 4 | #Used to retrieve HTML page from internet
import sys
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen
def get_html(page_address,
basepath = 'html/',
filename = None,
overwrite = False,
module = 'requests'):
print(page_address)
... |
ac5923deb722b5f0925ea302f4f623fdae4f8d0a | KentonJack/LongPlay | /Recommendation.py | 406 | 3.53125 | 4 | def matrix_mul(a, b):
result = [[0] * len(b[0]) for i in range(len(a))]
for i in range(len(a)):
for j in range(len(b[0])):
for k in range(len(b)):
result[i][j] += a[i][k] * b[k][j]
return result
A = [[2, 0, 0]]
i = 0
with open('info/record.txt', 'r') as f:
for line in f.readlines():
A[0][i] = int(line.... |
ec8444c4562b05d3fc9fcc47d07e78abbab5077c | beenzino/shingu | /baseball.py | 1,849 | 3.5625 | 4 | c=0
while(c==0):
import random
a = ["0","0","0"]
a[0] = str(random.randint(1,9))
a[1] = a[0]
a[2] = a[0]
while(a[0]==a[1]):
a[1] = str(random.randint(1,9))
while(a[1]==a[2] or a[0]==a[2]):
a[2] = str(random.randint(1,9))
print("야구 게임을 시작합니다, 0을 입력하시면 언제든지 종료 가능합니다")
... |
fa930ca9e9bb949afea93e8db3345831fcf7de26 | nhthung/mcgill-uni | /COMP 321 - Programming Challenges/Assignment 3/grid_260793376.py | 2,769 | 3.90625 | 4 | '''
You are on an n×m grid where each square on the grid has a digit on it. From a given square that has digit k on it, a Move consists of jumping exactly k squares in one of the four cardinal directions. A move cannot go beyond the edges of the grid; it does not wrap. What is the minimum number of moves required to ge... |
491ffe454bdd5161ea332eb5114561b1a56b8e36 | sacheenanand/pythondatastructures | /ReverseLinkedList.py | 557 | 4.1875 | 4 | __author__ = 'sanand'
# To implement reverse Linked we need 3 nodes(curr, prev and next) we are changing only the pointers here.
class node:
def __init__(self, value, nextNode=None):
self.value = value
self.nextNode = nextNode
class LinkedList:
def __init__(self, head):
self.head = he... |
04dce36f9f552216ea548da767dbf306fc2de8e9 | mrvbrn/HB_challenges | /medium/code.py | 1,162 | 4.1875 | 4 | """TinyURL is a URL shortening service where you enter a URL such as https://leetcode.com/problems/design-tinyurl
and it returns a short URL such as http://tinyurl.com/4e9iAk.
Design the encode and decode methods for the TinyURL service. There is no restriction on how your encode/decode algorithm should work.
You jus... |
289820dd78f4cf13538bde92149ae03d3e93784c | mrvbrn/HB_challenges | /hard/patternmatch.py | 2,712 | 4.59375 | 5 | """Check if pattern matches.
Given a "pattern string" starting with "a" and including only "a" and "b"
characters, check to see if a provided string matches that pattern.
For example, the pattern "aaba" matches the string "foofoogofoo" but not
"foofoofoodog".
Patterns can only contain a and b and must start with a:
... |
d4ad295edf0681aca8be2e4ff2c0c89f46ab306a | mrvbrn/HB_challenges | /hard/active.py | 1,831 | 3.71875 | 4 | """Find window of time when most authors were active.
For example::
>>> data = [
... ('Alice', 1901, 1950),
... ('Bob', 1920, 1960),
... ('Carol', 1908, 1945),
... ('Dave', 1951, 1960),
... ]
>>> most_active(data)
(1920, 1945)
(Alice, Bob, and Carol were all active the... |
d576e6059e0f9f5c12fd8e6954cd50a00666b08d | mrvbrn/HB_challenges | /hard/prefix.py | 10,958 | 3.921875 | 4 | """Example code for modeling tries, and searching them by prefix.
Joel Burton <joel@joelburton.com>
"""
class LetterStack(object):
"""Simple letter-based stack based on a list, useful for tries.
Stacks can be built using a linked list or an array; we'll just
use the built-in Python list-type (array) for... |
17e7d572d777f3f6706521de99e3b5ca3ee175fc | solaaremu-pelumi/PVT-ML | /pvt_ml/GUI.py | 1,276 | 3.8125 | 4 | """This is the first page in the GUI of the app"""
import tkinter as tk
from tkinter import ttk
class my_frame(tk.Frame):
"""Frame to hold the design"""
def __init__(self,parent,*args,**kwargs):
super().__init__(parent,*args,**kwargs)
#Widgetsgit
use_label=ttk.Label(self... |
9c02efad543b57e9b03001eba63001ee10fd9672 | IrinaNizova/5_lang_frequency | /lang_frequency.py | 671 | 3.75 | 4 | from collections import Counter
import argparse
import re
def load_data(filepath):
with open(filepath, "r") as file_object:
return file_object.read()
def count_words(text):
match_patterns = re.findall(r'\b\w{2,25}\b', text.lower())
return Counter(match_patterns)
if __name__ == '__main__':
... |
322aa3bedd4ce2c7bdf80cd7bca5c5bc1b24b743 | dhruvag02/Pyhton | /distinctPairs.py | 1,030 | 3.5 | 4 | def isNotEmpty(a):
if len(a) == 0:
return True
else:
return False
def binarySearch(a, value):
low = 0
high = len(a) - 1
while low <= high:
mid = (low + high)//2
if a[mid] < value:
low = mid+1
elif a[mid] > value:
high ... |
0228e00df8dec90fd27cadd6bec19d9223071f68 | vibinash/vision | /image_processing/hough_line_transform/hough_lines.py | 1,121 | 3.5 | 4 | import cv2
import numpy as np
# Hough Transform is a popular technique to detect shape, if it can be
# represented in mathematical form
# line:
# Cartesian form: y = mx + b
# Parametric form: p = xcos(theta) + ysin(theta)
# p = perpendicular distance from orgin to line
# theta = angle formed by this perpendicular lin... |
0c39ff499615b06812f118c9b8b79e8997244be1 | kontok/clever_magic | /task_01_04.py | 274 | 3.703125 | 4 | x1 = int(input())
y1 = int(input())
x2 = int(input())
y2 = int(input())
x3 = int(input())
y3 = int(input())
a = (x2-x1)**2 + (y2-y1)**2
b = (x3-x2)**2 + (y3-y2)**2
c = (x1-x3)**2 + (y1-y3)**2
if (a == c+b) or (c == a+b) or (b == a+c):
print('yes')
else:
print('no')
|
33de3b08054f3265ae46f52923e0cf7178e6bb5f | kontok/clever_magic | /task_02_01.py | 378 | 3.546875 | 4 | def delete(chars, s):
s=(str(s))
s=s.lower()
for i in chars:
if s.find(i):
s = ''.join(s.split(i))
return s
def is_palindrome(s):
p=True
s = delete(' !?,.\'"', s)
a=0
b=len(s)-1
while a<b:
if s[a] != s[b]:
p=Fals... |
50bd3576574391666e1c60d9aaea2a27f3da2d18 | Brahma1212/testing123 | /remove-duplicate.py | 125 | 3.859375 | 4 | duplicates=[1,1,2,2,3,3,4,4,5,6,7]
empty=[]
for i in duplicates:
if i not in empty:
empty.append(i)
print(empty)
|
46189e97c45b2babf68350b3e1351eca9da02207 | andreaschiavinato/python_grabber | /examples/example_3.py | 891 | 3.5 | 4 | # The following code uses the sample grabber filter to capture single images from the camera.
# To capture an image, the method grab_frame is called. The image will be retrieved from the callback function passed
# as parameter to the add_sample_grabber method. In this case, the image captured is shown using the functio... |
ee73f52b7f99cc07cd49b826dbe48450fab2e72f | njustqiyu/deep-learning | /linear_unitQY.py | 1,314 | 3.59375 | 4 | #!/usr/bin/env python
# -*- coding:UTF-8 -*-
#author:qiyu,date:2018/5/2
from perceptronQY import Perceptron
#定义激活函数f
f=lambda x:x
class LinearUnit(Perceptron):
def __init__(self,input_num):
'''初始化线性单元,设置输入参数的个数'''
Perceptron.__init__(self,input_num,f)
def get_training_dataset():
'''
创造5个人的收入数据,作为训练样本
'''
... |
238df9849fe555fe2baeeaf331119b9cf41345e8 | wangweihao/PythonCookbook | /search_occur_num_more.py | 380 | 4.09375 | 4 | __author__ = 'wwh'
from collections import Counter
words = [
'look', 'into', 'he', 'she', 'is', 'my',
'you', 'into', 'hi', 'into', 'is', 'look',
'eyes', 'the', 'a'
]
#计数
word_count = Counter(words)
print(word_count)
#运算
word_count += word_count
print(word_count)
#获得出现次数最多的前3个值
top_three = word_count.most... |
082ca8fc38be54f03366478516d9075648c9512f | raufmca/NewRepo | /sumArray.py | 362 | 4.09375 | 4 |
#Sum of arrays function
def sumArray(lst1):
sum=0
for i in lst1:
sum = sum + i
print(f'Sum of list item = ', sum)
s = int(input("Enter the size of array " ))
lst1=[]
while s != 0:
i = int(input("Enter you number = "))
lst1.append(i)
s = s-1
sumArray(lst1)
print('End of program')
p... |
560459ddf49384a758c3bcfde15517ba99e44077 | shaikharshiya/python_demo | /fizzbuzzD3.py | 278 | 4.15625 | 4 | number=int(input("Enter number"))
for fizzbuzz in range(1,number+1):
if fizzbuzz % 3==0 and fizzbuzz%5==0:
print("Fizz-Buzz")
elif fizzbuzz % 3==0:
print("Fizz")
elif fizzbuzz % 5==0:
print("Buzz")
else:
print(fizzbuzz)
|
27ff13f6f44bc41437cec3ee3f53dd7f3e0b06ce | Columnrunner/day1 | /Day1_YunfeiMao.py | 2,002 | 4.0625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jun 26 22:22:10 2019
@author: SHAIL
"""
abcd = ['nintendo','Spain', 1, 2, 3]
print(abcd)
# Ex1 - Select the third element of the list and print it
print(abcd[2])
# Ex2 - Type a nested list with the follwing list elements inside list abcd mentioned above ... |
cc06f8221ea3533918bfc37e2d637945895af013 | 2371406255/PythonLearn | /15_filter.py | 460 | 3.765625 | 4 | #!/usr/bin/env python3
#coding:utf-8
#filter:过滤序列,接收一个函数和一个序列,filter把传入的函数依次作用于每个元素,根据返回True还是False决定保留还是丢弃
#删除掉偶数
def is_odd(n):
return n%2==1
arr = list(filter(is_odd,[1,2,3,4,5,6]))
print(arr)#[1, 3, 5]
#删除掉空字符
def not_empty(s):
return s and s.strip()
arr = list(filter(not_empty,['a','','c',None,' ']))
pr... |
814d9846600316450e097ef7ce0cb8f40d45efd1 | 2371406255/PythonLearn | /24_访问限制.py | 1,728 | 4.125 | 4 | #!/usr/bin/env python3
#coding:utf-8
#如果要让内部属性不被外部访问,可以在属性名称前加上两个下划线,这样就变成了私有变量,只能内部访问
class Student(object):
def __init__(self, name, score):
self.__name = name
self.__score = score
def print_score(self):
print('%s : %s' % (self.__name, self.__score))
stu = Student('BOBO', 90)
stu.pri... |
7fef85965ad45ea0fb3550725c42c51abb250829 | 2371406255/PythonLearn | /04_条件语句.py | 703 | 4.0625 | 4 | #!/usr/bin/env python3
#coding:utf-8
#条件判断
age = 20
if age > 18:
print('%d岁,成年了!' % age)#20岁,成年了!
#if...else...
if age > 18:
print('成年了')#成年了
else:
print('未成年')
#if...elif...else...
if age < 18:
print('未成年')
elif age > 80:
print('你老了')
else:
print('很年轻')#很年轻
#if简写:判断的值是非零数值,非空字符串,非空list等,就为... |
e077da7130bb05c4e020527e0f7c8200cddc1daa | 2371406255/PythonLearn | /30_多重继承.py | 739 | 3.671875 | 4 | #!/usr/bin/env python3
#coding:utf-8
#多重继承
class Animal(object):
pass
#大类
class Mammal(Animal):
pass
class Bird(Animal):
pass
#各种动物
class Dog(Mammal):
pass
class Bat(Mammal):
pass
class Parrot(Bird):
pass
class Ostrich(Bird):
pass
#我们要给动物加上Runnable和Flyable功能
class Runable(object):
def... |
f8732e9e7a5c1f056a3e2a3e6b3d089588a469b2 | Monicasfe/AAB_C | /Automata_comp.py | 2,736 | 3.828125 | 4 | # -*- coding: utf-8 -*-
class Automata:
def __init__(self, alphabet, pattern):
self.numstates = len(pattern) + 1
self.alphabet = alphabet
self.transitionTable = {}
self.buildTransitionTable(pattern)
def buildTransitionTable(self, pattern): #o pattern vem como ... |
1c2ba5b0c957997f88e9d16a6ce8560f70c75ddb | lina1/python-algorithm | /string_duplicate.py | 787 | 3.765625 | 4 | #!/usr/bin/env python
# -*- coding: utf-8 -*-
__author__ = 'lina'
__date__ = '16/4/18'
def get_first_single(string):
# 获取字符串中第一个只出现一次的字符的index
if not string:
return -1
length = len(string)
char_count = dict()
for index in range(0, length):
char = string[index]
# if strin... |
1b10ddfa348801f4d9a816e35f86f07d84229ac5 | AdinaFakih/python | /sets.py | 214 | 3.6875 | 4 | # myset = set()
# print(myset)
# myset.add(1)
# print(myset)
# myset.add(2)
# print(myset)
# myset.add(2) # No changes will be made
# print(myset)
mylist = [1,1,1,1,1,2,2,2,3,3,3]
print(set(mylist)) |
0911c405b07c6c3166f367c900ef7400800293c9 | viktornordling/adventofcode2020 | /07/solve.py | 1,846 | 3.625 | 4 | from math import prod
import re
import math
import string
def parse_contain(can):
if can.strip() == "no other bags.":
return {'amount': 0, 'bag_name': None}
amount = can.strip().split(" ")[0]
bag_name = " ".join(can.split(" ")[2:-1])
return {'amount': amount, 'bag_name': bag_name}
def rchop(s... |
01bcc3ce85f91b578f96aa2e21c1dc5cfee9efbe | joannachenyijun/yijun-1 | /PythonAlgorithm/464.SortInteger.py | 724 | 3.8125 | 4 | '''Given an integer array, sort it in ascending order. Use quick sort, merge sort, heap sort or any O(nlogn) algorithm.
'''
class solution:
#input array
#return array
def sortIntegers2(self,A):
self.quick(A, 0, len(A) - 1)
def quick(self, A, start, end):
if start >= end:
return
left, right = start, e... |
57ad1e768b53dd85018fbfbece246a9bdb33cb90 | joannachenyijun/yijun-1 | /PythonAlgorithm/159.MinRotatedArray.py | 897 | 3.578125 | 4 | '''Suppose a sorted array is rotated at some pivot unknown to you beforehand.
(i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2).
Find the minimum element.
Example
Given [4, 5, 6, 7, 0, 1, 2] return 0
Notice
You may assume no duplicate exists in the array.'''
class solution:
#input array
#ouput interger index
... |
b1643984e4bb2c6f946183ce02a1a3e13a9833ed | manmaha/utilities | /buttons.py | 920 | 3.703125 | 4 | import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BCM)
button_pin = 18
GPIO.setup(button_pin, GPIO.IN, pull_up_down=GPIO.PUD_DOWN)
#button_pin is pulled down
#connect the other pin to 3.3v
def button_pressed(button_pin,previous_state):
#returns (button state, previous state)
GPIO.setup(button_pin, GPIO.IN, pul... |
916bca341fe50462c410a72b0031e68ec0f88df0 | ZhiCheng0326/SJTU-Python | /Sum of odd numbers between 2 numbers.py | 278 | 3.828125 | 4 | def main():
i = input("Please enter the initial number:")
f = input("Please enter the last number:")
total = 0
l = []
for a in range(i,f+1):
if a % 2 != 0:
l.append(a)
total += a
print l
print total
main()
|
4902a5355d72e15199c2a517b23b7b992f0620e2 | ZhiCheng0326/SJTU-Python | /Summation series.py | 247 | 3.953125 | 4 | def main():
x = input("Please input a digit:")
list1= []
for i in range(1,x+1):
a = i ** i
list1.append(a)
print list1
for j in list1:
number = str(j)
print number + " " + "+",
main()
|
935e1104e9ab9a31d97e901da8fc42d4f05b8fab | laisdutra/BasicHTTPServer | /HTTPserver.py | 2,594 | 3.515625 | 4 | # UNIVERSIDADE FEDERAL DO RIO GRANDE DO NORTE
# DEPARTAMENTO DE ENGENHARIA DE COMPUTACAO E AUTOMACAO
# DISCIPLINA REDES DE COMPUTADORES (DCA0113)
# AUTOR: PROF. CARLOS M D VIEGAS (viegas 'at' dca.ufrn.br)
#
# SCRIPT: Base de um servidor HTTP
#
# importacao das bibliotecas
import socket
import os
# definicao do host e... |
ceaf6bc170ae84ed937891818b47f4c788af181e | yxiao1994/python_leetcode | /PartStack.py | 4,261 | 3.765625 | 4 | class CQueue(object):
# 两个栈实现队列
def __init__(self):
self.s1 = []
self.s2 = []
def appendTail(self, value):
self.s1.append(value)
def deleteHead(self):
if not self.s1 and not self.s2:
return -1
if not self.s2:
while self.s1:
... |
1019833fd62896c78e4b542d4c45335ad989a929 | A7xSV/Algorithms-and-DS | /Codes/Py Docs/For.py | 242 | 3.671875 | 4 | words = ['cat', 'window', 'defenestrate']
for w in words[:]: # Sliced copy of the list is useful when some modification is needed.
if len(w) > 6:
words.insert(0, w)
print words
for i in range(len(words)):
print i, words[i]
|
c21f73253780164661997fa29d873dec5a4803ce | A7xSV/Algorithms-and-DS | /Codes/Py Docs/Zip.py | 424 | 4.4375 | 4 | """ zip()
This function returns a list of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables.
The returned list is truncated in length to the length of the shortest argument sequence. """
x = [1, 2, 3, 4]
y = [5, 6, 7, 8]
print x
print y
zipped = zip(x, y)
... |
259d5b4312f1f619e60f7fc91dadc0300c01a036 | Mengziyang-Doing/pandaset-devkit | /python/pandaset/utils.py | 404 | 4.03125 | 4 | #!/usr/bin/env python3
import os
from typing import List
def subdirectories(directory: str) -> List[str]:
"""List all subdirectories of a directory.
Args:
directory: Relative or absolute path
Returns:
List of path strings for every subdirectory in `directory`.
"""
return [d.path ... |
5890859ef1e424accf5b5998ad3e1682ac0cd97e | JetSimon/Advent-of-Code-2020 | /Solutions/Day 6/day6.py | 495 | 3.515625 | 4 | inputRead = []
inputFile = open('input.txt', 'r')
currentGroup = []
groups = []
totalCount = 0
for line in inputFile:
stripped = line.rstrip()
if(stripped != ''):
currentGroup.append(stripped)
else:
groups.append(currentGroup)
currentGroup = []
groups.append(currentGroup)
for group i... |
6f0fdeba1d1d9b337a375070162007a3422220cd | BruceHi/leetcode | /month6-21/peakIndexInMountainArray.py | 693 | 3.5625 | 4 | # 852. 山脉数组的峰顶索引
from typing import List
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
left, right = 0, len(arr)-1
while left < right:
mid = left + right >> 1
if arr[mid] < arr[mid+1]:
left = mid + 1
else:
... |
df98c08e33dfb75bd906ef7800e17129925c6a9c | BruceHi/leetcode | /month5-21/preorder.py | 2,149 | 3.671875 | 4 | # 589. N 叉树的前序遍历
from typing import List
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
class Solution:
# def preorder(self, root: 'Node') -> List[int]:
# res = []
#
# def dfs(root):
# if not root:
# ... |
d6ba381d714589831432f5f17383defa421bd3e7 | BruceHi/leetcode | /binarySearch/findMin.py | 1,827 | 3.75 | 4 | # 153.寻找旋转排序数组中的最小值
from typing import List
class Solution:
# def findMin(self, nums: List[int]) -> int:
# left, right = 0, len(nums) - 1
# while left < right:
# mid = left + right >> 1
# if nums[mid] > nums[right]:
# left = mid + 1
# else:
#... |
21a6e7728ad52a244c16a0bb06ade976df402d9b | BruceHi/leetcode | /month2/removePalindromeSub.py | 316 | 3.703125 | 4 | # 1332. 删除回文子序列
class Solution:
def removePalindromeSub(self, s: str) -> int:
if s == s[::-1]:
return 1
return 2
obj = Solution()
s = "ababa"
print(obj.removePalindromeSub(s))
s = "abb"
print(obj.removePalindromeSub(s))
s = "baabb"
print(obj.removePalindromeSub(s))
|
2816843a799ef7a0503197684d420325b1a32177 | BruceHi/leetcode | /month9/flatten.py | 1,638 | 3.734375 | 4 | # 430. 扁平化多级双向链表
# Definition for a Node.
import pkg_resources
class Node:
def __init__(self, val, prev, next, child):
self.val = val
self.prev = prev
self.next = next
self.child = child
class Solution:
# def flatten(self, head: 'Node') -> 'Node':
# dummy = Node(0, N... |
82235a171ec1cca3fe07301f0cb453355e8684e7 | BruceHi/leetcode | /month11/findUnsortedSubarray.py | 1,018 | 3.75 | 4 | # 581. 最短无序连续子数组
from typing import List
class Solution:
def findUnsortedSubarray(self, nums: List[int]) -> int:
n = len(nums)
nums_sort = sorted(nums)
left = 0
right = n - 1
while left <= right and nums[left] == nums_sort[left]:
left += 1
while left <= ... |
522fd172c04f5766ce643403c640adb9cb4be834 | BruceHi/leetcode | /month3/isSubStructure.py | 2,062 | 3.84375 | 4 | # 剑指offer 26.树的子结构
# 约定空树不是任意一个树的子结构
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 错误,
# def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
# # 空树是相同的,这是判断两个树一模一样的,而不是判断子结构,[10,12,6,8,3,11],[10,12,6,8]
#... |
3edc817a68cc1bbf028c1594a2b9b9c78bb4a879 | BruceHi/leetcode | /month1/MaxQueue.py | 1,378 | 4.1875 | 4 | # 剑指 offer 59-2:队列的最大值
from collections import deque
# class MaxQueue:
#
# def __init__(self):
# self.queue = deque()
#
# def max_value(self) -> int:
# if not self.queue:
# return -1
# return max(self.queue)
#
# def push_back(self, value: int) -> None:
# self.qu... |
e3e35e99d841a156463aecf21c7b932b1a5e0071 | BruceHi/leetcode | /month6/topKFrequent.py | 2,258 | 3.546875 | 4 | # 前 K 个高频元素
from typing import List
from collections import Counter
import heapq
class Solution:
# def topKFrequent(self, nums: List[int], k: int) -> List[int]:
# count = Counter(nums)
# return sorted(count, key=count.get, reverse=True)[:k]
# def topKFrequent(self, nums: List[int], k: int) ->... |
b4c8cd932bf8b315030522c2bd8b3e3a3fe7100d | BruceHi/leetcode | /binarySearch/myPow.py | 2,693 | 3.578125 | 4 | # 剑指 offer 16. 数值的整数次方
class Solution:
# def myPow(self, x: float, n: int) -> float:
# return pow(x, n)
# return x**n
# def myPow(self, x: float, n: int) -> float:
# if n == 1:
# return x
# if n == 0:
# return 1.0
# if n == -1:
# retur... |
7e60f4ea5b576cd04c9f088d414e79dc8cbb79e6 | BruceHi/leetcode | /month3/canPermutePalindrome.py | 411 | 3.5625 | 4 | # 面试题 01.04.回文排列
from collections import Counter
class Solution:
def canPermutePalindrome(self, s: str) -> bool:
counter = Counter(s)
count = 0
for val in counter.values():
if val & 1:
count += 1
if count > 1:
return False
ret... |
6df8f4f4784bda17dbf9223283dea24731d96f67 | BruceHi/leetcode | /Array/11rotateImage.py | 1,560 | 3.9375 | 4 | # 将图像顺时针旋转 90 度。
# 观察规律
# def rotate(matrix):
# n = len(matrix)
# matrix.reverse()
#
# for j in range(n): # 提取元素
# temp = [matrix[i][j] for i in range(n)]
# matrix.append(temp)
#
# for i in range(n-1, -1, -1): # 删除元素
# matrix.pop(i)
# def rotate(matrix):
# matrix[:] = ma... |
1489f4add9c1dbde1a515242fa48023aee640751 | BruceHi/leetcode | /LinkedList/reorderList.py | 3,177 | 3.796875 | 4 | # 143. 重排链表
from typing import List
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
# 中心节点,翻转,拼接
# def reorderList(self, head: ListNode) -> None:
# slow = fast = dummy = ListNode(0)
# dummy.next = head
# while ... |
2b17dbafcf8729f1d2b274d85c2d1d052e3f7626 | BruceHi/leetcode | /month11/sumNumbers.py | 1,436 | 3.640625 | 4 | # 129. 求根到叶子节点数字之和
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 错误解法:没法定位到叶子节点。
# def sumNumbers(self, root: TreeNode) -> int:
#
# res = []
#
# def dfs(root, num):
# if not root:
# ... |
58a73d18cba360cbba63a05da587dbd72f93fc85 | BruceHi/leetcode | /DFS/findCircleNum.py | 6,246 | 3.6875 | 4 | # 朋友圈
# 省份数量
from typing import List
# class Solution:
# # 邻接矩阵的深度优先遍历 看不懂
# def findCircleNum(self, M: List[List[int]]) -> int:
# n = len(M)
# visited = [0] * n
#
# # 按照诸如 [1, 2], [2, 3], [3, 5] 等可以标记 1, 2, 3,5 索引处为 1.
# def DFS(i):
# for j in range(n):
# ... |
4f311ffb537a9f0fac1386c8860d0647582de4bc | BruceHi/leetcode | /month12/divide.py | 935 | 3.625 | 4 | # 29.两数相除
class Solution:
# def divide(self, dividend: int, divisor: int) -> int:
# res = int(dividend / divisor)
# if -2**31 <= res <= 2**31-1:
# return res
# return 2**31-1
# def divide(self, dividend: int, divisor: int) -> int:
# if dividend * divisor > 0:
# ... |
66138da67a9aa3f230ce9f864d5b55eb38023586 | BruceHi/leetcode | /month11/permute.py | 3,061 | 3.640625 | 4 | # 46. 全排列,没有重复的数字
from typing import List
from itertools import permutations
class Solution:
# 回溯
# def permute(self, nums: List[int]) -> List[List[int]]:
# res = []
# n = len(nums)
#
# def dfs(nums, cur):
# if len(cur) == n:
# res.append(cur)
# ... |
584d2d2926aac7acffa0fa5f2ad4ba0d1e6a6278 | BruceHi/leetcode | /month8/rotate.py | 1,231 | 3.84375 | 4 | # 旋转矩阵
from typing import List
class Solution:
# def rotate(self, matrix: List[List[int]]) -> None:
# # matrix.reverse()
# matrix[:] = map(list, zip(*matrix[::-1]))
# def rotate(self, matrix: List[List[int]]) -> None:
# # matrix[::] = zip(*matrix[::-1])
# a = list(zip(matrix[:... |
955c78d571a9435ad73640a015cdaf6f76328a9c | BruceHi/leetcode | /month4/lengthLongestPath.py | 2,861 | 3.59375 | 4 | # 388.文件的最长绝对路径
from collections import defaultdict
class Solution:
# def lengthLongestPath(self, input: str) -> int:
# res = 0
# depth_length_map = {-1: 0}
# # 按照顺序来的,所以不担心新的路径会覆盖原有的
# for line in input.split('\n'):
# depth = line.count('\t')
# # 每行制表符(空格)最... |
72739ed175c389d74b8da34435f86a16c99d8fd6 | BruceHi/leetcode | /month6-21/judgeSquareSum.py | 1,127 | 3.65625 | 4 | # 633. 平方数之和
from math import sqrt
class Solution:
# def judgeSquareSum(self, c: int) -> bool:
# nums = [x*x for x in range(int(sqrt(c))+1)]
# set_nums = set(nums)
# for num in nums:
# if c-num in set_nums:
# return True
# return False
# 双指针
# d... |
ff2dd6d3d7bcf549387843cd90478362d95eb8e6 | BruceHi/leetcode | /month12/isPowerOfThree.py | 1,107 | 4.0625 | 4 | # 326. 3 的幂
from math import log
class Solution:
# # 递归
# def isPowerOfThree(self, n: int) -> bool:
# if n == 1:
# return True
# if not n:
# return False
# if n % 3:
# return False
# return self.isPowerOfThree(n//3)
# 迭代
def isPowerO... |
97249980777ff838856e4ff689a4a62047dbcaf5 | BruceHi/leetcode | /month1/trap.py | 1,562 | 3.625 | 4 | # 42. 接雨水
# 与 largestRectangleArea 相似
from typing import List
class Solution:
# 构建递减(包括相同的)栈,遇见大的就弹出去
# def trap(self, height: List[int]) -> int:
# res, stack = 0, []
# for i, num in enumerate(height):
# while stack and num > height[stack[-1]]:
# idx = stack.pop()
... |
3ea3fe02a309b8b7dd4b48d530d99fdd26257745 | BruceHi/leetcode | /grok/quicksort.py | 7,894 | 3.75 | 4 | # 快速排序(因为快,所以叫这个名字),要求原地排序
# 递归,非原地排序(不太合适)
# def quicksort(nums):
# if len(nums) < 2: # 包括 1 和 0 的情况
# return nums
# pivot = nums[0] # 选取第一个为基线条件,也可以选择最后一个
# less = [i for i in nums[1:] if i <= pivot]
# greater = [i for i in nums[1:] if i > pivot]
# return quicksort(less) + [pivot] + qui... |
652cf776936eb888b53f85cd45390403f8ce28db | BruceHi/leetcode | /month12-21/superPow.py | 1,377 | 3.65625 | 4 | # 372. 超级次方
from typing import List
class Solution:
# 超时
# def superPow(self, a: int, b: List[int]) -> int:
# num = 0
# for n in b:
# num = num * 10 + n
# return a ** num % 1337
# 快速幂 超时
# def superPow(self, a: int, b: List[int]) -> int:
# def power(x, y):
... |
75ab64c2c8fb273d494f53835992c627be34d051 | BruceHi/leetcode | /month3/lemonadeChange.py | 1,529 | 3.78125 | 4 | # 860. 柠檬水找零
from typing import List
class Solution:
# def lemonadeChange(self, bills: List[int]) -> bool:
# count5, count10 = 0, 0
# for bill in bills:
# if bill == 5:
# count5 += 1
# elif bill == 10:
# if count5 == 0:
# ... |
c12a78a64c19a88eeedaca4e54f0bef52715bb43 | BruceHi/leetcode | /DFS/generateParenthesis.py | 5,853 | 3.59375 | 4 | # 括号生成
from typing import List
class Solution:
# # 原始解法,不太好
# def generateParenthesis(self, n: int):
# res = set()
#
# def DFS(s, c, left, right): # s: 当前拼接到的字符串,c:传入的括号
# if len(s) == 2 * n:
# res.add(s)
# return
#
# s += c
... |
2cf1017d544db7c2389726d4468ca65201788d4f | BruceHi/leetcode | /month3/verifyPostorder.py | 638 | 3.9375 | 4 | # 剑指 offer 33.二叉搜索树的后序遍历序列
from typing import List
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def dfs(left, right):
if left >= right:
return True
root = postorder[right]
mid = left
while postorder[mid] < root:
... |
6a4d7784b455c699c8f41eb252a27b9c2a64b77e | BruceHi/leetcode | /month1/checkPossibility.py | 832 | 3.625 | 4 | # 655. 非递减数列
from typing import List
class Solution:
def checkPossibility(self, nums: List[int]) -> bool:
changed = False
for i in range(len(nums)-1):
if nums[i] > nums[i+1]:
if changed:
return False
changed = True
#... |
0e977ce63c8e0e46615d7f90042431e8276ede74 | BruceHi/leetcode | /month3/addDigits.py | 460 | 3.640625 | 4 | # 258. 各位相加
class Solution:
def addDigits(self, num: int) -> int:
def get_nums(num):
res = 0
while num:
res += num % 10
num //= 10
return res
if num < 10:
return num
res = get_nums(num)
while res >= 10:
... |
59643b32b20b675745daeb327ef70660e0f1e430 | BruceHi/leetcode | /month12/reverseLeftWords.py | 270 | 3.734375 | 4 | # 剑指 offer 58-2.左旋转字符串
class Solution:
def reverseLeftWords(self, s: str, n: int) -> str:
return s[n:] + s[:n]
obj = Solution()
s = "abcdefg"
k = 2
print(obj.reverseLeftWords(s, k))
s = "lrloseumgh"
k = 6
print(obj.reverseLeftWords(s, k))
|
3a44ec0068bcca1af854e071b5a01868d93d679c | BruceHi/leetcode | /month7/searchInsert.py | 908 | 3.796875 | 4 | # 搜索插入位置
from typing import List
import bisect
class Solution:
# def searchInsert(self, nums: List[int], target: int) -> int:
# return bisect.bisect_left(nums, target)
# def searchInsert(self, nums: List[int], target: int) -> int:
# return bisect.bisect_left(nums, target)
def searchInser... |
c454efbc05cf6d8231e6807312be9d71ccd9cf58 | BruceHi/leetcode | /month12/findNumberIn2DArray.py | 1,823 | 3.84375 | 4 | # 剑指 offer 04. 二维数组中的查找
# 与 240. 搜索二维矩阵 II searchMatrix 一样
from typing import List
class Solution:
# def findNumberIn2DArray(self, matrix: List[List[int]], target: int) -> bool:
# if not matrix:
# return False
# m, n = len(matrix), len(matrix[0])
# i, j = m-1, 0
# # whi... |
a22fb70a8d897b1764f4a1fffd97c6ce72edab55 | BruceHi/leetcode | /other/maxArea.py | 1,892 | 3.625 | 4 | # 盛最多水的容器
# def maxArea(height):
# left = 0
# right = len(height) - 1
# area = 0
# while left < right: # 低的移动,木桶盛水多少取决于最短的那个
# if height[left] >= height[right]:
# area = max(area, height[right] * (right-left))
# right -= 1
# else:
# area = max(area, h... |
53d86618be06468d738d16539864f2d425fe507b | BruceHi/leetcode | /month8-21/isPrefixString.py | 814 | 3.625 | 4 | from typing import List
class Solution:
# def isPrefixString(self, s: str, words: List[str]) -> bool:
# return ''.join(words).startswith(s)
def isPrefixString(self, s: str, words: List[str]) -> bool:
i = 0
for word in words:
n = len(word)
if s[i:n+i] != word:
... |
613302288e873e5389c81681278d6898c5510d38 | BruceHi/leetcode | /Array/removeDuplicates.py | 2,968 | 3.59375 | 4 | # 失败
# def removeDuplicates(nums):
# for i in range(len(nums) - 2):
# m = i + 1
# for j in range(m, len(nums)):
# if nums[i] == nums[j]:
# nums.remove(nums[j])
# if nums[-1] == nums[-2]:
# nums.remove(nums[-1])
# 从排序数组中删除重复项
# def removeDuplicates(nums):
# ... |
4192e51a0b5c3473206a8dacbb8aa42f7d43b0f6 | BruceHi/leetcode | /month11/hammingDistance.py | 476 | 3.78125 | 4 | # 461.汉明距离
class Solution:
# def hammingDistance(self, x: int, y: int) -> int:
# dist = x ^ y
# res = 0
# while dist:
# res += 1
# dist &= dist - 1
# return res
# def hammingDistance(self, x: int, y: int) -> int:
# return bin(x ^ y).count('1')
... |
234bbcfc1eaae78c7f1da50312404d0332b313c6 | BruceHi/leetcode | /month12/runningSum.py | 865 | 3.6875 | 4 | # 1480. 一维数组的动态和
from typing import List
class Solution:
# def runningSum(self, nums: List[int]) -> List[int]:
# res = [0]
# for num in nums:
# res.append(res[-1] + num)
# return res[1:]
# # 修改 nums 的值,这样是错误的,边运行边解包
# def runningSum(self, nums: List[int]) -> List[int]:... |
dd0d8ca77f1de34a52a741563d9c5dca0dbcfe40 | BruceHi/leetcode | /Tree/isSameTree.py | 1,147 | 3.84375 | 4 | # 相同的树
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# 先序遍历
# def isSameTree(self, p: TreeNode, q: TreeNode) -> bool:
#
# def preorder(root):
# if not root:
# ... |
3cf0a3f3c1a9b21735d80f5199ad7699e53ea50e | BruceHi/leetcode | /queue/MyCircularQueue.py | 9,350 | 4.03125 | 4 | # 设计循环队列
# # 这种方法没有达到空间的循环利用,不太好。
# class MyCircularQueue:
#
# def __init__(self, k: int):
# """
# Initialize your data structure here. Set the size of the queue to be k.
# """
# self.queue = [] # 使用可扩展的列表,才不会出现溢出问题,妙啊。
# self.capacity = k # 队列容量(数组长度)
#
# def enQueue(... |
93bcc701b30e3b1061d11b8d82c85d464ad920c1 | BruceHi/leetcode | /month8/merge.py | 4,438 | 3.9375 | 4 | # 合并两个有序数组到 nums1
# 面试题 10.01. 合并排序的数组
from typing import List
class Solution:
# 递归
# def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
# """
# Do not return anything, modify nums1 in-place instead.
# """
# def merge_two(nums1, nums2):
# i... |
281d2dd7982ececea09b887d6b495209e07a3f0e | BruceHi/leetcode | /month6-21/largestOddNumber.py | 342 | 3.5 | 4 | class Solution:
def largestOddNumber(self, num: str) -> str:
for i in range(len(num)-1, -1, -1):
if int(num[i]) & 1:
return num[:i+1]
return ''
s = Solution()
num = "52"
print(s.largestOddNumber(num))
num = "4206"
print(s.largestOddNumber(num))
num = "35427"
print(s.l... |
ad440ed2075442df0c269b2354a57b7ce26b0154 | BruceHi/leetcode | /month11-21/detectCapitalUse.py | 340 | 3.5 | 4 | # 520. 检测大写字母
class Solution:
def detectCapitalUse(self, word: str) -> bool:
# return word in (word.upper(), word.capitalize(), word.lower())
return word.isupper() or word.islower() or word.istitle()
s = Solution()
word = "USA"
print(s.detectCapitalUse(word))
word = "FlaG"
print(s.detectCapitalUse... |
867b0c8bd24505a9b0674e62b0c8ecbe1b719669 | BruceHi/leetcode | /bitOperate/missingNumber.py | 2,038 | 3.59375 | 4 | # 给定一个包含 0, 1, 2, ..., n 中 n 个数的序列,找出 0 .. n 中没有出现在序列中的那个数。
from functools import reduce
from operator import ixor
from typing import List
class Solution:
# 数学方法
# def missingNumber(self, nums) -> int:
# n = len(nums)
# return n * (n+1) // 2 - sum(nums)
# 按位异或
# def missingNumber(self,... |
434f6904c35a4608b7e55b68dfdc4f21b78d15c2 | BruceHi/leetcode | /month12/movingCount.py | 2,200 | 3.515625 | 4 | # 剑指 offer 13. 机器人的运动范围
# BFS 广度优先搜索
from collections import deque
class Solution:
# def movingCount(self, m: int, n: int, k: int) -> int:
# def digit_sum(n):
# res = 0
# while n:
# res += n % 10
# n //= 10
# return res
#
# qu... |
4512966968955e3d103045f2d9ed9c3125318b49 | BruceHi/leetcode | /month1/search4.py | 771 | 3.828125 | 4 | # 剑指 offer 53-1. 在排序数组中查找数字
from typing import List
import bisect
class Solution:
# def search(self, nums: List[int], target: int) -> int:
# left = bisect.bisect_left(nums, target)
# if left == len(nums) or nums[left] != target:
# return 0
# right = bisect.bisect(nums, target)
... |
d0247f858e0cc158b6152434c53a3c1b84a3d333 | BruceHi/leetcode | /month8/recoverTree.py | 1,495 | 3.625 | 4 | # 恢复二叉搜索树
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
# 递归 只会显式中序遍历
def recoverTree(self, root: TreeNode) -> None:
def inorder(root):
if not root:
return... |
5306cae0d27ec35a00764050f48089cf8d389098 | BruceHi/leetcode | /month8/removeElement.py | 1,086 | 3.75 | 4 | # 移除元素
from typing import List
class Solution:
# def removeElement(self, nums: List[int], val: int) -> int:
# try:
# while True:
# nums.remove(val)
# except ValueError:
# return len(nums)
# def removeElement(self, nums: List[int], val: int) -> int:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.