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 |
|---|---|---|---|---|---|---|
a929bac01aaa8cd1501ac5e811d9f578e4bf14a6 | mps-jenkins/API | /pythonwork/groupby.py | 119 | 3.546875 | 4 | from itertools import groupby
string="aabnnn"
print(groupby(string[1]))
#print(''.join(i[0] for i in groupby(string))) |
19ce271fbed21911cb4845774d3def642a180e1c | mps-jenkins/API | /pythonwork/ty.py | 266 | 4.0625 | 4 | def print_reverse(string_list):
dict = {}
for str in string_list:
print(str)
if dict[str]:
print(str)
print(''.join(reversed(str)))
dict[''.join(reversed(str))] = 1
list="youarewthene"
print_reverse(list) |
6ce31a00096f059a523de1c806c89d2150863b43 | mps-jenkins/API | /pythonwork/sumoflist.py | 206 | 3.96875 | 4 | #! /usr/bin/python
list1 = (1, 2, 10, 34, 22)
def addlist(listing):
if len(listing) == 1:
return listing[0]
else:
return listing[0] + addlist(listing[1:])
print(addlist(list1))
|
83c9e61357cd68a4c20f5a62a039ba3e4444171b | mps-jenkins/API | /pythonwork/reversetypes.py | 133 | 3.671875 | 4 | name = "Shreeti"
newstr = ""
def reversing(string):
newstring = string[::-1]
return newstring
print(reversing("Shreeti")) |
3e6435849f3f4e3e19b5ca9a3c2b50a58ff3947d | Rakhatolla/Rakhatolla | /day_1.py | 447 | 4.03125 | 4 | # числа, строки
# команда() - что-то, что выполняется
# print('привет')
# print(10 + 25)
# print('10' + '25')
# print(19 + '5')
# print(f'Сумма {39+10}')
# переменная - ячейка для хранения информация
num1 = int(input('Введите первое число'))
num2 = int(input('Введите второе число'))
print('Сумма {num1+num2}')
|
0ae6315a37bc2f857bd5bbe4785f4b0c8d019b86 | BeLazy167/css | /diffehellman.py | 771 | 3.65625 | 4 | import hashlib
g=int(input("Enter value of g: "))
p=int(input("Enter value of p: "))
a=int(input("Enter random number for alice: "))
b=int(input("Enter random number for bob: "))
A = (g**a) % p
B = (g**b) % p
print('g: ',g,' (a shared value), n: ',p, ' (a prime number)')
print('\nAlice calculates:')
print('a (Alice random): ',a)
print('Alice value (A): ',A,' (g^a) mod p')
print('\nBob calculates:')
print('b (Bob random): ',b)
print('Bob value (B): ',B,' (g^b) mod p')
print('\nAlice calculates:')
keyA=(B**a) % p
print('Key: ',keyA,' (B^a) mod p')
print('Key: ',hashlib.sha256(str(keyA).encode()).hexdigest())
print('\nBob calculates:')
keyB=(A**b) % p
print('Key: ',keyB,' (A^b) mod p')
print('Key: ',hashlib.sha256(str(keyB).encode()).hexdigest()) |
e9acdbfd9ab5a29c06f1e27abcd1d384611c5cf0 | chizhangucb/Python_Material | /cs61a/lectures/Week2/Lec_Week2_3.py | 2,095 | 4.21875 | 4 | ## Functional arguments
def apply_twice(f, x):
"""Return f(f(x))
>>> apply_twice(square, 2)
16
>>> from math import sqrt
>>> apply_twice(sqrt, 16)
2.0
"""
return f(f(x))
def square(x):
return x * x
result = apply_twice(square, 2)
## Nested Defintions
# 1. Every user-defined function has a parent environment / frame
# 2. The parent of a function is the frame in which it was defined
# 3. Every local frame has a parent frame
# 4. The parent of a frame is the parent of a function called
def make_adder(n):
"""Return a function that takes one argument k and returns k + n.
>>> add_three = make_adder(3)
>>> add_three(4)
7
"""
def adder(k):
return k + n
return adder
## Lexical scope and returning functions
def f(x, y):
return g(x)
def g(a):
return a + y
# f(1, 2) # name 'y' is not defined
# This expression causes an error because y is not bound in g.
# Because g(a) is NOT defined within f and
# g is parent frame is the global frame, which has no "y" defined
## Composition
def compose1(f, g):
def h(x):
return f(g(x))
return h
def triple(x):
return 3 * x
squiple = compose1(square, triple)
squiple(5)
tripare = compose1(triple, square)
tripare(5)
squadder = compose1(square, make_adder(2))
squadder(5)
compose1(square, make_adder(2))(3)
## Function Decorators
# special syntax to apply higher-order functions as part of executing a def statement
def trace(fn):
"""Returns a function that precedes a call to its argument with a
print statement that outputs the argument.
"""
def wrapped(x):
print("->", fn, '(', x, ')')
return fn(x)
return wrapped
# @trace affects the execution rule for def
# As usual, the function triple is created.
# However, the name triple is not bound to this function.
# Instead, the name triple is bound to the returned function
# value of calling trace on the newly defined triple function
@trace
def triple(x):
return 3 * x
triple(12)
# The decorator symbol @ may also be followed by a call expression |
6303e82883ac28ef965a177e45358a74a7ecd233 | sendador/Challenge | /Chapter 3/chapter_3.py | 1,141 | 3.875 | 4 | from itertools import groupby
def check_adjacent(number_list):
adjacent_groups = [len(list(g)) for k, g in groupby(number_list)]
identical_adjacent_digits_counter = len(
list(u for u in adjacent_groups if u > 1))
return identical_adjacent_digits_counter
def check_increasing_numbers(number_list):
return all(x <= y for x, y in zip(number_list, number_list[1:]))
def numbers_range(start_number, end_number):
numbers_list = []
for x in range(start_number, end_number+1):
numbers_list.append(str(x))
return numbers_list
def list_of_possible_combinations(number_list):
specific_list = []
result_list = []
for numbers in number_list:
if (check_adjacent(specific_list) > 1) and (check_increasing_numbers(specific_list) == True):
result_list.append(int(numbers)-1)
specific_list = []
for number in numbers:
specific_list.append(int(number))
return result_list
number_list = numbers_range(372**2, 809**2)
answer = list_of_possible_combinations(number_list)
print(f"You have to check {len(answer)} numbers. That's a bummer bro")
|
fbd7afe059c5eb0b6d99122e46b1ddbcaac18de0 | hammer-spring/PyCharmProject | /pythion3 实例/30_list常用操作.py | 1,680 | 4.1875 | 4 | print("1.list 定义")
li = ["a", "b", "mpilgrim", "z", "example"]
print(li[1])
print("2.list 负数索引")
print(li[-1])
print(li[-3])
print(li[1:3])
print(li[1:-1])
print(li[0:3])
print("3.list 增加元素")
li.append("new")
print(li)
li.insert(2,"new")
print(li)
li.extend(["two","elements"])
print(li)
print("4.list 搜索")
a = li.index("new")
print(a)
print("c" in li)
print("5.list 删除元素")
li.remove("z")
print(li)
li.remove("new") # 删除首次出现的一个值
print(li)
#li.remove("c") #list 中没有找到值, Python 会引发一个异常
#print(li)
print(li.pop()) # pop 会做两件事: 删除 list 的最后一个元素, 然后返回删除元素的值。
print(li)
print("6.list 运算符")
li = ['a', 'b', 'mpilgrim']
li = li + ['example', 'new']
print(li)
li += ['two']
print(li)
li = [1, 2] * 3
print(li)
print("8.list 分割字符串")
li = ['server=mpilgrim', 'uid=sa', 'database=master', 'pwd=secret']
s = ";".join(li)
print(s)
print(s.split(";") )
print(s.split(";", 1) )
print("9.list 的映射解析")
li = [1, 9, 8, 4]
print([elem*2 for elem in li])
li = [elem*2 for elem in li]
print(li)
print("10.dictionary中的解析")
params = {"server":"mpilgrim", "database":"master", "uid":"sa", "pwd":"secret"}
print(params.keys())
print(params.values())
print(params.items())
print([k for k, v in params.items()])
print([v for k, v in params.items()])
print(["%s=%s" % (k, v) for k, v in params.items()])
print("11.list 过滤")
li = ["a", "mpilgrim", "foo", "b", "c", "b", "d", "d"]
print([elem for elem in li if len(elem) > 1])
print([elem for elem in li if elem != "b"])
print([elem for elem in li if li.count(elem) == 1]) |
7ea2b18c1371846f59f41193d89a7480c08351fc | hammer-spring/PyCharmProject | /11_线程/17.py | 311 | 3.703125 | 4 | import threading
import time
def func():
print("I am running.........")
time.sleep(4)
print("I am done......")
if __name__ == "__main__":
t = threading.Timer(6, func)
t.start()
i = 0
while True:
print("{0}***************".format(i))
time.sleep(3)
i += 1
|
3a4377cb8dfe546ebb09bfef38f2fc5c2ae24f68 | hammer-spring/PyCharmProject | /01-python基础/2-OOP/01.py | 806 | 3.734375 | 4 |
'''
定以一个学生类,用来形容学生
'''
# 定义一个空的类
class Student():
# 一个空类,pass代表直接跳过
# 此处pass必须有
pass
# 定义一个对象
mingyue = Student()
# 在定义一个类,用来描述听Python的学生
class PythonStudent():
# 用None给不确定的值赋值
name = None
age = 18
course = "Python"
# 需要注意
# 1. def doHomework的缩进层级
# 2. 系统默认由一个self参数
def doHomework(self):
print("I 在做作业")
# 推荐在函数末尾使用return语句
return None
# 实例化一个叫yueyue的学生,是一个具体的人
yueyue = PythonStudent()
print(yueyue.name)
print(yueyue.age)
# 注意成员函数的调用没有传递进入参数
yueyue.doHomework() |
029c38ddbc3acc9025050bb84b6fc7661cd8a088 | hammer-spring/PyCharmProject | /07_图像处理-pillow/12.2.py | 1,404 | 3.5625 | 4 | from tkinter import *
import tkinter.filedialog
from PIL import Image
#创建主窗口
win = Tk()
win.title(string = "图像文件的属性")
#打开一个[打开旧文件]对话框
def createOpenFileDialog():
#返回打开的文件名
filename = myDialog.show()
#打开该文件
imgFile = Image.open(filename)
#填入该文件的属性
label1.config(text = "format = " + imgFile.format)
label2.config(text = "mode = " + imgFile.mode)
label3.config(text = "size = " + str(imgFile.size))
label4.config(text = "info = " + str(imgFile.info))
#创建Label控件, 用来填入图像文件的属性
label1 = Label(win, text = "format = ")
label2 = Label(win, text = "mode = ")
label3 = Label(win, text = "size = ")
label4 = Label(win, text = "info = ")
#靠左边对齐
label1.pack(anchor=W)
label2.pack(anchor=W)
label3.pack(anchor=W)
label4.pack(anchor=W)
#按下按钮后,即打开对话框
Button(win, text="打开图像文件",command=createOpenFileDialog).pack(anchor=CENTER)
#设置对话框打开的文件类型
myFileTypes = [('Graphics Interchange Format', '*.gif'), ('Windows bitmap', '*.bmp'),
('JPEG format', '*.jpg'), ('Tag Image File Format', '*.tif'),
('All image files', '*.gif *.jpg *.bmp *.tif')]
#创建一个[打开旧文件]对话框
myDialog = tkinter.filedialog.Open(win, filetypes=my FileTypes)
#开始程序循环
win.mainloop()
|
3a09ac22c92a4c6403f1e92f7dcbaf4a980bb887 | hammer-spring/PyCharmProject | /数据挖掘/基于SVM算法的手写数字识别系统/03_核转换函数.py | 1,048 | 3.609375 | 4 | #核转换函数
def kernelTrans(X, A, kTup): # calc the kernel or transform data to a higher dimensional space
m, n = shape(X)
K = mat(zeros((m, 1)))
if kTup[0] == 'lin':
K = X * A.T # linear kernel
elif kTup[0] == 'rbf':
for j in range(m):
deltaRow = X[j, :] - A
K[j] = deltaRow * deltaRow.T
K = exp(K / (-1 * kTup[1] ** 2)) # divide in NumPy is element-wise not matrix like Matlab
else:
raise NameError('Houston We Have a Problem -- \
That Kernel is not recognized')
return K
class optStruct:
def __init__(self, dataMatIn, classLabels, C, toler, kTup):
self.X = dataMatIn
self.labelMat = classLabels
self.C = C
self.tol = toler
self.m = shape(dataMatIn)[0]
self.alphas = mat(zeros((self.m, 1)))
self.b = 0
self.eCache = mat(zeros((self.m, 2)))
self.K = mat(zeros((self.m, self.m)))
for i in range(self.m):
self.K[:, i] = kernelTrans(self.X, self.X[i, :], kTup) |
99a4589ac6adbe80b7efc1a04fd9761892d09deb | hammer-spring/PyCharmProject | /18-Spider/v23.py | 986 | 4.125 | 4 | '''
python中正则模块是re
使用大致步骤:
1. compile函数讲正则表达式的字符串便以为一个Pattern对象
2. 通过Pattern对象的一些列方法对文本进行匹配,匹配结果是一个Match对象
3. 用Match对象的方法,对结果进行操纵
'''
import re
# \d表示以数字
# 后面+号表示这个数字可以出现一次或者多次
s = r"\d+" # r表示后面是原生字符串,后面不需要转义
# 返回Pattern对象
pattern = re.compile(s)
# 返回一个Match对象
# 默认找到一个匹配就返回
m = pattern.match("one12two2three3")
print(type(m))
# 默认匹配从头部开始,所以此次结果为None
print(m)
# 返回一个Match对象
# 后面为位置参数含义是从哪个位置开始查找,找到哪个位置结束
m = pattern.match("one12two2three3", 3, 10)
print(type(m))
# 默认匹配从头部开始,所以此次结果为None
print(m)
print(m.group())
print(m.start(0))
print(m.end(0))
print(m.span(0)) |
456c580d8fea29eee70b8e417cb5eccfb9431210 | hammer-spring/PyCharmProject | /pythion3 实例/9_判断奇数偶数.py | 299 | 3.84375 | 4 | while True:
try:
num=int(input('输入一个整数:')) #判断输入是否为整数
except ValueError: #不是纯数字需要重新输入
print("输入的不是整数!")
continue
if num%2==0:
print('偶数')
else:
print('奇数')
break |
fc93851b1d48839215c48b9e6434d0dd890ef028 | hammer-spring/PyCharmProject | /06_Tkinter/6.34 创建命令型单选按钮.pyw | 1,263 | 3.734375 | 4 | from tkinter import *
#创建主窗口
win = Tk()
#运动项目列表
sports = ["棒球", "篮球", "足球", "网球", "排球"]
#将用户的选择,显示在Label控件上
def showSelection():
choice = "您的选择是:" + sports[var.get()]
label.config(text = choice)
#读取用户的选择值,是一个整数
var = IntVar()
#创建单选按钮
radio1 = Radiobutton(win, text=sports[0], variable=var,value=0,command=showSelection)
radio2 = Radiobutton(win, text=sports[1], variable=var, value=1, command=showSelection)
radio3 = Radiobutton(win, text=sports[2], variable=var, value=2, command=showSelection)
radio4 = Radiobutton(win, text=sports[3], variable=var, value=3,command=showSelection)
radio5 = Radiobutton(win, text=sports[4], variable=var, value=4,command=showSelection)
#将单选按钮的外型,设置成命令型按钮
radio1.config(indicatoron=0)
radio2.config(indicatoron=0)
radio3.config(indicatoron=0)
radio4.config(indicatoron=0)
radio5.config(indicatoron=0)
#将单选按钮靠左边对齐
radio1.pack(anchor=W)
radio2.pack(anchor=W)
radio3.pack(anchor=W)
radio4.pack(anchor=W)
radio5.pack(anchor=W)
#创建文字标签,用来显示用户的选择
label = Label(win)
label.pack()
#开始程序循环
win.mainloop()
|
1a1c4576569d277cb166a2bb1dd81a5866b40114 | hammer-spring/PyCharmProject | /06_Tkinter/6.11 place()方法.py | 578 | 3.890625 | 4 | from tkinter import *
# 主窗口
win = Tk()
# 创建窗体
frame = Frame(win, relief=RAISED, borderwidth=2, width=400, height=300)
frame.pack(side=TOP, fill=BOTH, ipadx=5, ipady=5, expand=1)
# 第1个按钮的位置在距离窗体左上角的(40, 40)坐标处
button1 = Button(frame, text="Button 1")
button1.place(x=40, y=40, anchor=W, width=80, height=40)
# 第2个按钮的位置在距离窗体左上角的(140, 80)坐标处
button2 = Button(frame, text="Button 2")
button2.place(x=140, y=80, anchor=W, width=80, height=40)
# 开始窗口的事件循环
win.mainloop()
|
e4739836cd7ea6d249d79245517aeebe143bb502 | rylanlee/glakemap-dev | /glakemap/dirext/dirextmngmt.py | 2,424 | 3.5 | 4 | import os
import zipfile
class DirMngmt(object):
"""1) Creates folders and unzip files containing zip extension 2) Read
'.safe' file and process SAR data """
def __init__(self, main_dir, subfolder_1, subfolder_2, subfolder_3):
"""Note: Give 'subfolder_1' name and folder containing
SAR data the same name. Otherwise '.zip' cannot be located """
self.main_dir = main_dir
self.subfolder_1 = subfolder_1
self.subfolder_2 = subfolder_2
self.subfolder_3 = subfolder_3
def main_direc(self):
return self.main_dir
def makefolders(self):
""" Create folders"""
folder_1 = os.path.join(self.main_dir, self.subfolder_1)
if not os.path.exists(folder_1):
os.makedirs(folder_1)
folder_2 = os.path.join(folder_1, self.subfolder_2)
if not os.path.exists(folder_2):
os.makedirs(folder_2)
folder_3 = os.path.join(folder_1, self.subfolder_3)
if not os.path.exists(folder_3):
os.makedirs(folder_3)
class FileExtMngmt(DirMngmt):
def __init__(self, main_dir, subfolder_1, subfolder_2, subfolder_3, zip_extension, file_extension, polarisation):
# super().__init__(main_dir, subfolder_1, subfolder_2, subfolder_3) # Python >3
# DirMngmt.__init__(self, main_dir, subfolder_1, subfolder_2, subfolder_3)
super(FileExtMngmt, self).__init__(main_dir, subfolder_1, subfolder_2, subfolder_3) # only python 2
self.zip_extension = zip_extension
self.file_extension = file_extension
self.polarisation = polarisation
def unzipfiles(self):
"""Unzip files containing '.zip' extension """
for r, d, f in os.walk(os.path.join(self.main_dir, self.subfolder_1)):
for file in f:
if self.zip_extension in file:
print ('The files containing .ZIP extension are: {} \n'.format((os.path.join(r, file))))
file_name = os.path.join(r, file)
zip_ref = zipfile.ZipFile(file_name)
print ('The number of zip files: {}'.format(len(f)))
print ('Extracting {} of {} \n'.format(file, f))
zip_ref.extractall(os.path.join(self.main_dir, self.subfolder_1, self.subfolder_2))
print ('Extractring files completed!\n')
zip_ref.close() |
b24fbc344986a78340a95cb32da676f9d7a5b248 | muneermohd9690/Remove_Vowels | /Troll_Optimizer.py | 428 | 3.6875 | 4 | # This website is for losers LOL!" would become "Ths wbst s fr lsrs LL
import re
vowels = ('a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U')
def find_vowels(s, v):
#s = s.casefold()
newstring = s
for x in s:
if x in v:
newstring = newstring.replace(x, "")
print("Optimized string is :", newstring)
string = input("Please enter the string: ")
find_vowels(string, vowels)
|
8af5abe525f744858cddc9e5cb5746ccc3d997d3 | CDinuwan/PyUnitTesting | /Unit.py | 221 | 3.828125 | 4 | def add(x, y):
return x + y
def substract(x, y):
return x - y
def multiply(x, y):
return x * y
def divide(x, y):
if y == 0:
print("Cannot devide by zero")
return x / y
print(add(4, 5))
|
6b780c850343264c10ee5de6dd2856132dda26e0 | Apisk1991/LearnPyton | /Основы pyton/1/HumanDate.py | 481 | 3.90625 | 4 | # Задание по переводу секунд в минуты, часы, дни
# 1 min 60 sec
# 1 hour 3600 seconds
# 1 day 86400 seconds
dur = int(input('Введите число'))
if dur >= 86400:
day = dur // 86400
dur = dur % 86400
print(day, "дн. ")
if dur >= 3600:
hour = dur // 3600
dur = dur % 3600
print(hour, "час. ")
if dur >= 60:
min = dur // 60
dur = dur % 60
print(min, "мин. ")
print(dur, "сек. ")
|
75cb43a2a144fed4334ea1693c8cc9d0d56cbca5 | francliu/mmseg | /core/Chunk.py | 1,133 | 3.546875 | 4 | #encoding:utf-8
class Chunk(object):
def __init__(self, *words):
self.words = []
for word in words:
if len(word) == 0:
continue
self.words.append(word)
#计算chunk的总长度
def total_word_length(self):
length = 0
for word in self.words:
length += len(word)
return length
#计算平均长度
def average_word_length(self):
return float(self.total_word_length()) / float(len(self.words))
#统计有效词数
def effective_word_number(self):
_sum = 0
for word in self.words:
if len(word) > 1 and word.freq >=0:
_sum += 1
return _sum
#统计词频
def word_frequency(self):
_sum = 0
for word in self.words:
_sum += word.freq
return _sum
#计算标准差
def standard_deviation(self):
average = self.average_word_length()
_sum = 0.0
for word in self.words:
tmp = (len(word) - average)
_sum += float(tmp) * float(tmp)
return _sum |
2b02e816299308c0a6402507f38e2c1fb974ea8d | Mrs-Jekel/Python_exercises | /homework1_6_20.py | 240 | 3.9375 | 4 | list = [3, 6, 8, 2, 34, 379, 98, 7, 355, 6, 73]
list.sort()
print(list)
def find(sorted_list, num_to_find):
for i in list:
if i == num_to_find:
return True
print(i)
return False
print(find(2, 5)) |
cca9af58b9bde01d82a61f36f3de3986f01157c2 | MariaLaveniaVikaPamukasari/Maria-Lavenia-Vika-Pamukasari_I0320056_Tiffany-Bella-Nagari_Tugas4 | /I0320056_soal4.py | 852 | 3.90625 | 4 | # Program Pengujian Spesifikasi Kursus Mobil Online
#Mulai
print("\t\t\tSelamat datang di Mobiline")
print("\t\t\tBelajar bisa,Bisa belajar,Saya bisa")
a = input("\nSiapakah nama Anda? :")
print("Nama Anda adalah",a)
b = int(input("Berapa usia Anda? :"))
print("Usia Anda adalah",b,"tahun")
if b < 21 :
print("\nMaaf Anda terlalu muda untuk masuk ke sini")
input("Silahkan tekan enter untuk melanjutkan")
else :
print("\nUsia Anda telah mencukupi, silahkan masuk")
print("\n\t\t\tSelamat datang di tahap selanjutnya")
ab = str(input("Apakah Anda telah lulus ujian kualifikasi MobiLine? Yes/No :"))
if ab == "Yes":
print("Selamat", a,"!","Anda dapat mendaftar kursus ini")
input("Silahkan tekan enter untuk kembali")
else :
print("Anda tidak dapat mendaftar kursus ini")
input("Silahkan tekan enter untuk kembali")
#Selesai |
878cc1191155aa1265e6d6b591dcffc7ec9a898c | ursaMaj0r/python-csc-125 | /Snippets/image-manipulation-1/color_tinting.py | 850 | 3.578125 | 4 | from PIL import Image
# prompt for file
name = input("File name: ")
red_tint = int(input("Red tint: "))
green_tint = int(input("Green tint: "))
blue_tint = int(input("Blue tint: "))
img = Image.open(name)
# split into 3 profiles
red, green, blue = img.split()
# for each pixel, subtract value from 255
for y in range(img.height):
for x in range(img.width):
# red
orginal_value_red = red.getpixel((x, y))
red.putpixel((x, y), orginal_value_red + red_tint)
# green
orginal_value_green = green.getpixel((x, y))
green.putpixel((x, y), orginal_value_green + green_tint)
# blue
orginal_value_blue = blue.getpixel((x, y))
blue.putpixel((x, y), orginal_value_blue + blue_tint)
# output new image
new_image = Image.merge('RGB', (red, green, blue))
new_image.save('output.png')
|
1dc0538ba1efe1d972174d4daced83826d6d0979 | ursaMaj0r/python-csc-125 | /Snippets/Intro/speaker_backwards.py | 111 | 3.953125 | 4 | # input
input_text = input("Line: ")
# response
for letter in reversed(input_text):
print(letter, end='')
|
6d91127f84a5a041282cda7d0ae8db27e453e0f6 | ursaMaj0r/python-csc-125 | /Snippets/intro-1/how_many_words.py | 224 | 3.796875 | 4 | # input
input_words = []
input_word = input("Word: ")
# reponse
while input_word != '':
input_words.append(input_word)
input_word = input("Word: ")
print("You know {} unique word(s)!".format(len(set(input_words))))
|
63d2067421dcbba6c72de3e7827eb61a1c9a4aed | ursaMaj0r/python-csc-125 | /Snippets/code-gym-1/compare_two_numbers.py | 280 | 4.09375 | 4 | # prompt
number = int(input("Enter a number: "))
anotherOne = int(input("Enter another number: "))
# response
if number > anotherOne:
print("{0} is greater than {1}.".format(number, anotherOne))
else:
print("{0} is less than or equal to {1}.".format(number, anotherOne))
|
29bef0572e2a646e9a639494d3f826ae66f34d93 | ursaMaj0r/python-csc-125 | /Snippets/intro-2/bombs_away.py | 283 | 4 | 4 | guess = input('Guess: ')
guesses = set()
while guess != "":
# check if in set
if guess not in guesses:
print("Hit {}".format(guess))
guesses.add(guess)
else:
print("You've chosen that square already")
# reprompt
guess = input('Guess: ')
|
cff034359b7f5bb521b3c92817db6cf01b32c61e | ursaMaj0r/python-csc-125 | /Snippets/code-gym-1/hello_hello_hello.py | 135 | 3.859375 | 4 | # prompt
word = input("What did you say? ")
print("{0}".format(word))
print("{0} {0}".format(word))
print("{0} {0} {0}".format(word))
|
398205a1297308d15a1dda69775740c131fbd721 | ursaMaj0r/python-csc-125 | /Snippets/intro-2/maths_mix.py | 175 | 4 | 4 | # input
num1 = int(input("Number 1: "))
num2 = int(input("Number 2: "))
# response
print(num1, "plus", num2, "is", (num1+num2))
print(num1, "times", num2, "is", (num1*num2))
|
3db2e66a966211e9d81e46d5a55cb44419ab4259 | ursaMaj0r/python-csc-125 | /Snippets/intro-1/up_the_downstair.py | 178 | 4.0625 | 4 | # input
input_steps = int(input("How many steps? "))
step = 1
# reponse
print("__")
while step < input_steps:
print(" "*2*step + "|_")
step += 1
print("_"*2*step + "|")
|
0b1a1ec8e2a093a30358e8d544fcb0eb7d734867 | slagtkracht/data-processing | /homework/week_1/moviescraper.py | 4,828 | 3.828125 | 4 | #!/usr/bin/env python
# Name: Rosa Slagt
# Student number: 11040548
"""
This script scrapes IMDB and outputs a CSV file with highest rated movies.
"""
import csv
from requests import get
from requests.exceptions import RequestException
from contextlib import closing
from bs4 import BeautifulSoup
TARGET_URL = "https://www.imdb.com/search/title?title_type=feature&release_date=2008-01-01,2018-01-01&num_votes=5000,&sort=user_rating,desc"
BACKUP_HTML = 'movies.html'
OUTPUT_CSV = 'movies.csv'
def extract_movies(dom):
"""
Extract a list of highest rated movies from DOM (of IMDB page).
Each movie entry should contain the following fields:
- Title
- Rating
- Year of release (only a number!)
- Actors/actresses (comma separated if more than one)
- Runtime (only a number!)
"""
actors = []
# a temporary list for the actors per movie
actors_movie = ''
title = []
movies = dom.find_all("a")
# to find the actors and titles of the movies
for movie in movies:
line = movie.get("href")
# titles are found after the =adv_li_tt
if "=adv_li_tt" in line:
# to empty the temporary list of actors
if len(title) > 0:
actors.append(actors_movie[:-2])
actors_movie = ''
title.append(movie.text)
# actors are found after the =adv_li_st
elif "=adv_li_st" in line:
# to add the actors to the temporary list
actors_movie += movie.string
# the actors are seperated with a comma
actors_movie += ', '
# to make sure the actors from the last movie are added
actors.append(actors_movie)
rating = []
# ratings are found after div in 'data-value'
ratings = dom.find_all("div")
for rates in ratings:
if 'data-value' in rates.attrs:
rating.append(rates.attrs['data-value'])
runtime = []
# runtime is foun in the class runtime
runtimes = dom.find_all("span", class_="runtime")
for minutes in runtimes:
# to exclude 'min'
minutes = minutes.string.split(" ")
minutes = minutes[0].strip("()")
runtime.append(minutes)
year = []
# releaseyear is found in the class lister-item-year
releaseyear = dom.find_all("span", class_="lister-item-year")
for years in releaseyear:
# to make sure it only contains digits
years = years.string.split(" ")
years = years[-1].strip("()")
year.append(years)
# to return one list with all the seperated lists
return [title, rating, year, actors, runtime]
def save_csv(outfile, movies):
"""
Output a CSV file containing highest rated movies.
"""
writer = csv.writer(outfile)
writer.writerow(['Title', 'Rating', 'Year', 'Actors', 'Runtime'])
# the list which contains the info per movie
for i in range(len(movies[0])):
# per movie the info
movies_list = []
# to add the i-th element of the different lists to the movies_list
movies_list.append(movies[0][i])
movies_list.append(movies[1][i])
movies_list.append(movies[2][i])
movies_list.append(movies[3][i])
movies_list.append(movies[4][i])
# to write the new list
writer.writerow(movies_list)
def simple_get(url):
"""
Attempts to get the content at `url` by making an HTTP GET request.
If the content-type of response is some kind of HTML/XML, return the
text content, otherwise return None
"""
try:
with closing(get(url, stream=True)) as resp:
if is_good_response(resp):
return resp.content
else:
return None
except RequestException as e:
print('The following error occurred during HTTP GET request to {0} : {1}'.format(url, str(e)))
return None
def is_good_response(resp):
"""
Returns true if the response seems to be HTML, false otherwise
"""
content_type = resp.headers['Content-Type'].lower()
return (resp.status_code == 200
and content_type is not None
and content_type.find('html') > -1)
if __name__ == "__main__":
# get HTML content at target URL
html = simple_get(TARGET_URL)
# save a copy to disk in the current directory, this serves as an backup
# of the original HTML, will be used in grading.
with open(BACKUP_HTML, 'wb') as f:
f.write(html)
# parse the HTML file into a DOM representation
dom = BeautifulSoup(html, 'html.parser')
# extract the movies (using the function you implemented)
movies = extract_movies(dom)
# write the CSV file to disk (including a header)
with open(OUTPUT_CSV, 'w', newline='') as output_file:
save_csv(output_file, movies) |
d1cd9f83c1fa3ab54128aacfbdf1bc25d2f3c14e | dvaage/PHYS202-S14 | /iPython/mymodule.py | 164 | 3.53125 | 4 | #demonstrationn of modules
def add_numbers(x,y):
"""add x and y"""
return x + y
def subtract_numbers(x,y):
"""substract y from x"""
return x - y |
cf4cb4471c6a75f14207422340fed49f049be790 | brayanarroyo/Automatas2 | /triangulo.py | 785 | 3.921875 | 4 | #Nombre: triangulos.py
#Objetivo: determinar tipo de triangulo con su perimetro
#Autor: Arroyo Chávez Brayan Alberto
#Fecha: 01/07/2019
def determinarTipo(l1,l2,l3):
if (l1 == l2 and l1 ==l3):
return "Triangulo equilatero"
elif ((l1 == l2 and l3!= l1) or (l1 == l3 and l1 !=l2) or (l2 == l3 and l2!=l1)):
return "Triangulo isósceles"
elif (l1!=l2 and l1!=l3 and l2!=l3):
return "Triangulo escaleno"
def main():
lado1 = float(input("Ingrese el primer lado"))
lado2 = float(input("Ingrese el segundo lado"))
lado3 = float(input("Ingrese el tercer lado"))
print("El tipo de traingulo ingresado es:", determinarTipo(lado1,lado2,lado3))
perimetro = lado1+lado2+lado3
print("Perimetro: ", perimetro)
if __name__ == "__main__":
main() |
16de2e7de7cbfa9a4e206e143a970ab581307345 | brayanarroyo/Automatas2 | /fibonacci.py | 373 | 3.890625 | 4 | #Nombre: fibonacci.py
#Objetivo: calcula la serie de fibonacci
#Autor: Arroyo Chávez Brayan Alberto
#Fecha: 01/07/2019
def fibonacci(n,f1,f2,b):
if(b==1):
print("1")
if (n!=1):
fn=f1 + f2
f1=f2
print(fn)
fibonacci(n-1,f1,fn,0)
def main():
num = int(input("Ingrese un numero"))
fibonacci(num,0,1,1)
if __name__ == "__main__":
main() |
16021ebd861f8d23781064101d52eba228a6f800 | mldeveloper01/Coding-1 | /Strings/0_Reverse_Words.py | 387 | 4.125 | 4 | """
Given a String of length S, reverse the whole string
without reversing the individual words in it.
Words are separated by dots.
"""
def reverseWords(s):
l = list(s.split('.'))
l = reversed(l)
return '.'.join(l)
if __name__ == "__main__":
t = int(input())
for i in range(t):
string = str(input())
result = reverseWords(string)
print(result) |
51814edad633fa6b47cde948d3e8aae77d38353d | mldeveloper01/Coding-1 | /Strings/4_Check_String_Rot.py | 450 | 3.75 | 4 | """
Given two strings a and b. The task is to find
if a string 'a' can be obtained by rotating another string 'b' by 2 places.
"""
def areSame(a, b):
x = a[2:]+a[:2]
y = a[-2]+a[:-2]
print(x, y)
if b == x or b == y:
return 1
else:
return 0
if __name__ == "__main__":
t = int(input())
for i in range(t):
a = str(input())
b = str(input())
result = areSame(a, b)
print(result) |
50e3656d0540cd6ed8fe02aa73d24923d1096862 | mldeveloper01/Coding-1 | /Strings/5_Roman_to_Int.py | 619 | 3.890625 | 4 | """
Given an string in roman no format (s) your task is to convert it to integer .Given an string in roman no format (s)
your task is to convert it to integer .
"""
def RomantoInt(s):
romans = {'I':1,'V':5,'X':10,'L':50,'C':100,'D':500,'M':1000}
value = romans[s[-1]]
for i in range(len(s) - 1):
if romans[s[i]] >= romans[s[i+1]]:
value += romans[s[i]]
else:
value -= romans[s[i]]
return value
pass
if __name__ == "__main__":
t = int(input())
for i in range(t):
string = str(input())
result = RomantoInt(string)
print(result) |
f56cd3726af9261337bf475cfc309c97ad0c2bd9 | mldeveloper01/Coding-1 | /sudoku.py | 1,807 | 3.78125 | 4 | # Solving Sudoku by Backtracking
import numpy as np
mat = []
# mat = [
# [7,8,0,4,0,0,1,2,0],
# [6,0,0,0,7,5,0,0,9],
# [0,0,0,6,0,1,0,7,8],
# [0,0,7,0,4,0,2,6,0],
# [0,0,1,0,5,0,9,3,0],
# [9,0,4,0,6,0,0,0,5],
# [0,7,0,3,0,0,0,1,2],
# [1,2,0,0,0,7,4,0,0],
# [0,4,9,2,0,6,0,0,7]
# ]
#Check implicit conditions
def isPossible(y, x, n):
#print("Checking Possibilities of "+ str(n) +" in position "+ str(y) +" "+ str(x) +"" )
global mat
# Check in the Row
for i in range(0,9):
if mat[y][i] == n:
return False
# Check in the Column
for i in range (0,9):
if mat[i][x] == n:
return False
# Check in the square
y0, x0 = (y//3) * 3, (x//3) * 3
for j in range(y0, y0+3):
for k in range(x0, x0+3):
if mat[j][k] == n:
return False
return True
def Solve():
# Backtracking
global mat
for y in range(9):
for x in range(9):
if(mat[y][x] == 0):
# print("Find a number position "+ str(y) +" "+ str(x) +"" )
for n in range(1, 10):
if(isPossible(y,x,n)):
# print("Found "+ str(n) +" in position "+ str(y) +" "+ str(x) +"" )
mat[y][x] = n
if Solve():
return True
mat[y][x] = 0
return False
for row in mat:
print(*row, end=' ')
exit()
#input("More?")
if __name__ == "__main__":
# print("Enter all the values of sudoku if empty fill them with 0")
T = int(input())
for t in range(T):
list1 = [int(item) for item in input().split()]
mat = [list1[i : i+9] for i in range(0, len(list1), 9)]
Solve() |
b872799531e4406c213af6582cf5cb706184186c | LiaoTingChun/python_fundamental | /ch9_sort.py | 483 | 3.765625 | 4 | # select students with 2nd high score
def second_highest(students):
if len(students) < 2:
print("Need at least 2 students!")
else:
sorted_score = sorted([score[1] for score in students], reverse = True)
second_score = sorted_score[1]
for student in students:
if student[1] == second_score:
print(student[0])
list1 = [['Jerry', 100], ['Justin', 84], ['Tom', 90], ['Allen', 92], ['Harsh', 90]]
second_highest(list1) |
52ce0b5051d3cf5643af5b121f2b1e5dc18ed52a | wayayastone/encrypt | /myencrypt.py | 8,069 | 4 | 4 | # -*- coding: utf-8 -*-
import sys
import pyDes
from pyDes import *
import binascii
#凯撒加密
def Caesar(text, x):
x = int(x)
encode = ''
for ch in text:
encode = encode + chr((ord(ch) - ord('a') + x) % 26 + ord('a'))
print(('右移'+str(x)+'位,Caesar密文为:'+encode).decode('utf-8'))
#凯撒解密
def DeCaesar(text):
i = 1
decode = ''
file = open(text[0:3] + '.txt', 'w+')
while i < 26:
decode = ''
for ch in text:
decode = decode + chr((ord(ch) - ord('a') - i + 26) % 26 + ord('a'))
file.write(decode + '\n')
i = i + 1
file.close()
print(('解密数据已写入文件' + text[0:3] + '.txt').decode('utf-8'))
#Virginia加密
def Virginia(text, x):
if len(text) != len(x):
print(('Error! Message:明文密钥长度不匹配').decode('utf-8'))
encode = ''
i = 0
while i < len(text):
encode = encode + chr((ord(x[i]) - ord('a') + ord(text[i]) - ord('a')) % 26 + ord('a'))
i = i + 1
print(('密钥:' + x + ', Virginia密文为:' + encode ).decode('utf-8'))
#Virginia解密
def DeVirginia(text, x):
if len(text) != len(x):
print(('Error! Message:密文密钥长度不匹配').decode('utf-8'))
code = ''
i = 0
while i < len(text):
code = code + chr((ord(text[i]) - ord(x[i]) + 52) % 26 + ord('a'))
i = i + 1
print(('密钥:' + x + ', Virginia明文为:' + code ).decode('utf-8'))
#DES加密,使用BCB模式
def DES(text, x):
data = text
#参数依次为,密钥,模式,iv,pad,pad模式
k = pyDes.des(x, pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)
d = k.encrypt(data)
print(('密钥为:' + x + ',DES(CBC)密文为:' + binascii.hexlify(d)).decode('utf-8'))
#DES解密
def DeDES(text, x):
d = binascii.unhexlify(text)
k = pyDes.des(x, pyDes.CBC, "\0\0\0\0\0\0\0\0", pad=None, padmode=pyDes.PAD_PKCS5)
encode = k.decrypt(d)
print(('密钥为:' + x + ',DES(CBC)明文为:' + encode).decode('utf-8'))
#加密模块,统一加密入口
#参数分别为,待加密字符串,是否加密,加密方式,密钥和待加密字符串所在文件
def encrypt(text, isencypt, fun, x, filename):
if filename != '': #若待加密字符串为空,则从文件中获取
with open(filename, 'r') as f:
text = f.readline().strip()
if fun == '0' and isencypt:
Caesar(text, x)
elif fun == '0' and isencypt == False:
DeCaesar(text)
elif fun == '1' and isencypt:
Virginia(text, x)
elif fun == '1' and isencypt == False:
DeVirginia(text, x)
elif fun == '2' and isencypt:
DES(text, x)
elif fun == '2' and isencypt == False:
DeDES(text, x)
#交互模式
def mutual():
fun = ''
text = ''
is_encrypt = True
x = ''
print("<========================MyEncrypt==============================>")
print("<===============================================================>")
print("<=========================Welcome!==============================>")
print("<===============================================================>")
print("<========================Now Begin!=============================>")
print("<===============================================================>")
print("_____________________________说明_________________________________".decode('utf-8'))
print("____此程序由来自NUIST的学生姜斐和张向阳共同完成,实现了凯撒加密,维吉尼".decode('utf-8'))
print("亚加密和DES加密功能及其对应的解密功能。完成时间2018年5月14日。".decode('utf-8'))
print("____本软件有命令行和交互模式两种测试方式,命令行模式提供文件的读入,具体".decode('utf-8'))
print("操作请在命令行模式下使用‘-h’参数查看。键入‘quit’或者‘bye’可退出交互。".decode('utf-8'))
while True:
fun = ''
text = ''
is_encrypt = True
x = ''
#等待输入加解密方式,三种分别对应0,1,2
while True:
fun = raw_input("请输入加解密方式(Caesar:0; Virginia:1; DES:2):".decode('utf-8').encode('gbk'))
if fun == '0' or fun == '1' or fun == '2':
break
if fun == 'bye' or fun == 'quit':
return
#等待选择加密或者解密,分别对应0,1
while True:
str_temp = raw_input("请选择加密或者解密:(加密:0; 解密:1)".decode('utf-8').encode('gbk'))
if str_temp == '0':
is_encrypt = True
break
elif str_temp == '1':
is_encrypt = False
break
if str_temp == 'bye' or fun == 'quit':
return
#等待输入加解密字符串
while True:
text = raw_input("请输入待加解密字符串:".decode('utf-8').encode('gbk'))
if text is not None:
break
if text == 'bye' or fun == 'quit':
return
#等待输入加解密所需密钥
while True:
x = raw_input("请输入密钥:".decode('utf-8').encode('gbk'))
if x is not None:
break
if x == 'bye' or fun == 'quit':
return
#交互模式不支持文件读取,置空
filename = ''
encrypt(text, is_encrypt, fun, x, filename)
#main方法
def main():
i = 1#用作外部参数下标
comm_list = sys.argv#获取外部参数列表
fun = '0' #表示加解密方式
text = '' #存放待加解密字符串
is_encrypt = True #标识是否加密或解密,true为加密,false为解密
x = '3' #存放密钥,此处3为凯撒加密的位移量,也可存放其他两种加密方式的密钥
filename = '' #指定从文件读取时的文件名
#交互模式
if len(comm_list) == 1:
mutual()
#命令行模式
else:
while i < len(comm_list):
if comm_list[i] == '-e': #加密,后面跟字符串
is_encrypt = True
text = comm_list[i+1]
elif comm_list[i] == '-x': #用于指定密钥,后跟字符串
x = comm_list[i+1]
elif comm_list[i] == '-d': #解密,后跟字符串
is_encrypt = False
text = comm_list[i+1]
elif comm_list[i] == '-t': #用于指定加解密方式,后跟数字
fun = comm_list[i+1]
elif comm_list[i] == '-ef': #加密,从文件中读取待操作字符串,后跟文件路径
is_encrypt = True
filename = comm_list[i+1]
elif comm_list[i] == '-df': #解密,从文件中读取待操作字符串,后跟文件路径
is_encrypt = False
filename = comm_list[i+1]
elif comm_list[i] == '-h': #帮助
if i == len(comm_list) - 1:
print('语法:myencrypt.py -[edh] parameter [-t] type'.decode('utf-8'))
print('\t-e\t对一串字符进行加密,参数为需要加密的字符'.decode('utf-8'))
print('\t-d\t对一串字符进行解密,参数为需要解密的字符'.decode('utf-8'))
print('\t-t\t指定加、解密所使用的方式'.decode('utf-8'))
print('\t\t0\t凯撒加密'.decode('utf-8'))
print('\t\t1\t维吉尼亚加密'.decode('utf-8'))
print('\t\t2\tDES加密'.decode('utf-8'))
print('\t-h\t获取帮助'.decode('utf-8'))
return
i = i + 2
#从命令行获取参数后,进入加密模块
encrypt(text, is_encrypt, fun, x, filename)
if __name__ == '__main__':
main() |
5da38300cd8c406f1b1b8a40bbfdf6b1e318f314 | HanhengHe/NeuralNetworks | /BasicNN/basicNN.py | 7,472 | 3.609375 | 4 | # -*- coding: UTF-8 -*-
import numpy as np
from math import exp
# basic neural network
# which means only one hidden layer available
# parameters
# active function
def Sigmoid(X):
return 1 / (1 + exp(-X))
# low memory require Predictor
class Predictor:
def __init__(self, labelsName, HLSize, outputSize, IH, IHThreshold, HO, HOThreshold):
self.labelsName = labelsName
self.HLSize = HLSize
self.outputSize = outputSize
self.IH = IH
self.IHThreshold = IHThreshold
self.HO = HO
self.HOThreshold = HOThreshold
self.labelsMat = np.mat(np.zeros((self.outputSize, self.outputSize)))
for i in range(self.outputSize):
self.labelsMat[i, self.outputSize - 1 - i] = 1
def predict(self, X):
# type check
if not isinstance(X, list):
raise NameError('X should be list')
# change type
X = np.mat(X)
b = np.mat(np.zeros((1, self.HLSize)))
yCaret = np.zeros((1, self.outputSize))
for j in range(self.HLSize):
b[0, j] = Sigmoid(((X * self.IH[:, j]) - self.IHThreshold[0, j]).tolist()[0][0])
for j in range(self.outputSize):
yCaret[0, j] = Sigmoid(((b[0, :] * self.HO[:, j]) - self.HOThreshold[0, j]).tolist()[0][0])
print(yCaret, end=':; ')
temp = (np.abs(yCaret - np.ones((1, self.outputSize)))).tolist()[0]
print(self.labelsName[temp.index(min(temp))])
return self.labelsName[temp.index(min(temp))]
# both dataList and labelsList should be list
# dataList like [[data00,data01,data02, ...],[data10,data11,data12, ...], ...]
# labelsList like [label_1, label_2, ...]
# learnRate usually in [0.01, 0.8]. an overSize learnRate will cause unstable learning process
# tol is the quit condition of loop
# HLSize means number of hidden layers. -1 allow computer to make a decision itself
class BasicNN:
def __init__(self, dataList, labelsList, learnRateIH=0.8, learnRateHO=0.8, errorRate=0.05, maxIter=20, alpha=1,
HLSize=-1, IHpar=-1, HOpar=-1):
# type check
if not isinstance(dataList, list):
raise NameError('DataList should be list')
if not isinstance(labelsList, list):
raise NameError('LabelsList should be list')
if len(dataList) != len(labelsList):
raise NameError('len(dataList) not equal to len(labelsList)')
if not isinstance(HLSize, int):
raise NameError('NumHL should be int')
self.dataMat = np.mat(dataList) # dataset
self.numData, dataLen = np.shape(self.dataMat) # record shape of dataset
# turn labels into 1 and 0
self.labelNames = list(set(labelsList)) # for remember the meanings of transformed labels
self.outputSize = len(self.labelNames)
self.labelsMat = np.mat(np.zeros((self.numData, self.outputSize)))
self.transferLabelsMat = np.mat(np.zeros((self.outputSize, self.outputSize)))
for i in range(self.outputSize):
self.transferLabelsMat[i, i] = 1
for i in range(len(labelsList)):
self.labelsMat[i, self.labelNames.index(labelsList[i])] = 1
print(self.labelNames)
# record parameter
self.learnRate = (learnRateIH, learnRateHO)
self.errorRate = errorRate
self.maxIter = maxIter
# number of input nur
self.inputSize = dataLen
# base on an exist formula
self.HLSize = int((self.inputSize + self.outputSize) ** 0.5 + alpha) if HLSize == -1 else HLSize
# init threshold
self.IHThreshold = np.mat(np.random.random((1, self.HLSize)))
self.HOThreshold = np.mat(np.random.random((1, self.outputSize)))
temp = 0
for i in range(len(dataList)):
temp += np.sum(self.dataMat[i, :])
temp = temp / len(dataList)
if IHpar == -1:
self.IHpar = 1 / temp
else:
self.IHpar = IHpar
if HOpar == -1:
self.HOpar = self.IHpar # not sure here
else:
self.HOpar = HOpar
# init IH(input-hiddenLayer) weight matrix and HO(hiddenLayer-output) weight matrix
# IH:(I*H); HO(H*O)
self.IH = np.mat(np.random.random((self.inputSize, self.HLSize))) * self.IHpar
self.HO = np.mat(np.random.random((self.HLSize, self.outputSize))) * self.HOpar
# train should be call after init
# since i wanna return a small size predictor
def train(self):
# start training
for _ in range(self.maxIter):
# calculate the error rate with the hold data set
# if small enough the quit the loop
if self.calculateErrorRate() <= self.errorRate:
break
# train with every data set
for i in range(self.numData):
# get output of hidden layer
b = np.mat(np.zeros((1, self.HLSize)))
for j in range(self.HLSize):
b[0, j] = Sigmoid(((self.dataMat[i, :] * self.IH[:, j]) - self.IHThreshold[0, j]).tolist()[0][0])
# get output of output layer
yCaret = np.mat(np.zeros((1, self.outputSize)))
for j in range(self.outputSize):
yCaret[0, j] = Sigmoid(((b * self.HO[:, j]) - self.HOThreshold[0, j]).tolist()[0][0])
# print(b)
# calculate g and e defined by watermelon book
# g [size:(1, self.outputSize)] and e [size(1, self.HLSize)] should be narray
g = yCaret.getA() * (np.ones((1, self.outputSize)) - yCaret).getA() * (
self.labelsMat[i, :] - yCaret).getA()
e = b.getA() * (np.ones((1, self.HLSize)) - b).getA() * ((self.HO * np.mat(g).T).T.getA()) # !!
# upgrade weight IH
self.IH = self.IH + self.learnRate[0] * self.dataMat[i, :].T * np.mat(e)
# upgrade weight HO
self.HO = self.HO + self.learnRate[1] * b.T * np.mat(g) # not sure
# upgrade threshold
self.IHThreshold = self.IHThreshold - self.learnRate[0] * e
self.HOThreshold = self.HOThreshold - self.learnRate[1] * g
return Predictor(self.labelNames, self.HLSize, self.outputSize, self.IH, self.IHThreshold, self.HO,
self.HOThreshold)
def calculateErrorRate(self):
# calculate the error rate
# base on matrix IH and HO
errorCounter = 0
for i in range(self.numData):
# get the output of j-th neuron in hidden layer(after active function)
b = np.mat(np.zeros((1, self.HLSize)))
for j in range(self.HLSize):
b[0, j] = Sigmoid(((self.dataMat[i, :] * self.IH[:, j]) - self.IHThreshold[0, j]).tolist()[0][0])
# get output of output layer
yCaret = np.mat(np.zeros((1, self.outputSize)))
for j in range(self.outputSize):
yCaret[0, j] = Sigmoid(((b * self.HO[:, j]) - self.HOThreshold[0, j]).tolist()[0][0])
temp = (np.abs(yCaret - np.ones((1, self.outputSize)))).tolist()[0]
if self.transferLabelsMat[temp.index(min(temp))].tolist()[0] != self.labelsMat[i].tolist()[0]:
errorCounter += 1
print(errorCounter / self.numData)
return errorCounter / self.numData
|
a1c860865ec2611b532dcf6783432e253a002c00 | piyushaga27/Criminal-record | /criminal_record.py | 3,690 | 3.890625 | 4 | #criminal data
import pandas as pd
import matplotlib.pyplot as plt
df=pd.read_csv('criminal_data.csv',sep=',')
rew=list(df['reward'])
nme=list(df['name'])
city=list(df['city'])
city_dict={}
for i in city:
city_dict[i]=city.count(i)
def allData():
print('All Data is:')
print('='*50)
print(df)
def cityBasis():
print('Detais on City basis')
print('='*50)
loc=input('ENTER CITY :')
for b in city:
if loc.upper()==b:
print('Details are as follows . . . ')
print(df[df['city']==loc.upper()])
break
else:
print('City not Found')
def rewardBasis():
print('='*50)
print('Details on Reward Basis:')
m='''1. REWARD GREATER THAN
2. REWARD LESSER THAN
3. REWARD EQUAL TOO
4. RETURN TO MAIN MENU'''
print(m)
c=input('ENTER YOUR CHOICE :')
if c=='1':
print('='*50)
r=int(input('Enter Greater Than Reward Amount :'))
print('='*50)
print('Details are as follows :')
print(df[df['reward']>=r])
elif c=='2':
print('='*50)
r=int(input('Enter Lesser Than Reward Amount :'))
print('='*50)
print('Details are as follows :')
print(df[df['reward']<=r])
elif c=='3':
print('='*50)
r=int(input('Enter Reward Amount :'))
print('='*50)
print('Details are as follows :')
print(df[df['reward']==r])
elif c=='4':
pass
elif c=='':
print('user input is required')
else:
print('Invalid Character')
def nameBasis():
print('='*50)
print('Details from Name . . .')
print('='*50)
nm=input('Enter Name of Criminal :')
print('='*50)
for x in nme:
if nm.upper()==x:
print(df[df['name']==nm.upper()])
break
else:
print('Name not Found')
def menu():
print('Criminal Data')
print('''1. SHOW ALL DATA
2. INFORMATION ON CITY BASIS
3. IMFORMATION ON REWARD BASIS
4. DETAILS FROM NAME
5. CHARTS SECTION
6. EXIT''')
def chartSection():
print('='*50)
print('CHARTS SECTION')
mnu='''1. SHOW CHART ACCORDING TO CITY BASIS
2. SHOW CHART ACCORDING TO REWARD BASIS
3. MAIN MENU'''
print(mnu)
cho=input('ENTER YOUR CHOICE :')
print('='*50)
if cho=='1':
print('CHART ON CITY BASIS')
plt.bar(city_dict.keys(),city_dict.values(),color=['r','g','b','y'])
plt.title('Criminal details on City basis')
plt.ylabel('Number Of Criminal')
plt.xlabel('City')
print('Chart Displayed Sucessfully. . .')
print('='*50)
plt.show()
elif cho=='2':
print('CHART ON REWARD BASIS')
plt.hist(rew,bins=10,color='g')
plt.title('Criminal Details on Reward basis')
plt.xlabel('Rewards')
plt.ylabel('Number of Criminal')
print('Histogram Displayed Sucessfully. . .')
print('='*50)
plt.show()
elif cho=='3':
pass
a=True
while a:
print('='*50)
menu()
ch=(input('ENTER YOUR CHOICE :'))
if ch=='1':
allData()
elif ch=='2':
cityBasis()
elif ch=='3':
rewardBasis()
elif ch=='4':
nameBasis()
elif ch=='5':
chartSection()
elif ch=='6':
print('='*50)
print('Thank You . . .')
print('='*50)
a=False
elif ch=='':
print('='*50)
print('User Input is required:')
else:
print('='*50)
print('Invalid Character')
|
13563d927a4adb1a45b0bcf7b9501df715a8b801 | agalyaswami/datastructures | /delete singly.py | 1,375 | 3.71875 | 4 | class node:
def __init__(self,data):
self.data=data
self.next=None
class slinkedlist:
def __init__(self):
self.head=None
def atbeginning(self,data_in):
newnode=node(data_in)
newnode.next=self.head
self.head=newnode
def removenode(self,removekey):
headval=self.head
if(headval is not None):
if(headval.data==removekey):
print("deltion at head")
self.head=headval.next
return
else:
print("the list is empty")
return
while(headval is not None):
if headval.data==removekey:
break
prev=headval
headval=headval.next
else:
print("the key is not available")
if(headval==None):
return
prev.next=headval.next
headval=None
def llistprint(self):def __init__(self,data):
self.data=data
self.next=None
printval=self.head
while(printval):
print(printval.data)
printval=printval.next
llist=slinkedlist()
llist.removenode("tue")
llist.atbeginning("mon")
llist.atbeginning("tue")
llist.atbeginning("wed")
llist.atbeginning("thu")
llist.llistprint()
print("after removal of fri")
llist.removenode("fri")
llist.llistprint()
#llist.llistprint()
|
6505aa61ab8755e17c720c24691524ede1890632 | TrevorCap/Python | /PyBank/Main.py | 1,605 | 3.5625 | 4 | import os
import csv
csvpath = os.path.join('budget_data.csv')
with open(csvpath, newline="") as budget:
csvreader = csv.reader(budget, delimiter=",")
budget.readline()
total = 0
rows = 0
MaxV = 0
MaxD = ""
MinV = 0
MinD = ""
change = 0
Taverage = 0
val1 = 0
val2 = 0
for row in csv.reader(budget):
total += int(row[1])
rows += 1
val1 = int(row[1])
change = val1 - val2
if rows > 1:
Taverage += change
if change > MaxV:
MaxV = change
MaxD = row[0]
if change < MinV:
MinV = change
MinD = row[0]
val2 = val1
Taverage = round(Taverage/(rows-1), 2)
print("Financial Analysis", file=open('Output.txt', "a"))
print("-----------------------------------------------------", file=open('Output.txt', "a"))
print("Total Months: ", rows, file=open('Output.txt', "a"))
print("Total: $", total, file=open('Output.txt', "a"))
print("Average Change: $", Taverage, file=open('Output.txt', "a"))
print("Greatest increase in profits: ", MaxD, " ($", MaxV, ")", file=open('Output.txt', "a"))
print("Greatest decrease in profits: ", MinD, " ($", MinV, ")", file=open('Output.txt', "a"))
print("Financial Analysis")
print("-------------------------------")
print("Total Months: ")
print("Total: $")
print("Average Change: $", Taverage)
print("Greatest increase in profits: ", MaxD, " ($", MaxV, ")")
print("Greatest decrease in profits: ", MinD, " ($", MinV, ")") |
ff75931a0dd9ed44b400bd128f0b696a912f2a6f | SimplyAhmazing/go-board-game | /tests/test_piece.py | 2,368 | 3.640625 | 4 | import unittest
from utils import create_board_from_str
from colors import Color
from piece import Piece
class PieceTestCase(unittest.TestCase):
def setUp(self):
self.white_piece = Piece(Color.white, (0,0), None)
self.black_piece = Piece(Color.black, (0,0), None)
def test_piece_as_str(self):
self.assertEqual("B", str(self.black_piece))
self.assertEqual("W", str(self.white_piece))
def test_piece_get_neighbors(self):
expected = sorted([(-1, 0), (1, 0), (0, -1), (0, 1)])
result = sorted(self.white_piece.get_neighbors())
self.assertListEqual(expected, result)
def test_is_ally(self):
self.assertFalse(self.white_piece.is_ally(self.black_piece))
def test_is_enemy(self):
self.assertTrue(self.white_piece.is_enemy(self.black_piece))
class PieceIsDeadAlgorithmTestCase(unittest.TestCase):
def test_one_piece_on_board(self):
board_str = """
- - - - -
- - - - -
- - W - -
- - - - -
- - - - -
"""
board = create_board_from_str(board_str)
p = board[2][2]
self.assertFalse(p.is_dead())
def test_one_piece_surrounded(self):
board = """
- - - - -
- - B - -
- B W B -
- - B - -
- - - - -
"""
board = create_board_from_str(board)
p = board[2][2]
self.assertTrue(p.is_dead())
def test_two_pieces_partially_surrouned(self):
board = """
- - - - -
- - B - -
- B W W B
- - B B -
- - - - -
"""
board = create_board_from_str(board)
p = board[2][2]
self.assertFalse(p.is_dead())
def test_two_pieces_completely_surrouned(self):
board = """
- - - - -
- - B B -
- B W W B
- - B B -
- - - - -
"""
board = create_board_from_str(board)
p = board[2][2]
self.assertTrue(p.is_dead())
def test_multiple_pieces_completely_surrouned(self):
board = """
- - - B - -
- - B W B -
- B W W B -
- B W W B -
- - B W B -
- - - B - -
"""
board = create_board_from_str(board)
p = board[2][2]
self.assertTrue(p.is_dead())
if __name__ == '__main__':
unittest.main()
|
f02766bc5853123e4f99c4501e4dce2506fe6a11 | adamgreig/basebandboard | /gateware/bbb/rng.py | 6,957 | 3.546875 | 4 | """
Generate random numbers.
Copyright 2017 Adam Greig
"""
import numpy as np
from functools import reduce
from operator import xor
from migen import Module, Signal
from migen.sim import run_simulation
class LUTOPT(Module):
"""
Generates uniform random integers according to the given binary recurrence.
Based on the paper "High Quality Uniform Random Number Generation Using LUT
Optimised State-transition Matrices" by David B. Thomas and Wayne Luk.
"""
def __init__(self, a, init=1):
"""
Initialise with a recurrence matrix `a` that has shape k by k.
The initial state is set to `init`.
Outputs `x`, which is k bits wide and uniformly distributed,
on each clock cycle.
"""
self.x = Signal(a.shape[0], reset=init)
self.a = a
self.k = a.shape[0]
# Each row of `a` represents the input connections for each element of
# state. Each LUT thus XORs those old state bits together to produce
# the new state bit.
for idx, row in enumerate(a):
taps = np.nonzero(row)[0].tolist()
self.sync += self.x[idx].eq(reduce(xor, [self.x[i] for i in taps]))
@classmethod
def from_packed(cls, packed, init=1):
"""
Creates a new LUTOPT from a packed representation: a list of k lists,
which each contains the position of the 1 entries for that row.
The initial state is set to `init`.
"""
k = len(packed)
a = np.zeros((k, k), dtype=np.uint8)
for row in range(k):
for idx in packed[row]:
a[row, idx] = 1
return cls(a, init)
class CLTGRNG(Module):
"""
Generates a Gaussian-distributed random integer by tree-summing the bits
of a large uniform random integer.
The result is generated on each clock cycle, and has mean 0 (as a signed
integer) and variance equal to 2**(log2(n)-2), where n is the width of the
input URNG.
Outputs `x` each clock cycle, which is signed, has width log2(n),
is Gaussian-distributed, and is log2(n) clock cycles delayed from urng.
"""
def __init__(self, urng):
"""
`urng` must be provided, a n-bit wide uniform RNG module with output x,
where n is a power of two.
"""
n = urng.x.nbits
logn = int(np.log2(n))
self.x = Signal((logn, True))
self.submodules.urng = urng
# We have logn levels of registers (including the output).
# The first level contains n/2 Signals, each 2 bits wide, and is
# computed directly from the input signal. The next level is n/4
# Signals, each 3 bits wide, and so on until the final level,
# which has just 1 Signal which is logn bits wide (the output).
self.levels = [[] for _ in range(logn)]
for level in range(logn):
level_n = 2**(logn - level - 1)
level_bits = level+2
self.levels[level] = [Signal((level_bits, True))
for _ in range(level_n)]
# Input level computations.
# Each 2-bit entry in level0 is the difference of the two 1-bit
# entries in the input from the URNG.
for idx in range(len(self.levels[0])):
a, b = 2*idx, 2*idx+1
self.sync += self.levels[0][idx].eq(urng.x[a] - urng.x[b])
# Remaining level computations.
for level in range(1, logn):
for idx in range(len(self.levels[level])):
a, b = 2*idx, 2*idx + 1
self.sync += self.levels[level][idx].eq(
self.levels[level-1][a] - self.levels[level-1][b])
# Output
self.comb += self.x.eq(self.levels[-1][0])
def test_lutopt():
"""Tests that the HDL matches the normal recurrence implementation."""
# Generate a suitable recurrence matrix
packed = [
[8, 11, 12, 13], [2, 6, 14], [0, 3, 4, 7], [1, 5, 9, 15], [5, 10, 13],
[0, 2, 3, 6], [10, 12, 15], [4, 7, 9, 11], [0, 1, 8, 14],
[5, 9, 10, 12], [1, 7, 13, 15], [2, 4, 14], [3, 6, 8], [0, 8, 11, 15],
[6, 10, 11, 12], [2, 5, 7, 13]]
lutopt = LUTOPT.from_packed(packed, init=1)
a, k = lutopt.a, lutopt.k
def tb():
# x represents our state, k bits wide
x = np.zeros((k, 1), dtype=np.uint8)
# Initialise to the same initial state as the LUTOPT
x[0] = 1
# Check the first 100 outputs
for _ in range(100):
# Run the hardware for one clock
yield
# Run our recurrence, convert to an integer
x = np.mod(np.dot(a, x), 2)
x_int = int(''.join(str(xi) for xi in x[::-1].flatten()), 2)
assert (yield lutopt.x) == x_int
run_simulation(lutopt, tb())
def test_cltgrng():
"""Tests that the CLTGRNG matches the Python implementation."""
packed = [
[5, 15, 19], [11, 25, 30, 31], [10, 17, 21, 28], [1, 3, 23],
[2, 7, 18, 29], [9, 14, 20, 27], [4, 8, 16, 26], [0, 6, 12, 24],
[13, 22, 26], [10, 14, 24, 28], [2, 13, 15, 19], [4, 6, 9, 27],
[3, 17, 23, 25], [12, 16, 22, 30], [0, 1, 7, 8], [11, 18, 20, 31],
[2, 5, 21, 29], [0, 1, 14, 17], [9, 22, 25], [3, 18, 28, 31],
[7, 21, 24, 29], [4, 5, 6, 16], [8, 13, 20], [11, 15, 19, 26],
[10, 12, 23, 30], [5, 10, 13, 27], [2, 8, 22, 25], [7, 12, 14, 21],
[3, 15, 24, 31], [4, 6, 19, 23], [17, 28, 30], [16, 18, 20]]
urng = LUTOPT.from_packed(packed, init=1)
grng = CLTGRNG(urng)
n = len(packed)
logn = int(np.log2(n))
def tb():
# Run a few cycles of the URNG to warm it up and fill up the
# register hierarchy of the GRNG.
for _ in range(2*logn):
yield
# Check first 100 outputs match
results = []
for i in range(100):
# Run the hardware simulation for one clock cycle
yield
# Fetch the URNG value and compute the corresponding Gaussian.
# Note that we bit-reverse the URNG to correspond to the bit
# indexing of the hardware.
x = np.array([int(x) for x in
bin(int((yield urng.x)))[2:].rjust(n, "0")[::-1]])
for level in range(logn):
level_n = 2**(logn - level)
y = np.zeros(level_n//2, dtype=np.int16)
for pair in range(0, level_n, 2):
y[pair//2] = x[pair] - x[pair+1]
x = y
results.append(x[0])
# Convert grng.x into signed form
grng_x = (yield grng.x)
grng_x = grng_x if grng_x < 2**31 else (grng_x - 2**32)
# Once we've collected enough results to compensate for the
# clock delay, start comparing numbers.
if len(results) > logn:
assert grng_x == results[-logn-1]
run_simulation(grng, tb())
|
c1980126338e9c410c4c4d7cf46613a25bddba5f | rolkotaki/PythonForML | /loading_data/load_csv.py | 438 | 3.65625 | 4 | import pandas
path = 'fruits.csv'
# loading the CSV file
dataframe = pandas.read_csv(filepath_or_buffer=path,
sep=',',
skip_blank_lines=True) # header=None
# It has many parameters!
print(dataframe.head(2)) # returns the first n rows; -1 --> except the last one
print("****************")
print(dataframe.tail(1)) # last n rows
print("****************")
print(dataframe)
|
f4790912e0569ccd3954c0208c88477ecc6f33d4 | rolkotaki/PythonForML | /logistic_regression.py | 5,554 | 3.90625 | 4 | import numpy as np
from sklearn.linear_model import LogisticRegression, LogisticRegressionCV
from sklearn import datasets
from sklearn.preprocessing import StandardScaler
# Training a Binary Classifier
iris = datasets.load_iris()
features = iris.data[:100, :]
target = iris.target[:100]
# Standardize features
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)
# Create logistic regression object
logistic_regression = LogisticRegression(random_state=0)
# Train model
model = logistic_regression.fit(features_standardized, target)
# Create new observation
new_observation = [[.5, .5, .5, .5]]
# Predict class
print(model.predict(new_observation))
# View predicted probabilities
print(model.predict_proba(new_observation)) # it has 18.8% chance of being class 0 and 81.1% chance of being class 1
# Despite having “regression” in its name, a logistic regression is actually a widely used binary classifier
# (i.e., the target vector can only take two values).
# Training a Multiclass Classifier
# Given more than two classes, you need to train a classifier model
iris = datasets.load_iris()
features = iris.data
target = iris.target
# Standardize features
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)
# Create one-vs-rest logistic regression object
logistic_regression = LogisticRegression(random_state=0, multi_class="ovr") # OVR or MLR
# Train model
model = logistic_regression.fit(features_standardized, target)
# On their own, logistic regressions are only binary classifiers, meaning they cannot handle target vectors with more
# than two classes. However, two clever extensions to logistic regression do just that. First, in one-vs-rest logistic
# regression (OVR) a separate model is trained for each class predicted whether an observation is that class or not
# (thus making it a binary classification problem). It assumes that each classification problem (e.g., class 0 or not)
# is independent.
# Reducing Variance Through Regularization
iris = datasets.load_iris()
features = iris.data
target = iris.target
# Standardize features
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)
# Create decision tree classifier object
logistic_regression = LogisticRegressionCV(penalty='l2', Cs=10, random_state=0, n_jobs=-1)
# Train model
model = logistic_regression.fit(features_standardized, target)
# Regularization is a method of penalizing complex models to reduce their variance. Specifically, a penalty term is
# added to the loss function we are trying to minimize, typically the L1 and L2 penalties.
# Higher values of α increase the penalty for larger parameter values (i.e., more complex models). scikit-learn follows
# the common method of using C instead of α where C is the inverse of the regularization strength: C=1α. To reduce
# variance while using logistic regression, we can treat C as a hyperparameter to be tuned to find the value of C that
# creates the best model. In scikit-learn we can use the LogisticRegressionCV class to efficiently tune C.
# LogisticRegressionCV’s parameter, Cs, can either accept a range of values for C to search over (if a list of floats
# is supplied as an argument) or if supplied an integer, will generate a list of that many candidate values drawn from
# a logarithmic scale between –10,000 and 10,000.
# Training a Classifier on Very Large Data
iris = datasets.load_iris()
features = iris.data
target = iris.target
# Standardize features
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)
# Create logistic regression object
logistic_regression = LogisticRegression(random_state=0, solver="sag")
# Train model
model = logistic_regression.fit(features_standardized, target)
# scikit-learn’s LogisticRegression offers a number of techniques for training a logistic regression, called solvers.
# Most of the time scikit-learn will select the best solver automatically for us or warn us that we cannot do something
# with that solver. However, there is one particular case we should be aware of.
# stochastic average gradient descent allows us to train a model much faster than other solvers when our data is very
# large. However, it is also very sensitive to feature scaling, so standardizing our features is particularly important.
# We can set our learning algorithm to use this solver by setting solver='sag'.
# Handling Imbalanced Classes
# You need to train a simple classifier model
iris = datasets.load_iris()
features = iris.data
target = iris.target
# Make class highly imbalanced by removing first 40 observations
features = features[40:, :]
target = target[40:]
# Create target vector indicating if class 0, otherwise 1
target = np.where((target == 0), 0, 1)
# Standardize features
scaler = StandardScaler()
features_standardized = scaler.fit_transform(features)
# Create decision tree classifier object
logistic_regression = LogisticRegression(random_state=0, class_weight="balanced")
# Train model
model = logistic_regression.fit(features_standardized, target)
# Like many other learning algorithms in scikit-learn, LogisticRegression comes with a built-in method of handling
# imbalanced classes. If we have highly imbalanced classes and have not addressed it during preprocessing, we have the
# option of using the class_weight parameter to weight the classes to make certain we have a balanced mix of each class.
# Specifically, the balanced argument will automatically weigh classes inversely proportional to their frequency.
|
01bc8bc47ea5ecc7656e731b5ec007049efc4888 | faantoniadou/Computer-Simulation | /CP1.py | 2,962 | 3.96875 | 4 | '''
Polynomial Class
'''
from operator import add
class Polynomial(object):
coeffs = []
def __init__(self, coeffs):
"""
Constructor to form a polynomial
"""
self.coeffs = coeffs
def order(self):
"""
Method to return order of polynomial
"""
return len(self.coeffs) - 1
def polyadd(self, other):
"""
Method to add two polynomials and return as new polynomial
"""
# conditions for lists of different lengths
if len(self.coeffs) > len(other.coeffs):
for i in range(len(other.coeffs), len(self.coeffs)):
other.coeffs.insert(i, 0)
elif len(self.coeffs) < len(other.coeffs):
for i in range(len(self.coeffs), len(other.coeffs)):
self.coeffs.insert(i, 0)
new_coeffs = list(map(add, self.coeffs, other.coeffs))
return Polynomial(new_coeffs)
def derivative(self):
"""
Method to calculate the derivative
"""
derivative_coeffs = [] #empty list for new coefficients
for i in range(1,len(self.coeffs) - 1 ):
# loop to append coefficients of derivative
derivative = self.coeffs[i] * i
derivative_coeffs.append(derivative)
return Polynomial(derivative_coeffs)
def antiderivative(self):
"""
Method to calculate the antiderivative
"""
antiderivative_coeffs = [] #empty list for new coefficients
for k in range(0, len(self.coeffs)):
# loop to append coefficients of antiderivative
antiderivative = float(self.coeffs[k]/(k + 1))
antiderivative_coeffs.append(antiderivative)
antiderivative_coeffs.insert(0,2) #insert constant of integration
return Polynomial(antiderivative_coeffs)
def printPol(self):
"""
Method to print a string representation of the polynomial
"""
printed = str()
for m in range(1, len(self.coeffs) ):
if self.coeffs[m] != 0: #omit terms with coefficient 0
#coefficient sign conditions
if self.coeffs[m] > 0:
printed += (" + ")
elif self.coeffs[m] < 0:
printed += (" - ")
#conditions to omit printing 1x
if self.coeffs[m] != 1 and self.coeffs[m] != -1:
printed += (str(abs(self.coeffs[m]))) #take absolute value to avoid double signs
#conditions to omit printing x^1
if m == 1:
printed += ("x")
elif m != 1:
printed += ("x^" + str(m))
return (str(self.coeffs[0]) + str(printed)) |
0053bde8153d3559f824aed6a017c528410538ea | JaredD-SWENG/beginnerpythonprojects | /3. QuadraticSolver.py | 1,447 | 4.1875 | 4 | #12.18.2017
#Quadratic Solver 2.4.6
'''Pseudocode: The program is designed to solve qudratics. It finds it's zeros and vertex.
It does this by asking the user for the 'a', 'b', and 'c' of the quadratic.
With these pieces of information, the program plugs in the variables into the quadratic formula and the formula to solve for the vertex.
It then ouputs the information solved for to the user.'''
import math
print('''Welcome to Quadratic Solver!
ax^2+bx+c
''')
def FindVertexPoint(A,B,C):
if A > 0:
x_vertex = (-B)/(2*A)
y_vertex = (A*(x_vertex**2))+(B*x_vertex)+C
return('Minimum Vertex Point: '+str(x_vertex)+', '+str(y_vertex))
elif A < 0:
x_vertex = (-B)/(2*A)
y_vertex = (A*(x_vertex**2))+(B*x_vertex)+C
return('Maximum Vertex Point: '+str(x_vertex)+', '+str(y_vertex))
def QuadraticFormula(A,B,C):
D = (B**2)-(4*(A*C))
if D < 0:
return('No real solutions')
elif D == 0:
x = (-B+math.sqrt((B**2)-(4*(A*C))))/(2*A)
return('One solution: '+str(x))
else:
x1 = (-B+math.sqrt((B**2)-(4*(A*C))))/(2*A)
x2 = (-B-math.sqrt((B**2)-(4*(A*C))))/(2*A)
return('Solutions: '+str(x1)+' or '+str(x2))
a = float(input("Quadratic's a: "))
b = float(input("Quadratic's b: "))
c = float(input("Quadratic's c: "))
print('')
print(QuadraticFormula(a,b,c))
print(FindVertexPoint(a,b,c))
|
b8d23be3ed6ea8a2c50c939df0c15b80269be0da | LajosNeto/algorithms-n-more | /data-structures-algorithms/data-structures/stack/python/stack.py | 1,313 | 4.09375 | 4 | """
Stack data structure implementation based on linked lists
"""
# Author:
# Lajos Neto <lajosnetogit@gmail.com>
class _Node:
"""
Simple node used for representing values
inside the stack.
"""
def __init__(self, value):
self.value = value
self.next = None
class Stack:
"""
Stack data structure.
"""
def __init__(self):
self._top = None
self._bottom = None
self._size = 0
def __iter__(self):
iterator = self._top
while True:
if iterator is None:
return
yield iterator.value
iterator = iterator.next
def empty(self):
"""Check if the list is empty"""
return self._size == 0
def push(self, value):
"""Push new value on top of the stack"""
new_node = _Node(value)
if self.empty():
self._top = new_node
self._bottom = new_node
else:
new_node.next = self._top
self._top = new_node
self._size += 1
def pop(self):
"""Pop value on top of the stack"""
if self.empty():
raise IndexError("Empty stack")
pop_value = self._top.value
self._top = self._top.next
self._size -= 1
return pop_value |
21ebc7c9197a4effdaa167dd49d107d463b230d2 | LajosNeto/algorithms-n-more | /data-structures-algorithms/data-structures/tree/bst/python/bst_test.py | 6,355 | 3.578125 | 4 | # bst_test.py
#
# Binary Tree (BST) implementation tests
#
# author Lajos Onodi Neto
import sys
import unittest
from bst import Bst
class BstTest(unittest.TestCase):
def __init__(self, *args, **kwargs):
super(BstTest, self).__init__(*args, **kwargs)
self.bst = Bst()
def test_insert(self):
self.bst.insert(10)
self.bst.insert(5)
self.bst.insert(15)
self.assertTrue(self.bst.insert(20))
self.assertTrue(self.bst.insert(2))
self.assertTrue(self.bst.insert(12))
self.assertFalse(self.bst.insert(5))
def test_size_counter(self):
self.bst.insert(10)
self.bst.insert(5)
self.bst.insert(15)
self.assertEqual(self.bst._size, 3)
self.assertTrue(self.bst.insert(20))
self.assertTrue(self.bst.insert(1))
self.assertEqual(self.bst._size, 5)
def test_display(self):
self.bst.insert(10)
self.bst.insert(5)
self.bst.insert(15)
print("\nInorder traversal :")
self.bst.dfs_inorder()
print("Preorder traversal :")
self.bst.dfs_preorder()
print("Postorder traversal :")
self.bst.dfs_postorder()
def test_bfs(self):
self.bst.insert(10)
self.bst.insert(5)
self.bst.insert(15)
self.bst.insert(6)
self.bst.insert(2)
self.bst.insert(1)
self.bst.insert(3)
self.bst.insert(20)
self.bst.insert(12)
self.bst.insert(14)
self.bst.insert(13)
self.bst.insert(21)
self.bst.insert(22)
self.bst.insert(23)
bfs_order = self.bst.bfs()
self.assertEqual(bfs_order, [10,5,15,2,6,12,20,1,3,14,21,13,22,23])
def test_node_count(self):
self.bst.insert(10)
self.bst.insert(5)
self.bst.insert(15)
self.bst.insert(6)
self.assertEqual(self.bst.node_count(), 4)
self.bst.insert(2)
self.assertEqual(self.bst.node_count(), 5)
self.bst.insert(1)
self.bst.insert(3)
self.bst.insert(20)
self.bst.insert(12)
self.bst.insert(14)
self.assertEqual(self.bst.node_count(), 10)
self.bst.insert(13)
self.bst.insert(21)
self.assertEqual(self.bst.node_count(), 12)
self.bst.insert(22)
self.bst.insert(23)
self.assertEqual(self.bst.node_count(), 14)
def test_min(self):
self.bst.insert(10)
self.bst.insert(5)
self.bst.insert(15)
self.assertEqual(self.bst.min(), 5)
self.bst.insert(20)
self.bst.insert(12)
self.bst.insert(14)
self.assertEqual(self.bst.min(), 5)
self.bst.insert(13)
self.bst.insert(21)
self.assertEqual(self.bst.min(), 5)
self.bst.insert(22)
self.bst.insert(23)
self.bst.insert(6)
self.assertEqual(self.bst.min(), 5)
self.bst.insert(2)
self.assertEqual(self.bst.min(), 2)
self.bst.insert(1)
self.assertEqual(self.bst.min(), 1)
self.bst.insert(3)
self.assertEqual(self.bst.min(), 1)
def test_max(self):
self.bst.insert(10)
self.bst.insert(5)
self.bst.insert(15)
self.bst.insert(6)
self.assertEqual(self.bst.max(), 15)
self.bst.insert(2)
self.bst.insert(1)
self.bst.insert(3)
self.bst.insert(20)
self.assertEqual(self.bst.max(), 20)
self.bst.insert(12)
self.bst.insert(14)
self.assertEqual(self.bst.max(), 20)
self.bst.insert(13)
self.bst.insert(21)
self.assertEqual(self.bst.max(), 21)
self.bst.insert(22)
self.assertEqual(self.bst.max(), 22)
self.bst.insert(23)
self.assertEqual(self.bst.max(), 23)
def test_height(self):
self.bst.insert(10)
self.assertEqual(self.bst.height(), 0)
self.bst.insert(5)
self.bst.insert(15)
self.assertEqual(self.bst.height(), 1)
self.bst.insert(6)
self.bst.insert(2)
self.assertEqual(self.bst.height(), 2)
self.bst.insert(1)
self.bst.insert(3)
self.assertEqual(self.bst.height(), 3)
self.bst.insert(20)
self.bst.insert(12)
self.bst.insert(14)
self.bst.insert(13)
self.assertEqual(self.bst.height(), 4)
self.bst.insert(21)
self.bst.insert(22)
self.bst.insert(23)
self.assertEqual(self.bst.height(), 5)
def test_successor(self):
self.bst.insert(30)
self.assertEqual(self.bst.successor(30), -1)
self.bst.insert(15)
self.assertEqual(self.bst.successor(15), 30)
self.bst.insert(20)
self.assertEqual(self.bst.successor(20), 30)
self.bst.insert(18)
self.bst.insert(22)
self.assertEqual(self.bst.successor(20), 22)
self.assertEqual(self.bst.successor(22), 30)
self.bst.insert(10)
self.assertEqual(self.bst.successor(10), 15)
self.bst.insert(11)
self.assertEqual(self.bst.successor(11), 15)
self.bst.insert(6)
self.assertEqual(self.bst.successor(6), 10)
self.bst.insert(4)
self.assertEqual(self.bst.successor(4), 6)
self.bst.insert(1)
self.assertEqual(self.bst.successor(1), 4)
self.bst.insert(5)
self.assertEqual(self.bst.successor(5), 6)
self.bst.insert(9)
self.assertEqual(self.bst.successor(9), 10)
self.bst.insert(8)
self.bst.insert(7)
self.bst.insert(40)
self.assertEqual(self.bst.successor(30), 40)
self.assertEqual(self.bst.successor(40), -1)
self.bst.insert(50)
self.assertEqual(self.bst.successor(40), 50)
self.assertEqual(self.bst.successor(50), -1)
self.bst.insert(70)
self.assertEqual(self.bst.successor(70), -1)
self.bst.insert(90)
self.assertEqual(self.bst.successor(70), 90)
self.assertEqual(self.bst.successor(90), -1)
self.bst.insert(60)
self.bst.insert(65)
self.assertEqual(self.bst.successor(65), 70)
self.bst.insert(55)
self.bst.insert(51)
self.bst.insert(57)
self.assertEqual(self.bst.successor(57), 60)
if __name__ == '__main__':
unittest.main()
sys.exit(0) |
d5042d0f20d97b4557e967ae7a68bcb30cdfcd06 | sujmkim/Shop | /fruit_store.py | 2,610 | 3.515625 | 4 | #USM2-Assgn-8
class FruitInfo:
__fruit_name_list = ["Apple", "Guava", "Orange", "Grape", "Sweet Lime"]
__fruit_price_list = [200, 80, 70, 110, 60]
@staticmethod
def get_fruit_price(fruit_name):
if(fruit_name in FruitInfo.__fruit_name_list):
index = FruitInfo.__fruit_name_list.index(fruit_name)
return FruitInfo.__fruit_price_list[index]
return -1
@staticmethod
def get_fruit_name_list():
return FruitInfo.__fruit_name_list
@staticmethod
def get_fruit_price_list():
return FruitInfo.__fruit_price_list
class Customer:
def __init__(self, customer_name, cust_type):
self.__customer_name = customer_name
self.__cust_type = cust_type
def get_customer_name(self):
return self.__customer_name
def get_cust_type(self):
return self.__cust_type
class Purchase:
__counter = 101
def __init__(self, customer, fruit_name, quantity):
self.__purchase_id = None
self.__customer = customer
self.__fruit_name = fruit_name
self.__quantity = quantity
def get_purchase_id(self):
return self.__purchase_id
def get_customer(self):
return self.__customer
def get_quantity(self):
return self.__quantity
def calculate_price(self):
final_fruit_price = 0
individual_fruit_price = FruitInfo.get_fruit_price(self.__fruit_name)
#checking if the fruit exists
if(FruitInfo.get_fruit_price(self.__fruit_name) != -1):
#updating the total price
final_fruit_price += FruitInfo.get_fruit_price(self.__fruit_name)*self.get_quantity()
if(individual_fruit_price == max(FruitInfo.get_fruit_price_list()) and self.get_quantity() > 1):
final_fruit_price = final_fruit_price - final_fruit_price*0.02
elif(individual_fruit_price == min(FruitInfo.get_fruit_price_list()) and self.get_quantity() >= 5):
final_fruit_price = final_fruit_price - final_fruit_price*0.05
if(self.get_customer().get_cust_type() == "wholesale"):
final_fruit_price = final_fruit_price - final_fruit_price*0.1
self.__purchase_id = "P" + str(Purchase.__counter)
Purchase.__counter += 1
return final_fruit_price
return -1
cust = Customer("tom", "wholesale")
purchase1 = Purchase(cust, "Apple", 5)
print(purchase1.calculate_price())
'''
Created on Oct 3, 2019
@author: sujean.kim
'''
|
75e596334f33547dde5c94853d17360ae284042d | bekasov/PyQtFftAnalyzer | /Resources/_examples/DataCursor.py | 2,391 | 4.03125 | 4 | # -*- noplot -*-
"""
This example shows how to use matplotlib to provide a data cursor. It
uses matplotlib to draw the cursor and may be a slow since this
requires redrawing the figure with every mouse move.
Faster cursoring is possible using native GUI drawing, as in
wxcursor_demo.py.
The mpldatacursor and mplcursors third-party packages can be used to achieve a
similar effect. See
https://github.com/joferkington/mpldatacursor
https://github.com/anntzer/mplcursors
"""
from __future__ import print_function
import matplotlib.pyplot as plt
import numpy as np
class Cursor(object):
def __init__(self, ax):
self.ax = ax
self.lx = ax.axhline(color='k') # the horiz line
self.ly = ax.axvline(color='k') # the vert line
# text location in axes coords
self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
# update the line positions
self.lx.set_ydata(y)
self.ly.set_xdata(x)
self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
plt.draw()
class SnaptoCursor(object):
"""
Like Cursor but the crosshair snaps to the nearest x,y point
For simplicity, I'm assuming x is sorted
"""
def __init__(self, ax, x, y):
self.ax = ax
self.lx = ax.axhline(color='k') # the horiz line
self.ly = ax.axvline(color='k') # the vert line
self.x = x
self.y = y
# text location in axes coords
self.txt = ax.text(0.7, 0.9, '', transform=ax.transAxes)
def mouse_move(self, event):
if not event.inaxes:
return
x, y = event.xdata, event.ydata
indx = np.searchsorted(self.x, [x])[0]
x = self.x[indx]
y = self.y[indx]
# update the line positions
self.lx.set_ydata(y)
self.ly.set_xdata(x)
self.txt.set_text('x=%1.2f, y=%1.2f' % (x, y))
print('x=%1.2f, y=%1.2f' % (x, y))
plt.draw()
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2*2*np.pi*t)
fig, ax = plt.subplots()
#cursor = Cursor(ax)
cursor = SnaptoCursor(ax, t, s)
plt.connect('motion_notify_event', cursor.mouse_move)
ax.plot(t, s, 'o')
plt.axis([0, 1, -1, 1])
plt.show() |
e3d8c4a067cb6598b25756f109b3ea5807bd297e | Pooja1826/tathastu_week_of_code | /day1/program3.py | 212 | 3.984375 | 4 | num1=int(input("Enter first number: "))
num2=int(input("Enter second number: "))
num1 = num1+num2
num2= num1-num2
num1= num1-num2
print("After Swapping")
print("Value of num1:",num1)
print("Value of num2:",num2)
|
a01a2492929251aec7dc00154e1dc5824266a72a | davidcviray/lis161 | /Exercise9-10_FileReadSpamConfidence-EasterEgg.py | 465 | 3.671875 | 4 | filename = input("Enter the file name: ")
if filename=="na na boo boo":
print('Here is a funny message')
else:
fhand = open(filename + ".txt")
count = 0
average = 0
for line in fhand:
line = line.rstrip()
if line.startswith('X-DSPAM-Confidence:') :
count = count +1
data = float(line[20:])
average = average + data
print('Average spam confidence: ', average/count)
|
bc1e27bea818066ce6e066436a82b0d3fd418a01 | davidcviray/lis161 | /Exercise12_MaxMinLists.py | 455 | 3.875 | 4 | def computemin(numbercheck):
return min(numbercheck)
def computemax(numbercheck):
return max(numbercheck)
minval = None
maxval = None
values = list()
while True:
line = input('Enter a number: ')
if line == 'done' :
print(computemin(values),computemax(values))
break
try:
input_value = float(line)
values.append(input_value)
except ValueError:
print ("bad data")
|
7fb2fa209095f786f9e2be7ce34d8e7e28e3b7df | achutman/handpump-Aquifer-Monitoring-Lstm | /scripts/LSTMmultiInUniOut.py | 5,230 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on 29 Sep 2019
Class definition of LSTM multi input unit output framework.
@author: Achut Manandhar
Adapted from the following example:
https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/
"""
from keras.models import Sequential
from keras.layers import LSTM
from keras.layers import Dropout
from keras.layers import Dense
from keras.regularizers import L1L2
from keras.optimizers import Adam
from numpy import arange
from numpy import array
class LSTMmultiInUniOut(object):
'''
Implements LSTM in Keras with tensorFlow backend
Adapted from the example described in here:
https://machinelearningmastery.com/how-to-develop-lstm-models-for-time-series-forecasting/
'''
def __init__(self, n_input = 3, n_hid = 50, dropout = 0.2, validation_split = .2, loss_fn = 'mse', optimizer = 'Adam', learn_rate = .0001, L1L2 = [0.0,0.0001], batch_size = 10, n_epoch = 140, verbose = 1, shuffle = 0):
'''
Initializes parameters for LSTM network. Most of these parameter choices defaults to stardard keras parameters.
n_input = number of time steps in the input sequence
n_hid = number of hidden nodes
dropout = dropout rate
validation_split = proportion of training data to be used for validation
loss_fn = loss function
optimizer = optimizer
L1L2 = L1, L2 regularization
learn_rate = learning rate
batch_size = batch size
n_epoch = number of epochs
verbose = verbose
shuffle = whether to shuffle during each epoch
'''
self.n_input = n_input
self.n_hid = n_hid
self.dropout = dropout
self.validation_split = validation_split
self.loss_fn = loss_fn
self.optimizer = optimizer
self.L1L2 = L1L2
self.learn_rate = learn_rate
self.batch_size = batch_size
self.n_epoch = n_epoch
self.verbose = verbose
self.shuffle = shuffle
# Build model
def build_model(self, train_x, train_y):
n_timesteps, n_features = train_x.shape[1], train_x.shape[2]
# define model
# # One hidden layer with 50 units
model = Sequential()
model.add(LSTM(self.n_hid, activation='relu',
input_shape=(n_timesteps, n_features),
bias_regularizer = L1L2(l1=self.L1L2[0], l2=self.L1L2[1]),
kernel_regularizer = L1L2(l1=self.L1L2[0], l2=self.L1L2[1])))
model.add(Dropout(rate=self.dropout))
model.add(Dense(1))
optimizer = self.optimizer
model.compile(loss=self.loss_fn, optimizer=optimizer(lr=self.learn_rate))
# es = EarlyStopping(monitor='val_loss', mode='min', min_delta=esMinDelta, verbose=1, patience=10)
return model
# Train model
def train_model(self, model, train_x, train_y):
# fit model
modelHistory = model.fit(train_x, train_y,
epochs=self.n_epoch,
batch_size=self.batch_size,
verbose=self.verbose,
shuffle=self.shuffle,
validation_split=self.validation_split)
# callbacks=[es])
return modelHistory, model
# Predict using trained model
def predict_model(self, model, train, test, NhrBinsPerDay):
history = [x for x in train]
# walk-forward validation over each day
predictions = list()
for i in range(len(test)):
# get real observation and add to history for predicting this day
history.append(test[i, :])
# predict the day
# flatten data
data = array(history)
data = data.reshape((data.shape[0]*data.shape[1], data.shape[2]))
yhat_sequence = list()
for j in arange(1,NhrBinsPerDay+1):
# retrieve last observations for input data
if j<NhrBinsPerDay:
input_x = data[-self.n_input-NhrBinsPerDay+i:-NhrBinsPerDay+i, :-1]
else:
input_x = data[-self.n_input:, :-1]
# reshape into [1, n_input, 1]
input_x = input_x.reshape((1, len(input_x), input_x.shape[1]))
# forecast the next day
yhat = model.predict(input_x, verbose=0)
# we only want the vector forecast
yhat = yhat[0]
yhat_sequence.append(yhat)
# store the predictions
predictions.append(yhat_sequence)
predictions = array(predictions)
predictions = predictions.reshape(predictions.shape[0],predictions.shape[1])
return predictions
|
3d3a752ddf16bc39e94945f39b7b978d5f246995 | Gear-bao/Python | /dice_rolling_simulator.py | 3,104 | 4.21875 | 4 | #Made on May 27th, 2017
#Made by SlimxShadyx
#Dice Rolling Simulator
import random
#These variables are used for user input and while loop checking.
correct_word = False
dice_checker = False
dicer = False
roller_loop = False
#Checking the user input to start the program.
while correct_word == False:
user_input_raw = raw_input("\r\nWelcome to the Dice Rolling Simulator! We currently support 6, 8, and 12 sided die! Type [start] to begin!\r\n?>")
#Converting the user input to lower case.
user_input = (user_input_raw.lower())
if user_input == 'start':
correct_word = True
else:
print "Please type [start] to begin!\r\n"
#Main program loop. Exiting this, exits the program.
while roller_loop == False:
#Second While loop to ask the user for the certain die they want.
while dice_checker == False:
user_dice_chooser = raw_input("\r\nGreat! Begin by choosing a die! [6] [8] [10]\r\n?>")
user_dice_chooser = int(user_dice_chooser)
if user_dice_chooser == 6:
dice_checker = True
elif user_dice_chooser == 8:
dice_checker = True
elif user_dice_chooser == 12:
dice_checker = True
else:
print "\r\nPlease choose one of the applicable options!\r\n"
#Another inner while loop. This one does the actual rolling, as well as allowing the user to re-roll without restarting the program.
while dicer == False:
if user_dice_chooser == 6:
dice_6 = random.randint(1,6)
print "\r\nYou rolled a " + str(dice_6) + "!\r\n"
dicer = True
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker == 'roll':
dicer = False
elif user_exit_checker == 'exit':
roller_loop = True
elif user_dice_chooser == 8:
dice_8 = random.randint(1,8)
print "\r\nYou rolled a " + str(dice_8) + "!"
dicer = True
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker == 'roll':
dicer = False
elif user_exit_checker == 'exit':
roller_loop = True
elif user_dice_chooser == 12:
dice_12 = random.randint(1,12)
print "\r\nYou rolled a " + str(dice_12) + "!"
dicer = True
user_exit_checker_raw = raw_input("\r\nIf you want to roll another die, type [roll]. To exit, type [exit].\r\n?>")
user_exit_checker = (user_exit_checker_raw.lower())
if user_exit_checker == 'roll':
dicer = False
elif user_exit_checker == 'exit':
roller_loop = True
print "Thanks for using the Dice Rolling Simulator! Have a great day! =)"
|
87209c89e2b29804a7cbfc1f6f283048f2bbeaaa | wellqin/USTC | /leetcode/editor/cn/[24]两两交换链表中的节点.py | 3,070 | 4.0625 | 4 | # 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表。
#
# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
#
#
#
# 示例:
#
# 给定 1->2->3->4, 你应该返回 2->1->4->3.
#
#
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 和链表反转类似,关键在于有三个指针,分别指向前后和当前节点。不同点是两两交换后,移动节点步长为2
def swapPairs(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
# 创建一个不含任何信息的头结点,并添加到原链表的前面
dummy = ListNode(None)
dummy.next = head
pre = dummy # 指向已完成交换部分的尾结点,初始为头结点dummy
cur, nxt = head, head.next # 分别指向要交换的两个结点
while nxt: # 后二个都存在
# 重新调整结点位置
cur.next = nxt.next
nxt.next = cur
pre.next = nxt
# 更新指针
pre = cur
cur = cur.next
nxt = cur.next if cur else None # 如果奇数,则最后一个不交换,此处防止出错
return dummy.next
def swapPairs1(self, head: ListNode) -> ListNode:
if not head or not head.next:
return head
else:
head, head.next, head.next.next = head.next, head, self.swapPairs(head.next.next)
return head
def swapPairs2(self, head):
# 1. 终止条件:当前节点为null,或者下一个节点为null
if not (head and head.next):
return head
# 2. 函数内:将2指向1,1指向下一层的递归函数,最后返回节点2
# 假设链表是 1->2->3->4
# 就先保存节点2
tmp = head.next
# 继续递归,处理节点3->4
# 当递归结束返回后,就变成了4->3
# 于是head节点就指向了4,变成1->4->3
head.next = self.swapPairs2(tmp.next)
# 将2节点指向1
tmp.next = head
# 3. 返回给上一层递归的值应该是已经交换完成后的子链表
return tmp
def swapPairs3(self, head: ListNode) -> ListNode:
dummy = ListNode(-1)
dummy.next = head
pre = dummy
while pre.next and pre.next.next: # 后二个都存在
cur, nxt = pre.next, pre.next.next # 标记这二个
# 三步走
pre.next = nxt
cur.next = nxt.next
nxt.next = cur
# 更新指针位置,前进二个
pre = pre.next.next
return dummy.next
if __name__ == "__main__":
l1_1 = ListNode(1)
l1_2 = ListNode(2)
l1_3 = ListNode(3)
l1_4 = ListNode(4)
l1_1.next = l1_2
l1_2.next = l1_3
l1_3.next = l1_4
# print(ss.addTwoNumbers(ll, tt))
print(Solution().swapPairs2(l1_1))
|
a39e684c2138d23efca3d207f35e60821a2305cb | wellqin/USTC | /leetcode/editor/cn/[4]寻找两个有序数组的中位数.py | 8,916 | 3.921875 | 4 | # -*- coding: utf-8 -*-
# 给定两个大小为 m 和 n 的有序数组 nums1 和 nums2。
#
# 请你找出这两个有序数组的中位数,并且要求算法的时间复杂度为 O(log(m + n))。
#
# 你可以假设 nums1 和 nums2 不会同时为空。
#
# 示例 1:
#
# nums1 = [1, 3]
# nums2 = [2]
#
# 则中位数是 2.0
#
#
# 示例 2:
#
# nums1 = [1, 2]
# nums2 = [3, 4]
#
# 则中位数是 (2 + 3)/2 = 2.5
# for循环遍历两个列表失败—— ValueError: too many values to unpack
# nums1, = [3, 4, 6, 7, 8, 11]
# nums2, = [2, 5, 9, 12, 17, 20]
# https://blog.csdn.net/hehedadaq/article/details/81836025
"""
在pyhon3中/是真除法。 3/2=1.5
如果想在python3使用地板除,是// 3//2=1 7 // 2=3
%表示求余数 5%2=1
" / " 就表示 浮点数除法,返回浮点结果;
" // " 表示整数除法。
"""
from typing import List
# class Solution:
# def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# m = len(nums1)
# n = len(nums2)
# # 最后要找到合并以后索引是 median_index 的这个数
# median_index = (m + n) >> 1
#
# # nums1 的索引
# i = 0
# # nums2 的索引
# j = 0
#
# # 计数器从 -1 开始,在循环开始之前加 1
# # 这样在退出循环的时候,counter 能指向它最后赋值的那个元素
# counter = -1
#
# res = [0, 0]
# while counter < median_index:
# counter += 1
# # 先写 i 和 j 遍历完成的情况,否则会出现数组下标越界
# if i == m:
# res[counter & 1] = nums2[j]
# j += 1
# elif j == n:
# res[counter & 1] = nums1[i]
# i += 1
# elif nums1[i] < nums2[j]:
# res[counter & 1] = nums1[i]
# i += 1
# else:
# res[counter & 1] = nums2[j]
# j += 1
# # print(res)
# # 每一次比较,不论是 nums1 中元素出列,还是 nums2 中元素出列
# # 都会选定一个数,因此计数器 + 1
#
# # 如果 m + n 是奇数,median_index 就是我们要找的
# # 如果 m + n 是偶数,有一点麻烦,要考虑其中有一个用完的情况,其实也就是把上面循环的过程再进行一步
#
# if (m + n) & 1:
# return res[counter & 1]
# else:
# return sum(res) / 2
class Solution:
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
# 为了让搜索范围更小,我们始终让 num1 是那个更短的数组,PPT 第 9 张
if len(nums1) > len(nums2):
# 这里使用了 pythonic 的写法,即只有在 Python,中可以这样写
# 在一般的编程语言中,得使用一个额外变量,通过"循环赋值"的方式完成两个变量的地址的交换
nums1, nums2 = nums2, nums1
# 上述交换保证了 m <= n,在更短的区间 [0, m] 中搜索,会更快一些
m = len(nums1)
n = len(nums2)
# 使用二分查找算法在数组 nums1 中搜索一个索引 i,PPT 第 9 张
left = 0
right = m
# 这里使用的是最简单的、"传统"的二分查找法模板
while left <= right:
# 尝试要找的索引,在区间里完成二分,为了保证语义,这里就不定义成 mid 了
# 用加号和右移是安全的做法,即使在溢出的时候都能保证结果正确,但是 Python 中不存在溢出
# 参考:https://leetcode-cn.com/problems/guess-number-higher-or-lower/solution/shi-fen-hao-yong-de-er-fen-cha-zhao-fa-mo-ban-pyth/
i = (left + right) >> 1
j = ((m + n + 1) >> 1) - i
# 边界值的特殊取法的原因在 PPT 第 10 张
nums1_left_max = float('-inf') if i == 0 else nums1[i - 1]
nums1_right_min = float('inf') if i == m else nums1[i]
nums2_left_max = float('-inf') if j == 0 else nums2[j - 1]
nums2_right_min = float('inf') if j == n else nums2[j]
# 交叉小于等于关系成立,那么中位数就可以从"边界线"两边的数得到,原因在 PPT 第 2 张、第 3 张
if nums1_left_max <= nums2_right_min and nums2_left_max <= nums1_right_min:
# 已经找到解了,分数组之和是奇数还是偶数得到不同的结果,原因在 PPT 第 2 张
if (m + n) & 1:
return max(nums1_left_max, nums2_left_max)
else:
return (max(nums1_left_max, nums2_left_max) + min(nums1_right_min, nums2_right_min)) / 2
elif nums1_left_max > nums2_right_min:
# 这个分支缩短边界的原因在 PPT 第 8 张,情况 ②
right = i - 1
else:
# 这个分支缩短边界的原因在 PPT 第 8 张,情况 ①
left = i + 1
raise ValueError('传入无效的参数,输入的数组不是有序数组,算法失效')
class Solution1:
# 这题很自然地想到归并排序,再取中间数,但是是nlogn的复杂度,题目要求logn
# 所以要用二分法来巧妙地进一步降低时间复杂度
# 思想就是利用总体中位数的性质和左右中位数之间的关系来把所有的数先分成两堆,然后再在两堆的边界返回答案
def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
m = len(nums1)
n = len(nums2)
# 让nums2成为更长的那一个数组
if m > n:
nums1, nums2, m, n = nums2, nums1, n, m
# 如果两个都为空的异常处理
if n == 0:
raise ValueError
# nums1中index在imid左边的都被分到左堆,nums2中jmid左边的都被分到左堆
imin, imax = 0, m
# 二分答案
while imin <= imax:
imid = imin + (imax - imin) // 2
# 左堆最大的只有可能是nums1[imid-1],nums2[jmid-1]
# 右堆最小只有可能是nums1[imid],nums2[jmid]
# 让左右堆大致相等需要满足的条件是imid+jmid = m-imid+n-jmid 即 jmid = (m+n-2imid)//2
# 为什么是大致呢?因为有总数为奇数的情况,这里用向下取整数操作,所以如果是奇数,右堆会多1
jmid = (m + n - 2 * imid) // 2
# 前面的判断条件只是为了保证不会index out of range
if imid > 0 and nums1[imid - 1] > nums2[jmid]:
# imid太大了,这是里精确查找,不是左闭右开,而是双闭区间,所以直接移动一位
imax = imid - 1
elif imid < m and nums2[jmid - 1] > nums1[imid]:
imin = imid + 1
# 满足条件
else:
# 边界情况处理,都是为了不out of index
# 依次得到左堆最大和右堆最小
if imid == m:
minright = nums2[jmid]
elif jmid == n:
minright = nums1[imid]
else:
minright = min(nums1[imid], nums2[jmid])
if imid == 0:
maxleft = nums2[jmid - 1]
elif jmid == 0:
maxleft = nums1[imid - 1]
else:
maxleft = max(nums1[imid - 1], nums2[jmid - 1])
# 前面也提过,因为取中间的时候用的是向下取整,所以如果总数是奇数的话,
# 应该是右边个数多一些,边界的minright就是中位数
if ((m + n) % 2) == 1:
return minright
# 否则我们在两个值中间做个平均
return (maxleft + minright) / 2
def findMedianSortedArrays1(nums1, nums2):
m = len(nums1)
n = len(nums2)
p, q = 0, 0
# 获取中位数的索引
mid = ((m + n) // 2 - 1, (m + n) // 2) if (m + n) % 2 == 0 else ((m + n) // 2, (m + n) // 2)
li = []
while p < m and q < n:
if nums1[p] <= nums2[q]:
li.append(nums1[p])
p += 1
else:
li.append(nums2[q])
q += 1
else:
if p >= m:
while q < n:
li.append(nums2[q])
q += 1
else:
while p < m:
li.append(nums1[p])
p += 1
res = (li[mid[0]] + li[mid[1]]) / 2
print(li)
return res
nums1 = [3, 4, 6, 7, 8, 11, 13]
nums2 = [2, 5, 9, 12, 17, 20, 22]
solution = Solution()
print(solution.findMedianSortedArrays(nums1, nums2))
print(findMedianSortedArrays1(nums1, nums2))
|
110ef73dda205d379734a6a1333c8f692a40c564 | wellqin/USTC | /PythonBasic/base_pkg/python-05-flntPy-Review/fpy_05_decomp.py | 1,541 | 3.921875 | 4 | # normal usage
names = ("ZL", "World")
a, b = names
print(a)
print(b)
a, b = divmod(10, 3)
print(a)
print(b)
# ignore some elements
local = [(1, "hello"),
(2, "world"),
(3, "bonjure")]
for _, word in local:
print(word)
# ignore more
t = (3, 1, 1, 0, 10)
a, b, *rest = t
print(a)
print(b)
print(rest)
# more examples
metro_areas = [
('Tokyo','JP',36.933,(35.689722,139.691667)),
('Delhi NCR', 'IN', 21.935, (28.613889, 77.208889)),
('Mexico City', 'MX', 20.142, (19.433333, -99.133333)),
('New York-Newark', 'US', 20.104, (40.808611, -74.020386)),
('Sao Paulo', 'BR', 19.649, (-23.547778, -46.635833)),
]
print("{:15} | {:^9} | {:^9}".format('', 'lat.', 'long.'))
fmt = "{:15} | {:9.4f} | {:9.4f}"
for name, cc, pip, (latitude, longitude) in metro_areas:
if longitude <= 0:
print(fmt.format(name, latitude, longitude))
# namedtuple again
import collections
City = collections.namedtuple('City', 'name country population coordinates')
# or
# City = collections.namedtuple('City', ['name', 'country', 'population', 'coordinates'])
Tokyo = City('Tokyo', 'JP', 36.933, (35.689722, 139.691667))
# useful: _fields
print(City._fields) # just like headers in excel, variables in matrix in R
# useful: _make()
LatLong = collections.namedtuple('LatLong', 'lat long')
delhi_data = ('Delhi NCR', 'IN', 21.935, LatLong(28.613889, 77.208889))
delhi = City._make(delhi_data) # accept iterable and generate a namedtupe class
# useful: _asdict()
delhi._asdict()
for k, v in delhi._asdict().items():
print(k + ":", v) |
c1263b660b54e5ebbf61a82535e765332c994e2a | wellqin/USTC | /Thread/多线程/13-⽣产者与消费者模式.py | 3,193 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 13-⽣产者与消费者模式
Description :
Author : wellqin
date: 2019/9/11
Change Activity: 2019/9/11
-------------------------------------------------
"""
"""
Python的Queue模块中提供了同步的、线程安全的队列类,包括FIFO(先⼊先出)队列Queue,LIFO(后⼊先出)队列LifoQueue,和优先级队列
PriorityQueue。这些队列都实现了锁原语(可以理解为原⼦操作,即要么不做,要么就做完),能够在多线程中直接使⽤。
可以使⽤队列来实现线程间的同步。⽤FIFO队列实现上述⽣产者与消费者问题的代码如下:
1. 对于Queue,在多线程通信之间扮演重要的⻆⾊
2. 添加数据到队列中,使⽤put()⽅法
3. 从队列中取数据,使⽤get()⽅法
4. 判断队列中是否还有数据,使⽤qsize()⽅法
"""
import threading
import time
# python2中
# from Queue import Queue
# python3中
from queue import Queue
# 通过阻塞队列来进⾏通讯,消除二者之间的耦合
class Producer(threading.Thread):
def run(self):
global queue
count = 0
while True:
if queue.qsize() < 1000:
for i in range(100):
count = count + 1
msg = '⽣成产品'+str(count)
queue.put(msg)
print(msg)
time.sleep(0.5)
class Consumer(threading.Thread):
def run(self):
global queue
while True:
if queue.qsize() > 100:
for i in range(3):
msg = self.name + '消费了 '+queue.get()
print(msg)
time.sleep(1)
if __name__ == '__main__':
queue = Queue()
for i in range(500):
queue.put('初始产品'+str(i))
for i in range(2):
p = Producer()
p.start()
for i in range(5):
c = Consumer()
c.start()
"""
⽣产者消费者模式的说明
为什么要使⽤⽣产者和消费者模式
在线程世界⾥,⽣产者就是⽣产数据的线程,消费者就是消费数据的线程。
在多线程开发当中,如果⽣产者处理速度很快,⽽消费者处理速度很慢,那
么⽣产者就必须等待消费者处理完,才能继续⽣产数据。同样的道理,如果
消费者的处理能⼒⼤于⽣产者,那么消费者就必须等待⽣产者。为了解决这
个问题于是引⼊了⽣产者和消费者模式。
什么是⽣产者消费者模式
⽣产者消费者模式是通过⼀个容器来解决⽣产者和消费者的强耦合问题。⽣
产者和消费者彼此之间不直接通讯,⽽通过阻塞队列来进⾏通讯,所以⽣产
者⽣产完数据之后不⽤等待消费者处理,直接扔给阻塞队列,消费者不找⽣
产者要数据,⽽是直接从阻塞队列⾥取,阻塞队列就相当于⼀个缓冲区,平
衡了⽣产者和消费者的处理能⼒。
这个阻塞队列就是⽤来给⽣产者和消费者解耦的。纵观⼤多数设计模式,都
会找⼀个第三者出来进⾏解耦,
""" |
d9b8e47a7d2d0726a06fd3b203566e8c1eaca461 | wellqin/USTC | /leetcode/editor/cn/[74]搜索二维矩阵.py | 3,833 | 3.609375 | 4 | # 编写一个高效的算法来判断 m x n 矩阵中,是否存在一个目标值。该矩阵具有如下特性:
#
#
# 每行中的整数从左到右按升序排列。
# 每行的第一个整数大于前一行的最后一个整数。
#
#
# 示例 1:
#
# 输入:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = 3
# 输出: true
#
#
# 示例 2:
#
# 输入:
# matrix = [
# [1, 3, 5, 7],
# [10, 11, 16, 20],
# [23, 30, 34, 50]
# ]
# target = 13
# 输出: false
# Related Topics 数组 二分查找
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
def searchMatrix1(self, matrix, target):
if not matrix:
return False
for i in range(len(matrix)):
for j in range(len(matrix[0])):
if matrix[i][j] == target:
return True
return False
def searchMatrix2(self, matrix, target):
# 对每一行进行二分
if len(matrix) == 0 or len(matrix[0]) == 0 or target < matrix[0][0] or target > matrix[-1][-1]:
return False
for i in range(len(matrix)):
l = 0
r = len(matrix[i]) - 1
while l <= r:
mid = l + ((r - l) >> 1)
if matrix[i][mid] == target:
return True
elif matrix[i][mid] < target:
l = mid + 1
elif matrix[i][mid] > target:
r = mid - 1
return False
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]: return False
m, n = len(matrix), len((matrix[0]))
# 从左下角开始遍历,判断target在哪一行
while matrix[m - 1][0] > target and m > 1:
m -= 1
return target in matrix[m - 1]
# 因为m为len(matrix),最后定位的行为从1开始的,要以0下标开始则为[m - 1]
# 二次二分
def searchMatrix3(self, matrix: List[List[int]], target: int) -> bool:
# 矩阵为空则直接返回
if not matrix or not matrix[0]:
return False
R = len(matrix)
C = len(matrix[0])
# 如果 target不在矩阵(最小值, 最大值)范围内,直接返回
if not (matrix[0][0] <= target <= matrix[-1][-1]):
return False
r, c = -1, -1
left, right = 0, R - 1
while left <= right:
# 取左中位数
mid = (left + right) >> 1
# 如果该行最小值大于 target,那么target不可能在较大的另一半区间内,可能在较小的另一半区间内
if matrix[mid][0] > target:
right = mid - 1
# 如果该行最大值小于 target,那么target不可能在较小的另一半区间内,可能在较大的另一半区间内
elif matrix[mid][-1] < target:
left = mid + 1
# 否则,target可能在当前行内
else:
# print(f'{matrix[mid][0]} <= {target} <= {matrix[mid][-1]}')
r = mid
break
left, right = 0, C - 1
while left < right:
# 取右中位数
mid = (left + right) + 1 >> 1
# 如果右中值大于target,那么target一定不在右半区间
if matrix[r][mid] > target:
right = mid - 1
else:
left = mid
c = left
# 对最终结果值进行判断
return matrix[r][c] == target
# leetcode submit region end(Prohibit modification and deletion)
nums = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
t = 11
print(Solution().searchMatrix3(nums, t))
|
62f5d3d7f50398a679a084c8c68f5a84929e20dc | wellqin/USTC | /DataStructure/堆/算法导论.py | 2,816 | 3.5625 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 算法导论
Description :
Author : wellqin
date: 2019/7/10
Change Activity: 2019/7/10
-------------------------------------------------
堆排序的时间复杂度分为两个部分一个是建堆的时候所耗费的时间,一个是进行堆调整的时候所耗费的时间。而堆排序则是调用了建堆和堆调整。
刚刚在上面也提及到了,建堆是一个线性过程,从len/2-0一直调用堆调整的过程,相当于o(h1)+o(h2)+…+o(hlen/2)这里的h表示节点深度,len/2表示节点深度,对于求和过程,结果为线性的O(n)
堆调整为一个递归的过程,调整堆的过程时间复杂度与堆的深度有关系,相当于lgn的操作。
因为建堆的时间复杂度是O(n),调整堆的时间复杂度是lgn,所以堆排序的时间复杂度是O(nlgn)。
"""
def PARENT(i):
return i//2 # 为什么是一半 参考离散数学和数据结构
# 我的解释是:二叉树的性质+下标从1开始
def LEFT(i):
return i*2 # 同上,下标从1开始
def RIGHT(i):
return i*2 + 1 # 同上, 下标从1开始
class Mylist(list):
def __init__(self):
self.heap_size = 0
super().__init__() # super().__init__()的作用就是执行父类的构造函数,使得我们能够调用父类的属性。
def MAX_HEAPIFY(A, i):
l = i << 1
r = (i << 1) + 1
# 找出最大的结点
# i的左孩子是否大于i
# A.heap_size 写一个继承了list类 类中加上这个参数(Mylist)
# 或者选择A[0] 位放heap_size ??
# 或者设计全局变量
if l <= A.heap_size and A[l] > A[i]:
largest = l
else:
largest = i
# 和右孩子比
if r <= A.heap_size and A[r] > A[largest]:
largest = r
# largest = max(A[l], A[r], A[i]) # list index out of range
if largest != i: # 如果A[i]不是最大的 就要调堆了
A[i], A[largest] = A[largest], A[i] # 交换
MAX_HEAPIFY(A, largest) # 递归调largest
def BUILD_MAX_HEAP(A):
A.heap_size = len(A)-1
# print(len(A))
for i in range(A.heap_size//2, 0, -1): # 从n//2开始到1
print(i)
MAX_HEAPIFY(A, i)
def HEAPSORT(A):
BUILD_MAX_HEAP(A) # 建堆
print("建成的堆:", A)
for i in range(len(A)-1, 1, -1):
A[1], A[i] = A[i], A[1] # 第一位和最后一位换
A.heap_size = A.heap_size - 1 # 取出了一个
MAX_HEAPIFY(A, 1) # 调堆
if __name__ == '__main__':
A = Mylist()
# print(type(A))
for i in [-1,4,1,3,2,16,9,10,14,8,7]: # A = [,...] A会变成list
A.append(i)
# print(type(A))
HEAPSORT(A)
print("堆排序后:",A) |
5feeb8b7e5028174a702568103bdfe0ee3808f9c | wellqin/USTC | /PythonBasic/base_pkg/python-06-stdlib-review/chapter-01-Text/1.1-string/py_01_string.py | 1,459 | 3.78125 | 4 | """
std lib -- string
! why do I need it when I have tools like str class, format() function and % etc?
:: this lib provides other tools to make advanced text manipulation simple..
? hmm, advanced text manipulations
:: I'm not aware of these manipulations...
TODOS: learns advanced text manipulations.
string
|-- string.Template # alternative beyond the features of str objects. a good middle ground.
|-- string.textwrap # formats text from paragraphs by limiting the width of output, adding indentation, and inserting line breaks to wrap lines consistently.
|-- string.difflib # computes the actual differences between sequences of text in terms of the parts add, removed, or changed.
history
|-- string module datas from the earliest versions of Python.
|-- Many of the functions previously implemented in the module have been moved to method of str objects.
|-- but the module retains several usefull constants and classes for working with str objects.
"""
### functions: string.capwords() == str.title()
def cap(s):
"""returns capitalized all of the words in a string
"""
import string
return string.capwords(s)
def cap2(s):
"""returns capitalized the first word of a string
"""
return s.capitalize()
def cap3(s):
return s.title()
s = "hello world"
print(cap(s))
print(cap2(s))
print(cap3(s))
assert cap(s) == cap3(s), "string capitalization successed.."
assert cap(s) == cap2(s), "string capitalization failed.." |
3041fd1452213bb71bfa8b21fb1704df33c6f1f7 | wellqin/USTC | /PythonBasic/yield_from.py | 945 | 3.65625 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: yield_from
Description :
Author : wellqin
date: 2020/2/11
Change Activity: 2020/2/11
-------------------------------------------------
"""
from collections import namedtuple
Result = namedtuple("Result", "count average")
li = [40.9, 38.5, 44.3]
# 子生成器
def averager():
total = 0.0
count = 0
average = None
while True:
term = yield
if term is None:
break
total += term
count += 1
average = total / count
return Result(count, average)
# 委派生成器
def grouper(result, key):
while True:
result[key] = yield from averager()
# 调用方
def main():
results = {}
group = grouper(results, "kg")
next(group)
for value in li:
group.send(value)
group.send(None)
if __name__ == "__main__":
main()
|
ef0820cbaced0d6c3784e945dd11eb7daf3b430f | wellqin/USTC | /leetcode/editor/cn/[207]课程表.py | 2,268 | 3.71875 | 4 | #现在你总共有 n 门课需要选,记为 0 到 n-1。
#
# 在选修某些课程之前需要一些先修课程。 例如,想要学习课程 0 ,你需要先完成课程 1 ,我们用一个匹配来表示他们: [0,1]
#
# 给定课程总量以及它们的先决条件,判断是否可能完成所有课程的学习?
#
# 示例 1:
#
# 输入: 2, [[1,0]]
#输出: true
#解释: 总共有 2 门课程。学习课程 1 之前,你需要完成课程 0。所以这是可能的。
#
# 示例 2:
#
# 输入: 2, [[1,0],[0,1]]
#输出: false
#解释: 总共有 2 门课程。学习课程 1 之前,你需要先完成课程 0;并且学习课程 0 之前,你还应先完成课程 1。这是不可能的。
#
# 说明:
#
#
# 输入的先决条件是由边缘列表表示的图形,而不是邻接矩阵。详情请参见图的表示法。
# 你可以假定输入的先决条件中没有重复的边。
#
#
# 提示:
#
#
# 这个问题相当于查找一个循环是否存在于有向图中。如果存在循环,则不存在拓扑排序,因此不可能选取所有课程进行学习。
# 通过 DFS 进行拓扑排序 - 一个关于Coursera的精彩视频教程(21分钟),介绍拓扑排序的基本概念。
#
# 拓扑排序也可以通过 BFS 完成。
#
#
#
# todo
class Solution:
def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
pass
def topsort(G):
in_degrees = dict((u, 0) for u in G)
for u in G:
for v in G[u]:
in_degrees[v] += 1 # 每一个节点的入度
Q = [u for u in G if in_degrees[u] == 0] # 入度为 0 的节点
S = []
while Q:
u = Q.pop() # 默认从最后一个移除
S.append(u)
for v in G[u]:
in_degrees[v] -= 1 # 并移除其指向
if in_degrees[v] == 0:
Q.append(v)
if len(S) == len(in_degrees): # 如果循环结束后存在非0入度的顶点说明图中有环,不存在拓扑排序
return S
else:
return -1
G = {
'a':'bf',
'b':'cdf',
'c':'d',
'd':'ef',
'e':'f',
'f':''
}
G1 = { 'a':'bce', 'b':'d','c':'d','d':'e','e':'cd'}
print(topsort(G))
print(topsort(G1)) |
5f843a653c6e85236b302276e5bb0166a2bef614 | wellqin/USTC | /DataStructure/栈/二个队列实现栈.py | 2,995 | 3.8125 | 4 | # coding=utf-8
"""
-------------------------------------------------
File Name: 二个队列实现栈
Description :
Author : wellqin
date: 2019/7/11
Change Activity: 2019/7/11
-------------------------------------------------
"""
class Queue(object):
def __init__(self):
self.queue1 = []
self.queue2 = []
def enqueue(self, val):
# 二个队列在入栈时,只入空栈
if len(self.queue1) == 0:
self.queue1.append(val)
elif len(self.queue2) == 0:
self.queue2.append(val)
# 都不为空时,将数量大于1的POP加到只有1的栈尾部
if len(self.queue2) == 1 and len(self.queue1) >= 1:
while len(self.queue1) > 0:
self.queue2.append(self.queue1.pop(0))
elif len(self.queue1) == 1 and len(self.queue2) >= 1:
while len(self.queue2) > 0:
self.queue1.append(self.queue2.pop(0))
def dequeue(self):
if self.queue1:
return self.queue1.pop(0)
elif self.queue2:
return self.queue2.pop(0)
else:
return None
class Stock:
# 剑指
def __init__(self):
self.queueA = []
self.queueB = []
def enqueue(self, node):
self.queueA.append(node)
def dequeue(self):
if len(self.queueA) == 0:
return None
while len(self.queueA) != 1:
self.queueB.append(self.queueA.pop(0))
self.queueA, self.queueB = self.queueB, self.queueA # 交换是为了下一次的pop
return self.queueB.pop()
q = Stock()
q.enqueue(3)
# print(q.dequeue())
q.enqueue(4)
q.enqueue(5)
q.enqueue(6)
q.enqueue(7)
q.enqueue(8)
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
print(q.dequeue())
# class StackWithTwoQueues(object):
# def __init__(self):
# self._queue1 = []
# self._queue2 = []
#
# def push(self, x):
# if len(self._queue1) == 0:
# self._queue1.append(x)
# elif len(self._queue2) == 0:
# self._queue2.append(x)
# if len(self._queue2) == 1 and len(self._queue1) >= 1:
# while self._queue1:
# self._queue2.append(self._queue1.pop(0))
# elif len(self._queue1) == 1 and len(self._queue2) > 1:
# while self._queue2:
# self._queue1.append(self._queue2.pop(0))
#
# def pop(self):
# if self._queue1:
# return self._queue1.pop(0)
# elif self._queue2:
# return self._queue2.pop(0)
# else:
# return None
#
# def getStack(self):
# print("queue1", self._queue1)
# print("queue2", self._queue2)
#
#
# sta = StackWithTwoQueues()
# sta.push(1)
# sta.getStack()
# sta.push(2)
# sta.getStack()
# sta.push(3)
# sta.getStack()
# sta.push(4)
# sta.getStack()
# print(sta.pop())
# sta.getStack()
# print(sta.pop())
# sta.getStack()
# print(sta.pop())
# sta.getStack()
|
81d316841feb2f12e7afdb55b50575222e3ed1a6 | wellqin/USTC | /DataStructure/二叉树/二叉树的搜索/二叉树的最左下树节点的值.py | 1,039 | 3.640625 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 二叉树的最左下树节点的值
Description :
Author : wellqin
date: 2020/1/31
Change Activity: 2020/1/31
-------------------------------------------------
"""
# https://www.cnblogs.com/ArsenalfanInECNU/p/5346751.html
# from .CreateTree import Tree
from DataStructure.二叉树.二叉树的搜索.CreateTree import Node, Tree
def traverse(root): # 层次遍历
if root is None:
return []
queue = [root]
res = []
while queue:
node = queue.pop(0)
res.append(node.val)
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
return res
t = Tree()
for i in range(6):
t.add(i)
print('层序遍历:', traverse(t.root))
def FindLeft(root):
if not root:
return -1
cur = root
while cur.left:
cur = cur.left
return cur.val
print(FindLeft(t.root))
|
d5fdf34549d49cc2a0c40e70bb07641a874fa20e | wellqin/USTC | /leetcode/editor/cn/[61]旋转链表.py | 2,007 | 3.515625 | 4 | # 给定一个链表,旋转链表,将链表每个节点向右移动 k 个位置,其中 k 是非负数。
#
# 示例 1:
#
# 输入: 1->2->3->4->5->NULL, k = 2
# 输出: 4->5->1->2->3->NULL
# 解释:
# 向右旋转 1 步: 5->1->2->3->4->NULL
# 向右旋转 2 步: 4->5->1->2->3->NULL
#
#
# 示例 2:
#
# 输入: 0->1->2->NULL, k = 4
# 输出: 2->0->1->NULL
# 解释:
# 向右旋转 1 步: 2->0->1->NULL
# 向右旋转 2 步: 1->2->0->NULL
# 向右旋转 3 步: 0->1->2->NULL
# 向右旋转 4 步: 2->0->1->NULL
# Related Topics 链表 双指针
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
# 特判
if head is None or head.next is None or k <= 0:
return head
# 先看链表有多少元素,数这个链表的长度
cur = head
counter = 1
while cur.next:
cur = cur.next
counter += 1
k = k % counter # 判断是否为整倍数,是的话不用移动 先对k取模,取模后的k范围应该是 1<=k<=链表总长-1
if k == 0:
return head
cur.next = head # 此时cur在链表尾部,将链表串成环
cur = head # cur重新定位为原表头
# 可以取一些极端的例子找到规律
# counter - k - 1
for _ in range(counter - k - 1):
cur = cur.next
new_head = cur.next
cur.next = None # 处理尾部
return new_head
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == "__main__":
l1_1 = ListNode(1)
l1_2 = ListNode(2)
l1_3 = ListNode(3)
l1_4 = ListNode(4)
l1_5 = ListNode(5)
l1_1.next = l1_2
l1_2.next = l1_3
l1_3.next = l1_4
l1_4.next = l1_5
print(Solution().rotateRight(l1_1, 2))
|
2aee0d132a9bc1043c3460f310fb00f1a41e9e81 | wellqin/USTC | /PythonBasic/base_pkg/python-05-flntPy-Review/fpy_03_listcomp.py | 335 | 3.921875 | 4 | # list comprehension
symbols = '$¢£¥€¤'
codes = [ord(symbol) for symbol in symbols]
print(codes)
# or map
codes = list(map(ord, symbols))
print(codes)
# implement filtering
codes = [ord(symbol) for symbol in symbols if ord(symbol) > 127]
print(codes)
# or
codes = list(filter(lambda x: x > 127, map(ord, symbols)))
print(codes) |
227465cca1abd1e78f250c5991f716f719b4fcf1 | wellqin/USTC | /leetcode/editor/cn/[78]子集.py | 1,448 | 4.03125 | 4 | # 给定一组不含重复元素的整数数组 nums,返回该数组所有可能的子集(幂集)。
#
# 说明:解集不能包含重复的子集。
#
# 示例:
#
# 输入: nums = [1,2,3]
# 输出:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ]
#
from typing import List
class Solution:
def subsets(self, nums): # dfs or 回溯
if not nums:
return []
res = []
n = len(nums)
def helper(idx, temp_list):
res.append(temp_list)
for i in range(idx, n):
# if len(temp_list + [nums[i]]) == 2:
# res.append(temp_list + [nums[i]])
# continue
helper(i + 1, temp_list + [nums[i]])
helper(0, [])
return res
def subsets1(self, nums):
res = [[]]
for i in nums:
res = res + [[i] + num for num in res]
return res
def subsets2(self, nums): # 回溯
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
res = []
def search(tmp_res, idx):
if idx == len(nums):
res.append(tmp_res)
return
search(tmp_res + [nums[idx]], idx + 1)
search(tmp_res, idx + 1)
search([], 0)
return res
nums = [1, 1, 2]
print(Solution().subsets(nums))
# print(Solution().subsets1(nums))
|
bc8b1bf4f8e8e9c03494d58c294fc7eb74a697fc | wellqin/USTC | /PythonBasic/base_pkg/python-06-stdlib-review/chapter-10-ConcurrencyWithProcessThreadsCoroutines/10.4-multiprocessing/what-does-ellipsis(3dots)-do.py | 2,104 | 3.890625 | 4 | """
Q: wtf is `...` in Python?
A: it is `Ellipsis` object. Python > 3, using `...`, Python < 3, using `Ellipsis`
Q: why the fuck do we need this?
A: for showoff? i have no funcking idea.
Ellipsis is just a normal object. Ellipsis itself has no special methods or properties.
Official document says Ellipsis usually is used to expand `slice` functionality
Q: how tf do i use it?
A: see examples below
further reading: https://farer.org/2017/11/29/python-ellipsis-object/
"""
import logging, time
logging.basicConfig(
level=logging.DEBUG,
format='%(asctime)s - %(threadName)s - %(message)s'
)
### example 01
def add(a: int, b: int) -> None:
...
### example 02
class Magic:
def __getitem__(self, key):
if len(key) == 3 and key[2] is Ellipsis:
d = key[1] - key[0]
r = key[0]
while True:
yield r
r += d
def magic_thing():
ap = Magic()
for i in ap[1, 3, ...]:
logging.debug(f'{i}') # ! infinite loop
time.sleep(1) # show down output
### example 03
# Numpy. yeah, i used to see it alot, but i was fucking stupid or ignorant, i did NOT care it ..
# until now. this is so fucking funny
### example 04
# PEP484 -- Type Hints. hint placeholder
from typing import Callable, Tuple
def foo() -> Callable[..., int]:
return lambda x: 1
def bar() -> Tuple[int, ...]:
return (1, 2, 3)
def buz() -> Tuple[int, ...]:
return (1, 2, 3, 4)
### example 05
def treasure_against_colleague():
a, b = 1, 0
try:
return a / b
except ZeroDivisionError:
...
if __name__ == '__main__':
logging.debug(f'{type(...)}')
logging.debug(f'{bool(...)}')
logging.debug(f'{id(...)}')
### normal slice object
s = slice(1, 5, 2)
d = list('hello world wtf is ellipsis?')
logging.debug(d[s])
### magic ellipsis object
# magic_thing()
### Type Hints
logging.debug(f'{foo()}')
logging.debug(f'{bar()}')
logging.debug(f'{buz()}')
### treasure against colleague
logging.debug(f'{treasure_against_colleague()}') |
4cd4c4a1a0722f4e3c2a29493fe8bcc60114f9dc | wellqin/USTC | /PythonBasic/base_pkg/python-05-flntPy-Review/fpy_08_memoryview.py | 352 | 3.546875 | 4 | import array
# signed short array
numbers = array.array('h', [-2, -1, 0, 1, 2])
# puts the array into a memoryview
memv = memoryview(numbers)
# length
print(len(memv))
# retrieve element
print(memv[0])
# changes memv into unsinged char
memv_oct = memv.cast('B')
print(memv_oct.tolist())
# unsigned char -> singed short
memv_oct[5] = 4
print(numbers)
|
b57d5f57a387a69c4b3fdd8e06e57dcf83841c8c | wellqin/USTC | /DataStructure/排序/test.py | 2,001 | 4 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: test
Description :
Author : wellqin
date: 2020/3/12
Change Activity: 2020/3/12
-------------------------------------------------
"""
import random
def insertSort(nums):
pass
# def partition(nums, l, r):
# randInt = random.randint(l, r)
# nums[randInt], nums[r] = nums[r], nums[randInt]
#
# x = nums[r]
# i = l - 1
# for j in range(l, r):
# if nums[j] < x:
# i += 1
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# nums[i], nums[r] = nums[r], nums[i]
# return i
# def partition(nums, l, r):
# randInt = random.randint(l, r)
# nums[randInt], nums[l] = nums[l], nums[randInt]
# x = nums[l]
# i = l + 1
# j = r
#
# while True:
# while i <= r and nums[i] < x:
# i += 1
# while j >= l + 1 and nums[j] > x:
# j -= 1
# if i > j:
# break
#
# nums[i], nums[j] = nums[j], nums[i]
# i += 1
# j -= 1
#
# nums[l], nums[j] = nums[j], nums[l]
# return j
def partition(nums, l, r):
randInt = random.randint(l, r)
nums[randInt], nums[l] = nums[l], nums[randInt]
x = nums[l]
lt, gt = l, r + 1
i = l
while i < gt:
if nums[i] < x:
nums[i], nums[lt + 1] = nums[lt + 1], nums[i]
lt += 1
i += 1
elif nums[i] > x:
nums[i], nums[gt - 1] = nums[gt - 1], nums[i]
gt -= 1
else:
i += 1
nums[l], nums[lt] = nums[lt], nums[l]
return lt, gt
def quickSort(nums, l, r):
if not nums:
return []
# if l - l < 15:
# insertSort(nums)
# return nums
if l < r:
lt, gt = partition(nums, l, r)
quickSort(nums, l, lt - 1)
quickSort(nums, gt, r)
return nums
list = [-99, 19, 2, 13, 8, 34, 25, 7]
print(quickSort(list, 0, len(list) - 1))
|
bf217099c4cd2547f792e271d60cefcb696187ad | wellqin/USTC | /DataStructure/字符串/数字.py | 1,974 | 4.1875 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 数字
Description :
Author : wellqin
date: 2019/8/1
Change Activity: 2019/8/1
-------------------------------------------------
"""
import math
# // 得到的并不一定是整数类型的数,它与分母分子的数据类型有关系。
print(7.5//2) # 3.0
print(math.modf(7.5)) # (0.5, 7.0)
print(math.modf(7)) # (0.0, 7.0)
print(round(3.14159, 4)) # 3.1416
print(round(10.5)) # 10
"""
fractions 模块提供了分数类型的支持。
构造函数:
class fractions.Fraction(numerator=0, denominator=1)
class fractions.Fraction(int|float|str|Decimal|Fraction)
可以同时提供分子(numerator)和分母(denominator)给构造函数用于实例化Fraction类,但两者必须同时是int类型或者numbers.Rational类型,否则会抛出类型错误。当分母为0,初始化的时候会导致抛出异常ZeroDivisionError。
分数类型:
from fractions import Fraction
>>> x=Fraction(1,3)
>>> y=Fraction(4,6)
>>> x+y
Fraction(1, 1)
>>> Fraction('.25')
Fraction(1, 4)
"""
from fractions import Fraction
x = Fraction(1,3)
y = Fraction(4,6)
print(x+y) # 1
print(Fraction('.25')) # 1/4
print(Fraction('3.1415'), type(Fraction('3.1415'))) # 6283/2000
listres = str(Fraction('3.1415')).split("/")
print(listres[0], listres[1])
f = 2.5
z = Fraction(*f.as_integer_ratio())
print(z) # 5/2
xx=Fraction(1,3)
print(float(xx)) # 0.3333333333333333
# decimal 模块提供了一个 Decimal 数据类型用于浮点数计算,拥有更高的精度。
import decimal
decimal.getcontext().prec=4 # 指定精度(4位小数)
yy = decimal.Decimal(1) / decimal.Decimal(7)
print(yy) # 0.1429
print(yy) # 0.14286 decimal.getcontext().prec=5
# fractions.gcd(a, b)
# 用于计算最大公约数。这个函数在Python3.5之后就废弃了,官方建议使用math.gcd()。
print(math.gcd(21, 3))
import math
|
c9349ccb62462c57e247fd069636ec8eb45c370a | wellqin/USTC | /leetcode/editor/cn/[230]二叉搜索树中第K小的元素.py | 2,163 | 3.6875 | 4 | #给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
#
# 说明:
#你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
#
# 示例 1:
#
# 输入: root = [3,1,4,null,2], k = 1
# 3
# / \
# 1 4
# \
# 2
#输出: 1
#
# 示例 2:
#
# 输入: root = [5,3,6,2,4,null,null,1], k = 3
# 5
# / \
# 3 6
# / \
# 2 4
# /
# 1
#输出: 3
#
# 进阶:
#如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化 kthSmallest 函数?
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Node:
def __init__(self,item):
self.val = item
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, item):
node = Node(item)
if self.root is None:
self.root = node
else:
q = [self.root]
while True:
pop_node = q.pop(0)
if pop_node.left is None:
pop_node.left = node
return
elif pop_node.right is None:
pop_node.right = node
return
else:
q.append(pop_node.left)
q.append(pop_node.right)
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def count(node):
if not node:
return 0
return count(node.left) + count(node.right) + 1
if not root:
return None
left = count(root.left)
if left == k - 1:
return root.val
elif left > k - 1:
return self.kthSmallest(root.left, k)
else:
return self.kthSmallest(root.right, k - left - 1)
t = Tree()
for i in [5,3,6,2,4,"None","None",1 ]:
t.add(i)
print('kthSmallest:',t.kthSmallest(t.root, 7)) |
db0b2438e58491158c853913b3ba15fd6f8fedbe | wellqin/USTC | /leetcode/editor/cn/[782]变为棋盘.py | 1,375 | 3.515625 | 4 | # 一个 N x N的 board 仅由 0 和 1 组成 。每次移动,你能任意交换两列或是两行的位置。
#
# 输出将这个矩阵变为 “棋盘” 所需的最小移动次数。“棋盘” 是指任意一格的上下左右四个方向的值均与本身不同的矩阵。如果不存在可行的变换,输出 -1。
#
# 示例:
# 输入: board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]
# 输出: 2
# 解释:
# 一种可行的变换方式如下,从左到右:
#
# 0110 1010 1010
# 0110 --> 1010 --> 0101
# 1001 0101 1010
# 1001 0101 0101
#
# 第一次移动交换了第一列和第二列。
# 第二次移动交换了第二行和第三行。
#
#
# 输入: board = [[0, 1], [1, 0]]
# 输出: 0
# 解释:
# 注意左上角的格值为0时也是合法的棋盘,如:
#
# 01
# 10
#
# 也是合法的棋盘.
#
# 输入: board = [[1, 0], [1, 0]]
# 输出: -1
# 解释:
# 任意的变换都不能使这个输入变为合法的棋盘。
#
#
#
#
# 提示:
#
#
# board 是方阵,且行列数的范围是[2, 30]。
# board[i][j] 将只包含 0或 1。
#
# Related Topics 数组 数学
# leetcode submit region begin(Prohibit modification and deletion)
class Solution:
def movesToChessboard(self, board: List[List[int]]) -> int:
# leetcode submit region end(Prohibit modification and deletion)
|
c1b024fe6518776cbeaabb614ca1fa63813b02b7 | wellqin/USTC | /PythonBasic/base_pkg/python-06-stdlib-review/chapter-01-Text/1.1-string/py_02_stringTemplate.py | 1,422 | 4.1875 | 4 | ### string.Template is an alternative of str object's interpolation (format(), %, +)
import string
def str_tmp(s, insert_val):
t = string.Template(s)
return t.substitute(insert_val)
def str_interplote(s, insert_val):
return s % insert_val
def str_format(s, insert_val):
return s.format(**insert_val)
def str_tmp_safe(s, insert_val):
t = string.Template(s)
try:
return t.substitute(insert_val)
except KeyError as e:
print('ERROR:', str(e))
return t.safe_substitute(insert_val)
val = {'var': 'foo'}
# example 01
s = """
template 01: string.Template()
Variable : $var
Escape : $$
Variable in text: ${var}iable
"""
print(str_tmp(s, val))
# example 02
s = """
template 02: interpolation %%
Variable : %(var)s
Escape : %%
Variable in text: %(var)siable
"""
print(str_interplote(s, val))
# example 03
s = """
template 03: format()
Variable : {var}
Escape : {{}}
Variable in text: {var}iable
"""
print(str_format(s, val))
# example 04
s = """
$var is here but
$missing is not provided
"""
print(str_tmp_safe(s, val))
"""
conclusion:
- any $ or % or {} is escaped by repeating itself TWICE.
- string.Template is using $var or ${var} to identify and insert dynamic values
- string.Template.substitute() won't format type of the arguments..
-> using string.Template.safe_substitute() instead in this case
"""
|
e4e5ae4189e9e62096b88e1d867545d3fdc0ccc5 | wellqin/USTC | /DesignPatterns/creational/singleton/singleton_decorator.py | 510 | 4.0625 | 4 | # -*- coding:utf-8 -*-
def singleton(cls):
_instance = {}
def _singleton(*args, **kargs):
if cls not in _instance:
_instance[cls] = cls(*args, **kargs)
return _instance[cls]
return _singleton
@singleton
class A(object):
"""
装饰器解析
A = singleton(A) -> 此步骤返回了_singleton这个函数
"""
a = 1
def __init__(self, x=0):
self.x = x
if __name__ == '__main__':
a1 = A(2)
a2 = A(3)
print(id(a1), id(a2))
|
3915dd867788d1553cd3827c8105be9b87196a39 | wellqin/USTC | /DesignPatterns/structural/Iterator.py | 1,379 | 3.984375 | 4 | # -*- coding:utf-8 -*-
# Iterator Pattern with Python Code
from abc import abstractmethod, ABCMeta
# 创建Iterator接口
class Iterator(metaclass=ABCMeta):
@abstractmethod
def hasNext(self):
pass
@abstractmethod
def next(self):
pass
# 创建Container接口
class Container(metaclass=ABCMeta):
@abstractmethod
def getIterator(self):
pass
# 创建实现了Iterator接口的类NameIterator
class NameIterator(Iterator):
index = 0
aNameRepository = None
def __init__(self, inNameRepository):
self.aNameRepository = inNameRepository
def hasNext(self):
if self.index < len(self.aNameRepository.names):
return True
return False
def next(self):
if self.hasNext():
theName = self.aNameRepository.names[self.index]
self.index += 1
return theName
return None
# 创建实现了Container接口的实体类。
class NameRepository(Container):
names = ["Robert", "John", "Julie", "Lora"]
def getIterator(self):
return NameIterator(self)
# 调用输出
if __name__ == '__main__':
namesRespository = NameRepository()
iter = namesRespository.getIterator()
# print("Name : "+iter.aNameRepository.names[0])
while iter.hasNext():
strName = iter.next()
print("Name : " + strName)
|
2ac4045d4fd826c4b2c69be9ed87e68c37add73a | wellqin/USTC | /leetcode/editor/cn/[143]重排链表.py | 1,695 | 3.796875 | 4 | # 给定一个单链表 L:L0→L1→…→Ln-1→Ln ,
# 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→…
#
# 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。
#
# 示例 1:
#
# 给定链表 1->2->3->4, 重新排列为 1->4->2->3.
#
# 示例 2:
#
# 给定链表 1->2->3->4->5, 重新排列为 1->5->2->4->3.
# Related Topics 链表
# leetcode submit region begin(Prohibit modification and deletion)
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head or not head.next:
return head
fast, slow = head, head
# 找到中点
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# 反转后半链表cur
cur, pre = slow.next, None
slow.next = None # 此时head从此处断开,变成一半(left)
while cur:
pre, pre.next, cur = cur, pre, cur.next
# 重排练表
left = head
while left and pre:
left.next, pre.next, left, pre = pre, left.next, left.next, pre.next
# leetcode submit region end(Prohibit modification and deletion)
if __name__ == "__main__":
l1_1 = ListNode(1)
l1_2 = ListNode(2)
l1_3 = ListNode(3)
l1_4 = ListNode(4)
l1_5 = ListNode(5)
l1_1.next = l1_2
l1_2.next = l1_3
l1_3.next = l1_4
l1_4.next = l1_5
print(Solution().reorderList(l1_1))
|
988ab3ba48c2d279c3706a2f12224f3793182a14 | wellqin/USTC | /DesignPatterns/behavioral/Adapter.py | 1,627 | 4.21875 | 4 | # -*- coding:utf-8 -*-
class Computer:
def __init__(self, name):
self.name = name
def __str__(self):
return 'the {} computer'.format(self.name)
def execute(self):
return self.name + 'executes a program'
class Synthesizer:
def __init__(self, name):
self.name = name
def __str__(self):
return 'the {} synthesizer'.format(self.name)
def play(self):
return self.name + 'is playing an electronic song'
class Human:
def __init__(self, name):
self.name = name
def __str__(self):
return '{} the human'.format(self.name)
def speak(self):
return self.name + 'says hello'
class Adapter:
def __init__(self, obj, adapted_methods):
self.obj = obj
self.__dict__.update(adapted_methods)
def __str__(self):
return str(self.obj)
if __name__ == '__main__':
objects = [Computer('Computer')]
synth = Synthesizer('Synthesizer')
objects.append(Adapter(synth, dict(execute=synth.play)))
human = Human('Human')
objects.append(Adapter(human, dict(execute=human.speak)))
for i in objects:
print('{} {}'.format(str(i), i.execute()))
print('type is {}'.format(type(i)))
print("*" * 20)
"""
the Computer computer Computerexecutes a program
type is <class '__main__.Computer'>
the Synthesizer synthesizer Synthesizeris playing an electronic song
type is <class '__main__.Adapter'>
Human the human Humansays hello
type is <class '__main__.Adapter'>
"""
for i in objects:
print(i.obj.name) # i.name
|
8b827e7324cb5a5d9f0f690db82f3d94403f06f4 | wellqin/USTC | /DataStructure/树/travelTest.py | 2,275 | 3.75 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: travelTest
Description :
Author : wellqin
date: 2020/3/13
Change Activity: 2020/3/13
-------------------------------------------------
"""
class Node:
def __init__(self,val):
self.val = val
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, val):
node = Node(val)
if not self.root:
self.root = node
return
queue = [self.root]
while queue:
cur_node = queue.pop(0)
if not cur_node.left:
cur_node.left = node
return
elif not cur_node.right:
cur_node.right = node
return
else:
queue.append(cur_node.left)
queue.append(cur_node.right)
def travel(self, root):
def helper(node, level):
if not node:
return []
res[level - 1].append(node.val)
if len(res) == level:
res.append([])
helper(node.left, level+1)
helper(node.right, level+1)
res = [[]]
helper(root, 1)
return res[:-1]
t = Tree()
for i in range(7):
t.add(i)
print(t.travel(t.root))
root = t.root
def preOrder(root):
if not root:
return []
res = [root.val]
left = preOrder(root.left)
right = preOrder(root.right)
return res + left + right
print(preOrder(root))
def preOrderIteration(root):
if not root:
return []
res, stack, cur = [], [], root
while cur or stack:
if cur:
res.append(cur.val)
stack.append(cur.right)
cur = cur.left
else:
cur = stack.pop()
return res
print(preOrderIteration(root))
def inOrderIteration(root):
if not root:
return []
res, stack, cur = [], [], root
while cur or stack:
if cur:
stack.append(cur)
cur = cur.left
else:
cur = stack.pop()
res.append(cur.val)
cur = cur.right
return res
print(inOrderIteration(root))
|
ee8418ec927e244df1019eb7e450d6fce80b4823 | wellqin/USTC | /DataStructure/二叉树/二叉树遍历/postOrder.py | 2,147 | 4 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: postOrder
Description :
Author : wellqin
date: 2020/1/31
Change Activity: 2020/1/31
-------------------------------------------------
"""
# 构建了层序遍历: [0, 1, 2, 3, 4, 5, 6]的二叉树
class Node(object):
def __init__(self, val):
self.val = val
self.left = None
self.right = None
class Tree(object):
def __init__(self):
self.root = None
def add(self, val):
node = Node(val)
if not self.root:
self.root = node
else:
queue = [self.root]
while True:
cur_node = queue.pop(0)
if cur_node.left is None:
cur_node.left = node
return
elif cur_node.right is None:
cur_node.right = node
return
else:
queue.append(cur_node.left)
queue.append(cur_node.right)
def traverse(self, root): # 层次遍历
if root == None:
return []
queue = [root]
res = []
while queue:
node = queue.pop(0)
res.append(node.val)
if node.left != None:
queue.append(node.left)
if node.right != None:
queue.append(node.right)
return res
tree = Tree()
for i in range(7):
tree.add(i)
print('层序遍历:', tree.traverse(tree.root))
# 递归
def postOrder(root):
if not root:
return []
res = [root.val]
left = postOrder(root.left)
right = postOrder(root.right)
return left + right + res
print("Recursive", postOrder(tree.root))
# 迭代
def postOrderIteration(root):
if not root:
return []
stack = []
res = []
cur = root
while cur or stack:
if cur:
res.append(cur.val)
stack.append(cur.left)
cur = cur.right
else:
cur = stack.pop()
return res[::-1]
print("Iteration", postOrderIteration(tree.root)) |
5800fa4cbb7efda4b7b1167d2524c96ab52fc3e4 | wellqin/USTC | /DataStructure/链表/翻转.py | 3,096 | 3.734375 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 翻转
Description :
Author : wellqin
date: 2019/9/17
Change Activity: 2019/9/17
-------------------------------------------------
"""
# -*- coding: utf-8 -*-
'''
链表逆序
'''
class ListNode:
def __init__(self, val):
self.val = val
self.next = None
'''
第一种方法:
对于一个长度为n的单链表head,用一个大小为n的数组arr储存从单链表从头
到尾遍历的所有元素,在从arr尾到头读取元素简历一个新的单链表
时间消耗O(n),空间消耗O(n)
'''
# 第一种方法:
def reverse_linkedlist1(head):
if not head or not head.next: # 边界条件
return head
arr = [] # 空间消耗为n,n为单链表的长度
while head:
arr.append(head.val)
head = head.next
newhead = ListNode(0)
tmp = newhead
for i in arr[::-1]:
tmp.next = ListNode(i)
tmp = tmp.next
return newhead.next
'''
开始以单链表的第一个元素为循环变量cur,并设置2个辅助变量tmp,保存数据;
newhead,新的翻转链表的表头。
时间消耗O(n),空间消耗O(1)
'''
# 第二种方法:
def reverse_linkedlist2(head):
if head is None or head.next is None: # 边界条件
return head
cur = head # 循环变量
tmp = None # 保存数据的临时变量
newhead = None # 新的翻转单链表的表头
while cur:
tmp = cur.next
cur.next = newhead
newhead = cur # 更新 新链表的表头
cur = tmp
return newhead
'''
开始以单链表的第二个元素为循环变量,用2个变量循环向后操作,并设置1个辅助变量tmp,保存数据;
时间消耗O(n),空间消耗O(1)
'''
# 第三种方法:
def reverse_linkedlist3(head):
if head == None or head.next is None: # 边界条件
return head
p1 = head # 循环变量1
p2 = head.next # 循环变量2
tmp = None # 保存数据的临时变量
while p2:
tmp = p2.next
p2.next = p1
p1 = p2
p2 = tmp
head.next = None
return p1
'''
递归操作,先将从第一个点开始翻转转换从下一个节点开始翻转
直至只剩一个节点
时间消耗O(n),空间消耗O(1)
'''
# 第四种方法:
def reverse_linkedlist4(head):
if head is None or head.next is None:
return head
else:
newhead = reverse_linkedlist4(head.next)
head.next.next = head
head.next = None
return newhead
def create_ll(arr):
pre = ListNode(0)
tmp = pre
for i in arr:
tmp.next = ListNode(i)
tmp = tmp.next
return pre.next
def print_ll(head):
tmp = head
while tmp:
print(tmp.val, end='')
tmp = tmp.next
a = create_ll(range(5))
print_ll(a) # 0 1 2 3 4
a = reverse_linkedlist1(a)
print_ll(a) # 4 3 2 1 0
a = reverse_linkedlist2(a)
print_ll(a) # 0 1 2 3 4
a = reverse_linkedlist3(a)
print_ll(a) # 4 3 2 1 0
a = reverse_linkedlist4(a)
print_ll(a) # 0 1 2 3 4
|
61d59949fb0089fbf3d9d71f16521fa9ebeeb02b | wellqin/USTC | /leetcode/editor/cn/[23]合并K个排序链表.py | 1,174 | 3.78125 | 4 | # 合并 k 个排序链表,返回合并后的排序链表。请分析和描述算法的复杂度。
#
# 示例:
#
# 输入:
# [
# 1->4->5,
# 1->3->4,
# 2->6
# ]
# 输出: 1->1->2->3->4->4->5->6
#
import collections
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
from heapq import heappush, heappop
node_pools = []
lookup = collections.defaultdict(list)
for head in lists:
if head:
heappush(node_pools, head.val)
lookup[head.val].append(head)
dummy = cur = ListNode(None)
while node_pools:
smallest_val = heappop(node_pools)
smallest_node = lookup[smallest_val].pop(0)
cur.next = smallest_node
cur = cur.next
if smallest_node.next:
heappush(node_pools, smallest_node.next.val)
lookup[smallest_node.next.val].append(smallest_node.next)
return dummy.next
|
6148139a20c2643f6b94e3be310b5a7561da8da9 | wellqin/USTC | /leetcode/editor/cn/[54]螺旋矩阵.py | 2,324 | 3.984375 | 4 | # 给定一个包含 m x n 个元素的矩阵(m 行, n 列),请按照顺时针螺旋顺序,返回矩阵中的所有元素。
#
# 示例 1:
#
# 输入:
# [
# [ 1, 2, 3 ],
# [ 4, 5, 6 ],
# [ 7, 8, 9 ]
# ]
# 输出: [1,2,3,6,9,8,7,4,5]
#
#
# 示例 2:
#
# 输入:
# [
# [1, 2, 3, 4],
# [5, 6, 7, 8],
# [9,10,11,12]
# ]
# 输出: [1,2,3,4,8,12,11,10,9,5,6,7]
#
# Related Topics 数组
# leetcode submit region begin(Prohibit modification and deletion)
from typing import List
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
res = []
while matrix:
res += matrix.pop(0)
matrix = list(map(list, zip(*matrix)))[::-1]
"""
zip(*matrix) 将matrix[[4, 5, 6],[7, 8, 9]]进行解包为[(4,7), (5,8), (6,9)]
map(list, zip(*matrix)) 将解包内容的元祖转换成列表[[4,7], [5,8], [6,9]]
此时还是一个map对象,需要list()函数变成数组
最后[::-1]进行逆序,为 [[6, 9], [5, 8], [4, 7]]
完成了二维数组的逆序转置
"""
# matrix = [*zip(*matrix)][::-1]
print(matrix)
return res
def spiralOrder1(self, matrix):
"""
:type matrix: List[List[int]]
:rtype: List[int]
"""
if not matrix: return []
up = 0
down = len(matrix) - 1
left = 0
right = len(matrix[0]) - 1
res = []
while up <= down and left <= right:
# 从左到右
for i in range(left, right + 1):
res.append(matrix[up][i])
up += 1
if up > down: break
# 从上到下
for i in range(up, down + 1):
res.append(matrix[i][right])
right -= 1
if left > right: break
# 从右到左
for i in range(right, left - 1, -1):
res.append(matrix[down][i])
down -= 1
# 从下到上
for i in range(down, up - 1, -1):
res.append(matrix[i][left])
left += 1
return res
# leetcode submit region end(Prohibit modification and deletion)
nums = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(Solution().spiralOrder1(nums))
|
202e163898f01680e454e3d2833053e694486fef | wellqin/USTC | /leetcode/editor/cn/[394]字符串解码.py | 1,316 | 3.59375 | 4 | #给定一个经过编码的字符串,返回它解码后的字符串。
#
# 编码规则为: k[encoded_string],表示其中方括号内部的 encoded_string 正好重复 k 次。注意 k 保证为正整数。
#
# 你可以认为输入字符串总是有效的;输入字符串中没有额外的空格,且输入的方括号总是符合格式要求的。
#
# 此外,你可以认为原始数据不包含数字,所有的数字只表示重复的次数 k ,例如不会出现像 3a 或 2[4] 的输入。
#
# 示例:
#
#
#s = "3[a]2[bc]", 返回 "aaabcbc".
#s = "3[a2[c]]", 返回 "accaccacc".
#s = "2[abc]3[cd]ef", 返回 "abcabccdcdcdef".
#
#
class Solution:
def decodeString(self, s):
"""
:type s: str
:rtype: str
"""
if not s or len(s) == 0:
return ''
stack = [['', 1]]
num = 0
for i, c in enumerate(s):
if c.isdigit():
num = num * 10 + int(c)
elif c.isalpha():
stack[-1][0] += c
elif c == '[':
stack.append(['', num])
num = 0
elif c == ']':
prev_str, cnt = stack.pop()
stack[-1][0] += prev_str * cnt
return stack[0][0]
s = "3[a2[c]]"
print(Solution().decodeString(s)) |
660d95c531d49f25f00f7c7db961578f90d7aed1 | wellqin/USTC | /leetcode/editor/cn/[257]二叉树的所有路径.py | 1,778 | 3.796875 | 4 | # 给定一个二叉树,返回所有从根节点到叶子节点的路径。
#
# 说明: 叶子节点是指没有子节点的节点。
#
# 示例:
#
# 输入:
#
# 1
# / \
# 2 3
# \
# 5
#
# 输出: ["1->2->5", "1->3"]
#
# 解释: 所有根节点到叶子节点的路径为: 1->2->5, 1->3
#
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Node:
def __init__(self, item):
self.val = item
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, item):
node = Node(item)
if self.root is None:
self.root = node
else:
q = [self.root]
while True:
pop_node = q.pop(0)
if pop_node.left is None:
pop_node.left = node
return
elif pop_node.right is None:
pop_node.right = node
return
else:
q.append(pop_node.left)
q.append(pop_node.right)
def binaryTreePaths(self, root):
res = []
if not root:
return res
for g in self.helper(root):
res.append('->'.join(g))
return res
def helper(self, root, temp=[]):
if root:
temp.append(str(root.val))
if not root.left and not root.right:
yield temp
yield from self.helper(root.left, temp)
yield from self.helper(root.right, temp)
temp.pop()
t = Tree()
for i in range(7):
t.add(i)
print('先序遍历:', t.binaryTreePaths(t.root))
|
f3dfaccab0fda2249b97371e524960fa89a7c245 | wellqin/USTC | /open_source/funcy/funcy_demo.py | 347 | 3.578125 | 4 | # -*- coding:utf-8 -*-
"""
https://github.com/Suor/funcy
"""
from itertools import count
from pprint import pprint
import funcy as fc
"""Sequences"""
item = [1, 2, 3]
def sequences_generate():
pprint([item] * 3)
pprint(item * 3)
# pprint(list(map(lambda x: x ** 2, count(1))))
if __name__ == "__main__":
sequences_generate()
|
fb536fe2658f763ed392f61917ea0960a77e7a64 | wellqin/USTC | /DataStructure/队列/链表实现队列.py | 1,822 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 链表实现队列
Description :
Author : wellqin
date: 2019/7/11
Change Activity: 2019/7/11
-------------------------------------------------
"""
class QueueError(ValueError):
def __init__(self, text='队列为空,不可进行操作!'):
print(text)
# pass
# 链表节点
class Node:
def __init__(self, val, next_=None):
self.val = val
self.next = next_
# 链表实现队列,头部删除和查看O(1),尾部加入O(1)
class LQueue(object):
def __init__(self):
self._head = None
self._rear = None
def is_empty(self):
return self._head is None
# 查看队列中最早进入的元素,不删除
def peek(self):
if self.is_empty():
raise QueueError('队列为空不可进行查看元素操作!')
return self._head.val
# 将元素elem加入队列,入队
def enqueue(self, val):
'''
尾插法
'''
p = Node(val)
if self.is_empty():
self._head = p
self._rear = p
else:
self._rear.next = p
self._rear = self._rear.next
# 删除队列中最早进入的元素并将其返回,出队
def del_queue(self):
if self.is_empty():
raise QueueError('队列为空不可进行元素删除操作!')
cur = self._head.val
self._head = self._head.next
return cur
if __name__ == "__main__":
# pass
queue = LQueue()
print(queue.is_empty())
data_list = [1, 2, 3, 4]
for data in data_list:
queue.enqueue(data)
print(queue.is_empty())
print(queue.peek())
print(queue.del_queue())
print(queue.peek()) |
517e45cb3695fbf5c8cb545f5128f5e99e5f01c8 | wellqin/USTC | /leetcode/editor/cn/[35]搜索插入位置.py | 1,957 | 3.859375 | 4 | # 给定一个排序数组和一个目标值,在数组中找到目标值,并返回其索引。如果目标值不存在于数组中,返回它将会被按顺序插入的位置。
#
# 你可以假设数组中无重复元素。
#
# 示例 1:
#
# 输入: [1,3,5,6], 5
# 输出: 2
#
#
# 示例 2:
#
# 输入: [1,3,5,6], 2
# 输出: 1
#
#
# 示例 3:
#
# 输入: [1,3,5,6], 7
# 输出: 4
#
#
# 示例 4:
#
# 输入: [1,3,5,6], 0
# 输出: 0
# 【1, 3, 5, 6】,target=2, nums[mid]=3, 终于想明白了:当nums[mid]>target,
# 表明nums[mid]可能是解,所以右边间right =mid 先保留nums[mid]得到【1,3】, 再明确排除1之后,
# 最后 left=right退出时,剩下那一个可能的解【3】,就一定是解,所以直接return left, 有点绕
#
class Solution(object):
def searchInsertN(self, nums, target):
i = 0
while nums[i] < target:
i += 1
if i == len(nums):
return i
return i
def searchInsert1(self, nums, target):
l, r = 0, len(nums) - 1
while l <= r:
mid = l + ((r - l) >> 1)
if nums[mid] < target:
l = mid + 1
else:
r = mid - 1
return l
def searchInsert(self, nums, target): # 排序数组和一个目标值
if not nums or len(nums) == 0:
return 0
if target > nums[-1]:
return len(nums)
if target < nums[0]:
return 0
left = 0
right = len(nums) - 1
while left <= right:
mid = left + ((right - left) >> 1)
if nums[mid] == target: # 此部分可以去除,本题不存在重复相等情况
return mid
elif nums[mid] < target:
left = mid + 1
else:
right = mid - 1
return left
nums = [1, 3, 5, 6]
target = 2
print(Solution().searchInsert(nums, target))
|
1c3f394f36cccb7a009572700d25228070e85967 | wellqin/USTC | /leetcode/editor/cn/[926]将字符串翻转到单调递增.py | 3,130 | 3.625 | 4 | # 如果一个由 '0' 和 '1' 组成的字符串,是以一些 '0'(可能没有 '0')后面跟着一些 '1'(也可能没有 '1')的形式组成的,那么该字符串是单调
# 递增的。
#
# 我们给出一个由字符 '0' 和 '1' 组成的字符串 S,我们可以将任何 '0' 翻转为 '1' 或者将 '1' 翻转为 '0'。
#
# 返回使 S 单调递增的最小翻转次数。
#
#
#
# 示例 1:
#
# 输入:"00110"
# 输出:1
# 解释:我们翻转最后一位得到 00111.
#
#
# 示例 2:
#
# 输入:"010110"
# 输出:2
# 解释:我们翻转得到 011111,或者是 000111。
#
#
# 示例 3:
#
# 输入:"00011000"
# 输出:2
# 解释:我们翻转得到 00000000。
#
#
#
#
# 提示:
#
#
# 1 <= S.length <= 20000
# S 中只包含字符 '0' 和 '1'
#
# Related Topics 数组
# leetcode submit region begin(Prohibit modification and deletion)
# 遍历字符串,找到一个分界点,使得该分界点之前1的个数和分界点之后0的个数之和最小,把分界点之前的1变成0,之后的0变成1
class Solution(object):
def minFlipsMonoIncr1(self, S):
"""
:type S: str
:rtype: int
"""
m = S.count('0') # 分界点为0之前,统计之后的0
res = [m]
for x in S:
if x == '1': # 如果是1,分界点之前1的个数+1,分界点之后0的个数不变
m += 1
else: # 如果是0,分界点之前1的个数不变,分界点之后0的个数减1
m -= 1
res.append(m)
return min(res)
def minFlipsMonoIncr(self, S: str) -> int:
# 基本思路是遍历所有分隔点找最小值 s = "00110"
l, r, _sum = [0], [0], 0
for i in S:
if i == '1':
_sum += 1
l.append(_sum) # 将左边全翻转为0需要的翻转次数
_sum = 0
for i in reversed(S):
if i == '0':
_sum += 1
r.append(_sum) # 将右边全翻转为1需要的翻转次数
r.reverse()
print([l[i] + r[i] for i in range(len(l))])
# [3, 2, 1, 2, 3, 2]
return min(l[i] + r[i] for i in range(len(l)))
def minFlipsMonoIncr2(self, S: str) -> int:
zero = one = 0
res = 0
for s in S:
if s == "0":
zero += 1
else:
one += 1
if zero > one:
res += one
zero = 0
one = 0
res += zero
return res
def minFlipsMonoIncr3(self, S: str) -> int:
dp = [0 for _ in range(len(S))]
dp[0] = 1 if S[0] == '1' else 0
for i in range(1, len(S)):
dp[i] = dp[i - 1] + 1 if S[i] == '1' else dp[i - 1]
n = len(S)
ans = min(dp[n - 1], n - dp[n - 1])
for i in range(n - 1):
ans = min(ans, dp[i] + ((n - i - 1) - (dp[n - 1] - dp[i])))
return ans
# leetcode submit region end(Prohibit modification and deletion)
s = "00110"
print(Solution().minFlipsMonoIncr3(s)) |
5418a6f0c7d57b28dceac134cc4f7c0332573857 | wellqin/USTC | /leetcode/editor/cn/[169]求众数.py | 400 | 3.578125 | 4 | #给定一个大小为 n 的数组,找到其中的众数。众数是指在数组中出现次数大于 ⌊ n/2 ⌋ 的元素。
#
# 你可以假设数组是非空的,并且给定的数组总是存在众数。
#
# 示例 1:
#
# 输入: [3,2,3]
#输出: 3
#
# 示例 2:
#
# 输入: [2,2,1,1,1,2,2]
#输出: 2
#
#
class Solution:
def majorityElement(self, nums: List[int]) -> int:
|
9b91add0752b364855c9ecfa06cea14faff8f1c6 | wellqin/USTC | /Interview/快手/验证ip地址.py | 1,420 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
-------------------------------------------------
File Name: 验证ip地址
Description :
Author : wellqin
date: 2019/9/16
Change Activity: 2019/9/16
-------------------------------------------------
"""
# 验证ip地址
import sys
class Solution:
def vaild_ipaddr(self, str):
ip = str.split('.')
if len(ip) == 4:
for i in range(4):
length = len(ip[i])
if length > 3 or length ==0:
return "Neither"
if length>1:
if not ("1" <=ip[i][0] <= "9"):
return "Neither"
for j in range(length):
if not ("1" <=ip[i][j] <= "9"):
return "Neither"
if int(ip[i]) > 255:
return "Neither"
return "IPV4"
ips = str.split(':')
if len(ips) == 8:
for i in range(8):
length = len(ips[i])
if length > 4 or length == 0:
return "Neither"
for j in range(length):
if not ("1" <= ip[i][j] <= "9" or "a" <= ip[i][j] <= "f" or "A" <= ip[i][j] <= "F"):
return "Neither"
return "IPV6"
return "Neither"
str = sys.stdin.readline().strip()
print(Solution().vaild_ipaddr(str)) |
869249517b832ef71fc07a9b1c59bae4e6f8123a | wellqin/USTC | /PythonBasic/base_pkg/python-06-stdlib-review/chapter-18-LanguageTools/py_01_dis.py | 259 | 3.625 | 4 | import dis
def fib(n):
r = [0, 1]
if n < 2:
return r[n]
else:
for i in range(2, n + 1):
r.append(r[i-1] + r[i-2])
return r[n]
# print(fib(3))
if __name__ == "__main__":
dis.dis(fib)
dis.show_code(fib) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.