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.
Related
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 years ago.
Improve this question
Is it possible do like that with list comprehension. For example, if I call function f4(5), it should show like: [[[[[]]]]]. So each time append empty list in previous list.
You can append a list to itself, which since lists are mutable, sets off a recursion that leads to an infinitely nested list that can be indexed up until the recursion limit. Python uses the elipisis placeholder to display this:
>>> lst = []
>>> lst.append(lst)
>>> lst
[[...]]
>>> lst[0][0][0][0][0]
[[...]]
However, I can imagine no practical use for this at all.
def f(x):
if x == 1:
return []
return [f(x-1)]
print(f(5))
Output:
[[[[[[]]]]]]
I don't see any real use for that, but of course it's possible.
def f(n):
return [f(n - 1)] if n > 1 else []
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 5 years ago.
Improve this question
I have a for in c++ and I want to write it in python but I don't Know how to handle the condition in the for. Can anyone help me ?
for (int b = (i - a) / 2; a + b <= i; b++);
The terminating condition a + b <= i is equivalent to b <= i - a which in turn (as Python for uses less than not less than or equal) would be b < i - a + 1.
That means in Python you could write:
for b in range((i - a) / 2, i - a + 1):
...
But very often you don't want to write like for like when converting from C/C++ to Python. You may be better to restructure the code entirely.
use while
a=something
i=something
b=(i-a)/2
while(a+b<=i):
###do whatever you want in the loop###
b+=1
You could use the for loop and range() function. Example:
for i in range(15):
#code to execute 15 times
However, because of your code, I'd recommend using a while loop instead:
i = 1 #your value for i
b = (i-a)/2
while a+b <= i:
# Other code
b+=1
Your confusion stems from the over-generality of C's iteration construct. Python insists that all loop parameters implicitly refer to the loop index. For the terminating condition, solve your inequality in terms of b, and without equality: b < i - a + 1
Now we get the for loop
for b in range((i-a)/2, (i-a)+1):
One interpretation is that you have a range from 0 to i-a, and you want to deal with the upper half of that.
To answer your question directly:
for b in range((i-a)/2,a+b-1):
print (b)
And if, for some reason, you need a terminating value:
terminatingValue = 0
for b in range((i-a)/2,a+b-1):
terminatingValue = b
print (b)
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
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
I am still sort of new to python, I can do anything with a while loop and I am still having trouble comprehending that.
for i in range(len(s)):
for x in a: <- where a is an empty set
To get items out of a set without a for loop, you can use an iterator. This is probably what your prof. is referring to. Example:
i = iter(s)
while True:
try:
next(i)
except StopIteration:
break
You can do everything in a while loop but sometimes it can be awkward. The thing about a for loop is that it consumes a sequence.
For your first example, the loop is pretty straight forward because all we really wanted was in index in s
for i in range(len(s)):
print(i)
i = 0
while i < len(s):
print(i)
i += 1
Your second example is more problematic because you can't index sets. Likely, the best way to handle it is to convert the set to a list and index that. Or you could mimic for by creating your own iterator for the set and handling the end-of-iteration exception yourself.
a = set()
for x in a:
print(x)
# this would be illegal because you can't index the set
i = 0
while i < len(a):
print(a[i]) # ERROR
i += 1
# so we make a list
i = 0
_a = list(a)
while i < len(_a):
print(_a[i])
i += 1
# or use an iterator for the set
a_iter = iter(a)
while True:
try:
print(next(a_iter))
except StopIteration:
break
In some languages like C, while is just an abreviated form of for...
while(x < 5)) {...}
for(;x < 5;) {...}
but as you can see, such is not the case with python.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions concerning problems with code you've written must describe the specific problem — and include valid code to reproduce it — in the question itself. See SSCCE.org for guidance.
Closed 9 years ago.
Improve this question
I'm trying to make a function isPerm(P) that returns True if it is a permutation, and False otherwise.
So far I've got:
def isPerm(P):
if len(P) == list(range(P)):
return True
else:
return False
Any help would be great.
The simplest way which I can think of is to use Counter
from collections import Counter
def isPerm(P, Q):
return Counter(P) == Counter(Q)
print isPerm("oolegg", "google")
Output
True
This is the easy solution, for short lists.
def is_perm(a, b):
return sorted(a) == sorted(b)
Naive approach: sort a clone of the list and then compare the original list with the sorted clone. If equal then you have a permutation. But sorting takes time.
Efficient approach: create a dictionary/counter with items set to 0 and loop through the list increasing the value in the dictionary. If you get a value of 0 or greater that 1 after finishing the list then you don't have a permutation.