diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
new file mode 100644
index 0000000..23ab927
--- /dev/null
+++ b/.github/workflows/build.yml
@@ -0,0 +1,38 @@
+name: build
+on:
+ push:
+ branches: [ master ]
+ pull_request:
+ branches: [ master ]
+jobs:
+ build:
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v2
+ - uses: actions/setup-python@v1
+ with:
+ python-version: 3.10.14
+ - name: install python modules
+ run: pip install flake8 markdown pypinyin
+ - name: format code
+ run: flake8 . --count --select=E9,F63,F72,F82 --show-source --statistics
+ - name: generate information
+ run: |
+ python3 utils/genReadme.py
+ python3 utils/genIndex.py
+ - name: git config
+ run: |
+ git config --global user.name "mbinary"
+ git config --global user.email "zhuheqin1@gmail.com"
+ - name: generate pages and push to gh-pages branch
+ env:
+ ACCESS_TOKEN: ${{secrets.ACCESS_TOKEN}}
+ run: |
+ cd docs
+ git init
+ git remote add origin git@github.com:USTC-Resource/USTC-Course.git
+ git add --all
+ export TZ='Asia/Shanghai'
+ git commit -m "Update webpages at `date +%Y-%m-%d,%H:%m` UTC+8"
+ git push -f "https://${ACCESS_TOKEN}@github.com/USTC-Resource/USTC-Course" master:gh-pages
+
diff --git a/.gitignore b/.gitignore
index 9dd3bd4..749d3c1 100644
--- a/.gitignore
+++ b/.gitignore
@@ -14,3 +14,4 @@ do.sh
*.pyc
a.out
__pycache__/**
+.DS_Store
diff --git a/.travis.yml b/.travis.yml
deleted file mode 100644
index add7b1e..0000000
--- a/.travis.yml
+++ /dev/null
@@ -1,45 +0,0 @@
-language: python3
-sudo: required
-python:
- - "3.6"
-
-notifications:
- email:
- recipients:
- - zhuheqin1@gmail.com
- on_success: change # default: change
- on_failure: always # default: always
-
-install:
- - sudo apt-get install python3 -y
- - sudo apt-get install python3-pip -y
- - sudo pip3 install markdown
- - sudo pip3 install pypinyin
-
-script:
- - python3 utils/genReadme.py
- - python3 utils/genIndex.py
-
-after_script:
- # Build Master Repository(Coding Pages)
- - git config user.name "mbinary"
- - git config user.email "zhuheqin1@gmail.com"
- - cd docs
- - git init
- - git remote add origin git@github.com:USTC-Resource/USTC-Course.git
- - git add --all
- - git commit -m "Travis-CI Update pages with build $TRAVIS_BUILD_NUMBER"
- - git push -f "https://${GH_TOKEN}@${GH_REF}" master:gh-pages
-
-addons:
- apt:
- update: true
-
-branches:
- only:
- - master
-env:
- global:
- # Github Pages
- - GH_REF: github.com/USTC-Resource/USTC-Course
-
diff --git "a/Java\350\275\257\344\273\266\345\274\200\345\217\221\345\237\272\347\241\200/notes/\345\244\215\344\271\240\346\217\220\347\272\262.pdf" "b/Java\350\275\257\344\273\266\345\274\200\345\217\221\345\237\272\347\241\200/notes/\345\244\215\344\271\240\346\217\220\347\272\262.pdf"
new file mode 100644
index 0000000..8aaeeb7
Binary files /dev/null and "b/Java\350\275\257\344\273\266\345\274\200\345\217\221\345\237\272\347\241\200/notes/\345\244\215\344\271\240\346\217\220\347\272\262.pdf" differ
diff --git a/README.md b/README.md
index e51d32e..be3d3e3 100644
--- a/README.md
+++ b/README.md
@@ -1,8 +1,11 @@
+
+
# 中国科学技术大学课程资源
+
[](https://github.com/USTC-Resource/USTC-Course/stargazers)
[](https://github.com/USTC-Resource/USTC-Course/network/members)
-[](https://travis-ci.org/USTC-Resource/USTC-Course?branch=master)
+[]()
[]()
[](http://creativecommons.org/licenses/by-nc-sa/4.0/)
@@ -22,9 +25,11 @@
对无特别声明的资料,谨以[知识共享署名 - 非商业性使用 - 相同方式共享 4.0 国际许可协议](http://creativecommons.org/licenses/by-nc-sa/4.0/) 授权。
+请创作者及公众监督,如有资料违反许可协议,请告知我们改正错误。
+
# 反馈方式
- [issue](https://github.com/USTC-Resource/USTC-Course/issues/new)
-- email
+- email
# 资料下载
[戳我(●'◡'●)](https://ustc-resource.github.io/USTC-Course)
@@ -51,7 +56,7 @@
## HTTPS
-- [github 网页](#课程目录)
+- [GitHub 网页](#课程目录)
- [DownGit](http://downgit.zhoudaxiaa.com/#/home)
- [gitzip-chrome-extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn)
@@ -74,7 +79,7 @@ course
└ README.md
```
# 课程关系
-
+
更多信息可以下载[官网的培养方案](https://www.teach.ustc.edu.cn/education/241.html/attachment/14-215%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%AD%A6%E9%99%A2-2013)
@@ -86,25 +91,32 @@ course
* [操作系统原理与设计](./操作系统原理与设计)
* [c程序设计](./c程序设计)
* [代数结构](./代数结构)
- * [大学物理实验](./大学物理实验)
+ * [概率论与数理统计](./概率论与数理统计)
+ * [光学与原子物理](./光学与原子物理)
+ * [Java软件开发基础](./Java软件开发基础)
+ * [计算方法](./计算方法)
+ * [计算机图像学](./计算机图像学)
* [计算机网络](./计算机网络)
- * [计算机系统详解(csapp)](./计算机系统详解(csapp))
- * [计算机与信息类](./计算机与信息类)
+ * [计算机系统详解](./计算机系统详解)
* [计算机组成原理](./计算机组成原理)
+ * [马克思主义基本原理概论](./马克思主义基本原理概论)
* [模拟与数字电路](./模拟与数字电路)
* [数据结构](./数据结构)
+ * [数理方程](./数理方程)
* [数理逻辑](./数理逻辑)
* [算法基础](./算法基础)
* [随机过程](./随机过程)
- * [utils](./utils)
* [Web-信息处理与应用](./Web-信息处理与应用)
* [微机原理与系统](./微机原理与系统)
+ * [自然语言处理](./自然语言处理)
# 贡献投稿
-欢迎大家的参与与贡献^_^ , 欢迎联系 org 管理员, 申请加入 USTC-Resource org。
-* 仅接受学生原创的或者获得授权的资源
-* github 上不能直接上传大于 100mb 的文件。对于超过 100 mb 的文件,可以存在网盘,然后在 README 文件中贴上链接
-* 文件内容的改动会使 git 重新上传, 在没有必要的情况下, 不要对二进制文件做任何更改.
+
+>感谢您的贡献 :smiley:
+
+- 仅接受学生原创的或者获得授权的资源
+- GitHub 上不能直接上传大于 100Mb 的文件。对于超过 100 Mb 的文件,可以存在网盘,然后在 README.md 中贴上链接
+- 文件内容的改动会使 git 重新上传, 在没有必要的情况下, 不要对二进制文件做任何更改.
# 中国科学技术大学课程资源
## 说明
-下面列表根据拼音排序,可点击链接下载二进制文件,或者打开文本文件。点击这里**下载当前整个文件夹**(此功能由 [DownGit](http://downgit.zhoudaxiaa.com) 提供)。此页面[mbinary](https://mbinary.xyz) 制作
+- 列表根据拼音排序
+- 点击 Files 的链接下载二进制文件
+- 或者打开文本文件(markdown 文件经过渲染)
+
+ Directories
-## Directories
## Files
@@ -48,8 +48,8 @@
---
---
@@ -58,11 +58,14 @@
#* 非zip, 非以'.'开头的文件多于 3 个的目录下都有个 zip 文件:`-DIRECTORY 目录下的\d+个文件.zip`,包含当前目录下的一些文件, 这样方便大家一键下载. (在 git commit前, 运行 `./before__commit.sh`可以自动生成)
-README=r'''
+README = r'''
+
+
# 中国科学技术大学课程资源
+
[](https://github.com/USTC-Resource/USTC-Course/stargazers)
[](https://github.com/USTC-Resource/USTC-Course/network/members)
-[](https://travis-ci.org/USTC-Resource/USTC-Course?branch=master)
+[]()
[]()
[](http://creativecommons.org/licenses/by-nc-sa/4.0/)
@@ -82,9 +85,11 @@
对无特别声明的资料,谨以[知识共享署名 - 非商业性使用 - 相同方式共享 4.0 国际许可协议](http://creativecommons.org/licenses/by-nc-sa/4.0/) 授权。
+请创作者及公众监督,如有资料违反许可协议,请告知我们改正错误。
+
# 反馈方式
- [issue](https://github.com/USTC-Resource/USTC-Course/issues/new)
-- email
+- email
# 资料下载
[戳我(●'◡'●)](https://ustc-resource.github.io/USTC-Course)
@@ -111,7 +116,7 @@
## HTTPS
-- [github 网页](#课程目录)
+- [GitHub 网页](#课程目录)
- [DownGit](http://downgit.zhoudaxiaa.com/#/home)
- [gitzip-chrome-extension](https://chrome.google.com/webstore/detail/gitzip-for-github/ffabmkklhbepgcgfonabamgnfafbdlkn)
@@ -134,7 +139,7 @@
└ README.md
```
# 课程关系
-
+
更多信息可以下载[官网的培养方案](https://www.teach.ustc.edu.cn/education/241.html/attachment/14-215%E8%AE%A1%E7%AE%97%E6%9C%BA%E5%AD%A6%E9%99%A2-2013)
@@ -144,10 +149,12 @@
{index}
# 贡献投稿
-欢迎大家的参与与贡献^_^ , 欢迎联系 org 管理员, 申请加入 USTC-Resource org。
-* 仅接受学生原创的或者获得授权的资源
-* github 上不能直接上传大于 100mb 的文件。对于超过 100 mb 的文件,可以存在网盘,然后在 README 文件中贴上链接
-* 文件内容的改动会使 git 重新上传, 在没有必要的情况下, 不要对二进制文件做任何更改.
+
+>感谢您的贡献 :smiley:
+
+- 仅接受学生原创的或者获得授权的资源
+- GitHub 上不能直接上传大于 100Mb 的文件。对于超过 100 Mb 的文件,可以存在网盘,然后在 README.md 中贴上链接
+- 文件内容的改动会使 git 重新上传, 在没有必要的情况下, 不要对二进制文件做任何更改.
'''
-
diff --git a/utils/genIndex.py b/utils/genIndex.py
index 85b6737..544aade 100644
--- a/utils/genIndex.py
+++ b/utils/genIndex.py
@@ -1,10 +1,20 @@
#coding: utf-8
import os
import re
+from functools import partial
import markdown
import shutil
from getSize import getSize
-from config import PATH,HTML,WALKDIR,TARDIR,IGNORE,NAME,DOWNLOAD
+from config import PATH, HTML, WALKDIR, TARDIR, IGNORE, NAME, DOWNLOAD
+
+URL = 'https://github.com/USTC-Resource/USTC-Course/tree/master/'
+ImagePT = re.compile(r'\!\[(.*?)\]\(([a-zA-Z\d\.].*?)\)')
+
+
+def subFunc(match,pre):
+ name, suf = match.groups()
+ return f''
+
hasPinyin = False
try:
from pypinyin import pinyin
@@ -12,113 +22,161 @@
except:
print('No module pypinyin, using defalut method to sort')
+
def pinyinSort(items):
if hasPinyin:
- dic = {''.join(sum(pinyin(i,style=0),[])).lower():i for i in items}
+ dic = {''.join(sum(pinyin(i, style=0), [])).lower(): i for i in items}
return [dic[i] for i in sorted(dic.keys())]
else:
print('No module pypinyin')
return items
+
def md2html(s):
- exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite','markdown.extensions.tables','markdown.extensions.toc']
- s = re.sub(r'\<\!--.*?--\>','',s,flags=re.DOTALL)
- return markdown.markdown(s,extensions=exts)
+ exts = [
+ 'markdown.extensions.extra', 'markdown.extensions.codehilite',
+ 'markdown.extensions.tables', 'markdown.extensions.toc'
+ ]
+ s = re.sub(r'\<\!--.*?--\>', '', s, flags=re.DOTALL)
+ return markdown.markdown(s, extensions=exts)
+
def getFmt():
- dic={}
- sound_suf = ['file-sound-o',['mp3','wave','snd','aif','wav']]
- movie_suf =['file-movie-o', ['mp4','avi','mov','swf']]
- zip_suf = ['file-zip-o',['zip','rar','7z','tar','gz','bz','jar','z']]
- word_suf=['file-word-o',['doc','docx']]
- excel_suf=['file-excelo',['xls','xlt']]
- ppt_suf = ['file-powerpoint-o',['ppt','pptx','pps','pptx','ppa','ppam']]
- pdf_suf = ['file-pdf-o',['pdf']]
- pic_suf =['file-picture-o',['bmp','gif','png','jpg','jpeg','pic']]
- code_suf=['file-code-o',['c','o','h','sh','cc','m','cpp','py','lisp','scala','rust','java']]
- lst_suf=[sound_suf,movie_suf,zip_suf,word_suf,excel_suf,ppt_suf,pdf_suf,pic_suf,code_suf]
-
- for lst in lst_suf:
- suf, li = lst
- for i in li:
- dic[i]=suf
- dic['dir'] = 'folder'
- dic['other']='pencil-square-o'
- return dic
+ dic = {
+ 'file-audio': ['mp3', 'wave', 'snd', 'aif', 'wav'],
+ 'file-video': ['mp4', 'avi', 'mov', 'swf'],
+ 'file-archive': ['zip', 'rar', '7z', 'tar', 'gz', 'bz', 'jar', 'z'],
+ 'file-word': ['doc', 'docx'],
+ 'file-excel': ['xls', 'xlt'],
+ 'file-powerpoint': ['ppt', 'pptx', 'pps', 'pptx', 'ppa', 'ppam'],
+ 'file-pdf': ['pdf'],
+ 'file-image': ['bmp', 'gif', 'png', 'jpg', 'jpeg', 'pic'],
+ 'file-code': [
+ 'c', 'o', 'h', 'sh', 'cc', 'm', 'cpp', 'py', 'lisp', 'scala',
+ 'rust', 'java'
+ ],
+ 'file-import': ['md'],
+ }
+ FMT_DIC = {}
+ for i, li in dic.items():
+ for suf in li:
+ FMT_DIC[suf] = i
+ FMT_DIC['dir'] = 'folder'
+ FMT_DIC['other'] = 'file'
+ return FMT_DIC
+
FMT_DIC = getFmt()
+
def getIcon(name):
- suf=name[name.rfind('.')+1:]
+ suf = name[name.rfind('.') + 1:]
return FMT_DIC[suf] if suf in FMT_DIC else FMT_DIC['other']
+
def prepare():
if os.path.exists(TARDIR):
- os.system('rm -rf '+TARDIR)
+ os.system('rm -rf ' + TARDIR)
try:
os.mkdir(TARDIR)
- with open(os.path.join(TARDIR,'_config.yml'),'w',encoding='utf-8') as f:
+ with open(
+ os.path.join(TARDIR, '_config.yml'), 'w',
+ encoding='utf-8') as f:
f.write('theme: jekyll-theme-cayman\n')
- except:return
+ except:
+ return
+
+
def handleDir(target):
prepare()
n = len(target)
gen = os.walk(target)
- for path,dirs,files in gen:
+ for path, dirs, files in gen:
dirs = [d for d in dirs if d not in IGNORE]
dirs = pinyinSort(dirs)
files = pinyinSort(files)
path = path[n:].strip(os.path.sep)
segs = path.split(os.path.sep)
- if path.startswith('.') or any(seg in IGNORE for seg in segs) :continue
- tar = os.path.join(TARDIR ,path)
+ if path.startswith('.') or any(seg in IGNORE for seg in segs): continue
+ tar = os.path.join(TARDIR, path)
if 'index.html' in files:
- try:shutil.copytree(path,tar)
+ try:
+ shutil.copytree(path, tar)
except Exception as e:
- print(e,path)
- else: genIndex(path,dirs,files)
+ print(e, path)
+ else:
+ genIndex(path, dirs, files)
+
-def genIndex(path,dirs,files,htmlTemp = HTML):
+def genIndex(path, dirs, files, htmlTemp=HTML):
md = ''
if 'README.md' in files:
- with open(os.path.join(path,'README.md'),'r',errors='ignore') as f :
+ with open(os.path.join(path, 'README.md'), 'r', errors='ignore') as f:
#
\nRead Me\n
\n
- md = '\nRead Me
\n'+f.read()
+ md = '\nRead Me
\n' + f.read(
+ )
+ files.remove('README.md')
cur = getPath(path)
- dirLst = genDirectoryList(path,dirs)
- fileLst = genFileList(path,files)
- cont = htmlTemp.format(DOWNLOAD=DOWNLOAD+path,cur=cur,dirLst = dirLst,fileLst = fileLst,readme=md2html(md))
- tar = os.path.join(TARDIR ,path)
- if not os.path.exists(tar):os.mkdir(tar)
+ tar = os.path.join(TARDIR, path)
+ if not os.path.exists(tar): os.mkdir(tar)
+
+ dirLst = genDirectoryList(path, dirs)
+ fileLst = genFileList(path, files, tar)
+ cont = htmlTemp.format(
+ DOWNLOAD=DOWNLOAD + path,
+ cur=cur,
+ dirLst=dirLst,
+ fileLst=fileLst,
+ readme=md2html(md))
filename = os.path.join(tar, NAME)
- with open(filename,'w') as f:
- f.write(cont)
+ with open(filename, 'w') as f:
+ f.write(re.sub(ImagePT,partial(subFunc,pre = URL+path),cont))
+
def getPath(path):
lst = path.split(os.path.sep)
lst = lst[::-1]
- lst.append('home ')
+ lst.append('')
url = 'index.html'
res = []
for i in lst:
- res.append('{txt}'.format(url = url,txt = i))
- url='../'+url
+ res.append('{txt}'.format(url=url, txt=i))
+ url = '../' + url
return '/'.join(res[::-1])
-LIITEM = ' {name}'
-def genFileList(path,files):
- keys=[i for i in files if i[0]!='.']
- link= {i:os.path.join(path,i) for i in keys}
- lst = [LIITEM.format(icon=getIcon(key),name = key+'---({})'.format(getSize(link[key])),path = os.path.join(PATH,link[key])) for key in keys]
- if lst==[]: lst.append(' None')
+
+LIITEM = ' {name}'
+
+
+def genFileList(path, files, tar=TARDIR):
+ files = [i for i in files if not i.startswith('.')]
+ link = {}
+ for k in files:
+ if k.endswith('.md'):
+ shutil.copy(os.path.join(path, k), tar)
+ link[k] = k[:-3] + '.html'
+ else:
+ link[k] = os.path.join(PATH, path, k)
+ lst = [
+ LIITEM.format(
+ icon=getIcon(key),
+ name=key + '---({})'.format(getSize(os.path.join(path, key))),
+ path=link[key]) for key in files
+ ]
+ if lst == []: lst.append(' None')
return '\n'.join(lst)
-def genDirectoryList(path,dirs):
- keys=[i for i in dirs if i[0]!='.']
- link = {i:os.path.join(i,'index.html') for i in keys if i[0]!='.'}
- lst = [LIITEM.format(icon=FMT_DIC['dir'],name = key,path =link[key]) for key in keys]
- if lst==[]: lst.append(' None')
+
+def genDirectoryList(path, dirs):
+ keys = [i for i in dirs if i[0] != '.']
+ link = {i: os.path.join(i, 'index.html') for i in keys if i[0] != '.'}
+ lst = [
+ LIITEM.format(icon=FMT_DIC['dir'], name=key, path=link[key])
+ for key in keys
+ ]
+ if lst == []: lst.append(' None')
return '\n'.join(lst)
-if __name__ =='__main__':
+
+if __name__ == '__main__':
handleDir(WALKDIR)
diff --git a/utils/genReadme.py b/utils/genReadme.py
index 5da0185..c5beeb7 100644
--- a/utils/genReadme.py
+++ b/utils/genReadme.py
@@ -1,21 +1,24 @@
# coding: utf-8
from md_tree_links import tree
from argparse import ArgumentParser
-from config import README
+from config import README, IGNORE
parser = ArgumentParser()
-parser.add_argument('-p','--path',default='.',help='path to walk')
-parser.add_argument('-f','--fileinclude',action='store_true',help='if has, list files and dirs, else only dirs')
-parser.add_argument('-d','--depth', type = int, default = 1)
-#获取参数
+parser.add_argument('-p', '--path', default='.', help='path to walk')
+parser.add_argument(
+ '-f',
+ '--fileinclude',
+ action='store_true',
+ help='if has, list files and dirs, else only dirs')
+parser.add_argument('-d', '--depth', type=int, default=1)
+# 获取参数
args = parser.parse_args()
FILE = args.fileinclude
PATH = args.path
DEPTH = args.depth
-
-idxs = tree(PATH,DEPTH,FILE)
+idxs = tree(PATH, DEPTH, FILE, IGNORE)
s = README.format(index='\n'.join(idxs))
-with open('README.md','w') as f:
+with open('README.md', 'w') as f:
f.write(s)
diff --git a/utils/genZipFile.py b/utils/genZipFile.py
index f9b0619..0f63818 100644
--- a/utils/genZipFile.py
+++ b/utils/genZipFile.py
@@ -7,47 +7,62 @@
import argparse
parser = argparse.ArgumentParser()
-parser.add_argument('-r','--rewrite',help='rewrite zip file',action='store_true')
+parser.add_argument(
+ '-r', '--rewrite', help='rewrite zip file', action='store_true')
args = parser.parse_args()
REWRITE = args.rewrite
+
def checkZip(name):
'''check if this file should be added to the zip'''
- li = [name.startswith('.') ,name.endswith('.zip'),name.lower()=='readme.md']
+ li = [
+ name.startswith('.'),
+ name.endswith('.zip'),
+ name.lower() == 'readme.md'
+ ]
return not any(li)
-def isIgnore(li,files):
- return 'index.html' in files or any((i[0]=='.' and i!='.') or i.startswith('__') or i in IGNORE for i in li)
-def genZipFile(tar = WALKDIR,rewrite=False):
+
+def isIgnore(li, files):
+ return 'index.html' in files or any(
+ (i[0] == '.' and i != '.') or i.startswith('__') or i in IGNORE
+ for i in li)
+
+
+def genZipFile(tar=WALKDIR, rewrite=False):
os.chdir(tar)
n = len(tar)
gen = os.walk(tar)
pwd = os.path.abspath('.')
for path, dirs, files in gen:
li = path.strip(os.sep).split(os.sep)
- if isIgnore(li,files):continue
+ if isIgnore(li, files): continue
ziplst = []
for i in files:
if i.endswith('个文件.zip'):
if rewrite:
- os.remove(os.path.join(path,i))
- else:break
+ os.remove(os.path.join(path, i))
+ else:
+ break
elif checkZip(i):
- ziplst .append(i)
+ ziplst.append(i)
else:
- if len(ziplst)<3:continue
+ if len(ziplst) < 3: continue
ziplst.sort()
tmp = os.path.abspath(path) \
.replace(pwd,'')\
.replace(os.sep,'-')
- name = '{tmp}目录下的{length}个文件.zip'.format(tmp=tmp,length =len(ziplst))
- zipName = os.path.join(path,name)
+ name = '{tmp}目录下的{length}个文件.zip'.format(
+ tmp=tmp, length=len(ziplst))
+ zipName = os.path.join(path, name)
try:
- with ZipFile(zipName,'w') as z:
+ with ZipFile(zipName, 'w') as z:
os.chdir(path)
- for i in ziplst: z.write(i)
+ for i in ziplst:
+ z.write(i)
except Exception as e:
- print(e,path)
+ print(e, path)
+
if __name__ == '__main__':
genZipFile(rewrite=REWRITE)
diff --git a/utils/getSize.py b/utils/getSize.py
index 0e16d89..6a717e8 100644
--- a/utils/getSize.py
+++ b/utils/getSize.py
@@ -1,22 +1,24 @@
# coding: utf-8
import os
import sys
+
+
def formatSize(size):
s = 'BKMGTP'
ct = 0
- while size>=(1<=10: ct-=10
- return '{sz:.2f}{a}'.format(sz=size/(1<= (1 << ct):
+ ct += 10
+ if ct >= 10: ct -= 10
+ return '{sz:.2f}{a}'.format(sz=size / (1 << ct), a=s[ct // 10])
def getSize(path='.'):
if os.path.isdir(path):
gen = os.walk(path)
- li = []
+ li = []
for root, dirs, files in gen:
for f in files:
- sz = os.path.getsize(os.path.join(root ,f))
+ sz = os.path.getsize(os.path.join(root, f))
li.append(sz)
#li.insert(('.',sum(i[1] for i in li)),0)
#size = [f'{i[0]}: {formatSize(i[1])}' for i in li]
@@ -24,7 +26,8 @@ def getSize(path='.'):
else:
return formatSize(os.path.getsize(path))
+
if __name__ == "__main__":
items = sys.argv[1:]
for i in items:
- print('{i}: {sz}'.format(i=i,sz =getSize(i)))
+ print('{i}: {sz}'.format(i=i, sz=getSize(i)))
diff --git a/utils/md_tree_links.py b/utils/md_tree_links.py
index 108badf..bd51296 100644
--- a/utils/md_tree_links.py
+++ b/utils/md_tree_links.py
@@ -3,43 +3,58 @@
from pinyinSort import pinyinSort
from argparse import ArgumentParser
-#命令行输入参数处理
+# 命令行输入参数处理
parser = ArgumentParser()
-parser.add_argument('-p','--path',default='.',help='path to walk')
-parser.add_argument('-f','--fileinclude',action='store_true',help='if has, list files and dirs, else only dirs')
-parser.add_argument('-d','--depth', type = int, default = 2)
-#获取参数
+parser.add_argument('-p', '--path', default='.', help='path to walk')
+parser.add_argument(
+ '-f',
+ '--fileinclude',
+ action='store_true',
+ help='if has, list files and dirs, else only dirs')
+parser.add_argument('-d', '--depth', type=int, default=2)
+# 获取参数
args = parser.parse_args()
FILE = args.fileinclude
PATH = args.path
DEPTH = args.depth
+
def mklink(path):
- return '* [{name}]({path})'.format(name=os.path.basename(path),path=path)
+ return '* [{name}]({path})'.format(name=os.path.basename(path), path=path)
+
+
def clean(paths):
ret = []
for path in paths:
name = os.path.basename(path)
- if not ( name.startswith('.') or name.startswith('__')):
+ if not (name.startswith('.') or name.startswith('__')):
ret.append(path)
return ret
-def tree(path='.',depth=2,showfile=False):
+
+def tree(path='.', depth=2, showfile=False, ignore=None):
while not os.path.isdir(path):
print('[error]: please input a directory, not file path')
path = input()
- li = os.listdir(path)
- items = [os.path.join(path,i) for i in li if not i.startswith('.')]
+ if ignore is None:
+ ignore = set()
+ else:
+ ignore = set(ignore)
+ li = [i for i in os.listdir(
+ path) if i not in ignore and not i.startswith('.')]
+ items = [os.path.join(path, i) for i in li]
items = clean(items)
items = pinyinSort(items)
- if not showfile: items = [i for i in items if os.path.isdir(i)]
- if depth==1:
- return [mklink(path)] + [' '*4 + mklink(i) for i in items]
+ if not showfile:
+ items = [i for i in items if os.path.isdir(i)]
+ if depth == 1:
+ return [mklink(path)] + [' ' * 4 + mklink(i) for i in items]
else:
- uls = [tree(i,depth-1,showfile) for i in items]
- ret = [' '*4 + li for ul in uls for li in ul]
- return [mklink(path)] + ret
+ uls = [tree(i, depth - 1, showfile) for i in items]
+ ret = [' ' * 4 + li for ul in uls for li in ul]
+ return [mklink(path)] + ret
+
-if __name__ =='__main__':
- print('\n'.join(tree(PATH,DEPTH,FILE)))
+if __name__ == '__main__':
+ print('\n'.join(tree(PATH, DEPTH, FILE)))
diff --git a/utils/mywalk.py b/utils/mywalk.py
index f7c6403..af6b950 100644
--- a/utils/mywalk.py
+++ b/utils/mywalk.py
@@ -1,17 +1,18 @@
import os
-def mywalk(dire,valid=lambda x:True):
+
+def mywalk(dire, valid=lambda x: True):
if not os.path.isdir(dire):
raise Exception('[Error]: directory excepted')
dirs = []
files = []
for i in os.listdir(dire):
- i = os.path.join(dire,i)
+ i = os.path.join(dire, i)
if valid(i):
if os.path.isdir(i):
dirs.append(i)
else:
files.append(i)
- yield dire,dirs,files
+ yield dire, dirs, files
for d in dirs:
- yield from mywalk(os.path.join(dire,d),valid)
+ yield from mywalk(os.path.join(dire, d), valid)
diff --git a/utils/pinyinSort.py b/utils/pinyinSort.py
index 69891fd..3cc70e8 100644
--- a/utils/pinyinSort.py
+++ b/utils/pinyinSort.py
@@ -1,19 +1,22 @@
# coding: utf-8
-hasPinyin=False
+hasPinyin = False
try:
from pypinyin import pinyin
- hasPinyin=True
+ hasPinyin = True
except:
print('No module pypinyin, using defalut method to sort')
+
def pinyinSort(items):
if hasPinyin:
- dic = {''.join(sum(pinyin(i,style=0),[])).lower():i for i in items}
+ dic = {''.join(sum(pinyin(i, style=0), [])).lower(): i for i in items}
return [dic[i] for i in sorted(dic.keys())]
- else:return items
+ else:
+ return items
+
-if __name__ =='__main__':
- s='你是谁中国科学技术大学'
+if __name__ == '__main__':
+ s = '你是谁中国科学技术大学'
li = list(s)
print(li)
for i in pinyinSort(li):
diff --git "a/\345\205\211\345\255\246\344\270\216\345\216\237\345\255\220\347\211\251\347\220\206/notes/\345\205\211\345\255\246\345\205\254\345\274\2172016\347\247\213.pdf" "b/\345\205\211\345\255\246\344\270\216\345\216\237\345\255\220\347\211\251\347\220\206/notes/\345\205\211\345\255\246\345\205\254\345\274\2172016\347\247\213.pdf"
new file mode 100644
index 0000000..d4d609e
Binary files /dev/null and "b/\345\205\211\345\255\246\344\270\216\345\216\237\345\255\220\347\211\251\347\220\206/notes/\345\205\211\345\255\246\345\205\254\345\274\2172016\347\247\213.pdf" differ
diff --git "a/\345\205\211\345\255\246\344\270\216\345\216\237\345\255\220\347\211\251\347\220\206/notes/\345\216\237\345\255\220\347\211\251\347\220\206\345\244\215\344\271\240\350\246\201\347\202\271.pdf" "b/\345\205\211\345\255\246\344\270\216\345\216\237\345\255\220\347\211\251\347\220\206/notes/\345\216\237\345\255\220\347\211\251\347\220\206\345\244\215\344\271\240\350\246\201\347\202\271.pdf"
new file mode 100644
index 0000000..3ee862d
Binary files /dev/null and "b/\345\205\211\345\255\246\344\270\216\345\216\237\345\255\220\347\211\251\347\220\206/notes/\345\216\237\345\255\220\347\211\251\347\220\206\345\244\215\344\271\240\350\246\201\347\202\271.pdf" differ
diff --git "a/\345\244\247\345\255\246\347\211\251\347\220\206\345\256\236\351\252\214/README.md" "b/\345\244\247\345\255\246\347\211\251\347\220\206\345\256\236\351\252\214/README.md"
deleted file mode 100644
index af419c8..0000000
--- "a/\345\244\247\345\255\246\347\211\251\347\220\206\345\256\236\351\252\214/README.md"
+++ /dev/null
@@ -1,8 +0,0 @@
-## 大物实验模板
-
-> 百度云资源,来自 qq 群 973935817
-
-* [1 级](https://pan.baidu.com/s/1oRoANGJAR1VdEPBmArmX0w) 提取码:kpmk
-* [2 级](https://pan.baidu.com/s/1QZ3wyN-fC1Hr0cdGZx672A) 提取码:yfnz
-* [3 级](https://pan.baidu.com/s/1J39pLvg_r4FTsg0tgmCO4A) 提取码:z9v8
-* [5 级](https://pan.baidu.com/s/1ECwc9jSy_kODFslJaTcC-Q) 提取码:6u3q
diff --git "a/\346\223\215\344\275\234\347\263\273\347\273\237\345\216\237\347\220\206\344\270\216\350\256\276\350\256\241/homeworks/\346\223\215\344\275\234\347\263\273\347\273\237\346\246\202\345\277\265\346\225\231\346\235\220\347\254\2547\347\211\210\350\257\276\345\220\216\347\273\203\344\271\240\347\255\224\346\241\210(\350\213\261\346\226\207\345\256\214\346\225\264\347\211\210).pdf" "b/\346\223\215\344\275\234\347\263\273\347\273\237\345\216\237\347\220\206\344\270\216\350\256\276\350\256\241/homeworks/\346\223\215\344\275\234\347\263\273\347\273\237\346\246\202\345\277\265\346\225\231\346\235\220\347\254\2547\347\211\210\350\257\276\345\220\216\347\273\203\344\271\240\347\255\224\346\241\210(\350\213\261\346\226\207\345\256\214\346\225\264\347\211\210).pdf"
deleted file mode 100644
index 3b059a6..0000000
Binary files "a/\346\223\215\344\275\234\347\263\273\347\273\237\345\216\237\347\220\206\344\270\216\350\256\276\350\256\241/homeworks/\346\223\215\344\275\234\347\263\273\347\273\237\346\246\202\345\277\265\346\225\231\346\235\220\347\254\2547\347\211\210\350\257\276\345\220\216\347\273\203\344\271\240\347\255\224\346\241\210(\350\213\261\346\226\207\345\256\214\346\225\264\347\211\210).pdf" and /dev/null differ
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/allOone.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/allOone.py"
index c700df2..3efafec 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/allOone.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/allOone.py"
@@ -10,127 +10,168 @@
#########################################################################
'''
+
class node:
- def __init__(self,val=None,data_mp=None,pre=None,next=None):
- self.val=val
+ def __init__(self, val=None, data_mp=None, pre=None, next=None):
+ self.val = val
self.data_mp = {} if data_mp is None else data_mp
- self.pre=pre
- self.next=next
- def __lt__(self,nd):
- return self.valval or self.head.val==0:self.head= self.chain_mp[val]
- def delNode(self,val):
+ if dec: self.addDecNode(val)
+ else: self.addIncNode(val)
+ if self.tail.val < val: self.tail = self.chain_mp[val]
+ if self.head.val > val or self.head.val == 0:
+ self.head = self.chain_mp[val]
+
+ def delNode(self, val):
self.chain_mp[val].next.pre = self.chain_mp[val].pre
self.chain_mp[val].pre.next = self.chain_mp[val].next
- if self.tail.val==val:self.tail = self.chain_mp[val].pre
- if self.head.val==val:self.head = self.chain_mp[val].next
+ if self.tail.val == val: self.tail = self.chain_mp[val].pre
+ if self.head.val == val: self.head = self.chain_mp[val].next
del self.chain_mp[val]
- def incTo(self,key,val):
- if val not in self.chain_mp:
+
+ def incTo(self, key, val):
+ if val not in self.chain_mp:
self.addNode(val)
self.chain_mp[val][key] = val
- if val!=1 : # key in the pre node
- del self.chain_mp[val-1][key]
+ if val != 1: # key in the pre node
+ del self.chain_mp[val - 1][key]
#print(self.chain_mp[val-1])
- if self.chain_mp[val-1].isEmpty():
+ if self.chain_mp[val - 1].isEmpty():
#print('*'*20)
- self.delNode(val-1)
- def decTo(self,key,val):
+ self.delNode(val - 1)
+
+ def decTo(self, key, val):
if val not in self.chain_mp:
- self.addNode(val,dec=True)
+ self.addNode(val, dec=True)
# notice that the headnode(0) shouldn't add key
- if val!=0: self.chain_mp[val][key] = val
- del self.chain_mp[val+1][key]
- if self.chain_mp[val+1].isEmpty():
- self.delNode(val+1)
-
+ if val != 0: self.chain_mp[val][key] = val
+ del self.chain_mp[val + 1][key]
+ if self.chain_mp[val + 1].isEmpty():
+ self.delNode(val + 1)
+
+
class AllOne:
def __init__(self):
"""
Initialize your data structure here.
"""
- self.op = {"inc":self.inc,"dec":self.dec,"getMaxKey":self.getMaxKey,"getMinKey":self.getMinKey}
+ self.op = {
+ "inc": self.inc,
+ "dec": self.dec,
+ "getMaxKey": self.getMaxKey,
+ "getMinKey": self.getMinKey
+ }
self.mp = {}
self.dll = doubleLinkedList()
+
def __str__(self):
return str(self.dll)
- def __getitem__(self,key):
+
+ def __getitem__(self, key):
return self.mp[key]
- def __delitem__(self,key):
+
+ def __delitem__(self, key):
del self.mp[key]
- def __setitem__(self,key,val):
- self.mp[key]= val
+
+ def __setitem__(self, key, val):
+ self.mp[key] = val
+
def __iter__(self):
return iter(self.mp)
- def inc(self, key,n=1):
+
+ def inc(self, key, n=1):
"""
Inserts a new key with value 1. Or increments an existing key by 1.
:type key: str
:rtype: void
"""
if key in self:
- self[key]+=n
- else:self[key]=n
- for i in range(n): self.dll.incTo(key, self[key])
- def dec(self, key,n=1):
+ self[key] += n
+ else:
+ self[key] = n
+ for i in range(n):
+ self.dll.incTo(key, self[key])
+
+ def dec(self, key, n=1):
"""
Decrements an existing key by 1. If Key's value is 1, remove it from the data structure.
:type key: str
:rtype: void
"""
if key in self.mp:
- mn = min( self[key],n)
- for i in range(mn): self.dll.decTo(key, self[key]-i-1)
+ mn = min(self[key], n)
+ for i in range(mn):
+ self.dll.decTo(key, self[key] - i - 1)
if self[key] == n:
del self[key]
else:
- self[key] = self[key]-n
+ self[key] = self[key] - n
+
def getMaxKey(self):
"""
Returns one of the keys with maximal value.
@@ -146,17 +187,17 @@ def getMinKey(self):
return self.dll.getMin()
-
-
if __name__ == '__main__':
- ops=["inc","inc","inc","inc","inc","dec","dec","getMaxKey","getMinKey"]
- data=[["a"],["b"],["b"],["b"],["b"],["b"],["b"],[],[]]
+ ops = [
+ "inc", "inc", "inc", "inc", "inc", "dec", "dec", "getMaxKey",
+ "getMinKey"
+ ]
+ data = [["a"], ["b"], ["b"], ["b"], ["b"], ["b"], ["b"], [], []]
obj = AllOne()
- for op,datum in zip(ops,data):
+ for op, datum in zip(ops, data):
print(obj.op[op](*datum))
- print(op,datum)
+ print(op, datum)
print(obj)
-
'''
None
inc ['a']
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/test.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/test.py"
index 207c14b..53e3a36 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/test.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/allOone/test.py"
@@ -12,59 +12,74 @@
from allOone import AllOne
from time import time
-from random import choice,sample,randint
+from random import choice, sample, randint
+
class hashMap:
def __init__(self):
- self.op = {"inc":self.inc,"dec":self.dec,"getMaxKey":self.getMaxKey,"getMinKey":self.getMinKey}
- self.mp={'':0}
- def inc(self,key,n=1):
- if key in self.mp:self.mp[key]+=n
- else:self.mp[key]=n
- def dec(self,key,n=1):
- if key not in self.mp:return
- if self.mp[key]<=n:del self.mp[key]
- else: self.mp[key]-=n
+ self.op = {
+ "inc": self.inc,
+ "dec": self.dec,
+ "getMaxKey": self.getMaxKey,
+ "getMinKey": self.getMinKey
+ }
+ self.mp = {'': 0}
+
+ def inc(self, key, n=1):
+ if key in self.mp: self.mp[key] += n
+ else: self.mp[key] = n
+
+ def dec(self, key, n=1):
+ if key not in self.mp: return
+ if self.mp[key] <= n: del self.mp[key]
+ else: self.mp[key] -= n
+
def getMinKey(self):
- return min(list(self.mp.keys()),key=lambda key:self.mp[key])
+ return min(list(self.mp.keys()), key=lambda key: self.mp[key])
+
def getMaxKey(self):
- return max(list(self.mp.keys()),key=lambda key:self.mp[key])
+ return max(list(self.mp.keys()), key=lambda key: self.mp[key])
+
+op_origin = [
+ 'inc', 'dec', 'getMinKey', 'getMaxKey'
+] #'getMinKey','getMaxKey','getMinKey','getMaxKey','getMinKey','getMaxKey','getMinKey','getMaxKey']
+ch = list('qwertyuiopasdfghjklzxcvbnm')
+keys = [''.join(sample(ch, i)) for j in range(10) for i in range(1, 20, 5)]
-op_origin = ['inc','dec','getMinKey','getMaxKey']#'getMinKey','getMaxKey','getMinKey','getMaxKey','getMinKey','getMaxKey','getMinKey','getMaxKey']
-ch=list('qwertyuiopasdfghjklzxcvbnm')
-keys =[ ''.join(sample(ch,i)) for j in range(10) for i in range(1,20,5)]
def testCase(n=1000):
- ops=[]
- data=[]
+ ops = []
+ data = []
for i in range(n):
- p = randint(0,len(op_origin)-1)
+ p = randint(0, len(op_origin) - 1)
ops.append(op_origin[p])
- if p<2:
- data.append([randint(1,5)])
- else:data.append([])
- return ops,data
+ if p < 2:
+ data.append([randint(1, 5)])
+ else:
+ data.append([])
+ return ops, data
+
def test(repeat=100):
- t1,t2=0,0
+ t1, t2 = 0, 0
for i in range(repeat):
allOne = AllOne()
hsmp = hashMap()
- ops,data = testCase()
- t1-=time()
- for op,datum in zip(ops,data):
+ ops, data = testCase()
+ t1 -= time()
+ for op, datum in zip(ops, data):
allOne.op[op](*datum)
- t1+=time()
+ t1 += time()
- t2-=time()
- for op,datum in zip(ops,data):
+ t2 -= time()
+ for op, datum in zip(ops, data):
hsmp.op[op](*datum)
- t2+=time()
- return t1,t2
+ t2 += time()
+ return t1, t2
-if __name__=='__main__':
- t1,t2= test()
+if __name__ == '__main__':
+ t1, t2 = test()
print(f'allOone: {t1}')
print(f'hashmap: {t2}')
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/bTree.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/bTree.py"
index 1b9a888..420a486 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/bTree.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/bTree.py"
@@ -1,201 +1,230 @@
class node:
- def __init__(self,keys=None,isLeaf = True,children=None):
- if keys is None:keys=[]
- if children is None: children =[]
+ def __init__(self, keys=None, isLeaf=True, children=None):
+ if keys is None: keys = []
+ if children is None: children = []
self.keys = keys
- self.isLeaf = isLeaf
+ self.isLeaf = isLeaf
self.children = []
- def __getitem__(self,i):
+
+ def __getitem__(self, i):
return self.keys[i]
- def __delitem__(self,i):
+
+ def __delitem__(self, i):
del self.keys[i]
- def __setitem__(self,i,k):
+
+ def __setitem__(self, i, k):
self.keys[i] = k
+
def __len__(self):
return len(self.keys)
+
def __repr__(self):
return str(self.keys)
+
def __str__(self):
children = ','.join([str(nd.keys) for nd in self.children])
return f'keys: {self.keys}\nchildren: {children}\nisLeaf: {self.isLeaf}'
- def getChd(self,i):
+
+ def getChd(self, i):
return self.children[i]
- def delChd(self,i):
+
+ def delChd(self, i):
del self.children[i]
- def setChd(self,i,chd):
+
+ def setChd(self, i, chd):
self.children[i] = chd
- def getChildren(self,begin=0,end=None):
- if end is None:return self.children[begin:]
+
+ def getChildren(self, begin=0, end=None):
+ if end is None: return self.children[begin:]
return self.children[begin:end]
- def findKey(self,key):
- for i,k in enumerate(self.keys):
- if k>=key:
+
+ def findKey(self, key):
+ for i, k in enumerate(self.keys):
+ if k >= key:
return i
return len(self)
- def update(self,keys=None,isLeaf=None,children=None):
- if keys is not None:self.keys = keys
- if children is not None:self.children = children
+
+ def update(self, keys=None, isLeaf=None, children=None):
+ if keys is not None: self.keys = keys
+ if children is not None: self.children = children
if isLeaf is not None: self.isLeaf = isLeaf
- def insert(self,i,key=None,nd=None):
- if key is not None:self.keys.insert(i,key)
- if not self.isLeaf and nd is not None: self.children.insert(i,nd)
- def isLeafNode(self):return self.isLeaf
- def split(self,prt,t):
+
+ def insert(self, i, key=None, nd=None):
+ if key is not None: self.keys.insert(i, key)
+ if not self.isLeaf and nd is not None: self.children.insert(i, nd)
+
+ def isLeafNode(self):
+ return self.isLeaf
+
+ def split(self, prt, t):
# form new two nodes
- k = self[t-1]
+ k = self[t - 1]
nd1 = node()
nd2 = node()
- nd1.keys,nd2.keys = self[:t-1], self[t:] # note that t is 1 bigger than key index
+ nd1.keys, nd2.keys = self[:t - 1], self[
+ t:] # note that t is 1 bigger than key index
nd1.isLeaf = nd2.isLeaf = self.isLeaf
- if not self.isLeaf:
+ if not self.isLeaf:
# note that children index is one bigger than key index, and all children included
- nd1.children, nd2.children = self.children[0:t], self.children[t:]
+ nd1.children, nd2.children = self.children[0:t], self.children[t:]
# connect them to parent
idx = prt.findKey(k)
- if prt.children !=[]: prt.children.remove(self) # remove the original node
- prt.insert(idx,k,nd2)
- prt.insert(idx,nd = nd1)
+ if prt.children != []:
+ prt.children.remove(self) # remove the original node
+ prt.insert(idx, k, nd2)
+ prt.insert(idx, nd=nd1)
return prt
class bTree:
- def __init__(self,degree=2):
+ def __init__(self, degree=2):
self.root = node()
- self.degree=degree
+ self.degree = degree
self.nodeNum = 1
self.keyNum = 0
- def search(self,key,withpath=False):
+
+ def search(self, key, withpath=False):
nd = self.root
fathers = []
while True:
i = nd.findKey(key)
- if i==len(nd): fathers.append((nd,i-1,i))
- else: fathers.append((nd,i,i))
- if i1:self.rebalance(fathers)
- def rebalance(self,fathers):
- nd,keyIdx,chdIdx = fathers.pop()
- while len(nd) 1: self.rebalance(fathers)
+
+ def rebalance(self, fathers):
+ nd, keyIdx, chdIdx = fathers.pop()
+ while len(nd) < self.degree - 1: # rebalance tree from down to up
+ prt, keyIdx, chdIdx = fathers[-1]
+ lbro = [] if chdIdx == 0 else prt.getChd(chdIdx - 1)
+ rbro = [] if chdIdx == len(prt) else prt.getChd(chdIdx + 1)
+ if len(lbro) < self.degree and len(
+ rbro) < self.degree: # merge two deficient nodes
+ beforeNode, afterNode = None, None
+ if lbro == []:
keyIdx = chdIdx
- beforeNode,afterNode = nd,rbro
+ beforeNode, afterNode = nd, rbro
else:
- beforeNode,afterNode = lbro,nd
- keyIdx = chdIdx-1 # important, when choosing
- keys = beforeNode[:]+[prt[keyIdx]]+afterNode[:]
+ beforeNode, afterNode = lbro, nd
+ keyIdx = chdIdx - 1 # important, when choosing
+ keys = beforeNode[:] + [prt[keyIdx]] + afterNode[:]
children = beforeNode.getChildren() + afterNode.getChildren()
isLeaf = beforeNode.isLeafNode()
- prt.delChd(keyIdx+1)
+ prt.delChd(keyIdx + 1)
del prt[keyIdx]
- nd.update(keys,isLeaf,children)
- prt.children[keyIdx]=nd
- self.nodeNum -=1
- elif len(lbro)>=self.degree: # rotate when only one sibling is deficient
- keyIdx = chdIdx-1
- nd.insert(0,prt[keyIdx]) # rotate keys
- prt[keyIdx] = lbro[-1]
+ nd.update(keys, isLeaf, children)
+ prt.children[keyIdx] = nd
+ self.nodeNum -= 1
+ elif len(
+ lbro
+ ) >= self.degree: # rotate when only one sibling is deficient
+ keyIdx = chdIdx - 1
+ nd.insert(0, prt[keyIdx]) # rotate keys
+ prt[keyIdx] = lbro[-1]
del lbro[-1]
- if not nd.isLeafNode(): # if not leaf, move children
- nd.insert(0,nd=lbro.getChd(-1))
+ if not nd.isLeafNode(): # if not leaf, move children
+ nd.insert(0, nd=lbro.getChd(-1))
lbro.delChd(-1)
else:
keyIdx = chdIdx
- nd.insert(len(nd),prt[keyIdx]) # rotate keys
- prt[keyIdx] = rbro[0]
+ nd.insert(len(nd), prt[keyIdx]) # rotate keys
+ prt[keyIdx] = rbro[0]
del rbro[0]
- if not nd.isLeafNode(): # if not leaf, move children
+ if not nd.isLeafNode(): # if not leaf, move children
#note that insert(-1,ele) will make the ele be the last second one
- nd.insert(len(nd),nd=rbro.getChd(0))
+ nd.insert(len(nd), nd=rbro.getChd(0))
rbro.delChd(0)
- if len(fathers)==1:
- if len(self.root)==0:
+ if len(fathers) == 1:
+ if len(self.root) == 0:
self.root = nd
- self.nodeNum -=1
+ self.nodeNum -= 1
break
- nd,i,j = fathers.pop()
+ nd, i, j = fathers.pop()
+
def __str__(self):
- head= '\n'+'-'*30+'B Tree'+'-'*30
- tail= '-'*30+'the end'+'-'*30+'\n'
- lst = [[head],[f'node num: {self.nodeNum}, key num: {self.keyNum}']]
+ head = '\n' + '-' * 30 + 'B Tree' + '-' * 30
+ tail = '-' * 30 + 'the end' + '-' * 30 + '\n'
+ lst = [[head], [f'node num: {self.nodeNum}, key num: {self.keyNum}']]
cur = []
- ndNum =0
- ndTotal= 1
+ ndNum = 0
+ ndTotal = 1
que = [self.root]
- while que!=[]:
+ while que != []:
nd = que.pop(0)
cur.append(repr(nd))
- ndNum+=1
- que+=nd.getChildren()
- if ndNum==ndTotal:
+ ndNum += 1
+ que += nd.getChildren()
+ if ndNum == ndTotal:
lst.append(cur)
cur = []
ndNum = 0
- ndTotal =len(que)
+ ndTotal = len(que)
lst.append([tail])
lst = [','.join(li) for li in lst]
return '\n'.join(lst)
- def __iter__(self,nd = None):
+
+ def __iter__(self, nd=None):
if nd is None: nd = self.root
que = [nd]
- while que !=[]:
+ while que != []:
nd = que.pop(0)
yield nd
- if nd.isLeafNode():continue
- for i in range(len(nd)+1):
+ if nd.isLeafNode(): continue
+ for i in range(len(nd) + 1):
que.append(nd.getChd(i))
-if __name__ =='__main__':
+if __name__ == '__main__':
bt = bTree()
- from random import shuffle,sample
+ from random import shuffle, sample
n = 20
lst = [i for i in range(n)]
shuffle(lst)
- test= sample(lst,len(lst)//4)
+ test = sample(lst, len(lst) // 4)
print(f'building b-tree with {lst}')
for i in lst:
bt.insert(i)
@@ -204,7 +233,7 @@ def __iter__(self,nd = None):
print(bt)
print(f'serching {test}')
for i in test:
- nd,idx = bt.search(i)
+ nd, idx = bt.search(i)
print(f'node: {repr(nd)}[{idx}]== {i}')
for i in test:
print(f'deleting {i}')
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryHeap.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryHeap.py"
index f5452d1..f41c744 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryHeap.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryHeap.py"
@@ -10,107 +10,129 @@
#########################################################################
'''
+from collections import Iterable
+
-from collections import Iterable
class node:
- def __init__(self,val,freq=1):
- self.val=val
+ def __init__(self, val, freq=1):
+ self.val = val
self.freq = freq
- def __eq__(self,a):
- return self.val == a.val
- def __lt__(self,a):
- return self.vala.val
- def __ge__(self,a):
- return self.val>=a.val
- def __ne__(self,a):
+
+ def __eq__(self, a):
+ return self.val == a.val
+
+ def __lt__(self, a):
+ return self.val < a.val
+
+ def __le__(self, a):
+ return self.val <= a.val
+
+ def __gt__(self, a):
+ return self.val > a.val
+
+ def __ge__(self, a):
+ return self.val >= a.val
+
+ def __ne__(self, a):
return not self == a
+
+
class binaryHeap:
- def __init__(self,s=None,sortByFrequency = False,reverse=False):
- self.sortByFrequency=sortByFrequency
+ def __init__(self, s=None, sortByFrequency=False, reverse=False):
+ self.sortByFrequency = sortByFrequency
self.reverse = reverse
self.data = [node(0)] # make index begin with 1
- if s==None:return
- if not isinstance(s,Iterable):s = [s]
+ if s == None: return
+ if not isinstance(s, Iterable): s = [s]
for i in s:
self.insert(i)
+
def __bool__(self):
- return len(self)!=1
- def _cmp(self,a,b):
+ return len(self) != 1
+
+ def _cmp(self, a, b):
if self.sortByFrequency:
- if self.reverse:return a.freq>b.freq
- else:return a.freq b.freq
+ else: return a.freq < b.freq
else:
- if self.reverse:return a>b
- else:return a b
+ else: return a < b
+
+ def insert(self, k):
+ if not isinstance(k, node): k = node(k)
for j in range(self.data[0].val):
- i = self.data[j+1]
- if i==k:
- i.freq+=1
+ i = self.data[j + 1]
+ if i == k:
+ i.freq += 1
if self.sortByFrequency:
- idx = self.percolateDown(j+1)
+ idx = self.percolateDown(j + 1)
self.percolateUp(idx)
- return
+ return
self.data.append(k)
self.data[0].val += 1
self.percolateUp()
- def percolateUp(self,n=None):
- if n ==None:n=self.data[0].val
+
+ def percolateUp(self, n=None):
+ if n == None: n = self.data[0].val
tmp = self.data[n]
- while n!=1 and self._cmp(tmp,self.data[n//2]):
- self.data[n] = self.data[n//2]
- n = n//2
+ while n != 1 and self._cmp(tmp, self.data[n // 2]):
+ self.data[n] = self.data[n // 2]
+ n = n // 2
self.data[n] = tmp
+
def deleteTop(self):
tmp = self.data[1]
i = self.percolateDown(1)
self.data[i] = self.data[-1]
- self.data[0].val-= 1
+ self.data[0].val -= 1
del self.data[-1]
return tmp
- def percolateDown(self,i):
+
+ def percolateDown(self, i):
tmp = self.data[i]
- while self.data[0].val>=2*i+1:
- if self._cmp(self.data[i*2],self.data[2*i+1]):
- self.data[i] = self.data[2*i]
- i = 2*i
- else:
- self.data[i] = self.data[2*i+1]
- i = 2*i+1
+ while self.data[0].val >= 2 * i + 1:
+ if self._cmp(self.data[i * 2], self.data[2 * i + 1]):
+ self.data[i] = self.data[2 * i]
+ i = 2 * i
+ else:
+ self.data[i] = self.data[2 * i + 1]
+ i = 2 * i + 1
self.data[i] = tmp
return i
+
def __len__(self):
return self.data[0].val
- def Nth(self,n=1):
+
+ def Nth(self, n=1):
tmp = []
for i in range(n):
tmp.append(self.deleteTop())
for i in tmp:
self.insert(i)
return tmp[-1]
+
def display(self):
- val =self.data[0].val+1
+ val = self.data[0].val + 1
if self.sortByFrequency:
- info='heapSort by Frequency:'
- else:info = 'heapSort by Value:'
+ info = 'heapSort by Frequency:'
+ else:
+ info = 'heapSort by Value:'
if self.reverse:
- info +=' From big to small'
- else:info +=' From small to big'
- print('*'*15)
+ info += ' From big to small'
+ else:
+ info += ' From small to big'
+ print('*' * 15)
print(info)
- print('total items:%d\nval\tfreq'%(val-1))
+ print('total items:%d\nval\tfreq' % (val - 1))
fmt = '{}\t{}'
- for i in range(1,val):
- print(fmt.format(self.data[i].val,self.data[i].freq))
- print('*'*15)
+ for i in range(1, val):
+ print(fmt.format(self.data[i].val, self.data[i].freq))
+ print('*' * 15)
+
+
class Test:
def topKFrequent(self, words, k):
- hp = binaryHeap(sortByFrequency = True,reverse=True)
+ hp = binaryHeap(sortByFrequency=True, reverse=True)
for i in words:
hp.insert(i)
hp.display()
@@ -124,15 +146,34 @@ def topKFrequent(self, words, k):
mp[top.freq] = [top.val]
for i in mp:
mp[i].sort()
- key = sorted(mp.keys(),reverse = True)
+ key = sorted(mp.keys(), reverse=True)
rst = []
count = 0
- for i in key:
+ for i in key:
for j in mp[i]:
rst.append(j)
- count+=1
- if count == k:return rst
+ count += 1
+ if count == k: return rst
+
+
if __name__ == '__main__':
- s=["plpaboutit","jnoqzdute","sfvkdqf","mjc","nkpllqzjzp","foqqenbey","ssnanizsav","nkpllqzjzp","sfvkdqf","isnjmy","pnqsz","hhqpvvt","fvvdtpnzx","jkqonvenhx","cyxwlef","hhqpvvt","fvvdtpnzx","plpaboutit","sfvkdqf","mjc","fvvdtpnzx","bwumsj","foqqenbey","isnjmy","nkpllqzjzp","hhqpvvt","foqqenbey","fvvdtpnzx","bwumsj","hhqpvvt","fvvdtpnzx","jkqonvenhx","jnoqzdute","foqqenbey","jnoqzdute","foqqenbey","hhqpvvt","ssnanizsav","mjc","foqqenbey","bwumsj","ssnanizsav","fvvdtpnzx","nkpllqzjzp","jkqonvenhx","hhqpvvt","mjc","isnjmy","bwumsj","pnqsz","hhqpvvt","nkpllqzjzp","jnoqzdute","pnqsz","nkpllqzjzp","jnoqzdute","foqqenbey","nkpllqzjzp","hhqpvvt","fvvdtpnzx","plpaboutit","jnoqzdute","sfvkdqf","fvvdtpnzx","jkqonvenhx","jnoqzdute","nkpllqzjzp","jnoqzdute","fvvdtpnzx","jkqonvenhx","hhqpvvt","isnjmy","jkqonvenhx","ssnanizsav","jnoqzdute","jkqonvenhx","fvvdtpnzx","hhqpvvt","bwumsj","nkpllqzjzp","bwumsj","jkqonvenhx","jnoqzdute","pnqsz","foqqenbey","sfvkdqf","sfvkdqf"]
+ s = [
+ "plpaboutit", "jnoqzdute", "sfvkdqf", "mjc", "nkpllqzjzp", "foqqenbey",
+ "ssnanizsav", "nkpllqzjzp", "sfvkdqf", "isnjmy", "pnqsz", "hhqpvvt",
+ "fvvdtpnzx", "jkqonvenhx", "cyxwlef", "hhqpvvt", "fvvdtpnzx",
+ "plpaboutit", "sfvkdqf", "mjc", "fvvdtpnzx", "bwumsj", "foqqenbey",
+ "isnjmy", "nkpllqzjzp", "hhqpvvt", "foqqenbey", "fvvdtpnzx", "bwumsj",
+ "hhqpvvt", "fvvdtpnzx", "jkqonvenhx", "jnoqzdute", "foqqenbey",
+ "jnoqzdute", "foqqenbey", "hhqpvvt", "ssnanizsav", "mjc", "foqqenbey",
+ "bwumsj", "ssnanizsav", "fvvdtpnzx", "nkpllqzjzp", "jkqonvenhx",
+ "hhqpvvt", "mjc", "isnjmy", "bwumsj", "pnqsz", "hhqpvvt", "nkpllqzjzp",
+ "jnoqzdute", "pnqsz", "nkpllqzjzp", "jnoqzdute", "foqqenbey",
+ "nkpllqzjzp", "hhqpvvt", "fvvdtpnzx", "plpaboutit", "jnoqzdute",
+ "sfvkdqf", "fvvdtpnzx", "jkqonvenhx", "jnoqzdute", "nkpllqzjzp",
+ "jnoqzdute", "fvvdtpnzx", "jkqonvenhx", "hhqpvvt", "isnjmy",
+ "jkqonvenhx", "ssnanizsav", "jnoqzdute", "jkqonvenhx", "fvvdtpnzx",
+ "hhqpvvt", "bwumsj", "nkpllqzjzp", "bwumsj", "jkqonvenhx", "jnoqzdute",
+ "pnqsz", "foqqenbey", "sfvkdqf", "sfvkdqf"
+ ]
test = Test()
- print(test.topKFrequent(s,5))
+ print(test.topKFrequent(s, 5))
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryTree.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryTree.py"
index b3cbb80..4a8e53d 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryTree.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/binaryTree.py"
@@ -12,61 +12,75 @@
from functools import total_ordering
+
@total_ordering
class node:
- def __init__(self,val,left=None,right=None,freq = 1):
- self.val=val
- self.left=left
- self.right=right
+ def __init__(self, val, left=None, right=None, freq=1):
+ self.val = val
+ self.left = left
+ self.right = right
self.freq = freq
- def __lt__(self,nd):
- return self.valnewNode:
- if nd.left is None:nd.left = newNode
- else : _add(nd.left,newNode)
- else:nd.freq +=1
- _add(self.root,node(val))
- def find(self,val):
- prt= self._findPrt(self.root,node(val),None)
- if prt.left and prt.left.val==val:
+ self.root = None
+
+ def add(self, val):
+ def _add(nd, newNode):
+ if nd < newNode:
+ if nd.right is None: nd.right = newNode
+ else: _add(nd.right, newNode)
+ elif nd > newNode:
+ if nd.left is None: nd.left = newNode
+ else: _add(nd.left, newNode)
+ else: nd.freq += 1
+
+ _add(self.root, node(val))
+
+ def find(self, val):
+ prt = self._findPrt(self.root, node(val), None)
+ if prt.left and prt.left.val == val:
return prt.left
- elif prt.right and prt.right.val==val:return prt.right
- else :return None
- def _findPrt(self,nd,tgt,prt):
- if nd==tgt or nd is None:return prt
- elif ndtmp:
- ds[tgt]=tmp
+ else:
+ tgt = arc.v
+ tmp = ds[nd] + arc
+ if ds[tgt] > tmp:
+ ds[tgt] = tmp
last[tgt] = nd
- if not tgt.isVisited:q.append(tgt)
+ if not tgt.isVisited: q.append(tgt)
'''
cur = u
while cur !=v:
@@ -156,36 +187,39 @@ def minPath(self,v,u):
print(str(v))
'''
return ds[u]
+
def hasCircle(self):
pass
+
def display(self):
print('vertexs')
for i in self.vertexs:
print(i)
print('edges')
for i in self.edges:
- arc=self.edges[i]
- print(str(arc.v)+str(arc)+str(arc.u))
-
-if __name__=='__main__':
- n=int(input())
- while n>0:
- cities=int(input())
- n-=1
- g=graph()
- li={}
+ arc = self.edges[i]
+ print(str(arc.v) + str(arc) + str(arc.u))
+
+
+if __name__ == '__main__':
+ n = int(input())
+ while n > 0:
+ cities = int(input())
+ n -= 1
+ g = graph()
+ li = {}
for i in range(cities):
- li[input()]=i+1
- arc=int(input())
+ li[input()] = i + 1
+ arc = int(input())
for j in range(arc):
- s=input().split(' ')
- g.addEdge(i+1,int(s[0]),int(s[1]))
- ct =int(input())
- for i in range(ct):
+ s = input().split(' ')
+ g.addEdge(i + 1, int(s[0]), int(s[1]))
+ ct = int(input())
+ for i in range(ct):
line = input()
- line= line .split(' ')
- v,u = li[line[0]],li[line[1]]
- print(g.minPath(v,u))
+ line = line.split(' ')
+ v, u = li[line[0]], li[line[1]]
+ print(g.minPath(v, u))
g.revisit()
#http://www.spoj.com/submit/SHPATH/id=20525991
'''
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/directed.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/directed.py"
index 92780ea..05f4d31 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/directed.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/directed.py"
@@ -10,136 +10,174 @@
#########################################################################
'''
-from collections import Iterable,deque
+from collections import Iterable, deque
+
+
class vertex:
- def __init__(self,mark,val=None ,firstEdge = None):
+ def __init__(self, mark, val=None, firstEdge=None):
self.mark = mark
self.val = val
self.firstEdge = firstEdge
self.isVisited = False
+
def __str__(self):
- if '0'<=self.mark[0]<='9':return 'v'+str(self.mark)
+ if '0' <= self.mark[0] <= '9': return 'v' + str(self.mark)
return str(self.mark)
+
def __repr__(self):
- li=[]
- arc= self.firstEdge
- while arc!=None:
+ li = []
+ arc = self.firstEdge
+ while arc != None:
li.append(arc)
- arc= arc.outNextEdge
- return str(self)+ ' to:'+str([str(i.inArrow) for i in li])
+ arc = arc.outNextEdge
+ return str(self) + ' to:' + str([str(i.inArrow) for i in li])
+
+
class edge:
- def __init__(self,outArrow,inArrow,outNextEdge = None,inNextEdge = None, weight = 1):
+ def __init__(self,
+ outArrow,
+ inArrow,
+ outNextEdge=None,
+ inNextEdge=None,
+ weight=1):
self.weight = weight
- self.inNextEdge = inNextEdge
+ self.inNextEdge = inNextEdge
self.outNextEdge = outNextEdge
self.outArrow = outArrow
- self.inArrow=inArrow
+ self.inArrow = inArrow
self.isVisited = False
+
def __str__(self):
- return '--'+str(self.weight)+'-->'
+ return '--' + str(self.weight) + '-->'
+
def __repr__(self):
return str(self)
+
+
class graph:
- def __init__(self):
+ def __init__(self):
self.vertexs = {}
self.edges = {}
- def __getitem__(self,i):
+
+ def __getitem__(self, i):
return self.vertexs[i]
- def __setitem__(selfi,x):
- self.vertexs[i]= x
+
+ def __setitem__(self, i, x):
+ self.vertexs[i] = x
+
def __iter__(self):
return iter(self.vertexs.values())
+
def __bool__(self):
- return len(self.vertexs)!=0
- def addVertex(self,vertexs):
+ return len(self.vertexs) != 0
+
+ def addVertex(self, vertexs):
'''vertexs is a iterable or just a mark that marks the vertex,whichc can be every imutable type'''
- if not isinstance(vertexs,Iterable):vertexs=[vertexs]
+ if not isinstance(vertexs, Iterable): vertexs = [vertexs]
for i in vertexs:
- if not isinstance(i,vertex) and i not in self.vertexs:self.vertexs[i]= vertex(i)
- if isinstance(i,vertex) and i not in self.vertexs:self.vertexs[i.mark]= i
- def isConnected(self,v,u):
+ if not isinstance(i, vertex) and i not in self.vertexs:
+ self.vertexs[i] = vertex(i)
+ if isinstance(i, vertex) and i not in self.vertexs:
+ self.vertexs[i.mark] = i
+
+ def isConnected(self, v, u):
v = self.__getVertex(v)
u = self.__getVertex(u)
- arc= v.firstEdge
- while arc!=None:
- if arc.inArrow==u:return True
+ arc = v.firstEdge
+ while arc != None:
+ if arc.inArrow == u: return True
arc = arc.inNextEdge
return False
- def __getVertex(self,v):
- if not isinstance(v,vertex):
+
+ def __getVertex(self, v):
+ if not isinstance(v, vertex):
if v not in self.vertexs:
- self.vertexs[v]=vertex(v)
+ self.vertexs[v] = vertex(v)
return self.vertexs[v]
return v
- def addEdge(self,v,u,weight = 1):
+
+ def addEdge(self, v, u, weight=1):
v = self.__getVertex(v)
u = self.__getVertex(u)
arc = v.firstEdge
- while arc!=None: #examine that if v,u have been already connected
- if arc.inArrow==u: return
- arc= arc.outNextEdge
- newEdge = edge(v,u,v.firstEdge,u.firstEdge,weight)
- self.edges[(v.mark,u.mark)] = newEdge
+ while arc != None: #examine that if v,u have been already connected
+ if arc.inArrow == u: return
+ arc = arc.outNextEdge
+ newEdge = edge(v, u, v.firstEdge, u.firstEdge, weight)
+ self.edges[(v.mark, u.mark)] = newEdge
v.firstEdge = newEdge
- def delEdge(self,v,u):
- if not isinstance(v,vertex):v= self.vertexs[v]
- if not isinstance(u,vertex):u= self.vertexs[u]
- self._unrelated(v,u)
- del self.edges[(v.mark,u.mark)]
- def _unrelated(self,v,u):
- if v.firstEdge==None:return
+
+ def delEdge(self, v, u):
+ if not isinstance(v, vertex): v = self.vertexs[v]
+ if not isinstance(u, vertex): u = self.vertexs[u]
+ self._unrelated(v, u)
+ del self.edges[(v.mark, u.mark)]
+
+ def _unrelated(self, v, u):
+ if v.firstEdge == None: return
if v.firstEdge.inArrow == u:
- v.firstEdge =v.firstEdge.outNextEdge
+ v.firstEdge = v.firstEdge.outNextEdge
else:
arc = v.firstEdge
- while arc.outNextEdge!=None:
- if arc.outNextEdge.inArrow ==u:
- arc.outNextEdge = arc.outNextEdge.outNextEdge
- break
+ while arc.outNextEdge != None:
+ if arc.outNextEdge.inArrow == u:
+ arc.outNextEdge = arc.outNextEdge.outNextEdge
+ break
+
def revisit(self):
for i in self.vertexs:
- self.vertexs[i].isVisited=False
+ self.vertexs[i].isVisited = False
for i in self.edges:
- self.edges[i].isVisited=False
+ self.edges[i].isVisited = False
+
def __str__(self):
- arcs= list(self.edges.keys())
- arcs=[str(i[0])+'--->'+str(i[1])+' weight:'+str(self.edges[i].weight) for i in arcs]
- s= '\n'.join(arcs)
+ arcs = list(self.edges.keys())
+ arcs = [
+ str(i[0]) + '--->' + str(i[1]) + ' weight:' + str(
+ self.edges[i].weight) for i in arcs
+ ]
+ s = '\n'.join(arcs)
return s
+
def __repr__(self):
return str(self)
- def notIn(self,v):
- if (isinstance(v,vertex) and v.mark not in self.vertexs) or v not in self.vertexs:
+
+ def notIn(self, v):
+ if (isinstance(v, vertex)
+ and v.mark not in self.vertexs) or v not in self.vertexs:
return True
return False
- def visitPath(self,v,u):
+
+ def visitPath(self, v, u):
'''bfs'''
- if self.notIn(v) or self.notIn(u):
- return None,None
+ if self.notIn(v) or self.notIn(u):
+ return None, None
v = self.__getVertex(v)
u = self.__getVertex(u)
- if v.firstEdge==None:return None,None
- q=deque([v.firstEdge])
- isFind=False
- vs,es=[],[]
- while len(q)!=0:
- vs,es=[],[]
- arc= q.popleft()
- if arc.outNextEdge!=None and not arc.outNextEdge.isVisited:q.append(arc.outNextEdge)
- while arc!=None:
- if arc.isVisited:break
- arc.isVisited=True
+ if v.firstEdge == None: return None, None
+ q = deque([v.firstEdge])
+ isFind = False
+ vs, es = [], []
+ while len(q) != 0:
+ vs, es = [], []
+ arc = q.popleft()
+ if arc.outNextEdge != None and not arc.outNextEdge.isVisited:
+ q.append(arc.outNextEdge)
+ while arc != None:
+ if arc.isVisited: break
+ arc.isVisited = True
es.append(arc)
vs.append(arc.inArrow)
- arc.outArrow.isVisited=True
- if arc.inArrow==u:
- isFind=True
- break
+ arc.outArrow.isVisited = True
+ if arc.inArrow == u:
+ isFind = True
+ break
arc = arc.inArrow.firstEdge
# very important , avoid circle travel
- while arc.inArrow.isVisited and arc.outNextEdge:arc = arc.outNextEdge
- if isFind:break
- else:return None,None
+ while arc.inArrow.isVisited and arc.outNextEdge:
+ arc = arc.outNextEdge
+ if isFind: break
+ else: return None, None
'''
se = [str(i) for i in es]
sv = [str(i) for i in vs]
@@ -147,17 +185,20 @@ def visitPath(self,v,u):
for i,j in zip(se,sv):
print(i,j,end='')
'''
- return vs,es
- def hasVertex(self,mark):
+ return vs, es
+
+ def hasVertex(self, mark):
return mark in self.vertexs
+
def display(self):
print('vertexs')
for i in self.vertexs:
print(self.vertexs[i].__repr__())
print('edges')
for i in self.edges:
- arc=self.edges[i]
- print(str(arc.outArrow)+str(arc)+str(arc.inArrow))
+ arc = self.edges[i]
+ print(str(arc.outArrow) + str(arc) + str(arc.inArrow))
+
class Solution(object):
def calcEquation(self, equations, values, queries):
@@ -167,41 +208,42 @@ def calcEquation(self, equations, values, queries):
:type queries: List[List[str]]
:rtype: List[float]
"""
- rst =[]
- g= graph()
- for edge,wt in zip(equations,values):
- g.addEdge(edge[0],edge[1],wt)
- g.addEdge(edge[1],edge[0],1/wt)###### to serach quickly but sacrifacing some space
+ rst = []
+ g = graph()
+ for edge, wt in zip(equations, values):
+ g.addEdge(edge[0], edge[1], wt)
+ g.addEdge(
+ edge[1], edge[0],
+ 1 / wt) ###### to serach quickly but sacrifacing some space
g.display()
for i in queries:
- if i[0]==i[1]:
- if i[0] in g.vertexs:rst.append(1.0)
- else:rst.append(-1.0)
+ if i[0] == i[1]:
+ if i[0] in g.vertexs: rst.append(1.0)
+ else: rst.append(-1.0)
continue
- _,path = g.visitPath(i[0],i[1])
- if path==None:
- if not path:rst.append(-1.0)
+ _, path = g.visitPath(i[0], i[1])
+ if path == None:
+ if not path: rst.append(-1.0)
else:
mul = 1
- for i in path:mul*=i.weight
+ for i in path:
+ mul *= i.weight
rst.append(mul)
g.revisit()
return rst
-
-
-if __name__=='__main__':
- equations = [["a","b"],["e","f"],["b","e"]]
- values = [3.4,1.4,2.3]
- queries = [["b","a"],["a","f"],["f","f"],["e","e"],["c","c"],["a","c"],["f","e"]]
+
+
+if __name__ == '__main__':
+ equations = [["a", "b"], ["e", "f"], ["b", "e"]]
+ values = [3.4, 1.4, 2.3]
+ queries = [["b", "a"], ["a", "f"], ["f", "f"], ["e", "e"], ["c", "c"],
+ ["a", "c"], ["f", "e"]]
sol = Solution()
- ret=sol.calcEquation( equations, values, queries)
+ ret = sol.calcEquation(equations, values, queries)
print(ret)
-
'''
[0.29411764705882354, 10.947999999999999, 1.0, 1.0, -1.0, -1.0, 0.7142857142857143]
'''
-
-
'''
equations = [ ["a", "b"], ["b", "c"] ]
values = [2.0, 3.0]
@@ -210,11 +252,9 @@ def calcEquation(self, equations, values, queries):
ret=sol.calcEquation( equations, values, queries)
print(ret)
'''
-
'''
[6.0, 0.5, -1.0, -1.0, -1.0]
'''
-
'''
g = graph()
g.addEdge(1,2)
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/graph.cc" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/graph.cc"
index fc391bb..5a43873 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/graph.cc"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/graph.cc"
@@ -14,20 +14,26 @@
#include
#include
#include
-bool LOG=false;
+bool LOG = false;
using namespace std;
class edge;
class vertex
{
- friend ostream &operator<<(ostream&,const vertex *);
- friend ostream &operator<<(ostream&,const edge *);
+ friend ostream &operator<<(ostream&, const vertex *);
+ friend ostream &operator<<(ostream&, const edge *);
friend class graph;
friend class edge;
public:
- vertex(int n,edge* arc = NULL):val(n),firstEdge(arc){isVisited=false;}
- ~vertex(){if(LOG)cout<<"V"< vs;
vector es;
bool weighted;
bool directed;
public:
- graph():vNum(0),eNum(0),weighted(false),directed(false){}
- graph(int ,int,bool,bool);
+ graph(): vNum(0), eNum(0), weighted(false), directed(false) {}
+ graph(int, int, bool, bool);
~graph();
void getData();
void display();
- int minPath(int , int );
- void reVisitVertex(){for (int i=0;iisVisited=false ) ;}
- void reVisitEdge(){for (int i=0;iisVisited=false ) ;}
+ int minPath(int, int);
+ void reVisitVertex()
+ {
+ for (int i = 0; i < vNum ; vs[i++]->isVisited = false) ;
+ }
+ void reVisitEdge()
+ {
+ for (int i = 0; i < eNum ; es[i++]->isVisited = false) ;
+ }
};
-graph::graph(int n,int m,bool weighted,bool directed)\
- :vNum(n),eNum(m),weighted(weighted),directed(directed)
+graph::graph(int n, int m, bool weighted, bool directed)\
+:
+vNum(n), eNum(m), weighted(weighted), directed(directed)
{
cin.ignore(1);
- for (int i=0;i>a >>b;
- --a,--b;
- if(weighted)cin>>w;
- edge *arc=new edge (vs[a],vs[b],w,vs[a]->firstEdge);
+
+ for (int i = 0; i < vNum ; ++i) vs.push_back(new vertex(i)) ;
+
+ int a, b, w = 1;
+
+ for (int i = 0; i < eNum ; ++i) {
+ cin >> a >> b;
+ --a, --b;
+
+ if (weighted)cin >> w;
+
+ edge *arc = new edge(vs[a], vs[b], w, vs[a]->firstEdge);
vs[a]->firstEdge = arc;
es.push_back(arc);
}
}
-ostream& operator<<(ostream& os,const vertex* v)
+ostream& operator<<(ostream& os, const vertex* v)
{
- os<<"V"<val+1<<" -->";
- edge *arc= v->firstEdge;
- while(arc){
- os<<" V"<in->val+1;
- arc=arc->nextEdge;
+ os << "V" << v->val + 1 << " -->";
+ edge *arc = v->firstEdge;
+
+ while (arc) {
+ os << " V" << arc->in->val + 1;
+ arc = arc->nextEdge;
}
+
return os;
}
-ostream& operator<<(ostream& os,const edge* e)
+ostream& operator<<(ostream& os, const edge* e)
{
- os<<"V"<out->val+1<<"--"<weight<<"-->"<in->val+1;
+ os << "V" << e->out->val + 1 << "--" << e->weight << "-->" << e->in->val + 1;
return os;
}
graph::~graph()
{
- for (int i=0;ifirstEdge;
- while(arc){
- edge *p=arc;
- arc=arc->nextEdge;
+
+ while (arc) {
+ edge *p = arc;
+ arc = arc->nextEdge;
delete p;
}
+
delete vs[i];
}
}
void graph::display()
{
- cout<<"-----VERTEXS-----"< last; // can't initialize with n NULL ptr
- for (int i=0;i distnace(vNum,-1);
+
+ for (int i = 0; i < vNum ; last.push_back(NULL), ++i) ;
+
+ vector distnace(vNum, -1);
distnace[p->val] = 0;
list que;
que.push_back(p);
- while(!que.empty()){
+
+ while (!que.empty()) {
vertex * cur = que.front();
que.pop_front();
cur->isVisited = true;
edge *arc = cur->firstEdge;
- while(arc){
- vertex * tmp=arc->in;
- if(! tmp->isVisited){
+
+ while (arc) {
+ vertex * tmp = arc->in;
+
+ if (! tmp->isVisited) {
que.push_back(tmp);
- int sum = arc->weight+distnace[arc->out->val];
- if(distnace[tmp->val]==-1){
- distnace[tmp->val]= sum;
+ int sum = arc->weight + distnace[arc->out->val];
+
+ if (distnace[tmp->val] == -1) {
+ distnace[tmp->val] = sum;
last[tmp->val] = arc->out;
- }
- else if(distnace[tmp->val]>sum){
+ } else if (distnace[tmp->val] > sum) {
distnace[tmp->val] = sum;
last[tmp->val] = arc->out;
}
}
+
arc = arc->nextEdge;
}
}
- cout<<"path V"<val]!=p ){
- cout<<"V"<val+1<<"<--";
+
+ while (cur && last[cur->val] != p) {
+ cout << "V" << cur->val + 1 << "<--";
cur = last[cur->val];
}
+
reVisitVertex();
- if(! cur) {
+
+ if (! cur) {
cout.clear();
- cout<<"there isn't path from V"<>n>>m;
- graph g=graph(n,m,weighted,directed);
+ cout << "directed ? [y/N] :";
+
+ if (cin.get() == 'y') directed = true;
+ else directed = false;
+
+ cout << "input vertex num and edge num" << endl;
+ cin >> n >> m;
+ graph g = graph(n, m, weighted, directed);
g.display();
return 0;
}
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/undirected.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/undirected.py"
index 9ea58c6..f0e230d 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/undirected.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/graph/undirected.py"
@@ -10,122 +10,156 @@
#########################################################################
'''
-from collections import Iterable,deque
+from collections import Iterable, deque
+
+
class vertex:
- def __init__(self,mark,val=None):
+ def __init__(self, mark, val=None):
self.mark = mark
self.val = val
self.edges = {}
self.isVisited = False
- def __getitem__(self,adjVertexMark):
+
+ def __getitem__(self, adjVertexMark):
return self.edges[adjVertexMark]
- def __delitem__(self,k):
+
+ def __delitem__(self, k):
del self.edges[k]
+
def __iter__(self):
return iter(self.edges.values())
+
def __str__(self):
- return 'V'+str(self.mark)
+ return 'V' + str(self.mark)
+
def __repr__(self):
return str(self)
+
+
class edge:
- def __init__(self,adjVertexs, weight = 1):
+ def __init__(self, adjVertexs, weight=1):
'''adjVertexs:tuple(v.mark,u.mark)'''
self.weight = weight
self.adjVertexs = adjVertexs
self.isVisted = False
- def __add__(self,x):
- return self.weight +x
- def __radd__(self,x):
- return self+x
- def __getitem__(self,k):
- if k!=0 or k!=1:raise IndexError
+
+ def __add__(self, x):
+ return self.weight + x
+
+ def __radd__(self, x):
+ return self + x
+
+ def __getitem__(self, k):
+ if k != 0 or k != 1: raise IndexError
return self.adjVertexs[k]
+
def __str__(self):
- return '--'+str(self.weight)+'--'
+ return '--' + str(self.weight) + '--'
+
def __repr__(self):
return str(self)
+
@property
def v(self):
return self.adjVertexs[0]
+
@property
def u(self):
return self.adjVertexs[1]
+
+
class graph:
- def __init__(self):
+ def __init__(self):
self.vertexs = {}
self.edges = {}
- def __getitem__(self,i):
+
+ def __getitem__(self, i):
return self.vertexs[i]
- def __setitem__(selfi,x):
- self.vertexs[i]= x
+
+ def __setitem__(self, i, x):
+ self.vertexs[i] = x
+
def __iter__(self):
return iter(self.vertexs)
+
def __bool__(self):
- return len(self.vertexs)!=0
- def addVertex(self,vertexs):
+ return len(self.vertexs) != 0
+
+ def addVertex(self, vertexs):
'''vertexs is a iterable or just a mark that marks the vertex,whichc can be every imutable type'''
- if not isinstance(vertexs,Iterable):vertexs=[vertexs]
+ if not isinstance(vertexs, Iterable): vertexs = [vertexs]
for i in vertexs:
- if not isinstance(i,vertex) and i not in self.vertexs:self.vertexs[i]= vertex(i)
- if isinstance(i,vertex) and i not in self.vertexs:self.vertexs[i.mark]= i
+ if not isinstance(i, vertex) and i not in self.vertexs:
+ self.vertexs[i] = vertex(i)
+ if isinstance(i, vertex) and i not in self.vertexs:
+ self.vertexs[i.mark] = i
- def __getVertex(self,v):
- if not isinstance(v,vertex):
+ def __getVertex(self, v):
+ if not isinstance(v, vertex):
if v not in self.vertexs:
- self.vertexs[v]=vertex(v)
+ self.vertexs[v] = vertex(v)
return self.vertexs[v]
return v
- def addEdge(self,v,u,weight = 1):
+
+ def addEdge(self, v, u, weight=1):
v = self.__getVertex(v)
u = self.__getVertex(u)
for arc in v:
- if u in arc.adjVertexs:return #examine that if v,u have been already connected
- vertexs = (v,u)
- newEdge = edge (vertexs,weight)
+ if u in arc.adjVertexs:
+ return #examine that if v,u have been already connected
+ vertexs = (v, u)
+ newEdge = edge(vertexs, weight)
self.edges[vertexs] = newEdge
v.edges[u] = newEdge
- u.edges[v] = newEdge
- def delEdge(self,v,u):
- if not isinstance(v,vertex):v= self.vertexs[v]
- if not isinstance(u,vertex):u= self.vertexs[u]
+ u.edges[v] = newEdge
+
+ def delEdge(self, v, u):
+ if not isinstance(v, vertex): v = self.vertexs[v]
+ if not isinstance(u, vertex): u = self.vertexs[u]
try:
del v[u]
del u[v]
- except:print("error!"+str(v)+','+str(u)+' arent adjacent now')
- del self.edges[(v,u)]
+ except:
+ print("error!" + str(v) + ',' + str(u) + ' arent adjacent now')
+ del self.edges[(v, u)]
+
def revisit(self):
for i in self.vertexs.values():
i.isVisited = False
for i in self.edges.values():
i.isVisited = False
+
def __str__(self):
- arcs= list(self.edges.keys())
- arcs=[str(i[0])+str(self.edges[i])+str(i[1]) for i in arcs]
- s= '\n'.join(arcs)
+ arcs = list(self.edges.keys())
+ arcs = [str(i[0]) + str(self.edges[i]) + str(i[1]) for i in arcs]
+ s = '\n'.join(arcs)
return s
+
def __repr__(self):
return str(self)
- def minPath(self,v,u):
- v=self.__getVertex(v)
- u=self.__getVertex(u)
- q=deque([v])
- last={i:None for i in self.vertexs.values()}
+
+ def minPath(self, v, u):
+ v = self.__getVertex(v)
+ u = self.__getVertex(u)
+ q = deque([v])
+ last = {i: None for i in self.vertexs.values()}
last[v] = 0
- ds={i:1000000 for i in self.vertexs.values()}
- ds[v]=0
- while len(q)!=0:
+ ds = {i: 1000000 for i in self.vertexs.values()}
+ ds[v] = 0
+ while len(q) != 0:
nd = q.popleft()
- nd.isVisited=True
- for edge in nd:
- tgt=None
- if edge.v==nd:
+ nd.isVisited = True
+ for edge in nd:
+ tgt = None
+ if edge.v == nd:
tgt = edge.u
- else:tgt = edge.v
- tmp=ds[nd]+edge
- if ds[tgt] >tmp:
- ds[tgt]=tmp
+ else:
+ tgt = edge.v
+ tmp = ds[nd] + edge
+ if ds[tgt] > tmp:
+ ds[tgt] = tmp
last[tgt] = nd
- if not tgt.isVisited:q.append(tgt)
+ if not tgt.isVisited: q.append(tgt)
'''
cur = u
while cur !=v:
@@ -134,36 +168,39 @@ def minPath(self,v,u):
print(str(v))
'''
return ds[u]
+
def hasCircle(self):
pass
+
def display(self):
print('vertexs')
for i in self.vertexs:
print(i)
print('edges')
for i in self.edges:
- arc=self.edges[i]
- print(str(arc.v)+str(arc)+str(arc.u))
-
-if __name__=='__main__':
- n=int(input())
- while n>0:
- cities=int(input())
- n-=1
- g=graph()
- li={}
+ arc = self.edges[i]
+ print(str(arc.v) + str(arc) + str(arc.u))
+
+
+if __name__ == '__main__':
+ n = int(input())
+ while n > 0:
+ cities = int(input())
+ n -= 1
+ g = graph()
+ li = {}
for i in range(cities):
- li[input()]=i+1
- arc=int(input())
+ li[input()] = i + 1
+ arc = int(input())
for j in range(arc):
- s=input().split(' ')
- g.addEdge(i+1,int(s[0]),int(s[1]))
- ct =int(input())
- for i in range(ct):
+ s = input().split(' ')
+ g.addEdge(i + 1, int(s[0]), int(s[1]))
+ ct = int(input())
+ for i in range(ct):
line = input()
- line= line .split(' ')
- v,u = li[line[0]],li[line[1]]
- print(g.minPath(v,u))
+ line = line.split(' ')
+ v, u = li[line[0]], li[line[1]]
+ print(g.minPath(v, u))
g.revisit()
#http://www.spoj.com/submit/SHPATH/id=20525991
'''
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/hashTable.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/hashTable.py"
index 121fe66..1279279 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/hashTable.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/hashTable.py"
@@ -10,18 +10,23 @@
#########################################################################
'''
+
class item:
- def __init__(self,key,val,nextItem=None):
+ def __init__(self, key, val, nextItem=None):
self.key = key
self.val = val
self.next = nextItem
- def to(self,it):
+
+ def to(self, it):
self.next = it
- def __eq__(self,it):
+
+ def __eq__(self, it):
'''using keyword '''
return self.key == it.key
+
def __bool__(self):
return self.key is not None
+
def __str__(self):
li = []
nd = self
@@ -29,27 +34,32 @@ def __str__(self):
li.append(f'({nd.key}:{nd.val})')
nd = nd.next
return ' -> '.join(li)
+
def __repr__(self):
return f'item({self.key},{self.val})'
+
+
class hashTable:
- def __init__(self,size=100):
+ def __init__(self, size=100):
self.size = size
- self.slots=[item(None,None) for i in range(self.size)]
- def __setitem__(self,key,val):
+ self.slots = [item(None, None) for i in range(self.size)]
+
+ def __setitem__(self, key, val):
nd = self.slots[self.myhash(key)]
while nd.next:
- if nd.key ==key:
- if nd.val!=val: nd.val=val
+ if nd.key == key:
+ if nd.val != val: nd.val = val
return
- nd = nd.next
- nd.next = item(key,val)
+ nd = nd.next
+ nd.next = item(key, val)
- def myhash(self,key):
- if isinstance(key,str):
+ def myhash(self, key):
+ if isinstance(key, str):
key = sum(ord(i) for i in key)
- if not isinstance(key,int):
+ if not isinstance(key, int):
key = hash(key)
return key % self.size
+
def __iter__(self):
'''when using keyword , such as ' if key in dic',
the dic's __iter__ method will be called,(if hasn't, calls __getitem__
@@ -57,18 +67,20 @@ def __iter__(self):
'''
for nd in self.slots:
nd = nd.next
- while nd :
+ while nd:
yield nd.key
nd = nd.next
- def __getitem__(self,key):
- nd =self.slots[ self.myhash(key)].next
+
+ def __getitem__(self, key):
+ nd = self.slots[self.myhash(key)].next
while nd:
- if nd.key==key:
+ if nd.key == key:
return nd.val
nd = nd.next
- raise Exception(f'[KeyError]: {self.__class__.__name__} has no key {key}')
+ raise Exception(
+ f'[KeyError]: {self.__class__.__name__} has no key {key}')
- def __delitem__(self,key):
+ def __delitem__(self, key):
'''note that None item and item(None,None) differ with each other,
which means you should take care of them and correctly cop with None item
especially when deleting items
@@ -77,31 +89,33 @@ def __delitem__(self,key):
nd = self.slots[n].next
if nd.key == key:
if nd.next is None:
- self.slots[n] = item(None,None) # be careful
- else:self.slots[n] = nd.next
+ self.slots[n] = item(None, None) # be careful
+ else:
+ self.slots[n] = nd.next
return
while nd:
if nd.next is None: break # necessary
- if nd.next.key ==key:
+ if nd.next.key == key:
nd.next = nd.next.next
nd = nd.next
+
def __str__(self):
- li = ['\n\n'+'-'*5+'hashTable'+'-'*5]
- for i,nd in enumerate(self.slots):
- li.append(f'{i}: '+str(nd.next))
+ li = ['\n\n' + '-' * 5 + 'hashTable' + '-' * 5]
+ for i, nd in enumerate(self.slots):
+ li.append(f'{i}: ' + str(nd.next))
return '\n'.join(li)
-
-if __name__ =='__main__':
+
+if __name__ == '__main__':
from random import randint
dic = hashTable(16)
n = 100
- li = [1,2,5,40,324,123,6,22,18,34,50]
+ li = [1, 2, 5, 40, 324, 123, 6, 22, 18, 34, 50]
print(f'build hashTable using {li}')
for i in li:
- dic[i] = '$'+str(i)
+ dic[i] = '$' + str(i)
print(dic)
- for i in [1,34,45,123]:
+ for i in [1, 34, 45, 123]:
if i in dic:
print(f'{i} in dic, deleting it')
del dic[i]
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/huffman/huffman.cc" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/huffman/huffman.cc"
index 832a1bb..7a1b0b2 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/huffman/huffman.cc"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/huffman/huffman.cc"
@@ -28,348 +28,437 @@ using namespace std;
void cat(string s)
{
- FILE* f=fopen(s.c_str(),"rb");
- cout<<"file content"<
-void mapprint(map &f)
+void mapprint(map &f)
{
- for(class map::iterator i = f.begin();i!=f.end();++i)
- cout<first<<") : "<second<::iterator i = f.begin(); i != f.end(); ++i)
+ cout << i->first << ") : " << i->second << endl;
}
-template
+template
class node
{
- public:
+public:
ky key;
wt val;
bool visited;
- node * left,*right;
- node(const node &a){val = a.val;key= a.key;visited = a.visited;left= a.left;right=a.right;}
- node(ky k=0,wt v=0):key(k),val(v),visited(false),left(NULL),right(NULL){};
- bool operator<(const node & a)const{return val>a.val;};
+ node * left, *right;
+ node(const node &a)
+ {
+ val = a.val;
+ key = a.key;
+ visited = a.visited;
+ left = a.left;
+ right = a.right;
+ }
+ node(ky k = 0, wt v = 0): key(k), val(v), visited(false), left(NULL), right(NULL) {};
+ bool operator<(const node & a)const
+ {
+ return val > a.val;
+ };
};
-template
+template
class huffman
{
private:
- node root;
+ node root;
string res;
public:
- long total(){return root.val;}
- map encode_map;
- map decode_map;
- huffman(map& mp);
+ long total()
+ {
+ return root.val;
+ }
+ map encode_map;
+ map decode_map;
+ huffman(map& mp);
void display();
- string encode(string,long &);
- string decode(string,long&);
- void preOrder(node*,string);
+ string encode(string, long &);
+ string decode(string, long&);
+ void preOrder(node*, string);
};
-template
-huffman::huffman(map& mp)
+template
+huffman::huffman(map& mp)
{
- if(mp.empty()){
- cout<<"Error! No data!"< > hp;
- for(typename map::iterator i=mp.begin();i!=mp.end();++i){
- hp.push( node(i->first,i->second));
+
+ priority_queue > hp;
+
+ for (typename map::iterator i = mp.begin(); i != mp.end(); ++i) {
+ hp.push(node(i->first, i->second));
}
- int n =hp.size();
- if(n==1){
+
+ int n = hp.size();
+
+ if (n == 1) {
root = hp.top();
return;
}
- while(--n>=1){
- node *a = new node(hp.top());
+
+ while (--n >= 1) {
+ node *a = new node(hp.top());
hp.pop();
- node *b = new node(hp.top());
+ node *b = new node(hp.top());
hp.pop();
- node * tmp = new node(0,a->val+b->val);
- tmp->left = a,tmp->right = b;
+ node * tmp = new node(0, a->val + b->val);
+ tmp->left = a, tmp->right = b;
hp.push(*tmp);
}
+
root = hp.top();
- preOrder(&root,string());
+ preOrder(&root, string());
}
-template
-void huffman::preOrder(node* nd,string s)
+template
+void huffman::preOrder(node* nd, string s)
{
- if(nd->left == NULL){
- encode_map[nd->key] =s;
+ if (nd->left == NULL) {
+ encode_map[nd->key] = s;
decode_map[s] = nd->key;
delete nd;
return ;
}
- preOrder(nd->left,s+'0');
- preOrder(nd->right,s+'1');
+
+ preOrder(nd->left, s + '0');
+ preOrder(nd->right, s + '1');
delete nd;
}
-template
-string huffman::decode(string zipfile_name,long &charNum)
+template
+string huffman::decode(string zipfile_name, long &charNum)
{
string uniFileName(string);
- FILE * src = fopen(zipfile_name.c_str(),"rb");
+ FILE * src = fopen(zipfile_name.c_str(), "rb");
char file_name[nameLength];
- fgets(file_name,nameLength,src);
- int ct=-1;
- while(file_name[++ct]!='\n');
+ fgets(file_name, nameLength, src);
+ int ct = -1;
+
+ while (file_name[++ct] != '\n');
+
int pos = zipfile_name.find('.');
- if(pos==string::npos)pos=zipfile_name.size();
- string name(zipfile_name.substr(0,pos)) ,suffix(file_name,file_name+ct),file(name+suffix);
- file=uniFileName(file);
- cout<<"extracting compressed file :"<
-string huffman::encode(string file_name,long &charNum)
+template
+string huffman::encode(string file_name, long &charNum)
{
- charNum=0;
+ charNum = 0;
string uniFileName(string);
- int pos =file_name.rfind('.');
- if(pos==string::npos)pos=file_name.size();
- string zipfile = file_name.substr(0,pos)+string(".zzip");
+ int pos = file_name.rfind('.');
+
+ if (pos == string::npos)pos = file_name.size();
+
+ string zipfile = file_name.substr(0, pos) + string(".zzip");
zipfile = uniFileName(zipfile);
- cout<<"generating zip file :"<::iterator i=decode_map.begin();i!=decode_map.end() ;++i ){
+
+ for (class map::iterator i = decode_map.begin(); i != decode_map.end() ; ++i) {
data.append((i->first));
data.append(" ");
- data+=(i->second);
+ data += (i->second);
}
+
int data_size = data.size(); // calculate the size of the code_data
char sz[numDigit];
- snprintf(sz,numDigit,"%d",data_size);
- int ct=0;
- for(;sz[ct];++ct)fputc(sz[ct],dst);
- fputc('\n',dst);
- fwrite(data.c_str(),data_size,1,dst);
- int sum=0,digit=0,num;
+ snprintf(sz, numDigit, "%d", data_size);
+ int ct = 0;
+
+ for (; sz[ct]; ++ct)fputc(sz[ct], dst);
+
+ fputc('\n', dst);
+ fwrite(data.c_str(), data_size, 1, dst);
+ int sum = 0, digit = 0, num;
string code8;
- for(int i=0;i
-void huffman::display()
+template
+void huffman::display()
{
- cout<<"the encoding map,huffman codes are as bellow:"<::iterator i=encode_map.begin();i!=encode_map.end() ;++i )
- cout<first<<"("<<(int)i->first<<"):"<second<::iterator i = encode_map.begin(); i != encode_map.end() ; ++i)
+ cout << i->first << "(" << (int)i->first << "):" << i->second << endl;
}
-bool handle_one(string file_name,vector &origin,vector &compressed)
+bool handle_one(string file_name, vector &origin, vector &compressed)
{
int name_length = file_name.size();
- FILE *src=fopen(file_name.c_str(),"rb");
- cout<<"opening "< mp;
- while(!feof(src)){
- fread(&cur,sizeof(char),1,src);
- if(mp.count(cur)){
- mp[cur]+=1;
- }
- else mp[cur]=1;
+ map mp;
+
+ while (!feof(src)) {
+ fread(&cur, sizeof(char), 1, src);
+
+ if (mp.count(cur)) {
+ mp[cur] += 1;
+ } else mp[cur] = 1;
}
+
fclose(src);
- huffman hf(mp);
+ huffman hf(mp);
long sz;
- string s(hf.encode(file_name,sz));
- origin.push_back(hf.total()),compressed.push_back(sz);
- cout<<"\ncontinue to uncompress? [Y/n]"<& v)
+void splitToVec(char * s, vector& v)
{
- int i=0,last=0;
- for(;s[i];++i){
- if(isSep(s[i])){
- v.push_back(string(s+last,s+i));
- while(s[++i]&&isSep(s[i]));
- last=i;
+ int i = 0, last = 0;
+
+ for (; s[i]; ++i) {
+ if (isSep(s[i])) {
+ v.push_back(string(s + last, s + i));
+
+ while (s[++i] && isSep(s[i]));
+
+ last = i;
}
}
- if(s[last])v.push_back(string(s+last,s+i));
+
+ if (s[last])v.push_back(string(s + last, s + i));
}
-bool lenStr(string &a,string &b)
+bool lenStr(string &a, string &b)
{
- return a.size() & names)
{
- vector originSize,compressedSize;
+ vector originSize, compressedSize;
vector deltaTime;
double last;
vector indicator;
bool bl;
- for(vector::iterator i=names.begin();i!=names.end();++i){
+
+ for (vector::iterator i = names.begin(); i != names.end(); ++i) {
struct timeval tv;
- gettimeofday(&tv,NULL);
- last=tv.tv_sec;
- bl=handle_one(*i,originSize,compressedSize);
+ gettimeofday(&tv, NULL);
+ last = tv.tv_sec;
+ bl = handle_one(*i, originSize, compressedSize);
indicator.push_back(bl);
- gettimeofday(&tv,NULL);
- deltaTime.push_back(tv.tv_sec-last);
+ gettimeofday(&tv, NULL);
+ deltaTime.push_back(tv.tv_sec - last);
}
- cout<<"\nDealt file number "<::iterator p=max_element(names.begin(),names.end(),lenStr);
- int len = p->size()+2;
- for(int i =0;i::iterator p = max_element(names.begin(), names.end(), lenStr);
+ int len = p->size() + 2;
+
+ for (int i = 0; i < names.size(); ++i) {
+ if (! indicator[i]) {
+ continue;
+ }
+
+ cout << names[i] << string(len - names[i].size(), ' ');
+ cout << deltaTime[i] << "s " << compressedSize[i] / 1024.0 << "KB/" << originSize[i] / 1024.0 << "KB :";
+ cout << compressedSize[i] * 100.0 / originSize[i] << "%" << endl;
}
- cout< names;
string file;
- if(argv>1){
- for(int i=1;i 1) {
+ for (int i = 1; i < argv; ++i) {
names.push_back(argc[i]);
}
+
go(names);
names.clear();
}
+
char mk;
- while(1){
+
+ while (1) {
char s[201];
- cout<<"Input file names separated by space "< int
- if root is None:return t
- if t is None:return root
- if root int
+ if root is None: return t
+ if t is None: return root
+ if root < t:
+ root, t = t, root
+ root.right = leftHeap._merge(root.right, t)
if root.left is None or root.right is None:
- root.s=1
+ root.s = 1
if root.left is None:
- root.left,root.right = root.right,None
+ root.left, root.right = root.right, None
else:
- if root.left.sself.s else 2*p+self.lowExt-self.n+1
- def arrayToTree(self,i):
- return (i+self.offset)//2 if i<=self.lowExt else (i-self.lowExt+ self.n-1)//2
- def win(self,a,b):
- return ab
- def initTree(self,p):
- if p>=self.n:
- delta = p%2 #!!! good job notice delta mark the lchild or rchlid
- return self.players[self.treeToArray(p//2)+delta]
- l = self.initTree(2*p)
- r = self.initTree(2*p+1)
- if self.win(r,l):
+ self.lowExt = (self.n - i) * 2
+ self.s = i - 1
+ self.offset = 2 * i - 1
+
+ def treeToArray(self, p):
+ return 2 * p - self.offset if p > self.s else 2 * p + self.lowExt - self.n + 1
+
+ def arrayToTree(self, i):
+ return (i + self.offset) // 2 if i <= self.lowExt else (
+ i - self.lowExt + self.n - 1) // 2
+
+ def win(self, a, b):
+ return a < b if self.reverse else a > b
+
+ def initTree(self, p):
+ if p >= self.n:
+ delta = p % 2 #!!! good job notice delta mark the lchild or rchlid
+ return self.players[self.treeToArray(p // 2) + delta]
+ l = self.initTree(2 * p)
+ r = self.initTree(2 * p + 1)
+ if self.win(r, l):
self.tree[p] = l
self.dir = 'r'
return r
- else :
+ else:
self.tree[p] = r
self.dir = 'l'
return l
- def getWinIdx(self,idx=1):
- while 2*idx
bool isZero(float a)
{
- return a<0.00001&&-a<0.00001;
+ return a < 0.00001 && -a < 0.00001;
}
-template class map;
- //notice that if you declare a class template,declare the class first like this.
-template
+template class map;
+//notice that if you declare a class template,declare the class first like this.
+template
class pair
{
- friend class map;
- pair *next;
- public:
+ friend class map;
+ pair *next;
+public:
t1 first;
t2 second;
};
-template
+template
class map
{
int n;
- pair head;
+ pair head;
int cur;
- pair *last_visit;
- public:
+ pair *last_visit;
+public:
map();
~map();
bool has(t1);
void erase(t1);
t2& operator[](t1);
- pair &locate(int index = -1);
+ pair &locate(int index = -1);
int size();
};
-template
-map::map(){
- n=0;
- cur=-1;
- last_visit= &head;
- head.next=NULL;
+template
+map::map()
+{
+ n = 0;
+ cur = -1;
+ last_visit = &head;
+ head.next = NULL;
head.first = head.second = 0;
}
-template
-map::~map()
+template
+map::~map()
{
- pair *p,*q=&head;
- while(q!=NULL){
- p=q->next;
+ pair *p, *q = &head;
+
+ while (q != NULL) {
+ p = q->next;
delete q;
- q=p;
+ q = p;
}
}
-template
-bool map::has(t1 key)
+template
+bool map::has(t1 key)
{
- pair *p = head.next;
- for(int i = 0;ifirst<=key;++i){
- if(isZero(p->first-key)) return 1;
- p=p->next;
+ pair *p = head.next;
+
+ for (int i = 0; i < n && p->first <= key; ++i) {
+ if (isZero(p->first - key)) return 1;
+
+ p = p->next;
}
+
return 0;
}
-template
-pair& map::locate(int index)
+template
+pair& map::locate(int index)
{
- if(index>=n||index<0){
+ if (index >= n || index < 0) {
printf("the index is out of range\n");
return head;
}
- if(cur>index){
+
+ if (cur > index) {
last_visit = &head;
cur = -1;
}
- while(curnext;
++cur;
}
+
return *last_visit;
}
-template
-int map::size()
+template
+int map::size()
{
return n;
}
-template
-t2& map::operator[](t1 key)
+template
+t2& map::operator[](t1 key)
{
- pair * p=&head;
- while(p->next!=NULL){
- if(isZero(p->next->first-key)) return p->next->second;
- else if(p->next->first>key){break;}
- p=p->next;
+ pair * p = &head;
+
+ while (p->next != NULL) {
+ if (isZero(p->next->first - key)) return p->next->second;
+ else if (p->next->first > key) {
+ break;
+ }
+
+ p = p->next;
}
- cur=-1;
- last_visit= &head;
- pair *tmp = new pair;
+
+ cur = -1;
+ last_visit = &head;
+ pair *tmp = new pair;
tmp ->next = p->next;
tmp->first = key;
p->next = tmp;
++n;
return tmp->second;
}
-template
-void map::erase(t1 key)
+template
+void map::erase(t1 key)
{
- pair *p = &head;
- while(p->next!=NULL){
- if(isZero(p->next->first-key)){
- pair *q = p->next;
+ pair *p = &head;
+
+ while (p->next != NULL) {
+ if (isZero(p->next->first - key)) {
+ pair *q = p->next;
p->next = p->next->next;
delete q;
--n;
break;
}
- p=p->next;
+
+ p = p->next;
}
- cur=-1;
- last_visit= &head;
+
+ cur = -1;
+ last_visit = &head;
}
int main()
{
- map b;
- for(int i = 0;i<40;++i){
+ map b;
+
+ for (int i = 0; i < 40; ++i) {
b[i] = i;
- if(i%3){
+
+ if (i % 3) {
b[i] = 1;
}
- if(i%2){
+
+ if (i % 2) {
b.erase(i);
}
}
- for(int i = 0;i
+#include
#include
#include
#include
@@ -19,16 +19,17 @@
using namespace std;
#if defined(__linux__)
- #define LINUX true
+#define LINUX true
#elif defined(_WIN32)
- #define LINUX false
+#define LINUX false
#endif
bool isZero(double a)
{
- if((a<0.00001)&&-a<0.00001)
+ if ((a < 0.00001) && -a < 0.00001)
return true;
+
return false;
}
class node
@@ -42,9 +43,9 @@ class polynomial
int SIZE;
int n;
node* p;
- public:
- polynomial(int sz=50);
- polynomial(const polynomial & );
+public:
+ polynomial(int sz = 50);
+ polynomial(const polynomial &);
~polynomial();
double cal(double);
void getData();
@@ -54,10 +55,10 @@ class polynomial
polynomial operator-(const polynomial &);
polynomial operator*(const polynomial &);
};
-polynomial::polynomial(int sz):n(0),SIZE(sz)
+polynomial::polynomial(int sz): n(0), SIZE(sz)
{
p = (node*) new node[SIZE];
- memset(p,0,sizeof(p));
+ memset(p, 0, sizeof(p));
}
polynomial::~polynomial()
{
@@ -65,18 +66,21 @@ polynomial::~polynomial()
}
double polynomial::cal(double x)
{
- double rst=0;
- for(int i =0;i=0;--i){
+
+ // char *fmt = ("x"); printf(fmt,...);
+ for (int i = n - 1; i >= 0; --i) {
double t = tmp[i].coefficient;
double idx = tmp[i].index;
- if(isZero(idx)){
- printf("%+g",t);
+
+ if (isZero(idx)) {
+ printf("%+g", t);
continue;
}
- if(isZero(t-1)) printf("+");
- else if(isZero(t+1))printf("-");
- else printf("%+g",t);
+
+ if (isZero(t - 1)) printf("+");
+ else if (isZero(t + 1))printf("-");
+ else printf("%+g", t);
+
printf("x");
- if(!isZero(idx-1)) printf("^%g",idx);
+
+ if (!isZero(idx - 1)) printf("^%g", idx);
}
+
printf("\n");
}
void polynomial::getData()
{
printf("Please input data . \n");
printf("For every item,Coefficient first .Use space to separate,EOF to end\n");
- map mp;
+ map mp;
double idx;
double coef;
- while(scanf("%lf%lf",&coef,&idx)!=EOF){
- if(isZero(coef)) continue;
- if(mp.count(idx) == 0){
+
+ while (scanf("%lf%lf", &coef, &idx) != EOF) {
+ if (isZero(coef)) continue;
+
+ if (mp.count(idx) == 0) {
mp[idx] = coef;
- }
- else{
+ } else {
mp[idx] += coef;
- if(isZero(mp[idx])){
+
+ if (isZero(mp[idx])) {
mp.erase(idx);
}
}
}
- if(mp.size()>SIZE){
- SIZE *=2;
- p = (node*)realloc(p,sizeof(node)*SIZE) ;
+
+ if (mp.size() > SIZE) {
+ SIZE *= 2;
+ p = (node*)realloc(p, sizeof(node) * SIZE) ;
}
- for(map::iterator it = mp.begin();it!=mp.end();++it){
+
+ for (map::iterator it = mp.begin(); it != mp.end(); ++it) {
p[n].index = it->first;
p[n++].coefficient = it->second;
}
@@ -144,48 +161,52 @@ void polynomial::getData()
polynomial polynomial::operator+(const polynomial & a)
{
polynomial rst ;
- int p1 = 0,p2 = 0,p3 = 0;
+ int p1 = 0, p2 = 0, p3 = 0;
double exp1 = p[p1].index;
double exp2 = a.p[p2].index;
- while(p1exp2){
- rst.p[p3].index = exp2;
- rst.p[p3].coefficient = a.p[p2].coefficient;
- ++p2,++p3;
- exp2 = a.p[p2].index;;
+
+ while (p2 < a.n && exp1 > exp2) {
+ rst.p[p3].index = exp2;
+ rst.p[p3].coefficient = a.p[p2].coefficient;
+ ++p2, ++p3;
+ exp2 = a.p[p2].index;;
}
- if(isZero(exp1-exp2)){
- double tmp= p[p1].coefficient + a.p[p2].coefficient;
- if(isZero(tmp)){
- ++p1,++p2;
- }
- else{
+
+ if (isZero(exp1 - exp2)) {
+ double tmp = p[p1].coefficient + a.p[p2].coefficient;
+
+ if (isZero(tmp)) {
+ ++p1, ++p2;
+ } else {
rst.p[p3].index = p[p1].index;
rst.p[p3].coefficient = tmp;
- ++p1,++p2,++p3;
+ ++p1, ++p2, ++p3;
}
}
}
- if(p1 == n){
- while(p2 mp;
- for(int i = 0;i mp;
+
+ for (int i = 0; i < n; ++i) {
double idx = p[i].index;
double coef = p[i].coefficient;
- for(int j = 0;jsz){
- sz *=2;
+
+ int sz = 50;
+
+ while (mp.size() > sz) {
+ sz *= 2;
}
+
polynomial rst(sz);
- for(map::iterator it = mp.begin();it!=mp.end();++it){
+
+ for (map::iterator it = mp.begin(); it != mp.end(); ++it) {
rst.p[rst.n].index = it->first;
rst.p[rst.n++].coefficient = it->second;
}
+
return rst;
}
int num = 0;
@@ -250,94 +281,94 @@ void menu()
void loop()
{
int op;
- while(scanf("%d",&op)!=EOF){
- if(op == 0){
- pl[num].getData();
- ++num;
- printf("You've created polynomial %d:\n",num);
- pl[num-1].display();
- }
- else if(op==1||op==2||op==3){
- if(num<2){
- printf("Oops! you've got less two polynomial\nPlease choose another operation\n");
- continue;
- }
- printf("input two nums of the two polynomial to be operated.eg: 1 2\n");
- int t1=100,t2=100;
- while(1){
- scanf("%d%d",&t1,&t2);
- if(t1>num||t2>num||t1<0||t2<0){
- printf("wrong num ,please input again\n");
- }
- else break;
- }
- printf("the rst is:\n");
- t1 -=1,t2-=1;
- if(op == 1){
- (pl[t1]+pl[t2]).display();
- }
- else if(op == 2){
- (pl[t1]-pl[t2]).display();
- }
- else (pl[t1]*pl[t2]).display();
+
+ while (scanf("%d", &op) != EOF) {
+ if (op == 0) {
+ pl[num].getData();
+ ++num;
+ printf("You've created polynomial %d:\n", num);
+ pl[num - 1].display();
+ } else if (op == 1 || op == 2 || op == 3) {
+ if (num < 2) {
+ printf("Oops! you've got less two polynomial\nPlease choose another operation\n");
+ continue;
}
- else if(op == 4){
- printf("input a polynomial's num to display it\n");
- int tmp;
- scanf("%d",&tmp);
- if(tmp>num){
- printf("wrong num");
- }
- else{
- printf("info of polynomial %d\n",tmp);
- pl[tmp-1].display();
- }
+
+ printf("input two nums of the two polynomial to be operated.eg: 1 2\n");
+ int t1 = 100, t2 = 100;
+
+ while (1) {
+ scanf("%d%d", &t1, &t2);
+
+ if (t1 > num || t2 > num || t1 < 0 || t2 < 0) {
+ printf("wrong num ,please input again\n");
+ } else break;
}
- else if(op == 9){
- for(int i = 0;i num) {
+ printf("wrong num");
+ } else {
+ printf("info of polynomial %d\n", tmp);
+ pl[tmp - 1].display();
}
- else if(op == 5){
- menu();
+ } else if (op == 9) {
+ for (int i = 0; i < num; ++i) {
+ printf("polynomial %d : ", i + 1);
+ pl[i].display();
}
- else if(op == 6){
- if(LINUX) system("clear");
- else system("cls");
- menu();
+ } else if (op == 5) {
+ menu();
+ } else if (op == 6) {
+ if (LINUX) system("clear");
+ else system("cls");
+
+ menu();
+ } else if (op == 10) {
+ double x;
+ int t;
+ printf("choose a polynomial\n");
+ scanf("%d", &t);
+
+ if (t > num || t < 0) {
+ printf("wrong num\n");
+ } else {
+ printf("input a value\n");
+ scanf("%lf", &x);
+ pl[t - 1].display();
+ printf("%g\n", pl[t - 1].cal(x));
}
- else if(op == 10){
- double x;
- int t;
- printf("choose a polynomial\n");
- scanf("%d",&t);
- if(t>num||t<0){
- printf("wrong num\n");
- }
- else {
- printf("input a value\n");
- scanf("%lf",&x);
- pl[t-1].display();
- printf("%g\n",pl[t-1].cal(x));
- }
+ } else if (op == 8) {
+ if (num == 0) {
+ printf("you have'nt any polynomial tp copy\n");
+ continue;
}
- else if(op == 8){
- if(num == 0){
- printf("you have'nt any polynomial tp copy\n");
- continue;
- }
- int n = num+1;
- while(n>num){
- printf("input the number of an existing polynomial you want to copy\n");
- scanf("%d",&n);
- }
- (pl[num] = pl[n-1]);
- printf("You've copyed this polynomial:\n");
- pl[num++].display();
+
+ int n = num + 1;
+
+ while (n > num) {
+ printf("input the number of an existing polynomial you want to copy\n");
+ scanf("%d", &n);
}
- else exit(0);
- printf("select an operation\n");
+
+ (pl[num] = pl[n - 1]);
+ printf("You've copyed this polynomial:\n");
+ pl[num++].display();
+ } else exit(0);
+
+ printf("select an operation\n");
}
}
int main(void)
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/polynomial.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/polynomial.py"
index 74bbdfb..b51fa4e 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/polynomial.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/polynomial.py"
@@ -11,61 +11,71 @@
'''
#!/bin/python3
-# notice that creating a class's initialization won't conflict with __call__ method
+# notice that creating a class's initialization won't conflict with __call__ method
# because the former call class ,and the latter call instance
# to be implemented
+
class polynomial:
- pls= []
+ pls = []
n = 0
+
def dictize(pl):
- if isinstance(pl,int) or isinstance(pl,float):
- pl = {0:pl}
- if isinstance(pl,polynomial):
+ if isinstance(pl, int) or isinstance(pl, float):
+ pl = {0: pl}
+ if isinstance(pl, polynomial):
pl = pl.polynomial.copy()
return pl
+
def isZero(n):
- return abs(n)<0.000001
- def __init__(self,s='0 0'):
+ return abs(n) < 0.000001
+
+ def __init__(self, s='0 0'):
polynomial.pls.append(self)
- polynomial.n +=1
- if isinstance(s,polynomial):
- self.polynomial=s.polynomial.copy()
- # don't write like this .**self.polynomial = s.polynomial**,it's ref
+ polynomial.n += 1
+ if isinstance(s, polynomial):
+ self.polynomial = s.polynomial.copy()
+ # don't write like this .**self.polynomial = s.polynomial**,it's ref
return
- elif isinstance(s,dict):
+ elif isinstance(s, dict):
self.polynomial = s.copy()
return
- s= s.replace(',',' ')
- s= s.replace('x',' ')
- s= s.replace('x^',' ')
- s = s.replace(':',' ')
- s = s.replace('\n',' ')
+ s = s.replace(',', ' ')
+ s = s.replace('x', ' ')
+ s = s.replace('x^', ' ')
+ s = s.replace(':', ' ')
+ s = s.replace('\n', ' ')
s = s.split(' ')
num = len(s)
i = 0
print(s)
self.polynomial = dict()
li = [float(i) for i in s]
- while ichd and nd.left is not None:
- if nd.left is chd: return nd
+ if nd > chd and nd.left is not None:
+ if nd.left is chd: return nd
else: nd = nd.left
- elif ndval:
+ elif nd.val > val:
nd = nd.left
else:
nd = nd.right
- def getSuccessor(self,nd):
+
+ def getSuccessor(self, nd):
if nd:
if nd.right:
nd = nd.right
while nd.left:
nd = nd.left
return nd
- else:return self.getParent(nd)
- def transferParent(self,origin,new):
- if origin is self.root:
+ else:
+ return self.getParent(nd)
+
+ def transferParent(self, origin, new):
+ if origin is self.root:
self.root = new
else:
prt = self.getParent(origin)
prt.setChild(new, prt.left is origin)
- def insert(self,nd):
- if not isinstance(nd,node):
+ def insert(self, nd):
+ if not isinstance(nd, node):
nd = node(nd)
- elif nd.isBlack: nd.isBlack = False
+ elif nd.isBlack:
+ nd.isBlack = False
if self.root is None:
self.root = nd
@@ -111,12 +132,12 @@ def insert(self,nd):
else:
parent = self.root
while parent:
- if parent == nd : return None
- if parent>nd:
- if parent.left :
+ if parent == nd: return None
+ if parent > nd:
+ if parent.left:
parent = parent.left
else:
- parent.left = nd
+ parent.left = nd
break
else:
if parent.right:
@@ -124,12 +145,13 @@ def insert(self,nd):
else:
parent.right = nd
break
- self.fixUpInsert(parent,nd)
- def fixUpInsert(self,parent,nd):
+ self.fixUpInsert(parent, nd)
+
+ def fixUpInsert(self, parent, nd):
''' adjust color and level, there are two red nodes: the new one and its parent'''
while not self.checkBlack(parent):
grand = self.getParent(parent)
- isLeftPrt = grand.left is parent
+ isLeftPrt = grand.left is parent
uncle = grand.getChild(not isLeftPrt)
if not self.checkBlack(uncle):
# case 1: new node's uncle is red
@@ -146,35 +168,36 @@ def fixUpInsert(self,parent,nd):
# grand grand
# parent or parent
# nd nd
- parent.setChild(nd.getChild(isLeftPrt),not isLeftPrt)
- nd.setChild(parent,isLeftPrt)
- grand.setChild(nd,isLeftPrt)
- nd,parent = parent,nd
+ parent.setChild(nd.getChild(isLeftPrt), not isLeftPrt)
+ nd.setChild(parent, isLeftPrt)
+ grand.setChild(nd, isLeftPrt)
+ nd, parent = parent, nd
# case 2.2 the new node is inserted in left-left or right-right form
# grand grand
# parent or parent
# nd nd
- grand.setChild(parent.getChild(not isLeftPrt),isLeftPrt)
- parent.setChild(grand,not isLeftPrt)
+ grand.setChild(parent.getChild(not isLeftPrt), isLeftPrt)
+ parent.setChild(grand, not isLeftPrt)
self.setBlack(grand, False)
self.setBlack(parent, True)
- self.transferParent(grand,parent)
- self.setBlack(self.root,True)
+ self.transferParent(grand, parent)
+ self.setBlack(self.root, True)
- def copyNode(self,src,des):
+ def copyNode(self, src, des):
'''when deleting a node which has two kids,
copy its succesor's data to his position
data exclude left, right , isBlack
'''
des.val = src.val
- def delete(self,nd):
+
+ def delete(self, nd):
'''delete node in a binary search tree'''
- if not isinstance(nd,node):
+ if not isinstance(nd, node):
nd = self.find(nd)
if nd is None: return
y = None
if nd.left and nd.right:
- y= self.getSuccessor(nd)
+ y = self.getSuccessor(nd)
else:
y = nd
py = self.getParent(y)
@@ -186,68 +209,67 @@ def delete(self,nd):
else:
py.right = x
if y != nd:
- self.copyNode(y,nd)
+ self.copyNode(y, nd)
- if self.checkBlack(y): self.fixUpDel(py,x)
+ if self.checkBlack(y): self.fixUpDel(py, x)
-
- def fixUpDel(self,prt,chd):
+ def fixUpDel(self, prt, chd):
''' adjust colors and rotate '''
while self.root != chd and self.checkBlack(chd):
- isLeft = prt.left is chd
+ isLeft = prt.left is chd
brother = prt.getChild(not isLeft)
# brother is black
lb = self.checkBlack(brother.getChild(isLeft))
rb = self.checkBlack(brother.getChild(not isLeft))
- if not self.checkBlack(brother):
+ if not self.checkBlack(brother):
# case 1: brother is red. converted to case 2,3,4
# prt (isLeft) rotate
prt.setChild(brother.getChild(isLeft), not isLeft)
brother.setChild(prt, isLeft)
- self.setBlack(prt,False)
- self.setBlack(brother,True)
+ self.setBlack(prt, False)
+ self.setBlack(brother, True)
- self.transferParent(prt,brother)
- elif lb and rb:
- # case 2: brother is black and two kids are black.
+ self.transferParent(prt, brother)
+ elif lb and rb:
+ # case 2: brother is black and two kids are black.
# conveted to the begin case
- self.setBlack(brother,False)
+ self.setBlack(brother, False)
chd = prt
prt = self.getParent(chd)
else:
- if rb:
+ if rb:
# case 3: brother is black and left kid is red and right child is black
# uncle's son is nephew, and niece for uncle's daughter
nephew = brother.getChild(isLeft)
- self.setBlack(nephew,True)
- self.setBlack(brother,False)
+ self.setBlack(nephew, True)
+ self.setBlack(brother, False)
# brother (not isLeft) rotate
- prt.setChild(nephew,not isLeft)
- brother.setChild(nephew.getChild(not isLeft),isLeft)
+ prt.setChild(nephew, not isLeft)
+ brother.setChild(nephew.getChild(not isLeft), isLeft)
nephew.setChild(brother, not isLeft)
brother = nephew
# case 4: brother is black and right child is red
brother.isBlack = prt.isBlack
- self.setBlack(prt,True)
- self.setBlack(brother.getChild(not isLeft),True)
+ self.setBlack(prt, True)
+ self.setBlack(brother.getChild(not isLeft), True)
# prt left rotate
- prt.setChild(brother.getChild(isLeft),not isLeft)
- brother.setChild(prt,isLeft)
+ prt.setChild(brother.getChild(isLeft), not isLeft)
+ brother.setChild(prt, isLeft)
- self.transferParent(prt,brother)
+ self.transferParent(prt, brother)
chd = self.root
- self.setBlack(chd,True)
-
+ self.setBlack(chd, True)
def display(self):
def getHeight(nd):
- if nd is None:return 0
- return max(getHeight(nd.left),getHeight(nd.right)) +1
+ if nd is None: return 0
+ return max(getHeight(nd.left), getHeight(nd.right)) + 1
+
def levelVisit(root):
from collections import deque
lst = deque([root])
@@ -255,85 +277,93 @@ def levelVisit(root):
h = getHeight(root)
ct = lv = 0
while 1:
- ct+=1
+ ct += 1
nd = lst.popleft()
if ct >= 2**lv:
- lv+=1
- if lv>h:break
+ lv += 1
+ if lv > h: break
level.append([])
level[-1].append(str(nd))
if nd is not None:
- lst += [nd.left,nd.right]
+ lst += [nd.left, nd.right]
else:
- lst +=[None,None]
+ lst += [None, None]
return level
+
def addBlank(lines):
width = 5
- sep = ' '*width
+ sep = ' ' * width
n = len(lines)
- for i,oneline in enumerate(lines):
- k = 2**(n-i) -1
- new = [sep*((k-1)//2)]
+ for i, oneline in enumerate(lines):
+ k = 2**(n - i) - 1
+ new = [sep * ((k - 1) // 2)]
for s in oneline:
new.append(s.ljust(width))
- new.append(sep*k)
+ new.append(sep * k)
lines[i] = new
return lines
lines = levelVisit(self.root)
lines = addBlank(lines)
li = [''.join(line) for line in lines]
- li.insert(0,'red-black-tree'.rjust(48,'-') + '-'*33)
- li.append('end'.rjust(42,'-')+'-'*39+'\n')
- return '\n'.join(li)
-
+ li.insert(0, 'red-black-tree'.rjust(48, '-') + '-' * 33)
+ li.append('end'.rjust(42, '-') + '-' * 39 + '\n')
+ return '\n'.join(li)
+
def __str__(self):
return self.display()
-def genNum(n =10):
- nums =[]
+def genNum(n=10):
+ nums = []
for i in range(n):
while 1:
- d = randint(0,100)
+ d = randint(0, 100)
if d not in nums:
nums.append(d)
break
return nums
-def buildTree(n=10,nums=None,visitor=None):
- if nums is None or nums ==[]: nums = genNum(n)
+
+def buildTree(n=10, nums=None, visitor=None):
+ if nums is None or nums == []: nums = genNum(n)
rbtree = redBlackTree()
print(f'build a red-black tree using {nums}')
for i in nums:
rbtree.insert(i)
if visitor:
visitor(rbtree)
- return rbtree,nums
+ return rbtree, nums
+
+
def testInsert():
def visitor(t):
print(t)
- rbtree,nums = buildTree(visitor = visitor)
- print('-'*5+ 'in-order visit' + '-'*5)
- for i,j in enumerate(rbtree.sort()):
+
+ rbtree, nums = buildTree(visitor=visitor)
+ print('-' * 5 + 'in-order visit' + '-' * 5)
+ for i, j in enumerate(rbtree.sort()):
print(f'{i+1}: {j}')
+
def testSuc():
- rbtree,nums = buildTree()
+ rbtree, nums = buildTree()
for i in rbtree.sort():
print(f'{i}\'s suc is {rbtree.getSuccessor(i)}')
+
def testDelete():
#nums = [2,3,3,2,6,7,2,1]
nums = None
- rbtree,nums = buildTree(nums = nums)
+ rbtree, nums = buildTree(nums=nums)
print(rbtree)
for i in nums:
print(f'deleting {i}')
rbtree.delete(i)
print(rbtree)
-if __name__=='__main__':
+
+if __name__ == '__main__':
#testSuc()
#testInsert()
testDelete()
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/splayTree.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/splayTree.py"
index 42be71b..a4f84cf 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/splayTree.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/codes/mbinary/splayTree.py"
@@ -10,148 +10,170 @@
#########################################################################
'''
-from collections import deque,Iterable
+from collections import deque, Iterable
+
+
# use isinstance(obj,Iterable) to judge if an obj is iterable
class node:
- def __init__(self,val = None,left=None,right=None,parent=None):
+ def __init__(self, val=None, left=None, right=None, parent=None):
self.val = val
- if val :self.freq = 1
- else :self.freq = 0
+ if val: self.freq = 1
+ else: self.freq = 0
self.left = left
self.right = right
- self.parent = parent
- def getChild(self,s=0):
- if isinstance(s,int):s =[s]
+ self.parent = parent
+
+ def getChild(self, s=0):
+ if isinstance(s, int): s = [s]
last = self
for i in s:
- if not last:return None
+ if not last: return None
if i == 0: last = last.left
- else:last = last.right
+ else: last = last.right
return last
- def setChild(self,child,s=0):
- if isinstance(s,Iterable):
+
+ def setChild(self, child, s=0):
+ if isinstance(s, Iterable):
i = s[0]
del s[0]
- if i == 0:self.left.setChild(child,s)
- else:self.right.setChild(child,s)
- elif s:self.right = child
- else:self.left = child
+ if i == 0: self.left.setChild(child, s)
+ else: self.right.setChild(child, s)
+ elif s: self.right = child
+ else: self.left = child
+
+
class splayTree:
- def __init__(self,s=[]):
+ def __init__(self, s=[]):
s = list(s)
self.root = None
- s = sorted(s,reverse = True)
+ s = sorted(s, reverse=True)
for i in s:
- self.insert(self.root,i)
- def insert(self,k):
- if not self.root :self.root = node(k)
- else:self._insert(self.root,k)
- def _insert(self,root,k):
- if root.val == k :
- root.freq +=1
- elif root.val k:
- return self._find(root.left,k)
- elif root.valself.s else 2*p+self.lowExt-self.n+1
- def arrayToTree(self,i):
- return (i+self.offset)//2 if i<=self.lowExt else (i-self.lowExt+ self.n-1)//2
- def win(self,a,b):
- return ab
- def initTree(self,p):
- if p>=self.n:
- delta = p%2 #!!! good job notice delta mark the lchild or rchlid
- return self.players[self.treeToArray(p//2)+delta]
- l = self.initTree(2*p)
- r = self.initTree(2*p+1)
- self.tree[p] = l if self.win(l,r) else r
+ self.lowExt = (self.n - i) * 2
+ self.s = i - 1
+ self.offset = 2 * i - 1
+
+ def treeToArray(self, p):
+ return 2 * p - self.offset if p > self.s else 2 * p + self.lowExt - self.n + 1
+
+ def arrayToTree(self, i):
+ return (i + self.offset) // 2 if i <= self.lowExt else (
+ i - self.lowExt + self.n - 1) // 2
+
+ def win(self, a, b):
+ return a < b if self.reverse else a > b
+
+ def initTree(self, p):
+ if p >= self.n:
+ delta = p % 2 #!!! good job notice delta mark the lchild or rchlid
+ return self.players[self.treeToArray(p // 2) + delta]
+ l = self.initTree(2 * p)
+ r = self.initTree(2 * p + 1)
+ self.tree[p] = l if self.win(l, r) else r
return self.tree[p]
+
def winner(self):
idx = 1
- while 2*idx'
+ return '--' + str(self.weight) + '-->'
+
def __repr__(self):
return str(self)
+
+
class graph:
- def __init__(self):
+ def __init__(self):
self.vertexs = {}
self.edges = {}
- def __getitem__(self,i):
+
+ def __getitem__(self, i):
return self.vertexs[i]
- def __setitem__(selfi,x):
- self.vertexs[i]= x
+
+ def __setitem__(self, i, x):
+ self.vertexs[i] = x
+
def __iter__(self):
return iter(self.vertexs.values())
+
def __bool__(self):
- return len(self.vertexs)!=0
- def addVertex(self,i):
- if not (i,vertex) and i not in self.vertexs:self.vertexs[i]= vertex(i)
- if isinstance(i,vertex) and i not in self.vertexs:self.vertexs[i.mark]= i
- def isConnected(self,v,u):
+ return len(self.vertexs) != 0
+
+ def addVertex(self, i):
+ if not (i, vertex) and i not in self.vertexs:
+ self.vertexs[i] = vertex(i)
+ if isinstance(i, vertex) and i not in self.vertexs:
+ self.vertexs[i.mark] = i
+
+ def isConnected(self, v, u):
v = self.__getVertex(v)
u = self.__getVertex(u)
- arc= v.firstEdge
- while arc!=None:
- if arc.inArrow==u:return True
+ arc = v.firstEdge
+ while arc != None:
+ if arc.inArrow == u: return True
arc = arc.inNextEdge
return False
- def __getVertex(self,v):
- if not isinstance(v,vertex):
+
+ def __getVertex(self, v):
+ if not isinstance(v, vertex):
if v not in self.vertexs:
- self.vertexs[v]=vertex(v)
+ self.vertexs[v] = vertex(v)
return self.vertexs[v]
return v
- def addEdge(self,v,u,weight = 1):
+
+ def addEdge(self, v, u, weight=1):
v = self.__getVertex(v)
u = self.__getVertex(u)
arc = v.firstEdge
- while arc!=None: #examine that if v,u have been already connected
- if arc.inArrow==u: return
- arc= arc.outNextEdge
- newEdge = edge(v,u,v.firstEdge,u.firstEdge,weight)
- self.edges[(v.mark,u.mark)] = newEdge
+ while arc != None: #examine that if v,u have been already connected
+ if arc.inArrow == u: return
+ arc = arc.outNextEdge
+ newEdge = edge(v, u, v.firstEdge, u.firstEdge, weight)
+ self.edges[(v.mark, u.mark)] = newEdge
v.firstEdge = newEdge
- def delEdge(self,v,u):
- if not isinstance(v,vertex):v= self.vertexs[v]
- if not isinstance(u,vertex):u= self.vertexs[u]
- self._unrelated(v,u)
- del self.edges[(v.mark,u.mark)]
- def _unrelated(self,v,u):
- if v.firstEdge==None:return
+
+ def delEdge(self, v, u):
+ if not isinstance(v, vertex): v = self.vertexs[v]
+ if not isinstance(u, vertex): u = self.vertexs[u]
+ self._unrelated(v, u)
+ del self.edges[(v.mark, u.mark)]
+
+ def _unrelated(self, v, u):
+ if v.firstEdge == None: return
if v.firstEdge.inArrow == u:
- v.firstEdge =v.firstEdge.outNextEdge
+ v.firstEdge = v.firstEdge.outNextEdge
else:
arc = v.firstEdge
- while arc.outNextEdge!=None:
- if arc.outNextEdge.inArrow ==u:
- arc.outNextEdge = arc.outNextEdge.outNextEdge
- break
+ while arc.outNextEdge != None:
+ if arc.outNextEdge.inArrow == u:
+ arc.outNextEdge = arc.outNextEdge.outNextEdge
+ break
+
def reVisit(self):
for i in self.vertexs:
- self.vertexs[i].isVisited=False
+ self.vertexs[i].isVisited = False
for i in self.edges:
- self.edges[i].isVisited=False
+ self.edges[i].isVisited = False
+
def __str__(self):
- arcs= list(self.edges.keys())
- arcs=[str(i[0])+'--->'+str(i[1])+' weight:'+str(self.edges[i].weight) for i in arcs]
- s= '\n'.join(arcs)
+ arcs = list(self.edges.keys())
+ arcs = [
+ str(i[0]) + '--->' + str(i[1]) + ' weight:' + str(
+ self.edges[i].weight) for i in arcs
+ ]
+ s = '\n'.join(arcs)
return s
+
def __repr__(self):
return str(self)
- def notIn(self,v):
- if (isinstance(v,vertex) and v.mark not in self.vertexs) or v not in self.vertexs:
+
+ def notIn(self, v):
+ if (isinstance(v, vertex)
+ and v.mark not in self.vertexs) or v not in self.vertexs:
return True
return False
- def minPath(self,v,u):
+
+ def minPath(self, v, u):
'''dijstra'''
self.reVisit()
- if self.notIn(v) or self.notIn(u):
- return [],0
+ if self.notIn(v) or self.notIn(u):
+ return [], 0
v = self.__getVertex(v)
u = self.__getVertex(u)
- if v.firstEdge==None:return [],0
- q=deque([v])
- last = {i : None for i in self}
- distance={i : 1<<30 for i in self}
- distance[v]=0
- while len(q)!=0:
- cur= q.popleft()
+ if v.firstEdge == None: return [], 0
+ q = deque([v])
+ last = {i: None for i in self}
+ distance = {i: 1 << 30 for i in self}
+ distance[v] = 0
+ while len(q) != 0:
+ cur = q.popleft()
cur.isVisited = True
arc = cur.firstEdge
- while arc!=None:
+ while arc != None:
to = arc.inArrow
if not to.isVisited:
q.append(to)
- if distance [to] > distance[cur]+arc.weight:
- last[to]=cur
- distance[to] =distance[cur]+arc.weight
- arc= arc.outNextEdge
+ if distance[to] > distance[cur] + arc.weight:
+ last[to] = cur
+ distance[to] = distance[cur] + arc.weight
+ arc = arc.outNextEdge
cur = u
- path=[]
- while cur!=None and cur!=v:
+ path = []
+ while cur != None and cur != v:
path.append(cur.mark)
- cur=last[cur]
- if cur==None:return [], 0
+ cur = last[cur]
+ if cur == None: return [], 0
path.append(v.mark)
- return path[::-1],distance[u]
- def hasVertex(self,mark):
+ return path[::-1], distance[u]
+
+ def hasVertex(self, mark):
return mark in self.vertexs
+
def display(self):
print('vertexs')
for i in self.vertexs:
print(self.vertexs[i].__repr__())
print('edges')
for i in self.edges:
- arc=self.edges[i]
- print(str(arc.outArrow)+str(arc)+str(arc.inArrow))
+ arc = self.edges[i]
+ print(str(arc.outArrow) + str(arc) + str(arc.inArrow))
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/navigation/graph.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/navigation/graph.py"
index 799aaf6..f6964ef 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/navigation/graph.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/navigation/graph.py"
@@ -1,189 +1,227 @@
from collections import deque
import directed
+
+
class vertex:
- def __init__(self,mark,val=None):
+ def __init__(self, mark, val=None):
self.mark = mark
self.val = val
self.edges = {}
self.isVisited = False
- def __getitem__(self,adjVertexMark):
+
+ def __getitem__(self, adjVertexMark):
return self.edges[adjVertexMark]
- def __delitem__(self,k):
+
+ def __delitem__(self, k):
del self.edges[k]
+
def __iter__(self):
return iter(self.edges.values())
+
def __str__(self):
try:
int(self.mark)
- return 'v'+str(self.mark)
- except:return str(self.mark)
+ return 'v' + str(self.mark)
+ except:
+ return str(self.mark)
+
def __repr__(self):
return str(self)
+
+
class edge:
- def __init__(self,adjVertexs, weight = 1):
+ def __init__(self, adjVertexs, weight=1):
'''adjVertexs:tuple(v.mark,u.mark)'''
self.weight = weight
self.adjVertexs = adjVertexs
self.isVisted = False
- def __add__(self,x):
- return self.weight +x
- def __radd__(self,x):
- return self+x
- def __getitem__(self,k):
- if k!=0 or k!=1:raise IndexError
+
+ def __add__(self, x):
+ return self.weight + x
+
+ def __radd__(self, x):
+ return self + x
+
+ def __getitem__(self, k):
+ if k != 0 or k != 1: raise IndexError
return self.adjVertexs[k]
+
def __str__(self):
- return '--'+str(self.weight)+'--'
+ return '--' + str(self.weight) + '--'
+
def __repr__(self):
return str(self)
+
@property
def v(self):
return self.adjVertexs[0]
+
@property
def u(self):
return self.adjVertexs[1]
+
+
class graph:
- def __init__(self):
+ def __init__(self):
self.vertexs = {}
self.edges = {}
- def __getitem__(self,i):
+
+ def __getitem__(self, i):
return self.vertexs[i]
- def __setitem__(selfi,x):
- self.vertexs[i]= x
+
+ def __setitem__(self, i, x):
+ self.vertexs[i] = x
+
def __iter__(self):
return iter(self.vertexs)
+
def __bool__(self):
- return len(self.vertexs)!=0
- def addVertex(self,v):
- if not isinstance(v,vertex) and v not in self.vertexs:self.vertexs[v]= vertex(v)
- if isinstance(v,vertex) and v not in self.vertexs:self.vertexs[v.mark]= v
+ return len(self.vertexs) != 0
+
+ def addVertex(self, v):
+ if not isinstance(v, vertex) and v not in self.vertexs:
+ self.vertexs[v] = vertex(v)
+ if isinstance(v, vertex) and v not in self.vertexs:
+ self.vertexs[v.mark] = v
- def __getVertex(self,v):
- if not isinstance(v,vertex):
+ def __getVertex(self, v):
+ if not isinstance(v, vertex):
if v not in self.vertexs:
- self.vertexs[v]=vertex(v)
+ self.vertexs[v] = vertex(v)
return self.vertexs[v]
return v
- def addEdge(self,v,u,weight = 1):
+
+ def addEdge(self, v, u, weight=1):
v = self.__getVertex(v)
u = self.__getVertex(u)
for arc in v:
- if u in arc.adjVertexs:return #examine that if v,u have been already connected
- vertexs = (v,u)
- newEdge = edge (vertexs,weight)
+ if u in arc.adjVertexs:
+ return #examine that if v,u have been already connected
+ vertexs = (v, u)
+ newEdge = edge(vertexs, weight)
self.edges[vertexs] = newEdge
v.edges[u] = newEdge
- u.edges[v] = newEdge
- def delEdge(self,v,u):
- if not isinstance(v,vertex):v= self.vertexs[v]
- if not isinstance(u,vertex):u= self.vertexs[u]
+ u.edges[v] = newEdge
+
+ def delEdge(self, v, u):
+ if not isinstance(v, vertex): v = self.vertexs[v]
+ if not isinstance(u, vertex): u = self.vertexs[u]
try:
del v[u]
del u[v]
- except:print("error!"+str(v)+','+str(u)+' arent adjacent now')
- del self.edges[(v,u)]
+ except:
+ print("error!" + str(v) + ',' + str(u) + ' arent adjacent now')
+ del self.edges[(v, u)]
+
def reVisit(self):
for i in self.vertexs.values():
i.isVisited = False
for i in self.edges.values():
i.isVisited = False
+
def __str__(self):
- arcs= list(self.edges.keys())
- arcs=[str(i[0])+str(self.edges[i])+str(i[1]) for i in arcs]
- s= '\n'.join(arcs)
+ arcs = list(self.edges.keys())
+ arcs = [str(i[0]) + str(self.edges[i]) + str(i[1]) for i in arcs]
+ s = '\n'.join(arcs)
return s
+
def __repr__(self):
return str(self)
- def minPath(self,v,u):
+
+ def minPath(self, v, u):
self.reVisit()
- v=self.__getVertex(v)
- u=self.__getVertex(u)
- q=deque([v])
- last={i:None for i in self.vertexs.values()}
+ v = self.__getVertex(v)
+ u = self.__getVertex(u)
+ q = deque([v])
+ last = {i: None for i in self.vertexs.values()}
last[v] = 0
- ds={i:1<<30 for i in self.vertexs.values()}
- ds[v]=0
- while len(q)!=0:
+ ds = {i: 1 << 30 for i in self.vertexs.values()}
+ ds[v] = 0
+ while len(q) != 0:
nd = q.popleft()
- nd.isVisited=True
- for edge in nd:
- tgt=None
- if edge.v==nd:
+ nd.isVisited = True
+ for edge in nd:
+ tgt = None
+ if edge.v == nd:
tgt = edge.u
- else:tgt = edge.v
- tmp=ds[nd]+edge
- if ds[tgt] >tmp:
- ds[tgt]=tmp
+ else:
+ tgt = edge.v
+ tmp = ds[nd] + edge
+ if ds[tgt] > tmp:
+ ds[tgt] = tmp
last[tgt] = nd
- if not tgt.isVisited:q.append(tgt)
- path=[]
+ if not tgt.isVisited: q.append(tgt)
+ path = []
cur = u
- while cur !=None and cur.mark!=v.mark:
+ while cur != None and cur.mark != v.mark:
path.append(cur.mark)
cur = last[cur]
- if cur==None:return [],-1
+ if cur == None: return [], -1
path.append(v.mark)
- return path[::-1],ds[u]
+ return path[::-1], ds[u]
+
def hasCircle(self):
pass
+
def display(self):
print('vertexs')
for i in self.vertexs:
- print(i,end=' ')
+ print(i, end=' ')
print('')
print('edges')
for i in self.edges:
- arc=self.edges[i]
- print(str(arc.v)+str(arc)+str(arc.u))
+ arc = self.edges[i]
+ print(str(arc.v) + str(arc) + str(arc.u))
+
def loop(dic):
while True:
print('input vertexs to get the min distance, input \'exit\' to exit')
- s=input().strip()
- if s=='exit':break
- s=s.split(' ')
- s=[dic[i] if '0'<=i[0]<='9' else i for i in s]
- a,b,c=s[0],s[1],None
- path,d = g.minPath(a,b)
- path2=None
- if len(s)==3:
- c=s[2]
- path2,d2=g.minPath(b,c)
- d+=d2
- if path==[] or path2==[] :
- if len(s)==3: print(a+' can\'t reach '+c+' via '+b)
- else: print(a+' can\'t reach '+b)
+ s = input().strip()
+ if s == 'exit': break
+ s = s.split(' ')
+ s = [dic[i] if '0' <= i[0] <= '9' else i for i in s]
+ a, b, c = s[0], s[1], None
+ path, d = g.minPath(a, b)
+ path2 = None
+ if len(s) == 3:
+ c = s[2]
+ path2, d2 = g.minPath(b, c)
+ d += d2
+ if path == [] or path2 == []:
+ if len(s) == 3: print(a + ' can\'t reach ' + c + ' via ' + b)
+ else: print(a + ' can\'t reach ' + b)
continue
- if path2!=None:path+=path2[1:]
- print('distance : ',d)
- print('path','-->'.join(path))
+ if path2 != None: path += path2[1:]
+ print('distance : ', d)
+ print('path', '-->'.join(path))
-if __name__ =='__main__':
- s=input('1. undireted\n2. directed\n')
- flag=input('name vertex by 1. num(1-index) or 2. string? ').strip()
- dic={}
+if __name__ == '__main__':
+ s = input('1. undireted\n2. directed\n')
+ flag = input('name vertex by 1. num(1-index) or 2. string? ').strip()
+ dic = {}
g = graph()
- if s=='2': g=directed.graph()
- v,e=input('input vertex num & edge num: ').strip().split(' ')
- v,e=int(v),int(e)
- if flag=='1':
+ if s == '2': g = directed.graph()
+ v, e = input('input vertex num & edge num: ').strip().split(' ')
+ v, e = int(v), int(e)
+ if flag == '1':
for i in range(v):
- tmp=str(i+1)
- dic[tmp]=tmp
+ tmp = str(i + 1)
+ dic[tmp] = tmp
g.addVertex(tmp)
else:
- print('input vertex name line by line')
+ print('input vertex name line by line')
for i in range(v):
- dic[str(i+1)]=input().strip()
- g.addVertex(dic[str(i+1)])
- print('input edge info line by line')
+ dic[str(i + 1)] = input().strip()
+ g.addVertex(dic[str(i + 1)])
+ print('input edge info line by line')
for i in range(e):
- li=input().strip().split(' ')
- a,b,w=li[0],li[1],1
- if len(li)==3:w=int(li[2])
- a,b=dic[a],dic[b]
- g.addEdge(a,b,w)
+ li = input().strip().split(' ')
+ a, b, w = li[0], li[1], 1
+ if len(li) == 3: w = int(li[2])
+ a, b = dic[a], dic[b]
+ g.addEdge(a, b, w)
print('you\'ve build graph :')
g.display()
loop(dic)
@@ -197,7 +235,6 @@ def loop(dic):
3 4 1
1 5
'''
-
'''
6 10
NewYork
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/polynomial/polynomial.py" "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/polynomial/polynomial.py"
index c6d80dd..14f7830 100644
--- "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/polynomial/polynomial.py"
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2017/polynomial/polynomial.py"
@@ -1,55 +1,64 @@
-# notice that creating a class's omstamce won't conflict with __call__ method
+# notice that creating a class's omstamce won't conflict with __call__ method
# because the former call class ,and the latter call instance
class polynomial:
- pls= []
+ pls = []
n = 0
+
def dictize(pl):
- if isinstance(pl,int) or isinstance(pl,float):
- pl = {0:pl}
- if isinstance(pl,polynomial):
+ if isinstance(pl, int) or isinstance(pl, float):
+ pl = {0: pl}
+ if isinstance(pl, polynomial):
pl = pl.polynomial.copy()
return pl
+
def isZero(n):
- return abs(n)<0.000001
- def __init__(self,s='0 0'):
+ return abs(n) < 0.000001
+
+ def __init__(self, s='0 0'):
polynomial.pls.append(self)
- polynomial.n +=1
- if isinstance(s,polynomial):
- self.polynomial=s.polynomial.copy()
- # don't write like this .**self.polynomial = s.polynomial**,it's ref
+ polynomial.n += 1
+ if isinstance(s, polynomial):
+ self.polynomial = s.polynomial.copy()
+ # don't write like this .**self.polynomial = s.polynomial**,it's ref
return
- elif isinstance(s,dict):
+ elif isinstance(s, dict):
self.polynomial = s.copy()
return
- s= s.replace(',',' ')
- s= s.replace('x',' ')
- s= s.replace('x^',' ')
- s = s.replace(':',' ')
- s = s.replace('\n',' ')
+ s = s.replace(',', ' ')
+ s = s.replace('x', ' ')
+ s = s.replace('x^', ' ')
+ s = s.replace(':', ' ')
+ s = s.replace('\n', ' ')
s = s.split(' ')
num = len(s)
i = 0
print(s)
self.polynomial = dict()
li = [float(i) for i in s]
- while i)
+project(Elevator)
+
+set(CMAKE_CXX_STANDARD 14)
+
+include_directories(.)
+
+add_executable(Elevator
+ elevator.cpp
+ elevator.hpp
+ event.hpp
+ main.cpp
+ person.hpp)
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/README.md" "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/README.md"
new file mode 100644
index 0000000..b9897a9
--- /dev/null
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/README.md"
@@ -0,0 +1,14 @@
+# 电梯模拟
+
+```
+mkdir e
+cd e
+cmake ..
+make
+cd ..
+./e/Elevator
+```
+
+然后按回车查看效果
+
+建议使用xterm等速度快的终端效果更好
\ No newline at end of file
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/elevator.cpp" "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/elevator.cpp"
new file mode 100755
index 0000000..f4c39e1
--- /dev/null
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/elevator.cpp"
@@ -0,0 +1,492 @@
+/* elevator.cpp */
+#include
+#include
+#include
+#include
+#include
+#include
+#include "elevator.hpp"
+#include "person.hpp"
+using namespace std;
+void Panic(const char* s, ...)
+{
+ char sfinal[100];
+ va_list ap;
+ va_start(ap, s);
+ vsnprintf(sfinal, 100, s, ap);
+ cout << "FATAL Error: " << sfinal << "!" << endl;
+ exit(-2);
+}
+void notify(const char* s, ...)
+{
+#ifdef DEBUG
+ char sfinal[100];
+ va_list ap;
+ va_start(ap, s);
+ vsnprintf(sfinal, 100, s, ap);
+ string c1 = "zenity --info --text=\"";
+ string c2 = "\"";
+ system((c1 + sfinal + c2).c_str());
+#endif
+}
+ElevatorSystem::ElevatorSystem()
+{
+ cout << "Default constructor will never work, please give parameters" << endl;
+}
+ElevatorSystem::ElevatorSystem(Building* building, EventList* elist)
+{
+ this->eventlist = elist;
+ this->building = building;
+ for(int i = 0; i < ElevatorNumber; i++)
+ elevators[i] = Elevator(i, this);
+ for(int i = 1; i <= FloorNumber; i++){
+ upassigns[i] = -1;
+ downassigns[i] = -1;
+ buttons[i] = Button();
+ }
+}
+void ElevatorSystem::PressButton(int floor, Direction d)
+{
+ if(this->buttons[floor].Get(d))
+ //Already pressed, do nothing
+ return;
+ //Assign this press to the nearest elevator and activate it
+ this->buttons[floor].Press(d);
+ int elevindex = this->AssignElevator(floor, d);
+ //cout << "E:" << elevindex << endl;
+ //cin.get();
+ if(d == UP)
+ upassigns[floor] = elevindex;
+ else if(d == DOWN)
+ downassigns[floor] = elevindex;
+ else
+ Panic("Pressed and idle button");
+ //Another bug corpse here. If activate several times, a disaster will happen
+ if(!elevators[elevindex].isactive){
+ //cout << "elev " << elevindex << " now begin working by elevsys" << endl;
+ //cin.get();
+ elevators[elevindex].Activate();
+ }
+}
+int ElevatorSystem::AssignElevator(int floor, Direction d)
+{
+ //TODO: actually, if several elevator take (evaluated) same time to the given position, then a random index between them should be given to balance wear off in Physical World.
+ //In this program just pick the first one. (change < to <= to choose the last one)
+ int minelevidx = -1;
+ Time mintimeused = Inf;
+ Time timeused;
+ for(int i = 0; i < ElevatorNumber; i++){
+ timeused = elevators[i].EvaluateTimeToFloor(floor, d);
+ if(timeused < mintimeused){
+ minelevidx = i;
+ mintimeused = timeused;
+ }
+ }
+ notify("AssignElevator %d.", minelevidx);
+ return minelevidx;
+}
+
+Elevator::Elevator()
+{
+ //cout << "an Elevator should belong to an ElevatorSystem and should not be defined explicitly" << endl;
+}
+Elevator::Elevator(int idx, ElevatorSystem* father)
+{
+ this->index = idx;
+ this->father = father;
+ this->isactive = false;
+ this->isdooropened = false;
+ this->personnum = 0;
+ this->atfloor = 1;
+ this->dir = NODIRECTION;
+ this->personsonboard = Linklist();
+ this->floorbutton = FloorButton();
+ this->maxperson = ElevatorMaxPerson;
+ this->homefloor = ElevatorHomeFloor;
+ this->timeGotoNextFloor = ElevatorGotoNextFloorTime;
+ this->timeDoorOpen = ElevatorDoorOpenTime;
+ this->timeDoorClose = ElevatorDoorCloseTime;
+ this->timeDoorKeepOpen = ElevatorDoorKeepOpenTime;
+}
+//This func is NOT GOOD ENOUGH, some small points NOT CONSIDIRED
+//but it can work
+Time Elevator::EvaluateTimeToFloor(int floor, Direction d) const
+{
+ if(!this->isactive)
+ return this->timeGotoNextFloor * fabs(floor - this->atfloor);
+ int maxfloor = this->atfloor;
+ int minfloor = this->atfloor;
+ int dooropentimes = 0;
+ //up to top, then down to bottom, and then (up or down without stop) to fetch new person
+ if(this->dir == UP && d == UP && atfloor >= floor){
+ for(int i = atfloor; i <= FloorNumber; i++)
+ if(father->buttons[i].Get(UP) || this->floorbutton.isPressed(i)){
+ maxfloor = i;
+ dooropentimes++;
+ }
+ for(int i = maxfloor; i >= 1; i--)
+ //use && to avoid recount dooropentimes
+ if(father->buttons[i].Get(DOWN) || (this->floorbutton.isPressed(i) && i < atfloor)){
+ minfloor = i;
+ dooropentimes++;
+ }
+ //only one of the two following cases will be executed
+ for(int i = minfloor; i < floor; i++)
+ if(father->buttons[i].Get(UP))
+ dooropentimes++;
+ for(int i = minfloor; i > floor; i--)
+ if(father->buttons[i].Get(DOWN))
+ dooropentimes++;
+ return this->timeGotoNextFloor * (maxfloor - this->atfloor + maxfloor - minfloor + fabs(floor - minfloor)) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ }
+ //up(or then down after) and fetch person
+ if(this->dir == UP && d == UP && this->atfloor < floor){
+ for(int i = this->atfloor; i <= floor; i++)
+ if(this->father->buttons[i].Get(UP) || this->floorbutton.isPressed(i))
+ dooropentimes++;
+ return this->timeGotoNextFloor * fabs(floor - this->atfloor) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ }
+ //up to top and down to fetch person
+ if(this->dir == UP && d == DOWN){
+ for(int i = this->atfloor; i <= FloorNumber; i++)
+ if(this->father->buttons[i].Get(UP) || this->floorbutton.isPressed(i)){
+ maxfloor = i;
+ dooropentimes++;
+ }
+ for(int i = maxfloor; i >= floor; i--)
+ if(this->father->buttons[i].Get(DOWN) || (this->floorbutton.isPressed(i) && i < atfloor))
+ dooropentimes++;
+ return this->timeGotoNextFloor * (maxfloor - this->atfloor + fabs(maxfloor - floor)) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ }
+ //down cases, the same
+ if(this->dir == DOWN && d == DOWN && atfloor <= floor){
+ for(int i = atfloor; i >= 1; i--)
+ if(father->buttons[i].Get(DOWN) || this->floorbutton.isPressed(i)){
+ minfloor = i;
+ dooropentimes++;
+ }
+ for(int i = minfloor; i <= FloorNumber; i++)
+ //use && to avoid recount dooropentimes
+ if(father->buttons[i].Get(UP) || (this->floorbutton.isPressed(i) && i > atfloor)){
+ maxfloor = i;
+ dooropentimes++;
+ }
+ //only one of the two following cases will be executed
+ for(int i = maxfloor; i > floor; i--)
+ if(father->buttons[i].Get(DOWN))
+ dooropentimes++;
+ for(int i = maxfloor; i < floor; i++)
+ if(father->buttons[i].Get(UP))
+ dooropentimes++;
+ return this->timeGotoNextFloor * (maxfloor - this->atfloor + maxfloor - minfloor + fabs(floor - minfloor)) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ }
+ if(this->dir == DOWN && d == DOWN && this->atfloor > floor){
+ for(int i = this->atfloor; i >= floor; i--)
+ if(this->father->buttons[i].Get(DOWN) || this->floorbutton.isPressed(i))
+ dooropentimes++;
+ return this->timeGotoNextFloor * fabs(floor - this->atfloor) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ }
+ if(this->dir == DOWN && d == UP){
+ for(int i = this->atfloor; i >= 1; i--)
+ if(this->father->buttons[i].Get(DOWN) || this->floorbutton.isPressed(i)){
+ minfloor = i;
+ dooropentimes++;
+ }
+ for(int i = minfloor; i <= floor; i++)
+ if(this->father->buttons[i].Get(UP) || (this->floorbutton.isPressed(i) && i > atfloor))
+ dooropentimes++;
+ return this->timeGotoNextFloor * (maxfloor - this->atfloor + fabs(maxfloor - floor)) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ }
+
+ ////down to btm, up to top, and then (up or down without stop) to fetch person
+ //if(this->dir == DOWN && d == DOWN && this->atfloor <= floor){
+ //for(int i = this->atfloor; i >= 1; i--)
+ //if((this->father->downassigns[i] == this->index && this->father->buttons[i].Get(DOWN)) || this->floorbutton.isPressed(i)){
+ //minfloor = i;
+ //dooropentimes++;
+ //}
+ //for(int i = minfloor; i <= FloorNumber; i++)
+ //if((this->father->upassigns[i] == this->index && this->father->buttons[i].Get(UP)) || this->floorbutton.isPressed(i)){
+ //maxfloor = i;
+ //dooropentimes++;
+ //}
+ //return this->timeGotoNextFloor * (this->atfloor - minfloor + maxfloor - minfloor + fabs(maxfloor - floor)) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+
+ //}
+ ////down and fetch, or down to bottom and up again without stop to fetch
+ //if(this->dir == DOWN && d == DOWN && this->atfloor > floor){
+ //for(int i = this->atfloor; i >= floor; i--)
+ //if((this->father->downassigns[i] == this->index && this->father->buttons[i].Get(DOWN)) || this->floorbutton.isPressed(i))
+ //dooropentimes++;
+ //return this->timeGotoNextFloor * (this->atfloor - floor) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ //}
+ ////down to btm and up(or still down but without stop) to fetch person
+ //if(this->dir == DOWN && d == UP){
+ //for(int i = this->atfloor; i >= 1; i--)
+ //if((this->father->downassigns[i] == this->index && this->father->buttons[i].Get(DOWN)) || this->floorbutton.isPressed(i)){
+ //minfloor = i;
+ //dooropentimes++;
+ //}
+ //for(int i = minfloor; i <= floor; i++)
+ //if((this->father->upassigns[i] == this->index && this->father->buttons[i].Get(UP)) || this->floorbutton.isPressed(i))
+ //dooropentimes++;
+ //return this->timeGotoNextFloor * (this->atfloor - minfloor + fabs(floor - minfloor)) + (timeDoorOpen + timeDoorKeepOpen + timeDoorClose) * dooropentimes;
+ //}
+ //This shouldn't be reached
+ Panic("error when evaluating");
+ return Inf;
+}
+void Elevator::PressFloorButton(int floor)
+{
+ this->floorbutton.Press(floor);
+ //this->Activate();
+}
+//also a func with recursive call, the func means things happened when
+//elev door is opened, person get off and get on ONE BY ONE
+//LOW TIME PERFORMANCE WARNING!
+void Elevator::DoorOpened()
+{
+ this->isdooropened = true;
+ Person* p;
+ EventCase e;
+ //dump persons
+ //judge first to increase some time performance
+ if(this->floorbutton.isPressed(atfloor)){
+ int l = personsonboard.GetLength();
+ for(int i = 1; i <= l; i++){
+ personsonboard.GetElem(i, p);
+ if(p->gotofloor == atfloor){
+ this->personnum--;
+ p->timegetoff = father->eventlist->GetTime();
+ e = EventCase(PersonGetOffTime, "Person", "GetOff", p);
+ father->eventlist->EnqEvent(e);
+ e = EventCase(PersonGetOffTime, "Elevator", "DoorOpened", this);
+ father->eventlist->EnqEvent(e);
+ //note that the delete caused length to change, but then
+ //the func returns, so no bug
+ personsonboard.ListDelete(i, p);
+ //Handle one by one
+ return;
+ }
+ }
+ }
+ //clear floor button, this is executed only after all persons got off
+ this->floorbutton.Clear(atfloor);
+ //collect persons
+ //automatic stop collecting and go on when elev is full or all collected
+ int l = father->building->persons[atfloor].GetLength();
+ //first remove all unpatiently left persons
+ for(int i = l; i >= 1; i--){
+ father->building->persons[atfloor].GetElem(i, p);
+ if(p->istimedout)
+ father->building->persons[atfloor].ListDelete(i, p);
+ }
+ //re-calc length
+ l = father->building->persons[atfloor].GetLength();
+ for(int i = 1; i <= l && !this->isFull(); i++){
+ father->building->persons[atfloor].GetElem(i, p);
+ //the person has already left? And only collect people on this dir
+ if(p->dir == this->dir){
+ //if(!p->istimedout){
+ this->personnum++;
+ this->personsonboard.Append(p);
+ this->PressFloorButton(p->gotofloor);
+ p->timegeton = father->eventlist->GetTime();
+ e = EventCase(PersonGetOnTime, "Person", "GetOn", p);
+ father->eventlist->EnqEvent(e);
+ //}
+ father->building->persons[atfloor].ListDelete(i, p);
+ e = EventCase(PersonGetOnTime, "Elevator", "DoorOpened", this);
+ father->eventlist->EnqEvent(e);
+ return;
+ }
+ }
+ //Clear buttons, moved to DoorClosed to avoid clear twice
+ for(int i = 1; i <= l; i++){
+ father->building->persons[atfloor].GetElem(i, p);
+ if(!p->istimedout && p->dir == this->dir){
+ //father->buttons[atfloor].Press(this->dir);
+ father->PressButton(atfloor, this->dir);
+ //cout << father->downassigns[atfloor]<< endl;
+ //cout << "Re-pressed";cin.get();
+ break;
+ }
+ }
+ //If the func goes here without return,
+ //then all persons are satisfied and continue to move on
+ //door should now close
+ e = EventCase(timeDoorKeepOpen, "Elevator", "DoorClosed", this);
+ father->eventlist->EnqEvent(e);
+}
+//Door closed, continue moving or stay still
+void Elevator::DoorClosed()
+{
+ this->isdooropened = false;
+ //seems too simple to be right, but i think it's OK
+ //And assigns must be cleared ASAP because many judgements depend on this
+ if(this->dir == UP)
+ father->upassigns[this->atfloor] = -1;
+ if(this->dir == DOWN)
+ father->downassigns[this->atfloor] = -1;
+ Person* p = NULL;
+ int l = father->building->persons[atfloor].GetLength();
+ //Clear btn even if some not satisfied,
+ //and then re-press btn if someone left, to let elev sys to reassign a elev.
+ //Because a mere elev don't know whether all persons had got on without overload.
+ father->buttons[atfloor].Clear(this->dir);
+ for(int i = 1; i <= l; i++){
+ father->building->persons[atfloor].GetElem(i, p);
+ if(!p->istimedout && p->dir == this->dir){
+ father->PressButton(atfloor, this->dir);
+ //cout << father->downassigns[atfloor]<< endl;
+ //cout << "Re-pressed";cin.get();
+ break;
+ }
+ }
+ this->Activate();
+}
+void Elevator::ArrivedNextFloor()
+{
+ ////if door should open at the floor, then enqueue DoorOpened
+ ////if continue moving without stop, then activate and decide what to do
+ //all action moved into Activate function
+ if(this->dir == UP){
+ if(atfloor == FloorNumber)
+ Panic("the elev is flying up into sky");
+ this->atfloor++;
+ ////Just pass by without stop if full
+ //if((father->upassigns[atfloor] == index && !isFull()) || this->floorbutton.isPressed(atfloor)){
+ //EventCase e = EventCase(this->timeDoorOpen, "Elevator", "DoorOpened", this);
+ //this->father->eventlist->EnqEvent(e);
+ //return;
+ //}
+ }
+ if(this->dir == DOWN){
+ if(atfloor == 1)
+ Panic("the elev is drilling into underground");
+ this->atfloor--;
+ //if((father->downassigns[atfloor] == index && !isFull()) || this->floorbutton.isPressed(atfloor)){
+ //EventCase e = EventCase(this->timeDoorOpen, "Elevator", "DoorOpened", this);
+ //this->father->eventlist->EnqEvent(e);
+ //return;
+ //}
+
+ }
+ if(this->dir == NODIRECTION)
+ Panic("arrived at new floor when idle? some thing when wrong");
+ //cout << "ArrivedNextFloor: " << atfloor << endl;
+ this->Activate();
+}
+//This is a single elev Main Ctrl Function
+//Decide what to do next, considering all possible conditions
+//Be called frequently
+void Elevator::Activate()
+{
+ //Point: down and up assigns array is at same status with button[].Get, but
+ //we assume that an elev should do it's own work without bothering others, but when
+ //it comes that it just pass by other floor, it will also open the door if this floor need
+ //to be served, even if the floor's job is not assigned to this elev.
+
+ notify("Activate elev %d...", this->index);
+ //First, have a judge of need to up or need to down
+ bool isneedtoup = false;
+ bool isneedtodown = false;
+ for(int i = atfloor + 1; i <= FloorNumber; i++)
+ //even if an upper floor need down, then the elev still need up, *sooner or later*
+ if(father->downassigns[i] == index || father->upassigns[i] == index || floorbutton.isPressed(i)){
+ //Fatal algorithm bug killed here!! Here is a bug's corpse
+ //if((father->buttons[i].Get(UP) && father->upassigns[i] == index) || floorbutton.isPressed(i)){
+ isneedtoup = true;
+ break;
+ }
+ for(int i = 1; i <= atfloor - 1; i++)
+ if(father->upassigns[i] == index || father->downassigns[i] == index || floorbutton.isPressed(i)){
+ isneedtodown = true;
+ break;
+ }
+ //Should stop at this floor.
+ //another another bug corpse here. elev may pass a floor even if btn on this floor is pressed
+ //At this floor, first judge whether to change direction(important), then open door and start working
+ //if((father->upassigns[atfloor] == index && !(this->dir == DOWN && isneedtodown) && !isFull()) ||
+ //(father->downassigns[atfloor] == index && !(this->dir == UP && isneedtoup) && !isFull()) ||
+ if((father->buttons[atfloor].Get(UP) && !(this->dir == DOWN && isneedtodown) && !isFull()) || \
+ (father->buttons[atfloor].Get(DOWN) && !(this->dir == UP && isneedtoup) && !isFull()) || \
+ floorbutton.isPressed(atfloor)){
+ //It's time to change direction?
+ //Change dir: now up, no need to up further, on this floor no UP pressed,
+ //and DOWN MUST BE PRESSED, or means error HAD occured, because the elev SHOULDN'T HAVE GONE to this floor
+ //But, but, when executed here, downassigns (or upassigns) HAD BEEN Cleared!!
+ //if(this->dir == UP && father->downassigns[atfloor] == index && father->upassigns[atfloor] != index && !isneedtoup){
+ //if(this->dir == UP && !(father->upassigns[atfloor] == index) && !isneedtoup){
+ if(this->dir == UP && !(father->buttons[atfloor].Get(UP)) && !isneedtoup){
+ this->dir = DOWN;
+ }
+ //if(this->dir == DOWN && father->upassigns[atfloor] == index && father->downassigns[atfloor] != index && !isneedtodown){
+ //if(this->dir == DOWN && !(father->downassigns[atfloor] == index) && !isneedtodown){
+ if(this->dir == DOWN && !(father->buttons[atfloor].Get(DOWN)) && !isneedtodown){
+ this->dir = UP;
+ }
+ //start working from idle when a person precisely come to the floor the elev resting at
+ if(this->dir == NODIRECTION){
+ //if(father->upassigns[atfloor] == index)
+ if(father->buttons[atfloor].Get(UP))
+ this->dir = UP;
+ //if(father->downassigns[atfloor] == index)
+ if(father->buttons[atfloor].Get(DOWN))
+ this->dir = DOWN;
+ }
+ EventCase e = EventCase(this->timeDoorOpen, "Elevator", "DoorOpened", this);
+ this->father->eventlist->EnqEvent(e);
+ return;
+ }
+ //no work, be idle no matter was idle or busy
+ //(no need to up, no need to down. executed here means no need to open door)
+ if(!isneedtoup && !isneedtodown){
+ this->dir = NODIRECTION;
+ this->isactive = false;
+ //cout << "be idle";
+ //for(int i = 1; i <= FloorNumber; i++)
+ //cout << father->upassigns[i] << " " << father->downassigns[i] << endl;
+ //cin.get();
+ return;
+ }
+ //was moving and continue moving in old direction
+ //the most simple case
+ if(this->isactive){
+ if((this->dir == UP && isneedtoup) || (this->dir == DOWN && isneedtodown)){
+ //cout << "continu to next floooooooooooooooooooooooooor" << endl;
+ //cin.get();
+ EventCase e = EventCase(this->timeGotoNextFloor, "Elevator", "ArrivedNextFloor", this);
+ this->father->eventlist->EnqEvent(e);
+ return;
+ }
+ }
+ //was idle and should start moving
+ else{
+ if(isneedtoup){
+ //cout << "up to next floooooooooooooooooooooooooor" << endl;
+ //cin.get();
+ this->dir = UP;
+ this->isactive = true;
+ EventCase e = EventCase(this->timeGotoNextFloor, "Elevator", "ArrivedNextFloor", this);
+ this->father->eventlist->EnqEvent(e);
+ return;
+ }
+ else if(isneedtodown){
+ //cout << "down to next floooooooooooooooooooooooooor" << endl;
+ //cin.get();
+ this->dir = DOWN;
+ this->isactive = true;
+ EventCase e = EventCase(this->timeGotoNextFloor, "Elevator", "ArrivedNextFloor", this);
+ this->father->eventlist->EnqEvent(e);
+ return;
+ }
+ else
+ Panic("wrong ctrl flow in Activate");
+ }
+ Panic("Nothing done in Activate. Another wrong ctrl flow in Activate");
+}
+bool Elevator::isFull() const
+{
+ return personnum >= maxperson;
+}
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/elevator.hpp" "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/elevator.hpp"
new file mode 100755
index 0000000..2a459d2
--- /dev/null
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/elevator.hpp"
@@ -0,0 +1,153 @@
+/* elevator.hpp */
+#ifndef ELEVATOR_HPP
+#define ELEVATOR_HPP
+#include
+#include
+#include
+#include
+#include
+#include "../Lib/linklist.hpp"
+#include "../Lib/queue.hpp"
+#include "event.hpp"
+#include "person.hpp"
+using namespace std;
+const int ElevatorNumber = 3;
+const int FloorNumber = 7;
+//const int MaxPersonNumber = 1000;
+void Panic(const char*, ...);
+class Building{
+ public:
+ Building(){
+ for(int i = 1; i < FloorNumber; i++)
+ persons[i] = Linklist();
+ }
+ Linklist* GetPersons(int floor){
+ if(floor < 1 || floor > FloorNumber)
+ Panic("No such floor");
+ return persons + floor;
+ }
+ Linklist persons[FloorNumber + 1];
+};
+class Button{
+ public:
+ Button(){
+ BtnUp = false;
+ BtnDown = false;
+ }
+ bool Get(Direction d) const{
+ if(d == UP)
+ return BtnUp;
+ else if(d == DOWN)
+ return BtnDown;
+ else{
+ Panic("No such direction");
+ return false;
+ }
+ }
+ void Press(Direction d){
+ if(d == UP)
+ BtnUp = true;
+ else if(d == DOWN)
+ BtnDown = true;
+ else
+ Panic("No such direction");
+ }
+ void Clear(Direction d){
+ if(d == UP)
+ BtnUp = false;
+ if(d == DOWN)
+ BtnDown = false;
+ }
+ private:
+ bool BtnUp;
+ bool BtnDown;
+};
+class FloorButton{
+ public:
+ FloorButton(){
+ for(int i = 1; i <= FloorNumber; i++)
+ btns[i] = false;
+ }
+ void Press(int floor){
+ if(floor < 1 || floor > FloorNumber)
+ Panic("No such button, fatal error");
+ else
+ btns[floor] = true;
+ }
+ void Clear(int floor){
+ if(floor < 1 || floor > FloorNumber)
+ Panic("No such button, fatal error");
+ else
+ btns[floor] = false;
+ }
+ bool isPressed(int floor) const{
+ return btns[floor];
+ }
+ private:
+ bool btns[FloorNumber + 1];
+};
+const Time ElevatorGotoNextFloorTime = 50 * BaseTime;
+const Time ElevatorDoorKeepOpenTime = 40 * BaseTime;
+const Time ElevatorDoorOpenTime = 20 * BaseTime;
+const Time ElevatorDoorCloseTime = 20 * BaseTime;
+const int ElevatorMaxPerson = 3;
+const int ElevatorHomeFloor = 1;
+class Elevator;
+class ElevatorSystem;
+class Elevator{
+ public:
+ Elevator();
+ Elevator(int idx, ElevatorSystem* father);
+ void PressFloorButton(int floor);
+ //collect people, press button, then send event to close door
+ void DoorOpened();
+ //Door closed means totally closed and don't open for lated persons. Decide to sleep or continue to go
+ void DoorClosed();
+ //Dynamically decide to go to next floor
+ void ArrivedNextFloor();
+ //ElevSys call this function, Activate means to make this Elev to have a check, means to call ArrivedNextFloor if someone is waiting
+ void Activate();
+ //When elev arrived at a floor, it will judge whether to go on or stop and be idle. this func do this.
+ //bool TryDeactivate();
+ Time EvaluateTimeToFloor(int floor, Direction d) const;
+ //No Deactivate because don't enqueue new "NextFloor" event means the elev is already not active.
+ bool isFull() const;
+
+ int index;
+ ElevatorSystem* father;
+ bool isactive;
+ bool isdooropened;
+ //the variables personnum and maxperson below SHOULD BE CHANGED TO WEIGHT,
+ //an elev never how many people on it, but a weight sensor do get
+ //the total weight. let's assume one person weight one unit, and
+ //i'm lazy to change all those variables
+ int personnum;
+ int atfloor;
+ Direction dir;
+ Linklist personsonboard;
+ FloorButton floorbutton;
+ private:
+ int maxperson;
+ Time timeDoorOpen;
+ Time timeDoorKeepOpen;
+ Time timeDoorClose;
+ Time timeGotoNextFloor;
+ int homefloor;
+
+};
+class ElevatorSystem{
+ public:
+ ElevatorSystem();
+ ElevatorSystem(Building*, EventList*);
+ void PressButton(int floor, Direction d);
+ int AssignElevator(int floor, Direction d);
+
+ EventList* eventlist;
+ Building* building;
+ Elevator elevators[ElevatorNumber];
+ //All arrays with length FloorNumber+1 don't use the first element
+ Button buttons[FloorNumber + 1];
+ int upassigns[FloorNumber + 1];
+ int downassigns[FloorNumber + 1];
+};
+#endif
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/event.hpp" "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/event.hpp"
new file mode 100755
index 0000000..4da00d7
--- /dev/null
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/event.hpp"
@@ -0,0 +1,68 @@
+/* event.hpp */
+#ifndef EVENT_HPP
+#define EVENT_HPP
+#include
+#include
+#include "../Lib/queue.hpp"
+using namespace std;
+typedef double Time;
+const Time BaseTime = .1;
+class EventCase{
+ public:
+ EventCase(){
+ delaytime = -1;
+ occurtime = -1;
+ obj = "";
+ cmd = "";
+ ptr = NULL;
+ }
+ //Event will happen after delaytime, occurtime and endtime will be handled by EventList
+ EventCase(Time t, string o, string c, void* p){
+ delaytime = t;
+ occurtime = -1;
+ obj = o;
+ cmd = c;
+ ptr = p;
+ }
+ Time delaytime;
+ Time occurtime;
+ string obj;
+ string cmd;
+ void* ptr;
+};
+inline bool operator<(const EventCase& e1, const EventCase& e2){
+ return e1.occurtime < e2.occurtime ? true : false;
+}
+class EventList: public Queue {
+ public:
+ EventList(){
+ curtime = 0;
+ }
+ EventList(Time t_init){
+ curtime = t_init;
+ }
+ Status EnqEvent(EventCase& e){
+ e.occurtime = curtime + e.delaytime;
+ return this->Enqueue(e);
+ }
+ Status DeqEvent(EventCase& e){
+ if(ListEmpty())
+ return ERROR;
+ this->Dequeue(e);
+ return OK;
+ }
+ Status ListEmpty(){
+ return this->QueueEmpty();
+ }
+ void FastForward(Time t)
+ {
+ this->curtime = t;
+ }
+ Time GetTime()
+ {
+ return this->curtime;
+ }
+ private:
+ Time curtime;
+};
+#endif
diff --git "a/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/main.cpp" "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/main.cpp"
new file mode 100755
index 0000000..181494c
--- /dev/null
+++ "b/\346\225\260\346\215\256\347\273\223\346\236\204/labs/2018/Elevator/main.cpp"
@@ -0,0 +1,374 @@
+/* main.cpp for Elevator Simulation Program */
+#include
+#include
+#include
+#include
+#include
+#include
+#include "../Lib/queue.hpp"
+#include "../SimpleDraw/SimpleDraw.hpp"
+#include "event.hpp"
+#include "elevator.hpp"
+#include "person.hpp"
+using namespace std;
+
+//void test_queue()
+//{
+ //Queue q;
+ //int d;
+ //q.Enqueue(1);
+ //q.Enqueue(-3);
+ //q.Enqueue(5);
+ //q.Enqueue(4);
+ //q.Enqueue(4);
+ //q.Enqueue(3);
+ //q.Enqueue(-1);
+ //Node* p;
+ //p = q.head;
+ //while((p = p->next))
+ //cout << p->data << endl;
+ //q.Dequeue(d);
+ //cout << "---" << endl;
+ //cout << d << endl;
+ //q.Dequeue(d);
+ //cout << d << endl;
+ //q.Dequeue(d);
+ //cout << d << endl;
+ //cout << "---" << endl;
+ //p = q.head;
+ //while((p = p->next))
+ //cout << p->data << endl;
+ //cout << "---" << endl;
+ //q.Enqueue(-5);
+ //q.Enqueue(15);
+ //cout << "---" << endl;
+ //p = q.head;
+ //while((p = p->next))
+ //cout << p->data << endl;
+ //cout << "---" << endl;
+ //q.Dequeue(d);
+ //cout << d << endl;
+ //q.Dequeue(d);
+ //cout << d << endl;
+ //cout << "---" << endl;
+
+//}
+/*
+graphics!
+n floors, m elevs
+1 +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+
+2 |Time: 000.0s |
+3 |==============================================|
+-1+5*1/| 5 +-----+ |
+5 / | |DOWN | |
+6 | | UP |1 | |
+7 \ |-> DOWN |@ | ->|
+8 \|===================+-----+=-------=-------====|
+-1+5*2 | 4 |
+ | |
+ | UP |
+ |-> @@@@@@ ->|
+ |===================-------=-------=-------====|
+ | 3 |
+ | |
+ | UP |
+ |-> DOWN ->|
+ |===================-------=-------=-------====|
+ | 2 +-----+ |
+ | |UP | |
+ | 9 |
+ |-> @ DOWN @@@@@ ->|
+ |===================-------=+-----+=-------====|
+-1+5*n | 1 +-----+ |
+ | |IDLE | |
+ | UP |0 | |
+ |-> DOWN | | ->|
+ |===================-------=-------=+-----+====|
+4+5*n +==============================================+
+rows = 4+5*n
+
+one floor, row start from -1+5*n
+| 5 +-----+ |
+| |DOWN | |
+| |11 | |
+|->@@@@@@@ |@@@@@| ->|
++===================+-----+=-------=-------====+
+123456789012345678901234567890123456789012345678
+ 23 1234567 1234567 9012345 7890123
+col:
+1 Wall
+2,3 ->
+4-10 @
+11-16
+
+row -1+5*n to -1+5*n+4
+col 21 to 27 elev_1
+col 21-8+8*m to 27-8+8*m
+
+21+8*m + 3, 21+8*m + 4 ->
+21+8*m + 5 Wall
+ */
+void err_notify(const char* s)
+{
+ cout << "in err main" << endl;
+ string c1 = "zenity --info --text=\"Error:";
+ string c2 = "\"";
+ cout << (c1 + string(s) + c2).c_str() << endl;
+ system((c1 + string(s) + c2).c_str());
+}
+void UpdateScreen(SimpleCanvas& cvs, const Building& building, const ElevatorSystem& es, Time t)
+{
+ int n = FloorNumber;
+ int m = ElevatorNumber;
+ int colmax = 21+8*m+5;
+ int rowmax = 4+5*n;
+ cvs.ClearCanvas();
+ cvs.AddRowLine(1, 1, colmax, '~');
+ cvs.AddRowLine(3, 1, colmax, '=');
+ cvs.AddRowLine(rowmax, 1, colmax, '=');
+ cvs.AddColLine(1, 1, rowmax, '|');
+ cvs.AddColLine(colmax, 1, rowmax, '|');
+ cvs.AddRowLine(4+5*n, 1, colmax, '=');
+ cvs.AddChar('+', 1, 1);
+ cvs.AddChar('+', 1, colmax);
+ cvs.AddChar('+', rowmax, 1);
+ cvs.AddChar('+', rowmax, colmax);
+ //Draw Time
+ cvs.AddString("Time: %.1fs", 2, 2, t);
+ for(int i = 1; i <= n; i++){
+ int thisfloor = n + 1 - i;
+ int row0 = -1+5*i;
+ //Draw floor ground
+ cvs.AddRowLine(row0+4, 2, colmax - 1, '=');
+ //Draw '->' symbol
+ cvs.AddString("->", row0+3, 2);
+ cvs.AddString("->", row0+3, colmax-2);
+ //Draw floor number
+ cvs.AddString("%d", row0, 3, thisfloor);
+ //Draw persons waiting, red color for left person
+ Node* p = building.persons[thisfloor].head;
+ int j = 0;
+ while((p = p->next) && ++j <= 7){
+ if(p->data->istimedout)
+ cvs.ChangeColor("Red");
+ else
+ cvs.ChangeColor("Green");
+ cvs.AddChar('@', row0 + 3, 11 - j);
+ cvs.ChangeColor("No");
+ }
+ //Draw UP and DOWN btn
+ if(es.buttons[thisfloor].Get(UP)){
+ cvs.ChangeColor("Yellow");
+ cvs.AddString("