Right now I'm trying to get my program to take a two dimensional list as an input and return either true or false depending on whether or not it is "rectangular" (eg. [[2,3],[1,5],[6,9]] is rectangular whereas [[2,3],[1,8,6]] is not.) So far I've come up with this:
def rectangular(List):
n = List
for i in n:
if len(i) != len(n[0]):
return False
elif len(i) == len(n[0]):
i
I can't seem to figure out how to create a "true" case. Using the elif above I'm able to cycle through the list but if i were to add a return true portion it stops as soon as that is the case. Would a while loop work better in this case? All help is appreciated! Thanks.
If you get to the end without finding a false case, then you know it's true, right? There aren't any other possibilities.
So, you can just remove the elif entirely, and just add a return True at the end:
def rectangular(List):
n = List
for i in n:
if len(i) != len(n[0]):
return False
return True
As a side note, your elif that has exactly the opposite condition as the if is better written as just else:. That way, there's no chance of you getting the opposite condition wrong, no need for your readers to figure out that it's the opposite, etc.
Also, there's no reason to take the argument as List, then bind the same value to n and use that. Why not just take n in the first place?
def rectangular(n):
for i in n:
if len(i) != len(n[0]):
return False
return True
You can make this more concise, and maybe more Pythonic, by replacing the for statement with a generator expression and the all function:
def rectangular(n):
return all(len(i) == len(n[0]) for i in n)
But really, this isn't much different from what you already have. You should learn how this works, but if you don't understand it yet, there's no problem doing it the more verbose way.
If you want to get clever:
def rectangular(n):
lengths = {len(i) for i in n}
return len(lengths) == 1
We're making a set of all of the lengths. Sets don't have duplicates, so this is a set of all of the distinct lengths. If there's only 1 distinct length, that means all of the lengths are the same.
However, note that for an empty list, this will return False (because there are 0 lengths, not 1), while the other two will return True (because a condition is vacuously true for all values if there are no values to test). I'm not sure which one you want, but it should be relatively easy to figure out how to change whichever one you choose to do the opposite.
Try using the all function with a generator:
def rectangular(lst):
first_len = len(lst[0])
# I used lst[1:] to skip the 0th element
return all(len(x) == first_len for x in lst[1:])
The all function returns True if all elements of an iterable are True, and False otherwise.
It's good that you didn't call your variable list, but capitalized names usually represent a class in Python, so lst is a better choice than List.
NOTE: I made the assumption that "rectangular" means each sublist is the same length. If in reality each sublist should be (say) 2 elements long, just replace first_len with the literal 2 and remove the [1:] on lst[1:]. You may also want to add some exception handling in case you pass a list with only one element.
You can make sure that the lengths of all elements of the list are the same length. Or in Python:
all(map(lambda m: len(m) == len(x[0]), x))
Where x is what you want to check.
The only problem with this solution is that the if the list looks like [ [1,2], [1,[1,2]], 'ab' ], it is still going to return True. So you additionally need to do some type checking.
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
def check(x,num,i):
for n in range(len(x)):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
return False
def User(x,num):
return(check(x,num,0))
User([2,6,1,9,7,3],5,0)
this should out put false since 5 is not in the list
checks whether an element occurs in a list recursively
so for example:
Input: a list L read from the keyboard, for example L = [2,6,1,9,7,3]
an element e, for example e = 9
but for some reason, i get an error when the number is not in the list
The beauty (and purpose) of recursion is that you do not need the loop:
def check(x, num, i):
if not x[i:]: # index past length
return False
if x[i] == num:
return True
return(check(x, num, i+1))
You can also do without the index parameter:
def check(x, num):
if not x:
return False
return x[0] == num or check(x[1:], num)
I don't exactly understand what you're doing, but this is a bizarre combination of recursion and iteration. If you're going to use recursion, it's worthwhile, at least for a basic recursive problem like this, to avoid iteration. Try something like this
def check(x, num, i = 0):
if i >= len(x):
return False
elif x[i] == num:
return True
else:
return check(x, num, i + 1)
This solution will work perfectly fine and is tail recursive so it will work quickly and optimally.
The way this works is it checks if the index, i, is out of bounds. If so, then it returns False. If it is in bounds, it checks if x[i] is equal to the number. If so, it returns True. If it is not, it returns check with the index increased and thus the recursion works.
First of all, your for loop doesn't make any sense. You never use that n and never go into the loop a second time, as you always return something in the first iteration. The return statement after the for loop is also unreachable, so your code could as well be
def check(x,num,i):
if x[i] == num:
return True
else:
return(check(x,num,i+1))
Then the actual issue is, that if you have a list with 5 elements for example, which does not contain the element searched for, you ask what the 6th is, although there is no 6th element, thus the error. You'd have to check whether the list contains 6 elements. So you check whether it has more than 5, return false if it does and continue if it doesn't. (Alternatively you could also check this at the start of the whole function)
def check(x,num,i):
if x[i] == num:
return True
else:
if len(num)>i:
return False
else:
return(check(x,num,i+1))
What you've done then is nothing but a overcomlicated, recursive for-Loop. You just increase i and compare, until you find the element or i is bigger than the list length. So this is equivalent to
def check(x,num):
for i in range(len(num)):
if x[i]==num:
return True
return False
It is very important that the return False is AFTER the for-Loop, as you only return, if you didn't find the element, even after iterating over the WHOLE list.
Also you can avoid indices. With a for-Loop you can directly iterate over the elements in a list:
def check(x,num):
for elem in num:
if elem==num:
return True
return False
This makes the variable elem become every element in you list, one after another.
I was making a poker simulator and tried to define a function which would identify a straight and give it a handstrength value of 5.
def straightCheck(playerHand):
playerHand.sort()
print(playerHand)
for playerHand in range(len(playerHand)):
for i in playerHand:
if playerHand[i] == playerHand [i+1] -1:
straight = True
else:
straight = False
if straight == True:
handstrength = 5
x = [1,3,5,4,2]
straightCheck(x)
i can't figure out what is wrong with is but it keeps returning this error message:
for i in playerHand:
TypeError: 'int' object is not iterable
First of all you are trying to iterate of an integer, which cannot (and shouldn't) be done. It seems like your two nested for loops should just be one for, like for i in range(len(playerHand) - 1), when the -1 is used so that you don't try to accessplayerHand[len(playerHand)].
In addition, since you set straight to True or False in every iteration, only your last iteration will count, so you'll get false positives.
Finally, I'm not sure whether you want your function to return a value, but currently your function returns no data (unless handstrength is a global variable). Also, please note that currently, by using .sort() you are actually sorting playerHand, thus changing it from within the function - this might not be what you want.
A possible function to check whether a hand is straight, similar to your code, is this:
def is_straight(playerHand):
playerHand.sort()
for i in range(len(playerHand) - 1):
if playerHand[i] != playerHand [i+1] - 1:
return False
return True
This function returns True if playerHand is straight, and False otherwise.
What about this. You sort the list, then convert it to a set and back to a list, which makes it unique. Then the length must be 5 and if so, the difference between max and min for 5 consecutive numbers must be 4. I can't mathematically prove this here, but it should be. ;)
>>> x=[2,1,5,3,4]
>>> y=sorted(x)
>>> y=list(set(y))
>>> if len(y) == 5 and y[4]-y[0] == 4:
... print "straight"
...
straight
Also see this here: Check for consecutive numbers
For some reason the same method is working for one function and not the other. The function that works already is defined as the following:
def is_unique1(lst):
for item in lst:
current_index = lst.index(item)
if lst[current_index] in lst[current_index + 1:-1]:
return False
return True
You pass in a list and checks the uniqueness of it, if it is unique then return TRUE if not return FALSE. However I am then asked to create another function, except this time copy the list and sort it. Then iterate over every index for values in the list to check whether the value at that index is equal to the value at the next higher index. But it keeps returning TRUE no matter what input. The function looks like this:
def is_unique2 ( myList ):
list_copy = list(myList)
list_copy.sort()
print(list_copy)
for item in list_copy:
index = list_copy.index(item)
if list_copy[index] in list_copy[index + 1: -1]:
return False
return True
Why is this happening. Am I using the slice incorrectly. I am checking if the current value at list_copy[index] is in the index + 1. I am testing it like so:
print('\nTesting is_unique2')
print (is_unique2(['raisin', 'apricot', 'celery', 'carrot']) )
print (is_unique2(['raisin', 'apricot', 'raisin', 'carrot']) )
Your bug is that by checking if list_copy[index] in list_copy[index + 1: -1] you're not checking the very last item in the list.
Remember, in Python, it's always "upper bound excluded": so somelist[a:b] will span somelist[a] included to somelist[b] excluded... for any a and b.
Easy fix: use in list_copy[index + 1:]. IOW, give no upper bound for the slice, so the slice will run all the way to the end of the list.
Incidentally, your approach is very dubious if the list's items are hashable -- in which case,
def is_unique3(myList):
return len(myList) == len(set(myList))
will be much faster and much less bug-prone too:-)
Try this line instead of your -1 indexed list for unique1:
lst[current_index] in lst[current_index + 1:None:-1]:
I need to Check that every number in numberList is positive and implement the below
function using recursion. I'm stuck. Just learning recursion and I'm completely lost as I am very new to programming. Help!
def isEveryNumberPositiveIn(numberList):
foundCounterexampleYet = False
for number in numberList:
if(number <= 0):
foundCounterexampleYet = True
return not(foundCounterexampleYet)
Your function is not recursive because it never calls itself; a recursive version would look like
def all_positive(lst):
if lst:
return lst[0] > 0 and all_positive(lst[1:])
# ^
# this is the recursive bit -
# the function calls itself
else:
return True
# this keeps the function from looping forever -
# when it runs out of list items, it stops calling itself
This is a bad example to choose for a recursive function because (a) there is a simple non-recursive solution and (b) passing it a large list (ie over 1000 items) will overflow the call stack and crash your program. Instead, try:
def all_positive(lst):
return all(i > 0 for i in lst)
Your indentation is incorrect, but your thinking is correct, though the algorithm is not recursive. You could make it a bit more efficient though, by jumping out of the loop when a negative number is detected:
def isEveryNumberPositiveIn(numberList):
foundCounterexampleYet = False
for number in numberList:
if number <= 0:
foundCounterexampleYet = True
break
return not foundCounterexampleYet
then for example:
a = [1,-2,3,4,45]
print(isEveryNumberPositiveIn(a))
returns False
By the way, those parentheses forif and not are unnecessary.
With this sort of recursive problem, here is how you should think about it:
There should be a "basis case", which answers the question trivially.
There should be a part that does something that brings you closer to a solution.
In this case, the "basis case" will be an empty list. If the list is empty, then return True.
The part that brings you closer to a solution: shorten the list. Once the list get shortened all the way to a zero-length (empty) list, you have reached the basis case.
In pseudocode:
define function all_positive(lst)
# basis case
if lst is zero-length:
return True
if the first item in the list is not positive:
return False
# the actual recursive call
return all_positive(lst[with_first_value_removed]
Try to convert the above pseudocode into Python code and get it working. When you are ready to peek at my answer, it's below.
def all_positive(lst):
"""
Recursive function to find out if all members of lst are positive.
Because it is recursive, it must only be used with short lists.
"""
# basis case
if len(lst) == 0:
return True
if lst[0] <= 0:
return False
# recursive call
return all_positive(lst[1:])
There's several ways you can write this. One way would be to use lst.pop() to remove one element from the list. You could combine that with the if statement and it would be kind of elegant. Then the list would already be shortened and you could just do the recursive call with the list.
if lst.pop() <= 0:
return False
return all_positive(lst)
There is one problem though: this destroys the list! Unless the caller knows that it destroys the list, and the caller makes a copy of the list, this is destructive. It's just plain dangerous. It's safer to do it the way I wrote it above, where you use "list slicing" to make a copy of the list that leaves off the first item.
Usually in a language like Python, we want the safer program, so we make copies of things rather than destructively changing them ("mutating" them, as we say).
Here's one more version of all_positive() that makes a single copy of the list and then destroys that copy as it works. It relies on a helper function; the helper is destructive. We don't expect the user to call the helper function directly so it has a name that starts with an underscore.
def _all_positive_helper(lst):
"""
Recursive function that returns True if all values in a list are positive.
Don't call this directly as it destroys its argument; call all_positive() instead.
"""
if len(lst) == 0:
return True
if lst.pop() <= 0:
return False
return _all_positive_helper(lst)
def all_positive(lst):
"""
Return True if all members of lst are positive; False otherwise.
"""
# use "list slicing" to make a copy of the list
lst_copy = lst[:]
# the copy will be destroyed by the helper but we don't care!
return _all_positive_helper(lst_copy)
It's actually possible in Python to use a default argument to implement the above all in one function.
def all_positive(lst, _lst_copy=None):
"""
Return True if all members of lst are positive; False otherwise.
"""
if _lst_copy is None:
return all_positive(lst, lst[:])
if len(_lst_copy) == 0:
return True
if _lst_copy.pop() <= 0:
return False
return all_positive(lst, _lst_copy)
Recursion doesn't really help you with this. A better use for recursion would be, for example, visiting every node in a binary tree.
I am trying to write a recursive function that does a Boolean check if a list is sorted. return true if list is sorted and false if not sorted. So far I am trying to understand if I have the 'base case' correct (ie, my first 'if' statement):
def isSorted(L, i=[]):
if L[i] > L[i + 1]:
return false
else:
return true
Am I correct with my initial if "L[i] > L[i + 1]:" as base case for recursion?
Assuming my 'base case' is correct I am not sure how to recursively determine if the list is sorted in non-descending order.
here is what I came up with. I designate the default list to 0; first check to see if first item is the last item. if not, should check each item until it reaches the end of the list.
def isSorted(L):
# Base case
if len(L) == 1:
return True
return L[0] <= L[1] and isSorted(L[1:])
This is how I would start. Write a function with the following signature:
function isSorted(currentIndex, collection)
Inside the function, check to see if currentIndex is at the end of the collection. If it is, return true.
Next, check to see if collection[index] and collection[index+1] are sorted correctly.
If they aren't, return false
If they are, return isSorted(currentIndex+1, collection)
Warning: this is a horrible use for recursion
No, the base case will be when you reach the end of the list, in which case you return true.
Otherwise, if the two elements you are looking at are out of order return false.
Otherwise, return the result of a recursive call on the next elements down the list.
I agree with #MStodd: recursion is not the way to solve this problem in Python. For a very long list, Python may overflow its stack! But for short lists it should be okay, and if your teacher gave you this problem, you need to do it this way.
Here is how you should think about this problem. Each recursive call you should do one of three things: 0) return False because you have found that the list is not sorted; 1) return True because you have reached your base case; 2) break the work down and make the remaining problem smaller somehow, until you reach your base case. The base case is the case where the work cannot be broken down any further.
Here is a broad outline:
def recursive_check(lst, i):
# check at the current position "i" in list
# if check at current position fails, return False
# update current position i
# if i is at the end of the string, and we cannot move it any more, we are done checking; return true
# else, if i is not at the end of the string yet, return the value returned by a recursive call to this function
For example, here is a function that checks to see if there is a character '#' in the string. It should return True if there is no # anywhere in the string.
def at_check(s, i):
if s[i] == '#':
return False
i += 1
if i >= len(s):
return True
else:
return at_check(s, i)
I wrote the above exactly like the outline I gave above. Here is a slightly shorter version that does the same things, but not in exactly the same order.
def at_check(s, i=0):
if i >= len(s):
return True
if s[i] == '#':
return False
return at_check(s, i+1)
EDIT: notice that I put i=0 in the arguments to at_check(). This means that the "default" value of i will be 0. The person calling this function can just call at_check(some_string) and not explicitly pass in a 0 for the first call; the default argument will provide that first 0 argument.
The only time we really need to add one to i is when we are recursively calling the function. The part where we add 1 is the important "breaking down the work" part. The part of the string we haven't checked yet is the part after i, and that part gets smaller with each call. I don't know if you have learned about "slicing" yet, but we could use "slicing" to actually make the string get smaller and smaller with each call. Here is a version that works that way; ignore it if you don't know slicing yet.
def at_check(s):
if s == '': # empty string
return True
if s[-1] == '#': # is last character '#'?
return False
return at_check(s[:-1]) # recursive call with string shortened by 1
In this version, an empty string is the basis case. An empty string does not contain #, so we return True. Then if the last character is # we can return False; but otherwise we chop off the last character and recursively call the function. Here, we break the work down by literally making the string get shorter and shorter until we are done. But adding 1 to the index variable, and moving the index through the string, would be the same thing.
Study these examples, until you get the idea of using recursion to break down the work and make some progress on each recursive call. Then see if you can figure out how to apply this idea to the problem of finding whether a list is sorted.
Good luck!