Find duplicates in an array using Python DSA [closed] - python

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
This post was edited and submitted for review 5 months ago and failed to reopen the post:
Original close reason(s) were not resolved
Improve this question
Can anyone help me out with this question. I did it in the right way but it is showing me an error. I dont know whats the issue.
Find duplicates in an array
Given an array a[] of size N which contains elements from 0 to N-1, you need to find all the elements occurring more than once in the given array.
Error while compiling
Here is my code
def duplicates(self, arr, n):
result = []
a = []
arr.sort()
for i in arr:
if i not in a:
a.append(i)
else:
if i not in result:
result.append(i)
if len(a) == n:
result.append(-1)
return result

I think the error the error is due to the worst time and space complexity. You have used the brute force method to program the code which is not the right way. Make your code more efficient for a good time and space complexity. Here is my code.
def duplicates(self, arr, n):
# Make an array of n size with a default value of 0
result = [0] * n
ans = []
#Update the index with value in an array
for i in range(n):
result[arr[i]] +=1
# Iterate through each element in an array to find the element which has a value of more than 1. return the I value and break.
for i in range(len(result)):
if result[i] >1:
ans.append(i)
if not ans:
ans.append(-1)
return ans

Related

basic question about python for loop and enumerate [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to build a function that will return the sum of the first item in the data list and every tenth item after, so I write the script below, however, the result is always the first data in my list. How should I modify my code and fix it?
def Sum10th(data):
sum=0
for i,d in enumerate(data):
if (i % 10 == 0): sum = sum+d
return sum
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(Sum10th(p))
The desired result should be 31, however the computer only returns the value of 1.
You can try
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
def Sum10th(data):
return sum([v for i, v in enumerate(p) if (i + 1) % 10 == 0 or i == 0])
print(Sum10th(p))
Output
31
By using the list comprehension with an if, at the end of it, you can get all the first item with the tenth item following it from a list.
Try this way:
def sum10thdata(data):
sum = 0
l = len(data)
for i in range(0,l,10):
sum+=data[i]
return sum

how exactly is the recursion working in this code [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have this code , and it is not mine , I saw it online and i am wondering how is the recursion working , can someone please explain !
(this function accepts a list of integers(distances) and a value 'r' lets say 10) and it returns all the possibilities of how we can reach 100 using the distances) lets say the list is [3,5,2,5] and the value r is 10 ! so to make 10 we need [5,5] or [3,2,5] ,this is the code:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for last_distance in d:
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions
i hope i made my self clear
I'd suggest using python print function
print("")
At multiple locations to actually see the recursion happening. You would get a better idea than someone trying to explain it to you.
Although the function itself is quite simple. For every element in distances, the function subtracts the element from the required r value and checks the value with the if conditions.
If r value is zero ie, the for some elements in distance, their sum is r, a multi list is returned, which furthermore has the said elements.
At the end, the complete list of elements whose sum adds to r are appended to solution list and returned.
Say that given a list distances0 of length n, you are able to return all tuples i1,..,infrom the list that sums to a number r for any number r.
You would like to do the same for a list distances of length n+1.
Since you know how to solve the problem for a list of size n, you will do the following: for every element last_distance of distances, return all tuples i1,...,in that sums to r-last_distance from a list distances0 which is similar to distances but without the element last_distance (and hence of length n).
I think there might be some mistakes in the code, here should be a working version:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for i in range(len(distances)):
d = distances[:i]+distances[i+1:]
last_distance = distances[i]
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions

Converting a C function to Python function [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 6 years ago.
Improve this question
this function searches the number of an element in an array and returns the number of the element in the array if it exists or returns -1 if the input number does not exist on the array
int iSearch (int st[],int len,int no)
{
int i;
for (i=1;i<=len;i++) //len=lenth of the array , no = the number that we want to search in the array , st[] = the array
if (st[i]==no)
return i;
return -1;
}
and i want to write the python version of this function but since i use lists instead of arrays in python, i dont know how to write it in python.
i wrote the code below in python but it doesn't work
def iSearch(list,lenth,no):
x=0
for x in range (lenth):
if (list(x) == no)
return i
else
return -1
Here's the loop equivalent:
def iSearch(lst,no):
for i,x in enumerate(lst):
if x == no:
return i
return -1
There is, however, function lst.index(no) which is doing what you need, but in a more efficient way:
def iSearch(lst,no):
if no in lst:
return lst.index(no)
return -1
Or with the try/except (probably the fastest):
def iSearch(lst,no):
try:
return lst.index(no)
except ValueError:
return -1
It would help if you included the error you got next time.
Your code has some issues: 1. "list" is the name of an already existing object 2. You're only checking if the first item is the desired object, because at that point, both branches return. 3. accessing an element of a list requires square brackets, not parentheses.
This appears to work:
def linear_search_c(l,length,num):
for x in range(0,length):
if (l[x] == num):
return x
return -1
As an aside, there are better list searching methods than linear search if the array is sorted: binary search

sumDivs could you help me with my code please [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Write a function called sumDivs that accepts a single, positive integer and calculates the
sum of all of its proper divisors. Use a for loop to find and sum the proper divisors of the
given integer.
For example,
>>> sumDivs(8)
7
this is what i have:
def sums(n):
i=0
for i in range (1, n-1):
if n % i == 0:
return n-1
i+=1
You shouldn't return the first divisor you find, you should be adding them as you go; i takes on the values from 1 to n-2 in your loop change to for i in range(1,n); and there is no need to define an initial value for i. Try this instead:
def sums(n):
sum=0
for i in range (1, n):
if n % i == 0:
sum+=i
return sum

Hackerrank Code not working [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
The problem is given here
I am coding in python and my code is given below:
num =raw_input()
li=list()
count=150*[0]
ans=0
while num>0:
li.append(raw_input())
num=int(num)-1
for i in range (0, len(li)):
for j in range(0, len(li[i])):
count.insert (ord(li[i][j]), count[ord(li[i][j])]+1)
for i in range(0, len(count)):
if count[i]==len(li):
ans=ans+1
print ans
On running the sample test case the output is 3 instead of 2.
Where am I going wrong?
There are several things wrong with your program.
First the insert method doesn't do what you seem to think it does.
list.insert(i, x)
Insert an item at a given position. The first argument is the index of the element before which to insert, so a.insert(0, x) inserts at the front of the list, and a.insert(len(a), x) is equivalent to a.append(x).
Second, you're attempting to count every time a letter appears at all, not just the first instance in a line.
This also looks like a low effort question, which is why you're getting downvoted. What have you tried?
Here's a solution that uses your method correctly, but it's still not a very pythonic approach. Have you considered using a dict to keep track of this information instead?
num = raw_input()
li = list()
count = 150*[0]
seen = 150*[False]
ans = 0
while num > 0:
li.append(raw_input())
num = int(num)-1
for i in range(0, len(li)):
for j in range(0, len(li[i])):
if (not seen[ord(li[i][j])]):
count[ord(li[i][j])] += 1
seen[ord(li[i][j])] = True
seen = 150*[False]
print count
for i in range(0, len(count)):
if count[i] == len(li):
ans = ans+1
print chr(i)
print ans
Here's the same approach using more pythonic language, isn't this much easier to understand?
num = raw_input()
lines = []
seen = set()
count = {}
while num > 0:
lines.append(raw_input())
num = int(num)-1
for line in lines:
for char in line:
if (char not in seen):
count[char] = count.get(char, 0) + 1
seen.add(char)
seen = set()
print count
print list(count.values()).count(len(lines))
There are, of course even better ways to do this.
The website states: Required Knowledge: Implementation, Sets: Time Complexity: O(n)
So using set.intersection would be a better way to go:
num = raw_input()
sets = [set(raw_input()) for x in range(int(num))] ]# make set from each line
print len(set.intersection(*sets)) # find letters that are common in all sets and print the length
You are counting c as a gem-element. It occurs 3 times, but not in 3 different lines. Thus count[i]==len(li) is not a sufficient criterion for a gem-element.

Categories

Resources