Converting a C function to Python function [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 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

Related

Find duplicates in an array using Python DSA [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 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

int is not an interable? [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 2 years ago.
Improve this question
trying to make an average function myself as requested by a book I'm using to learn python. This is what I have and I need it to basically have a requirement of at least 1 argument to avoid division by zero, but to accept any amount of other arguments. But I keep getting this error. Here's my code. Any help is appreciated!
1 def average(x, *args):
----> 2 return sum(x, *args) / len(x, *args)
3
TypeError: 'int' object is not iterable
sum() and len() only take in iterables, which are objects that python can iterate through, like strings, lists, sets, etc.
You need to close the integers with brackets, so it would be a list, and then, you can put the iterable into sum() and len().
def average(x, *args):
return sum([x, *args]) / len([x, *args])
print(average(1, 4, 2, 6))
Output:
3.25
Neither sum nor len take an arbitrary number of arguments. If you want average to do so, you need to pass them all as a single iterable to sum and as a single object (that supports the length protocol) to len.
def average(x, *args):
all_nums = [x]
all_nums.extend(args)
return sum(all_nums)/len(all_nums)
(I suppose all_nums = [x, *args] would work as well; I spend too much time in Python 2 for that to feel natural yet.)
If you wanted average to be more like sum and take an arbitrary iterable, it would be easier to compute the sum and length in parallel, rather than use sum directly (since len does not work with arbitrary iterables)
def average(nums):
length = 0
total = 0
for x in nums:
length += 1
total += x
return total/length

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

Python reverse 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 9 years ago.
Improve this question
Write the definition of a function, is_reverse , whose two parameters are arrays of integers of equal size. The function returns true if and only if one array is the reverse of the other. ("Reverse" here means same elements but in reverse order.)
This is what I have so far:
def is_reverse(a,b):
c = b.reverse()
for i in len(a):
if a[i] == c[i]:
return True
if a[i] != c[i]:
return False
It can be written on one line with
def is_reverse(a, b): return a == b[::-1]
Your code unconditionally exits after the first time in the loop (either the characters are the same, or they're different and you have a return statement for both cases). You only want to return True after you've checked all the string elements.
There's also another slight catch -- list.reverse() reverses the list in place. This means that c = b.reverse() changes b and sets c to None. I've modified that in my code below.
def is_reverse(a,b):
# copy b -- Not strictly necessary if you don't care about changing the inputs...
c = b[:]
c.reverse()
for i in range(len(a)):
if a[i] != c[i]:
return False
return True
Others have pointed out that there are more idiomatic ways to go about doing this:
a == b[::-1]
is the classic example (it does the loop for you!). But I left the structure of the original code as much intact as I could to hopefully make it more clear how python works.
If you want to avoid making a copy of either list:
len(a) == len(b) and all(itertools.imap(operator.eq, a, reversed(b)))
If you're using Python3 then there's no itertools.imap, because the builtin map no longer copies.

Producing a list of squares from 1 to n [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Write a function called squares that takes in a parameter named n. If n is a positive integer, the function returns a list consisting of the squares of the numbers from 1 through n. Otherwise (i.e., if n is not a positive integer) the function should return an empty list.
This function to work correctly even if the function is called with nonsensical arguments. In other words, function calls such as squares('Iowa'), squares(range(10)), and squares([1, 2, 3]) should return an empty list.
def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans+=1
if ans *ans == x:return ans;
return -1;
def square(n):
i=0
blist= []
ans = list(range(1, n ))
if (n < 0):
return blist
if isinstance(ans, str):
return blist
while( i < len(ans)):
if(sqrt(ans[i])!= -1):
blist.append(ans[i])
i = i+1
return blist
i = square('boy')
print(i)
To define a function, you do
def squares(n): # Where n is the parameter/argument
To check if n is an integer or a string (like Iowa) or a list (like range(10)), use isinstance (Hint: the function returns True or False). Use an if/else statement here to determine the function either returns an empty list [] or to continue:
Use another if/else statement to determine whether a number is positive or negative (if it's bigger than 0 it's positive, else it's negative)
To get the squares of a number, well, how would you figure out what two squared is? Or three squared?
**
You can then use a list comprehension to get the squares of every number between one and n (but how would you get a list of numbers between one and n? You'll need a range or something)
Don't forget to return the items ;)

Categories

Resources