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
21fbb16cd1da3148922030c29f5f6f0563d12463
Ahmedatef-09/machine_learning
/python_files/ML_English/logistic_regreesion/logistic_regression.py
1,681
3.578125
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import statsmodels.api as sm sns.set() from sklearn.linear_model import LinearRegression from sklearn.feature_selection import f_regression from sklearn.preprocessing import StandardScaler from sklearn.model_selecti...
266cb9b64f570b1262f7bfd62d9d81892ced05fe
Ahmedatef-09/machine_learning
/python_files/ML_Arabic/pandas_groupby.py
618
3.546875
4
import numpy as np import pandas as pd dic = {'a':[1,2,3], 'b':[4,5,6], 'c':[7,8,9], 'key':'a b c'.split()} dic2 = {'a':[10,20,30], 'b':[40,50,60], 'c':[70,80,90], 'key':'a b c'.split()} df = pd.DataFrame(dic,index=[0,1,2]) df2 = pd.DataFrame(dic2,in...
6e825fd8dbd70ac20d3502995a7a1efa4da77ab9
shivangsoni/NLP
/HW/ShivangSoni_HW1/CustomLanguageModel
2,439
3.546875
4
import math from collections import Counter from collections import defaultdict class CustomLanguageModel: def __init__(self, corpus): """Initialize your data structures in the constructor.""" self.unigram_count = Counter() self.bigram_count = Counter() self.trigram_count = Counter() self.vocabu...
26a5cbe6f6590d875069427d1b72cf5f7d6a86c1
nikolajjsj/IntoToCSPython
/week2/tower_of_hanoi.py
418
3.8125
4
def printMove(from_stack, to_stack): print('Move from ' + str(from_stack) + ' to ' + str(to_stack)) def towers_of_hanoi(n, from_stack, to_stack, spare_stack): if n == 1: printMove(from_stack, to_stack) else: towers_of_hanoi(n-1, from_stack, spare_stack, to_stack) towers_of_hanoi(n, ...
dfabde0a7eddb09e12accbde3198111ff9f0cfa0
770847573/Python_learn
/Hello/正则/3.边界匹配.py
2,098
3.890625
4
""" --------------锚字符(边界字符)------------- ^ 行首匹配,和在[]里的^不是一个意思 [^xxxxx] $ 行尾匹配 \A 匹配字符串开始,它和^的区别是,\A只匹配整个字符串的开头,即使在re.M模式下也不会匹配它行的行首 \Z 匹配字符串结束,它和$的区别是,\Z只匹配整个字符串的结束,即使在re.M模式下也不会匹配它行的行尾 \b 匹配一个单词的边界,也就是值单词和空格间的位置 \B 匹配非单词边界 """ import re # search():使用指定的正则在指定的字符串中从左往右依次进行搜索,只要找到一个符合条件的子字符串,则立...
d4509f58c0d0721b86336e567946646df9431717
770847573/Python_learn
/Hello/错误和异常/抛出异常raise.py
391
4.15625
4
# 产生异常的形式 # 形式一:根据具体问题产生异常【异常对象】 try: list1 = [12, 3, 43, 34] print(list1[23]) except IndexError as e: print(e) #形式2:直接通过异常类创建异常对象, # raise异常类(异常描述)表示在程序中跑出一个异常对象 try: raise IndexError("下标越界~~~") except IndexError as e: print(e)
fdc709509a4898c4be7205c77a5f0a7c3a3f029e
770847573/Python_learn
/Hello/正则/1.数量词匹配.py
1,759
3.875
4
""" -------------------匹配多个字符------------------------ 说明:下方的x、y、z均为假设的普通字符,n、m(非负整数),不是正则表达式的元字符 (xyz) 匹配小括号内的xyz(作为一个整体去匹配) x? 匹配0个或者1个x x* 匹配0个或者任意多个x(.* 表示匹配0个或者任意多个字符(换行符除外)) x+ 匹配至少一个x x{n} 匹配确定的n个x(n是一个非负整数) x{n,} 匹配至少n个x x{n,m} 匹配至少n个最多m个x。注意:n <= m x|y |表示或,匹配的是x或y """ """ (...
df37cd6d0c236e8f92f0892484ea4d63bfcd1d93
770847573/Python_learn
/Hello/Day13Code/4.装饰器使用一.py
2,245
4
4
# 1.闭包 def func1(): n = 45 def func2(): print(n) return func2 # 方式一 f = func1() f() # 方式二 func1()() # 2. """ 假设我们要增强某个函数的功能,但又不希望修改原函数的定义, 这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator) """ # 装饰器的本质:实际上是一个闭包 # 闭包的书写形式 # 方式一 def outter1(a): def inner1(b): print(a,b) return inner1 f1 = outter...
7b756c270d420e1256cfe977fb7576833a54b4d5
770847573/Python_learn
/Hello/简单排序算法/1.作业讲解.py
900
3.796875
4
# 需求:利用列表推导式将已知列表中的整数提取出来 list1 = [True, 17, "hello", "bye", 98, 34, 21] # 注意:isdigit()是字符串的功能,其他类型的变量无法使用 # 方式一:str() list2 = [ele for ele in list1 if str(ele).isdigit()] print(list2) # 方式二:type() # [17, 98, 34, 21] list2 = [ele for ele in list1 if type(ele) == int] print(list2) # 方式三:isinstance(变量,类型)判断一个变量是否是指定的数据类...
69ecb5fe76a1dee7a56808755922d0a942c069cb
770847573/Python_learn
/shopcar1/storage.py
2,479
3.65625
4
""" 仓库类:【信息保存在本地磁盘:程序刚启动时把列表先存储到文件中,之后使用再读取出来】 商品列表 商品名称 价格 剩余量 Mac电脑 20000 100 PthonBook 30 200 草莓键盘 80 60 iPhone 7000 70 """ import os,pickle from shopcar1.goods import Goods # 注意:导入类和导入函数以及变量的方式相同 # 假设存储仓库中商品列表的文件名为goodslist.txt path = r"goodslist.txt" ...
7bbf2b2e59d035278ed1512201e70391af6c2e8a
770847573/Python_learn
/day19/4.多态的应用.py
1,664
4.4375
4
# 1.多态的概念 # a. class Animal(object): pass class Cat(Animal): pass # 在继承的前提下,一个子类对象的类型可以是当前类,也可以是父类,也可以是祖先类 c = Cat() # isinstance(对象,类型)判断对象是否是指定的类型 print(isinstance(c,object)) # True print(isinstance(c,Animal)) # True print(isinstance(c,Cat)) # True a = Animal() print(isinstance(a,Cat)) # False # b. ...
37cb9c59405d6f6c92945782ff7c68b5adff0388
770847573/Python_learn
/Hello/Day15/day15作业.py
504
3.609375
4
#获取当前时间,判断是否是元旦,如果不是,计算和元旦差了多少天 import datetime def get_time(): time_now = datetime.datetime.now() time_now_day = time_now.strftime('%Y/%m/%d') if time_now_day == '2021/01/01': print('今天是是元旦') else: yuandan_date =datetime.datetime(2021,1,1,0,0,0) days1= time_now - yuandan_date ...
bccdae6959d7354f0a68014f753b98a6e7075dc0
770847573/Python_learn
/Hello/抽象类的使用.py
400
4.125
4
import abc class MyClass(metaclass=abc.ABCMeta): @abc.abstractmethod def mymethod(self): pass class My1(MyClass): def mymethod(self): print('Do something!!!') my = My1()#如果一个类继承自抽象类,而未实现抽象方法,仍然是一个抽象类 my.mymethod() #my1 = MyClass() TypeError: Can't instantiate abstract class MyClass with abs...
a5fc666c80858fc0a3f313bfe562b0e25115e840
770847573/Python_learn
/Hello/Day13Code/5.装饰器使用二.py
1,517
3.875
4
# 1.需求:书写一个装饰器,对年龄进行校验 def get_age(age): print("年龄:%d" % (age)) def check_age(func): def inner(n): # 新的功能:校验传进来的年龄是否是负数,如果是负数,则改为相反数 if n < 0: n = -n # 调用原函数 func(n) return inner f = check_age(get_age) f(-6) # 使用场景:如果原函数有参数,而且在装饰器中需要对原函数中的参数做出操作,则在装饰器的内部函数中设置参数...
7a61d100ca4bd6b29b7642691b09b1de68709424
770847573/Python_learn
/Hello/正则/7.正则练习一.py
551
3.609375
4
# 1.要求从控制台输入用户名和密码,如果用户名和密码都输入合法,则注册成功 """ 要求: 用户名:只能由数字或字母组成,长度为6~12位 密码:只能由数字组成,长度必须为6位 """ import re username = input("请输入用户名:") pwd = input("请输入密码:") # 匹配上,返回一个对象,匹配不上,返回None r1 = re.match(r"^[0-9a-zA-Z]{6,12}$",username) r2 = re.match(r"^\d{6}$",pwd) if r1 and r2: print("注册成功") else: print("注册失败...
b10c4327168a5edd2d50a588ac0731f3b67bc4c9
KurinchiMalar/DataStructures
/DynamicProgramming/MaximumSumContiguousSubsequence.py
3,855
3.78125
4
''' Given a sequence of n numbers A(1)....A(n) give an algorithm for finding a contiguous subsequence A(i)....A(j) for which the sum of elements in the subsequence is maximum. Example : {-2, 11,-4, 13, -5, 2} --> 20 (11 + -4 + 13) {1, -3, 4, -2, -1, 6} --> 7 (4 + -2,+ -1 + 6) ''' # Time C...
9e97f5a89008686e2f7317b30441b7f2eeffe933
KurinchiMalar/DataStructures
/Sorting/CountingSort.py
1,053
3.671875
4
# Time Complexity : O(n+k) # Space Complexity : O(n+k) def counting_sort(Ar,k): B = [0 for el in Ar] C = [0 for el in range(0,k+1)] print "Ar :"+str(Ar) print "B :"+str(B) print "C :"+str(C) for j in range(0,len(Ar)): #Build the counting array...how many times current index has occured in origi...
9a97498c8f5dfe49b5a0118718c8e6b81dbd97f2
KurinchiMalar/DataStructures
/Strings/RemoveAdjacentDuplicatesRecursively.py
1,016
3.890625
4
''' Recursively remove all adjacent duplicates. Given a string of characters, recursively remove adjacent duplicate characters from string. The output string should not have any adjacent duplicates. ''' # Time Complexity : O(n) # Space Complexity : O(1) ... inplace, no stack. def remove_adj_duplicates(mystr...
6b1dc96656928464dc9fd37109885b88c9560134
KurinchiMalar/DataStructures
/Searching/FirstRepeatingElement.py
2,180
3.578125
4
#https://ideone.com/daLlg9 #Time Complexity = O(n) (Building hash_ar and finding max of negatives) #Space Complexity = O(k) ---- k is the range of numbers in the input array. Here 0 to 5. Hence k = 5 ''' Solution: 1) Store the position of occurence in input array in hash_ar 2) On second occurence negate 3) If alread...
d15a8a84b1a7e7ac54f74d47180757109a17782a
KurinchiMalar/DataStructures
/Medians/FindLargestInArray.py
505
4.28125
4
__author__ = 'kurnagar' import sys # Time Complexity : O(n) # Worst Case Comparisons : n-1 # Space Complexity : O(1) def find_largest_element_in_array(Ar): max = -sys.maxint - 1 # pythonic way of assigning most minimum value #print type(max) #max = -sys.maxint - 2 #print type(max) for i in rang...
dcd5df108f3668bfb8e8c2228d1cc86350703500
KurinchiMalar/DataStructures
/LinkedLists/DoublyLinkedListInsert.py
1,889
4.03125
4
class Node(object): def __init__(self, data=None, next_node=None, prev_node=None): self.data = data self.next = next_node self.prev = prev_node def SortedInsert(head, data): if head == None: head = Node(data) return head p = head newNode = Node(data) if p...
f0a64396e3cd7998f6c982d1b059344d2adfb94d
KurinchiMalar/DataStructures
/Medians/MajorityElement_Copy.py
4,505
3.875
4
# Sorting Solution # Time Complexity : O(nlogn) + O(n) from Sorting.MergeSort import mergesort from Sorting.Median import getMedian_LinearTime def find_majorityelem_bruteforce(Ar): Ar = mergesort(Ar) print Ar max_elem = -1 max_count = 0 for i in range(0,len(Ar)): count = 1 for j i...
f2640a1412c6ee3414bf47175439aba242d5c81f
KurinchiMalar/DataStructures
/LinkedLists/SqrtNthNode.py
1,645
4.1875
4
''' Given a singly linked list, write a function to find the sqrt(n) th element, where n is the number of elements in the list. Assume the value of n is not known in advance. ''' # Time Complexity : O(n) # Space Complexity : O(1) import ListNode def sqrtNthNode(node): if node == None: return None ...
1133d5be23312ce519c55837cea5880fd729c3f6
KurinchiMalar/DataStructures
/Medians/PairComparisonMinMax.py
991
4.09375
4
# Time Complexity : O(n) # Space Complexity : O(1) ''' Number of Comparisons: n is even : (3n/2) - 2 n is odd : (3n/2) - 3/2 ''' def get_MinMax_using_paircomparison(Ar): start = -1 if len(Ar)% 2 == 0 : # even min_elem = Ar[0] max_elem = Ar[1] start = 2 else: # ...
ec4a2fc2faea5acfea8a352c16b768c79e679104
KurinchiMalar/DataStructures
/Hashing/RemoveGivenCharacters.py
507
4.28125
4
''' Give an algorithm to remove the specified characters from a given string ''' def remove_chars(inputstring,charstoremove): hash_table = {} result = [] for char in charstoremove: hash_table[char] = 1 #print hash_table for char in inputstring: if char not in hash_table: ...
82ecc3e32e7940422238046cd7aa788979c51f9c
KurinchiMalar/DataStructures
/Stacks/Stack.py
1,115
4.125
4
from LinkedLists.ListNode import ListNode class Stack: def __init__(self,head=None): self.head = head self.size = 0 def push(self,data): newnode = ListNode(data) newnode.set_next(self.head) self.head = newnode self.size = self.size + 1 def pop(self): ...
0bd2a4006643ef1a0955fa89137bc9dc280efecc
KurinchiMalar/DataStructures
/DynamicProgramming/CountOccurenceOfStringInAnotherString.py
1,821
3.90625
4
''' Given two strings S and T, give an algorithm to find the number of times S appears in T. It's not compulsory that all the characters of S should appear contiguous to T. eg) S = ab and T = abadcb ---> ab is occuring 2 times in abadcb. ''' ''' Algorithm: if dest[i-1] == source[j-1]: T[i][j...
ace208de8edd92accd7286e73e99b99c89c1eadc
KurinchiMalar/DataStructures
/DynamicProgramming/LongestIncreasingSubsequence.py
2,826
3.90625
4
''' Given an array find longest increasing subsequence in this array. https://www.youtube.com/watch?v=CE2b_-XfVDk ''' # Time Complexity : O(n*n) # Space Complexity : O(n) def get_length_of_longest_increasing_subsequence(Ar): n = len(Ar) T = [1]*(n) #print T for i in range(1,n): for ...
bd92e67855f505019f17694631ca04db74aa3fc4
KurinchiMalar/DataStructures
/lcaBT.py
1,309
3.71875
4
# Time Complexity : O(n) class BTNode: def __init__(self,data): self.data = data self.left = None self.right = None def isNodePresentBT(root, node): if node == None: return True if root == None: return False if root == node: return True return is...
61aca3793e81011ff08632c1b110e7fe4a7b7e7d
KurinchiMalar/DataStructures
/LinkedLists/Stack.py
1,133
4.0625
4
import ListNode class Stack: def __init__(self,head=None): self.head = None self.size = 0 def print_stack(self): current = self.head while current != None: print current.get_data(), current = current.get_next() print #return self.size ...
98783f5bfd44ae9259f05242baaac5ff796008e5
KurinchiMalar/DataStructures
/Searching/SeparateOddAndEven.py
799
4.25
4
''' Given an array A[], write a function that segregates even and odd numbers. The functions should put all even numbers first and then odd numbers. ''' # Time Complexity : O(n) def separate_even_odd(Ar): even_ptr = 0 odd_ptr = len(Ar)-1 while even_ptr < odd_ptr: while even_ptr < odd_ptr...
c407defd7ab9eef69e27f3ca7134e49d068962b0
KurinchiMalar/DataStructures
/LinkedLists/PalindromeOrNot.py
3,930
4.1875
4
''' Give a function to check if linked list is palindrome or not. ''' import ListNode import Stack def reverse_recursive(node): if node == None: return if node.get_next() == None: head = node return node head = reverse_recursive(node.get_next()) node.get_next().set_next(node) ...
c0a0d05abe2be7af0b67b81d46002b4b8cdcbd40
KurinchiMalar/DataStructures
/LinkedLists/OddFirstThenEven.py
2,091
4.03125
4
__author__ = 'kurnagar' import ListNode ''' Segregate a link list to put odd nodes in the beginning and even behind ''' # Time Complexity : O(n) # Space Complexity : O(1) def swap_values_nodes(node1,node2): temp = node1.get_data() node1.set_data(node2.get_data()) node2.set_data(temp) def segregate_odd_an...
2661ddc368e29f81cb002a4a5c413580f227d284
KurinchiMalar/DataStructures
/Searching/CountOccurence.py
1,957
3.953125
4
''' Given a sorted array of n elements, possibly with duplicates. Find the number of occurrences of a number. ''' # BruteForce # Time Complexity - O(n) from FirstAndLastOccurence import find_first_occurence,find_last_occurence def count_occurence_bruteforce(Ar,k): count = 0 for i in range(0,len(Ar)): ...
30a81157968dcd8771db16cf6ac48e9cd235d713
KurinchiMalar/DataStructures
/Stacks/InfixToPostfix.py
2,664
4.28125
4
''' Consider an infix expression : A * B - (C + D) + E and convert to postfix the postfix expression : AB * CD + - E + Algorithm: 1) if operand just add to result 2) if ( push to stack 3) if ) till a ( is encountered, pop from stack and append to result. 4) if operator ...
982e3cb81b9a194b629434923943f919b3e36ab8
KurinchiMalar/DataStructures
/LinkedLists/floyd_LoopLinkList.py
3,145
4.125
4
__author__ = 'kurnagar' import ListNode # Time Complexity : O(n) # Space Complexity : O(n) for hashtable def check_if_loop_exits_hashtable_method(node): if node == None: return -1 hash_table = {} current = node while current not in hash_table: hash_table[current] = current.get_d...
22f1d817b2d292a4b3fae09a77e3013b9d45bd31
KurinchiMalar/DataStructures
/Sorting/NearlySorted_MergeSort.py
1,528
4.125
4
#Complexity O(n/k * klogk) = O(nlogk) # merging k elements using mergesort = klogk # every n/k elem group is given to mergesort # Hence totally O(nlogk) ''' k = 3 4 5 9 | 7 8 3 | 1 2 6 1st merge sort all blocks 4 5 9 | 3 8 9 | 1 2 6 Time Complexity = O(n * (n/k) log k) i.e to sort k numbers is k * log k to sort n/...
6d878bd6ab1e0dbecb0c2a5a2803ee41359b51b8
KurinchiMalar/DataStructures
/LinkedLists/MergeZigZagTwoLists.py
2,040
4.15625
4
''' Given two lists list1 = [A1,A2,.....,An] list2 = [B1,B2,....,Bn] merge these two into a third list result = [A1 B1 A2 B2 A3 ....] ''' # Time Complexity : O(n) # Space Complexity : O(1) import ListNode import copy def merge_zigzag(node1,node2,m,n): if node1 == None or no...
d1c079ea514b668ac8e2ca32afbaa2aa171754d0
kwichmann/euler
/pe012.py
437
3.6875
4
def factor_count(n): count = 0 for i in range(1, n + 1): if n % i == 0: count += 1 return count def triangle(n): return int(n * (n + 1) / 2) num = 1 while True: if num % 2 == 0: fac = factor_count(int(num / 2)) * factor_count(num + 1) else: fac = factor_cou...
f4726dd533c9efdff032b1e5d3b8589b7469d56f
kwichmann/euler
/pe003.py
505
3.53125
4
num = 600851475143 def divides(n, p): return n % p == 0 def divides_list(n, l): for p in l: if divides(n, p): return True return False def next_prime(l): counter = max(l) + 1 while divides_list(counter, l): counter += 1 return counter cur_prime = 2 prime_list = [2...
3304d188c15ebea8b0f4f7d4846e90c1dbd9420c
cdpn/htb-challenges
/misc/eternal-loop/unzip-loop.py
811
3.71875
4
#!/usr/bin/env python3 import zipfile zip_file = "Eternal_Loop.zip" password = "hackthebox" # Take care of the first zip file since password won't be the filename inside with zipfile.ZipFile(zip_file) as zr: zr.extractall(pwd = bytes(password, 'utf-8')) # namelist() returns an array, so take the first index ...
c1bb89404de014f6a188d04c61ba6bc32f68a4f4
slw2/library-python
/Books.py
1,710
3.734375
4
from Book import Book import random class Books: database = "" def __init__(self, database): self.database = database def books(self): self.database.cursor.execute('''SELECT title, author, code FROM books''') allrows = self.database.cursor.fetchall() list_of_books = [] ...
36e1619c70ac8f322aaa1ac085dc3c9c3e61f099
slw2/library-python
/LoanController.py
2,356
3.921875
4
class LoanController: books = "" users = "" loans = "" def __init__(self, books, users, loans): self.books = books self.users = users self.loans = loans def borrow(self, book_code, user_code): book = self.books.booksearch_by_code(book_code) user = self.user...
228ee138bdc254c9cb229ae19fb4432dadb2e43c
yeyifu/python
/other/set.py
621
4.03125
4
#集合的创建:1.初始化{1,2,3},2.set()函数声明 #特点:无序,无下标,去重 # set = {10, 20, 30, 40, 50, 10} # print(set) #增加 # set1 = {10,20} # set1.add(30) #增加单一数据 # print(set1) # # set1.update([5,6,9,5]) #追加数据序列 # print(set1) #删除 # set2 = {10,20,30,40,50} # set2.remove(10) #删除不存在的值则报错 # print(set2) # set2.discard(20) # print(set2) # # set2.po...
b61a043aedd39dc9120e0b4066327d0095979556
yeyifu/python
/other/function.py
602
3.90625
4
# 定义函数说明文档 def info_print(): """函数说明文档""" print(1+2) info_print() # 查看函数文档 help(info_print) # 一个函数返回多个值 def return_num(): # return 1, 3 #返回的是元组(默认) # return(10,20) #返回的是元组 # return[10,20] #返回的是列表 return {'name':'python','age':'30'} #返回的是字典 print(return_num()) #函数的参数 # 1.位置参数:传递和定义参数的顺序及个...
2a5e1828f8e2bc9f46274bd166d3f566f0225d22
yeyifu/python
/other/test.py
1,561
3.75
4
# import sys # print(sys.argv) # num1 = 1 # num2 = 1.1 # print(type(num2)) # name = 'tom' # age = 18 # weight = 55.5 # stu_id = 2 # print('我叫%s,学号是%.10d,今年%d岁,体重%.2f' % (name, stu_id, age, weight)) # print(f'我叫{name},学号是{stu_id}') # print('hello\nworld') # print('hello\tworld') # print('hello', end='\t') # print('worl...
10b994ebf775a1ad965e7522fae132d5bdc1e1ee
colorfulComeMonochrome/data_analysis
/matplotlib/fish.py
555
3.546875
4
import pandas as pd import numpy as np import matplotlib.pyplot as plt imdata = plt.imread('fish.png') # 数据变换 # mydata = np.random.rand(100*100*3).reshape(100,100,3) # mydata = np.ones(100*100*3).reshape(100,100,3) mydata = np.zeros(100*100*3).reshape(100,100,3) # mydata = mydata + np.array([1, 0, 0]) mydata = myda...
c10b5596458ddc22d97f6dd93968adf9e7766833
HyunAm0225/Python_Algorithm
/study/programmers/kakao_dart_game.py
1,163
3.625
4
from collections import deque dartResult = input() dartque = deque(dartResult) point = [] def check_dart_point(dartque,point): index = -1 while dartque: data = dartque.popleft() if data.isnumeric(): if data =="0" and index== -1: point.append(int(data)) ...
ad9b99eef4faff4186c37a26516e4dc085ae9060
HyunAm0225/Python_Algorithm
/코딩테스트책/7-5.py
687
3.71875
4
# 이진 탐색 실전 문제 # 부품찾기 import sys input = sys.stdin.readline def search_binary(array,start,end,target): while start <= end: mid = (start + end)//2 if array[mid] == target: return mid elif array[mid] > target: end = mid -1 else: start = mid + 1 r...
16e12fbf8289dfb9d62274ccae8196bb06849314
HyunAm0225/Python_Algorithm
/study/9012.py
875
3.65625
4
# 9012 # 괄호 # 스택문제 # 테스트 케이스의 숫자를 입력받음 t = int(input()) ans = [] data = [] def check_vps(stack_list): # pop 한 괄호를 담을 list temp_list = [] temp_list.append(stack_list.pop()) for i in range(len(stack_list)): # temp_list 비어있을 경우 append if not temp_list: temp_list.append(stack_l...
ca0de2eabb70373eccdefd891484900c21fef0fb
HyunAm0225/Python_Algorithm
/study/1181.py
203
3.5625
4
n = int(input()) data = [] ans = [] for _ in range(n): data.append(input()) data.sort(key = lambda x:(len(x),x)) for x in data: if x not in ans: ans.append(x) for i in ans: print(i)
65f583ecf0cd952237b9dcd7130cc71a7a519177
HyunAm0225/Python_Algorithm
/코딩테스트책/10-7.py
889
3.796875
4
# 팀결성 문제 # 서로소 집합 자료구조를 이용하여 구한다 def find_parent(parent,x): if parent[x] !=x: return find_parent(parent,parent[x]) return parent[x] def union_parent(parent,a,b): a = find_parent(parent,a) b = find_parent(parent,b) if a<b: parent[b] = a else: parent[a] = b n,m = map(int...
194086367cacb0dffa9a8e996b35edfe94887754
HyunAm0225/Python_Algorithm
/hello_coding/chap04/quick_sum.py
180
3.78125
4
def sum(lst): if lst == []: return 0 else: print(f"sum({lst[:]}) = {lst[0]} + sum({lst[1:]})") return lst[0] + sum(lst[1:]) print(sum([1,2,3,4,5]))
1b1a4d3bd63310edc10c7e0add62526b041591bb
HyunAm0225/Python_Algorithm
/study/programmers/ternary.py
443
3.9375
4
# 3진법으로 만드는 코드 def ternary(n): tern_list = [] ans = '' while n > 0: # print(f"현재 n값 : {n}") tern_list.append(n%3) n //=3 tern_list.reverse() return tern_list def solution(n): tern_list = ternary(n) ans = 0 for i,num in enumerate(tern_list): num = num * (...
83115abfeb4394433aafa7fd291614a826743049
HyunAm0225/Python_Algorithm
/2292.py
265
3.625
4
# 백준 # 백준 수학 문제 def room_count(number): six_num = 1 count = 1 while number > six_num and number >1: six_num+=(6*count) count +=1 # print(f"six_num : {six_num}") return count n = int(input()) print(room_count(n))
0e08b45d1f4917cd9d4854344441c635283d683c
hucatherine7/cs362-hw4
/test_question1.py
451
3.734375
4
#Unit testing question 1 import unittest import question1 class Question1(unittest.TestCase): def test_calcVolume(self): #Normal test case self.assertEqual(question1.calcVolume(4), 64) #Negative number test case self.assertEqual(question1.calcVolume(-1), -1) #Wrong input ...
40ef7592544d316ec0fe22e2d0a08e6f95e5611d
lavakin/bioinformatics_tools
/bioinf/distance.py
1,094
3.875
4
#!/usr/bin/env python3 from Bio import pairwise2 def editing_distance(seq1:str, seq2:str): """ :param seq1: sequence one :param seq2: sequence two :return: editing distance of two sequences along with all alignments with the maximum score """ align = list(pairwise2.align.globalms(seq1, seq2, ...
77990bea69aff99c9201bc80da4e4ede8e2e7f93
WYHNUS/old-xirvana
/assets/Practice/practice02/skeleton/mile_to_km.py
317
4.0625
4
# mile_to_km.py # Converts distance in miles to kilometers. import sys # main function def main(): KMS_PER_MILE = 1.609 miles = float(raw_input("Enter distance in miles: ")) kms = KMS_PER_MILE * miles print "That equals %9.2f km." % kms # Runs the main method if __name__ == "__main__": main() sys.exit(0)
f07201523a286803dafc06c5a4305451f9ea9fd9
ibbles/HousyBuying
/Stepper.py
6,811
3.859375
4
from datetime import timedelta import datetime import calendar class FastDateNumberList(object): """ This may be a bit unnecessary. It is a fixed sized, pre-allocated DateNumberList used when running the stepper. The purpose is to avoid reallocations inside the innermost loop, where hundreds of thousands of ...
276faf09e77e69979004b00a910df2d0ce4c7923
sumanthreddy07/GOST_Algorithm
/src/main.py
2,163
3.65625
4
#import section import os import argparse from encryption import encrypt,encrypt_cbc from decryption import decrypt,decrypt_cbc #locate function returns the path for the txt files in the data folder def locate(filename): __location__ = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__f...
3b91de50d77f86a93f67b9da205573ca8231b874
Shuguberu/Hello-World
/猜整数.py
383
3.84375
4
import random secret=random.randint(1,10) print("=======This is Shuguberu=======") temp=input("输入数字") guess=int(temp) while guess!=secret: temp=input("wrong,once again:") guess=int(temp) if guess==secret: print("right") else: if guess>secret: print("大了") ...
f3ab92ce7e915013dc8d62cb87d0dbbc05a16275
mangrisano/ProjectEuler
/euler17.py
1,646
4.03125
4
# If the numbers 1 to 5 are written out in words: one, two, three, four, five, then there are 3 + 3 + 5 + 4 + 4 = 19 # letters used in total. # # If all the numbers from 1 to 1000 (one thousand) inclusive were written out in words, how many letters would be used? # # Result: 21124 def problem(): result = 0 al...
21a192f8d31f93d63fa60d4b2b19f7e6821a171d
mangrisano/ProjectEuler
/euler6.py
650
3.5625
4
# The sum of the squares of the first ten natural numbers is, # # 12 + 22 + ... + 102 = 385 # The square of the sum of the first ten natural numbers is, # # (1 + 2 + ... + 10)2 = 552 = 3025 # Hence the difference between the sum of the squares of the first ten natural numbers and the square of the sum # is 3025 - 385 =...
3fd420c5f119f608dda0a1bb30f6014a76a6f82a
mangrisano/ProjectEuler
/euler38.py
1,318
4.03125
4
# Take the number 192 and multiply it by each of 1, 2, and 3: # # 192 x 1 = 192 # 192 x 2 = 384 # 192 x 3 = 576 # By concatenating each product we get the 1 to 9 pandigital, 192384576. # We will call 192384576 the concatenated product of 192 and (1,2,3) # # The same can be achieved by starting with 9 and multiplying by...
0ec6ab37481600c42bb40b7d7560afd1cfa06e67
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 6&7/studentrecord.py
2,470
3.90625
4
class Student: def __init__(self,name,classs,section,rollno): self.name=name self.classs=classs self.section=section self.rollno=rollno def __str__(self): string='Student Name:'+str(self.name)+'\nStudent Class:'+\ str(self.classs)+'\nStudent Section:'+str(...
e818073196e6fabaf47145fab615f345237bf7e3
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Practical3/binsearch.py
924
4.03125
4
class binsearch: def __init__(self): self.n=input('Enter number of elements: ') self.L=[] for i in range (self.n): self.L.append(input('Enter element: ')) itemi=input('Enter element to be searched for : ') self.L.sort(reverse=True) self.index=self.binsearc...
3f1f068d1d557358a42db8bbb9534e5236e2f0f9
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question5.py
1,123
3.65625
4
class Bowler: def __init__(self): self.fname='' self.lname='' self.oversbowled=0 self.noofmaidenovers=0 self.runsgiven=0 self.wicketstaken=0 def inputup(self): self.fname=raw_input("Player's first name: ") self.lname=raw_input("Player's last name: ...
4ad77d79088f85449035804824a12f6beb2e1e7a
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 5/int.py
503
3.515625
4
def compare(listsuper,listsub): stat=None for element in listsuper: if listsuper.count(element)==listsub.count(element): pass else: stat=False if stat==None: for element in listsub: if element in listsub and element in list...
8147118c98c5d7bf084f405607d3b15c22ea1d3f
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question10.py
1,464
3.625
4
class HOUSING: def __init__(self): self.__REG_NO=0 self.__NAME='' self.__TYPE='' self.__COST=0.0 def Read_Data(self): while not(self.__REG_NO>=10 and self.__REG_No<=1000): self.__REG_NO=input('Enter registraton number betwee 10-1000: ') self.__NAME=raw...
e8cee8af302c88e5e20ff072a466e28c2aa808ae
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 6&7/queue.py
1,875
3.96875
4
class queue: '''This normal queue''' def __init__(self,limit): self.L=[] self.limit=limit self.insertstat=True def insertr(self,element): if self.insertstat==True: if len(self.L)==0: self.L.append(element) elif len(self.L)...
4ff55a48679abadf58c65cd9e92f86231c089424
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question8.py
539
3.65625
4
class ticbooth: price=2.50 people=0 totmoney=0.0 def __init__(self): self.totmoney=float(input('Enter the amount if paid else 0:')) ticbooth.people+=1 if self.totmoney==2.50: ticbooth.totmoney+=2.50 @staticmethod def reset(): ticbooth.people=0 ...
6ad09ceb2ab4a05697fb9673000154dcae6d3e0a
SubrataSarkar32/college3rdsem3035
/class12pythoncbse-master/Chapter 4/Question11.py
876
3.796875
4
class DATE: monda=[[1,31],[2,28],[3,31],[4,30],[5,31],[6,30],[7,31],[8,31],[9,30],[10,31],[11,30],[12,31]] def __init__(self,month,day): a=len(DATE.monda) self.month=month self.day=day while self.month<1 or self.month>12: self.month=input('Enter month (1 to 12):') ...
b31f09ab94e4cbddb88f5180b3d2951c55d4b868
Kmr-Chetan/python_practice
/Palindrome.py
907
4
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head= None def isPalindromeUtil(self, string): return (string == string[:: -1]) def isPalindrome(self): node = self.head temp = [] ...
4277a08cf47b4f91712841ef2e3757a49090650f
IStealYourSkill/python
/les3/3_3.py
579
4.28125
4
'''3. Проверить, что хотя бы одно из чисел a или b оканчивается на 0.''' a = int(input('Введите число A: ')) b = int(input('Введите число B: ')) if ((a >= 10) or (b >= 10)) and (a % 10 == 0 or b % 10 == 0): print("Одно из чисел оканчивается на 0") else: print("Числа {}, {} без нулей".format(a, b)) ...
36c1f3a4606a1e9cc61a363387495cb2f8fdb31d
charlottekosche/compciv-2018-ckosche
/week-05/ezsequences/ezlist.py
2,581
3.546875
4
################################# # ezsequences/ezlist.py # # This skeleton script contains a series of functions that # return ez_list = [0, 1, 2, 3, 4, ['a', 'b', 'c'], 5, ['apples', 'oranges'], 42] def foo_hello(): """ This function should simply return the `type` of the `ez_list` object. This...
cfdeb5d426d745a6986a5da2c172d9ff4293ab35
storm2513/Task-manager
/task-manager/library/tmlib/models/notification.py
755
3.640625
4
import enum class Status(enum.Enum): """ Enum that stores values of notification's statuses CREATED - Notification was created PENDING - Notification should be shown SHOWN - Notification was shown """ CREATED = 0 PENDING = 1 SHOWN = 2 class Notification: """Notification clas...
ec5f0599d0af4f726978ea37e17c66b4e67da986
sweetkristas/mercy
/utils/citygen.py
4,065
3.5625
4
from random import randint, random import noise # variables: block_vertical block_horizontal road_vertical road_horizontal # start: block_vertical # rules: (block_vertical -> block_horizontal road_vertical block_horizontal) # (block_horizontal -> block_vertical road_horizontal block_vertical) block_vertical = ...
31d6a644a8962ddabee4d3d9140d47b131880667
ivanifp/tresEnRaya
/main.py
641
3.625
4
from utils import numJugadores,getFicha,colocaFicha,imprimirTablero,tableroLibre,victoria #me creo mi tablero con nueve posiciones tablero = [' ']*9 numJu = numJugadores() fichaj1,fichaj2 = getFicha() while tableroLibre(tablero) or victoria(tablero,fichaj1)== False or victoria(tablero,fichaj2)== False: ...
264b622be15b275164a1259f3906c9d69fe00819
stteem/Python
/MyPython/SearchExercise.py
689
3.875
4
# -*- coding: utf-8 -*- """ Created on Tue Jun 20 13:29:27 2017 @author: Uwemuke """ print("Please think of a number between 0 and 100!") high = 100 low = 0 guess = (high - low)//2.0 while guess**2 < high: print('Is your secret number' + str(guess) + '?') (input("Enter 'h' to indicate the g...
fb43e3221791f1b84663b42bb5d3b7e2917270a5
stteem/Python
/MyPython/Finding biggest value of a key.py
471
3.875
4
# -*- coding: utf-8 -*- """ Created on Mon Jun 26 12:04:30 2017 @author: Uwemuke """ def biggest(aDict): ''' aDict: A dictionary, where all the values are lists. returns: The key with the largest number of values associated with it ''' result = None biggestValue = 0 for key...
25dcce43a2306b81de2040ec215ae16dd77a2136
stteem/Python
/MyPython/midterm1 unfinished.py
569
3.875
4
# -*- coding: utf-8 -*- """ Created on Sat Jul 1 23:48:44 2017 @author: Uwemuke """ def largest_odd_times(L): L1 = {} for i in L: if i in L1: L1[i] += 1 else: L1[i] = 1 return L1 def even(k): k = max(freq) for ...
a63221aca27c99efdc063aa6a716b4fa4f6670c0
stteem/Python
/Pset4/Pset402.py
797
3.96875
4
# -*- coding: utf-8 -*- """ Created on Mon Jul 10 00:19:54 2017 @author: Uwemuke """ def updateHand(hand, word): """ Assumes that 'hand' has all the letters in word. In other words, this assumes that however many times a letter appears in 'word', 'hand' has at least as many of that let...
861508bd3e5b4eeeeb8fcfe56fff987e723f4176
stteem/Python
/MyPython/multiplication_iterative_solution.py
225
3.6875
4
# -*- coding: utf-8 -*- """ Created on Wed Jun 21 12:58:11 2017 @author: Uwemuke """ def multi_iter(a, b): result = 0 while b > 0: result += a b -= 1 return result multi_iter(4, 8)
0f9bc0663d9c38f5e3be9a5051cf0e960736d148
unbecomingpig/scotchbutter
/scotchbutter/util/database.py
4,711
3.515625
4
"""Contains functions to help facilitate reading/writing from a database. NOTE: Currently only supporting sqlite databases """ import logging import sqlite3 import time from scotchbutter.util import environment, tables DB_FILENAME = 'tvshows.sqlite' logger = logging.getLogger(__name__) class DBInterface(): ""...
08ef8703147476759e224e66efdc7b5de5addf6e
chaoma1988/Coursera_Python_Program_Essentials
/days_between.py
1,076
4.65625
5
''' Problem 3: Computing the number of days between two dates Now that we have a way to check if a given date is valid, you will write a function called days_between that takes six integers (year1, month1, day1, year2, month2, day2) and returns the number of days from an earlier date (year1-month1-day1) to a later date...
d53544648c25cc8d0562cc4cd92ce70341e8d353
lch172061365/Computational-Physics
/Project3/3e(for jupiter of original mass).py
3,370
3.640625
4
import matplotlib.pyplot as plt import matplotlib.animation as animation import numpy as np import math from mpl_toolkits.mplot3d import Axes3D import matplotlib.image as img G = 6.67*10**(-11) m1 = 6*10**24 #earth m2 = 2*10**30 #sun m3 = 1.9*10**27 #jupiter #m1 x10 = -149597870000 y10 = 0 z10 = 0 p...
95357539ad5ea90938cb13440a9e419206ba42f3
moisindustries/Leetcode-practice
/238-product-of-array-except-self.py
855
3.546875
4
""" Problem Link: https://leetcode.com/problems/product-of-array-except-self/description/ Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Example: Input: [1,2,3,4] Output: [24,12,8,6] Note: Please solve it...
b2ead9da892231c4d5e5c610d88797290a1cda29
ken4815/CP3-Pakkapong-Thonchaisuratkrul
/Lexture 46.py
87
3.546875
4
n = int(input("N:")) for x in range(24): x = x+1 print(n ,"*",x,"=",n * (x))
562ac5cebcf516d7e40724d3594186209d79c2f4
Vyara/First-Python-Programs
/quadratic.py
695
4.3125
4
# File: quadratic.py # A program that uses the quadratic formula to find real roots of a quadratic equation. def main(): print "This program finds real roots of a quadratic equation ax^2+bx+c=0." a = input("Type in a value for 'a' and press Enter: ") b = input("Type in a value for 'b' and press...
301a8410b1a192e4c0c40b404e0bdaca03005de6
chilu49/python
/deck-blackjack.py
321
3.6875
4
#from random import shuffle #ranks = range(2,11) + ['JACK', 'QUEEN', 'KING', 'ACE'] #print ranks #suits = ['S', 'H', 'D', 'C'] #print suits #def get_deck(): # """Return new deck of cards""" # return [[rank,suit] for rank in ranks for suit in suits] #deck = get_deck() #shuffle(deck) #print deck #print len(deck) ...
2981b59c33aec6471398075ff81f7757888d68e5
hurenkam/AoC
/2022/Day02/part2.py
538
3.765625
4
#!/bin/env python with open('input.txt','r') as file: lines = [line.strip() for line in file] lookup = { "A X": "A C", "A Y": "A A", "A Z": "A B", "B X": "B A", "B Y": "B B", "B Z": "B C", "C X": "C B", "C Y": "C C", "C Z": "C A" } scores = { "A A": 4, "A B": 8, ...
f8ce648c17349a1b550f4e22d6146a9bffe2509f
hurenkam/AoC
/2022/Day11/part2.py
2,832
3.625
4
#!/bin/env python with open('input.txt','r') as file: lines = [line.strip() for line in file] def parseInput(lines): while len(lines): while not lines[0].startswith("Monkey"): lines.pop(0) parseMonkey(lines) monkeys={} def parseMonkey(lines): global monkeys index = parseIn...
4dcb005342c13a213a78196aab6a4739aa80776a
hurenkam/AoC
/2022/Day08/part2.py
1,310
3.578125
4
#!/bin/env python with open('input.txt','r') as file: lines = [line.strip() for line in file] def buildMatrix(): forrest = [] for line in lines: treeline = [] for tree in line: height = int(tree) treeline.append(height) forrest.append(treeline) return f...
23aeb35a5d118fe8e57e355514ff5bb71652b62b
hurenkam/AoC
/2020/Day13/solve.py
1,214
3.703125
4
#!/usr/bin/env python3 #=================================================================================== def Part1(): departures={} tmp = [int(bus) for bus in busses if bus !='x'] for bus in tmp: departs = (int(arrival / bus) +1) * bus waittime = departs - arrival departures[wai...
852cba828e67b97d2ddd91322a827bfdc3c6a849
ridhamaditi/tops
/Assignments/Module(1)-function&method/b1.py
287
4.3125
4
#Write a Python function to calculate the factorial of a number (a non-negative integer) def fac(n): fact=1 for i in range(1,n+1): fact *= i print("Fact: ",fact) try: n=int(input("Enter non-negative number: ")) if n<0 : print("Error") else: fac(n) except: print("Error")
287f5f10e5cc7c1e40e545d958c54c8d01586bfb
ridhamaditi/tops
/Assignments/Module(1)-Exception Handling/a2.py
252
4.15625
4
#write program that will ask the user to enter a number until they guess a stored number correctly a=10 try: n=int(input("Enter number: ")) while a!=n : print("Enter again") n=int(input("Enter number: ")) print("Yay") except: print("Error")
4337d05a72684cdfc0bdef255ccfcce72d5f6432
ridhamaditi/tops
/Assignments/Module(1)-modules/I2.py
188
4.375
4
# Aim: Write a Python program to convert degree to radian. pi=22/7 try: degree = float(input("Input degrees: ")) radian = degree*(pi/180) print(radian) except: print("Invalid input.")
e3eca8bce227d8d6c6b4526189945c2cd79e0c41
ridhamaditi/tops
/functions/prime.py
234
4.1875
4
def isprime(n,i=2): if n <= 2: return True elif n % i == 0: return False elif i*i > n: return True else: return isprime(n,i+1) n=int(input("Enter No: ")) j=isprime(n) if j==True: print("Prime") else: print("Not prime")
bcc1edf1be77b38dff101b8221497dc5baa3f2ec
ridhamaditi/tops
/modules/math_sphere.py
237
4.15625
4
import math print("Enter radius: ") try: r = float(input()) area = math.pi * math.pow(r, 2) volume = math.pi * (4.0/3.0) * math.pow(r, 3) print("\nArea:", area) print("\nVolume:", volume) except ValueError: print("Invalid Input.")
1d2389112a628dbf8891f85d6606ec44543fc81d
ridhamaditi/tops
/Assignments/Module(1)-Exception Handling/a4.py
791
4.21875
4
#Write program that except Clause with No Exceptions class Error(Exception): """Base class for other exceptions""" pass class ValueTooSmallError(Error): """Raised when the input value is too small""" pass class ValueTooLargeError(Error): """Raised when the input value is too large""" pass # user guess...