blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
5a367d3dd3e82aa5d85c20ea4554371c2c6849f1
bingli8802/leetcode
/0652_ Find_Duplicate_Subtrees.py
1,190
3.734375
4
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution(object): def findDuplicateSubtrees(self, root): """ :type root: TreeNode :rty...
5b4880ce175d8be6af3722c888fbb4d504188293
madeibao/PythonAlgorithm
/PartB/Py双指针解决两数之和的问题.py
341
3.546875
4
class Solution(): def sumOfTwo(self,nums, target): i = 0 j = len(nums)-1 while i < j: temp = nums[i] +nums[j] if temp==target: return [l+1, r+1] elif temp>target: j-=1 else: i+=1 return [] if __name__ == "__main__": s = Solution() list2 =[2, 7, 9, 13] target = 9 print(s.sumOf...
f94e2f8d0a23596689200a00e4cabc7fe7f56185
shoriwe-upb/TallerEjercicios
/Exercises/start_with.py
241
3.859375
4
def main(): text = input("Text: ").split(" ") word = input("Word: ") if text[0].lower() == word.lower(): print("They are the same") else: print("They are not the same") if __name__ == '__main__': main()
477e7d33fdfe77dbcd4555976ef5ff49e10d85a8
QIAOZHIBAO0104/My-Leetcode-Records
/1738. Find Kth Largest XOR Coordinate Value.py
1,073
4.0625
4
''' https://leetcode.com/problems/find-kth-largest-xor-coordinate-value/ You are given a 2D matrix of size m x n, consisting of non-negative integers. You are also given an integer k. The value of coordinate (a, b) of the matrix is the XOR of all matrix[i][j] where 0 <= i <= a < m and 0 <= j <= b < n (0-indexed). Find ...
03441d8b5dcea3afc44ab8274f659ef8e8fcd077
Junow/python-algorithms
/algorithms/binary-search/binarySearch.py
254
3.765625
4
def binarySearch(arr, l, r, target): m = int((l+r)/2) if l > r: return None if arr[m] == target: return m if arr[m] < target: return binarySearch(arr, m+1, r, target) if arr[m] > target: return binarySearch(arr, l, m-1, target)
5e399a6bd3b6bc4ce47b61877b375c6698b2a65b
briankw1108/MITOPENCOURSEWARE
/psets/ps1/ps1b.py
820
3.984375
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 20 14:27:38 2018 @author: bw033154 """ # Problem Set 1 B annual_salary = int(input("Enter your annual salary: ")) portion_saved = float(input("Enter the percentage of your salary to save, as a decimal: ")) total_cost = int(input("Enter the cost of your dream house: ")) ...
2f792e2882837b75ee2a1e21a223257d2215720f
anthonychl/python-and-flask-bootcamp-create-websites-using-flask
/04 flask basics/05-Routing_Exercise.py
721
3.625
4
# Set up your imports here! # import ... from flask import Flask app = Flask(__name__) @app.route('/') # Fill this in! def index(): return "<h1> Hello go to /puppy_latin/type_a_dog_name_here </h1>" @app.route('/puppy_latin/<name>') # Fill this in! def puppylatin(name): # This function will take in the name p...
da525aece71f7807d490393317310381de92659f
gomanish/Python
/basic/7th.py
296
3.53125
4
''' ANIMAL CRACKERS: Write function takes a two-word string and returns true if both words begin with same letter''' def animal_crackers(text): return(text.lower().split()[0][0]==text.lower().split()[1][0]) print(animal_crackers('Levelheaded Llama')) print(animal_crackers('Crazy Kangaroo'))
0421776f1cadb3d2575f750379f7002259cedb6a
DanOakeley/OakeleyDJF-Year12ComputerScience
/coding/ACS Prog tasks/08 Words Words Words.py
219
4.1875
4
#program to take a sentence and output the number of words. sSentence = str(input("Please input your sentence.")) nNumofwords = len(sSentence.split()) print("The number of words in the setence are: " + str(nNumofwords))
d6efae86d0fd45232676619de09398833a3f78d8
seen2/Python
/DataStructure/LinkedList/main.py
423
3.578125
4
from linkedList import LinkedList # from linkedList1 import LinkedList def main(): l = LinkedList(9) l.insert(10) l.insert(9) l.insert(11) l.insert(11) # l.deleteDups() # print("\n") # print(l.delete(11)) l.display() print() print(l.deleteKth(1)) print("\n") try: ...
d4f7b9146b6a97eb73d1df0c11ef791abdbc7803
alfonsog714/Sorting
/src/recursive_sorting/recursive_sorting.py
3,244
4.1875
4
# TO-DO: complete the helper function below to merge 2 sorted arrays #arrA and arrB must be sorted! Expect already sorted arrays. def brady_merge( arrA, arrB ): print(f"MERGE: {arrA} - {arrB}") num_elements = len( arrA ) + len( arrB ) merged_arr = [0] * num_elements # 3. Start merging your single lists...
f2297d36ee447a213cf69206d9087a46b72aec7e
makhmudislamov/leetcode_problems
/intr_cake/validate_bst.py
3,128
4.15625
4
""" Write a function to check that a binary tree ↴ is a valid binary search tree. ↴ """ # Here's a sample binary tree node class: class BinaryTreeNode(object): def __init__(self, value): self.value = value self.left = None self.right = None def insert_left(self, value): self...
778dbc2968f0444b4e5cf0f2428edd748377aacf
ZhangYajun12138/buxianxian
/BuXianXian/buxianxian18.py
685
3.59375
4
# coding:utf-8 # dictionary字典 def main(): scores = { "yajun":100, "luozng":95, "lige":88 } # 通过key可以获取字典中对应的值 print(scores["yajun"]) print(scores["luozng"]) #遍历 for item in scores: print("key:",item,"---value:",scores[item]) # 更新 scores["yajun"] = ...
1467d722b26c1fbe4aa595b104ef410d64ab72c4
csinrn/SimpleTCPClient
/simpleTCPclient.py
654
3.640625
4
import socket import sys def TCPsend(ip, port, msg): clientsock=socket.socket() addr = (ip, port) clientsock.connect(addr) clientsock.send(bytes(msg, encoding='gbk')) rec = clientsock.recv(1024) res = str(rec, encoding='gbk') clientsock.close() return res if __name__ == '__main__': ...
86135d4598a9f14f43e75173d5698ce6fb8b0f42
subash143-zz/leetcode_exercises
/easy/e_821.py
675
3.71875
4
# https://leetcode.com/problems/shortest-distance-to-a-character/ # 821. Shortest Distance to a Character class Solution(object): def shortestToChar(self, s, c): """ :type s: str :type c: str :rtype: List[int] """ indices = [] for i in range(len(s)): ...
a6a90aff2e9d6e6f9076aeea4f4d19c4d56a0508
maq1995/JianZhi_offer_python
/Q45_圆圈中最后剩下的数字.py
3,003
3.734375
4
# encoding: utf-8 """ @project:JianZhi_offer @author: Ma Qian @language:Python 2.7.2 @time: 2019/9/18 上午10:21 @desc: """ ''' 题目:0,1,...,n-1这n个数字排成一个圆圈,从数字0开始每次从这个圆圈里删除第m个数字。求出这个圆圈里剩下的最后一个数字。 例如0,1,2,3,4这五个数字组成一个圆圈,从数字0开始每次删除第3个数字,则删除的前四个数字依次是:2,0,4,1,最后剩下的数字是3. ''' ''' 解法1:用环形链表模拟圆圈 ''' class ListNod...
df0f4f322907fc2daddc24fcb2c695780bc56145
IshitaPEC/Web-Scraping-Tutorial-Assignments
/regex.py
3,264
4.5
4
import re #Specialised language used to search for text within a given document with precision and efficiency #Special characters which cannot be matched are: # META CHARACTERS: ^,$,*,+,?,{,},[,],\,|,(,) #Regular expressions -> primarily used for string matching #regex= re.compile(pattern) #regex.match(main_string) #W...
d9f5d75939077467f4302339c443616ccc408e70
Aissen-Li/LeetCode
/987.verticalTraversal.py
1,285
3.859375
4
from typing import List # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def verticalTraversal(self, root: TreeNode) -> List[List[int]]: if not root: return [[]] dic = ...
67c6e394580052edfc0d95f890ff532dae538fb8
Vahid-Esmaeelzadeh/CTCI-Python
/Chapter2/Q2_1.py
1,020
3.625
4
''' LinkedList Remove Dups: Write code to remove duplicates from an unsorted linked list. FOLLOW UP How would you solve this problem if a temporary buffer is not allowed? ''' from Common.common import * # using Hash-Set def removeDups(ll: linkedList): n = ll.head dataset = set() prev = Node() while n:...
3b0077d73751e248398ee5ba2c28de16c82f568d
bosen365/PythonStudy
/oop/Property.py
913
3.78125
4
# !/usr/bin/env python3 # -*- coding:utf-8 -*- '@property属性使用' __author___ = "click" class Property(object): @property def height(self): return self.__height @height.setter def height(self, value): if value <= 0: print("高度必须大于0") else: print("输入高度合格")...
1666a86caf2d0a37a13a9b6b62bac060c9813474
jkh-code/data_science
/assignments/algorithmic-complexity/src/sorters.py
1,192
3.890625
4
from abc import ABC from time import time def timeit(fn): def timed(*args, **kw): ts = time() fn(*args, **kw) te = time() return te - ts return timed class SortTester(ABC): """ Abstract base class for our sorting classes Allows for the calling of a sort, a stac...
f7a6ae298dc4641c1f3c1dee572a7ff7e86c864e
maccergit/Euler
/prob007 - 10001st prime/prob007/002.py
622
3.65625
4
# coding: utf8 """ 10001st prime By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can see that the 6th prime is 13. What is the 10 001st prime number? pyprimesieve - 60 µsec """ import timeit import pyprimesieve def getSolution(limit): return pyprimesieve.primes_nth(limit) assert getSolution...
d5b7aae1212c2ecfef6166335af8d070c73c461d
ChimCatz/Pirple.com_Python_Is_Easy
/homework3.py
701
4.34375
4
# HOMEWORK #3 If Statements # Change to "Hot" or "Cold" for Weather Weather = "Cold" # Change Temperature value to any Integer or String Temperature = "9" Temperature = int(Temperature) Umbrella = True Jacket = False # IF statement conditions and output if Weather == "Hot" and Temperature >= 25: U...
a20f12fe0c69a5fdaf266416a874eacebf149f51
rfilmyer/lobbyist
/hearing.py
2,201
3.984375
4
import random class Question(object): def __init__(self): self.question_pool = { 'kids' : "What about the children? What impact does {0} " "legislation have on my younger constituents?", 'deficit' : "What impact does {0} have on the deficit?", 'elec_year' : "This is an elect...
be4efb87ece486ca4c3f65fccb756f24779df5e1
Cherry93/coedPractices
/demos/W1/day3/02GetUserInput.py
436
3.875
4
''' ·接收矩形的宽高,输出其面积 ·接收三个值,求其平均值 ''' # # 同时输入多个数值型字符串,转换类型,并使用多个变量进行接收 # a,b = eval(input("请输入矩形的宽高")) # print(a,b) # # # 计算并打印结果 # area = a*b # print("矩形的面积是",area) # print("矩形的面积是",a*b) a,b,c = eval(input("请输入三个数值")) print("他们的平均值为",(a+b+c)/3)
e8f95885a1b434dc8acb7b7b98aa935152f33a32
William93/swat
/multithreading.py
4,099
3.5625
4
# import Queue # import threading # import urllib2 as ul # # called by each thread # def get_url(q, url): # q.put(ul.urlopen(url).read()) # theurls = ["https://www.google.com.sg/?gfe_rd=cr&ei=54GhVuizL6Gl8weftLPACQ", "http://mainichi.jp/"] # q = Queue.Queue() # for u in theurls: # t = threading.Thread(target=get_...
b78930a4d7943fe816772522c9569e4236d26f2e
Karthicksaga/python-Exercise
/python alphaphet pattern/printingname.py
191
3.953125
4
#printin name as pramid string = str(input("Enter the string:")) k=len(string) for row in range (k): for col in range (row+1): print(string[col] , end = " ") print()
ec34b12ca522ba41fa089b29ae1c4ca82df3bc24
denze11/BasicsPython_video
/theme_5/3.py
613
4.34375
4
# 3: Дан список заполненный произвольными целыми числами. # Получите новый список, элементами которого будут только уникальные элементы исходного. # Примечание. Списки создайте вручную, например так: # my_list_1 = [2, 2, 5, 12, 8, 2, 12] # # В этом случае ответ будет: # [5, 8] my_list = [2, 2, 5, 12, 8, 2, 12] new_li...
b6439365be9b5fc0fe2a421cd4682c4b1b5e9846
LeonLipu/python-learning
/function.py
303
3.75
4
#it happens in functional programming def expon(element,n): if(n==0): return 1 else: return element*expon(element,n-1) print expon(5,3) arr=[(lambda x:x*x)(x) for x in range(10)] print arr def f(n): for i in range(n): yield i**3 for x in f(5): print x
a5b837da46ee36c54e138755bf9683b1694ae9b6
Anshul1196/leetcode
/solutions/22-2.py
734
3.75
4
""" Solution for Algorithms #22: Generate Parentheses Runtime: 40 ms, faster than 85.82% of Python3 online submissions for Generate Parentheses. Memory Usage: 13.3 MB, less than 5.10% of Python3 online submissions for Generate Parentheses. """ class Solution: def recursion(self, prefix: str, left: int, righ...
72f2a756c99e09b7ff1f08309d08c186b24faa7a
JulyKikuAkita/PythonPrac
/cs15211/ShiftingLetters.py
2,781
3.859375
4
__source__ = 'https://leetcode.com/problems/shifting-letters/' # Time: O(N) # Space: O(N) # # Description: Leetcode # 848. Shifting Letters # # We have a string S of lowercase letters, and an integer array shifts. # # Call the shift of a letter, the next letter in the alphabet, # (wrapping around so that 'z' becomes '...
83a3c9a85beb0cb8e151f21ca2d4c2c66da15b02
AllanBastos/Atividades-Python
/ALGORITMOS E PROGRAMAÇÃO/Roteiro 1/Identificando Região de Procedência.py
285
4
4
codigo = int(input()) if codigo == 1: print("Nordeste") elif codigo == 2: print("Norte") elif codigo == 3 or codigo == 4: print("Centro-Oeste") elif 5 <= codigo <= 9 : print("Sul") elif 10 <= codigo <= 15 : print("Sudeste") else: print("Regiao nao encontrada")
99a10c6486b8c9962b9ed0d7319a157da59f1a17
collegemenu/week2-hello-world
/helloworld.py
1,123
4.5
4
# Joel Mclemore # write a program that: # 1. greets the user in English # 2. asks the user to choose from 1 of 3 spoken languages (pick your favorite languages!) # 3. displays the greeting in the chosen language # 4. exits # make sure that your code contains comments explaining your logic! while True: #While loop to...
965bde543d0529d4befb3ada7601693583f06162
crizzy9/Algos
/leetcode/merge_k_sorted_ll.py
1,993
3.890625
4
# Definition for singly-linked list. from operator import itemgetter import sys class ListNode: def __init__(self, x): self.val = x self.next = None def __repr__(self): return "{}->{}".format(self.val, self.next) class Solution: def mergeKLists(self, lists): """ :t...
0437786ce3b34dc2eefca0cb51b15c90459317b3
anabeatrizzz/exercicios-pa-python
/exercicios_1/exercicios_1_03.py
293
4.125
4
# Escreva um programa que leia um número inteiro, calcule e exiba o resultado do quadrado deste número. # (usar função da classe Math) import math num = int(input("Escreva um numero para saber sua raiz quadrada: ")) quadrado = math.pow(num, 2) print(f'O quadrado de {num} é {quadrado}')
42e41fe49ba193130eaff3489c19434724406e2b
evertondutra/Curso_em_Video_Python
/exe072.py
604
4.09375
4
""" Crie um programa que tenha uma tupla totalmente preenchida com uma contagem por extensão, de zero a vinte. Seu programa deverá ler um número pelo teclado(entre 0 e 20) e mostrá-lo por extenso. """ ext = ('zero', 'um', 'dois', 'tres', 'quatro', 'cinco', 'seis', 'sete', 'oito', 'nove', 'dez', 'onze', 'doze', '...
8c30dca9fafcb7ec040aefa341796e4bfdd86c17
Anshul8j/nepactober
/Python Basics/pclass2.py
68
3.640625
4
str1="abc" str2="xyz" print(str1[:2]+str2[2:]+' '+str2[:2]+str1[2:])
518e5b723d0d26addb259ab2b57645c4c982e99a
MariannaKrawczak/zadanieCodecool
/Python test .py
2,932
3.828125
4
# # # print("Hello, World!") # # # a = 10 # # # b = 5 # # # c = a ** b # # # print(c) # # # print(c) # # # print("nananana") # # print("Tell us your name: ") # # name = input() # # print("Hello, "+ name+ '!') # print ("Provide a number") # number = int(input) # if number == 0: # print("You've typer ZERO!") #...
2cc1c9c67c2668fa619b810e20abf85562da3fee
jiaxiaochu/spider
/02-Regular/06-2-re模块的高级用法-sub.py
525
3.703125
4
# !/Library/Frameworks/Python.framework/Versions/3.7/bin/python3 # @blog : www.jiazhixiang.xyz # @Author : Jiazhixiang # -*- coding:utf-8 -*- # sub 将匹配到的数据进行替换 # 需求:将匹配到的阅读次数加1 import re # 方法1: ret = re.sub(r"\d+", "999", "python = 997") print(ret) # 方法2: import re def add(temp): strNum = temp.group() num =...
20d5a963f394bcc4623f3f7019f2117991a77e26
alvarodelaflor/ssii
/CAI/cai2/apartado_a/test1.py
369
3.65625
4
import threading x = 0 i = 1 def increment(): global x, i while i < 50000: x +=1 i += 1 def main(): hilo_1 = threading.Thread(target= increment) hilo_2 = threading.Thread(target= increment) hilo_1.start() hilo_2.start() hilo_1.join() hilo_2.join() if __name__ == "__ma...
fac8df9000cc9faac67e6d532770c4a8a05bce2b
Declan-Routledge/BBC-Sounds---Junior-Engineer-Challenge
/csvtool/csvTool.py
2,078
3.8125
4
import csv # Requires user to input a row of data at a time. Updates the CSV file of an appended row def Add(id, album_title, artist, year_released): with open('rms_albums.csv', 'a', newline='') as csvfile: writer = csv.writer(csvfile) writer.writerow([id,album_title,artist,year_released]) ...
4d9e71e4cc85f4ddc20a239e25018058054a686a
myliu/python-algorithm
/leetcode/binary_tree_level_order_traversal_ii_v1.py
1,247
3.875
4
import collections # Definition for a binary tree node class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: # @param root, a tree node # @return a list of lists of integers def levelOrderBottom(self, root): """ ...
aee0c42abe3eb8eff6ca6eea7e40f1e60b57b515
LuluwahA/100daysofcode
/Day 36.py
200
3.59375
4
def myfun(n): return lambda a:a*n mydoubler=myfun(2) print(mydoubler(11)) def myfun(n): return lambda a:a*n mydoubler=myfun(2) mytr=myfun(3) print(mydoubler(11)) print(mytr(11))
1d99c418551ff52b5593b4efeabf189b4d7990f0
Posanderi/Posanderi.github.io
/functions.py
2,409
3.765625
4
def party_cmap(party): ''' A function that returns a color value according to what finnish political party was given as an input. input: Party: The short name of the party. The parties with unique colors are SDP, PS, KOK, KESK, VIHR, VAS and RKP. Other inputs return the same colorvalue. ...
2c407ba889a40809ae3ea5dc119eb750b71ac0c1
kidpeterpan/my-python-tutorials
/org/konghiran/lesson/_03_methods_and_functions/_00_methods_and_python_document.py
179
3.703125
4
my_list = [1,2,3] my_list.append(4) # .append is a method print(my_list) my_list.pop() # .pop is a method print(my_list) # to see documentation of method help(my_list.append)
8a66633f1c65017095de383388de87af5dc3e914
MFarooq786/Python_Matplotlib
/simpleplot.py
520
3.953125
4
#load library import matplotlib.pyplot as plt#for plots import numpy as np #for arrays and lists import math#needed for pi #We now obtain the ndarray object of angles between 0 and 2π using the arange() function from the NumPy library. x=np.arange(0,math.pi*2,0.05)#values for x-axis y=np.sin(x)#values for y-axis ...
c60128013d7e1ae2ccbf729b611e3135b51ed40e
lalitp20/Python-Projects
/Self Study/Basic Scripts/Comparison Operator.py
298
3.96875
4
a = 9 b = 4 print(" The Output of 9 > 4 is : ", a > b ) print(" The Output of 9 < 4 is : ", a < b ) print(" The Output of 9 <= 4 is : ", a <= b ) print(" The Output of 9 >= 4 is : ", a >= b ) print(" The Output of 9 Equal to 4 is : ", a == b ) print(" The Output of 9 Not Equal To is : ", a != b )
a12a83cd5b54547512ffb06f01417634f82378f5
jmitchward/thesis
/ML_LR.py
3,776
3.90625
4
# Jason Ward 2017-2019 from math import exp import pickle import ML_base # Its iloc[row][column] # Features are coluns, datapoints are rows class logistic_regression: def __init__(self, train_data, test_data, train_class, test_class): print("Training data retrieved.") # self.weight_key = 0.0 ...
96613eb5edc324d556959160da73e08d5b2b1a67
graciousme/playground
/api_practice.py
934
3.8125
4
from urllib2 import urlopen from json import load #sf open data source: film location in sf #apiUrl = "https://data.sfgov.org/resource/yitu-d5am.json?title=180" def search_year(): apiUrl = "https://data.sfgov.org/resource/yitu-d5am.json?" release_year_wanted = raw_input ("What release year would you like to search?...
205317052228705578133d69a65e0c57bef471b9
SanJJ1/justForFun
/acsl/contest1long.py
948
3.796875
4
# Construct a Numeral Hex Triangle according to the following rules: # 1. The first row contains a starting hex number # 2. Each of the next rows has one more number than the starting row. # 3. Each number in the triangle is more than the previous number by a specified amount, # given in Hex. # one the triangles is con...
1f60231f8081875c05d1e7ce834937a850600b25
alexchronopoulos/codewars
/soduku_solution_validator.py
2,771
3.734375
4
def test_rows(board): results = [] for row in board: if ([1, 2, 3, 4, 5, 6, 7, 8 ,9] == sorted(row)): results.append(True) else: results.append(False) if False in results: return False else: return True def test_columns(board): columnMatrix = [] columnCounter = 0 rowCounter = 0 while rowCounter <...
37cb9396577541bb621a079590f75ce0ce34300f
Skyexu/machine-learning-practice
/knn/knn.py
3,367
3.53125
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # Author:xukaihui # Datetime:2019/7/29 21:09 # Description: 统计学习方法第三章,k近邻(k-nearest neighbor, k-nn)算法实现 """ 数据集:mnist Train:60000 test:10000 特征为 0~255 之间的数,标签为 0~9 --------------- 为了计算速度,只测试测试集中前100组数据, k = 20 欧式距离 accuracy: 0.97 running time : 92.55344700813293 曼哈顿距离 ...
956444a28be32f484256cf7d5f72c9e2a44a70fd
cal-smith/Class
/COMP1005/t4/t4.py
9,226
3.71875
4
from __future__ import division class Student(object): def __init__(self, fname, lname, snum, a1, a2, a3, a4, mid, exm): self.fname = fname self.lname = lname self.snum = snum self.a1 = a1 self.a2 = a2 self.a3 = a3 self.a4 = a4 self.mid = mid self.exm = exm self.final = 0 def __str__(self): re...
b2e12100bdebfafa5c4be8bff06e085f3cd4799a
edithbeen/CareerCup
/Q13_Find_Key_Words.py
558
4.0625
4
# given a dictionary of key words, and and a key, if the key is the concatenation of arbitrary number of key words, return True, else return False # question: can the key words be used more than once? def is_Key_Words(words, key): if len(key) == 0: return True b = False for word in words: i...
267aeecf700e530a71adcec4ba9011a670dfffc3
lonely7yk/LeetCode_py
/LeetCode305NumberofIslandsII.py
3,183
4.1875
4
""" A 2d grid map of m rows and n columns is initially filled with water. We may perform an addLand operation which turns the water at position (row, col) into a land. Given a list of positions to operate, count the number of islands after each addLand operation. An island is surrounded by water and is formed by connec...
35cdd5f661ad11c8964d6c701ab95e28893dcd2e
tinkle1129/Leetcode_Solution
/Segment Tree/315. Count of Smaller Numbers After Self.py
4,334
4.09375
4
# - * - coding:utf8 - * - - ########################################### # Author: Tinkle # E-mail: shutingnjupt@gmail.com # Name: Count of Smaller Numbers After Self.py # Creation Time: 2017/9/1 ########################################### ''' You are given an integer array nums and you have to return a new counts arra...
cee4d9704cefce3a3d38178b61a6c9f26b2ccd58
Chansazm/Project_31_Dynamic_Programming
/cansumTab.py
502
3.671875
4
def cansumtab(targetsum,numbers): Table = [False] * (targetsum + 1) Table[0] = True for i in range(targetsum): if Table[i] == True: for num in numbers: if i+ num <= targetsum: Table[i+num] = True return Table[targetsum] #Driver function #Time...
a8e121faba18600cc2ec9f969118ee407148a5ac
quangvinh86/python-projecteuler
/PE-024/millionth_lexicographic_permutation.py
972
3.625
4
""" Solution to Project Euler problem 24 @author: vinh.nguyenquang @email: quangvinh19862003@gmail.com """ import math LIMIT_NUMBER = 1000000 def find_millionth_lexicographic_permutation(): perm = [_ for _ in range(0, 10)] numbers = [str(_) for _ in range(0, 10)] count = len(perm) perm_num = "" ...
26534a227a8b042dd34d93d1f75092e22305f81d
geediegram/parsel_tongue
/emmanuel_oludairo/comparisons.py
292
4.0625
4
first_number = int(input("Enter first number: ")) second_number = int(input("Enter second number: ")) third_number = int(input("Enter third number: ")) if first_number < second_number < third_number: print(True) else: print(False) print(first_number < second_number < third_number)
c008927779adcb65c37a71665eb060e030ba71c7
miroslavio/Python_Euler
/problem_27.py
1,867
3.828125
4
# Find product of coefficients a and b that produce the largest number of primes # Can be sped up by only considering primes for values of b, since if b is not prime # then all generated numbers cannot be prime from itertools import compress def is_prime(n): if n < 2: return False i = 2 ...
9b863f043a5ff384e784ba792aff3477052013c9
nicky1503/Python-Advanced
/comprehensions/bunker.py
651
3.640625
4
item_category = input().split(", ") n = int(input()) storage = {item_category[i]: {} for i in range(len(item_category))} quantity = 0 avg_quality = 0 for i in range(n): category, item, stats = input().split(" - ") storage[category][item] = stats quantity_quality = stats.split(";") quantity_num = quantit...
81c73e133a6818ed95b15864976409d106d04399
blueLibertas/BOJ
/Python/#2292 벌집.py
268
3.65625
4
# 문제 출처: https://www.acmicpc.net/problem/2292 # 풀이: 2021.01.22 import math def count(dest): if dest == 1: return 1 k = math.floor(math.sqrt((dest-1)/3)) if dest > 1+3*(k+1)*k: k += 1 return k+1 print(count(int(input())))
f671ab17d71114bce110afd438506249d014da35
chrishuskey/Intro-Python-I
/src/10_functions.py
752
4.28125
4
""" Program that asks for a number from the user, and returns whether that number is even or odd. """ # Write a function is_even that will return true if the passed-in number is even. def is_even(number:int): """ Determines if the input integer is an even number or not. """ if number % 2 == 0: ...
c4d33e6037dd000d342ba88331fd589d8b4f6e42
winterismute/linguistic-analysis
/twitteranalysis.py
11,060
3.5625
4
#!/usr/bin/env python # Import from the pattern lib from pattern.web import Twitter, plaintext from pattern.en import parse, pprint, split, lemma, Chunk, Word from pattern.en.wordlist import PROFANITY from pattern.search import search # Import from BeautifulSoup, an XML parser used to create the HTML results' page # ...
bc59c79f2dcb4fa8698f903467cbd320b813eb7d
sumukhbh/SearchingandSorting
/CountingSort.py
409
3.71875
4
# Implementation of Counting Sort # def counting_sort(array, max_range_value): output_array = [0] * (max_range_value +1) for val in array: output_array[val] += 1 ans = [] for i,value in enumerate(output_array): for j in range(value): ans.append(i) return ans print(...
e55a3e1b324974c19e0239e9d5b4d0c1cbc26411
Bluemavim/Data-Analysis
/Numpy/ExerciseNumPy6.py
348
3.796875
4
#Encontrar los índices de los valores mínimos y máximos de la matriz creada en el ejercicio 3. import numpy as np matrix= np.arange(0,9).reshape(3,3) print(matrix) minimo = np.amin(matrix) maximo = np.amax(matrix) indice_minimo= np.where(matrix == minimo) print(indice_minimo) indice_maximo= np.where(matrix == maximo...
1610e6feeda1aff94abec9c501096ff87fa17cfa
FlappyBirdCodes/Language-Classifier
/PredictLanguageGUI.py
4,985
3.84375
4
#Date: April 2nd, 2020 #Written by: Oscar Law #Description: Using machine learning to predict language, first every machine learning project import pygame import sys import string from Screens import Screen from PredictLanguageML import counter, classifier import random #Initiating pygame pygame.init() ...
2cc2021e8b972e7efd887147e469b27d1e8a4bee
sameerarora/python-workshop
/src/main/python/hello/two_sum_sorted.py
417
3.6875
4
def find_pairs(arr, target): low, high = 0, len(arr) - 1 pairs = [] while high >= low: if arr[low] + arr[high] > target: high = high - 1 elif arr[low] + arr[high] < target: low = low + 1 else: pairs.append((arr[low], arr[high])) low, hi...
f41b5ff6dbc407742c61ea535593a3e929da1e27
SmileShmily/LaunchCode-summerofcode-Unit1
/ClassExercise & studio/Hacker Chapter--Files/ex.01.py
642
4.03125
4
'''The following sample file called studentdata.txt contains one line for each student in an imaginary class. The student’s name is the first thing on each line, followed by some exam scores. The number of scores might be different for each student. joe 10 15 20 30 40 bill 23 16 19 22 sue 8 22 17 14 32 17 24 21 2 9 ...
8512a4c112923e64f714e06c3e622cda779ea0e4
charliechenye/MarketDesign
/Deferred_Acceptance_Entity.py
5,042
3.609375
4
""" Gale-Shapley algorithm for Stable Matching Problem (SMP) between two equally sized sets of elements, Proposers and Responders """ from collections import namedtuple from typing import List, Optional class Proposer: NO_NEXT_PROPOSAL = -1 def __init__(self, uuid: int, name: str = None): """ ...
190ed89f4368506a89b642582f4e674660f6e5da
nikitamog/GameStuff
/Utilities/Save.py
769
3.90625
4
''' Created on Oct 13, 2016 @author: nikita This class' goal is to read and write save files in the local source folder. WriteSave() - Store a player's information in a separate file. ReadSave(file) - read a save file so and initialize the objects using the data. ''' import pickle class WriteSave(object): ...
d676ddae50ba5e34191a31289b50d265e751a0d7
rosteeslove/bsuir-4th-term-python-stuff
/numerical_analysis_methods/interpolation/ls_bestapprox.py
1,776
3.6875
4
""" This module facilitates calculation of best approximation polynomials. The method is least squares. """ import numpy as np from polynomial import Polynomial def bestapprox_alpha(nodes, m): """ Return a polynomial of degree m which is the best approximation polynomial for a list of interpolation nod...
8d1ff81e65b5969e7d59b91f82c69c889ecf2063
undersonrs1/PYTHON_Projetos
/bubble_sort.py
360
4
4
def bubble_sort (lista): n = len(lista) for j in range (n-1): for i in range(n-1): if lista[i] > lista[i+1]: # troca de elementos nas posições i e i+1 lista[i], lista[i+1] = lista[i+1], lista[i] b = [5,3,1,2,4] print('') print (b) a = bubble_sort (b) a = b ...
50f45b2abe53baf6a6727bdcf0e431a674096f17
vamvindev/DSA-Collab
/Python/Array/Valid Parentheses.py
1,382
4.3125
4
# Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid. # An input string is valid if: # - Open brackets are closed by the same type of brackets. # - Open brackets are closed in the correct order. # - Note that an empty string is also considered valid. #...
b13d7beab94b381f4c0e6edf5165c926b852ba90
firatmetin/Python
/engine calculator.py
3,415
3.734375
4
import sys import os import math # welcome message print("Welcome to engine calculator 1.0 openBeta") print("Please note the following functions will only work for naturally aspirated : \n" "1. Torque calculation. \n" "2. Horsepower calculation. \n" "\n" "--------------------\n" "Please c...
8d79406727284ed50f6f1d133959b29b91e9373a
q-omar/UofC
/compsci courses/CPSC231 - Intro to CompSci in Python/practicestuff/function.py
439
3.734375
4
# Author: James Tam # Version: Oct 2016 def start(): name = input("Enter your name: ") #this line executes next displayName(name)#the second function is called within a function and it copies the variable name to that function #the second function is still within the block of the first and...
40eb0f8396c0085adf64af7b2e6d3a8fee9fd64f
taruntrehan/pythonic
/incubator/ListItems.py
208
3.546875
4
def simpleArraySum(ar): sum=0 for i in inputList: sum=sum+i return str(sum) # Input list inputList = [1, 1, 2, 3, 5] inputList.append(34) sumVal=simpleArraySum(inputList) print(sumVal)
2e2b7d29b02f58a6c26f937750b5398ef9045cb6
Yang-Hyeon-Seo/1stSemester
/python/소프트웨어의 이해/tkarkrgud.py
217
3.609375
4
#헤론의 공식 import math print('삼각형 세 변의 길이 입력') a=int(input()) b=int(input()) c=int(input()) s=(a+b+c)/2 area = math.sqrt(s*(s-a)*(s-b)*(s-c)) print('삼각형의 면적 %s'%area)
2657da6e2234ef1af194629d460e3ba49af0d1bd
fp-computer-programming/cycle-2-labs-p22melsheikh
/lab_6-1.py
170
3.75
4
# author__= ME 9/22/2021 first_name = input("Enter your first name ") last_name = input("Enter your last name ") full_name = first_name + " " + last_name print(full_name)
5638b6120c8aceded55425c60652b53c0f56d9d6
sheldon2015/reading
/python_learn/begin.python/day06/04.py
182
3.59375
4
# coding:utf-8 # *创建集合 s = set(range(1, 20)) s2 = {x for x in range(20)} print(s) print(s2) s3 = dict(key='value') print(s3) s4 = {'a': 2, 'b': 3} print(dict(**s4))
aaf25b6df15b77a1d18b6311dfe6b10f5c7fcc59
Zigje9/Algorithm_study
/python/5618.py
355
3.53125
4
# PyPy3로 통과 python3 시간초과 import sys N = int(sys.stdin.readline()) numbers = list(map(int, sys.stdin.readline().split())) def gcd(a, b): if a == 0: return b return gcd(b % a, a) g = gcd(numbers[0], numbers[1]) if len(numbers) == 3: g = gcd(g, numbers[2]) for i in range(1, g+1): if g % i ==...
5675534373592a61c08e529b6e0a150728f7d742
jjy1132/source
/q3_2.py
94
3.578125
4
i = 1 total = 0 while i <= 1000: if i % 3 == 0: total += i i +=1 print(total)
92c5eed7acc9b3bdf6de7eb7f56dc5750a8bb731
dEzequiel/Python_ejercicios
/Poo/Manejo_atributos/visualizarAtributosObjeto.py
1,753
3.546875
4
class CuentaCorriente: def __init__(self, nombre, apellidos, direccion, telefono, saldo): self.nombre = nombre self.apellidos = apellidos self.direccion = direccion self.telefono = telefono self.saldo = saldo self.numerosRojos = False def __repr__(self): return '[%s: %s]' % (self....
7400e501b3d2ab544386cf5365d9c18badf3ede8
Kay-Towner/Homework6
/hwk6_flat_earth.py
3,551
3.640625
4
#Finished by: Kay Towner import numpy as np import math import scipy.integrate as integrate import numpy.ma as ma #Problem 2.) Flat Earth def grav_accel(p1, p2, m): """ p1 = point where the mass element is p2 = point you are interested in m = mass returns a vector of the gra...
de534d17836f4d5f2c5fa095e26b21713a67f52a
Usherwood/pos_ngrams
/pos_ngrams/preprocessing/cleaning.py
3,285
3.71875
4
#!/usr/bin/env python """Functions for cleaning generic text data, the master function 'clean_text' calls all sub functions if required.""" import string from pos_ngrams.preprocessing.tokenizer import tokenizer_word, tokenizer_pos, de_tokenizer_pos __author__ = "Peter J Usherwood" __python_version__ = "3.6" def c...
7f68d14006cb491d1a6669113ce92376071d4f30
woohams/Python
/Day05.py
6,227
3.90625
4
''' # [산술 연산자] # [예제 1] print("{}".format(3+2)) #[+] : 두 값을 더한 결과를 반환 print("{}".format(3-2)) #[-] : 두 값을 뺀 결과를 반환 print("{}".format(3*2)) #[*] : 두 값을 곱한 결과를 반환 print("{}".format(3/2)) #[/] : 두 값을 나눈 결과를 반환(실수 값) print("{}".format(3//2)) #[//] : 두 값을 나눈 결과의 몫 반환(정수 값) print("{}".format(3...
0e73896443b6f51fef781ead59ad4a896cb6739c
pranjaj011/How-to-think-like-a-Computer-Scientist-Interesting-Exercises
/Area Circle.py
120
4.15625
4
import math r = int(input("What is the circle's radius?")) A = math.pi * (r ** 2) print("The area of the circle is", A)
b023076522ed55f08e2012de6a8b5d645c200e5d
abhi8893/Intensive-python
/tutorials/argparse-tutorial/char_seq.py
1,315
3.75
4
# Link: https://t.ly/5882b # Generate character sequence class StartingCharacterHasGreaterUnicodeError(Exception): pass def char_seq(c1, c2): o1, o2 = ord(c1), ord(c2) if o1 < o2: seq = ' '.join([chr(o) for o in range(ord(c1), ord(c2)+1)]) return(seq) else: raise( StartingC...
f0d3984c4fc3ff85e93991f33741d27f0b1e39ac
maciejborkowski1/PracticePython
/09_list_overlap_comprehensions.py
588
4.28125
4
''' Take two lists, say for example these two: a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13] and write a program that returns a list that contains only the elements that are common between the lists (without duplicates). Make sure your program works on two lists ...
0375698a04d417e14837eb4fff3060a22b810a5f
webabrakadabra/python_1
/random1.py
555
3.546875
4
import random a = input('Введіть початок: ') b = input('Введіть кінець: ') def gen_list(a, b): return [i for i in range(int(a), int(b)+1)] lst = gen_list(a, b) while True: if input("Вибрати число із списка - 1, закінчити роботу програми - 2: ") == "1": if len(lst) > 0: a = random.choi...
31c74c01063e96debaa921465a60c52d1a3686c2
SprytnyModrzew/PrinterProject
/valid.py
3,368
3.5625
4
polish_small_characters = ['ą', 'ć', 'ę', 'ł', 'ń', 'ó', 'ś', 'ź', 'ż'] polish_big_characters = ['Ą', 'Ć', 'Ę', 'Ł', 'Ń', 'Ó', 'Ś', 'Ź', 'Ż'] def name_valid(name): if len(name) <= 0: raise ValueError("Imię nie może być puste!") if name[0] < chr(65) or name[0] > chr(90): if name[0] not in polis...
1b94ea1c22847e642da26e6a81681568af93befa
Liam-Pigott/python_crash_course
/09-Decorators/decorators.py
1,623
4.375
4
def func(): return 1 def hello(): return "Hello!" greet = hello greet() del hello print(greet()) def hello(name='Liam'): print("The hello() function has been executed") def greet(): return "\t This is the greet() func inside hello!" def welcome(): return "\t This is the welcome...
d5dfe2ebf7ab2773d990d43562c84e4b4e78bf4a
Triose/Codes-when-I-was-young
/python_learning/python_book/capter_2/sequence.py
6,646
4.3125
4
#序列有6种类型,其中有列表和元组(列表可修改,元组不行) #序列: edward = ['Edward Gumby', 42] print(edward) #可以print john = ['John Smith', 50] database = [edward, john] print(database) #相当于二维 #通用序列操作:(索引indexing, 分片slicing, 加adding, 乘multiplying, 映射mapping, 成员资格 etc) #indexing: greeting = "Hello" print(greeting[0]) print(greeting[-1]) print(...
9089430b14d7394bb49872e5d432b9a608f618cd
IfYouThenTrue/Simple-Programs-in-Python
/koch_snowflake.py
869
3.578125
4
#!python3 import turtle class Koch: def __init__(self, speed=None, angle=60): self.t = turtle.Turtle() if speed: self.t.speed(speed) self.turn = 180-angle self.f = self.t.forward self.l = self.t.left self.r = self.t.right self.rlr = [(angle, self...
13276ec2f5b02c3dab65c85e6acf9b889856c94f
olegkeldanovitch/Python_H
/HW_2.py
8,071
4.46875
4
# Arithmetic print('Arithmetic') import math # 1. Создать переменную item_1 типа integer. item_1 = 10 # 2. Создать переменную item_2 типа integer. item_2 = 3 # 3. Создать переменную result_sum в которой вы суммируете item_1 и item_2. result_sum = item_1 + item_2 # 4. Вывести result_sum в консоль. print('result_sum ...
13f72b0849b308d358bef230cdd9acc5dd9769c2
oolubeko/CS313-Python-Projects
/USFlag.py
5,590
3.6875
4
# File: USFlag.py # Description: Use turtle graphics to draw the US flag # Student's Name: Tomi Olubeko # Student's UT EID: oeo227 # Course Name: CS 313E # Unique Number: 50940 # # Date Created: 9/14/16 # Date Last Modified:9/16/16 def drawWhiteStar(ttl,radius,startx,starty): ttl.setheading(0) ttl.fil...
ae05b0937a231ea1bee9c59386af79abc80079a3
YoTcA/Rezeptdatenbank
/src/Database_Files.py
3,210
3.71875
4
import sqlite3 # connect to database Rezeptdatenbank.db connection = sqlite3.connect("Rezeptdatenbank.db") cursor = connection.cursor() cursor.execute("""CREATE TABLE IF NOT EXISTS recipe ( recipename TEXT COLLATE NOCASE, duration INTEGER, preparation TEXT)""") cursor.execute("""...
6128599527c9d1ff54bb0a3021b699d10369691c
KeremTurgutlu/keremai
/file_utils.py
409
3.703125
4
import pickle def write_pickle(target_file, obj): """ Pickle a python object to target file """ with open(target_file, 'wb') as handle: pickle.dump(obj, handle, protocol=pickle.HIGHEST_PROTOCOL) def read_pickle(source_file): """ Read a pickled python object from source file """ ...
ba955440760155ab525514d97659fed6321c616d
Benzsoft/Python-Stuff
/Apps/Ayncio.py
629
3.734375
4
from time import sleep import asyncio # Standard (Synchronous) Python def hello(): print('Hello') sleep(3) print('World') if __name__ == '__main__': hello() # Asyncio Example1 loop = asyncio.get_event_loop() @asyncio.coroutine def hello2(): print('Hello') yield from asyncio.sleep(3) ...
11e0e3fa1c4ef45e83add85d2db200d60c0750bc
anassBelcaid/ComputerVision
/Courses/understanding_Images_Sanja/solutions/A2/02_harris_corner.py
674
3.640625
4
""" Implement and visualize the harris corner """ from panorama import harris_corners from skimage.io import imread from skimage.feature import corner_peaks import matplotlib.pyplot as plt if __name__ == "__main__": #reading the image Img = imread("./building.jpg", as_gray=True) #computing the re...