python - 向用户询问优先级列表,然后根据该列表对列表进行排序

标签 python python-3.x

我正在开发一个小程序,其中有 4 个灯开关。仅当 4 个开关中的 3 个打开时,灯才会亮。我想问用户是否应该有优先级,如果是,应该是什么。假设 C 开关必须先打开,然后是 A,然后是 B。如果用户按顺序输入 1-s(1-打开,0-关闭),灯就会亮,否则灯就会亮。保持关闭状态。我有点卡住了,不知道该怎么办,也许我过度补偿了这个问题。谢谢。

def sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]


A = B = C = D = int()
arr = []

sorrend = input("What should be the switches order: ")
lista = sorrend.split()
print("Switches order: ")
print(lista)


while [A, B, C, D] != 0 or [A, B, C, D] != 1:
    A = int(input("A switch (1-on, 0-off): "))
    B = int(input("B switch  (1-on, 0-off): "))
    C = int(input("C switch  (1-on, 0-off): "))
    D = int(input("D switch  (1-on, 0-off): "))
    if 1 in (A, B, C, D) or 0 in (A, B, C, D):
        arr.append(A)
        arr.append(B)
        arr.append(C)
        arr.append(D)
        break
    else:
        print("The switch status could be 1 or 0.")

print(arr)

sort(arr)


print('sorted arr:')
for i in range(len(arr)):
    print(arr[i], end=" ")

最佳答案

from random import randrange

def value_sum(dic):
    if sum(dic.values()) > 2:
        print("The lamp is on!")
    else:
        print("The lamp is off!")

dic={"A": None, "B": None, "C": None, "D": None}
question = input("Do you want to specify the order of switches and their state? (yes/no) ")

if question == "no":
    for i in dic.keys():
        dic[i] = randrange(2)
        print("{} is {}-{}".format(i, dic[i],"on" if dic[i] == 1 else "off"))
    value_sum(dic)

if question == "yes":
    sorrend = input("What should be the switches(A B C D) order: ")
    lista = sorrend.split()
    for i in lista:
        if i not in ('A', 'B', 'C', 'D'):
            print("Not corect switches: A B C D are the options")
            exit()
    print("Switches order is: ")
    print(lista)
    for i in lista:
        a = int(input("{} switch (1-on, 0-off): ".format(i)))
        if a in range(0,2):
            dic[i] = a
        else:
            print("The switch {} status should be 1-on or 0-off.".format(i))
            exit()
    value_sum(dic)

else:
    exit()

这是我的解决方案。如果用户用来指定开关状态,则它会从他那里获取输入。如果不是,它将选择一些随机值。如果 3 或 4 个开关打开 (1),则会显示灯亮起的消息。如果需要,您可以使用它并添加一些新功能。

关于python - 向用户询问优先级列表,然后根据该列表对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58895066/

相关文章:

python - 同时在 Pandas 数据框中进行多个操作

python - 如何将列表中的行插入到QSqlTableModel中?

python - Python 中向后兼容的输入调用

python - 如何使用stepic.encode()

Python 邻居都指向相同的值

php - 为什么散列(不使用盐)随机数?

python - 整数除以负数

python - Openpyxl 中的列宽(某些列)在超过 60 列后变为零

python - 无需 try/catch 即可安全访问 Python 中的对象

python - if else 在 for 循环下工作 != but ==