推荐 :在Python编程面试前需要学会的10个算法(附代码)

HackerRank:
https://www.hackerrank.com/interview/interview-preparation-kit
LeetCode?:
https://leetcode.com/explore/interview/card/top-interview-questions-easy/
CodingBat :
https://codingbat.com/python
GeeksForGeeks:
https://www.geeksforgeeks.org/python-programming-language/?ref=leftbar

字符串处理
# Given an integer, return the integer with reversed digits.# Note: The integer could be either positive or negative.def solution(x):string = str(x)if string[0] == '-':return int('-'+string[:0:-1])else:return int(string[::-1])print(solution(-231))print(solution(345))
这是一个预热算法,将帮助您练习切片技巧。实际上,唯一棘手的问题是确保您考虑整数为负数的情况。我已经看到此问题以许多不同的方式呈现,但这通常有更复杂的要求。
# For a given sentence, return the average word length.# Note: Remember to remove punctuation first.sentence1 = "Hi all, my name is Tom...I am originally from Australia."sentence2 = "I need to work very hard to learn more about algorithms in Python!"def solution(sentence):for p in "!?',;.":sentence = sentence.replace(p, '')words = sentence.split()return round(sum(len(word) for word in words)/len(words),2)print(solution(sentence1))print(solution(sentence2))
要求使用字符串来进行一些简单计算的算法非常常见,因此你需要对.replace()和.split()这些方法非常熟悉,这样才能帮助你删除不想要的字符并且创建单词长度容易计算和求和的单词表。
# Given two non-negative integers num1 and num2 represented as string, return the sum of num1 and num2.# You must not use any built-in BigInteger library or convert the inputs to integer directly.#Notes:#Both num1 and num2 contains only digits 0-9.#Both num1 and num2 does not contain any leading zero.num1 = '364'num2 = '1836'# Approach 1:def solution(num1,num2):eval(num1) + eval(num2)return str(eval(num1) + eval(num2))print(solution(num1,num2))#Approach2#Given a string of length one, the ord() function returns an integer representing the Unicode code point of the character#when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string.def solution(num1, num2):n1, n2 = 0, 0m1, m2 = 10**(len(num1)-1), 10**(len(num2)-1)for i in num1:n1 += (ord(i) - ord("0")) * m1m1 = m1//10for i in num2:n2 += (ord(i) - ord("0")) * m2m2 = m2//10return str(n1 + n2)print(solution(num1, num2))
# Given a string, find the first non-repeating character in it and return its index.# If it doesn't exist, return -1. # Note: all the input strings are already lowercase.#Approach 1def solution(s):frequency = {}for i in s:if i not in frequency:frequency[i] = 1else:frequency[i] +=1for i in range(len(s)):if frequency[s[i]] == 1:return ireturn -1print(solution('alphabet'))print(solution('barbados'))print(solution('crunchy'))print('###')#Approach 2import collectionsdef solution(s):# build hash map : character and how often it appearscount = collections.Counter(s) # <-- gives back a dictionary with words occurrence count#Counter({'l': 1, 'e': 3, 't': 1, 'c': 1, 'o': 1, 'd': 1})# find the indexfor idx, ch in enumerate(s):if count[ch] == 1:return idxreturn -1print(solution('alphabet'))print(solution('barbados'))print(solution('crunchy'))
# Given a non-empty string s, you may delete at most one character. Judge whether you can make it a palindrome.# The string will only contain lowercase characters a-z.s = 'radkar'def solution(s):for i in range(len(s)):t = s[:i] + s[i+1:]if t == t[::-1]: return Truereturn s == s[::-1]solution(s)
# Given an array of integers, determine whether the array is monotonic or not.A = [6, 5, 4, 4]B = [1,1,1,3,3,4,3,2,4,2]C = [1,1,2,3,7]def solution(nums):return (all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) orall(nums[i] >= nums[i + 1] for i in range(len(nums) - 1)))print(solution(A))print(solution(B))print(solution(C))
#Given an array nums, write a function to move all zeroes to the end of it while maintaining the relative order of#the non-zero elements.array1 = [0,1,0,3,12]array2 = [1,7,0,0,8,0,10,12,0,4]def solution(nums):for i in nums:if 0 in nums:nums.remove(0)nums.append(0)return numssolution(array1)solution(array2)
# Given an array containing None values fill in the None values with most recent# non None value in the arrayarray1 = [1,None,2,3,None,None,5,None]def solution(array):valid = 0res = []for i in nums:if i is not None:res.append(i)valid = ielse:res.append(valid)return ressolution(array1)
#Given two sentences, return an array that has the words that appear in one sentence and not#the other and an array with the words in common.sentence1 = 'We are really pleased to meet you in our city'sentence2 = 'The city was hit by a really heavy storm'def solution(sentence1, sentence2):set1 = set(sentence1.split())set2 = set(sentence2.split())return sorted(list(set1^set2)), sorted(list(set1&set2)) # ^ A.symmetric_difference(B), & A.intersection(B)print(solution(sentence1, sentence2))
# Given k numbers which are less than n, return the set of prime number among them# Note: The task is to write a program to print all Prime numbers in an Interval.# Definition: A prime number is a natural number greater than 1 that has no positive divisors other than 1 and itself.n = 35def solution(n):prime_nums = []for num in range(n):if num > 1: # all prime numbers are greater than 1for i in range(2, num):if (num % i) == 0: # if the modulus == 0 is means that the number can be divided by a number preceding itbreakelse:prime_nums.append(num)return prime_numssolution(n)
原文标题:
10 Algorithms To Solve Before your Python Coding Interview
原文链接:
https://towardsdatascience.com/10-algorithms-to-solve-before-your-python-coding-interview-feb74fb9bc27
译者简介:陈超,北京大学应用心理硕士在读。本科曾混迹于计算机专业,后又在心理学的道路上不懈求索。越来越发现数据分析和编程已然成为了两门必修的生存技能,因此在日常生活中尽一切努力更好地去接触和了解相关知识,但前路漫漫,我仍在路上。
END
转自:?数据派THU 公众号;
版权声明:本号内容部分来自互联网,转载请注明原文链接和作者,如有侵权或出处有误请和我们联系。
合作请加QQ:365242293??
数据分析(ID?:?ecshujufenxi?)互联网科技与数据圈自己的微信,也是WeMedia自媒体联盟成员之一,WeMedia联盟覆盖5000万人群。

关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/
关注网络尖刀微信公众号随时掌握互联网精彩
- 1 因地制宜发展新质生产力 7903943
- 2 中央经济工作会议在北京举行 7808439
- 3 一粒米盖住6个字 药品说明书该改了 7713342
- 4 乘冬而起 向雪而行 7617943
- 5 哈尔滨机场出租羽绒服 洗2次不再租 7521074
- 6 特朗普:被扣押油轮上的石油归美国了 7428788
- 7 网警:男子AI生成车展低俗视频被拘 7331495
- 8 联合国厕所不再提供擦手纸 7232340
- 9 华为重夺中国手机市场份额第一 7139860
- 10 卓越工程师培养有了新标准 7048221


![吃不胖娘新鲜出炉的照片来啦~!可别再说库存啦[允悲]#春天摄影大赛# ](https://imgs.knowsafe.com:8087/img/aideep/2022/3/21/7eb67f6c5af856eeff94ff761aa94554.jpg?w=250)
![胡66铁粉标咋这么容易掉啊[doge] ](https://imgs.knowsafe.com:8087/img/aideep/2022/3/23/9b91f936f4b6fbfd4dc1b5fcba1b7cdc.jpg?w=250)



数据分析
