关于数据科学的3个Python编码面试问题 您所在的位置:网站首页 第三季超女短发的有谁啊 关于数据科学的3个Python编码面试问题

关于数据科学的3个Python编码面试问题

2023-04-03 03:45| 来源: 网络整理| 查看: 265

关于数据科学的3个Python编码面试问题

在今天的文章中,我将重点介绍数据科学中的Python技能。没有Python的数据科学家就像没有笔的作家。或者一台打字机。或者一台笔记本电脑。好吧,这样如何:没有Python的数据科学家就像我没有幽默的尝试。

你可以懂Python,但不是数据科学家。但是反过来呢?如果你认识不使用Python也能在数据科学领域成功的人,请告诉我。在过去的20年里。

为了帮助你练习Python和面试技巧,CPDA数据分析师经常会在课程中,模拟选择三个Python编码面试问题。其中两个来自StrataScratch,这类问题需要使用Python来解决特定的业务问题。第三个问题来自LeetCode,测试你对Python算法的熟练程度。

Python编程面试问题1:Python中的数学

看看谷歌的问题。

你的任务是使用这两种方法根据GPS数据计算平均距离。一个是考虑到地球的曲率,另一个是没有考虑到它。

这个问题给出了两种方法的公式。正如你所看到的,这个python编程面试问题有很多数学问题。您不仅需要理解这一层次的数学,还需要知道如何将其转换为Python代码。

没那么简单,对吧?

你应该做的第一件事是认识到有一个数学Python模块可以让你访问数学函数。在这个问题中你会经常用到这个模块。

让我们从导入必要的库和正弦、余弦、反余弦和弧度函数开始。下一步是在用户ID、会话ID和会话日期上将可用的DataFrame与其本身合并。另外,为id添加后缀,以便区分它们。

import numpy as np

import pandas as pd

from math import cos, sin, acos, radians

df = pd.merge(

google_fit_location,

google_fit_location,

how="left",

on=["user_id", "session_id", "day"],

suffixes=["_1", "_2"],

)

Then find the difference between the two step IDs.

df['step_var'] = df['step_id_2'] - df['step_id_1']

The previous step was necessary so we can exclude all the sessions that have only one step ID in the next step. That’s what the questions tell us to do. Here’s how to do it.

df = df.loc[

df[df["step_var"] > 0]

.groupby(["user_id", "session_id", "day"])["step_var"]

.idxmax()

]

Use the pandas idxmax() function to access the sessions with the biggest difference between the steps.

After we prepared the dataset, now comes the mathematics part. Create a pandas Series and then the for loop. Use the iterrows() method to calculate the distance for each row, i.e., session. This is a distance that takes the Earth's curvature into account, and the code reflects the formula given in the question.

df["distance_curvature"] = pd.Series()

for i, r in df.iterrows():

df.loc[i, "distance_curvature"] = (

acos(

sin(radians(r["latitude_1"])) * sin(radians(r["latitude_2"]))

+ cos(radians(r["latitude_1"]))

* cos(radians(r["latitude_2"]))

* cos(radians(r["longitude_1"] - r["longitude_2"]))

)

* 6371

)

Now, do the same thing but considering the Earth is flat. This is the only occasion being a flat-Earther is beneficial.

df["distance_flat"] = pd.Series()

for i, r in df.iterrows():

df.loc[i, "distance_flat"] = (

np.sqrt(

(r["latitude_2"] - r["latitude_1"]) ** 2

+ (r["longitude_2"] - r["longitude_1"]) ** 2

)

* 111

)

将结果转换为DataFrame并开始计算输出指标。第一个是与地球曲率的平均距离。同样的计算没有曲率。最后一个度量是两者之间的差值。

result = pd.DataFrame()

result["avg_distance_curvature"] = pd.Series(df["distance_curvature"].mean())

result["avg_distance_flat"] = pd.Series(df["distance_flat"].mean())

result["distance_diff"] = result["avg_distance_curvature"] - result["avg_distance_flat"]

result

完整的代码及其结果如下所示。

import numpy as np

import pandas as pd

from math import cos, sin, acos, radians

df = pd.merge(

google_fit_location,

google_fit_location,

how="left",

on=["user_id", "session_id", "day"],

suffixes=["_1", "_2"],

)

df["step_var"] = df["step_id_2"] - df["step_id_1"]

df = df.loc[

df[df["step_var"] > 0]

.groupby(["user_id", "session_id", "day"])["step_var"]

.idxmax()

]

df["distance_curvature"] = pd.Series()

for i, r in df.iterrows():

df.loc[i, "distance_curvature"] = (

acos(

sin(radians(r["latitude_1"])) * sin(radians(r["latitude_2"]))

+ cos(radians(r["latitude_1"]))

* cos(radians(r["latitude_2"]))

* cos(radians(r["longitude_1"] - r["longitude_2"]))

)

* 6371

)

df["distance_flat"] = pd.Series()

for i, r in df.iterrows():

df.loc[i, "distance_flat"] = (

np.sqrt(

(r["latitude_2"] - r["latitude_1"]) ** 2

+ (r["longitude_2"] - r["longitude_1"]) ** 2

)

* 111

)

result = pd.DataFrame()

result["avg_distance_curvature"] = pd.Series(df["distance_curvature"].mean())

result["avg_distance_flat"] = pd.Series(df["distance_flat"].mean())

result["distance_diff"] = result["avg_distance_curvature"] - result["avg_distance_flat"]

result

avg_distance_curvatureavg_distance_flatdistance_diff0.0770.088-0.01

Python编程面试问题2:Python中的图论

这是来自StrataScratch的一个非常有趣的Python编程面试问题。它将您置于现实生活中数据科学家非常常见但复杂的情况中。

达美航空提出的问题。让我们来看看。

这个问题要求你找到最便宜的最多两站的联程航班。这听起来很熟悉,不是吗?是的,这是一个修正过的最短路径问题:不是路径,而是代价。

我将向您展示的解决方案广泛使用merge() pandas函数。我还将使用itertools进行循环。导入所有必要的库和模块之后,第一步是生成所有可能的源和目标组合。

import pandas as pd

import itertools

df = pd.DataFrame(

list(

itertools.product(

da_flights["origin"].unique(), da_flights["destination"].unique()

)

),

columns=["origin", "destination"],

)

现在,只显示原点与终点不同的组合。

df = df[df['origin'] != df['destination']]

现在让我们合并da_flights与其本身。我将使用merge()函数,这些表将从目标和源的左侧连接起来。这样,你就得到了所有到第一个目的地的直飞航班,然后是与第一个航班目的地相同的中转航班。

connections_1 = pd.merge(

da_flights,

da_flights,

how="left",

left_on="destination",

right_on="origin",

suffixes=["_0", "_1"],

)

然后我们将这个结果与da_flights合并。这样我们就能赶上第三次航班了。这等于两站,这是问题允许的最大值。

connections_2 = pd.merge(

connections_1,

da_flights[["origin", "destination", "cost"]],

how="left",

left_on="destination_1",

right_on="origin",

suffixes=["", "_2"],

).fillna(0)

现在让我们通过分配逻辑列名来整理合并结果,并计算一个站点和两个站点的飞行成本。(我们已经有直飞航班的费用了!)很容易!一站式飞行的总费用是第一次飞行加上第二次飞行。对于两站飞行,它是所有三次飞行费用的总和。

connections_2.columns = [

"id_0",

"origin_0",

"destination_0",

"cost_0",

"id_1",

"origin_1",

"destination_1",

"cost_1",

"origin_2",

"destination_2",

"cost_2",

]

connections_2["cost_v1"] = connections_2["cost_0"] + connections_2["cost_1"]

connections_2["cost_v2"] = (

connections_2["cost_0"] + connections_2["cost_1"] + connections_2["cost_2"]

)

现在我将合并我创建的DataFrame与给定的DataFrame。这样,我将分配每个直飞航班的成本。

result = pd.merge(

df,

da_flights[["origin", "destination", "cost"]],

how="left",

on=["origin", "destination"],

)

接下来,将上述结果与connections_2合并,以获得到需要一站的目的地的航班费用。

result = pd.merge(

result,

connections_2[["origin_0", "destination_1", "cost_v1"]],

how="left",

left_on=["origin", "destination"],

right_on=["origin_0", "destination_1"],

)

对两站航班做同样的处理。

result = pd.merge(

result,

connections_2[["origin_0", "destination_2", "cost_v2"]],

how="left",

left_on=["origin", "destination"],

right_on=["origin_0", "destination_2"],

)

这样做的结果是一个表格,提供了从一个出发地到目的地的直飞、一站式和两站航班的费用。现在您只需要使用min()方法找到最低成本,删除NA值并显示输出。

result["min_price"] = result[["cost", "cost_v1", "cost_v2"]].min(axis=1)

result[~result["min_price"].isna()][["origin", "destination", "min_price"]]

使用这些最后的代码行,完整的解决方案如下所示。

import pandas as pd

import itertools

df = pd.DataFrame(

list(

itertools.product(

da_flights["origin"].unique(), da_flights["destination"].unique()

)

),

columns=["origin", "destination"],

)

df = df[df["origin"] != df["destination"]]

connections_1 = pd.merge(

da_flights,

da_flights,

how="left",

left_on="destination",

right_on="origin",

suffixes=["_0", "_1"],

)

connections_2 = pd.merge(

connections_1,

da_flights[["origin", "destination", "cost"]],

how="left",

left_on="destination_1",

right_on="origin",

suffixes=["", "_2"],

).fillna(0)

connections_2.columns = [

"id_0",

"origin_0",

"destination_0",

"cost_0",

"id_1",

"origin_1",

"destination_1",

"cost_1",

"origin_2",

"destination_2",

"cost_2",

]

connections_2["cost_v1"] = connections_2["cost_0"] + connections_2["cost_1"]

connections_2["cost_v2"] = (

connections_2["cost_0"] + connections_2["cost_1"] + connections_2["cost_2"]

)

result = pd.merge(

df,

da_flights[["origin", "destination", "cost"]],

how="left",

on=["origin", "destination"],

)

result = pd.merge(

result,

connections_2[["origin_0", "destination_1", "cost_v1"]],

how="left",

left_on=["origin", "destination"],

right_on=["origin_0", "destination_1"],

)

result = pd.merge(

result,

connections_2[["origin_0", "destination_2", "cost_v2"]],

how="left",

left_on=["origin", "destination"],

right_on=["origin_0", "destination_2"],

)

result["min_price"] = result[["cost", "cost_v1", "cost_v2"]].min(axis=1)

result[~result["min_price"].isna()][["origin", "destination", "min_price"]]

下面是代码输出。

origindestinationmin_priceSFOJFK400SFODFW200SFOMCO300SFOLHR1400DFWJFK200DFWMCO100DFWLHR1200JFKLHR1000

Python编程面试问题3:Python中的二叉树

除了图形,作为数据科学家,您还将使用二叉树。这就是为什么如果你知道如何解决DoorDash、Facebook、微软、亚马逊、彭博、苹果和TikTok等公司提出的Python编程面试问题,它会很有用。

约束条件是:

class Solution:

def maxPathSum(self, root: Optional[TreeNode]) -> int:

max_path = -float("inf")

def gain_from_subtree(node: Optional[TreeNode]) -> int:

nonlocal max_path

if not node:

return 0

gain_from_left = max(gain_from_subtree(node.left), 0)

gain_from_right = max(gain_from_subtree(node.right), 0)

max_path = max(max_path, gain_from_left + gain_from_right + node.val)

return max(gain_from_left + node.val, gain_from_right + node.val)

gain_from_subtree(root)

return max_path

解决方案的第一步是定义一个maxPathSum函数。要确定从根到左节点或右节点是否有一条路径,请编写递归函数gain_from_subtree。

第一个实例是子树的根。如果路径等于根(没有子节点),那么子树的增益为0。然后在左右节点上进行递归。如果路径和是负的,问题要求不考虑它;我们把它设为0。

然后将子树的增益和与当前最大路径进行比较,并在必要时更新它。

最后,返回子树的路径和,它是根加上左节点和根加上右节点的最大值。

这些是情况1和2的输出。



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

    专题文章
      CopyRight 2018-2019 实验室设备网 版权所有