CIST1401-Computational Thinking with Python
两个单词包含完全相同的字母,但顺序不同
def are_anagrams(word1, word2):
if word1!=word2 and sum([ord(x) for x in word1]) == sum([ord(x) for x in word2]):
return True
else:
return False
最大公约数
def gcd(num1,num2):
temp=num1%num2
while(temp!=0):
num1=num2
num2=temp
temp=num1%num2
return num2
二进制字符串左移右移
def bitshift(s,k,b):
s=str(s)
if b==True:
return s[k:] + s[:k]
if b==False:
return s[-k:] + s[:-k]
sentence中word出现个数
def count_word(sentence, word):
return sentence.count(word)
列表截取【:】前闭后开
列表中数值相邻数值对交换
def list_swap(lst):
i=0
while i<len(lst)-1:
lst[i],lst[i+1]=lst[i+1],lst[i]
i=i+2
return lst
lst1姓名lst2年龄,按照年龄降序,相同年龄按照姓名升序
def list_sorting(lst1,lst2):
z = list(zip(lst1,lst2))
a=sorted(z, key=lambda x: (-x[1], x[0]))
x,y=list(unzip(z))
x=[] y=[] for i in a: x.append(i[0]) y.append(i[1]) return x,y
两矩阵相加
result = [[0 for i in X] for j in X[0]]
for i in range(len(X)):
for j in range(len(X[0])):
result[i][j] = X[i][j] + Y[i][j]
print(result)
两矩阵相乘
def matrix_multiply(matrix1,matrix2):
new_matrix = [[0 for i in range(len(matrix1))] for j in range(len(matrix1))]
for i in range(len(matrix1)):
for j in range(len(matrix1)):
for x in range(len(matrix1)):
new_matrix[i][j] += matrix1[i][x]*matrix2[x][j]
return new_matrix
matrix1 = [[1,2,3], [4,5,6], [7,8,9]]
matrix2 = [[2,2,2], [3,3,3], [4,4,4]]
new_matrix = matrix_multiply(matrix1, matrix2)
print(new_matrix) # [[20, 20, 20], [47, 47, 47], [74, 74, 74]]
字典
vege_set.union(edible_set)并
vege_set.intersection(edible_set)交
vege_set.difference(edible_set) vege_set-共有的
vege_set.symmetric_difference(edible_set)并-共有的
set1.issubset(set2) (set1 <= set2) set1.issuperset(set2) (set1 >= set2)
字典Counting words in a string
def word_counter(input_str):
input_str=input_str.lower()
input_str=input_str.split(" ")
for i in range(len(input_str)):
if input_str[i]=="":
input_str.remove(input_str[i])
dict={}
for key in input_str:
dict[key] = dict.get(key, 0) + 1
return dict
通过值找键
def find_key(input_dict, value):
a=[k for k,v in input_dict.items() if v == value]
if a==[]:
return None
else:
return a[0]
值在那些键里出现过
def make_index(words_on_page):
newdict = {}
for key, value in words_on_page.items():
for string in value:
newdict.setdefault(string, []).append(key)
return newdict
input_dict = {
1: ['hi', 'there', 'fred'],
2: ['there', 'we', 'go'],
3: ['fred', 'was', 'there']}
output_dict = make_index(input_dict)
for word in sorted(output_dict.keys()):
print(word + ': ' + str(output_dict[word]))
fred: [1, 3]
go: [2]
hi: [1]
there: [1, 2, 3]
was: [3]
we: [2]
txt文档中单词短语数量统计
def make_dictionary(filename):
file1 = open(filename, 'r', encoding='utf-8')
file = open('text.txt', 'w', encoding='utf-8')
for line in file1.readlines():
if line == '\n':
line = line.strip("\n")
file.write(line)
file = open('text.txt', 'r', encoding='utf-8')
filetxt=file.read()
filist=filetxt.split("\n")
dic={}
for i in range(len(filist)):
if filist[i] == '':
filist.remove(filist[i])
for word in filist:
dic[word]=dic.get(word, 0)+1
return dic
dog
triceratops
persian cat
dog
persian cat
large white fluffy thing
persian cat
{'dog': 2, 'persian cat': 3, 'triceratops': 1, 'large white fluffy thing': 1}
txt文档语句中单词数量统计
import re
def print_word_counts(filename):
input_file = open(filename, 'r')
source_string = input_file.read().lower()
input_file.close()
words = re.findall('[a-zA-Z]+', source_string)
counts={}
for word in words:
counts[word] = counts.get(word, 0) + 1
for key in sorted(counts.keys()):
print((key + ': ' + str(counts[key])))
CSV->字典
def isbn_dictionary(filename):
list = []
dict = {}
try:
infile = open(filename, "r")
for line in infile:
line = line.strip()
author, title, isbn = line.split(",")
list.append([author, title, isbn])
for i in list:
dict[i[2]] = tuple(i[0:2])
except:
dict=None
print('The file '+filename+' was not found.')
return dict
For example, if the input file were:
Kurt Vonnegut,Breakfast of Champions,0-586-08997-7
Lloyd Jones,Mister Pip,978-0-14-302089-9
Joe Bennett,So Help me Dog,1-877270-02-4
Orson Scott Card,Speaker for the Dead,0-812-55075-7
the output dictionary would be (in some arbitrary order)
{'0-586-08997-7': ('Kurt Vonnegut', 'Breakfast of Champions'),
'978-0-14-302089-9': ('Lloyd Jones', 'Mister Pip'),
'1-877270-02-4': ('Joe Bennett', 'So Help me Dog'),
'0-812-55075-7': ('Orson Scott Card', 'Speaker for the Dead')}
data = [5, 5, 5, 10, 10]print(run_length_encode(data)) [(5, 3), (10, 2)]
def run_length_encode(nums):
count_set = list(set(nums))
count_list = list()
count_set.sort(key = nums.index)
for item in count_set:
count_list.append((item,nums.count(item)))
return count_list
将整数N作为输入并返回第N个不能 被2整除的 复合数
def countDivisors(num):
return sum(num % i == 0 for i in range(1, num + 1))
def composite2(N):
list=[]
for num in range(N9):
if countDivisors(num)>2 and num%2!=0:
list.append(num)
return list[N-1]
近似于前几项,直到该项小于x为止
def series(x):
ans=0
n=0
while (1/2*n>=x):
ans=float(ans)+float(1/2*n)
n=n+1
return round(ans10000)/10000.0
print(singleDigit(48)) 3
print(singleDigit(198)) 9
def singleDigit(N):
while (N>=10):
N=sum([int(i) for i in list(str(N))])
return N