Home > Enterprise >  reapeted numbers in a list on python
reapeted numbers in a list on python

Time:08-04

Write a program that receives as input n elements of a list, and as output, prints True if there is an element that appears more than once, and False otherwise. This is what I already did, but it don´t works and I don´t know why, it keeps showing "False" to all.

lst = []
n = input().split()
flag = False
for i in n:
    if n.count(i) > 1:
        flag = True
        break
    print(flag)

CodePudding user response:

You should do print after loop, not inside, that is

lst = []
n = input().split()
flag = False
for i in n:
    if n.count(i) > 1:
        flag = True
        break
print(flag)

CodePudding user response:

You can try this.Just checking if there is a space in it's string type.

EDIT: no need to create a loop for that indeed.you can use it like this.

lst = []
n = input().split()
flag = False

if " " in str(n):
    flag = True

print(flag)

CodePudding user response:

use hash / dictionary to get the frequency of each number, and once a number is found in dictionary then return False as we have encountered the duplicate element.

frequency = {}
n = list(map(int, input().split()))
flag = False
for i in n:
    if i not in frequency:
        frequency[i] =1
    else:
        flag = True
        break
print(flag)
  • Related