gpt4 book ai didi

python - 如何正确格式化Python代码结构?

转载 作者:行者123 更新时间:2023-12-01 08:37:17 24 4
gpt4 key购买 nike

我对 python 还是有点陌生​​,我正在尝试学习如何为现实世界的应用程序和面试正确格式化我的代码。

下面的代码将一个数字作为输入,然后返回列表中高于和低于给定数字的数字数量。我创建了一个类 solution 来存储执行所有处理逻辑的函数 placeOfNum

如果我想输出我的答案,如下所示,最好的做法是调用 Solution 类函数,如下所示,或者我应该将所有内容保留在类中以帮助提高可读性,还是应该我在类中创建另一个函数,例如 answer 并在该类中输出解决方案?

def placeOfNum(self, n, array):
aboveNum = 0
belowNum = 0
array = sorted(array)

for x in array:
if x < n:
belowNum += 1
if x > n:
aboveNum += 1
return (above, below)

numList = [1,5,21,2,1,10,232]
num = 21
x = Solution()

answer = x.placeOfNum(num, numList)
print("above:", answer[0], "below:", answer[1])

# returns "above:1, below:5"

最佳答案

def place_of_num(num, array):
above_num = 0
below_num = 0

for x in array:
if x < num:
below_num += 1
if x > num:
above_num += 1
return tuple((above_num, below_num))

num_list = sorted([1,5,21,2,1,10,232])
num = 21

answer = place_of_num(num, num_list)
print(f"above: {answer[0]} and below: {answer[1]}")

我会这样写。保持命名一致,例如对变量、函数使用蛇形命名法,对类名使用驼峰式命名法。保持代码简单易读

关于python - 如何正确格式化Python代码结构?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53656837/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com