gpt4 book ai didi

Python初学者--如何清理这一段代码

转载 作者:太空宇宙 更新时间:2023-11-04 06:04:21 25 4
gpt4 key购买 nike

<分区>

这是我从头开始构建的第一个 python 脚本的一部分。完整的代码旨在将许多珠子用于珠饰项目,并评估某些设计模式是否有效。代码是功能性的,我已经通过 pylint 运行它直到我的分数超过 9.5,但我被告知函数“number_selection”有太多分支,我正在寻求帮助来清理它。我知道必须有一种简单的方法来使这段代码更简洁并摆脱我所有的 if 语句,但我不知所措。

顺便说一下,“beads”是一个从 raw_input 提供的全局变量

任何建议表示赞赏。感谢您的帮助。

def number_suggestion():
''' if number entered does not work, then find the closest
usable numbers, figure out which number provides the greatest
number of design options and suggest that number.
'''
next_lower = beads
next_higher = beads
list1 = []
list2 = []
add_one = 1

# find next usable next_lower bead number
while next_lower >= 12 and next_lower % 6 != 0 and \
next_lower % 9 != 0 and next_lower % 12 != 0:
next_lower -= 1
# find next usable next_higher bead number
while next_higher >= 12 and next_higher % 6 != 0 and \
next_higher % 9 != 0 and next_higher % 12 != 0:
next_higher += 1

# add elements to list while counting to next usable number
if next_lower >= 12 and next_lower % 6 == 0:
list1.append(add_one)
if next_lower > 12 and next_lower % 9 == 0:
list1.append(add_one)
if next_lower > 12 and next_lower % 12 == 0:
list1.append(add_one)
if next_higher >= 12 and next_higher % 6 == 0:
list2.append(add_one)
if next_higher > 12 and next_higher % 9 == 0:
list2.append(add_one)
if next_higher > 12 and next_higher % 12 == 0:
list2.append(add_one)

# make a suggestion, but not if the number works
# in that case, return True
if beads >= 12 and beads % 6 == 0:
return
if beads >= 12 and beads % 12 == 0:
return
if beads >= 12 and beads % 9 == 0:
return

# if number is less than 12, print error message
if beads < 12:
print('Please use 12 or more beads in your design.')
return

# if number doesn't work, suggest better options
if len(list1) == len(list2):
print('\nThere was an error.')
print('Try either ' + str(next_lower) + ' or ' \
+ str(next_higher) + ' beads')
elif len(list1) > len(list2):
print('\nThere was an error.')
print('Try ' + str(next_lower) + ' beads instead.')
else:
print('\nThere was an error.')
print('Try ' + str(next_higher) + ' beads instead.')

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