I have following string and I want to convert it to array/list so I can measure its length.
a="abc,cde,ert,ert,eee"
b="a", "b", "c"
The expected length for a should be 1 and the expected length for b should be 3.
a is a string, b is a tuple. You can try something like this:
def length_of_str_or_tuple(obj):
if(isinstance(obj,basestring)):
return 1
return len(obj)
Although what you're doing is really weird and you should probably rethink your approach.
You can use something like this:
>>> a="abc,cde,ert,ert,eee"
>>> b="a", "b", "c"
>>> 1 if isinstance(a, str) else len(a)
1
>>> 1 if isinstance(b, str) else len(b)
3
>>>
In the above code, the conditional expression uses isinstance to test whether or not item is a string object. It returns 1 if so and len(item) if not.
Note that in Python 2.x, you should use isinstance(item, basestring) in order to handle both unicode and str objects.
There's a crude way to do this: check which is a string and which a tuple:
x ={}
for item in (a,b):
try:
item.find('')
x[item] = 1
except:
x[item] = len(item)
Since a tuple object doesn't have an attribute find, it will raise an exception.
To measure the length of the string:
len(a.split())
for the tuple:
len(list(b))
combine the previous answers to test for tuple or list and you would get what you want, or use:
if type(x) is tuple:
len(list(x))
else:
a = x.split("\"")
len(a)
Related
My question is to write a function which returns the longest string and ignores any non-strings, and if there are no strings in the input list, then it should return None.
my answer:
def longest_string(x):
for i in max(x, key=len):
if not type(i)==str:
continue
if
return max
longest_string(['cat', 'dog', 'horse'])
I'm a beginner so I have no idea where to start. Apologies if this is quite simple.
This is how i would do it:
def longest_string(x):
Strings = [i for i in x if isinstance(i, str)]
return(max(Strings, key=len)) if Strings else None
Based on your code:
def longest_string(x):
l = 0
r = None
for s in x:
if isinstance(s, str) and len(s) > l:
l = len(s)
r = s
return r
print(longest_string([None, 'cat', 1, 'dog', 'horse']))
# horse
def longest_string(items):
try:
return max([x for x in items if isinstance(x, str)], key=len)
except ValueError:
return None
def longest_string(items):
strings = (s for s in items if isinstance(s, str))
longest = max(strings, key=len) if strings else None
return longest
print(longest_string(['cat', 'dog', 'horse']))
Your syntax is wrong (second-to-last line: if with no condition) and you are returning max which you did not define manually. In actuality, max is a built-in Python function which you called a few lines above.
In addition, you are not looping through all strings, you are looping through the longest string. Your code should instead be
def longest_string(l):
strings = [item for item in l if type(item) == str]
if len(strings):
return max(strings, key=len)
return None
You're on a good way, you could iterate the list and check each item is the longest:
def longest_string(x)
# handle case of 0 strings
if len(x) == 0:
return None
current_longest = ""
# Iterate the strings
for i in x:
# Handle nonestring
if type(i) != str:
continue
# if the current string is longer than the longest, replace the string.
if len(i) > len(current_longest):
current_longest = i
# This condition handles multiple elements where none are strings and should return None.
if len(current_longest) > 0:
return current_longest
else:
return None
Since you are a beginner, I recommend you to start using python's built-in methods to sort and manage lists. Is the best when it comes to logic and leaves less room for bugs.
def longest_string(x):
x = filter(lambda obj: isinstance(obj, str), x)
longest = max(list(x), key=lambda obj: len(obj), default=None)
return longest
Nonetheless, you were in a good way. Just avoid using python´s keywords for variable names (such as max, type, list, etc.)
EDIT: I see a lot of answers using one-liner conditionals, list comprehension, etc. I think those are fantastic solutions, but for the level of programming the OP is at, my answer attempts to document each step of the process and be as readable as possible.
First of all, I would highly suggest defining the type of the x argument in your function.
For example; since I see you are passing a list, you can define the type like so:
def longest_string(x: list):
....
This not only makes it more readable for potential collaborators but helps enormously when creating docstrings and/or combined with using an IDE that shows type hints when writing functions.
Next, I highly suggest you break down your "specs" into some pseudocode, which is enormously helpful for taking things one step at a time:
returns the longest string
ignores any non-strings
if there are no strings in the input list, then it should return None.
So to elaborate on those "specifications" further, we can write:
Return the longest string from a list.
Ignore any element from the input arg x that is not of type str
if no string is present in the list, return None
From here we can proceed to writing the function.
def longest_string(x: list):
# Immediately verify the input is the expected type. if not, return None (or raise Exception)
if type(x) != list:
return None # input should always be a list
# create an empty list to add all strings to
str_list = []
# Loop through list
for element in x:
# check type. if not string, continue
if type(element) != str:
pass
# at this point in our loop the element has passed our type check, and is a string.
# add the element to our str_list
str_list.append(element)
# we should now have a list of strings
# however we should handle an edge case where a list is passed to the function that contains no strings at all, which would mean we now have an empty str_list. let's check that
if not str_list: # an empty list evaluates to False. if not str_list is basically saying "if str_list is empty"
return None
# if the program has not hit one of the return statements yet, we should now have a list of strings (or at least 1 string). you can check with a simple print statement (eg. print(str_list), print(len(str_list)) )
# now we can check for the longest string
# we can use the max() function for this operation
longest_string = max(str_list, key=len)
# return the longest string!
return longest_string
I want to loop over each element and check if its type is int and if it lays within range of 12 <= i <= 20
if so return True
I use any to return if all elements are correct and isinstance to catch the type of each element.
The function gives me no output and no bug report so I don't know where the error is.
listoflist = [[14,13,13,14]]
def list_check(my_list):
if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
print("true")
return True
Problem is that you use nested list. Also you do not get any output whatsoever because you are not calling the function.Following code prints True on console
my_list = [14,13,13,14]
def list_check(my_list):
if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
print("true")
return True
list_check(my_list)
This is because you're looping through a one element list, so basically the for i in my_list only has one resulting item: [14,13,13,14]
You will need to select list[0] to iterate through the inner elements. There are also more elegant solutions than using for loops to apply such simple operations on lists, for instance map() and lambda:
listoflist = [[14,13,13,14]]
def list_check(mylist):
f = lambda x: isinstance(x, int) and 12 <= x <= 20
return all(map(f, mylist[0]))
list_check(listoflist)
Out[55]: True
lambda creates a "callable" function, and map applies this function to all elements of an iterable (e.g., list).
The problem in your case because you have list in list:
listoflist = [14,13,13,14]
def list_check(my_list):
if all(isinstance(i, int) and 12 <= i <= 20 for i in my_list):
print("true")
return True
print(list_check(listoflist))
Try this
def list_check(my_list_of_lists):
for my_list in my_list_of_lists:
if all([isinstance(i, int) and 12 <= i <= 20 for i in my_list]):
print("true")
return True
Its not clear that you want it always to use list of lists as you post in your example. Or if you want the output to be true if all the lists are true. This will output true as many times as there are lists that fulfill the condition.
I was requested to write a function called summer which gets a list and returns its sum but only if all the elements in the list are of the same type.
For example if:
summer(['a','b','c'])
the result will be:
abc
if
summer (['True','False','True'])
the result will be:
2
but
if
summer (['a','1','k'])
it will print the elements are not of the same type.
Here's my code:
def summer(lst):
summary=0
for i in range(len(lst)):
if i==0:
summary=lst[0]
else:
summary+=lst[i]
return summary
lst=input("Insert list ")
lst=lst.split(',')
print(summer(lst))
My code just joins everything:
if the input is True, False the printing is TrueFalse
please help me fix it, thank you!
The first thing you'll have to do is to check each element's type.
So over your if/else condition within the for loop, consider to check if all elements are of the same type. Something like:
for item in lst:
if (type(item) != lst[0]):
break;
If I correctly understood your problem, only if there's no difference among all the elements then the desired operation should be performed.
I hope that it can be clarifying.
I think this might be what you are trying to do or somewhat close.
def summer(lst):
summary=0
if all(isinstance(i,int) for i in lst):
return sum(lst)
if all(isinstance(i,str) for i in lst):
return ''.join(lst)
else:
return 'Elements not the same'
summer([True,False,True])
def summer(items):
from functools import reduce
from operator import add
assert isinstance(items, list)
types = {type(item) for item in items}
if len(types) != 1:
raise TypeError("All items must have the same type!")
return reduce(add, items)
Output:
>>> summer(["a", "b", "c"])
'abc'
>>> summer([1, 2, 3])
6
>>> summer([True, False, True])
2
>>> summer([True, False, "A"])
TypeError: All items must have the same type!
I am making a recursive function that slices string until it is empty. When it is empty it alternatively selects the characters and is supposed to print or return the value. In this case I am expecting my function to return two words 'Hello' and 'World'. Maybe I have got it all wrong but what I don't understand is that my function doesn't let me print or return string. I am not asking for help but I'd like some explanation :) thanks
def lsubstr(x):
a= ''
b= ''
if x == '':
return ''
else:
a = a + x[0:]
b = b + x[1:]
lsubstr(x[2:])
#print (a,b)
return a and b
lsubstr('hweolrllod')
so I changed my code to this:
def lsubstr(x):
if len(x) <1:
return x
else:
return (lsubstr(x[2:])+str(x[0]),lsubstr(x[2:])+str(x[1]))
lsubstr('hweolrllod')
and what I am trying to make is a tuple which will store 2 pairs of characters and concatenate the next ones,
the error I get is
TypeError: Can't convert 'tuple' object to str implicitly
what exactly is going wrong, I have checked in visualization, it has trouble in concatenating.
The and keyword is a boolean operator, which means it compares two values, and returns one of the values. I think you want to return a tuple instead, like this:
...
return (a, b)
And then you can access the values using the indexing operator like this:
a = lsubstr( ... )
a[0]
a[1]
Or:
word1, word2 = lsubstr( ... )
I have written a function to check for the existence of a value in a list and return True if it exists. It works well for exact matches, but I need for it to return True if the value exists anywhere in the list entry (e.g. value <= listEntry, I think.) Here is the code I am using for the function:
def isValInLst(val,lst):
"""check to see if val is in lst. If it doesn't NOT exist (i.e. != 0),
return True. Otherwise return false."""
if lst.count(val) != 0:
return True
else:
print 'val is '+str(val)
return False
Without looping through the entire character string and/or using RegEx's (unless those are the most efficient), how should I go about this in a pythonic manner?
This is very similar to another SO question, but I need to check for the existence of the ENTIRE val string anywhere in the list. It would also be great to return the index / indices of matches, but I'm sure that's covered elsewhere on Stackoverflow.
If I understood your question then I guess you need any:
return any(val in x for x in lst)
Demo:
>>> lst = ['aaa','dfbbsd','sdfdee']
>>> val = 'bb'
>>> any(val in x for x in lst)
True
>>> val = "foo"
>>> any(val in x for x in lst)
False
>>> val = "fde"
>>> any(val in x for x in lst)
True
Mostly covered, but if you want to get the index of the matches I would suggest something like this:
indices = [index for index, content in enumerate(input) if substring in content]
if you want to add in the true/false you can still directly use the result from this list comprehension since it will return an empty list if your input doesn't contain the substring which will evaluate to False.
In the terms of your first function:
def isValInLst(val, lst):
return bool([index for index, content in enumerate(lst) if val in content])
where the bool() just converts the answer into a boolean value, but without the bool this will return a list of all places where the substring appears in the list.
There are multiple possibilities to do that. For example:
def valInList1 (val, lst):
# check `in` for each element in the list
return any(val in x for x in lst)
def valInList2 (val, lst):
# join the list to a single string using some character
# that definitely does not occur in val
return val in ';;;'.join(lst)