In: Computer Science
Write a program named “hw2-extra.py” that will find duplicate numbers in an array.Here is a
sample run of the program. An example for an input is as follows. The program tells you “The
7
duplicate numbers: 2 3 7 1”.
Again, do not use built-in functions if there is any.
You can read
the input from the file named as “hw2-ExtraCredit.txt”
235231779 13 15 99 96 4 1
The duplicate numbers: 2 3 1 7
Answer : please up vote or comment for any query i will update the same . Thanks
Check output image and program image for indentation
Note :- it will treat first numbers as a single digit separate number as u treated in output
Program plan :
1. open file read one by one
2. treat numbers between two spaces as a single number
3. check in list for matching
4. if found also check in duplicate number to append or not append
5. display duplicate number
Program :
List=[] #store one by one character
Duplicate=[] #store duplicate number
space=0 #to store numbers between two space a single number
num="" #append numbers between two space
def Find(a,List,x): #find a number between list x= index number
of list to find
i=x+1 #start check +1 of current index to count current index as
match
while i<len(List):
if(int(a)==int(List[i])): #if found return 1
return 1
i+=1
return -1 #else return -1
with open("hw2-ExtraCredit.txt") as fileobj: #open file
for line in fileobj:
for ch in line: #read chracter by character in line
if(ch!=' ' and space==0):
List.append(ch) #only add numbers not space
elif(ch==' ' and space==0): #if space append numbers between
space
space=1
elif(ch!=' ' and space==1):
num+=ch
elif(ch==' ' and space==1):
List.append(num)
num=""
space=1
if(num!="" and num!=' '): #last element of file append if a
number
List.append(num)
i=0
while i<len(List): #print file data
print("File Data",int(List[i]))
i+=1
i=0
while i<len(List): #run a loop 0 to last element
if(Find(List[i],List,i)==1): #check for match in List
if(Find(List[i],Duplicate,-1)!=1): #also check in duplicate if
already appended
Duplicate.append(List[i])
i+=1
print("the Duplicate number is: ",Duplicate) #print list
Output Images :
Output