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 |
|---|---|---|---|---|---|---|
117bc69dcf0ef36f8e572aced374d4cb7b1a1585 | Arxtage/leetcode | /sudoku-solver/sudoku-solver.py | 2,000 | 3.78125 | 4 | class Solution:
def solveSudoku(self, board: List[List[str]]) -> None:
# Backtracking
"""
Do not return anything, modify board in-place instead.
"""
rows = collections.defaultdict(set)
cols = collections.defaultdict(set)
boxes = collections.defaultdic... |
2f9511b4eb343255fd8c7948fef1bfb3999f2cf3 | Arxtage/leetcode | /check-if-it-is-a-straight-line/check-if-it-is-a-straight-line.py | 940 | 3.53125 | 4 | class Solution:
def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
# O(n)
# y = ax + b
coord1 = coordinates[0]
coord2 = coordinates[1]
if coord2[0] - coord1[0] == 0:
a = 0
else:
a = (coord2[1] - coord1[1]) ... |
b372c0cbcca4882e7e923a70248b46fcaee64564 | Arxtage/leetcode | /design-circular-deque/design-circular-deque.py | 2,969 | 3.78125 | 4 | class Node():
def __init__(self, val, nxt = None, prev = None):
self.val = val
self.next = nxt
self.prev = prev
class MyCircularDeque:
# linked list (two ways)
def __init__(self, k: int):
self.k = k
self.size = 0
self.deque = None
self.front =... |
24dcd14bd37c82d94ae89cb0bcf5d22108c677c4 | Arxtage/leetcode | /implement-queue-using-stacks/implement-queue-using-stacks.py | 798 | 3.859375 | 4 | class MyQueue:
# O(n) push
# O(1) pop
def __init__(self):
self.stack1 = []
self.stack2 = []
def push(self, x: int) -> None:
while self.stack2:
self.stack1.append(self.stack2.pop())
self.stack2.append(x)
while self.stack1... |
9790dfcfe2914cdfd54459c205729c600a292b22 | Arxtage/leetcode | /valid-parentheses/valid-parentheses.py | 614 | 3.828125 | 4 | class Solution:
def isValid(self, s: str) -> bool:
queue = deque()
for val in s:
if val == '(' or val == '[' or val == '{':
queue.append(val)
elif val == ')':
if not queue or queue.pop() !='(':
return(False... |
8974fdefb21a034570613665712a2dee93515b64 | lenkamac/TicTacToe | /TicTacToe.py | 3,615 | 3.890625 | 4 | board = [' ' for b in range(9)]
game_go = True
winner = None
current_player = "x"
def play_game():
# display initial board
display_board()
while game_go:
global current_player
print(line)
move = input(f"Player {current_player}| Please enter your move number /"
... |
d08d7747f6b98d3cec75db1c425c46c5b6397919 | VladyslavPodrazhanskyi/python-cursor | /week2/lesson2-intro-to-functional/homework/DmytroMelnyk/utils/task_5.py | 806 | 4.09375 | 4 | def sum_min_max(l: list):
"""
Write function that return three values
:param l: input list of dict
:return:
- Summary age of members.
- The youngest member
- The oldest member
"""
min_l = min(l, key=lambda x: x['age'])
max_l = max(l, key=lambda x: x['age'])
sum_l = sum(map(la... |
d7c6280a38368eae1f8b9577e8a49075427416d3 | VladyslavPodrazhanskyi/python-cursor | /week2/lesson2-intro-to-functional/homework/RomanZhovna/utils/task7.py | 856 | 3.90625 | 4 | # this is "simple" convertor for arabic to roman conversion and numbers from initial_map are enough only for arabic numbers up to 3999.
def arabic2roman(input_number: int) -> str:
assert 0 < input_number <= 3999 and int(input_number)
initial_map = [(1000, "M"),
(900, "CM"),
... |
69aae732d9a7411862d38e01058023caa05b0fa0 | VladyslavPodrazhanskyi/python-cursor | /week10/gang_of_four/structural/composite.py | 1,381 | 3.96875 | 4 | from __future__ import annotations
from abc import ABC, abstractmethod
from typing import List, Union
class Position(ABC):
@abstractmethod
def calc_price(self):
raise NotImplementedError
class Product(Position):
def __init__(self, price):
self.__price = price
def calc_price(self):... |
f01d29c462313808548082ffff6bf97a4d6e9e2d | jesslam948/Programming-Practice | /2021/UniquePaths.py | 1,042 | 3.765625 | 4 | class Solution:
def uniquePaths(self, m: int, n: int) -> int:
# create our dp array
dp = [[0 for x in range(n)] for y in range(m)]
# set first row and first column to 1
# bc there's only one way to either continually go right or go down
for i in range(0, m):
... |
cd44403f660a09972f210baac28a06d2e82eefc0 | jb1113/practice_python | /FourCal.py | 954 | 3.53125 | 4 | # FourCal.py
class FourCal:
def __init__(self, first, second):
self.first = first
self.second = second
def setData(self, first, second):
self.first = first
self.second = second
def add(self):
return self.first + self.second
def sub(self):
return self.f... |
38699d975312ecb176c0e32aea99c6f5dcc6a667 | jb1113/practice_python | /practice3.py | 4,632 | 4.09375 | 4 | # 1. 주어진 자연수가 홀수인지 짝수인지 판별해 주는 함수를 작성해보자
def is_odd(number):
if number % 2 == 0:
print("even")
else:
print("odd")
# lambda와 조건부 표현식(conditional expression) 사용
is_odd = lambda number : "even" if number % 2 == 0 else "odd"
# 조건부 표현식
조건문이 참인 경우 if 조건문 else 조건문이 거짓인 경우
# lambda
lambda 매개변수1, 매개변수2, ... |
c57509ab295a8ce3ba976c8b71b743ae076eb650 | shivamdubey1801/AI-30-Days | /opencv1.py | 213 | 3.59375 | 4 | import cv2
img=cv2.imread("sample1.jpg")
cv2.imshow("pantechLogo",img)#Opening the image with a name
cv2.imwrite("logo.png",img)#Saving opened image with specified name
cv2.waitKey(0)
cv2.destroyAllWindow()
|
ec90f8fbc04de639e8c4b8e9aa9b177108a09749 | JacobPfau/Electoral-Systems-Simulations | /utils.py | 1,148 | 3.625 | 4 | import numpy as numpy
class Vertex():
'''
A vertex within a directed graph.
'''
def __init__(self, name=None):
self.out_vertices = []
self.in_vertices = []
self.name = name
class NamedGraph():
'''
A directed gaph in which the vertices are named
'''
def __init__... |
cfa270b609c6a74caf769af2caa984cd369bec10 | RankGM/data-structures | /python/linked-list.py | 2,575 | 3.890625 | 4 | '''
Todo:
- def sort
- Include exceptions
'''
class node:
def __init__ (self, data=None):
self.key = data
self.next = None
class linkedList:
def __init__(self):
self.head = None
self.tail = None
# O(1)
def insertAtEnd(self, data):
aux = node(data)
# if first node
if not self.head:
self.h... |
a106e847217cb314cd6e55804c10282ac6118d05 | dkurth/projecteuler | /prob1.py | 93 | 3.59375 | 4 | s = 0
for x in range(1, 1000):
if not (x % 3) or not (x % 5):
s += x
print(s) |
157d18d5ed7ef80224bb76f12ff416cb95ae070a | deepaksoni70/machine_learning | /python/learn/TensorFlow/GradientDescent.py | 1,445 | 3.65625 | 4 | import numpy as np
def gradient_descent_runner(xValues, yValues, starting_m, starting_b, learning_rate, num_iterations):
m = starting_m
b = starting_b
mValues=[]
bValues=[]
costValues=[]
for i in range(num_iterations):
m, b = step_gradient(m, b, xValues, yValues, learning_rate)
... |
2bfcc4444097d67986b8c07c023fbbb7b10a9b5f | thiagosfluz/university-portal | /multiplerows.py | 502 | 3.90625 | 4 | import sqlite3
list_ = ['a', 'b', 'c']
#create a data structure
conn = sqlite3.connect('example.db')
c = conn.cursor()
#Create table
c.execute('''Create TABLE if not exists server("sites")''')
#Insert links into table
def data_entry():
for item in list_:
c.execute("INSERT INTO server(sites) VALUES(?)", ... |
af000c826bff0ce5a887c2ba838f3585317ffd41 | Bratquote/DjangoCourse_ITIS | /DjangoCourse_TimurKarimov_11-608.py | 1,526 | 3.96875 | 4 | while True:
name = input("Enter file names ")
name = name + ".html"
try:
file = open(name, 'w')
break
except FileNotFoundError:
print("Invalid value ")
except PermissionError:
print("Invalid value ")
size = abs(int(float(input("Enter size of multiplication table "))))... |
120deabf6a4da39735fbdf49cd1061788257e304 | fennieliang/week3 | /lesson_02_call.py | 730 | 3.625 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 30 11:35:17 2021
@author: fennieliang
"""
from lesson_02_class import Text_process as tp
string = 'I’m willing to bet you’ve Taipei heard of Harry Poter for 1000 times.'
p=tp.doc_length(string)
print(p)
'''
##### test split word method ########... |
7157f20e3565c8ec175b673725fd2073ad8ae33e | fennieliang/week3 | /lesson_0212_regex.py | 1,082 | 4.1875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 25 14:40:57 2021
@author: fennieliang
"""
#useful links for regular expression
#http://python-learnnotebook.blogspot.com/2018/10/python-regular-expression.html
#https://www.tutorialspoint.com/python/python_reg_expressions.htm
#regular expression
i... |
8512fcf684efa889d2a82eeb1381e89eb1395710 | eddynmn/Schedaddle | /sorter.py | 718 | 3.765625 | 4 | def sortByDate(dataList):
return sorted(dataList,key=getDate)
def getDate(data):
return data["dueDate"]
if __name__ == "__main__":
l = [{"dueDate":"1/23", "time":1, "type":"sleep"},
{"dueDate":"4/23", "time":2, "type":"sleep"},
{"dueDate":"3/18", "time":3, "type":"sleep"},
{"dueDat... |
0bd2d1cc9dcf84d5d91e8aab72ed2966ec1a217d | cdesk/MovieTrailerSite | /media.py | 1,519 | 3.78125 | 4 | import webbrowser
class Video():
"""This class is a parent class to store information that is applicable
to all video types."""
def __init__(self, title, duration):
self.title = title
self.duration = duration
class Movie(Video):
"""This class provides a way to store... |
eb4dd9eb182579cd3eba82bb5d1e1acfc2d55c25 | yonhyun/Artificial-Intelligence | /Bayesfilters/bayesfilters.py | 5,332 | 3.625 | 4 | import numpy as np
world = np.zeros(shape=(8, 10))
world[1:5, 1] = 1
world[2:4, 3] = 1
world[4, 2:4] = 1
world[2, 4] = 1
world[2:7, 6] = 1
world[6, 2] = 1
world[6, 4:7] = 1
world[1:5, 8] = 1
world[6:8, 8] = 1
def neighbors(world, x, y):
temp_list = []
if (world[x, y] == 1):
temp_list.append([x, y])
... |
45f5ebd5c50afdc95c512355e7f6febb1447f1c1 | DenizG13/Python-Codes | /R_S_P.py | 3,702 | 4.1875 | 4 | ##### Taş Kağıt Makas Oyunu #####
import random
import time
finish_count = int(input("How many games you want as finish point? "))
print("""\nTo select the elements please type;
s for Scissors
r for Rock
p for Paper\n
""")
player_wins = 0
computer_wins... |
8f87b112a6dc091d57d549d34a3f41d2dab03a30 | raymondFU-EAT/Q1_if-c_f | /age.py | 326 | 3.90625 | 4 | driver = input("請問有開過車嗎?")
age = int(input("請問年齡?"))
if driver == "有":
if age <= 18:
print("違法喔")
if age > 18:
print("測驗成功")
elif driver =="沒有":
if age <= 18:
print("過幾年就能考摟")
if age > 18:
print("該考個駕照瞜")
else:
print("請輸入有或沒有")
|
a2a0a5b5c8a69bc5f4d296cd6c2c78ae2a7e93b5 | josephcardillo/lpthw | /ex37.py | 6,158 | 4.5 | 4 | # and
# assert - https://docs.python.org/3.7/reference/simple_stmts.html#the-assert-statement
# asserts something is true, and if not, throws assertion error
# https://www.programiz.com/python-programming/assert-statement
coffee = True
sleep = False
def health_check():
if not coffee and sleep:
pri... |
d32aa6fa40b6dd5c0201e74f53d5bd581d6a3fe9 | josephcardillo/lpthw | /ex19.py | 1,825 | 4.375 | 4 | # creating a function called cheese_and_crackers that takes two arguments.
def cheese_and_crackers(cheese_count, boxes_of_crackers):
print(f"You have {cheese_count} cheeses.")
print(f"You have {boxes_of_crackers} boxes of crackers.")
print("Get a blanket.\n")
print("We can just give the function numbers di... |
7f97672e9989079ecf723aad9f71c57952440e35 | josephcardillo/lpthw | /ex15.py | 795 | 4.375 | 4 | # imports argv module from sys
from sys import argv
# the two argv arguments
script, filename = argv
# Using only input instead of argv
# filename = input("Enter the filename: ")
# Opens the filename you gave when executing the script
txt = open(filename)
# prints a line
print(f"Here's your file {filename}:")
# Th... |
19eda635f1a76c583aa665d8c4b696a708b8e6cf | Adoria298/greek-and-latin | /add_tags.py | 3,816 | 3.59375 | 4 | # external imports
from bs4 import BeautifulSoup, NavigableString
# stdlib imports
from pprint import pprint
from pathlib import Path
import sys
# open file - default is docs/the_ethiopians.html
path = Path(input("Please input the document you'd like to be opened: "))
if not path.exists() or not path.is_file() or not... |
d6f5fe50b26ed83e79cf18ced00601f49d116c3d | pkmlp/ggT | /ggT_Subtraktion.py | 1,081 | 3.671875 | 4 | #!/usr/bin/python
# -*- coding: latin-1 -*-
def ggt_subtraktion(zahlA, zahlB):
"""
Berechnet den grössten gemeinsamen Teiler zweier Zahlen.
Dazu wird die kleinere der beiden Zahlen von der grösseren
Subtrahiert, bis die beiden Zahlen gleich sind.
Return GGT wenn input OK, sonst -1.
... |
77ca910a2d36367d46dd70fcbb60a3fad3deac07 | mohddelpiero/Python | /while_loop.py | 446 | 3.890625 | 4 | num_of_tries=0
while num_of_tries != 3:
username = input('Please Enter Your Username: ')
password = input('Please Enter Your Password: ')
if username == 'Mohamed' and password == 'adp10': # condition
print('Welcome to our website')
num_of_tries = 0
exit()
else: # else condition
... |
448446beb4869b40a40d3948f06a4767dec18fcc | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 2. Практическое задание/task_7/task_7_2.py | 654 | 4.09375 | 4 | """
7. Напишите программу, доказывающую или проверяющую, что для множества
натуральных чисел выполняется равенство: 1+2+...+n = n(n+1)/2,
где n - любое натуральное число.
ЗДЕСЬ ДОЛЖНА БЫТЬ РЕАЛИЗАЦИЯ ЧЕРЕЗ РЕКУРСИЮ
"""
n = int(input('Введите N: '))
summ = n * (n + 1) // 2
def sequence_sum(n):
if n == 1:
... |
0acf752027a79e61e08614afe051967e62793655 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 1. Практическое задание/task_4.py | 1,653 | 3.6875 | 4 | """
Задание 4. Написать программу, которая генерирует в указанных пользователем границах:
случайное целое число;
случайное вещественное число;
случайный символ.
Для каждого из трех случаев пользователь задает свои границы диапазона.
Например, если надо получить случайный символ от 'a' до 'f', то вводя... |
4cbf9d70d37fd866daac7da5bec9eeda55edf714 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /homework_7.3.py | 4,446 | 3.546875 | 4 | # 3. Реализовать программу работы с органическими клетками, состоящими из ячеек.
# Необходимо создать класс Клетка.
# В его конструкторе инициализировать параметр, соответствующий количеству ячеек клетки (целое число).
# В классе должны быть реализованы методы перегрузки арифметических операторов:
# сложение (__add... |
09f1000e2058e584e8261d7dc437af52c3709674 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 1. Практическое задание/task_6.py | 760 | 4.34375 | 4 | """
Задание 6. Пользователь вводит номер буквы в алфавите.
Определить, какая это буква.
Пример:
Введите номер буквы: 4
Введёному номеру соответствует буква: d
Подсказка: используйте ф-ции chr() и ord()
"""
user_input_symbol = int(input('Введите номер буквы: '))
if 0 < user_input_symbol < 27:
user_in... |
3e44def6ce391382f2d8b1ef28d55fdb7c6cf01b | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /homework_3.3.py | 609 | 4.03125 | 4 | # 3. Реализовать функцию my_func(), которая принимает три позиционных аргумента, и возвращает сумму наибольших двух аргументов.
def my_func(x = int(input('Введите X: ')), y = int(input('Введите Y: ')), z = int(input('Введите Z: '))):
start_list = [x, y, z]
finish_list = []
a = max(start_list)
fin... |
6c7beee44a89b6b3f5c99e9164ebfe51db81e734 | IslamOrtobaev/This_is_my_own_private_repository_and_I_will_not_be_harassed | /Алгоритмы и структуры данных на Python. Базовый курс/Урок 2. Практическое задание/task_2_1.py | 1,043 | 4.15625 | 4 | """
2. Посчитать четные и нечетные цифры введенного натурального числа.
Например, если введено число 34560, то у него 3 четные цифры
(4, 6 и 0) и 2 нечетные (3 и 5).
Подсказка:
Для извлечения цифр числа используйте арифм. операции
Пример:
Введите натуральное число: 44
В числе 44 всего 2 цифр, из которых 2 чётных и 0 ... |
7751df9af40c3bd63d750c0095c81e06edf419cf | coolerks/backup | /Untitled-1.py | 176 | 3.84375 | 4 | c = int(input())
sum = 0
for i in range(3):
sum2 = 0
for j in range(c):
num = int(input())
sum2 += num
sum+=sum2
print(sum2,end=' ')
print(sum)
|
1804b1f3d5793f1bcf9de0f3461c9670a1f9cf19 | swetshaw/data-structures-and-algorithms | /Sorting/heap_sort.py | 1,273 | 3.59375 | 4 | import timeit
def max_heapify(a, i):
l = 2*i
r = 2*i + 1
n = len(a)
if l < n and a[l] > a[i]:
largest = l
else:
largest = i
if r < len(a) and a[r] > a[largest]:
largest = r
if largest != i:
a[i], a[largest] = a[largest], a[i]
max_heapify(a,... |
964fda70673aa5e9142298a15410934832c38665 | amyl1/GraphsB | /graph11.py | 644 | 3.5 | 4 | import networkx as nx
def Graph():
G = nx.Graph()
k = 7
for i in range(1,k+2):
G.add_node(i)
G.add_edge(1,2)
G.add_edge(1,3)
G.add_edge(1,4)
G.add_edge(1,5)
G.add_edge(2,1)
G.add_edge(2,6)
G.add_edge(2,7)
G.add_edge(3,1)
G.add_edge(3,7)
G.add_edge(4,1)... |
92d5b7baabf7a69b962240330a16f5cdd5e99873 | OGluffy/maryvillework | /total_service_score.py | 230 | 4 | 4 | score_number = input("How many days of scores? ")
sum_num = 0
for score in range(int(score_number)):
score = input("Enter score for day : ")
sum_num += int(score)
print("The total score of the 4 days is", sum_num)
|
20ffcb38f1861e553a2ecb742ec9109f9f004e52 | AmeyMankar/Leetcode | /3sum.py | 851 | 3.75 | 4 |
# Given an array nums of n integers, are there elements a, b, c in nums such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
#
# Note:
#
# The solution set must not contain duplicate triplets.
#
# Example:
#
# Given array nums = [-1, 0, 1, 2, -1, -4],
#
# A solution set is:
# [
#... |
88995d964d190f28c6f53dbe879f1f79c2c2127b | crispding/crossin_weekly | /max_product/max_product.py | 868 | 3.78125 | 4 | #!/usr/bin/env python3
"""
设定一个长度为 N 的数字串,将其分为两部分,找出一个切分位置,使两部分的乘积值最大,并返回最大值。
附加题:
输入的数字串可以重新打乱排列,比如输入 123 ,打乱排列之后会有 132,213,231,312,321 等情况,其他条件不变,求最大值。
"""
def product(num):
l = len(str(num))
result = []
for i in range(l):
p1 = num // 10**(i + 1)
p2 = num % 10**(i + 1)
m = p1 * ... |
652509579cbf2c0ebd0d7592d9193dd89b5f33db | fhca/Sistemas-Complejos-1 | /programas/Fractales/Python/sierp.py | 957 | 3.6875 | 4 | # encoding: latin-1
from Tkinter import *
import math
def sierp(e):
""" Devuelve arreglo de vértices luego de una iteración de
Sierpinski. """
r=[]
while e:
(a,b,c)=e[:3]
ab=((a[0]+b[0])/2.,(a[1]+b[1])/2.)
bc=((b[0]+c[0])/2.,(b[1]+c[1])/2.)
ac=((a[0]+c[0])/2.,(a[1]+c[1]... |
4b81280de73b54e807649466a5efdbc2b68a7adc | siuxoes/Checkio | /Elementary/Pangram.py | 680 | 3.71875 | 4 | __author__ = 'Siuxoes'
def check_pangram(text):
alphabet = "abcdefghijklmnopqrstuvwxyz"
alphabetList = []
for x in alphabet:
alphabetList.append(x)
text = text.replace(" ", "")
text = text.replace(".", "")
text = text.lower()
import re
regex = re.compile('[^a-zA-Z]')
text = ... |
f83edd4d9c5315c4a35f35526c0b994daff8243f | er1zo/school | /scripting/python/homework.py | 1,088 | 3.515625 | 4 | #!/usr/bin/python
# -*- coding: utf-8 -*-
# Autor Aleksei Volkov
# Python homework
from __future__ import print_function
from __future__ import unicode_literals
import re
import sys
import urllib2
# if there are enough params
if len(sys.argv) != 3:
print("2 params needed")
sys.exit(1)
# If the 1st file is... |
8ea90702bbf874a3d329167ccd41ed7ff532b614 | richardtiffin/wordle | /fileReader.py | 6,975 | 3.703125 | 4 | # Author: Hayk Aleksanyan
# read file and tokenize into words
import re
import codecs
import chardet # for determining the encoding of files
from pathlib import Path
from os import getcwd, listdir
from os.path import isfile, join
def readFrom(fName):
"""
tries to determine the correct encoding of the fi... |
c8dd53af112aff6cb1d4387916e28191514bc923 | reyllama/algorithms | /#1.py | 873 | 3.796875 | 4 | """
1. Two Sum
Given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
You can return the answer in any order.
"""
class Solution:
def two... |
b1a771fe478aa4f4a65c47723a82812d8e9c87ff | reyllama/algorithms | /#4.py | 1,226 | 3.609375 | 4 | """
4. Median of Two Sorted Arrays
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)).
"""
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
m, n = len(nums1), len(nums2)
... |
ad239880077af9acb2a0dd5a3cc97392fa98e869 | reyllama/algorithms | /#84.py | 1,079 | 3.765625 | 4 | """
2023.05.16
"""
"""
84. Largest Rectangle in Histogram
Given an array of integers heights representing the histogram's bar height where the width of each bar is 1, return the area of the largest rectangle in the histogram.
"""
class Solution:
def largestRectangleArea(self, heights: List[int]) -> int:
cu... |
1317ed4aa3fce3e5aa3d226b659bbc422088c767 | reyllama/algorithms | /#54.py | 688 | 3.78125 | 4 | """
2023.04.07
"""
"""
54. Spiral Matrix
Given an m x n matrix, return all elements of the matrix in spiral order.
"""
class Solution:
def rotate(self, matrix):
m = len(matrix)
if m == 0:
return
n = len(matrix[0])
out = [None for _ in range(n)]
for r in range(n):... |
992e24dd40fe7684f820d5b1742a79eea5ea4228 | linhnn247/home-work-4 | /20.8.1.py | 438 | 3.828125 | 4 | stringinput = input("Nhập chuỗi cần đếm: ")
stringlower = stringinput.lower()
lettercount ={}
for letter in stringlower:
if letter != ' ':
lettercount[letter] = lettercount.get(letter,0)+1
## ---- sap xep theo alphabetical ---- output dua ra la dang string------
sortlettercount = sorted(lettercount... |
c1592dccf20a12765b22e2c6f1fbe86c5f568487 | skyskys00/hornet-model | /test/haversine_test.py | 1,840 | 3.5625 | 4 | import unittest
import numpy as np
from src.haversine import distance, new_point
class DistanceTest(unittest.TestCase):
def test_orl_nyc(self):
"""Calculate the distance between Orlando and NY based on lat/long"""
ny_lat = 40.7128
ny_long = 74.0060
orl_lat = 28.5383
... |
6fb99f7f646c260eb763fc5804868a9bcf529971 | Shubham1744/HackerRank | /30_Days_of_code/Day_1_Data_Types/Solution.py | 777 | 4.25 | 4 |
int_2 = int(input())
double_2 = float(input())
string_2 = input()
# Read and save an integer, double, and String to your variables.
sum_int = i + int_2
sum_double = d + double_2
sum_string = s + string_2
# Print the sum of both integer variables on a new line.
# Print the sum of the double variables on a new line.
... |
07f2d3c45853ea453a147d734c87ae5978a89c8a | joelericswanson/reverse | /data/_10_create_a_pcfg_and_flip_each_rule.py | 1,846 | 3.53125 | 4 | # 10/20: Create a Probabilistic Context-Free Grammar and flip each rule
# Learn a PCFG to describe the input string. Then take the
# rules and flip each rule's right-hand side.
# Parse candidates for reverse versions, output the one with
# the highest probability.
import nltk
import random
def build_tree(word, le... |
43b94c3a290873d0fef66a8a7483b56cd74b2a12 | joelericswanson/reverse | /data/_15_api_reverse_server.py | 605 | 3.671875 | 4 | # 15/20: Look it up via an API!
# - STEP 1 OF 2 -
# Start the API server.
from flask import Flask, request
from flask_restful import Resource, Api
import json
app = Flask(__name__)
api = Api(app)
with open("./data.json", "r", encoding="utf8") as f:
reversed = json.load(f)
class ReverseString(Resource):
def... |
a965145ebc8e58468b1d0bdbc4270bf9377c0abd | TM946466/CS265_Coursework | /lab09/test_gInt.py | 3,330 | 3.578125 | 4 | #!/usr/bin/env python3
# test_gInt - Unit test for gInt class
#
# Timothy McGowan
# 6/18
# CS265 - Lab09
# Python version 3.5.2
import sys
import unittest
from gInt import gInt
class gIntTest( unittest.TestCase ) :
def setUp( self ) :
self.u1 = gInt( 1, 3)
self.u2 = gInt( -1, 3)
self.u3 = gInt( 1, -3)
se... |
de400df2981438ebf3e25e7933b15c7eca6cd91a | inquisitour/kite | /kite/env.py | 1,422 | 3.90625 | 4 | class Environment:
def __init__(self, bindings=None):
self.stack = [bindings or {}]
self.index = 0
def set(self, name, val, i=None):
"""
Assign value to a name. By default, names will be
stored in the lowest scope possible.
"""
i = i if i != None else sel... |
ad5fcd2606e3560f9ac1ed9080ab1123b749226b | jsza/getoverhere | /getoverhere/utils.py | 1,804 | 3.984375 | 4 | import os
import re
import sys
def query_yes_no(question, default="yes"):
"""Ask a yes/no question via raw_input() and return their answer.
"question" is a string that is presented to the user.
"default" is the presumed answer if the user just hits <Enter>.
It must be "yes" (the default), "no" or... |
c09e0982169645ff7257fbdeec45bc29c865af26 | yunfanz11/Riddler | /20190412_Transitive Champions.py | 2,583 | 3.734375 | 4 | #https://fivethirtyeight.com/features/how-many-times-a-day-is-a-broken-clock-right/
"""
On Sunday, the Baylor Lady Bears won the 2019 NCAA women’s basketball championship, and on Monday, the Virginia Cavaliers did the same on the men’s side.
But what about all of the unsung transitive champions? For example, earlier i... |
20547a5e4470dddc8214ba1e1b1426d5f0005140 | lealzhan/vs-python-test | /vs_python/vs_python/test_numpy.py | 1,529 | 3.984375 | 4 | # http://old.sebug.net/paper/books/scipydoc/numpy_intro.html
import numpy as np
#array
a = np.array([1,2,3,4])
print a[0]
print a.shape
b = np.array([[1,2],
[3,4],
[5,6]])
print b
c = np.array((1,2))
print c
d = np.array(((1,2),
(3,4),
(5,6)))
print d
a = np.array([[1,2]])
print "a=",a[0],a[... |
9219304b0224b30362f2965bf130c774f6e86ffb | lealzhan/vs-python-test | /vs_python/vs_python/test_json.py | 588 | 3.875 | 4 | import json
#python dict
data = {
'name' : 'ACME',
'shares' : 100,
'price' : 542.23
}
print data
#python dict => json str
json_str = json.dumps(data)
print json_str
#json str => json structure
json_structure = json.loads(json_str)
print 'name',json_structure['name']
print 'share',json_structure['shares']
print 'p... |
611276f4827e994bc6e80d36d32ebad708ade636 | AmrReda/Algorithms | /src/Algorithm Implementation/Geometry/Convex hull/convex_hull.py | 837 | 3.796875 | 4 | """Computes the convex hull of a set of 2D points.
Input: an iterable sequence of (x, y) pairs representing the points.
Output: a list of vertices of the convex hull in counter-clockwise order,
starting from the vertex with the lexicographically smallest coordinates.
Implements Andrew's monotone ch... |
e08a591e4db84ac0af86e6b5b23c67dc01bea59f | arturtondera/palindrome | /palindrome.py | 418 | 3.96875 | 4 | def palindrome_check(word):
# dwie listy o tej samej zawartości
list_of_letters1 = list(word)
list_of_letters2 = list(word)
# odwracam kolejność jednej z nich:
list_of_letters2.reverse()
# i powrównuję, co jest sprawdzeniem, czy wyraz jest palindromem:
if list_of_letters1 == list_of_letters2... |
ada6b8f20ce70a8e13fcdc0109a4dc0d66a4bf96 | kajal-puri/game-ai-bonn-ss18 | /project-3/breakout.py | 15,458 | 4.0625 | 4 | """
Sample Breakout Game
Simpson College Computer Science
http://programarcadegames.com/
http://simpson.edu/computer-science/
Modified Version using Fuzzy Controller (With acceleration)
"""
# --- Import libraries used for this program
import math
import pygame
import numpy as np
import skfuzzy as fuzz
impor... |
b533021e17e50136a1f8ec89e42bf0a997321b96 | kajal-puri/game-ai-bonn-ss18 | /project-1/connect-four.py | 5,870 | 3.671875 | 4 | import itertools
import matplotlib.pyplot as plt
import numpy as np
import random
HIGHT = 6
WIDTH = 7
WINNING_NUMBER = 4
def move_still_possible(S):
return not (S[S==0].size == 0)
# Return all column indices of columns
# in which there exists a free entry.
def column_with_empty_entries(S):
return np.where(np... |
da6446fb7b0517ad02561cffe7105709de7f9791 | pradeeplam/CSCI567 | /Assignment-1/hw1_perceptron.py | 3,039 | 3.84375 | 4 | from __future__ import division, print_function
from typing import List, Tuple, Callable
import numpy as np
import scipy
import matplotlib.pyplot as plt
class Perceptron:
def __init__(self, nb_features=2, max_iteration=10, margin=1e-4):
'''
Args :
nb_features : Number of feature... |
91398f8c733f0f328e0c5857efbd82c396db9288 | Achilik/holbertonschool-higher_level_programming-2 | /0x01-python-if_else_loops_functions/101-remove_char_at.py | 194 | 3.90625 | 4 | #!/usr/bin/python3
def remove_char_at(str, n):
result = ""
for character in range(0, len(str)):
if character != n:
result = result + str[character]
return result
|
af307494a05c08ba8666b2f8d15f30f6d839211a | Achilik/holbertonschool-higher_level_programming-2 | /0x05-python-exceptions/0-safe_print_list.py | 229 | 3.875 | 4 | #!/usr/bin/python3
def safe_print_list(my_list=[], x=0):
try:
for item in range(0, x):
print(my_list[item], end='')
print('')
return (x)
except:
print('')
return (item)
|
fb4212546facccbf2716e6856740a519dfaab41e | jasonpark3306/python | /.vscode/Tutorial/testDictionary.py | 1,418 | 4.09375 | 4 | # mydict = {"name":"Max", "age":29, "city":"New York"}
# print(mydict)
# mydict2 = dict(name="Mary", age=28, city="Boston")
# print(mydict2)
# print(mydict["name"])
# mydict["email"] = "max@xyz.com"
# print(mydict)
# del mydict["name"]
# print(mydict)
# mydict.pop("age")
# print(mydict)
# mydict.popitem()
# print(... |
708315c5cf4a58307bfd3b06f94cee08f7e63b8a | jasonpark3306/python | /.vscode/Tutorial/python_tips_tricks.py | 2,105 | 3.578125 | 4 | from getpass import getpass
#Tip 08
username = input("Username:")
# password = input("Password:")
password = getpass("Password:")
print('Logging in....')
#Tip 07
# class Person:
# pass
# person = Person()
# person_info = {'first' : 'Corey', 'last':'Schafer'}
# for key, value in person_info.items() :
# se... |
bd25ff4a65a268848778917df39b996f2cf4f9f0 | jasonpark3306/python | /.vscode/Sort/selection_sort.py | 456 | 3.9375 | 4 | import random
def selection_sort(arr:list) -> None :
for i in range(len(arr)-1) :
min_index = i
for j in range(i+1, len(arr)) :
if arr[j] < arr[min_index] :
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
elements = []
for i in range(10) :
e... |
e9ac2dac71e46570b68a4301a5a19429d8b18bec | jasonpark3306/python | /.vscode/DataStructure/binary_tree.py | 4,306 | 3.671875 | 4 | class BinarySearchTreeNode :
def __init__(self, data) :
self.data = data
self.left = None
self.right = None
def addNode(self, data) :
if (self.data == data) :
return
if data < self.data :
if self.left :
self.left.addN... |
1796324a61f79d402f6e45128d6ae1ca671d62a0 | jasonpark3306/python | /.vscode/SWDesign/MathFunctions.py | 1,062 | 3.859375 | 4 | """
LIST FUNCTIONS
"""
def get_max(list) :
mx = float("-inf")
for num in list:
if num > mx :
mx = num
return mx
def get_min(list) :
mn = float("inf")
for num in list :
if num < mn :
mn = num
return mn
def get_average(list) :
return sum(list) ... |
5d84a0353dda50e73ebd3fac709699c1c143a3f7 | matheusschuetz/HbsisJedi | /BlackJack/baralho.py | 1,033 | 3.578125 | 4 | import random
class Baralho:
def __init__(self):
self.J, self.Q, self.K, self.A = 10, 10, 10, 'A'
self.lista_cartas = [1, 2, 3, 4, 5, 6, 7, 8, 9, self.A, self.J, self.Q, self.K]
def embaralhar(self):
random.shuffle(self.lista_cartas)
def hint(self):
lista_quantidade = []
... |
d1db4f25896af9d30f47a8fb70598d73e61f23a2 | DarkEyeX/CSES | /weird algorithm.py | 196 | 3.953125 | 4 | def weird(n):
print(n, end=' ')
if n == 1:
return(n)
elif n % 2 == 0 :
return(weird(n//2))
else:
return(weird((n*3)+1))
n = int(input())
weird(n)
|
4a182315b049afb21b4d296855f44ffa59d3686b | infamousdarius/Python-Practice | /Core_Python/File Handling/Check if File exist.py | 269 | 3.734375 | 4 | import os
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
f = open("demofile.txt", "x")
f.close()
if os.path.exists("demofile.txt"):
os.remove("demofile.txt")
else:
print("The file does not exist")
|
56daa260b2cf45ac356b2cc2258aa6e26798252c | MorganFrenk/farmy_game_telegram_bot | /objects/items.py | 1,950 | 3.59375 | 4 | import random
from .settings import power_setting
class Item():
'''Item in the game with price and power'''
def __init__(self, name, power, price):
self.name = name
self.power = power
self.price = price
def __repr__(self):
return f'<Item {self.name} with power {self.power... |
cff97b2c99af7fe57a02233fb49e0e09db361242 | bagreve/Nivelacion | /26082019/000000.py | 771 | 4.15625 | 4 | # En la nivelacion numero 6,se ensana como usar y crear diccionarios
d = {} # Se crea un diccionario vacio
d["George"] = 24 # se crean nuevos valores ligados a llaves , siendo George la llave y su edad el valor
d["Tom"] = 32
d["Jenny"] = 20
d[10] = 100 # no solo se pueden crear listas con llave... |
27614f70694b592025fefaf402816d3b35e71d4c | soumitra9/PreCourse_2 | /Exercise_5.py | 1,600 | 3.671875 | 4 | # Time Complexity : O(n log n) where n is the number of nodes
# Space Complexity : O(h) = O(log n)
# Did this code successfully run on Leetcode : Yes
# Any problem you faced while coding this : Yes a little bit, I got confused about how to imitate pre order
# traversal iteratively, and how to account for low,high. B... |
8b6d3936e2640ce964e96be5c7a6ba1dcaa54caf | vg283/DS-Algos | /DP/word_break_with_all_arrangements.py | 2,264 | 4.0625 | 4 | # Problem: Given a dictionary of words and a pattern. We need to find ALL possible ways to break down the pattern into
# smaller words such that each of those words are present in the dictionary.
# Solution:
# Recursive approach: Starting from index 0 of the pattern, adding one character at a time, check if the char se... |
2247136f9770d6ed6ba472967a47eaa507d62f95 | chenzeshenga/python_lessons | /com/chenzeshenga/study/while03.py | 162 | 3.640625 | 4 | i = 1
while i < 10:
j = 1
while j <= i:
result = i * j
print("%s*%s=%s" % (j, i, i * j), end="\t")
j += 1
print()
i += 1
|
345011432993c9ac7315aa56bfdd9c764023f0cc | chenzeshenga/python_lessons | /com/chenzeshenga/study/for01.py | 126 | 3.578125 | 4 | for i in "ahdkhkhsbcksdhfks":
print(i)
else:
print("end")
for i in range(1, 10):
print(i)
else:
print("end")
|
2f5057fee369e35fd3d1f3ff230a22c013a8a676 | josealbm/PracticasPython | /Práctica 3/P3E3.py | 647 | 4.0625 | 4 | #Práctica 3 - Ejercicio 3 - José Alberto Martín
#Pida al usuario si quiere calcular el área de un triángulo o un cuadrado, y pida los
#datos según que caso y muestre el resultado.
figgeo=input("Dime si prefieres calcular el área de un cuadrado o un triángulo ")
if figgeo==("cuadrado"):
lado=int(input("Dime... |
efcb3598b115a7a810bdd345d75cfa5448c645bb | josealbm/PracticasPython | /Práctica 2/P2E8.py | 682 | 3.984375 | 4 | día=int(input("intoduce el día "))
mes=int(input("intruduce el mes "))
año=int(input("introduce el año "))
bisiesto= año%4
if (día>31) or (día<1) or (mes>12) or (mes<1):
print("La fecha",día,"/", mes, "/", año, "es incorrecta")
elif (año>2100) or (año<1980):
print ("La fecha",día,"/", mes, "/", año, ... |
250bbfc0aac5bf851b2cdb6ca2ca7fc5a2d658af | josealbm/PracticasPython | /Práctica 3/P3E2.py | 684 | 4.25 | 4 | #Práctica 3 - Ejercicio 2 - José Alberto Martín
#Pida al usuario 5 números y diga si estos estaban en
#orden decreciente, creciente o desordenados.
print ("Escribe cinco números y te diré que orden has utilizado")
a=int(input("Escribe el primer número "))
b=int(input("Escribe el segundo número "))
c=int(input... |
a8139a87f03cc8a94f98fb02541d3b19272d7367 | josealbm/PracticasPython | /Práctica 4/P4E5.py | 543 | 4.0625 | 4 | #Práctica 4 Ejercicio 5 - José Alberto Martín
#Escriu un programa que demani l'amplada i alçada d'un rectangle i ho dibuixi de la següent
#manera:
#Amplada del rectangle: 5
#Alçada del rectangle: 3
#*****
#*****
#*****
alt=int(input("Escribe la altura de tu rectángulo "))
base=int(input("Escribe la base de... |
670efb0e6c1807247434ea2b21f83dbccddb5e28 | josealbm/PracticasPython | /Práctica 7/P7E4.py | 428 | 4.25 | 4 | #Práctica 7 -Ej 4 - José Alberto Martín Marí
#Escribe un programa que pida una frase, y le pase como parámetro
#a una función dicha frase. La función debe sustituir todos
#los espacios en blanco de una frase por un asterisco,
#y devolver el resultado para que el programa principal la imprima
#por pantalla... |
6dad818288d32ed0797f59fc4af3700c49a6e6b8 | josealbm/PracticasPython | /Práctica 5/P5E12.py | 1,901 | 4.125 | 4 | #Práctica 5 - Ejercicio 12 - José Alberto Martín Marí
#Escriu un programa per a jugar a endevinar un nombre (l'usuari pensa un nombre i el programa
#l'ha d'endevinar). El programa comença demanant entre què nombres està el nombre
#a endevinar i després intenta endevinar de què nombre es tracta. L'usuari va
#dient s... |
289f8b01db267f8d45dea5b449a2657a59c1cba9 | josealbm/PracticasPython | /Práctica 2/P2E3.py | 244 | 3.734375 | 4 | km=int(input("Por favor, dime cuántos kilómetros has hecho "))
time=int(input("Ahora dime cuántas horas has tardado en realizar tu recorrido "))
velocidad = km/time
print ("Tu velocidad media ha sido", velocidad ,"kilómetros por hora")
|
3b5d980707776d526c7bee921f2cf7ace2f9dd4e | beaubadilla/cpsc386_intro_game_design | /super-mario/background.py | 881 | 3.515625 | 4 | import pygame
from pygame.sprite import Sprite
class Background(Sprite):
def __init__(self, screen):
"""Initialize the mario, and set its starting position."""
super(Background, self).__init__()
self.screen = screen
# Load the background image, and get its rect.
self.image... |
0588c0bd94e17ff84616c9868f2bd5d29b7d830a | CodeKul/Python-Jan-2020-Weekday-10am | /AccessControl.py | 956 | 3.75 | 4 | class Account:
def __init__(self, name, acc_no, phone, type):
super().__init__()
self.name = name
self.acc_no = acc_no
self.phone = phone
self.type = type
self.__balance = 0
def account_info(self):
print("Name:", self.name)
print("Account no:", s... |
55d75b6a7c9384b01530c73695071736b276dca9 | CodeKul/Python-Jan-2020-Weekday-10am | /Inheritance.py | 893 | 3.71875 | 4 | class Employee:
def __init__(self, id, name, salary):
super().__init__()
self.id = id
self.name = name
self.salary = salary
def info(self):
print("Id:", self.id)
print("Name:", self.name)
print("salary:", self.salary)
class Developer(Employee):
def ... |
6ad023dc40a19c46dec48a27c9f4a6b83d0711c5 | potykion/leetcode-blya | /src/6_Best_Time_to_Buy_and_Sell_Stock.py | 1,796 | 3.84375 | 4 | from typing import List
class Solution:
"""
https://leetcode.com/problems/best-time-to-buy-and-sell-stock/
>>> prices = [7,1,5,3,6,4]
>>> Solution().maxProfit(prices)
5
>>> prices = [7,6,4,3,1]
>>> Solution().maxProfit(prices)
0
>>> prices = [1]
>>> Solution().maxProfit(prices... |
f5ab83a0491988fac7c9d5a6573bcb457215f2d5 | potykion/leetcode-blya | /src/7_Maximum Subarray.py | 2,588 | 3.828125 | 4 | from collections import deque
from typing import List
class Solution:
"""
https://leetcode.com/problems/maximum-subarray/
>>> s = Solution()
>>> nums = [3,2,-3,-1,1,-3,1,-1]
>>> s.maxSubArray(nums)
5
>>> nums = [-1,-2,3,-1,-2,1,1]
>>> s.maxSubArray(nums)
3
>>> nums = [-1,1,-1,... |
31fe246810d4d6ee9d5aa7c5e8b0e5b8120195fd | tanujdey7/Python | /Python_Assignment_3/3.py | 273 | 4.09375 | 4 | #GitHub.com/tanujdey7
try:
num1 = int(input("Enter Number 1: "))
num2 = int(input("Enter Number 2: "))
ans = num1/num2
print(ans)
except ValueError:
print("Enter Numeric Value")
except Exception as e:
print("Can't Divide by Zero "+str(e))
|
96c8108dee8899654bf58a9571560cf242daf238 | jorillac105/AdventureOfChefChef | /navGraph.py | 4,515 | 3.609375 | 4 | import edge
import node
import math
import queue as Q
class navGraph():
def __init__(self, map, walkableTiles, levelNum):
self.tiles = walkableTiles
self.graph = self.createNodes(map)
self.createEdges()
self.levelNum = levelNum
# for y in range(len(self.graph)):
# for x in range(len(self.graph[y])):
... |
ad07b60b0c4d663663a286ca854833a903e3ee6a | Philiplam4516/TRM | /Python Workshop/Advnaced Python/Codes/Functions/Functions/F05.py | 431 | 4.125 | 4 | '''
Write a program to get a circle radius from terminal,
and then compute the area of the circle by a function
'''
PI = 3.14
def compute_circle_area(radius):
return radius*radius*PI
def main():
print("Enter a circle radius (m)")
radius=input()
radius = float(radius) # type cast from string to float
area... |
89697577538e9347c184c7eb4f0bf3f0cea71ad7 | Philiplam4516/TRM | /Python Workshop/Advnaced Python/Codes/Functions/Functions/F03.py | 497 | 3.8125 | 4 | '''
Pass by reference in Python functions
'''
def test_pass_by_reference(arg_fruits):
print("id of arg_fruits", id(arg_fruits))
#change the 0th element
arg_fruits[0] = "orange"
print("id of arg_fruits", id(arg_fruits))
#append a new element
arg_fruits.append("grape")
print("id of arg_fruits", id(arg_... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.