简体   繁体   中英

manipulating lists in python

Take three integers as input.
N1=123
N2=456
N3=789
Generate 4 digit password ie WXYZ.
Where
W is maximum digit of all the input numbers
X is the minimum of 100th position of all input numbers
Y is the minimum of 10th position of all input numbers
Z is the minimum of 1st position of all input numbers
Example:
N1=123
N2=456
N3=789
Password=WXYZ
W=maximum of 1,2,3,4,5,6,7,8,9 is 9
X= minimum of 1,4,7 is 1
Y=minimum of 2,5,8 is 2
Z=minimum of 3,6,9 is 3
4 digit password generated from given numbers is 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))


The problem is, that you can't change a value of an item at an index of a list in python, where there currently is no item in the list at that index. That is why

a[i] = x%10
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 

Your function could be implemented as follows:

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())

Here's an approach that might be considered more "Pythonic".

def digits(x):
    return list(map(int,str(x)))

def password(*args):
    n = list(map(digits,args))
    first = max([max(lst) for lst in n])
    lasts = [min(col) for col in zip(*n)]
    return str(first)+''.join(map(str,lasts))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM