Single number python

Single number

Problem Name: Single Number

Problem DescriptionGiven non-empty array integers (positive, negatives), every number in the array appears twice or more except for one or more numbers. Find that single number.

Problem Modification: The problem is the modified version of the leetcode 'Single Number'.

How does this code work? : We use the 'set()' built-in function of the python programming language. As the 'set()' only stores the unique numbers, we use that to find the single number from an array or list.

Python code for 'Single Number'

def Find_Single_number(array):
SET = set()
LIST = []
# checking array is there any duplicate number
for i in array:
if i not in SET:
SET.add(i)
else:
LIST.append(i)
single_num = []
# checking array for the unique number
for i in array:
if i not in LIST:
single_num.append(i)
return single_num


if __name__ == '__main__':
numbers=list(map(int, input("Enter the numbers: ").split()))
print("Numbers are: ", numbers)
result=Find_Single_number(numbers)
# if the 'result' length more than 1, then there are 'Numbers'
if len(result)>1:
print("Single Numbers are: ", result)
# else the 'result' has only one number
else:
print("Single number is: ", result)


Sample input:

Enter the numbers: 1 1 1 1 2 2 2 33 33 4 2 1 232 34 3 2 33 22 1 2 3 4

Sample Output:

Numbers are:  [1, 1, 1, 1, 2, 2, 2, 33, 33, 4, 2, 1, 232, 34, 3, 2, 33, 22, 1, 2, 3, 4]
Single Numbers are:  [232, 34, 22]

Post a Comment

Previous Post Next Post