├── .gitignore
├── .project
├── .pydevproject
├── .settings
├── org.eclipse.core.resources.prefs
└── org.eclipse.ltk.core.refactoring.prefs
├── README.md
├── algorithms
├── __init__.py
└── sort
│ ├── HeapSort.py
│ ├── QuickSort.py
│ └── __init__.py
├── concurrency
├── coroutine
│ ├── __init__.py
│ ├── __pycache__
│ │ └── example03.cpython-35.pyc
│ ├── example01.py
│ ├── example02.py
│ ├── example03.py
│ ├── example04.py
│ ├── example05.py
│ ├── example06.py
│ ├── example07.py
│ ├── example08.py
│ ├── example09.py
│ ├── example10.py
│ └── my father.txt
└── thread
│ ├── myThread.py
│ ├── myThread.pyc
│ ├── prodcons.py
│ ├── producer_customer.py
│ ├── thread_example04.py
│ ├── thread_example05.py
│ └── thread_facfib.py
├── data
├── __init__.py
└── structure
│ ├── ListNode.py
│ ├── __init__.py
│ └── cache
│ ├── LRUCache.py
│ └── __init__.py
├── my father.txt
├── nowcoder
├── __init__.py
└── foroffer
│ ├── Solution1.py
│ ├── Solution10.py
│ ├── Solution11.py
│ ├── Solution12.py
│ ├── Solution2.py
│ ├── Solution3.py
│ ├── Solution4.py
│ ├── Solution5.py
│ ├── Solution6.py
│ ├── Solution7.py
│ ├── Solution8.py
│ ├── Solution9.py
│ └── __init__.py
├── others
├── Quine.py
├── TryTimes.py
└── __init__.py
├── problems
├── __init__.py
└── solution0.py
├── sort
├── SortAlgorithms.py
└── algorithms
│ ├── HeapSort.py
│ └── __pycache__
│ └── HeapSort.cpython-35.pyc
├── test
├── PrimeProducer.py
└── WordCounter.py
├── whxk
├── __init__.py
└── com
│ ├── ContentModifier.py
│ └── __init__.py
└── with
├── with_example01.py
└── with_example02.py
/.gitignore:
--------------------------------------------------------------------------------
1 | .settings
2 | .project
3 | .pydevproject
--------------------------------------------------------------------------------
/.project:
--------------------------------------------------------------------------------
1 |
2 |
3 | HelloPython
4 |
5 |
6 |
7 |
8 |
9 | org.eclipse.wst.common.project.facet.core.builder
10 |
11 |
12 |
13 |
14 | org.python.pydev.PyDevBuilder
15 |
16 |
17 |
18 |
19 |
20 | org.python.pydev.pythonNature
21 | org.eclipse.wst.common.project.facet.core.nature
22 |
23 |
24 |
--------------------------------------------------------------------------------
/.pydevproject:
--------------------------------------------------------------------------------
1 |
2 |
3 | python36
4 | python interpreter
5 |
6 | /${PROJECT_DIR_NAME}
7 |
8 |
9 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.core.resources.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | encoding//concurrency/coroutine/example01.py=utf-8
3 | encoding//concurrency/thread/myThread.py=utf-8
4 | encoding//concurrency/thread/prodcons.py=utf-8
5 | encoding//concurrency/thread/producer_customer.py=utf-8
6 | encoding//concurrency/thread/thread_example04.py=utf-8
7 | encoding//concurrency/thread/thread_example05.py=utf-8
8 | encoding//concurrency/thread/thread_facfib.py=utf-8
9 | encoding//test/PrimeProducer.py=utf-8
10 | encoding//test/WordCounter.py=utf-8
11 | encoding//with/with_example01.py=utf-8
12 | encoding//with/with_example02.py=utf-8
13 | encoding/=UTF-8
14 |
--------------------------------------------------------------------------------
/.settings/org.eclipse.ltk.core.refactoring.prefs:
--------------------------------------------------------------------------------
1 | eclipse.preferences.version=1
2 | org.eclipse.ltk.core.refactoring.enable.project.refactoring.history=false
3 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # 09.24
2 | - 合并算法代码
3 | - 添加一些工程文件至.gitignore
--------------------------------------------------------------------------------
/algorithms/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/algorithms/__init__.py
--------------------------------------------------------------------------------
/algorithms/sort/HeapSort.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月24日
3 |
4 | @author: zwustudy
5 | '''
6 | def heapSort(array):
7 | if not array:
8 | return
9 | length = len(array)
10 | start = length // 2 - 1
11 | """构建大顶堆
12 | """
13 | for i in range(start, -1, -1):
14 | adjustHeap(array, i, length)
15 | """取走堆顶,放到数组最后,把数组最后一个元素放到堆顶,让其下沉,调整成大顶堆
16 | """
17 | for i in range(length - 1, 0, -1):
18 | array[i], array[0] = array[0], array[i]
19 | adjustHeap(array, 0, i)
20 |
21 | """进行堆调整
22 | """
23 | def adjustHeap(array, index, length):
24 | x = 2 * index + 1
25 | while x < length:
26 | if array[x] < array[x + 1] and x + 1 < length:
27 | x = x + 1
28 | if array[index] < array[x]:
29 | """大数往上调整,小数往下调整
30 | """
31 | array[index], array[x] = array[x], array[index]
32 | index = x
33 | x = x * 2 + 1
34 |
35 | def testHeapSort():
36 | lst = [10,20,1,6,6,8,5,2,7,8,9]
37 | heapSort(lst);
38 | for x in lst:
39 | print(x)
40 |
41 | if __name__ == '__main__':
42 | testHeapSort()
--------------------------------------------------------------------------------
/algorithms/sort/QuickSort.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月24日
3 |
4 | @author: minmin
5 | '''
6 |
7 | def quick_sort_algorithms(array, l ,r):
8 | if l < r:
9 | x = array[r]
10 | i = l - 1
11 | for j in range(l, r):
12 | if array[j] < x:
13 | i += 1
14 | array[j], array[i] = array[i], array[j]
15 | array[i + 1], array[r] = array[r], array[i + 1]
16 | quick_sort_algorithms(array, l, i)
17 | quick_sort_algorithms(array, i + 2, r)
18 |
19 | def quick_sort_usual(array, l, r):
20 | if l >= r:
21 | return
22 | low = l
23 | high = r
24 | x = array[low]
25 | while low < high:
26 | while low < high and array[high] >= x:
27 | high -= 1
28 | array[low] = array[high]
29 | while low < high and array[low] <= x:
30 | low += 1
31 | array[high] = array[low]
32 | array[high] = x
33 | quick_sort_usual(array, l, low - 1)
34 | quick_sort_usual(array, low + 1, r)
35 |
36 | def sort0(array, l, r):
37 | if l >= r:
38 | return
39 | key = array[r]
40 | i = l - 1
41 | for x in range(l, r):
42 | if array[x] < key:
43 | i += 1
44 | array[i], array[x] = array[x], array[i]
45 | array[i + 1], array[r] = array[r], array[i + 1]
46 |
47 | #递归的深度不变,但是栈的深度有优化
48 | if 2 * i >= r:
49 | sort0(array, i + 2, r)
50 | sort0(array, l, i)
51 | else:
52 | sort0(array, l, i)
53 | sort0(array, i + 2, r)
54 |
55 | def main():
56 |
57 | array = [10,20,1,6,6,8,5,2,7,8,9]
58 | sort0(array, 0, len(array) - 1)
59 | for x in array:
60 | print(x)
61 |
62 | if __name__ == "__main__":
63 | main()
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
--------------------------------------------------------------------------------
/algorithms/sort/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/algorithms/sort/__init__.py
--------------------------------------------------------------------------------
/concurrency/coroutine/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/concurrency/coroutine/__init__.py
--------------------------------------------------------------------------------
/concurrency/coroutine/__pycache__/example03.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/concurrency/coroutine/__pycache__/example03.cpython-35.pyc
--------------------------------------------------------------------------------
/concurrency/coroutine/example01.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2018年6月21日
4 |
5 | @author: zwustudy
6 |
7 | yield存入数据,通过for循环不断往外读出
8 | '''
9 |
10 | def fib():
11 | a, b = 0, 1
12 | while True and a < 100000:
13 | yield a
14 | a, b = b, a+b
15 |
16 | for i in fib():
17 | print(i)
18 |
19 | if __name__ == '__main__':
20 | pass
--------------------------------------------------------------------------------
/concurrency/coroutine/example02.py:
--------------------------------------------------------------------------------
1 | #code=utf-8
2 | '''
3 | Created on 2018年6月21日
4 |
5 | @author: zwustudy
6 |
7 | yield接收外部value,先通过next()函数 开启携程coroutine
8 | 之后每一次调用send(),将参数传入yield,同时相当于grep函数自动运行到line=send的内容,协同工作。最终调用。close()关闭这个协程
9 | '''
10 |
11 | def grep(pattern):
12 | print("Searching for", pattern)
13 | while True:
14 | line = (yield)
15 | if pattern in line:
16 | print(line)
17 |
18 | search = grep('coroutine')
19 | next(search)
20 | # Output: Searching for coroutine
21 | search.send("I love you")
22 | search.send("Don't you love me?")
23 | search.send("I love coroutines instead!")
24 | # Output: I love coroutines instead!
25 | search.send("But where is coroutine!")
26 | search.close()
27 |
28 | if __name__ == '__main__':
29 | pass
--------------------------------------------------------------------------------
/concurrency/coroutine/example03.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月21日
3 |
4 | @author: zwustudy
5 |
6 | 作为filter使用,
7 | follow将file中的每一行读取,send到coroutine中,grep查找匹配的line,send到下一个coroutine中,printer接收send过来的data,并且输出。 完成整个filter的流程。
8 | follow()-> grep() : send()
9 | grep() -> printer():send()
10 | '''
11 | import asyncio
12 | import time
13 |
14 | def follow(thefile, target):
15 | #thefile.seek(0,2) # Go to the end of the file
16 | next(target)
17 | while True:
18 | line = thefile.readline()
19 | if not line:
20 | time.sleep(0.1) # Sleep briefly
21 | continue
22 | target.send(line)
23 |
24 | @asyncio.coroutine
25 | def printer():
26 | while True:
27 | line = (yield)
28 | print(line)
29 |
30 | @asyncio.coroutine
31 | def grep(pattern, target):
32 | next(target)
33 | while True:
34 | line = (yield) # Receive a line
35 | if pattern in line:
36 | print(line)
37 | target.send(line) # Send to next stage
38 |
39 |
40 | if __name__ == '__main__':
41 | f = open("my father.txt")
42 | target3 = follow(f, grep('the', printer()))
43 | pass
--------------------------------------------------------------------------------
/concurrency/coroutine/example04.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月21日
3 |
4 | @author: zwustudy
5 | '''
6 | import asyncio
7 | import example03
8 |
9 |
10 | @asyncio.coroutine
11 | def broadcast(targets):
12 | for target in targets:
13 | next(target)
14 | while True:
15 | item = (yield)
16 | for target in targets:
17 | target.send(item)
18 |
19 |
20 | if __name__ == '__main__':
21 | f = open("my father.txt")
22 | p = example03.printer()
23 | example03.follow(f,
24 | broadcast([example03.grep('mandolin',p),
25 | example03.grep('a',p),
26 | example03.grep('music',p)])
27 | )
28 | pass
--------------------------------------------------------------------------------
/concurrency/coroutine/example05.py:
--------------------------------------------------------------------------------
1 | '''
2 | <<<<<<< HEAD
3 | Created on 2018年6月21日
4 |
5 | @author: zwustudy
6 | '''
7 | import random
8 | import time
9 |
10 | def stupid_fib(n):
11 | index = 0
12 | a = 0
13 | b = 1
14 | while index < n:
15 | sleep_cnt = yield b
16 | print('let me think {0} secs'.format(sleep_cnt))
17 | time.sleep(sleep_cnt)
18 | a, b = b, a + b
19 | index += 1
20 | print('-'*10 + 'test yield send' + '-'*10)
21 | N = 20
22 | sfib = stupid_fib(N)
23 | fib_res = next(sfib)
24 | while True:
25 | print(fib_res)
26 | try:
27 | fib_res = sfib.send(random.uniform(0, 0.5))
28 | except StopIteration:
29 | break
30 |
31 | if __name__ == '__main__':
32 | pass
33 | =======
34 | Created on 2018年6月23日
35 |
36 | @author: zwustudy
37 | '''
38 |
39 | from greenlet import greenlet
40 | import time
41 |
42 |
43 | def test1():
44 | while True:
45 | print("---我是A函数--")
46 | gr2.switch()
47 | time.sleep(0.5)
48 |
49 |
50 | def test2():
51 | while True:
52 | print("---我是B函数--")
53 | gr1.switch()
54 | time.sleep(0.5)
55 |
56 |
57 | def main():
58 | # 切换到gr1中运行
59 | gr1.switch()
60 |
61 |
62 | if __name__ == '__main__':
63 | gr1 = greenlet(test1)
64 | gr2 = greenlet(test2)
65 | main()
66 | >>>>>>> 24c33f5f978ec73fcee812e2f472b20a7da274bb
67 |
--------------------------------------------------------------------------------
/concurrency/coroutine/example06.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月23日
3 |
4 | @author: zwustudy
5 | '''
6 |
7 | def jumping_range(up_to):
8 | """Generator for the sequence of integers from 0 to up_to, exclusive.
9 |
10 | Sending a value into the generator will shift the sequence by that amount.
11 | """
12 | index = 0
13 | while index < up_to:
14 | jump = yield index
15 | if jump is None:
16 | jump = 1
17 | index += jump
18 | print("----index----", index)
19 | print("----jump----", jump)
20 |
21 | if __name__ == '__main__':
22 | iterator = jumping_range(6)
23 | print(next(iterator))
24 | print(next(iterator)) # 0
25 | print(iterator.send(2)) # 2
26 | print(next(iterator)) # 3
27 | print(iterator.send(-1)) # 2
28 | for x in iterator:
29 | print(x)
--------------------------------------------------------------------------------
/concurrency/coroutine/example07.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月23日
3 |
4 | @author: zwustudy
5 | '''
6 | def lazy_range(up_to):
7 | """Generator to return the sequence of integers from 0 to up_to, exclusive."""
8 | def gratuitous_refactor():
9 | index = 0
10 | while index < up_to:
11 | yield index
12 | index += 1
13 | yield from gratuitous_refactor()
14 |
15 | if __name__ == '__main__':
16 | iterator = lazy_range(5)
17 | for x in iterator:
18 | print(x)
--------------------------------------------------------------------------------
/concurrency/coroutine/example08.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月23日
3 |
4 | @author: zwustudy
5 | '''
6 |
7 | def bottom():
8 | # Returning the yield lets the value that goes up the call stack to come right back
9 | # down.
10 | print("----bottom----")
11 | return (yield 42)
12 |
13 | def middle():
14 | print("----middle----")
15 | return (yield from bottom())
16 |
17 | def top():
18 | print("----top----")
19 | return (yield from middle())
20 |
21 | if __name__ == '__main__':
22 | # Get the generator.
23 | gen = top()
24 | value = next(gen)
25 | print(value) # Prints '42'.
26 | try:
27 | value = gen.send(value * 2)
28 | except StopIteration as exc:
29 | print("----except----")
30 | print(value) # Prints '42'.
31 | value = exc.value
32 | print(value) # Prints '84'.
33 |
--------------------------------------------------------------------------------
/concurrency/coroutine/example09.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月23日
3 |
4 | @author: zwustudy
5 | '''
6 | import asyncio
7 |
8 | @asyncio.coroutine
9 | def countdown(number, n):
10 | while n > 0:
11 | print('T-minus', n, '({})'.format(number))
12 | yield from asyncio.sleep(1)
13 | n -= 1
14 |
15 | if __name__ == '__main__':
16 |
17 | loop = asyncio.get_event_loop()
18 | tasks = [asyncio.ensure_future(countdown("A", 2)),
19 | asyncio.ensure_future(countdown("B", 3))]
20 | loop.run_until_complete(asyncio.wait(tasks))
21 | loop.close()
22 |
23 |
--------------------------------------------------------------------------------
/concurrency/coroutine/example10.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月23日
3 |
4 | @author: zwustudy
5 | '''
6 | import datetime
7 | import heapq
8 | import types
9 | import time
10 |
11 | class Task:
12 |
13 | """Represent how long a coroutine should before starting again.
14 |
15 | Comparison operators are implemented for use by heapq. Two-item
16 | tuples unfortunately don't work because when the datetime.datetime
17 | instances are equal, comparison falls to the coroutine and they don't
18 | implement comparison methods, triggering an exception.
19 |
20 | Think of this as being like asyncio.Task/curio.Task.
21 | """
22 |
23 | def __init__(self, wait_until, coro):
24 | self.coro = coro
25 | self.waiting_until = wait_until
26 |
27 | def __eq__(self, other):
28 | return self.waiting_until == other.waiting_until
29 |
30 | def __lt__(self, other):
31 | return self.waiting_until < other.waiting_until
32 |
33 | class SleepingLoop:
34 |
35 | """An event loop focused on delaying execution of coroutines.
36 |
37 | Think of this as being like asyncio.BaseEventLoop/curio.Kernel.
38 | """
39 |
40 | def __init__(self, *coros):
41 | self._new = coros
42 | self._waiting = []
43 |
44 | def run_until_complete(self):
45 | # Start all the coroutines.
46 | for coro in self._new:
47 | wait_for = coro.send(None)
48 | heapq.heappush(self._waiting, Task(wait_for, coro))
49 | # Keep running until there is no more work to do.
50 | while self._waiting:
51 | now = datetime.datetime.now()
52 | # Get the coroutine with the soonest resumption time.
53 | task = heapq.heappop(self._waiting)
54 | if now < task.waiting_until:
55 | # We're ahead of schedule; wait until it's time to resume.
56 | delta = task.waiting_until - now
57 | time.sleep(delta.total_seconds())
58 | now = datetime.datetime.now()
59 | try:
60 | # It's time to resume the coroutine.
61 | wait_until = task.coro.send(now)
62 | heapq.heappush(self._waiting, Task(wait_until, task.coro))
63 | except StopIteration:
64 | # The coroutine is done.
65 | pass
66 |
67 | @types.coroutine
68 | def sleep(seconds):
69 | """Pause a coroutine for the specified number of seconds.
70 |
71 | Think of this as being like asyncio.sleep()/curio.sleep().
72 | """
73 | now = datetime.datetime.now()
74 | wait_until = now + datetime.timedelta(seconds=seconds)
75 | # Make all coroutines on the call stack pause; the need to use `yield`
76 | # necessitates this be generator-based and not an async-based coroutine.
77 | actual = yield wait_until
78 | # Resume the execution stack, sending back how long we actually waited.
79 | return actual - now
80 |
81 | async def countdown(label, length, *, delay=0):
82 | """Countdown a launch for `length` seconds, waiting `delay` seconds.
83 |
84 | This is what a user would typically write.
85 | """
86 | print(label, 'waiting', delay, 'seconds before starting countdown')
87 | delta = await sleep(delay)
88 | print(label, 'starting after waiting', delta)
89 | while length:
90 | print(label, 'T-minus', length)
91 | await sleep(1)
92 | length -= 1
93 | print(label, 'lift-off!')
94 |
95 | def main():
96 | """Start the event loop, counting down 3 separate launches.
97 |
98 | This is what a user would typically write.
99 | """
100 | loop = SleepingLoop(countdown('A', 5), countdown('B', 3, delay=2),
101 | countdown('C', 4, delay=1))
102 | start = datetime.datetime.now()
103 | loop.run_until_complete()
104 | print('Total elapsed time is', datetime.datetime.now() - start)
105 |
106 | if __name__ == '__main__':
107 | main()
108 |
--------------------------------------------------------------------------------
/concurrency/coroutine/my father.txt:
--------------------------------------------------------------------------------
1 | My father was a self-taught mandolin player. He was one of the best string instrument players in our town. He could not read music, but if he heard a tune a few times, he could play it. When he was younger, he was a member of a small country music band. They would play at local dances and on a few occasions would play for the local radio station. He often told us how he had auditioned and earned a position in a band that featured Patsy Cline as their lead singer. He told the family that after he was hired he never went back. Dad was a very religious man. He stated that there was a lot of drinking and cursing the day of his audition and he did not want to be around that type of environment.
2 | Occasionally, Dad would get out his mandolin and play for the family. We three children: Trisha, Monte and I, George Jr., would often sing along. Songs such as the Tennessee Waltz, Harbor Lights and around Christmas time, the well-known rendition of Silver Bells. "Silver Bells, Silver Bells, its Christmas time in the city" would ring throughout the house. One of Dad's favorite hymns was "The Old Rugged Cross". We learned the words to the hymn when we were very young, and would sing it with Dad when he would play and sing. Another song that was often shared in our house was a song that accompanied the Walt Disney series: Davey Crockett. Dad only had to hear the song twice before he learned it well enough to play it. "Davey, Davey Crockett, King of the Wild Frontier" was a favorite song for the family. He knew we enjoyed the song and the program and would often get out the mandolin after the program was over. I could never get over how he could play the songs so well after only hearing them a few times. I loved to sing, but I never learned how to play the mandolin. This is something I regret to this day.
3 | Dad loved to play the mandolin for his family he knew we enjoyed singing, and hearing him play. He was like that. If he could give pleasure to others, he would, especially his family. He was always there, sacrificing his time and efforts to see that his family had enough in their life. I had to mature into a man and have children of my own before I realized how much he had sacrificed.
4 | I joined the United States Air Force in January of 1962. Whenever I would come home on leave, I would ask Dad to play the mandolin. Nobody played the mandolin like my father. He could touch your soul with the tones that came out of that old mandolin. He seemed to shine when he was playing. You could see his pride in his ability to play so well for his family.
5 | When Dad was younger, he worked for his father on the farm. His father was a farmer and sharecropped a farm for the man who owned the property. In 1950, our family moved from the farm. Dad had gained employment at the local limestone quarry. When the quarry closed in August of 1957, he had to seek other employment. He worked for Owens Yacht Company in Dundalk, Maryland and for Todd Steel in Point of Rocks, Maryland. While working at Todd Steel, he was involved in an accident. His job was to roll angle iron onto a conveyor so that the welders farther up the production line would have it to complete their job. On this particular day Dad got the third index finger of his left hand mashed between two pieces of steel. The doctor who operated on the finger could not save it, and Dad ended up having the tip of the finger amputated. He didn't lose enough of the finger where it would stop him picking up anything, but it did impact his ability to play the mandolin.
6 | After the accident, Dad was reluctant to play the mandolin. He felt that he could not play as well as he had before the accident. When I came home on leave and asked him to play he would make excuses for why he couldn't play. Eventually, we would wear him down and he would say "Okay, but remember, I can't hold down on the strings the way I used to" or "Since the accident to this finger I can't play as good". For the family it didn't make any difference that Dad couldn't play as well. We were just glad that he would play. When he played the old mandolin it would carry us back to a cheerful, happier time in our lives. "Davey, Davey Crockett, King of the Wild Frontier", would again be heard in the little town of Bakerton, West Virginia.
7 | In August of 1993 my father was diagnosed with inoperable lung cancer. He chose not to receive chemotherapy treatments so that he could live out the rest of his life in dignity. About a week before his death, we asked Dad if he would play the mandolin for us. He made excuses but said "okay". He knew it would probably be the last time he would play for us. He tuned up the old mandolin and played a few notes. When I looked around, there was not a dry eye in the family. We saw before us a quiet humble man with an inner strength that comes from knowing God, and living with him in one's life. Dad would never play the mandolin for us again. We felt at the time that he wouldn't have enough strength to play, and that makes the memory of that day even stronger. Dad was doing something he had done all his life, giving. As sick as he was, he was still pleasing others. Dad sure could play that Mandolin!
8 | the
--------------------------------------------------------------------------------
/concurrency/thread/myThread.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月23日
4 |
5 | @author: zwustudy
6 | '''
7 | import threading
8 | import time
9 |
10 | class MyThread(threading.Thread):
11 |
12 | def __init__(self, func, args, name = ''):
13 | threading.Thread.__init__(self)
14 | self.func = func
15 | self.args = args
16 | self.name = name
17 |
18 | def getResult(self):
19 | return self.res
20 |
21 | def run(self):
22 | print('starting %s at:%s' % (self.name, time.strftime('%Y-%m-%d %H:%M:%S')))
23 | #self.res = apply(self.func, self.args)
24 | self.res = self.func(*self.args)
25 | print('%s finished at:%s' % (self.name, time.strftime('%Y-%m-%d %H:%M:%S')))
26 |
--------------------------------------------------------------------------------
/concurrency/thread/myThread.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/concurrency/thread/myThread.pyc
--------------------------------------------------------------------------------
/concurrency/thread/prodcons.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月23日
4 |
5 | @author: zwustudy
6 | '''
7 | import random
8 | import time
9 | import myThread
10 | from queue import Queue
11 | import threading
12 |
13 | '''
14 | 生产者,每nsleep秒生产nprod个产品,放入queue中
15 | a 产品标记
16 | name 生产者的名字
17 | '''
18 | def producer(queue, nsleep, nprod, name, a, lock):
19 | while True:
20 | for i in range(nprod):
21 | lock.acquire()
22 | queue.put(a[0], 1)
23 | print('%s生产了一个产品:%d, 当前队列大小:%d' % (name, a[0], queue.qsize()))
24 | a[0] += 1
25 | lock.release()
26 | time.sleep(nsleep)
27 |
28 | '''
29 | 消费着,每nsleep秒从queue中消费minProd至maxProd间随机产生的一个值的产品
30 | name 消费者的名字
31 | '''
32 | def consumer(queue, nsleep, minProd, maxProd, name):
33 | while True:
34 | nprod = random.randint(minProd, maxProd)
35 | for i in range(nprod):
36 | val = queue.get(1)
37 | print('%s消费了一个产品:%d, 当前队列大小:%d' % (name, val, queue.qsize()))
38 |
39 | time.sleep(nsleep)
40 |
41 | def main():
42 |
43 | queue = Queue(10)
44 | a = [0]
45 |
46 | lock = threading.Lock()
47 |
48 | producer1 = myThread.MyThread(producer, (queue, 1, 1, 'producer1', a, lock), 'producer1')
49 | producer2 = myThread.MyThread(producer, (queue, 1, 2, 'producer2', a, lock), 'producer2')
50 | consumer1 = myThread.MyThread(consumer, (queue, 1, 1, 5, 'consumer1'), 'consumer1')
51 | threads = [producer1, producer2, consumer1]
52 |
53 | for i in threads:
54 | i.start()
55 |
56 | for i in threads:
57 | i.join()
58 |
59 | if __name__ == '__main__':
60 | main()
61 |
--------------------------------------------------------------------------------
/concurrency/thread/producer_customer.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月19日
4 |
5 | 设计三个线程,线程1每秒钟对一个值进行+1操作,线程2每秒钟对该值进行+3操作,线程3每秒钟对该值进行-2操作
6 |
7 | @author: minmin
8 | '''
9 | import time
10 | import thread
11 |
12 | def loop(name, value, nsleep, action, lock1, lock2):
13 |
14 | while True:
15 | lock1.acquire()
16 | value[0] += action
17 | action_str = ""
18 | if action >= 0:
19 | action_str = "+" + str(action)
20 | else:
21 | action_str = str(action)
22 |
23 | print name + "对value做了" + action_str + "操作, value = " + str(value[0])
24 | lock1.release()
25 | time.sleep(nsleep)
26 |
27 | lock2.release()
28 |
29 | def main():
30 |
31 | lock = thread.allocate_lock()
32 | lock1 = thread.allocate_lock()
33 | lock2 = thread.allocate_lock()
34 | lock3 = thread.allocate_lock()
35 |
36 | value = [10]
37 |
38 | lock1.acquire()
39 | lock2.acquire()
40 | lock3.acquire()
41 |
42 | locks = [lock1, lock2, lock3]
43 |
44 | thread.start_new_thread(loop, ("Producer1", value, 1, 1, lock, lock1))
45 | thread.start_new_thread(loop, ("Producer2", value, 1, 3, lock, lock2))
46 | thread.start_new_thread(loop, ("Customer1", value, 1, -2, lock, lock3))
47 |
48 | #防止主线程执行完自动关闭运行的三个线程
49 | for i in locks:
50 | while i.locked(): pass
51 |
52 | if __name__ == '__main__':
53 | main()
54 |
55 |
--------------------------------------------------------------------------------
/concurrency/thread/thread_example04.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月19日
4 |
5 | @author: minmin
6 | '''
7 |
8 | import threading
9 | import time
10 |
11 | loops = [4, 2]
12 |
13 | class ThreadFunc(object):
14 |
15 | def __init__(self, func, args, name=''):
16 | self.name = name
17 | self.func = func
18 | self.args = args
19 |
20 | def __call__(self):
21 | #大于1.6的版本下面一句可以这样写 self.res = self.func(*self.args)
22 | apply(self.func, self.args)
23 |
24 |
25 | def loop(nloop, nsleep):
26 | print "start loop" + str(nloop) + " at:" + time.ctime()
27 | time.sleep(nsleep)
28 | print "loop" + str(nloop) + " done at:"+ time.ctime()
29 |
30 |
31 | def main():
32 | print "starting at:", time.ctime()
33 | threads = []
34 |
35 | nloops = range(len(loops))
36 |
37 | for i in nloops:
38 | thread = threading.Thread(target=ThreadFunc(loop, (i, loops[i]), loop.__name__))
39 | threads.append(thread)
40 |
41 | for i in threads:
42 | i.start()
43 |
44 | for i in threads:
45 | i.join()
46 |
47 | print "all done at:", time.ctime()
48 |
49 | if __name__ == '__main__':
50 | main()
--------------------------------------------------------------------------------
/concurrency/thread/thread_example05.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月23日
4 |
5 | @author: minmin
6 | '''
7 |
8 | import threading
9 | import time
10 |
11 | class MyThread(threading.Thread):
12 |
13 | def __init__(self, func, args, name = ''):
14 | threading.Thread.__init__(self)
15 | self.name = name
16 | self.func = func
17 | self.args = args
18 |
19 | def run(self):
20 | apply(self.func, self.args)
21 |
22 |
23 | def loop(nloop, nsleep):
24 | print "start loop%d at:%s" % (nloop, time.strftime('%Y-%m-%d %H:%M:%S'))
25 | time.sleep(nsleep)
26 | print "loop%d done at:%s" % (nloop, time.strftime('%Y-%m-%d %H:%M:%S'))
27 |
28 |
29 | def main():
30 | print "starting at:%s" % time.strftime('%Y-%m-%d %H:%M:%S')
31 | loops = [4, 2]
32 | nloops = range(len(loops))
33 |
34 | threads = []
35 |
36 | for i in nloops:
37 | thread = MyThread(loop, (i, loops[i]))
38 | threads.append(thread)
39 |
40 | for i in threads:
41 | i.start()
42 |
43 | for i in threads:
44 | i.join()
45 |
46 | print "all done at:%s" % time.strftime('%Y-%m-%d %H:%M:%S')
47 |
48 | if __name__ == '__main__':
49 | main()
--------------------------------------------------------------------------------
/concurrency/thread/thread_facfib.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月23日
4 |
5 | @author: zwustudy
6 | '''
7 | from myThread import MyThread
8 | import time
9 |
10 | def fib(index):
11 | time.sleep(0.005)
12 | if index < 2: return 1
13 | return fib(index - 1) + fib(index - 2)
14 |
15 | def fac(index):
16 | time.sleep(0.1)
17 | if index < 2: return 1
18 | return index * fac(index - 1)
19 |
20 | def sum(index):
21 | time.sleep(0.1)
22 | if index < 2: return 1
23 | return index + sum(index - 1)
24 |
25 | def main():
26 |
27 | funcs = [fib, fac, sum]
28 | n = 12
29 | nfuncs = range(len(funcs))
30 |
31 | print('*** SINGLE THREAD all starting at:%s ***' % time.strftime('%Y-%m-%d %H:%M:%S'))
32 | for i in nfuncs:
33 | print('starting %s, at:%s' % (funcs[i].__name__, time.strftime('%Y-%m-%d %H:%M:%S')))
34 | print(funcs[i](n))
35 | print('%s finished at:%s' % (funcs[i].__name__, time.strftime('%Y-%m-%d %H:%M:%S')))
36 |
37 | print('*** SINGLE THREAD all done at:%s ***' % time.strftime('%Y-%m-%d %H:%M:%S'))
38 |
39 | print('*** MULTIPLE THREAD all starting at:%s ***' % time.strftime('%Y-%m-%d %H:%M:%S'))
40 |
41 | threads = []
42 | for i in nfuncs:
43 | thread = MyThread(funcs[i], (n,), funcs[i].__name__)
44 | threads.append(thread)
45 |
46 | for i in threads:
47 | i.start()
48 |
49 | for i in threads:
50 | i.join()
51 | print(i.getResult())
52 |
53 | print('*** MULTIPLE THREAD all starting at:%s ***' % time.strftime('%Y-%m-%d %H:%M:%S'))
54 | if __name__ == '__main__':
55 | main()
--------------------------------------------------------------------------------
/data/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/data/__init__.py
--------------------------------------------------------------------------------
/data/structure/ListNode.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月25日
3 |
4 | 单向链表
5 | 打印方法
6 | 提供逆置的方法,两种实现迭代和递归
7 |
8 | @author: zwustudy
9 | '''
10 | class ListNode(object):
11 |
12 | def __init__(self, val, nxt):
13 | self.val = val
14 | self.nxt = nxt
15 |
16 | """单向链表打印
17 | """
18 | def toString(self):
19 | if not self.nxt:
20 | return str(self.val)
21 | return str(self.val) + " " + self.nxt.toString()
22 |
23 | """单向链表逆置
24 | """
25 | def reverse(self):
26 | node = self
27 | if not node.nxt:
28 | return node
29 |
30 | """A->B->C->D
31 | """
32 | nxt = node.nxt
33 | node.nxt = None#取到B,把A断开
34 |
35 | """A<-B C->D
36 | """
37 | while nxt:
38 | nextnext = nxt.nxt #取到B的下一个节点
39 | nxt.nxt = node #由于已经获得了下一个节点的引用,这里可以放心大胆的把B的下一个节点指向当前的头节点,
40 | node = nxt #把B赋值给头结点,这样就node永远表示已经逆置的部分的头结点
41 | nxt = nextnext #之前持有的下一个节点的引用,继续往下遍历
42 | return node
43 |
44 | """通过递归来实现,只是不是尾递归
45 | """
46 | def reverse_by_recursive(self):
47 |
48 | node = self
49 | if not node.nxt:
50 | return node
51 |
52 | """
53 | A->B->C->D
54 | """
55 | result = node.nxt.reverse();
56 | node.nxt.nxt = node #C的next是D,也就是操作把D的next指向C。
57 | node.nxt = None
58 | """处理成:A->B->C<-D的结构,C不指向。每递归一层,这样的截点就往前走一步,最后直到A<-B<-C<-D
59 | """
60 | return result
61 |
62 | def main():
63 |
64 | """通过循环的方式创建单向链表
65 | """
66 | node = None
67 | for x in range(3, 0 , -1):
68 | node = ListNode(x, node);
69 |
70 | print(node.toString())
71 | node = node.reverse();
72 | print(node.toString())
73 | print(node.reverse_by_recursive().toString())
74 | if __name__ == "__main__":
75 | main()
--------------------------------------------------------------------------------
/data/structure/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/data/structure/__init__.py
--------------------------------------------------------------------------------
/data/structure/cache/LRUCache.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月25日
3 |
4 | 缓存常用淘汰算法之一:LRU(least recently used 最近最少使用)算法根据数据的历史访问记录来进行淘汰数据,其核心思想是:如果数据最近被访问过,那么将来被访问的几率也更高。
5 | 当存在热点数据时,LRU的效率很好,但偶发性的、周期性的批量操作会导致LRU命中率急剧下降,缓存污染情况比较严重。
6 |
7 | @author: zwustudy
8 | '''
9 | import collections
10 |
11 | class LRUCache(collections.OrderedDict):
12 |
13 | def __init__(self, size=5):
14 | self.size = size
15 | self.cache = collections.OrderedDict()
16 |
17 |
18 | def get(self, key):
19 |
20 | if self.cache.__contains__(key):
21 | value = self.cache.pop(key) #新访问了缓存,因此缓存需要移到最新的位置
22 | self.cache[key] = value
23 | return value
24 | else:
25 | return None
26 |
27 |
28 | def set(self, key, value):
29 |
30 | if self.cache.__contains__(key):
31 | self.cache.pop(key) #新访问了缓存,因此缓存需要移到最新的位置
32 | elif len(self.cache) >= self.size:
33 | self.cache.popitem(last = False)
34 | self.cache[key] = value
35 |
36 | class LRUCache1(object):
37 |
38 | def __init__(self, size = 5):
39 | self.size = size
40 | self.cache = dict()
41 | self.keyset = list()
42 |
43 | def get(self, key):
44 | if self.cache.__contains__(key):
45 | self.keyset.remove(key) #新访问了缓存,因此缓存需要移到最新的位置
46 | self.keyset.insert(0, key)
47 | return self.cache.get(key)
48 | else:
49 | return None
50 |
51 | def set(self, key, value):
52 | if self.cache.__contains__(key):
53 | self.keyset.remove(key) #原来的key移除,好让后面把key的位置移到最新访问
54 | elif len(self.cache) >= self.size:
55 | removeKey = self.keyset.pop() #移除最近最少访问的缓存,给新缓存让个位置
56 | self.cache.pop(removeKey)
57 | self.keyset.insert(0, key)
58 | self.cache[key] = value
59 |
60 |
61 | def main():
62 | cache = LRUCache1(5)
63 | for i in range(0, 6, 1):
64 | if i == 3:
65 | cache.set("key0", 0) #本来最早的缓存key是 key0,但是这里更新了之后,最早更新的就是key1,key1的缓存应该被淘汰
66 | cache.set("key" + str(i), i)
67 |
68 | for i in range(0, 7, 1):
69 | key = "key" + str(i)
70 | print(key + ":" + str(cache.get(key)))
71 |
72 | if __name__ == "__main__":
73 | main()
74 |
75 |
--------------------------------------------------------------------------------
/data/structure/cache/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/data/structure/cache/__init__.py
--------------------------------------------------------------------------------
/my father.txt:
--------------------------------------------------------------------------------
1 | My father was a self-taught mandolin player. He was one of the best string instrument players in our town. He could not read music, but if he heard a tune a few times, he could play it. When he was younger, he was a member of a small country music band. They would play at local dances and on a few occasions would play for the local radio station. He often told us how he had auditioned and earned a position in a band that featured Patsy Cline as their lead singer. He told the family that after he was hired he never went back. Dad was a very religious man. He stated that there was a lot of drinking and cursing the day of his audition and he did not want to be around that type of environment.
2 | Occasionally, Dad would get out his mandolin and play for the family. We three children: Trisha, Monte and I, George Jr., would often sing along. Songs such as the Tennessee Waltz, Harbor Lights and around Christmas time, the well-known rendition of Silver Bells. "Silver Bells, Silver Bells, its Christmas time in the city" would ring throughout the house. One of Dad's favorite hymns was "The Old Rugged Cross". We learned the words to the hymn when we were very young, and would sing it with Dad when he would play and sing. Another song that was often shared in our house was a song that accompanied the Walt Disney series: Davey Crockett. Dad only had to hear the song twice before he learned it well enough to play it. "Davey, Davey Crockett, King of the Wild Frontier" was a favorite song for the family. He knew we enjoyed the song and the program and would often get out the mandolin after the program was over. I could never get over how he could play the songs so well after only hearing them a few times. I loved to sing, but I never learned how to play the mandolin. This is something I regret to this day.
3 | Dad loved to play the mandolin for his family he knew we enjoyed singing, and hearing him play. He was like that. If he could give pleasure to others, he would, especially his family. He was always there, sacrificing his time and efforts to see that his family had enough in their life. I had to mature into a man and have children of my own before I realized how much he had sacrificed.
4 | I joined the United States Air Force in January of 1962. Whenever I would come home on leave, I would ask Dad to play the mandolin. Nobody played the mandolin like my father. He could touch your soul with the tones that came out of that old mandolin. He seemed to shine when he was playing. You could see his pride in his ability to play so well for his family.
5 | When Dad was younger, he worked for his father on the farm. His father was a farmer and sharecropped a farm for the man who owned the property. In 1950, our family moved from the farm. Dad had gained employment at the local limestone quarry. When the quarry closed in August of 1957, he had to seek other employment. He worked for Owens Yacht Company in Dundalk, Maryland and for Todd Steel in Point of Rocks, Maryland. While working at Todd Steel, he was involved in an accident. His job was to roll angle iron onto a conveyor so that the welders farther up the production line would have it to complete their job. On this particular day Dad got the third index finger of his left hand mashed between two pieces of steel. The doctor who operated on the finger could not save it, and Dad ended up having the tip of the finger amputated. He didn't lose enough of the finger where it would stop him picking up anything, but it did impact his ability to play the mandolin.
6 | After the accident, Dad was reluctant to play the mandolin. He felt that he could not play as well as he had before the accident. When I came home on leave and asked him to play he would make excuses for why he couldn't play. Eventually, we would wear him down and he would say "Okay, but remember, I can't hold down on the strings the way I used to" or "Since the accident to this finger I can't play as good". For the family it didn't make any difference that Dad couldn't play as well. We were just glad that he would play. When he played the old mandolin it would carry us back to a cheerful, happier time in our lives. "Davey, Davey Crockett, King of the Wild Frontier", would again be heard in the little town of Bakerton, West Virginia.
7 | In August of 1993 my father was diagnosed with inoperable lung cancer. He chose not to receive chemotherapy treatments so that he could live out the rest of his life in dignity. About a week before his death, we asked Dad if he would play the mandolin for us. He made excuses but said "okay". He knew it would probably be the last time he would play for us. He tuned up the old mandolin and played a few notes. When I looked around, there was not a dry eye in the family. We saw before us a quiet humble man with an inner strength that comes from knowing God, and living with him in one's life. Dad would never play the mandolin for us again. We felt at the time that he wouldn't have enough strength to play, and that makes the memory of that day even stronger. Dad was doing something he had done all his life, giving. As sick as he was, he was still pleasing others. Dad sure could play that Mandolin!
--------------------------------------------------------------------------------
/nowcoder/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/nowcoder/__init__.py
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution1.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月20日
3 | 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
4 | 如果是则返回True,否则返回False。假设输入的数组的任意两个数字都互不相同。
5 | @author: minmin
6 | '''
7 | class Solution:
8 |
9 | '''
10 | 递归实现
11 | '''
12 | def VerifySquenceOfBSTByRecursion(self, sequence):
13 | # write code here
14 | if not sequence:
15 | return False
16 | if len(sequence) == 1:
17 | return True
18 | r = sequence[-1]
19 | i = 0
20 | while i < len(sequence):
21 | if sequence[i] < r:
22 | i = i + 1
23 | else:
24 | break
25 | leftSequence = sequence[0:i]
26 | rightSequence = sequence[i:len(sequence) - 1]
27 | for x in rightSequence:
28 | if x < r:
29 | return False
30 | left = True
31 | right = True
32 | if len(leftSequence) > 1:
33 | left = self.VerifySquenceOfBSTByRecursion(leftSequence)
34 | if len(rightSequence) > 1:
35 | right = self.VerifySquenceOfBSTByRecursion(rightSequence)
36 | return left and right
37 |
38 | '''
39 | 非递归实现
40 | '''
41 | def VerifySquenceOfBSTByNotRecursion(self, sequence):
42 | # write code here
43 | if not sequence:
44 | return False
45 | if len(sequence) == 1:
46 | return True
47 | i = len(sequence) - 1
48 | while i >= 2:
49 | j = 0
50 | while j <= i:
51 | if sequence[j] > sequence[i]:
52 | break
53 | else:
54 | j = j + 1
55 | rightS = sequence[j:i]
56 | for x in rightS:
57 | if x < sequence[i]:
58 | return False
59 | i = i - 1
60 | return True
61 |
62 | if __name__ == "__main__":
63 | sequence = [1,2,3,10,20,13,12]
64 | print(Solution().VerifySquenceOfBSTByNotRecursion(sequence))
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution10.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月30日
3 | 题目描述
4 | 输入一棵二叉搜索树,将该二叉搜索树转换成一个排序的双向链表。要求不能创建任何新的结点,只能调整树中结点指针的指向。
5 | @author: minmin
6 | '''
7 |
8 | class Solution10:
9 |
10 | def Convert(self, pRootOfTree):
11 | # write code here
12 | if not pRootOfTree:
13 | return None
14 | if not pRootOfTree.left and not pRootOfTree.right:
15 | return pRootOfTree
16 | if pRootOfTree.right:
17 | #如果右节点存在,通过递归找到右节点链表的首节点,将其与pRootOfTree连接起来
18 | rightNode = self.Convert(pRootOfTree.right)
19 | rightNode.left = pRootOfTree
20 | pRootOfTree.right = rightNode
21 |
22 | if pRootOfTree.left:
23 | #如果左节点存在,通过递归找到左节点链表的尾节点,将其与pRootOfTree连接起来
24 | leftNode = self.Convert(pRootOfTree.left)
25 | leftNode_last = self.FindLastNode(leftNode)
26 | leftNode_last.right = pRootOfTree
27 | pRootOfTree.left = leftNode_last
28 | return leftNode
29 | else:
30 | #如果左节点不存在,则说明pRootOfTree已经是首节点了
31 | return pRootOfTree
32 |
33 | def FindLastNode(self, treeNode):
34 | if not treeNode:
35 | return None
36 | while treeNode.right:
37 | treeNode = treeNode.right
38 | return treeNode
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution11.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年2月1日
3 |
4 | @author: minmin
5 | '''
6 |
7 | class Solution:
8 |
9 | def Permutation(self, ss):
10 | # write code herenot
11 | if not ss:
12 | return []
13 | if len(ss) == 1:
14 | return [ss]
15 | charArr = list(ss)
16 | res = []
17 | for i in range(len(ss)):
18 | _str = "".join(charArr)
19 | if not _str in res:
20 | res.append(_str)
21 | for j in range(1,len(ss)):
22 | temp = charArr[j - 1]
23 | charArr[j - 1] = charArr[j]
24 | charArr[j] = temp
25 | _str = "".join(charArr)
26 | if not _str in res:
27 | res.append(_str)
28 |
29 | res.sort()
30 | return res
31 |
32 |
33 | if __name__ == "__main__":
34 | print(Solution().Permutation("aaABC"));
35 |
36 |
37 |
38 |
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution12.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年4月16日
3 | 按层序打印二叉树 A
4 | B C
5 | D E F
6 | 输出:
7 | A
8 | B,C
9 | D,E,F
10 | @author: minmin
11 | '''
12 | class TreeNode:
13 |
14 | def __init__(self, value, left, right):
15 | self.value = value
16 | self.left = left
17 | self.right = right
18 |
19 | class Solution12:
20 |
21 | def printTree(self, root):
22 | if not root:
23 | return False
24 | nodeList = [root]
25 | size = len(nodeList)
26 | last = 0
27 | i = 0
28 | while i < len(nodeList):
29 | print(nodeList[i].value, end="")
30 | if i == size - 1:
31 | print()
32 | for j in range(last, size):
33 | if nodeList[j].left:
34 | nodeList.append(nodeList[j].left)
35 | if nodeList[j].right:
36 | nodeList.append(nodeList[j].right)
37 | last = size
38 | size = len(nodeList)
39 | i += 1
40 |
41 | if __name__ == '__main__':
42 |
43 | d = TreeNode('D', None, None)
44 | e = TreeNode('E', None, None)
45 | f = TreeNode('F', None, None)
46 |
47 | b = TreeNode('B', d, e)
48 | c = TreeNode('C', None, f)
49 |
50 | a = TreeNode('A', b ,c)
51 |
52 | Solution12().printTree(a)
53 |
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution2.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月17日
3 | 题目描述
4 | 输入一个链表,从尾到头打印链表每个节点的值。
5 | 知识点:链表
6 | @author: minmin
7 | '''
8 | class ListNode:
9 | def __init__(self, x):
10 | self.val = x;
11 | self.next = None
12 |
13 |
14 | class Solution:
15 | # 返回从尾部到头部的列表值序列,例如[1,2,3]
16 | def printListFromTailToHead(self, listNode):
17 |
18 | list1 = [listNode.val]
19 | while listNode.next != None:
20 | listNode = listNode.next
21 | if listNode != None:
22 | list1.append(listNode.val)
23 |
24 | list1.reverse()
25 | return list1
26 |
27 |
28 | if __name__ == '__main__':
29 | listNode0 = ListNode(0);
30 | listNode1 = ListNode(1);
31 | listNode2 = ListNode(2);
32 | listNode0.next = listNode1;
33 | listNode1.next = listNode2;
34 | print(Solution().printListFromTailToHead(listNode0));
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution3.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月17日
3 | 题目描述
4 | 输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。
5 | 假设输入的前序遍历和中序遍历的结果中都不含重复的数字。
6 | 例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},
7 | 则重建二叉树并返回。
8 | @author: minmin
9 | '''
10 | from test.badsyntax_future3 import result
11 | class TreeNode:
12 | def __init__(self, x):
13 | self.val = x
14 | self.left = None
15 | self.right = None
16 |
17 | class Solution:
18 | # 返回构造的TreeNode根节点
19 | def reConstructBinaryTree(self, pre, tin):
20 | if len(pre) == 0:
21 | return None
22 | elif len(pre) == 1:
23 | return TreeNode(pre[0])
24 | else:
25 | index = tin.index(pre[0])
26 | result = TreeNode(pre[0])
27 | result.left = self.reConstructBinaryTree(pre[1 : index + 1], tin[ : index])
28 | result.right = self.reConstructBinaryTree(pre[index + 1 : ], tin[index + 1 : ])
29 | return result
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution4.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月25日
3 |
4 | @author: minmin
5 | '''
6 | from _collections import deque
7 |
8 | class Solution4:
9 |
10 | def reOrderArray(self, array):
11 | odd = deque()
12 | l = len(array)
13 | for i in range(l):
14 | if array[l - i - 0] % 2 != 0:
15 | odd.appendLeft(array[l - i - 0])
16 | if array[i] % 2 == 0:
17 | odd.append(array[i])
18 | return list(odd)
19 |
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution5.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月18日
3 | 把一个数组最开始的若干个元素搬到数组的末尾,我们称之为数组的旋转。
4 | 输入一个非递减排序的数组的一个旋转,输出旋转数组的最小元素。
5 | 例如数组{3,4,5,1,2}为{1,2,3,4,5}的一个旋转,该数组的最小值为1。
6 | NOTE:给出的所有元素都大于0,若数组大小为0,请返回0。
7 | @author: minmin
8 | '''
9 |
10 | class Solution:
11 |
12 | def minNumberInRotateArray(self, rotateArray):
13 | # write code here
14 | length = len(rotateArray)
15 | if length == 0:
16 | return 0
17 | elif length == 1:
18 | return rotateArray[0]
19 | left = 0
20 | right = length - 1;
21 | while rotateArray[left] >= rotateArray[right]:
22 | if right - left == 1:
23 | #临界情况
24 | return rotateArray[right];
25 | middle = (left + right) / 2
26 |
27 | #三个顺序不能颠倒,因为第二个会用到第一个的排除情况
28 | if rotateArray[left] == rotateArray[middle] and rotateArray[right] == rotateArray[middle]:
29 | #无法判断在左边还是右边的情况
30 | return Solution.findMinByOrder(rotateArray, left, right)
31 | elif rotateArray[left] <= rotateArray[middle]:
32 | left = middle
33 | else:
34 | right = middle
35 |
36 | return rotateArray[middle]
37 |
38 | def findMinByOrder(self, rotateArray, left, right):
39 | m = rotateArray[left];
40 | for i in range(left + 1, right):
41 | if rotateArray[i] < m:
42 | return rotateArray[i]
43 | m = rotateArray[i];
44 | return rotateArray[left]
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution6.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月27日
3 | 输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下矩阵:
4 | [[1,2,3,4]
5 | [5,6,7,8]
6 | [9,10,11,12]
7 | [13,14,15,16]] 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.
8 | @author: minmin
9 | '''
10 |
11 | class Solution6:
12 |
13 | # matrix类型为二维列表,需要返回列表
14 | def printMatrix(self, matrix):
15 | # write code here
16 | res = []
17 | m = len(matrix)
18 | n = len(matrix[0])
19 | if m == 1 and n == 1:
20 | res.append(matrix[0][0])
21 | return res
22 | a = 0
23 | b = 0
24 | c = m - 1
25 | d = n - 1
26 | i = 0
27 | print(m)
28 | print(n)
29 | while c >= a and d >= b:
30 | for i in range(b, d + 1):
31 | if c < a:
32 | break
33 | res.append(matrix[b][i])
34 | a = a + 1
35 | for i in range(a, c + 1):
36 | if d < b:
37 | break
38 | res.append(matrix[i][d])
39 | d = d - 1
40 | for i in range(d, b - 1, -1):
41 | if c < a:
42 | break
43 | res.append(matrix[c][i])
44 | c = c - 1
45 | for i in range(c, a - 1, -1):
46 | if d < b:
47 | break
48 | res.append(matrix[i][b])
49 | b = b + 1
50 | return res
51 |
52 | if __name__ == '__main__':
53 | matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]
54 | res = Solution6().printMatrix(matrix)
55 | for x in res:
56 | print(x)
57 |
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution7.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月28日
3 | 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
4 | 假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1
5 | 是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
6 | (注意:这两个序列的长度是相等的)
7 |
8 | 借助一个栈实现,push进元素,如果栈顶元素等于pop序列的第一个,就出栈。
9 | 如果最后栈为空,则说明是。两个序列的长度要满足相等
10 | @author: minmin
11 | '''
12 |
13 | class Solution:
14 |
15 | '''
16 | 解题思路:借助一个栈实现,push进元素,如果栈顶元素等于pop序列的第一个,就出栈。
17 | 如果最后栈为空,则说明是。两个序列的长度要满足相等
18 | '''
19 | def isPopOrder(self, pushV, popV):
20 | if len(pushV) != len(popV):
21 | return False
22 | stack = []
23 | index = 0
24 | for x in pushV:
25 | stack.append(x);
26 | while stack[-1] == popV[index]:
27 | stack.pop()
28 | index = index + 1
29 | return len(stack) == 0
30 |
31 |
32 |
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution8.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月28日
3 | 输入一颗二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。
4 | 路径定义为从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。
5 | 返回二维列表,内部每个列表表示找到的路径
6 | @author: minmin
7 | '''
8 | from collections import deque
9 |
10 | class TreeNode:
11 | def __init__(self, x):
12 | self.val = x
13 | self.left = None
14 | self.right = None
15 |
16 | class Solution:
17 |
18 | # 返回二维列表,内部每个列表表示找到的路径
19 | # 通过递归来实现,递归的关键是找到递归点,二叉树的结构本身是非常好的递归点,这题的关键是能够找到
20 | # 递归的时候和为expectNumber如何处理:递归后expectNumber = 递归前expectNumber - root.val
21 | def FindPathRecursion(self, root, expectNumer):
22 | if not root:
23 | return []
24 | if root and not root.left and not root.right and root.val == expectNumer:
25 | return [[root.val]]
26 | leftPath = self.FindPathRecursion(root.left, expectNumer - root.val)
27 | rightPath = self.FindPathRecursion(root.right, expectNumer - root.val)
28 | res = []
29 | for x in leftPath + rightPath:
30 | res.append([root.val] + x)
31 | return res
32 |
33 | # 返回二维列表,内部每个列表表示找到的路径
34 | # 通过遍历计算出所有的路径,遍历路径集合求和为expectNumber的所有路径
35 | # 使用到deque double-end-queque是亮点
36 | def FindPathByTraversal(self, root, expectNumber):
37 | # write code here
38 | if not root:
39 | return []
40 | allPath = self.calculatePath(root)
41 | res = []
42 | for x in allPath:
43 | s = 0
44 | for i in x:
45 | s = s + i
46 | if s == expectNumber:
47 | res.append(x)
48 | return res
49 |
50 | def calculatePath(self, treeNode):
51 | if not treeNode.left and not treeNode.right:
52 | return [deque([treeNode.val])]
53 | leftPath = []
54 | rightPath = []
55 | if treeNode.left:
56 | leftPath = self.calculatePath(treeNode.left)
57 | if treeNode.right:
58 | rightPath = self.calculatePath(treeNode.right)
59 | for x in leftPath:
60 | x.appendleft(treeNode.val)
61 | for x in rightPath:
62 | x.appendleft(treeNode.val)
63 | leftPath.append(x)
64 | return leftPath
--------------------------------------------------------------------------------
/nowcoder/foroffer/Solution9.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月28日
3 | 题目描述:输入一个复杂链表(每个节点中有节点值,以及两个指针,一个指向下一个节点,另一个特殊指针指向任意一个节点),
4 | 返回结果为复制后复杂链表的head。(注意,输出结果中请不要返回参数中的节点引用,否则判题程序会直接返回空)
5 |
6 | 解题思路:这题的难点在于如何给节点的random引用如何赋值
7 | 可以这样操作:
8 | 第一步:在链表中每一个节点后面都插入一个赋值节点A->B->C改为A->A1->B->B1->C->C1
9 | 第二步:把A的random节点下一个节点赋值给A1的random引用。这样巧妙的利用了上面的结构
10 | 不用去找出来random节点到底是哪个,因为random节点的下一个节点就刚好是我们构造出来的Random1节点
11 | 第三步:按照奇偶拆分两个链表
12 | @author: minmin
13 | '''
14 | class RandomListNode:
15 | def __init__(self, x):
16 | self.val = x
17 | self.next = None
18 | self.random = None
19 |
20 | class Solution:
21 |
22 | #返回RandomListNode的头结点
23 | def Clone(self, pHead):
24 | if not pHead:
25 | return None
26 | old = pHead
27 | while pHead:
28 | old_next = pHead.next
29 | new_next = RandomListNode(pHead.val)
30 | pHead.next = new_next
31 | new_next.next = old_next
32 | pHead = old_next
33 | pHead = old
34 | while pHead:
35 | old_random = pHead.random
36 | new_next = pHead.next
37 | if old_random:
38 | new_next.random = old_random.next
39 | pHead = new_next.next
40 | pHead = old
41 | new = pHead.next
42 | while pHead:
43 | new_next = pHead.next
44 | old_next = new_next.next
45 | pHead.next = old_next
46 | if old_next:
47 | new_next.next = old_next.next
48 | pHead = old_next
49 | return new
50 |
51 | if __name__ == "__main__":
52 | pHead = RandomListNode(100);
53 |
54 | pHead.next = RandomListNode(200);
55 |
56 | print(Solution().Clone(pHead).val)
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
--------------------------------------------------------------------------------
/nowcoder/foroffer/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/nowcoder/foroffer/__init__.py
--------------------------------------------------------------------------------
/others/Quine.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年6月14日
3 |
4 | @author: minmin
5 | '''
6 | s='s=%r\nprint(s%%s)'
7 | print(s%s)
--------------------------------------------------------------------------------
/others/TryTimes.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年1月22日
3 | 题目描述:从第一级升级到第二级成功的概率是0.8,失败的概率是0.2,失败不降级;
4 | 从第二级升级到第三级的成功的概率是0.6,失败的概率是0.4,失败降一级;
5 | 从第三级升级到第四级的成功的概率是0.4,失败的概率是0.6,失败降一级;
6 | 从第四级升级到第五级的成功的概率是0.1,失败的概率是0.9,失败降一级;
7 | 升到第五级立即结束
8 | 现有100颗宝石,能够成功升到第五级的概率是多少?
9 | 每尝试一次升级消耗一颗宝石,请问从第一级升级到第五级需要的宝石期望是多少?
10 | 解答:
11 | 这是一个典型的动态规划的题目,问题的解要依赖于子问题的解的综合
12 | 其实求有限颗宝石之内,能够成功升级到某级的概率比较合适,
13 | 如果求从第一级升到第五级需要多少颗宝石,可以尝试100000次,得出结果取平均数大概在75-78之间的一个数字
14 | @author: minmin
15 | '''
16 | import random
17 |
18 |
19 | def getTryTimes():
20 | i = 1
21 | result = 0
22 | while (i < 5):
23 | number = random.randint(0, 9);
24 | result = result + 1
25 | mod = number % 10;
26 | if i == 1:
27 | if mod <= 1:
28 | i = 1
29 | else:
30 | i = 2
31 | elif i == 2:
32 | if mod <= 3:
33 | i = 1
34 | else:
35 | i = 3
36 | elif i == 3:
37 | if mod <= 5:
38 | i = 2
39 | else:
40 | i = 4
41 | elif i == 4:
42 | if mod <= 8:
43 | i = 3
44 | else:
45 | i = 5
46 | return result
47 |
48 | def calculateRate(tryTimes):
49 | if tryTimes < 4:
50 | return 0;
51 | #rate = [[0] * 6] * (tryTimes + 1);
52 | rate = [([0] * 6) for i in range(tryTimes + 1)]
53 | rate[1][1] = 0.2
54 | rate[1][2] = 0.8
55 | for n in range(2, tryTimes + 1):
56 | for m in range(1, 6):
57 | rate[n][m] = calculate(rate, n, m)
58 | #print("%s,%s:%.6f" % (n, m, rate[n][m]))
59 | result = 0
60 |
61 | for i in range(1, tryTimes + 1):
62 | result = result + rate[i][5];
63 | #print("------%s,%s:%.20f" % (i, 5, rate[i][5]))
64 |
65 | return result
66 |
67 | def calculate(rate, n, m):
68 | if m > n + 1:
69 | return 0
70 | if m == 1:
71 | return rate[n - 1][1] * 0.2 + rate[n - 1][2] * 0.4
72 | if m == 2:
73 | return rate[n - 1][1] * 0.8 + rate[n - 1][3] * 0.6
74 | if m == 3:
75 | return rate[n - 1][2] * 0.6 + rate[n - 1][4] * 0.9
76 | if m == 4:
77 | return rate[n - 1][3] * 0.4
78 | if m == 5:
79 | return rate[n - 1][4] * 0.1
80 | if __name__ == '__main__':
81 | sum1 = 0
82 | testTimes = 10000
83 | for i in range(testTimes):
84 | times = getTryTimes()
85 | sum1 += times
86 | print(sum1/testTimes)
87 |
88 | rate = calculateRate(100)
89 | print("%.20f" % rate)
90 |
91 |
92 |
--------------------------------------------------------------------------------
/others/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/others/__init__.py
--------------------------------------------------------------------------------
/problems/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/problems/__init__.py
--------------------------------------------------------------------------------
/problems/solution0.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年7月8日
3 |
4 | 描述:输入一个正整数,求其二进制表示的1的个数;
5 | 可以利用这样一个事实,二进制表示为AAAAAB,B为最后一位,AAAAA为正整数除以2向下取整
6 | 这样就可以递归求解出正整数中1的个数
7 |
8 | @author: zwustudy
9 | '''
10 |
11 | def count_one(num):
12 | if num < 2:
13 | return num
14 | return num % 2 + count_one(num >> 1)
15 |
16 | def main():
17 | for x in range(0, 11):
18 | print(str(x) + "二进制表示中1的个数有:" + str(count_one(x)))
19 |
20 | if __name__ == '__main__':
21 | main();
--------------------------------------------------------------------------------
/sort/SortAlgorithms.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年3月25日
3 |
4 | @author: minmin
5 | '''
6 | from sort.algorithms import HeapSort
7 |
8 | def testHeapSort():
9 | lst = [10,20,1,6,6,8,5,2,7,8,9]
10 | HeapSort.HeapSort().sort(lst);
11 | for x in lst:
12 | print(x)
13 |
14 | if __name__ == '__main__':
15 | testHeapSort()
--------------------------------------------------------------------------------
/sort/algorithms/HeapSort.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年3月25日
3 |
4 | @author: zwustudy
5 | '''
6 |
7 | class HeapSort:
8 |
9 | def sort(self, lst):
10 | if not lst:
11 | return False
12 | length = len(lst)
13 | start = length // 2 - 1 #地板除,为了取到整数
14 | for x in range(start, -1, -1):
15 | self.adjustHeap(lst, x, length)
16 | index = length - 1
17 | for x in range(index, 0, -1):
18 | self.swap(lst, x, 0)
19 | #因为只是把大顶堆的堆顶元素和最后一个元素进行交换了,整个堆只有第一个元素是不合求的,因此只需要
20 | #把第一个元素沉下去
21 | self.adjustHeap(lst, 0, x)
22 |
23 | '''
24 | 使用异或运算交换元素的值
25 | '''
26 | def swap(self, lst, i, j):
27 | if lst[i] == lst[j]:
28 | return
29 | lst[j] ^= lst[i]
30 | lst[i] ^= lst[j]
31 | lst[j] ^= lst[i]
32 |
33 | '''
34 | 建立大顶堆
35 | '''
36 | def adjustHeap(self, lst, index, length):
37 |
38 | value = lst[index]
39 | x = 2 * index + 1
40 | while x < length:
41 | if x + 1 < length and lst[x] < lst[x + 1]:
42 | x += 1
43 | if value < lst[x]:
44 | lst[index] = lst[x]
45 | index = x
46 | x = 2 * x + 1
47 | lst[index] = value
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/sort/algorithms/__pycache__/HeapSort.cpython-35.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/sort/algorithms/__pycache__/HeapSort.cpython-35.pyc
--------------------------------------------------------------------------------
/test/PrimeProducer.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月14日
4 |
5 | @author: zwustudy
6 | 1、输出所有小于等于max的质数,这里提供两种方法:
7 | producePrime1使用质数判断方法,一直遍历到某一个数的平方根值
8 | producePrime2使用筛选法,筛选剔除小于等于max的所有非质数,剩下的就是质数了
9 | 2、从小到大,输出前m个质数。 筛法的速度远超普通方法,针对这个需求,普通方法很慢,筛法又不适用,因为不知道前m个质数对应的max是多少,
10 | 这怎么办呢?质数越往后越稀疏,有个素数定理就是用来预估max以内有多少质数,最简洁的公式有x/ln(x),会有一定的误差,但是不超过百分之十五
11 | 那么我们可以根据m反推出max的大小
12 | '''
13 | import math
14 | import time
15 |
16 |
17 | '''
18 | 最朴素的判断质数的方法, 即根据质数的定义,一直从2到该数的平方根,判断是否能整除
19 | '''
20 | def producePrime1(max):
21 | for i in range(2, max + 1):
22 | if __isPrime(i): print(i)
23 |
24 | '''
25 | 筛选法找质数,即“埃拉托色尼筛法”,挖掉2的倍数、3的倍数、一直到max的平方根的倍数,剩下的都是质数了
26 | '''
27 | def producePrime2(max):
28 | li = []
29 | for i in range(2, max + 1):
30 | if i > 2 and i % 2 == 0:
31 | li.append(0)
32 | else:
33 | li.append(i)
34 |
35 | for i in range(3, int(math.sqrt(max)) + 1, 2):
36 | if li[i - 2] != 0:
37 | for j in range(i + i, max + 1, i):
38 | li[j - 2] = 0
39 |
40 | for i in li:
41 | if i != 0:
42 | print(i)
43 |
44 | '''
45 | 从小到大,输出前count(count > 10)个质数
46 | 这里先使用素数定理求出count个素数分布的范围,再使用筛选法筛除所有素数,最后输出前count个素数
47 | '''
48 | def producePrePrime(count):
49 | max = int(__findMax(count) * 1.15)
50 | li = []
51 | for i in range(2, max + 1):
52 | if i > 2 and i % 2 == 0:
53 | li.append(0)
54 | else:
55 | li.append(i)
56 |
57 | for i in range(3, int(math.sqrt(max)) + 1, 2):
58 | if li[i - 2] != 0:
59 | for j in range(i + i, max + 1, i):
60 | li[j - 2] = 0
61 |
62 | j = 0
63 | for i in li:
64 | if i != 0:
65 | print(i)
66 | j += 1
67 | if j >= count:
68 | break
69 |
70 |
71 |
72 | '''
73 | 判断number是否是质数
74 | '''
75 | def __isPrime(number):
76 | if number <= 1 : return False
77 | for i in range(2, int(math.sqrt(number)) + 1):
78 | if number % i == 0 :
79 | return False
80 | return True
81 |
82 | '''
83 | 根据素数定理,x/ln(x) >= m 找到最小的一个整数x解,m > 10
84 | '''
85 | def __findMax(m):
86 | if m <= 10:
87 | raise NameError('input illeagal m <= 10!')
88 |
89 | start = m
90 | end = m * 2
91 | while True:
92 | if end / math.log(end,math.e) >= m:
93 | break;
94 | start = end
95 | end = end * 2
96 | index = int((start + end) / 2)
97 | while True:
98 | m1 = index / math.log(index, math.e)
99 | m2 = (index - 1) / math.log(index - 1, math.e)
100 | if m1 >= m and m2 < m:
101 | break;
102 | if m1 >= m:
103 | end = index
104 | else:
105 | start = index
106 | index = int((start + end) / 2)
107 |
108 | return index
109 |
110 | max = 1000000
111 |
112 | start = long(time.time() * 1000)
113 | producePrime1(max)
114 | end1 = long(time.time() * 1000)
115 | producePrime2(max)
116 | end2 = long(time.time() * 1000)
117 |
118 | producePrePrime(10000)
119 |
120 | print("使用质数定义法找出所有小于等于" + str(max) + "质数并输出,总共耗时" + str(end1 - start) + "毫秒")
121 | print("使用筛选法找出所有小于等于" + str(max) + "质数并输出,总共耗时" + str(end2 - end1) + "毫秒")
122 |
--------------------------------------------------------------------------------
/test/WordCounter.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月15日
4 | 统计一篇英文文章各个单词出现的词频,并按单次的词频从大到小输出
5 | @author: minmin
6 | '''
7 | import re
8 | import collections
9 |
10 | '''
11 | 从文件中读取内容,统计词频
12 | '''
13 | def count_word(path):
14 | result = {}
15 | with open(path) as file_obj:
16 | all_the_text = file_obj.read()
17 | #大写转小写
18 | all_the_text = all_the_text.lower()
19 | #正则表达式替换特殊字符
20 | all_the_text = re.sub("\"|,|\.", "", all_the_text)
21 |
22 | for word in all_the_text.split():
23 | if word not in result:
24 | result[word] = 0
25 | result[word] += 1
26 |
27 | return result
28 |
29 |
30 | '''
31 | 以词频倒序
32 | '''
33 | def sort_by_count(d):
34 | #字典排序
35 | d = collections.OrderedDict(sorted(d.items(), key = lambda t: -t[1]))
36 | return d
37 |
38 | if __name__ == '__main__':
39 | file_name = "..\my father.txt"
40 |
41 | dword = count_word(file_name)
42 | dword = sort_by_count(dword)
43 |
44 | for key,value in dword.items():
45 | print(key + ":%d" % value)
46 |
47 |
--------------------------------------------------------------------------------
/whxk/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/whxk/__init__.py
--------------------------------------------------------------------------------
/whxk/com/ContentModifier.py:
--------------------------------------------------------------------------------
1 | '''
2 | Created on 2018年4月18日
3 |
4 | @author: minmin
5 | '''
6 | import os
7 | from os import path
8 |
9 | class ContentModifier:
10 |
11 | def modifier(self, rootDir):
12 |
13 | files = os.listdir(rootDir)
14 | for i in range(0, len(files)):
15 | path = os.path.join(rootDir, files[i])
16 | if os.path.isdir(path):
17 | print("dir:" + os.path.abspath(path))
18 | self.modifier(path)
19 | if os.path.isfile(path):
20 | print("file:" + os.path.abspath(path))
21 |
22 | if __name__ == '__main__':
23 | rootDir = "D:\work\武汉新科\_\_"
24 | ContentModifier().modifier(rootDir)
--------------------------------------------------------------------------------
/whxk/com/__init__.py:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/zwustudy/HelloPython/0671de7adf59311a38aa71d9c0a4999fd5ffc7e1/whxk/com/__init__.py
--------------------------------------------------------------------------------
/with/with_example01.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月16日
4 |
5 | #with_sample
6 | @author: minmin
7 | '''
8 |
9 | class Sample(object):
10 | '''
11 | classdocs
12 | '''
13 | def __enter__(self):
14 | print "In __enter__ function"
15 | return "Foo"
16 |
17 | def __exit__(self, type, value, trace):
18 | print "In __exit__ function"
19 |
20 | def __init__(self):
21 | print "In __init__ function"
22 |
23 | def get_sample():
24 | return Sample()
25 |
26 |
27 | with get_sample() as sample:
28 | print "Sample:", sample
29 |
30 |
--------------------------------------------------------------------------------
/with/with_example02.py:
--------------------------------------------------------------------------------
1 | #coding=utf-8
2 | '''
3 | Created on 2015年8月16日
4 |
5 | @author: minmin
6 | '''
7 |
8 | class Sample(object):
9 | '''
10 | classdocs
11 | '''
12 | def __enter__(self):
13 | return self
14 |
15 | def __exit__(self, type, value, trace):
16 | print "type:", type
17 | print "value:", value
18 | print "trace:", trace
19 |
20 | def do_something(self):
21 | bar = 1 / 0
22 | return bar + 10
23 |
24 | with Sample() as sample:
25 | sample.do_something()
26 |
27 |
28 |
--------------------------------------------------------------------------------