text stringlengths 37 1.41M |
|---|
'''
我们创建一个 job, 分别用 threading 和 一般的方式执行这段程序并且创建一个 list 来存放我们要处理的数据.
在 Normal 的时候, 我们这个 list 扩展4倍;
在 threading 的时候, 我们建立4个线程, 并对运行时间进行对比.
'''
import threading, copy, time
from queue import Queue
def job(l, q):
res = sum(l)
q.put(res)
def multithreading(l):
q = Queue()
threads = []
for i in range(4):
t = threading.Thread(target=job, args=(copy.copy(l), q), name='T%i' % i)
t.start()
threads.append(t)
[t.join() for t in threads]
total = 0
for _ in range(4):
total += q.get()
print(total)
def normal(l):
total = sum(l)
print(total)
if __name__ == '__main__':
l = list(range(1000000))
s_t = time.time()
normal(l*4)
print('normal: ',time.time()-s_t)
s_t = time.time()
multithreading(l)
print('multithreading: ', time.time()-s_t)
'''
【输出结果】:
1999998000000
normal: 0.2830162048339844
1999998000000
multithreading: 0.2710154056549072
【原因】:
所以程序 threading 和 Normal 运行了一样多次的运算.
但是我们发现 threading 却没有快多少,
按理来说, 我们预期会要快3-4倍, 因为有建立4个线程,
但是并没有. 这就是其中的 GIL 在作怪.
'''
|
'''
557. Reverse Words in a String III [Easy]
Given a string, you need to reverse the order of characters in each word within a sentence
while still preserving whitespace and initial word order.
Example 1:
Input: "Let's take LeetCode contest"
Output: "s'teL ekat edoCteeL tsetnoc"
Note: In the string, each word is separated by single space and there will not be any extra space in the string.
[Method 1]: 用split(), join() and string slicing
Time: O(n), where nn is the length of the string.
Space: O(n)
Runtime: 36 ms, faster than 90.28% of Python3 online submissions for Reverse Words in a String III.
Memory Usage: 14.5 MB, less than 7.69% of Python3 online submissions for Reverse Words in a String III.
'''
class Solution:
def reverseWords(self, s: str) -> str:
if not s: return ''
words = s.split(' ')
reverse = [word[::-1] for word in words]
return ' '.join(reverse)
#Or:
return " ".join([i[::-1] for i in s.split()])
'''
[Method 2]: 手写split()和reverse()
Time: O(n)
Runtime: 116 ms, faster than 6.52% of Python3 online submissions for Reverse Words in a String III.
Memory Usage: 14.4 MB, less than 7.69% of Python3 online submissions for Reverse Words in a String III.
'''
class Solution:
def reverseWords(self, s: str) -> str:
if not s: return ''
words = self.split(s, ' ')
rev_words = []
for word in words:
rev_words.append(self.reverse(word))
return ' '.join(rev_words)
def split(self, s, delimiter):
ans = []
word = ''
for char in s:
if char == delimiter:
ans.append(word)
word = ''
continue
word += char
ans.append(word)
return ans
def reverse(self, s):
s = list(s)
mid = len(s)//2
for i in range(mid):
s[i], s[len(s)-1-i] = s[len(s)-1-i], s[i]
return ''.join(s)
'''
[Method 3]: Using Stack
利用stack先进后出的性质,把每一个单词按字符加进stack,
遇到空格时就把stack里的已存单词的字符按顺序一个个Pop到最终要输出的字符串ans里,再加一个空格隔开;
要特别注意的是,输入字符串里的末端是没有空格的,所以我们最后要手动地把存在stack里的最后一个单词按老方法加入ans。
Time: O(n)
Runtime: 124 ms, faster than 5.18% of Python3 online submissions for Reverse Words in a String III.
Memory Usage: 14.1 MB, less than 7.69% of Python3 online submissions for Reverse Words in a String III.
'''
class Solution:
def reverseWords(self, s: str) -> str:
stack, ans = [], ''
for char in s:
if char == ' ':
while stack:
ans += stack.pop()
ans += ' '
continue
stack.append(char)
while stack:
ans += stack.pop()
return ans
'''
#也可以手动地给输入字符串末端添加空格,最后输出时切片处理去掉开始的空格:
Runtime: 120 ms, faster than 5.81% of Python3 online submissions for Reverse Words in a String III.
Memory Usage: 14.2 MB, less than 7.69% of Python3 online submissions for Reverse Words in a String III.
'''
class Solution:
def reverseWords(self, s: str) -> str:
s = s + ' '
stack, ans = [], ''
for char in s:
if char == ' ':
while stack:
ans += stack.pop()
ans += ' '
continue
stack.append(char)
return ans[:-1]
'''
#Or:
Runtime: 120 ms, faster than 5.81% of Python3 online submissions for Reverse Words in a String III.
Memory Usage: 14.1 MB, less than 7.69% of Python3 online submissions for Reverse Words in a String III.
'''
class Solution:
def reverseWords(self, s: str) -> str:
s = s + " "
stack, res=[], ""
for i in s:
stack.append(i)
if i == " ":
while stack:
res += stack.pop()
return res[1:]
'''
还可以用双指针l,r标记单词的首位,遇到空格就把单词反着加进输出字符串并且更新l,r;
但是添加单词的过程中实际上还是用的stack结构,或者再从r循环到l添加,但是这样的话时间复杂度就大大增加了。
'''
|
'''
10. Regular Expression Matching [Hard]
Given an input string (s) and a pattern (p),
implement regular expression matching with support for '.' and '*'.
'.' Matches any single character.
'*' Matches zero or more of the preceding element.
The matching should cover the entire input string (not partial).
Note:
s could be empty and contains only lowercase letters a-z.
p could be empty and contains only lowercase letters a-z, and characters like . or *.
Example 1:
Input:
s = "aa"
p = "a"
Output: false
Explanation: "a" does not match the entire string "aa".
Example 2:
Input:
s = "aa"
p = "a*"
Output: true
Explanation: '*' means zero or more of the preceding element, 'a'.
Therefore, by repeating 'a' once, it becomes "aa".
Example 3:
Input:
s = "ab"
p = ".*"
Output: true
Explanation: ".*" means "zero or more (*) of any character (.)".
Example 4:
Input:
s = "aab"
p = "c*a*b"
Output: true
Explanation: c can be repeated 0 times, a can be repeated 1 time. Therefore, it matches "aab".
Example 5:
Input:
s = "mississippi"
p = "mis*is*p*."
Output: false
[Method 1]: Recursion
Intuition
If there were no Kleene stars (the * wildcard character for regular expressions),
the problem would be easier
- we simply check from left to right if each character of the text matches the pattern.
When a star is present, we may need to check many different suffixes of the text
and see if they match the rest of the pattern.
A recursive solution is a straightforward way to represent this relationship.
If a star is present in the pattern, it will be in the second position pattern[1].
Then, we may ignore this part of the pattern, or delete a matching character in the text.
If we have a match on the remaining strings after any of these operations,
then the initial inputs matched.
Runtime: 1532 ms, faster than 5.78% of Python3 online submissions for Regular Expression Matching.
Memory Usage: 12.7 MB, less than 100.00% of Python3 online submissions for Regular Expression Matching.
'''
class Solution:
def isMatch(self, s: str, p: str) -> bool:
if not p: return not s
if '*' not in p:
return self.match(s, p)
first_match = bool(s) and p[0] in {s[0], '.'}
if len(p) >= 2 and p[1] == '*':
return self.isMatch(s,p[2:]) or first_match and self.isMatch(s[1:],p)
return first_match and self.isMatch(s[1:],p[1:])
def match(self, s, p):
if not p: return not s
first_match = bool(s) and p[0] in {s[0], '.'}
return first_match and self.match(s[1:], p[1:])
'''
[Method 2]: Recursion + dictionary (dp)
[Time]: O(len(s)*len(p))
[Space]: O(len(s)*len(p))
Runtime: 64 ms, faster than 37.08% of Python3 online submissions for Regular Expression Matching.
Memory Usage: 12.8 MB, less than 100.00% of Python3 online submissions for Regular Expression Matching.
'''
class Solution:
def isMatch(self, s: str, p: str) -> bool:
self.memo = dict()
def dp(i, j):
if (i,j) in self.memo:
return self.memo[(i, j)]
if j == len(p): return i == len(s)
first_match = i < len(s) and p[j] in {s[i], '.'}
if j <= len(p)-2 and p[j+1] == '*':
ans = dp(i, j+2) or (first_match and dp(i+1, j))
else:
ans = first_match and dp(i+1, j+1)
self.memo[(i,j)] = ans
return ans
return dp(0,0)
'''
[Method 3]: DP
[Time]: O(len(s)*len(p))
[Space]: O(len(s)*len(p))
Runtime: 96 ms, faster than 29.08% of Python3 online submissions for Regular Expression Matching.
Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Regular Expression Matching.
'''
class Solution(object):
def isMatch(self, text, pattern):
dp = [[False] * (len(pattern) + 1) for _ in range(len(text) + 1)]
dp[-1][-1] = True
for i in range(len(text), -1, -1):
for j in range(len(pattern) - 1, -1, -1):
first_match = i < len(text) and pattern[j] in {text[i], '.'}
if j+1 < len(pattern) and pattern[j+1] == '*':
dp[i][j] = dp[i][j+2] or first_match and dp[i+1][j]
else:
dp[i][j] = first_match and dp[i+1][j+1]
return dp[0][0]
'''
One-line cheatsheet:
'''
import re
class Solution:
def isMatch(self, s, p):
return s in re.findall(p, s)
# or:
class Solution:
def isMatch(self, s, p):
return bool(re.match(r"%s" %p, s)) and re.match(r"%s" %p, s).group() == s
|
'''
最简易版的聊天室服务端,仅用一个线程来收消息。只支持建立一个TCP socket连接。
[注意]:
1.socket连接的正常关闭(即双方都close)需要双方发送'exit'消息。
2.如果客户端主动断开,则服务端的收消息线程rec因为收到了'exit'消息所以跳出循环,终止线程,
但是主函数会因继续尝试给客户端发送消息而报错,因此主函数必须设置一个try/except捕捉exception;
但是客户端的收消息rec仍继续等待从已经断开了的socket收消息,则会报错,所以也必须设置try/except来避免bug。
同时因为服务端主函数的input()阻塞,所以服务端也该应该发出'exit'来正确地断开服务端这边的socket连接。
3.如果是服务端主动断开,即主函数因发送'exit'而break出来主动关闭socket,
则客户端的收消息线程rec也收到'exit'而终结,客户端的主函数也发送'exit'即可断开,
那么服务端收消息的rec线程收到'exit'则顺利终结线程。
'''
import socket, threading
s = socket.socket(socket.AF_INET,socket.SOCK_STREAM)
s.bind((socket.gethostname(), 1234))
s.listen(2)
sock,addr = s.accept()
print(f'Connection from {addr} is established!')
true = True
def rec(sock):
global true
while true:
msg_received = sock.recv(1024).decode()
if msg_received == 'exit': # 只要有一方发出'exit',都会断开socket连接
true = False
print('He/She has ended the conversation.') # 客户端方已断开连接
break #线程终结
if true:
print('Him/Her:', msg_received)
#创建线程来专门接收消息, target是线程函数名,args是一个元祖,包含了传入该函数的参数,
# 即已经连接好了的socket
trd = threading.Thread(target = rec, args = (sock,))
trd.start()
print('Server Thread rec started')
#发送消息:
while true:
msg_for_client = input()
try: # 如果客户端主动断开连接,服务端仍继续发送消息则会报错,因为消息发不出去
sock.send(msg_for_client.encode())
if msg_for_client == 'exit': # 服务端断开连接
true = False
print('You have ended the conversation.')
break
except: #当客户端突然断开连接的时候会报错
break
print('Closing socket from server')
s.close()
|
#服务端
from socket import *
import select
server = socket(AF_INET, SOCK_STREAM)
server.bind(('127.0.0.1',8093))
server.listen(5)
# 设置为非阻塞
server.setblocking(False)
# 初始化将服务端socket对象加入监听列表,后面还要动态添加一些conn连接对象,当accept的时候socket就有感应,当recv的时候conn就有动静
rlist=[server,]
rdata = {} #存放客户端发送过来的消息
wlist=[] #等待写对象
wdata={} #存放要返回给客户端的消息
print('Server starts listening ...')
count = 0 #写着计数用的,为了看实验效果用的,没用
while True:
# 开始 select 监听,对rlist中的服务端server进行监听,select函数阻塞进程,直到rlist中的套接字被触发
#此例中,套接字接收到客户端发来的握手信号,从而变得可读,满足select函数的“可读”条件
# 被触发的(有动静的)套接字(服务器套接字)返回赋给了rl里面;
rl,wl,xl = select.select(rlist,wlist,[],1)
print('次数 %s >>'%(count),rl)
count = count + 1
# 对rl进行循环判断是否有客户端连接进来,当有客户端连接进来时select将触发
for sock in rl:
# 判断当前触发的是不是socket对象, 当触发的对象是socket对象时,说明有新客户端accept连接进来了
if sock == server:
# 接收客户端的连接, 获取客户端对象和客户端地址信息
conn,addr = sock.accept()
print(f'Connected with {addr}')
# 把新的客户端连接加入到监听列表中,当客户端的连接有接收消息的时候,select将被触发,会知道这个连接有动静,有消息,那么返回给rl这个返回值列表里面。
rlist.append(conn)
else:
# 由于客户端连接进来时socket接收客户端连接请求,将客户端连接加入到了监听列表中(rlist),客户端发送消息的时候这个连接将触发
# 所以判断是否是客户端连接对象触发
try:
data = sock.recv(1024)
#当客户端主动断开后就会发送'',所以没有数据的时候,我们将这个连接关闭掉,并从监听列表中移除
if not data:
sock.close()
rlist.remove(sock)
print(f'Client {sock} closed.')
continue
print("Received {0} from client {1}".format(data.decode(), sock['rddr']))
#将接受到的客户端的消息保存下来
rdata[sock] = data.decode()
#将客户端连接对象和这个对象接收到的消息大写加工成返回消息,并添加到wdata这个字典里面
wdata[sock] = data.upper()
#需要给这个客户端回复消息的时候,我们将这个连接添加到wlist写监听列表中
wlist.append(sock) # 改变了select的input参数,只有下一轮select阻塞时wl才会有返回
#如果这个连接出错了,客户端暴力断开了(注意,我还没有接收他的消息,或者接收他的消息的过程中出错了)
except Exception:
#关闭这个连接
sock.close()
#在监听列表中将他移除,因为不管什么原因,它毕竟是断开了,没必要再监听它了
rlist.remove(sock)
# 如果现在没有客户端请求连接,也没有客户端发送消息时,开始对发送消息列表进行处理,是否需要发送消息
print('Outside of the select loop')
for sock in wl:
print(f'Sending {wdata[sock].decode()} to client {sock}')
sock.send(wdata[sock])
wlist.remove(sock)
wdata.pop(sock)
#将一次select监听列表中有接收数据的conn对象所接收到的消息打印一下
for k,v in rdata.items():
print(k,'发来的消息是:',v)
#清空接收到的消息
rdata.clear()
|
'''
[Pool]
如果要启动大量的子进程,可以用进程池的方式批量创建子进程:
'''
from multiprocessing import Pool,cpu_count
import os,time,random
def task(name):
print('result is %s' %(name**2))
return name**2
def long_time_task(name):
print('Run task %s (%s)' % (name, os.getpid()))
start = time.time()
time.sleep(random.random()*3)
end = time.time()
print('Task %s runs %0.2f seconds' % (name, end-start))
if __name__ == '__main__':
print('This computer has %s cores.' % cpu_count())
print('Parent process (%s).' % os.getpid())
p = Pool(4) # if not passing it paramter, the default value will be set to the number of cpu cores
for i in range(1,7): #一下子创建6个进程,但是因为进程池容量为4,所以后两个进程要等一下
p.apply_async(long_time_task,args=(i,))
print('Waiting for all processes to finish...')
p.close()
p.join()
print('All subprocesses done.\n')
# Results:
'''
This computer has 4 cores.
Parent process (7608).
Waiting for all processes to finish...
Run task 1 (8812)
Run task 2 (8544)
Run task 3 (8876)
Run task 4 (5360)
Task 3 runs 1.02 seconds
Run task 5 (8876)
Task 2 runs 1.10 seconds
Run task 6 (8544)
Task 1 runs 1.61 seconds
Task 4 runs 1.80 seconds
Task 6 runs 1.47 seconds
Task 5 runs 2.64 seconds
All subprocesses done.
【代码注解】
1.pool.apply_async() 采用异步的方式调用task, pool.apply() 则是同步调用,
意味着下一个task需要等上一个task完成后才能开始运行,这不符合我们cpu并行处理的目的,
所以采用异步方式连续第提交任务。
2.对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),
即关闭进程池,之后就不能继续添加新的Process了。
也可以直接用 with...as...操作:
'''
results = []
with Pool(4) as p:
for i in range(1,7):
result = p.apply_async(long_time_task, args=(i,))
results.append(result)
p.join()
print('Results: ',results)
'''
结果为:
Results: [<multiprocessing.pool.ApplyResult object at 0x02731950>, <multiproces
sing.pool.ApplyResult object at 0x027245F0>, <multiprocessing.pool.ApplyResult o
bject at 0x027249B0>, <multiprocessing.pool.ApplyResult object at 0x027249D0>, <
multiprocessing.pool.ApplyResult object at 0x02724230>, <multiprocessing.pool.Ap
plyResult object at 0x008749B0>]
运行时long_time_task里面的print()都没打印出来,
但是不用with...as...就可以。
'''
|
'''
509. Fibonacci Number [Easy]
The Fibonacci numbers, commonly denoted F(n) form a sequence, called the Fibonacci sequence, such that each number is the sum of the two preceding ones, starting from 0 and 1. That is,
F(0) = 0, F(1) = 1
F(N) = F(N - 1) + F(N - 2), for N > 1.
Given N, calculate F(N).
Example 1:
Input: 2
Output: 1
Explanation: F(2) = F(1) + F(0) = 1 + 0 = 1.
Example 2:
Input: 3
Output: 2
Explanation: F(3) = F(2) + F(1) = 1 + 1 = 2.
Example 3:
Input: 4
Output: 3
Explanation: F(4) = F(3) + F(2) = 2 + 1 = 3.
Note:
0 ≤ N ≤ 30.
[Method]: Top-Down Recursion using Memoization(hashmap)
[Time]: O(n). Each number, starting at 2 up to and including N,
is visited, computed and then stored for O(1) access later on.
[Space]: O(n)
Runtime: 28 ms, faster than 85.08% of Python3 online submissions for Fibonacci Number.
Memory Usage: 12.6 MB, less than 100.00% of Python3 online submissions for Fibonacci Number.
'''
import unittest
class Solution(object):
def Fibonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n < 0:
raise ValueError('n shouldn\'t be negative.')
if n < 2:
return n
self.cache = {0:0,1:1}
return self.helper(n)
def helper(self, n):
if n in self.cache:
return self.cache[n]
self.cache[n] = self.helper(n-2) + self.helper(n-1)
return self.cache[n]
class TestFib(unittest.TestCase):
def setUp(self):
self.sol = Solution()
def test_value(self):
self.assertRaises(ValueError, self.sol.Fibonacci,-2)
self.assertEqual(self.sol.Fibonacci(0), 0)
self.assertEqual(self.sol.Fibonacci(1), 1)
def test_n(self):
self.assertEqual(self.sol.Fibonacci(5), 5)
self.assertEqual(self.sol.Fibonacci(4), 3)
self.assertEqual(self.sol.Fibonacci(30), 832040)
if __name__ == '__main__':
unittest.main()
'''
[Method 2]:
'''
class Solution:
def fib(self, N: int) -> int:
if (N <= 1):
return N
A = [[1, 1], [1, 0]]
self.matrix_power(A, N-1)
return A[0][0]
def matrix_power(self, A: list, N: int):
if (N <= 1):
return A
self.matrix_power(A, N//2)
self.multiply(A, A)
B = [[1, 1], [1, 0]]
if (N%2 != 0):
self.multiply(A, B)
def multiply(self, A: list, B: list):
x = A[0][0] * B[0][0] + A[0][1] * B[1][0]
y = A[0][0] * B[0][1] + A[0][1] * B[1][1]
z = A[1][0] * B[0][0] + A[1][1] * B[1][0]
w = A[1][0] * B[0][1] + A[1][1] * B[1][1]
A[0][0] = x
A[0][1] = y
A[1][0] = z
A[1][1] = w
|
'''
69. Sqrt(x) (Easy)
Method 1: Binary Search: O(lgn)
'''
class Solution:
def mySqrt(self, x: int) -> int:
if x == 0:
return 0
left, right = 1, x
while left <= right:
mid = left + (right - left) // 2
if mid == x // mid:
return mid
if mid < x // mid:
left = mid + 1
else:
right = mid - 1
return right
'''
Method 2: Newton's Method
Runtime: 16 ms, faster than 92.83% of Python online submissions for Sqrt(x).
Memory Usage: 11.9 MB, less than 5.88% of Python online submissions for Sqrt(x).
Using Newton's method, the time complexity of calculating a root of a function f(x) with n-digit precision,
provided that a good initial approximation is known,
is O((log n) F(n)) where F(n) is the cost of calculating f(x)/f'(x), with n-digit precision.
'''
def my_Sqrt(x):
r = x
while r*r > x:
r = (r + x//r) // 2
return r
'''
Functional version:
'''
def average(x, y):
return (x + y)/2
def improve(update, close, guess=1):
while not close(guess):
guess = update(guess)
return guess
def approx_eq(x, y, tolerance=1e-3):
return abs(x - y) < tolerance
def sqrt(a):
def sqrt_update(x):
return average(x,a/x)
def sqrt_close(x):
return approx_eq(x * x, a)
return improve(sqrt_update, sqrt_close)
result = sqrt(256)
'''
239. Sliding Window Maximum (Hard)
1.Heap O(N logK)
'''
class Solution:
def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
if not nums:
return []
hp = [-x for x in nums[:k]]
heapq.heapify(hp)
ans = [-hp[0]]
wait_to_pop = collections.Counter()
for i in range(k, len(nums)):
out_x, in_x = nums[i-k], nums[i]
wait_to_pop[out_x] += 1
heapq.heappush(hp, -in_x)
while wait_to_pop[-hp[0]] > 0:
wait_to_pop[-hp[0]] -= 1
heapq.heappop(hp)
ans.append(-hp[0])
return ans
'''
2. O(n) solution using deque
Keep indexes of good candidates in deque d.
The indexes in d are from the current window, they're increasing,
and their corresponding nums are decreasing.
Then the first deque element is the index of the largest window value.
For each index i:
Pop (from the end) indexes of smaller elements (they'll be useless).
Append the current index.
Pop (from the front) the index i - k, if it's still in the deque (it falls out of the window).
If our window has reached size k, append the current window maximum to the output.
'''
from collections import deque
class Solution(object):
def maxSlidingWindow(self, nums, k):
"""
:type nums: List[int]
:type k: int
:rtype: List[int]
"""
q = deque()
result = []
for i in range(len(nums)):
# pop it if the first/left (max) element is out of the current window
if q and i - q[0] == k:
q.popleft()
# Can only pop element of deque when it's not empty
while q:
# pop useles elements from last/right of the queue
if nums[q[-1]] < nums[i]:
q.pop()
# if the right side ele is less than q[-1], break the while loop
else:
break
# Not adding index of ele less than q[-1]
q.append(i)
# Start adding result when it's a full window
if i >= k-1: # i == k-1 is the beginning of a full window
result.append(nums[q[0]])
return result
# Or:
def maxSlidingWindow(self, nums, k):
d = collections.deque()
out = []
for i, n in enumerate(nums):
while d and nums[d[-1]] < n:
d.pop()
d += i,
if d[0] == i - k:
d.popleft()
if i >= k - 1:
out += nums[d[0]],
return out
'''
Last three lines could be this, but for relatively large k it would waste space:
out += nums[d[0]],
return out[k-1:]
Documentation about Deque:
https://docs.python.org/2/library/collections.html#collections.deque
https://www.geeksforgeeks.org/deque-in-python/
https://pymotw.com/2/collections/deque.html
'''
'''
3. Brute Force:
Python O(kn) one-liner:
'''
def maxSlidingWindow(self, nums, k):
return nums and [max(nums[i:i+k]) for i in range(len(nums)-k+1)]
|
import time
import queue
import threading
def worker(i):
while True:
item = q.get()
if item is None:
print("线程%s发现了一个None,可以休息了^-^" % i)
break
# do_work(item)做具体的工作
time.sleep(0.5)
print("线程%s将任务<%s>完成了!" % (i, item))
# 做完后发出任务完成信号,然后继续下一个任务
q.task_done()
if __name__ == '__main__':
num_of_threads = 5
source = [i for i in range(1, 21)] # 模拟20个任务
# 创建一个FIFO队列对象,不设置上限
q = queue.Queue()
# 创建一个线程池
threads = []
# 创建指定个数(5)的工作线程,并放到线程池threads中
for i in range(1, num_of_threads+1):
t = threading.Thread(target=worker, args=(i,))
threads.append(t)
t.start()
# 将任务源里的任务逐个放入队列
for item in source:
time.sleep(0.5) # 每隔0.5秒发布一个新任务
q.put(item)
# 阻塞队列直到队列里的任务都完成了
q.join()
print("-----工作都完成了-----")
# 停止工作线程
for i in range(num_of_threads):
q.put(None)
for t in threads:
t.join() # 虽然是同步结束,但是因为之前线程阻塞来get queue里的任务,所以哪个线程先拿到任务是不确定的,
# 因此print("线程%s发现了一个None,可以休息了^-^" % i)的次序也不一样,但是线程的结束是同步的
print(threads)
'''
【可能输出结果】(每次运行结果都不一样):
线程1将任务<1>完成了!
线程2将任务<2>完成了!
线程3将任务<3>完成了!
线程4将任务<4>完成了!
线程5将任务<5>完成了!
线程1将任务<6>完成了!
线程2将任务<7>完成了!
线程3将任务<8>完成了!
线程4将任务<9>完成了!
线程5将任务<10>完成了!
线程1将任务<11>完成了!
线程2将任务<12>完成了!
线程3将任务<13>完成了!
线程4将任务<14>完成了!
线程5将任务<15>完成了!
线程1将任务<16>完成了!
线程2将任务<17>完成了!
线程3将任务<18>完成了!
线程3将任务<19>完成了!
线程5将任务<20>完成了!
-----工作都完成了-----
线程1发现了一个None,可以休息了^-^
线程3发现了一个None,可以休息了^-^
线程5发现了一个None,可以休息了^-^
线程4发现了一个None,可以休息了^-^
线程2发现了一个None,可以休息了^-^
[<Thread(Thread-1, stopped 4172)>, <Thread(Thread-2, stopped 4976)>, <Thread(Thr
ead-3, stopped 6596)>, <Thread(Thread-4, stopped 5852)>, <Thread(Thread-5, stopp
ed 3344)>]
'''
|
'''
92. Reverse Linked List II [Medium]
Reverse a linked list from position m to n. 反转从位置 m 到 n 的链表。
Do it in one-pass. 请使用一趟扫描完成反转。
Note: 1 ≤ m ≤ n ≤ length of list.
Example:
Input: 1->2->3->4->5->NULL, m = 2, n = 4
Output: 1->4->3->2->5->NULL
[Method 1]: 迭代 + dummy node + 多指针:
记住要反转部分的前一个节点 begin,要反转部分的开头节点(即为反转后部分的尾节点)end,
然后按照全部分反转的思路,对要反转的节点记录prev和nxt,反转完后的prev即为反转后部分链表的起始节点,
nxt则为反转前该部分链表的后面部分,此时将begin的指针连改到指向prev, end的指针改向连接nxt,
返回dummy.next即可。
[Time]: O(n),按题意,只需一次遍历。
[Space]: O(1),只是改变了指针。
Runtime: 20 ms, faster than 46.08% of Python online submissions for Reverse Linked List II.
Memory Usage: 12 MB, less than 60.00% of Python online submissions for Reverse Linked List II.
'''
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head or m > n: return
if m == n: return head
dummy = ListNode(0) #以防m==1的情况
dummy.next = head
cur = dummy
count = 0
while count < m-1:
cur = cur.next
count += 1
begin = cur # prev of the node to start reversion
cur = cur.next
count += 1
end = cur # end node of the reversed linked list
prev, nxt = None, None
while count <= n:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
count += 1
begin.next = prev
end.next = nxt
return dummy.next
# or: without dummy node
# 需要reverse的部分按照reverse linked list I的方法做,
# 最后判断reverse部分的前后还有没有节点,
# 如果有,还需要将前后连接起来,返回head,
# 否则就直接返回反转后的链表的头结点pre
class Solution:
def reverseBetween(self, head: ListNode, m: int, n: int) -> ListNode:
if not head or m > n: return head
i = 1
start, cur = None, head
while i < m and cur:
start = cur
cur = cur.next
i += 1
last, pre = cur, None
while i <= n and cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
i += 1
if start: # if m != 1
start.next = pre
if cur:
last.next = cur
return head if start else pre
'''
[Method 2]: 递归
'''
|
def largest_twice(nums):
largest = second = 0
for i in range(len(nums)):
if largest < nums[i]:
second, largest = largest, nums[i]
index = i
elif second < nums[i]:
second = nums[i]
return index if largest >= second * 2 else -1
nums = [1, 2,3,8,3,2,1]
|
'''
169. Majority Element [Easy]
Given an array of size n, find the majority element.
The majority element is the element that appears more than ⌊ n/2 ⌋ times.
You may assume that the array is non-empty and the majority element always exist in the array.
Example 1:
Input: [3,2,3]
Output: 3
Example 2:
Input: [2,2,1,1,1,2,2]
Output: 2
[Method 1]: Boyer-Moore Voting Algorithm
不同就cancel,相同就保留,最后剩下的必然是众数。
但是因为我们用的列表,删除操作不方便,所以可以用两个变量,一个candidate初始为nums[0],
一个count初始化为1记录当前遇到的candidate的个数,如果当前遍历到的数字num和candidate相同,
count += 1,否则减1,但当count为0时,也就是说candidate被之前遍历的数字消掉了(像消消乐一样配对消掉了),
那么我们就把num作为新的candidate,把count设置为1,继续遍历下一个元素,直到遍历完后返回最后的candidate即可。
[Time]: O(n)
[Space]: O(1)
Runtime: 176 ms, faster than 74.11% of Python3 online submissions for Majority Element.
Memory Usage: 14.4 MB, less than 26.19% of Python3 online submissions for Majority Element.
'''
class Solution:
def majorityElement(self, nums: List[int]) -> int:
if not nums: return
count = 1
candidate = nums[0]
for i in range(1, len(nums)):
if nums[i] == candidate:
count += 1
elif count == 0:
candidate = nums[i]
count += 1
else:
count -= 1
return candidate
# or:
def majorityElement(nums):
count, cand = 0, 0
for num in nums:
if num == cand:
count += 1
elif count == 0:
cand, count = num, 1
else:
count -= 1
return cand
|
'''
【动态规划】
0-1 背包问题 0/1 Knapsack Problem
完全背包问题 Unbounded Knapsack Problem
最小路径和(详细可看 Minimum Path Sum)
编程实现莱文斯坦最短编辑距离
编程实现查找两个字符串的最长公共子序列
编程实现一个数据序列的最长递增子序列
Note:
递归不是动态规划,不能混淆,二者有相通的地方:递归是自顶向下,动归是自底向上。
动归是递归综合备忘录算法以后的反向思维形式。
动态规划算法通常基于一个递推公式及一个或多个初始状态。
当前子问题的解将由上一次子问题的解推出。
使用动态规划来解题只需要多项式时间复杂度, 因此它比回溯法、暴力法等要快许多。
'''
'''
1. 0-1背包问题
假设我们有n件物品,分别编号为0, 2...n-1,每个只有1件。
其中编号为i的物品价值为value[i],它的重量为weight[i]。
为了简化问题,假定价值和重量都是整数值。
现在,假设我们有一个背包,它能够承载的重量是capacity。
现在,我们希望往包里装这些物品,使得包里装的物品价值最大化,那么我们该如何来选择装的东西呢?
[思路]:
1.首先我们先构建一个表格dp[i][j],横轴为各个可选择的物品,纵轴为背包的容纳重量(从1到背包的实际最大容纳)。
dp[i][j]表示前i个物品放入容量为j的背包中可以获得的最大价值。
2.状态转移方程为:
dp[i][j] = max{dp[i-1][j], dp[i-1][j-weight[i]] + value[i]}
即,“将前i件物品放入容量为j的背包中”这个子问题,若只考虑第i件物品的策略(放或者不放),
则可转化为一个只牵扯前i-1件物品的问题:
1.若不放当前的第i件物品,则问题转化为“前i-1件物品放入容量为j的背包中”,价值为dp[i-1][j];
2.若放当前的第i件物品,则问题转化为“先将前i-1件物品放入剩下容量为j-weight[i-1]的背包中,再放入当前第i件物品”,
价值为dp[i-1][j-weight[i]] + value[i]。
[优化空间复杂度]:
以上方法的时间和空间复杂度都为O(n*capacity),其中时间复杂度基本已经不能再优化了,
但空间复杂度却可以优化到O(capacity)。
因为dp[i][j]只和上一层的两个状态有关,所以可以将状态转化为一维数组:
dp[j] = max(dp[j],dp[j-weight[i]] + value[i]);
即要推dp[j],必须保证dp[j]是从dp[j-weight[i]]推出来的。
如果j是顺序递增的,则dp[i][j]是由dp[i][j-weight[i]]推出来的,并非由原来的dp[i-1][j-weight[i]]推导得到的。
E.g.
开始循环前,即背包为空时,dp[0]到最大容量dp[5]的值都为0.
开始循环后,我们需要比较dp[j](即循环前的值)和dp[j-weight[i]] + value[i];
因为是顺序循环,j-weight[i] < j, 因此dp[j-weight[i]]会成为前面才刚刚被赋值过得值,
例如当i = 0,
从j=1(至少要让背包容量大于等于物品重量,不然为负没有意义)开始循环,dp[1] = max(dp[1],dp[1-1]+1500) = max(0,1500) = 1500,
(即dp[0][1] = 1500,即背包容量为1时刚好可以放第0件物品,所获得的最大价值为该物品的价值1500.)
然后dp[2] = max(dp[2], dp[2-1] + 1500) = max(0, dp[1] + 1500) = 1500 + 1500 = 3000,
注意!!!
这个时候的dp[j-weight[i]]就成了dp[1],而这个dp[1]是我们刚才才更新的值,是当前的dp[i],并不是由dp[i-1]得到的,
而且此时我们明明只是想把第一个物品(i=0)放进容量为2的背包里,得到的最大价值只是第一个物品的价值,即1500而已,
又怎么可能是3000?所以由此可知0-1背包问题中j不可顺序循环,而是逆序。
https://blog.csdn.net/xiajiawei0206/article/details/19933781
'''
#0-1 背包问题
def knapsack1(weight, value, capacity):
'''
>>> knapsack1([], [], 10)
0
>>> knapsack1([3], [10], 0)
0
>>> knapsack1([4], [15], 4)
15
>>> knapsack1([4], [15], 10)
15
>>> knapsack1([4], [15], 3)
0
>>> weight = [1, 2, 3, 8, 7, 4]
>>> value = [20, 5, 10, 40, 15, 25]
>>> capacity = 10
>>> knapsack1(weight, value, capacity)
60
>>> weight = [10, 20, 30]
>>> value = [60, 100, 120]
>>> capacity = 50
>>> knapsack1(weight, value, capacity)
220
'''
#winpty python -m doctest knapsack_problem_0_1.py
n = len(weight)
if n < 1 or capacity < 1: return 0
dp = [0]*(capacity + 1)
for item in range(n):
for j in range(capacity, weight[item]-1, -1):
dp[j] = max(dp[j], dp[j - weight[item]] + value[item])
return dp[capacity]
'''
拓展:01硬币找零问题(01背包)
给定不同面额的硬币 coins 和总金额 m。每个硬币最多选择一次。
计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
同理,dp[i][j]表示选取当前第i个硬币能凑成总金额为j时最少的硬币个数,
即不拿当前第i个硬币时只用之前的硬币可以凑成j块钱所需最少硬币个数dp[i-1][j],
与拿当前第i个硬币加上拿之前的硬币凑成j-Coins[i]块钱的硬币数量之和dp[i-1][j-coins[i]] + 1 的最小值。
即写成状态转移方程如下:
dp[i][j] = min(dp[i-1][j], dp[i-1][j-coins[i]] + 1)
同样,我们来优化空间复杂度,依然必须从最大总金额amount开始逆序枚举(枚举到当前硬币i的比值,不然j-coins[i]为负没有意义)。
dp[j] = min(dp[j], dp[j-coins[i]] + 1)
因为这道题是求最少硬币个数,在状态转移方程中用的是min(),所以初始化dp矩阵时给每个值都设为最大值float('inf'),
边界情况为dp[0] = 0, 表示凑出金额为0的最小个数是0个。(但是若本身输入amount为0,则没有硬币组合,返回-1)
最后检查dp[amount], 如果值为'inf', 则说明找不到硬币组合,输出-1,反之才输出相应硬币组合的个数。
[注意]:其实在主循环循环到最后一个硬币时的从amount开始的内循环的第一步就可以结束了,因为我们只需要dp[amount],
但是接着循环的话可以更新其他amount的硬币组合,毕竟多考虑了一个硬币的情况。
'''
#0-1 硬币找零问题
def coinChange1(coins, amount):
'''
>>> coinChange1([2], 1)
-1
>>> coins = [2, 3, 5]
>>> coinChange1(coins, 10)
3
>>> coinChange1(coins, 11)
-1
>>> coinChange1(coins, 0)
-1
>>> coins = [2, 1, 2, 3, 5]
>>> coinChange1(coins, 10)
3
>>> coinChange1(coins, 11)
4
>>> coinChange1(coins, 5)
1
>>> coinChange1(coins, 6)
2
'''
n = len(coins)
if n < 1 or amount < 1: return -1
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for j in range(amount, coin-1, -1):
dp[j] = min(dp[j], dp[j-coin] + 1)
print(dp)
return dp[amount] if dp[amount] != float('inf') else -1
'''
2.完全背包问题 Unbounded Knapsack Problem
假设我们有n种物品,分别编号为0, 2...n-1,每种物品有多件。
其中编号为i的物品价值为value[i],它的重量为weight[i]。
为了简化问题,假定价值和重量都是整数值。
现在,假设我们有一个背包,它能够承载的重量是capacity。
现在,我们希望往包里装这些物品,使得包里装的物品价值最大化,那么我们该如何来选择装的东西呢?
[思路]
这个问题非常类似于01背包问题,所不同的是每种物品有无限件。
也就是从每种物品的角度考虑,与它相关的策略已并非取或不取两种,而是有取0件、取1件、取2件……等很多种。
如果仍然按照解01背包时的思路,令DP[i][j]表示前i种物品恰放入一个容量为v的背包的最大权值。
仍然可以按照每种物品不同的策略写出状态转移方程,像这样:
DP[i][j] = max{DP[i-1][j-k*weight[i]] + k*value[i] | 0 <= k*weight[i] <= j}
这跟01背包问题一样有O(n*capacity)个状态需要求解,但求解每个状态的时间已经不是常数了,
求解状态DP[i][j]的时间是O(capacity/weight[i]),(即k的最大值),
总的复杂度为O(n*capacity*Σ(capacity/weight[i])),是比较大的。
[代码优化]:
完全背包问题有一个很简单有效的优化,是这样的:
若两件物品i、j满足weight[i] <= weight[j]且value[i] >= value[j],则将物品j去掉,不用考虑。
即,如果一个物品A是占的地少且价值高,而物品B是占地多,但是价值不怎么高,那么肯定是优先考虑A物品的。
对于随机生成的数据,这个方法往往会大大减少物品的件数,从而加快速度。
然而这个并不能改善最坏情况的复杂度,因为有可能特别设计的数据可以一件物品也去不掉。
这个优化可以简单的O(N^2)地实现,一般都可以承受。
另外,针对背包问题而言,比较不错的一种方法是:
首先将重量大于capacity的物品去掉,然后使用类似计数排序的做法,
计算出重量相同的物品中价值最高的是哪个,可以O(capacity+n)地完成这个优化。
[转化为01背包问题求解]
既然01背包问题是最基本的背包问题,那么我们可以考虑把完全背包问题转化为01背包问题来解。
最简单的想法是,考虑到第i种物品最多选capacity/weight[i]件,
于是可以把第i种物品转化为capacity/weight[i]件费用及价值均不变的物品,然后求解这个01背包问题。
这样完全没有改进基本思路的时间复杂度,但这毕竟给了我们将完全背包问题转化为01背包问题的思路:将一种物品拆成多件物品。
更高效的转化方法是:把第i种物品拆成费用为weight[i]*2^k、价值为value[i]*2^k的若干件物品,
其中k满足weight[i]*2^k <= capacity。这是二进制的思想,因为不管最优策略选几件第i种物品,总可以表示成若干个2^k件物品的和。
这样把每种物品拆成O(log capacity/weight[i])件物品,是一个很大的改进。
但我们有更优的O(n*capacity)的算法。
[O(n*capacity)的算法]
这个算法使用一维数组,先看伪代码:
for i=1..N
for j=0...capacity
DP[j]=max{DP[j], DP[j-weight[i]]+value[i]}
我们会发现,这个伪代码与01背包的伪代码只有j的循环次序不同而已。
为什么这样一改就可行呢?
首先想想为什么01中要按照j=capacity...0的逆序来循环。
这是因为要保证第i次循环中的状态DP[i][j]是由状态DP[i-1][j-weight[i]]递推而来。
换句话说,这正是为了保证每件物品只选一次,保证在考虑“选入第i件物品”这件策略时,
依据的是一个绝无已经选入第i件物品的子结果f[i-1][j-weight[i]]。
而现在完全背包的特点恰是每种物品可选无限件,所以在考虑“加选一件第i种物品”这种策略时,
却正需要一个可能已选入第i种物品的子结果f[i][j-weight[i]],所以就可以并且必须采用j=0...capacity的顺序循环。
这就是这个简单的程序为何成立的道理。
'''
# Unbounded Knapsack Problem
def knapsack2(weight, value, capacity):
'''
>>> knapsack2([], [], 10)
0
>>> knapsack2([3], [10], 0)
0
>>> knapsack2([4], [15], 4)
15
>>> knapsack2([4], [15], 10)
30
>>> knapsack2([4], [15], 3)
0
>>> weight = [1, 50]
>>> value = [1, 30]
>>> capacity = 100
>>> knapsack2(weight, value, capacity)
100
>>> weight = [1, 3, 4, 5]
>>> value = [10, 40, 50, 70]
>>> capacity = 8
>>> knapsack2(weight, value, capacity)
110
'''
n = len(weight)
if n < 1 or capacity < 1: return 0
dp = [0]*(capacity + 1)
for i in range(n):
for j in range(weight[i], capacity+1):
dp[j] = max(dp[j], dp[j - weight[i]]+value[i])
#print(dp)
return dp[capacity]
'''
拓展:完全硬币找零问题(完全背包)
322. Coin Change [Medium]
给定不同面额的硬币 coins 和总金额 amount。每个硬币可以选择无数次。
计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
状态表示:
dp[i][j] 为考虑前 i 种硬币,凑出金额为 j 的最少数目。
状态转移:
对第 i 种硬币,我们可以不拿,或者拿 1...k 个,直到把金额拿爆:
dp[i][j] = min(dp[i-1][j], dp[i-1][j-c]+1, dp[i-1][j-2*c]+2, ..., dp[i-1][j-k*c]+k)
又因为其中包含了大量的冗余计算
例如:dp[i][j-c] = min(dp[i-1][j-c], dp[i-1][j-2*c]+2, ..., dp[i-1][j-k*c]+k)
两者合并得到:dp[i][j] = min(dp[i-1][j], dp[i][j-c]+1)
dp[i][j-c]+1可表示在当前i状态(也许已经拿了好几个i物品了)还要不要继续拿的情况。
又因为dp[i][j]只和上一层一个状态 (dp[i-1][j]) 和这一层的一个状态 (dp[i][j-c]+1) 有关。
可以将状态优化为一维数组:
dp[j] = min(dp[j], dp[j-c]+1)
边界情况:
dp[0] = 0 表示金额为0时,最小硬币凑法为0
其余要初始化为inf,因为此题要求的是恰好金额为amount时的最小硬币数,所以有些状态可能达不到。
'''
def coinChange2(coins, amount):
'''
>>> coinChange2([2], 1)
-1
>>> coins = [2, 3, 5]
>>> coinChange2(coins, 10)
2
>>> coinChange2(coins, 11)
3
>>> coinChange2(coins, 0)
0
>>> coinChange2([1, 2, 5], 10)
2
>>> coinChange2([1, 2, 5], 11)
3
'''
if len(coins) < 1: return -1
dp = [float('inf')] * (amount + 1)
dp[0] = 0
for coin in coins:
for j in range(coin, amount + 1):
dp[j] = min(dp[j], dp[j-coin] + 1)
return dp[amount] if dp[amount] != float('inf') else -1
'''
可以看到,此题解法与01问题解法几乎完全相同!!!只是枚举金额时变为由小到大了。
'''
'''
518. Coin Change 2 [Medium]
You are given coins of different denominations and a total amount of money.
Write a function to compute the number of combinations that make up that amount.
You may assume that you have infinite number of each kind of coin.
Example 1:
Input: amount = 5, coins = [1, 2, 5]
Output: 4
Explanation: there are four ways to make up the amount:
5=5
5=2+2+1
5=2+1+1+1
5=1+1+1+1+1
Example 2:
Input: amount = 3, coins = [2]
Output: 0
Explanation: the amount of 3 cannot be made up just with coins of 2.
Example 3:
Input: amount = 10, coins = [10]
Output: 1
Note:
You can assume that
0 <= amount <= 5000
1 <= coin <= 5000
the number of coins is less than 500
the answer is guaranteed to fit into signed 32-bit integer
[Method 1]: DP:完全背包问题
用dp[i][j]表示用前i个硬币可以凑成j块钱的组合个数。
对于第i个硬币,仍然不用或者用两种情况,以及用的话用几枚硬币。
可得状态转移方程:
dp[i][j] = dp[i-1][j] + dp[i][j-coin]
即用前i-1个硬币凑成j块钱的组合,加上用前i-1个硬币凑成j-coin块钱,然后用第i个硬币凑成剩下的coin块钱的组合个数。
[注意!!!]
对于dp[i-1][j-coin],要考虑硬币面额刚好为当前要凑的面值的情况,即单独那枚硬币就是1种组合,
所以dp[0][0] = 1, 语义是,不考虑任何硬币,凑出总金额为0的组合数为1。
例如硬币coins = [1, 2, 5], amount = 5 时,不考虑面额为5的最后一枚硬币,只考虑前两枚硬币,已经有:
1+1+1+1+1 = 5
1+1+1+2 = 5
1+2+2 = 5
这3种组合,
那么再考虑最后一枚硬币,即 0 + 5 = 5 这1种组合,
也就是dp[1][5] + dp[2][0] = 3 + dp[2][0], 因此dp[2][0] 必须为1, 也就是dp[i][0]都得为1。
因为每个硬币就可以取无数枚,可以看成完全背包问题,因此dp[i][j]不需要从dp[i-1][j]得到,
而是才更新的dp[i][j],因为可能已经放了几个i物品了,所以我们用的是顺序循环,从当前coin的面额开始循环到总面值,
毕竟如果面值j < coin的话,减出来为负是没有意义的。
所以优化后的一维状态转移方程为:
dp[j] = dp[j] + dp[j-coin]
Time: O(NV), N为硬币个数,V为需要凑的面值。
Space: O(V)
Runtime: 140 ms, faster than 79.18% of Python3 online submissions for Coin Change 2.
Memory Usage: 13.7 MB, less than 16.67% of Python3 online submissions for Coin Change 2.
'''
class Solution:
def change(self, amount: int, coins: List[int]) -> int:
dp = [0] * (amount + 1)
dp[0] = 1
for coin in coins:
for i in range(coin, amount + 1):
dp[i] = dp[i] + dp[i-coin]
return dp[amount]
'''
3.多重背包问题 Multi-Knapsack Problem (MKP)
[题目]:
有N种物品和一个容量为V的背包。第i种物品最多有n[i]件可用,每件的重量是w[i],价值是v[i]。
求解将哪些物品装入背包可使这些物品的费用总和不超过背包容量,且价值总和最大。
[基本算法]:
这题目和全然背包问题非常类似。
主要的方程仅仅需将全然背包问题的方程稍微一改就可以,由于对于第i种物品有n[i]+1种策略:
取0件,取1件……取n[i]件。
令dp[i][j]表示前i种物品恰放入一个容量为j的背包的最大权值,则有状态转移方程:
dp[i][j] = max{dp[i - 1][j - k*w[i]] + k*v[i] | 0 <= k <= n[i]}。
复杂度是O(V*Σn[i])。
[转化为01背包问题]:
还有一种好想好写的基本方法是转化为01背包求解:
把第i种物品换成n[i]件01背包中的物品,则得到了物品数为Σn[i]的01背包问题,直接求解,复杂度仍然是O(V*Σn[i])。
可是我们期望将它转化为01背包问题之后可以像全然背包一样减少复杂度。
仍然考虑二进制的思想,我们考虑把第i种物品换成若干件物品,
使得原问题中第i种物品可取的每种策略——取0..n[i]件——均能等价于取若干件代换以后的物品。
另外,取超过n[i]件的策略必不能出现。
多重背包转换成 01 背包问题就是多了个初始化,把它的件数C 用二进制分解成若干个件数的集合,
这里面数字可以组合成任意小于等于C的件数,而且不会重复,之所以叫二进制分解,是因为这样分解可以用数字的二进制形式来解释:
7的二进制 7 = 111 它可以分解成 001 010 100 这三个数可以组合成任意小于等于7的数;
15 = 1111 可分解成 0001 0010 0100 1000 四个数字
13 = 1101 则分解为 0001 0010 0100 0110 前三个数字可以组合成7以内任意一个数,
即1、2、4可以组合为1——7内所有的数,加上 0110 = 6,可以组合成任意一个大于6小于等于13的数,比如12,可以让前面贡献6且后面也贡献6就行了。
虽然有重复但总是能把 13 以内所有的数都考虑到了,基于这种思想去把多件物品转换为,多种一件物品,就可用01背包求解了。
即,将第i种物品分成若干件物品,当中每件物品有一个系数,这件物品的费用和价值均是原来的费用和价值乘以这个系数。
使这些系数分别为 1,2,4,...,2^(k-1),n[i]-2^k+1,且k是满足n[i]-2^k+1>0的最大整数。
比如,假设n[i]为13,就将这样的 物品分成系数分别为1,2,4,6的四件物品。
分成的这几件物品的系数和为n[i],表明不可能取多于n[i]件的第i种物品。
另外这样的方法也能保证对于0..n[i]间的每个整数,均能够用若干个系数的和表示,
这个证明能够分0..2^k-1和2^k..n[i]两段来分别讨论得出,并不难,希望你自己思考尝试一下。
这样就将第i种物品分成了O(log n[i])种物品,将原问题转化为了复杂度为<math>O(V*Σlog n[i])的01背包问题,是非常大的改进。
以下给出O(log amount)时间处理一件多重背包中物品的过程,当中amount表示物品的数量:
procedure MultiplePack(cost,weight,amount)
if cost*amount>=V
CompletePack(cost,weight)
return
integer k=1
while k<amount
ZeroOnePack(k*cost,k*weight)
amount=amount-k
k=k*2
ZeroOnePack(amount*cost,amount*weight)
'''
weight = [3,2,6,7,1,4,9,5]
value = [6,3,5,8,3,1,6,9]
N = [3,5,1,9,3,5,6,8]#每种物品的个数
target = 20 #The capacity of the knapsack
DP = [0] * (target+1)
n = len(weight)
def UnboundedKnapsack(weight,value):
for j in range(weight,target+1):
DP[j] = max(DP[j],DP[j-weight] + value)
def OneZeroKnapsack(weight,value):
for j in range(target, weight-1, -1):
DP[j] = max(DP[j],DP[j-weight] + value)
def MultiKnapsack(weight,value,count):
if (weight * count) >= target:#当该种物品的个数乘以体积大于背包容量,视为有无限个即完全背包
UnboundedKnapsack(weight,value)
return
temp_count = 1 #以上情况不满足,转化为以下情况,具体参考《背包九讲》多重背包的时间优化
while temp_count < count:
OneZeroKnapsack(temp_count*weight,temp_count*value)
count = count - temp_count
temp_count = temp_count * 2 #转化为1,2,4
OneZeroKnapsack(count*weight,count*value) #9个中剩下两个
for i in range(n):
MultiKnapsack(weight[i],value[i],N[i])
print(DP[target])
'''
三、多重硬币找零问题(多重背包)
给定不同面额的硬币 coins 和总金额 m。每个硬币选择的次数有限制为s。
计算可以凑成总金额所需的最少的硬币个数。如果没有任何一种硬币组合能组成总金额,返回 -1。
[状态表示]
这里和完全硬币问题的的初始状态表态表示很相似。
对于第i种硬币,我们可以不拿,或者拿1...k个,直到拿到个数的限制。
dp[i][j] = min(dp[i-1][j], dp[i-1][j-c]+1, dp[i-1][j-2*c]+2, ..., dp[i-1][j-k*c]+k)
所以在01问题的代码的基础上添加一层枚举硬币个数的循环即可
这里可以使用二进制优化,转化为01背包问题求解。
'''
coins1 = [2, 5, 3]
N1 = [5, 5, 5]
m1 = 12
coins2 = [5, 3, 2]
N2 = [1, 5, 5]
m2 = 13
#用0-1背包求解
def coin_change1(coins, m, N):
n = len(coins)
dp = [float('inf')] * (m + 1)
dp[0] = 0
for i in range(n):
for j in range(m, coins[i]-1, -1):
for k in range(1, N[i] + 1):
if k*coins[i] <= j:
dp[j] = min(dp[j], dp[j - k*coins[i]] + k)
print(dp)
return -1 if dp[m] == float('inf') else dp[m]
#print(coin_change1(coins1, m1, N1))
print(coin_change1(coins2, m2, N2))
#多重背包
def coin_change2(coins, m, N):
n = len(coins)
dp = [float('inf')] * (m + 1)
dp[0] = 0
def unbounded(coin, k):
for j in range(coin, m+1):
dp[j] = min(dp[j], dp[j-coin] + k)
def zeroOne(coin, k):
for j in range(m, coin-1, -1):
dp[j] = min(dp[j], dp[j-coin] + k)
def multi(coin, count):
if count*coin > m:
unbounded(coin, 1)
return
k = 1
while k < count:
zeroOne(k*coin, k)
count = count - k
k = k*2
zeroOne(count*coin, count)
for i in range(n):
multi(coins[i], N[i])
print(dp)
return -1 if dp[m] == float('inf') else dp[m]
print(coin_change2(coins2, m2, N2))
'''
474. Ones and Zeroes [Medium]
[题目大意]:
我们现在从数组中每个字符串都有一些0和1,问给了m个0,n个1,从数组中取出最多的字符串,这些字符串中1和0的出现次数之和不超过m,n.
[Analysis]:
遇到这种求最多或最少的次数的,并且不用求具体的解决方案,一般都是使用DP。
This problem is a typical 0-1 knapsack problem,
we need to pick several strings in provided strings to get the maximum number of strings using limited number 0 and 1.
We can create a three dimensional array, in which dp[i][j][k] means the maximum number of strings
we can get from the first i argument strs using limited j number of '0's and k number of '1's.
For dp[i][j][k], we can get it by fetching the current string i or discarding the current string,
which would result in dp[i][j][k] = dp[i-1][j-numOfZero(strs[i])][i-numOfOnes(strs[i])] and dp[i][j][k] = dp[i-1][j][k];
We only need to treat the larger one in it as the largest number for dp[i][j][k].
we cannot decrease the time complexity, but we can decrease the space complexity from ijk to j*k。
这个DP很明白了,定义一个数组dp[m+1][n+1],代表m个0, n个1能组成的字符串得最大数目。
遍历每个字符串统计出现的0和1得到zeros和ones,所以有状态转移方程:
dp[i][j] = max(dp[i][j], dp[i - zeros][j - ones] + 1)
即,用i个0和j个1,在数组strs里面,求能组成的字符串的最大数目时有两种情况:
1.不算当前的字符串str,则有dp[i][j]个;
2.要算当前的字符串str,则str之前的字符串只能用i-zeros个0和j-ones个1,所得的字符串个数和为dp[i - zeros][j - ones] + 1。
因此我们比较大小,取最大的值。
其中dp[i - zeros][j - ones]表示如果取了当前的这个字符串,那么之前的字符串用用剩下的0和1时取的最多的数字。
边界条件:dp[0][0],表示用0个0和0个1能凑出的字符串个数为0。
[Time]: O(s*m*n)
[Space]: O(m*n)
Runtime: 2864 ms, faster than 68.16% of Python3 online submissions for Ones and Zeroes.
Memory Usage: 13.8 MB, less than 100.00% of Python3 online submissions for Ones and Zeroes.
'''
class Solution:
def findMaxForm(self, strs: List[str], m: int, n: int) -> int:
dp = [[0] * (n + 1) for _ in range(m + 1)]
for s in strs:
zeros, ones = s.count('0'), s.count('1')
for i in range(m, zeros - 1, -1):
for j in range(n, ones - 1, -1):
dp[i][j] = max(dp[i - zeros][j - ones] + 1, dp[i][j])
return dp[m][n]
|
'''
74. Search a 2D Matrix [Medium]
Write an efficient algorithm that searches for a value in an m x n matrix.
This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
Example 1:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 3
Output: true
Example 2:
Input:
matrix = [
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
target = 13
Output: false
[Method 1]:
[Time]:nlogm,n为行数,m为列数
[Space]: O(1)
Runtime: 52 ms, faster than 99.92% of Python3 online submissions for Search a 2D Matrix.
Memory Usage: 14.9 MB, less than 5.88% of Python3 online submissions for Search a 2D Matrix.
'''
class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
if not matrix or not matrix[0]:
return False
rows = len(matrix)
cols = len(matrix[0])
for row in matrix:
if row[0] <= target <= row[-1]:
idx = self.binary_search(row, target)
if idx:
return True
continue
return False
def binary_search(self,arr,k):
lo,hi = 0, len(arr)-1
while lo <= hi:
mid = lo + (hi-lo)//2
if k == arr[mid]:
return True
elif k < arr[mid]:
hi = mid - 1
else:
lo = mid + 1
return False
|
'''
226. Invert Binary Tree [Easy]
Invert a binary tree.
Example:
Input:
4
/ \
2 7
/ \ / \
1 3 6 9
Output:
4
/ \
7 2
/ \ / \
9 6 3 1
Trivia:
This problem was inspired by this original tweet by Max Howell:
Google: 90% of our engineers use the software you wrote (Homebrew),
but you can’t invert a binary tree on a whiteboard so f*** off.
[Method 1]: Recursion
反转一颗空树结果还是一颗空树。
对于一颗根为 root ,左子树为 left, 右子树为 right 的树来说,
它的反转树是一颗根为 root,左子树为 right 的反转树,右子树为 left 的反转树的树。
[Time]: O(n), 既然树中的每个节点都只被访问一次,其中 n 是树中节点的个数。
在反转之前,不论怎样我们至少都得访问每个节点至少一次,因此这个问题无法做地比 O(n) 更好了。
[Space]: 在最坏情况下栈内需要存放 O(h) 个方法调用,其中 h 是树的高度。
Runtime: 16 ms, faster than 73.91% of Python online submissions for Invert Binary Tree.
Memory Usage: 12 MB, less than 7.50% of Python online submissions for Invert Binary Tree.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if not root or (not root.left and not root.right): return root
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
'''
#Or:
Runtime: 20 ms, faster than 41.08% of Python online submissions for Invert Binary Tree.
Memory Usage: 11.8 MB, less than 37.50% of Python online submissions for Invert Binary Tree.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
if root:
root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
return root
'''
[Method 2]: Iteration + stack(DFS)
我们需要交换树中所有节点的左孩子和右孩子。
因此可以创一个栈来存储所有左孩子和右孩子还没有被交换过的节点。
开始的时候,只有根节点在这个栈里面。
只要这个队列不空,就一直从栈中出队节点,然后互换这个节点的左右孩子节点,
接着再把孩子节点入栈,对于其中的空节点不需要加入栈。
最终栈一定会空,这时候所有节点的孩子节点都被互换过了,直接返回最初的根节点就可以了。
E.g.
4 4 4
/ \ / \ / \
2 7 => 7 2 => 7 2
/ \ / \ / \ / \ / \ / \
1 3 6 9 6 9 1 3 9 6 3 1
[Time]: O(n), 既然树中的每个节点都只被访问一次,其中 n 是树中节点的个数。
[Space]: O(n), 即使在最坏的情况下,也就是队列里包含了树中所有的节点。
对于一棵完整二叉树来说,叶子节点那一层拥有⌈n/2] = O(n) 个节点。
Runtime: 16 ms, faster than 73.91% of Python online submissions for Invert Binary Tree.
Memory Usage: 11.9 MB, less than 7.50% of Python online submissions for Invert Binary Tree.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def invertTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
"""
stack = [root]
while stack:
node = stack.pop()
if node:
node.left, node.right = node.right, node.left
stack.append(node.left)
stack.append(node.right)
return root
|
'''
剑指offer22. 链表中倒数第k个节点
输入一个链表,输出该链表中倒数第k个节点。
为了符合大多数人的习惯,本题从1开始计数,即链表的尾节点是倒数第1个节点。
例如,一个链表有6个节点,从头节点开始,它们的值依次是1、2、3、4、5、6。
这个链表的倒数第3个节点是值为4的节点。
示例:
给定一个链表: 1->2->3->4->5, 和 k = 2.
返回链表 4->5.
[Method 1]: 双指针一次遍历
当不允许求链表长度时,可以用一个fast指针先走k-1步,再用一个slow指针指向head,
使得两个指针之间相差k-1个节点,再同时让两个指针一起一步步地走,当fast走到最后一个节点时,
slow指向的就是倒数第k个节点。
注意:
此题由其要注意非法输入,如链表为空、k为0和链表长度小于k的情况,通通都要先考虑到并且避免。
'''
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def getKthFromEnd(self, head: ListNode, k: int) -> ListNode:
if not head or not k: return
fast = slow = head
# make a distance of (k-1) between slow and fast
for _ in range(k-1):
try:
fast = fast.next
except: # 如果链表还没有k长则输入非法
raise(IndexError)
while fast.next:
fast = fast.next
slow = slow.next
return slow
|
'''
448. Find All Numbers Disappeared in an Array [Easy]
Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array),
some elements appear twice and others appear once.
Find all the elements of [1, n] inclusive that do not appear in this array.
Could you do it without extra space and in O(n) runtime?
You may assume the returned list does not count as extra space.
Example:
Input:
[4,3,2,7,8,2,3,1]
Output:
[5,6]
[Method 1]: 先set()再 一一比对
修改了input array
[Time]: O(nlgn)
[Space]: O(1)
Runtime: 428 ms, faster than 47.66% of Python3 online submissions for Find All Numbers Disappeared in an Array.
Memory Usage: 23.6 MB, less than 7.14% of Python3 online submissions for Find All Numbers Disappeared in an Array.
'''
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
n = len(nums)
nums = sorted(list(set(nums)))
count, offset, res = n - len(nums), 0, []
i = 1
for num in nums:
if count == 0: break
if i + offset != num:
for _ in range(num-i-offset):
res.append(i+offset)
count -= 1
offset += 1
i += 1
i += offset
while count != 0:
res.append(i)
count -= 1
i += 1
return res
#Or:
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
marked = set(nums)
return [i for i in range(1, len(nums)+1) if i not in marked]
'''
[Method 2]: 抽屉原理(把nums作哈希表用)
把每个数看作是它们在假设是从从 1 到 N 排好序的数列Nums里的位置(index),
并把其(位置)对应的数字标记为负数。
所以最终为正的位置就是未被标记的,即该位置为空,缺少相应的数字 index+1,
最后把它加入输出数组即可。
[Time]: O(n)
[Space]: O(1)
Runtime: 432 ms, faster than 42.92% of Python3 online submissions for Find All Numbers Disappeared in an Array.
Memory Usage: 21.5 MB, less than 17.86% of Python3 online submissions for Find All Numbers Disappeared in an Array.
'''
class Solution:
def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
n = len(nums)
for num in nums:
index = abs(num) - 1
nums[index] = - abs(nums[index])
return [index + 1 for index in range(n) if nums[index] > 0]
'''
[Method 3]:
Iterate the array and add N to the existing number at the position implied by every element.
This means that positions implied by the numbers present in the array
will be strictly more than N (smallest number is 1 and 1+N > N).
Therefore. in the second iteration,
we simply need to report the numbers less than equal to N to return the missing numbers..
'''
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
N = len(nums)
for i in range(len(nums)):
nums[(nums[i]%N)-1] += N
return [i+1 for i in range(len(nums)) if nums[i]<=N]
'''
若将题目要求改为数组中每个元素出现的可能次数是 n 次,
求出数组中出现此次为偶数(奇数)次的元素(出现 0 次也算偶数次)。
'''
class Solution(object):
def findDisappearedNumbers(self, nums):
"""
:type nums: List[int]
:rtype: List[int]
"""
# 将所有正数作为数组下标,置对应数组值为相反数。那么,仍为正数的位置即为出现偶数次(未出现是0次,也是偶数次)数字。
# 举个例子:
# 原始数组:[1, 1, 1, 1, 2, 3, 4, 5]
# 重置后为:[1, -1, -1, -1, -2, 3, 4, 5]
# 结论:[1,3,4,5] 分别对应的index为[1,6,7,8](消失的数字)
for num in nums:
index = abs(num) - 1
# 保持nums[index]为相反数,唯一和上面的解法不同点就是这里,好好体会
nums[index] = -nums[index]
#偶数次
return [i + 1 for i, num in enumerate(nums) if num > 0]
#奇数次
return [i + 1 for i, num in enumerate(nums) if num < 0]
|
'''
激活生成器主要有两个方法:
1. 使用next(generator),即不给生成器传任何参数,
如果生成器的yield语句为 received_value = yield some_value,则received_value为None;
2. 使用generator.send(None): send括号里是传给生成器的参数,
如果生成器的yield语句只是 yield some_value, 那么send括号里则只能为None;
如果语句为 received_value = yield some_value, 则send括号里的参数会被发送给生成器后
存在received_value这个变量里。
'''
def mygen(n):
now = 0
while now < n:
yield now
now += 1
if __name__ == '__main__':
gen = mygen(4)
# 通过交替执行,来说明这两种方法是等价的。
print(gen.send(None))
print(next(gen))
print(gen.send(None))
print(next(gen))
'''
【输出结果】:
0
1
2
3
'''
|
'''
9. Palindrome Number
Determine whether an integer is a palindrome.
An integer is a palindrome when it reads the same backward as forward.
Example 1:
Input: 121
Output: true
Example 2:
Input: -121
Output: false
Explanation: From left to right, it reads -121. From right to left, it becomes 121-. Therefore it is not a palindrome.
Example 3:
Input: 10
Output: false
Explanation: Reads 01 from right to left. Therefore it is not a palindrome.
Follow up:
Coud you solve it without converting the integer to a string?
[Method 1]: 用数学的方法先比较最外层的digits,然后处理x使之去掉已经比较了的digits,继续比较。
Time: O(lgn); Space: O(1)
Runtime: 88 ms, faster than 21.05% of Python3 online submissions for Palindrome Number.
Memory Usage: 14 MB, less than 6.50% of Python3 online submissions for Palindrome Number.
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0:
return False
#找出x的位数,如121,则ranger=100
ranger = 1
while x // ranger >= 10:
ranger *= 10
while x:
left = x // ranger
right = x % 10
if left != right:
return False
#比较完最外面两个digit后,处理x
x = (x % ranger) // 10
ranger //= 100
return True
'''
[Method 2]: Reverse 所有digits:把x reverse处理后与原x比较,若相等则return True。
Time: O(lgn); Space: O(1)
Runtime: 84 ms, faster than 28.09% of Python3 online submissions for Palindrome Number.
Memory Usage: 14 MB, less than 6.50% of Python3 online submissions for Palindrome Number.
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0: return False
num, rev = x, 0
while num > 0:
rev *= 10
rev += num%10
num //= 10
return rev == x
'''
[Method 3]: Reverse Half of the digits.
To avoid the overflow issue of the reverted number, (No worries in Python)
what if we only revert half of the int number?
As the reverse of the last half of the palindrome
should be the same as the first half of the number,
if the number is a palindrome.
[Note]:
1.首先需要处理以0结尾的数字如1210,因为根据(while x > rev)循环条件,
half reversed后的数字为012,即12,而剩下的x位12,则相等会返回True。
2.奇数位数字如121,half reversed后的数字为21,而x为1,因此需要把rev除掉10后再比较。
Time: O(log(lgn)), 每次x都会除以10,并且之比较一半的位数,所以再除以2;
Space: O(1)
Runtime: 76 ms, faster than 48.54% of Python3 online submissions for Palindrome Number.
Memory Usage: 14.1 MB, less than 6.50% of Python3 online submissions for Palindrome Number.
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
if x < 0 or (x%10 == 0 and x != 0): return False
rev = 0
while x > rev:
rev *= 10
rev += x%10
x //= 10
return rev == x or rev//10 == x
'''
[Method 3]: Fastest: Converting Integer to String
'''
class Solution:
def isPalindrome(self, x: int) -> bool:
s = str(x)
return s == s[::-1]
|
'''
98. Validate Binary Search Tree [Medium]
Given a binary tree, determine if it is a valid binary search tree (BST).
Assume a BST is defined as follows:
The left subtree of a node contains only nodes with keys less than the node's key.
The right subtree of a node contains only nodes with keys greater than the node's key.
Both the left and right subtrees must also be binary search trees.
Example 1:
2
/ \
1 3
Input: [2,1,3]
Output: true
Example 2:
5
/ \
1 4
/ \
3 6
Input: [5,1,4,null,null,3,6]
Output: false
Explanation: The root node's value is 5 but its right child's value is 4.
[Method 1]:
> 类型:DFS遍历
> Time Complexity O(n)
> Space Complexity O(h)
错误代码(Buggy Code):
'''
class Solution(object):
def isValidBST(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root: return True
if root.left:
if root.left.val >= root.val or not self.isValidBST(root.left):
return False
if root.right:
if root.right.val <= root.val or not self.isValidBST(root.right):
return False
return True
'''
上面代码看起来好像也没什么毛病,但以下这种情况是过不了的
5
/ \
1 4
/ \
3 6
为什么?因为我们每层在当前的root分别做了两件事情:
检查root.left.val是否比当前root.val小并且root.left是不是BST;
检查root.right.val是否比当前root.val大并且root.right是不是BST
大家可以用这个思路过一下上面这个例子,完全没问题。
那么问题来了,Binary Search Tree还有一个定义,就是
左边所有的孩子的大小一定要比root.val小
右边所有的孩子的大小一定要比root.val大
我们错就错在底层的3,比顶层的5,要小。
ok,概念弄懂了,如何解决这个问题呢?我们可以从顶层开始传递一个区间,举个例子。
在顶层5,向下传递的时候,
他向告诉左边一个信息:
左孩子,你和你的孩子,和你孩子的孩子,孩子的...........孩子都不能比我大哟
他向告诉右边一个信息:
右孩子,你和你的孩子,和你孩子的孩子,孩子的...........孩子都不能比我小哟
所以5告诉左边1的信息/区间是:(-infinite, 5)
所以5告诉右边4的信息/区间是:(5 , infinite)
然后我们要做的就是把这些信息带入到我们的代码里,我们把区间的左边取名lower_bound, 右边取名upper_bound
这样才有了LC被复制到烂的标准答案:
'''
class Solution(object):
def isValidBST(self, root):
return self.helper(root, -float('inf'), float('inf'))
def helper(self, node, lower_bound, upper_bound):
if not node: return True
if node.val >= upper_bound or node.val <= lower_bound:
return False
left = self.helper(node.left, lower_bound, node.val)
right = self.helper(node.right, node.val, upper_bound)
return left and right
#或者更直观的写法:
def isValidBST(self, root, floor=float('-inf'), ceiling=float('inf')):
if not root:
return True
if root.val <= floor or root.val >= ceiling:
return False
# in the left branch, root is the new ceiling; contrarily root is the new floor in right branch
return self.isValidBST(root.left, floor, root.val) and self.isValidBST(root.right, root.val, ceiling)
'''
[Method 2]:根据BST性质进行Inorder操作的暴力解法
利用数组储存inorder过的数,如果出现重复,或者数组不等于sorted(arr),证明不是Valid Tree
这个解法比较易读,如果对Space Complexity要求不严格,可以通过比对数组里面的数而不是sorted(arr)来达到O(N)时间复杂。
'''
class Solution(object):
def isValidBST(self, root):
self.arr = []
self.inorder(root)
return self.arr == sorted(self.arr) and len(self.arr) == len(set(self.arr))
def inorder(self, root):
if not root: return
self.inorder(root.left)
self.arr.append(root.val)
self.inorder(root.right)
'''
O(1) Space解法:
在上面的算法里进行了优化,每次只需要将当前root.val和上次储存的self.last比对即可知道是否满足条件。
然后设立self.flag用于返回。
'''
class Solution(object):
def isValidBST(self, root):
self.last = -float('inf')
self.flag = True
self.inorder(root)
return self.flag
def inorder(self, root):
if not root: return
self.inorder(root.left)
if self.last >= root.val:
self.flag = False
self.last = root.val
self.inorder(root.right)
|
import unittest
class MyQueue(object):
def __init__(self):
"""
Initialize your data structure here.
"""
self.push_stack = []
self.pop_stack = []
self.size = 0
def push(self, x):
"""
Push element x to the back of queue.
:type x: int
:rtype: void
"""
self.push_stack.append(x)
self.size += 1
def pop(self):
"""
Removes the element from in front of queue and returns that element.
:rtype: int
"""
if self.size == 0:
raise IndexError('The queue is empty!')
self.size -= 1
if self.pop_stack:
return self.pop_stack.pop()
while len(self.push_stack) > 1:
self.pop_stack.append(self.push_stack.pop())
return self.push_stack.pop()
def peek(self):
"""
Get the front element.
:rtype: int
"""
if self.size == 0:
raise IndexError('The queue is empty!')
if not self.pop_stack:
while len(self.push_stack) > 0:
self.pop_stack.append(self.push_stack.pop())
return self.pop_stack[-1]
def empty(self):
"""
Returns whether the queue is empty.
:rtype: bool
"""
return self.size == 0
# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()
class TestQueue(unittest.TestCase):
def setUp(self):
self.q = MyQueue()
self.q.push(1)
self.q.push(2)
def test_empty(self):
new_q = MyQueue()
self.assertEqual(new_q.size, 0)
self.assertEqual(new_q.empty(), True)
self.assertRaises(IndexError,new_q.pop)
def test_push(self):
self.assertEqual(self.q.size, 2)
self.q.push(3) #不影响其他函数,只在本函数内部修改self.q
self.assertEqual(self.q.size, 3)
def test_pop(self):
self.assertEqual(self.q.pop(), 1)
self.assertEqual(self.q.size, 1)
self.assertEqual(self.q.peek(), 2)
self.assertEqual(self.q.pop(), 2)
self.assertEqual(self.q.empty(), True)
if __name__ == '__main__':
unittest.main()
|
'''
【递归】
通过LeetCode上【70. 爬楼梯】学习(建议)
'''
'''
70. Climbing Stairs
You are climbing a stair case. It takes n steps to reach to the top.
Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
Note: Given n will be a positive integer.
Example 1:
Input: 2
Output: 2
Explanation: There are two ways to climb to the top.
1. 1 step + 1 step
2. 2 steps
Example 2:
Input: 3
Output: 3
Explanation: There are three ways to climb to the top.
1. 1 step + 1 step + 1 step
2. 1 step + 2 steps
3. 2 steps + 1 step
'''
'''
Method1: (Top-Down)Recursion using fibonacci without memoization
Time: O(2^n)
Time Limit Exceeded
Note: 之所以会TLE,是因为递归的时候出现了很多次重复的运算。
这种重复计算随着input的增大,会出现的越来越多,时间复杂度也会将以指数的级别上升。
'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n <= 3:
return n
return self.climbStairs(n-1) + self.climbStairs(n-2)
'''
# OPTIMIZE: (Top-Down) Recursion + memoization by hash table(global variable)
Time: O(n)
Runtime: 4 ms, faster than 99.78% of Python online submissions for Climbing Stairs.
Memory Usage: 11.9 MB, less than 17.19% of Python online submissions for Climbing Stairs.'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
self.dic = {0:1, 1:1, 2:2}
def helper(n):
if n not in self.dic:
# 每次递归时只有helper(n-1)是O(n),
# 因为前者已经把后者helper(n-2)存入哈希表,所以后者只是O(1)
self.dic[n] = helper(n-1) + helper(n-2)
return self.dic[n]
return helper(n)
'''
Metho2: (Bottom-up) iteration use O(1) space
Time: O(n) Space:O(1)
Runtime: 8 ms, faster than 97.54% of Python online submissions for Climbing Stairs.
Memory Usage: 11.6 MB, less than 100.00% of Python online submissions for Climbing Stairs.
'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
curr, next = 1, 1
for i in range(n):
curr, next = next, curr + next
return curr
'''
Method2: (Bottom-up) iteration use list for memoization
Time: O(n) Space:O(n)
Runtime: 8 ms, faster than 97.54% of Python online submissions for Climbing Stairs.
Memory Usage: 11.7 MB, less than 46.88% of Python online submissions for Climbing Stairs.
'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
res = [0] * (n+1)
res[0], res[1] = 1, 1
for i in range(2, n+1):
res[i] = res[i-1] + res[i-2]
return res[-1]
'''
Method3: (Top-Down) Dynamic Programming
Runtime: 4 ms, faster than 99.78% of Python online submissions for Climbing Stairs.
Memory Usage: 11.8 MB, less than 35.94% of Python online submissions for Climbing Stairs.
[思路]
根据TLE的代码进行优化,如果能够将之前的计算好了的结果存起来,之后如果遇到重复计算直接调用结果,
会从之前的指数时间复杂度,变成O(N)的时间复杂度。
[实现]
开辟一个长度为N的数组,将其中的值全部赋值成-1,用-1是因为这一类问题一般都会要你求多少种可能,
在现实生活中,基本不会要你去求负数种可能,所以这里-1可以成为一个很好的递归条件/出口。
然后只要我们的数组任然满足arr[n] == -1,说明我们在n层的数没有被更新,
即就是我们还在向下递归或者等待返回值的过程中,所以我们继续递归直到n-1和n-2的值返回上来。
这里注意我们递归的底层,也就是arr[0]和arr[1],分别对应n==1和n==2时,即arr[0], arr[1] = 1, 2
'''
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
if n == 1: return 1
res = [-1 for i in range(n)]
res[0], res[1] = 1, 2
return self.dp(n-1, res)
def dp(self, n, res):
if res[n] == -1:
res[n] = self.dp(n - 1, res) + self.dp(n - 2, res)
return res[n]
|
class Tree:
def __init__(self, label, branches=[]):
self.label = label
for branch in branches:
assert isinstance(branch, Tree)
self.branches = list(branches)
def __repr__(self):
if self.branches:
branch_str = ', ' + repr(self.branches)
else:
branch_str = ''
return 'Tree({0}{1})'.format(repr(self.label), branch_str)
def is_leaf(self):
return not self.branches
def __str__(self):
return '\n'.join(self.indented())
def indented(self):
lines = []
for b in self.branches:
for line in b.indented():
lines.append(' ' + line)
return [str(self.label)] + lines
def is_leaf(self):
return not self.branches
def fib_tree(n):
"""A Fibonacci tree.
>>> print(fib_tree(4))
3
1
0
1
2
1
1
0
1
"""
if n == 0 or n == 1:
return Tree(n)
else:
left = fib_tree(n-2)
right = fib_tree(n-1)
fib_n = left.label + right.label
return Tree(fib_n, [left, right])
def leaves(tree):
"""Return the leaf values of a tree.
>>> leaves(fib_tree(4))
[0, 1, 1, 0, 1]
"""
if tree.is_leaf():
return [tree.label]
else:
return sum([leaves(b) for b in tree.branches], [])
def height(tree):
"""The height of a tree."""
if tree.is_leaf():
return 0
else:
return 1 + max([height(b) for b in tree.branches])
def tree_mutate(tree, f):
tree.label = f(tree.label)
for b in tree.branches:
tree_mutate(b, f)
def prune(t, n):
"""Prune sub-trees whose label value is n.
>>> t = fib_tree(5)
>>> prune(t, 1)
>>> print(t)
5
2
3
2
"""
t.branches = [b for b in t.branches if b.label != n]
for b in t.branches:
prune(b, n)
def prune_repeats(t, seen):
"""Remove repeated sub-trees
>>> def fib_tree(n):
... if n == 0 or n == 1:
... return Tree(n)
... else:
... left = fib_tree(n-2)
... right = fib_tree(n-1)
... return Tree(left.label + right.label, (left, right))
>>> fib_tree = memo(fib_tree)
>>> t = fib_tree(6)
>>> print(t)
8
3
1
0
1
2
1
1
0
1
5
2
1
1
0
1
3
1
0
1
2
1
1
0
1
>>> prune_repeats(t, [])
>>> print(t)
8
3
1
0
1
2
5
"""
t.branches = [b for b in t.branches if b not in seen]
seen.append(t)
for b in t.branches:
prune_repeats(b, seen)
### Treating the tree as immutable (as in the ADT)
def tree_map_broken(tree, f):
"""Return a new tree with f applied to all labels"""
if tree.is_leaf():
return Tree(f(tree.label))
else:
return 1 + max([height(b) for b in tree.branches])
def tree_map(t,f):
"""Return a tree like t but with all labels having f applied to them."""
return Tree(f(t.label), [tree_map(b,f) for b in t.branches])
### TREES ADT (FROM LECTURE 13)
def tree(label, branches=[]):
for branch in branches:
assert is_tree_adt(branch), 'branches must be trees'
return [label] + list(branches)
def label(tree):
return tree[0]
def branches(tree):
return tree[1:]
def is_tree_adt(tree):
if type(tree) != list or len(tree) < 1:
return False
for branch in branches(tree):
if not is_tree_adt(branch):
return False
return True
def is_leaf_adt(tree):
return not branches(tree)
def print_tree_adt(t, indent=0):
print(' ' * indent+str(label(t)))
for b in branches(t):
print_tree_adt(b, indent + 1)
### FIB_TREE_ADT
def fib_tree_adt(n):
if n == 0 or n == 1:
return tree(n)
else:
left = fib_tree_adt(n-2)
right = fib_tree_adt(n-1)
fib_n = label(left) + label(right)
return tree(fib_n, [left, right])
def tree_map_adt(t,f):
"""Return a tree like t but with all labels having f applied to them."""
return tree(f(label(t)), [tree_map_adt(b,f) for b in branches(t)])
def add10(label):
return label + 10
### new tree (via ADT) that starts with fib_tree_adt(3)
### but increases all its labels by 10
print("\ntree ADT")
print_tree_adt(tree_map_adt(fib_tree_adt(3), add10))
### Tree Class immutable
print("\nTree Class immutable")
print(tree_map(fib_tree(3),add10))
### Tree Class mutable
print("\nTree Class mutable")
f3 = fib_tree(3)
tree_mutate(f3, add10)
print(f3)
|
'''
136. Single Number
Given a non-empty array of integers, every element appears twice except for one.
Find that single one.
Note:
Your algorithm should have a linear runtime complexity.
Could you implement it without using extra memory?
Example 1:
Input: [2,2,1]
Output: 1
Example 2:
Input: [4,1,2,1,2]
Output: 4
A number XOR itself will get result 0. And a number XOR 0 will get itself.
For example,
>>> 1 ^ 1
0
>>> 0 ^ 2
2
In this way, if we XOR numbers with each other: two identical numbers XOR to 0,
the standard will be the single number finally.
known that A XOR A = 0 and the XOR operator is commutative,
the solution will be very straightforward.
'''
#Version 1
def singleNumber(self, nums):
res = 0
for num in nums:
res ^= num
return res
#Version 2
from functools import reduce
class Solution:
def singleNumber(self, nums):
return reduce(lambda a, b : a ^ b, nums)
#Version 3
def singleNumber(self, nums):
return reduce(operator.xor, nums)
'''
Other methods:
'''
def singleNumber1(self, nums):
dic = {}
for num in nums:
dic[num] = dic.get(num, 0)+1
for key, val in dic.items():
if val == 1:
return key
def singleNumber2(self, nums):
return 2*sum(set(nums))-sum(nums)
|
'''
75. Sort Colors [Medium]
Given an array with n objects colored red, white or blue,
sort them in-place so that objects of the same color are adjacent,
with the colors in the order red, white and blue.
Here, we will use the integers 0, 1, and 2 to represent the color red, white, and blue respectively.
Note: You are not suppose to use the library's sort function for this problem.
Example:
Input: [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]
Follow up:
A rather straight forward solution is a two-pass algorithm using counting sort.
First, iterate the array counting number of 0's, 1's, and 2's,
then overwrite array with total number of 0's, then 1's and followed by 2's.
Could you come up with a one-pass algorithm using only constant space?
[Method 1]: Counting Sort
First, iterate the array counting number of 0's, 1's, and 2's,
then overwrite array with total number of 0's, then 1's and followed by 2's.
[Time]: O(2N) = O(N)
[Space]: O(range),range其实为2-0+1=3
Runtime: 32 ms, faster than 59.34% of Python3 online submissions for Sort Colors.
Memory Usage: 13 MB, less than 95.31% of Python3 online submissions for Sort Colors.
'''
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
counter = [0]*3
for num in nums:
counter[num] += 1
k = 0
for i in range(3):
while counter[i]:
nums[k] = i
counter[i] -= 1
k += 1
'''
[Method 2]: 双指针(实际上是三指针)
原理和快排的partition相似。用i来对nums进行遍历
l指示最后一个0的下一位,r指示第一个2的前一位。
[Time]: O(n), 一次遍历
[Space]: O(1)
Runtime: 32 ms, faster than 59.34% of Python3 online submissions for Sort Colors.
Memory Usage: 13 MB, less than 95.31% of Python3 online submissions for Sort Colors.
'''
class Solution:
def sortColors(self, nums: List[int]) -> None:
"""
Do not return anything, modify nums in-place instead.
"""
i,l,r = 0,0,len(nums)-1
while i <= r: # 因为r后面的都是排好序的,所以当i到r时最后再检测一次
if nums[i] == 2:
nums[i],nums[r] = nums[r],nums[i]
r -= 1 # 此时不需要移动i,因为交换后的nums[i]的值还不知道
elif nums[i] == 0:
nums[i],nums[l] = nums[l],nums[i]
l += 1
i += 1 # i需要移动因为交换后的i是从l来的,l是我们默认的最后一个0的下一位,即1
else:
i += 1 # 即nums[i]为1,默认放中间
|
'''
230. Kth Smallest Element in a BST [Medium]
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note: You may assume k is always valid, 1 ≤ k ≤ BST's total elements.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
Example 2:
Input: root = [5,3,6,2,4,null,null,1], k = 3
5
/ \
3 6
/ \
2 4
/
1
Output: 3
二叉查找树(Binary Search Tree),也称为二叉搜索树、有序二叉树(ordered binary tree)
或排序二叉树(sorted binary tree),是指一棵空树或者具有下列性质的二叉树:
1.若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值;
2.若任意节点的右子树不空,则右子树上所有节点的值均大于它的根节点的值;
3.任意节点的左、右子树也分别为二叉查找树;
4.没有键值相等的节点。
'''
'''
Method 1: Stack + Iteration
Code1:
Using deque, setting its maximum length to k.
# O(n) time, O(k) space
Runtime: 36 ms, faster than 91.60% of Python online submissions for Kth Smallest Element in a BST.
Memory Usage: 19.9 MB, less than 6.52% of Python online submissions for Kth Smallest Element in a BST.
## keep only k elements in stac, if full while appending,
## stack will implement popleft automatically
## the val of the last element in stac is wanted
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
import collections
stac = collections.deque(maxlen=k)
while True:
while root:
stac.append(root)
root = root.left
root = stac.pop()
if k == 1:
return root.val
k -= 1
root = root.right
'''
Code2:
Use Stack
O(n) time, O(n) space
Runtime: 32 ms, faster than 97.17% of Python online submissions for Kth Smallest Element in a BST.
Memory Usage: 19.7 MB, less than 39.13% of Python online submissions for Kth Smallest Element in a BST.
'''
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
stack = []
while root or stack:
while root:
stack.append(root)
root = root.left
root = stack.pop()
k -= 1
if k == 0:
return root.val
root = root.right
'''
Method2: DFS recursive, stop early when meet kth
Code1:
'''
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
self.k = k
self.res = None
self.dfs_recur(root)
return self.res
def dfs_recur(self, node):
if node is None:
return
self.dfs_recur(node.left)
self.k -= 1
if self.k == 0:
self.res = node.val
return
self.dfs_recur(node.right)
'''
Code2
Runtime: 40 ms, faster than 79.17% of Python online submissions for Kth Smallest Element in a BST.
Memory Usage: 19.7 MB, less than 32.61% of Python online submissions for Kth Smallest Element in a BST.
'''
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
res = [k]
self.dfs_recur(root, res)
return res[1]
def dfs_recur(self, node, res):
if len(res) > 1:
return
if node.left:
self.dfs_recur(node.left, res)
res[0] -= 1
if res[0] == 0:
res.append(node.val)
return
if node.right:
self.dfs_recur(node.right, res)
'''
Method3: Generator
Time: O(k), Space: O(1)
Code1
Runtime: 44 ms, faster than 61.80% of Python online submissions for Kth Smallest Element in a BST.
Memory Usage: 19.6 MB, less than 56.52% of Python online submissions for Kth Smallest Element in a BST.
'''
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
for val in self.inorder(root):
if k == 1:
return val
else:
k -= 1
def inorder(self, root):
if root is not None:
for val in self.inorder(root.left):
yield val
yield root.val
for val in self.inorder(root.right):
yield val
'''
Code2
Runtime: 44 ms, faster than 61.80% of Python online submissions for Kth Smallest Element in a BST.
Memory Usage: 19.7 MB, less than 41.30% of Python online submissions for Kth Smallest Element in a BST.
'''
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def inorder(node):
if node:
for val in inorder(node.left):
yield val
yield node.val
for val in inorder(node.right):
yield val
return next(itertools.islice(inorder(root), k-1, k))
'''
Method4: Binary Search + Recursion
### We only need to traverse all nodes if it's NOT a BST.
Runtime: 52 ms, faster than 27.51% of Python online submissions for Kth Smallest Element in a BST.
Memory Usage: 19.8 MB, less than 6.52% of Python online submissions for Kth Smallest Element in a BST.
'''
class Solution(object):
def kthSmallest(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: int
"""
def sort_tree(root):
if root:
left = sort_tree(root.left)
right = sort_tree(root.right)
return left + [root.val] + right
return []
sorted_tree = sort_tree(root)
return sorted_tree[k - 1]
|
pwinicial = input('senha inicial \n')
senha = ''
for letra in pwinicial:
if letra in 'Ss': senha = senha + '$'
elif letra in 'Ii': senha = senha + '!'
elif letra in 'Pp': senha = senha + '>'
elif letra in 'Qq': senha = senha + '<'
elif letra in 'Ee': senha = senha + '&'
elif letra in 'Aa': senha = senha + '@'
elif letra in '0': senha = senha + 'o'
elif letra in 'Oo': senha = senha + '0'
else: senha = senha + letra
print (senha) |
class DivisorDigits:
def howMany(self, number):
numDigits = len(str(number))
count = 0
for digit in range(0, numDigits):
if int(str(number)[digit])!=0 and number%int(str(number)[digit])==0:
count += 1
return count
a = 52527
x = DivisorDigits
print(x.howMany(a,a))
|
# -*- coding: utf-8 -*-
"""
Created on Mon Jul 13 21:29:15 2015
@author: Wasit
"""
from turtle import *
def leaf(size):
init_pos=pos()
init_head=heading()
forward(size*0.5)
left(30)
for i in range(3):
forward(size*0.5)
right(120)
setpos(init_pos)
setheading(init_head)
def branch(size):
init_pos=pos()
init_head=heading()
forward(size*0.75)
left(45)
for i in range(3):
leaf(size*0.25)
right(45)
setpos(init_pos)
setheading(init_head)
def tree(size):
left(90)
init_pos=pos()
init_head=heading()
forward(size*0.5)
left(45)
for i in range(3):
branch(size*0.5)
right(45)
setpos(init_pos)
setheading(init_head)
color('brown', 'green')
begin_fill()
tree(200)
end_fill() |
# -*- coding: utf-8 -*-
"""
Created on Thu Sep 10 17:33:33 2015
@author: Wasit
"""
class Rect:
def __init__(self, x,y,w,h):
self.x=x
self.y=y
self.w=w
self.h=h
def __str__(self):
return "x:%d y:%d w:%d h:%d"%(self.x,self.y,self.w,self.h)
if __name__ == "__main__":
import myclass as mc
obj=mc.Rect(1,2,3,4)
print obj
obj2=mc.Rect(6,7,8,9)
print obj2 |
"""
Rain simulation
Simulates rain drops on a surface by animating the scale and opacity
of 50 scatter points.
Author: Nicolas P. Rougier
"""
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
# Create new Figure and an Axes which fills it.
fig = plt.figure(figsize=(7,7))
ax = fig.add_axes([0, 0, 1, 1], frameon=False)
ax.set_xlim(0,1), ax.set_xticks([])
ax.set_ylim(0,1), ax.set_yticks([])
# Create rain data
n_drops = 50
rain_drops = np.zeros(n_drops, dtype=[('position', float, 2),
('size', float, 1),
('growth', float, 1),
('color', float, 4)])
# Initialize the raindrops in random positions and with
# random growth rates.
rain_drops['position'] = np.random.uniform(0, 1, (n_drops, 2))
rain_drops['growth'] = np.random.uniform(50, 200, n_drops)
# Construct the scatter which we will update during animation
# as the raindrops develop.
scat = ax.scatter(rain_drops['position'][:,0], rain_drops['position'][:,1],
s=rain_drops['size'], lw=0.5, edgecolors=rain_drops['color'],
facecolors='none')
def update(frame_number):
# Get an index which we can use to re-spawn the oldest raindrop.
current_index = frame_number % n_drops
# Make all colors more transparent as time progresses.
rain_drops['color'][:, 3] -= 1.0/len(rain_drops)
rain_drops['color'][:,3] = np.clip(rain_drops['color'][:,3], 0, 1)
# Make all circles bigger.
rain_drops['size'] += rain_drops['growth']
# Pick a new position for oldest rain drop, resetting its size,
# color and growth factor.
rain_drops['position'][current_index] = np.random.uniform(0, 1, 2)
rain_drops['size'][current_index] = 5
rain_drops['color'][current_index] = (0, 0, 0, 1)
rain_drops['growth'][current_index] = np.random.uniform(50, 200)
# Update the scatter collection, with the new colors, sizes and positions.
scat.set_edgecolors(rain_drops['color'])
scat.set_sizes(rain_drops['size'])
scat.set_offsets(rain_drops['position'])
# Construct the animation, using the update function as the animation
# director.
animation = FuncAnimation(fig, update, interval=10)
plt.show() |
from itertools import zip_longest
def grouper(iterable, n, fillvalue=None):
"""Collect data into fixed-length chunks or blocks
>>> tuple(map(''.join, grouper('ABCDEFG', 3, 'x')))
('ABC', 'DEF', 'Gxx')
>>> tuple(grouper('ABC', 2))
(('A', 'B'), ('C', None))
"""
args = [iter(iterable)] * n
return zip_longest(*args, fillvalue=fillvalue)
|
# toh.py
# to be completed for the CSE 512 midterm, Winter 2016
#
# STUDENT NAME: Yazhuo Liu 004194007
# *** MIDTERM ***
# COMPLETE THIS MODULE BY REPLACING EACH OCCURRENCE OF 'pass' WITH THE
# PYTHON CODE THAT WILL IMPLEMENT THE DESCRIBED FUNCTIONALITY.
# TEST by loading and RUN-ing file astar_search_midterm.py;
# DO NOT make any changes to file astar_search_midterm.py, or to any
# of this file that is not marked with 'pass'
# SUBMIT: (1) A hardcopy of the completion of this file
# (2) A hardcopy of the IDLE window demonstrating loading
# and running of the programc you get;
SIZE = 5
toh = range(1,SIZE+1)
toh.reverse()
class TOH:
def __init__(self, a = toh, b = [], c = []):
self.pegA = a[:]
self.pegB = b[:]
self.pegC = c[:]
def __str__(self):
return 'A:%s B:%s C:%s' %\
(self.pegA, self.pegB, self.pegC)
def __eq__(self,other):
if other.__class__ == TOH:
return self.pegA == other.pegA and\
self.pegB == other.pegB and\
self.pegC == other.pegC
else:
return False
def pegA (self):
return self.pegA
def pegB (self):
return self.pegB
def pegC (self):
return self.pegC
# move disk from pegA to pegB; if this move is not possible
# in the current configuration, return None;
# otherwise make a COPY of self with
# toh = TOH(self.pegA, self.pegB, selfpegC)
# and execute the move on the toh object;
# return modified toh;
def move_A_to_B(self):
toh = TOH(self.pegA, self.pegB, self.pegC)
if not toh.pegA or len(toh.pegB)>5:
return None
if not toh.pegB:
toh.pegB.append(toh.pegA[-1])
toh.pegA = toh.pegA[:-1]
return toh
else:
if toh.pegA[-1] < toh.pegB[-1]:
toh.pegB.append(toh.pegA[-1])
toh.pegA = toh.pegA[:-1]
return toh
return None
# move disk from pegA to pegC; ...
def move_A_to_C(self):
toh = TOH(self.pegA, self.pegB, self.pegC)
if not toh.pegA or len(toh.pegC)>5:
return None
if not toh.pegC:
toh.pegC.append(toh.pegA[-1])
toh.pegA = toh.pegA[:-1]
return toh
else:
if toh.pegA[-1] < toh.pegC[-1]:
toh.pegC.append(toh.pegA[-1])
toh.pegA = toh.pegA[:-1]
return toh
return None
def move_B_to_A(self):
toh = TOH(self.pegA, self.pegB, self.pegC)
if not toh.pegB or len(toh.pegA)>5:
return None
if not toh.pegA:
toh.pegA.append(toh.pegB[-1])
toh.pegB = toh.pegB[:-1]
return toh
else:
if toh.pegB[-1] < toh.pegA[-1]:
toh.pegA.append(toh.pegB[-1])
toh.pegB = toh.pegB[:-1]
return toh
return None
def move_B_to_C(self):
toh = TOH(self.pegA, self.pegB, self.pegC)
if not toh.pegB or len(toh.pegC)>5:
return None
if not toh.pegC:
toh.pegC.append(toh.pegB[-1])
toh.pegB = toh.pegB[:-1]
return toh
else:
if toh.pegB[-1] < toh.pegC[-1]:
toh.pegC.append(toh.pegB[-1])
toh.pegB = toh.pegB[:-1]
return toh
return None
def move_C_to_A(self):
toh = TOH(self.pegA, self.pegB, self.pegC)
if not toh.pegC or len(toh.pegA)>5:
return None
if not toh.pegA:
toh.pegA.append(toh.pegC[-1])
toh.pegC = toh.pegC[:-1]
return toh
else:
if toh.pegC[-1] < toh.pegA[-1]:
toh.pegA.append(toh.pegC[-1])
toh.pegC = toh.pegC[:-1]
return toh
return None
def move_C_to_B(self):
toh = TOH(self.pegA, self.pegB, self.pegC)
if not toh.pegC or len(toh.pegB)>5:
return None
if not toh.pegB:
toh.pegB.append(toh.pegC[-1])
toh.pegC = toh.pegC[:-1]
return toh
else:
if toh.pegC[-1] < toh.pegB[-1]:
toh.pegB.append(toh.pegC[-1])
toh.pegC = toh.pegC[:-1]
return toh
return None
# given toh, compute all possible next states;
def successor_fct(toh):
succs = [toh.move_A_to_B(), toh.move_A_to_C(),\
toh.move_B_to_A(), toh.move_B_to_C(),\
toh.move_C_to_A(), toh.move_C_to_B()]
while None in succs:
succs.remove(None)
return succs
# for a TOH object tw, return True if pegA and pegB are empty,
# and the 5-tower [5,4,3,2,1] sits on pegC
def goal_fct(tw):
if not tw.pegA and not tw.pegB and tw.pegC == toh:
return True
return False
# evaluate the distance of a TOH object by computing the difference
# between 5 (also: global SIZE) and the number of disks on pegC
def eval_fct(toh):
dis = SIZE - len(toh.pegC)
return dis
|
import turtle
turtle.goto(0,0)
DOWN = 1
LEFT = 2
RIGHT = 3
UP = 0
direction = None
def up():
global direction
direction = UP
print("you pressed the up key.")
on_move(10,20)
def down():
global direction
direction = DOWN
print("you pressed the down key.")
on_move(10,20)
def left():
global direction
direction = LEFT
print("you pressed the left key.")
on_move(10,20)
def right():
global direction
direction = RIGHT
print("you pressed the right key.")
on_move(10,20)
turtle.onkey(up, "Up")
turtle.onkey(down, "Down")
turtle.onkey(left, "Left")
turtle.onkey(right, "Right")
turtle.listen()
def on_move(x, y):
turtlepos = turtle.position()
turtlexpos = turtlepos[0]
turtleypos = turtlepos[1]
if direction==UP:
turtle.goto(turtlexpos , turtleypos+y)
if direction==DOWN:
turtle.goto(turtlexpos , turtleypos-y)
if direction==LEFT:
turtle.goto(turtlexpos-x , turtleypos)
if direction==RIGHT:
turtle.goto(turtlexpos+x , turtleypos)
|
class Node:
def __init__(self, key):
self.key = key
self.next = None
class LL:
def __init__(self, key):
head = Node(key)
self.head = head
def push(self, key):
node = Node(key)
node.next = self.head
self.head = node
def printList(self):
n = self.head
while n:
print n.key
n = n.next
def findMerge(l1, l2):
n1 = l1.head
n2 = l2.head
merge = None
while n1 and n2:
if n1.key == n2.key:
print n1.key
merge = n1
else:
merge = None
n1 = n1.next
n2 = n2.next
return merge
<<<<<<< HEAD
def mergeSorted(h1, h2):
# l1 : 2->6->11->25->43->79
# l2 : 3->19->111->178
# res : 2->3->6->11->19->25->43->79->111->178
# h1 : 2
# h2 : 3
res = None
if not h1:
return h2
if not h2:
return h1
if h1.key <= h2.key:
res = h1
res.next = mergeSorted(h1.next, h2)
else:
res = h2
res.next = mergeSorted(h1, h2.next)
return res
if __name__ == "__main__":
l = LL(35)
l.push(22)
l.push(18)
l.push(1)
l2 = LL(45)
l2.push(32)
l2.push(21)
l2.push(18)
l2.push(9)
l2.push(7)
l2.push(5)
l2.push(2)
#res = findMerge(l, l2)
# 1->18->22->35
# 2->5->7->9->11->18->21-32->45
####
# 1->2->5->-7->9->18->21->22->32->35->45
res = mergeSorted(l.head, l2.head)
while res:
print res.key
res = res.next
|
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def height(r):
height = 0
s = r
while s:
height += 1
s = s.left
return height
def printVS(r, level):
if not r: return
if 1 == level:
print r.key
elif level >= 1:
printVS(r.left, level-1)
printVS(r.right, level-1)
def rbfs(r):
for i in range(1, height(r)+1):
printVS(r, i)
def bfs(r):
q = []
q.append(r)
while len(q) > 0:
node = q.pop()
print node.key
if node.left:
q.append(node.left)
if node.right:
q.append(node.right)
if __name__ == "__main__":
r = Node(5)
n1 = Node(57)
n2 = Node(13)
n3 = Node(313)
n4 = Node(890)
n5 = Node(39)
n6 = Node(1000)
n7 = Node(225)
n8 = Node(38)
n9 = Node(15)
n10 = Node(333)
###
r.left = n1
r.right = n2
n1.left = n3
n1.right = n4
n2.left = n5
n2.right = n6
n3.left = n7
n3.right = n8
n4.left = n9
n4.right = n10
#rbfs(r)
bfs(r)
|
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
def supported_scales():
print("F - Fahrenheit")
print("K - Kelvin")
print("F - Celsius")
print("RE - Réamour")
print("RA - Rankine")
print("N - Newton")
print("D - Delisle")
print("RO - Rømer")
def get_fahrenheit(t, e):
if e.upper() == 'K': return 9*get_celsius(t, 'K')/5 + 32
elif e.upper() == 'C': return 9*t/5 + 32
elif e.upper() == 'RE': return t*9/4 + 32
elif e.upper() == 'RA': return t - 459.67
elif e.upper() == 'N': return t*60/11 + 32
elif e.upper() == 'D': return 212 - t*6/5
elif e.upper() == 'RO': return (t - 7.5)*24/7 + 32
else: return t
def get_kelvin(t, e):
if e.upper() == 'F': return get_celsius(t, 'F') + 273.15
elif e.upper() == 'C': return t + 273.15
elif e.upper() == 'RE': return t*5/4 + 273.15
elif e.upper() == 'RA': return t*5/9
elif e.upper() == 'N': return t*100/33 + 273.15
elif e.upper() == 'D': return 373.15 - t*2/3
elif e.upper() == 'RO': return (t - 7.5)*40/21 + 273.15
else: return t
def get_celsius(t, e):
if e.upper() == 'F': return (t-32)*5/9
elif e.upper() == 'K': return t - 273.15
elif e.upper() == 'RE': return t*5/4
elif e.upper() == 'RA': return t*5/9 - 273.15
elif e.upper() == 'N': return t*100/33
elif e.upper() == 'D': return 100 - t*2/3
elif e.upper() == 'RO': return (t - 7.5)*40/21
else: return t
def get_reamour(t, e):
if e.upper() == 'F': return (t - 32)*4/9
elif e.upper() == 'K': return get_celsius(t, 'K')*4/5
elif e.upper() == 'C': return t*4/5
elif e.upper() == 'RA': return (t - 491.67)*4/9
elif e.upper() == 'N': return t*80/33
elif e.upper() == 'D': return 80 - t*8/15
elif e.upper() == 'RO': return (t - 7.5)*32/21
else: return t
def get_rankine(t, e):
if e.upper() == 'F': return t + 459.67
elif e.upper() == 'K': return t*9/5
elif e.upper() == 'C': return get_kelvin(t, 'C')*9/5
elif e.upper() == 'RE': return t*9/4 + 491.67
elif e.upper() == 'N': return t*60/11 + 491.67
elif e.upper() == 'D': return 671.67 - t*6/5
elif e.upper() == 'RO': return (t - 7.5)*24/7 + 491.67
else: return t
def get_newton(t, e):
if e.upper() == 'F': return (t - 32)*11/60
elif e.upper() == 'K': return get_celsius(t, 'K')*33/100
elif e.upper() == 'C': return t*33/100
elif e.upper() == 'RA': return (t - 491.67)*11/60
elif e.upper() == 'RE': return t*33/80
elif e.upper() == 'D': return 33 - t*11/50
elif e.upper() == 'RO': return (t - 7.5)*22/35
else: return t
def get_delisle(t, e):
if e.upper() == 'F': return (212 - t)*5/6
elif e.upper() == 'K': return (373.15 - t)*3/2
elif e.upper() == 'C': return (100 - t)*3/2
elif e.upper() == 'RA': return (671.67 - t)*5/6
elif e.upper() == 'RE': return (80 - t)*15/8
elif e.upper() == 'N': return (33 - t)*50/11
elif e.upper() == 'RO': return (60 - t)*20/7
else: return t
def get_romer(t, e):
if e.upper() == 'F': return (t - 32)*7/24 + 7.5
elif e.upper() == 'K': return (t - 273.15)*21/40 + 7.5
elif e.upper() == 'C': return t*21/40 + 7.5
elif e.upper() == 'RA': return (t - 491.67)*7/24 + 7.5
elif e.upper() == 'RE': return t*21/32 + 7.5
elif e.upper() == 'N': return t*35/22 + 7.5
elif e.upper() == 'D': return 60 - t*7/20
else: return t
temperature = float(input("Temperature: "))
print("Supported Scales:")
supported_scales()
scale = input("Scale: ")
print("Fahrenheit:", get_fahrenheit(temperature, scale))
print("Kelvin:", get_kelvin(temperature, scale))
print("Celsius:", get_celsius(temperature, scale))
print("Réamour:", get_reamour(temperature, scale))
print("Rankine:", get_rankine(temperature, scale))
print("Newton:", get_newton(temperature, scale))
print("Delisle:", get_delisle(temperature, scale))
print("Rømer:", get_romer(temperature, scale))
|
# lab02#
sal = int(input("What is your salary? (Please enter value between 0 and 100) \n"))
kid1 = input("Do you have children? Y/N \n")
kid = kid1.upper()
if (30 <= sal < 50) and (kid == 'N'):
print("Your Tax is 40")
elif (30 <= sal < 50) and (kid == 'Y'):
print("Your Tax is 35")
elif (50 <= sal < 70) and (kid == 'N'):
print("Your Tax is 50")
elif (50 <= sal < 70) and (kid == 'Y'):
print("Your Tax is 45")
elif sal < 30:
print("Your Tax is 0")
elif sal > 70:
print("Your Tax is 55")
else:
print("You entered incorrect data")
|
import streamlit as st
import numpy as np
import pandas as pd
from PIL import Image
st.title("Streamlit 超入門")
st.write("Display Image")
img = Image.open("img/untitled2.jpg")
st.image(img, caption="flower", use_column_width=True)
#st.write("DataFrame")
#df = pd.DataFrame(
# np.random.rand(100,2)/[50,50] + [35.69, 139.70],
# columns=["lat","lon"]
#)
#st.line_chart(df) #線グラフ
#st.area_chart(df) #エリアグラフ
#st.bar_chart(df) #棒グラフ
#st.dataframe(df.style.highlight_max(axis=0)) #ハイライト
#st.map(df) #地図を表示
|
# /usr/bin/env python
# -*- coding:utf-8 -*-
'''
L = ['A','B','C']
for name in L:
print('hello '+ name)
while True:
print (123)
#continue
break
print (456)
li = [11,22,33]
for k,v in enumerate(li, 1):
print(k,v)
'''
# 一、元素分类
#
# 有如下值集合 [11,22,33,44,55,66,77,88,99,90...],将所有大于 66 的值保存至字典的第一个key中,将小于 66 的值保存至第二个key的值中。
# 即: {'k1': 大于66的所有值, 'k2': 小于66的所有值}
# li = [11,22,33,44,55,66,77,88,99,90]
# dic = {
# 'k1' : [],
# 'k2' : []
# }
# for item in li:
# if item >= 66:
# dic['k1'].append(item)
# else :
# dic['k2'].append(item)
# print(dic)
# 二、查找
# 查找列表中元素,移除每个元素的空格,并查找以 a或A开头 并且以 c 结尾的所有元素。
# li = ["alec", " aric", "Alex", "Tony", "rain"]
# tu = ("alec", " aric", "Alex", "Tony", "rain")
# dic = {'k1': "alex", 'k2': ' aric', "k3": "Alex", "k4": "Tony"}
#
# for i in dic.values():
# i1 = i.strip()
# #print(i1)
# if i1.startswith('a') or i1.startswith('A') and i1.endswith('c'):
# print(i1)
# 三、输出商品列表,用户输入序号,显示用户选中的商品
# 商品 li = ["手机", "电脑", '鼠标垫', '游艇']
# li = ["手机", "电脑", '鼠标垫', '游艇']
# for key,i in enumerate(li):
# pass
# j = input('请输入序列号:')
# jint = int(j)
# print(li[jint-1])
#五、用户交互,显示省市县三级联动的选择
# dic = {
# "河北": {
# "石家庄": ["鹿泉", "藁城", "元氏"],
# "邯郸": ["永年", "涉县", "磁县"],
# }
# "河南": {
# ...
# }
# "山西": {
# ...
# }
#
# }
# 四、购物车
# 功能要求:
#
# 要求用户输入总资产,例如:2000
# 显示商品列表,让用户根据序号选择商品,加入购物车
# 购买,如果商品总额大于总资产,提示账户余额不足,否则,购买成功。
# 附加:可充值、某商品移除购物车
'''
goods = [
{"name": "电脑", "price": 1999},
{"name": "鼠标", "price": 10},
{"name": "游艇", "price": 20},
{"name": "美女", "price": 998},
]
all = int(input('请输入总资产:'))
a = 1
for i in goods:
print(a,i['name'],i['price'])
a+=1
dic = {
'name' : [],
'price' : []
}
#加入购物车
while True:
goods_car = int(input('请输入序列号加入购物车:'))
if goods_car <= len(goods):
dic['name'].append(goods[goods_car-1]['name'])
dic['price'].append(goods[goods_car - 1]['price'])
print(dic)
else:
print('商品不存在,请重新选择!')
continue
tips = input('继续选择商品&删除商品&去结算?1/2/3:')
if tips == '1':
continue
elif tips == '2':
del_goods = input('请输入要删除的商品名称:')
if del_goods in dic['name']:
#print(dic['name'].index(del_goods))
dic['price'].pop(dic['name'].index(del_goods))
dic['name'].remove(del_goods)
print(dic)
else:
print('购物车没有该商品!')
break
else:
break
#print(dic)
#结算
tips2 = input('结算购物车?Y/N:')
while True:
if tips2 == 'Y' or 'y':
car_all = 0
for j in dic['price']:
car_all = j + car_all
if all >= car_all:
all = all - car_all
print('支付成功,支付金额%d,余额%d'% (car_all,all))
break
else:
print('余额不足,请充值!')
all1 = int(input('请输入充值金额:'))
all = all + all1
print('充值成功,余额%d,正在支付...'% all)
continue
else:
break
#################面向对象编程########################
class Foo:
def __init__(self,name,age,gender):
self.name = name
self.age = age
self.gender = gender
def kanchai(self):
print('%s,%s,%s,上山去砍柴'%(self.name,self.age,self.gender))
def kaiche(self):
print('%s,%s,%s,开车去东北' % (self.name, self.age, self.gender))
def baojian(self):
print('%s,%s,%s,最爱大保健' % (self.name, self.age, self.gender))
a=Foo('小明','10','男')
a.kanchai()
a.kaiche()
a.baojian()
class youxirensheng:
def __init__(self,name,gender,age,zhandouli):
self.name = name
self.gender = gender
self.age = age
self.zhandouli = zhandouli
def chuangjian(self):
print('%s,%s,%s,初始战斗力%s'%(self.name,self.gender,self.age,self.zhandouli))
def zhandou(self):
print('%s,%s,%s,草丛战斗消耗200战斗力'%(self.name,self.gender,self.age))
self.zhandouli -= 200
def xiulian(self):
print('%s,%s,%s,自身修炼增长100战斗力' % (self.name, self.gender, self.age))
self.zhandouli +=100
def duoren(self):
print('%s,%s,%s,多人游戏消耗500战斗力' % (self.name, self.gender, self.age))
self.zhandouli -=500
cang = youxirensheng('苍井井', '女', 18, 1000)
dong = youxirensheng('东尼木木', '男', 20, 1800)
bo = youxirensheng('波多多', '女', 19, 2500)
cang.zhandou()
dong.xiulian()
bo.duoren()
cang.chuangjian()
dong.chuangjian()
bo.chuangjian()
##############百分比#####################
import sys
import time
def view_bar(num, total):
rate = float(num) / float(total)
rate_num = int(rate * 100)
r = '\r%d%%' % (rate_num, )
sys.stdout.write(r)
sys.stdout.flush()
if __name__ == '__main__':
for i in range(1, 100):
time.sleep(0.5)
view_bar(i, 100)
import random
checkcode = ''
for i in range(5):
current = random.randrange(0,5)
if current != i:
temp = chr(random.randint(65,90))
else:
temp = random.randint(0,9)
checkcode += str(temp)
print (checkcode)
class Foo:
def __init__(self,name,age):
self.name = name
self.age = age
def view(self):
print(self.name)
print(self.age)
a = Foo('alex',18)
a.view()
'''
# def func_1(n):
# return func_2(n,1)
#
# def func_2(num, m):
# if num==1:
# return m
# return func_2(num-1, num*m)
#
# a=func_1(4)
# print(a)
#
# def Fi(depth, a1, a2):
# print(depth, a1)
# if depth ==20:
# return 'over'
# a3 = a1 + a2
# i = Fi(depth+1, a2, a3)
# return i
# Fi(1, 0, 1)
# import re
#
# #match:从起始位置开始匹配,匹配成功返回一个对象,未匹配成功返回None
# #text = r'ainy day ! 123'
# text2 = {
# 'a': 'lalala'
# }
# #r = re.match("r\w+", text)
# r = re.match("{'.+'", str(text2))
# rb = re.findall('\'.+\'', str(text2))
# print(rb)
# # print(r.group()) # 获取匹配到的所有结果
# # r = re.match("r(\w+)", text)
# # print(r.groups()) # 获取模型中匹配到的分组结果,元组
# # r = re.match("(?P<n1>r\w+)", text)
# # print(r.groupdict()) # 获取模型中匹配到的分组结果,字典
# import xlrd
# excel_path=r'C:\\test.xlsx'
# data = xlrd.open_workbook(excel_path)
# for i in data._sheet_names:
# print(i)
# table = data.sheet_by_name(i)
# nrows = table.nrows
# ncols = table.ncols
# for j in range(0, nrows):
# for k in range(0, ncols):
# cell_value = table.cell_value(j, k)
# # print(cell_value)
# if cell_value == 22.0:
# print(i, j+1, k+1)
from selenium import webdriver
from selenium.webdriver import ActionChains
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.support.ui import WebDriverWait
import time
import find_element
driver = webdriver.Chrome()
driver.get('http://192.168.2.32:7070/emm-manager/')
driver.maximize_window()
fi = find_element.findElement(driver)
fi.find_element('username')
fi.find_element('username').clear()
fi.find_element('username').send_keys('secadmin')
fi.find_element('password').clear()
fi.find_element('password').send_keys('emm@2018')
fi.find_element('submit').click()
time.sleep(1)
driver.switch_to.frame('mainframe')
time.sleep(1)
fi.find_element('desktop').click()
time.sleep(1)
# checks = driver.find_elements_by_class_name('portal_checkbox')
checks = fi.find_element('checkbox')
for i in checks:
i.click()
time.sleep(1)
fi.find_element('desktop').click()
driver.save_screenshot('首页.png')
time.sleep(3)
driver.close()
|
class analyzer():
def __init__(self, cname, target_grade, grade_details, db):
self.cname = cname
self.target_grade = target_grade
self.comment_format = "|{0:^60}|"
self.total_mark, self.total_weight = db.sum_weight(cname)
self.total_lost_marks = self.total_weight - self.total_mark
def calculate_grade_needed(self, weight):
new_weight = self.total_weight + weight
target_mark = new_weight * self.target_grade / 100
temp = target_mark - self.total_mark
return temp / weight * 100
def comment_component(self, weight, grade): #grade in percent%, weight in percent%
if grade is None:
grade_needed = self.calculate_grade_needed(weight)
print(self.comment_format.format("You need at least {0:.3}% to achieve your goal.".format(grade_needed)))
elif grade<self.target_grade:
lostmark = (100-grade)*weight/100
print(self.comment_format.format("You have lost {0:.3}% of the total mark in this component.".format(lostmark)))
else:
lostmark = (100-grade)*weight/100
print(self.comment_format.format("You are doing well, you only lost {0:.3}% in this part.".format(lostmark)))
def comment_course(self):
if self.total_lost_marks >= (100-self.target_grade):
print(" Your goal is unrealistic, you are {0:.3}% behind of your goal.".format(self.target_grade-(100-self.total_lost_marks)))
else:
print(" Your goal is achievable, you have lost {0:.3}% of the total grade.".format(self.total_lost_marks))
if self.total_weight != 0.0:
print(" Your current average is {0:.3%}, your goal is {1:.3}%.\n".format(self.total_mark/self.total_weight, self.target_grade))
|
import pygame
from .env import *
# class HightWay():
# def __init__(self):
# # lanes is collection of lane and lane is a rect with white color
# self.lanes = []
# pass
#
# def draw(self,screen):
# # TODO screen blit way here
# pass
#
# def update(self,car):
# # TODO update infomation you need here
# # if lanes is out of screen , they will be reset their position
# # according velocity of car , revise the position of car
# pass
class Lane(pygame.sprite.Sprite):
def __init__(self,x,y,maxVel):
pygame.sprite.Sprite.__init__(self)
self.image = pygame.Surface((5,30))
self.image.fill(WHITE)
self.rect = self.image.get_rect()
self.rect.center = x ,y
self.vel = maxVel
def update(self):
if self.rect.top > HEIGHT:
self.rect.bottom = 0
if self.rect.bottom < 0:
self.rect.top = HEIGHT
self.rect.centery += self.vel*2 |
from argparse import ArgumentParser
def get_parser_from_dict(parser_config: dict):
"""
Generate `argparse.ArgumentParser` from `parser_config`
@param parser_config A dictionary carries parameters for creating `ArgumentParser`.
The key "()" specifies parameters for constructor of `ArgumentParser`,
its value is a dictionary of which the key is the name of parameter and
the value is the value to be passed to that parameter.
The remaining keys of `parser_config` specifies arguments to be added to the parser,
which `ArgumentParser.add_argument() is invoked`. The key is the name
of the argument, and the value is similar to the "()"
but for the `add_argument()`. Note that the name of the key is used as the name
of the argument, but if "name_or_flags" is specified in the dictionary of it,
it will be passed to the `add_argument()` instead. The value of "name_or_flags"
must be a tuple.
An example of `parser_config`:
```
{
"()": {
"usage": "game <difficulty> <level>"
},
"difficulty": {
"choices": ["EASY", "NORMAL"],
"metavar": "difficulty",
"help": "Specify the game style. Choices: %(choices)s"
},
"level": {
"type": int,
"help": "Specify the level map"
},
}
```
"""
if parser_config.get("()"):
parser = ArgumentParser(**parser_config["()"])
else:
parser = ArgumentParser()
for arg_name in parser_config.keys():
if arg_name != "()":
arg_config = parser_config[arg_name].copy()
name_or_flag = arg_config.pop("name_or_flags", None)
if not name_or_flag:
name_or_flag = (arg_name, )
parser.add_argument(*name_or_flag, **arg_config)
return parser
|
# Square Gradient generator by RaddedMC
# Did this instead of sleeping or doing uni homework -- have fun :D
# pip install Pillow numpy
from PIL import Image, ImageDraw
import numpy
## USER-CONTROLLED VARIABLES ##
startColor = (234,80,255) # Color #1
endColor = (255,255,0) # Color #2
resolution = (1920,1080) # Image resolution -- gradient is generated along the x-axis
tilesWidth = resolution[0] # Leave unchanged for a perfect gradient
squareImage = Image.new(mode = "RGB", size=resolution);
squareImageDraw = ImageDraw.Draw(squareImage);
for i in range(tilesWidth):
# Variables? Who needs those??
squareImageDraw.rectangle(
[
(i*resolution[0]/tilesWidth,0),
((i+1)*resolution[0]/tilesWidth,resolution[1])
],
fill=tuple(
numpy.subtract(
startColor, numpy.subtract(startColor,endColor) * i/tilesWidth).astype(int))
)
squareImage.show() |
#%% [markdown]
# # Train your first neural network: basic classification
# In this notebook you will make a program that recognize hand written letters.
# But this is not a image recognition app, at least not a typical one.
# The letter data is in form of trace. A trace registered by digital tablet, the time and x, y
# coordinates. This method is original by me and will not be found else where.
# the feature used here is significantly smaller than the image input.
# ## You will learn
# 1. read data from csv file using pandas
# 2. data pre-processing and basice feature engineering. this is a "deep" learning
# model, so very minimum of feature enginerring.
# 3. neural network model define and traning, evaluation and prediction
# 4. visualizion result and plot confusion matrix
# **You will learning a lot in this single notebook**
#%% [markdown]
# You see in python every non-basic function is in python modules that you must import
# before you use it.
#%% import useful libraries
# TensorFlow and tf.keras deep learning frameworks
import tensorflow as tf
from tensorflow import keras
# Helper libraries
# numpy gives you matrix like operations
import numpy as np
# matplotlib let you plot figures
import matplotlib.pyplot as plt
# this is a module written by us for this program specifically,
# as you should keep you code clean and readable. This are reusable functions.
import dataLoader as dl
# sklearn provides many useful functions related to ML.
from sklearn.model_selection import train_test_split
from sklearn.metrics import confusion_matrix
# just check you have tf 2.0
print(tf.__version__)
#%% load the data
# see the dataloader file for details
features,labels=dl.readData(r"..\Lesson2.6-before-deep-learning\machinelearning_course_files\Data")
#%% [markdown]
# Plot a trace to see if we get everything right.
# **NOTE: **Here we plot the trace of the features and get a letter which looks the same as
# the hand written letter in the data. So this is just data cleaning no feature engineering.
# But the data is changed, and the Time is discared, so you can call it sort of feature engineering.
#%% show some samples
plt.plot(features[5,0:30],features[5,30:])
plt.suptitle="Real: "+labels[5]
plt.show()
#%% [markdown]
# Split the data into train and test using sklearn with 20% for test set.
# %%
X_train, X_test, y_train, y_test = train_test_split(features, labels, test_size=0.2, random_state=42)
#%% [markdown]
# ## Build the network
# Build a NN with Keras is the most simple thing in this notebook.
# The NN has 2 hidden layer, the numbers are choose randomly.
# The input has to match the feature size 60.
# The output is 26 to match the one hot encoded target. A softmax is used to regulate the
# out put to a probability distribution.
# ## Train it
# 1. the optimizer is adam, this is a gradient decent optimizer, use this if you don't know which to use.
# 2. the Loss is important `sparse_categorical_crossentropy`, this will encoder your categorical target as one hot than using
# cross entropy for the loss. cross entropy is common in classification and one hot target. It is like maximum likelihood method.
#%% build the model
model = keras.Sequential([
keras.Input(shape=(60)),
keras.layers.Dense(128, activation=tf.nn.relu),
keras.layers.Dense(50, activation=tf.nn.relu),
keras.layers.Dense(26, activation=tf.nn.softmax)
])
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy'])
#%% train the model
# as I said, keras accept only numeric input the the Y have to be in a nparray of numbers.
# yes keras accept nparray not python list.
y=[]
for letter in y_train:
y.append(dl.letter2Number(letter))
y_train2=np.asarray(y)
y=[]
for letter in y_test:
y.append(dl.letter2Number(letter))
y_test2=np.asarray(y)
#%%
# batch size is random
# 1000 epoch will almost hit the limit in this data set
model.fit(X_train, y_train2,batch_size=1500, epochs=1000)
#%% test
# keras models have building evaluation for accuracy
test_loss, test_acc = model.evaluate(X_test, y_test2)
print('Test accuracy:', test_acc)
# make a prediction of the whole test set
y_hat=model.predict(X_test)
# calculate the accuracy by yourself, it is allway better knowing how numbers are calculated
y_hat=np.argmax(y_hat,axis=1)
acc=sum((y_hat==y_test2).tolist())/y_hat.size
print('Test accuracy:', acc)
y_hat_letters=[]
for num in y_hat:
y_hat_letters.append(dl.number2Letter(num))
#%% [markdown]
# Show the final result, change test sample to see the result
# Calculate the confution matrix using sklearn and plot it.
#%% show some result
test_sample=55
plt.plot(X_test[test_sample,0:30],X_test[test_sample,30:])
result="Real: "+y_test[test_sample] + " Predicted: "+ y_hat_letters[test_sample]
print(result)
plt.suptitle=result
plt.show()
#%% confusion
con_mat=confusion_matrix(y_test, y_hat_letters,labels=dl.getAlphabet(),normalize="true")
plt.matshow(con_mat)
plt.xticks(np.arange(26),dl.getAlphabet())
plt.yticks(np.arange(26),dl.getAlphabet())
plt.show()
# %%
|
"""The N-pieces puzzle"""
# Further changes - mkings checking, noard array, changing board size, other pieces, etc.
class NPieces:
"""Generate all solutions for N-pieces puzzle for specified piece and board size"""
def __init__(self, size, piece):
# Store the puzzle (problem) size and the number of valid solutions
# add - row, col, num-pieces
self.size = size
self.piece = piece
self.solutions = 0
self.solve()
def solve(self):
"""Solve the N-pieces puzzle and print the number of solutions"""
positions = [-1] * self.size
if self.piece == "q" or "Q":
self.put_queen(positions, 0)
else:
if self.piece == "r" or "R":
self.put_rook(positions, 0)
else:
if self.piece == "k" or "K":
self.put_king(positions, 0)
else:
if self.piece == "b" or "B":
self.put_bishop(positions,0)
print("Found ", self.solutions, " solutions.")
print("Press the <ENTER> key to continue...")
input()
def put_queen(self, positions, target_row):
"""
Try to place a queen on target_row by checking all N possible cases.
If a valid place is found the functions recurses trying to place a queen
on the next row until all N pieces are placed on the NxN board.
"""
# Base case - all N rows are occupied
if target_row == self.size:
self.show_full_board(positions)
self.solutions += 1
else:
# For all N columns positions try to place a queen
for column in range(self.size):
# Reject all invalid positions
if self.check_place_queen(positions, target_row, column):
positions[target_row] = column
self.put_queen(positions, target_row + 1)
def put_rook(self, positions, target_row):
"""
Try to place a rook on target_row by checking all N possible cases.
If a valid place is found the functions recurses trying to place a rook
on the next row until all N pieces are placed on the NxN board.
"""
# Base case - all N rows are occupied
if target_row == self.size:
self.show_full_board(positions)
self.solutions += 1
else:
# For all N columns positions try to place a rook
for column in range(self.size):
# Reject all invalid positions
if self.check_place_rook(positions, column):
positions[target_row] = column
self.put_rook(positions, target_row + 1)
def put_bishop(self, positions, target_row):
"""
Try to place a bishop on target_row by checking all N possible cases.
If a valid place is found the functions recurses trying to place a bishop
on the next row until all N pieces are placed on the NxN board.
"""
# Base case - all N rows are occupied
if target_row == self.size:
self.show_full_board(positions)
self.solutions += 1
else:
# For all N columns positions try to place a bishop
for column in range(self.size):
# Reject all invalid positions
if self.check_place_bishop(positions, target_row, column):
positions[target_row] = column
self.put_bishop(positions, target_row + 1)
def put_king(self, positions, target_row):
"""
Try to place a king on target_row by checking all N possible cases.
If a valid place is found the functions recurses trying to place a king
on the next row until all N pieces are placed on the NxN board.
"""
# Base case - all N rows are occupied
if target_row == self.size:
self.show_full_board(positions)
self.solutions += 1
else:
# For all N columns positions try to place a queen
for column in range(self.size):
# Reject all invalid positions
if self.check_place_king(positions, target_row, column):
positions[target_row] = column
self.put_king(positions, target_row + 1)
def put_mking(self, positions, target_row):
"""
Try to place a mking on target_row by checking all N possible cases.
If a valid place is found the functions recurses trying to place a mking
on the next row until all N pieces are placed on the NxN board.
"""
# Base case - all N rows are occupied
if target_row == self.size:
self.show_full_board(positions)
self.solutions += 1
else:
# For all N columns positions try to place a queen
for column in range(self.size):
# Reject all invalid positions
if self.check_place_mking(positions, target_row, column):
positions[target_row] = column
self.put_mking(positions, target_row + 1)
def check_place_queen(self, positions, occupied_rows, column):
"""
Check if a given position is under attack from any of
the previously placed queens (check column and diagonal positions)
"""
for i in range(occupied_rows):
if positions[i] == column or \
positions[i] - i == column - occupied_rows or \
positions[i] + i == column + occupied_rows:
return False
return True
def check_place_rook(self, positions, column):
"""
Check if a given position is under attack from any of
the previously placed rooks (check column)
"""
if positions[i] == column:
return False
return True
def check_place_bishop(self, positions, occupied_rows, column):
"""
Check if a given position is under attack from any of
the previously placed queens (check diagonal positions)
"""
for i in range(occupied_rows):
if positions[i] - i == column - occupied_rows or \
positions[i] + i == column + occupied_rows:
return False
return True
def check_place_king(self, positions, occupied_rows, column):
"""
Check if a given position is under attack from any of
the previously placed kings (check column and diagonal positions)
"""
for i in range(occupied_rows):
if positions[i] == column or \
positions[i] - i == column - occupied_rows or \
positions[i] + i == column + occupied_rows:
return False
return True
def check_place_mking(self, positions, occupied_rows, column):
"""
Check if a given position is under attack from any of
the previously placed mkings (check column positions)
"""
for i in range(occupied_rows):
if positions[i] == column:
return False
return True
def show_full_board(self, positions):
"""Show the full NxN board"""
for row in range(self.size):
line = ""
for column in range(self.size):
if positions[row] == column:
line = line + self.piece + " "
else:
line += ". "
print(line)
print("\n")
"""
def main():
# Initialize and solve the n-pieces puzzle
NPieces(8,"Q")
if __name__ == "__main__":
# execute only if run as a script
main()
"""
def main(size, piece):
"""Initialize and solve the n-pieces puzzle"""
NPieces(size, piece)
if __name__ == "__main__":
# execute only if run as a script
main(size, piece)
|
hour= float(input("Enter the hours: "))
minutes= float(input("Enter the minutes: "))
seconds= float(input("Enter the seconds: "))
if 0<hour>23:
print("Your time is invalid")
if 0<minutes>59:
print("Your time is invalid")
if 0<seconds>59:
print("Your time is invalid")
elif (hour,minutes,seconds):
print("Your time is valid") |
a = eval(input('Enter the start point N: \n'))
b =eval(input('Enter the start point M: \n'))
a += 1
for i in range(a,b):
y = True
if(str(i) == str(i)[::-1]):
if(i>2):
for a in range(2,i):
if(i%a==0):
y = False
break
if y:
print(i)
|
string = input("Input new string: ")
string = str(string)
reverse = string[::-1]
if(reverse == string):
print("It is a palindrome")
else:
print("It is not a palindrome") |
a = int(input("Unesi broj: "))
if (a % 2 == 0):
print("Broj je paran")
else:
print("Broj je neparan") |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
import math
import numpy as np
import matplotlib.pyplot as plt
print("\TALLER #3 - Graficando funciones...sen(x), cos(x), tan(X) y transformadas.")
# 0. Preliminares
def to_rad(c):
return(c*math.pi/180)
def to_deg(r):
return(r*180/math.pi)
def factorial(n):
if n == 0 or n == 1:
res = 1
elif n > 1:
res = n*factorial(n-1)
else:
return"NaN"
return res
# 1.Cree las funciones trigonométricas(misin, micos, mitan), exponencial y
# logarítmica a partir de la función dada. (ver imagen)
def misin(x):
sumatoria = 0
termino = 0
n = 0
aportemin = 0.00001
while(True):
termino = ((-1)**n)/(factorial(2*n+1))*x**(2*n+1)
sumatoria = sumatoria+termino
n = n+1
if(math.fabs(termino) < aportemin):
break
return sumatoria
# Grafica función seno(x)
plt.figure()
plt.title("Función: misin(x)")
plt.grid(True)
plt.xlabel("Eje x")
plt.ylabel("Eje y")
x = np.linspace(0, 2*math.pi, 100)
i = 0
while(i < 100):
y = misin(x[i])
plt.plot(x[i], y, '.')
i = i+1
# # plt.show()
def micos(x):
sumatoria = 0
termino = 0
n = 0
aportemin = 0.00001
while(True):
termino = ((-1)**n/factorial(2*n)) * (x**(2*n))
sumatoria = sumatoria+termino
n = n+1
if(math.fabs(termino) < aportemin):
break
return sumatoria
# Grafica función coseno(x)
plt.figure()
plt.title("Función: micos(x)")
plt.grid(True)
plt.xlabel("Eje x")
plt.ylabel("Eje y")
x = np.linspace(0, 2*math.pi, 100)
i = 0
while(i < 100):
y = micos(x[i])
plt.plot(x[i], y, '.')
i = i+1
# # plt.show()
def mitan(x):
return (misin(x)/micos(x))
# Gráfica función tangente(x)
puntos = 50
plt.figure()
plt.title("Función: micos(x)")
plt.grid(True)
plt.xlabel("Eje x")
plt.ylabel("Eje y")
x = np.linspace(0, 3, puntos)
i = 0
while(i < puntos):
y = mitan(x[i])
plt.plot(x[i], y, '.')
i = i+1
# # plt.show()
# 2. Sean las series de Fourier para las funciones donde T es el periodo.
# Programe el algoritmo en Matlab que permita generar la función haciendo
# uso de las funciones a partir de las series del punto anteior.
# Grafique usando subplot permitiendo ver para algunos armónicos del aporte.
# -Cuadrada(micuadrada())
# -Diente de Sierra(misierra())
# -Triangular(mitriangular())
def micuadrada(t):
pi = 3.141592653589793
T = 2*pi
n = 1
sumatoria = 0
termino = 0
aportemin = 0.00001
while(True):
termino = ((1/n) * (to_deg(math.sin(2*pi*n*t/T))))
sumatoria = sumatoria+termino
n = n+1
if(math.fabs(termino) < aportemin):
break
return ((4/pi)*sumatoria)
puntos = 50
plt.figure()
plt.title("Función: micuadrada(x)")
plt.grid(True)
plt.xlabel("Eje x")
plt.ylabel("Eje y")
x = np.linspace(0, 10, puntos)
i = 1
while(i < (puntos-1)):
y = (micuadrada(x[i]))
plt.plot(x[i], y, '.')
i = i+1
# plt.show()
def misierra(t):
T = 10
n = 1
pi = 3.141592653589793
sumatoria = 0
termino = 0
aportemin = 0.00001
while(True):
termino = ((1/n) * (math.sin(2*pi*n*t/T)))
sumatoria = sumatoria+termino
n = n+1
if(math.fabs(termino) < aportemin):
break
return ((1/2) - (1/pi*sumatoria))
puntos = 50
plt.figure()
plt.title("Función: misierra(x)")
plt.grid(True)
plt.xlabel("Eje x")
plt.ylabel("Eje y")
x = np.linspace(0, 10, puntos)
i = 1
while(i < (puntos-1)):
y = (misierra(x[i]))
plt.plot(x[i], y, '.')
i = i+1
# plt.show()
def mitriangular(t):
T = 10
n = 1
pi = 3.141592653589793
sumatoria = 0
termino = 0
aportemin = 0.00001
while(True):
termino = ((((-1)**((n-1)/2)) / n) * math.sin(2*pi*n*t/T))
sumatoria = sumatoria+termino
n = n+2
if(math.fabs(termino) < aportemin):
break
return (8/(pi**2)*sumatoria)
puntos = 50
plt.figure()
plt.title("Función: mitriangular(x)")
plt.grid(True)
plt.xlabel("Eje x")
plt.ylabel("Eje y")
x = np.linspace(0, 10, puntos)
i = 1
while(i < (puntos-1)):
y = (mitriangular(x[i]))
plt.plot(x[i], y, '.')
i = i+1
# plt.show()
plt.show()
|
N = int(raw_input())
num = [int(i) for i in raw_input().split()]
if N != len(num):
print 'Not matching'
print sorted(list(set(num)))[-2] |
def Mean(arr,l):
s = sum(arr)
mean = s/(l*1.0)
return "{0:0.1f}".format(mean)
def Median(arr, l):
arr.sort()
if l%2 == 0:
median = (arr[l/2]+arr[(l/2)-1]) / 2.0
else:
median = arr[l/2]
return "{0:0.1f}".format(median)
def Mode(arr):
d = {}
mode = 0
max_count = 0
for i in arr:
if i not in d:
d[i] = 1
else:
d[i] += 1
for key in d.keys():
if d[key] >= max_count:
if d[key] == max_count:
if key < mode:
mode = key
max_count = d[key]
else:
max_count = d[key]
mode = key
return mode
if __name__ == '__main__':
n = int(raw_input())
arr = [int(i) for i in raw_input().split()]
print Mean(arr, n)
print Median(arr, n)
print Mode(arr) |
def quartile(arr):
l = len(arr)
if l%2 == 0:
q = (arr[(l/2)-1]+arr[l/2]) / 2
else:
q = arr[l/2]
return q
if __name__ == '__main__':
n = int(raw_input())
X = [int(i) for i in raw_input().strip().split()]
X.sort()
if n%2 == 0:
low = (n/2) - 1
high = n/2
else:
low = (n/2) - 1
high = (n/2) + 1
print quartile(X[0:low+1])
print quartile(X)
print quartile(X[high:n]) |
# import math
# import random
# import sys
class Player:
def __init__(self, letter):
self.letter = letter
def get_move(self, game):
pass
# super() function will create a class that will inherit all the methods and properties from another class:
# The isinstance() function returns True if the specified object is of the specified type, otherwise False.
# If the type parameter is a tuple, this function will return True if the object is one of the types in the tuple.
class RandomComputerPlayer(Player):
def __init__(self, letter):
super().__init__(letter)
def get_move(self, game):
pass
class HumanPlayer(Player):
def __init__(self, letter):
super().__init__(self, letter)
def get_move(self, game):
pass
|
import sys
words = 'I used splitlines on the list and then assigned the proper listing to a new variable'
# print(words.splitlines()) # splitlines can only be used on a string and in this case you cannot paste a vertical list
# of words like I did above because a string cannot extend to multiple lines without the \ character for each line
# this is really a consequence of the separate line for each word. I converted to a docstring then used splitlines to
# make it a list
# splitlines() is dangerous use it sparingly to convert multiple lines of single word docstrings to lists of comma
# separated strings.
# The logic of it can mess up especially with short strings
# it only separates on each new physical newline and each \n newline
words_in_a_list = ['sausage', 'blubber', 'pencil', 'cloud', 'moon', 'water', 'computer', 'school', 'network', 'hammer',
'walking', 'violently', 'mediocre', 'literature', 'chair', 'two', 'window', 'cords', 'musical',
'zebra', 'xylophone', 'penguin', 'home', 'dog', 'final', 'ink', 'teacher', 'fun', 'website', 'banana',
'uncle', 'softly', 'mega', 'ten', 'awesome', 'attach', 'blue', 'internet', 'bottle', 'tight', 'zone',
'tomato', 'prison', 'hydro', 'cleaning', 'television', 'send', 'frog', 'cup', 'book', 'zooming',
'evily', 'gamer', 'lid', 'juice', 'moniter', 'Goku', 'Vegeta', 'Freiza', 'Stardust', 'Killer',
'captain', 'bonding', 'loudly', 'thudding', 'guitar', 'shaving', 'hair', 'soccer', 'water', 'racket',
'table', 'late', 'media', 'desktop', 'flipper', 'club', 'flying', 'smooth', 'monster', 'purple',
'guardian', 'bold', 'hyperlink', 'presentation', 'world', 'national ', 'comment', 'element',
'magic', 'lion', 'sand', 'crust', 'toast', 'jam', 'hunter', 'forest', 'foraging', 'silently',
'tawesomated', 'joshing', 'pong']
print(sys.getsizeof(words_in_a_list))
|
import requests
from requests import ConnectionError
from urllib3.exceptions import ResponseError
class XkcdAPIUnavailable(Exception):
pass
def get_comics_count():
url_comics = "https://xkcd.com/info.0.json"
try:
response = requests.get(url_comics)
if not response.ok:
raise ResponseError
except (ConnectionError, ResponseError):
raise XkcdAPIUnavailable("{} is not available!".format(url_comics))
content = response.json()
return content['num']
def get_comics(comics_number=None):
if not comics_number:
url_comics = "https://xkcd.com/info.0.json"
else:
url_comics = "https://xkcd.com/{}/info.0.json".format(comics_number)
try:
response = requests.get(url_comics)
if not response.ok:
raise ResponseError
except (ConnectionError, ResponseError):
raise XkcdAPIUnavailable("{} is not available!".format(url_comics))
content = response.json()
comment = content['alt']
img_comics_url = content['img']
title = content['title']
return [comment, img_comics_url, title, url_comics]
if __name__ == '__main__':
pass |
from insert import ajouter_plante , consulter,supprimer,rechercher
print( "que souhaitez vous faire")
print("C = CONSULTER ")
print("A = AJOUTER ")
print("S= SUPPRIMER ")
print("R=RECHERCHER")
choix=input("que choisissez-vous ")
if choix.upper()== "A":
id = 10
nom = input("nom de la nouvelle plante")
indication = input("indication de la plante")
partie_utilisee = input("quel partie de la plante utilisez vous")
prix = input("quel est le prix")
ajouter_plante(id,nom,indication,partie_utilisee,prix )
if choix.upper() =="C":
consulter()
if choix.upper() == "S":
consulter()
plante_supprimer= input("entrez le numero de la plante a supprimer")
supprimer(plante_supprimer)
if choix.upper()=="r":
plante_recherchee=input("entre la plante recherchée")
rechercher(plante_recherchee)
|
>>> # объявление функции
def draw_triangle(fill, base):
l = [i for i in range(1,base//2+2,)]
l.extend([i for i in range(base//2, 0, -1)])
for elem in l:
print(fill * elem)
# считываем данные
fill = input()
base = int(input())
# вызываем функцию
draw_triangle(fill, base)
|
# - Import random
# - Engine
# - Play function
# - Map
# - next_scene function
# - opening_scene function
# - Scenes
# - Intro/entry scene(broom closet)
# - Enter
# - Room and game description
# - Action input from user
# - Exit leads to hallway
# - Hallway
# - Enter function
# - Description (include door labels)
# - Action input from user
# - Steve function random chance
# - Mess Hall/Dining room
# - Enter function
# - Room description
# - Action input from user
# - Food choices
# - Live(all but one food option)
# - Die(one clear bad choice food, special unique death condition/message)
# - Set to return a True value once the user has executed the action of picking a non-death food
# - Exit function
# - Steve function random chance
# - Bathroom
# - Enter function
# - Room description
# - Action input from user
# - Use bathroom function
# - Set to return True once user uses restroom
# - Wall safe
# - Nice-to-have
# - Contains repellent (one-use item to get rid of Steve one time)
# - Infirmary
# - Room is a nice-to-have
# - Enter function
# - Room description
# - Action input from user
# - Largely full of jokes and world-building items for the user to find, no gameplay advancement in this room
# - Escape Condition
# - Check for values returned by the use bathroom, food choice, and liquor functions
# - Death scenes
# - Create funny death lines
# - Function for handling death conditions
# - Bar
# - Enter Function
# - Room description
# - Action input from user
# - Cabinet function
# - Describe available liquor
# - List of liquor types
# - Input for user to select type of alcohol
# Create classes for all hierarchy objects
import random
import sys
# list of possible messages for the Death function
death_messages = ["Steve chuckles as you feel something seem to slowly seep out of you. At this point, you learn goats are capable of smiling maliciously. You wish you hadn't learned that. Thankfully, you won't know it much longer, as you collapse on the ground...","Well that didn't work at all. Good look reincarnating!","Y'know, it was a good thing you took out that life insurance policy!"]
inv = {
"food":0,
"booze":0,
"toilet":0
}
# If a player loses, select a random death message and display it
def Death():
message = death_messages[random.randint(0,len(death_messages) - 1)]
print(message)
sys.exit(0)
# define a "hallway" in which the user can access the functions for the other rooms
def Hallway():
print('''
You find yourself in the ship's main hallway. Nearby, you see 3 doors. These lead to:
Dining Room
Bar
Bathroom
''')
user_action = input("What would you like to do? ").lower()
if user_action == "broom closet":
print("The aardvark told you to get out of here!")
elif user_action == "dining room":
DiningRoom()
elif user_action == "bar":
Bar()
elif user_action == "bathroom":
Bathroom()
else:
print("That must be a room in some bizarro dimension where nothing makes sense.")
# run a randomizer to determine if Steve spawns, intended to be used when the player enters any room but the hallway
def Steve():
spawn_roll=random.randint(1,100)
if spawn_roll in range(0, 33):
print("Suddenly, the air chills and the lights flicker. As they stabilize again, you see a small, goat-like creature floating in the middle of the room.")
i = 1
while True:
user_action = input("What would you like to do? ").lower()
if (user_action == "run") or (user_action == "exit"):
player_exit = True
return player_exit
else:
print("That doesn't do anything!")
if i == 3:
Death()
i += 1
def BroomCloset():
print('''
You awaken in your trusty broom closet, the room that has served you so well while hiding from security aboard this cruise ship. Suddenly, what appears to be a miniature aardvark appears through the air vent.
"Steve the Devourer has arrived! You must run, quickly! He will encourage you to do fun and relaxing things aboard this ship to fatten up your soul for his feast!" it exclaims.
"..." you reply.
"...Steve the Devourer is a soul-gobbling goat from the Abyss. I don't have time to convince you, just trust me and get out of here!" the aardvark implores.
"..." you reply.
"Oooook, this is such a stimulating conversation, but you have to go. Remember to eat, go to the bathroom, and get yourself something to drink for the trip!" it says with a motherly intonation.
You shrug and consider whether to exit the broom closet.
''')
while True:
user_action = input("What would you like to do? ").lower()
if user_action == "exit":
print("You exit the broom closet, bidding farewell to the miniature aardvark.")
break
else:
print("That's not quite right...")
def DiningRoom():
foods = [
"Steak",
"Chicken Cordon Bleu",
"Seared Salmon",
]
print("You enter the ship's Dining Room. There are a few choices for dinner tonight. You can order: ")
for food in foods:
print(food)
Steve()
while True:
user_action = input("What would you like to do? ").lower()
if user_action == "steak":
print("Good choice! A medium rare steak appears in front of you. You tear off a bite with your teeth, fold it up in a napkin, and place it in your bag.")
inv["food"] = 1
break
elif user_action == "chicken cordon bleu":
print("A juicy piece of Chicken Cordon Bleu appears. You cut into it, a lovely stream of molten cheese flowing out. Bringing your fork to your mouth, you savor the delicious combination of ingredients. Then you wrap up the rest of it in a napkin and shove it into your bag, you Cretin.")
inv["food"] = 1
break
elif user_action == "seared salmon":
print("A salmon appears in front of you, swimming in midair. It appears confused and perhaps annoyed. The chef rushes over, grabs the salmon, and sprints off. Moments later a plate of seared salmon appears in front of you. You warily take a bite, look around, then store the remainder of your dish in a napkin and secure it in your bag.")
inv["food"] = 1
break
elif user_action == "exit":
break
else:
print("That is not an option here.")
liquors = [
"Whiskey",
"Vodka",
"Gin",
"Tequila",
"Rum",
]
liquor_choice = "None"
def Bar():
print('''
You enter the bar, or at least what is marked as a bar. It appears to be haphazard chair and table storage in which a few passengers are having panic attacks. You notice a liquor cabinet with the door ajar. You can:
Open Liquor Cabinet
Exit
'''
)
Steve()
while True:
user_action = input("What would you like to do? ").lower()
if user_action == "open liquor cabinet":
print("There are several bottles of liquor available. You can choose:")
for liquor in liquors:
print(liquor)
liquor_choice = input("Which bottle do you take? ").lower()
if (liquor_choice == "whiskey") or (liquor_choice == "vodka") or (liquor_choice == "gin") or (liquor_choice == "tequila") or (liquor_choice == "rum"):
print("You take a swig and tuck the bottle into your bag.")
inv["booze"] = 1
break
else:
print("That isn't an option.")
elif user_action == "exit":
break
else:
print("You can't do that here.")
def Bathroom():
print('''
You enter the bathroom. As you look around you realize this is, in fact, a bathroom. You can:
Use The Toilet
'''
)
Steve()
while True:
user_action = input("What would you like to do? ").lower()
if user_action == "use the toilet":
print("It's best we not dwell on exactly what's happening right now.")
inv["toilet"] = 1
break
elif user_action == "exit":
break
else:
print("That is not an option here.")
def EscapePod():
print("You finally make your way to the escape pod! You see a chair with flight straps and a big button labeled Launch. You can:")
print("Launch")
i = 0
while True:
user_choice = input("What would you like to do? ").lower()
if user_choice == "launch":
return True
elif i > 2:
Death()
else:
print("You can't do that here.")
i += 1
def check_stock():
if inv["food"] == inv["booze"] == inv["toilet"] == 1:
return False
else:
return True
def play():
BroomCloset()
while True:
Hallway()
check_stock()
if check_stock() == False:
if EscapePod() == True:
print('As you move away from the docking collar, you see a ghastly goat-like face appear in the mirror and say "Remember, a free soul is a tasty soul" and laughs maniacally. You have no idea how you were able to hear the goat. You take a long pull from your bottle and settle in until you are rescued.')
break
play() |
#Recall last exercise that you wrote a function, word_lengths,
#which took in a string and returned a dictionary where each
#word of the string was mapped to an integer value of how
#long it was.
#
#This time, write a new function called length_words so that
#the returned dictionary maps an integer, the length of a
#word, to a list of words from the sentence with that length.
#If a word occurs more than once, add it more than once. The
#words in the list should appear in the same order in which
#they appeared in the sentence.
#
#For example:
#
# length_words("I ate a bowl of cereal out of a dog bowl today.")
# -> {3: ['ate', 'dog', 'out'], 1: ['a', 'a', 'i'],
# 5: ['today'], 2: ['of', 'of'], 4: ['bowl'], 6: ['cereal']}
#
#As before, you should remove any punctuation and make the
#string lowercase.
#Write your function here!
def length_words(string):
lengths = {}
string = string.lower()
to_replace = ".,'!?"
for mark in to_replace:
string = string.replace(mark, "")
words = string.split()
for word in words:
if len(word) not in lengths:
lengths[len(word)] = [word]
else:
lengths[len(word)].append(word)
return lengths
#Below are some lines of code that will test your function.
#You can change the value of the variable(s) to test your
#function with different inputs.
#
#If your function works correctly, this will originally
#print:
#{1: ['i', 'a', 'a'], 2: ['of', 'of'], 3: ['ate', 'out', 'dog'], 4: ['bowl', 'bowl'], 5: ['today'], 6: ['cereal']}
#
#The keys may appear in a different order, but within each
#list the words should appear in the order shown above.
print(length_words("I ate a bowl of cereal out of a dog bowl today."))
|
#Copy your Burrito class from the last exercise. Now, add
#a method called "get_cost" to the Burrito class. It should
#accept zero arguments (except for "self", of course) and
#it will return a float. Here's how the cost should be
#computed:
#
# - The base cost of a burrito is $5.00
# - If the burrito's meat is "chicken", "pork" or "tofu",
# add $1.00 to the cost
# - If the burrito's meat is "steak", add $1.50 to the cost
# - If extra_meat is True and meat is not set to False, add
# $1.00 to the cost
# - If guacamole is True, add $0.75 to the cost
#
#Make sure to return the result as a float even if the total
#is a round number (e.g. for burrito with no meat or
#guacamole, return 5.0 instead of 5).
#Write your code here!
class Burrito:
def __init__(self, meat, to_go, rice, beans, extra_meat=False, guacamole=False, cheese=False, pico=False, corn=False):
self.meat = self.set_meat(meat)
self.to_go = self.set_to_go(to_go)
self.rice = self.set_rice(rice)
self.beans = self.set_beans(beans)
self.extra_meat = extra_meat
self.guacamole = guacamole
self.cheese = cheese
self.pico = pico
self.corn = corn
def set_meat(self, meat):
valid = ["chicken", "pork", "steak", "tofu", False]
if meat in valid:
self.meat = meat
else:
self.meat = False
return self.meat
def set_to_go(self, to_go):
valid = [True, False]
if to_go in valid:
self.to_go = to_go
else:
self.to_go = False
return self.to_go
def set_rice(self, rice):
valid = ["brown", "white", False]
if rice in valid:
self.rice = rice
else:
self.rice = False
return self.rice
def set_beans(self, beans):
valid = ["black", "pinto", False]
if beans in valid:
self.beans = beans
else:
self.beans = False
return self.beans
def set_extra_meat(self, extra_meat):
valid = [True, False]
if extra_meat in valid:
self.extra_meat = extra_meat
else:
self.extra_meat = False
return self.extra_meat
def set_guacamole(self, guacamole):
valid = [True, False]
if guacamole in valid:
self.guacamole = guacamole
else:
self.guacamole = False
return self.guacamole
def set_cheese(self, cheese):
valid = [True, False]
if cheese in valid:
self.cheese = cheese
else:
self.cheese = False
return self.cheese
def set_pico(self, pico):
valid = [True, False]
if pico in valid:
self.pico = pico
else:
self.pico = False
return self.pico
def set_corn(self, corn):
valid = [True, False]
if corn in valid:
self.corn = corn
else:
self.corn = False
return self.corn
def get_meat(self):
return self.meat
def get_to_go(self):
return self.to_go
def get_rice(self):
return self.rice
def get_beans(self):
return self.beans
def get_extra_meat(self):
return self.extra_meat
def get_guacamole(self):
return self.guacamole
def get_cheese(self):
return self.cheese
def get_pico(self):
return self.pico
def get_corn(self):
return self.corn
def get_cost(self):
cost = 5.0
if self.meat in ['chicken', 'pork', 'tofu']:
cost += 1.0
if self.meat == 'steak':
cost += 1.5
if self.extra_meat == True and self.meat != False:
cost += 1.0
if self.guacamole == True:
cost += 0.75
return cost
#Below are some lines of code that will test your class.
#You can change the value of the variable(s) to test your
#class with different inputs.
#
#If your function works correctly, this will originally
#print: 7.75
a_burrito = Burrito("pork", False, "white", "black", extra_meat = True, guacamole = True)
print(a_burrito.get_cost())
|
#Write a function called get_grade that will read a
#given .cs1301 file and return the student's grade.
#To do this, we would recommend you first pass the
#filename to your previously-written reader() function,
#then use the list that it returns to do your
#calculations. You may assume the file is well-formed.
#
#A student's grade should be 100 times the sum of each
#individual assignment's grade divided by its total,
#multiplied by its weight. So, if the .cs1301 just had
#these two lines:
#
# 1 exam_1 80 100 0.6
# 2 exam_2 30 50 0.4
#
#Then the result would be 72:
#
# (80 / 100) * 0.6 + (30 / 50) * 0.4 = 0.72 * 100 = 72
#Write your function here!
def get_grade(filename):
def reader(filename):
data = open(filename, 'r')
tups = []
for line in data:
val = line.split()
tup = (int(val[0]), val[1], int(val[2]), int(val[3]), float(val[4]))
tups.append(tup)
data.close()
return tups
values = reader(filename)
result = 0
for score in values:
result += ((score[2] / score[3]) * score[4])
return result * 100
|
#Write a function called "reader" that reads in a ".cs1301"
#file described in the previous problem. The function should
#return a list of tuples representing the lines in the file like so:
#
#[(line_1_number, line_1_assignment_name, line_1_grade, line_1_total, line_1_weight),
#(line_2_number, line_2_assignment_name, line_2_grade, line_2_total, line_2_weight)]
#
#All items should be of type int except for the name (string)
#and the weight (float). You can assume the file will be in the
#proper format -- in a real program, you would use your code
#from the previous problem to check for formatting before
#trying to call the function below.
#
#Write your function here!
def reader(filename):
data = open(filename, 'r')
tups = []
for line in data:
val = line.split()
tup = (int(val[0]), val[1], int(val[2]), int(val[3]), float(val[4]))
tups.append(tup)
data.close()
return tups
|
key1=[1,2,3]
str1=['a','b','c']
print (key1)
print (key1*2)
print (key1*3)
key2 = key1 + str1
print (key2)
del key1[2]
print (key1)
key1[1]='aab'
print (key1)
print()
print("列表查找")
str2=[13,2,23,5]
print (str2.index(5))
print()
print("列表插入")
key1.insert(1,'a1')
print (key1)
print()
print("列表追加")
key1.append('ccc')
print (key1)
print()
key1.remove('ccc')
print (key1)
print()
print("列表排序-升序")
str2=[13,2,23,5]
str2.sort()
print (str2)
print()
print("列表排序-降序")
str2=[13,2,23,5]
str2.sort(reverse=True)
print (str2)
|
import math
N = int(raw_input("Enter N:"))
R_i = raw_input("Enter R's seperated by a space: ")
M = int(raw_input("Enter M: "))
coor_list = []
if M > 1:
for i in range(M):
coordinate = raw_input("Enter coordinates: ")
coor_list.append(coordinate)
else:
coordinate = raw_input("Enter coordinates: ")
coor_list.append(coordinate)
#Split the radius' into a list of integers
R_list = [int(n) for n in R_i.split()]
#Split the coordinates into a list of lists
for i in range(len(coor_list)):
temp_list = [int(n) for n in coor_list[i].split()]
coor_list[i] = temp_list
count = 0
#function that will determine if a line and circle intersect
def do_they_intersect(radius,x1,y1,x2,y2):
global count
#figure out which of the two points is closer to the center
first_point_distance = math.sqrt((x1)**2 + (y1)**2)
second_point_distance = math.sqrt((x2)**2 + (y2)**2)
print first_point_distance, second_point_distance, radius
#find distance between the two points:
between_distance = math.sqrt((x1- x2)**2 + (y1 - y2)**2)
#Check if the inner point is within the circle, if the inner point is within the circle
#check if outer point is outside of it
#if inner point not in the cirlce, then they do not touch
if first_point_distance < second_point_distance:
if first_point_distance < radius and second_point_distance > radius:
count += 1
else:
if second_point_distance > radius and first_point_distance < radius:
count += 1
print count
#Check each arrow with each circle
for i in range(len(R_list)):
for n in range(len(coor_list)):
do_they_intersect(R_list[i],coor_list[n][0],coor_list[n][1],coor_list[n][2],coor_list[n][3])
print count
#### The above will solve the problem in O(mn) m-> number of circles , n->number of lines
#### A better solution of O(nlogm) can be given . The idea is :
#### 1) Sort the array of radius in incresing order
#### 2) For each line ,
#### A) Select the point which has minimum distance from origin (i.e the innermost of the two).
#### B) Now we find the innermost circle which has this start point inside it . (Can be done in O(logm) using Binary Search )
#### C) Select the point which has maximum distance from origin (i.e the outermost of the two).
#### D) Now we find the Outermost circle which has this end point outside it . (Can be done in O(logm) using Binary Search )
#### Therefore number of circles this line intersects is (Result_CircleIndexOf( Step D) - Result_CircleIndexOf( Step A) + 1 )
#### 3) Repeat Step 2 , n times.
##### So O(mlogn)
####
|
"""
两个数组的交集,考虑顺序问题所以先sort了一下,如果不sort则蜕变为最长公共子串问题
"""
num1 = [4, 4, 8]
num2 = [4, 2, 5, 4, 13]
print("Input two list :")
print(num1)
print(num2)
small = 0
big = 0
common = []
num1.sort()
num2.sort()
for i in num2:
if small < len(num1):
if num1[small] == num2[big]:
common.append(num2[big])
big += 1
small += 1
else:
big += 1
small = 0
print("Intersaction : \n",common)
|
import os
from Rule import *
# This function creates a new rule, asking the user to enter different information about the rule.
# Each information entered by the user is stored in a dictionary. Before sending this new rule into our database,
# we check if there are rules with the same id entered, or having a higher id number.
# If yes, we will increment the id of these rules, then we will send our new rule in the database.
# Finally, we display the rules of our database
def rule_creation():
print(os.system("clear"))
print_rules()
print("Enter the different information about your rule:\nPress enter to set the field blank")
rule = {}
rule["Position"] = str(input("Index: "))
rule["Decision"] = str(input("Type: "))
rule["IpSrc"] = str(input("Ip Source: "))
rule["IpDst"] = str(input("Ip Destination: "))
rule["PortSrc"] = str(input("Port Source: "))
rule["PortDst"] = str(input("Port Destination: "))
rule["Proto"] = str(input("Protocol: "))
cursor.execute("SELECT ID FROM RulesConnection ORDER BY ID DESC")
rules_connection = cursor.fetchall()
if len(rules_connection) > 0:
last_rule = rules_connection[0]
last_id = str(last_rule[0])
while last_id >= rule["Position"]:
new_id = str(int(last_id) + 1)
cursor.execute("UPDATE RulesConnection SET ID=(?) WHERE ID=(?)", (new_id, last_id))
last_id = str(int(last_id) - 1)
cursor.execute("""INSERT INTO RulesConnection(ID, IpSrc, IpDst, PortSrc, PortDst, Proto, Decision)
VALUES(:Position, :IpSrc, :IpDst, :PortSrc, :PortDst, :Proto, :Decision)""", rule)
conn.commit()
print_rules()
rule_creation()
|
# Now, we don't just want our computer to be able to do preset calculations -
# we want it to respond to different situations; otherwise we might as well
# do the maths using just a calculator!
# We can do this using inputs.
print("Type your name:")
name = input()
print("Your name is " + name + ". I hope that isn't surprising.")
# Now hit run. On the window on the right, you should be prompted to enter
# your name. See if the program works as you'd expect.
# A caveat for python is that all inputs are `string` type (`string` is a
# fancy computer term for 'word'). That means, we need to convert our inputs
# to numbers if we want to make a calculator.
print("Type a number:")
num1 = int(input())
print("Type another number:")
num2 = int(input())
print("The sum is:")
print(num1 + num2)
# So what did we do here? We asked python to remember two numbers that we
# typed in, and then add them. Now you can run this program multiple times
# without changing the code, and it'll still produce the sum each time.
|
from nltk.stem import SnowballStemmer
from collections import defaultdict
def decompound(word, vocabulary):
'''Decompounds a word.
This function tries to split a given word up into combinations
of different words from a given vocabulary.
Example:
- decompound('toothbrush', ['tooth', 'brush']) => [['tooth', 'brush']]
Arguments:
word {str} -- Target word
vocabulary {str[]} -- Target vocabulary
Returns:
str[][] -- List of possible combinations to construct the target word
with words from the vocabulary
'''
# Prepare dictionary for O(1) lookup and stemming.
stemmer = SnowballStemmer('german')
dictionary = { w: w for w in set([ stemmer.stem(w) for w in vocabulary ]) }
# Dict containing found words within target word with their indexes
subwords = defaultdict(set)
# This list contains the indexes from which a word should be searched.
#
# Example:
#
# - word = "Autobahn" and todo = [0] => Check "A", "Au", "Aut", "Auto" ...
# - word = "Autobahn" and todo = [0, 3] => Check "A", "Au", ... AND "b", "ba", "bah", "bahn" ...
todo = [0]
# Phase 1: Find all subwords
fugenlaute = ['e', 's', 'es', 'n', 'en', 'er', 'ens']
while todo:
if not todo[0] in subwords:
for i in range(todo[0] + 1, len(word) + 1):
current_subword = word[todo[0]:i]
current_subword_stemmed = stemmer.stem(current_subword)
if current_subword_stemmed in dictionary:
# determine possible indices for the
# next word.
# 1. Just right after the non-stemmed subword
next_indices = [todo[0] + len(current_subword)]
# 2. If 'Fugenlaut' comes afterwards, respect that too
# as a possible start of a new subword.
for j in range(1, 3):
tmp = next_indices[0] + j
if tmp > len(word):
break
if word[next_indices[0]:tmp] in fugenlaute:
next_indices.append(tmp)
# Add subword to dict
subwords[todo[0]] = subwords[todo[0]].union(next_indices)
# Update todo list
todo += next_indices
del todo[0]
# Phase 2: Try to combine all subwords
result = []
def tree_search(i, configuration):
if i == len(word):
if configuration:
# Found a match
result.append(configuration)
return
if not i in subwords:
return
for j in subwords[i]:
tree_search(j, configuration + [word[i:j]])
tree_search(0, [])
return result
|
# 1. import Flask
from flask import Flask, jsonify
app = Flask(__name__)
@app.route("/")
def trip():
print("All available routes")
r return(
f"<br/>"
f"/api/v1.0/precipitation<br/>"
f"<br/>"
f"/api/v1.0/stations<br/>"
f"<br/>"
f"/api/v1.0/tobs<br/>"
f"<br/>"
f"/api/v1.0/<start><br/>"
f"<br/>"
f"/api/v1.0/<start>/<end><br/>"
)
@app.route("/api/v1.0/precipitation")
def precipitation():
# * Query for the dates and precipitation observations from the last year.
# * Convert the query results to a Dictionary using `date` as the key and `prcp` as the value.
# * Return the json representation of your dictionary.
last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()
last_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)
rain = session.query(Measurement.date, Measurement.prcp).\
filter(Measurement.date > last_year).\
order_by(Measurement.date).all()
# Create a list of dicts with `date` and `prcp` as the keys and values
rain_totals = []
for result in rain:
row = {}
row["date"] = rain[0]
row["prcp"] = rain[1]
rain_totals.append(row)
return jsonify(rain_totals)
#########################################################################################
@app.route("/api/v1.0/stations")
def stations():
# * Return a JSON list of stations from the dataset.
stations = session.query(Station.station,Station.name).all()
return jsonify(stations)
#########################################################################################
@app.route("/api/v1.0/tobs")
def tobs():
# * Query for the dates and temperature observations from a year from the last data point.
# * Return a JSON list of Temperature Observations (tobs) for the previous year.
last_date = session.query(Measurement.date).order_by(Measurement.date.desc()).first()
last_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)
tobs = session.query(Measurement.date,Measurement.tobs).\
filter(Measurement.date > last_year).\
order_by(Measurement.date).all()
return jsonify(tobs)
#########################################################################################
@app.route("/api/v1.0/<start>")
def startDate(date):
# * When given the start only, calculate TMIN, TAVG, and TMAX for all dates greater than and equal to the start date.
start_Date= session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= date).all()
return jsonify(start_Date)
@app.route("/api/v1.0/<start>/<end>")
# * When given the start and the end date, calculate the TMIN, TAVG, and TMAX for dates between the start and end date inclusive.
def startDateEndDate(start,end):
Dates_results = session.query(func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)).filter(Measurement.date >= start).filter(Measurement.date <= end).all()
return jsonify(Dates_results) |
import pygame
from .Pieces import *
from .constants import *
class newBoard:
def __init__(self, Width, Height, Rows, Cols, Square, Win):
self.Width = Width
self.Height = Height
self.Square = Square
self.GameBoard = self.Width//2
self.Win = Win
self.Rows = Rows
self.Cols = Cols
self.Board = []
self.create_Board()
def create_Board(self):
for row in range(self.Rows):
self.Board.append([0 for i in range(self.Cols)])
for col in range(self.Cols):
if row == 1:
self.Board[row][col] = Pawn(self.Square,Black_pawn,Black,"Pawn",row,col)
if row == 6:
self.Board[row][col] = Pawn(self.Square,White_pawn,White,"Pawn",row,col)
if row == 0:
if col == 0 or col == 7:
self.Board[row][col] = Rook(self.Square, Black_Rook,Black,"Rook",row,col)
if col == 1 or col == 6:
self.Board[row][col] = Knight(self.Square, Black_Knight,Black,"Knight",row,col)
if col == 2 or col == 5:
self.Board[row][col] = Bishop(self.Square, Black_Bishop,Black,"Bishop",row,col)
if col == 3:
self.Board[row][col] = Queen(self.Square, Black_Queen,Black,"Queen",row,col)
if col == 4:
self.Board[row][col] = King(self.Square, Black_King,Black,"King",row,col)
if row == 7:
if col == 0 or col == 7:
self.Board[row][col] = Rook(self.Square, White_Rook,White,"Rook",row,col)
if col == 1 or col == 6:
self.Board[row][col] = Knight(self.Square, White_Knight,White,"Knight",row,col)
if col == 2 or col == 5:
self.Board[row][col] = Bishop(self.Square, White_bishop,White,"Bishop",row,col)
if col == 3:
self.Board[row][col] = Queen(self.Square, White_Queen,White,"Queen",row,col)
if col == 4:
self.Board[row][col] = King(self.Square, White_King,White,"King",row,col)
def get_piece(self,row,col):
return self.Board[row][col]
def move(self,piece,row,col):
self.Board[piece.row][piece.col], self.Board[row][col] = self.Board[row][col], self.Board[piece.row][piece.col]
piece.piece_move(row,col)
if piece.type == "Pawn":
if piece.first_move:
piece.first_move = False
def draw_Board(self):
self.Win.fill(brown)
for row in range(Rows):
for col in range(row%2, Cols,2):
pygame.draw.rect(self.Win,White,(Square*(row), Square*(col),Square,Square))
def draw_piece(self,piece,Win):
Win.blit(piece.image, (piece.x, piece.y))
def draw_pieces(self):
for row in range(self.Rows):
for col in range(self.Cols):
if self.Board[row][col] != 0:
self.draw_piece(self.Board[row][col], self.Win)
|
asignaturas = ["Matemáticas", "Física", "Química", "Historia", "Lengua"]
notas = []
for asignatura in asignaturas:
nota = input("¿Qué nota has sacado en " + asignatura + "?")
notas.append(nota)
for i in range(len(asignaturas)):
print("En " + asignaturas[i] + " has sacado " + notas[i]) |
class Telefono():
def __init__(self,marca,color,precio):
self.marca = marca
self.color = color
self.precio = precio
self.encendido=False
def encender(self):
self.encendido=True
def estado(self):
if(self.encendido):
return "El telefono esta encendido"
else:
return "El telefono esta en apagado"
Telefono1 = Telefono ("Samsung","negro","$25000")
Telefono2 = Telefono ("Nokia","Blanco","$17000")
print ("El telefono es marca",Telefono1.marca,", su color es",Telefono1.color,"y su precio es",Telefono1.precio,"pesos")
print ("El telefono es marca",Telefono2.marca,", su color es",Telefono2.color,"y su precio es",Telefono2.precio,"pesos")
Telefono1.encender()
print (Telefono1.estado())
|
import turtle
import random
import lsystem
"""
Randomizes the lsystem and sets the turtle position
args: snap(turtle)
return: fn (text file)
"""
def randLsystem(snap):
fn = "Rules" + str(random.randint(2,3)) + ".txt"
if(fn == "Rules3.txt"):
snap.setpos(-325,325)
else:
snap.setpos(0,0)
return fn
"""
Creates the turtle (Jeff) and screen
args: colors (list of tuples of ints)
return: None
"""
def colorTurtle(colors):
wn = turtle.Screen()
wn.colormode(255)
wn.bgcolor("black")
jeff = turtle.Turtle()
jeff.shape("turtle")
jeff.pensize(5)
jeff.penup()
#jeff.setpos(-325,325)
jeff.pendown()
jeff.speed(0)
sys = lsystem.Lsystem(randLsystem(jeff))
sys.createLsystem()
sys.drawLSystem(jeff,colors)
wn.exitonclick()
def main():
''' Takes words from the user and changes them to the hex value - Adds 125 to make it lighter'''
colorList = []
while (len(colorList) < 9):
word = input("Please enter a different 3-letter word: ")
if len(word) > 3:
print("You idiot, I said 3-letter word")
elif len(word) == 0:
print("You idiot, enter a 3-letter word")
else:
for char in word:
colorList += [(ord(char)//16) * 10 + (ord(char)%16 + 125)]
''' Adjusts colors if too high or low'''
rgbList = []
for i in range(0, len(colorList), 3):
(r,g,b) = (colorList[i], colorList[i+1], colorList[i+2])
for i in range(3):
if r > 200 and g < 200:
b -= 50
elif r <= 200:
r += 50
elif g >= 200:
g -= 70
else:
b += 20
rgbList += [(r,g,b)]
colorTurtle(rgbList)
main()
|
#字典的数据类型
a={}
print(type(a))
a["one"]="this is number 1"
a["two"]="this is number 2"
print(a)
print(a['one'])
a["one"]="this is number 1,yeal"
print(a)
b={'one':'this is apple','two':'this is banana'}
print(b['one'])
#用dict初始化字典
inventory=dict([('a',123),('b',456),('c',789)])
print(inventory)
inventory['a']+=1
print(inventory) |
class Node(object):
def __init__(self,data,next=None):
self.data = data
self.next = next
class linkOne(object):
def __init__(self):
self.head = None
self.tail = None
self.count = 0
def isEmpty(self):
return self.count==0
def size(self):
return self.count
def addElementToTail(self,data):
if(self.tail!= None):
temp = Node(data,None)
self.tail.next = temp
self.tail = temp
self.count += 1
else:
self.head=self.tail=Node(data,None)
self.count+=1
def DeleteElementFromTail(self):
if(self.head==self.tail):
self.count=0
self.head=self.tail=None
else:
temp = self.tail
t = self.head
while(t.next!=self.tail):
t = t.next
self.tail=t
self.count -= 1
del temp
return temp.data
lk = linkOne()
lk.addElementToTail(10)
lk.addElementToTail(20)
lk.addElementToTail(30)
lk.addElementToTail(40)
a = lk.size()
b = lk.tail.data
c = lk.head.next.next.data
print(a)
print(b)
print(c)
|
#!/usr/bin/python3
# -*- encoding: utf-8 -*-
class Lnode:
def __init__(self, elem, next_=None): ##初始化链表,并结点的next赋None
self.elem = elem
self.next = next_
llist1 = Lnode(1) ##头结点
p = llist1
for i in range(2, 11):
p.next = Lnode(i) ##创建新的结点
p = p.next
p = llist1 ###p重新指向表头 遍历所有的结点输出元素
while p is not None:
print(p.elem)
p = p.next |
# Course: CS261 - Data Structures
# Student Name: Nick Askam
# Assignment: 6
# Description: Undirected Graph implementation, to add, track, remove edges and vertices. Also, tell if there's a cycle
# , valid path, and count the connected
import heapq
class UndirectedGraph:
"""
Class to implement undirected graph
- duplicate edges not allowed
- loops not allowed
- no edge weights
- vertex names are strings
"""
def __init__(self, start_edges=None):
"""
Store graph info as adjacency list
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
self.adj_list = dict()
# populate graph with initial vertices and edges (if provided)
# before using, implement add_vertex() and add_edge() methods
if start_edges is not None:
for u, v in start_edges:
self.add_edge(u, v)
def __str__(self):
"""
Return content of the graph in human-readable form
DO NOT CHANGE THIS METHOD IN ANY WAY
"""
out = [f'{v}: {self.adj_list[v]}' for v in self.adj_list]
out = '\n '.join(out)
if len(out) < 70:
out = out.replace('\n ', ', ')
return f'GRAPH: {{{out}}}'
return f'GRAPH: {{\n {out}}}'
# ------------------------------------------------------------------ #
def add_vertex(self, v: str) -> None:
"""
Add new vertex to the graph
"""
self.adj_list[v] = list()
def add_edge(self, u: str, v: str) -> None:
"""
Add edge to the graph
"""
if u != v:
# test if the vertex is in the list
if u not in self.adj_list:
self.add_vertex(u)
if v not in self.adj_list:
self.add_vertex(v)
# see if the value is already in the list, if not remove
if v not in self.adj_list[u]:
self.adj_list[u].append(v)
if u not in self.adj_list[v]:
self.adj_list[v].append(u)
def remove_edge(self, v: str, u: str) -> None:
"""
Remove edge from the graph
"""
# make sure both are in the graph and are connected
if (v in self.adj_list and u in self.adj_list) and v in self.adj_list[u] and u in self.adj_list[v]:
# remove the vertex edges
self.adj_list[u].remove(v)
self.adj_list[v].remove(u)
def remove_vertex(self, v: str) -> None:
"""
Remove vertex and all connected edges
"""
# remove vertex if in the graph
if v in self.adj_list:
for endpoints in self.adj_list:
if endpoints in self.adj_list[v]:
self.remove_edge(v, endpoints)
self.adj_list.pop(v)
def get_vertices(self) -> []:
"""
Return list of vertices in the graph (any order)
"""
heap = []
for vertices in self.adj_list:
heapq.heappush(heap, vertices)
return heap
def get_edges(self) -> []:
"""
Return list of edges in the graph (any order)
"""
edge_container = []
# look in each vertex for each connector to add
for vertex in self.adj_list:
for element in self.adj_list[vertex]:
# if it's already been added, do not add
if (element, vertex) not in edge_container:
edge_container.append((vertex, element))
return edge_container
def is_valid_path(self, path: []) -> bool:
"""
Return true if provided path is valid, False otherwise
"""
# if the path is empty
if not path:
return True
path_length = path.__len__()
path_index = 0
# if the path only has one element
if path_length == 1:
if path[0] in self.adj_list:
return True
else:
return False
while path_index < path_length:
# if the path is in the list
if path[path_index] in self.adj_list:
# set what value should be checked based upon the index
if path_index != path_length - 1:
path_index_check = path_index + 1
else:
path_index_check = 0
# make sure the next index can be reached
if path[path_index_check] in self.adj_list[path[path_index]]:
path_index += 1
else:
return False
else:
return False
return True
def dfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during DFS search
Vertices are picked in alphabetical order
"""
reachable_vertices = []
if v_start not in self.adj_list:
return reachable_vertices
stack = [v_start]
# as long as the stack is not empty
while stack.__len__() > 0:
popped_vertex = stack.pop()
# if the popped vertex is not in the current reachable vertices
if popped_vertex not in reachable_vertices:
reachable_vertices.append(popped_vertex)
if popped_vertex == v_end:
return reachable_vertices
# reverse the list
reverse_list = sorted(self.adj_list[popped_vertex])[::-1]
# test the next vertices to see if they should be checked next
for vertex in reverse_list:
if vertex not in reachable_vertices:
stack.append(vertex)
return reachable_vertices
def bfs(self, v_start, v_end=None) -> []:
"""
Return list of vertices visited during BFS search
Vertices are picked in alphabetical order
"""
reachable_vertices = []
if v_start not in self.adj_list:
return reachable_vertices
# set the stack constants
stack = [v_start]
reachable_vertices.append(v_start)
# as long as the stack is not empty
while stack.__len__() > 0:
# pop the last element
popped_vertex = stack.pop()
# return if at the end of the stack
if popped_vertex == v_end:
return reachable_vertices
# sort to find alphabetically
sorted_vertices = sorted(self.adj_list[popped_vertex])
# print("reachable: " + str(reachable_vertices))
# print("sorted: " + str(sorted_vertices))
for sibling in sorted_vertices:
# do processing if the sibling is not in reachable vertices
if sibling not in reachable_vertices:
reachable_vertices.append(sibling)
stack.insert(0, sibling)
# return if at the end of the stack
if sibling == v_end:
return reachable_vertices
return reachable_vertices
def count_connected_components(self) -> int:
"""
Return number of connected components in the graph
"""
# set the intro values
connect_components = 0
total_vertices = self.get_vertices()
# while there are still vertices left to be counted
while total_vertices:
for vertex in total_vertices:
total_vertices.remove(vertex)
# if the vertices is in bfs, remove
for value in self.bfs(vertex):
if value in total_vertices:
total_vertices.remove(value)
connect_components += 1
return connect_components
def has_cycle(self) -> bool:
"""
Return True if graph contains a cycle, False otherwise
"""
available_vertices = self.get_vertices()
# print(self.get_edges())
for vertex in available_vertices:
# set the parent and go digging to find the children
parent = vertex
for next_vertex in self.adj_list[vertex]:
for next_next_vertex in self.adj_list[next_vertex]:
if next_next_vertex != parent:
found_parent = False
dfs_next_next_vertex = self.dfs(next_next_vertex)
# look in the dfs and see if a different path was taken to the parent (not reversed)
for vertex_in_dfw in dfs_next_next_vertex:
if vertex_in_dfw == next_vertex:
found_parent = True
if vertex_in_dfw == parent and not found_parent:
return True
return False
if __name__ == '__main__':
print("\nPDF - method add_vertex() / add_edge example 1")
print("----------------------------------------------")
g = UndirectedGraph()
print(g)
for v in 'ABCDE':
g.add_vertex(v)
print(g)
g.add_vertex('A')
print(g)
for u, v in ['AB', 'AC', 'BC', 'BD', 'CD', 'CE', 'DE', ('B', 'C')]:
g.add_edge(u, v)
print(g)
print("\nPDF - method remove_edge() / remove_vertex example 1")
print("----------------------------------------------------")
g = UndirectedGraph(['AB', 'AC', 'BC', 'BD', 'CD', 'CE', 'DE'])
g.remove_vertex('DOES NOT EXIST')
g.remove_edge('A', 'B')
g.remove_edge('X', 'B')
print(g)
g.remove_vertex('D')
print(g)
print("\nPDF - method get_vertices() / get_edges() example 1")
print("---------------------------------------------------")
g = UndirectedGraph()
print(g.get_edges(), g.get_vertices(), sep='\n')
g = UndirectedGraph(['AB', 'AC', 'BC', 'BD', 'CD', 'CE'])
print(g.get_edges(), g.get_vertices(), sep='\n')
print("\nPDF - method is_valid_path() example 1")
print("--------------------------------------")
g = UndirectedGraph(['AB', 'AC', 'BC', 'BD', 'CD', 'CE', 'DE'])
test_cases = ['ABC', 'ADE', 'ECABDCBE', 'ACDECB', '', 'D', 'Z']
for path in test_cases:
print(list(path), g.is_valid_path(list(path)))
print("\nPDF - method dfs() and bfs() example 1")
print("--------------------------------------")
edges = ['AE', 'AC', 'BE', 'CE', 'CD', 'CB', 'BD', 'ED', 'BH', 'QG', 'FG']
g = UndirectedGraph(edges)
test_cases = 'ABCDEGH'
for case in test_cases:
print(f'{case} DFS:{g.dfs(case)} BFS:{g.bfs(case)}')
print('-----')
for i in range(1, len(test_cases)):
v1, v2 = test_cases[i], test_cases[-1 - i]
print(f'{v1}-{v2} DFS:{g.dfs(v1, v2)} BFS:{g.bfs(v1, v2)}')
print("\nPDF - method count_connected_components() example 1")
print("---------------------------------------------------")
edges = ['AE', 'AC', 'BE', 'CE', 'CD', 'CB', 'BD', 'ED', 'BH', 'QG', 'FG']
g = UndirectedGraph(edges)
test_cases = (
'add QH', 'remove FG', 'remove GQ', 'remove HQ',
'remove AE', 'remove CA', 'remove EB', 'remove CE', 'remove DE',
'remove BC', 'add EA', 'add EF', 'add GQ', 'add AC', 'add DQ',
'add EG', 'add QH', 'remove CD', 'remove BD', 'remove QG')
for case in test_cases:
command, edge = case.split()
u, v = edge
g.add_edge(u, v) if command == 'add' else g.remove_edge(u, v)
print(g.count_connected_components(), end=' ')
print()
print("\nPDF - method has_cycle() example 1")
print("----------------------------------")
edges = ['AE', 'AC', 'BE', 'CE', 'CD', 'CB', 'BD', 'ED', 'BH', 'QG', 'FG']
g = UndirectedGraph(edges)
test_cases = (
'add QH', 'remove FG', 'remove GQ', 'remove HQ',
'remove AE', 'remove CA', 'remove EB', 'remove CE', 'remove DE',
'remove BC', 'add EA', 'add EF', 'add GQ', 'add AC', 'add DQ',
'add EG', 'add QH', 'remove CD', 'remove BD', 'remove QG',
'add FG', 'remove GE')
for case in test_cases:
command, edge = case.split()
u, v = edge
g.add_edge(u, v) if command == 'add' else g.remove_edge(u, v)
print('{:<10}'.format(case), g.has_cycle())
|
import re
import json
from src.logger import logger
from src.utils import Util
class AnaHelper():
@staticmethod
def is_condition_match(left_operand, operator, right_operand):
match = 0
if operator != "IsNull":
if left_operand is None or right_operand is None:
return match
if isinstance(left_operand, bool):
left_operand = "true" if left_operand else "false"
elif isinstance(left_operand, float):
try:
left_operand = float(left_operand)
right_operand = float(right_operand)
except ValueError:
left_operand = str(left_operand)
right_operand = str(right_operand)
elif isinstance(left_operand, int):
left_operand = int(left_operand)
right_operand = int(right_operand)
if operator == "EqualTo":
match = left_operand == right_operand
elif operator == "NotEqualTo":
match = left_operand != right_operand
elif operator == "GreaterThan":
match = left_operand > right_operand
elif operator == "LessThan":
match = left_operand < right_operand
elif operator == "GreaterThanOrEqualTo":
match = left_operand >= right_operand
elif operator == "LessThanOrEqualTo":
match = left_operand <= right_operand
elif operator == "Mod":
match = left_operand % right_operand
elif operator == "In":
values = right_operand.split(",")
match = left_operand in values
elif operator == "NotIn":
values = right_operand.split(",")
match = left_operand not in values
elif operator == "StartsWith":
match = left_operand.startswith(right_operand)
elif operator == "EndsWith":
match = left_operand.endswith(right_operand)
elif operator == "Contains":
match = right_operand in left_operand
elif operator == "IsNull":
match = bool(left_operand) is False
elif operator == "Between":
values = right_operand.split(",")[:2]
match = left_operand > values[0] and left_operand < values[1]
else:
logger.error(f"Unknown operator found {operator}")
return match
@staticmethod
def verb_replacer(text, state):
if text is None:
return text
variable_data = state.get("var_data", {})
logger.debug(f"variable_data {variable_data} {variable_data.__class__}")
logger.debug(f"text received for replacing verbs is {text}")
# if isinstance(variable_data, str):
# variable_data = json.loads(variable_data)
all_matches = re.findall(r"\[~(.*?)\]|{{(.*?)}}", text)
for matches in all_matches:
for match in matches:
logger.debug(f"match: {match}")
if variable_data.get(match, None) is not None:
logger.debug(f"Match exists in variable_data {variable_data[match]}")
variable_value = variable_data[match]
variable_value = str(AnaHelper.escape_json_text(variable_value))
text = text.replace("[~" + match + "]", variable_value).replace("{{" + match + "}}", variable_value)
logger.debug(f"Text just after replacing is {text}")
else:
logger.debug("No exact match")
root_key = re.split(r"\.|\[", match)[0]
logger.debug(f"match: {match}")
logger.debug(f"root_key: {root_key}")
if variable_data.get(root_key, None) is None:
continue
variable_value = Util.deep_find({root_key:variable_data[root_key]}, match)
variable_value = str(AnaHelper.escape_json_text(variable_value))
logger.debug(f"match: {match}")
logger.debug(f"variable_value: {variable_value}")
text = text.replace("[~" + match + "]", str(variable_value)).replace("{{" + match + "}}", str(variable_value))
logger.debug(f"Text after replacing verbs is {text}")
return text
@staticmethod
def escape_json_text(text):
if isinstance(text, str):
text = text.replace("\n", "\\n").replace("\t", "\\t").replace("\r", "\\r")
return text
|
def levi_civita(dtype=float):
"""
Build the 3-D Levi--Civita matrix
:param dtype: data type of the matrix
:return: Levi--Civita matrix
:rtype: ndarray(3, 3, 3)
"""
from numpy import zeros
e_tensor = zeros([3, 3, 3], dtype=dtype)
for i in [(0, 1, 2), (1, 2, 0), (2, 0, 1)]:
e_tensor.itemset(i, 1)
e_tensor.itemset(i[::-1], -1)
e_tensor.setflags(write=False)
return e_tensor
LEVI_CIVITA = levi_civita(int)
|
'''
Name: Rohit Nachaloor
Date: 04/05/2019
Mastery Project
Period: 1
Cowart
'''
import mysql.connector as SQL
def final():
#establishes connection to database
dbGrade = SQL.connect(
host='localhost',
user='root',
passwd='123456',
database='grades'
)
mycursor = dbGrade.cursor()
#user inputs class they want to
print('Which class do you want to test your final grade.')
className = input()
#sql query for the getting the total weight of all the catagorys
sql = 'SELECT SUM(percent) FROM '+className+'cat;'
mycursor.execute(sql)
myresult = mycursor.fetchone()
totPer = myresult
totPer = str(totPer)
totPer = totPer.strip("(Decimal'")
totPer = int(float(totPer.strip("'),)")))
xCatNum = 1
#sql query for counting the amount of categories in a class
sql = 'SELECT COUNT(id) FROM '+str(className)+'cat;'
mycursor.execute(sql)
myresult = mycursor.fetchone()
CATNUM = myresult
catNUM = str(CATNUM)
CATnum = catNUM.strip('(')
catNum = int(CATnum.strip(',)'))
calcList = []
calcTot = lambda x, y, z : x + y + z
#if statements dependent on the amount of the number of grade categories
if (catNum == 2):
while (xCatNum < 3):
#sql statement that collects the names of the categories
sql = 'SELECT catagory FROM '+str(className)+'cat WHERE id = '+str(xCatNum)
mycursor.execute(sql)
myresult = mycursor.fetchone()
CAT = myresult
caT = str(CAT)
CaT = caT.strip('(')
cat = CaT.strip(',)')
#sql query that counts the amount of grades in a catagory
sql = 'SELECT COUNT(grade) FROM '+str(className)+' WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
y = myresult
#sql query that averages the grades in a certain category
sql = 'SELECT AVG(grade) FROM '+str(className)+' WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
gradeAvg = str(myresult)
gradeAvg = gradeAvg.strip("(Decimal'")
gradeAvg = int(float(gradeAvg.strip("'),)")))
#sql query that gets the percent of grade that a category takes up
sql = 'SELECT percent FROM '+str(className)+'cat WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
res = str(myresult)
res = res.strip('(')
res = int(res.strip(',)'))
#lambda function that calculates the weighted portion of a category
catCalc = lambda x, y : x * (y / 100)
#the previous value is being added to a list.
calcList.append(catCalc(gradeAvg, res))
xCatNum = xCatNum + 1
#gives final exam weight
finalWeig = 100 - totPer
#asks for desired final exam grade
print('What do you want on the final exam.')
gradeWish = int(input())
wishWeight = (finalWeig / 100) * gradeWish
#lambda that calculates the average with the desired final exam grade
finalCalc = lambda x, y, z : ((x + y + z) / 100) * 100
average = finalCalc(int(calcList[0]), int(calcList[1]), wishWeight)
print(average)
if (catNum == 3):
while (xCatNum < 4):
#sql statement that collects the names of the categories
sql = 'SELECT catagory FROM '+str(className)+'cat WHERE id = '+str(xCatNum)
mycursor.execute(sql)
myresult = mycursor.fetchone()
CAT = myresult
caT = str(CAT)
CaT = caT.strip('(')
cat = CaT.strip(',)')
#sql query that counts the amount of grades in a catagory
sql = 'SELECT COUNT(grade) FROM '+str(className)+' WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
y = myresult
#sql query that averages the grades in a certain category
sql = 'SELECT AVG(grade) FROM '+str(className)+' WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
gradeAvg = str(myresult)
gradeAvg = gradeAvg.strip("(Decimal'")
gradeAvg = int(float(gradeAvg.strip("'),)")))
#sql query that gets the percent of grade that a category takes up
sql = 'SELECT percent FROM '+str(className)+'cat WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
res = str(myresult)
res = res.strip('(')
res = int(res.strip(',)'))
#lambda function that calculates the weighted portion of a category
catCalc = lambda x, y : x * (y / 100)
calcList.append(catCalc(gradeAvg, res))
xCatNum = xCatNum + 1
#gives final exam weight
finalWeig = 100 - totPer
print('What do you want on the final exam.')
gradeWish = int(input())
wishWeight = (finalWeig / 100) * gradeWish
# lambda that calculates the average with the desired final exam grade
finalCalc = lambda w, x, y, z : ((w + x + y + z) / 100) * 100
average = finalCalc(int(calcList[0]), int(calcList[1]), int(calcList[2]), wishWeight)
print(average)
if (catNum == 4):
while (xCatNum < 5):
#sql statement that collects the names of the categories
sql = 'SELECT catagory FROM '+str(className)+'cat WHERE id = '+str(xCatNum)
mycursor.execute(sql)
myresult = mycursor.fetchone()
CAT = myresult
caT = str(CAT)
CaT = caT.strip('(')
cat = CaT.strip(',)')
#sql query that counts the amount of grades in a catagory
sql = 'SELECT COUNT(grade) FROM '+str(className)+' WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
y = myresult
#sql query that averages the grades in a certain category
sql = 'SELECT AVG(grade) FROM '+str(className)+' WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
gradeAvg = str(myresult)
gradeAvg = gradeAvg.strip("(Decimal'")
gradeAvg = int(float(gradeAvg.strip("'),)")))
#sql query that gets the percent of grade that a category takes up
sql = 'SELECT percent FROM '+str(className)+'cat WHERE catagory = '+str(cat)
mycursor.execute(sql)
myresult = mycursor.fetchone()
res = str(myresult)
res = res.strip('(')
res = int(res.strip(',)'))
#lambda function that calculates the weighted portion of a category
catCalc = lambda x, y : x * (y / 100)
calcList.append(catCalc(gradeAvg, res))
xCatNum = xCatNum + 1
#gives final exam weight
finalWeig = 100 - totPer
print('What do you want on the final exam.')
gradeWish = int(input())
wishWeight = (finalWeig / 100) * gradeWish
# lambda that calculates the average with the desired final exam grade
finalCalc = lambda v, w, x, y, z : ((v + w + x + y + z) / 100) * 100
average = finalCalc(int(calcList[0]), int(calcList[1]), int(calcList[2]), int(calcList[3]), wishWeight)
print(average)
|
# coding: utf-8
# # Handwritten Number Recognition with TFLearn and MNIST
#
# In this notebook, we'll be building a neural network that recognizes handwritten numbers 0-9.
#
# This kind of neural network is used in a variety of real-world applications including: recognizing phone numbers and sorting postal mail by address. To build the network, we'll be using the **MNIST** data set, which consists of images of handwritten numbers and their correct labels 0-9.
#
# We'll be using [TFLearn](http://tflearn.org/), a high-level library built on top of TensorFlow to build the neural network. We'll start off by importing all the modules we'll need, then load the data, and finally build the network.
# [ ]:
# Import Numpy, TensorFlow, TFLearn, and MNIST data
import numpy as np
import tensorflow as tf
import tflearn
import tflearn.datasets.mnist as mnist
import pandas as pd
# ## Retrieving training and test data
#
# The MNIST data set already contains both training and test data. There are 55,000 data points of training data, and 10,000 points of test data.
#
# Each MNIST data point has:
# 1. an image of a handwritten digit and
# 2. a corresponding label (a number 0-9 that identifies the image)
#
# We'll call the images, which will be the input to our neural network, **X** and their corresponding labels **Y**.
#
# We're going to want our labels as *one-hot vectors*, which are vectors that holds mostly 0's and one 1. It's easiest to see this in a example. As a one-hot vector, the number 0 is represented as [1, 0, 0, 0, 0, 0, 0, 0, 0, 0], and 4 is represented as [0, 0, 0, 0, 1, 0, 0, 0, 0, 0].
#
# ### Flattened data
#
# For this example, we'll be using *flattened* data or a representation of MNIST images in one dimension rather than two. So, each handwritten number image, which is 28x28 pixels, will be represented as a one dimensional array of 784 pixel values.
#
# Flattening the data throws away information about the 2D structure of the image, but it simplifies our data so that all of the training data can be contained in one array whose shape is [55000, 784]; the first dimension is the number of training images and the second dimension is the number of pixels in each image. This is the kind of data that is easy to analyze using a simple neural network.
# [ ]:
# Retrieve the training and test data
trainX, trainY, testX, testY = mnist.load_data(one_hot=True)
# ## Visualize the training data
#
# Provided below is a function that will help you visualize the MNIST data. By passing in the index of a training example, the function `show_digit` will display that training image along with it's corresponding label in the title.
# [ ]:
# Visualizing the data
import matplotlib.pyplot as plt
get_ipython().magic('matplotlib inline')
# Function for displaying a training image by it's index in the MNIST set
def show_digit(index):
label = trainY[index].argmax(axis=0)
# Reshape 784 array into 28x28 image
image = trainX[index].reshape([28,28])
plt.title('Training data, index: %d, Label: %d' % (index, label))
plt.imshow(image, cmap='gray_r')
plt.show()
# Display the first (index 0) training image
show_digit(0)
# ## Building the network
#
# TFLearn lets you build the network by defining the layers in that network.
#
# For this example, you'll define:
#
# 1. The input layer, which tells the network the number of inputs it should expect for each piece of MNIST data.
# 2. Hidden layers, which recognize patterns in data and connect the input to the output layer, and
# 3. The output layer, which defines how the network learns and outputs a label for a given image.
#
# Let's start with the input layer; to define the input layer, you'll define the type of data that the network expects. For example,
#
# ```
# net = tflearn.input_data([None, 100])
# ```
#
# would create a network with 100 inputs. The number of inputs to your network needs to match the size of your data. For this example, we're using 784 element long vectors to encode our input data, so we need **784 input units**.
#
#
# ### Adding layers
#
# To add new hidden layers, you use
#
# ```
# net = tflearn.fully_connected(net, n_units, activation='ReLU')
# ```
#
# This adds a fully connected layer where every unit (or node) in the previous layer is connected to every unit in this layer. The first argument `net` is the network you created in the `tflearn.input_data` call, it designates the input to the hidden layer. You can set the number of units in the layer with `n_units`, and set the activation function with the `activation` keyword. You can keep adding layers to your network by repeated calling `tflearn.fully_connected(net, n_units)`.
#
# Then, to set how you train the network, use:
#
# ```
# net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
# ```
#
# Again, this is passing in the network you've been building. The keywords:
#
# * `optimizer` sets the training method, here stochastic gradient descent
# * `learning_rate` is the learning rate
# * `loss` determines how the network error is calculated. In this example, with categorical cross-entropy.
#
# Finally, you put all this together to create the model with `tflearn.DNN(net)`.
# **Exercise:** Below in the `build_model()` function, you'll put together the network using TFLearn. You get to choose how many layers to use, how many hidden units, etc.
#
# **Hint:** The final output layer must have 10 output nodes (one for each digit 0-9). It's also recommended to use a `softmax` activation layer as your final output layer.
# [ ]:
# Define the neural network
def build_model():
# This resets all parameters and variables, leave this here
tf.reset_default_graph()
#### Your code ####
# Include the input layer, hidden layer(s), and set how you want to train the model
net = tflearn.input_data([None, 28*28]) # Input
net = tflearn.fully_connected(net, 30, activation='ReLU') # Hidden
net = tflearn.fully_connected(net, 10, activation='softmax') # Output
net = tflearn.regression(net, optimizer='sgd', learning_rate=0.1, loss='categorical_crossentropy')
# This model assumes that your network is named "net"
model = tflearn.DNN(net)
return model
# [ ]:
# Build the model
model = build_model()
# 增加 callback 函数,观察 loss,acc 的变化情况
class MonitorCallback(tflearn.callbacks.Callback):
def __init__(self, num_samples):
self.num_samples = num_samples
self.iter = []
self.train_losses = []
self.train_acc = []
self.valid_losses = []
self.valid_acc = []
def on_batch_end(self, training_state, snapshot=False):
# print("The training loss is: ", training_state.global_loss)
self.iter.append(training_state.current_iter + (training_state.epoch - 1) * self.num_samples)
self.train_losses.append(training_state.loss_value)
self.train_acc.append(training_state.acc_value)
def on_epoch_end(self, training_state):
self.valid_losses.append(training_state.val_loss )
self.valid_acc.append(training_state.val_acc )
monitorCallback = MonitorCallback(len(trainX)*0.9)
# ## Training the network
#
# Now that we've constructed the network, saved as the variable `model`, we can fit it to the data. Here we use the `model.fit` method. You pass in the training features `trainX` and the training targets `trainY`. Below I set `validation_set=0.1` which reserves 10% of the data set as the validation set. You can also set the batch size and number of epochs with the `batch_size` and `n_epoch` keywords, respectively.
#
# Too few epochs don't effectively train your network, and too many take a long time to execute. Choose wisely!
# [ ]:
# Training
# 分多次训练(运行model.fit),大约在106 epoch模型逐渐达到最优,准确率大约99%
# 训练时,经常出现loss突然大幅增加的情况,是否fit内部采取了kick off优化?
# 重新开始训练,一次106 epoch,大约在40epoch模型就达到最优,准确率不到97%
# 大约在epoch 30附近有几次loss突然大幅增加,其它阶段大致平稳。
model.fit(trainX, trainY, validation_set=0.1, show_metric=True, batch_size=100, n_epoch=106, snapshot_step=False, callbacks=monitorCallback)
min(monitorCallback.iter)
max(monitorCallback.iter)
len(monitorCallback.iter)
monitorCallback.train_losses
monitorCallback.train_acc
monitorCallback.valid_losses
monitorCallback.valid_acc
# 将训练过程的 loss 和 acc 画出曲线
# 但是 tflearn 没有给出每一步的 验证集的loss和acc,没法画曲线
df_progress = pd.DataFrame(monitorCallback.iter, columns=['iter'])
df_progress['train_loss'] = monitorCallback.train_losses
df_progress['train_acc'] = monitorCallback.train_acc
#df_progress_valid = pd.DataFrame(monitorCallback.iter, columns=['iter'])
df_progress_valid = pd.DataFrame(monitorCallback.valid_losses, columns=['valid_losses'])
#df_progress_valid['valid_loss'] = monitorCallback.valid_losses
df_progress_valid['valid_acc'] = monitorCallback.valid_acc
df_progress.plot(x='iter', y='train_loss')
df_progress.plot(x='iter', y='train_acc')
df_progress_valid.plot(y='valid_losses')
df_progress_valid.plot(y='valid_acc')
# ## Testing
# After you're satisified with the training output and accuracy, you can then run the network on the **test data set** to measure it's performance! Remember, only do this after you've done the training and are satisfied with the results.
#
# A good result will be **higher than 95% accuracy**. Some simple models have been known to get up to 99.7% accuracy!
# [ ]:
# Compare the labels that our model predicts with the actual labels
# Find the indices of the most confident prediction for each item. That tells us the predicted digit for that sample.
predictions = np.array(model.predict(testX)).argmax(axis=1)
# Calculate the accuracy, which is the percentage of times the predicated labels matched the actual labels
actual = testY.argmax(axis=1)
test_accuracy = np.mean(predictions == actual, axis=0)
# Print out the result
print("Test accuracy: ", test_accuracy)
#a=[1,2]
#b=[3,4]
#sum(np.array(a)*np.array(b))
|
# simple class to house code for median filter
import math
class filter:
def __init__(self, reserved):
self.data = [None] * reserved
self.sorted = []
self.reserved = reserved
# adding a value
def add(self, value):
if len(self.data) == self.reserved:
self.data.pop(0)
self.data.append(float(value))
# retrieving median value
def median(self):
self.sorted = []
for i in range(self.reserved):
if self.data[i] != None:
self.sorted.append(float(self.data[i]))
self.sorted.sort()
middle = int(math.floor(len(self.sorted) / 2))
return self.sorted[middle]
|
tags = ['python', 'development', 'tutorials', 'code']
tag_range = tags[1:2]
print(tag_range) # => development
tag_range = tags[1:3]
print(tag_range) # => development, tutorials
tag_range = tags[1:]
print(tag_range) # => development, tutorials, code
tag_range = tags[:3]
print(tag_range) # => python, development, tutorials
tag_range = tags[:-1]
print(tag_range) # => lists all except last item
tag_range = tags[:]
print(tag_range) # => prints entire list
|
post = ('Python Basics', 'Intro guide to Python', 'Some python content')
tags = ['python', 'coding', 'tutorial']
post += (tags,) # remember that the comma indicates this is intended to be a tuple
# => This will add the list tags to the end of the tuple post
print(post) # => ('Python Basics', 'Intro guide to Python', 'Some python content', ['python', 'coding', 'tutorial'])
print(post[-1]) # => ['python', 'coding', 'tutorial']
print(post[-1][1]) # => coding |
def weird_string_converter(input_text):
x = 0
result = ""
while x < len(input_text):
if x % 2 == 0:
result += input_text[x].upper()
else:
result += input_text[x].lower()
x += 1
return result
if __name__ == "__main__":
print(weird_string_converter("Moim zdaniem to nie ma tak, że dobrze albo że nie dobrze.")) |
def nb_year(p0, percent, aug, p):
"""In a small town, the population is p0 at the beginning of a year. The population regularly increases by X percent per year and moreover Z new inhabitants per year come to live in the town.
How many years does the town need to see its population greater or equal to p inhabitants?
"""
years = 0
percent /= 100
while p0 < p:
p0 = p0 + (p0 * percent) + aug
years += 1
return years
if __name__ == "__main__":
print(nb_year(1500, 5, 100, 5000)) |
def camelcase(input_text):
"""Camel Case text generator.
All words must have their first letter capitalized without spaces.
"""
words = input_text.split()
result = ""
for word in words:
result += f'{word[0].upper()}{word[1:]}'
return result
if __name__ == "__main__":
print(camelcase("oh camel camel texterino")) |
def setalarm(employed, vacation):
"""Function that determines whether alram is needed or not.
The function should return true if you are employed and not on vacation (because these are the circumstances under which you need to set an alarm). It should return false otherwise.
"""
if employed == True and vacation == False:
return True
else:
return False
if __name__ == "__main__":
print(setalarm(True, False)) |
def change(order, money):
"""Bob's Coffee Shop order and change automat.
Returns client ordered coffee when given exact amount of money, if not, asks to return the next day.
"""
menu = {
"Americano" : 2.20,
"Latte" : 2.30,
"Flat white" : 2.40,
"Filter" : 3.50
}
if menu[order] == money:
return f'Here is your {order}, have a nice day!'
else:
return "Sorry, exact change only, try again tomorrow!"
if __name__ == "__main__":
print(change("Americano", 2.20)) |
import re
def checkbook_calc(filename: str):
"""Checkbook cleaner and summarizer.
Cleans unnecessary characters and provides beautiful summary.
"""
with open(filename, "r", encoding="utf-8") as f:
checkbook_data = f.read()
checkbook_data = checkbook_data.split("\n")
balance = float(checkbook_data[0])
output_string = []
expenses = []
output_string.append(f"Original_Balance: {balance}")
for line in checkbook_data[1::]:
item_id, item_name, item_price = line.split(" ")
item_price = re.sub(r"[^\d\.]", "", item_price)
item_price = float(item_price)
expenses.append(item_price)
balance -= item_price
output_string.append(f"{item_id} {item_name} {item_price} Balance {balance:.2f}")
output_string.append(f"Total expense {sum(expenses):.2f}")
output_string.append(f"Average expense {sum(expenses)/len(expenses):.2f}")
return "\n".join(output_string)
if __name__ == "__main__":
print(checkbook_calc("input.txt")) |
def points(e):
return e['points']
def name(e):
return e['name']
def position_ranking():
contestants = [
{
'name': "John",
'points': 100,
},
{
'name': "Bob",
'points': 130,
},
{
'name': "Mary",
'points': 120,
},
{
'name': "Kate",
'points': 120,
}
]
contestants.sort(key=name)
contestants.sort(key=points, reverse=True)
cont = 0
while cont < len(contestants):
if contestants[cont] == contestants[-1]:
contestants[cont]["position"] = cont+1
cont += 1
elif contestants[cont]["points"] == contestants[cont+1]["points"]:
contestants[cont]["position"] = cont+1
contestants[cont+1]["position"] = cont+1
cont += 2
else:
contestants[cont]["position"] = cont+1
cont += 1
return contestants
if __name__ == "__main__":
print(position_ranking()) |
def phone_number_hider(number):
number = list(number)
for x in range(5, 12):
if number[x].isnumeric():
number[x] = "X"
number = "".join(number)
return number
if __name__ == "__main__":
print(phone_number_hider("201-680-0202")) |
from card import Card
import random
class Deck():
def __init__(self):
self.values = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K']
self.suites = ['Hearts', 'Clubs', 'Diamonds', 'Spades']
self.cards = []
def construct_deck(self):
for value in self.values:
for suite in self.suites:
self.cards.append(Card(value, suite))
def print_deck(self):
for card in self.cards:
print(f"{card.value} of {card.suite}")
def shuffle(self):
random.shuffle(self.cards)
def draw(self):
card = self.cards.pop(0)
return card
def return_to_deck(self, card):
self.cards.append(card)
|
email = raw_input("Enter your email text here:\n")
if email.find('emergency') == 0:
print "Do you want to make this email urgent?"
elif email.find('joke') == 0:
print "Do you want to set this email as non-urgent?"
else:
print "Mail sent, without special instructions"
|
import random
class Item(object):
def __init__(self, n, v, w):
self.name = n
self.value = v
self.weight = w
def getName(self):
return self.name
def getValue(self):
return self.value
def getWeight(self):
return self.weight
def __str__(self):
result = '<' + (self.name) + ', ' + str(self.value) + ', ' + str(self.weight) + '>'
return result
def maxValue(toConsider, avail):
if toConsider == [] or avail == 0:
result = (0, ())
elif toConsider[0].getWeight() > avail:
result = maxValue(toConsider[1:], avail)
else:
nextItem = toConsider[0]
withVal, withToTake = maxValue(toConsider[1:], (avail - nextItem.getWeight()))
withVal += nextItem.getValue()
withoutVal, withoutToTake = maxValue(toConsider[1:], avail)
if withVal > withoutVal:
result = (withVal, withToTake + (nextItem,))
else:
result = (withoutVal, withoutToTake)
return result
def buildManyItems(numItems, maxVal, maxWeight):
items = []
for i in range(numItems):
items.append(Item(str(i), random.randint(1, maxVal), random.randint(1, maxWeight)))
return items
def bigTest_rec(numItems):
items = buildManyItems(numItems, 10, 10)
val, taken = maxValue(items, 40)
print("Items taken")
for item in taken:
print(item)
print("Total value of items taken = ", val)
def fastMaxVal(toConsider, avail, memo={}):
if (len(toConsider), avail) in memo:
result = memo[(len(toConsider), avail)]
elif toConsider == [] or avail == 0:
result = (0, ())
elif toConsider[0].getWeight() > avail:
result = fastMaxVal(toConsider[1:], avail, memo)
else:
nextItem = toConsider[0]
withVal, withToTake = fastMaxVal(toConsider[1:], (avail - nextItem.getWeight()), memo)
withVal += nextItem.getValue()
withoutVal, withoutToTake = fastMaxVal(toConsider[1:], avail, memo)
if withVal > withoutVal:
result = (withVal, withToTake + (nextItem,))
else:
result = (withoutVal, withoutToTake)
memo[(len(toConsider), avail)] = result
return result
def bigTest_dyn(numItems):
items = buildManyItems(numItems, 10, 10)
val, taken = fastMaxVal(items, 40)
print("Items taken")
for item in taken:
print(item)
print("Total value of items taken = ", val)
bigTest_rec(4)
print("---------")
bigTest_dyn(4)
|
import sympy
import math
from sympy import Symbol, solve, sin, Limit, S, oo
theta = Symbol('theta')
# math.sin(theta)
"""
There's an error here. Can't get mathematical sinus. Because theta isn't a mathematical magnitude.
Burada hata var. Matematiksel sinüs alamıyor. Çünkü theta matematiksel bir büyüklük değil.
"""
print(sympy.sin(theta)*sympy.sin(theta))
u = Symbol('u')
t = Symbol('t')
g = Symbol('g')
print(solve(u*sin(theta)-g*t, t))
# We find what is the value of t. / T değerinin ne olduğunu buluruz.
x = Symbol('x')
l = Limit(1/x, x, oo)
print(l.doit())
st = 5*t**2 + 2*t + 8
t1 = Symbol('t1')
delta_t = Symbol('delta_t')
st1 = st.subs({t:t1})
# We updated the t variables in st with t1. / St'deki t değişkenlerini t1 ile güncelledik.
st1_delta = (st.subs({t: t1+delta_t}))
f_d = Limit(((st1_delta - st1) / delta_t), delta_t, 0)
# We found the derivative of the st function. / St fonksiyonunun türevini bulduk.
print(f_d.doit())
|
print('Лабораторная работа №12')
print()
print('Название программы : Текст')
print('Назначение программы : Работа с текстом')
print()
print()
print()
text = [' Приветствую каждого читателя. Сегодня я с радостью ',
' расскажу Вам прекрасный рецепт лабораторной ',
' работы по программированию на Питоне! Вам точно понадобится',
' придумать алгоритм и записать его на нужном ',
' языке программирования. Затем Вам нужно написать',
'комментарий к каждому сложному моменту программы. Далее ',
' следует описать все переменные. И также Вам пригодится ',
' тестовый пример. Мы все обожаем Питон!']
t = []
for i in range(len(text)):
t.append(text[i].split())
choice = None
while choice != '0':
print('''
Индивидуальное задание : поменять местами самое короткое слово самой \
длинной строки и самое длинное слово самой короткой строки
1) Показать текст
2) Показать результат
0) Выход
''')
choice = input('Введите пункт меню : ')
if choice == '1':
print()
for i in range(len(t)):
for j in range(len(t[i])):
print(t[i][j], end = ' ')
print()
print('\n\n\n')
elif choice == '2':
print()
# Самое длинное предложение и самое короткое предложение
predl = []
k = 0
for i in range(len(t)):
for j in range(len(t[i])):
predl.append(t[i][j])
signs = ['.','!','?']
temp = 0
maxw = 0
minw = 100
num1 = 0
num2 = 0
for i in range(len(predl)):
temp += 1
if predl[i][-1:] in signs:
if maxw < temp:
maxw = temp
num1 = i
elif minw > temp:
minw = temp
num2 = i
temp = 0
prmin = []
prmax = []
for i in range(num1-maxw+1, num1+1):
prmax.append(predl[i])
for i in range(num2-minw+1, num2+1):
prmin.append(predl[i])
# print(prmin, '\n', prmax)
# Самое короткое слово самой длинной строки и самое длинное слово самой \
# короткой строки
mina = 100
maxa = 0
for i in range(len(prmin)):
if len(prmin[i]) > maxa:
maxa = len(prmin[i])
slvmax = prmin[i]
# print(slvmax)
for i in range(len(prmax)):
if len(prmax[i]) < mina:
mina = len(prmax[i])
slvmin = prmax[i]
# print(slvmin)
for i in range(len(t)):
for j in range(len(t[i])):
if t[i][j] == slvmax:
print(slvmin, end = ' ')
elif t[i][j] == slvmin:
print(slvmax, end = ' ')
else:
print(t[i][j], end = ' ')
print()
|
#1 print all integers from 0 to 150
for x in range (151):
print(x)
#2 Multiples of Five - Print all the multiples of 5 from 5 to 1,000
for m in range (5, 1001, 1):
if (m % 5 == 0):
print(m)
#3 Counting, the Dojo Way - Print integers 1 to 100. If divisible by 5, print "Coding" instead. If divisible by 10, print "Coding Dojo".
for d in range (1,101,1):
if (d % 10 == 0):
print("Coding Dojo")
elif (d % 5 == 0):
print("Coding")
#4 Whoa. That Sucker's Huge - Add odd integers from 0 to 500,000, and print the final sum.
total = 0
for s in range (500001):
if (s % 2 == 1):
total += s
print(total)
#5 Countdown by Fours - Print positive numbers starting at 2018, counting down by fours.
year = 2018
while year % 2 == 0:
print(year)
year -= 4
if year == -2:
break
#6 Flexible Counter - Set three variables: lowNum, highNum, mult. Starting at lowNum and going through highNum, print only the integers that are a multiple of mult. For example, if lowNum=2, highNum=9, and mult=3, the loop should print 3, 6, 9 (on successive lines)
lowNum = 2
highNum = 9
mult = 3
for x in range(lowNum,(highNum + 1),1):
if (x % mult == 0):
print(x)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.