Проверка дубликатов в списке из пользовательского ввода - PullRequest
0 голосов
/ 01 июня 2018

Итак, я написал код, который генерирует случайный список со случайным количеством значений.Затем спрашивает пользователя, какой номер он ищет, и если его в списке, он скажет пользователю, в какой позиции в списке находится номер.

import random

a = [random.randint(1, 20) for i in range(random.randint(8, 30))]

a.sort()
print(a)


def askUser():

    n = input("What number are you looking for?")
    while not n.isdigit():
        n = input("What number are you looking for?")

    n = int(n)
    s = 0

    for numbers in a:
        if numbers == n:
            s += 1
            print("Number", n, "is located in the list and the position is:", (a.index(n)+1))
            # Something here to skip this index next time it goes through the loop
        else:
            pass
    if s == 0:
        print("Your number could not be found")


askUser()

Я хотел бы добавить что-то, что будетпропустите найденный индекс в первый раз, а затем найдите индекс дубликата, если он есть.

Текущий результат

[2, 4, 8, 9, 10, 10, 16, 19, 20, 20]
What number are you looking for?20
Number 20 is located in the list and the position is: 9
Number 20 is located in the list and the position is: 9

Желаемый результат

[2, 4, 8, 9, 10, 10, 16, 19, 20, 20]
What number are you looking for?20
Number 20 is located in the list and the position is: 9
Number 20 is located in the list and the position is: 10

Ответы [ 4 ]

0 голосов
/ 01 июня 2018

Если вам кажется, что вы можете преобразовать некоторые из ваших циклов в списки:

def askUser():

    n = input("What number are you looking for?")
    while not n.isdigit():
        n = input("What number are you looking for?")

    n = int(n)

    # get a list of all indexes that match the number
    foundAt = [p+1 for p,num in enumerate(a) if num == n]

    if foundAt:
        # print text by creating a list of texts to print and decompose them
        # printing with a seperator of linefeed
        print( *[f"Number {n} is located in the list and the position is: {q}" for 
                 q in foundAt], sep="\n")
    else: 
        print("Your number could not be found")

Редактировать: как указал Криц f"" строки формата поставляются с PEP-498 дляPython 3.6 (не знал: o /) - поэтому для более ранних версий 3.x Python должен был бы использовать

print( *["Number {} is located in the list and the position is: {}".format(n,q) for 
                 q in foundAt], sep="\n")
0 голосов
/ 01 июня 2018
num =20

numlist = [2, 4, 8, 9, 10, 10, 16, 19, 20, 20]

for each in numlist:
    if num is each:
        print num
        print [i for i, x in enumerate(numlist) if x == num]
0 голосов
/ 01 июня 2018

Вы можете упростить этот код, используя numpy для удаления ваших петель.

a = np.array([random.randint(1,20) for i in range(random.randint(8,30))])

Затем вы можете использовать np.where, чтобы определить, выбрал ли пользователь значение в вашем массиве a случайных значений:

idx_selections = np.where(a == n)[0]

Тогда вы можете определить, соответствует ли пользователь ответу или нет:

if len(idx_selections) == 0:
    print("Your number could not be found")
else:
    for i in idx_selections:
        print("Number", n, "is located in the list and the position is:", i)
0 голосов
/ 01 июня 2018

Измените эту строку:

for numbers in a:

Кому:

for i, numbers in enumerate(a):

А затем измените способ печати индексов:

print("Number", n, "is located in the list and the position is:", (i+1))

Пример вывода:

[1, 2, 2, 5, 5, 5, 6, 7, 8, 8, 8, 10, 10, 10, 10, 10, 11, 11, 16, 17, 17, 19, 19]
What number are you looking for? 8
Number 8 is located in the list and the position is: 9
Number 8 is located in the list and the position is: 10
Number 8 is located in the list and the position is: 11
...