看知乎上說要變得better一天得寫個8小時代碼吧。。。c也好Python也好。。。但是我太蒻了
12/25 更新 真的掛了!!!!!
一、素數相關
1.輸出1-n的所有素數(輸出1-n素數有幾個,加一個計數器num)
2.判斷數字i是否爲素數,可以定義一個函數 isprime(i),直接繼承第一題……
開一個列表,看i是否在素數列表裏(當然也可以直接判斷的)
3.輸出小於n的最大素數
for n in range(99,2,-2):
for i in range(3,int(n**0.5)+1):
if n%i==0:
break
else:
print(n)
break
二、字符串處理
真是與c一脈相承
但是比c簡單
#複習了這些
stri="Python"
stri.lower()
stri.upper()
str0.split(",")
str0.count(sub)#sub爲子串,輸出有多少個子串
str0.replace(old,new)
str0.strip("p") #從str0中去掉在其左側和右側中列出的字符
str0.join()
",".join("12345") #輸出 1,2,3,4,5 注意不要顛倒
字符串類型格式化
"{.2f}".format("1.2345")
"{0:=^20}".format("python")
C語言帶來的習慣:用ascii碼判斷字符 python中也可行
65<=ord(i)<=97
字符轉爲ascii碼 ord()
ascii碼轉爲字符 chr()
事實上可用 str.isalpha() 如果字符串至少有一個字符並且所有字符都是字母則返回 True,否則返回 False
eval() 函數用來執行一個字符串表達式,並返回表達式的值。
如何判斷字符大小寫?
str.isupper()
str.islower()
str.isdigit()
Python isdigit() 方法檢測字符串是否只由數字組成。
去除重複字符的好方法:利用集合的性質
集合:set()
例題:描述
將給定字符串去掉重複的字符後,按照字符ASCII碼順序從小到大排序後輸出。忽略原字符串中的空格。
輸入格式:
輸入是一個以回車結束的非空字符串(少於80個字符)。
輸出格式:
輸出去重排序後的結果字符串。
示例 1
輸入:ad2f3adjfeainzzzv
輸出:23adefijnvz
string=input()
list1=list(set(string.replace(" ",'')))
list1.sort()
print("".join(list1))
分析:set()用於去重
.replace()用於忽略空格
.sort() 用於列表中元素的排序
.join()用於講列表轉化爲字符串
join()函數
語法: ‘sep’.join(seq)
參數說明 sep:分隔符。可以爲空 seq:要連接的元素序列、字符串、元組、字典
三、斐波那契數列相關問題
1.問第n個元素是什麼
斐波那契第n個數的話 只要遞歸就行了
2.問小於n的數列元素
寫一個函數名爲Fibonacci,帶一個參數n,函數打印斐波那契數列中所有小於n的值。函數沒有返回值。
def Fibonacci(n):
"""accept an integer n.
return the numbers less than n in Fibonacci sequence."""
list1=[0,1]
num=0
index=0
while num<int(n):
num=list1[index]+list1[index+1]
if num<int(n):
list1.append(num)
index+=1
for i in list1:
print(i,end=' ')
n=input()
Fibonacci(n)
思路:把小於n的元素都放進列表
然後再將列表元素輸出(循環輸出)
思考:剛剛講了 .join 那我們這裏能否用這個呢???
結果:TypeError: sequence item 0: expected str instance, int found 報錯why? 列表中含有int類整數,如果列表中都是字符串形式的元素,則可用join() ,含數字需要先轉化爲字符串
小例子: a = [‘1’,‘2’,‘3’,1] print(’ ‘.join(a))
以爲會打印 1 2 3 1 結果報了錯
解決辦法:
print(" ".join(’%s’ %id for id in list1))
四、統計單詞出現次數
這是一道給了答案的經典題,考點:字典
- 輸入輸出示例
此程序輸出爲一個字典,字典的鍵是字符串中每個單詞,值是單詞的個數。
所有單詞一律按照小寫對待,去除字符串中的標點符號。
myString = "This is the string whose words we would like to count. " \
"This string contains some repeated words, " \
"as well as some unique words. " \
"It contains punctuation, " \
"and it contains words that are capitalized in different ways. " \
"If the method we write runs correctly, " \
"it will count 4 instances of the word 'it', " \
"3 instances of the word 'this', " \
"and 3 instances of the word 'count'."
# we remove punctuations .,'?!
myString = myString.replace('.' ,'')
myString = myString.replace('?', '')
myString = myString.replace(',', '')
myString = myString.replace('\'', '')
# split it by spaces so that we have a list
# of words
myString = myString.lower()
list1 = myString.split(' ')
#Create empty dictionary
wordDictionary = {}
for i in list1:
if i < 'a':
continue
if i not in wordDictionary:
wordDictionary[i] = 1
else:
wordDictionary[i] += 1
key = input()
print(wordDictionary[key])
五、子串問題
如果要知道某子串在一個字符串中的數量 可用str.count()方法,這在剛剛已經提到
如果要知道位置呢?可以用find方法
描述
Python find() 方法檢測字符串中是否包含子字符串 str ,如果指定 beg(開始) 和 end(結束)
範圍
則檢查是否包含在指定範圍內,如果包含子字符串返回開始的索引值,否則返回-1。語法
find()方法語法:
str.find(str, beg=0, end=len(string)) 參數 str – 指定檢索的字符串 beg –
開始索引,默認爲0。 end – 結束索引,默認爲字符串的長度。 返回值 如果包含子字符串返回開始的索引值,否則返回-1。
與s.index()區分:index() 方法從字符串中找出某個子字符串第一個匹配項的索引位置,該方法與 find() 方法一樣,只不過如果子字符串不在字符串中會報一個異常。
缺陷是什麼呢 如果你直接 str原串.find(str子串) 只能返回第一個子串的位置
所以就有以下題目:
打印出子字符串的所有位置
描述
編寫一個函數,接收2個字符串myString和findString爲參數,利用字符串的find()方法,將myString中所有出現findString的位置打印在一行中,每個位置之間用空格隔開。
提示:
輸入使用一行,輸入的2個字符串用 , 分割。
示例 1
ABCDEABCDE,CD
2 7
方法1:(我的老方法)不用find
此方法要注意:防止下標越界
def print_indices(myString,findString):
a=len(myString)
b=len(findString)
str1=""
i=0
for i in range(0,a-b):
if myString[i:i+b]==findString:
str1=str1+str(i)+" "
return str1
myString,findString = input().split(",")
print(print_indices(myString,findString))
方法2:利用find 但是要分段利用
(老師寫的)
def print_indices(mystring,fingstring):
location=mystring.find(findstring)
while location>=0:
print(location,end=' ')
location=mystring.find(findstring,location+1)
記得location要+1!!!!!!
六、文件問題
萬萬沒想到BIT 的期末會考文件。。。。還好我瞟了一眼!!!
文件關鍵行數
描述
關鍵行指一個文件中包含的不重複行。關鍵行數指一個文件中包含的不重複行的數量。
統計附件文件中與關鍵行的數量。
輸入輸出示例
此處僅示例輸出格式。
示例 1
共99關鍵行
附件
附件 1: latex.log
with open('latex.log', 'r', encoding='utf-8') as f:
rows = set()
s = 0
for line in f:
if line not in rows:
rows.add(line)
s += 1
print('共{}關鍵行'.format(s))
# 最簡潔的答案
with open('latex.log', 'r', encoding='utf-8') as f:
rows_set = set(f.readlines())
print('共{}關鍵行'.format(len(rows_set)))
分析:此處用到的是集合的去重功能
add() 方法用於給集合添加元素,如果添加的元素在集合中已存在,則不執行任何操作。
add()方法語法:
set.add(elmnt)