blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
ac1bb4b1acc7df8629d2389430afd78ac8e2d742
niwasawa/fitbit-api-python-client
/mycommon.py
520
3.609375
4
import json from datetime import date, timedelta class JsonFile: def __init__(self, path): self.path = path def read(self): with open(self.path, "r") as f: data = json.load(f) return data def write(self, data): with open(self.path, "w") as f: json...
dc1a3ef67c780cf3de3de82a817c69fef1787cc4
Jimut123/competitive_programming
/Code/CodeChef/sums_in_triangle.py
315
3.59375
4
T = int(input()) w, h = 100, 100; arr = [[0 for x in range(w)] for y in range(h)] for i in range(T): N = int(input()) for L in range(N+1): for m in range(L): arr[L][m] = int(input()) ''' for L in range(N+1): for m in range(L): print(arr[L][m], end=" ") print() '''
d3406bd578abf761070551779b8526f8c118d9ea
Jimut123/competitive_programming
/Code/HackerRank/Algorithms/fact_py.py
120
3.921875
4
def fact(n): f=1 for i in range(1,n): f=f*i return f n=int(input("Enter a number")) print(fact(n))
52953d818956d0b0ba34b89d35df93d657df3688
Jimut123/competitive_programming
/Code/CodeChef/smallest_no_notes.py
327
3.734375
4
T = int(input()) for i1 in range(T): #print("next") notes = [1,2,5,10,50,100] notes = reversed(notes) sum1 = int(input()) #print("sum1 : ",sum1) count = 0 for item in notes: #print("item : ",item) while sum1 >= item: sum1 -= item count += 1 print(...
08b2e9d9090c0c65d526a4cfa38a0e678b88bfac
delaven007/Date-analysis
/1-numpy-元数据-实际数据-数组的维度-元素的类型-个数-元素的索引下标-维度操作-多维数组的切片操作/demo08_stack.py
867
3.65625
4
""" demo08_stack.py 组合与拆分 """ import numpy as np a = np.arange(1, 7).reshape(2, 3) b = np.arange(7, 13).reshape(2, 3) # 水平方向操作 c = np.hstack((a, b)) print(c) a, b = np.hsplit(c, 2) # 把c沿水平方向拆2份 print(a) print(b) # 垂直方向操作 c = np.vstack((a, b)) print(c) a, b = np.vsplit(c, 2) # 把c沿垂直方向拆2份 print(a) ...
03d9ce71e855604deabf35a3436af68de49972ed
delaven007/Date-analysis
/1-numpy-元数据-实际数据-数组的维度-元素的类型-个数-元素的索引下标-维度操作-多维数组的切片操作/demo01_ndarray.py
178
3.640625
4
""" demo01_ndarray.py numpy演示 """ import numpy as np ary = np.array([1, 2, 3, 4, 5, 6]) print(ary, type(ary)) print(ary + 10) print(ary * 3) print(ary + ary)
d5aafce8e98b320a653cfbd90c2a3d609bb1be12
delaven007/Date-analysis
/8-pandas-Series-Date Timeindex-DateFrame-核心数据结构-描述性统计-排序-分组-分组聚合-透视表与交叉表-数据表关联-可视化-数据读取-电影评分数据分析/4-dfoper-df操作.py
791
3.53125
4
import pandas as pd import numpy as np data={'Name':['Tom','jerry','dabai'],'age':[15,20,11]} df=pd.DataFrame(data,index=['01','02','03']) # print(df) #访问Name列 # print(df['Name']) # print(df['age']) #列添加score列 df['score']=pd.Series([90,56,91],index=['01','03','02']) print(df) #删除列 # del(df['score']) # df.pop('age...
08338c83c60b18ba456752b3494bb74bc6681eab
Djbrr/code-tele
/Sin título0.py
135
3.765625
4
edad=input("Ingrese su edad") a=int(edad) if a >= 18: print("Eres mayor de edad ") else: print("Eres mmenor de edad ")
2729e8514a968a691aee045c69c845b29d39f1b7
tocxu/program
/python/do_using_list.py
500
3.984375
4
#This is my shopping list shoplist=['apple','mange','carrot','banana'] print 'These items are:', for item in shoplist: print item, print '\nI also have to buy rice.' shoplist.append('rice') print 'My shopping list is now', shoplist print 'I will sort my list now' shoplist.sort() print 'Sorted shopping list is', shopl...
c6b2dab45e102ae19dc887e97e296e5c90f68a51
tocxu/program
/python/function_docstring.py
264
4.34375
4
def print_max(x,y): '''Prints the maximum of two numbers. The two values must be integers.''' #convert to integers, if possible x=int(x) y=int(y) if x>y: print x, 'is maximum' else: print y,'is maximum' print (3,5) print_max(3,5) print print_max.__doc__
b7c49cc9c6eca7d9f299308a4a87f012c7ae41ed
tjm8975/TargetPractice
/MouseEvents.py
576
4.0625
4
from pynput.mouse import Listener, Button # ----------------------------------------------------------- # Gets the cursor position when the left mouse button is clicked # # Author: Tyler McGuire (tjm8975) # ----------------------------------------------------------- def on_click(x, y, button, pressed): """Print t...
36fa2fbfc5a1a77e0dd81a3d62bef9a2a4d86d61
L200180117/Algostruk
/Modul_2/tugas6.py
801
3.515625
4
from lat3 import Manusia import datetime class SiswaSMA(Manusia): """Class Mahasiswa yang dibangun dari class Manusia.""" def __init__(self,nama,NIS,kota,umur,us): """Metode inisiai ini menutupi metode inisiai di class Manusia.""" self.nama = nama self.NIS = NIS self.kota...
c66702277bade24ae3cdce28fb78111979cd199a
Aj588/Feb4thClass
/Tests/test_Calculator.py
1,212
3.703125
4
import unittest from Calculator.Calculator import Calculator class MyTestCase(unittest.TestCase): def test_instantiate_calculator(self): calculator = Calculator() self.assertIsInstance(calculator, Calculator) def test_calculator_addition(self): calculator = Calculator() resu...
c19034291b53f933bcc8d1af192e47b2a23a1d60
shahab627/CashConversion
/ConversionCode.py
6,060
3.921875
4
# -------------------------Number to Word Conversion--------------------------------------# # ----------------------------------------------------------------------------------------# # Function to convert single digit or two digit number into words def convertToDigitCash(n, suffix): # if n is zero if n == 0: ...
00dba434bf3305670d82a6d4bbbac34f41658a71
Amaan5033/Leetcode
/Array/leetcodearray2.py
1,832
3.75
4
# def merge(nums1,m,nums2,n): # i=0 # while i<n: # j=0 # while j<=m: # if nums2[i]<=nums1[j]: # nums1.insert(j,nums2[i]) # i+=1 # j+=2 # else: # j+=1 # if nums2[i]>nums1[j-1]: # nums1....
0939ff340b6f0410cedac5b9966dc13d0e42269d
yaelh1995/AlumniPythonClass
/ex18.py
592
4.15625
4
'''def print_two(*args): arg1, arg2 = args print(f"arg1: {arg1}, arg2: {arg2}") def print_two_again(arg1, arg2): print(f"arg1: {arg1}, arg2: {arg2}" def print_one(arg1): print(f"arg1: {arg1}") def print_none(): print("I got nothin'.") print_two("Zed","Shaw")''' '''def function(x, y, z): ans...
a1f7e3ef0244e6459c522035d3807234bf678d42
Tacola320/Beginning
/Python3 practice/books.py
6,922
3.71875
4
import os.path class Book: def __init__(self, title, authors, rating, read): # constructor - object initialisation self.title = title # self - reference to created object - new declarations container self.authors = authors self.rating = rating self.read = read self.set_ra...
2fd61df5b932b1a8d6629b90af109be7cf5381e5
AshleyLab/myheartcounts
/julian_code/motionTrackerParser_update.py
10,771
3.578125
4
### Motion Tracker Parser ### # Aim: # Read in motion tracker files # Output motion tracker summary table and other useful tables # Two output tables: # Table 1: Activity by Person # Table 2: Activity by Time # Input is going to be a file containing a list of motion tracker .csv files to parse together import argpa...
8a36efe4fd98d51d8a1dd50f36f0676656120a97
sahil1291sharma/Linked-List-2
/problem4.py
1,164
3.796875
4
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> ListNode: lenA = 0 lenB = 0 pointerA = headA pointerB = h...
21af03a112d1a154ea5148e32b5b5e9308df1ca1
LeviWadd/filterflow
/filterflow/flow.py
4,201
3.5625
4
from typing import List, Union from plotly.graph_objects import Figure, Funnel class FlowElement: """ A class representing individual steps to be visualised in the process chart. ... Attributes ---------- value : Union[int, float] The value of the data after the processing step. ...
cb224f7dcc0c1fc7ee28b2b3cee1c03d88e6515e
Mortpo/SysIntel
/TD1_TD2_Perceptron_Fonction_AND/Exercice_army_character/character.py
1,354
3.546875
4
print("Classe character bien importee") class Character: # constructeur def __init__(self, nom, prenom, age, profession, boostDeMoral): self.nom = nom self.prenom = prenom self.age = int(age) self.profession = profession self.boostDeMoral = float(boostDeMora...
260e1cf7586341e628064f6c945467d4da442f54
dattapm/ditto
/points.py
5,928
4.0625
4
""" This file has code to get the colinear points in a list of coordinates in a 2D plane. Inputs are from a file called "test_example.csv" and the output is written back to a file called "test_output.csv". Both the csv files are in the same path as this file. """ class Point(object): """ Point cla...
5035109af3e0d2d26d834ccb96ac9f06eb10d728
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter04/cubes.py
127
3.84375
4
#!/usr/bin/python3 cubes = [1**3, 2**3, 3**3, 4**3, 5**3, 6**3, 7**3, 8**3, 9**3, 10**3] for value in cubes: print(value)
8333e601a59a7d7c55d044e79ebdc3750e74816b
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter09/login_attempts.py
2,006
3.953125
4
#!/usr/bin/python3 """Class user""" class Person(): """Model a Person.""" def __init__(self, first_name, last_name): """Initialize first_name and last_name attribute.""" self._first_name = first_name self._last_name = last_name @property def first_name(self): """first_...
3f50d3f8dbc9413e66c76c4dac368bce5c86b98e
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter09/user.py
1,499
3.546875
4
#!/usr/bin/python3 """Class user""" class Person(): """Model a Person.""" def __init__(self, first_name, last_name): """Initialize first_name and last_name attribute.""" self._first_name = first_name self._last_name = last_name @property def first_name(self): """first_...
4c7331490e6a1e22c19134f36556fcc6aed3b653
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter05/favorite_fruit.py
435
3.78125
4
#!/usr/bin/python3 favorite_fruits = ['mango', 'guava', 'strawberry'] if 'mango' in favorite_fruits: print("You really like mango!") if 'guava' in favorite_fruits: print("You really like guava!") if 'strawberry' in favorite_fruits: print("You really like strawberry!") if 'blueberry' in favorite_fruits: ...
684c0c1dda56869fc93817a64f67acb1606107a2
humbertoperdomo/practices
/python/PythonPlayground/PartI/Chapter02/draw_circle.py
455
4.4375
4
#!/usr/bin/python3 # draw_circle.py """Draw a circle """ import math import turtle def draw_circle_turtle(x, y, r): """Draw the circle using turtle """ # move to the start of circle turtle.up() turtle.setpos(x + r, y) turtle.down() # draw the circle for i in range(0, 361, 1): a...
0cf86471707a1038f925e4059d58937729335d70
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter04/numbers.py
180
4.4375
4
#!/usr/bin/python3 # Using the range() function #for value in range(1, 6): #print(value) # Using range() to make a list of numbers numbers = list(range(1, 6)) print(numbers)
ad44d111da84f7e5862bf87e88459ac2a678dab8
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter10/programming_poll.py
336
4
4
#!/usr/bin/python3 """Programming poll.""" path_file = "text_files/programming_poll.txt" print("Write 'quit' to exit") while True: answer = input("Why do you like programming? ") if answer == "quit": break if answer: with open(path_file, 'a') as file_object: file_object.write...
ccb9fdc52feee2381b9eff7c5648bebb796cbb7b
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter05/checking_usernames.py
353
3.984375
4
#!/usr/bin/python3 current_users = ['anonymous', 'webmaster', 'admin', 'dbadmin', 'humberto'] new_users = ['guest', 'WEBMASTER', 'postgres', 'humberto', 'elliot'] for new_user in new_users: if new_user.lower() in current_users: print("You need to enter a new username") else: print("Username "...
032e54a8d1e4616fec42ddb093841c364fc8e65f
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter09/privileges.py
645
3.75
4
#!/usr/bin/python3 """Class user""" class Privileges(): """Model for privileges.""" def __init__(self, privileges): """Initialize privilege attributes.""" self.privileges = privileges def show_privileges(self): """Display user's privileges.""" print("Privileges".center(17)...
c589157feb043c0aabe18f212ed926fa65e35ecf
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter04/my_pizzas_your_pizzas.py
503
4.03125
4
#!/usr/bin/python3 my_pizzas = ['neapolitan', 'california style', 'chicago deep dish', 'chicago thin crust', 'detroit style', 'new england greek', 'new york thin crust', 'st. louis style', 'new jersey style'] friend_pizzas = my_pizzas[:] my_pizzas.append('pepperoni') friend_pizzas.ap...
a4b203896d017258eb8d703b4afc92ce8d03df7c
humbertoperdomo/practices
/python/PythonCrashCourse/PartI/Chapter09/number_served.py
1,550
4.15625
4
#!e/urs/bn/python3 # restaurant.py """Class Restaurant""" class Restaurant(): """Class that represent a restaurant.""" def __init__(self, restaurant_name, cuisine_type): """Initialize restaurant_name and cuisine_type attributes.""" self.restaurant_name = restaurant_name self.cuisine_typ...
cb208c5c106dd65f826a49444f8bacafbb42f73c
nguyenhaitrieu10/algorithm
/helper.py
421
3.546875
4
import random def check_order(a, increase=True): l = len(a) for i in range(l-1): if (a[i] > a[i+1]) == increase: return False return True def init_arr(length, min_value = -100, max_value=100): a = [0] * length for i in range(length): a[i] = random.randint(min_value, ...
0a3647b83534beaea14c2c93ae3feb6bd25156de
nguyenhaitrieu10/algorithm
/sort.py
2,996
3.5
4
def insertion_sort(a): l = len(a) for i in range(1, l): tmp = a[i] j = i - 1 while a[j] > tmp and j >= 0: a[j+1] = a[j] j -= 1 a[j+1] = tmp def flash_sort(a, m = None): n = len(a) if n < 2: return if not m: m = int(0.45 * n)...
6824e7c7d9116fc808d6320f206dd5845e6b0ba5
guguda1986/python100-
/例8.py
351
4.1875
4
#例8:输出99乘法表 for x in range(0,10): for y in range(0,10): if x==0: if y==0: print("*",end="\t") else: print(y,end="\t") else: if y==0: print(x,end="\t") else: print(x*y,end="\t")...
ca8ef99dd051c3de63fd6a7ce5d8e8c4451016e0
guguda1986/python100-
/例2.py
948
3.625
4
#例2:题目:企业发放的奖金根据利润提成。利润(I)低于或等于10万元时,奖金可提10%;利润高于10万元, # 低于20万元时,低于10万元的部分按10%提成,高于10万元的部分,可可提成7.5%;20万到40万之间时,高于20万元的部分,可提成5%; # 40万到60万之间时高于40万元的部分,可提成3%;60万到100万之间时, # 高于60万元的部分,可提成1.5%,高于100万元时,超过100万元的部分按1%提成, # 从键盘输入当月利润I,求应发放奖金总数? try: profit=int(input("请输入利润值(万元):")) except ValueError as e: prin...
12aa7a2427ee54468c5365dc415aa434380dd06f
thonycarrera/El-tiempo-de-valor-esperado-en-algoritmos-de-ordenamiento
/BubbleSort_Random.py
952
3.921875
4
# coding: utf-8 # In[3]: import random print("Ingrese cuantos numeros aleatorios desea obtener") n=int(input()) vector = [random.randint(0,1000) for _ in range(n)] print ("vector desordenado") print(vector) def bubble_sort(vector): permutation = True iteración = 0 while permutation == True: pe...
5d2c49f3e11cc346105c7fb02c59435e2b56af76
Necmttn/learning
/python/algorithms-in-python/r-1/main/twenty.py
790
4.25
4
""" Python’s random module includes a function shuffle(data) that accepts a list of elements and randomly reorders the elements so that each possi- ble order occurs with equal probability. The random module includes a more basic function randint(a, b) that returns a uniformly random integer from a to b (including both ...
235660ef27949d38f8e7f335c67ad084123b9660
Necmttn/learning
/python/algorithms-in-python/r-1/main/eighteen.py
224
4.09375
4
""" Demonstrate how to use Python’s list comprehension syntax to produce the list [0, 2, 6, 12, 20, 30, 42, 56, 72, 90]. """ print([0, 2, 6, 12, 20, 30, 42, 56, 72, 90]) array = [n * (n+1) for n in range(10)] print(array)
d69ba19f1271f93a702fd8009c57a34a11122c6b
Necmttn/learning
/python/algorithms-in-python/r-1/main/sixteen.py
684
4.21875
4
""" In our implementation of the scale function (page25),the body of the loop executes the command data[j]= factor. We have discussed that numeric types are immutable, and that use of the *= operator in this context causes the creation of a new instance (not the mutation of an existing instance). How is it still poss...
8cc73de7110d0300d84909f76d7cebb6f0e772e9
tboy4all/Python-Files
/csv_exe.py
684
4.1875
4
#one that prints out all of the first and last names in the users.csv file #one that prompts us to enter a first and last name and adds it to the users.csv file. import csv # Part 2 def print_names(): with open('users.csv') as file: reader = csv.DictReader(file) for row in reader: pri...
5a831727b65f8e4f84d3832b04ea062b9a116df4
tboy4all/Python-Files
/file.py
2,689
3.90625
4
# Working with files # with open('first.txt', 'w') as file: # file.write('Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eos molestias ea sit veniam, rerum, totam quis eaque excepturi aut, nostrum reiciendis. At, harum quos adipisci magni nesciunt aliquid beatae sit!') # with open('first.txt', 'r') as ...
a86bfe04b79656bf4510ba9c70d16f26eb0e29e6
afroll/learnpy
/Specialist/Mart20/session1/task17.py
253
3.703125
4
class Circle: R = 0 class Reactangle: A = 0.0 B = 0.0 def Ratio(c : Circle, r:Reactangle) -> bool: answer = (c.R *2 <= r.A and c.R * 2 <= r.B) return answer c = Circle() c.R = 20 r = Reactangle() r.A, r.B = 100, 200 print(Ratio(c,r))
d8d07e4a3043a16f0080521d3182621452cbabde
afroll/learnpy
/Specialist/Mart20/session1/temp2.py
233
3.875
4
#a = int(input()) #b = int(input()) c = int(input()) a, b, c = int(input()), int(input()), int(input()) if a**2 + b**2 == c**2 or b**2 + c**2 == a**2 or c**2 + a**2 == b**2: print(b*a/2) elif: True pass # print(a + b + c)
43655bef160270d41e6c9c76c4460e72dc414666
holomorphicsean/PyCharmProjectEuler
/euler8.py
712
3.640625
4
"""The four adjacent digits in the 1000-digit number that have the greatest product are 9 x 9 x 8 x 9 = 5832. (num in txt file) Find the thirteen adjacent digits in the 1000-digit number that have the greatest product. What is the value of this product?""" import time t0 = time.time() # import number from file wit...
0fbfcaafa9794d32855c67db1117c3ec4d682864
holomorphicsean/PyCharmProjectEuler
/euler9.py
778
4.28125
4
"""A Pythagorean triplet is a set of three natural numbers, a < b < c, for which, a**2 + b**2 = c**2 For example, 3**2 + 4**2 = 9 + 16 = 2**5 = 52. There exists exactly one Pythagorean triplet for which a + b + c = 1000. Find the product abc.""" import time import math # We are going to just brute force this and ch...
bf7d29ded9cdd5e26cdc9f8bb5583700a49348a0
an-2-an/new_stuff
/salary1.py
489
3.625
4
class Salary: def __init__(self, pay): self.pay = pay def getTotal(self): return (self.pay * 12) class Employee: def __init__(self, name, pay, bonus): self.name = name self.bonus = bonus self.salary = Salary(pay) def annualSalary(self): ...
0b82df64587bb39a5af9fa81f636ad60dc77e94c
balajipothula/python
/greet.py
161
3.765625
4
def greet(* names): """this function greets the person in names tuple.""" for name in names: print("Hi... " + name) greet("Ram", "Ali", "Sam", "Jak")
bed2ed9eb986d2efacaccbf97073282809dc47f5
balajipothula/python
/emp.py
1,450
3.671875
4
class Emp: org = "InfoSys" def __init__(self): pass def set_no(self, no): self.no = no def set_name(self, name): self.name = name def set_sal(self, sal): self.sal = sal def get_no(self): return self.no def get_name(self): return self.name def get_sal(self): return self.sal @clas...
17f3e4d1171761cfd80c0a558c2b2a02eebca558
balajipothula/python
/nano_second.py
255
3.5625
4
import time ns_list = list() for i in range(10): time_now_ns = time.time_ns() ns_list.insert(i, time_now_ns) if 0 < i and i < 10: print("Current NS:", ns_list[i], "| Previous NS:", ns_list[i - 1], "| Difference:", ns_list[i] - ns_list[i - 1])
d0b194a1bd993ee9c4b2c648aaae4760c0406a5e
balajipothula/python
/iterator.py
562
3.90625
4
import random item = random.randrange(9) item_list = [item for item in range(9)] item_list_len = len(item_list) item_iter = iter(item_list) # creating an iterator object from iter. for _ in range(item_list_len): print(next(item_iter)) for item in item_list: print(item) item_iter = iter(item_lis...
2b82dcdcaf78f81b3d68a6d2e995870d8c8e6c42
balajipothula/python
/time_diff.py
157
3.515625
4
import time """ for i in range(9): sns = time.time_ns() print(time.time_ns() - sns) """ for i in range(9): print(abs(time.time_ns() - time.time_ns()))
0d28d444459d700a617cfc31982164e99f81f53d
balajipothula/python
/fun_add.py
96
3.734375
4
def sum(a, b): a = int(a) b = int(b) return a + b a = int(2) b = int(3) print(sum(a, b))
d5f309bd31d8ebb7fa7bfdc87627db767f442ecc
wdixon2186/greenGithub
/page.py
225
3.8125
4
def myfunc(word): result = "" index = 0 for letter in word: if index % 2 == 0: result += letter.lower() else: result += letter.upper() index += 1 return result
0d50b95e198e76d47c1818668f7a8426ee08b711
niels-bijl/pws-het-optimale-neurale-netwerk
/neuralNetwork.py
13,804
3.90625
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ neuralNetwork.py is a module to create a neural network with variable inputs, outputs, hidden neurons, hidden layers, learning rate and activation function. The activation function is either sigmoid or tanh, any similar function could be added. \nThis module is not op...
b56575c39d08442c6d7f3d0b029be47e80bc5afd
mflix21/BasicCode
/exam.py
392
4.0625
4
bangla = int(input("Enter Your Bangla Exam score :")) english = int(input("Enter Your English exam's score: ")) math=int(input(" Enter your Math exam's score:")) average=(bangla + english + math)/3 print("Avearge is: ", average) if (average <=100) and (average >=80): print("You got A+") elif (average <=79) and (a...
c6229d083483d04db5018d7eb41646566efed9dd
Murali1125/Fellowship_programs
/DataStructurePrograms/tree.py
2,262
3.953125
4
"""-------------------------------------------- ------- Binary Search Tree -------------------- --------------------------------------------""" class Node(): # declaring and initializing left_child and right_child variables def __init__(self,data): self.data = data self.left_child = None ...
1dbf066eeb432496cb1cc5dec86d41f54eefd74f
Murali1125/Fellowship_programs
/DataStructurePrograms/2Darray_range(0,1000).py
901
4.15625
4
"""-------------------------------------------------------------------- -->Take a range of 0 - 1000 Numbers and find the Prime numbers in that --range. Store the prime numbers in a 2D Array, the first dimension --represents the range 0-100, 100-200, and so on. While the second --dimension represents the prime numbers ...
31bede31943cb2a73b2df927ac9715047967fb5b
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/intermediate-bite-47-write-a-new-password-field-validator.py
1,106
3.671875
4
import string import re PUNCTUATION_CHARS = list(string.punctuation) used_passwords = set('PassWord@1 PyBit$s9'.split()) def validate_password_1(password): if len(password) < 6 or len(password) > 12: return False if not any(elem in password for elem in string.ascii_lowercase): return False ...
c68bcee8dcd0d839f4aa1f3cab3b33b4eda4a4b7
syurskyi/Python_Topics
/070_oop/001_classes/examples/Python_3_Deep_Dive_Part_4/Section 02 - Classes/02-Class_Attributes.py
3,088
4.625
5
# %% ''' ### Class Attributes ''' # %% ''' As we saw, when we create a class Python automatically builds-in properties and behaviors into our class object, like making it callable, and properties like `__name__`. ''' # %% class Person: pass # %% print(Person.__name__) # %% ''' `__name__` is a **class attribute...
d72e105cbde6386290ce7356a16daad6728b1abb
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/beginner-bite-54-nicer-formatting-of-a-poem-or-text-solution.py
2,292
3.640625
4
INDENTS = 4 poem = """Remember me when I am gone away, Gone far away into the silent land; When you can no more hold me by the hand, Nor I half turn to go yet turning stay. Remember me when no more day by day You tell me of our future that you planned: Only remember me; you understand""" ''' TO: Remember me when I ...
521f66164c2a06be0ae2df82b20a533b13aaaa6f
syurskyi/Python_Topics
/125_algorithms/002_linked_lists/_exercises/templates/Linked Lists/Linked Lists Interview Problems/SOLUTIONS/Implement a Linked List -SOLUTION.py
900
4.0625
4
# # Implement a Linked List - SOLUTION # # Problem Statement # # Implement a Linked List by using a Node class object. Show how you would implement a Singly Linked List and # # a Doubly Linked List! # # Solution # # Since this is asking the same thing as the implementation lectures, please refer to those video lectures...
ebfd35ab13d1b55fe3b78f1974a512a1dccb7a4d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/921 Minimum Add to Make Parentheses Valid.py
1,116
4.21875
4
#!/usr/bin/python3 """ Given a string S of '(' and ')' parentheses, we add the minimum number of parentheses ( '(' or ')', and in any positions ) so that the resulting parentheses string is valid. Formally, a parentheses string is valid if and only if: It is the empty string, or It can be written as AB (A concatenate...
298e2bd5741161edb39348e568dd55eee554aefd
syurskyi/Python_Topics
/115_testing/examples/Github/_Level_1/Python_Unittest_Suite-master/Python_Unittest_Autospeccing.py
9,071
3.640625
4
# Python Unittest # unittest.mock � mock object library # unittest.mock is a library for testing in Python. # It allows you to replace parts of your system under test with mock objects and make assertions about how they have been used. # unittest.mock provides a core Mock class removing the need to create a host of stu...
0d8b57365beaaca6940ad84d70f49ee2738f93ae
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/beginner/beginner-bite-189-filter-a-list-of-names.py
1,362
3.921875
4
''' Here is a Bite to practice the continue and break statements in Python. Complete filter_names that takes a list of names and returns a filtered list (or generator) of names using the following conditions: names that start with IGNORE_CHAR are ignored, names that have one or more digits are ignored, if a name star...
5aaa6779a3165835b1148017ba0f72374d93bd9b
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/leetCode/DP/FindAllAnagramsInAString.py
6,136
3.890625
4
""" Given a string s and a non-empty string p, find all the start indices of p's anagrams in s. Strings consists of lowercase English letters only and the length of both strings s and p will not be larger than 20,100. The order of output does not matter. Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] E...
27fbcb3e2bd4f38542bfeb641a06522b0b78dbc8
syurskyi/Python_Topics
/090_logging/examples/Good logging practice in Python/005_Capture exceptions with the traceback.py
1,036
3.796875
4
# Capture exceptions with the traceback # While its a good practice to log a message when something goes wrong, but it won’t be helpful if there is no # traceback. You should capture exceptions and record them with traceback. Following is an example: try: open('/path/to/does/not/exist', 'rb') except (SystemExit, K...
3ee769cd56f9442727c6d6d340f4d2339a22b4b1
syurskyi/Python_Topics
/085_regular_expressions/examples/Python 3 Most Nessesary/7.1. Validating Date Entry.py
1,275
4.0625
4
# -*- coding: utf-8 -*- import re # Подключаем модуль d = "29,12.2009" # Вместо точки указана запятая p = re.compile(r"^[0-3][0-9].[01][0-9].[12][09][0-9][0-9]$") # Символ "\" не указан перед точкой if p.search(d): print("Дата введена правильно") else: print("Дата введена неправильно") # Так как точ...
5c40b91d1ff705a2d6251384d1f5cc94fc6f8308
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/222/grouping.py
777
3.96875
4
import types from itertools import islice def group(iterable, n): """Splits an iterable set into groups of size n and a group of the remaining elements if needed. Args: iterable (list): The list whose elements are to be split into groups of size n. n (int...
3b5585e2325079f5f377799d776e8d310a8b4785
syurskyi/Python_Topics
/120_design_patterns/018_memento/examples/Memento_003.py
1,768
3.75
4
#!/usr/bin/env python # Written by: DGC import copy #============================================================================== class Memento(object): def __init__(self, data): # make a deep copy of every variable in the given class for attribute in vars(data): # mechanism for usi...
fbe432fd9b639b65e4a30d24dbc28b030ccf1f92
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/Combination/300_LongestIncreasingSubsequence.py
1,487
3.578125
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # @Author: xuezaigds@gmail.com class Solution(object): """ Clear explanation is here: https://leetcode.com/discuss/67687/c-o-nlogn-solution-with-explainations-4ms https://leetcode.com/discuss/67643/java-python-binary-search-o-nlogn-time-with-explanation ...
b996bce21762c5818b39e4808aa6634d269daa8a
syurskyi/Python_Topics
/050_iterations_comprehension_generations/001_iterations_and_iteration_tool/examples/006_Iterators and Iterables.py
2,804
4.09375
4
# Rolling our own Next method # implement a __len__ method to support the len() function class Squares: def __init__(self, length): self.length = length self.i = 0 def next_(self): if self.i >= self.length: raise StopIteration else: result = self.i ** 2 ...
beb405bd8df7b3ca250f33ed290c7c3bf6cdc220
syurskyi/Python_Topics
/070_oop/001_classes/_exercises/exercises/The_Complete_Python_Course_l_Learn_Python_by_Doing/69. More @classmethod and @staticmethod examples.py
3,952
4.3125
4
# # -*- coding: utf-8 -*- # # """ # Those were some terrible examples in the last section, # but I just wanted to show you the syntax for these two types of method. # # The `@...` is called a decorator. Those are important in Python, and we’ll be looking at creating our own later on. # They are used to modify the fun...
8e0473060aebbd4bbff8b043dbb4c22e89182310
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/beginner/beginner-bite-67-working-with-datetimes.py
897
3.734375
4
''' This Bite involves solving two problems using datetime: We kicked off our 100 Days of Code project on March 30th, 2017. Calculate what date we finished the full 100 days! PyBites was founded on the 19th of December 2016. We're attending our first PyCon together on May 8th, 2018. Can you calculate how many days fro...
ca37843c0c1342edad186433fbf19a555ffd4606
syurskyi/Python_Topics
/125_algorithms/_exercises/exercises/Learn_Python_by_solving_100_Coding_Challenges/Coding Challenge No. 51 - LongestSubStrWR.py
777
3.640625
4
# # Longest Substring without Repeating Characters # # Question: Given a string, find the length of the longest substring without repeating characters. For example: # # Given "abcabcbb", the answer is "abc", which the length is 3. # # Given "bbbbb", the answer is "b", with the length of 1. # # Given "pwwkew", the answe...
915d32ec5540ad020ffdffd0110922a6996848bf
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/59_v2/tables.py
770
3.90625
4
# c_ MultiplicationTable # # ___ - length # """Create a 2D self._table of (x, y) coordinates and # their calculations (form of caching)""" # _length ? # _table s.. x * y ___ ? __ r.. 1 l.. + 1 ___ ? __ r.. 1 l.. + 1 # # ___ -l # """Returns the area of the table (len ...
3e60a45e7923bb72bece7ee0f705b2d6467ee4a6
syurskyi/Python_Topics
/070_oop/001_classes/examples/The_Complete_Python_Course_l_Learn_Python_by_Doing/61. More about classes and objects.py
1,239
4.5
4
""" Object oriented programming is used to help conceptualise the interactions between objects. I wanted to give you a couple more examples of classes, and try to answer a few frequent questions. """ class Movie: def __init__(self, name, year): self.name = name self.year = year """ Parameter na...
1194267d03094c9f1f6ac33eae62de730fc10019
syurskyi/Python_Topics
/055_modules/001_modules/examples/ITVDN Python Essential 2016/08_StdlibCopy/example.py
1,434
3.859375
4
"""Пример использования модуля copy. Операция присваивания не копирует объект, а лишь создаёт ссылку на объект. Для изменяемых объектов и для объектов, содержащих ссылки на изменяемые объекты, часто необходима такая копия, чтобы её можно было изменить, не изменяя оригинал. Данный модуль предоставляет общие операции к...
46f9f5b645560f406172428f36f3c72a061db1a7
syurskyi/Python_Topics
/125_algorithms/_exercises/exercises/Python_Hand-on_Solve_200_Problems/Section 5 List/check_a_list_contains_sublist_solution.py
671
3.59375
4
# # To add a new cell, type '# %%' # # To add a new markdown cell, type '# %% [markdown]' # # %% # # Write a Python program to check whether a list contains a sublist. # # Input # # a = [2,4,3,5,7] # # b = [4,3] # # c = [3,7] # # print(is_Sublist(a, b)) # # print(is_Sublist(a, c)) # # Output # # ___ is_Sublist l s # s...
747b574831fc38f3245ebd9f7e1b2f5436e042bd
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/BreadthFirstSearch/104_MaximumDepthOfBinaryTree.py
1,131
4
4
#! /usr/bin/env python # -*- coding: utf-8 -*- # Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def maxDepth(self, root): """ :type root: TreeNode ...
1909c924fae99d2f138b8a8039110b773308beb9
syurskyi/Python_Topics
/120_design_patterns/018_memento/examples/Section_18_Memento/memento.py
630
3.5625
4
class Memento: def __init__(self, balance): self.balance = balance class BankAccount: def __init__(self, balance=0): self.balance = balance def deposit(self, amount): self.balance += amount return Memento(self.balance) def restore(self, memento): self.balance...
71bd3afd970929adfb4c2b56d0042e479ffc234d
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/997 Find the Town Judge.py
1,459
3.75
4
#!/usr/bin/python3 """ In a town, there are N people labelled from 1 to N. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: The town judge trusts nobody. Everybody (except for the town judge) trusts the town judge. There is exactly one person that satisfies proper...
6824db8b7b9584ddfdb168ba5b18db0085e598e6
syurskyi/Python_Topics
/125_algorithms/_examples/Python_Hand-on_Solve_200_Problems/Section 6 String/revert_word_in_string_solution.py
500
3.8125
4
# To add a new cell, type '# %%' # To add a new markdown cell, type '# %% [markdown]' # %% # 'The quick brown fox jumps over the lazy dog.' # input : "The quick brown fox jumps over the lazy dog." # output : "dog. lazy the over jumps fox brown quick The " def reverse_string_words(text): for line in text.split('\n'...
bbbd1d21e8e907c7353f2a1aee9c6c2984a4c255
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/Algorithmic Problems in Python/binary_search.py
986
4.3125
4
#we can achieve O(logN) but the array must be sorted ___ binary_search(array,item,left,right): #base case for recursive function calls #this is the search miss (array does not contain the item) __ right < left: r.. -1 #let's generate the middle item's index middle left + (right-left)//2 print("Middle index...
be41d3202083ac50de9a80f6f6629af48caf4221
syurskyi/Python_Topics
/100_databases/001_sqlite/examples/Python SQLite Tutorial/005.Updating (UPDATE) and Deleting (DELETE) Data.py
508
3.828125
4
import sqlite3 # Create a database in RAM # db = sqlite3.connect(':memory:') # Creates or opens a file called mydb with a SQLite3 DB db = sqlite3.connect('mydb.db') # Get a cursor object cursor = db.cursor() # Update user with id 1 newphone = '7113093164' userid = 1 cursor.execute('''UPDATE users SET phone = ? WHERE...
55b4a567ef2be40b7d5be1589f00fa226e2f1fe5
syurskyi/Python_Topics
/045_functions/003_scopes/_exercises/templates/003_scopes_template.py
8,906
4.25
4
# Function # Python Scope Basics # X = 99 # # ___ func # X = 88 # # # Global scope # X = 99 # X and func assigned in module: global # # ___ func # Y and Z assigned in function: locals # # Local scope # Z = X + Y # X is a global # ___ Z # # print(f_(1)) # func in module: result=100 # # print() # ###...
bd28ee784125856bb70381ba15cfa76809cf5712
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/846 Hand of Straights.py
2,127
4
4
#!/usr/bin/python3 """ Alice has a hand of cards, given as an array of integers. Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards. Return true if and only if she can. Example 1: Input: hand = [1,2,3,6,2,3,4,7,8], W = 3 Output: true Explanation: Ali...
11b7c7731c24d0f364c457bc063de71751d32996
syurskyi/Python_Topics
/060_context_managers/examples/98. Context Managers - Coding.py
12,754
4.40625
4
# You should be familiar with try and finally. # # We use the finally block to make sure a piece of code is executed, whether an exception has happened or not: print('#' * 52 + ' You should be familiar with `try` and `finally`.') try: 10 / 2 except ZeroDivisionError: print('Zero division exception occurred')...
5fb93b463f49e0440570a02f3d1eea4cc91e8d0f
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/405 Convert a Number to Hexadecimal.py
1,467
4.3125
4
""" Given an integer, write an algorithm to convert it to hexadecimal. For negative integer, two's complement method is used. Note: All letters in hexadecimal (a-f) must be in lowercase. The hexadecimal string must not contain extra leading 0s. If the number is zero, it is represented by a single zero character '0'; ...
14aa4a84710ad91c28ff1edfa56d88a79a164da5
syurskyi/Python_Topics
/125_algorithms/005_searching_and_sorting/_exercises/templates/03_Selection Sort/6 Selection Sort - Optimizing the Process/Selection-Sort.py
721
3.640625
4
# ___ selection_sort lst # # Traverse the list. # # i represents the index where the unsorted portion of the list starts. # ___ i __ ra.. le. ? # # The min_index variable describes the index of the # # smallest element in the remaining unsorted array. # min_index __ i # # For...
e415830c017fb802d0f55c1f525d59af43fe82b1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/838 Push Dominoes.py
2,392
4.1875
4
#!/usr/bin/python3 """ There are N dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dom...
36cc9545d385aa5187f8384778f1ef4f5ea63e6f
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/ToBeOptimized/131_PalindromePartitioning.py
1,552
3.921875
4
#! /usr/bin/env python # -*- coding: utf-8 -*- class Solution(object): def partition(self, s): if not s: return [] self.result = [] self.end = len(s) self.str = s self.is_palindrome = [[False for i in range(self.end)] for j in rang...
e63f828f4754b9fc0144158f00d8590a2d647b05
syurskyi/Python_Topics
/018_dictionaries/__for_nuke/dict_implement_in_nuke_for_exercise.py
12,808
3.609375
4
# Генераторы словарей # ===== Python Example ================================================================================ keys = ["a", "b"] # Список с ключами values = [1, 2] # Список со значениями print({k: v for (k, v) in zip(keys, values)}) # {'a': 1, 'b': 2} # ===============================================...
231c8bcd489bcb10e9021dbe12f65ab5fe8b39e1
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/049 Anagrams.py
1,795
3.96875
4
""" Given an array of strings, return all groups of strings that are anagrams. Note: All inputs will be in lower-case. """ __author__ 'Danyang' c_ Solution: ___ anagrams_complicated strs """ sorting :param strs: a list of strings :return: a list of strings """ temp ...
cf7895c32a09b5ad12e8985b811797f8d3962c58
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/leetcode/LeetCode_with_solution/590 N-ary Tree Postorder Traversal.py
1,316
4.1875
4
#!/usr/bin/python3 """ Given an n-ary tree, return the postorder traversal of its nodes' values. For example, given a 3-ary tree: Return its postorder traversal as: [5,6,3,2,4,1]. Note: Recursive solution is trivial, could you do it iteratively? """ # Definition for a Node. c_ Node: ___ - , val, children ...
3b861d116d0289dc7662a3956020bfffc88e471e
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/pybites/intermediate/296_v3/jagged_list.py
325
3.5625
4
from typing import List def jagged_list(lst_of_lst: List[List[int]], fillvalue: int = 0) -> List[List[int]]: if not lst_of_lst: return lst_of_lst max_length = max(len(l) for l in lst_of_lst) for l in lst_of_lst: l.extend([fillvalue] * (max_length - len(l))) return lst_of_lst ...
ddcc76ac47bbc8655cd30fcc09ed79e21fa84ed7
syurskyi/Python_Topics
/125_algorithms/_exercises/templates/_algorithms_challenges/pybites/intermediate/159_v4/calculator.py
852
3.84375
4
# _______ o.. # # OPS '+': o__.a.. # '-': o__.s.. # '*': o__.m.. # '/': o__.t.. # # # ___ simple_calculator calculation # """Receives 'calculation' and returns the calculated result, # # Examples - input -> output: # '2 * 3' -> 6 # '2 + 6' -> 8 # # Support +, -, * an...
944ce5faed641cfb22809ba5fd7ba92bcc9d26a3
syurskyi/Python_Topics
/070_oop/007_exceptions/_exercises/templates/The_Modern_Python_3_Bootcamp/Coding Exercise 72 Debugging and Error Handling Exercises.py
295
3.703125
4
# Division Exercise Solution # # Here's my version of the divide function: def divide(a, b): try: total = a / b except TypeError: return "Please provide two integers or floats" except ZeroDivisionError: return "Please do not divide by zero" return total
9b89a115415f646f17a49c89128e129f6e337211
syurskyi/Python_Topics
/125_algorithms/_examples/_algorithms_challenges/leetcode/leetCode/String/MinimumWindowSubstring.py
3,305
3.875
4
""" Given a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n). Example: Input: S = "ADOBECODEBANC", T = "ABC" Output: "BANC" Note: If there is no such window in S that covers all characters in T, return the empty string "". If there is such window, yo...