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(ans
10000)/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

全部评论

相关推荐

首先讲三个故事,关于牛客的事件一:2024年,牛客上有一对高学历情侣,求职方向与我当时一致,都是嵌入式方向。他们恰好是我的朋友,专业能力和学历背景都很扎实,也因此拿到了不少优质offer。和很多求职者一样,他们把offer情况整理后发在平台上,本意是记录与交流,但很快引发了争议。有声音指责他们“集邮”“不释放名额”,认为这种展示本身就是一种炫耀。最终讨论失控,当事人删除内容,事件也很快被遗忘。事件二:小红书评论区,一条评价获得了不少共鸣:“感觉牛客就是当年那群做题区毕业了开始找工作还收不住那股味,颇有一种从年级第一掉到年纪第二后抱怨考不上大学的味道”,这条评论被水印里这个同学转发到牛客后,评论...
小型域名服务器:当看到别人比自己强的时候,即便这是对方应得的,很多人会也下意识的歪曲解构对方的意图,来消解自己在这本就不存在的比较中输掉的自信,从而平白制造出很多无谓的争论。比如你会在空余时间来写优质好文,而我回家只会暗区突围,那么我就可以作为键盘侠在这里评论你是不是XXXXXXXX。即便我自己都知道这是假的,但只要这没那么容易证伪,那么当你开始回应的时候,脏水就已经泼出去了,后面可能会有更多的人带着情绪来给我点赞,而毫不关注你写的文章内容本身是啥了。
SAGIMA牛马咖啡
点赞 评论 收藏
分享
程序员花海:实习和校招简历正确格式应该是教育背景+实习+项目经历+个人评价 其中项目经历注意要体现业务 实习经历里面的业务更是要自圆其说 简历模板尽可能保持干净整洁 不要太花哨的
秋招吐槽大会
点赞 评论 收藏
分享
求你们别卷了的大学生...:把学历放大放粗即可
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务