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 |
|---|---|---|---|---|---|---|
b9e8f2c8b94c1c64609d5fcf7b295812c2cc5c97 | fluent93/Practice | /spiral_array.py | 891 | 3.546875 | 4 | __author__ = 'changhan.ryu'
input_str1, input_str2 = input("input the number").split()
var1 = int(input_str1)
var2 = int(input_str2)
board = []
row_index = 0
col_index = 0
whole_num_index = 0
row = [x for x in range(var1)]
col = [y for y in range(var2)]
whole_num = [z for z in range(var1 * var2)]
# make a dull M*N m... |
031c1d3f3c13973cd35f44fe1d0c262e3920623c | kurofito/Knights_Tour_Puzzle | /knights_tour.py | 8,585 | 3.78125 | 4 | class Knight:
def __init__(self):
self.dimension = [0, 0]
self.current_position = [0, 0]
self.cell_size = None
self.board = None
self.X_sign = None
self.visited_mark = None
self.border = None
self.total_moves = 0
self.available_moves ... |
d2e113be4619cdd2b389dd8066e067c2ee1f1440 | gsmcclellan/sorting_algorithms | /merge.py | 749 | 4.34375 | 4 | """
A merge sort recursively splits a list into smaller lists until they
have a len of one or zero, then combine each list into a single
sorted list
"""
def merge_sort(nums):
if len(nums) > 1:
first_half = nums[:len(nums)//2]
second_half = nums[len(nums)//2:]
first_half = merge_sort(first_half)
second_h... |
c334fe480d0721158b5dcf854c60ca0b03c0b508 | Guilhermeslucas/MC886-Machine-Learning-Class | /LR.py | 7,500 | 3.5 | 4 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.feature_selection import RFE
from sklearn.metrics import r2_score, mean_squared_error
from sklearn.model_selection import cross_val_predict, cross_val_score
def lin_reg(regressor, X_train, y_train, X_test, y_test):
"""
Function... |
c1216918c5c9a9d02cec5e0e966e9fa19f2b7de0 | anand1431/Major-project-python | /finalcode1.py | 980 | 3.765625 | 4 |
import cv2
from matplotlib import pyplot as plt
path = r'C:\AI\apple.png' # Reading the image from the path
img = cv2.imread(path,cv2.IMREAD_UNCHANGED)
print('image_shape:',img.shape) #shape of original image
scale_percent = 200 #fixing scaling percent
width = int(img.shape[1] * scale_percent / 100) #scaling the w... |
a7b2d24798b7ac4186e6b1dc8bc25f4a9c582f71 | anadeangelo/pdf_crop | /croppdfpage.py | 1,655 | 3.546875 | 4 | # -*- coding: utf-8 -*-
"""
This script splits scanned pdf pages with two actual pages gathered in one (horizontally).
It returns a single new pdf file with the split pages placed in correct order.
This can be usefull if you have pdf files of scanned old books and need to read them in an e-book reader like kindle.
"mo... |
33579d9a2d351a6a33f82b708c68be6233c45afb | DrSneus/cse-20289-sp21-examples | /lecture09/is_anagram.py | 2,111 | 4.1875 | 4 | #!/usr/bin/env python3
import os
import sys
# Functions
def usage(status=0):
print(f'''Usage: {os.path.basename(sys.argv[0])} [flags]
-i Ignore case distinctions
This program reads in two words per line and determines if they are anagrams.
''')
sys.exit(status)
def count_letters(string):
''' Retur... |
14b52d289963322819ce0cdf4baf3122b9354fa5 | DrSneus/cse-20289-sp21-examples | /lecture10/exam01_stats.py | 1,965 | 3.828125 | 4 | #!/usr/bin/env python3
import csv
import requests
# Constants
URL = 'https://yld.me/raw/dS03'
POINTS = [5]*6
MAX = sum(POINTS)
# Fetch data
data = requests.get(URL).text.splitlines() # Review: requests.get
# Compute individual scores (Imperative)
scores = []
for student in csv.reader(data): ... |
7946883a88c19520b7527323f4b5c43a3b0c42cd | jemarsha/leetcode_shenanigans | /Random_problems/first_unique_element.py | 419 | 3.765625 | 4 | def list_first(lst): #return the first unique one which would be
long = []
for i in range(len(lst)): # dont do minus one unless you don't need the last element in the list
if lst[i] in long:
long.remove(lst[i])
else:
long.append(lst[i])
return long[0]
if __name... |
6d292fb6ba7cbb0beed8e0f13fdec68ff066fc98 | jemarsha/leetcode_shenanigans | /Sorting_Algos/merge_sort.py | 857 | 4.0625 | 4 | def merge_sort(arr):
if len(arr) < 2:
return arr
#mid = len(arr)/2
mid = len(arr) //2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])
return merge(left,right)
def merge(l_arr,r_arr):
if not len(l_arr) or not len(r_arr):
return l_arr or r_arr
result = []... |
0b777077897ac2ae8fc9bea47dae6853cafd31fd | jemarsha/leetcode_shenanigans | /Random_problems/Merged_k_linked_lists.py | 1,138 | 4.375 | 4 | #from typing import List
class Node:
def __init__(self,value):
self.value = value
self.next = None
def merge_lists(lists):
"""
This function merges sorted linked lists- Reads the values in one at a time into a list O(kn). Then
sorts them O(nlogn). Then puts them into a linked list (... |
41dd31be7b34644a340088d2e23f36f295138c1c | ekeesec33/CircuitPython | /photointerrupter.py | 1,263 | 3.703125 | 4 | import board
from digitalio import DigitalInOut, Direction, Pull
import time
button = DigitalInOut (board.D7)
button.direction = Direction.INPUT # is an input because we are finding the output of the number of counts
button.pull = Pull.UP #pulls the button up in order to
now = True
later = True
# establishe... |
5442d1cd5661c9d3b6f22f31040520f259577b30 | andrewkoman/EZEN_20190810 | /calculator/controller.py | 617 | 3.578125 | 4 | from calculator.model import CalculatorModel
class CaculatorController:
def __init__(self):
num1 = int( input("첫번째 값 : \n"))
num2 = int(input("두번째 값 : \n"))
# op = input("연산자 입력 : \n")
self.calc = CalculatorModel(num1, num2)
def exe(self):
op = input('연산자 입력 : ')
... |
81ade07d0881570c4d1ddc424c107c9e2e51dfef | nicecoolwinter/note | /python/data/python_book_slides/code_5/Person_2.py | 756 | 4.1875 | 4 |
class Person():
HI_STR = 'Hi, I am '
def __init__(self, name, age):
self.name = name
self.age = age
def say_hello(self):
print('Hello, I am ' + self.name)
def say_hi(self):
print(Person.HI_STR + self.name)
def __str__(self):
... |
89c59bb5c8bc869ab6ec9285dbe999a66d5f4a63 | nicecoolwinter/note | /python/data/python_book_slides/code_1_2/numpy_ex2.py | 536 | 3.578125 | 4 |
# -*- coding: utf-8 -*-
import numpy as np
a = np.arange(5)
print("Element's type is", a.dtype)
# 維度
print("Shape is", a.shape)
print()
# 矩陣
from numpy import array, arange
m1 = array([[7, 8, 9], arange(3), [4, 5, 6]])
print("Element's type is", m1.dtype)
print("Shape is", m1.shape)
print(m1)
pri... |
d9263fe3a7c61e75801a5287f95c62da9858605d | nicecoolwinter/note | /python/data/python_book_slides/code_1_2/fact_exception.py | 667 | 3.859375 | 4 |
# -*- coding: utf-8 -*-
def fact(n):
if n < 0:
raise ValueError('Argument must be non-negative')
result = 1
for i in range(1, n+1):
result *= i
return result
while True:
try:
s = input('input n: ')
sn = int(s)
f = fact(sn)
except TypeEr... |
bf3a43b7f372c346fc7f0b6aba55cbdba9dc0724 | nicecoolwinter/note | /python/data/python_book_slides/code_5/Person_property.py | 1,128 | 3.90625 | 4 |
from datetime import datetime
class Person():
def __init__(self, name, birthyear):
self._name = name
self._birthyear = birthyear
def get_birthyear(self):
return self._birthyear
def set_birthyear(self, v):
self._birthyear = v
def de... |
9a05a0ab1014fb0fc48afe25706fa3818610fb61 | nicecoolwinter/note | /python/data/python_book_slides/code_5/unique_set.py | 239 | 3.921875 | 4 |
li = (3, 1, 'a', 'Amy', 1, 3, 5, 'a')
def unique(iterable):
result = []
for x in iterable:
if x not in result:
result.append(x)
return result
print(unique(li))
print()
print(set(li))
|
c9ac84d0d5b45b22bb4da47fc7590a8514e3db7e | nicecoolwinter/note | /python/data/python_book_slides/code_4/m99_format.py | 550 | 3.796875 | 4 |
for y in range(1, 9+1):
for x in (2, 3, 4, 5):
print('%2d x%2d = %2d ' % (x, y, x*y), end='')
print()
print()
for y in range(1, 9+1):
for x in (6, 7, 8, 9):
print('%2d x%2d = %2d ' % (x, y, x*y), end='')
print()
# def p99(li):
# for y in range(1, 9... |
56853e0e40c6f248ceb2d7052eaf7236ca27c7dc | FuteLuo/battleship | /Computer.py | 6,032 | 3.984375 | 4 | import random
from Board import Board
from Ship import Ship
from Tile import Tile
class Computer:
def __init__(self, difficulty):
"""
Default Constructor
Parameters: n/a
Returns: n/a
Preconditions: n/a
Postconditions: A Computer object is created with a... |
d44174892c522f237cfde1f2f1e7d644083f1ec8 | clemsos/db-debutants | /music/4-music_import_artists.py | 653 | 3.5 | 4 | # -*- coding: utf-8 -*-
import csv
import sqlite3
db = sqlite3.connect('../chinook/chinook.db')
print 'Database connectée'
with open('music.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',')
for i, row in enumerate(csv_reader):
if i != 0:
artist_name = row[2]
... |
217f1efc8501abc9a20b2a79d83bd8df41de9960 | clemsos/db-debutants | /scripts/7-delete-record.py | 299 | 3.609375 | 4 | import sqlite3
db = sqlite3.connect('shoes_test.db') # Open a database File
print 'Database opened'
def delete_record():
db.execute(''' DELETE from shoes WHERE ID = 1 ''')
db.commit()
print 'Deleted'
delete_record()
print '----------------------'
db.close()
print ' Database Closed'
|
9831e8179785079dea0219ff199ffac024c2e579 | takuti/HackerRank | /dynamic-programming/maxsubarray/solution.py | 976 | 3.734375 | 4 | #!/bin/python
import math
import os
import random
import re
import sys
#
# Complete the 'maxSubarray' function below.
#
# The function is expected to return an INTEGER_ARRAY.
# The function accepts INTEGER_ARRAY arr as parameter.
#
def maxSubarray(arr):
max_subarray = max(arr)
if max_subarray > 0:
s ... |
244c18a20cf7f603e7d81304a7cf72c84cc994db | DigitalDataLab/ASN16-18_CitationNetwork | /script/03.02.populateDB.sectors.py | 2,384 | 3.59375 | 4 | import sqlite3
from sqlite3 import Error
from glob import glob
import json
import csv
import sys
import os
import conf
def create_connection(db_file):
""" create a database connection to the SQLite database
specified by db_file
:param db_file: database file
:return: Connection object or None
"""
conn = None
t... |
526db632a0a6844f5849eb225e81db0d1075f922 | ddubson/lets-python | /cryptography/des_crypto.py | 871 | 3.625 | 4 | # DES - Data Encryption Standard (Symmetric Key)
from Crypto.Cipher import DES
from Crypto import Random
# Initialization Vector (8 bytes)
init_vector = Random.new().read(DES.block_size)
# Output Feedback Mode (1 of 5 available)
mode = DES.MODE_OFB
def des_encrypt(key, plaintext):
cipher = DES.new(key, mode, in... |
70826eefc7345f3d96c93173f0b17a4b5c1123e5 | Sumanpal3108/21-days-of-programming-Solutions | /Day14.py | 371 | 4.625 | 5 | str1 = input("Enter any String: ")
str2 = input("Enter the substring you want to replace: ")
str3 = input("Enter the string you want to replace it with: ")
s = str1.replace(str2,str3)
print("The original string is: ",str1)
print("The substring you want to replace: ",str2)
print("The string you want to use instead... |
35d63b5e2f65b675c138fcc477b9a4d0185f33c7 | Sumanpal3108/21-days-of-programming-Solutions | /21daysprogrammingDay1.py | 683 | 4.15625 | 4 | import math
a = float(input("Enter the coefficient a: "))
b = float(input("Enter the coefficient b: "))
c = float(input("Enter the coefficient c: "))
print("The quadratic equation is: {}X2 + {}X + {} = 0".format(a,b,c))
d = b**2 - 4*a*c
print('The value of d is: ',d)
if d>0:
r1 = (-b + math.sqrt(d))/(... |
ed218c4ee622a8ae358b43ff4458857b418a7012 | AlBannaTechno/WorkingWithDecorator- | /very helpful/Full-Decorator-Explainations/Class/3-decoratorWithoutArguments.py | 647 | 3.5 | 4 | class DecodetWithoutArguments(object):
def __init__(self,func):# rec : test'function'
print("insied __init__")
self.fun=func
# __call__ : rec func'test' parameters
def __call__(self,*args,**kwargs):# we can pass args kwargs to fun or not
print("Inside __call__")# down
self.f... |
0a778c10c6cac9dc9fa8c6203b18bd013e055100 | ritiksingla/DeepLearningPython | /conv_utils.py | 2,869 | 3.71875 | 4 | import numpy as np
from numpy import ndarray
from utils import assert_dim, assert_same_shape
def _pad_1d(input_: ndarray, num: int) -> ndarray:
'''
Pads single example of 1-dimensional vector with zeros
Parameters
----------
input_ : ndarray of size = (len,)
num : int
padding size
... |
73ab7e74ea7744f4e69cdd8f3db0e08ed96dd403 | kazzastic/CV | /maze/kazim_maze.py | 1,537 | 3.703125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 17 01:29:59 2019
@author: kazzastic
"""
from mazelib import *
import numpy as np
import cv2
def working(file):
'''Here we load our image in the var img'''
img = cv2.imread(file)
cv2.imshow('The Initial', img)
cv2.waitKey(0)
cv2.... |
00084f448701944f0adeddb74a544c01a40d0a5a | kazzastic/CV | /maze/mazelib/generate/TrivialMaze.py | 3,286 | 3.75 | 4 |
from random import randint
import numpy as np
import cython
if not cython.compiled:
from mazelib.generate.MazeGenAlgo import MazeGenAlgo
SERPENTINE = 1
SPIRAL = 2
class TrivialMaze(MazeGenAlgo):
"""
The Algorithm
This is actually a collection of little tools to make simple,
unicursal mazes. Cur... |
e8a71bbfd5a755f85d3935d33b7f53a150249025 | kazzastic/CV | /maze/mazelib/solve/BacktrackingSolver.py | 1,700 | 3.625 | 4 |
from random import choice
import cython
if not cython.compiled:
from mazelib.solve.MazeSolveAlgo import MazeSolveAlgo
class BacktrackingSolver(MazeSolveAlgo):
"""
The Algorithm
1. Pick a random direction and follow it
2. Backtrack if and only if you hit a dead end.
"""
def __init__(self,... |
fe511ba08d1ba756f4a7b7122ccee3b331bdf1a3 | Yasir77788/Shopping-Cart | /shoppingCart.py | 1,959 | 4.21875 | 4 | # shopping cart to perform adding, removing,
# clearing, and showing the items within the cart
# import functions
from IPython.display import clear_output
# global list variable
cart = []
# create function to add items to cart
def addItem(item):
clear_output()
cart.append(item)
print("{} ha... |
3554a999ea67f7ff8ceb221f96fa81c7d9c2d368 | Kevinloritsch/Buffet-Dr.-Neato | /Python Labs/30. Python Graphics - make a class/Meow.py | 327 | 3.515625 | 4 | from graphics import *;
class Penny:
coinColor = color_rgb(184,115,51);
def __init__(self,point):
self.point = point;
self.coin = Circle(point,30);
self.coin.setFill(self.coinColor);
self.val = Text(point,"1c");
self.val.setFill("tan");
def draw(self,canvas):
self.coin.draw(canvas);
self.val.draw(canva... |
6f4cfa2188d0845d9ad888f1540edd6f74c83b87 | Kevinloritsch/Buffet-Dr.-Neato | /Python Warmup/Warmup #3 - #2 was Disneyland/run3.py | 766 | 4.125 | 4 | import math
shape = input("What shape do you want the area of? Choose a rectangle, triangle, or circle ;) ")
if shape=='rectangle':
rone = input("What is the length of the first side? ")
rtwo = input("What is the length of the second side? ")
answer = int(rone)*int(rtwo)
print(answer)
elif shape=='t... |
3fd8314a13ad9ecccc8213aea92ac2b721fbc9a6 | sumegim/Alpha-Santorini | /santorini.py | 9,298 | 3.59375 | 4 | import numpy as np
import copy
def _coord_to_action(x, y):
return int(x+5*y)
def _action_to_coord(a):
x = int(a%5)
y = int((a-x)/5)
return x, y
def _create_space(xy):
x, y = _action_to_coord(xy)
return space(x, y)
def c(obj):
return copy.deepcopy(obj)
class Game():
def __init__(self... |
27fd01098ce6f68a304f25eb885af97217863453 | shivambhojani/Python-Practice | /remove_char.py | 372 | 4.3125 | 4 | # Write a method which will remove any given character from a String?
def remove(str, char):
new_str = ""
for i in range(0, len(str)):
if i != char:
new_str = new_str + str[i]
return new_str
a = input("String: ")
b = int(input("which Character you want to remove: "))
b = b... |
795f7c1765dce0d7932a3ca6ac665b72d8c302e8 | kabayan55/NLP100knock2015 | /Chapter2/knock015.py | 324 | 3.515625 | 4 | # -*- coding: utf-8 -*-
import sys
if __name__ == "__main__":
n = input()
input_file = open('./hightemp.txt', 'r')
lines = input_file.readlines()
lines_list=[]
for line in lines:
lines_list.append(line.strip())
for i in range(len(lines_list)-n, len(lines_list)):
print lines_list... |
9321da35952b1df306a7e3c5a5dfe905a41313a6 | ShVA010864/geek | /task01.4.py | 441 | 3.75 | 4 | n = int(input("Введите число n: "))
m = n % 10 # Извлекаем цифры с помощью остатка при делении на 10
while n > 0:
if n % 10 > m: # Если извлекаемая цифра больше (m),
m = n % 10 # тогда присваиваем её переменной (m)
n = n // 10 # Избавляемся от последней учтенной цифры
print(m)
|
731a2f722a08b278a3b03d601baae3440338dafe | PacoCampuzanoB/Python-Course | /interfaces-graficas-con-tkinter/pareja.py | 1,371 | 3.75 | 4 | from tkinter import *
def eleccion():
if opcion.get()==1:
mensaje.set("seguro que es por dinero?")
elif opcion.get()==2:
mensaje.set("el metro no está tan mal")
elif opcion.get()==3:
mensaje.set("se vale")
elif opcion.get()==4:
mensaje.set("a la friendzone")
elif opcion.get()==5:
mensaje.set("friendzone... |
d7663a06b1041bea043d80daad8639c19549b9b7 | PacoCampuzanoB/Python-Course | /programacion-concurrente/servidor.py | 876 | 4.0625 | 4 | # Sockets
# La forma de comunicar programas/equipos bajo la misma red se resuelve con los llamados Sockets. El Socket en su forma mas simple es un canal/flujo de comunicacion entre dos puntos terminales.
# Para crear un socket se necesita una ip y puerto.
import socket
socketServidor = socket.socket()
# Ip local... |
6cd89b87685cff0ace843154b4b15ee405026a96 | PacoCampuzanoB/Python-Course | /archivos/archivos.py | 2,040 | 3.84375 | 4 | # Archivos
# objetoArchivo = open(nombreArchivo, modoApertura)
# Modos modoApertura
# r -> read Lectura, el archivo ya debe existir
# w -> write Escritura, si el archivo no existe lo crea, y si existe lo sobreescribe
# a -> append Añadir, agrega datos al final del archivo
# + -> r y w
try:
f = open("texto.txt", "w"... |
ea9964053443642fd754f6ebbe6e35af25ab97a7 | PacoCampuzanoB/Python-Course | /programacion-orientada-a-objetos/ejercicio4.py | 235 | 3.625 | 4 | def primos(n):
a = 0
x = 2
i = 0
while(i<n):
a = 0
for j in range(1,x):
if x%j==0:
a+=1
if a<2:
print(x)
i += 1
x += 1
dato = int(input("Dame la cantidad de numeros primos que deseas obtener: "))
primos(dato) |
cb0a871091aa6cb80dd7afcf45c52de548e30208 | PacoCampuzanoB/Python-Course | /interfaces-graficas-con-tkinter/eventos.py | 357 | 4 | 4 | from tkinter import *
ventana = Tk()
def clicIzquierdo(evento):
print("Izquierdo")
def tecla(evento):
print("Deja de apretarme! >:v")
marco = Frame(ventana, width=200, height=300)
entrada = Entry(ventana) #Para ingresar texto
entrada.pack(side=LEFT)
marco.bind("<Button-3>", clicIzquierdo)
entrada.bind("<Up>", tec... |
3c4163cd8487336a4d36e137a9fb5b586cdbfd9e | PacoCampuzanoB/Python-Course | /interfaces-graficas-con-tkinter/calculadora.py | 7,290 | 3.75 | 4 | """
DISFRUTEN DE SU CALCULADORA Y CUALQUIER COSA ME PUEDEN MANDAR CORREO :) rodrigo.vivas.proteco@gmail.com o mandenme mensaje por Face
Disculpen que no la pudimos terminar en clase, pero el tiempo se fue volando.
Esta es la versión 1.0 y la hice a la 1:00 am xd así que si ven algo que se le pueda mejorar inténtenlo :p... |
11b2f238ba7868979cefee0d6b0ebd70a7ef18f8 | MarcusLuong/InterviewPractice | /Algos/DecreaseArrayZigzag.py | 1,461 | 3.578125 | 4 | # Given an array nums of integers, a move consists of choosing any element and decreasing it by 1.
# An array A is a zigzag array if either:
# Every even-indexed element is greater than adjacent elements, ie. A[0] > A[1] < A[2] > A[3] < A[4] > ...
# OR, every odd-indexed element is greater than adjacent elemen... |
4ed6cf3d41b07050357aad7d742547f9ae6563fe | varadsrivastava/Python_hackerrank | /itertool_combination.py | 1,427 | 3.90625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Thu Jan 23 19:48:47 2020
@author: Varad Srivastava
This tool returns the length subsequences of elements from the input iterable.
Combinations are emitted in lexicographic sorted order. So, if the input iterable is sorted, the combination tuples will be produced in sorted orde... |
2372f4aae38f93c41314a971fd855460c63b9420 | varadsrivastava/Python_hackerrank | /ginortS.py | 1,392 | 3.875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Apr 8 16:58:30 2020
@author: Varad Srivastava
You are given a string .
contains alphanumeric characters only.
Your task is to sort the string in the following manner:
All sorted lowercase letters are ahead of uppercase letters.
All sorted uppercase letters are ahead of ... |
b8116ad360d663a3446d570eba87f337886619bb | varadsrivastava/Python_hackerrank | /swap_case.py | 1,353 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Dec 25 01:29:03 2019
@author: Varad Srivastava
"""
"""
ou are given a string and your task is to swap cases. In other words, convert all lowercase letters to uppercase letters and vice versa.
For Example:
Www.HackerRank.com → wWW.hACKERrANK.COM
Pythonist 2 → pYTHONIST 2
In... |
324cd05b3ed39a35be21b80b9645a01c84349fff | menliang99/CodingPractice | /LCA2.py | 673 | 3.78125 | 4 | class Node:
def __init__(self, key):
self.key = key
self.right = None
self.left = None
def findLCA(root, n1, n2):
if root is None:
return None
if (root.key == n1 or root.key == n2):
return root
left_lca = findLCA(root.left, n1, n2)
right_lca = findLCA(root.right, n1, n2)
if (left_lca != None and rig... |
06c3a2d0892fe3e4eff2be2d87fda6899dd0efab | menliang99/CodingPractice | /BASIC/FactoryATClass.py | 341 | 3.65625 | 4 | BaseClass = type("BaseClass", (object,), {}) #use type is another way to create class!!
C1 = type("C1", (BaseClass,), {"x":1})
C2 = type("C2", (BaseClass,), {"x":30})
def MyFactory(myBool):
return C1() if myBool else C2()
m = MyFactory(True)
v = MyFactory(False)
print m.x, v.x
##clear method of Factory###
#see ... |
bf487f36d7cf9d2f62c0e573996fb04d828445d0 | menliang99/CodingPractice | /rotate.py | 1,035 | 3.859375 | 4 |
def rotateArray(nums, k):
length = len(nums)
k = k % length
reverse(nums, 0, length - 1)
reverse(nums, 0, k - 1) # Intelligence Defence to figure out
reverse(nums, k, length - 1)
def reverse(nums, start, end):
print nums
while (start < end):
nums[start], nums[end] = nums[end], nums[start]
start... |
98b2d96c2e894cddb6fa1239c95d6a823d020afe | menliang99/CodingPractice | /UniqueBST.py | 354 | 3.8125 | 4 | # Catalan number
def numTrees(n):
dp = [1, 1, 2]
if n <= 2:
return dp[n]
else:
dp += [0 for i in range(n - 2)] # numbers in the array will increase here!
print dp
for i in range(3, n + 1):
for j in range(1, i + 1):
dp[i] += dp[j-1] * dp[i-j]
print dp
return dp[n]
def generateTrees(n):
return df... |
4067c6b39abf37b18537c930109aa732e9dfe885 | menliang99/CodingPractice | /PeakingIterator.py | 714 | 4.25 | 4 | # Decorator Pattern is a design pattern that allows behavior to be added to an individual object, either statically or dynamically, without affecting the behavior of other objects from the same class.
class PeekingIterator(object):
def __init__(self, iterator):
self.iter = iterator
self.peekFlag = False
self.n... |
0312a221309f546836230b69bf7b6c81f02bac56 | mhetrick29/COS429_Assignments | /A4_P2/relu_backprop.py | 1,208 | 4.15625 | 4 | def relu_backprop(dLdy, x):
import numpy as np
# Backpropogates the partial derivatives of loss with respect to the output
# of the relu function to compute the partial derivatives of the loss with
# respect to the input of the relu function. Note that even though relu is
# applied elementwise to ma... |
32aecdb1ce61aa0071b2482a1e222a93e5f3137d | mhetrick29/COS429_Assignments | /A4_P1/test_logistic_sgd.py | 2,166 | 3.703125 | 4 | """
Princeton University, COS 429, Fall 2019
"""
import numpy as np
import matplotlib.pyplot as plt
from logistic_sgd import logistic_sgd
from logistic_predict import logistic_predict
def test_logistic_sgd():
""" Test logistic regression on some simple data in 'training_data.txt'
and 'test_data.txt'
... |
97e51355fbb2e5f1100d49d4ef3c8c7a3c0a59ac | kart2k15/Tic-Tac-Toe | /src/Tic-Tac-Toe.py | 4,699 | 4.25 | 4 | import os
import random
#Function to display board
def display_board(board):
os.system('clear') # Remember, this only works in jupyter!
print("The number represent the positions at which markers can be placed!")
print("7 | 8 | 9\n4 | 5 | 6\n1 | 2 | 3\n\n")
print(' | |')
print(' ' + board[7] + ... |
e56c29cc6afc63b4ec4cf5afc97355e0385ee367 | nunu2021/DijkstraPathFinding | /dijkstra/basic_algo.py | 2,208 | 4.125 | 4 | import pygame
graph = {
'a': {'b': 1, 'c': 1, 'd': 1},
'b': {'c': 1, 'f': 1},
'c': {'f': 1, 'd': 1},
'd': {'e': 1, 'g': 1},
'e': {'g': 1, 'h': 1},
'f': {'e': 1, 'h': 1},
'g': {'h': 1},
'h': {'g': 1},
}
def dijkstra(graph, start,goal):
shortest_distance ={} # records the cost to re... |
65048acdb71a42ae34d56958a9383fb0a663bc76 | ariangcc/SO | /02 Material/dibujaBoot.py | 2,810 | 3.5625 | 4 | """
Programa que muestra el Boot Sector de la FAT
Prof. A. Bello
Pontificia Universidad Católica del Perú
"""
import sys
import pygame
# Definimos algunos colores
NEGRO = (0, 0, 0)
BLANCO = (255, 255, 255)
VERDE = ( 0, 255, 0)
ROJO = (255, 0, 0)
VERDE = (0, 255, 0)
AZUL = (0, 0, 255)
AMARILLO = (255, 255, 0)
CIAN ... |
4e59fe86d0d92f12f3b726dcdd22676143321806 | knwnw/yandex-algorithmic-training | /lesson1/c.py | 893 | 3.984375 | 4 | def solution(number_to_add: str, num1: str, num2: str, num3: str) -> str:
norm_num_to_add = normalize(number_to_add)
norm_num1 = normalize(num1)
norm_num2 = normalize(num2)
norm_num3 = normalize(num3)
result = ''
result += 'YES\n' if norm_num_to_add == norm_num1 else 'NO\n'
result += 'YES\n... |
bc97a3aca49631f37dba1cc7b9b12d53ecaafe33 | knwnw/yandex-algorithmic-training | /lesson3/j.py | 262 | 3.796875 | 4 | def solve(k: int) -> set:
"""Solves the equation: |x| + |y| = k."""
result = set()
for v in range(-k, k + 1):
result.add((v, k - abs(v)))
result.add((v, -k + abs(v)))
return result
def gps(coord: tuple, d: int) -> set:
pass
|
056dded30c1c92f30d2d50c76f938d48d86ccc9c | Jofemago/Computacion-Grafica | /SPACE INVADERS/Player.py | 1,903 | 3.640625 | 4 | '''
Se crea una clase jugador la cual tendra un movimiento con los teclas
y dispara
'''
import pygame
from configuraciones import *
TIEMPODESTRUCION = 8
class Vida(pygame.sprite.Sprite):
def __init__(self, img):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(img).convert()
... |
9879c1b40bc6580b562d3080b32ef54010549755 | guanhejiuzhou/PythonStudy | /Python语言基础/Day005-分支和循环结构应用.py | 3,683 | 3.828125 | 4 | from random import randint
"""
分支和循环结构的应用
经典小案例
"""
''' ========== 寻找水仙花数 ========== '''
# 水仙花数被称为超完全数字不变数、自恋数、自幂数、阿姆斯特朗数,它是一个3位数,该数字每个位上数字的立方之和正好等于它本身
# 1³+5³+3³=153
# 这个题目的关键是将一个3位数拆分为个位、十位、百位,这一点利用python中的//(整除)和%(求模)可以实现
for num in range(100, 1000):
low = num % 10 # 个位数(求模运算 % )
mid = num // 10 % 10 # 十位... |
0fbca70b44d8bcf4fc87316e0b840e40ad8881f0 | guanhejiuzhou/PythonStudy | /Python语言基础/Day001-元素的变量.py | 2,438 | 4.4375 | 4 | """
变量和类型
变量时数据的载体,简单的说就是一块用来保存数据的内存空间,变量的值可以被读取和修改。
python中的几种常用数据类型
整型 int:python中可以处理任意大小的整数
浮点型 float
字符串型 str:字符串是以单引号或者双引号括起来的任意文本
布尔型 bool:布尔值只有true和false两种值,要么true要么false
"""
'''
变量命名
硬性规则:
1、变量名由字母、数字、下划线构成,数字不能开头
2、大小写敏感,大写的A和小写的a是两个不同的变量
3、不要跟Python语言的关键字和保留字(如函数、模块等的名字)发生重名的冲突
非硬性规则:
1、变量名... |
4b1e2247c24f7876c63fcb1b75ffa96c15e41e3f | den-hk555/IT_Step_Repository | /Python/HW3_Ladyzhnikov_Den_Sortirovka.py | 3,357 | 3.515625 | 4 | import random, time
def sort_buble(list_input) :
n = 1
while n < len(list_input) :
for i in range(len(list_input) - n):
if list_input[i] > list_input[i + 1]:
list_input[i],list_input[i + 1] = list_input[i + 1],list_input[i]
n += 1
return list(list_input)
def so... |
438d2e0e5baceb05a7e0eb8d7d276fb1fd63c527 | ignited19/PythonDrills | /StringOperations.py | 5,363 | 4.1875 | 4 | class StringOperations(object):
#=======================================================
# The purpose of this function is to determine if a
# string contains all unique characters. The basic
# attribute to determine if a string contains unique
# characters is the character count. Luckily with
... |
a41c22c9b286575981234bdf491936510587ef95 | felexkemboi/4thProject | /three.py | 1,198 | 3.703125 | 4 | import numpy
import operator
import functools
original_matrix = [[1,2,3],[5,6,7],[2,3,4],[3,4,5],[4,5,6],[6,7,1],[7,1,2]]
def matrix():
rows = int(input("\nPlease key in the number of matrices: "))
m = int(input("\nPlease key in the number to be added to the matrix: "))
n = 3
bigger_list = functools.r... |
66f8757cf0264ca28117ad826a9e02dc80382b78 | loqum/Curso-Python | /Tema6_Ejercicio1.py | 208 | 3.8125 | 4 | def concatena_palabras_ordenadas(palabra1, palabra2):
return palabra1 + palabra2 if (len(palabra1) >= len(palabra2)) else palabra2 + palabra1
print(concatena_palabras_ordenadas("Pamplona ", "Vitoria "))
|
835081ff2fa1c8d64a1f447d99a605fd68ec4305 | loqum/Curso-Python | /PruebaLabelFrameTkinter.py | 475 | 3.65625 | 4 | from tkinter import *
class App:
def __init__(self, master):
labelFrame = LabelFrame(master, height = 100, width = 100, text="Prueba LabelFrame")
labelFrame.pack()
self.hello = Button(labelFrame, text = "Hello", command = self.say_hello)
self.hello.pack(side = LEFT)
label_he... |
d72a7776c5c7e045333f31c54fd2079d151931cd | loqum/Curso-Python | /PruebaFrameTkinter.py | 492 | 3.703125 | 4 | from tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
frame.height = 10
frame.width = 10
frame.pack()
self.hello = Button(frame, text = "Hello", command = self.say_hello)
self.hello.pack(side = LEFT)
self.label_hello = Label(frame... |
4385c2fc53c50f04f32cdeee59449a603f2d11b1 | loqum/Curso-Python | /PruebaListBox.py | 538 | 3.515625 | 4 | from tkinter import *
class App:
def __init__(self, master):
frame = Frame(master)
label = Label(text = 'Animales')
listbox = Listbox()
listbox.insert(0, ('Perro'))
listbox.insert(1, ('Gato'))
listbox.insert(2, ('Orangutan'))
listbox.insert(3, ('Paloma'))
... |
264391afed629f4946435c1a8f840b90d5842c44 | echase6/codeguild | /practice/sudoku/main.py | 11,461 | 3.84375 | 4 | """Sudoku solving program.
Will handle 4x4, 9x9 and 16x16 puzzles.
Puzzle comes from the file referenced in board.py (sudoku_.txt)
Algorithm comes from considering the board in a 3-D space, with the 3rd
dimension being cell contents. In this manner, the puzzle is solved
when only one cell-cube is filled when loo... |
d9e5811143e4a5a43612776c257491bcaf0523e1 | echase6/codeguild | /practice/timezone/timezone/logic.py | 921 | 3.890625 | 4 | """timezone Logic."""
from tzwhere import tzwhere
import arrow
tz = tzwhere.tzwhere()
def get_time_at_tz(tz_string):
"""Return the current time (as a string) at a given timezone."""
utc = arrow.utcnow()
time_string = str(utc.to(tz_string))
return time_string
def get_tz(lat, lng):
r"""Return the... |
19667d8cd7c9c82438df92eff2f4062be06ef339 | echase6/codeguild | /practice/pig-latin-sentence.py | 1,693 | 4.15625 | 4 | """
Program to translate a single word into Pig Latin
This is an individual project by Eric Chase, 7/11/16
Input: a single words
Output: a word converted into Pig Latin
"""
# setup
VOWELS = ['a', 'e', 'i', 'o', 'u']
pig_latin = []
def convert_pig_latin(english_input):
# First, break into three parts: beginning p... |
89ff91a2e8e259b5d2ba6f1ae44789d9dd9de4ec | echase6/codeguild | /practice/case.py | 4,566 | 4.375 | 4 | """Case conversion between various cases
Handles snake_case, CONSTANT_CASE, kebob-case, CamelCase
Automatically detects case, assuming perfectly-typed
Inputs: word
Output: word converted to snake, camel, kebob and constant cases
"""
CASES = ['snake', 'camel', 'kebob', 'constant']
def get_input_word():
"""Ge... |
62c3b567d2bb3755264766f8531b2d0b4c04b925 | echase6/codeguild | /practice/adventure/creature.py | 1,146 | 3.78125 | 4 | from weapon import Weapon
class Creature:
"""Creature class."""
def __init__(self, location, health, weapons, icon):
self.location = location
self.health = health
self.weapons = weapons
self.icon = icon
def __repr__(self):
"""Return repr()
>>> repr(Creatu... |
c2da973382153cb9d17fe48140d1da2d5f5a7fb6 | echase6/codeguild | /practice/account.py | 2,224 | 3.765625 | 4 | # def _cents_to_dollars(self, cents):
class Account:
def __init__(self):
"""Initialize Class balance in cents, rate in real numbers"""
self._balance_cents = 0
self._rate = 0.001
def __repr__(self):
"""Return repr
>>> repr(Account())
'Account()'
"""
... |
85c9435201575421a3b5ce0bc6c75d850e37bdd8 | ZatixVFX/python-progression | /python_project/project.py | 5,501 | 4 | 4 | # Import in-built modules
import random
import sys
# Open Project.txt and append the code to the file
#sys.stdout = open('project.txt', 'a+') (optional)
# Function used to get user's age and check whether user has met the age requirement to play
def age():
file = open('project.txt', 'a+')
user_age = int(inpu... |
b10b564ebc7e1c81f08fcbc62b2db79f0ffc7d75 | fishermancome/python_daily_program | /daily_program/0015.py | 600 | 3.53125 | 4 | import xlwt as ExcelWrite
def write_XLS(filename):
dict1 = {
"1" : "上海",
"2" : "北京",
"3" : "成都"
}
xls = ExcelWrite.Workbook()
sheet = xls.add_sheet("Sheet1")
keys = []
values = []
for k in dict1.keys():
keys.append(k)
values.append... |
2c3e208686f9af639bc394c8c44c340e2d81a566 | jamiejamiebobamie/CS1.1-Madlibs.py | /madlibs.py | 3,940 | 4.1875 | 4 | import random
#run in python3
def inputWords():
print("I don't care what the requirements say: you're not seeing my story until I get some words, so...")
verbs = []
while len(verbs) < 1:
verb = input("Give me a verb.")
if type(verb) is str and len(verb)>0:
... |
c5814b2a9ada7fd67ff93d51ee4c864545bad0b7 | larry520/py-learning | /tools/mongoDB_class.py | 3,369 | 3.578125 | 4 | # -*- encoding:UTF-8 -*-
# can use Robo 3T for visualization
"""
class Database is used for MongoDB option
"""
from pymongo import MongoClient
class Database(object):
def __init__(self, address, port, database):
self.conn = MongoClient(host=address, port=port)
self.db = self.conn[database]
... |
fa4e603e6acd82f9d218ff3976a44b355cddf770 | louridas/rwa | /content/notebooks/lzw.py | 4,759 | 4.125 | 4 | import argparse
def lzw_compress(input_file, output_file, nb, n):
"""
Perform LZW compression.
Parameters
----------
message : str
the message to compress
nb : int
the number of bits used for each encoding
n : int
the size of the alphabet
Returns
... |
6ca79260ee78614c41d52a19725ea657b5c5e3d6 | dhruvrathod23/pep-8 | /peppp.py | 786 | 4.03125 | 4 | # Python program to explain property() function
# Alphabet class
class Alphabet:
def __init__(self, value):
self._value = value
# getting the values
def getValue(self):
print('Getting value')
return self._value
#... |
2a07964e8b4126bc971183fe77622f3d3941b6ad | 317787106/spider | /business/posInPolygon.py | 4,058 | 3.53125 | 4 | #encoding:utf-8
from __future__ import division
cityid2name = {1:"beijing",
2:"shanghai",
3:"guangzhou",
4:"shenzhen",
37:"tianjin"
}
class Point:
def __init__(self,lon,lat):
self.lon = lon
self.lat = lat
'''判断点p是否在多边形pol... |
06eaef5862baeee9aec94a44e2c22ba0d6c2b832 | gsvijayraajaa/DS-Python | /DS/src/insertion.py | 317 | 4 | 4 | """ Implementation of Insertion Sort in Python """
def sort(list):
for i in range(0,len(list)-1):
for j in range(i+1,0,-1):
if list[j] < list[j-1]:
temp = list[j]
list[j] = list[j-1]
list[j-1] = temp
return list
ll=[10,2,30,4]
print sort(ll) |
0540aaa6f156d2f017ea12380f97f3a68166fac6 | Deepika-bala/conversion | /main.py | 375 | 4.25 | 4 | decimal=int(input("enter the decimal : "))
convert =int(input("convert into : [1] binary,[2] octal,[3] hexadecimal:\n"))
if convert == 1:
print("convert into binary\n " ,bin(decimal))
elif convert == 2 :
print("convert into octal\n", oct(decimal))
elif convert == 3:
print("convert into octadecimal\n"... |
c9632d0ae5ef1a7289ecb0e51af58152530ec537 | ggopher/Python_GetStarted | /Lesson3/task2.py | 901 | 4 | 4 | def user(name='default', surname='default', birthday='default', city='default', email='default', phone='default'):
"""
:param name: str
:param surname: str
:param birthday: str
:param city: str
:param email: str
:param phone: str
:return: str
"""
return f'Имя:{name}, Фамилия:{su... |
3970ffc7e5f474d0bcbc6f871152168cf5ee5a21 | ggopher/Python_GetStarted | /Lesson3/lesson3.py | 1,557 | 4.0625 | 4 | """
my_list = [1, 2, 3, 4, 5]
try:
a = my_list[10]/0
except ZeroDivisionError:
print('Овцебык')
except IndexError:
print('Овцебык индекс')
#except Exception:
# print('Овцебык Все ошибки')
finally:
print('Овцебык в любом случае')
"""
=======
#def my_sum(tmp: list):
# return tmp[0] ... |
fd4add8b77968cc813378929fae4334014444584 | katyamust/databricks_poc | /kmeans_poc/data/generate_dataset.py | 692 | 3.921875 | 4 | # generate dataset : random data in a two-dimensional space
#https://towardsdatascience.com/understanding-k-means-clustering-in-machine-learning-6a6e67336aa1
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
#%matplotlib inline
def generate_x():
X = -2 * ... |
33ba09225e07677a64a3cf995024f8506c402a84 | Chao8219/py-starter | /tests/beginner.py | 1,116 | 3.84375 | 4 | import random
# __init__ will loaded when the instance of this class is created.
# self refers to the object itself
# *args will pass various number of parameters and form them as a tuple
# To read tuple, one could use index to do that, i.e. args[0]
# **kwargs is similar with *arg, but it will form a dictionary.
# To ... |
d910ace967310607bd317fbb2aaccd745a85cec4 | mbg615/pythonSkills | /test.py | 1,364 | 3.953125 | 4 | from random import randint
def flipList(lst, start):
store = []
reversedList = []
listVal = start
for i in range(0, start):
store.append(lst[i])
while listVal < len(lst) - start:
reversedList.append(lst[listVal])
listVal += 1
for i in store:
reversedList.append(i... |
079b0e961c408f6b2b6c8edf65b56eaa0f2b4e61 | WaqasAkbarEngr/Python-Tutorials | /smallest_number.py | 612 | 4.1875 | 4 | def smallest_number():
numbers = []
entries = input("How many number you want to enter? ")
entries = int(entries)
while entries > 0:
entered_number = input("Enter a number? ")
numbers.append(entered_number)
smallest_number = entered_number
entries = entries - 1
... |
cf83e693183bfad71ee68b47e64c709092b7817a | WaqasAkbarEngr/Python-Tutorials | /Data_Structure_Tuples.py | 3,372 | 4.84375 | 5 | # Tuple is a type of data structure which has ordered elements in it.
# The elements of a tuple cannot be changed after they are defined.
# A tuple may contain duplicate value in it, means there may be two or more same elements in a tuple
# In order to define a tuple, elements are written in a round bracket or par... |
ecd0bbbd3f911f59cd5578f8cccba0ad0cd41134 | WaqasAkbarEngr/Python-Tutorials | /Data_Structure_Dictionaries.py | 7,312 | 4.78125 | 5 | # Dictionary is a data structure in Python which is unordered and have index number. A dictionary has one or more items. Each item
# of dictionary consists of key and value. A key is similar to a variable and value is similar to constant value assigned to a
# variable. In other words each key has an assigned value.
... |
cb98d70e9b12b07d0c0bbff545e439809eeb69b6 | superY-25/algorithm-learning | /src/algorithm/longestConsecutive.py | 1,738 | 3.734375 | 4 | """
最长连续序列
给定一个未排序的整数数组,找出最长连续序列的长度。
要求算法的时间复杂度为 O(n)。
link:https://leetcode-cn.com/problems/longest-consecutive-sequence/
"""
def longestConsecutive(nums):
"""
算法正确,算法时间复杂度为O(n^2)但不符合O(n)的时间复杂度要求
:param nums:
:return:
"""
res = []
max_len = 0
for n in nums:
if n in res:
... |
065432e1ef4ba3e168b5c30c3781b9327f875e53 | superY-25/algorithm-learning | /src/algorithm/202003/swapPairs.py | 1,147 | 4.09375 | 4 | """
给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
示例:
给定 1->2->3->4, 你应该返回 2->1->4->3.
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/swap-nodes-in-pairs
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
"""
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val =... |
9521a82feadfed54c036a1854fc4a63418f28095 | superY-25/algorithm-learning | /src/algorithm/threeSumClosest.py | 1,767 | 3.828125 | 4 | """
给定一个包括 n 个整数的数组 nums 和 一个目标值 target。找出 nums 中的三个整数,使得它们的和与 target 最接近。
返回这三个数的和。假定每组输入只存在唯一答案
link:https://leetcode-cn.com/problems/3sum-closest
"""
def threeSumClosest(nums, target):
"""
暴力求解
:param nums:
:param target:
:return:
"""
res = nums[0] + nums[1] + nums[2]
size = len(nu... |
9377db53f9ca6f34669fd4695af1a359e8855f23 | superY-25/algorithm-learning | /src/algorithm/combinationSum2.py | 812 | 3.625 | 4 |
def combinationSum2(candidates, target):
dic = {}
for i in range(1, target + 1):
dic[i] = []
for i in range(1, target + 1):
for e in candidates:
if e == i and [i] not in dic[i]:
dic[i].append([i])
elif i > e:
for k in dic[i - e]:
... |
8dca89cb1525c61c3dae224d47db2e5430de2b9d | superY-25/algorithm-learning | /src/algorithm/longestPalindrome.py | 792 | 3.65625 | 4 | """
动态规划
给定一个字符串 s,找到 s 中最长的回文子串。你可以假设 s 的最大长度为 1000。
link:https://leetcode-cn.com/problems/longest-palindromic-substring/
"""
def longestPalindrome(s):
"""
:param s:
:return:
"""
str_length = len(s)
max_length = 0
start = 0
for i in range(str_length):
if i - max_length >= 1 an... |
5a6b1586b8e324fae66e0dc7cd11bd51804813df | superY-25/algorithm-learning | /src/algorithm/maxArea.py | 835 | 3.703125 | 4 | """
给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。
找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。
link:https://leetcode-cn.com/problems/container-with-most-water
"""
def maxArea(height):
"""
双指针法,面积的大小取决于数值更小的那一边,
:param height:
:return:
"""
max_area = 0
l... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.