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
e18412d42429782751836ec1759665325a172b4f
mareaokim/hello-world
/03_12번number2.py
975
4.375
4
def main(): print("This program finds the sum of the cubes of the first n natural numbers.") print() n = int(input("Please enter a value for n : ")) sum = 0 for i in range(1,n+1): sum = sum + i**3 print() print("The sum of cubes of 1 through through", n, "is : ",s...
3612389e3f8f12b32e32c99275df117449b2b974
Guilherme26/ml_models
/LogisticRegression.py
2,199
3.890625
4
""" This module is able to perform Logistic Regression for multidimensional data. However, it only outputs binary responses according to a given probability. In order to work correctly, the algorithm must receive a list of records, that, by its turn must also be a list """ import numpy as np, math, copy class...
2504939a5b956809e8901dd787f485eb966d6b85
homutovan/HomeWork2.2
/main.py
6,871
4
4
#Создаем базовый класс животных import random class Animal: """Базовый класс домашних животных""" animal_count = 0 animal_hunger = 0 resourse_complit = 0 def __init__(self, animal_name, animal_voice, animal_type, animal_resource): self.animal_resource = animal_resource self.ani...
4ece349c188704771758b14bc2bf32e5b1f0ad86
younik/SetCoveringMachine
/scmpy/SCM.py
7,964
3.953125
4
import numpy as np class SCM: """ SCM(max_features=4, machine_type="conjunction", penalty_value=2.0) This class implement the Set Covering Machine classifier with data-dependent balls. For further details about this classifier: https://www.jmlr.org/papers/volume3/marchand02a/marchand02a.pdf Par...
5d0bd9d068ae281c18009adf21c33b5f91f47ca9
GuoXinjian/Python
/LeetCode/Python/Done/414.py
772
3.984375
4
''' 给定一个非空数组,返回此数组中第三大的数。如果不存在,则返回数组中最大的数。要求算法时间复杂度必须是O(n)。 示例 1: 输入: [3, 2, 1] 输出: 1 解释: 第三大的数是 1. 示例 2: 输入: [1, 2] 输出: 2 解释: 第三大的数不存在, 所以返回最大的数 2 . 示例 3: 输入: [2, 2, 3, 1] 输出: 1 解释: 注意,要求返回第三大的数,是指第三大且唯一出现的数。 存在两个值为2的数,它们都排第二。 ''' class Solution: def thirdMax(self, nums:' List[int]') -> int: num...
3a918e8501958191656e267009b1df4df86a89e3
GuoXinjian/Python
/LeetCode/Python/Done/11.PY
1,006
3.5625
4
''' 给定 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai) 。在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)。找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水。 说明:你不能倾斜容器,且 n 的值至少为 2。 图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]。在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49。 示例: 输入: [1,8,6,2,5,4,8,3,7] 输出: 49 ''' class Solution: def maxArea(self, height): ...
7402b8fc2f10acd85332a6924012dd3f8380fa41
GuoXinjian/Python
/LeetCode/Python/UNDO/845.py
1,153
3.90625
4
''' 我们把数组 A 中符合下列属性的任意连续子数组 B 称为 “山脉”: B.length >= 3 存在 0 < i < B.length - 1 使得 B[0] < B[1] < ... B[i-1] < B[i] > B[i+1] > ... > B[B.length - 1] (注意:B 可以是 A 的任意子数组,包括整个数组 A。) 给出一个整数数组 A,返回最长 “山脉” 的长度。 如果不含有 “山脉” 则返回 0。 示例 1: 输入:[2,1,4,7,3,2,5] 输出:5 解释:最长的 “山脉” 是 [1,4,7,3,2],长度为 5。 示例 2: 输入:[2,2,2] 输出:0 解释:不含 “...
113cee7b2ab6733f85ea4712f800e6b6b8857395
GuoXinjian/Python
/LeetCode/Python/Done/724.py
1,163
3.578125
4
''' 给定一个整数类型的数组 nums,请编写一个能够返回数组“中心索引”的方法。 我们是这样定义数组中心索引的:数组中心索引的左侧所有元素相加的和等于右侧所有元素相加的和。 如果数组不存在中心索引,那么我们应该返回 -1。如果数组有多个中心索引,那么我们应该返回最靠近左边的那一个。 示例 1: 输入: nums = [1, 7, 3, 6, 5, 6] 输出: 3 解释: 索引3 (nums[3] = 6) 的左侧数之和(1 + 7 + 3 = 11),与右侧数之和(5 + 6 = 11)相等。 同时, 3 也是第一个符合要求的中心索引。 示例 2: 输入: nums = [1, 2, 3] 输出: -1 解释:...
099d1e9a2c162102b7d70d34b2e45d488b8fac51
aglyzov/netcall
/netcall/datastruct.py
7,224
3.96875
4
# vim: fileencoding=utf-8 et ts=4 sts=4 sw=4 tw=0 from heapq import heapify, heappush, heappop class priority_dict(dict): """Dictionary that can be used as a priority queue. Keys of the dictionary are items to be put into the queue, and values are their respective priorities. All dictionary methods work...
22b8d929c8fe6ab23fdbe677d6e8548dfa7a230b
lydiateinfalt/DATS6103-DataMining-Spring2021
/Homework/Class-Ex-Lecture4_1.py
12,848
3.890625
4
# Lydia Teinfalt # DATS 6103: Data Mining # Spring 2021 # 02/27/2021 # Homework 4 and Lecture 4_1 Exercises # Reference: https://www.w3resource.com/python-exercises/numpy/basic/index.php # ================================================================= import numpy as np import matplotlib.pyplot as plt Print("Soluti...
d37960db9511a6699a59797939080277585ec508
riteshsahu16/python-programming
/2 loop/ex5.3_decimal_binary.py
722
4
4
#Q3. Write a program to accept decimal number and display its binary number. n = int(input()) tmp = "" #divide n repeatedly by 2 till you get 1 as qoutient then take all the remainder in last to first order. rem=n%2 quotient = n//2 n = n//2 count = 1 while True: tmp = tmp + str(rem) if quotient == 1: br...
74a984c050abd2f23a860b299a38976361138882
riteshsahu16/python-programming
/2 loop/ex1.7_product_digits.py
210
4.0625
4
#Q7. Write a program to display product of the digits of a number accepted from the user. n = int(input()) prod = 1 while n>0: last = n%10 prod *= last n = n//10 print("product of digits : ", prod)
2decab40de10c88aa8102ab675e9fa1f3a46c8b0
riteshsahu16/python-programming
/2 loop/ex1.10_check_ifprime.py
270
4.125
4
#Q10. Write a program to check whether a number is prime or not. n = int(input()) i = 2 is_prime = True while(i <= n//2): if n%i==0: is_prime = False break i += 1 if is_prime: print("The no. is prime") else: print("The no. is NOT prime")
7dde7fa7aac2351a1d6eeead7dba6877f177db3b
riteshsahu16/python-programming
/1 if else/ex9_min_three.py
576
4.21875
4
#[9] Find minimum number out of given three numbers. print("Enter three no.") a = int(input("a: ")) b = int(input("b: ")) c = int(input("c: ")) if(a==b and b==c): print("all are equal") elif (a==b and a<c) or (a==c and a<b) or (a<b and a<c): if(a==b): print("a and b are equal & minimum") elif(a==c...
2f82dba4a6ea5e5edaccb2667585cdcd3a8195e8
riteshsahu16/python-programming
/1 if else/ex20_seat_booking.py
1,128
3.8125
4
# Ordinary – 2500 # Pavillion – 3500 # Upper Pavillion – 4500 # Commentary Box – 6000 # VIP – 8000 # 10% discount for online booking # 8% discount for advance booking # no discount for ticket window. # Ask user to enter the booking type like online, advance or window booking. # Ask user to select the types of sea...
55fa837a834bac38dab6ac2ea9e7a5147d932acc
riteshsahu16/python-programming
/2 loop/ex1.6_print_table.py
170
3.9375
4
#Q6. Write a program to print table of a number accepted from user. n = int(input()) for i in range(1,11): print(n, "x", i, "=", n*i) #print(f"{n} x {i} = ", n*i)
7fe8362c43fc33041f951b8ca5ebc120bd3d4cd8
riteshsahu16/python-programming
/2 loop/ex1.8_factorial.py
144
4.15625
4
#Q8. Write a program to find the factorial of a number. n = int(input()) factorial = 1 while n>0: factorial *= n n -= 1 print(factorial)
2792a96560d6c6a462b13fd2886f099b51128ca3
riteshsahu16/python-programming
/3 strings/ex_slice2_Last_n_char.py
184
4.15625
4
# Q2. Write a program to accept a string from the user and display n characters from the left # of the string. (Accept n from the user) str1 = input() n = int(input()) print(str1[-n:])
3a81d0c735b8eee6d95620ae87930879f48b678b
riteshsahu16/python-programming
/3 strings/ex_slice4_first_n_char.py
184
4.0625
4
# Q4. Write a program to accept a string from the user and display n characters from the # right of the string. (Accept n from the user) str1 = input() n = int(input()) print(str1[:n])
d59ddc73dc3e39a2db9e15002d448742a475a1ab
detective-sokka/Competitive-Programming
/OtherProblems/HackerEarth/SegmentTree.py
3,293
3.71875
4
# https://www.hackerearth.com/practice/data-structures/advanced-data-structures/segment-trees/tutorial/ # Algorithm taken from above link # Complete # Sum of range of elements in range from collections import defaultdict class SegmentTree: def __init__(self, input_list): self.list_ = input_list...
163f1a4d8ac4b3c9525172e11808b1b0ab2c6d70
detective-sokka/Competitive-Programming
/Animations/tutorial.py
1,829
3.9375
4
from manim import * class SquareToCircle(Scene): def construct(self): circle = Circle() # create a circle circle.set_fill(PINK, opacity=0.5) # set color and transparency square = Square() # create a square square.rotate(PI / 4) # rotate a certain amount self.play(Crea...
789ba383c1f5c1807d23d63a4a60ac25428e6ebc
detective-sokka/Competitive-Programming
/OtherProblems/HackerEarth/zoos.py
532
3.578125
4
# hackerearth.com Zoos Problem [November circuits] (Accepted) input_word = list(input()) word_len = len(input_word) x_count = 0 y_count = 0 # to count number of zs for i in range(word_len): if input_word[i] == 'o': break elif input_word[i] != 'z': x_count = -1 break ...
b9bd0b1f68ca94b34a55f7a7432a7d15d641b267
detective-sokka/Competitive-Programming
/OtherProblems/CodeChecf/ALTARAY.py
706
3.515625
4
# https://www.codechef.com/problems/ALTARAY (Accepted) def CheckAlternating(a, b): if a >= 0 and b < 0: return True elif a < 0 and b >= 0: return True else: return False def Alt_SubArray_Count(input_list, input_len): list_ = [1] * input_len i = input_len - 2...
a0a1fbc6a48d45ccb858529ca0f5718390adeb00
MOIPA/MyPython
/practice/basic/text_encode.py
473
4.21875
4
# in RAM all text would be translated to Unicode # while in Disk there are UTF-8 str = u'编码' # Unicode now str = str.encode('utf-8') # UTF-8 print(str) str = str.decode('utf-8') print(str) # riverse a = u'\u5916' print(a) a = a.encode('utf-8') print(a) # -*- coding: utf-8 -*- # the above line means read the code fi...
1bac14fb6c190f9fa62a744684d0d2887608bd8f
MOIPA/MyPython
/practice/process_thread/thread_local.py
1,049
3.75
4
# ThreadLocal可以用于处理局部变量共享问题 # 比如A函数传递参数a给B函数,B再传给C函数,非常麻烦。但是如果a参数改为全局变量需要加锁使用。所以出现了ThreadLocal import threading local_school = threading.local() class Student(object): def __init__(self, name, age): self.__name = name self.__age = age def __str__(self): return 'name %s age %s' % (self...
6e0e2c9518732023f4416e5971029e73947d5ea3
MOIPA/MyPython
/practice/basic/list_tuple.py
372
4.15625
4
list_num = [1, 2, 3, 4, 5] print(list_num[-1]) # 3 # delete list_num.pop() # delete the end one list_num.pop(2) # delete the third one print(list_num) # add list_num.append(6) list_num.insert(0, -1) # update list_num[0] = 0 # tow dimensional array one = [2.1, 2.2, 2.3] array = [1, one, 2, 3] print(array[1][0]) ...
97b1751c7fbb10c9c3fd5d44b1b15e566b1c4953
MOIPA/MyPython
/practice/basic/decorator.py
4,567
3.75
4
# 由于函数也是一个对象,而且函数对象可以被赋值给变量,所以,通过变量也能调用该函数。 # >>> def now(): # ... print '2013-12-25' # ... # >>> f = now # >>> f() # 2013-12-25 # 函数对象有一个__name__属性,可以拿到函数的名字: # >>> now.__name__ # 'now' # >>> f.__name__ # 'now' # 现在,假设我们要增强now()函数的功能,比如,在函数调用前后自动打印日志,但又不希望修改now()函数的定义,这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。 # 本...
d1c88be4322ec32db61223c5196b3fa40f55a100
w758736122/python
/python/word_count.py
721
3.765625
4
d ={i:i+1 for i in range(4)} #{i为键,i+1 值} print(d) #============================词频统计 import string def word_count(): path ='D:\PycharmProjects/a month\Walden.txt' with open(path,'r',encoding='UTF-8') as text: words=[raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()] ...
e38354ef33660cf231f4c9e5179f1dab315b2329
max-conroy/Python
/FamilyRelations.py
21,879
3.5
4
''' Group #2 - Program 4 - Family Relations Program Max Conroy CSC 485 - Special Topics in Computer Science - Python ''' #People data version 1 completed on my own import sys import os.path # main will serve as the command handler def main(...
487b4f8fa75ce2c2f594ee7076bd26457bbc5732
sophieluo/homework
/HW5/make_website.py
7,798
3.953125
4
import string ''' Name: Xiexiao Luo PennID: 70364612 ''' def read_resume(file1): """reads the resume file and stores it in the program's memory""" f = open(file1, "r") resume_texts_list = [] # create a list and store info from the resume in the list for line in open(file1): resume_text...
cb7cd28a0e436f4e51cc96050a49541932fadd19
zouwen198317/ZyPythonTechs
/python_基础入门/by_runoob/basic_17_MultiThread.py
4,602
3.796875
4
# -*- coding:UTF-8 -*- ''' 多线程 ''' import log_utils as log # ----------------- _thread 使用 ----------------- log.loge("_thread 使用") import time # 为纯种定义一个函数 def print_time(threadName, delay): count = 0 while count < 5: time.sleep(delay) count += 1 print("%s: %s" % (threadN...
2c0dadee962e249a5a99adf975fb528059bae3ff
seankwalker/yale-data
/B_4.py
759
3.625
4
""" B_4.py Name: Sean Walker NetID: skw34 CPSC 310, Spring 2019 Homework 3 Implements an unsupervised nearest-neighbors algorithm to find friends of a specified student. """ import math from sklearn.neighbors import NearestNeighbors from B_4_data import process_dining_data NUM_FRIEN...
c0ce60493b55770acca20c65050d38f815f55d5d
sandeep-v1404/DSA
/DSA-Python/quick_sort.py
1,039
4
4
def swap(a, b, arr): if a!= b: tmp = arr[a] arr[a] = arr[b] arr[b] = tmp def partition(elements, start, end): pivot_index = start pivot = elements[pivot_index] while start < end: while start < len(elements) and elements[start] <= pivot: start += 1 ...
436c65d8a5f6e07387c549dfbd779a1912f0ae11
sandeep-v1404/DSA
/Recursion/minion.py
1,499
3.609375
4
import re s = "BANANA" vowels = "AEIUO" a = "Stuart" st = [] a1 = 0 b = "Kevin" kv = [] b1 = 0 x = [] sop = "" def solve(a, b): if (len(a) == 0): x.append(b) return else: b1 = b b2 = b b2 = b2 + a[0] a = a[1:] solve(a, b1) solve(a, b2) re...
b98564bf8b1edb0ae776955e788723a87f3c8ea4
sandeep-v1404/DSA
/DSA 450/Arrays/24consub.py
1,037
3.625
4
# Find longest coinsecutive subsequence # https://practice.geeksforgeeks.org/problems/longest-consecutive-subsequence2449/1 # Own Solution - Time Complexit: O(NlogN) def findLongestConseqSubseq(arr, N): arr.sort() arr1 = list(set(arr)) mx = 1 temp = 1 for i in range(len(arr1)-1): if(arr1[i+...
b9264193654029226d311cf218d3c92a94599c38
sandeep-v1404/DSA
/Stack/2_nextgrtright.py
638
3.609375
4
# 2 NGR | Nearest Greater to right | Next Largest Element # https://practice.geeksforgeeks.org/problems/next-larger-element-1587115620/1 # https://leetcode.com/problems/next-greater-element-i/ (Similar - Extension) arr = [1, 3, 2, 4] stack = [] ans = [] for i in range(len(arr)-1, -1, -1): if(len(stack) == 0): ...
cbb9786c1cef96f1908691806d8dfa21355d3b59
sandeep-v1404/DSA
/Striver Sheet/Arrays/7_matrixzero.py
756
3.859375
4
# Set Matrix Zeros # https://practice.geeksforgeeks.org/problems/boolean-matrix-problem-1587115620/1# (Similar but here we need to set 1's) # https://leetcode.com/problems/set-matrix-zeroes/ # Time Complexity: O(n*m), Space Complexity: O(1) arr = [[1,1,1],[1,0,1],[1,1,1]] def setZeroes(a): col = True n = len...
b27ae6a7f2c81d0b35afcee51a77b9f5afc49e06
sandeep-v1404/DSA
/DSA-Python/stack.py
660
3.8125
4
# Stack follows LIFO from collections import deque class Stack(): def __init__(self): self.container = deque() def push(self, val): self.container.append(val) def pop(self): self.container.pop() def peek(self): if(self.is_empty()): return ("St...
537fa44a12a2c7f196bc7c452efe2ef0c1e31d10
sandeep-v1404/DSA
/DSA 450/Arrays/4sort012.py
844
3.84375
4
# Given an array which consists of only 0, 1 and 2. Sort the array without using any sorting algo # https://practice.geeksforgeeks.org/problems/sort-an-array-of-0s-1s-and-2s4231/1 def sort012(arr,n): a = [] for i in range(n): if(arr[i] == 0): a.append(arr[i]) for i in range(n): ...
b7655a3657206cc97ba8ace149cf3481ac3a8936
sandeep-v1404/DSA
/Striver Sheet/Arrays/13_ser2dmat.py
1,201
3.875
4
# Search in a 2D matrix # https://practice.geeksforgeeks.org/problems/search-in-a-matrix17201720/1# # https://leetcode.com/problems/search-a-2d-matrix/ # https://leetcode.com/problems/search-a-2d-matrix-ii/submissions/ (Similar to GFG problem) arr = [[1,3,5,7],[10,11,16,20],[23,30,34,60]] n = len(arr) m = len(arr[0]) ...
59b7ed58ae583876e1d539b9faad0bd96d8962ad
sandeep-v1404/DSA
/DSA 450/Arrays/35mediansamesize.py
1,021
3.921875
4
# Median of 2 sorted arrays of equal size # https://www.geeksforgeeks.org/median-of-two-sorted-arrays/ ar1 = [1, 12, 15, 26, 38] ar2 = [2, 13, 17, 30, 45] arr1 = [1, 2, 3, 6] arr2 = [4, 6, 8, 10] # GFG Solution def getMedian( ar1, ar2 , n): i = 0 # Current index of i/p list ar1[] j = 0 # Current index ...
906f4365bc9e5963eb5b2a6542aff36d0dc7a887
sandeep-v1404/DSA
/DSA-Python/binary_search.py
1,951
3.78125
4
from util import time_it @time_it def linear_search(numbers_list, number_to_find): for index, element in enumerate(numbers_list): if(element == number_to_find): return index return -1 @time_it def binary_search(numbers_list, number_to_find): left_index = 0 right_index = len(numbers...
b775dfc1115701d24ba4c9ae69f0c02f607356bf
kwu83tw/leetcode-python
/347 Top K Frequent Elements.py
2,612
3.796875
4
""" Given a non-empty array of integers, return the k most frequent elements. For example, Given [1,1,1,2,2,3] and k = 2, return [1,2]. Note: You may assume k is always valid, 1 <= k <= number of unique elements. Your algorithm's time complexity must be better than O(n log n), where n is the array's size. """ from col...
f9c0d5bed6da02aa9d389e9684c7abd0031651c2
declankeyesbevan/bananas-as-a-service
/bananas_as_a_service/banana.py
7,039
3.625
4
""" This module is for parsing your friend's phrases and turning them into somewhat readable, sorta, kinda English language sentences. It uses advanced Aritifical Intelligence Machine Learning AKA sentences can generally follow this basic syntax: adverb, adjective, noun. It also takes into account if your friend has a ...
545029454bc1226bc4e131157a8c2457e419dd71
dirksen/toyrobot
/python/toyrobot.py
2,492
3.6875
4
import sys import re from enum import Enum from collections import namedtuple class Facing(Enum): NORTH = 0 EAST = 1 SOUTH = 2 WEST = 3 Step = namedtuple("Step", "x y") # Movement increment per direction. MOVEMENTS = dict(EAST=Step(1, 0), WEST=Step(-1, 0), NORTH=Step(0, 1), SOUTH=Step(0, -1)) clas...
1666020d6ddc8d879e2c188ea81bd34d3483444a
subeen-lee/One-Time-Pad-Cipher
/cipher.py
1,127
3.796875
4
# Shift a letter by the designated amount, regardless of case def shiftLetter(c,shift): code = ord(c) pad = ord(shift)-65 if (code>=65) and (code<=90): code = (code-pad-39)%26+65 elif (code>=97) and (code<=122): code = (code-pad-71)%26+97 return chr(code) # Shift all characters in a...
46cfca0b38e359f143d02a9f0a3fbef3a7b822e9
djoshuac/competitive-programming
/hackerrank/Algorithms/Bit_Manipulation/Sum_vs_XOR/brute.py
311
3.84375
4
#!/bin/python3 def sum_xor(n): mask = 1 for _ in range(n): mask *= 2 if mask > n: break; mask -= 1 count = 0 for i in range(n): if i + n == i ^ n: count += 1 return count if __name__ == "__main__": n = int(input()) print(sum_xor(n))
1896faae57236b64f19ec2dc844c7216ea5f3d5e
djoshuac/competitive-programming
/hackerrank/Week_Of_Code/34/C-Same_occurrence/brute.py
674
3.609375
4
#!/bin/python3 def same_occurrances(x, y, numbers): occurrences = 0 for i in range(len(numbers)): for j in range(i + 1, len(numbers) + 1): x_count = 0 y_count = 0 for v in numbers[i:j]: if v == x: x_count += 1 elif ...
1f6a248a757eaa0612b1c76f677bcf92bf511373
Edean2023/ACS-Algorightms
/Sorting/algorithms (1).py
2,016
3.921875
4
# partitions the list def partition(arr: list, low: int, high: int): # smaller element index index = (low - 1) # pivot point pivot = arr[high] for j in range(low, high): # if current element is smaller than the pivot if arr[j] < pivot: # increment index of smaller eleme...
0700cea5daf7d292eb7da0af56695dc03a66b5d6
annierak/odor_tracking_sim
/odor_tracking_sim/borrowed_wind_models.py
13,718
3.546875
4
from __future__ import division import scipy import scipy.interpolate as interp import math import scipy.special import matplotlib.pyplot as plt import matplotlib import wind_models import odor_models import time class WindModel(object): """ Wind velocity model to calculate advective transport of odour. ...
4d6f3b984bd2d72d4636d0bba401e7326abc1eeb
DmitryNaimark/leetcode-solutions-python
/topics/Bitwise/Missing_Number_268/[4_HashTable]_Missing_Number_268.py
753
4
4
# https://leetcode.com/problems/missing-number/ # --------------------------------------------------- from typing import List # Runtime Complexity: O(N) # Space Complexity: O(N) # Idea: Use set to find number which is not in the array class Solution: def missingNumber(self, nums: List[int]) -> int: nums_se...
67c086a90727a14cc35eb4f78bb4f673f73b7985
DmitryNaimark/leetcode-solutions-python
/topics/DynamicProgramming/Coin_Change_322/[2_Bottom_up_DP]_Coin_Change_322.py
884
3.84375
4
# https://leetcode.com/problems/coin-change/ # --------------------------------------------------- from typing import List # Runtime Complexity: O(coins * amount) # Space Complexity: O(amount) for memo. # Idea: top-down iterative dynamic programming with memoization. class Solution: def coinChange(self, coins: Lis...
1db60b0cea90bf822c16148e2db719afe01eae69
DmitryNaimark/leetcode-solutions-python
/topics/HashTable/Contains_Duplicate_217/[Sorting]_Contains_Duplicate_217.py
758
3.703125
4
# https://leetcode.com/problems/contains-duplicate/ # --------------------------------------------------- from typing import List # Runtime Complexity: O(N*log(N)) # Space Complexity: O(1) class Solution: def containsDuplicate(self, nums: List[int]) -> bool: nums.sort() for i in range(1, len(nums))...
37a3258116d92939328d524d9ad0af9ce7a5f32a
DmitryNaimark/leetcode-solutions-python
/topics/String/Implement_strStr_28/[Knuth-Morris-Pratt-KMP]_Implement_strStr_28.py
1,488
3.8125
4
# https://leetcode.com/problems/implement-strstr/ # --------------------------------------------------- # Runtime Complexity: O(haystack + needle) # Space Complexity: O(needle) class Solution: def strStr(self, haystack: str, needle: str) -> int: if needle == "": return 0 return kmp_se...
1fe4810aecee015e0967c01fd426ade82ec0a5c2
DmitryNaimark/leetcode-solutions-python
/topics/HashTable/Two_Sum_1/Two_Sum_1.py
739
3.703125
4
# https://leetcode.com/problems/two-sum/ # --------------------------------------------------- from typing import List # Runtime Complexity: O(N) # Space Complexity: O() class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: num_pos = {} for i, num in enumerate(nums): ...
4085cd36120b5f8c2f279a756130c89f24e6df7c
DmitryNaimark/leetcode-solutions-python
/topics/Array/Find_Minimum_in_Rotated_Sorted_Array_153/[Binary_Search_Invariants_Ascending]_Find_Minimum_in_Rotated_Sorted_Array_153.py
982
3.6875
4
# https://leetcode.com/problems/find-minimum-in-rotated-sorted-array/ # --------------------------------------------------- from typing import List # Runtime Complexity: O(log(N)) # Space Complexity: O(1) class Solution: def findMin(self, nums: List[int]) -> int: if nums[0] < nums[-1]: return n...
c5ae232d79a231fe6ef04ed5808cc60e5d0a90f1
DmitryNaimark/leetcode-solutions-python
/topics/Array/Longest_Harmonious_Subsequence_594/[Sort]_Longest_Harmonious_Subsequence_594.py
1,179
3.625
4
# https://leetcode.com/problems/longest-harmonious-subsequence/ # --------------------------------------------------- from typing import List # Runtime Complexity: O(N * log(N)) # Space Complexity: O(log(N)), log N space is required by sorting in average case class Solution: def findLHS(self, nums: List[int]) -> ...
de89cb68e9d89a50e82a89a6711bb1fca137a703
kaysu97/Algorithm
/Recursion&Stack.py
2,489
4.15625
4
#!/usr/bin/env python # coding: utf-8 # f()的複雜度是多少 def f(problemSize): work = 0 for i in range(problemSize): for j in range(i, problemSize): work += 1 class Solution01: def complexity(self): print("n^2") # print your answer here. # 把所有位數相加用Recursion的方式 class Solution02: de...
79f486acaf374eda0095fa427b8495b621545a73
jesus987/programacionjesusblasjimenez
/taresas/if ,else,elif/33.py
424
3.84375
4
def sumar(num1, num2): return num1+num2 def restar(num1, num2): return num1-num2 def multiplicar(num1, num2): return num1*num2 def dividir(num1, num2): return num1/num2 def calcular(x, y, z): resultado=dividir(multiplicar(sumar(x,y),restar(y,z)),sumar(x**2,y**2))**2 return resultado x=input("In...
bbfe830c357cbb643ffa5c66878f9027c91fd0eb
jesus987/programacionjesusblasjimenez
/taresas/if ,else,elif/31.py
977
4
4
def numeros(numero): if numero==0: return "cero" elif numero==1: return "cero, uno, dos" elif numero==2: return "cero, uno, dos, tres" elif numero==3: return "cero, uno, dos, tres, cuatro" elif numero==4: return "cero, uno, dos, tres, cuatro, cinco" elif n...
1ca73dc06d2e2d8acd9a56f3478a2c9198d91a9e
jesus987/programacionjesusblasjimenez
/taresas/25.py
229
3.765625
4
#!/usr/bin/python3 numeros = (5,4,3,2,1,6,45,3,6,6,6,6,6) numero = int(input("Dame un numero: ")) contador= 0 for i in numeros: if numero == i: contador = contador + 1 print ("Hay ",contador," repeticion/es")
1a76972342ac266d471cab4d02540d0b75a9cfd5
htphan16/DataStructuresFinal
/extend_linked_binary_tree.py
15,309
3.5
4
from linked_binary_tree import LinkedBinaryTree class ExtendedLinkedBinaryTree(LinkedBinaryTree): def postorder_next(self, p): """Return the next position from p in postorder tranversal""" if self.parent(p) == None: #base case return None elif self.right(self.parent(p...
9d34b4cff4a84ab85ee900eda38303aff057cd88
Amjad50/Fyp
/utils/geometry.py
1,286
3.953125
4
# got this from # https://stackoverflow.com/questions/563198/how-do-you-detect-where-two-line-segments-intersect/1968345#1968345 from math import degrees, atan2, sqrt def get_line_intersection(line1, line2): """ Finds an intersection point between two lines, each line in the form [(x1, y1), (x2, y2)]. If...
a39dfc65e6ee3c70c5d8e138a47eed3dd7ca7b05
yl2612/Python-project
/final project test/mypackage/StockClass.py
2,681
3.53125
4
''' Created on 2014.12.1 @author: apple ''' import numpy as np import pandas as pd import pandas.io.data as web import matplotlib.pyplot as plt from mypackage.MarketClass import * class Stock(): ''' Generate a class describe the stock containing several attributes and functions. ''' def __init_...
164770ceea76f244004822e8b3788e3864ea76da
j16949/Programming-in-Python-princeton
/3.1/15.py
795
3.703125
4
#判断一个网址的域名类型,如com,edu #判断方法为判断是否有‘.xxx/'的形式的内容,如果没有,取出最有一个.xxx #https://introcs.cs.princeton.edu/python/31datatype/ #https://www.runoob.com/python3/python3-inputoutput.html import sys import re def typeOfDomain(s): r= re.search('\.(.(?!\.))*/.*',s) #匹配以.开始,后续字符串不含.的string(包含后续路径) if not r: r1 = re.s...
654f33aa8bca0e2dd32144a3bb7cbe9b91b51fec
j16949/Programming-in-Python-princeton
/3.2/29/entry.py
477
3.703125
4
class Entry: def __init__(self,date,openPrice,high,low,closePrice): self._date = date self._openPrice = openPrice self._high = high self._low = low self._closePrice = closePrice def __str__(self): return self._date + ' ' + self._openPrice + ' ' + self._hig...
eec22981e0ac13edfe46414233bff234debea3b3
j16949/Programming-in-Python-princeton
/2.3/factorial_r.py
115
3.640625
4
import sys def factorial(n): if n == 1: return 1 return n * factorial(n-1) print(factorial(eval(sys.argv[1])))
7898cc96b91b8498e602393c141ad992e9375787
j16949/Programming-in-Python-princeton
/3.3/17.py
789
3.734375
4
import euclid class Rational: def __init__(self,x,y): divisor = euclid.gcd(x,y) self._x = x/divisor if y != 0: self._y = y/divisor else: #raise ValueException('被除数不能为0') raise Exception("ValueException:'被除数不能为0'") def __add__(self,b): ...
b256c403fb381bef35f94a0a75de56467bacb28f
j16949/Programming-in-Python-princeton
/3.2/24/dragonBook.py
862
3.90625
4
#绘制龙形曲线,其中dragon()绘制期望的龙形曲线,nogard()绘制反方向 #参考1.2节32题,1.5节9题 #使用的是书中的turtle+题目要求的递归 import turtleBook import stddraw def dragon(n): if n == 1: return 'F' else: return dragon(n-1) + 'L' + nogard(n-1) def nogard(n): if n == 1: return 'F' else: return dragon(n-1) + 'R' + n...
4867d6a5a6bd9d8367eb0637bb0da2906859b407
j16949/Programming-in-Python-princeton
/3.2/test.py
1,020
4
4
import stddraw class Rectangle: # Construct self with center (x, y), width w, and height h. def __init__(self, x, y, w, h): self._x = x self._y = y self._width = w; self._height = h; # Return the area of self. def area(self): return self._width * self._height ...
9a69fbca02129a49c7d525e4743075a3757be782
j16949/Programming-in-Python-princeton
/2.3/18_p.py
1,746
3.5625
4
#----------------------------------------------------------------------- # perm.py #----------------------------------------------------------------------- import stdio import sys #----------------------------------------------------------------------- # Return a list of strings, each of which is a length k permutat...
9b27696c7904f22ee20af07e38fa527439dc6608
j16949/Programming-in-Python-princeton
/3.3/testClassList.py
372
4
4
#测试在一个类的构造函数里传入list import copy class ListCopy: def __init__(self,l): self._l = l[:] def __str__(self): return str(self._l) def main(): l = [[[0,1],1],2,3] lc = ListCopy(l) print(lc) l.append(4) print(lc) l[0][0][0] = 'x' print(lc) print(l) if __name__ ==...
18cc4243736d1016ed5ed13ad5c01912c3afc3dd
j16949/Programming-in-Python-princeton
/2.2/22.py
1,070
3.75
4
#判断是否是素数 def prime(a): if len(factors(a)) == 2: return True else: return False #判断是否互质 def relativelyPrime(a,b): fa = factors(a) fa.remove(1) fb = factors(b) fb.remove(1) for s in fa: if s in fb: return False return True #求所有因子 def factors(a): b = [] for i in range(1,a+1): t = a % i if t == 0: ...
bf57079f2bed1ebe426dbbb408659679cfe76a7a
j16949/Programming-in-Python-princeton
/3.2/gosperIsland.py
1,184
3.6875
4
#画Gosper Island #使用的书中的turtle #n = 1:六边形 2:六个边每个边变为3条 3:六个边每个边变为9条,也就是18条边,每个变为3条;即*3的节奏 import turtle import stddraw import sys def gosper(n): if n == 0: return 'F' else: return 'B' + gosper(n-1) + 'L' +gosper(n-1) + 'R' + gosper(n-1) + 'A' def treblih(n): if n == 1: return 'RFLF...
17793d481db169e050b08a1c5dd1e281aa08e094
j16949/Programming-in-Python-princeton
/3.3/20_time/time_seconds.py
1,724
4.1875
4
#python官方文档time模块写道: #此模块中定义的大多数函数的实现都是调用其所在平台的C语言库的同名函数。因为这些函数的语义可能因平台而异,所以使用时最好查阅对应平台的相关文档。 #且python或C获取的时间都为运行程序的终端的时间,所以依据题意,想获得当前时间无论如何都得引入系统时间,无论是OS.SYSTEM()还是time。 #python有两个主要处理时间的模块:1.datetime;2.time,其中datetime也可以计算日期。datetime.datetime可以作运算返回datetime.timedelta对象,time.time()则返回float对象 #由于需要创建0点的时间,而time模块中t...
3ad3d8b63e8f9a123589d25e086d0478a09d8b2d
j16949/Programming-in-Python-princeton
/1.5/3.py
206
3.609375
4
import sys n=eval(sys.argv[1]) ls=[] for i in range(n): t=input('Please input a number:') ls.append(eval(t)) avg=sum(ls)/n suml=0 for t in ls: suml+=(t-avg)**2 standDe=suml**0.5/(n-1) print(avg,standDe)
bf8f72e85e272501a1ad98433264b06ea08d250e
j16949/Programming-in-Python-princeton
/1.3/test.py
211
3.78125
4
import math import sys # x=eval(sys.argv[1]) x=math.pi/3 total=0 term=x i=2 while total!=total+term: total+=term term*=x/i i+=1 term*=(-1)*x/i i+=1 print(total) print(total) print('math.sin:',math.sin(x))
e8489eb2479f95a2ea62ed8d1400f962ee8b9648
j16949/Programming-in-Python-princeton
/2.2/20.py
318
3.5
4
import stdstats import stddraw #a = [1,1,9,3,5,6,8,10] a = [1] print('mean:',stdstats.mean(a)) print('var:',stdstats.var(a)) print('stddev:',stdstats.stddev(a)) print('median:',stdstats.median(a)) stddraw.setYscale(min(a)-2,max(a)+2) stdstats.plotPoints(a) stdstats.plotLines(a) stdstats.plotBars(a) stddraw.show()
a14b65dd8b6188760ad7e4e0fed68736ae332029
j16949/Programming-in-Python-princeton
/2.3/17.py
430
3.546875
4
import sys import math #函数返回一个列表,列表中元素为排列字符串,分别在字符串的第i个位置插入序号为n的字母 def permutation(n): if n == 1 : return ['a'] l = permutation(n-1) r = [] for i in range(n): for j in range(len(l)): r.append(l[j][:i]+chr(n+96)+l[j][i:]) #使用ascii/unicode码 return r n = 4 print(permutation(n)) print(len(permutation(n))) print...
0f0b7392f8c87e6613576d01e5c9b58379cd3a6a
j16949/Programming-in-Python-princeton
/1.4/13.py
336
3.890625
4
import random n=3 a=[] b=[] c=0 for i in range(n): a.append([]) for j in range(n): a[i].append(random.randrange(2)) print('a[]:\n',a) for i in range(n): b.append([]) for j in range(n): b[i].append(random.randrange(2)) print('b[]:\n',b) for i in range(n): for j in range(n): c=(c or (a[i][j] and b[i][j])) pr...
ce5ffd23099efdc032d4ba00fa4445c4268f1a42
j16949/Programming-in-Python-princeton
/3.1/17.py
204
3.859375
4
#返回一个字符串的倒序 import sys def mystery(s): n = len(s) if (n <= 1):return s a = s[0:n//2] b = s[n//2:n] return mystery(b)+mystery(a) s = sys.argv[1] print(mystery(s))
bdfda46b9eacbfed1c8d182d0d42ef1fb226d2d2
lifengshuo/leetcode
/题目二十一/21.py
90
3.5625
4
def f(x): if x > 0: return x + f(x-1) else: # f(0) = 0 return 0
6856382dc57916810a70b71b0de4420826dafdf7
kravchuk-kv41/python-moneycounter
/storage_pickle.py
734
3.640625
4
import pickle class PickleFormat: """ This class works with pickle file. Class has 2 methods: 1. serialization 2. deserialization. """ @staticmethod def serialization(file, data): """ This method dumps into pickle file. :param file: object f...
d47af399c0c701882f4c78b20395df6808d2c503
Douglass-Jeffrey/Unit-5-06-Python
/rounder.py
1,330
4.375
4
#!/usr/bin/env python3 # Created by: Douglass Jeffrey # Created on: Nov 2019 # This program turns inputs into a proper address format def rounding(number, rounder): # This function rounds the user's number # Process rounded_number = (number[0]*(10**rounder)) rounded_number = rounded_number + 0.5 ...
6743280ecd0a2e512625cbf4a7618e2d5da9a196
kevinpeterson/SEng-5811
/homework3/part2.py
5,830
3.546875
4
print ''' ############## Kevin Peterson SEng 5811 Homework #3 Part 2 https://github.com/kevinpeterson/SEng-5811/blob/master/homework3/part2.py ############## ''' ''' Predicate: ((a + b) < c and not p) or (r > s) Constraints: t1: > F = t2: = F < t3: < T = t4:...
65feb1f16b90b0652e56d8f339d720c9ff0d297f
hfeger4/pythonReview
/elements_of_programming_interviews/average of tree levels.py
848
3.875
4
""" Given a non-empty binary tree, return the average value of the nodes on each level in the form of an array. Example 1: Input: 3 / \ 9 20 / \ 15 7 Output: [3, 14.5, 11] Explanation: The average value of nodes on level 0 is 3, on level 1 is 14.5, and on level 2 is 11. Hence return [3, 14.5, 11]. ...
409517126c55ce7e8485cbe94ce7376c6dbebf44
hfeger4/pythonReview
/elements_of_programming_interviews/minimum partition.py
992
3.671875
4
""" Partition a set into two subsets such that the difference of subset sums is minimum Given a set of integers, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum. If there is a set S with n elements, then if we assume Subset1 has m elements, Subset2 must ...
8e8eb1b2132088f780c36a403b74f21ed9d5d3e6
hfeger4/pythonReview
/elements_of_programming_interviews/selection_sort.py
394
3.921875
4
def selection_sort(arr): for fillslot in range(len(arr)-1,0,-1): positionOfMax = 0 for location in range(1,fillslot+1): if arr[location] > arr[positionOfMax]: positionOfMax = location temp = arr[fillslot] arr[fillslot] = arr[positionOfMax] arr...
9e6d51abce4fc2e21e1615f0aed5345c03addca4
hfeger4/pythonReview
/elements_of_programming_interviews/find_missing_element.py
751
3.90625
4
# My solution: # def finder(arr1,arr2): # arr2.sort() # arr1.sort() # for i in range(len(arr1)-1): # if arr1[i] != arr2[i]: # missing = arr1[i] # break # return ("{} is the missing number".format(missing)) # His solution 1 # def finder(arr1, arr2): # arr1.sort() # ...
8106742372eed12053e7d11f35e23594b2972a53
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL1/Day14/DistanceOfX.py
225
3.78125
4
def solution(x, n): answer = [] for i in range(n): answer.append(x*(i+1)) return answer x1 = 2 x2 = 4 x3 = -4 n1 = 5 n2 = 3 n3 = 2 print(solution(x1, n1)) print(solution(x2, n2)) print(solution(x3, n3))
fb80ea0ed4875cf692d1b0970723aa0ba06f076a
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL1/Day8/StringofPAndY_sb.py
294
3.609375
4
def solution(s): answer = True s = str(s).lower() if s.count('p') != s.count('y'): return False # [실행] 버튼을 누르면 출력 값을 볼 수 있습니다. print('Hello Python') return True s1 = "pPoooyY" s2 = "Pyy" print(solution(s1)) print(solution(s2))
9d7c2405c677993aae7f7cfb57b91d97fd91ecfb
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL2/Day3/CountOfAliquotAndSum.py
1,166
3.640625
4
# 45. 약수의 개수와 덧셈 def solution(left, right): answer = 0 for cost in range(left, right + 1): aliquot_cnt = 0 for aliquot in range(1, cost + 1): if cost % aliquot == 0: aliquot_cnt += 1 if aliquot_cnt % 2 == 0: answer += cost e...
c89fb2222c7c89bd0a61c7ca0af7b76216e9e2f5
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL1/Day7/NoyEqualNumber_sb.py
317
3.515625
4
def solution(arr): answer = [] for i in range(len(arr)): if( i == len(arr)- 1): answer.append(arr[i]) else: if (arr[i] != arr[i+1]): answer.append(arr[i]) return answer a1 = [1, 1, 3, 3, 0, 1, 1] a2 = [4, 4, 4, 3, 3] print(solution(a1)) print(solution(a2))
d8a6f01e0901f95bc7646224af2f12034ba42a3f
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL2/Day4/124CountryOfNumber.py
480
3.515625
4
# 3진법을 이용 3으로 나눴을 때 나머지값을 이용할건데, 0부터 시작해야하므로 n - 1을 해주고 시작 # n이 3보다 작은값을 만났을때 나머지값을 리스트 [1,2,4] 인덱스로 접근하여 결과값 반환 # n이 3보다 크면 반복문을 이용해 몫을 n으로두고 반복 def solution(n): answer = '' num = [1,2,4] while n > 0: n -= 1 answer = str(num[n%3]) + answer n = n//3 return answer
0e114a98f7ad2c5b90c42257bc306eb5bf4d46a8
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL1/Day12/GCDandLCM.py
580
3.890625
4
# 34. 최대공약수와 최소공배수 # 좀만 더 생각하지... def solution(n, m): answer = [] a, b = max(n, m), min(n, m) t = 1 while t > 0: t = a % b a, b = b, t answer = [a, int(n * m / a)] return answer n_1 = 3 n_2 = 2 m_1 = 12 m_2 = 5 print(solution(n_1, m_1)) print(solution(n_2, m_2)) from math i...
b30a008fd3082c0d9a8a6463a1bdc0b769b650a9
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL1/Day9/SooBakSooBakSooBak.py
534
3.671875
4
# 18. 수박수박수박수박수박수? def solution(n): answer = '' if n == 1: answer = '수' elif n == 2: answer = '수박' else: answer += '수박' if n % 2 == 0: answer += (n // 2 - 1) * '수박' else: answer += (n // 2 - 1) * '수박' + '수' return answer n_1 = 3 n_2...
41b477c820c6fbd7bfdc4b36ad613ba8ae2d8859
AlgorithmWithFriend/Programmers_Algorithm
/LEVEL1/Day3/KthNumber_sb.py
252
3.75
4
def solution(array, commands): answer = [] for i,j,k in commands: answer.append(sorted(array[i-1 : j])[k-1]) return answer arrays = [1, 5, 2, 6, 3, 7, 4] command = [[2, 5, 3], [4, 4, 1], [1, 7, 3]] print(solution(arrays, command))
930ee22c87d4d75ba03e2af4d622e816a5316a6f
paulywog13/python-challenge
/PyPoll/main.py
2,562
3.84375
4
#import library import os import csv #define input path in order to read and ananlyze data election_csv = os.path.join("Resources", "election_data.csv") #define output path for analysis data outputfile= os.path.join('Analysis', "Polling_Data.txt") with open(election_csv, newline="") as election_file: election_re...
712c3fd4fa36a63e61e114bd70da042c0ff8f215
amberprakash/Ronin
/Ronin.py
2,801
3.734375
4
import pyttsx3 import datetime import wikipedia import speech_recognition as sr import webbrowser import os engine = pyttsx3.init('sapi5') voices = engine.getProperty('voices') #print(voices) engine.setProperty('voice',voices[0].id) def speak(audio): engine.say(audio) engine.runAndWait() ...
462aa96e88edad09bd4430ef5472101ca7e5bf8c
yoannmos/PythonGuide
/pythonguide/_Module Base/Tkinter/inter.py
946
3.640625
4
import tkinter fenetre = tkinter.Tk() # fonction appellée lorsque l'utilisateur presse une touche def clavier(event): global coords touche = event.keysym if touche == "Up": coords = (coords[0], coords[1] - 10) elif touche == "Down": coords = (coords[0], coords[1] + 10) elif touch...