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.dump(data, f, indent=2)
class DateTime:
def yesterday():
return date.today() - timedelta(days=1)
def yyyymmdd(date):
# YYYY-MM-DD
return date.strftime("%Y-%m-%d")
|
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(count)
|
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)
print(b)
# 深度方向操作
c = np.dstack((a, b))
print(c)
a, b = np.dsplit(c, 2) # 把c沿深度方向拆2份
print(a)
print(b)
# 数组头尾补全
a = np.array([1,2,3,4,5,6])
b = np.array([8,8,8,8])
b = np.pad(b, pad_width=(1,1), mode='constant',
constant_values=-1)
print(b)
# 一维数组的组合方案:
a = np.arange(10, 20)
b = np.arange(20, 30)
print(a)
print(b)
c = np.row_stack((a, b))
print(c)
d = np.column_stack((a, b))
print(d)
|
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')
# print(df)
# print('-'*45)
#
# #行访问
# print(df[:2]) #前两行
# print(df.loc['01']) #通过索引标签名
# print(df.loc[['01','02']]) #通过索引标签组
# print(df.iloc[0])
# print(df.iloc[[0,2]])
#行添加
# print('*'*45)
# print(df)
# df=df.append(df)
# print(df)
# print(df.loc['01'])
#行删除
print('^'*56)
print(df)
df=df.drop('02')
print(df)
#修改元素
df['Name'][0]='lucy'
print(df)
|
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', shoplist
print 'The first item I will buy is ',shoplist[0]
olditem = shoplist[0]
del shoplist[0]
print 'I bought the ', olditem
print 'My shopping list is now ',shoplist
print 'Done'
|
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 the cursor position when the left mouse button is clicked"""
if pressed and button == Button.left:
print("Mouse Clicked: (%d, %d)" %(x, y))
listener.stop()
# Create the Listener
with Listener(on_click=on_click) as listener:
listener.join() |
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.kotaTinggal = kota
self.umur = umur
self.uangSaku = us
def __str__(self):
s = self.nama + ', NIS ' + str(self.NIS) \
+ '. Tinggal di ' + self.kotaTinggal \
+ '. Berumur ' + str(self.umur) \
+ '. Uang Saku Rp ' + str(self.uangSaku) \
+ ' tiap harinya.'
return s
def tahunLahir(self):
thnskr = datetime.datetime.now().year
tl = thnskr - self.umur
return tl
|
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()
result = calculator.addition(1,2)
self.assertEquals(3, result)
def test_calculator_subtraction(self):
calculator = Calculator()
result = calculator.subtraction(1, 2)
self.assertEquals(-1, result)
def test_calculator_division(self):
calculator = Calculator()
result = calculator.division(6,3)
self.assertEquals(2, result)
def test_calculator_multiplication(self):
calculator = Calculator()
result = calculator.multiplication(6,3)
self.assertEquals(18, result)
def test_calculator_squared(self):
calculator = Calculator()
result = calculator.squared(6)
self.assertEquals(36, result)
def test_calculator_sqrt(self):
calculator = Calculator()
result = calculator.sqrt(9)
self.assertEquals(3, result)
if __name__ == '__main__':
unittest.main() |
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:
return ""
# split n if it is more than 19
if n > 19:
return Twenties[n // 10] + Ones[n % 10] + suffix
else:
return Ones[n] + suffix
def convertToDigitPhone(n):
if n == 0:
return ""
# split n if it is more than 19
if n > 19:
return Twenties[n // 10] + Ones[n % 10]
else:
return Ones[n]
def num2Word(num, symbol):
n = int(num)
result = ""
if (symbol != '+'): # For Cash
# add digits at ten millions & hundred millions place
result = convertToDigitCash((n // 1000000000) % 100, "Billion ")
# add digits at ten millions & hundred millions place
result += convertToDigitCash((n // 10000000) % 100, "Crore ")
# add digits at hundred thousands & one millions place
result += convertToDigitCash(((n // 100000) % 100), "Lakh ")
# add digits at thousands & tens thousands place
result += convertToDigitCash(((n // 1000) % 100), "Thousand ")
# add digit at hundreds place
result += convertToDigitCash(((n // 100) % 10), "Hundred ")
if n > 100 and n % 100:
result += "and "
else: # For Phone number
result = "Plus "
result += convertToDigitPhone((n // 100000000000) % 100)
# add digits at ten millions & hundred millions place
result += convertToDigitPhone((n // 1000000000) % 100)
# add digits at ten millions & hundred millions place
result += convertToDigitPhone((n // 10000000) % 100)
# add digits at hundred thousands & one millions place
result += convertToDigitPhone(((n // 100000) % 100))
# add digits at thousands & tens thousands place
result += convertToDigitPhone(((n // 1000) % 100))
# add digit at hundreds place
result += convertToDigitPhone(((n // 100) % 10))
if n > 100 and n % 100:
result += "and "
# add digits at ones & tens place
result += convertToDigitCash((n % 100), "")
# adding currency type
if symbol == '' or symbol == '+' or "None":
result += ""
else:
result += " " + str(Symbol.get(symbol))
return result
# -------------------------Word to Number Conversion--------------------------------------#
# ----------------------------------------------------------------------------------------#
def word2Num(num):
result = ""
ones = {'zero': 0,
'one': 1, 'eleven': 11,
'two': 2, 'twelve': 12,
'three': 3, 'thirteen': 13,
'four': 4, 'fourteen': 14,
'five': 5, 'fifteen': 15,
'six': 6, 'sixteen': 16,
'seven': 7, 'seventeen': 17,
'eight': 8, 'eighteen': 18,
'nine': 9, 'nineteen': 19}
# a mapping of digits to their names when they appear in the 'tens'
# place within a number group
tens = {'ten': 10,
'twenty': 20,
'thirty': 30,
'forty': 40,
'fifty': 50,
'sixty': 60,
'seventy': 70,
'eighty': 80,
'ninety': 90}
# an ordered list of the names assigned to number groups
groups = {'thousand': 1000,
'million': 1000000,
'billion': 1000000000,
'trillion': 1000000000000}
Symbol2Word = {"Dollar": '$',
"pence": 'p',
"pounds": '£',
"plus": '+'}
# initializing string
test_str = num
# checking word from list in Dictionary and obtaining Value
for word in test_str:
if word in ones:
result += str(ones.get(word))
if word in tens:
result += str(tens.get(word))
if "-" in word:
half = word.split('-')
num1 = tens.get(half[0])
num2 = ones.get(half[1])
data = num1 + num2
result += str(data)
if word in Symbol2Word:
result += Symbol2Word.get(word)
return result
# --------------------------------------------------------------------------------------------#
def ReadFile():
with open(r"C:\Users\User\Downloads\TestCase.txt", "r+") as file_in: # loading File Data from file
for line in file_in:
line = line.strip('\n')
line = line.strip('Â')
lines.append(line)
def WriteFile(Result):
with open(r"C:\Users\User\Downloads\Result.txt", "a+") as f:
f.writelines(Result + '\n')
f.closed
# -------------------------------------------------------------------------------#
Ones = ["", "One ", "Two ", "Three ", "Four ", "Five ", "Six ",
"Seven ", "Eight ", "Nine ", "Ten ", "Eleven ", "Twelve ",
"Thirteen ", "Fourteen ", "Fifteen ", "Sixteen ",
"Seventeen ", "Eighteen ", "Nineteen "]
Twenties = ["", "", "Twenty ", "Thirty ", "Forty ", "Fifty ",
"Sixty ", "Seventy ", "Eighty ", "Ninety "]
Symbol = {'$': "Dollar",
'p': "pence ",
'£': "pound",
'+': "plus"}
word = []
lines = []
ReadFile()
for line in lines:
if line.isnumeric() or line[0] in Symbol:
symbol = line[0]
line = line[1:] # obtaining and removing Cash symbol from line
result = num2Word(line, symbol)
WriteFile(result) # writing in file
else:
line = line.lower()
if "and" in line: # Splitting String in Word by word
word = line.split(' ')
result = word2Num(word)
WriteFile(result) # writing in file
if "," in line: # Splitting String in Word by word
word = line.split(',')
result = word2Num(word)
WriteFile(result) # writing in file
|
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.append(nums2[i])
# i+=1
# return nums1
# print(merge([4,5,6],3,[1,2,8],3))
# def merge(nums1,m,nums2,n):
# nums1=nums1[:m]
# nums2=nums2[:n]
# if len(nums1)==0:
# return nums2
# if len(nums2)==0:
# return nums1
# else:
# i=0
# j=0
# while i<len(nums1) and j<n:
# if nums1[i]>=nums2[j]:
# nums1.insert(i,nums2[j])
# i+=1
# j+=1
# else:
# i+=1
# if j!=n and nums1[i-1]<nums2[j]:
# nums1=nums1+nums2[j:]
# return nums1
# print(merge([1,2,3,0,0,0],3,[2,5,6],3))
# if __name__=="__main__":
# testcases=[[1,2,3],[2,5,6],
# [2,3,8],[4,7,9],
# [1,2,5,6,8],[1,3,4,7,9],
# [1,2,5,6,8],[1,4,7],
# [1,2,5,6,8,10,13,16,17,19,21,23],[1,3,4,7,9,10,13,16,17,90,98,205],
# [1,2],[],
# [1,3,4,6,8]]
# for i in range(len(testcases)-1):
# print(merge(testcases[i],len(testcases[i]),testcases[i+1],len(testcases[i+1])))
def merge(nums1,m,nums2,n):
last =m+n-1
while m>0 and n>0:
if nums1[m-1]>nums2[n-1]:
nums1[last]=nums1[m-1]
m-=1
else:
nums1[last]=nums2[n-1]
n-=1
last-=1
while n>0:
nums1[last]=nums2[n-1]
n,last=n-1,last-1
return nums1
print(merge([1,2,3,0,0,0],3,[2,5,6],3))
|
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):
answer = (x + y + z) / 3
print(f"""
The sum of all three numbers
divided by three is {answer}.""")
function(1, 2, 3)'''
def function(x, y, z):
sum = (x + y + z)
print(f"The sum is {sum}.")
function(19, -8, 9)
function(15, 9, 8)
function(30, -29, 5)
|
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_rating(rating)
self.set_read(read)
def set_rating(self, value):
if 1.0 <= value <= 10.0:
self.rating = value
else:
print("Improper rating - rating set as default - 0\n Modify it if you want")
self.rating = 0
def set_read(self, value):
if value == "True" or value == True:
self.read = True
elif value == "False" or value == False:
self.read = False
else:
print("Improper read status - read status set as default - False \n Modify it if you want")
class BookBot:
def __init__(self):
self.shelf = []
# -----=------ Bot interaction functionalities -----=------
def introduce(self):
print("\nHi, Im bot Olivier - I will assist you. Pick what you want to do: ")
self.load_books()
self.help()
self.options()
def help(self):
print("\n Commands: ")
print("Add - Add new book")
print("List - List books from shelf")
print("Modify - Choose a book and change record")
print("View rating - filter shelf by books rating from defined scope")
print("View read - filter shelf by read books")
print("Save - Save database to csv file")
print("Help - View available commands")
print("Exit - Say goodbye to Olivier")
def options(self):
text = input("\nWhat I need to do? ")
if text == "Add":
self.input_add_book()
elif text == "List":
self.list_books()
elif text == "Modify":
self.pick_book_change()
elif text == "View rating":
self.filter_rating()
elif text == "View read":
self.filter_read()
elif text == "Save":
self.save_books()
elif text == "Help":
self.help()
self.options()
elif text == "Exit":
exit()
else:
self.repeat()
def repeat(self):
print("Unrecognised operation, try again")
self.options()
# -----=------ Adding items to list -----=------
def add_book(self, title, authors, rating, read):
b = Book(title, authors, rating, read) # create object Book
self.shelf.append(b) # add to list
# def insert_book(self):
# self.add_book("Pan Tadeusz", "Adam Mickiewicz", 1, False)
# self.add_book("Splatana Siec", "Michal Zalewski", 10, True)
def input_add_book(self):
title = input("Title: ")
author = input("Author: ")
rating = float(input("Rating: "))
read = input("Read? ")
self.add_book(title, author, rating, read)
print("--------------------------")
self.options()
# -----=------ Modify items in list -----=------
def pick_book_change(self):
print("\nPick up book what you want to change!")
index = int(input("Index: "))
try:
book = self.shelf[index - 1]
except IndexError:
print("You overlapped index in shelf - try again with proper index.")
self.options()
else:
self.change_record(book)
def change_record(self, book):
choice = input("\nWhat do you want to change? ")
if choice == "Title":
book.title = input("Insert new title: ")
elif choice == "Author":
book.authors = input("Insert new author: ")
elif choice == "Rating":
book.set_rating(float(input("Insert new rating: ")))
elif choice == "Read":
book.set_read(input("Insert new read status True/False: "))
else:
print("Unknown value - try again")
print("--------------------------")
self.options()
# -----=------ Print books -----=------
def print_book(self, index):
book = self.shelf[index]
print("{:4} | {:30} | {:30} | {:5} | {:5}".format(index, book.title, book.authors, book.rating, book.read))
def list_books(self):
print("\n--------------------------")
for index in range(len(self.shelf)):
self.print_book(index)
print("--------------------------")
self.options()
def print_all_read_book(self, choice):
print("\n--------------------------")
for i in range(len(self.shelf)):
book = self.shelf[i]
if choice == 1:
if book.read:
self.print_book(i)
else:
if not book.read:
self.print_book(i)
print("--------------------------")
def print_all_rating_books(self, min, max):
print("\n--------------------------")
for i in range(len(self.shelf)):
book = self.shelf[i]
if min <= book.rating <= max:
self.print_book(i)
print("--------------------------")
# -----=------ Filtering options -----=------
def filter_rating(self):
print("Rating value scope - 1.0 - 10.0 \nUnset value - 0")
min = float(input("Min rating value: "))
max = float(input("Max rating value: "))
if min >= 1.0 and max <= 10.0:
self.print_all_rating_books(min, max)
self.options()
else:
print("Improper rating value - try again")
self.options()
def filter_read(self):
print("Sort by: \n read - 1 \n unread - 0")
choice = int(input("\n Choose (1 or 0): "))
if 0 >= choice or choice <= 1:
self.print_all_read_book(choice)
self.options()
else:
print("Improper read value - try again")
self.options()
# -----=------ Load/Save items in list (file) -----=------
def save_books(self):
text_holder = []
for i in range(len(self.shelf)):
book = self.shelf[i]
text = "{};{};{};{}".format(book.title, book.authors, book.rating, book.read)
text_holder.append(text)
with open('books.csv', 'w') as f:
for line in text_holder:
f.write(line + '\n')
self.options()
def load_books(self):
if os.path.isfile('./books.csv'):
with open('books.csv', 'r') as f:
for line in f:
book_list = line.split(';')
if book_list[3] == 'True\n':
read = True
else:
read = False
self.add_book(book_list[0], book_list[1], float(book_list[2]), read)
print("\nDatabase loaded!\n")
bot = BookBot()
bot.introduce()
|
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 argparse
import sys
import re
import datetime
# Every time I use this package I think of Monty Python's Argument Clinic
# Will you have the 5 minute argument, the 15 minute argument, or the 30 minute special argument?
parser=argparse.ArgumentParser()
parser.add_argument("-f", help="List of Motion Tracker .csv files to parse")
parser.add_argument("-o", default="", help="Output table of individual delimited data")
parser.add_argument("-t", default="", help="Output table of time delimited data")
parser.add_argument("-b", default="", help="Output the BIG table of minute delimited data")
parser.add_argument("-test", default=0, help="Should I only do the first 100 as a test")
parser.add_argument("-s", default=24*3600, help="Max number of seconds between intervals")
args = parser.parse_args()
csvs = list()
big=0
test = int(args.test)
if (test):
print "Test mode active, will only output first 100 records"
if (args.b != ""):
print "Will output the BIG TABLE, this takes increase memory and runtime"
big = 1
# Open up all the files
try:
filelistfile = open(args.f, "r")
if (args.t != ""):
timeout = open(args.t, "w")
if (args.o != ""):
indout = open(args.o, "w")
except IOError as e:
print "Could not open specified files:"
print "I/O error({0}): {1}".format(e.errno, e.strerror)
sys.exit(0)
# This may be redundant but eh
for k in filelistfile:
csvs.append(k.strip())
def timeStringParse(timestring):
"""
The goal of this function is to parse the time strings from a line in the csv file.
It will return a list with the following information:
[Year, Month, Day, Hours, Minutes, Seconds], TimeZone, TimeZoneHours, TimeZone+-
"""
regexphell = re.match(r'(\d+)-(\d\d)-(\d\d)T(\d\d):(\d\d):(\d\d)([-+])(\d\d):(00)', timestring)
if (not regexphell):
return(None)
year = int(regexphell.group(1))
if (len(str(year)) < 4): # its the Y2K problem all over again!
year = year + 2000
month= int(regexphell.group(2))
day = int(regexphell.group(3))
hours = int(regexphell.group(4))
minutes = int(regexphell.group(5))
seconds = int(regexphell.group(6))
thistime = datetime.datetime(year, month, day, hours, minutes, seconds)
tz = regexphell.group(7) + regexphell.group(8)
tzh = int(regexphell.group(8))
tzpm = regexphell.group(7)
return([thistime, tz, tzh, tzpm])
## Need a function to discretize the data by minute, and return that information
## Rounds a datetime to a specific minute
## Going to take the 'closest' activity for each minute in the data
def roundTime(dt=None, roundTo=60):
"""Round a datetime object to any time laps in seconds
dt : datetime.datetime object, default now.
roundTo : Closest number of seconds to round to, default 1 minute.
Author: Thierry Husson 2012 - Use it as you want but don't blame me.
From: http://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python
"""
if dt == None : dt = datetime.datetime.now()
seconds = (dt - dt.min).seconds
# // is a floor division, not a comment on following line:
rounding = (seconds+roundTo/2) // roundTo * roundTo
return dt + datetime.timedelta(0,rounding-seconds,-dt.microsecond)
def buildTimeSeries(timesort, thistimes):
"""
Function that takes a sorted list of times
rounds everything to the nearest minute, and then
it will assign the most common 'activity' to that minute
"""
timehash = dict()
for t in range(0,len(timesort)):
## Remove the out of range times
if (timesort[t] < datetime.datetime(2015, 3,1,1,1,1)): # If the year isn't in 2015, something went wrong
continue
time_round = roundTime(timesort[t])
## Next, get the current activity
thisact = thistimes[timesort[t]][0]
if time_round in timehash and thisact != 0:
timehash[time_round].append(thisact)
else:
timehash[time_round] = [thisact]
return(timehash)
def most_common(lst):
return max(set(lst), key=lst.count)
# Now lets import and parse the individual data
# Grab for individuals: total time in each activity type, total time with high confidence, time total, time unknown
# Let's make this a list of lists for each individual
indList = list()
allrecords = dict()
all_times = set()
# This is a summary of the number of people doing a specific activity at any given
# minutes throughout the day. It will be indexed by the 'minute' and return a
# vector containing the number of individuals walking, stationary, etc.
# The vector will be as follows:
# [ missing, act1, act2, act3, act4, act5, total_nonMissing, total]
time_summary = dict()
all_inds = dict()
## Let's loop through each individuals data
i = 0
for c in csvs:
#print c
## Make sure this is set to the correct REGEX
recordmatch = re.search(r'(.+).tsv$', c)
# recordmatch = re.search(r'/(.+)\.data.csv$', c)
#print recordmatch
recordID = recordmatch.group(1)
thisfile = open(c, "r")
if (i % 100 == 0):
print "Analyzing record number: " + str(i) + " out of " + str(len(csvs))
i +=1
if (test == 1 and i > 100):
break
# Initialize data, we will record times in seconds for ease:
# first element is ID, second through sixth will be times in each activity, 7th: high conf time, 8: total time, 9: unknown time
thisrecord = [recordID, 0, 0,0,0,0, 0, 0, 0, "", ""]
head = thisfile.readline()
thistimes = dict()
for line in thisfile:
splits = line.strip().split("\t")
if not line.startswith("2015"):
continue
# Some lines were weird and contained only a 0, so skip those
if len(splits) < 5:
continue
# Ok now for the fun part
# We can't assume that the data is in order, so we will need to devise some way to order the data.
# Can sort the date using the built-in datetime functions
#print splits[0]
timeparse = timeStringParse(splits[0])
if (timeparse==None):
continue
# Only keep high and medium confidence intervals:
if (splits[3]!="low"):
activity = int(splits[2])
else:
activity = 0
thistimes[timeparse[0]] = [activity, timeparse[1], timeparse[2], timeparse[3]]
## Ok we have read the entire file at this point, and saved data into the thistimes dictionary
## Now, we need to sort by time, get the time deltas, and add that to the summary:
timesort = sorted(thistimes.keys())
if (len(timesort) < 2):
continue
#print(max(timesort))
thisrecord[9] = max(timesort)
#print(min(timesort))
thisrecord[10] = min(timesort)
# This is going to lop off the last timepoint, but whatever?
for t in range(0,len(timesort)-1):
## I am debating hard-coding 2015 as the year, but we will see...
if (timesort[t] < datetime.datetime(2015, 1,1,1,1,1)): # If the year isn't in 2015, something went wrong
continue
## Thisact = the activity number associated with the current entry
thisact = thistimes[timesort[t]][0]
second_diff = (timesort[t+1] - timesort[t]).total_seconds()
# This gets the total number of seconds that this activity is performed at
# If it is longer then this time, I don't believe it:
if (second_diff > int(args.s)):
continue
if thisact != 0: # If not unknown, add to summary counts
thisrecord[thisact] += second_diff # This gets the seconds
thisrecord[6] += second_diff
thisrecord[7] += second_diff
else:
thisrecord[7] += second_diff
thisrecord[8] += second_diff
## Add this record to the dictionary containing all the data for output
allrecords[thisrecord[0]] = thisrecord
## Now lets build the time series data:
thistimehash = buildTimeSeries(timesort, thistimes)
if (big == 1):
all_inds[thisrecord[0]] = thistimehash
for th in thistimehash.keys():
all_times.add(th)
if th in time_summary:
## Find the common activity for the individual at this minute:
thisact = most_common(thistimehash[th])
## Increment the proper list indexes in the time summary hash
time_summary[th][thisact] += 1
time_summary[th][7] += 1
if thisact != 0:
time_summary[th][6] += 1
else:
# If not in the time summary hash, add it to the hash and do the same procedure
thisact = most_common(thistimehash[th])
time_summary[th] = [0]*8
time_summary[th][thisact] += 1
time_summary[th][7] += 1
if thisact != 0:
time_summary[th][6] += 1
### Write output to file
print "Writing Individual Summary data..."
indout.write("\t".join(["healthCode", "SecStationary", "SecWalking", "SecRunning", "SecAutomotive",
"SecCycling", "SecTotal", "SecTotUnk", "SecUnk", "MaxTime", "MinTime"]) + "\n")
for r in allrecords.keys():
indout.write("\t".join(map(str, allrecords[r])) + "\n")
## Write time series data to file
timeout.write("\t".join(["timeID", "Year", "Month", "Day", "Hour", "Minute", "NumUnk", "NumStationary", "NumWalking", "NumRunning", "NumAutomotive", "NumCycling", "NumTotal", "NumTotalUnk"]) + "\n")
times = time_summary.keys()
times.sort()
lastq = times[1]
print "Writing time summary data..."
for q in times:
while ( (q - lastq).total_seconds() > 61 ):
new_time = lastq + datetime.timedelta(seconds=60)
time_list = [new_time.year, new_time.month, new_time.day, new_time.hour, new_time.minute]
timeout.write(str(new_time) + "\t" + "\t".join(map(str, time_list)) + "\t" + "\t".join(["NA"]*8) + "\n")
lastq=new_time
time_list = [q.year, q.month, q.day, q.hour, q.minute]
timeout.write(str(q) + "\t" + "\t".join(map(str, time_list)) + "\t" + "\t".join(map(str, time_summary[q])) + "\n")
lastq = q
# Profit
# Quit if we aren't outputting the big table
if (big != 1):
sys.exit()
## Ok, now we need to output the table
big_table = open(args.b, "w")
# Loop through all the possible times:
timelist = list(all_times)
timelist.sort()
## What is the header line for this file?
big_header = ["timeID", "Year", "Month", "Day", "Hour", "Minute"]
inds_in_order = list()
for thisperson in all_inds.keys():
big_header.append(thisperson)
inds_in_order.append(thisperson)
print "Writing the big table..."
# Write header row
big_table.write("\t".join(map(str, big_header)) + "\n")
# Each subsequent row represents a time
for t in timelist:
# For each time:
bigLineOut = [t, t.year, t.month, t.day, t.hour, t.minute]
for happyperson in inds_in_order:
# For each individual:
# Also don't worry about my new variable names
if t in all_inds[happyperson]:
bigLineOut.append(most_common(all_inds[happyperson][t]))
# Does this time exist in hash?
# Yes: write activity at this time
# No: write NA
else:
bigLineOut.append("NA")
big_table.write("\t".join(map(str,bigLineOut)) + "\n")
|
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 = headB
while headA is not None:
headA = headA.next
lenA +=1
while headB is not None:
headB = headB.next
lenB +=1
while lenA > lenB:
pointerA = pointerA.next
lenA -=1
while lenB > lenA:
pointerB = pointerB.next
lenB -=1
while pointerA != None:
if pointerA == pointerB:
return pointerA
else:
pointerA = pointerA.next
pointerB = pointerB.next
return None
#Time complexity is O(n) and space complexity is O(1)
#Aligning the position of the two pointers at the same distance from end and incrementing them until they either hit intersection or null |
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.
title : str
A string describing the processing step.
"""
def __init__(self, title: str, value: Union[int, float]):
"""
Initialiser for FlowElement class.
Parameters
----------
title : str
A string describing the processing step.
value : Union[int, float]
The value of the data after the processing step.
"""
self.value = value
self.title = title
def __str__(self):
return str({self.title, self.value})
def __repr__(self):
return self.__str__()
class Flow:
"""
A class to represent the full flow of our process to
be visualised.
...
Attributes
----------
title : str
The title of the process flow plot.
initial_val : Union[int, float]
The starting length of the dataset before any
of the process flow steps have taken place.
steps : List[FlowElement], optional
The data processing steps, by default [].
Methods
-------
add_step(title, value)
Adds a data processing step.
plot(font_size=18)
Creates a funnel plot of the data processing flow using plotly.
"""
def __init__(self, title: str, initial_val: Union[int, float]):
"""
Initialiser for Flow class.
Parameters
----------
title : str
The title of the process flow plot.
initial_val : Union[int, float]
The starting length of the dataset before any
of the process flow steps have taken place.
steps : List[FlowElement], optional
The data processing steps, by default [].
"""
self.title = title
self.initial_val = initial_val
self.steps = []
self.fig = None
def add_step(self, title: str, value: Union[int, float]):
"""
Add a step to the process flow.
Parameters
----------
title : str
The title of the process step.
value : Union[int, float]
The length of the data after the process step.
"""
el = FlowElement(title, value)
self.steps.append(el)
def __str__(self):
return (
f"Title: '{self.title}'\n"
f"Initial value: '{self.initial_val}'\n"
f"Elements: {self.steps}")
def __repr__(self):
return self.__str__()
def plot(self,
font_size: int = 18,
figure_kwargs = {},
funnel_kwargs = {},
update_layout_kwargs = {}):
"""
Plots a funnel graph depicting the process flow.
Parameters
----------
font_size : int, optional
The font size for the plots, by default 18
figure_kwargs : dict, optional
The keyword-arguments passed to go.Figure(), by default {}
funnel_kwargs : dict, optional
The keyword-arguments passed to go.Funnel(), by default {}
update_layout_kwargs : dict, optional
The keyword-arguments passed to the update_layout call, by default {}
Returns
-------
go.Figure
Figure showing the flow of data processing steps.
"""
self.fig = Figure(
Funnel(
name = self.title,
orientation = "h",
y = ["Start "] + [f"{el.title} " for el in self.steps],
x = [self.initial_val] + [el.value for el in self.steps],
textposition = "inside",
texttemplate = "n = %{x}",
**funnel_kwargs,
),
**figure_kwargs,
)
self.fig.update_layout(
title = self.title,
font=dict(
size=font_size,
),
**update_layout_kwargs,
)
return self.fig |
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(boostDeMoral)
# getters
def getNom(self):
return self.nom
def getPrenom(self):
return self.prenom
def getAge(self):
return self.age
def getProfession(self):
return self.profession
def getBoostDeMoral(self):
return self.boostDeMoral
# setters
def setNom(self, nouveauNom):
self.nom = nouveauNom
def setPrenom(self, nouveauPrenom):
self.prenom = nouveauPrenom
def setAge(self, nouvelAge):
self.age = nouvelAge
def setProfession(self, nouvelleProfession):
self.profession = nouvelleProfession
def setBoostDeMoral(self, nouveauBoostDeMoral):
self.boostDeMoral = nouveauBoostDeMoral
# surcharge de __repr__() -> déscription de l'objet
def __repr__(self):
return self.getPrenom() + " " + self.getNom() + ", age: " + str(
self.getAge()) + ", profession: " + self.getProfession() + ", boost de moral: " + str(
self.getBoostDeMoral())
|
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 class holds the X and Y coordinates.
"""
def __init__(self, x, y):
"""
:param x: X coordinate
:param y: Y coordinate
"""
self._x = x
self._y = y
def getX(self):
"""
:return: X coordinate
"""
return self._x
def getY(self):
"""
:return: Y coordinate
"""
return self._y
class Line(Point):
"""
Line class represents a line connecting two points
_point_1 and _point_2.
"""
def __init__(self, point1, point2):
"""
:param point1: Represent _point_1
:param point2: Represent _point_2
"""
self._point_1 = point1
self._point_2 = point2
def getSlope(self):
"""
slope = (Y2 - Y1/X2- X1
Returns: slope
"""
slope = ((self._point_1.getY() - self._point_2.getY()) / (self._point_1.getX() - self._point_2.getX()))
return slope
def getPoint1(self):
"""
:return: _point_1
"""
return self._point_1
def getPoint2(self):
"""
:return: _point_2
"""
return self._point_2
class ColinearPoints(object):
"""
Class to calculate the co-linear points from a list of points.
"""
def __init__(self, points):
"""
:param points: A list of Point objects in a 2D plane.
"""
self._points = points
self._global_slope_points = {}
self._colinear_points = []
def calculateSlopesOfPoints(self):
"""
Calculate the slope of points.
"""
for index, this_point in enumerate(self._points):
local_slopes = {}
for that_point in self._points[index+1:]:
line = Line(this_point, that_point)
slope = round(line.getSlope(), 2)
# if the slope already exist, then append to it, else add to it.
if slope not in local_slopes:
local_slopes[slope] = set()
local_slopes[slope].add(line.getPoint1())
local_slopes[slope].add(line.getPoint2())
for key in local_slopes.keys():
if key in self._global_slope_points:
# Check if there is an intersection.
if self._global_slope_points[key] & local_slopes[key]:
self._global_slope_points[key] = self._global_slope_points[key]|local_slopes[key]
else:
self._global_slope_points[key] = local_slopes[key]
def getColinearPoints(self):
"""
:return: co-linear points as a list.
"""
for key in self._global_slope_points.keys():
if len(self._global_slope_points[key]) > 2:
self._colinear_points.append(self._global_slope_points[key])
return self._colinear_points
def read_input_file(file):
"""
Read inputs from a file.
:param file: input file name.
:return: Points in a 2D plane as a list.
"""
points = []
try:
f = open(file)
for line in f.readlines():
# Remove the "\n" from the end.
# Split them at ","
coords = line.strip("\n").split(",")
# if more than two inputs on the same line, take the first 2 and ignore the rest.
if len(coords) > 2:
coords = coords[:2]
if len(coords) != 2:
# not enough inputs to proceed, ignore this line.
continue
if type(coords[0]) is not float or type(coords[1]) is not float:
# convert to float, if possible
try:
coords = [float(entry) for entry in coords]
except ValueError:
continue
# convert the inputs to an immutable format and add to the points list.
point = Point(coords[0], coords[1])
points.append(point)
except Exception as e:
# Unable to open or read the file, exit the program.
print(e)
exit(1)
return points
def write_output_file(points, file):
"""
Write to an output file.
:param points: List of sets. Each set is a collection of co-linear Points.
:param file: output file.
"""
try:
f = open(file, "w")
for index, point in enumerate(points):
local_s = []
for t in point:
local_s.append(t.getX())
local_s.append(t.getY())
s = str(index + 1) + "," + ",".join(str(x) for x in local_s)
f.write(s)
f.write("\n")
except Exception as e:
# Unable to open or write to a file, exit the program.
print(e)
exit(1)
if __name__ == "__main__":
input_file_name = "./test_example.csv"
output_file_name = "./test_output.csv"
colinear_points = []
# open the csv file and read the content.
# read each line as a tuple.
# add all the tuples to a list for further processing.
points = read_input_file(input_file_name)
# Not enough inputs from the file, stop the program.
# we need at least 3 points to run the solution.
if len(points) < 3:
exit(0)
# Find the co-linear points by using
# a list of points in a 2D plane.
obj = ColinearPoints(points)
obj.calculateSlopesOfPoints()
colinear_points = obj.getColinearPoints()
# Write to an output file with all colinear points in a single line.
write_output_file(colinear_points, output_file_name) |
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_name property"""
return self._first_name
@property
def last_name(self):
"""last_name property"""
return self._last_name
class User():
"""Model a user"""
def __init__(self, person, user_name, user_password, user_email):
"""Initialize first_name and last_name attributes."""
self.person = person
self.user_name = user_name
self.user_password = user_password
self.user_email = user_email
self.login_attemps = 0
def describe_user(self):
"""Describes user."""
print('First name:'.ljust(12) + self.person.first_name.title())
print('Last name:'.ljust(12) + self.person.last_name.title())
print('Username:'.ljust(12) + self.user_name)
print('Email:'.ljust(12) + self.user_email)
def greet_user(self):
"""Greeting user."""
print("\nHello " + self.user_name)
def increment_login_attempts(self):
"""Increment the number of login attempts by 1."""
self.login_attemps += 1
def reset_login_attempts(self):
"""Reset the login attempts counter to 0."""
self.login_attemps = 0
person_one = Person('humberto', 'perdomo')
user_one = User(person_one, 'hperdomo', '!Q2w3e4r', 'humberto.perdomo@gmail.com')
user_one.greet_user()
print("Number of login attempts till now: " + str(user_one.login_attemps))
user_one.increment_login_attempts()
user_one.increment_login_attempts()
user_one.increment_login_attempts()
user_one.increment_login_attempts()
print("Number of login attempts till now: " + str(user_one.login_attemps))
user_one.reset_login_attempts()
print("Number of login attempts till now: " + str(user_one.login_attemps))
|
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_name property"""
return self._first_name
@property
def last_name(self):
"""last_name property"""
return self._last_name
class User():
"""Model a user"""
def __init__(self, person, user_name, user_password, user_email):
"""Initialize first_name and last_name attributes."""
self.person = person
self.user_name = user_name
self.user_password = user_password
self.user_email = user_email
def describe_user(self):
"""Describes user."""
print('First name:'.ljust(12) + self.person.first_name.title())
print('Last name:'.ljust(12) + self.person.last_name.title())
print('Username:'.ljust(12) + self.user_name)
print('Email:'.ljust(12) + self.user_email)
def greet_user(self):
"""Greeting user."""
print("\nHello " + self.user_name)
#person_one = Person('humberto', 'perdomo')
#user_one = User(person_one, 'hperdomo', '!Q2w3e4r', 'humberto.perdomo@gmail.com')
#user_one.greet_user()
#user_one.describe_user()
#person_two = Person('jose', 'perez')
#user_two = User(person_two, 'jperez', 'password', 'jperez@mail.com')
#user_two.greet_user()
#user_two.describe_user()
|
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:
print("You really like blueberry!")
if 'watermelon' in favorite_fruits:
print("You really like watermelon!")
|
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 = math.radians(i)
turtle.setpos(x + r * math.cos(a), y + r * math.sin(a))
draw_circle_turtle(100, 100, 50)
turtle.mainloop()
|
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(answer + '\n')
|
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 " + new_user + " is available.")
|
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))
for privilege in self.privileges:
print(privilege.ljust(17))
#person = Person('humberto', 'perdomo')
#privileges = Privileges(["can add post", "can delete post", "can be user"])
#admin = Administrator(person, 'hperdomo', '!Q2w3e4r', 'humberto.perdomo@gmail.com', privileges)
#admin.greet_user()
#admin.show_privileges()
|
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.append('hawaiian')
print("My favorite pizzas are: ")
for pizza in my_pizzas:
print(pizza)
print("\nMy friend's favorite pizzas are:")
for pizza in friend_pizzas:
print(pizza)
|
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_type = cuisine_type
self.number_served = 0
def describe_restaurat(self):
"""Describes restaurant using both attributes."""
print(self.restaurant_name.title() + " is a restaurant of " +
self.cuisine_type + " food.")
def open_restaurant(self):
"""Simulates that restaurant is open."""
print(self.restaurant_name.title() + " is open.")
def set_number_served(self, number_served):
"""Set the number of customers served."""
self.number_served = number_served
def increment_number_served(self, served):
"""Increment the customers served using served amount."""
self.number_served += served
RESTAURANT = Restaurant("alessandro's", 'italian')
print("Restaurant name: " + RESTAURANT.restaurant_name.title() + ".")
print("Cuisine type: " + RESTAURANT.cuisine_type + ".")
RESTAURANT.describe_restaurat()
RESTAURANT.open_restaurant()
print("Customer the restaurant has served: " + str(RESTAURANT.number_served))
RESTAURANT.set_number_served(7)
print("Customer the restaurant has served: " + str(RESTAURANT.number_served))
RESTAURANT.increment_number_served(5)
print("Customer the restaurant has served: " + str(RESTAURANT.number_served))
|
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, max_value)
return a
def check_arr_increase(a):
b = a.copy()
b.sort()
return b == a
|
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)
l = [0] * m
i_max = 0
min = a[0]
for i in range(1, n):
if a[i] > a[i_max]:
i_max = i
elif a[i] < min:
min = a[i]
if a[i_max] == min:
return
c = (m - 1) / (a[i_max] - min)
for i in range(n):
k = int((a[i] - min) * c)
l[k] += 1
for i in range(1, m):
l[i] += l[i-1]
a[i_max], a[0] = a[0], a[i_max]
count = 0
k = m - 1
j = 0
while count < n - 1:
while j > (l[k] - 1):
j += 1
k = int((a[j] - min) * c)
hold = a[j]
while j != l[k]:
k = int((hold - min) * c)
l[k] -= 1
tmp = a[l[k]]
a[l[k]] = hold
hold = tmp
count += 1
insertion_sort(a)
def heapify(a, n, i):
tmp = a[i]
while True:
left = 2 * i + 1
right = 2 * i + 2
largest = i
max_value = tmp
if left < n and a[left] > max_value:
largest = left
max_value = a[left]
if right < n and a[right] > max_value:
largest = right
max_value = a[right]
if i != largest:
a[i] = max_value
i = largest
else:
a[i] = tmp
break
def heap_sort(a):
n = len(a)
for i in range(n // 2 -1, -1, -1):
heapify(a, n, i)
for i in range(n - 1, 0, -1):
a[i], a[0] = a[0], a[i]
heapify(a, i, 0)
return a
def quick_sort(a):
left = 0
right = len(a) - 1
qsort(a, left, right)
def qsort(a, left, right):
if left >= right:
return
key = a[(left + right) // 2]
i = left
j = right
while i <= j:
while a[i] < key:
i += 1
while a[j] > key:
j -= 1
if i <= j:
a[i], a[j] = a[j], a[i]
i += 1
j -= 1
qsort(a, left, j)
qsort(a, i, right)
def merge_sort(a):
return msort(a, 0, len(a) - 1)
def msort(a, left, right):
if left >= right:
return
mid = (right + left) // 2
msort(a, left, mid)
msort(a, mid + 1, right)
tmp = [0] * (right - left + 1)
l1 = left
r1 = mid
l2 = mid + 1
r2 = right
i = l1
j = l2
p = 0
while i <= r1 and j <= r2:
if a[i] < a[j]:
tmp[p] = a[i]
i += 1
else:
tmp[p] = a[j]
j += 1
p += 1
while i <= r1:
tmp[p] = a[i]
i += 1
p += 1
while j <= r2:
tmp[p] = a[j]
j += 1
p += 1
for i in range(0, right - left+ 1):
a[i + left] = tmp[i]
|
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")
print("\n") |
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:
print("请输入整数!")
except Exception as e:
print(e)
else:
print("利润值为%d万元,开始计算提成:" %profit)
#定义利润区间
profit_area=[0,10,20,40,60,100]
#定义提成系数
commision_num=[0.1,0.075,0.05,0.03,0.015,0.01]
|
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:
permutation = False
iteración = iteración + 1
for actual in range(0, len(vector) - iteración):
if vector[actual] > vector[actual + 1]:
permutation = True
# Intercambiamos los dos elementos
vector[actual], vector[actual + 1] = vector[actual + 1],vector[actual]
return vector
bubble_sort(vector)
print ("vector desordenado")
print(vector)
def test():
start = time.clock()
bubble_sort(vector)
elapsed = (time.clock() - start)
print("Tiempo esperado para Bubble_Sort = ", elapsed)
if __name__ == '__main__':
import time
test()
|
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 endpoints). Using only the randint function, implement your own version of the shuffle function.
"""
import random
array = [1,2,3,5,6,7,8,9,0]
# random.shuffle(array)
# print(array)
def everyday_shuffling(arr):
for n in range(len(arr)):
random_index = random.randint(0, n)
tmp = arr[random_index]
arr[random_index] = arr[n]
arr[n] = tmp
return arr
print(len(array))
everyday_shuffling(array)
print(array)
print(len(array))
|
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 possible, then, that our implementation of scale
changes the actual parameter sent by the caller?
"""
#the function which is at (page25)
def scale(data, factor):
#for j in range(len(data)):
# arr[j] *= factor
for k in data:
k *= factor
print k
return data
array = [1,2,3,4,5,6]
array2 = scale(array, 3)
print array
print array
|
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:
print("{} {}".format(row['first_name'], row['last_name']))
def add_name():
with open('users.csv', 'a') as file:
fieldnames = ['first_name', 'last_name']
writer = csv.DictWriter(file, fieldnames)
first = input("First name please: ")
last = input("Last name please: ")
writer.writerow(dict(first_name=first, last_name=last)) |
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 file:
# print(file.read())
# with open('first.txt', 'r+') as file:
# file.write("\nI'm at the beginning\n")
# file.seek(100)
# file.write("\nI'm in the middle\n")
# file.seek(0)
# print(file.read())
# with open('first.txt', 'a+') as file:
# file.write("\nI'm at the end\n")
# file.seek(0)
# print(file.read())
# with open('first.txt', 'w+') as file:
# file.write("Now everything is overwritten :(")
# file.seek(0)
# print(file.read())
# Working with File i/o with CSV And tsv
#import csv
# with open('file.csv') as csvfile:
# reader = csv.reader(csvfile, delimiter='|')
# rows = list(reader)
# for row in rows:
# print(', '.join(row))
# Using Dictionary to create row instead of a list
import csv
# with open('file.csv') as csvfile:
# reader = csv.DictReader(csvfile, delimiter='|')
# rows = list(reader)
# for row in rows:
# print(row)
# Writing in lists form using csv
# with open('file.csv', 'a') as csvfile:
# data_writer = csv.writer(csvfile, delimiter="|")
# data_writer.writerow(['Gab','Cattle','55'])
# # Reading in List form using csv
# with open('file.csv') as csvfile:
# reader = csv.reader(csvfile, delimiter='|')
# rows = list(reader)
# for row in rows:
# print(', '.join(row))
# # Writing in Dictionaries form using csv
# with open('newfile.csv', 'a') as csvfile:
# data = ['name', 'fav_topic']
# writer = csv.DictWriter(csvfile, fieldnames=data)
# writer.writeheader() # this writes the first row with the column headings
# writer.writerow({
# 'name': 'Elie',
# 'fav_topic': 'Writing to CSVs!'
# })
# def gensquares(n):
# for num in range(n):
# yield num**2
# for x in gensquares(10):
# print(x)
# def fib_with_generator(n):
# a = 1
# b = 1
# for i in range(n):
# yield a
# # a,b = b, a+b -> tuple unpacking instead of the three lines below!
# temp = a
# a = b
# b = temp + b
# for num in fib_with_generator(10):
# print(num)
# Using Next function
def use_next():
# for x in range(10):
# yield x
# # gen = use_next()
# # print(next(gen))
# # print(next(gen))
# # print(next(gen))
# for val in use_next():
# print(val)
# OR
return print((x for x in range(10)))
|
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
with open('euler8_num.txt') as f:
num = f.read()
f.close()
# break number into a big list
num = [int(i) for i in num if i != '\n']
# initialize our ans
ans = 0
# now search for the greatest product
for i in range(len(num)-3):
prod = num[i]*num[i+1]*num[i+2]*num[i+3]
if prod > ans:
ans = prod
print(ans)
t1 = time.time()
print("Execution: " + str(t1 - t0) + " seconds.") |
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 check all combinations
# until we come across our answer
t0 = time.time()
for a in range(1,1000+1):
for b in range(a,1000+1):
c = math.sqrt(a**2 + b**2)
# if c is not an integer forget it
if c != int(c):
continue
# now we check if we hit the special triplet
if a + b + c == 1000:
print(int(a*b*c))
break
t1 = time.time()
print("Execution time: " + str(t1 - t0) + " seconds.") |
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):
print(f"{self.name}\'s total: {self.salary.getTotal() + self.bonus}")
if __name__ == '__main__':
employee = Employee('Ben', 100, 10)
employee.annualSalary() |
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
@classmethod
def get_org(cls): return cls.org
@staticmethod
def class_info(): return "This is Emp Class"
def to_string(self): return dict(org = Emp.get_org(), sal = str(self.sal), name = self.name, no = str(self.no))
def __str__(self): return str(self.no)
def equals(self, e):
if self is None or e is None or self.no != e.no or self.name != e.name or self.sal != e.sal: return False
return True
print(Emp.class_info())
e1 = Emp()
e2 = Emp()
e1.set_no(101)
e1.set_name("Ram")
e1.set_sal(98765.43)
e2.set_no(101)
e2.set_name("Ram")
e2.set_sal(98765.43)
print(e1.to_string())
print(e2.to_string())
# e2 = None
if not e1.equals(e2):
print("e1 and e2 are not equal")
else:
print("e1 and e2 are equal")
print(e1, id(e1), hex(id(e1)))
print(e2, id(e2), hex(id(e2)))
e1 = None
e2 = None
print(id(e1))
print(id(e2))
print(e1)
class C:
def __init__(self):
self._x = None
@property
def x(self):
"""I'm the 'x' property."""
return self._x
@x.setter
def x(self, value):
self._x = value
@x.deleter
def x(self):
del self._x
|
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_list)
for _ in range(item_list_len):
print(item_iter.__next__())
item_iter = iter(item_list)
while True:
try:
item = next(item_iter)
print(item)
except StopIteration as e:
print("end of the list")
break
finally:
pass |
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 optimized.
\nAdded softmax
\nCreated on Mon Dec 10 13:30:30 2019
@author: N. Bijl, O. Erkemeij
"""
import numpy as np
import os
class NeuralNetwork:
"""
Class to generate a neural network.\n
inp: input neurons\n
out: output neurons\n
hid: hidden neurons(default=1)\n
lay: hidden_layers(default=1)\n
lr: learning_rate(default=0.1)\n
act: activation_function(default="sigmoid")
"""
def __init__(self, inp=784, out=10, hid=16, lay=3, lr=0.02, act="sigmoid", pathwb="./logwb"):
"""Method to create an instance of the neuralNetwork class."""
self.inputs = inp
self.outputs = out
self.hidden = hid
self.layers = lay
self.lr = lr
self.act = act
# set path to dir for log file
self.pathwb = os.path.join(pathwb, "wbi{}o{}h{}l{}l{}a{}".format(self.inputs, self.outputs, self.hidden, self.layers, self.lr, self.act))
# seed to generate the same random values every time.
np.random.seed(0)
# generate arrays with random weights
self.weights_ih = np.random.randn(self.hidden, self.inputs)
if(self.layers > 1):
self.weights_hh = np.random.randn((self.layers -1), self.hidden, self.hidden)
self.weights_ho = np.random.randn(self.outputs, self.hidden)
# generate arrays with random biases
self.bias_h = np.random.randn(self.layers, self.hidden)
self.bias_o = np.random.randn(self.outputs)
# set the desired activation function
if(self.act == "sigmoid" or self.act == "tanh"):
if(self.act == "sigmoid"):
# activation function of sigmoid
act_func = lambda x: 1 / (1 + np.exp(-x))
# derivative of sigmoid
act_d_func = lambda y: y * (1 - y)
elif(self.act == "tanh"):
# activation function of tanh
act_func = lambda x: np.tanh(x)
# derivative of tanh
act_d_func = lambda y: 1 - (y * y)
# vectors are made to use a function on a array
# make vector of activation function
self.act = np.vectorize(act_func)
# make vector of derivative of the activation function
self.act_d = np.vectorize(act_d_func)
else:
print("Warning, {} is not a known activation function".format(act))
return
def feedforward(self, inputs, isRound=False, isSoftmax=True):
"""
Method to feedforward an array of inputs to calculate the outputs.\n
inputs: a numpy array with the inputs.\n
isRound: a boolean function to convert the outputs to rounded values(default=False).
"""
# create an array to store the calculated hidden outputs
hidden = []
# calculate the output of the first hidden layer
# output: act(dot(weights, inputs) + bias)
# dot: the dot product of two matrices
hidden.append(np.dot(self.weights_ih, inputs))
hidden[0] += self.bias_h[0]
hidden[0] = self.act(hidden[0])
# calculate the output of the hidden layers if there is more than 1 hidden layer
# output: act(dot(weights, output of previous hidden layer) + bias)
if(self.layers > 1):
for i in range(self.layers -1):
i += 1
hidden.append(np.dot(self.weights_hh[i -1], hidden[i -1]))
hidden[i] += self.bias_h[i]
hidden[i] = self.act(hidden[i])
# calculate the output of the output layer
# output: act(dot(weights, output of last hidden layer) + bias)
outputs = np.dot(self.weights_ho, hidden[-1])
outputs += self.bias_o
outputs = self.act(outputs)
# round the outputs if desired
if(isSoftmax == True):
outputs = self.softmax(outputs)
if(isRound == True):
round_func = lambda r: round(r)
round_vect = np.vectorize(round_func)
outputs = round_vect(outputs)
return outputs
def softmax(self, outputs):
"""Method to return the normalized output."""
# output[i] / sum
sum = np.sum(outputs)
outputs = outputs/sum
return outputs
def train(self, inputs_arr, targets_arr, epochs=1, data=None):
"""
Method to train the neural network by adjusting the weights and biases.\n
inputs: a numpy array with the inputs.\n
targets: a numpy array with the targets that belong to the inputs.
"""
# assertion
assert data <= len(inputs_arr)
# bach is equel to the array length if it is not set
if(data == None):
data = len(inputs_arr)
# iterate for batch for e epochs
for e in range(epochs):
for d in range(data):
inputs = inputs_arr[d]
targets = targets_arr[d]
# calculate the output (see feedforward)
# feedforward is not used in this function because the outputs of the hidden layers are needed to calculate the new weights
hidden = []
hidden.append(np.dot(self.weights_ih, inputs))
hidden[0] += self.bias_h[0]
hidden[0] = self.act(hidden[0])
if(self.layers > 1):
for i in range(self.layers -1):
i += 1
hidden.append(np.dot(self.weights_hh[i -1], hidden[i -1]))
hidden[i] += self.bias_h[i]
hidden[i] = self.act(hidden[i])
outputs = np.dot(self.weights_ho, hidden[-1])
outputs += self.bias_o
outputs = self.act(outputs)
# backpropagation
# calculate error (output --> input)
output_error = targets - outputs
# transpose weights (output --> input)
# the weights are transposed because of the network going backwards
weights_hot = np.transpose(self.weights_ho)
weights_hht = []
for i in range(self.layers -1):
weights_hht.append(np.transpose(self.weights_hh[-i-1]))
# calculate the error of the hidden layers (output --> input)
hidden_error = []
hidden_error.append(np.dot(weights_hot, output_error))
for i in range(self.layers -1):
hidden_error.append(np.dot(weights_hht[i], hidden_error[i]))
# weights = weights + lr * error * derivative of act * outputs of the layers transposed
# calculate activation derivative (output --> input)
output_s = self.act_d(outputs)
hidden_s = []
for i in range(self.layers):
hidden_s.append(self.act_d(hidden[-i-1]))
# get transposed outputs of layers (output --> inputs)
hidden_t = []
for i in range(self.layers):
hidden_t.append(np.transpose(hidden[-i-1])[np.newaxis])
inputs_t = np.transpose(inputs)[np.newaxis]
# calculate the gradient (output-->input)
# gradient = error * derivative
outputs_g = output_error * output_s
hidden_g = []
for i in range(self.layers):
hidden_g.append(hidden_error[i] * hidden_s[i])
# reshape gradient (output-->input)
# reshape is needed for numpy to calculate the dot product
outputs_gr = np.reshape(outputs_g,(self.outputs,1))
hidden_gr = []
for i in range(self.layers):
hidden_gr.append(np.reshape(hidden_g[i],(self.hidden,1)))
# add delta weights to weights (output-->hidden)
# delta weights = dot(gradient, transposed outputs of previous layer)
# dot: dot product of two matrices
delta_weights_ho = np.dot(outputs_gr[0], hidden_t[0])
delta_weights_ho *= self.lr
self.weights_ho += delta_weights_ho
delta_weights_hh = []
if (self.layers > 1):
for i in range(self.layers -1):
delta_weights_hh.append((np.dot(hidden_gr[i], hidden_t[-i-1]) * self.lr))
self.weights_hh[-i-1] += delta_weights_hh[i]
delta_weights_ih = np.dot(hidden_gr[-1], inputs_t)
delta_weights_ih *= self.lr
self.weights_ih += delta_weights_ih
# add gradient to bias (ouput-->input)
self.bias_o += (outputs_g * self.lr)
for i in range(self.layers):
self.bias_h[-i-1] += (hidden_g[i] * self.lr)
# print num of done epochs
# print num of done data
print("data: {:5}/{}\t\t epochs: {:5}/{}".format(d+1, data, e+1, epochs), end="\r")
# print new line
print("")
def logwb(self):
"""Method to log the weights and biases."""
# check if the dir exists
if(not(os.path.exists(os.path.dirname(self.pathwb)))):
print(os.path.dirname(self.pathwb))
os.mkdir(os.path.dirname(self.pathwb))
# set file name and its path
filename_ih = "wih.txt"
path_wih = os.path.join(self.pathwb, filename_ih)
# make array with weights and biases for each layer
if (self.layers > 1):
path_whh = []
for i in range(self.layers -1):
path_whh.append(os.path.join(self.pathwb, "whh{}.txt".format(i)))
filename_ho = "who.txt"
path_who = os.path.join(self.pathwb, filename_ho)
path_bh = []
for i in range(self.layers):
path_bh.append(os.path.join(self.pathwb, "bh{}.txt".format(i)))
filename_bo = "bo.txt"
path_bo = os.path.join(self.pathwb, filename_bo)
if(not(os.path.exists(self.pathwb))):
os.mkdir(self.pathwb)
# create file for ih
with open(path_wih, 'w') as fo:
# add data tab spaced, end of line \n
for d in range(self.hidden):
for i in range(self.inputs):
fo.write("{}\t".format(self.weights_ih[d][i]))
# create newline
fo.write("\n")
# create file for hh
if(self.layers > 1):
for k in range(self.layers - 1):
with open(path_whh[k], 'w') as fo:
# add data tab spaced, end of line \n
for d in range(self.hidden):
for i in range(self.hidden):
fo.write("{}\t".format(self.weights_hh[k][d][i]))
# create newline
fo.write("\n")
# create file for ho
with open(path_who, 'w') as fo:
# add data tab spaced, end of line \n
for d in range(self.outputs):
for i in range(self.hidden):
fo.write("{}\t".format(self.weights_ho[d][i]))
# create newline
fo.write("\n")
# same for biases
for i in range(self.layers):
with open(path_bh[i], 'w') as fo:
# add data tab spaced, end of line \n
for j in range(self.hidden):
fo.write("{}\t".format(self.bias_h[i][j]))
# create newline
fo.write("\n")
with open(path_bo, 'w') as fo:
# add data tab spaced, end of line \n
for i in range(self.outputs):
fo.write("{}\t".format(self.bias_o[i]))
# create newline
fo.write("\n")
def loadwb(self):
"""Method to load loged weights and biases"""
wih = np.loadtxt(os.path.join(self.pathwb, "wih.txt"))
# create array to store weights and biases and load the weights and biases
if(self.layers > 1):
# create np array
whh = np.zeros((self.layers -1, self.hidden, self.hidden))
for i in range(self.layers -1):
whh[i] = np.loadtxt(os.path.join(self.pathwb, "whh{}.txt".format(i))).reshape(16,16)
who = np.loadtxt(os.path.join(self.pathwb, "who.txt"))
bh = np.zeros((self.layers, self.hidden))
for i in range(self.layers):
bh[i] = np.loadtxt(os.path.join(self.pathwb, "bh{}.txt".format(i)))
bo = np.loadtxt(os.path.join(self.pathwb, "bo.txt"))
return wih, whh, who, bh, bo
def setwb(self):
# set the loaded weights and biases
self.weights_ih, self.weights_hh, self.weights_ho, self.bias_h, self.bias_o = self.loadwb()
|
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 (average >=59):
print("You got B")
else:
print("You failed! lol")
|
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
self.right_child = None
class BS_tree:
# declaring and initializing root variable
def __init__(self):
self.root = None
# inserting data into the nodes
def ins(self,data):
# creating a Node and if root is None assign node as root
if self.root == None:
self.root = Node(data)
else:
BS_tree.insert(self,data,self.root)
def insert(self,data,cur_node):
# if data is less-than the current node data assigned as left child
if data < cur_node.data:
# if current_node left child is None then assign the data
if cur_node.left_child == None:
cur_node.left_child = Node(data)
# else it calls recursively insert method to arrange nodes
else:
BS_tree.insert(self,data,cur_node.left_child)
# if data is greater-than the current node data assigned as right-child
elif data > cur_node.data:
# if current node right child is None, assigned node as right-child
if cur_node.right_child == None:
cur_node.right_child = Node(data)
# else it calls recursively insert method to arrange nodes
else:
BS_tree.insert(self,data,cur_node.right_child)
# else the value is duplicate, tree cant allow duplicate values
# print an error msg
else:
print("Duplicate values are not allowed ",data)
# Displaying the elements in the tree
def show(self):
# if root variable is not None then call the print program
if self.root != None:
BS_tree.print(self,self.root)
else:
print("None")
def print(self,cur_node):
# printing the tree values
if cur_node != None:
BS_tree.print(self,cur_node.left_child)
print(cur_node.data)
BS_tree.print(self,cur_node.right_child)
|
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 in that range
--------------------------------------------------------------------"""
from Fellowship_programs.DataStructurePrograms.Array2D import prime
print("range is 0 to 1000")
# creating object for array2D class
obj = prime()
# declare a iterator variable to count the loop iterations
itr = 0
# creating an empty list to store the prime numbers in the given range
list = []
for i in range(0,1000,100):
# calling the prime function to get the prime numbers
lis = obj.prime(i,i+100)
itr +=1
list.append(lis)
# printing the 2d prime number array
obj.Print(itr)
|
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
if not any(elem in password for elem in string.ascii_uppercase):
return False
if not any(elem in password for elem in PUNCTUATION_CHARS):
return False
if password in used_passwords:
return False
used_passwords.add(password)
return True
def validate_password_2(password):
if len(password) < 6 or len(password) > 12:
return False
if not re.search(r'[0-9]', password):
return False
if not re.search(r'[a-z]', password):
return False
if not re.search(r'[A-Z]', password):
return False
if not any(elem in password for elem in PUNCTUATION_CHARS):
return False
if password in used_passwords:
return False
used_passwords.add(password)
return True
validate_password("passWord9_") |
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**. We can add our own class attributes easily this way:
'''
# %%
class Program:
language = 'Python'
version = '3.6'
# %%
print(Program.__name__)
# %%
print(Program.language)
# %%
print(Program.version)
# %%
'''
Here we used "dotted notation" to access the class attributes. In fact we can also use dotted notation to set
the class attribute:
'''
# %%
Program.version = '3.7'
# %%
print(Program.version)
# %%
'''
But we can also use the functions `getattr` and `setattr` to read and write these attributes:
'''
# %%
print(getattr(Program, 'version'))
# %%
setattr(Program, 'version', '3.6')
# %%
print(Program.version, getattr(Program, 'version'))
# %%
'''
Python is a dynamic language, and we can create attributes at run-time, outside of the class definition itself:
'''
# %%
Program.x = 100
# %%
'''
Using dotted notation we added an attribute `x` to the Person class:
'''
# %%
print(Program.x, getattr(Program, 'x'))
# %%
'''
We could also just have used a `setattr` function call:
'''
# %%
setattr(Program, 'y', 200)
# %%
print(Program.y, getattr(Program, 'y'))
# %%
'''
So where is the state stored? Usually in a dictionary that is attached to the **class** object
(often referred to as the **namespace** of the class):
'''
# %%
print(Program.__dict__)
# %%
'''
As you can see that dictionary contains our attributes: `language`, `version`, `x`, `y` with their corresponding
current values.
'''
# %%
'''
Notice also that `Program.__dict__` does not return a dictionary, but a `mappingproxy` object - this is essentially
a read-only dictionary that we cannot modify directly (but we can modify it by using `setattr`, or dotted notation).
'''
# %%
'''
For example, if we change the value of an attribute:
'''
# %%
setattr(Program, 'x', -10)
# %%
'''
We'll see this reflected in the underlying dictionary:
'''
# %%
print(Program.__dict__)
# %%
'''
#### Deleting Attributes
'''
# %%
'''
So, we can create and mutate class attributes at run-time. Can we delete attributes too?
The answer of course is yes. We can either use the `del` keyword, or the `delattr` function:
'''
# %%
del Program.x
# %%
print(Program.__dict__)
# %%
delattr(Program, 'y')
# %%
'''
#### Direct Namespace Access
'''
# %%
print(Program.__dict__)
# %%
'''
Although `__dict__` returns a `mappingproxy` object, it still is a hash map and essentially behaves like a read-only
dictionary:
'''
# %%
print(Program.__dict__['language'])
# %%
print(list(Program.__dict__.items()))
# %%
'''
One word of caution: not every attribute that a class has lives in that dictionary (we'll come back to this later).
For example, you'll notice that the `__name__` attribute is not there:
'''
# %%
print(Program.__name__)
# %%
print(__name__ in Program.__dict__) |
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 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
'''
shakespeare_unformatted = """
To be, or not to be, that is the question:
Whether 'tis nobler in the mind to suffer
The slings and arrows of outrageous fortune,
Or to take Arms against a Sea of troubles,
"""
rosetti_unformatted = """
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
"""
def print_hanging_indents(poem):
# poem = poem.strip()
whitespace = " "
prefix = INDENTS*whitespace
current_line_cnt = 0
target_poem = []
for line in poem.splitlines():
# trim current line
current_line = line.lstrip()
# adjust counters
if line == "":
current_line_cnt = 0
continue
else:
current_line_cnt += 1
# check the line we're dealing with
if current_line_cnt == 0:
line_to_be_inserted = ""
elif current_line_cnt == 1:
line_to_be_inserted = current_line
elif current_line_cnt > 1:
line_to_be_inserted = prefix + current_line
target_poem.append(line_to_be_inserted)
result = '\n'.join(target_poem)
print(result)
print_hanging_indents(shakespeare_unformatted)
print_hanging_indents(rosetti_unformatted)
|
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 and notes
# # for a full explanation. The code from those lectures is displayed below:
# # Singly Linked List
# #
# c_ LinkedListNode o..
# ___ - value
#
# ? ?
# nextnode _ N..
#
# a = ? 1
# b = ? 2
# c = ? 3
#
# a.nextnode = b
# b.nextnode = c
#
# # Doubly Linked List
# #
# c_ DoublyLinkedListNode o..
#
# ___ - value
#
# ? ?
# next_node _ N..
# prev_node _ N..
#
# a = ? 1
# b = ? 2
# c = ? 3
#
# # Setting b after a
# b.prev_node = a
# a.next_node = b
#
# # Setting c after a
# b.next_node = c
# c.prev_node = b
#
# # Good Job! |
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 concatenated with B), where A and B are valid
strings, or
It can be written as (A), where A is a valid string.
Given a parentheses string, return the minimum number of parentheses we must add
to make the resulting string valid.
Example 1:
Input: "())"
Output: 1
Example 2:
Input: "((("
Output: 3
Example 3:
Input: "()"
Output: 0
Example 4:
Input: "()))(("
Output: 4
Note:
S.length <= 1000
S only consists of '(' and ')' characters.
"""
c_ Solution:
___ minAddToMakeValid S: s..) __ i..
"""
stk
"""
ret 0
stk # list
___ s __ S:
__ s __ "(":
stk.a..(s)
____
__ stk:
stk.p.. )
____
ret += 1
ret += l..(stk)
r.. ret
|
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 stubs throughout your test suite.
# After performing an action, you can make assertions about which methods / attributes were used and arguments they were called with.
# You can also specify return values and set needed attributes in the normal way.
#
# Additionally, mock provides a patch() decorator that handles patching module and class level attributes within the scope of a test, along with sentinel
# for creating unique objects.
#
# Mock is very easy to use and is designed for use with unittest. Mock is based on the �action -> assertion� pattern instead of �record -> replay� used by
# many mocking frameworks.
#
#
# Autospeccing:
#
# Autospeccing is based on the existing spec feature of mock. It limits the api of mocks to the api of an original object (the spec), but it is recursive
# (implemented lazily) so that attributes of mocks only have the same api as the attributes of the spec.
# In addition mocked functions / methods have the same call signature as the original so they raise a TypeError if they are called incorrectly.
# Mock is a very powerful and flexible object, but it suffers from two flaws when used to mock out objects from a system under test. One of these flaws is
# specific to the Mock api and the other is a more general problem with using mock objects.
#
#
# Mock has two assert methods that are extremely handy: assert_called_with() and assert_called_once_with().
#
mock = Mock(name='Thing', return_value=None)
mock(1, 2, 3)
mock.assert_called_once_with(1, 2, 3)
mock(1, 2, 3)
mock.assert_called_once_with(1, 2, 3)
#
# Because mocks auto-create attributes on demand, and allow you to call them with arbitrary arguments, if you misspell one of these assert methods then your
# assertion is gone:
#
mock = Mock(name='Thing', return_value=None)
mock(1, 2, 3)
mock.assret_called_once_with(4, 5, 6)
#
# Your tests can pass silently and incorrectly because of the typo.
# The second issue is more general to mocking. If you refactor some of your code, rename members and so on, any tests for code that is still using the old
# api but uses mocks instead of the real objects will still pass. This means your tests can all pass even though your code is broken.
#
#
# Note that this is another reason why you need integration tests as well as unit tests. Testing everything in isolation is all fine and dandy, but if you
# don�t test how your units are �wired together� there is still lots of room for bugs that tests might have caught.
# mock already provides a feature to help with this, called speccing. If you use a class or instance as the spec for a mock then you can only access
# attributes on the mock that exist on the real class:
#
from urllib import request
mock = Mock(spec=request.Request)
mock.assret_called_with
#
# The spec only applies to the mock itself, so we still have the same issue with any methods on the mock:
#
mock.has_data()
# OUTPUT: '<mock.Mock object at 0x...>'
mock.has_data.assret_called_with()
#
# Auto-speccing solves this problem. You can either pass autospec=True to patch() / patch.object() or use the create_autospec() function to create a mock
# with a spec. If you use the autospec=True argument to patch() then the object that is being replaced will be used as the spec object.
# Because the speccing is done �lazily� (the spec is created as attributes on the mock are accessed) you can use it with very complex or deeply nested
# objects (like modules that import modules that import modules) without a big performance hit.
#
#
# Here�s an example of it in use:
#
from urllib import request
patcher = patch('__main__.request', autospec=True)
mock_request = patcher.start()
request is mock_request
# OUTPUT: 'True'
mock_request.Request
# OUTPUT: '<MagicMock name='request.Request' spec='Request' id='...'>'
#
# You can see that request.Request has a spec. request.Request takes two arguments in the constructor (one of which is self).
#
#
# Here�s what happens if we try to call it incorrectly:
#
req = request.Request()
#
# The spec also applies to instantiated classes (i.e. the return value of specced mocks):
#
req = request.Request('foo')
req
# OUTPUT: '<NonCallableMagicMock name='request.Request()' spec='Request' id='...'>'
#
# Request objects are not callable, so the return value of instantiating our mocked out request.Request is a non-callable mock.
# With the spec in place any typos in our asserts will raise the correct error:
#
req.add_header('spam', 'eggs')
# OUTPUT: '<MagicMock name='request.Request().add_header()' id='...'>'
req.add_header.assret_called_with
req.add_header.assert_called_with('spam', 'eggs')
#
# In many cases you will just be able to add autospec=True to your existing patch() calls and then be protected against bugs due to typos and api changes.
#
#
# As well as using autospec through patch() there is a create_autospec() for creating autospecced mocks directly:
#
from urllib import request
mock_request = create_autospec(request)
mock_request.Request('foo', 'bar')
# OUTPUT: '<NonCallableMagicMock name='mock.Request()' spec='Request' id='...'>'
#
# This isn�t without caveats and limitations however, which is why it is not the default behaviour.
# In order to know what attributes are available on the spec object, autospec has to introspect (access attributes) the spec.
# As you traverse attributes on the mock a corresponding traversal of the original object is happening under the hood.
# If any of your specced objects have properties or descriptors that can trigger code execution then you may not be able to use autospec.
# On the other hand it is much better to design your objects so that introspection is safe.
#
#
# A more serious problem is that it is common for instance attributes to be created in the __init__() method and not to exist on the class at all.
# autospec can�t know about any dynamically created attributes and restricts the api to visible attributes.
#
class Something:
def __init__(self):
self.a = 33
with patch('__main__.Something', autospec=True):
thing = Something()
thing.a
#
# There are a few different ways of resolving this problem.
# The easiest, but not necessarily the least annoying, way is to simply set the required attributes on the mock after creation.
# Just because autospec doesn�t allow you to fetch attributes that don�t exist on the spec it doesn�t prevent you setting them:
#
with patch('__main__.Something', autospec=True):
thing = Something()
thing.a = 33
#
# There is a more aggressive version of both spec and autospec that does prevent you setting non-existent attributes.
# This is useful if you want to ensure your code only sets valid attributes too, but obviously it prevents this particular scenario:
#
with patch('__main__.Something', autospec=True, spec_set=True):
thing = Something()
thing.a = 33
#
# Probably the best way of solving the problem is to add class attributes as default values for instance members initialised in __init__().
# Note that if you are only setting default attributes in __init__() then providing them via class attributes (shared between instances of course) is faster
# too. e.g.
#
class Something:
a = 33
#
# This brings up another issue.
# It is relatively common to provide a default value of None for members that will later be an object of a different type.
# None would be useless as a spec because it wouldn�t let you access any attributes or methods on it.
# As None is never going to be useful as a spec, and probably indicates a member that will normally of some other type, autospec doesn�t use a spec for
# members that are set to None. These will just be ordinary mocks (well - MagicMocks):
#
class Something:
member = None
mock = create_autospec(Something)
mock.member.foo.bar.baz()
# OUTPUT: '<MagicMock name='mock.member.foo.bar.baz()' id='...'>'
#
# If modifying your production classes to add defaults isn�t to your liking then there are more options.
# One of these is simply to use an instance as the spec rather than the class.
# The other is to create a subclass of the production class and add the defaults to the subclass without affecting the production class.
# Both of these require you to use an alternative object as the spec.
# Thankfully patch() supports this - you can simply pass the alternative object as the autospec argument:
#
class Something:
def __init__(self):
self.a = 33
class SomethingForTest(Something):
a = 33
p = patch('__main__.Something', autospec=SomethingForTest)
mock = p.start()
mock.a
# OUTPUT: '<NonCallableMagicMock name='Something.a' spec='int' id='...'>'
|
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 starts with QUIT_CHAR it inmediately exits the loop, so no more names are added/generated
at this point (neither the QUIT_CHAR name),
return up till MAX_NAMES names max.
'''
IGNORE_CHAR = 'b'
QUIT_CHAR = 'q'
MAX_NAMES = 5
names = ['John', 'Joshua', '1tim', 'Al', 'Benjamin', 'Franklin', 'George', 'Nagendra', '1tim']
# Solution #1
def filter_names_1(names):
filtered = []
cnt = 0
for name in names:
if name.lower()[0] == IGNORE_CHAR or not name.isalpha():
continue
if name.lower()[0] == QUIT_CHAR:
break
if cnt < 5:
filtered.append(name)
else:
break
cnt += 1
return filtered
print(filter_names_1(names))
# Solution 2 (using generator)
def filter_names_2(names):
cnt = 0
for name in names:
if name.lower()[0] == IGNORE_CHAR or not name.isalpha():
continue
if name.lower()[0] == QUIT_CHAR:
break
if cnt < 5:
cnt += 1
yield name
else:
break |
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]
Explanation:
The substring with start index = 0 is "cba", which is an anagram of "abc".
The substring with start index = 6 is "bac", which is an anagram of "abc".
Example 2:
Input:
s: "abab" p: "ab"
Output:
[0, 1, 2]
Explanation:
The substring with start index = 0 is "ab", which is an anagram of "ab".
The substring with start index = 1 is "ba", which is an anagram of "ab".
The substring with start index = 2 is "ab", which is an anagram of "ab".
给定一个字符串 s 和 非空字符串 p。 找到所有 p 在 s 中的变位词,将变位词开始部分的索引添加到结果中。
字符串包含的字符均为小写英文字母。
结果的顺序无关紧要。
思路:
看到标的是个 easy .. 估计数据不会很大,直接 sorted(s[i:i+len(p)]) == sorted(p) 判断了..
结果是 TLE。
好吧,只能认真思考下了。
想到的是利用动态规划,还有点回溯的味道。
子问题为:
当前点加上之前的点是否覆盖了全部的p。
若全部覆盖了,则返回 i - len(p) + 1 的开始索引,同时,将 s[i - len(p) + 1] 处的字符添加到 dp 的判断点中。
这样做可以扫描到这种情况:
s = ababab
p = ab
循环这种。
若没有存在于最后一个dp中,那么先判断是否有重复:
1. 如果在 p 中,但不在上一个子问题的需求解里。
2. 如果与最前面的一个字符发生了重复。
3. 如果与之前的一个字符不同。
满足这三个条件那么可以无视这个重复的字符。
比如这样:
s = abac
p = abc
这样相当于把重复的一个 a 忽略掉了。
同时还要判断是否它的前一个是否一致,一致的话就不能单纯的忽略了。
s = abaac / aabc
p = abc
没有满足的上述三个条件,那么重新复制一份原始子问题,然后将当前字符判断一下,继续下一个循环即可。
beat 99% 84ms
测试地址:
https://leetcode.com/problems/find-all-anagrams-in-a-string/description/
2018/10/27 修正:
上次分析后是有不足的,可以AC只是因为这个题的测试用例很少。
问题出在上面分析的 2. 和 3. 中,
重新梳理下:
若没有存在于最后一个dp中,那么先判断是否有重复:
1. 如果在 p 中,但不在上一个子问题的需求解里。
2. 此时要找一个合适的 ·复活点·,直接上例子吧
s "cbdbcae"
cbd b 当出现第二个 b 时,b不与之前分析后所找到的 c 相同,那么可以判定为要从 b 这个点开始复活了,但如果是的话那就找不到了。
要复活的点是 从 b 之前的一个 d。 也就是复活点要在重复的那个字符后面开始,那么我们要做的就是把在它之前的字符给加回来。
p "abcde"
待学习 Discuss 滑动窗口。
"""
c.. Solution o..
___ findAnagrams s, p
"""
:type s: str
:type p: str
:rtype: List[int]
"""
# p = sorted(p)
__ n.. s:
r_ []
_p _ # dict
___ i __ p:
try:
_p[i] += 1
except:
_p[i] = 1
result # list
x = _p.copy()
__ s[0] __ _p:
x[s[0]] -= 1
__ n.. x[s[0]]:
x.pop(s[0])
dp = x
__ n.. dp:
r_ [i ___ i __ r..(l..(s)) __ s[i] __ p]
___ i __ r..(1, l..(s)):
__ s[i] __ dp:
t = dp
t[s[i]] -= 1
__ n.. t[s[i]]:
t.pop(s[i])
__ n.. t:
result.a.. i-l..(p)+1)
x _ # dict
_t = s[i-l..(p)+1]
x[_t] = 1
dp = x
____
__ s[i] __ _p:
__ s[i] != s[i-l..(p)+s..(dp.values())]:
___ t __ s[i-l..(p)+s..(dp.values()):i]:
__ t __ s[i]:
______
try:
dp[t] += 1
except:
dp[t] = 1
c_
x = _p.copy()
__ s[i] __ x:
x[s[i]] -= 1
__ n.. x[s[i]]:
x.pop(s[i])
dp = x
r_ result
# 下面这个代码有瑕疵。
c.. Solution o..
___ findAnagrams s, p
"""
:type s: str
:type p: str
:rtype: List[int]
"""
# p = sorted(p)
__ n.. s:
r_ []
_p _ # dict
___ i __ p:
try:
_p[i] += 1
except:
_p[i] = 1
result # list
x = _p.copy()
__ s[0] __ _p:
x[s[0]] -= 1
__ n.. x[s[0]]:
x.pop(s[0])
dp = x
__ n.. dp:
r_ [i ___ i __ r..(l..(s)) __ s[i] __ p]
___ i __ r..(1, l..(s)):
__ s[i] __ dp:
t = dp
t[s[i]] -= 1
__ n.. t[s[i]]:
t.pop(s[i])
__ n.. t:
result.a.. i-l..(p)+1)
x _ # dict
_t = s[i-l..(p)+1]
x[_t] = 1
dp = x
____
__ s[i] __ _p a.. s[i] != s[i-1] a.. s[i] __ s[i-l..(p)+s..(dp.values())]:
c_
x = _p.copy()
__ s[i] __ x:
x[s[i]] -= 1
__ n.. x[s[i]]:
x.pop(s[i])
dp = x
r_ result
|
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, KeyboardInterrupt):
raise
except Exception as exception:
logger.error('Failed to open file', exc_info=True)
# By calling logger methods with exc_info=True parameter, the traceback will be dumped to the logger. As you can see the result
#
# ERROR:__main__:Failed to open file
# Traceback (most recent call last):
# File "example.py", line 6, in <module>
# open('/path/to/does/not/exist', 'rb')
# IOError: [Errno 2] No such file or directory: '/path/to/does/not/exist'
# Since Python 3.5, you can also pass the exception instance to exc_info parameter. Besides exc_info parameter, you can also call logger.exception(msg, *args), it is the same as calling to logger.error(msg, *args, exc_info=True). |
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("Дата введена неправильно")
# Так как точка означает любой символ,
# выведет: Дата введена правильно
p = re.compile(r"^[0-3][0-9]\.[01][0-9]\.[12][09][0-9][0-9]$")
# Символ "\" указан перед точкой
if p.search(d):
print("Дата введена правильно")
else:
print("Дата введена неправильно")
# Так как перед точкой указан символ "\",
# выведет: Дата введена неправильно
p = re.compile(r"^[0-3][0-9][.][01][0-9][.][12][09][0-9][0-9]$")
# Точка внутри квадратных скобок
if p.search(d):
print("Дата введена правильно")
else:
print("Дата введена неправильно")
# Выведет: Дата введена неправильно
input() |
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): The number of elements per group.
Returns:
list: The list of groups of size n,
where each group is a list of n elements.
"""
if not isinstance(iterable, types.GeneratorType):
input = (ele for ele in iterable)
else:
input = iterable
result = []
while True:
section = list(islice(input, n))
if section:
result.append(section)
else:
break
return result |
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 using properties without knowing their names
setattr(self, attribute, copy.deepcopy(getattr(data, attribute)))
#==============================================================================
class Undo(object):
def __init__(self):
# each instance keeps the latest saved copy so that there is only one
# copy of each in memory
self.__last = None
def save(self):
self.__last = Memento(self)
def undo(self):
for attribute in vars(self):
# mechanism for using properties without knowing their names
setattr(self, attribute, getattr(self.__last, attribute))
#==============================================================================
class Data(Undo):
def __init__(self):
super(Data, self).__init__()
self.numbers = []
#==============================================================================
if (__name__ == "__main__"):
d = Data()
repeats = 10
# add a number to the list in data repeat times
print("Adding.")
for i in range(repeats):
print("0" + str(i) + " times: " + str(d.numbers))
d.save()
d.numbers.append(i)
print("10 times: " + str(d.numbers))
d.save()
print("")
# now undo repeat times
print("Using Undo.")
for i in range(repeats):
print("0" + str(i) + " times: " + str(d.numbers))
d.undo()
print("10 times: " + str(d.numbers))
|
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
The key to the solution is: build a ladder for numbers: dp.
dp[i]: the smallest num of all increasing subsequences with length i+1.
When a new number x comes, compare it with the number in each level:
1. If x is larger than all levels, append it, increase the size by 1
2. If dp[i-1] < x <= dp[i], update dp[i] with x.
For example, say we have nums = [4,5,6,3],
then all the available increasing subsequences are:
len = 1: [4], [5], [6], [3] => dp[0] = 3
len = 2: [4, 5], [5, 6] => dp[1] = 5
len = 3: [4, 5, 6] => dp[2] = 6
"""
def lengthOfLIS(self, nums):
dp = [0] * len(nums)
size = 0
for n in nums:
# Binary search here.
left, right = 0, size
while left < right:
mid = (left + right) / 2
if dp[mid] < n:
left = mid + 1
else:
right = mid
# Append the next number
dp[right] = n
# Update size
if right == size:
size += 1
return size
"""
[]
[3]
[1,1,1,1]
[10,9,2,5,3,7,101,18]
"""
|
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
self.i += 1
return result
def __len__(self):
return self.length
sq = Squares(3)
len(sq)
sq.next_()
sq.next_()
sq.next_()
#
# So now, we can essentially loop over the collection in a very similar way to how we did it with sequences and the __getitem__ method:
#
sq = Squares(5)
while True:
try:
print(sq.next_())
except StopIteration:
# reached end of iteration
# stop looping
break
# Iterating Collections
# class RandomNumbers:
import random
class RandomNumbers:
def __init__(self, length, *, range_min=0, range_max=10):
self.length = length
self.range_min = range_min
self.range_max = range_max
self.num_requested = 0
def __len__(self):
return self.length
def __next__(self):
if self.num_requested >= self.length:
raise StopIteration
else:
self.num_requested += 1
return random.randint(self.range_min, self.range_max)
numbers = RandomNumbers(10)
len(numbers)
while True:
try:
print(next(numbers))
except StopIteration:
break
# We still cannot use a for loop, and if we want to 'restart' the iteration, we have to create a new object every time.
#
numbers = RandomNumbers(10)
for item in numbers:
print(item) #error
# Iterators and Iterables
# build class Cities
class Cities:
def __init__(self):
self._cities = ['New York', 'Newark', 'New Delhi', 'Newcastle']
def __len__(self):
return len(self._cities)
def __getitem__(self, s):
print('getting item...')
return self._cities[s]
def __iter__(self):
print('Calling Cities instance __iter__')
return self.CityIterator(self)
class CityIterator:
def __init__(self, city_obj):
# cities is an instance of Cities
print('Calling CityIterator __init__')
self._city_obj = city_obj
self._index = 0
def __iter__(self):
print('Calling CitiyIterator instance __iter__')
return self
def __next__(self):
print('Calling __next__')
if self._index >= len(self._city_obj):
raise StopIteration
else:
item = self._city_obj._cities[self._index]
self._index += 1
return item
# cities = Cities()
# cities[0]
# next(iter(cities))
# cities = Cities()
# for city in cities:
|
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 function directly below them.
# """
#
#
# c_ FixedFloat
# ___ - ____ amount
# ____.? ?
#
# ___ -r
# r_ _*<FixedFloat |____.a..; @ >' # 2 symbols after dot
#
#
# number = ?(18.5746)
# print ? # 18.57
#
# """
# We have this `FixedFloat` class that is really basic—doesn’t really do anything other than print the number out
# to two decimal places with the class name.
#
# Imagine we wanted to get a new `FixedFloat` object which is a result of summing two numbers together:
# """
#
#
# c_ FixedFloat
# ___ - ____ amount
# ____.? ?
#
# ___ -r
# r_ _*<FixedFloat |____.assert; @ >' # 2 symbols after dot
#
# ___ from_sum ____ value1 value2
# r_ F.. ? + ?
#
#
# number = ? 18.5746
# new_number = ?.f.. 19.575, 0.789
# print ?
#
# """
# This doesn’t make any sense, because we created a `FixedFloat` object (`number`),
# and then proceeded to call an instance method to create a new object.
# But that instance method didn’t use `____` at all—so really the fact that it’s
# a method inside a class is not very useful.
#
# Instead, we could make it a `@staticmethod`. That way, we’re not getting `____` but
# we can still put the method in the class, since it is _related_ to the class:
# """
#
#
# c_ FixedFloat
# ___ - ____, amount
# ____.? ?
#
# ___ -r
# r_ _*<FixedFloat |____.a..: @ >' # 2 symbols after dot
#
# ??
# ___ from_sum value1 value2
# r_ F.. ? + ?
#
#
# static_number = F__.f.. 19.575, 0.789)
# print ?
#
# """
# That looks a bit better! Now we don’t have the useless parameter AND we don’t need to create an object before
# we can call the method. Win-win!
#
# However, let’s now include some inheritance. We’ll create a `Currency` class that extends this `Float` class.
# """
#
#
# c_ Euro FixedFloat
# ___ - ____ amount
# s__.- ?
# ____.symbol = '€'
#
# ___ -r
# r_ _*<Euro |____.s.. |____.a.. @}>' # 2 symbols after dot
#
# # Skip defining from_sum as that's inherited
#
#
# """
# We’ve defined this new class that extends the `FixedFloat ` class.
# It’s got an `__init__` method that calls the parent’s `__init__`, and a `__repr__` method that overrides the parents’.
# It doesn’t have a `from_sum` method as that’s inherited and we’ll just use the one the parent defined.
# """
#
# euros = ? 18.5963
# print ? # <Euro €18.59>
#
# result = ?.f.. 15.76, 19.905
# print ? # <FixedFloat 35.66>
#
# """
# Oops! When we called the `Euro` constructor directly, we got a `Euro ` object with the symbol.
# But when we call `from_sum`, we got a `FixedFloat ` object. Not what we wanted!
#
# In order to fix this, we must make the `from_sum` method r_ an object of the class that called it—so that:
#
# * `FixedFloat.from_sum()` returns a `FixedFloat ` object; and
# * `Euro.from_sum()` returns an `Euro` object.
#
# `@classmethod` to the rescue! If we modify the `FixedFloat` class:
# """
#
#
# c_ FixedFloat
# ___ - ____ amount
# ____.? ?
#
# ___ -r
# r_ _*<FixedFloat |____.a.. @}>' # 2 symbols after dot
#
# ??
# ___ from_sum ___ value1 value2
# r_ ___ ? + ?
#
#
# c_ Euro F..
# ___ - ____ amount
# s__.- ?
# ____.symbol _ '€'
#
# ___ -r
# r_ _*<Euro |____.s.. |____.assert @ >' # 2 symbols after dot
#
#
# """
# When we now call:
#
# * `Euro.from_sum()`, `cls` is the `Euro` class.
# * `FixedFloat.from_sum()`, `cls` is the `FixedFloat` class.
# """
#
# print(E__.f.. 16.7565, 90 # <Euro €106.75>
|
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 from PyBites' inception to our first PyCon meet up?
'''
____ d__ _______ d__, t..
start_100days date(2017, 3, 30)
pybites_founded date(2016, 12, 19)
pycon_date date(2018, 5, 8)
___ get_hundred_days_end_date
"""Return a string of yyyy-mm-dd"""
t t..(100)
finish start_100days + t
print(s..(finish
r.. s..(finish)
___ get_days_between_pb_start_first_joint_pycon
"""Return the int number of days"""
diff pycon_date - pybites_founded
print(diff.days)
r.. diff.days
get_hundred_days_end_date()
get_days_between_pb_start_first_joint_pycon() |
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 answer is "wke", with the length of 3.
# # Solutions:
#
#
# c_ Solution
# # @return an integer
# ___ lengthOfLongestSubstring s
# lastRepeating _ -1
# longestSubstring _ 0
# positions _ # dict
# ___ i __ ra.. 0 le. s
# __ ? ? __ p.. an. l.. < p.. ? ?
# l.. _ p... ? ?
# __ ? - l.. > l..
# l.. _ ? - l..
# p.. ? ? _ ?
# r_ ?
#
#
# ? .? "abcabcbb" |
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 x* len y)"""
#
# r.. ?**2
#
# ___ -s
# """Returns a string representation of the table"""
#
# s ''
#
# ___ row __ _?
# ? +_ (' | '.j.. ? + '\n'
#
#
# r.. ?
#
#
#
#
#
#
# ___ calc_cell x, y
# """Takes x and y coords and returns the re-calculated result"""
#
#
# __ n.. 1 <_ ? <_ _? a.. 1 <_ y <_ _?
# r.. I.. "Invalid x and y"
#
#
# r.. i.. _? ? -1 ? -1
|
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 names (in `(self, name, year)`) hold the values of the arguments that we were given when the method
was called: `Movie(‘The Matrix’, 1994)`.
`self.name` and `self.year` are the names of the properties of the new object we are creating.
They only exist within the `self` object, so it’s totally OK to have `self.name = name`.
"""
## `self` ?
"""
It’s common in Python to call the “current object” `self`.
But it doesn’t have to be that way!
"""
class Movie:
def __init__(current_object, name, year):
current_object.name = name
current_object.year = year
"""
Don’t do this, for it will look very weird when someone reads your code
(e.g. if you work or go to an interview), but just remember that `self` is like any other variable name—
it can be anything you want. `self` is just the convention. Many editors will syntax highlight it differently
because it is so common.
""" |
1194267d03094c9f1f6ac33eae62de730fc10019 | syurskyi/Python_Topics | /055_modules/001_modules/examples/ITVDN Python Essential 2016/08_StdlibCopy/example.py | 1,434 | 3.859375 | 4 | """Пример использования модуля copy.
Операция присваивания не копирует объект, а лишь создаёт ссылку на объект.
Для изменяемых объектов и для объектов, содержащих ссылки на изменяемые объекты,
часто необходима такая копия, чтобы её можно было изменить, не изменяя оригинал.
Данный модуль предоставляет общие операции копирования.
Неполная (поверхностная) копия (shallow copy) создаёт новый составной объект
и добавляет те же ссылки на объекты, которые содержатся в оригинальном.
Полная (глубокая) копия (deep copy) рекурсивно копирует данные объект и все
объекты, которые в него входят.
"""
import copy
obj = [1, 5, [12, 5]]
print(obj)
obj_copy = copy.copy(obj) # неполная копия
obj_deepcopy = copy.deepcopy(obj) # полная копия
obj[2].append(4) # изменения оригинала
print(obj_copy) # поверхностная копия изменилась
print(obj_deepcopy) # полная копия не изменилась
|
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
# sub_set _ F..
# __ ? __ # list:
# ? _ T..
# ____ ? __ ?
# ? _ T..
# ____ le. ? > le. ?
# ? _ F..
#
# ____
# ___ i __ ra..(le. l
# __ l ? __ ? 0
# n _ 1
# w___ ? < le. ? an. ? ?+? __ ? ?
# ? +_ 1
#
# __ ? __ le. ?
# s_s.. _ T..
#
# r_ ?
#
# a _ [2,4,3,5,7]
# b _ [4,3]
# c _ [3,7]
# print ? a b
# print ? a c
#
#
|
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
:rtype: int
"""
if not root:
return 0
node_list = [root]
depth_count = 1
# Breadth-first Search
while node_list:
# node_scan: all the nodes in one level.
# Traverse node_scan and get all the nodes of next level,
# Then update node_list
node_scan = node_list[:]
node_list = []
for node in node_scan:
l_child = node.left
r_child = node.right
if l_child:
node_list.append(l_child)
if r_child:
node_list.append(r_child)
if node_list:
depth_count += 1
return depth_count
"""
[]
[1]
[1,2,3]
[0,1,2,3,4,5,6,null,null,7,null,8,9,null,10]
"""
|
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 = memento.balance
def __str__(self):
return f'Balance = {self.balance}'
if __name__ == '__main__':
ba = BankAccount(100)
m1 = ba.deposit(50)
m2 = ba.deposit(25)
print(ba)
# restore to m1
ba.restore(m1)
print(ba)
# restore to m2
ba.restore(m2)
print(ba) |
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 properties 1 and 2.
You are given trust, an array of pairs trust[i] = [a, b] representing that the
person labelled a trusts the person labelled b.
If the town judge exists and can be identified, return the label of the town
judge. Otherwise, return -1.
Example 1:
Input: N = 2, trust = [[1,2]]
Output: 2
Example 2:
Input: N = 3, trust = [[1,3],[2,3]]
Output: 3
Example 3:
Input: N = 3, trust = [[1,3],[2,3],[3,1]]
Output: -1
Example 4:
Input: N = 3, trust = [[1,2],[2,3]]
Output: -1
Example 5:
Input: N = 4, trust = [[1,3],[1,4],[2,3],[2,4],[4,3]]
Output: 3
Note:
1 <= N <= 1000
trust.length <= 10000
trust[i] are all different
trust[i][0] != trust[i][1]
1 <= trust[i][0], trust[i][1] <= N
"""
____ t___ _______ L..
____ c.. _______ d..
c_ Solution:
___ findJudge N: i.., trust: L..[L..[i..]]) __ i..
"""
like the find the celebrity
"""
ingress d..(s..)
egress =d..(s..)
___ p, q __ trust:
egress[p].add(q)
ingress[q].add(p)
___ i __ r..(1, N+1
__ l..(egress[i]) __ 0 a.. l..(ingress[i]) __ N - 1:
r.. i
r.. -1
|
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'):
return(' '.join(line.split()[::-1]))
print(reverse_string_words("The quick brown fox jumps over the lazy dog."))
print(reverse_string_words("Python Exercises."))
|
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: ",middle)
#the middle item is the item we are looking for
__ array[middle] __ item:
r.. middle
#the item we are looking for is smaller than the middle item
#so we have to consider the left subarray
____ array[middle] > item:
print("Checking items on the left...")
r.. binary_search(array,item,left,middle-1)
#the item we are looking for is greater than the middle item
#so we have to consider the right subarray
____ array[middle] < item:
print("Checking items on the right...")
r.. binary_search(array,item,middle+1,right)
__ _______ __ _______
array [1,4,7,8,9,10,11,20,22,25]
print(binary_search(array,111,0,l..(array)-1)) |
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 id = ? ''',
(newphone, userid))
# Delete user with id 2
delete_userid = 2
cursor.execute('''DELETE FROM users WHERE id = ? ''', (delete_userid,))
db.commit()
db.close()
|
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()
# ######################################################################################################################
# The global Statement
# X = 88 # Global X
#
# ___ func
# g_ X
# X = 99 # Global X: outside def
#
# func()
# print(X) # Prints 99
#
# y, z = 1, 2 # Global variables in module
#
# ___ all_global
# g___ x # Declare globals assigned
# x = y + z # No need to declare y, z: LEGB rule
#
# print()
# ######################################################################################################################
# Scopes and Nested Functions
# X = 99 # Global scope name: not used
# print(X)
#
# ___ f1
# X = 88 # Enclosing def local
#
# ___ f2
# print(X) # Reference made in nested def
#
# f2()
#
# f1() # Prints 88: enclosing def local
#
# ___ f1
# X = 89
#
# ___ f2
# print(X) # Remembers X in enclosing def scope
#
# ___ f2 # Return f2 but don't call it
#
#
# action = f1() # Make, return function
# action() # Call it now: prints 88
#
# print()
# ######################################################################################################################
# Retaining Enclosing Scope State with Defaults
# ___ f1
# x = 88
#
# ___ f2_x_x # Remember enclosing scope X with defaults
# print(x)
#
# f2()
#
# f1() # Prints 88
#
#
# ___ f1
# x = 88 # Pass x along instead of nesting
# f2(x) # Forward reference okay
#
# ___ f2 x
# print(x)
#
# f1()
# print()
# ######################################################################################################################
# Nested scopes, defaults, and lambdas
# ___ func
# x = 4
# action = l_ n x ** n # x remembered from enclosing def
# ___ a_
#
# x f_
# print(x(2)) # Prints 16, 4 ** 2
#
# ___ func
# x = 4
# action = l_ n x_x x ** n # Pass x in manually
# ___ a_
# print()
# ######################################################################################################################
# nonlocal in Action
# ___ tester start
# state = start # Referencing nonlocals works normally
# ___ nested label
# print l_, s_) # Remembers state in enclosing scope
# ___ n_
# F = t_(0)
# F('spam')
# F('ham')
# ___ tester start
# state = start
# ___ nested label
# print l_ s_
# s_ += 1 # Cannot change by default (or in 2.6)
# ___ n_
# F = t_(0)
# F('spam') # UnboundLocalError: local variable 'state' referenced before assignment
# print()
# ######################################################################################################################
# Using nonlocal for changes
# ___ tester start
# state = start # Each call gets its own state
# ___ nested label
# n______
# s___ # Remembers state in enclosing scope
# print(l_, s_)
# s_ __ 1 # Allowed to change it if nonlocal
# ____ n_
# F = t_(0)
# print('#' * 52 + ' Increments state on each call')
# F('spam') # Increments state on each call
# F('ham')
# F('eggs')
# print('#' * 52 + ' Make a new tester that starts at 42')
# G = t__42 # Make a new tester that starts at 42
# G__spam
# print('#' * 52 + ' My state information updated to 43')
# G__eggs # My state information updated to 43
# print('#' * 52 + ' ')
# F__bacon # But F's is where it left off: at 3
# Each call has different state information
# print()
# ######################################################################################################################
# Arguments and Shared References
# ___ f_a_ # a is assigned to (references) passed object
# a = 99 # Changes local variable a only
# b = 88
# f(b) # a and b both reference same 88 initially
# print(b) # b is not changed
# ___ changer a b # Arguments assigned references to objects
# a = 2 # Changes local name's value only
# b_0_ 'spam' # Changes shared object in-place
# X = 1
# L = [1, 2] # Caller
# c_(X, L) # Pass immutable and mutable objects
# X, L # X is unchanged, L is different!
# X = 1
# a = X # They share the same object
# a = 2 # Resets 'a' only, 'X' is still 1
# print(X)
# L = [1, 2]
# b = L # They share the same object
# b_0_ _ 'spam' # In-place change: 'L' sees the change too
# print(L)
# print()
# ######################################################################################################################
# suppose we have points (represented as tuples), and we want to sort them based on the distance of the point from
# some other fixed point:
# origin = (0, 0)
# l = [(1,1), (0, 2), (-3, 2), (0,0), (10, 10)]
# dist2 = l_ x_ y| (x|0|-y|0|)**2 + (x|1|-y|1|)**2
# dist2((0,0), (1,1))
# s_(l, key _ l_ x| dist2((0,0)_ x))
# s_(l, key_p_(dist2, (0,0)))
#
# print()
# ######################################################################################################################
# we have some generic email() function that can be used to notify someone when various things happen
# in our application. But depending on what is happening we may want to notify different people.
# ___ sendmail to subject body
# # code to send email
# print('To:|0|, Subject:|1|, Body:|2|'.f_ to subject body
#
# # Now, we may haver different email adresses we want to send notifications to, maybe defined in a config file in our app.
# # Here, I'll just use hardcoded variables:
#
# email_admin = 'palin@python.edu'
# email_devteam = 'idle@python.edu;cleese@python.edu'
#
# # Now when we want to send emails we would have to write things like:
#
# sendmail(email_admin, 'My App Notification', 'the parrot is dead.')
# sendmail(';'.j_ email_admin email_devteam _ 'My App Notification', 'the ministry is closed until further notice.')
#
# # We could simply our life a little using partials this way:
#
# send_admin = p_(sendmail, email_admin, 'For you eyes only')
# send_dev = p_(sendmail, email_devteam, 'Dear IT:')
# send_all = p_(sendmail, ';'.j_((email_admin, email_devteam)), 'Loyal Subjects')
#
# send_admin('the parrot is dead.')
# send_all('the ministry is closed until further notice.')
#
# # Finally, let's make this a little more complex, with a mixture of positional and keyword-only argument
#
# print()
# ######################################################################################################################
# Functions defined inside anther function can reference variables from that enclosing scope,
# just like functions can reference variables from the global scope.
# ___ outer_func
# x _ 'hello'
#
# ___ inner_func
# print(x)
#
# inner_func()
#
# outer_func()
#
# print()
# ######################################################################################################################
# if we assign a value to a variable, it is considered part of the local scope, and potentially masks enclsogin scope
# variable names:
#
# x _ 'hello'
# ___ inner
# no_ x
# x _ python'
# inner()
# print(x)
#
# outer()
# Of course, this can work at any level as well:
# ___ outer
# x _ 'hello'
#
# ___ inner1
# ___ inner2
# no_
# x
# x _ 'python'
#
# inner2
#
# inner1
# print x
#
# outer()
#
# print()
# ######################################################################################################################
# Let's examine that concept of a cell to create an indirect reference for variables that are in multiple scopes.
# ___ outer
# x _ 'python'
# ___ inner
# print x
# r_ inn_
#
# fn _ out___
# fn.__c_.c_f_
# fn.__c_
#
# print()
# ######################################################################################################################
# Modifying the Free Variable
# We know we can modify nonlocal variables by using the nonlocal keyword. So the following will work:
# ___ counter
# count _ 0 # local variable
#
# ___ inc
# no_
# co____ # this is the count variable in counter
# co___ += 1
# r_ co___
#
# r_ inc
#
# c = co____
# c()
# c()
#
# print()
# ######################################################################################################################
# Shared Extended Scopes
#
# ___ outer
# count _ 0
#
# ___ inc1
# no__
# co__
# co__ += 1
# r_ co__
#
# ___ inc2
# no__
# co__
# co__ += 1
# r_ co__
#
# r_ inc1 inc2
#
# fn1, fn2 = outer()
# fn1.__c_, fn2.__c_
#
# # As you can see here, the count label points to the same cell.
#
# fn1()
# fn1()
# fn2()
#
# 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: Alice's hand can be rearranged as [1,2,3],[2,3,4],[6,7,8].
Example 2:
Input: hand = [1,2,3,4,5], W = 4
Output: false
Explanation: Alice's hand can't be rearranged into groups of 4.
Note:
1 <= hand.length <= 10000
0 <= hand[i] <= 10^9
1 <= W <= hand.length
"""
____ t___ _______ L..
____ c.. _______ C.., d..
_______ h__
c_ Solution:
___ isNStraightHand A: L..[i..], W: i.. __ b..
"""
sort + queue
prev = previous value
prev_cnt = previous value count
"""
q d..()
counter C..(A)
prev 0
prev_cnt 0
___ k __ s..(counter # sorted by key
__ prev_cnt > counter[k] o. prev_cnt > 0 a.. k > prev + 1:
r.. F..
q.a..(counter[k] - prev_cnt)
prev, prev_cnt k, counter[k]
__ l..(q) __ W:
c q.popleft()
prev_cnt -_ c
r.. prev_cnt __ 0
___ isNStraightHand_heap A: L..[i..], W: i.. __ b..
"""
sort + heap
O(N log N + N log N)
"""
A.s..()
__ l..(A) % W !_ 0:
r.. F..
__ W __ 1:
r.. T..
h # list # tuple of (-3, [1, 2, 3])
___ a __ A:
__ n.. h:
h [(a, [a])]
_____
__ a __ h[0][1][-1]:
h__.heappush(h, (a, [a]
____ a __ h[0][1][-1] + 1:
_, lst h__.heappop(h)
lst.a..(a)
__ l..(lst) < W:
h__.heappush(h, (a, lst
____
r.. F..
__ h:
r.. F..
r.. T..
__ _______ __ _______
... Solution().isNStraightHand([1,2,3,6,2,3,4,7,8], 3) __ T..
... Solution().isNStraightHand([1,1,2,2,3,3], 3) __ T..
|
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')
finally:
print('finally ran!')
print('#' * 52 + ' ')
# finally ran!
try:
1 / 0
except ZeroDivisionError:
print('Zero division exception occurred')
finally:
print('finally ran!')
print('#' * 52 + ' You will see that in both instances, the `finally` block was executed.'
' Even if an exception is raised in the `except` block, the `finally` block will **still** execute!')
print(
'#' * 52 + 'Even if the finally is in a function and there is a return statement in the `try` or `except` blocks:')
# Zero division exception occurred
# finally ran!
# ######################################################################################################################
# You'll see that in both instances, the finally block was executed. Even if an exception is raised in the except block,
# the finally block will still execute!
# Even if the finally is in a function and there is a return statement in the try or except blocks:
def my_func():
try:
1 / 0
except:
return
finally:
print('finally running...')
my_func()
print('#' * 52 + ' This is very handy to release resources even in cases where an exception occurs. ')
print('#' * 52 + ' For example making sure a file is closed after being opened:')
try:
f = open('test.txt', 'w')
a = 1 / 0
except:
print('an exception occurred...')
finally:
print('Closing file...')
f.close()
# We should always do that when dealing with files.
# But that can get cumbersome...
# So, there is a better way.
# Let's talk about context managers, and the pattern we are trying to solve:
# Run some code to create some object(s)
# Work with object(s)
# Run some code when done to clean up object(s)
# Context managers do precisely that.
# We use a context manager to create and clean up some objects. The key point is that the cleanup needs to happens
# automatically - we should not have to write code such as the try...except...finally code we saw above.
# When we use context managers in conjunction with the with statement, we end up with the "cleanup" phase happening as
# soon as the with statement finishes:
print('#' * 52 + ' We should **always** do that when dealing with files.')
print('#' * 52 + ' ')
print('#' * 52 + ' When we use context managers in conjunction with the `with` statement,'
' we end up with the "cleanup" phase happening as soon as the `with` statement finishes:')
with open('test.txt', 'w') as file:
print('inside with: file closed?', file.closed)
print('after with: file closed?', file.closed)
# inside with: file closed? False
# after with: file closed? True
# ######################################################################################################################
print('#' * 52 + ' This works even in this case:')
def test():
with open('test.txt', 'w') as file:
print('inside with: file closed?', file.closed)
return file
# As you can see, we return directly out of the with block...
file = test()
# inside with: file closed? False
print(file.closed)
# True
print('#' * 52 + ' And yet, the file was still closed.')
print('#' * 52 + ' It also works even if we have an exception in the middle of the block')
# with open('test.txt', 'w') as f:
# print('inside with: file closed?', f.closed)
# raise ValueError() ###### ValueError:
# ######################################################################################################################
print('after with: file closed?', f.closed)
# after with: file closed? True
print('#' * 52 + ' ')
print('#' * 52 + ' ')
print('#' * 52 + ' ')
# Context managers can be used for more than just opening and closing files.
# If we think about it there are two phases to a context manager:
# when the with statement is executing: we enter the context
# when the with block is done: we exit the context
# We can create our own context manager using a class that implements an __enter__ method which is executed when
# we enter the context, and an __exit__ method that is executed when we exit the context.
# There is a general pattern that context managers can help us deal with:
# Open - Close
# Lock - Release
# Change - Reset
# Enter - Exit
# Start - Stop
# The __enter__ method is quite straightforward. It can (but does not have to) return one or more objects we then
# use inside the with block.
# The __exit__ method however is slightly more complicated.
# It needs to return a boolean True/False. This indicates to Python whether to suppress any errors that occurred
# in the with block. As we saw with files, that was not the case - i.e. it returns a False
# If an error does occur in the with block, the error information is passed to the __exit__ method - so it needs
# three things: the exception type, the exception value and the traceback. If no error occured, then those values
# will simply be None.
#
# We haven't covered exceptions in detail yet, so let's quickly see what those three things are:
# def my_func():
# return 1.0 / 0.0
# my_func() # ZeroDivisionError: float division by zero
# ######################################################################################################################
print('#' * 52 + ' Lets go ahead and create a context manager:')
# The exception type here is ZeroDivisionError.
# The exception value is float division by zero.
# The traceback is an object of type traceback (that itself points to other traceback objects forming the trace stack)
# used to generate that text shown in the output.
# I am not going to cover traceback objects at this point - we'll do this in a future part (OOP) of this series.
# Let's go ahead and create a context manager:
class MyContext:
def __init__(self):
self.obj = None
def __enter__(self):
print('entering context...')
self.obj = 'the Return Object'
return self.obj
def __exit__(self, exc_type, exc_value, exc_traceback):
print('exiting context...')
if exc_type:
print(f'*** Error occurred: {exc_type}, {exc_value}')
return False # do not suppress exceptions
# with MyContext() as obj:
# raise ValueError # ValueError:
# As you can see, the __exit__ method was still called - which is exactly what we wanted in the first place. Also,
# the exception that was raise inside the with block is seen.
# We can change that by returning True from the __exit__ method:
print('#' * 52 + ' As you can see, the `__exit__` method was still called -'
' which is exactly what we wanted in the first place.')
print('#' * 52 + ' Also, the exception that was raise inside the `with` block is seen.')
print('#' * 52 + ' We can change that by returning `True` from the `__exit__` method:')
class MyContext:
def __init__(self):
self.obj = None
def __enter__(self):
print('entering context...')
self.obj = 'the Return Object'
return self.obj
def __exit__(self, exc_type, exc_value, exc_traceback):
print('exiting context...')
if exc_type:
print(f'*** Error occurred: {exc_type}, {exc_value}')
return True # suppress exceptions
with MyContext() as obj:
raise ValueError
print('reached here without an exception...')
# entering context...
# exiting context...
# *** Error occurred: <class 'ValueError'>,
# reached here without an exception...
# ######################################################################################################################
print('#' * 52 + ' Look at the output of this code:')
with MyContext() as obj:
print('running inside with block...')
print(obj)
print(obj)
# entering context...
# running inside with block...
# the Return Object
# exiting context...
# the Return Object
# Notice that the obj we obtained from the context manager, still exists in our scope after the with statement.
# The with statement does not have its own local scope - it's not a function!
# However, the context manager could manipulate the object returned by the context manager:
print('#' * 52 + ' Notice that the `obj` we obtained from the context manager,'
' still exists in our scope after the `with` statement.')
print('#' * 52 + ' The `with` statement does **not** have its own local scope - its not a function!')
print('#' * 52 + ' However, the context manager could manipulate the object returned by the context manager:')
class Resource:
def __init__(self, name):
self.name = name
self.state = None
class ResourceManager:
def __init__(self, name):
self.name = name
self.resource = None
def __enter__(self):
print('entering context')
self.resource = Resource(self.name)
self.resource.state = 'created'
return self.resource
def __exit__(self, exc_type, exc_value, exc_traceback):
print('exiting context')
self.resource.state = 'destroyed'
if exc_type:
print('error occurred')
return False
with ResourceManager('spam') as res:
print(f'{res.name} = {res.state}')
print(f'{res.name} = {res.state}')
# entering context
# spam = created
# exiting context
# spam = destroyed
# ######################################################################################################################
# We still have access to res, but it's internal state was changed by the resource manager's __exit__ method.
# Although we already have a context manager for files built-in to Python, let's go ahead and write our own anyways -
# good practice.
print('#' * 52 + ' We still have access to `res`, but its internal state was changed'
' by the resource managers `__exit__` method.')
print('#' * 52 + ' Although we already have a context manager for files built-in to Python,'
' lets go ahead and write our own anyways - good practice.')
class File:
def __init__(self, name, mode):
self.name = name
self.mode = mode
def __enter__(self):
print('opening file...')
self.file = open(self.name, self.mode)
return self.file
def __exit__(self, exc_type, exc_value, exc_traceback):
print('closing file...')
self.file.close()
return False
with File('test.txt', 'w') as f:
f.write('This is a late parrot!')
# opening file...
# closing file...
# ######################################################################################################################
# Even if we have an exception inside the with statement, our file will still get closed.
# Same applies if we return out of the with block if we're inside a function:
print('#' * 52 + ' Even if we have an exception inside the `with` statement, our file will still get closed.')
print('#' * 52 + ' Same applies if we return out of the `with` block if we are inside a function:')
def test():
with File('test.txt', 'w') as f:
f.write('This is a late parrot')
if True:
return f
print(f.closed)
print(f.closed)
f = test()
# opening file...
# closing file...
# ######################################################################################################################
# Note that the __enter__ method can return anything, including the context manager itself.
# If we wanted to, we could re-write our file context manager this way:
print('#' * 52 + ' Note that the `__enter__` method can return anything, including the context manager itself.')
print('#' * 52 + ' If we wanted to, we could re-write our file context manager this way:')
class File():
def __init__(self, name, mode):
self.name = name
self.mode = mode
def __enter__(self):
print('opening file...')
self.file = open(self.name, self.mode)
return self
def __exit__(self, exc_type, exc_value, exc_traceback):
print('closing file...')
self.file.close()
return False
# Of course, now we would have to use the context manager object's file property to get a handle to the file:
with File('test.txt', 'r') as file_ctx:
print(next(file_ctx.file))
print(file_ctx.name)
print(file_ctx.mode)
# opening file...
# This is a late parrot
# test.txt
# r
# closing file...
|
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'; otherwise, the first character in the hexadecimal string will not be the zero character.
The given number is guaranteed to fit within the range of a 32-bit signed integer.
You must not use any method provided by the library which converts/formats the number to hex directly.
Example 1:
Input:
26
Output:
"1a"
Example 2:
Input:
-1
Output:
"ffffffff"
"""
__author__ 'Daniel'
c_ Solution(o..
___ toHex num
"""
All use bit manipulation
:type num: int
:rtype: str
"""
ret # list
w.... l..(ret) < 8 a.. num:
ret.a..(encode(num & 0xf
num >>= 4
r.. ''.j..(ret||-1]) o. '0'
___ toHexNormal num
"""
Python arithmetic handles the negative number very well
:type num: int
:rtype: str
"""
ret # list
w.... l..(ret) < 8 a.. num:
ret.a..(encode(num % 16
num /= 16
r.. ''.j..(ret||-1]) o. '0'
___ encode d
__ 0 <_ d < 10:
r.. s..(d)
r.. chr(o..('a') + d - 10)
__ _______ __ _______
... Solution().toHex(-1) __ 'ffffffff'
|
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 each element in the unsorted portion of the list,
# # check if the element is smaller than the current min
# # and assign that index as the new min_index.
# ___ curr_index __ ra.. ?+1 le. ?
# __ ?|? > ?|?
# ? _ ?
# # Swap the min element with the first element of the
# # unsorted portion of the list.
# ?|? ?|? _ ?|? ?|?
#
|
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 dominoes falling to the right push their adjacent dominoes
standing on the right.
When a vertical domino has dominoes falling on it from both sides, it stays
still due to the balance of the forces.
For the purposes of this question, we will consider that a falling domino
expends no additional force to a falling or already fallen domino.
Given a string "S" representing the initial state. S[i] = 'L', if the i-th
domino has been pushed to the left; S[i] = 'R', if the i-th domino has been pushed to the right; S[i] = '.', if the i-th domino has not been pushed.
Return a string representing the final state.
Example 1:
Input: ".L.R...LR..L.."
Output: "LL.RR.LLRRLL.."
Example 2:
Input: "RR.L"
Output: "RR.L"
Explanation: The first domino expends no additional force on the second domino.
Note:
0 <= N <= 10^5
String dominoes contains only 'L', 'R' and '.'
"""
c_ Solution:
___ pushDominoes dominoes: s..) __ s..
"""
DP L & R from both ends
Let L[i] be the distance to the "L" from the right
we will consider that a falling domino expends no additional force
"""
n l..(dominoes)
L [f__("inf") ___ i __ r..(n)]
R [f__("inf") ___ i __ r..(n)]
___ i __ r..(n-1, -1, -1
__ dominoes[i] __ "L":
L[i] 0
____ dominoes[i] __ "R":
L[i] f__("inf")
____ i + 1 < n:
L[i] L[i+1] + 1
___ i __ r..(n
__ dominoes[i] __ "R":
R[i] 0
____ dominoes[i] __ "L":
R[i] f__("inf")
____ i - 1 >_ 0:
R[i] R[i-1] + 1
ret # list
___ i __ r..(n
d m..(R[i], L[i])
__ d __ f__("inf"
cur "."
____ R[i] __ L[i]:
cur "."
____ d __ R[i]:
cur "R"
____
cur "L"
ret.a..(cur)
r.. "".j..(ret)
__ _______ __ _______
... Solution().pushDominoes(".L.R...LR..L..") __ "LL.RR.LLRRLL.."
|
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 range(self.end)]
for i in range(self.end-1, -1, -1):
for j in range(self.end):
if i > j:
pass
elif j-i < 2 and s[i] == s[j]:
self.is_palindrome[i][j] = True
elif self.is_palindrome[i+1][j-1] and s[i] == s[j]:
self.is_palindrome[i][j] = True
else:
self.is_palindrome[i][j] = False
self.palindrome_partition(0, [])
return self.result
def palindrome_partition(self, start, sub_strs):
if start == self.end:
# It's confused the following sentence doesn't work.
# self.result.append(sub_strs)
self.result.append(sub_strs[:])
return
for i in range(start, self.end):
if self.is_palindrome[start][i]:
sub_strs.append(self.str[start:i+1])
self.palindrome_partition(i+1, sub_strs)
sub_strs.pop() # Backtracking here
if __name__ == "__main__":
sol = Solution()
print sol.partition("aab")
print sol.partition("aabb")
print sol.partition("aabaa")
print sol.partition("acbca")
print sol.partition("acbbca")
|
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}
# ======================================================================================================
# ===== Nuke Example ===================================================================================
transformNode = nuke.createNode('Transform', '{} {}'.format(keys[1], values[1]))
print({k: 0 for k in keys})
# {'a': 0, 'b': 0}
d = {"a": 1, "b": 2, "c": 3, "d": 4 }
print({k: v for (k, v) in d.items() if v % 2 == 0})
# # {'b': 2, 'd': 4}
# Zip together keys and values
print(list(zip(['a', 'b', 'c'], [1, 2, 3])))
# Make a dict from zip result
D = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
# dict keyword argument form
print(dict(name='mel', age=45))
# dict key/value tuples form
print(dict([('name', 'mel'), ('age', 45)]))
# Zip together keys and values
print(list(zip(['a', 'b', 'c'], [1, 2, 3])))
# Make a dict from zip result
D = dict(zip(['a', 'b', 'c'], [1, 2, 3]))
# dict comprehension
D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])}
print(D)
# dict comprehension
D = {k: v for (k, v) in zip(['a', 'b', 'c'], [1, 2, 3])}
print(D)
# dict comprehension
# Or: range(1, 5)
D = {x: x ** 2 for x in [1, 2, 3, 4]}
print(D)
# dict comprehension
# Loop over any iterable
D = {c: c * 4 for c in 'SPAM'}
print(D)
D = {c.lower(): c + '!' for c in ['SPAM', 'EGGS', 'HAM']}
print(D)
# Initialize dict from keys
# with a comprehension
D = dict.fromkeys(['a', 'b', 'c'], 0)
# Initialize dict from keys
print(D)
D = {k:0 for k in ['a', 'b', 'c']}
# Same, but with a comprehension
print(D)
# d.get key[, default]
# безопасное получение значения по ключу никогда не выбрасывает KeyError .
# Если ключ не найден, возвращается значение default по-умолчанию – None .
# #
numbers_dict = dict.fromkeys(range(3, 42))
print(numbers_dict)
for key in range(5):
print('{}:'.format(key), numbers_dict.get(key, 0))
d = {'x': 1, 'y': 2, 'z': 3}
for key in d.keys(): # Использование метода keys()
print("({0} => {1})".format(key, d[key], end=" "))
# Выведет: (y => 2) (x => 1) (z => 3)
print() # Вставляем символ перевода строки
for key in d: # Словари также поддерживают итерации
print("({0} => {1})".format(key, d[key], end=" "))
# Выведет: (y => 2) (x => 1) (z => 3)
d = {"x": 1, "y": 2, "z": 3}
k = list(d.keys()) # Получаем список ключей
k.sort() # Сортируем список ключей
for key in k:
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (x => 1) (y => 2) (z => 3)
print()
d = {'x': 1, 'y': 2, 'z': 3}
for key in sorted(d.keys()):
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (x => 1) (y => 2) (z => 3)
print()
d = {'x': 1, 'y': 2, 'z': 3}
for key in sorted(d):
print("({0} => {1})".format(key, d[key]), end=" ")
# Выведет: (x => 1) (y => 2) (z => 3)
# d.items
# в Python 3 возвращает объект представления словаря, соответствующий парам двухэлементным кортежам
# вида ключ, значение . В Python 2 возвращает соответствующий список, а метод iteritems возвращает итератор.
# Аналогичный метод в Python 2.7 – viewitems .
#
phonebook = {
'Jack': '032-846',
'Guido': '917-333',
'Mario': '120-422',
'Mary': '890-532', # последняя запятая игнорируется
}
print('Items:', phonebook.items())
# d.keys
# в Python 3 возвращает объект представления словаря, соответствующий ключам словаря. В Python 2 возвращает соответствующий
# список, а метод iterkeys возвращает итератор. Аналогичный метод в Python
# 2.7 – viewkeys .
#
phonebook = {
'Jack': '032-846',
'Guido': '917-333',
'Mario': '120-422',
'Mary': '890-532', # последняя запятая игнорируется
}
print('Keys:', phonebook.keys())
phonebook = {
'Jack': '032-846',
'Guido': '917-333',
'Mario': '120-422',
'Mary': '890-532', # последняя запятая игнорируется
}
print('Values:', phonebook.values())
# # d.popitem
# # удаляет произвольную пару ключ-значение и возвращает её. Если словарь пустой, возникает исключение KeyError.
# # Метод полезен для алгоритмов, которые обходят словарь, удаляя уже обработанные значения например,
# # определённые алгоритмы, связанные с теорией графов .
# #
phonebook = {
'Jack': '032-846',
'Guido': '917-333',
'Mario': '120-422',
'Mary': '890-532', # последняя запятая игнорируется
}
person = phonebook.popitem()
print('Popped {} phone: {} '.format(*person))
# d.setdefault key[, default]
# если ключ key существует, возвращает
# соответствующее значение. Иначе создаёт элемент с ключом key и значением default. default по умолчанию равен None.
#
phonebook = {
'Jack': '032-846',
'Guido': '917-333',
'Mario': '120-422',
'Mary': '890-532', # последняя запятая игнорируется
}
for person in ('Jack', 'Liz'):
phone = phonebook.setdefault(person, '000-000')
print('{}: {}'.format(person, phonebook))
print(phonebook)
# d.update(mapping)
# принимает либо другой словарь или отображение, либо итерабельный объект, состоящий из итерабельных объектов –
# пар ключ-значение, либо именованные аргументы. Добавляет соответствующие элементы в словарь,
# перезаписывая элементы с существующими ключами.
#
phonebook = {
'Jack': '032-846',
'Guido': '917-333',
'Mario': '120-422',
'Mary': '890-532', # последняя запятая игнорируется
}
phonebook.update({'Alex': '832-438', 'Alice': '231-987'})
phonebook.update([('Joe', '217-531'), ('James', '783-428')])
phonebook.update(Carl='783-923', Victoria='386-486')
print(phonebook)
# d[key]
# получение значения с ключом key. Если такой ключ не существует
# # и отображение реализует специальный метод __missing__(self, key), то он
# # вызывается. Если ключ не существует и метод __missing__ не определён,
# # выбрасывается исключение KeyError.
#
phonebook ={
'Jack': '032-846',
'Guido': '917-333',
'Mario': '120-422',
'Mary': '890-532', # последняя запятая игнорируется
}
try:
print('Mary:', phonebook['Mary'])
print('Lumberjack:', phonebook['Lumberjack'])
except KeyError as e:
print('No entry for', *e.args)
# how many times each character occurred ib a st___:
text = 'Some long text'
counts = dict()
for c in text:
key = c.lower().strip()
if key:
counts[key] = counts.get(key, 0) + 1
print(counts)
# how many times each character occurred in a string:
#
# Suppose now that we just want a dictionary to track the uppercase, lowercase, and other characters in the string
# (i.e. kind of grouping the data by uppercase, lowercase, other) - again ignoring spaces:
import string
print(string.ascii_lowercase)
print(string.ascii_uppercase)
text = 'Some long text'
categories = {}
for c in text:
if c != ' ':
if c in string.ascii_lowercase:
key = 'lower'
elif c in string.ascii_uppercase:
key = 'upper'
else:
key = 'other'
if key not in categories:
categories[key] = set() # set we'll insert the value into
categories[key].add(c)
for cat in categories:
print(f'{cat}:', ''.join(categories[cat]))
# how many times each character occurred in a string:
# We can simplify this a bit using setdefault:
text = 'Some long text'
categories = {}
for c in text:
if c != ' ':
if c in string.ascii_lowercase:
key = 'lower'
elif c in string.ascii_uppercase:
key = 'upper'
else:
key = 'other'
categories.setdefault(key, set()).add(c)
for cat in categories:
print(f'{cat}:', ''.join(categories[cat]))
categories = {}
for c in text:
if c != ' ':
if c in string.ascii_lowercase:
key = 'lower'
elif c in string.ascii_uppercase:
key = 'upper'
else:
key = 'other'
categories.setdefault(key, set()).add(c)
for cat in categories:
print(f'{cat}:', ''.join(categories[cat]))
# how many times each character occurred in a string:
#
# Just to clean things up a but more, let's create a small utility function that will return the category key:
text = 'Some long text'
def cat_key(c):
if c == ' ':
return None
elif c in string.ascii_lowercase:
return 'lower'
elif c in string.ascii_uppercase:
return 'upper'
else:
return 'other'
categories = {}
for c in text:
key = cat_key(c)
if key:
categories.setdefault(key, set()).add(c)
for cat in categories:
print(f'{cat}:', ''.join(categories[cat]))
# how many times each character occurred in a string:
#
# If you are not a fan of using if...elif... in the cat_key function we could do it this way as well
text = 'Some long text'
def cat_key(c):
categories = {' ': None,
string.ascii_lowercase: 'lower',
string.ascii_uppercase: 'upper'}
for key in categories:
if c in key:
return categories[key]
else:
return 'other'
cat_key('a'), cat_key('A'), cat_key('!'), cat_key(' ')
categories = {}
for c in text:
key = cat_key(c)
if key:
categories.setdefault(key, set()).add(c)
for cat in categories:
print(f'{cat}:', ''.join(categories[cat]))
# In this example we have some dictionaries we use to configure our application. One dictionary specifies
# some configuration defaults for every configuration parameter our application will need.
# Another dictionary is used to configure some global configuration, and another set of dictionaries is used
# to define environment specific configurations, maybe dev and prod.
conf_defaults = dict.fromkeys(('host', 'port', 'user', 'pwd', 'database'), None)
print(conf_defaults)
conf_global = {
'port': 5432,
'database': 'deepdive'}
conf_dev = {
'host': 'localhost',
'user': 'test',
'pwd': 'test'}
conf_prod = {
'host': 'prodpg.deepdive.com',
'user': '$prod_user',
'pwd': '$prod_pwd',
'database': 'deepdive_prod'}
# Now we can generate a full configuration for our dev environment this way:
config_dev = {**conf_defaults, **conf_global, **conf_dev}
print(conf_dev)
# and a config for our prod environment:
config_prod = {**conf_defaults, **conf_global, **conf_prod}
print(config_prod)
# defaultdict
# The defaultdict is a specialized dictionary found i_ the collections module. (It is a subclass of the dict type).
# Write a Python function that will create and r_ a dictionary from another dictionary, but sorted by value.
# You can assume the values are all comparable and have a natural sort order.
#
# composers _ {'Johann': 65, 'Ludwig': 56, 'Frederic': 39, 'Wolfgang': 35}
#
# instead of using a dictionary comprehension, we can simply use the dict()
# function to create a dictionary from the sorted tuples!
composers = {'Johann': 65, 'Ludwig': 56, 'Frederic': 39, 'Wolfgang': 35}
def sort_dict_by_value(d):
d = {k: v for k, v in sorted(d.items(), key = lambda el: el[1])}
return d
print(sort_dict_by_value(composers))
def sort_dict_by_value(d):
return dict(sorted(d.items(), key = lambda el: el[1]))
print(sort_dict_by_value(composers)) |
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 l..(strs)
___ ind, s__ __ e..(temp
__ s__ a.. s__!_"": # avoid case of empty string
s__ [char ___ char __ s__]
s__.s..()
s__ "".j..(s__)
temp[ind] s__
hash_map # dict
___ ind, s__ __ e..(temp
indexes hash_map.g.. s__, # list)
indexes.a..(ind) # side-effect
hash_map[s__] indexes
result # list
___ val __ hash_map.v..
__ l..(val)>1:
# result.append([strs[i] for i in val])
result += [strs[i] ___ i __ val]
r.. ?
___ anagrams strs
"""
Algorithm: sort string and hash map
:param strs: a list of strings
:return: a list of strings
"""
hash_map # dict
___ ind, s__ __ e..(strs
s__ "".j..(s..(s__ # string reversing and sorting are a little different
__ s__ n.. __ hash_map:
hash_map[s__] [ind]
____
hash_map[s__].a..(ind)
# indexes = hash_map.get(string, [])
# indexes.append(ind) # side-effect
# hash_map[string] = indexes # reassign
result # list
___ val __ hash_map.v..
__ l..(val)>1:
# result.append([strs[i] for i in val])
result += [strs[i] ___ i __ val]
r.. ?
__ _____ __ ____
Solution().anagrams(["", ""]) |
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
val val
children children
____ t___ _______ L..
____ c.. _______ d..
c_ Solution:
___ postorder root: 'Node') __ L.. i..
"""
maintain a stack, pop and reverse
"""
__ n.. root:
r.. # list
ret d..()
stk [root]
visited s..()
w.... stk:
cur stk.p.. )
ret.appendleft(cur.val)
___ c __ cur.children:
stk.a..(c)
r.. l..(ret)
___ postorder_visited root: 'Node') __ L.. i..
"""
maintain a stack, if visited before, then pop
"""
ret # list
__ n.. root:
r.. ret
stk [root]
visited s..()
w.... stk:
cur stk[-1]
__ cur __ visited:
stk.p.. )
ret.a..(cur.val)
____
visited.add(cur)
___ c __ r..(cur.children
stk.a..(c)
r.. ret
|
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 +, -, * and /, use "true" division (so 2/3 is .66
# rather than 0)
#
# Make sure you convert both numbers to ints.
# If bad data is passed in, raise a ValueError.
# """
# __ n.. a__ op __ ? ___ ? __ ?
# r.. V...
#
# # assume op is good and split the string
# args ?.s..
#
# __ l.. ? !_ 3
# r.. V...
#
# a, op, b args
#
# # convert to int raising error. Note, int does this
# a, b i..(x) ___ ? __ ? ?
#
# __ b __ 0 a.. o. __ '/'
# r.. V...
#
# r.. ? o. ? ?
|
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, you are guaranteed that there will always be only one unique minimum window in S.
在S中找到包含T所有字符的长度最小的子字符串。
要求在 O(n) 时间复杂度内完成。
思路:
1. emmm.本来是一个 O(n)的但是最后出了点问题...总体思路没错,待改进。passed的了,但效率很低。
首先是 哈希 T .
哈希后的结果放到两个变量里。一个用于对比一个用于删除判断。
返回迭代S:
如果这个元素存在于 T 中,记录,并在T中删除对应的字符。
如果此时用于删除的 T 没有了。ok,找出记录的下标的最大与最小。记录为结果。
用于删除的T没有了也不要停止,继续迭代,此后不断更新重复出现的字符的下标,重复对比此时记录的长度。
为什么可行呢?
S = ADOBE A CODEBANC T = ABC
在这里加一个A进去。
当迭代到ADOBE 时,记录的A = 0 B = 3。此时如果记录的话为 0:3 包含了 A与B.
不管此后与谁重复,只要找里面的最小与最大的下标,即可找到所有想要的值。
这个思路看起来是 O(n) 的。只需迭代一遍,中途就记录几个min,max就可以。
可实际实施起来...
发现这个min与max还不是很好记录...
用堆吧只能很快速的获取一个。
用二叉搜索树吧删除还有点麻烦。
想用红黑吧...还不会写。
到是可以用set暂时代替红黑,喔对,可以用set试试。
啊哈,现在什么都没用,直接用了生成器生成。
以后再试试,先记下来。
下面这个pass了喔。
600+ms beat 7% = =.
测试地址:
https://leetcode.com/problems/minimum-window-substring/description/
"""
from collections import deque
class Solution(object):
def minWindow(self, s, t):
"""
:type s: str
:type t: str
:rtype: str
"""
# b = set(t)
b = {}
for i in t:
try:
b[i] += 1
except:
b[i] = 1
a = b.copy()
# [(mins_index, maxs_index), (mins_index, maxs_index), (mins_index, maxs_index)]
x = {}
mins = ""
# t_min = 0
# t_max = 0
for i, d in enumerate(s):
if d in b:
try:
x[d].append(i)
except:
x[d] = deque([i], maxlen=b[d])
if a.get(d):
a[d] -= 1
if not a[d]:
a.pop(d)
if not a:
values = x.values()
if not mins:
mins = s[min((q[0] for q in values)):max((q[-1] for q in values))+1]
else:
mins = min(mins, s[min((q[0] for q in values)):max((q[-1] for q in values))+1], key=len)
if a:
return ""
return mins
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.