├── .gitignore ├── 7zero ├── 7zero.md ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question_6.py ├── CY ├── question1.py ├── question2.py ├── question3.py └── question4.py ├── DuCCNUer ├── question02.md ├── question06.md └── readme.md ├── Godsing ├── question1.py ├── question2.py ├── question3.py ├── question4.py ├── question5.py ├── question6.py └── test_for_question3.txt ├── Jauking └── question4.py ├── Kurset ├── question5.py └── question6.py ├── Lzy ├── q_1.md ├── q_2.md ├── q_3.py ├── q_4.py └── q_5.py ├── Paranoid-kid ├── zen_of_python_01.py ├── zen_of_python_02.py ├── zen_of_python_03.py └── zen_of_python_04.py ├── README.md ├── Rouzip ├── import_this.txt ├── question1.py ├── question2.py ├── question3.py ├── question4.py ├── question5.py └── question6.py ├── Sixth.py ├── Treehl ├── question4.py └── question6.py ├── a1.php ├── captainwell └── question_4 ├── chairman └── question_1 ├── chenfeng ├── question1.md ├── question2.py ├── question3.py ├── question4.py ├── question5.py └── question6.py ├── chengjun ├── question4.py └── question5.py ├── dingshubo ├── question1.py ├── question2.py └── question4.py ├── dinjufen ├── README.md ├── question5.py └── question6.py ├── gaoxianli ├── images │ ├── question_4 │ │ ├── General_formula1.png │ │ └── General_formula2.png │ ├── question_5 │ │ ├── Domain_name_rules.png │ │ ├── No_distinction_between_agreements.png │ │ ├── Simplified_Chinese_domain_name_suffix.png │ │ ├── Transfer_Protocol.png │ │ ├── WSS_Transfer_Protocol.png │ │ ├── path_and_file.png │ │ └── relatively_path.png │ └── question_6 │ │ ├── Match_to_the_contents_of_the_comments.png │ │ ├── Multi-line_comment_indentation_problem.png │ │ ├── No_matching_blank_lines.gif │ │ ├── No_white_box_frame_live.png │ │ ├── Sneak_matched_to_the_next_line_is_not_the_beginning_of_blank_lines.png │ │ ├── The_fourth_title_of_the_code_file_statistics.png │ │ ├── The_fourth_title_source_code.png │ │ └── White_box_appears.png ├── import_this.txt ├── question_1.md ├── question_2.md ├── question_2.py ├── question_3.md ├── question_3.py ├── question_4.md ├── question_4.py ├── question_5.md ├── question_5.py ├── question_6.md └── question_6.py ├── heguilong ├── question1.py ├── question2.py ├── question3.py ├── question4.py ├── question5.py ├── question6.py └── test_question5.py ├── huangguolong ├── question3.py ├── question4.py └── resource │ └── import_this.txt ├── hxc92 ├── import_this.txt ├── question1.py ├── question2.py ├── question2_test.py ├── question3.py ├── question4.py ├── question_5.py └── question_6.py ├── jinhao ├── jinhao_q1.py ├── jinhao_q2.py ├── jinhao_q3.py ├── jinhao_q4.py ├── jinhao_q5.py └── jinhao_q6.py ├── koukekouke ├── README.md ├── question_1.py ├── question_2.py ├── question_3.py ├── question_4.py ├── question_5.py └── question_6.py ├── linkun ├── question1.md ├── question2.md ├── question3.md ├── question4.md ├── question5.md └── question6.md ├── linshizuowei ├── question_1.md ├── question_2.md ├── question_3.md ├── question_5.md └── question_6.md ├── liuzhijun ├── question5.py └── weixincrawler │ ├── crawler.py │ ├── models.py │ ├── utils.py │ └── weixin_history.html ├── loongoo └── sendcopy │ └── pywin32demo1.py ├── lumingfei ├── question1.md ├── question2.md ├── question3.md └── question4.md ├── lytl890 ├── question1.py ├── question2.py ├── question3.py ├── question4.py ├── question5.py └── question_6.py ├── maxingmin ├── question1.py ├── question2.py ├── question3.py ├── question4.py └── question5.py ├── puhuaqiang ├── question1.py ├── question2.py ├── question3.py └── question4.py ├── question_2 └── xiaoxuan ├── question_3 ├── day3_homework.py └── maxingmin.py ├── question_4 ├── Q4_CY ├── captainwell_q4 ├── dingshubo.md ├── heguilong.py ├── liumaolin.md ├── lytl890 ├── maxingmin.py ├── ralph_q4.md ├── task4.md └── zen_of_python_04.py ├── ralph ├── question1.py ├── question2.py ├── question3.py ├── question4.py ├── question5.py └── question6.py ├── rui ├── question2.py ├── question3.py ├── question4.py └── question5 ├── shuaidi ├── question01.py └── question02.py ├── suixinlu ├── __init__.py ├── question1.py ├── question3.py └── question4.py ├── sunshiqi ├── question1.md ├── question2.py ├── question3.py └── question4.py ├── totaljfb ├── Q1.py ├── Q2.py ├── Q3.py └── Q5.py ├── tttt.py ├── vimiix ├── question5.py └── question6.py ├── wangdemiao └── dailywork_1.py ├── xiaoxuan └── Question_4.py ├── xuehua ├── GuessNumber.md ├── question1.md ├── question4.md └── question5.md └── zhaopengfei ├── question1.md ├── question2.md ├── question3.md └── question4.md /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | *.py.swp 6 | 7 | # C extensions 8 | *.so 9 | 10 | # Distribution / packaging 11 | .Python 12 | env/ 13 | build/ 14 | develop-eggs/ 15 | dist/ 16 | downloads/ 17 | eggs/ 18 | .eggs/ 19 | lib/ 20 | lib64/ 21 | parts/ 22 | sdist/ 23 | var/ 24 | wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | 29 | # PyInstaller 30 | # Usually these files are written by a python script from a template 31 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 32 | *.manifest 33 | *.spec 34 | 35 | # Installer logs 36 | pip-log.txt 37 | pip-delete-this-directory.txt 38 | 39 | # Unit test / coverage reports 40 | htmlcov/ 41 | .tox/ 42 | .coverage 43 | .coverage.* 44 | .cache 45 | nosetests.xml 46 | coverage.xml 47 | *.cover 48 | .hypothesis/ 49 | 50 | # Translations 51 | *.mo 52 | *.pot 53 | 54 | # Django stuff: 55 | *.log 56 | local_settings.py 57 | .static_storage/ 58 | .media/ 59 | 60 | # Flask stuff: 61 | instance/ 62 | .webassets-cache 63 | 64 | # Scrapy stuff: 65 | .scrapy 66 | 67 | # Sphinx documentation 68 | docs/_build/ 69 | 70 | # PyBuilder 71 | target/ 72 | 73 | # Jupyter Notebook 74 | .ipynb_checkpoints 75 | 76 | # pyenv 77 | .python-version 78 | 79 | # celery beat schedule file 80 | celerybeat-schedule 81 | 82 | # SageMath parsed files 83 | *.sage.py 84 | 85 | # dotenv 86 | .env 87 | 88 | # virtualenv 89 | .venv 90 | venv/ 91 | ENV/ 92 | 93 | # Spyder project settings 94 | .spyderproject 95 | .spyproject 96 | 97 | # Rope project settings 98 | .ropeproject 99 | 100 | # mkdocs documentation 101 | /site 102 | 103 | # mypy 104 | .mypy_cache/ 105 | 106 | .idea/ 107 | .DS_Store 108 | .vscode/ 109 | -------------------------------------------------------------------------------- /7zero/7zero.md: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /7zero/question1.py: -------------------------------------------------------------------------------- 1 | numbers = [10, 29, 30, 41] 2 | 3 | for i in list(enumerate(numbers)): 4 | print(i, end=' ') 5 | 6 | 7 | for index, value in enumerate(numbers): 8 | print(index, value) 9 | 10 | 11 | for i in range(len(numbers)): 12 | print('{},{}'.format(i, numbers[i])) 13 | -------------------------------------------------------------------------------- /7zero/question2.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | class GuessGame: 4 | def __init__(self, min_num, max_num, choice): 5 | 6 | self.max_num = max_num 7 | self.min_num = min_num 8 | self.target = random.randint(min_num, max_num) 9 | self.choice = choice 10 | 11 | def guess(self): 12 | choice = self.choice 13 | 14 | while choice > 0: 15 | choice -= 1 16 | try: 17 | num = int(input("输入幸运数字:")) 18 | except ValueError as e: 19 | print("请输入有效数字") 20 | continue 21 | 22 | if num == self.target: 23 | print("恭喜你猜中了") 24 | break 25 | elif num < self.target: 26 | print("你猜的数字小了,还有 %d 次机会" % choice) 27 | else: 28 | print("你猜的数字大了!,还有 %d 次机会" % choice) 29 | else: 30 | print('很遗憾,{} 次机会都用完了,正确答案是 {}'.format(self.choice,self.target)) 31 | 32 | 33 | if __name__ == '__main__': 34 | game = GuessGame(1, 100, 5) 35 | game.guess() 36 | -------------------------------------------------------------------------------- /7zero/question3.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | filename = 'import_this.txt' 4 | with open(filename) as f: 5 | list_str = f.read().split() 6 | data_dict = collections.Counter(list_str) 7 | new_list = (sorted(data_dict.items(), key=lambda x: x[1], reverse = True)) 8 | for i in new_list[0:5]: 9 | print(i) 10 | -------------------------------------------------------------------------------- /7zero/question4.py: -------------------------------------------------------------------------------- 1 | from itertools import islice 2 | 3 | 4 | def fib(): 5 | a, b = 0, 1 6 | while True: 7 | yield a 8 | a, b = b, a + b 9 | 10 | 11 | fib_list = list(islice(fib(), 10)) 12 | print(fib_list) 13 | -------------------------------------------------------------------------------- /7zero/question_6.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | def count_linenum(filename): 4 | total_line = 0 5 | comment_line = 0 6 | blank_line = 0 7 | with open(filename) as f: 8 | lines = f.readlines() 9 | total_line = len(lines) 10 | line_index = 0 11 | # 遍历每一行 12 | while line_index < total_line: 13 | line = lines[line_index] 14 | # 检查是否为注释 15 | if line.startswith("#"): 16 | comment_line += 1 17 | elif re.match("\s*'''", line) is not None: 18 | comment_line += 1 19 | while re.match(".*'''$", line) is None: 20 | line = lines[line_index] 21 | comment_line += 1 22 | line_index += 1 23 | # 检查是否为空行 24 | elif line == "\n": 25 | blank_line += 1 26 | line_index += 1 27 | print("在%s中:" % filename) 28 | print("代码行数:", total_line) 29 | print("注释行数:", comment_line) 30 | print("空行数: ", blank_line) 31 | 32 | 33 | if __name__ == '__main__': 34 | filename = input("please enter filename:") 35 | count_linenum(filename) 36 | -------------------------------------------------------------------------------- /CY/question1.py: -------------------------------------------------------------------------------- 1 | numbers = [10, 29, 30, 41] 2 | print(numbers) 3 | for i, val in enumerate(numbers): 4 | print("(%d, %d)" % (i, val)) 5 | 6 | -------------------------------------------------------------------------------- /CY/question2.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | theNumber = int(random.random() * 100) 4 | #print("theNumber: %d" % theNumber) 5 | 6 | playTimes = 5 7 | correctFlag = False 8 | 9 | for i in range(1, playTimes + 1): 10 | ans = int(input("Input number:")) 11 | if ans < theNumber: 12 | print("Answer will be bigger!") 13 | elif ans > theNumber: 14 | print("Answer will be smaller!") 15 | else: 16 | correctFlag = True 17 | break 18 | 19 | if correctFlag: 20 | print("Answer correct! Game end...") 21 | else: 22 | print("You played excceed %d time, gave over~" % playTimes) -------------------------------------------------------------------------------- /CY/question3.py: -------------------------------------------------------------------------------- 1 | file_object = open('import_this.txt', 'r') 2 | 3 | count_dict = {} 4 | try: 5 | while True: 6 | read_line = file_object.readline() 7 | 8 | if read_line: 9 | line = "" 10 | for c in read_line: 11 | if c.isalpha(): 12 | line += c 13 | else: 14 | line += " " 15 | 16 | strAry = line.split() 17 | for word in strAry: 18 | word = word.lower() 19 | if word in count_dict: 20 | count_dict[word] += 1 21 | else: 22 | count_dict[word] = 1 23 | #print(strAry) 24 | else: 25 | break 26 | finally: 27 | file_object.close() 28 | 29 | print(count_dict) 30 | 31 | listWord = sorted(count_dict.items(), key=lambda d: d[1], reverse=True)#用value排序 32 | 33 | topX = 5 34 | 35 | for i in range(0, 5): 36 | print("word: %s, count: %s" % (listWord[i][0], listWord[i][1]))#0 是key, 1 是value -------------------------------------------------------------------------------- /CY/question4.py: -------------------------------------------------------------------------------- 1 | def fib(): 2 | now_loop = 0 3 | the_n_1 = 1 4 | the_n_2 = 0 5 | now_number = 1 6 | 7 | if now_loop == 0: 8 | yield 0 9 | now_loop = now_loop + 1 10 | 11 | while True: 12 | yield now_number 13 | now_number = the_n_1 + the_n_2 14 | the_n_2 = the_n_1 15 | the_n_1 = now_number 16 | now_loop = now_loop + 1 17 | return 18 | 19 | def get_fib_list(run_time): 20 | g = fib() 21 | for i in range(0,run_time): 22 | print(next(g)) 23 | 24 | get_fib_list(10) 25 | -------------------------------------------------------------------------------- /DuCCNUer/question02.md: -------------------------------------------------------------------------------- 1 | ## 第2题 ## 2 | 3 | > 题目描述:系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了,则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案。 4 | 5 | ``` 6 | import random 7 | 8 | class GuessGame: 9 | def __init__(self, min_num, max_num, choice): 10 | ''' 11 | :param min_num: 最小值 12 | :param max_num: 最大值 13 | :param choice: 中奖机会 14 | ''' 15 | 16 | self.min_num = min_num 17 | self.max_num = max_num 18 | self.target = random.randint(min_num, max_num) 19 | self.choice = choice 20 | 21 | def guess(self): 22 | ''' 23 | 猜数字 24 | ''' 25 | choice = self.choice 26 | 27 | while choice > 0: 28 | choice -= 1 29 | try: 30 | num = int(input("输入幸运数字:")) 31 | except ValueError as e: 32 | print("请输入有效数字") 33 | continue 34 | 35 | if num == self.target: 36 | print("恭喜你猜中了") 37 | break 38 | elif num <= self.target: 39 | print("数字偏小,还剩 %d 次机会" % choice) 40 | else: 41 | print("数字偏大,还剩 %d 次机会" % choice) 42 | else: 43 | print("很遗憾,%d 次机会都用完了,只差一点点就猜中了,正确答案是 %d" % (self.choice, self.target)) 44 | 45 | if __name__ == '__main__': 46 | game = GuessGame(1, 100, 5) 47 | game.guess() 48 | ``` 49 | -------------------------------------------------------------------------------- /DuCCNUer/question06.md: -------------------------------------------------------------------------------- 1 | ## 第6题 ## 2 | 3 | > 题目描述:统计文件数、文件总行数、空行行数、注释行数 4 | 5 | ``` 6 | # 统计文件数、文件总行数、空行行数、注释行数(目前只能统计 Python 文件) 7 | import os 8 | 9 | class FileCounter(object): 10 | def __init__(self, path): 11 | self.whitelist = ['py', 'java'] 12 | # 文件路径 13 | self.path = path 14 | # 文件列表 15 | self.filelists = [] 16 | # 代码行数 17 | self.codelines = 0 18 | # 空行行数 19 | self.blanklines = 0 20 | # 注释行数 21 | self.commentlines = 0 22 | 23 | def get_file(self): 24 | for parent, dirnames, filenames in os.walk(self.path): 25 | for filename in filenames: 26 | ext = filename.split('.')[-1] 27 | if ext in self.whitelist: 28 | self.filelists.append(os.path.join(parent, filename)) 29 | 30 | def get_file_num(self): 31 | return len(self.filelists) 32 | 33 | def count_file(self): 34 | self.codelines = 0 35 | self.blanklines = 0 36 | self.commentlines = 0 37 | # 标记是否开始注释 38 | is_comment = False 39 | # 行数(不包括空行和注释) 40 | lines = 0 41 | for filename in self.filelists: 42 | ext = filename.split('.')[-1] 43 | with open(filename, 'r', encoding='utf-8') as f: 44 | for index, fileline in enumerate(f, start=1): 45 | fileline = fileline.strip() 46 | if ext == 'py': 47 | if not is_comment: 48 | if fileline.startswith("'''") or fileline.startswith('"""'): 49 | is_comment = True 50 | start_comment_index = index 51 | # 注释行 52 | elif fileline.startswith("#"): 53 | self.commentlines += 1 54 | # 空白行 55 | elif fileline == '' or fileline == '\n': 56 | self.blanklines += 1 57 | else: 58 | lines += 1 59 | else: 60 | if fileline.endswith("'''") or fileline.endswith('"""'): 61 | is_comment = False 62 | self.commentlines += index - start_comment_index + 1 63 | else: 64 | pass 65 | self.codelines = lines + self.blanklines + self.commentlines 66 | 67 | def get_codelines(self): 68 | return self.codelines 69 | 70 | def get_blanklines(self): 71 | return self.blanklines 72 | 73 | def get_commentlines(self): 74 | return self.commentlines 75 | 76 | if __name__ == "__main__": 77 | file_counter = FileCounter("D:\\aa") 78 | file_counter.get_file() 79 | print("files:%s" % file_counter.get_file_num()) 80 | file_counter.count_file() 81 | print("code_lines:%s" % file_counter.get_codelines()) 82 | print("blanks:%s" % file_counter.get_blanklines()) 83 | print("comments:%s" % file_counter.get_commentlines()) 84 | 85 | ``` 86 | 87 | **输出结果:** 88 | > files:1 89 | code_lines:47 90 | blanks:3 91 | comments:11 92 | -------------------------------------------------------------------------------- /DuCCNUer/readme.md: -------------------------------------------------------------------------------- 1 | > question06 2 | 1. 完成对 Python文件的统计 3 | 2. 待完成...... 4 | -------------------------------------------------------------------------------- /Godsing/question1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | numbers = [10, 29, 30, 41] 4 | 5 | # use enumerate to get the answer 6 | print(list(enumerate(numbers))) 7 | 8 | # if the square bracket was unnecessary, then we can strip it. 9 | # send the whole list to str() regardless of the element's data type. 10 | str1 = str(list(enumerate(numbers))) 11 | print(str1.strip('[]')) 12 | -------------------------------------------------------------------------------- /Godsing/question2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: UTF-8 -*- 3 | 4 | import random 5 | 6 | true_int = random.randint(1, 100) 7 | times = 5 8 | 9 | while times > 0: 10 | times -= 1 11 | try: 12 | guess = int(input('Please input the number you guess:')) 13 | except Exception as e: 14 | print('Invalid input! You have %s chances left.' % times) 15 | continue 16 | 17 | if guess > true_int: 18 | print('Sorry, it\'s too BIG! You have %s chances left.' % times) 19 | elif guess < true_int: 20 | print('Sorry, it\'s too SMALL! You have %s chances left.' % times) 21 | else: 22 | print('Bingo! You got the right answer.') 23 | break 24 | else: 25 | print('Sorry, GAME OVER!\n') 26 | print('The true answer is: %s' % true_int) 27 | -------------------------------------------------------------------------------- /Godsing/question3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: UTF-8 -*- 3 | 4 | import re 5 | import collections 6 | 7 | 8 | filename = 'test_for_question3.txt' 9 | words = re.findall(r"[A-Za-z\-']+", open(filename).read().lower()) 10 | result = collections.Counter(words).most_common(5) 11 | print(result) 12 | -------------------------------------------------------------------------------- /Godsing/question4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: UTF-8 -*- 3 | 4 | 5 | def gen_fibonacci(n=10): 6 | if n == 1: 7 | print([0]) 8 | elif n == 2: 9 | print([0, 1]) 10 | else: 11 | i = 2 12 | lis = [0, 1] 13 | while i < n: 14 | lis.append(lis[-1] + lis[-2]) 15 | i += 1 16 | print(lis) 17 | 18 | 19 | try: 20 | num = int(input('Please input the number of objects you want to generate:')) 21 | except Exception as e: 22 | print('Invalid input! Out first 10 objects by default.') 23 | exit(1) 24 | else: 25 | if num <= 0: 26 | print("Must be greater than 0.") 27 | else: 28 | gen_fibonacci(num) 29 | -------------------------------------------------------------------------------- /Godsing/question5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: UTF-8 -*- 3 | 4 | import re 5 | 6 | 7 | class URL: 8 | def __init__(self, schema, netloc, path, query_params, fragment): 9 | self.schema = schema 10 | self.netloc = netloc 11 | self.path = path 12 | self.params = query_params 13 | self.fragment = fragment 14 | 15 | # print时要转成str 16 | def __str__(self): 17 | return "scheme='{}', netloc='{}', path='{}', query_params={}, fragment='{}'".format( 18 | self.schema, self.netloc, self.path, self.params, self.fragment) 19 | 20 | 21 | def url_parse(url): 22 | match_obj = re.match(r'(\w+)://([^/\s]+)([^\s?#&]+)?(\?([^#\s]+))?(#(.+))?', url) 23 | schema = match_obj.group(1) 24 | netloc = match_obj.group(2) 25 | path = match_obj.group(3) 26 | fragment = match_obj.group(7) 27 | query_params = {} 28 | params = match_obj.group(5) 29 | if params: 30 | for query in params.split('&'): 31 | q = query.split('=', maxsplit=1) 32 | query_params[q[0]] = q[1] 33 | return URL(schema, netloc, path, query_params, fragment) 34 | 35 | 36 | if __name__ == "__main__": 37 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 38 | parsed_url = url_parse(url) 39 | print(parsed_url) 40 | 41 | -------------------------------------------------------------------------------- /Godsing/question6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | # -*- coding: UTF-8 -*- 3 | 4 | import os 5 | import sys 6 | 7 | 8 | param_dict = { 9 | "Python": 'py', 10 | "Java": 'java', 11 | "JS": 'js', 12 | "C": ["c", "h"] 13 | } 14 | 15 | filetype = { 16 | 'py': [r"^\s*#", r'^\s*"""', r'"""\r?\n'], 17 | 'java': [r"^\s*//", r"^\s*/*", r"*/\r?\n"], 18 | 'js': [r"^\s*//", r"^\s*/*", r"*/\r?\n"], 19 | 'c': [r"^\s*//", r"^\s*/*", r"*/\r?\n"], 20 | 'h': [r"^\s*//", r"^\s*/*", r"*/\r?\n"] 21 | } 22 | 23 | 24 | class Stats: 25 | def __init__(self, basedir=os.getcwd(), file_type="auto"): 26 | self.basedir = basedir 27 | self.file_type = file_type 28 | self.type_list = [] 29 | self.file_num = 0 30 | self.code_line_num = 0 31 | self.comment_num = 0 32 | self.blank_num = 0 33 | self.flag = 0 34 | 35 | def calc(self): 36 | if self.file_type == "auto": 37 | self.type_list = filetype.keys() 38 | else: 39 | self.type_list = param_dict[self.file_type] 40 | 41 | for dirpath, dirnames, filenames in os.walk(self.basedir): 42 | for filename in filenames: 43 | ext = filename.split('.')[-1] 44 | if ext in self.type_list: 45 | self.file_num += 1 46 | with open(os.path.join(dirpath, filename)) as f: 47 | for line in f.readlines(): 48 | line = line.strip(' \t') 49 | line = line.replace(r'\r\n', r'\n') 50 | if self.flag and ~line.endswith(filetype[ext][2]): 51 | self.comment_num += 1 52 | self.flag = 0 53 | elif line.startswith(filetype[ext][1]): 54 | self.comment_num += 1 55 | self.flag = 1 56 | elif line == '\n': 57 | self.blank_num += 1 58 | elif line.startswith(filetype[ext][0]): 59 | self.comment_num += 1 60 | else: 61 | self.code_line_num += 1 62 | 63 | def __str__(self): 64 | return "Number of files:{}\n Number of code lines:{}\n Number of comment lines:{}\n " \ 65 | "Number of blank line{}".format(self.file_num, self.code_line_num, self.comment_num, self.blank_num) 66 | 67 | 68 | # python3 question6.py [-d directory --type project_type] 69 | if __name__ == "__main__": 70 | if len(sys.argv) == 5: 71 | counter = Stats(basedir=sys.argv[2], file_type=sys.argv[4]) 72 | elif len(sys.argv) == 3 and sys.argv[1] == "-d": 73 | counter = Stats(basedir=sys.argv[2]) 74 | elif len(sys.argv) == 3 and sys.argv[1] == "--type": 75 | counter = Stats(file_type=sys.argv[2]) 76 | else: 77 | counter = Stats() 78 | counter.calc() 79 | print(counter) 80 | -------------------------------------------------------------------------------- /Godsing/test_for_question3.txt: -------------------------------------------------------------------------------- 1 | Returns a new ChainMap built-in containing a new map followed by all of the maps in the current instance. 2 | It's 3 | If m is specified, it becomes the new map at the it's front of the list of mappings; 4 | built-in 5 | if not specified, an empty dict is used, so built-in that a call to d.new_child() is equivalent to: ChainMap({}, *d.maps). 6 | This method is used It's for creating subcontexts that can be updated without altering values in any of the parent mappings. 7 | Property returning a new built-in ChainMap containing all of it's the maps in the current instance except the first one. 8 | It's 9 | This is useful for skipping the first map in the search. Use cases are similar to those for the nonlocal keyword used in nested scopes. 10 | The use cases also parallel those for the built-in super() function. it's 11 | A reference to d.parents built-in is equivalent to: ChainMap(*d.maps[1:]). 12 | -------------------------------------------------------------------------------- /Jauking/question4.py: -------------------------------------------------------------------------------- 1 | # 张强的question_4作业 2 | # 从题目图片上看,军哥好像是希望用递归解题 3 | # 我脑筋绕不过弯,不会做。先用循环写个,递归的坐等讲解 4 | 5 | def fib(end = 10000, f0 = 0, f1 = 1): 6 | fib_list = [f0, f1] 7 | while True: 8 | if f0 + f1 > end: 9 | break 10 | fib_list.append(f0 + f1) 11 | f0, f1 = f1, f0 + f1 12 | 13 | return print(fib_list) 14 | 15 | fib(200) 16 | -------------------------------------------------------------------------------- /Kurset/question5.py: -------------------------------------------------------------------------------- 1 | class URL: 2 | def __init__(self, url): 3 | self.url = url 4 | self.scheme = '' 5 | self.netloc = '' 6 | self.path = '' 7 | self.query_params = '' 8 | self.fragment = '' 9 | 10 | self.__url_parse() 11 | 12 | def print_all_parts(self): 13 | print(self.url) 14 | print(self.scheme) 15 | print(self.netloc) 16 | print(self.path) 17 | print(self.query_params) 18 | print(self.fragment) 19 | 20 | def __url_parse(self): 21 | if (self.url.find('://') == -1): 22 | raise Exception('url not legal') 23 | 24 | # find scheme 25 | self.scheme = self.url.split('://')[0] 26 | 27 | # find netloc 28 | after_scheme_url = self.url.split('://')[1] 29 | self.netloc = after_scheme_url.split('/')[0] 30 | 31 | if (self.netloc == ''): 32 | raise Exception('url not legal') 33 | 34 | #find path 35 | _after_netloc_url = self.url.split(self.netloc)[1] 36 | self.path = _after_netloc_url.split('?')[0] 37 | 38 | #find query 39 | _query_str = '' 40 | if (self.url.find('?') != -1): 41 | _after_path_url = self.url.split('?')[1] 42 | _query_str = _after_path_url.split('#')[0] 43 | 44 | self.query_params = {} 45 | if (self.url.find('&') != -1): 46 | for _params_item in _query_str.split('&'): 47 | key = _params_item.split('=')[0] 48 | self.query_params[key] = _params_item.split('=')[1] 49 | 50 | # find fragment 51 | self.fragment = '' 52 | if (self.url.find('#') != -1): 53 | self.fragment = self.url.split('#')[1] 54 | 55 | 56 | test_url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 57 | new_url = URL(test_url) 58 | new_url.print_all_parts() 59 | -------------------------------------------------------------------------------- /Kurset/question6.py: -------------------------------------------------------------------------------- 1 | import argparse 2 | import re 3 | import os 4 | import io 5 | 6 | parser = argparse.ArgumentParser() 7 | parser.add_argument('-f', '--file', help='file name:java c python') 8 | parser.add_argument('-p', '--project', help='project path') 9 | args = parser.parse_args() 10 | 11 | 12 | class CountFile(): 13 | def __init__(self, file_path = '', file_project = ''): 14 | self.all_files = [] 15 | self.code_lines = 0 16 | self.blanks_lines = 0 17 | self.comment_lines = 0 18 | if file_path: 19 | self.__count_line_data(file_path) 20 | self.__count_comment_data(file_path) 21 | self.all_files.append(file_path) 22 | if file_project: 23 | path_dir = os.listdir(file_project) 24 | for i in path_dir: 25 | self.__count_line_data(file_project + '/' + i) 26 | self.__count_comment_data(file_project + '/' + i) 27 | self.all_files.append(i) 28 | print('文件目录:', self.all_files) 29 | print('文件注释:', self.comment_lines) 30 | print('文件空行:', self.blanks_lines) 31 | print('文件代码数:', self.code_lines) 32 | 33 | def judge_file_type(self, file_name): 34 | if '.' in file_name: 35 | return file_name.split('.')[-1] 36 | else: 37 | raise '文件未识别' 38 | 39 | def __count_line_data(self, file_name): 40 | file_type = self.judge_file_type(file_name) 41 | with io.open(file_name, encoding='utf-8') as f: 42 | while True: 43 | line = f.readline() 44 | if not line: 45 | break 46 | if line == '\n': 47 | self.blanks_lines += 1 48 | if file_type == 'py' and line.startswith('#'): 49 | #python 单行注释 50 | self.comment_lines += 1 51 | self.code_lines += 1 52 | 53 | def __count_comment_data(self, file_name): 54 | file_type = self.judge_file_type(file_name) 55 | with io.open(file_name, encoding='utf-8') as f: 56 | if file_type == 'java' or file_type == 'c': 57 | mult_comment_re = re.compile(r'/\*((?:.|\n)*?)\*/') 58 | data = f.read() 59 | for i in mult_comment_re.findall(data): 60 | nums = i.count('\n') 61 | if nums == 0: 62 | #单行注释 63 | self.comment_lines += 1 64 | else: 65 | #多行注释 66 | self.comment_lines += nums + 1 67 | if file_type == 'py': 68 | mult_comment_re = re.compile(r"'''((?:.|\n)*?)'''") 69 | data = f.read() 70 | for i in mult_comment_re.findall(data): 71 | nums = i.count('\n') 72 | #多行注释 73 | self.comment_lines += nums + 1 74 | 75 | #python3 question6.py -p demo 76 | #python3 question6.py -f question5.py 77 | CountFile(args.file, args.project) -------------------------------------------------------------------------------- /Lzy/q_1.md: -------------------------------------------------------------------------------- 1 | # _*_coding:utf-8 _*_ 2 | 3 | # author: Lzy 4 | # version: python 2.7 5 | # question: 6 | 在使用for循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少? 7 | 例如:有列表 numbers = [10, 29, 30, 41], 8 | 要求输出(0, 10),(1, 29),(2, 30),(3, 41) 9 | # 这是我的回答: 10 | 11 | numbers= [10, 29, 30, 41] 12 | for key, value in enumerate(numbers): 13 | print "(%s,%s)" %(key,value) 14 | -------------------------------------------------------------------------------- /Lzy/q_2.md: -------------------------------------------------------------------------------- 1 | # author: Lzy 2 | # version: python 2.7 3 | # question: 设计一个猜数字的游戏 4 | 系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统会提示玩家该数字是偏大 5 | 还是偏小,如果猜中了,则告诉玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知 6 | 正确答案 7 | 8 | # 这是我的回答: 9 | # _*_coding:utf-8_*_ 10 | 11 | import random 12 | 13 | def main(): 14 | correct_number= random.randint(1, 100) 15 | 16 | print u"猜数字游戏:" 17 | print u"游戏规则:请输入1-100之间的数字." 18 | print u"你有5次机会,看看你的运气如何吧!" 19 | 20 | for i in range(1, 6): 21 | print u'第 %s 次请输入你猜的数字:' %i 22 | guess_number = raw_input('->') 23 | #判断guess_number是否为数字用 isdigit() 24 | if guess_number.isdigit(): 25 | if correct_number == int(guess_number): 26 | print u"恭喜你答对了!游戏结束!" 27 | break 28 | elif correct_number < int(guess_number): 29 | print u"你猜的太大了!" 30 | else: 31 | print u"你猜的太小了!" 32 | else: 33 | print u"输入错误,请重新输入1-100之间的数字!" 34 | if i == 5 and guess_number != correct_number: 35 | print u"游戏结束,要猜的数字是:%s" % correct_number 36 | 37 | if __name__== '__main__': 38 | main() -------------------------------------------------------------------------------- /Lzy/q_3.py: -------------------------------------------------------------------------------- 1 | # _*_coding:utf-8_*_ 2 | # author: Lzy 3 | # version: python 2.7 4 | # question: 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 5 | 6 | # 这是我的回答: --------- 抄作业 7 | 8 | import re 9 | 10 | class Counter(object): 11 | def __init__(self,path): 12 | self.mapping = dict() 13 | with open(path) as f: 14 | data = f.read() 15 | words = [s.lower() for s in re.findall("\w+",data)] 16 | for word in words: 17 | #这里这个get(word,0)用的好,需要记住 18 | self.mapping[word] = self.mapping.get(word,0) + 1 19 | 20 | def most_common(self,n): 21 | #assert 的用法需要记住,以前只知道assert用来判断一个条件的真假,但知道和会用是2个概念!! 22 | assert n > 0, "n should be large than 0" 23 | return sorted(self.mapping.items(),key = lambda item: item[1],reverse=Ture)[:n] 24 | 25 | 26 | if __name__ == '__main__': 27 | most_common_5 = Counter("this.txt").most_common(5) 28 | for item in most_common_5: 29 | print item 30 | 31 | 32 | -------------------------------------------------------------------------------- /Lzy/q_4.py: -------------------------------------------------------------------------------- 1 | # _*_ coding=utf-8 _*_ 2 | # # author: Lzy 3 | # # version: python 2.7 4 | # # question: 5 | # ''' 6 | # 用Python实现斐波那契数列,费波那契数列由0和1开始, 7 | # 之后的费波那契系数就是由之前的两数相加而得出, 8 | # 例如前 斐波那契数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 9 | # ''' 10 | # # 这是我的回答: 11 | 12 | #方法1:正常处理 13 | 14 | def feibo1(n): 15 | #此处可以写成 a,b,i=0,1,0 16 | a = 0 17 | b = 1 18 | i = 0 19 | #while 处也可以用for 20 | while i < n: 21 | a, b = b, a + b 22 | i += 1 23 | return a 24 | 25 | if __name__ == '__main__': 26 | for i in range(10): 27 | print feibo1(i), 28 | 29 | #方法2:用列表 30 | def feibo2(n): 31 | list_a = [0,1] 32 | while n-2: 33 | list_a.append(list_a[-1]+list_a[-2]) 34 | n -= 1 35 | return list_a 36 | 37 | if __name__ == '__main__': 38 | print feibo2(10) 39 | 40 | #方法3:递归函数 41 | def feibo3(n): 42 | 43 | if n == 0: 44 | return 0 45 | elif n == 1: 46 | return 1 47 | else: 48 | return feibo3(n-2) + feibo3(n-1) 49 | 50 | if __name__ == '__main__': 51 | for i in range(10): 52 | print feibo3(i), 53 | 54 | #方法4:迭代---有空补上 55 | 56 | 57 | 58 | 59 | -------------------------------------------------------------------------------- /Lzy/q_5.py: -------------------------------------------------------------------------------- 1 | # _*_ coding=utf-8 _*_ 2 | # author: Lzy 3 | # version: python 2.7 4 | # question: 5 | # ''' 6 | # 一个完整的URL由5部分组成,格式为: 7 | 8 | # :///?# 9 | # 例如 10 | # 11 | # url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 12 | # 解析后得到: 13 | # scheme='http' 14 | # netloc='mp.weixin.qq.com' 15 | # path='/s' 16 | # query_params='__biz=MzA4MjEyNTA5Mw==&mid=2652566513' 17 | # fragment='wechat_redirect' 18 | # 问题:设计一个算法,将URL转换成5部分,注意,query_params 要转换成字典类型 19 | # 20 | # query_params={'__biz': 'MzA4MjEyNTA5Mw==', 'mid=2652566513'} 21 | # 可以设计一个URL的类,还有一个算法,大概的框架就是下面这样子。 22 | # 23 | # class URL: 24 | # .... 25 | # pass 26 | # 27 | # def url_parse(url): 28 | # ..... 29 | # return URL(xxx) 30 | # ''' 31 | 32 | # 这是我的回答: 33 | 34 | # 正常方式实现: 35 | 36 | import re 37 | 38 | # url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 39 | # 40 | # pattern1 = re.compile(r'(?P\w+)://(?P.+)/(?P\w+)' 41 | # r'\?(?P.+)#(?P\w+)') 42 | # content1 = pattern1.match(url).groupdict() 43 | # 44 | # for key , value in content1.iteritems(): 45 | # print "%s = %s" % (key, value) 46 | # 47 | # query_params = content1['query_params'] 48 | # print query_params 49 | # 50 | # pattern2 = re.compile(r'(.+)&(.+)') 51 | # content2 = pattern2.match(query_params).groups() 52 | # ff = [] 53 | # for i in content2: 54 | # a = re.match(r'(\w+)=(.+)',i).groups() 55 | # ff.append(a) 56 | # 57 | # print dict(ff) 58 | 59 | 60 | # 类及函数方法: 61 | 62 | class Url(object): 63 | def __init__(self, url_dict): 64 | self.url_dict = url_dict 65 | for key, value in self.url_dict.iteritems(): 66 | print "%s= %s" % (key, value) 67 | 68 | def url_paise(url): 69 | pattern1 = re.compile(r'(?P\w+)://(?P.+)/(?P\w+)' 70 | r'\?(?P.+)#(?P\w+)') 71 | content1 = pattern1.match(url).groupdict() 72 | if 'path' in content1: 73 | content1['path'] = '/'+content1['path'] 74 | pattern2 = re.compile(r'(.+)&(.+)') 75 | content2 = pattern2.match(content1['query_params']).groups() 76 | temp = [] 77 | for i in content2: 78 | v = re.match(r'(\w+)=(.+)', i).groups() 79 | temp.append(v) 80 | # print dict(temp) 81 | content1['query_params'] = dict(temp) 82 | 83 | return Url(content1) 84 | 85 | if __name__=='__main__': 86 | 87 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 88 | url_paise(url) 89 | -------------------------------------------------------------------------------- /Paranoid-kid/zen_of_python_01.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | numbers = [10, 29, 30, 41] 4 | 5 | for value in numbers: 6 | print('({},{})'.format(numbers.index(value),value)) 7 | -------------------------------------------------------------------------------- /Paranoid-kid/zen_of_python_02.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | import random 4 | 5 | random_number = random.randrange(1, 100) 6 | 7 | 8 | def guess(): 9 | status = False 10 | for i in range(0, 5): 11 | print('-' * 10) 12 | print('You have {} shot(s) now'.format(5 - i)) 13 | guess_number = int(input('Input a number between 1 and 100 :')) 14 | if not isinstance(guess_number, int): 15 | print('Wrong Input!') 16 | break 17 | 18 | if random_number == guess_number: 19 | print('You Win! The number is {}.'.format(random_number)) 20 | status = True 21 | break 22 | elif guess_number < random_number: 23 | print('The number should be BIGGER !') 24 | else: 25 | print('The number should be SMALLER !') 26 | 27 | return status 28 | 29 | 30 | result = guess() 31 | 32 | if result == False: 33 | print('-' * 10) 34 | print('Sorry, you used all your chances!') 35 | else: 36 | print('-' * 10) 37 | print('Congratulation! You got the right answer!') 38 | -------------------------------------------------------------------------------- /Paranoid-kid/zen_of_python_03.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | # ----------------Ver 1.0---------------- 5 | # path = 'd:/import_this.txt' 6 | # with open(path, 'r') as text: 7 | # words = text.read().split() 8 | # result = {} 9 | # for word in words: 10 | # print('{} - {} times'.format(word, words.count(word))) 11 | # result[word] = words.count(word) 12 | # sort = sorted(result.items(), key=lambda kv: (-kv[1], kv[0])) 13 | # print(sort[0:5]) 14 | 15 | 16 | # ----------------Ver 2.0 ---------------- 17 | path = 'd:/import_this.txt' 18 | with open(path, 'r') as text: 19 | words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()] 20 | for i in words: 21 | if i == '': 22 | words.remove(i) 23 | words_index = set(words) 24 | counts_dict = {index: words.count(index) for index in words_index} 25 | sort = sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True) 26 | 27 | for word in sort: 28 | print('{} - {} times'.format(word, counts_dict[word])) 29 | print(sort[0:5]) 30 | -------------------------------------------------------------------------------- /Paranoid-kid/zen_of_python_04.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | def fib(num): 4 | n, a, b = 0, 0, 1 5 | while n < num: 6 | yield a 7 | a, b = b, a + b 8 | n = n + 1 9 | 10 | def output(num): 11 | res = [] 12 | for i in fib(num): 13 | res.append(i) 14 | print(res) 15 | 16 | output(10) -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # DailyQuestion 2 | Python之禅和他朋友们知识星球的每日一题 https://t.xiaomiquan.com/IUFmuFu 3 | 4 | ## 第6题 5 | 6 | 设计一个程序,用于统计一个项目中的代码数,包括文件个数,代码行数,注释行数,空行行数。尽量设计灵活一点可以通过输入不同参数来统计不同语言的项目 7 | 8 | 例如执行: 9 | ``` 10 | # type用于指定文件类型 11 | python counter.py --type python 12 | ``` 13 | 14 | 输出: 15 | 16 | ``` 17 | files:10 18 | code_lines:200 19 | comments:100 20 | blanks:20 21 | ``` 22 | 23 | ## 第5题: 24 | 25 | 一个完整的URL由5部分组成,格式为: 26 | 27 | ``` 28 | :///?# 29 | ``` 30 | 31 | 例如 32 | ```python 33 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 34 | ``` 35 | 解析后得到: 36 | ``` 37 | scheme='http' 38 | netloc='mp.weixin.qq.com' 39 | path='/s' 40 | query_params='__biz=MzA4MjEyNTA5Mw==&mid=2652566513' 41 | fragment='wechat_redirect' 42 | ``` 43 | 44 | 问题:设计一个算法,将URL转换成5部分,注意,query_params 要转换成字典类型 45 | 46 | ``` 47 | query_params={'__biz': 'MzA4MjEyNTA5Mw==', 'mid=2652566513'} 48 | ``` 49 | 50 | 提示:字符串在编程中是最常用的操作之一,这个题目主要是要求大家熟悉字符串的常用方法。此外,大家尽可能用抽象、面向对象的风格来写。可以设计一个URL的类,还有一个算法,大概的框架就是下面这样子。 51 | 52 | ```python 53 | class URL: 54 | .... 55 | pass 56 | 57 | def url_parse(url): 58 | ..... 59 | return URL(xxx) 60 | ``` 61 | 62 | ## 第4题: 63 | 64 | 用Python实现斐波那契数列,费波那契数列由0和1开始,之后的费波那契系数就是由之前的两数相加而得出,例如前 斐波那契数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。用数学方法可定义为如图所示: 65 | 66 | ![fib](./images/fn.png) 67 | 68 | 69 | ## 第3题: 70 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 71 | 72 | ## 第2题: 73 | 74 | 设计一个猜数字的游戏,系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了,则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案。 75 | 76 | ## 第1题: 77 | 78 | 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少,例如:有列表 numbers = [10, 29, 30, 41],要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 79 | 80 | 81 | 82 | 83 | 84 | 85 | 86 | 87 | 88 | 89 | -------------------------------------------------------------------------------- /Rouzip/import_this.txt: -------------------------------------------------------------------------------- 1 | The Zen of Python, by Tim Peters 2 | 3 | Beautiful is better than ugly. 4 | Explicit is better than implicit. 5 | Simple is better than complex. 6 | Complex is better than complicated. 7 | Flat is better than nested. 8 | Sparse is better than dense. 9 | Readability counts. 10 | Special cases aren't special enough to break the rules. 11 | Although practicality beats purity. 12 | Errors should never pass silently. 13 | Unless explicitly silenced. 14 | In the face of ambiguity, refuse the temptation to guess. 15 | There should be one-- and preferably only one --obvious way to do it. 16 | Although that way may not be obvious at first unless you're Dutch. 17 | Now is better than never. 18 | Although never is often better than *right* now. 19 | If the implementation is hard to explain, it's a bad idea. 20 | If the implementation is easy to explain, it may be a good idea. 21 | Namespaces are one honking great idea -- let's do more of those! -------------------------------------------------------------------------------- /Rouzip/question1.py: -------------------------------------------------------------------------------- 1 | # 已经给定的列表 2 | numbers = [10, 29, 30, 41] 3 | 4 | # 打印位置和shuzhi 5 | for pos_and_val in enumerate(numbers): 6 | print(pos_and_val) 7 | -------------------------------------------------------------------------------- /Rouzip/question2.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | # 选定随机答案 4 | ans = random.randint(1, 100) 5 | 6 | 7 | class OverValueException(Exception): 8 | ''' 9 | 猜测的数值超过了100 10 | ''' 11 | pass 12 | 13 | 14 | class LessValueException(Exception): 15 | ''' 16 | 猜测的数值小于1 17 | ''' 18 | pass 19 | 20 | 21 | # 所有机会 22 | chances = 5 23 | while(chances): 24 | guessAns = input("请输入猜测的数字:") 25 | try: 26 | intAns = int(guessAns, 10) 27 | if intAns > 100: 28 | raise OverValueException 29 | elif intAns < 1: 30 | raise LessValueException 31 | if intAns == ans: 32 | print("恭喜你,猜对了!") 33 | break 34 | elif intAns > ans: 35 | print("太大啦") 36 | chances -= 1 37 | else: 38 | print("太小啦") 39 | chances -= 1 40 | except OverValueException as over: 41 | print("答案在1到100呢,您猜的太大了") 42 | chances -= 1 43 | except LessValueException as less: 44 | print("答案在1到100呢,您猜的太小了") 45 | chances -= 1 46 | except Exception as ex: 47 | print("请输入数字呢") 48 | chances -= 1 49 | print("答案是" + str(ans)) 50 | -------------------------------------------------------------------------------- /Rouzip/question3.py: -------------------------------------------------------------------------------- 1 | import re 2 | import string 3 | from collections import OrderedDict, Counter 4 | 5 | with open('import_this.txt', 'r') as fp: 6 | files = fp.read() 7 | line = files.translate(str.maketrans('', '', string.punctuation)) 8 | line = re.sub('\n', ' ', line) 9 | line = re.sub(' +', ' ', line) 10 | lists = line.split() 11 | order_dict = Counter(lists).most_common(5) 12 | # 打印最频繁的五个单词 13 | print(order_dict) 14 | -------------------------------------------------------------------------------- /Rouzip/question4.py: -------------------------------------------------------------------------------- 1 | def finonacii(): 2 | a, b = 0, 1 3 | while True: 4 | yield a 5 | a, b = b, a + b 6 | 7 | # 测试 8 | if __name__ == '__main__': 9 | for i in finonacii(): 10 | print(i) 11 | if i > 50: 12 | break 13 | -------------------------------------------------------------------------------- /Rouzip/question5.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | class URL(object): 5 | ''' 6 | 将给定的URL转化为指定的五个部分 7 | ''' 8 | 9 | def __init__(self, url): 10 | self.url = url 11 | self.scheme = None 12 | self.netloc = None 13 | self.path = None 14 | self.query_params = dict() 15 | self.fragment = None 16 | 17 | def parm(self): 18 | i = self.url.find(':') 19 | if i > 0: 20 | self.scheme = self.url[:i] 21 | url = self.url[i + 3:] 22 | # 这里借鉴了urllib的写法 23 | delim = len(url) 24 | for i in '/?#': 25 | wdelim = url.find(i) 26 | if wdelim >= 0: 27 | delim = min(delim, wdelim) 28 | self.netloc = url[:delim] 29 | url = url[delim + 1:] 30 | 31 | # 重复上边的步骤 32 | # 选出虚拟目录 33 | # 如果有?或者# 34 | delim = len(url) 35 | for i in '?#': 36 | wdelim = url.find(i) 37 | if wdelim >= 0: 38 | delim = min(delim, wdelim) 39 | self.path = url[:delim] 40 | url = url[delim + 1:] 41 | 42 | # 假如没有query_params或者fragment直接结束 43 | if len(url) == 0: 44 | pass 45 | else: 46 | if '?' in url and '#' in url: 47 | all_query, self.fragment = url.split('#') 48 | all_query_list = all_query[1:].split('&') 49 | for i in all_query_list: 50 | tmp = i.split('=') 51 | self.query_params[tmp[0]] = tmp[1] 52 | elif '#' in url: 53 | self.fragment = url[1:] 54 | else: 55 | all_query_list = url[1:].split('&') 56 | for i in all_query_list: 57 | tmp = i.split('=') 58 | self.query_params[tmp[0]] = tmp[1] 59 | 60 | if __name__ == '__main__': 61 | # test = URL(r'https://www.baidu.com/s?wd=url%E5%AE%8C%E6%95%B4%E6%A0%BC%E5%BC%8F&rsv_spt=1&rsv_iqid=0x8f665dba0005246d&issp=1&f=3&rsv_bp=1&rsv_idx=2&ie=utf-8&rqlang=cn&tn=baiduhome_pg&rsv_enter=0&oq=url%25E5%25AE%258C%25E6%2595%25B4%25E6%25A0%25BC%25E5%25BC%258F&rsv_t=7bc5WCvKlg4UD6URz5dRyQ2BjEfJobDX9TbRjMMJNYB2TuaYFVxlfXfV9JCvOl0WEpM2&rsv_pq=b49c034700007345&prefixsug=url%25E5%25AE%258C%25E6%2595%25B4%25E6%25A0%25BC%25E5%25BC%258F&rsp=0') 62 | test = URL(r'https://youtube.com') 63 | test.parm() 64 | print(test.scheme, test.netloc, test.path) 65 | print(test.query_params) 66 | print(test.fragment) 67 | -------------------------------------------------------------------------------- /Sixth.py: -------------------------------------------------------------------------------- 1 | # _*_ coding:utf-8 _*_ 2 | 3 | import os 4 | 5 | ''' 6 | 第六题,设计一个程序,用于统计一个项目中的代码数, 7 | 包括文件个数,代码行数,注释行数,空行行数 8 | ''' 9 | 10 | #os.remove() 删除文件 11 | #os.rename() 重命名文件 12 | #os.walk() 生成目录树下的所有文件名 13 | #os.chdir() 改变目录 14 | #os.mkdir/makedirs 创建目录/多层目录 15 | #os.rmdir/removedirs 删除目录/多层目录 16 | #os.listdir() 列出指定目录的文件 17 | #os.getcwd() 取得当前工作目录 18 | #os.chmod() 改变目录权限 19 | #os.path.basename() 去掉目录路径,返回文件名 20 | #os.path.dirname() 去掉文件名,返回目录路径 21 | #os.path.join() 将分离的各部分组合成一个路径名 22 | #os.path.split() 返回( dirname(), basename())元组 23 | #os.path.splitext() 返回 (filename, extension) 元组 24 | #os.path.getatime\ctime\mtime 分别返回最近访问、创建、修改时间 25 | #os.path.getsize() 返回文件大小 26 | #os.path.exists() 是否存在 27 | #os.path.isabs() 是否为绝对路径 28 | #os.path.isdir() 是否为目录 29 | #os.path.isfile() 是否为文件 30 | 31 | path = '/Users/ssaw/PycharmProjects/untitled/DailyQuestion/' 32 | # 列出指定目录的文件 33 | files = os.listdir(path) 34 | # 打印files 35 | # print(files) 36 | 37 | ''' 38 | ['Fifth.py', 'First.py', 'Fourth.py', 'importthis.txt', 'Second.py', 'Third.py', '__init__.py'] 39 | ''' 40 | 41 | 42 | def count(file): 43 | # 代码行数 44 | count_total = 0 45 | # 注释行数 46 | count_explain = 0 47 | # 空行数 48 | count_blank = 0 49 | # 打开文件file,编码未utf-8 50 | line = open(file, 'r', encoding='utf-8') 51 | # readlines一次性读取所有行 52 | for li in line.readlines(): 53 | # print(li) 54 | # count_total = count_total + 1 55 | count_total += 1 56 | # 判断是否为空行 57 | if not li.split(): 58 | count_blank += 1 59 | # strip() 方法用于移除字符串头尾指定的字符(默认为空格) 60 | li.strip() 61 | # 判断起始位置是否为#开头 62 | # startswith() 方法用于检查字符串是否是以指定子字符串开头 63 | # 星球第五题也用到了 64 | if li.startswith('#'): 65 | count_explain += 1 66 | 67 | print(file) 68 | #字符串格式化 69 | print('count_blank:%d' % count_blank) 70 | print('count_explain:%d' % count_explain) 71 | print('count_total:%d' % count_total) 72 | 73 | for file in files: 74 | count(path + file) 75 | 76 | ''' 77 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Fifth.py 78 | count_blank:8 79 | count_explain:0 80 | count_total:34 81 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/First.py 82 | count_blank:4 83 | count_explain:10 84 | count_total:20 85 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Fourth.py 86 | count_blank:4 87 | count_explain:9 88 | count_total:30 89 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/importthis.txt 90 | count_blank:1 91 | count_explain:0 92 | count_total:21 93 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Second.py 94 | count_blank:8 95 | count_explain:0 96 | count_total:45 97 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Third.py 98 | count_blank:4 99 | count_explain:1 100 | count_total:38 101 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/__init__.py 102 | count_blank:0 103 | count_explain:0 104 | count_total:0 105 | 106 | Process finished with exit code 0 107 | ''' 108 | 109 | -------------------------------------------------------------------------------- /Treehl/question4.py: -------------------------------------------------------------------------------- 1 | # _*_ coding:utf-8 _*_ 2 | 3 | ''' 4 | 用Python实现斐波那契数列(Fibonacci sequence) 5 | 除第一个和第二个数外,任意一个数都可由前两个数相加得到: 6 | 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ... 7 | ''' 8 | 9 | def fib(max): 10 | #n=0, a=0, b=1 11 | n, a, b = 0, 0, 1 12 | #条件满足 n < max 就循环,n > max 就停止 13 | while n < max: 14 | print(b) 15 | #不等于a=b, b=a + b 16 | a, b = b, a + b 17 | n = n + 1 18 | return 'done' 19 | #调用函数 20 | f= fib(9) 21 | print(f) 22 | -------------------------------------------------------------------------------- /Treehl/question6.py: -------------------------------------------------------------------------------- 1 | # _*_ coding:utf-8 _*_ 2 | 3 | import os 4 | 5 | ''' 6 | 第六题,设计一个程序,用于统计一个项目中的代码数, 7 | 包括文件个数,代码行数,注释行数,空行行数 8 | ''' 9 | 10 | #os.remove() 删除文件 11 | #os.rename() 重命名文件 12 | #os.walk() 生成目录树下的所有文件名 13 | #os.chdir() 改变目录 14 | #os.mkdir/makedirs 创建目录/多层目录 15 | #os.rmdir/removedirs 删除目录/多层目录 16 | #os.listdir() 列出指定目录的文件 17 | #os.getcwd() 取得当前工作目录 18 | #os.chmod() 改变目录权限 19 | #os.path.basename() 去掉目录路径,返回文件名 20 | #os.path.dirname() 去掉文件名,返回目录路径 21 | #os.path.join() 将分离的各部分组合成一个路径名 22 | #os.path.split() 返回( dirname(), basename())元组 23 | #os.path.splitext() 返回 (filename, extension) 元组 24 | #os.path.getatime\ctime\mtime 分别返回最近访问、创建、修改时间 25 | #os.path.getsize() 返回文件大小 26 | #os.path.exists() 是否存在 27 | #os.path.isabs() 是否为绝对路径 28 | #os.path.isdir() 是否为目录 29 | #os.path.isfile() 是否为文件 30 | 31 | path = '/Users/ssaw/PycharmProjects/untitled/DailyQuestion/' 32 | # 列出指定目录的文件 33 | files = os.listdir(path) 34 | # 打印files 35 | # print(files) 36 | 37 | ''' 38 | ['Fifth.py', 'First.py', 'Fourth.py', 'importthis.txt', 'Second.py', 'Third.py', '__init__.py'] 39 | ''' 40 | 41 | 42 | def count(file): 43 | # 代码行数 44 | count_total = 0 45 | # 注释行数 46 | count_explain = 0 47 | # 空行数 48 | count_blank = 0 49 | # 打开文件file,编码未utf-8 50 | line = open(file, 'r', encoding='utf-8') 51 | # readlines一次性读取所有行 52 | for li in line.readlines(): 53 | # print(li) 54 | # count_total = count_total + 1 55 | count_total += 1 56 | # 判断是否为空行 57 | if not li.split(): 58 | count_blank += 1 59 | # strip() 方法用于移除字符串头尾指定的字符(默认为空格) 60 | li.strip() 61 | # 判断起始位置是否为#开头 62 | # startswith() 方法用于检查字符串是否是以指定子字符串开头 63 | # 星球第五题也用到了 64 | if li.startswith('#'): 65 | count_explain += 1 66 | 67 | print(file) 68 | #字符串格式化 69 | print('count_blank:%d' % count_blank) 70 | print('count_explain:%d' % count_explain) 71 | print('count_total:%d' % count_total) 72 | 73 | for file in files: 74 | count(path + file) 75 | 76 | ''' 77 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Fifth.py 78 | count_blank:8 79 | count_explain:0 80 | count_total:34 81 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/First.py 82 | count_blank:4 83 | count_explain:10 84 | count_total:20 85 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Fourth.py 86 | count_blank:4 87 | count_explain:9 88 | count_total:30 89 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/importthis.txt 90 | count_blank:1 91 | count_explain:0 92 | count_total:21 93 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Second.py 94 | count_blank:8 95 | count_explain:0 96 | count_total:45 97 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/Third.py 98 | count_blank:4 99 | count_explain:1 100 | count_total:38 101 | /Users/ssaw/PycharmProjects/untitled/DailyQuestion/__init__.py 102 | count_blank:0 103 | count_explain:0 104 | count_total:0 105 | 106 | Process finished with exit code 0 107 | ''' 108 | 109 | -------------------------------------------------------------------------------- /a1.php: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythonzhichan/DailyQuestion/267779109e2f31e42c7bf25512316bbc57f97afd/a1.php -------------------------------------------------------------------------------- /captainwell/question_4: -------------------------------------------------------------------------------- 1 | def fabonacci(fab=[]): try: n = int(input("请输入变量n:")) if n < 0: print("请输入大于等于0的整数") return except ValueError: print("请输入大于等于0的整数") return for item in range(0,n+1): if item == 0: fab.append(0) elif item == 1: fab.append(1) elif n > 1: fab.append(fab[item-1] + fab[item-2]) print("您需要的斐波那契数列为") for item in range(0,n+1): print(fab[item],end=" ")if __name__ == '__main__': fabo = [] fabonacci(fabo) 2 | -------------------------------------------------------------------------------- /chairman/question_1: -------------------------------------------------------------------------------- 1 | subscript = 0 2 | numbers = [10, 29, 30, 41] 3 | for number in numbers: 4 | print('('+str(subscript)+','+str(number)+')') 5 | subscript +=1 6 | -------------------------------------------------------------------------------- /chenfeng/question1.md: -------------------------------------------------------------------------------- 1 | #### chenfeng 2 | --- 3 | ##### date:2017-10-27 4 | ##### question:在使用`for`循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少,例如:有列表 `numbers = [10, 29, 30, 41]`,要求输出`(0, 10),(1, 29),(2, 30),(3, 41)` 5 | --- 6 | > 解题思路: 7 | 8 | 1) 主要知识点: 9 | 1. 内置函数`enumerate()`的使用,可以同时获得索引和值; 10 | 2. 字符串`join()`函数的使用. 11 | >代码实现 12 | ```python 13 | numbers = [10,29,30,41] 14 | print(",".join(str((i,number)) for (i,number) in enumerate(numbers))) 15 | ``` 16 | -------------------------------------------------------------------------------- /chenfeng/question2.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/python3 2 | #-*- coding:utf-8 -*- 3 | 4 | import random 5 | 6 | def startGame(): 7 | print("<<< 游戏开始 >>>") 8 | print("请输入1~100之间任意一个数字,一共有5次猜中的机会。") 9 | 10 | def endGame(number,isGuess=False): 11 | if isGuess: 12 | print("恭喜你,答对了,就是它:{0}".format(number)) 13 | else: 14 | print("很遗憾,机会已用完,正确答案是:{0}".format(number)) 15 | print("<<< 游戏结束 >>>") 16 | 17 | def guessNum(): 18 | number = random.randint(1,100) 19 | totalCount = 5 20 | 21 | startGame() 22 | while totalCount > 0: 23 | choiseNum = input("请输入:") 24 | 25 | if choiseNum.isdigit(): 26 | totalCount -= 1 27 | choiseNum = int(choiseNum) 28 | if choiseNum == number: 29 | endGame(number,True) 30 | break 31 | elif choiseNum > number and totalCount > 0: 32 | print("数字大了,还有{0}次机会".format(totalCount)) 33 | elif choiseNum < number and totalCount > 0: 34 | print("数字小了,还有{0}次机会".format(totalCount)) 35 | 36 | if(totalCount == 0): 37 | endGame(number) 38 | else: 39 | print("输入有误") 40 | if __name__ == '__main__': 41 | guessNum() 42 | 43 | -------------------------------------------------------------------------------- /chenfeng/question3.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/python3 2 | #-*- coding:utf-8 -*- 3 | 4 | ''' 5 | @auter:chenfeng 6 | @date:2017-11-2 7 | @remark:统计python之禅中出现频率最多的5个单词 8 | ''' 9 | 10 | import collections 11 | import re 12 | 13 | def read_file(file_source): 14 | #读取文件 15 | with open(file_source,'r') as article_file: 16 | return article_file.read() 17 | 18 | def statistic_words(file_source): 19 | result_list = re.findall('[a-z\'A-Z]+',read_file(file_source)) 20 | #print(result_list) 21 | coll_words = collections.Counter(result_list) 22 | print(coll_words.most_common(5)) 23 | 24 | if __name__ == '__main__': 25 | file_source = "import_this.txt" 26 | statistic_words(file_source) 27 | -------------------------------------------------------------------------------- /chenfeng/question4.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/python3 2 | #-*- coding:utf-8 -*- 3 | 4 | ''' 5 | @auter:chenfeng 6 | @date:2017-11-7 7 | @remark:简单实现斐波拉契数列 8 | ''' 9 | 10 | def print_fib(index): 11 | the_front, the_behind = 0, 1 12 | 13 | while the_front < index: 14 | print(the_front, end=',') 15 | the_front, the_behind = the_behind, the_front + the_behind 16 | 17 | if __name__ == '__main__': 18 | try: 19 | index_num = int(input("请输入需要打印的前n位的斐波那契数列:")) 20 | print_fib(index_num) 21 | except ValueError as e: 22 | print("输入的数字不合法") 23 | -------------------------------------------------------------------------------- /chenfeng/question5.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/python3 2 | #-*- coding:utf-8 -*- 3 | 4 | ''' 5 | @auter:chenfeng 6 | @date:2017-11-12 7 | @remark:问题:设计一个算法,将URL转换成5部分,注意,query_params 要转换成字典类型 8 | 通过字符串的常用方法实现。实际编码中也可以直接使用内置模块的urllib.parse()快速处理。 9 | ''' 10 | from collections import namedtuple 11 | class URL: 12 | def __init__(self): 13 | # 定义namedtuple url类 14 | self.URL = namedtuple('URL','scheme netloc path query_params fragment') 15 | 16 | def url_parse(self, url_str): 17 | scheme = netloc = path = fragement ='' 18 | query_params = {} 19 | 20 | #split url 格式::///?# 21 | i = url_str.find(':') 22 | if i > 0: 23 | if url_str[:i] == 'http': 24 | scheme = url_str[:i].lower() 25 | url_str = url_str[i+1:] 26 | elif not url_str[i+1:] or any(c not in '0123456789' for c in url_str[i+1:]): 27 | scheme, url_str = url_str[:i].lower(), url_str[i+1:] 28 | 29 | if url_str[:2] == '//': 30 | netloc, url_str = self.split_netloc(url_str, 2) 31 | if '?' in url_str: 32 | path, url_str = url_str.split('?', 1) 33 | if '#' in url_str: 34 | url_str, fragement = url_str.split('#', 1) 35 | if '=' not in url_str: 36 | path = url_str 37 | else: 38 | query_params = self.gen_dict_query(url_str) 39 | else: 40 | return "not a standard url pattern" 41 | 42 | #实例化namedtuple对象 43 | url = self.URL(scheme=scheme, netloc=netloc, path=path, query_params=query_params, fragment=fragement) 44 | return url 45 | 46 | def split_netloc(self, url, start=0): 47 | index_len = len(url) 48 | # 获取主机部分 49 | for c in '/?#': 50 | wdelim = url.find(c, start) 51 | if wdelim >= 0: 52 | index_len = min(index_len, wdelim) 53 | return url[start:index_len], url[index_len:] 54 | 55 | def gen_dict_query(self, url): 56 | #获取key-value键值对 57 | params_dict = {} 58 | 59 | for param in url.split('&'): 60 | if len(param.split('=',1)) > 1: 61 | key = param.split('=')[0] 62 | value = param.split('=',1)[1] 63 | params_dict[key] = value 64 | return params_dict 65 | 66 | if __name__ == '__main__': 67 | 68 | website_urls = ['https://mp.weixin.qq.com/s/-paroQtl8vtYykLbuQ7w5Q', 69 | 'http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect', 70 | 'www.google.com/search?ei=epYGWp', 71 | 'https://docs.python.org/2.7/library/urlparse.html?highlight=urlparse#module-urlparse' 72 | ] 73 | utils = URL() 74 | for url in website_urls: 75 | print(utils.url_parse(url)) 76 | 77 | #output: 78 | ''' 79 | URL(scheme='https', netloc='mp.weixin.qq.com', path='/s/-paroQtl8vtYykLbuQ7w5Q', query_params={}, fragment='') 80 | URL(scheme='http', netloc='mp.weixin.qq.com', path='/s', query_params={'__biz': 'MzA4MjEyNTA5Mw==', 'mid': '2652566513'}, fragment='wechat_redirect') 81 | not a standard url pattern 82 | URL(scheme='https', netloc='docs.python.org', path='/2.7/library/urlparse.html', query_params={'highlight': 'urlparse'}, fragment='module-urlparse') 83 | ''' 84 | -------------------------------------------------------------------------------- /chengjun/question4.py: -------------------------------------------------------------------------------- 1 | import math 2 | def fibo(index): 3 | if index >2: 4 | return fibo(index-1)+fibo(index-2) 5 | elif index ==2: 6 | return 1 7 | elif index ==1: 8 | return 0 9 | if __name__=="__main__": 10 | temp = int(input('please input a num(num>2):')) 11 | print fibo(index) 12 | -------------------------------------------------------------------------------- /chengjun/question5.py: -------------------------------------------------------------------------------- 1 | #!usr/bin/python 2 | import re 3 | class extrac_url(): 4 | def __init__(self,url): 5 | self.url = url 6 | def pater(self): 7 | url = self.url 8 | [scheme1,url_rest] = url.split('//') 9 | scheme = re.search(r'(.+)//',url).group(1) 10 | #print "scheme is %s " % scheme 11 | netloc = re.search(r'//(.+)/',url).group(1) 12 | #print "netloc is %s " % netloc 13 | path = re.search(r'(/.+)\?',url_rest).group(1) 14 | #print 'path is %s'%path 15 | #tt =re.compile(r'\?.+') 16 | query_param = re.search(r'\?(.+)#',url).group(1) 17 | query_params={} 18 | for item in re.split(r'&', query_param): 19 | #print item 20 | index = item.find('=') 21 | query_params[item[:index]] = item[index+1:] 22 | #print "query_params is %s " %query_params 23 | fragment = re.search(r'#(.+)',url).group(1) 24 | #print "fragment is %s " %self.fragment 25 | return [scheme,netloc,path,query_params,fragment] 26 | 27 | if __name__=="__main__": 28 | ttt = extrac_url("http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect").pater() 29 | print "scheme is %s " % ttt[0] 30 | print "netloc is %s " % ttt[1] 31 | print 'path is %s'%ttt[2] 32 | print 'query_params is %s'%ttt[3] 33 | print 'fragment is %s'%ttt[4] 34 | -------------------------------------------------------------------------------- /dingshubo/question1.py: -------------------------------------------------------------------------------- 1 | #_*_ coding:utf-8 _*_ 2 | number=[10,29,30,41] 3 | #遍历一个序列 4 | for i in number: 5 | print(i) 6 | #enumerate函数 7 | for i,j in enumerate(number): 8 | print (i,j) 9 | -------------------------------------------------------------------------------- /dingshubo/question2.py: -------------------------------------------------------------------------------- 1 | #_*_ coding:utf-8 _*_ 2 | 3 | #!/user/bin/python 4 | 5 | import random 6 | 7 | number_random = random.randint(1,100) 8 | 9 | 10 | 11 | for chance in range(5): #玩家有5次机会 12 | 13 | number_player=input('请输入一个1-100之间的整数:') 14 | 15 | if(number_player>number_random): 16 | 17 | print('这个数字偏大') 18 | 19 | elif (number_player ## 现在是通过Git的方式向GitHub远程仓库提现的结果 2 | ``` 3 | numbers = [10, 29, 30, 41] 4 | for i in range(len(numbers)): 5 | print("(%d, %d)" % (i,numbers[i]),end="") 6 | if i < len(numbers) - 1: 7 | print(end=",") 8 | ``` 9 | ## 但我希望可以跟简洁点 10 | ``` 11 | numbers = [10, 29, 30, 41] 12 | for i in range(len(numbers)): 13 | print("(%d, %d)" % (i,numbers[i]),end=",") 14 | print(end="\b") 15 | ``` 16 | ## 可惜输出的结果是 17 | > (0, 10),(1, 29),(2, 30),(3, 41), 18 | ### 最后一个逗号不但没删掉,反而多了一个乱码 19 | -------------------------------------------------------------------------------- /gaoxianli/question_2.md: -------------------------------------------------------------------------------- 1 | ## 源代码 2 | ``` 3 | import random 4 | print("系统已生成了一个1~100之间的整数,请输入系统生成的数字,不过您只有五次机会") 5 | print("游戏开始:\n") 6 | num = random.randint(1,100) 7 | count = 5 8 | 9 | while count: 10 | usernum = int(input("第%d次猜的数字是:" % (6 - count))) 11 | if usernum == num: 12 | print("恭喜您猜中了,答案就是",num) 13 | break 14 | elif usernum < num: 15 | if count != 1:#如果已经是最后一次机会就不用输出 16 | print("真不走运,您猜小了,请猜大点的吧:\n") 17 | else: 18 | if count != 1: 19 | print("真不走运,您猜大了,请猜小点的吧:\n") 20 | count -= 1 21 | 22 | # 评价玩家的游戏结果 23 | if count == 0: 24 | print('太倒霉了,您用光了五次机会,而且还没猜中!') 25 | elif count == 1: 26 | print("太危险了,刚好最后一次机会被您猜中了,不过也挺厉害的了!") 27 | else: 28 | print('你牛B,五次机会还没用完就猜中了!') 29 | 30 | print("游戏结束") 31 | ``` 32 | ## 需要注意的细节 33 | * 用户每次输入后,系统给用户一个提示,并能再次输入 34 | * 最多输入五次,如果提前猜对了就退出循环 35 | * 如果最后一次机会也猜错了,就不用输出 玩家下次输入的提示了 36 | * 在提示“游戏结束”前,根据剩下的机会次数,给玩家一段评价 37 | -------------------------------------------------------------------------------- /gaoxianli/question_2.py: -------------------------------------------------------------------------------- 1 | import random 2 | print("系统已生成了一个1~100之间的整数,请输入系统生成的数字,不过您只有五次机会") 3 | print("游戏开始:\n") 4 | num = random.randint(1,100) 5 | count = 5 6 | 7 | while count: 8 | usernum = int(input("第%d次猜的数字是:" % (6 - count))) 9 | if usernum == num: 10 | print("恭喜您猜中了,答案就是",num) 11 | break 12 | elif usernum < num: 13 | if count != 1:#如果已经是最后一次机会就不用输出 14 | print("真不走运,您猜小了,请猜大点的吧:\n") 15 | else: 16 | if count != 1: 17 | print("真不走运,您猜大了,请猜小点的吧:\n") 18 | count -= 1 19 | 20 | if count == 0: 21 | print('太倒霉了,您用光了五次机会,而且还没猜中!') 22 | elif count == 1: 23 | print("太危险了,刚好最后一次机会被您猜中了,不过也挺厉害的了!") 24 | else: 25 | print('你牛B,五次机会还没用完就猜中了!') 26 | 27 | print("游戏结束") 28 | -------------------------------------------------------------------------------- /gaoxianli/question_3.md: -------------------------------------------------------------------------------- 1 | ## 思路 2 | * 将所有单词转换为小写,提取所有的单词(我使用了正则)到一个列表中 3 | * 计算每个单词出现的次数(频率) 4 | * 创建一个字典,存放:{单词频率 : [单词列表]}(同一频率的单词放在同一列表,并且该列表中没有重复单词) 5 | * 将字典按频率从高到低排序 6 | * 先输出高频中的单词列表(最多五个单词,即使列表中有超过五个的同频率单词) 7 | ## 面向过程源代码 8 | ``` 9 | import re 10 | word_dict = {} 11 | with open("import_this.txt") as f: 12 | words = re.findall(r'[A-Za-z]+\'?[A-Za-z]',f.read().lower()) 13 | word_join = [] 14 | for word in words: 15 | # 单词的频率 16 | count = words.count(word) 17 | # 频率次数相同 且 单词不重复 18 | if count in word_dict and word not in word_dict[count]: 19 | word_join = word_dict[count]+[word] 20 | count_word = {count : word_join} 21 | else: 22 | # {频率 : 同频率单词列表} 23 | count_word = {count : [word]} 24 | word_dict.update(count_word) 25 | 26 | # 从大到小排序 27 | count_list = sorted(word_dict, reverse=True) 28 | # 输出个数 29 | out_num = 5 30 | # 从频率最高的开始输出 31 | for count in count_list: 32 | # 输出相同频率的单词(有些单词可能频率相同 33 | # 但由于只能输出5个,所以位置靠后单词没机会输出) 34 | for word in word_dict[count]: 35 | if out_num: 36 | print(word) 37 | out_num -=1 38 | ``` 39 | ## 半面向对象 40 | ``` 41 | import re 42 | 43 | word_dict = {} 44 | try: 45 | with open("import_this.txt") as f: 46 | words = re.findall(r'[A-Za-z]+\'?[A-Za-z]',f.read().lower()) 47 | word_join = [] 48 | for word in words: 49 | # 单词的频率 50 | count = words.count(word) 51 | # 频率次数相同 且 单词不重复 52 | if count in word_dict and word not in word_dict[count]: 53 | word_join = word_dict[count]+[word] 54 | count_word = {count : word_join} 55 | else: 56 | # {频率 : 同频率单词列表} 57 | count_word = {count : [word]} 58 | word_dict.update(count_word) 59 | except: 60 | print('出错啦') 61 | 62 | def before(out_num, rsort = False): 63 | # 从大到小排序 64 | count_list = sorted(word_dict, reverse=rsort) 65 | # 输出个数 66 | out_num = 5 67 | # 从频率最高的开始输出 68 | for count in count_list: 69 | # 输出相同频率的单词(有些单词可能频率相同 70 | # 但由于只能输出5个,所以位置靠后单词没机会输出) 71 | for word in word_dict[count]: 72 | if out_num: 73 | print(word) 74 | out_num -=1 75 | 76 | if __name__ == '__main__': 77 | before(5, True) 78 | ``` 79 | ## 进一步面向对象 80 | * 本想进一步把代码抽象化,但由于对面向对象编程还不太熟练,具体错在什么地方,如何修改都不知道 81 | ``` 82 | import re 83 | def __init__(self, filename, out_num, rsort=False): 84 | self.filename = filename 85 | self.out_num = out_num 86 | self.rsort = rsort 87 | self.word_dict = {} 88 | 89 | def organize(filename, word_dict={}): 90 | try: 91 | with open(self.filename) as f: 92 | words = re.findall(r'[A-Za-z]+\'?[A-Za-z]',f.read().lower()) 93 | word_join = [] 94 | for word in words: 95 | # 单词的频率 96 | count = words.count(word) 97 | # 频率次数相同 且 单词不重复 98 | if count in self.word_dict and word not in self.word_dict[count]: 99 | word_join = self.word_dict[count]+[word] 100 | count_word = {count : word_join} 101 | else: 102 | # {频率 : 同频率单词列表} 103 | count_word = {count : [word]} 104 | self.word_dict.update(count_word) 105 | except OSError as reason: 106 | print('出错啦:'+str(reason)) 107 | 108 | def before(out_num, rsort = False): 109 | # 从大到小排序 110 | count_list = sorted(self.word_dict, reverse=self.rsort) 111 | # 从频率最高的开始输出 112 | for count in count_list: 113 | # 输出相同频率的单词(有些单词可能频率相同 114 | # 但由于只能输出5个,所以位置靠后单词没机会输出) 115 | for word in self.word_dict[count]: 116 | if self.out_num: 117 | print(word) 118 | self.out_num -=1 119 | 120 | if __name__ == '__main__': 121 | organize("import_this.txt") 122 | before(5, True) 123 | ``` 124 | ## 遇到的问题: 125 | * 代码中的 word_join = word_dict[count]+[word],是向单词列表中添加新单词。但原先是用这种方法的: word_join = word_dict[count].append([word]),但不知道为什么老是返回 None,不知道是哪里的问题。 126 | -------------------------------------------------------------------------------- /gaoxianli/question_3.py: -------------------------------------------------------------------------------- 1 | import re 2 | word_dict = {} 3 | try: 4 | with open("import_this.txt") as f: 5 | words = re.findall(r'[A-Za-z]+\'?[A-Za-z]',f.read().lower()) 6 | word_join = [] 7 | for word in words: 8 | # 单词的频率 9 | count = words.count(word) 10 | # 频率次数相同 且 单词不重复 11 | if count in word_dict and word not in word_dict[count]: 12 | word_join = word_dict[count]+[word] 13 | count_word = {count : word_join} 14 | else: 15 | # {频率 : 同频率单词列表} 16 | count_word = {count : [word]} 17 | word_dict.update(count_word) 18 | except OSError as reason: 19 | print('出错啦:'+str(reason)) 20 | 21 | def before(out_num, rsort = False): 22 | # 从大到小排序 23 | count_list = sorted(word_dict, reverse=rsort) 24 | # 输出个数 25 | out_num = 5 26 | # 从频率最高的开始输出 27 | for count in count_list: 28 | # 输出相同频率的单词(有些单词可能频率相同 29 | # 但由于只能输出5个,所以位置靠后单词没机会输出) 30 | for word in word_dict[count]: 31 | if out_num: 32 | print(word) 33 | out_num -=1 34 | 35 | if __name__ == '__main__': 36 | before(5, True) -------------------------------------------------------------------------------- /gaoxianli/question_4.md: -------------------------------------------------------------------------------- 1 | # 斐波那契数列 2 | ### 斐波那契数列是一组数列,从 0 和 1 开始,之后(第3项开始)的每一项都等于前两项之和。 3 | 例如:斐波那契数列的前 10 个数是: 4 | > 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 5 | 6 | 在数学上,用递归的方法定义斐波纳契数列如下: 7 | > F(0)=0 8 | F(1)=1 9 | F(n)=F(n-1)+F(n-2)(n>=2,n∈N*) 10 | 11 | 也可用通项公式: 12 | 13 | ![General formula](./images/question_4/General_formula1.png) 14 | 15 | (如上,又称为“比内公式”,是用无理数表示有理数的一个范例) 16 | 17 | 注:此时![General formula](./images/question_4/General_formula2.png) 18 | 19 | ## 思路 20 | 1.用递归方法能求得任意一项的斐波那契数; 21 | 2.从第一项开始输出,直到指定项结束。 22 | 23 | ## 代码片段 24 | `fibo_num(item)` 函数是利用递归的方式求第 item 项的的斐波那契数。要输出某项斐波那契数,调用该函数即可: 25 | ``` 26 | def fibo_num(item): 27 | if item > 2: 28 | return fibo_num(item-1) + fibo_num(item-2) 29 | elif item == 2: 30 | return 1 31 | elif item == 1: 32 | return 0 33 | ``` 34 | 而 `each_item(items)` 函数里面定义了从第 1 项开始输出之后的每一项,直到第 items 项结束。 35 | ``` 36 | def each_item(items): 37 | for item in range(1,items+1): 38 | print("%d, " % fibo_num(item), end="") 39 | print("……\n") 40 | ``` 41 | 在用户输入要输出多少项斐波那契数之后,应该判断用户输入值是否符合程序要求的正整数(多少项),如果不符合要求就给出相应的提示。 42 | 所以用户不能输入比 1 小的数,也不能输入小数(输出 5.1 项是啥意思?)。 43 | 判断是否比 1 小比较简单 `items < 1` ,那判断是不是小数呢?我注意到 `type(5.1)` 返回的是 `float`,因此可以用 `type(items) == float`。 44 | ``` 45 | items = input("您要输出斐波那契数列的多少项?(正整数):") 46 | if items < 1: 47 | print("不能输入小于1的数,请您重新输入一个正整数\n") 48 | elif type(items) == float: 49 | print("不能输入小数,请您重新输入一个正整数\n") 50 | ``` 51 | 可是万万没想到程序报错。 52 | ``` 53 | F:\Python>python Fibonacci_sequence.py 54 | 您要输出斐波那契数列的多少项?(正整数):10 55 | Traceback (most recent call last): 56 | File "Fibonacci_sequence.py", line 18, in 57 | if items < 1: 58 | TypeError: '<' not supported between instances of 'str' and 'int' 59 | 60 | F:\Python> 61 | ``` 62 | 上面提示的意思是 **str** 不能与 **int** 作比较,也就是说用户以为输入的是数字,但其实是字符串。 63 | 如果把输入的转换为 **int** 类型不就可以比较了吗? 64 | ``` 65 | items = int(input("您要输出斐波那契数列的多少项?(正整数):")) 66 | if items < 1: 67 | print("不能输入小于1的数,请您重新输入一个正整数\n") 68 | elif type(items) == float: 69 | print("不能输入小数,请您重新输入一个正整数\n") 70 | ``` 71 | 可是再观察一下会发现 `type(items) == float` 永远不会成立!因为 items 被 `int()` 转化为整数。 72 | 如果把用户输入的字符串用 `float()` 转成浮点型,`type(items) == float` 又永远都成立。 73 | 后来我又注意到 `int(5.0)` 返回 `5`,而 `int(5.1)` 也返回 `5`,这样就可以根据 `int()` 转换前后的值是否相等来判断是小数还是整数。 74 | ``` 75 | >>> int(5.0) == 5 76 | True 77 | >>> int(5.1) == 5.1 78 | False 79 | ``` 80 | 返回 `True` 表示用户输入的是整数(当然也可能用户本来输入 `5.0`,这种情况也当作整数吧), 81 | 返回 `False` 表示用户输入的是小数。 82 | 83 | 为了方便用户可以不断输入,让程序不断循环,可以把修改后的代码放进 ``while True:``,直到用户按 `Ctrl + C` 快捷键才结束。代码如下: 84 | ``` 85 | try: 86 | while True: 87 | items = input("您要输出斐波那契数列的多少项?(正整数):") 88 | if items < 1: 89 | print("不能输入小于1的数,请您重新输入一个正整数\n") 90 | elif type(items) == float: 91 | print("不能输入小数,请您重新输入一个正整数\n") 92 | else: 93 | each_item(items) 94 | except KeyboardInterrupt: 95 | print('\n结束!') 96 | ``` 97 | ## Python Code 98 | ``` 99 | def fibo_num(item): 100 | if item > 2: 101 | return fibo_num(item-1) + fibo_num(item-2) 102 | elif item == 2: 103 | return 1 104 | elif item == 1: 105 | return 0 106 | 107 | def each_item(items): 108 | for item in range(1,items+1): 109 | print("%d, " % fibo_num(item), end="") 110 | print("……\n") 111 | 112 | if __name__ == "__main__": 113 | try: 114 | while True: 115 | items_float=float(input("您要输出斐波那契数列的多少项?(正整数):")) 116 | items_int = int(items_float) 117 | if items_int < 1: 118 | print("不能输入小于1的数,请您重新输入一个正整数\n") 119 | elif items_int != items_float: 120 | print("不能输入小数,请您重新输入一个正整数\n") 121 | else: 122 | each_item(items_int) 123 | except KeyboardInterrupt: 124 | print('\n结束!') 125 | ``` 126 | 执行结果如下: 127 | ``` 128 | F:\Python>python Fibonacci_sequence.py 129 | 您要输出斐波那契数列的多少项?(正整数):10 130 | 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, …… 131 | 132 | 您要输出斐波那契数列的多少项?(正整数):2 133 | 0, 1, …… 134 | 135 | 您要输出斐波那契数列的多少项?(正整数):1 136 | 0, …… 137 | 138 | 您要输出斐波那契数列的多少项?(正整数):0 139 | 不能输入小于1的数,请您重新输入一个正整数 140 | 141 | 您要输出斐波那契数列的多少项?(正整数):-1 142 | 不能输入小于1的数,请您重新输入一个正整数 143 | 144 | 您要输出斐波那契数列的多少项?(正整数):5.1 145 | 不能输入小数,请您重新输入一个正整数 146 | 147 | 您要输出斐波那契数列的多少项?(正整数): 148 | 结束! 149 | 150 | F:\Python> 151 | ``` 152 | -------------------------------------------------------------------------------- /gaoxianli/question_4.py: -------------------------------------------------------------------------------- 1 | def fibo_num(item): 2 | if item > 2: 3 | return fibo_num(item-1) + fibo_num(item-2) 4 | elif item == 2: 5 | return 1 6 | elif item == 1: 7 | return 0 8 | 9 | def each_item(items): 10 | for item in range(1,items+1): 11 | print("%d, " % fibo_num(item), end="") 12 | print("……\n") 13 | 14 | if __name__ == "__main__": 15 | try: 16 | while True: 17 | items_float=float(input("您要输出斐波那契数列的多少项?(正整数):")) 18 | items_int = int(items_float) 19 | if items_int < 1: 20 | print("不能输入小于1的数,请您重新输入一个正整数\n") 21 | elif items_int != items_float: 22 | print("不能输入小数,请您重新输入一个正整数\n") 23 | else: 24 | each_item(items_int) 25 | except KeyboardInterrupt: 26 | print('\n结束!') -------------------------------------------------------------------------------- /gaoxianli/question_5.py: -------------------------------------------------------------------------------- 1 | import re 2 | class url: 3 | def __init__(self, url_str): 4 | self.url_str=url_str 5 | 6 | def url_parse(self): 7 | # 协议 8 | m = re.search(r"([a-zA-Z]+(?=://))?", self.url_str) 9 | scheme=m.group() 10 | 11 | # 主机名 12 | m = re.search(r"(?<=//)?([a-zA-Z0-9]+-?[a-zA-Z0-9]+\.?)+\.[a-zA-Z]+(?=\/)?", self.url_str) 13 | netloc=m.group() 14 | 15 | # 路径 16 | m = re.search(r"(?<=[a-zA-Z])(\.?\/[\w\-\.\#\%\(\)\']*)+", self.url_str) 17 | path=m.group() 18 | 19 | # 查询参数 20 | query_params_key = re.findall(r"(?<=\?|\&)[\w\-]+(?=\=)", self.url_str) 21 | query_params_value = re.findall(r"(?<=\=)[\w\-\=\%]+(?=\&)?", self.url_str) 22 | query_params = {} 23 | for index in range(len(query_params_key)): 24 | query_params.update({query_params_key[index] : query_params_value[index]}) 25 | 26 | # 分段(指定id所在的位置) 27 | m = re.search(r"((?<=\#)([\w\-\/\.]*))?$", self.url_str) 28 | fragment=m.group() 29 | 30 | print("scheme:", scheme) 31 | print("netloc:", netloc) 32 | print("path:", path) 33 | print("query_params:", query_params) 34 | print("fragment:", fragment, "\n") 35 | 36 | 37 | 38 | 39 | if __name__ == "__main__": 40 | try: 41 | while True: 42 | url_str = input("解析URL:") 43 | urlapp = url(url_str) 44 | urlapp.url_parse() 45 | except KeyboardInterrupt: 46 | print("结束\n") 47 | -------------------------------------------------------------------------------- /heguilong/question1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | 3 | 4 | # answer 1 5 | numbers = [10, 29, 30, 41] 6 | for index, num in enumerate(numbers): 7 | print("({}, {})".format(index, num), end=', ') 8 | 9 | # answer 2 10 | for pair in list(enumerate(numbers)): 11 | print(pair, end=', ') 12 | -------------------------------------------------------------------------------- /heguilong/question2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/python3 2 | import random 3 | """ 4 | 系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了,则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案。 5 | """ 6 | gen_num = random.randint(1, 100) 7 | times = 5 8 | while times > 0: 9 | times -= 1 10 | print("Please input your guess number:") 11 | try: 12 | guess = int(input()) 13 | except ValueError as e: 14 | print("Please input valid number.") 15 | continue 16 | if guess > gen_num: 17 | print("Sorry, larger than generated number.") 18 | elif guess == gen_num: 19 | print("Bingo, you got it!") 20 | break 21 | else: 22 | print("Sorry, smaller than generated number") 23 | else: 24 | print("Sorry, you run out of times. Game over!") 25 | -------------------------------------------------------------------------------- /heguilong/question3.py: -------------------------------------------------------------------------------- 1 | """ 2 | File: heguilong.py 3 | Author: heguilong 4 | Email: hgleagle@gmail.com 5 | Github: https://github.com/hgleagle 6 | Description: 7 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 8 | """ 9 | import logging 10 | import sys 11 | import re 12 | from collections import Counter 13 | 14 | 15 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s \ 16 | - %(message)s') 17 | class WordCount: 18 | def __init__(self, file_name): 19 | self.file_name = file_name 20 | 21 | def count_word(self, most_num): 22 | """print most counts words 23 | 24 | :most_num: print most counts words 25 | 26 | """ 27 | with open(self.file_name, 'r') as f: 28 | data = f.read().lower() 29 | # characters and single quote not split 30 | words = re.split(r'[^\w\']+', data) 31 | logging.debug(words) 32 | most_cnts_words = Counter(words).most_common(most_num) 33 | print(most_cnts_words) 34 | 35 | 36 | if __name__ == '__main__': 37 | if len(sys.argv) != 2: 38 | print('Usage: python3 heguilong.py file_name') 39 | sys.exit() 40 | word_count = WordCount(sys.argv[1]) 41 | word_count.count_word(5) 42 | -------------------------------------------------------------------------------- /heguilong/question4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | File: heguilong.py 4 | Author: heguilong 5 | Email: hgleagle@gmail.com 6 | Github: https://github.com/hgleagle 7 | Description: 8 | 斐波那契数列由0和1开始,之后的斐波那契系数就是由之前的两数相加而得出,例如 9 | 斐波那契数列的前10个数是 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。 10 | """ 11 | import logging 12 | import sys 13 | 14 | import numpy as np 15 | 16 | 17 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s \ 18 | - %(message)s') 19 | 20 | 21 | # solution 1, O(1.618^n) 22 | class Fibonacci(): 23 | def __init__(self): 24 | """TODO: Docstring for __init__. 25 | 26 | :arg1: TODO 27 | :returns: TODO 28 | 29 | """ 30 | self.fib_dict = {} 31 | 32 | def calculate(self, number): 33 | """TODO: Docstring for calculate. 34 | 35 | :f: TODO 36 | :number: TODO 37 | :returns: TODO 38 | 39 | """ 40 | # logging.debug("number: {%d}" % number) 41 | assert number >= 0 42 | if number in (0, 1): 43 | result = number 44 | else: 45 | result = self.calculate(number - 1) + self.calculate(number - 2) 46 | if number > 0 and number not in self.fib_dict: 47 | self.fib_dict[number] = result 48 | return result 49 | 50 | def show_fib_values(self): 51 | print(self.fib_dict.values()) 52 | 53 | 54 | # solution 2, O(n) 55 | def fib_loop(n): 56 | a, b = 0, 1 57 | while n > 0: 58 | yield b 59 | a, b = b, a + b 60 | n -= 1 61 | 62 | 63 | # solution 3, O(logn) 64 | def fib_matr(n): 65 | return (np.matrix([1, 1], [1, 0]) ** (n - 1) * np.matrix([1], [0]))[0, 0] 66 | 67 | 68 | if __name__ == "__main__": 69 | if len(sys.argv) != 2: 70 | print("Usage: python3 heguilong.py number") 71 | sys.exit() 72 | number = int(sys.argv[1]) 73 | if number <= 0: 74 | print("number should be larger than 0") 75 | 76 | # solution 1 77 | print("Solution 1:") 78 | fib_obj = Fibonacci() 79 | fib_obj.calculate(number) 80 | fib_obj.show_fib_values() 81 | 82 | # solution 2 83 | print("Solution 2:") 84 | for i in fib_loop(number): 85 | print(i, end=" ") 86 | 87 | # solution 3 88 | print("Solution 3:") 89 | for n in range(number): 90 | print(fib_matr(n), end=" ") 91 | -------------------------------------------------------------------------------- /heguilong/question5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | 4 | ``` 5 | :///?# 6 | ``` 7 | 8 | 例如 9 | ```python 10 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 11 | ``` 12 | 解析后得到: 13 | ``` 14 | scheme='http' 15 | netloc='mp.weixin.qq.com' 16 | path='/s' 17 | query_params='__biz=MzA4MjEyNTA5Mw==&mid=2652566513' 18 | fragment='wechat_redirect' 19 | ``` 20 | 21 | 问题:设计一个算法,将URL转换成5部分,注意,query_params 要转换成字典类型 22 | 23 | ``` 24 | query_params={'__biz': 'MzA4MjEyNTA5Mw==', 'mid=2652566513'} 25 | ``` 26 | 27 | """ 28 | import re 29 | 30 | 31 | class URL: 32 | def __init__(self, schema, netloc, path, query_params, fragment): 33 | self.schema = schema 34 | self.netloc = netloc 35 | self.path = path 36 | self.params = query_params 37 | self.fragment = fragment 38 | 39 | def __str__(self): 40 | return "scheme='{}', netloc='{}', path='{}', query_params={}, fragment='{}'".format( 41 | self.schema, self.netloc, self.path, self.params, self.fragment) 42 | 43 | 44 | def _params_parse(params): 45 | if not params: 46 | return None 47 | pairs = [s for s in params.split('&')] 48 | param_dict = dict() 49 | for pair in pairs: 50 | k, v = pair.split('=', 1) 51 | param_dict[k] = v 52 | return param_dict 53 | 54 | 55 | # def parse_url(url): 56 | # rex = r'^(http[s]?)://([^/\s]+)([/\w\-.]+[^#?\s]*)?(\?([^#]*))?(#(.*))?$' 57 | # schema = netloc = params = fragment = path = '' 58 | 59 | # pattern = re.compile(rex) 60 | # match = pattern.match(url) 61 | # if match: 62 | # schema = match.group(1) 63 | # netloc = match.group(2) 64 | # path = match.group(3) 65 | # params = match.group(5) 66 | # fragment = match.group(7) 67 | # return URL(schema=schema, netloc=netloc, path=path, 68 | # query_params=_params_parse(params), fragment=fragment) 69 | 70 | 71 | def parse_url(url): 72 | m = re.match(r'(\w+)://([^/\s]+)([\w\-/.]+)?(\?([^#]*))?(#(.*))?', url) 73 | query_params = {} 74 | param_match = m.group(5) 75 | if param_match: 76 | for query in param_match.split('&'): 77 | q = query.split('=', maxsplit=1) 78 | query_params[q[0]] = q[1] 79 | else: 80 | query_params = None 81 | return URL( 82 | schema=m.group(1), netloc=m.group(2), path=m.group(3), 83 | query_params=query_params, fragment=m.group(7)) 84 | 85 | 86 | if __name__ == "__main__": 87 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 88 | obj = parse_url(url) 89 | print(obj) 90 | -------------------------------------------------------------------------------- /heguilong/question6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | File: question6.py 4 | Author: heguilong 5 | Email: hgleagle@gmail.com 6 | Github: https://github.com/hgleagle 7 | 8 | 今天来第六题,设计一个程序,用于统计一个项目中的代码数,包括文件个数,代码行数,注释行数,空行行数 9 | 10 | 尽量设计灵活一点可以通过输入不同参数来统计不同语言的项目 11 | 12 | 例如:python counter.py --type python 用于统计python代码,type是java就用于统计java代码 13 | 14 | 输出: 15 | 16 | files:10 17 | code_lines:200 18 | comments:100 19 | blanks:20 20 | """ 21 | import os 22 | import sys 23 | 24 | 25 | prog_lang_dict = { 26 | "python": [["py"], '#', '"""', '"""\n'], 27 | "java": [["java"], "//", "/*", "*/\n"], 28 | "C": [["c", "h"], "//", "/*", "*/\n"], 29 | "C++": [["cpp", "h"], "//", "/*", "*/\n"] 30 | } 31 | 32 | 33 | class Project(): 34 | """ 35 | count code lines in the project 36 | """ 37 | def __init__(self, cwd, prog_lang): 38 | """TODO: Docstring for __init__. 39 | 40 | :cwd: TODO 41 | :returns: TODO 42 | 43 | """ 44 | self.files = 0 45 | self.code_lines = 0 46 | self.comments = 0 47 | self.blanks = 0 48 | self.cwd = cwd 49 | self.file_types = prog_lang_dict[prog_lang][0] 50 | self.single_comment_sign = prog_lang_dict[prog_lang][1] 51 | self.multi_start_comment_sign = prog_lang_dict[prog_lang][2] 52 | self.multi_end_comment_sign = prog_lang_dict[prog_lang][3] 53 | 54 | def count(self): 55 | """count files, blanks, code_lines, comments in the project 56 | """ 57 | is_end = True 58 | self.files = self.code_lines = self.comments = self.blanks = 0 59 | for foldername, subfolders, filenames in os.walk(self.cwd): 60 | for filename in filenames: 61 | for filetype in self.file_types: 62 | if filename.endswith(filetype): 63 | self.files += 1 64 | with open(filename) as f: 65 | lines = f.readlines() 66 | for line in lines: 67 | # delete left space 68 | line = line.lstrip(' ') 69 | # converted to unix 70 | line = line.replace(r'\r\n', r'\n') 71 | if line == '\n': 72 | self.blanks += 1 73 | elif line.startswith(self.multi_start_comment_sign): 74 | self.comments += 1 75 | is_end = not is_end 76 | elif line.endswith(self.multi_end_comment_sign): 77 | self.comments += 1 78 | is_end = not is_end 79 | elif not is_end: 80 | self.comments += 1 81 | elif line.startswith(self.single_comment_sign): 82 | self.comments += 1 83 | else: 84 | self.code_lines += 1 85 | 86 | def __str__(self): 87 | return "file: %d\ncode_lines: %d\ncomments: %d\nblanks: %d" % ( 88 | self.files, self.code_lines, self.comments, self.blanks) 89 | 90 | 91 | if __name__ == "__main__": 92 | if len(sys.argv) != 3: 93 | print("Usage: python3 question6.py --type [language]") 94 | sys.exit() 95 | elif sys.argv[1] != '--type': 96 | print("should start with --") 97 | sys.exit() 98 | elif sys.argv[2] not in prog_lang_dict: 99 | print("language can be python, C, C++, java") 100 | sys.exit() 101 | 102 | project = Project(os.getcwd(), sys.argv[2]) 103 | project.count() 104 | print(project) 105 | -------------------------------------------------------------------------------- /heguilong/test_question5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | 3 | 4 | import unittest 5 | from question5 import parse_url 6 | 7 | 8 | class URLParse(unittest.TestCase): 9 | def test_with_full_url(self): 10 | url = "http://www.example.com:80/path/to/myfile.html?key1=value1&key2=value2#SomewhereInTheDocument" 11 | result = parse_url(url) 12 | self.assertEqual(result.schema, "http") 13 | self.assertEqual(result.netloc, "www.example.com:80") 14 | self.assertEqual(result.path, "/path/to/myfile.html") 15 | self.assertEqual(result.params, {"key1": "value1", "key2": "value2"}) 16 | self.assertEqual(result.fragment, "SomewhereInTheDocument") 17 | 18 | def test_with_fragment(self): 19 | url = "http://docs.python.org/2/library/string.html#format-examples" 20 | result = parse_url(url) 21 | self.assertEqual(result.schema, "http") 22 | self.assertEqual(result.netloc, "docs.python.org") 23 | self.assertEqual(result.path, "/2/library/string.html") 24 | self.assertEqual(result.params, None) 25 | self.assertEqual(result.fragment, "format-examples") 26 | 27 | def test_with_params(self): 28 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513" 29 | result = parse_url(url) 30 | self.assertEqual(result.schema, "http") 31 | self.assertEqual(result.netloc, "mp.weixin.qq.com") 32 | self.assertEqual(result.path, "/s") 33 | self.assertEqual(result.params, {"__biz": "MzA4MjEyNTA5Mw==", "mid": "2652566513"}) 34 | self.assertEqual(result.fragment, None) 35 | 36 | def test_with_path(self): 37 | url = "https://www.zhihu.com/topic/19661050/hot" 38 | result = parse_url(url) 39 | self.assertEqual(result.schema, "https") 40 | self.assertEqual(result.netloc, "www.zhihu.com") 41 | self.assertEqual(result.path, "/topic/19661050/hot") 42 | self.assertEqual(result.params, None) 43 | self.assertEqual(result.fragment, None) 44 | 45 | def test_with_only_host(self): 46 | url = "https://www.zhihu.com" 47 | result = parse_url(url) 48 | self.assertEqual(result.schema, "https") 49 | self.assertEqual(result.netloc, "www.zhihu.com") 50 | self.assertEqual(result.path, None) 51 | self.assertEqual(result.params, None) 52 | self.assertEqual(result.fragment, None) 53 | -------------------------------------------------------------------------------- /huangguolong/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | ## 第3题: 3 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 4 | 文件在DailyQuestion/huangguolong/resource/import_this.txt 5 | ''' 6 | import re 7 | from collections import Counter 8 | 9 | 10 | class MyCounter(): 11 | def __init__(self,file_path,top_num): 12 | ''' 13 | 14 | :param file_path: 文件路径 15 | :param top_num: 显示出现次数最多几个单词 16 | ''' 17 | 18 | self.file_path = file_path 19 | self.top_num = top_num 20 | 21 | def iCounter(self): 22 | ''' 23 | 24 | 列出出现次数最多的几个单词 25 | ''' 26 | try: 27 | with open(self.file_path) as f: 28 | text = f.read() 29 | words = re.findall(r'[a-zA-Z\']+',text) 30 | c= Counter(words) 31 | topData = c.most_common(self.top_num) 32 | print('出现次数最多的前{0}个单词是:'.format(self.top_num)+str(topData)) 33 | 34 | except FileNotFoundError as e: 35 | print('文件不存在') 36 | 37 | 38 | if __name__ == '__main__': 39 | mycounter = MyCounter('../huangguolong/resource/import_this.txt',5) 40 | mycounter.iCounter() 41 | 42 | -------------------------------------------------------------------------------- /huangguolong/question4.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | def fib(nums): 4 | ''' 5 | :param nums: 一个整数,相当于数列的下标 6 | :return: 返回该下标的值 7 | ''' 8 | if nums == 0 or nums == 1: 9 | return nums 10 | else: 11 | return fib(nums-2) + fib(nums-1) 12 | 13 | 14 | def createFib(n): 15 | ''' 16 | :param n: 需要展示前面n个数 17 | :return: 返回一个列表,费波那契数列 18 | ''' 19 | list1 = [] 20 | for i in range(n): 21 | 22 | list1.append(fib(i)) 23 | 24 | print(list1) 25 | 26 | #调用生成费波那契数列函数,指定展示的前面n个数 27 | createFib(20) 28 | -------------------------------------------------------------------------------- /huangguolong/resource/import_this.txt: -------------------------------------------------------------------------------- 1 | The Zen of Python, by Tim Peters 2 | 3 | Beautiful is better than ugly. 4 | Explicit is better than implicit. 5 | Simple is better than complex. 6 | Complex is better than complicated. 7 | Flat is better than nested. 8 | Sparse is better than dense. 9 | Readability counts. 10 | Special cases aren't special enough to break the rules. 11 | Although practicality beats purity. 12 | Errors should never pass silently. 13 | Unless explicitly silenced. 14 | In the face of ambiguity, refuse the temptation to guess. 15 | There should be one-- and preferably only one --obvious way to do it. 16 | Although that way may not be obvious at first unless you're Dutch. 17 | Now is better than never. 18 | Although never is often better than *right* now. 19 | If the implementation is hard to explain, it's a bad idea. 20 | If the implementation is easy to explain, it may be a good idea. 21 | Namespaces are one honking great idea -- let's do more of those! 22 | -------------------------------------------------------------------------------- /hxc92/import_this.txt: -------------------------------------------------------------------------------- 1 | The Zen of Python, by Tim Peters 2 | 3 | Beautiful is better than ugly. 4 | Explicit is better than implicit. 5 | Simple is better than complex. 6 | Complex is better than complicated. 7 | Flat is better than nested. 8 | Sparse is better than dense. 9 | Readability counts. 10 | Special cases aren't special enough to break the rules. 11 | Although practicality beats purity. 12 | Errors should never pass silently. 13 | Unless explicitly silenced. 14 | In the face of ambiguity, refuse the temptation to guess. 15 | There should be one-- and preferably only one --obvious way to do it. 16 | Although that way may not be obvious at first unless you're Dutch. 17 | Now is better than never. 18 | Although never is often better than *right* now. 19 | If the implementation is hard to explain, it's a bad idea. 20 | If the implementation is easy to explain, it may be a good idea. 21 | Namespaces are one honking great idea -- let's do more of those! -------------------------------------------------------------------------------- /hxc92/question1.py: -------------------------------------------------------------------------------- 1 | numbers = [10, 29, 30, 41] 2 | for i, j in enumerate(numbers): 3 | print(i, j) 4 | -------------------------------------------------------------------------------- /hxc92/question2.py: -------------------------------------------------------------------------------- 1 | from random import randrange 2 | 3 | 4 | class GuessGame(object): 5 | def __init__(self, min_int, max_int, times ): 6 | self.truth = randrange(min_int, max_int) 7 | self.min_int = min_int 8 | self.max_int = max_int 9 | self.times = times 10 | 11 | def guessing(self): 12 | times = self.times 13 | truth = self.truth 14 | while times: 15 | try: 16 | guess = int(input('剩余游戏次数:%s\n请输入您的答案:' % times)) 17 | except ValueError as e: 18 | print('输入的不是数字,请重新输入') 19 | continue 20 | if guess == truth: 21 | print('回答正确,游戏结束') 22 | break 23 | else: 24 | if guess > truth: 25 | print('您的结果偏大') 26 | else: 27 | print('您的结果偏小') 28 | times -= 1 29 | else: 30 | print('游戏结束,失败\n答案为%s' % truth) 31 | 32 | 33 | if __name__ == '__main__': 34 | game = GuessGame(1, 100, 5) 35 | game.guessing() 36 | 37 | -------------------------------------------------------------------------------- /hxc92/question2_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from day_2 import GuessGame 3 | 4 | 5 | class TestGuessGame(unittest.TestCase): 6 | 7 | def test_is_range_and_times_int(self): 8 | game = GuessGame(1, 100, 5) 9 | self.assertIsInstance(game.min_int, int) 10 | self.assertIsInstance(game.max_int, int) 11 | self.assertIsInstance(game.times, int) 12 | 13 | 14 | if __name__ == '__main__': 15 | unittest.main() 16 | -------------------------------------------------------------------------------- /hxc92/question3.py: -------------------------------------------------------------------------------- 1 | import nltk 2 | from nltk.corpus import stopwords 3 | import fileinput 4 | from nltk.tokenize import word_tokenize 5 | import re 6 | import collections 7 | 8 | 9 | class WordsFrequency: 10 | def __init__(self, path): 11 | self.path = path 12 | 13 | def get_text(self): 14 | with fileinput.input(files=self.path) as f: 15 | words = [] 16 | for line in f: 17 | words.append(line) 18 | return words 19 | 20 | def clean_text(self): 21 | sr = stopwords.words('english') # 包含了英语中的一些诸如is、a之类无意义的词 22 | clean_texts = list() 23 | pattern = re.compile('\W') 24 | for sentence in self.get_text(): 25 | tokens = word_tokenize(sentence) # 用word_tokenize将句子分成了单词,但是句点等符号还在 26 | for token in tokens: 27 | if token not in sr: 28 | match = re.search(pattern,token) 29 | if not match: # 去除标点符号 30 | clean_texts.append(token) 31 | return clean_texts 32 | 33 | def freq_dist(self): 34 | freq = collections.Counter(self.clean_text()) 35 | return freq 36 | 37 | def most_common(self, number): # 统计频率最高的n个 38 | return self.freq_dist().most_common(number) 39 | 40 | def nltk_method(self): 41 | clean_tokens = self.clean_text() 42 | freq = nltk.FreqDist(clean_tokens) # nltk库提供的词频统计 43 | freq.plot(30, cumulative=False) # ‘10’用于说明要统计的是词频数前10的 44 | 45 | 46 | words = WordsFrequency('import_this.txt') 47 | -------------------------------------------------------------------------------- /hxc92/question4.py: -------------------------------------------------------------------------------- 1 | class Fibo: 2 | @staticmethod 3 | def get_all(n): # 用于获取斐波那契数列前n+1个值,也可以通过列表获取任意值 4 | seq = list() 5 | for i in range(n+1): 6 | if len(seq) == 0: 7 | seq.append(0) 8 | elif len(seq) == 1: 9 | seq.append(1) 10 | else: 11 | seq.append(seq[i-1] + seq[i-2]) 12 | return seq 13 | 14 | def get_certain_rec(self, n): # 递归获取斐波那契数列第n+1个值 15 | if n == 0: 16 | return 0 17 | elif n == 1: 18 | return 1 19 | else: 20 | return self.get_certain_rec(n - 1) + self.get_certain_rec(n - 2) 21 | 22 | @staticmethod 23 | def get_certain(n): # 迭代方式 24 | fibo_0 = 0 25 | fibo_1 = 1 26 | if n == 0: 27 | return 0 28 | elif n == 1: 29 | return 1 30 | else: 31 | for i in range(2, n+1): 32 | fibo_n = fibo_0 + fibo_1 33 | fibo_0, fibo_1 = fibo_1, fibo_n 34 | return fibo_n 35 | 36 | 37 | f = Fibo() 38 | print(f.get_certain(20)) 39 | print(f.get_certain_rec(20)) 40 | print(f.get_all(20)) 41 | -------------------------------------------------------------------------------- /hxc92/question_5.py: -------------------------------------------------------------------------------- 1 | class UrlParse: 2 | def __init__(self, url): 3 | self.url = url 4 | self.colon_index = url.find(':') 5 | self.single_smash_index = self.colon_index + 3 + url[self.colon_index+3:].find('/') # +3是用于去除双斜杆影响 6 | self.question_mark_index = url.find('?') 7 | self.hash_index = url.find('#') 8 | 9 | def get_scheme(): # scheme一定是在第一个,并且以冒号结束 10 | return self.url[:self.colon_index] 11 | 12 | def get_netloc(): # 双斜杆开始,单斜杆结束 13 | return self.url[self.colon_index+3:self.single_smash_index] 14 | 15 | def get_path(): 16 | return self.url[self.single_smash_index:self.question_mark_index] # 包括单斜杆 17 | 18 | def get_query_params(): # para有时不止两个 19 | params = self.url[self.question_mark_index+1:self.hash_index] 20 | paras = params.split('&') 21 | 22 | def get_para(para): 23 | equal_index = para.find('=') 24 | return para[:equal_index], para[equal_index+1:] 25 | 26 | parameters = dict() 27 | for parameter in paras: 28 | para_name, para_value = get_para(parameter) 29 | parameters.setdefault(para_name, para_value) 30 | return parameters 31 | 32 | def get_fragment(): 33 | return self.url[self.hash_index+1:] 34 | 35 | self.scheme = get_scheme() 36 | self.netloc = get_netloc() 37 | self.path = get_path() 38 | self.query_params = get_query_params() 39 | self.fragment = get_fragment() 40 | 41 | 42 | url = UrlParse("http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect") 43 | print(url.scheme) 44 | print(url.netloc) 45 | print(url.path) 46 | print(url.query_params) 47 | print(url.fragment) 48 | -------------------------------------------------------------------------------- /hxc92/question_6.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | class Project: 5 | def __init__(self, direct, suffix, one_comment_symbol, inline_comment_symbol, long_comment_symbol): 6 | self.direct = direct 7 | self.suffix = suffix 8 | self.one_comment_symbol = one_comment_symbol 9 | self.inline_comment_symbol = inline_comment_symbol 10 | self.long_comment_symbol = long_comment_symbol 11 | self.codes, self.comments, self.blanks, self.project_files = self.project_check() 12 | 13 | @staticmethod 14 | def is_blank(line): 15 | if line == '' or line == '\n': 16 | return True 17 | else: 18 | return False 19 | 20 | def is_codes(self, line): 21 | if line == '' or line == '\n': 22 | return False 23 | if line.startswith(self.one_comment_symbol) or line.startswith(self.long_comment_symbol): 24 | return False 25 | if line == ' ' or line == '\n': 26 | return False 27 | else: 28 | return True 29 | 30 | def is_comment(self, line): 31 | beg, end, flag = False, False, False 32 | if line.startswith(self.long_comment_symbol): 33 | beg = True 34 | if line.endswith(self.long_comment_symbol): 35 | end = True 36 | if beg and end: 37 | flag = True 38 | if line == self.long_comment_symbol: 39 | flag = True 40 | if line.startswith(self.one_comment_symbol) or self.inline_comment_symbol in line: 41 | flag = True 42 | return flag 43 | 44 | def file_check(self, path, codecount=0, blankcount=0, commentcount=0): 45 | with open(path, encoding='utf-8') as f: 46 | long_comment_flag = False 47 | for line in f: 48 | line = line.strip() 49 | blank_flag = self.is_blank(line) 50 | code_flag = self.is_codes(line) 51 | comment_flag = self.is_comment(line) 52 | if long_comment_flag: # 多行注释时只需考虑注释何时结束 53 | if line == self.long_comment_symbol: 54 | long_comment_flag = False 55 | commentcount += 1 56 | else: # 非多行注释时考虑多行注释是否开始,是否是单行注释,是否是代码段,是否是空行 57 | if line == self.long_comment_symbol: 58 | long_comment_flag = True 59 | if comment_flag: 60 | commentcount += 1 61 | if code_flag: 62 | codecount += 1 63 | if blank_flag: 64 | blankcount += 1 65 | return codecount, commentcount, blankcount 66 | 67 | def project_check(self): 68 | codes = 0 69 | comments = 0 70 | blanks = 0 71 | project_files = dict() 72 | for dirpath, direc, files in os.walk(self.direct): 73 | for file in files: 74 | if self.suffix in file.split('.'): 75 | file_path = os.path.join(dirpath, file) 76 | code, comment, blank = self.file_check(file_path) 77 | codes += code 78 | comments += comment 79 | blanks += blank 80 | project_files.setdefault(file, [code, comment, blank]) # 在project中若出现同名文件则会有问题 81 | return codes, comments, blanks, project_files 82 | 83 | def file_view(self, filename): 84 | file = self.project_files[filename] 85 | print(filename + ':' + '\n' + 86 | 'code' + str(file[0]) + ' ' + 'comment' + str(file[1]) + ' ' + 'blank' + str(file[2])) 87 | 88 | 89 | class Pyproject(Project): 90 | def __init__(self, direct, suffix='py', one_comment_symbol='#', inline_comment_symbol=' # ', long_comment_symbol="'''"): 91 | super(Pyproject, self).__init__(direct, suffix, one_comment_symbol, inline_comment_symbol, long_comment_symbol) 92 | 93 | def is_codes(self, line): 94 | Project.is_codes(self, line) 95 | # super(Pyproject, self).is_codes(line) 96 | 97 | def is_comment(self, line): 98 | Project.is_comment(self, line) 99 | # super(Pyproject, self).is_comment(line) 100 | 101 | 102 | project = Project('D:\python', suffix='py', one_comment_symbol='#', inline_comment_symbol=' # ', long_comment_symbol="'''") 103 | print(project.codes, project.comments, project.blanks) 104 | project.file_view('day_6.py') 105 | -------------------------------------------------------------------------------- /jinhao/jinhao_q1.py: -------------------------------------------------------------------------------- 1 | 2 | # 每日一题的第1题: 3 | # 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少, 4 | # 例如 numbers = [10, 29, 30, 41], 5 | # 要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 6 | 7 | # Answer 1 8 | numbers = [10, 29, 30, 41] 9 | for i in range(len(numbers)): 10 | print('({0}, {1})'.format(i, numbers[i])) 11 | 12 | # Answer 2 13 | numbers = [10, 29, 30, 41] 14 | for n in numbers: 15 | print('({0}, {1})'.format(numbers.index(n), n)) 16 | -------------------------------------------------------------------------------- /jinhao/jinhao_q2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 第2题:设计一个猜数字的游戏 3 | 系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了,则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案。 4 | ''' 5 | 6 | 7 | import random 8 | 9 | low = 1 10 | high = 100 11 | times = 5 12 | 13 | #随机生成一个数字 14 | goal = random.randrange(low, high) 15 | 16 | print('数字已选好,游戏开始。你只有{0}次机会!'.format(times)) 17 | 18 | while times > 0: 19 | number = int(input('请输入你猜的数字:')) 20 | times = times - 1 21 | if number > goal: 22 | print('太大了,请重试。你还有{0}次机会!'.format(times)) 23 | elif number < goal: 24 | print('太小了,请重试。你还有{0}次机会!'.format(times)) 25 | elif number == goal: 26 | print('猜对了!我想的数字就是{0}!'.format(goal)) 27 | break 28 | -------------------------------------------------------------------------------- /jinhao/jinhao_q3.py: -------------------------------------------------------------------------------- 1 | # 每日一题 # 第3题: 2 | # 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 3 | 4 | python 3 5 | -*- coding:utf-8 -*- 6 | 7 | import re 8 | import collections 9 | 10 | class wordsCounter(object): 11 | 12 | def __init__(self, file, top): 13 | 14 | self.file = file 15 | self.top = top 16 | 17 | def count(self): 18 | 19 | with open(self.file, 'r') as f: 20 | text = f.read() 21 | 22 | words = re.findall(r'[\w\']+', text.lower()) 23 | 24 | result = collections.Counter(words) 25 | 26 | total_words = sum(result.values()) 27 | 28 | top = result.most_common(self.top) 29 | #print(top) 30 | 31 | print('The file has {0} words totally, the top {1} Words are:'.format(total_words, self.top)) 32 | for word in top: 33 | print(word[0], '-', word[1]) 34 | 35 | 36 | if __name__ == '__main__': 37 | file = 'import_this.txt' 38 | top = 5 39 | c = wordsCounter(file, top) 40 | c.count() -------------------------------------------------------------------------------- /jinhao/jinhao_q4.py: -------------------------------------------------------------------------------- 1 | # python 3 2 | # -*- Coding:utf-8 -*- 3 | 4 | class Fibo(object): 5 | def __init__(self): 6 | self.fibo_0 = 0 7 | self.fibo_1 = 1 8 | 9 | def fibo_top(self, n): 10 | ''' 11 | 获取前n个斐波那契数 12 | ''' 13 | fibo = [self.fibo_0, self.fibo_1] 14 | for i in range(2, n): 15 | # print(i) 16 | fibo.append(fibo[i-2] + fibo[i-1]) 17 | return fibo 18 | 19 | 20 | def fibo_before(self, n): 21 | ''' 22 | 获取小于数字n的所有斐波那契数 23 | ''' 24 | fibo = [self.fibo_0, self.fibo_1] 25 | i = 2 26 | while True: 27 | fibo.append(fibo[i-2] + fibo[i-1]) 28 | # print(i, fibo) 29 | if fibo[i] > n: 30 | return fibo[:-1] 31 | else: 32 | i += 1 33 | 34 | 35 | if __name__ == '__main__': 36 | f= Fibo() 37 | top_n = 20 38 | print('前{0}个斐波那契数:\n{1}'.format(top_n, f.fibo_top(top_n))) 39 | 40 | before_n = 20000 41 | print('小于数字{0}的所有斐波那契数:\n{1}'.format(before_n,f.fibo_before(before_n))) 42 | -------------------------------------------------------------------------------- /jinhao/jinhao_q5.py: -------------------------------------------------------------------------------- 1 | # python 3 2 | # -*-coding:utf-8-*- 3 | 4 | # 问题5:设计一个算法,将URL转换成5部分。 5 | # :///?# 6 | 7 | import re 8 | from collections import namedtuple 9 | 10 | class URL: 11 | def __init__(self): 12 | # 定义namedtuple类 13 | self.URLs = namedtuple('URLs', ['scheme', 'netloc', 'path', 'query_params', 'fragment']) 14 | 15 | def url_parse(self, url): 16 | #解析url 17 | scheme = self.get_scheme(url) 18 | netloc = self.get_netloc(url) 19 | path = self.get_path(url) 20 | query_params = self.get_query_param(url) 21 | fragment = self.get_fragment(url) 22 | 23 | # 用获取的数据初始化namedtuple实例对象 24 | url = self.URLs(scheme=scheme, netloc=netloc, path=path, query_params=query_params, fragment=fragment) 25 | return(url) 26 | 27 | def get_scheme(self, url): 28 | # 获取scheme部分 29 | if '://' in url: 30 | return url.split('://')[0] 31 | 32 | def get_netloc(self, url): 33 | # 获取netloc部分 34 | pattern = re.compile('[^\/](\w+\.)+\w+') 35 | return re.search(pattern, url).group() 36 | 37 | def get_path(self, url): 38 | # 获取path部分 39 | pattern = re.compile('\w(\/+[\w\.-_]+\w*)\?') 40 | path = re.search(pattern, url) 41 | if path: 42 | return path.group(1) 43 | 44 | def get_query_param(self, url): 45 | # 获取query param 部分 46 | if '?' in url: 47 | if '#' in url: 48 | params = url[url.find('?')+1 : url.find('#')] 49 | else: 50 | params = url[url.find('?')+1 : ] 51 | 52 | query_params = dict() 53 | 54 | for param in params.split('&'): 55 | key= param[0:param.find('=')] 56 | value = param[param.find('=') + 1 :] 57 | query_params[key] = value 58 | return query_params 59 | 60 | 61 | def get_fragment(self, url): 62 | # 获取fragment部分 63 | if '#' in url: 64 | return url.split('#')[1] 65 | 66 | 67 | if __name__ == '__main__': 68 | url1 = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 69 | url2 = "https://search.jd.com/Search.html?keyword=python%E7%BC%96%E7%A8%8B%20%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E5%AE%9E%E8%B7%B5&enc=utf-8&suggest=6.his.0.0&wq=&pvid=d8fcb24e53634679a54f4a4cbf35038c" 70 | url3 = "www.baidu.com" 71 | u = URL() 72 | print(u.url_parse(url1)) 73 | print(u.url_parse(url2)) 74 | print(u.url_parse(url3)) 75 | print(u.get_path(url1)) 76 | print(u.get_query_param(url2)) 77 | 78 | 79 | # output: 80 | 81 | # URLs(scheme='http', netloc='mp.weixin.qq.com', path='/s', query_params={'mid': '2652566513', '__biz': 'MzA4MjEyNTA5Mw=='}, fragment='wechat_redirect') 82 | # URLs(scheme='https', netloc='search.jd.com', path='/Search.html', query_params={'pvid': 'd8fcb24e53634679a54f4a4cbf35038c', 'keyword': 'python%E7%BC%96%E7%A8%8B%20%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E5%AE%9E%E8%B7%B5', 'enc': 'utf-8', 'wq': '', 'suggest': '6.his.0.0'}, fragment=None) 83 | # URLs(scheme=None, netloc='www.baidu.com', path=None, query_params=None, fragment=None) 84 | # /s 85 | # {'pvid': 'd8fcb24e53634679a54f4a4cbf35038c', 'keyword': 'python%E7%BC%96%E7%A8%8B%20%E4%BB%8E%E5%85%A5%E9%97%A8%E5%88%B0%E5%AE%9E%E8%B7%B5', 'enc': 'utf-8', 'wq': '', 'suggest': '6.his.0.0'} -------------------------------------------------------------------------------- /koukekouke/README.md: -------------------------------------------------------------------------------- 1 | 刘老师您好: 2 | 我是您知乎的一名观众,之前一直有看您发的干货,也买了您推荐的《流畅的Python》,这次赠书活动追到微信公众号,看到还有知识星球的活动,就趁这两天赶紧把题做了参与一下。 3 | 没想到这些题的质量很高,之前没怎么学习正则,最后两题倒是耗费了很长时间来翻阅教程,程序PASS的那一刻,感觉已经收获到自己想要的东西了,活动已经不重要了。 4 | 我爱Python,也爱传播Python知识的各位老师们。 5 | 谢谢刘老师! -------------------------------------------------------------------------------- /koukekouke/question_1.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少, 3 | 例如:有列表 numbers = [10, 29, 30, 41],要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 4 | ''' 5 | 6 | 7 | def enumerator(seq): 8 | for index, num in enumerate(seq): 9 | yield (index, num) 10 | 11 | 12 | numbers = [10, 29, 30, 41] 13 | for each in enumerator(numbers): 14 | print(each) 15 | -------------------------------------------------------------------------------- /koukekouke/question_2.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 设计一个猜数字的游戏,系统随机生成一个1~100之间的整数,玩家有5次机会, 3 | 每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了,则告知玩家并提前结束游戏, 4 | 如果5次都没猜中,结束游戏并告知正确答案。 5 | ''' 6 | 7 | 8 | import random 9 | 10 | 11 | num = random.randint(1, 100) 12 | times = 5 13 | 14 | for time in range(5, 0, -1): 15 | if time < 5: 16 | print('你还有%d次机会' % time) 17 | while True: 18 | try: 19 | guess = int(input('请输入您猜的整数(1~100):')) 20 | break 21 | except ValueError: 22 | print('输入错误') 23 | if guess > num: 24 | print('大了!') 25 | continue 26 | elif guess < num: 27 | print('小了!') 28 | continue 29 | else: 30 | print('恭喜你猜对了!') 31 | break 32 | else: 33 | print('你没有机会了,正确答案:%d' % num) 34 | -------------------------------------------------------------------------------- /koukekouke/question_3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 3 | ''' 4 | 5 | 6 | import io 7 | import re 8 | from collections import defaultdict 9 | 10 | 11 | def countor(file): 12 | word_dict = defaultdict(int) 13 | with io.open(file, 'r', encoding='utf-8') as f: 14 | word_list = re.compile('[a-zA-Z]+').findall(f.read()) 15 | for word in word_list: 16 | word_dict[word] += 1 17 | return sorted(word_dict.items(), key=lambda item: item[1], reverse=True)[:5] 18 | 19 | 20 | for word, times in countor('test.txt'): 21 | print(word, times) 22 | -------------------------------------------------------------------------------- /koukekouke/question_4.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 用Python实现斐波那契数列,费波那契数列由0和1开始,之后的费波那契系数就是由之前的两数相加而得出, 3 | 例如前 斐波那契数列 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。 4 | ''' 5 | 6 | 7 | def fibonacci(n): 8 | num_list = [] 9 | a, b = 0, 1 10 | for i in range(n): 11 | num_list.append(a) 12 | a, b = b, a+b 13 | return num_list 14 | 15 | 16 | print(fibonacci(10)) 17 | -------------------------------------------------------------------------------- /koukekouke/question_5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 一个完整的URL由5部分组成,格式为: 3 | :///?# 4 | 设计一个算法,将URL转换成5部分,注意,query_params 要转换成字典类型 5 | ''' 6 | 7 | 8 | import re 9 | 10 | 11 | class URL(object): 12 | 13 | def __init__(self, url): 14 | self.url = url 15 | self.url_parse = self.url_parse() 16 | 17 | def url_parse(self): 18 | query_params = {} 19 | params_key = re.search(r'(?<=\?)[^=]+', self.url) 20 | if params_key: 21 | query_params[params_key.group()] = \ 22 | re.findall(r'(?<==|&)[^&^#]+', self.url) 23 | 24 | parse = { 25 | 'scheme': re.match(r'\w+(?=://)', self.url), 26 | 'netloc': re.search(r'(?<=//)[\w.]+', self.url), 27 | 'path': re.search(r'(?<=\w/)\S+(?=\?)', self.url), 28 | 'query_params': query_params, 29 | 'fragment': re.search(r'(?<=#)\S+', self.url) 30 | } 31 | 32 | for key, val in parse.items(): 33 | if val and key != 'query_params': 34 | parse[key] = val.group() 35 | return parse 36 | 37 | def get_result(self): 38 | return self.url_parse 39 | 40 | 41 | if __name__ == '__main__': 42 | url1 = 'http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect' 43 | url2 = 'http://news.baidu.com/ns?ct=1&rn=20&ie=utf-8&bs=re.search&rsv_bp=1&sr=0&cl=2&f=8&prevct=no&tn=news&word=TEST&rsv_sug3=3&rsv_sug4=121&rsv_sug1=1&rsv_sug2=0&inputT=1409' 44 | url3 = 'http://github.com' 45 | url_obj = URL(url1) 46 | for k, v in url_obj.get_result().items(): 47 | print('%s: %s' % (k, v)) 48 | -------------------------------------------------------------------------------- /koukekouke/question_6.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 设计一个程序,用于统计一个项目中的代码数,包括文件个数,代码行数,注释行数,空行行数。 3 | 尽量设计灵活一点可以通过输入不同参数来统计不同语言的项目 4 | ''' 5 | 6 | 7 | import io 8 | import re 9 | import os 10 | import sys 11 | from getopt import getopt, GetoptError 12 | 13 | 14 | class Args(object): 15 | 16 | def __init__(self): 17 | self.type_arg = self._args_getopt() 18 | 19 | def _args_getopt(self): # 解析命令行参数 20 | try: 21 | opt, _ = getopt(sys.argv[1:], '', ['type=']) 22 | _, type_arg = opt[0] 23 | except (GetoptError, IndexError): 24 | print('e.g. >>> countor.py --type python') 25 | exit() 26 | return type_arg 27 | 28 | def get_type(self): 29 | return self.type_arg 30 | 31 | 32 | class CodeCountor(object): 33 | 34 | def __init__(self, type): 35 | self.result_dict = { 36 | 'files': 0, 37 | 'code_lines': 0, 38 | 'comments': 0, 39 | 'blanks': 0 40 | } 41 | self.type = type 42 | self._type_config = self._type_config() 43 | self._file_num = self._file_num() 44 | 45 | def _type_config(self): 46 | type_key = self.type.lower().strip() 47 | config = { 48 | 'python': ['.py', r'#[^\'\"]*', r'\s*(\'\'\')|(\"\"\")', r'.*(\'\'\')|(\"\"\")'], 49 | 'java': ['.java', r'//', r'/\*', r'.*(\*/)'], 50 | 'php': ['.php', r'//', r'/\*', r'.*(\*/)'], 51 | 'c': ['.c', r'//', r'/\*', r'.*(\*/)'], 52 | 'c++': ['.cpp', r'//', r'/\*', r'.*(\*/)'] 53 | } 54 | try: 55 | type_config = config[type_key] 56 | except KeyError: 57 | print('This type is not supported') 58 | exit() 59 | return type_config 60 | 61 | def _file_num(self): # 遍历当前文件夹下的文件 62 | all_file = os.listdir('./') 63 | for filename in all_file: 64 | if self._type_config[0] in filename: 65 | self._lines_count(filename) 66 | self.result_dict['files'] += 1 67 | 68 | def _lines_count(self, file): # 统计每行的内容 69 | with io.open(file, 'r', encoding='utf-8') as f: 70 | multi_comments = 0 # 用来判断多行注释 71 | for line in f.readlines(): 72 | if re.search(r'\S', line): # 判断非空行 73 | if not multi_comments: 74 | if re.match(r'\s*[a-zA-Z]+', line): # 判断代码行 75 | self.result_dict['code_lines'] += 1 76 | if re.search(self._type_config[1], line): # 判断单行注释 77 | self.result_dict['comments'] += 1 78 | continue 79 | if re.search(self._type_config[2], line): # 判断多行注释开始 80 | self.result_dict['comments'] += 1 81 | if not re.search(self._type_config[3], re.sub(self._type_config[2], '', line, 1)): 82 | multi_comments = 1 # 防止多行注释在本行结束 83 | 84 | elif multi_comments: 85 | self.result_dict['comments'] += 1 86 | if re.match(self._type_config[3], line): # 判断多行注释结束 87 | multi_comments = 0 88 | 89 | else: # 空行 90 | self.result_dict['blanks'] += 1 91 | 92 | def get_result(self): 93 | return self.result_dict 94 | 95 | 96 | if __name__ == '__main__': 97 | args = Args() 98 | code_countor = CodeCountor(args.get_type()) 99 | for key, val in code_countor.get_result().items(): 100 | print('%s: %d' % (key, val)) 101 | -------------------------------------------------------------------------------- /linkun/question1.md: -------------------------------------------------------------------------------- 1 | def tr(list): 2 | 3 | n = len(list) - 2 4 | i = 0 5 | L = set() 6 | while i <= n: 7 | print("(%d,%d)"%(i,list[i]),end=',') 8 | i = i + 1 9 | if i == n + 1: 10 | print("(%d,%d)"%(i,list[i])) 11 | numbers = [21,42,64,59] 12 | 13 | tr(numbers) 14 | -------------------------------------------------------------------------------- /linkun/question2.md: -------------------------------------------------------------------------------- 1 | #林坤的作业 2 | import random 3 | answer = random.randint(1,100) 4 | i = 1 5 | while i <= 5: 6 | guess = int(input("猜一个0到100的整数:")) 7 | if guess == answer: 8 | print('厉害了,猜对了!') 9 | break 10 | else : 11 | if guess > answer: 12 | print('猜大了!') 13 | else : 14 | print('猜小了!') 15 | chance = 5 - i 16 | print('再猜,还有%d次机会!'%chance) 17 | i += 1 18 | print('游戏结束,正确答案是:%d'%answer) -------------------------------------------------------------------------------- /linkun/question3.md: -------------------------------------------------------------------------------- 1 | 2 | #林坤的作业 3 | #统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 4 | import string 5 | 6 | def high_frequency_words(path,number): 7 | #打开文件,并将文档里的单词(去标点、小写化)分离 8 | with open(path,'r') as text: 9 | words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()] 10 | #单词列表变成集合,去重 11 | word_index = set(words) 12 | #用一个词典表示单词及对应的词频 13 | counts_dict ={word : words.count(word) for word in word_index} 14 | #将词汇按照频率从大到小排序,形成一个词汇列表 15 | counts_dict_sorted = sorted(counts_dict, key=lambda x: counts_dict[x], reverse=True) 16 | #输出前五个单词 17 | for i in range(number): 18 | hf_word = counts_dict_sorted[i] 19 | print('{} -- {} times'.format(hf_word,counts_dict[hf_word])) 20 | 21 | 22 | path = 'D:\_programming exercise\每日一题\Zen of Python.txt' 23 | high_frequency_words(path,5) 24 | -------------------------------------------------------------------------------- /linkun/question4.md: -------------------------------------------------------------------------------- 1 | ''' 2 | 斐波那契数列由0和1开始,之后的斐波那契系数就是由之前的两数相加而得出,例如 3 | 斐波那契数列的前10个数是 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。 4 | ''' 5 | def f(n): 6 | if n > 1: 7 | return f(n-1)+f(n-2) 8 | elif n == 1: 9 | return 1 10 | else: 11 | return 0 12 | try: 13 | n = int(input('How many sequence numbers do you want ?')) 14 | if isinstance(n,int) and n >= 0: 15 | for i in range (0,n): 16 | print(f(i),end=' ') 17 | else: 18 | print("Please input an integer not less than 0") 19 | except ValueError as e: 20 | print(e) 21 | 22 | -------------------------------------------------------------------------------- /linkun/question5.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # _*_ coding:utf-8 _*_ 4 | '''通过我的努力,下面的代码仅仅能完成对示例中url的解析......期待观摩学习别人的作品~ 5 | ''' 6 | 7 | import re 8 | from collections import namedtuple 9 | 10 | 11 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 12 | 13 | def parse(url): 14 | url_parse = namedtuple('url_parse', 'scheme netloc path query_params fragment ') 15 | p = re.split('\://|\/|\?|\#', url) 16 | p[2]='/'+p[2] 17 | p[3]=re.split('\&',p[3]) 18 | for i in range(len(p[3])): 19 | p[3][i] = re.split('\=', p[3][i],maxsplit=1) 20 | p[3] = dict(p[3]) 21 | my_url = url_parse(scheme=p[0],netloc=p[1],path=p[2],query_params=p[3],fragment=p[4]) 22 | return my_url 23 | 24 | print(parse(url)) 25 | 26 | 27 | -------------------------------------------------------------------------------- /linkun/question6.md: -------------------------------------------------------------------------------- 1 | ###靠着搜索,实现了一部分功能: 2 | ####统计一个文件夹里的文件数以及某个文件里的代码行等情况 3 | 4 | import os 5 | 6 | files = 0 7 | code_lines = 0 8 | blanks = 0 9 | comments = 0 10 | my_path = os.getcwd() 11 | my_file = open('2.py', 'r') 12 | 13 | for root, dirs, file_ in os.walk(my_path): 14 | for each in file_: 15 | files += 1 16 | print('files=', files) 17 | for line in my_file: 18 | code_lines += 1 19 | line = line.strip() 20 | if len(line) == 0: 21 | blanks += 1 22 | elif line.startswith("#"): 23 | comments += 1 24 | print('code_lines=', code_lines, '\n', 'blanks=', blanks, '\n', 'comments=', comments) -------------------------------------------------------------------------------- /linshizuowei/question_1.md: -------------------------------------------------------------------------------- 1 | # 第1题: 2 | 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少,例如:有列表 numbers = [10, 29, 30, 41],要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 3 | 4 | ``` 5 | for index, value in enumerate(numbers): 6 | print index, value 7 | ``` -------------------------------------------------------------------------------- /linshizuowei/question_2.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ``` 4 | import random 5 | def guess_numbers(): 6 | print 'game start' 7 | target_num = random.randint(1, 100) 8 | for times in range(5, 0, -1): 9 | tag = 'you have ' + str(times) + ' chances to get the special number:' 10 | input_num = raw_input(tag) 11 | for s in input_num: 12 | if ord(s) < 48 or ord(s) > 57: 13 | print 'please input a valid number' 14 | break 15 | else: 16 | guess_num = int(input_num) 17 | if guess_num == target_num: 18 | print 'bingo!' 19 | break 20 | elif guess_num > target_num: 21 | print 'too large' 22 | else: 23 | print 'too small' 24 | else: 25 | print 'What a pity! you did not got the number' 26 | ``` -------------------------------------------------------------------------------- /linshizuowei/question_3.md: -------------------------------------------------------------------------------- 1 | # 每日一题 # 第3题: 2 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 3 | 4 | ``` 5 | def count_words(): 6 | words = {} 7 | with open('import_this.txt','r') as file: 8 | for line in file: 9 | for word in line.split(): 10 | for i in range(len(word)): 11 | if (ord(word[i]) > 64 and ord(word[i]) < 91 ) or ( ord(word[i]) > 96 and ord(word[i]) < 123 ): 12 | word = word[i:] 13 | break 14 | else: 15 | continue 16 | for j in range(len(word)-1, -1, -1): 17 | if (ord(word[j]) > 64 and ord(word[j]) < 91 ) or ( ord(word[j]) > 96 and ord(word[j]) < 123 ): 18 | word = word[:j+1] 19 | break 20 | words.setdefault(word, 0) 21 | words[word] += 1 22 | 23 | for out in sorted(words.values(), key=lambda x:x[0],reverse=True)[:5]: 24 | print out[1] 25 | 26 | ``` -------------------------------------------------------------------------------- /linshizuowei/question_5.md: -------------------------------------------------------------------------------- 1 | 问题:设计一个算法,将URL转换成5部分,注意,query_params 要转换成字典类型 2 | ``` 3 | import re 4 | 5 | class URL(object): 6 | def __init__(self,url): 7 | self.url = url 8 | self.scheme = None 9 | self.netloc = None 10 | self.path = None 11 | self.query_params = {} 12 | self.fragment = None 13 | 14 | def url_parse(self): 15 | self.scheme_parse() 16 | self.netloc_parse() 17 | self.path_parse() 18 | self.query_parse() 19 | self.fragment_parse() 20 | 21 | def scheme_parse(self): 22 | if self.url: 23 | self.scheme = re.match(r'.*(?=:)', self.url).group() 24 | 25 | def netloc_parse(self): 26 | if self.url: 27 | self.netloc = re.search(r'(?<=//)[a-z]+\.[a-z]+\.[a-z]+\.[a-z]+', self.url).group() 28 | 29 | def path_parse(self): 30 | if self.url: 31 | self.path = re.search(r'(?<=\w/).*(?=\?)',self.url).group() 32 | 33 | def query_parse(self): 34 | if self.url: 35 | q_str = re.search(r'(?<=\?).*(?=#)',self.url).group() 36 | for item in re.split(r'&', q_str): 37 | index = item.find('=') 38 | self.query_params[item[:index]] = item[index+1:] 39 | 40 | def fragment_parse(self): 41 | if self.url: 42 | self.fragment = re.search(r'(?<=#).*', self.url).group() 43 | ``` -------------------------------------------------------------------------------- /linshizuowei/question_6.md: -------------------------------------------------------------------------------- 1 | ## 第6题 2 | 3 | 设计一个程序,用于统计一个项目中的代码数,包括文件个数,代码行数,注释行数,空行行数。尽量设计灵活一点可以通过输入不同参数来统计不同语言的项目 4 | 5 | ``` 6 | import os 7 | import argparse 8 | class Summarise(object): 9 | def __init__(self): 10 | self.pro_name = None 11 | self.type = None 12 | self.file_sum = None 13 | self.files = 0 14 | self.code_lines = 0 15 | self.comments = 0 16 | self.blanks = 0 17 | 18 | def sum_print(self): 19 | print 'files:', self.files 20 | print 'code_lines:', self.code_lines 21 | print 'comments:', self.comments 22 | print 'blanks:', self.blanks 23 | 24 | def summarize(self): 25 | if self.type == None: 26 | self.type = 'py' 27 | if self.type == 'py': 28 | self.file_sum = self.py_file_sum 29 | elif self.type == 'java': 30 | self.file_sum = self.java_file_sum 31 | for entry in os.listdir(self.pro_name): 32 | entry = os.path.join(self.pro_name, entry) 33 | if os.path.isfile(entry): 34 | self.file_sum(entry) 35 | elif os.path.isdir(entry): 36 | self.dir_sum(entry) 37 | self.sum_print() 38 | 39 | def py_file_sum(self, file): 40 | self.files += 1 41 | with open(file, 'r') as f: 42 | while True: 43 | line = f.readline() 44 | if line == '': 45 | break 46 | line = line.lstrip('\t ') 47 | if line == '\n': 48 | self.blanks += 1 49 | elif line.startswith('#'): 50 | self.comments += 1 51 | elif line.startswith('"""'): 52 | self.comments += 1 53 | while True: 54 | line = f.readline() 55 | self.comments += 1 56 | if line == '"""': 57 | break 58 | elif line.startswith("'''"): 59 | self.comments += 1 60 | while True: 61 | line = f.readline() 62 | self.comments += 1 63 | if line == "'''": 64 | break 65 | else: 66 | self.code_lines += 1 67 | 68 | def java_file_sum(self, file): 69 | self.files += 1 70 | with open(file, 'r') as f: 71 | while True: 72 | line = f.readline() 73 | if line == '': 74 | break 75 | line = line.lstrip('\t ') 76 | if line == '\n': 77 | self.blanks += 1 78 | elif line.startswith('//'): 79 | self.comments += 1 80 | elif line.startswith('/**'): 81 | self.comments += 1 82 | while True: 83 | line = f.readline() 84 | self.comments += 1 85 | if line == '*/': 86 | break 87 | elif line.startswith('/*'): 88 | self.comments += 1 89 | while True: 90 | line = f.readline() 91 | self.comments += 1 92 | if line == '*/': 93 | break 94 | else: 95 | self.code_lines += 1 96 | 97 | def dir_sum(self, dir): 98 | for entry in os.listdir(dir): 99 | entry = os.path.join(dir, entry) 100 | if os.path.isfile(entry): 101 | self.file_sum(entry) 102 | elif os.path.isdir(entry): 103 | self.dir_sum(entry) 104 | 105 | 106 | if __name__ == '__main__': 107 | parser = argparse.ArgumentParser(description='This is a summary program',) 108 | parser.add_argument('--type', default='py', choices=['py','java'], help='This argument specified the language type') 109 | parser.add_argument('-i', default=os.getcwd(), help='Project that being summarized') 110 | args = parser.parse_args() 111 | summa = Summarise() 112 | summa.pro_name = args.i 113 | summa.type = args.type 114 | summa.summarize() 115 | ``` -------------------------------------------------------------------------------- /liuzhijun/weixincrawler/models.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | from mongoengine import connect 4 | from mongoengine import Document 5 | from mongoengine import IntField 6 | from mongoengine import StringField 7 | from mongoengine import DateTimeField 8 | from mongoengine import URLField 9 | 10 | __author__ = "liuzhijun" 11 | 12 | # 连接 mongodb 13 | connect('weixin', host='localhost', port=27017) 14 | 15 | 16 | class Post(Document): 17 | """ 18 | 文章信息 19 | """ 20 | title = StringField() # 文章标题 21 | content_url = StringField() # 文章链接 22 | content = StringField() # 文章内容 23 | source_url = StringField() # 原文链接 24 | digest = StringField() # 文章摘要 25 | cover = URLField(validation=None) # 封面图 26 | c_date = DateTimeField() # 推送时间 27 | read_num = IntField(default=0) # 阅读数 28 | like_num = IntField(default=0) # 点赞数 29 | comment_num = IntField(default=0) # 评论数 30 | reward_num = IntField(default=0) # 赞赏数 31 | author = StringField() # 作者 32 | 33 | 34 | class Account(Document): 35 | """ 36 | 公众号账号信息 37 | """ 38 | # TODO 39 | pass 40 | 41 | 42 | -------------------------------------------------------------------------------- /liuzhijun/weixincrawler/utils.py: -------------------------------------------------------------------------------- 1 | import re 2 | 3 | 4 | def sub_dict(data, keys): 5 | """ 6 | 获取字典对象的子字典 7 | :param data: 源字典 8 | :param keys: 需要提取key列表 9 | :return:dict 10 | """ 11 | return {key: data[key] for key in data if key in keys} 12 | 13 | 14 | def str_to_dict(s, join_symbol="\n", split_symbol=":"): 15 | """ 16 | key与value通过split_symbol连接, key,value 对之间使用join_symbol连接 17 | 例如: a=b&c=d join_symbol是&, split_symbol是= 18 | :param s: 原字符串 19 | :param join_symbol: 连接符 20 | :param split_symbol: 分隔符 21 | :return: 字典 22 | """ 23 | s_list = s.split(join_symbol) 24 | data = dict() 25 | for item in s_list: 26 | item = item.strip() 27 | if item: 28 | k, v = item.split(split_symbol, 1) 29 | data[k] = v.strip() 30 | return data 31 | 32 | 33 | def extract_text(text, rex): 34 | """ 35 | 根据正则表达式提取文本 36 | :param text: 原文本 37 | :param rex: 正则 38 | :return: 39 | """ 40 | 41 | pattern = re.compile(rex, re.S) 42 | match = pattern.search(text) 43 | if match: 44 | return match.groups() 45 | 46 | 47 | def xx(s): 48 | return s.replace("&", "&\"\\\n\"") 49 | 50 | 51 | if __name__ == '__main__': 52 | s = "__biz=MjM5MzgyODQxMQ==&mid=2650367644&idx=1&sn=9951edf4e9bfebcdaa7dd66a639befea&chksm=be9cddc889eb54de36a00865dcd15f9cf906d1868430dd62f1fe550b55e713b333344811e717&scene=27#wechat_redirect" 53 | print(str_to_dict(s, join_symbol="&", split_symbol="=")) -------------------------------------------------------------------------------- /loongoo/sendcopy/pywin32demo1.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | # pywin32 应用演示 4 | # 目标:实现将列表中的单词自动翻译出来 5 | # 项目进度:未完成! 6 | # 20171208 实现了向文本框发送单词。问题暂时无法取回翻译结果 7 | 8 | 9 | import time 10 | import win32gui 11 | import win32api 12 | import win32con 13 | 14 | 15 | # 从网络复制的模块:查找窗口句柄 16 | def find_idxSubHandle(pHandle, winClass, index=0): 17 | """ 18 | 已知子窗口的窗体类名 19 | 寻找第index号个同类型的兄弟窗口 20 | """ 21 | assert type(index) == int and index >= 0 22 | handle = win32gui.FindWindowEx(pHandle, 0, winClass, None) 23 | while index > 0: 24 | handle = win32gui.FindWindowEx(pHandle, handle, winClass, None) 25 | index -= 1 26 | return handle 27 | 28 | def find_subHandle(pHandle, winClassList): 29 | """ 30 | 递归寻找子窗口的句柄 31 | pHandle是祖父窗口的句柄 32 | winClassList是各个子窗口的class列表,父辈的list-index小于子辈 33 | """ 34 | assert type(winClassList) == list 35 | if len(winClassList) == 1: 36 | return find_idxSubHandle(pHandle, winClassList[0][0], winClassList[0][1]) 37 | else: 38 | pHandle = find_idxSubHandle(pHandle, winClassList[0][0], winClassList[0][1]) 39 | return find_subHandle(pHandle, winClassList[1:]) 40 | 41 | 42 | words = ['girl','boy','man','study'] 43 | 44 | yd_win_title = u"网易有道词典" 45 | yd_win_hd = win32gui.FindWindow('YodaoMainWndClass',yd_win_title) 46 | print('{} - {:x}'.format(yd_win_hd,yd_win_hd)) 47 | if int(yd_win_hd) <= 0 : 48 | print(yd_win_title,'未启动') 49 | exit(0) 50 | 51 | 52 | yd_win2_hd=win32gui.FindWindowEx(yd_win_hd,None,None,None) 53 | print('{} - {:x}'.format(yd_win2_hd,yd_win2_hd)) 54 | 55 | yd_win3_hd=find_subHandle(yd_win_hd,[('Edit',0)]) 56 | print('{} - {:x}'.format(yd_win3_hd,yd_win3_hd)) 57 | 58 | yd_win4_hd = find_subHandle(yd_win_hd,[('YodaoMainWndClass',0), 59 | ('CefBrowserWindow',0), 60 | ('Chrome_WidgetWin_0',0), 61 | ('Chrome_RenderWidgetHostHWND',0)]) 62 | print('{} - {:x}'.format(yd_win4_hd,yd_win4_hd)) 63 | 64 | #获取窗口焦点 65 | win32gui.SetForegroundWindow(yd_win_hd) 66 | win32gui.SetForegroundWindow(yd_win3_hd) 67 | 68 | 69 | for word in words: 70 | # WM_SETTEXT 71 | win32api.SendMessage(yd_win3_hd,win32con.WM_SETTEXT,None,word) 72 | win32api.keybd_event(13,0,0,0) # 回车键 73 | win32api.keybd_event(13,0,win32con.KEYEVENTF_KEYUP,0) 74 | #win32gui.SetForegroundWindow(yd_win4_hd) 75 | time.sleep(2.5) -------------------------------------------------------------------------------- /lumingfei/question1.md: -------------------------------------------------------------------------------- 1 | 路明非的回答 2 | 3 | ``` python 4 | #!/usr/bin/env python 5 | # -*- coding:utf-8 -*- 6 | 7 | numbers = [10, 29, 30, 41] 8 | 9 | # 第一种方法,使用一个变量记录列表的索引 10 | index = 0 11 | for i in numbers: 12 | print(index, i) 13 | index += 1 14 | 15 | print('---------\n') 16 | 17 | # 第二种方法,通过索引获取值 18 | for i in range(0, len(numbers)): 19 | print(i, numbers[i]) 20 | 21 | print('---------\n') 22 | 23 | # 第三种方法,使用list的index()方法获取元素的索引值 24 | for i in numbers: 25 | print(numbers.index(i), i) 26 | 27 | print('---------\n') 28 | 29 | # 第四种方法,使用enumerate(枚举) 30 | i = 0 31 | for i, element in enumerate(numbers): 32 | print(i, element) 33 | ``` 34 | -------------------------------------------------------------------------------- /lumingfei/question2.md: -------------------------------------------------------------------------------- 1 | 路明非的回答 2 | 3 | ``` python 4 | #!/usr/bin/env python 5 | # -*- coding:utf-8 -*- 6 | import random 7 | 8 | chioce = input('欢迎来到猜数字游戏(输入q退出)') 9 | 10 | while True: 11 | guess_flag = False 12 | key_num = random.randint(1, 100) 13 | if chioce == 'q': 14 | break 15 | for guess_time in range(5): 16 | guess_num = 0 17 | if guess_time == 0: 18 | guess_num = int(input('数字范围是1-100,你猜的数字是:')) 19 | if guess_num == key_num: 20 | print('恭喜你,猜对了!') 21 | guess_flag = True 22 | chioce = input('还要继续玩下去吗?(回车继续,输入q退出)') 23 | break 24 | else: 25 | if guess_num < key_num: 26 | print('你输入的数字小了') 27 | else: 28 | print('你输入的数字大了') 29 | else: 30 | guess_num = int(input('你还有%d次机会哦,你猜的数字是:' % (5-guess_time))) 31 | if guess_num == key_num: 32 | print('恭喜你,猜对了!') 33 | guess_flag = True 34 | chioce = input('还要继续玩下去吗?(回车继续,输入q退出)') 35 | break 36 | else: 37 | if guess_num < key_num: 38 | print('你输入的数字小了') 39 | else: 40 | print('你输入的数字大了') 41 | if not guess_flag: 42 | print('很遗憾,你的机会用完了,你输了。') 43 | chioce = input('还要继续玩下去吗?(回车继续,输入q退出)') 44 | ``` 45 | -------------------------------------------------------------------------------- /lumingfei/question3.md: -------------------------------------------------------------------------------- 1 | 路明非的回答: 2 | 3 | ``` python 4 | #!/usr/bin/env python 5 | # -*- coding:utf-8 -*- 6 | 7 | import re 8 | 9 | word_list = re.sub('[,|.|!|*|-]', ' ', open('import_this.txt').read()).split() 10 | word_dict = {} 11 | 12 | for word in word_list: 13 | if word in word_dict.keys(): 14 | word_dict[word] += 1 15 | else: 16 | word_dict[word] = 1 17 | 18 | new_word_list = sorted(word_dict.items(), key=lambda item:item[1]) 19 | print('出现频率最多的五个单词是:') 20 | for index in range(0, 5): 21 | print('单词:', new_word_list[::-1][index][0], ' 次数:', new_word_list[::-1][index][1]) 22 | ``` 23 | -------------------------------------------------------------------------------- /lumingfei/question4.md: -------------------------------------------------------------------------------- 1 | 路明非的回答 2 | 3 | 斐波那契数列是常见的递归问题,很多oj题目的规律都是斐波那契,但是使用递归方法会超时,一般在oj遇到这种题目都用递推。 4 | 5 | ``` python 6 | #!/usr/bin/env python 7 | # -*- coding:utf-8 -*- 8 | 9 | num_list = [0, 1] 10 | 11 | index = int(input('要取前多少个数?')) 12 | for i in range(2, index): 13 | num_list.append(num_list[i-1] + num_list[i-2]) 14 | 15 | print(num_list) 16 | ``` 17 | -------------------------------------------------------------------------------- /lytl890/question1.py: -------------------------------------------------------------------------------- 1 | # -*- encoding:utf-8 -*- 2 | 方法一:使用enumerate函数 3 | numbers=[10,29,30,41] 4 | for key,value in enumerate(numbers): 5 | print (key,value) 6 | 方法二:通过列表长度来迭代列表下标 7 | for i in range(len(numbers)): 8 | print('({0},{1})'.format(i,numbers[i])) 9 | 10 | -------------------------------------------------------------------------------- /lytl890/question2.py: -------------------------------------------------------------------------------- 1 | # -*- encoding:utf-8 -*- 2 | from random import randint 3 | rannumber=randint(1,100) 4 | count=0 5 | print rannumber 6 | while count<5: 7 | number=input('请输入你要猜的数字:') 8 | if isinstance(number,int): 9 | count+=1 10 | if number==rannumber: 11 | print ('恭喜你,猜对了') 12 | break 13 | elif number>> numbers = [10, 29, 30, 41] 10 | >>> printInfo(numbers) 11 | (0, 10), (1, 29), (2, 30), (3, 41) 12 | ''' 13 | for index, value in enumerate(lst): 14 | print((index, value), end=', ') -------------------------------------------------------------------------------- /maxingmin/question2.py: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | def init_data(min, max): 4 | return random.randint(min, max) 5 | 6 | def guess(min, max, choice): 7 | target = init_data(min, max) 8 | 9 | for time in range(1, choice+1): 10 | try: 11 | guess_num = int(input(f'请输入{min}到{max}间的整数: ')) 12 | except ValueError: 13 | print(f'请输入有效数字!, 还剩{choice-time}次机会') 14 | continue 15 | 16 | if guess_num > target: 17 | print(f'偏大!, 还剩{choice-time}次机会') 18 | elif guess_num < target: 19 | print(f'偏小!, 还剩{choice-time}次机会') 20 | else: 21 | print('猜对了!') 22 | break 23 | else: 24 | print(f'正确答案为:{target}') 25 | 26 | guess(1, 100, 5) 27 | 28 | -------------------------------------------------------------------------------- /maxingmin/question3.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词. 3 | ''' 4 | import re 5 | from collections import Counter 6 | 7 | 8 | def version1(): 9 | words = re.findall(r'\w+', open('import_this.txt').read().lower()) 10 | print(Counter(words).most_common(5)) 11 | 12 | 13 | def version2(): 14 | def read_data(path): 15 | with open(path, encoding='utf-8') as f: 16 | data = f.read().lower() 17 | 18 | words = re.findall(r'\w+', data) 19 | mapping = dict() 20 | for word in words: 21 | mapping[word] = mapping.get(word, 0) + 1 22 | return mapping 23 | 24 | def count_common(path, n): 25 | assert n > 0 26 | mapping = read_data(path) 27 | return sorted(mapping.items(), key=lambda item: item[1], reverse=True)[:n] 28 | a = str() 29 | 30 | print(count_common('import_this.txt', 5)) 31 | 32 | 33 | version1() 34 | version2() 35 | -------------------------------------------------------------------------------- /maxingmin/question4.py: -------------------------------------------------------------------------------- 1 | '''菲波那切数列.''' 2 | 3 | 4 | def fib_recr(n): 5 | ''' 6 | 7 | >>> fib_recr(10) 8 | 55 9 | ''' 10 | if n in (0, 1): 11 | return n 12 | return fib_recr(n - 1) + fib_recr(n - 2) 13 | 14 | 15 | def fib_iter(n): 16 | ''' 17 | 18 | >>> fib_iter(10) 19 | 55 20 | ''' 21 | a, b = 0, 1 22 | for _ in range(n - 1): 23 | a, b = b, a + b 24 | return b 25 | 26 | 27 | def fib_matrix(n): 28 | '''Using matrix to calculate the nth fibonaci number. 29 | 30 | >>> fib_matrix(10) 31 | 55 32 | ''' 33 | import numpy 34 | return (numpy.matrix([[1, 1], [1, 0]]) ** (n - 1) * numpy.matrix([[1], [0]]))[0, 0] 35 | 36 | 37 | def fibonacci_sequence(n): 38 | ''' 39 | 40 | >>> fibonacci_sequence(10) 41 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 42 | ''' 43 | return [fib_recr(x) for x in range(n)] 44 | -------------------------------------------------------------------------------- /maxingmin/question5.py: -------------------------------------------------------------------------------- 1 | ''' 2 | >>> url = url_parse('http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect') 3 | >>> url.schema 4 | 'http' 5 | >>> url.netloc 6 | 'mp.weixin.qq.com' 7 | >>> url.path 8 | '/s' 9 | >>> url.query_params 10 | {'__biz': 'MzA4MjEyNTA5Mw', 'mid': '2652566513'} 11 | >>> url.fragment 12 | 'wechat_redirect' 13 | ''' 14 | 15 | import collections 16 | import re 17 | 18 | URL = collections.namedtuple('URL', 'schema netloc path query_params fragment') 19 | 20 | 21 | def url_parse(url): 22 | url_regex = re.compile(r''' 23 | (\w+) #schema 24 | ://([\w./]+) #netloc 25 | (/(\w+)) #path 26 | \?(.+) #query_params 27 | \#(.+) #fragment 28 | ''', re.VERBOSE) 29 | ma = url_regex.search(url) 30 | 31 | params = { 32 | param_pair.split('=')[0]: param_pair.split('=')[1] 33 | for param_pair in ma.group(5).split('&')} 34 | 35 | return URL( 36 | schema=ma.group(1), 37 | netloc=ma.group(2), 38 | path=ma.group(3), 39 | query_params=params, 40 | fragment=ma.group(6)) 41 | -------------------------------------------------------------------------------- /puhuaqiang/question1.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | ''' 5 | @Author : {PHQ} 6 | @License : (C) Copyright 2017, {public} 7 | @Contact : {puhuaqiang@hotmail.com} 8 | @Software: {question_1} 9 | @File : question1.py 10 | @Time : 2017-10-28 11 | @Desc : 12 | 13 | 每日一题的第1题: 14 | 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少, 15 | 例如 numbers = [10, 29, 30, 41],要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 16 | ''' 17 | 18 | ''' 19 | @analysis: 20 | 1.构造列表 21 | 2.枚举列表 22 | 3.格式化字符串 23 | 4.字符串拼接 24 | 涉及知识点:列表、字符串、内建函数 25 | @result: 26 | 代码执行输出结果:(0,10),(1,29),(2,30),(3,41) 27 | ''' 28 | 29 | numbers = [10, 29, 30, 41] 30 | str_ret = '' 31 | index = 0 32 | for item in numbers: 33 | if len(str_ret) > 0: 34 | str_ret += ',' 35 | str_ret += '({1},{0})'.format(item,index) 36 | index += 1 37 | print(str_ret); 38 | 39 | -------------------------------------------------------------------------------- /puhuaqiang/question2.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | ''' 5 | @Author : {PHQ} 6 | @License : (C) Copyright 2017, {public} 7 | @Contact : {puhuaqiang@hotmail.com} 8 | @Software: {question_2} 9 | @File : question2.py 10 | @Time : 2017-10-30 11 | @Desc : 12 | 13 | 每日一题的第2题: 14 | 系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了, 15 | 则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案 16 | ''' 17 | 18 | import random 19 | 20 | answer_number = random.randint(1,100) 21 | answer_cnt = 5 22 | while answer_cnt > 0: 23 | number = input('Answer a number({0} chances): '.format(answer_cnt)) 24 | number = int(number) 25 | if number == answer_number: 26 | break 27 | elif number > answer_number: 28 | print("The numbers are too big!") 29 | else: 30 | print("The numbers are too small!") 31 | answer_cnt -= 1; 32 | 33 | if answer_cnt > 0: 34 | print("Congratulations, right answer!") 35 | else: 36 | print("The correct answer is ", answer_number) 37 | 38 | 39 | 40 | 41 | 42 | 43 | -------------------------------------------------------------------------------- /puhuaqiang/question3.py: -------------------------------------------------------------------------------- 1 | #!D:\\Python34 2 | # -*- coding: UTF-8 -*- 3 | 4 | ''' 5 | @Author : {PHQ} 6 | @License : (C) Copyright 2017, {public} 7 | @Contact : {puhuaqiang@hotmail.com} 8 | @Software: {question_3} 9 | @File : question3.py 10 | @Time : 2017-11-02 11 | @Desc : 12 | 每日一题的第3题: 13 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 14 | ''' 15 | 16 | import re 17 | try: 18 | # 打开文件,如果运行请修改文件路径 19 | with open("f:\import_this.txt",'r') as my_file: 20 | data = my_file.read() 21 | #print(data) 22 | read_len = 0 23 | words = {} 24 | # 使用正则表达式读取单个单词 25 | while 1: 26 | if read_len > 0: 27 | data = data[read_len:] 28 | matchObj = re.search(r'(\S+\b)', data, re.M|re.I) 29 | if not matchObj: 30 | print("Nothing found!!") 31 | break 32 | read_len = matchObj.end() 33 | if len(matchObj.group()) <= 0: 34 | continue 35 | #print(matchObj.group()) 36 | 37 | # 读取的单词放在字典中 38 | if matchObj.group() in words.keys(): 39 | words[matchObj.group()] += 1 40 | else: 41 | words[matchObj.group()] = 1 42 | print("单词总数:",len(words)); 43 | 44 | # 单词按出现次数排序 45 | sort_words = sorted(words.items(), key=lambda el:el[1], reverse = True) 46 | '''for word,count in words.items(): 47 | print("单词:{0}\t总数:{1}".format(word,count));''' 48 | 49 | for word in sort_words: 50 | print("单词:{0}\t总数:{1}".format(word[0],word[1])); 51 | except IOError: 52 | print("File Error!") 53 | 54 | ''' 55 | 前五的单词: 56 | 57 | 单词:is 总数:10 58 | 单词:better 总数:8 59 | 单词:than 总数:8 60 | 单词:to 总数:5 61 | 单词:the 总数:5 62 | ''' 63 | -------------------------------------------------------------------------------- /puhuaqiang/question4.py: -------------------------------------------------------------------------------- 1 | #! /usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | ''' 5 | @Author : {PHQ} 6 | @License : (C) Copyright 2017, {public} 7 | @Contact : {puhuaqiang@hotmail.com} 8 | @Software: {question_3} 9 | @File : question4.py 10 | @Time : 2017-11-07 11 | @Desc : 12 | 13 | 用Python实现斐波那契数列 14 | ''' 15 | 16 | class Fibonacci(): 17 | 18 | def __init__(self, n): 19 | # 需要查询的序号 20 | self.que_serial_number = n 21 | #当前序号, 0是第0项,不是第1项 22 | self.current_serial_number = 0 23 | #当前序号的值 24 | self.current_serial_number_value = 0 25 | #保存前2个值的数组 [0]=f(n-2) [1]=f(n-1) 26 | self.val = [0,0] 27 | 28 | def calculate(self): 29 | ''' 30 | 得到当前序号的值 31 | ''' 32 | if self.current_serial_number < 2: 33 | if self.current_serial_number == 0: 34 | self.current_serial_number_value = 0 35 | else: 36 | self.current_serial_number_value = 1 37 | else: 38 | self.current_serial_number_value = self.val[0] + self.val[1] 39 | 40 | self.val[0] = self.val[1] 41 | self.val[1] = self.current_serial_number_value 42 | 43 | if self.current_serial_number == self.que_serial_number: 44 | return 45 | # 计算下一个序号 46 | self.current_serial_number += 1 47 | self.calculate() 48 | 49 | def ans(self): 50 | if not isinstance(self.que_serial_number, int): 51 | print("查询序号值错误!") 52 | return 53 | self.current_serial_number = 0 54 | self.calculate() 55 | return self.current_serial_number_value 56 | 57 | if __name__ == '__main__': 58 | number = 6 59 | print("第%d序列数:%d" % (number,Fibonacci(number).ans())) 60 | 61 | 62 | 63 | -------------------------------------------------------------------------------- /question_2/xiaoxuan: -------------------------------------------------------------------------------- 1 | import random 2 | TargetNum = random.randint(0,100) 3 | print "Hey! Let's start the game!!!" 4 | print "Please guess the correct number in 5 times!!!" 5 | print TargetNum 6 | for count in range(0,5): 7 | GuessNum = int(input("Please input the number in your mind: ")) 8 | if GuessNum > TargetNum: 9 | print "The number that you input is too large" 10 | elif GuessNum < TargetNum: 11 | print "The number that you input is too small" 12 | elif GuessNum == TargetNum: 13 | print "YOU MADE IT! YOU ARE SUCH A LUCKY DOG!" 14 | break 15 | if count == 4&GuessNum != TargetNum: 16 | print "YOU WASTED 5 TIMES! YOU ARE SUCH A IDIOT!!!" 17 | print "The CORRECT NUMBER IS: ",TargetNum 18 | -------------------------------------------------------------------------------- /question_3/day3_homework.py: -------------------------------------------------------------------------------- 1 | #-*-codeing:utf-8-*- 2 | import io 3 | import re 4 | 5 | class Counter: 6 | def __init__(self,path): 7 | """ 8 | :param path: file path 9 | """ 10 | self.mapping = dict() 11 | with io.open(path,encoding="utf-8")as f: 12 | data = f.read() 13 | print data 14 | words= [s.lower() for s in re.findall("\w+",data)] 15 | for word in words: 16 | print word 17 | self.mapping[word]=self.mapping.get(word,0)+1 18 | 19 | def most_common(self,n): 20 | assert n>0,"n should be large than 0" 21 | return sorted(self.mapping.items(),key=lambda item:item[1],reverse=True)[:n] 22 | 23 | if __name__=='__main__': 24 | most_common_5 = Counter("import_this.txt").most_common(10) 25 | for item in most_common_5: 26 | print(item) 27 | -------------------------------------------------------------------------------- /question_3/maxingmin.py: -------------------------------------------------------------------------------- 1 | ''' 2 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词. 3 | ''' 4 | import re 5 | from collections import Counter 6 | 7 | 8 | def version1(): 9 | words = re.findall(r'\w+', open('import_this.txt').read().lower()) 10 | print(Counter(words).most_common(5)) 11 | 12 | 13 | def version2(): 14 | def read_data(path): 15 | with open(path, encoding='utf-8') as f: 16 | data = f.read().lower() 17 | 18 | words = re.findall(r'\w+', data) 19 | mapping = dict() 20 | for word in words: 21 | mapping[word] = mapping.get(word, 0) + 1 22 | return mapping 23 | 24 | def count_common(path, n): 25 | assert n > 0 26 | mapping = read_data(path) 27 | return sorted(mapping.items(), key=lambda item: item[1], reverse=True)[:n] 28 | a = str() 29 | 30 | print(count_common('import_this.txt', 5)) 31 | 32 | 33 | version1() 34 | version2() 35 | -------------------------------------------------------------------------------- /question_4/Q4_CY: -------------------------------------------------------------------------------- 1 | def fib(): 2 | now_loop = 0 3 | the_n_1 = 1 4 | the_n_2 = 0 5 | now_number = 1 6 | 7 | if now_loop == 0: 8 | yield 0 9 | now_loop = now_loop + 1 10 | 11 | while True: 12 | yield now_number 13 | now_number = the_n_1 + the_n_2 14 | the_n_2 = the_n_1 15 | the_n_1 = now_number 16 | now_loop = now_loop + 1 17 | return 18 | 19 | def get_fib_list(run_time): 20 | g = fib() 21 | for i in range(0,run_time): 22 | print(next(g)) 23 | 24 | get_fib_list(10) 25 | -------------------------------------------------------------------------------- /question_4/captainwell_q4: -------------------------------------------------------------------------------- 1 | def fabonacci(fab=[]): try: n = int(input("请输入变量n:")) if n < 0: print("请输入大于等于0的整数") return except ValueError: print("请输入大于等于0的整数") return for item in range(0,n+1): if item == 0: fab.append(0) elif item == 1: fab.append(1) elif n > 1: fab.append(fab[item-1] + fab[item-2]) print("您需要的斐波那契数列为") for item in range(0,n+1): print(fab[item],end=" ")if __name__ == '__main__': fabo = [] fabonacci(fabo) 2 | -------------------------------------------------------------------------------- /question_4/dingshubo.md: -------------------------------------------------------------------------------- 1 | #!/user/bin/env python 2 | #_*_coding:utf-8_*_ 3 | try: 4 | num_input=int(raw_input('请输入你想获得n+2位的斐波那契数列):')) #输出斐波那契数列个数,2为初始位 5 | num_feb=[0,1] #初始位 6 | while num_input<=0: 7 | print('你所输入的不是一个有效整数!') 8 | break 9 | for i in range(0,num_input): 10 | num_feb.append(num_feb[-2]+num_feb[-1]) 11 | print('所想获得的斐波那契数列为%r')%num_feb 12 | except ValueError: 13 | print('\n你输入的不是一个整数!') 14 | -------------------------------------------------------------------------------- /question_4/heguilong.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python3 2 | """ 3 | File: heguilong.py 4 | Author: heguilong 5 | Email: hgleagle@gmail.com 6 | Github: https://github.com/hgleagle 7 | Description: 8 | 斐波那契数列由0和1开始,之后的斐波那契系数就是由之前的两数相加而得出,例如 9 | 斐波那契数列的前10个数是 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。 10 | """ 11 | import logging 12 | import sys 13 | 14 | import numpy as np 15 | 16 | 17 | logging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(levelname)s \ 18 | - %(message)s') 19 | 20 | 21 | # solution 1, O(1.618^n) 22 | class Fibonacci(): 23 | def __init__(self): 24 | """TODO: Docstring for __init__. 25 | 26 | :arg1: TODO 27 | :returns: TODO 28 | 29 | """ 30 | self.fib_dict = {} 31 | 32 | def calculate(self, number): 33 | """TODO: Docstring for calculate. 34 | 35 | :f: TODO 36 | :number: TODO 37 | :returns: TODO 38 | 39 | """ 40 | # logging.debug("number: {%d}" % number) 41 | assert number >= 0 42 | if number in (0, 1): 43 | result = number 44 | else: 45 | result = self.calculate(number - 1) + self.calculate(number - 2) 46 | if number > 0 and number not in self.fib_dict: 47 | self.fib_dict[number] = result 48 | return result 49 | 50 | def show_fib_values(self): 51 | print(self.fib_dict.values()) 52 | 53 | 54 | # solution 2, O(n) 55 | def fib_loop(n): 56 | a, b = 0, 1 57 | while n > 0: 58 | yield b 59 | a, b = b, a + b 60 | n -= 1 61 | 62 | 63 | # solution 3, O(logn) 64 | def fib_matr(n): 65 | return (np.matrix([1, 1], [1, 0]) ** (n - 1) * np.matrix([1], [0]))[0, 0] 66 | 67 | 68 | if __name__ == "__main__": 69 | if len(sys.argv) != 2: 70 | print("Usage: python3 heguilong.py number") 71 | sys.exit() 72 | number = int(sys.argv[1]) 73 | if number <= 0: 74 | print("number should be larger than 0") 75 | 76 | # solution 1 77 | print("Solution 1:") 78 | fib_obj = Fibonacci() 79 | fib_obj.calculate(number) 80 | fib_obj.show_fib_values() 81 | 82 | # solution 2 83 | print("Solution 2:") 84 | for i in fib_loop(number): 85 | print(i, end=" ") 86 | 87 | # solution 3 88 | print("Solution 3:") 89 | for n in range(number): 90 | print(fib_matr(n), end=" ") 91 | -------------------------------------------------------------------------------- /question_4/liumaolin.md: -------------------------------------------------------------------------------- 1 | # 第四题 2 | ### 用Python实现斐波那契数列,费波那契数列由0和1开始,之后的费波那契系数就是由之前的两数相加而得出,例如斐波那契数列 前10个数分别为:0, 1, 1, 2, 3, 5, 8, 13, 21, 34。 3 | 4 | 5 | 6 | ``` python 7 | # Solution1 递归实现 8 | def Fibonacci(n): 9 | assert n >= 0, "n should be large than 0" 10 | if n < 2: 11 | return n 12 | return Fibonacci(n - 1) + Fibonacci(n - 2) 13 | 14 | 15 | # Solution2 循环实现 16 | def Fibonacci(n): 17 | assert n >= 0, "n should be large than 0" 18 | if n < 2: 19 | return n 20 | x, y = 0, 1 21 | for i in range(2, n + 1): 22 | x, y = y, x + y 23 | return y 24 | ``` -------------------------------------------------------------------------------- /question_4/lytl890: -------------------------------------------------------------------------------- 1 | def fib(n): 2 | if n==0: 3 | return 0 4 | elif n==1: 5 | return 1 6 | else: 7 | return fib(n-1)+fib(n-2) 8 | if __name__=="__main__": 9 | n=3 10 | print('你有输入出错{}次的机会'.format(n)) 11 | while True: 12 | if n>0: 13 | number=input('请输入要输出多少项斐波那契数:') 14 | if number<1: 15 | n-=1 16 | print ('你输入的数字小于1,请输入大于1的数字,你还剩余%s次机会了'%n) 17 | else: 18 | for i in range(1,number+1): 19 | print fib(i), 20 | print '\n' 21 | else: 22 | break 23 | print ('游戏结束') 24 | -------------------------------------------------------------------------------- /question_4/maxingmin.py: -------------------------------------------------------------------------------- 1 | '''菲波那切数列.''' 2 | 3 | def fibonacci(n): 4 | ''' 5 | 6 | >>> fibonacci(10) 7 | 55 8 | ''' 9 | if n == 0: 10 | return 0 11 | elif n == 1: 12 | return 1 13 | else: 14 | return fibonacci(n-1) + fibonacci(n-2) 15 | 16 | def fibonacci_sequence(n): 17 | ''' 18 | 19 | >>> fibonacci_sequence(10) 20 | [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] 21 | ''' 22 | return [fibonacci(x) for x in range(n)] 23 | -------------------------------------------------------------------------------- /question_4/ralph_q4.md: -------------------------------------------------------------------------------- 1 | # 每日一题 第四题 2 | 用Python实现斐波那契数列 3 | 斐波那契数列由0和1开始,之后的斐波那契系数就是由之前的两数相加而得出, 4 | 例如斐波那契数列的前10个数是 0, 1, 1, 2, 3, 5, 8, 13, 21, 34 5 | 6 | ``` 7 | #!/usr/bin/env python 8 | # -*- coding: utf-8 -*- 9 | class Fibo(object): 10 | 11 | def __init__(self): 12 | pass 13 | 14 | def fib(self, num): 15 | fibo_list = [0] 16 | cnt, x, y = 0, 0, 1 17 | while cnt < num - 1: 18 | fibo_list.append(y) 19 | x, y = y, x + y 20 | cnt += 1 21 | return fibo_list 22 | 23 | fibo = Fibo() 24 | num = int(input("请输入你想得到的斐波那契数列的长度: ")) 25 | print("该数列为: ", fibo.fib(num)) 26 | ``` -------------------------------------------------------------------------------- /question_4/task4.md: -------------------------------------------------------------------------------- 1 | ''' 2 | 斐波那契数列由0和1开始,之后的斐波那契系数就是由之前的两数相加而得出,例如 3 | 斐波那契数列的前10个数是 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。 4 | ''' 5 | def f(n): 6 | if n > 1: 7 | return f(n-1)+f(n-2) 8 | elif n == 1: 9 | return 1 10 | else: 11 | return 0 12 | try: 13 | n = int(input('How many sequence numbers do you want ?')) 14 | if isinstance(n,int) and n >= 0: 15 | for i in range (0,n): 16 | print(f(i),end=' ') 17 | else: 18 | print("Please input an integer not less than 0") 19 | except ValueError as e: 20 | print(e) 21 | 22 | -------------------------------------------------------------------------------- /question_4/zen_of_python_04.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | def fib(num): 4 | n, a, b = 0, 0, 1 5 | while n < num: 6 | yield a 7 | a, b = b, a + b 8 | n = n + 1 9 | 10 | def output(num): 11 | res = [] 12 | for i in fib(num): 13 | res.append(i) 14 | print(res) 15 | 16 | output(10) -------------------------------------------------------------------------------- /ralph/question1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | ''' 6 | 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少, 7 | 例如:有列表 numbers = [10, 29, 30, 41],要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 8 | ''' 9 | 10 | 11 | numbers = [10, 29, 30, 41] 12 | for key, value in enumerate(numbers): 13 | print((key, value)) -------------------------------------------------------------------------------- /ralph/question2.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | ''' 6 | 系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小, 7 | 如果猜中了,则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案。 8 | ''' 9 | 10 | 11 | import random 12 | 13 | 14 | number = random.randint(1, 100) 15 | print("游戏开始!") 16 | chances = 5 17 | while True: 18 | try: 19 | guess = int(input("请输入你的数字: ")) 20 | if guess == number: 21 | break 22 | elif guess > number: 23 | print("大了大了") 24 | else: 25 | print("小了小了") 26 | chances = chances - 1 27 | if chances == 0: 28 | print("太遗憾了,正确答案是%s,你没有猜对。"% number) 29 | break 30 | else: 31 | print("你还有%d次机会,再猜一次吧!" % chances) 32 | except Exception as e: 33 | print("请输入正确的数字格式!!") -------------------------------------------------------------------------------- /ralph/question3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | ''' 6 | 第3题: 7 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 8 | ''' 9 | 10 | 11 | import re 12 | 13 | 14 | class AnalyzeWords(object): 15 | 16 | def __init__(self, filename, num): 17 | self.filename = filename 18 | self.num = num 19 | 20 | def get_word_dict(self): 21 | with open(self.filename, "r") as f: 22 | article = f.read() 23 | words_list = re.split(r'\s*[\s\W]\s*', article) 24 | result_list = [] 25 | words_count = {} 26 | for word in words_list: 27 | word = word.lower() 28 | if word: 29 | if word in result_list: 30 | words_count[word] += 1 31 | else: 32 | words_count[word] = 1 33 | result_list.append(word) 34 | return words_count 35 | 36 | def output_words(self, words_dict): 37 | sorted_list = sorted(words_dict.items(), key=lambda w: w[1], reverse=True) 38 | print("文章中出现频率最多的%s个单词是: " % self.num) 39 | print(sorted_list) 40 | for i in range(0, self.num): 41 | try: 42 | print("第%s" %(i+1), sorted_list[i][0], "%s 次" % sorted_list[i][1]) 43 | i += 1 44 | except Exception as e: 45 | print(e) 46 | 47 | 48 | analyze_words = AnalyzeWords("import_this.txt", 5) 49 | word_dict = analyze_words.get_word_dict() 50 | analyze_words.output_words(word_dict) -------------------------------------------------------------------------------- /ralph/question4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | ''' 6 | 第4题: 7 | 8 | 用Python实现斐波那契数列,费波那契数列由0和1开始,之后的费波那契系数就是由之前的两数相加而得出 9 | ''' 10 | 11 | 12 | class Fibo(object): 13 | 14 | def __init__(self): 15 | pass 16 | 17 | def fib(self, num): 18 | fibo_list = [0] 19 | cnt, x, y = 0, 0, 1 20 | while cnt < num - 1: 21 | fibo_list.append(y) 22 | x, y = y, x + y 23 | cnt += 1 24 | return fibo_list 25 | 26 | fibo = Fibo() 27 | num = int(input("请输入你想得到的斐波那契数列的长度: ")) 28 | print("该数列为: ", fibo.fib(num)) -------------------------------------------------------------------------------- /ralph/question5.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | 4 | 5 | ''' 6 | 问题:设计一个算法,将URL转换成5部分, 7 | 例如 8 | url = "http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect" 9 | 解析后得到: 10 | scheme='http' 11 | netloc='mp.weixin.qq.com' 12 | path='/s' 13 | query_params='__biz=MzA4MjEyNTA5Mw==&mid=2652566513' 14 | fragment='wechat_redirect' 15 | 注意,query_params 要转换成字典类型 16 | ''' 17 | 18 | 19 | from collections import namedtuple 20 | import re 21 | 22 | 23 | class URL(object): 24 | 25 | def __init__(self): 26 | # 定义namedtuple类 27 | self.URL = namedtuple('URL', ['scheme', 'netloc', 'path', 'query_params', 'fragment']) 28 | 29 | def url_parse(self, url): 30 | scheme = self.get_scheme(url) 31 | netloc = self.get_netloc(url) 32 | path = self.get_path(url) 33 | query_params = self.get_query_params(url) 34 | fragment = self.get_fragment(url) 35 | # 实例化namedtuple对象 36 | url = self.URL(scheme=scheme, netloc=netloc, path=path, query_params=query_params, fragment=fragment) 37 | return url 38 | 39 | def get_scheme(self, url): 40 | # 如果有://说明写出了scheme,否则默认为http 41 | if '://' in url: 42 | return url.split('://')[0] 43 | return 'http' 44 | 45 | def get_netloc(self, url): 46 | # 获取netloc 47 | pat = re.compile('[^\/](\w+\.)+\w+') 48 | return pat.search(url).group() 49 | 50 | def get_path(self, url): 51 | # 获取path,如果没有,返回空 52 | pat = re.compile(r'\w(\/)(.*)\?') 53 | path = pat.search(url) 54 | if path: 55 | return path.group(2) 56 | return 57 | 58 | def get_query_params(self, url): 59 | params_dict = {} 60 | # 如果有?说明有query_params参数 否则返回空{} 61 | if '?' in url: 62 | if '#' in url: 63 | pat = re.compile(r'\?(.*)\#') 64 | params = pat.search(url).group(1) 65 | else: 66 | params = url.split('?')[1] 67 | for param in params.split('&'): 68 | key = param.split('=')[0] 69 | value = param.split('=')[1] 70 | params_dict[key] = value 71 | return params_dict 72 | 73 | def get_fragment(self, url): 74 | # 如果有#,说明有fragment,否则返回空 75 | if '#' in url: 76 | return url.split('#')[1] 77 | return 78 | 79 | 80 | if __name__ == '__main__': 81 | url_ps = URL() 82 | urls = ['http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect', 83 | 'https://www.google.com/search?ei=epYGWpzOF8La0gKe4Kl4&q=dota2&oq=dota2', 84 | 'www.google.com', 85 | ] 86 | try: 87 | for url in urls: 88 | print(url_ps.url_parse(url)) 89 | except AttributeError: 90 | print("url不合法") -------------------------------------------------------------------------------- /ralph/question6.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | ''' 4 | 第6题 5 | 6 | 设计一个程序,用于统计一个项目中的代码数,包括文件个数,代码行数,注释行数,空行行数。尽量设计灵活一点可以通过输入不同参数来统计不同语言的项目 7 | is 8 | 例如执行: 9 | ``` 10 | # type用于指定文件类型 11 | python counter.py --type python 12 | ``` 13 | 14 | 输出: 15 | 16 | ``` 17 | files:10 18 | code_lines:200 19 | comments:100 20 | blanks:20 21 | ''' 22 | 23 | 24 | import os 25 | import sys 26 | 27 | 28 | lang_dict = { 29 | 'python': ['py', '#', "'''", "'''\n"], 30 | 'javascript': ['js', '//', '/*', '*/\n'], 31 | 'java': ['java', '//', '/*', '*/\n'], 32 | 'c': ['c', '//', '/*', '*/\n'], 33 | } 34 | 35 | 36 | class PromCounter(object): 37 | 38 | def __init__(self, dirpath, lang): 39 | ''' 40 | 41 | ''' 42 | self.files = 0 43 | self.code_lines = 0 44 | self.comments = 0 45 | self.blanks = 0 46 | self.dirpath = dirpath 47 | self.file_type = lang_dict[lang][0] 48 | self.single_line_comment = lang_dict[lang][1] 49 | self.multi_start_comment = lang_dict[lang][2] 50 | self.multi_end_comment = lang_dict[lang][3] 51 | 52 | def count(self): 53 | end_comment = True 54 | for dirpath, dirnames, filenames in os.walk(self.dirpath): 55 | for filename in filenames: 56 | if filename.endswith(self.file_type): 57 | self.files += 1 58 | with open(filename, encoding="utf-8") as f: 59 | lines = f.readlines() 60 | for line in lines: 61 | line = line.replace(r'\r\n', r'\n').strip(' ') 62 | if line == '' or line == '\n': 63 | self.blanks += 1 64 | elif line.startswith(self.single_line_comment): 65 | self.comments += 1 66 | elif line.startswith(self.multi_start_comment or self.multi_end_comment): 67 | self.comments += 1 68 | end_comment = not end_comment 69 | elif not end_comment: 70 | self.comments += 1 71 | else: 72 | self.code_lines += 1 73 | count_result = { 74 | 'files': self.files, 75 | 'code_lines': self.code_lines, 76 | 'comments': self.comments, 77 | 'blanks': self.blanks, 78 | } 79 | return count_result 80 | 81 | 82 | if __name__ == "__main__": 83 | if len(sys.argv) != 5: 84 | print("Usage: python3 question6.py --propath [path] --type [language]") 85 | sys.exit() 86 | elif sys.argv[1] != '--propath': 87 | print("this argument should be --propath") 88 | sys.exit() 89 | elif not os.path.isdir(sys.argv[2]): 90 | print("the path is not a folder") 91 | sys.exit() 92 | elif sys.argv[3] != '--type': 93 | print("should start with --") 94 | sys.exit() 95 | elif sys.argv[4] not in lang_dict: 96 | print("language can be python, javascript, java and c. You should input with lowercase.") 97 | sys.exit() 98 | 99 | counter = PromCounter(sys.argv[2], sys.argv[4]) 100 | result = counter.count() 101 | print('files' + ':' + str(result['files']) + '\n' + 102 | 'code_lines' + ':' + str(result['code_lines']) + '\n' + 'comments' + ':' + str(result['comments']) + 103 | '\n' + 'blanks' + ':' + str(result['blanks'])) 104 | -------------------------------------------------------------------------------- /rui/question2.py: -------------------------------------------------------------------------------- 1 | #-*-coding:utf-8-*- 2 | import random 3 | 4 | for i in range(5): 5 | right_number = random.randint(1,100) 6 | guess_number = int(input("please enter a number:")) 7 | if right_number == guess_number: 8 | print("you win!!!") 9 | break 10 | elif guess_number > right_number: 11 | print('your guess_number is bigger') 12 | continue 13 | elif guess_number < right_number: 14 | print('your guess_number is smaller') 15 | continue 16 | -------------------------------------------------------------------------------- /rui/question3.py: -------------------------------------------------------------------------------- 1 | import collections 2 | 3 | def find_words(path,number): 4 | with open(path) as f: 5 | str = f.read().split(' ') 6 | str_conter = collections.Counter(str).most_common(number) 7 | 8 | for str in str_conter: 9 | print(str[0]) 10 | 11 | 12 | 13 | if __name__ == '__main__': 14 | path = 'import_this.txt' 15 | number = 5 16 | find_words(path,number) 17 | -------------------------------------------------------------------------------- /rui/question4.py: -------------------------------------------------------------------------------- 1 | #-*-coding:utf-8-*- 2 | 3 | def fibonaci(n): 4 | if n == 0: 5 | return 0 6 | elif n == 1: 7 | return 1 8 | else: 9 | return fibonaci(n-1) + fibonaci(n-2) 10 | 11 | 12 | 13 | if __name__ == '__main__': 14 | n = 10 15 | numbers = [] 16 | for i in range(n): 17 | numbers.append(fibonaci(i)) 18 | print(numbers) 19 | -------------------------------------------------------------------------------- /rui/question5: -------------------------------------------------------------------------------- 1 | from collections import namedtuple 2 | 3 | 4 | class URL(): 5 | 6 | 7 | def get_params(slef,query_params): 8 | param_dict = {} 9 | params = [] 10 | param1_pos = query_params.index('=') 11 | param1 = query_params[:param1_pos] 12 | query_params = query_params[param1_pos+1:] 13 | param_dict.setdefault(param1,[]).append(query_params) 14 | param1_pos = query_params.index('&') 15 | query_params = query_params[param1_pos+1:] 16 | param_dict.setdefault(param1,[]).append(query_params) 17 | return param_dict 18 | 19 | 20 | 21 | 22 | def url_parse(self,url): 23 | frage_pos = url.index('#') 24 | fragement = url[frage_pos+1:] 25 | query_pos = url.index('?') 26 | query_params = url[query_pos+1:frage_pos] 27 | query_dict = {} 28 | query_dict = self.get_params(query_params) 29 | path_pos_begin = url.rindex('/') 30 | path_pos_end = url.index('?') 31 | path = url[path_pos_begin:path_pos_end] 32 | netloc_pos_begin = url.index('/') 33 | netloc = url[netloc_pos_begin+2:path_pos_begin] 34 | scheme = url[:netloc_pos_begin-1] 35 | Url = namedtuple('Url','scheme netloc path query_params fragement') 36 | return Url(scheme=scheme,netloc=netloc,path=path,query_params=query_dict,fragement=fragement) 37 | 38 | 39 | 40 | 41 | if __name__ == '__main__': 42 | url_str = 'http://mp.weixin.qq.com/s?__biz=MzA4MjEyNTA5Mw==&mid=2652566513#wechat_redirect' 43 | url = URL() 44 | parsed_url = url.url_parse(url_str) 45 | -------------------------------------------------------------------------------- /shuaidi/question01.py: -------------------------------------------------------------------------------- 1 | def print_index_value_pair_for_list(in_list): 2 | if not isinstance(in_list, list): 3 | raise TypeError(f"print_index_value_pair_for_list() takes a list ({type(in_list)} given)") 4 | 5 | length = len(in_list) 6 | 7 | if length == 0: 8 | print("()") 9 | return None 10 | 11 | list_for_print = [] # prepare elements to print 12 | for i in range(0, length-1): 13 | list_for_print.append(f"({i}, {in_list[i]}), ") 14 | 15 | # handle the last element 16 | list_for_print.append(f"({length-1}, {in_list[length-1]})") 17 | 18 | print("".join(list_for_print)) 19 | 20 | # invoke to test print_index_value_pair_for_list() 21 | in_param = ["a", "b", "c"] 22 | print_index_value_pair_for_list(in_param) 23 | -------------------------------------------------------------------------------- /shuaidi/question02.py: -------------------------------------------------------------------------------- 1 | from random import randint 2 | from sys import exit 3 | 4 | min_of_target = 0 5 | max_of_target = 100 6 | target = randint(min_of_target,max_of_target) 7 | chances = 7 8 | 9 | print("Welcome to guess number game!") 10 | print(f"You have {chances} chances to guess the number, which is range from {min_of_target} to {max_of_target}.") 11 | print("Each time you guessed, you will get a hint about that your number is greater or smaller, until you guesss it or you use up all {chances} chances.") 12 | print("Are you ready? (y or n)") 13 | is_ready = input("> ") 14 | while(True): 15 | if is_ready == "y": 16 | print("Let's begin.") 17 | break 18 | elif is_ready == "n": 19 | print("Bye") 20 | exit(0) 21 | else: 22 | print("Are you ready? (y or n)") 23 | is_ready = input("> ") 24 | 25 | 26 | for i in range(0, chances): 27 | print(f"Now, you have {chances-i} chance(s), please input your number.") 28 | input_number = None 29 | while(True): 30 | try: 31 | input_str = input("> ") 32 | input_number = int(input_str) 33 | break 34 | except ValueError: 35 | print(f"Please input a NUMBER, {input_str} is not a number.") 36 | if i == chances-1 and input_number != target: 37 | print(f"You don't guess it, but you already use up all chances, the target number is {target}.") 38 | exit(0) 39 | elif input_number == target: 40 | print(f"Congratulations! The target number is {input_number}") 41 | exit(0) 42 | else: 43 | if input_number > target: 44 | print(f"Your number {input_number} is greater than the target, pleas try again.") 45 | elif input_number < target: 46 | print(f"Your number {input_number} is less than the target, pleas try again.") 47 | -------------------------------------------------------------------------------- /suixinlu/__init__.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | __title__ = '' 5 | __author__ = 'gz' 6 | __mtime__ = '2017/11/7' 7 | # code is far away from bugs with the god animal protecting 8 | I love animals. They taste delicious. 9 | ┏┓ ┏┓ 10 | ┏┛┻━━━┛┻┓ 11 | ┃ ☃ ┃ 12 | ┃ ┳┛ ┗┳ ┃ 13 | ┃ ┻ ┃ 14 | ┗━┓ ┏━┛ 15 | ┃ ┗━━━┓ 16 | ┃ 神兽保佑 ┣┓ 17 | ┃ 永无BUG! ┏┛ 18 | ┗┓┓┏━┳┓┏┛ 19 | ┃┫┫ ┃┫┫ 20 | ┗┻┛ ┗┻┛ 21 | """ -------------------------------------------------------------------------------- /suixinlu/question1.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | __title__ = '' 5 | __author__ = 'gz' 6 | __mtime__ = '2017/11/7' 7 | # code is far away from bugs with the god animal protecting 8 | I love animals. They taste delicious. 9 | ┏┓ ┏┓ 10 | ┏┛┻━━━┛┻┓ 11 | ┃ ☃ ┃ 12 | ┃ ┳┛ ┗┳ ┃ 13 | ┃ ┻ ┃ 14 | ┗━┓ ┏━┛ 15 | ┃ ┗━━━┓ 16 | ┃ 神兽保佑 ┣┓ 17 | ┃ 永无BUG! ┏┛ 18 | ┗┓┓┏━┳┓┏┛ 19 | ┃┫┫ ┃┫┫ 20 | ┗┻┛ ┗┻┛ 21 | """ 22 | def test1(): 23 | numbers = [10, 29, 30, 41] 24 | for index,value in enumerate(numbers): 25 | print("("+str(index)+","+str(value)+")") 26 | test1() -------------------------------------------------------------------------------- /suixinlu/question3.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | __title__ = '' 5 | __author__ = 'gz' 6 | __mtime__ = '2017/11/2' 7 | # code is far away from bugs with the god animal protecting 8 | I love animals. They taste delicious. 9 | ┏┓ ┏┓ 10 | ┏┛┻━━━┛┻┓ 11 | ┃ ☃ ┃ 12 | ┃ ┳┛ ┗┳ ┃ 13 | ┃ ┻ ┃ 14 | ┗━┓ ┏━┛ 15 | ┃ ┗━━━┓ 16 | ┃ 神兽保佑 ┣┓ 17 | ┃ 永无BUG! ┏┛ 18 | ┗┓┓┏━┳┓┏┛ 19 | ┃┫┫ ┃┫┫ 20 | ┗┻┛ ┗┻┛ 21 | """ 22 | import string 23 | path = 'import_this.txt' 24 | with open(path,'r') as text: 25 | words = [raw_word.strip(string.punctuation).lower() for raw_word in text.read().split()] 26 | words_index = set(words) 27 | counts_dict = {index:words.count(index) for index in words_index} 28 | 29 | for word in sorted(counts_dict,key=lambda x:counts_dict[x],reverse=True): 30 | print('{}-{} 次'.format(word,counts_dict[word])) -------------------------------------------------------------------------------- /suixinlu/question4.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | # -*- coding: utf-8 -*- 3 | """ 4 | __title__ = '' 5 | __author__ = 'gz' 6 | __mtime__ = '2017/11/7' 7 | # code is far away from bugs with the god animal protecting 8 | I love animals. They taste delicious. 9 | ┏┓ ┏┓ 10 | ┏┛┻━━━┛┻┓ 11 | ┃ ☃ ┃ 12 | ┃ ┳┛ ┗┳ ┃ 13 | ┃ ┻ ┃ 14 | ┗━┓ ┏━┛ 15 | ┃ ┗━━━┓ 16 | ┃ 神兽保佑 ┣┓ 17 | ┃ 永无BUG! ┏┛ 18 | ┗┓┓┏━┳┓┏┛ 19 | ┃┫┫ ┃┫┫ 20 | ┗┻┛ ┗┻┛ 21 | """ 22 | 23 | 24 | def fib(n): 25 | if n == 1: 26 | return 0 27 | elif n == 2: 28 | return 1 29 | else: 30 | return fib(n - 1) + fib(n - 2) 31 | 32 | 33 | def each_item(items): 34 | for item in range(1, items + 1): 35 | print('%d,' % fib(item), end='') 36 | print('......') 37 | 38 | print(each_item(10)) 39 | -------------------------------------------------------------------------------- /sunshiqi/question1.md: -------------------------------------------------------------------------------- 1 | numbers = [10, 29, 30, 41] 2 | 3 | new_dic = {} 4 | for keys,item in enumerate(numbers): 5 | new_dic[keys] = numbers[keys] 6 | 7 | print new_dic.items() -------------------------------------------------------------------------------- /sunshiqi/question2.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | __title__ = '' 4 | __author__ = 'Administrator' 5 | __mtime__ = '2017/10/31 0031' 6 | # code is far away from bugs with the god animal protecting 7 | I love animals. They taste delicious. 8 | ┏┓ ┏┓ 9 | ┏┛┻━━━┛┻┓ 10 | ┃ ☃ ┃ 11 | ┃ ┳┛ ┗┳ ┃ 12 | ┃ ┻ ┃ 13 | ┗━┓ ┏━┛ 14 | ┃ ┗━━━┓ 15 | ┃ 神兽保佑 ┣┓ 16 | ┃ 永无BUG! ┏┛ 17 | ┗┓┓┏━┳┓┏┛ 18 | ┃┫┫ ┃┫┫ 19 | ┗┻┛ ┗┻┛ 20 | """ 21 | import random 22 | 23 | class GuessValue(): 24 | def __init__(self, min_num, max_num, choice): 25 | self.min_num = min_num 26 | self.max_num = max_num 27 | self.choice = choice 28 | self.target = random.randint(min_num, max_num) 29 | 30 | def guess(self): 31 | choice = self.choice 32 | 33 | while choice > 0: 34 | choice -= 1 35 | try: 36 | num = int(input('请输入幸运数字:')) 37 | except ValueError: 38 | print('请输入整数') 39 | continue 40 | 41 | if num == self.target: 42 | print('恭喜你猜中了!') 43 | break 44 | elif num < self.target: 45 | print('猜小了,你还有%d次机会' % choice) 46 | else: 47 | print('猜小了,你还有%d次机会' % choice) 48 | else: 49 | print('很遗憾,%d次机会都用光了,正确的数字是%d' % (self.choice, self.target)) 50 | 51 | if __name__ == '__main__': 52 | game = GuessValue(1, 100, 5) 53 | game.guess() -------------------------------------------------------------------------------- /sunshiqi/question3.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | __title__ = 'q3.py' 4 | __author__ = 'sunshiqisky' 5 | __mtime__ = '2017/11/1 0001' 6 | # code is far away from bugs with the god animal protecting 7 | I love animals. They taste delicious. 8 | ┏┓ ┏┓ 9 | ┏┛┻━━━┛┻┓ 10 | ┃ ☃ ┃ 11 | ┃ ┳┛ ┗┳ ┃ 12 | ┃ ┻ ┃ 13 | ┗━┓ ┏━┛ 14 | ┃ ┗━━━┓ 15 | ┃ 神兽保佑 ┣┓ 16 | ┃ 永无BUG! ┏┛ 17 | ┗┓┓┏━┳┓┏┛ 18 | ┃┫┫ ┃┫┫ 19 | ┗┻┛ ┗┻┛ 20 | """ 21 | 22 | import re 23 | from collections import Counter 24 | 25 | filesource = 'import_this.txt' 26 | 27 | def getword(checkfile,checknum): 28 | pattern = r'''[a-zA-z]+''' 29 | with open(checkfile) as f: 30 | words = re.findall(pattern, f.read()) 31 | return Counter(words).most_common(checknum) 32 | 33 | if __name__ == '__main__': 34 | print(getword(filesource, 5)) 35 | -------------------------------------------------------------------------------- /sunshiqi/question4.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | """ 3 | __title__ = '' 4 | __author__ = 'Administrator' 5 | __mtime__ = '2017/11/6 0006' 6 | # code is far away from bugs with the god animal protecting 7 | I love animals. They taste delicious. 8 | ┏┓ ┏┓ 9 | ┏┛┻━━━┛┻┓ 10 | ┃ ☃ ┃ 11 | ┃ ┳┛ ┗┳ ┃ 12 | ┃ ┻ ┃ 13 | ┗━┓ ┏━┛ 14 | ┃ ┗━━━┓ 15 | ┃ 神兽保佑 ┣┓ 16 | ┃ 永无BUG! ┏┛ 17 | ┗┓┓┏━┳┓┏┛ 18 | ┃┫┫ ┃┫┫ 19 | ┗┻┛ ┗┻┛ 20 | """ 21 | class Fibonacci(): 22 | def __init__(self, number): 23 | self.number = number 24 | 25 | def check_for_Fib(self): 26 | if not isinstance(self.number,int): 27 | print('please input the integer') 28 | return False 29 | self.number = int(self.number) 30 | if self.number < 0: 31 | print('Your input should be greater than zero') 32 | return False 33 | return True 34 | 35 | def count_for_Fib(self): 36 | if not self.check_for_Fib(): 37 | return 38 | n, a, b = 0, 0, 1 39 | while n < self.number: 40 | yield a 41 | a, b = b, a+b 42 | n = n + 1 43 | 44 | def display_for_Fib(self): 45 | if self.number == 0: 46 | print(self.number) 47 | elif self.number == 1: 48 | print(self.number) 49 | else: 50 | for num in self.count_for_Fib(): 51 | print(num) 52 | 53 | if __name__ == "__main__": 54 | fib = Fibonacci(10) 55 | fib.display_for_Fib() -------------------------------------------------------------------------------- /totaljfb/Q1.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: module1 3 | # Purpose: 4 | # 5 | # Author: Jason Zhang 6 | # 7 | # Created: 05/12/2017 8 | # Copyright: (c) Jason Zhang 2017 9 | # Licence: 10 | #------------------------------------------------------------------------------- 11 | 12 | def main(): 13 | pass 14 | 15 | if __name__ == '__main__': 16 | main() 17 | 18 | #question 1 is to get familiar with enumrate function 19 | numbers = [10, 29, 30, 41] 20 | for index, value in enumerate(numbers): 21 | print(index,value) 22 | -------------------------------------------------------------------------------- /totaljfb/Q2.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: module1 3 | # Purpose: 4 | # 5 | # Author: Jason Zhang 6 | # 7 | # Created: 08/12/2017 8 | # Copyright: (c) Jason Zhang 2017 9 | # Licence: 10 | #------------------------------------------------------------------------------- 11 | 12 | def main(): 13 | pass 14 | 15 | if __name__ == '__main__': 16 | main() 17 | #Question 2 18 | #a function to validate the input and return the input as an integer 19 | def input_validation(): 20 | input_number = input("Please enter a number to guess: ") 21 | while(True): 22 | try: 23 | given_number = int(input_number) 24 | return given_number 25 | except ValueError: 26 | input_number = input("Please enter an integer: ") 27 | import random 28 | random_number = random.randint(1,100) 29 | the_input = input_validation() 30 | #two conditions make the guess over, guess is correct and under 5 times 31 | guess_correct = False 32 | n = 4 33 | while(not guess_correct and n != 0): 34 | if the_input > random_number: 35 | print("Your number is greater, try again, " +str(n)+ " time(s) left to guess.") 36 | n -= 1 37 | the_input = input_validation() 38 | elif the_input < random_number: 39 | print("Your number is smaller, try again, " +str(n)+ " time(s) left to guess.") 40 | n -= 1 41 | the_input = input_validation() 42 | else: 43 | print("You got the number! It's", the_input) 44 | print("You have used " + str(5-n) + " times to get it.") 45 | guess_correct = True 46 | #when n = 0, while loop quits, check the last guess below: 47 | if guess_correct == False: 48 | if the_input == random_number: 49 | print("You got the number! It's", the_input) 50 | print("You have used " + str(5-n) + " times to get it.") 51 | else: 52 | print("Sorry, you need more luck to guess, the number is " + str(random_number)) 53 | 54 | -------------------------------------------------------------------------------- /totaljfb/Q3.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: module1 3 | # Purpose: 4 | # 5 | # Author: Jason Zhang 6 | # 7 | # Created: 17/12/2017 8 | # Copyright: (c) Jason Zhang 2017 9 | # Licence: 10 | #------------------------------------------------------------------------------- 11 | 12 | def main(): 13 | pass 14 | 15 | if __name__ == '__main__': 16 | main() 17 | #Q3 18 | import os 19 | import collections 20 | import re 21 | 22 | #define a function to read and store the text as a list 23 | def read_text(file): 24 | #open the file and read as a string 25 | #need some time to study on encoding... 26 | f = open(file,encoding="ascii", errors="surrogateescape") 27 | file_string = f.read() 28 | #convert the string to a list 29 | word_list = file_string.split() 30 | #use regular expression to remove non-word items in the list 31 | regex = re.compile(r'\w+') 32 | for item in word_list: 33 | if not regex.match(item): 34 | word_list.remove(item) 35 | f.close() 36 | return word_list 37 | ''' 38 | define a function to get the top n most counts items 39 | ''' 40 | def most_occurrences_word(input_list,n): 41 | c = collections.Counter(input_list) 42 | return c.most_common()[0:n] 43 | 44 | #program starts here 45 | #validate the input 46 | text_file = input("Plase enter the text to summarize: ") 47 | while not os.path.isfile(text_file): 48 | text_file = input("Plase enter a vaild file: ") 49 | in_list = read_text(text_file) 50 | occurences_list = most_occurrences_word(in_list,5) 51 | 52 | #show result 53 | for item in occurences_list: 54 | print(item) 55 | 56 | 57 | 58 | -------------------------------------------------------------------------------- /totaljfb/Q5.py: -------------------------------------------------------------------------------- 1 | #------------------------------------------------------------------------------- 2 | # Name: module1 3 | # Purpose: 4 | # 5 | # Author: Jason Zhang 6 | # 7 | # Created: 15/11/2017 8 | # Copyright: (c) Jason Zhang 2017 9 | # Licence: 10 | #------------------------------------------------------------------------------- 11 | 12 | def main(): 13 | pass 14 | 15 | if __name__ == '__main__': 16 | main() 17 | import re 18 | 19 | #create a URL class 20 | class URL: 21 | def __init__(self, url_scheme, url_netloc, url_path, url_query_params, url_fragment): 22 | self.scheme = url_scheme 23 | self.netloc = url_netloc 24 | self.path = url_path 25 | self.query_params = url_query_params 26 | self.fragment = url_fragment 27 | def display_result(self): 28 | print 'scheme: ' + self.scheme 29 | print 'netloc: ' + self.netloc 30 | print 'path: ' + self.path 31 | print 'query_params: '+ str(self.query_params) 32 | print 'fragment: '+ self.fragment 33 | 34 | #the parsing function to parse the url address 35 | def url_parse(url): 36 | regex = re.compile(r'''( 37 | [^:^\/]*)? #scheme, group 1, ':' and '/' excluded 38 | (:)? #separator ':', group 2 39 | (\/\/)? #separator '//', group 3 40 | ([^\/]*)? #netloc, '/' excluded, group 4 41 | (\/)? #separator '/'. group 5 42 | ([^\?]*)? #path, '?' excluded, group 6 43 | (\?)? #separator '\', group 7 44 | ([^\#]*)? #query_params, group 8 45 | (\#)? #separator '#', group 9 46 | ([^\#]* #fragment, '#' excluded, group 10 47 | )?''',re.VERBOSE) 48 | result = regex.match(url) 49 | #deal with the optional sections if any of them are not available 50 | if result.group(10) == '' or result.group(10) is None: 51 | fragment = 'NA' 52 | else: 53 | fragment = result.group(10) 54 | if result.group(8) == '' or result.group(8) is None: 55 | query_params = 'NA' 56 | else: 57 | query_params = parse_url_query(result.group(8)) 58 | if result.group(6) == '' or result.group(6) is None: 59 | path = 'NA' 60 | else: 61 | path = '/' + result.group(6) 62 | if result.group(4) == '' or result.group(4) is None: 63 | netloc = 'NA' 64 | else: 65 | netloc = result.group(4) 66 | if result.group(1) == '' or result.group(1) is None: 67 | scheme = 'NA' 68 | else: 69 | scheme = result.group(1) 70 | print result.groups() 71 | return URL(scheme,netloc,path,query_params,fragment) 72 | #define the function to parse the url query strings 73 | #easier to use string split method than regular expression? 74 | def parse_url_query(query_string): 75 | query_params = {} 76 | dic_pair_list = query_string.split('&') 77 | for each_item in dic_pair_list: 78 | query_params[each_item.split('=',1)[0]] = each_item.split('=',1)[1] 79 | return query_params 80 | url = raw_input("Enter an url address to parse: ") 81 | test = url_parse(url) 82 | test.display_result() 83 | 84 | -------------------------------------------------------------------------------- /tttt.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pythonzhichan/DailyQuestion/267779109e2f31e42c7bf25512316bbc57f97afd/tttt.py -------------------------------------------------------------------------------- /vimiix/question5.py: -------------------------------------------------------------------------------- 1 | #coding=utf-8 2 | __author__ = 'vimiix' 3 | 4 | class URL(object): 5 | 6 | def __init__(self, url): 7 | self.url = url 8 | self.scheme = None 9 | self.netloc = None 10 | self.path = None 11 | self.query_params = {} 12 | self.fregment = None 13 | 14 | def parse(self): 15 | if '://' in self.url: 16 | self.scheme, tail = self.url.split('://') 17 | else: 18 | tail = self.url 19 | if '/' in tail: 20 | sep = tail.find('/') 21 | self.netloc = tail[:sep] 22 | tail = tail[sep:] 23 | else: 24 | self.netloc = tail 25 | if '#' in tail: 26 | tail, fregment = tail.split('#') 27 | self.fregment = fregment if fregment else None 28 | if '?' in tail: 29 | self.path, tail = tail.split('?') 30 | if not tail: 31 | self.query_params = None 32 | else: 33 | params = tail.split('&') if '&' in tail else [tail] 34 | for item in params: 35 | sep = item.find('=') 36 | key = item[:sep] if sep > -1 else item 37 | val = item[sep+1:] if sep > -1 else None 38 | self.query_params.update({key : val}) 39 | else: 40 | self.path = tail 41 | 42 | def pack_result(self): 43 | return ''' 44 | scheme={scheme}\n 45 | netloc={netloc}\n 46 | path={path}\n 47 | query_params={query_params}\n 48 | fregment={fregment}\n 49 | '''.format( 50 | scheme = self.scheme, 51 | netloc=self.netloc, 52 | path = self.path, 53 | query_params = self.query_params, 54 | fregment = self.fregment 55 | ) 56 | 57 | 58 | def parse_url(url): 59 | url_instance = URL(url) 60 | url_instance.parse() 61 | result = url_instance.pack_result() 62 | return result 63 | 64 | 65 | if __name__ == "__main__": 66 | src_url = raw_input("Please input url:").strip() 67 | print parse_url(src_url) -------------------------------------------------------------------------------- /wangdemiao/dailywork_1.py: -------------------------------------------------------------------------------- 1 | #每日一题第一题 2 | 3 | numbers=[10,29,30,41] 4 | for i in range(len(numbers)): 5 | print("(%d,%d)" % (i,numbers[i])) 6 | -------------------------------------------------------------------------------- /xiaoxuan/Question_4.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | 3 | def Fib(n): 4 | if n == 0: 5 | return 0 6 | elif n == 1: 7 | return 1 8 | elif n >= 2: 9 | return Fib(n - 1) + Fib(n - 2) 10 | 11 | def sequence(n): 12 | seq = [] 13 | for num in range(n + 1): 14 | seq.append(Fib(num)) 15 | print seq 16 | 17 | 18 | if __name__== "__main__": 19 | sequence(20) -------------------------------------------------------------------------------- /xuehua/GuessNumber.md: -------------------------------------------------------------------------------- 1 | import random 2 | 3 | class GuessGame: 4 | def __init__(self, min_num, max_num, choice): 5 | """ 6 | 7 | :param min_num: 最小值 8 | :param max_num: 最大值 9 | :param choice: 中奖机会 10 | """ 11 | 12 | self.max_num = max_num 13 | self.min_num = min_num 14 | self.target = random.randint(min_num, max_num) 15 | self.choice = choice 16 | 17 | def guess(self): 18 | """ 19 | 猜数字 20 | """ 21 | choice = self.choice 22 | 23 | while choice > 0: 24 | choice -= 1 25 | try: 26 | num = int(input("输入幸运数字:")) 27 | except ValueError as e: 28 | print("请输入有效数字") 29 | continue 30 | 31 | if num == self.target: 32 | print("恭喜你猜中了") 33 | break 34 | elif num <= self.target: 35 | print("你猜的数字太小了,还剩 %d 次机会" % choice) 36 | else: 37 | print("你猜的数字太大,还剩 %d 次机会" % choice) 38 | else: 39 | print("很遗憾,%d 次机会都用完了,只差一点点就猜中了,正确答案是 %d" % (self.choice, self.target)) 40 | 41 | 42 | if __name__ == '__main__': 43 | game = GuessGame(1, 100, 5) 44 | # print(game.target) 45 | game.guess() -------------------------------------------------------------------------------- /xuehua/question1.md: -------------------------------------------------------------------------------- 1 | ''' 2 | # 第1题: 3 | 4 | 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少, 5 | 例如: 6 | 有列表 numbers = [10, 29, 30, 41],要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 7 | ''' 8 | 9 | numbers = [10 , 29 , 30 , 41] 10 | 11 | for i in range(0,len(numbers)): 12 | newnumbers = (i , numbers[i]) 13 | print(newnumbers) 14 | 15 | -------------------------------------------------------------------------------- /xuehua/question4.md: -------------------------------------------------------------------------------- 1 | # -*- coding : UTF-8 -*- 2 | 3 | nums = int(input("你需要几项(1~50)?")) 4 | 5 | # 第一和第二项 6 | Fibo_1 = 0 7 | Fibo_2 = 1 8 | count = 2 9 | 10 | # 判断输入的值是否合法 11 | if nums <= 0 or nums >= 51 : 12 | print("请输入一个不大于50的正整数。") 13 | elif nums == 1: 14 | print("斐波那契数列:") 15 | print(Fibo_1) 16 | else: 17 | print("斐波那契数列:") 18 | print(Fibo_1,",",Fibo_2,end=" , ") 19 | while count < nums: 20 | Fibo = Fibo_1 + Fibo_2 21 | print(Fibo,end=" , ") 22 | # 更新值 23 | Fibo_1 = Fibo_2 24 | Fibo_2 = Fibo 25 | count += 1 -------------------------------------------------------------------------------- /xuehua/question5.md: -------------------------------------------------------------------------------- 1 | # Python 3 2 | 3 | from urllib.parse import urlparse 4 | 5 | url = str(input('Please input your URL : \n')) 6 | url = urlparse(url) 7 | 8 | print('scheme : ',url.scheme) 9 | print('netloc : ',url.netloc) 10 | print('path : ',url.path) 11 | print('params : ',url.params) 12 | print('query : ',url.query) 13 | print('fragment : ',url.fragment) 14 | -------------------------------------------------------------------------------- /zhaopengfei/question1.md: -------------------------------------------------------------------------------- 1 | 在使用 for 循环迭代一个列表时,有时我们需要获取列表中每个元素所在的下标位置是多少,例如:有列表 numbers = [10, 29, 30, 41],要求输出 (0, 10),(1, 29),(2, 30),(3, 41) 2 | 3 | numbers = [10, 29, 30, 41] 4 | for i in enumerate(numbers): 5 | print(i) -------------------------------------------------------------------------------- /zhaopengfei/question2.md: -------------------------------------------------------------------------------- 1 | # 每日一题 第2题: 2 | 3 | 设计一个猜数字的游戏,系统随机生成一个1~100之间的整数,玩家有5次机会,每猜一次系统就会提示玩家该数字是偏大还是偏小,如果猜中了,则告知玩家并提前结束游戏,如果5次都没猜中,结束游戏并告知正确答案。 4 | 5 | ```python 6 | import random 7 | secret = random.randint(1, 100) # 生成随机数 8 | 9 | time = 5 # 猜数字的次数 10 | guess = 0 # 输入的数字 11 | minNum = 0 # 最小随机数 12 | maxNum = 100 # 最大随机数 13 | print("---------欢迎来到猜数字的地方,请开始---------") 14 | while guess!=secret and time>=0:#条件 15 | guess = int(input("*数字区间0-100,请输入你猜的数字:")) 16 | print("你输入数字是:", guess) 17 | if guess == secret: 18 | print("猜对了,真厉害") 19 | else: 20 | # 当不等于的时候,还需要打印出相应的区间,让用户更容易使用 21 | if guess < secret: 22 | minNum = guess 23 | print("你的猜数小于正确答案") 24 | print("现在的数字区间是:", minNum, "-", maxNum) 25 | else: 26 | maxNum = guess 27 | print("你的猜数大于正确答案") 28 | print("数字区间是:", minNum, "-", maxNum) 29 | print("太遗憾了,你猜错了,你还有", time, "次机会") 30 | time -= 1 31 | print("游戏结束!正确数字是:" + str(secret)) 32 | ``` 33 | -------------------------------------------------------------------------------- /zhaopengfei/question3.md: -------------------------------------------------------------------------------- 1 | 2 | ## 每日一题 # 第3题: 3 | 统计一个文件中每个单词出现的次数,列出出现频率最多的5个单词。 4 |
 5 | from collections import Counter
 6 | import re
 7 | 
 8 | filesource = 'c:\ces\\test.txt'
 9 | 
10 | def getword(source):
11 | 
12 |     pattern = r'[a-zA-z]+'
13 | 
14 |     with open(source) as f:
15 |         r = re.findall(pattern, f.read())
16 |         return Counter(r).most_common(5)
17 | 
18 | if __name__ == '__main__':
19 |     print(getword(filesource))
20 | 
21 | 22 | -------------------------------------------------------------------------------- /zhaopengfei/question4.md: -------------------------------------------------------------------------------- 1 | 2 | #每日一题# 第4题: 3 | 终身学习是一本万利的投资,又是新的一周,行动起来 4 | 今天来做一道算法题,用Python实现斐波那契数列 5 | 斐波那契数列由0和1开始,之后的斐波那契系数就是由之前的两数相加而得出, 6 | 例如斐波那契数列的前10个数是 0, 1, 1, 2, 3, 5, 8, 13, 21, 34。用数学方法可定义为如图所示: 7 |
 8 | def fibo(n):
 9 |     if n == 0:
10 |         return 0
11 |     elif n == 1:
12 |         return 1
13 |     else:
14 |         return fibo(n-1)+fibo(n-2)
15 | 
16 | def print_fibo(each):
17 |     for i in range(0,each):
18 |         print("%d," % fibo(i),end='')
19 | 
20 | if __name__ == '__main__':
21 |         while True:
22 |             number = int(input('\n请输入需要输出的斐波那契数列的项数:'))
23 |             print_fibo(number)
24 | 
--------------------------------------------------------------------------------