Why am I getting a syntax error (python number checking function)? - python

I've written this function in Python, which is designed to check if any list element is a number, and return that list element if it is. This is the code:
def check_for_number(list):
x = 0
print(isinstance(list[x], (int, float))
true_or_false = False
for x in range(len(list)-1):
if isinstance(list[x], (int, float) == True):
true_or_false = True
num = list[x]
x += 1
print(true_or_false)
return true_or_false
return num
Whenever I try to run it I get a syntax error saying that the colon at the end of the if statement is an 'unexpected token', and every item in the last two lines of the if statement gives the same unexpected token error. I've checked the indentation and I can't see anything wrong with it, what am I missing? Thanks.

You just have to indend the code of your function and fix the if isinstance(list[x], (int, float) == True): part and close the paranthesis of your first print statement.
def check_for_number(list):
x = 0
print(isinstance(list[x], (int, float)))
true_or_false = False
for x in range(len(list)-1):
if isinstance(list[x], (int, float)) == True:
true_or_false = True
num = list[x]
x += 1
print(true_or_false)
# Decide what you want to return here
return true_or_false
return num
If you are interested in improving your code, remove the == True part, as has been stated in the comments as well. And from your question I assume you want to return fals, if true_or_false is False or num otherwise.
If you add a breakstatement in the loop, the loop will be exited when you have found the first number. So your computer does not need to loop through the complete list and this can save you some execution time.
I also expect, your x += 1 statement is not what you want to do. The for ... in range ... loop will increase your x in each cycle. That is why x += 1 will make your code skip every second list element. You also will not need to declare x first.
def check_for_number(list):
print(isinstance(list[x], (int, float)))
true_or_false = False
for x in range(len(list)-1):
if isinstance(list[x], (int, float)):
true_or_false = True
num = list[x]
break
print(true_or_false)
if (true_or_false):
return num
else:
return False
Concering your question about the unnecessary == True part:
The if statement is working like the following pseudo code.
if (CONDITION) == True then do something special
So, if you add a == True, python would check it like so:
if (valeu == True) == True then do something special
which is the same as:
if (value) == True then do something special

Here is a solution using a list comprehension. It checks each element against the Number abstract base class. It will return a list of numbers, since there might be more than 1 numeric elelement.
import numbers
def get_numbers(l):
return [x for x in l if isinstance(x, numbers.Number)]
example:
>>> l = ['1', 4.0, 'abc', 'XYZ', 'test', 5]
>>> nums = get_numbers(l)
>>> print(nums)
[4.0, 5]

Python is tab-sensitive and intolerant of errors in this regard. I'm also seeing an instance of an unmatched parenthesis on line 6. Try the following and you might get a more informative error on what to fix next:
def check_for_number(list):
x = 0
print(isinstance(list[x], (int, float))
true_or_false = False
for x in range(len(list)-1):
if isinstance(list[x], (int, float) == True): # missing a parenthesis to close isinstance.
# "== True" is unnecessary because isinstance() will resolve to True or False
true_or_false = True
num = list[x]
x += 1
print(true_or_false)
return true_or_false
return num # this will result in unexpected behavior...
# ...because num will not be defined if this line is reached.
# Either the return inside the if will finish the method or num will never be defined.
It's a bit ambiguous how some of that should be indented because I can't tell what you're trying to do.
If you're trying to return to values, consider returning a list or a dictionary containing the values.

Related

I am seeing if the items in list two is triple the data in list one in every position

for i in range(0,len(data1)):
if data1[i] == data2[i] *3:
return True
else:
return False
How can I see if every item in data1 is tripled in the same spot as data2 I am stuck I think I have the right loop.
You don't need to return anything, when data IS trippled as you will break your loop right away. You should only return False when it is not and then return True if nothing was falsy.
for i in range(len(data1)):
if data1[i] != data2[i] * 3:
return False
return True
Here is a oneliner:
return all(map(lambda x: x[0] == x[1] * 3, zip(data1, data2)))
Simply, you can do this :
for i in range(0,len(data1)):
if data1[i] != data2[i] *3:
return False
return True
Try this:
data1==[3*i for i in data2]
Actually, your technique seems pretty fine to me, except for a few small mistakes in the code itself. I'll show you your own code with notes, then the new corrected code:
#your code
for i in range(0,len(data1)):
^
#if you will start from 0 anyway, it's always better to just leave it out.
if data1[i] == data2[i] *3:
^^^^
#here, i would change data2[i] to int before multiplying also change data1, just to be safe.
return True
else:
return False
now here's the full correction:
#correction
for i in range(len(data1)):
if int(data1[i]) == int(data2[i]) *3:
return True
else:
return False
postscript:
sometimes an error would occur in the if int(data1[i]) == int(data2[i]) *3 line (idk why) but if this ever happens just add a line before it containing an int of i*3.
num = int(i)
num2 = int(i*3)
note that this has to be inside the for loop but before the conditions.
Happy coding
**if this didn't work..well im not a professional so sorry in advance

How to delete an item from a list by python only using recursion

How do I write a code in python by only using the recursion without loops and any build in methods or functions? I tried:
def myRemove(x, cont): # x is a string inside of the list cont
if x == cont:
return None
elif len(x) > len(cont):
return None
else:
if "x" not in cont[0]:
return myRemove(x,cont[1:])
else:
return cont
Some problems I see in your code:
1. Difference between a string and a variable
You have the following line in your code which is semantically wrong:
if "x" not in cont[0]:
...
Here "x" is the string 'x' and not the value of x. To fix this remove the quotation marks.
if x not in cont[0]:
...
2. Difference between list and variable
To check if a variable is in a list use in. e.g.
>>> "test" in ["test", "wow", "u"]
true
To check if a variable is equal to another variable use ==. e.g.
>>> "test" == ["test", "wow", "u"][0]
true
The fixed part of your code: (Because cont[0] returns a value and not a list)
if x == cont[0]:
...
3. Returns in recursion
You have to concatenate the returned list with the list part before the other list.
Otherwise, you are always returning the last part of the list.
One possible solution
def remove(string, string_list):
if string_list[0] == string:
return string_list[1:]
else:
return string_list[:1] + remove(string,string_list[1:])
def recursive_remove(x: str, cont: list):
""" removes items equal to x using recursion only
cont: list of strings
x: string to remove from list
"""
if len(cont) == 0:
return []
if cont[0] != x:
return [cont[0]] + recursive_remove(x=x, cont=cont[1:])
else:
return recursive_remove(x=x, cont=cont[1:])
list_without_banana = recursive_remove(x='banana', cont=['apple', 'banana', 'strawberry', 'peanut'])
print(list_without_banana)
>>>['apple', 'strawberry', 'peanut']

How do I write a recursive function that multiplies each character in a string by 2?

I'm trying to complete a recursive function which given a number, returns a string where the returned value has duplicate of each digit
Example: if 507, returns 550077
if the number is only 0 then just return 0
also if it is a negative number, return the negative sign only once
Example: -507 returns -550077
I haven't yet implemented anything to recognize a negative number, I was just trying to get my function to work first
so far I have:
def double(x):
if x == 0:
return x
else:
x = str(x)
return x[0]*2 + double(x[1: ])
print(double(527))
however this returns IndexError: string index out of range
I had it working by printing the result instead of returning the result, but the problem I am trying to solve strictly wants the result returned, not printed. What am I doing wrong?
This works recursively, fixes the x==0 termination error, checks whether a character is a digit before doubling, and returns the final answer as an int (instead of a str).
def double(x):
x = str(x)
if len(x) == 0:
return ''
else:
first_char = x[0]
# only double if it's an integer
if first_char in map(str, range(10)):
first_char *= 2
return int(first_char + str(double(x[1: ])))
print(double(-527))
>>> -552277
Something like this might work.
def double(x):
if x == 0:
return x
else:
x = str(x)
l=[]
for a in x:
if a == '-':
l.append(a)
else:
l.append(a*2)
return ''.join(l)

How can I return false if more than one number while ignoring "0"'s?

This is a function in a greater a program that solves a sudoku puzzle. At this point, I would like the function to return false if there is more then 1 occurrence of a number unless the number is zero. What do am I missing to achieve this?
L is a list of numbers
l =[1,0,0,2,3,0,0,8,0]
def alldifferent1D(l):
for i in range(len(l)):
if l.count(l[i])>1 and l[i] != 0: #does this do it?
return False
return True
Assuming the list is length 9, you can ignore the inefficiency of using count here (Using a helper datastructure - Counter etc probably takes longer than running .count() a few times). You can write the expression to say they are all different more naturally as:
def alldifferent1D(L):
return all(L.count(x) <= 1 for x in L if x != 0)
This also saves calling count() for all the 0's
>>> from collections import counter
>>> def all_different(xs):
... return len(set(Counter(filter(None, xs)).values()) - set([1])) == 0
Tests:
>>> all_different([])
True
>>> all_different([0,0,0])
True
>>> all_different([0,0,1,2,3])
True
>>> all_different([1])
True
>>> all_different([1,2])
True
>>> all_different([0,2,0,1,2,3])
False
>>> all_different([2,2])
False
>>> all_different([1,2,3,2,2,3])
False
So we can break this down into two problems:
Getting rid of the zeros, since we don't care about them.
Checking if there are any duplicate numbers.
Striping the zeros is easy enough:
filter(lambda a: a != 0, x)
And we can check for differences in a set (which has only one of each element) and a list
if len(x) == len(set(x)):
return True
return False
Making these into functions we have:
def remove_zeros(x):
return filter(lambda a: a != 0, x)
def duplicates(x):
if len(x) == len(set(x)):
return True
return False
def alldifferent1D(x):
return duplicates(remove_zeros(x))
One way to avoid searching for every entry in every position is to:
flags = (len(l)+1)*[False];
for cell in l:
if cell>0:
if flags[cell]:
return False
flags[cell] = True
return True
The flags list has a True at index k if the value k has been seen before in the list.
I'm sure you could speed this up with list comprehension and an all() or any() test, but this worked well enough for me.
PS: The first intro didn't survive my edit, but this is from a Sudoku solver I wrote years ago. (Python 2.4 or 2.5 iirc)

Trying to check a condition for every element in a list of integers

I'm trying to define a method to check whether or not every element of a list is a factor of the parameter.
Here's what I have:
def factorall(x):
if all(x % num for num in nums) == 0:
return True
else:
return False
(In this case nums is a list of the integers from 1 to 10)
However, this returns true for any number. I'm assuming this happens because it is only checking 1 and then returning True, but shouldn't all() be checking for every element of the list before returning True?
I'm a bit unfamiliar with all() so I probably implemented it incorrectly. Can someone point me in the right direction?
Thanks!
you should use not any instead of all
def factorall(x):
return not any(x%num for num in nums) #if any of these is a value other than 0
or if you want it like you currently have it
def factorall(x):
return all(x%num==0 for num in nums)
You should do the comparison inside the all function, or simply remove it, and use negation of the result x % num:
def factorall(x):
return all(not x % num for num in nums)
The return statement works same as:
return all(x % num == 0 for num in nums)
I agree that the 2nd one seems clearer.
def factorall(x):
if all(x % num == 0 for num in nums):
return True
else:
return False

Categories