推荐 :在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, 0
m1, m2 = 10**(len(num1)-1), 10**(len(num2)-1)
for i in num1:
n1 += (ord(i) - ord("0")) * m1
m1 = m1//10
for i in num2:
n2 += (ord(i) - ord("0")) * m2
m2 = m2//10
return 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 1
def solution(s):
frequency = {}
for i in s:
if i not in frequency:
frequency[i] = 1
else:
frequency[i] +=1
for i in range(len(s)):
if frequency[s[i]] == 1:
return i
return -1
print(solution('alphabet'))
print(solution('barbados'))
print(solution('crunchy'))
print('###')
#Approach 2
import collections
def solution(s):
# build hash map : character and how often it appears
count = 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 index
for idx, ch in enumerate(s):
if count[ch] == 1:
return idx
return -1
print(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 True
return 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)) or
all(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 nums
solution(array1)
solution(array2)
# Given an array containing None values fill in the None values with most recent
# non None value in the array
array1 = [1,None,2,3,None,None,5,None]
def solution(array):
valid = 0
res = []
for i in nums:
if i is not None:
res.append(i)
valid = i
else:
res.append(valid)
return res
solution(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 = 35
def solution(n):
prime_nums = []
for num in range(n):
if num > 1: # all prime numbers are greater than 1
for 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 it
break
else:
prime_nums.append(num)
return prime_nums
solution(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 奋力打开改革发展新天地 7931575
- 2 保时捷断臂求生 7980607
- 3 刘强东提前发年终奖 7887819
- 4 “冷资源”里的“热经济” 7795769
- 5 全球约有1.9亿妇女为内异症患者 7643697
- 6 国足原主帅李铁已上诉 7586952
- 7 俄3人零下24℃山中待3天奇迹生还 7417852
- 8 渔民捕到205斤野生石斑鱼引围观 7388257
- 9 喝水后有4种表现提示肾有问题 7251190
- 10 吉尼斯纪录 世界最大锅杀猪菜 7186378