以三个整数作为输入。
N1=123
N2=456
N3=789
生成4位密码,即WXYZ。
哪里
W是所有输入数字的最大数字。
X是所有输入数字的第100位的最小值。
Y是所有输入数字的第10位的最小值。
Z是所有输入数字的第一位置的最小值。
示例:
N1=123
N2=456
N3=789
Password=WXYZ
1,2,3,4,5,6,7,8,9的W=maximum是9
X=最小值为1,4,7为1
2,5,8的Y=minimum是2
3,6,9的Z=minimum是3
由给定号码生成的4位密码是9123。
def add(x):
a = []
i = 2
while x > 0:
a[i] = x % 10
x /= 10
i -= 1
return a
def password(x1, x2, x3):
i = 0
p = 0
n = []
n.append(add(x1))
n.append(add(x2))
n.append(add(x3))
p = max(n) * 1000
m = []
for j in range(0, 9, 3):
m.append(n[j])
p += min(m) * 100
m = []
for j in range(1, 9, 3):
m.append(n[j])
p += min(m) * 10
m = []
for j in range(2, 9, 3):
m.append(n[j])
p += min(m)
return p
print("Enter three numbers: ")
n1 = int(input())
n2 = int(input())
n3 = int(input())
print("Generated password: ", password(n1, n2, n3))我最初用Java编写了这段代码,它运行得很好。我正在尝试用Python编写它,并得到了这个错误。我刚到毕森州,所以我不知道我做错了什么。请就如何纠正我的代码提出建议。
ai =x% 10
IndexError:超出范围的列表赋值索引p= max(n) * 1000
‘'list’和'int'的实例之间between >不支持‘
发布于 2022-02-06 23:47:14
def password(N1, N2, N3):
#takes all three Ns ^ and makes them single digits
N1 = [int(char) for char in str(N1)]
N2 = [int(char) for char in str(N2)]
N3 = [int(char) for char in str(N3)]
#it goes into each variable and finds the max and mins in each section
#W is just the biggest digit out of all of them
W = (N1 + N2 + N3)
W = max(W)
#X is the smallest digit from the first digits given in each N input
X = [N1[0], N2[0], N3[0]]
X = min(X)
#same thing as X just for the second digits this time
Y = [N1[1], N2[1], N3[1]]
Y = min(Y)
#same but for the third digits
Z = [N1[2], N2[2], N3[2]]
Z = min(Z)
#groups all the numbers together into a variable called "password"
password = [W, X, Y, Z]
#Done!
return password 发布于 2022-02-06 23:08:19
问题是,您不能在python中的列表索引处更改项的值,在该索引中,当前列表中没有项。这就是为什么
a[i] = x%10如果当前列表中没有I项,则无法工作。此外,add-函数中的while-循环永远不会结束,因为如果在python中除以整数,它将根据结果给出整数或浮点数。因此x/10永远不会是零或更小。
发布于 2022-02-07 00:11:27
您的功能可以实现如下:
def password(n1='123', n2='456', n3='789'):
w = max(map(int, n1 + n2 + n3))
x = min(map(int, n1[0] + n2[0] + n3[0]))
y = min(map(int, n1[1] + n2[1] + n3[1]))
z = min(map(int, n1[2] + n2[2] + n3[2]))
return f"{w}{x}{y}{z}"
print(password())退出:
9123https://stackoverflow.com/questions/71011900
复制相似问题