一、筆試技巧
提高通過率大原則:
1.本地IDE調代碼的速度更快
2.修改已>0%的代碼比新做一道題更快
3.一定要看清題意!!!
提高通過率的技巧:
1.時間複雜度問題:增加條件break或continue出循環,能break儘量break;
減少不必要的判斷條件(比如在不在字典中);
做一些排序來減少後期的工作量
2.空間複雜度問題:
3.邊界條件:某些數據是不是始終存在
測試用例通過但0%的原因:
1.沒有理解題意
輸入
第一行說明nmp這種數據量,最後一個參數一般爲第二行開始有幾行,且是字符型的數據輸入,可以按下面的方法進行輸入處理。
第一行:
a,b,c=[int(i) for i in input(0.solit()]
第二行:
info=[]
for i in range(c):
info.append([int(i) for i in input().split()])
不用input()的話也可以用sys.stdin.readline().strip()
輸出
一般逐行打印
for i in result:
print(i)
常用數據結構
list和dict比較好用,不能導入numpy庫
list:做整體的排序
dict:做局部的排序,要在單個條件下xxx
常用函數
list
min() max() sum() .index()
.remove(具體內容) .pop(索引號) del a[索引號]
.sort(key=lambda x: x[0])
.sort(key=lambda x:(-x[1],x[0],x[2]))#默認是升序,加個符號變降序,可做多級排序。
sorted()#不在本地做排序
元素 in list名稱
變量
float('inf')無窮大
字典
.keys()
.values()
.items()#返回的是元組
字符串
.strip() 去除首位空格
.strip().strip(‘-a’)去除首位空格和字符
S[:3]+S[5:] 拼接字符串,去除某個字符
.replace(‘a’,’b’) 替換字符
re.sub(‘a’,’b’,s) 替換字符
二、單行、多行輸入
python的讀取方法包括如下方法readline、readlines和read。
python
import sys
try:
while True:
line = sys.stdin.readline().strip()
if line == '':
break
lines = line.split()
print int(lines[0]) + int(lines[1])
except:
pass
python3
import sys
for line in sys.stdin:
a = line.split()
print(int(a[0]) + int(a[1]))
代碼多行讀取
import sys
lines = []
while True:
line = sys.stdin.readline().strip()
if line == "":
break
lines.append(line)
print(lines)
2. 單行輸入:注意要通過強制轉換,將字符串轉爲數字
import sys
line = sys.stdin.readline().strip()
print(line)
3.
Python中的Input()函數在輸入時,遇到回車符,那麼一次輸入就結束了。這不能滿足輸入多行文本並且行數也不確定的情形,當然輸入空行也是允許的。
方法1:利用異常處理機制實現
lines=[]
while True:
try:
lines.append(input())
except:
break
print(lines)
實際運行時,可以輸入多行,當輸入最後一行並回車後,按組合鍵ctrl+D,表示EOF,即End of File、文件尾的意思。此時,input()函數會遇到EOF的異常。Python的異常處理機制將捕獲到此異常,執行except部分的語句,此語句爲break,因此,立即跳出while循環。這正好滿足了我們的需要。
例如,輸入:
12 345 3.14159回車
I am a student.回車
Hello, world!回車
在集成開發環境中運行時,請按ctrl+D組合鍵結束多行輸入。如果在Windows命令行下用"python 源代碼文件名.py”方式運行時,請按ctrl+Z組合鍵結束多行輸入。
輸出結果如下:
['12 345 3.14159', 'I am a student.', 'Hello, world!']
方法二:利用標準輸入文件對象sys.stdin的readlines()函數實現
因爲鍵盤是標準輸入設備,計算機操作系統將鍵盤也是當做文件來對待的,其實計算機操作系統將包括鍵盤顯示器鼠標打印機等在內的各種外圍設備都當做文件來對待。Python中與鍵盤對應的文件對象是sys.stdin,因此可以利用sys.stdin.readlines()函數來實現讀取多行文本,一直到遇到文件尾即EOF爲止。
import sys
lines=sys.stdin.readlines()
print(lines)
輸入同上,
輸出如下:
['12 345 3.14159\n', 'I am a student.\n', 'Hello, world!\n']
可以看出,這種方式2與方式1的輸出結果有細微差別,每行末尾有'\n'字符(即回車符)。
————————————————
===============================================================================================
轉自:https://www.cnblogs.com/BigFishFly/p/6622784.html
python之sys.stdout、sys.stdin
轉自:http://www.cnblogs.com/turtle-fly/p/3280519.html
本文環境:Python 2.7
使用 print obj 而非 print(obj)
sys.stdin,sys.stdout,sys.stderr: stdin , stdout , 以及stderr 變量包含與標準I/O 流對應的流對象. 如果需要更好地控制輸出,而print 不能滿足你的要求, 它們就是你所需要的. 你也可以替換它們, 這時候你就可以重定向(script.py < file.txt>)輸出和輸入到其它設備( device ), 或者以非標準的方式處理它們
1.1 sys.stdout 與 print
當我們在 Python 中打印對象調用 print obj 時候,事實上是調用了 sys.stdout.write(obj+'\n')
print 將你需要的內容打印到了控制檯,然後追加了一個換行符
print 會調用 sys.stdout 的 write 方法
以下兩行在事實上等價:
sys.stdout.write('hello'+'\n')
print 'hello'
1.2sys.stdin 與 raw_input
當我們用 raw_input('Input promption: ') 時,事實上是先把提示信息輸出,然後捕獲輸入
以下兩組在事實上等價:
hi=raw_input('hello? ')
print 'hello? ', #comma to stay in the same line
hi=sys.stdin.readline()[:-1] # -1 to discard the '\n' in input stream
1.3從控制檯重定向到文件
原始的 sys.stdout 指向控制檯
如果把文件的對象的引用賦給 sys.stdout,那麼 print 調用的就是文件對象的 write 方法
f_handler=open('out.log', 'w')
sys.stdout=f_handler
print 'hello'
# this hello can't be viewed on concole
# this hello is in file out.log
記住,如果你還想在控制檯打印一些東西的話,最好先將原始的控制檯對象引用保存下來,向文件中打印之後再恢復 sys.stdout
__console__=sys.stdout
# redirection start #
...
# redirection end
sys.stdout=__console__
1.4同時重定向到控制檯和文件
如果我們希望打印的內容一方面輸出到控制檯,另一方面輸出到文件作爲日誌保存,那麼該怎麼辦?
將打印的內容保留在內存中,而不是一打印就將 buffer 釋放刷新,那麼放到一個字符串區域中會怎樣?
a=''
sys.stdout=a
print 'hello'
OK,上述代碼是無法正常運行的
Traceback (most recent call last): File
".\hello.py", line xx, in print 'hello'
AttributeError: 'str'
object has no attribute 'write'
錯誤很明顯,就是上面強調過的,在嘗試調用 sys.stdout.write() 的時候,發現沒有 write 方法
另外,這裏之所以提示 attribute error 而不是找不到函數等等,我猜想是因爲python 將對象/類的函數指針記錄作爲對象/類的一個屬性來對待,只是保留了函數的入口地址
既然這樣,那麼我們必須給重定向到的對象實現一個 write 方法:
import sys
class __redirection__:
def __init__(self):
self.buff=''
self.__console__=sys.stdout
def write(self, output_stream):
self.buff+=output_stream
def to_console(self):
sys.stdout=self.__console__
print self.buff
def to_file(self, file_path):
f=open(file_path,'w')
sys.stdout=f
print self.buff
f.close()
def flush(self):
self.buff=''
def reset(self):
sys.stdout=self.__console__
if __name__=="__main__":
# redirection
r_obj=__redirection__()
sys.stdout=r_obj
# get output stream
print 'hello'
print 'there'
# redirect to console
r_obj.to_console()
# redirect to file
r_obj.to_file('out.log')
# flush buffer
r_obj.flush()
# reset
r_obj.reset()
同樣的,sys.stderr, sys.stdin 也都可以被重定向到多個地址