list to integer - python

I'm trying to write a recursive python function that takes in a list for example [1,2,3,4] and returns an integer 1234. Any help on how to do this
def listtoint(lst):
if lst==[]:
return 0
return lst[-1:]+clti(lst/10)
I know you can't divide the list but I would like a way to get around it

def listtoint(lst):
if lst == []:
return 0
s = ''.join([str(i) for i in lst])
return int(s)
How this works is: ''.join(some_list) takes every element of the list and concatenates them into one long string. every element of some_list here must already be a string, thus the list comprehension in the code above.
int is then used to turn the resulting string into an integer.
There should be error checking but you can deal with that. Also, this isn't recursive and doesn't need to be.
To do this recursively...
def listtoint(lst):
if lst==[]:
return 0
iPower = 10**(len(lst)-1)
return lst[0]*iPower + listtoint(lst[1:])

Related

python, printing longest length of string in a list

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

Recursive function of the product of a list not working

I'm trying to create a function that multiplies each item in a list and returns the total. The function doesn't stop running until memory runs out.
Can someone please explain to me why this isn't working?
items = [1,2,3,4,10]
def mult2(items):
if not items:
return 0
return mult2(items[0]) * mult2(items[1:])
mult2(items)
Couple of mistakes here
Your base case is wrong. The Base case has to be when the list is reduced to a single element and you need to return 1 and not 0.
You need to send a list with a single element and not the single element alone to meet your base case.
Corrected code
def mult2(items):
if len(items)==1:
return items[0]
return mult2([items[0]]) * mult2(items[1:])
Demo
>>> items = [1,2,3,4,10]
>>>
>>> def mult2(items):
... if len(items)==1:
... return items[0]
... return mult2([items[0]]) * mult2(items[1:])
...
>>> print(mult2(items))
240
There are two issues:
Single element is passed to mult2, but sequence is expected. That's why TypeError: 'int' object has no attribute '__getitem__' is raised, due to trying to subscripting int (code being executed resolves to 1[1:] which is simply not possible).
Your exit condition is broken. Neutral multiplier is 1, not 0.
After fixes your code would look like this:
def mult2(seq):
if not seq:
return 1
return seq[0] * mult2(seq[1:])
items = [1,2,3,4,10]
assert 240 == mult2(items)
You don't have a base case for your recursion that works properly.
Consider calling mult2 with [1,2,3] this gets to the return statement which called mult2 with 1 and with [1,2].
The problem is in the call to mult2 with the parameter 1 which is just an integer. When you get to the recursive part there's no indexing available because items is just an int at this point, so items[0] and items[1:] don't make sense at this point.
Fixed the errors in the OP, and this works:
items = [1,2,3,4,10]
def mult2(items):
if len(items) == 1:
return items[0]
return items[0] * mult2(items[1:])
print "sum:",mult2(items)

Python: can a function return a string?

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( ... )

(Python 2.7) Use a list as an argument in a function?

So I'm trying to learn Python using codecademy but I'm stuck. It's asking me to define a function that takes a list as an argument. This is the code I have:
# Write your function below!
def fizz_count(*x):
count = 0
for x in fizz_count:
if x == "fizz":
count += 1
return count
It's probably something stupid I've done wrong, but it keeps telling me to make sure the function only takes one parameter, "x". def fizz_count(x): doesn't work either though. What am I supposed to do here?
Edit: Thanks for the help everyone, I see what I was doing wrong now.
There are a handful of problems here:
You're trying to iterate over fizz_count. But fizz_count is your function. x is your passed-in argument. So it should be for x in x: (but see #3).
You're accepting one argument with *x. The * causes x to be a tuple of all arguments. If you only pass one, a list, then the list is x[0] and items of the list are x[0][0], x[0][1] and so on. Easier to just accept x.
You're using your argument, x, as the placeholder for items in your list when you iterate over it, which means after the loop, x no longer refers to the passed-in list, but to the last item of it. This would actually work in this case because you don't use x afterward, but for clarity it's better to use a different variable name.
Some of your variable names could be more descriptive.
Putting these together we get something like this:
def fizz_count(sequence):
count = 0
for item in sequence:
if item == "fizz":
count += 1
return count
I assume you're taking the long way 'round for learning porpoises, which don't swim so fast. A better way to write this might be:
def fizz_count(sequence):
return sum(item == "fizz" for item in sequence)
But in fact list has a count() method, as does tuple, so if you know for sure that your argument is a list or tuple (and not some other kind of sequence), you can just do:
def fizz_count(sequence):
return sequence.count("fizz")
In fact, that's so simple, you hardly need to write a function for it!
when you pass *x to a function, then x is a list. Do either
def function(x):
# x is a variable
...
function('foo') # pass a single variable
funciton(['foo', 'bar']) # pass a list, explicitly
or
def function(*args):
# args is a list of unspecified size
...
function('foo') # x is list of 1 element
function('foo', 'bar') # x is list with two elements
Your function isn't taking a list as an argument. *x expands to consume your passed arguments, so your function is expecting to be called like this:
f(1, 2, 3)
Not like this:
f([1, 2, 3])
Notice the lack of a list object in your first example. Get rid of the *, as you don't need it:
# Write your function below!
def fizz_count(lst):
count = 0
for elem in lst:
if elem == "fizz":
count += 1
return count
You can also just use list.count:
# Write your function below!
def fizz_count(lst):
return lst.count('fizz')
It must be a typo. You're trying to iterate over the function name.
try this:
def fizz_count(x):
counter = 0
for element in x:
if element == "fizz":
counter += 1
return counter
Try this:
# Write your function below!
def fizz_count(x):
count = 0
for i in x:
if i == "fizz":
count += 1
return count
Sample :
>>> fizz_count(['test','fizz','buzz'])
1
for i in x: will iterate through every elements of list x. Suggest you to read more here.

Python: Converting from a list to a string

I'm having problems with a homework question.
"Write a function, to_str(a), that takes an array, a, converts each of
its elements to a string (using str(a[i])) and appends all these
strings together."
This is what I have
def to_str(a):
for i in a: a.append([i])
return str(a[i])
I have no idea how to use str(a[i]), I was wondering if someone can point me to the right direction
From the docs:
str(object) -> string
Return a nice string representation of the object. If the argument is
a string, the return value is the same object.
So str(a[i]) will return a string representation of a[i], i.e. convert a[i] to a string.
You will then need to concatenates the strings for all values of i.
As for your code, I have the following comments:
i is an element of a, not an index, as you might be thinking;
you are appending elements of a to a (endlessly, I'm afraid);
a[i] can cause an exception, because, like I said, i is an element, not an index;
you need to return a concatenation of strings, not a string from one element.
Also, if using str(a[i]) is not strictly mandatory, I'd suggest to skip it as unpythonic. You don't need indexes at all for this. Examples:
''.join(str(element) for element in a)
or
''.join(map(str, a))
will return what you need. In both cases str is applied to all elements of a.
The simplest-to-understand ("beginner") way without using indexes will be
s = ''
for element in a:
s += str(element)
return s
It's a bit less efficient, though it does effectively the same thing.
Converting each element into a string is easiest to use list comprehension:
[ str(i) for i in a ]
# equivalent to
[ str(a[i]) for i in range(len(a)) ]
# equivalent to
map(str, a) # most concise, use if you want to feel incredibly clever...
So you can write the function:
def to_str2(a):
''.join([str(i) for i in a]) # concatenates the list as a list of strings
.
Your code nearly does this:
def to_str(a):
new_a = [] # rather than use the same a!
for i in a:
new_a.append(str(i)) #convert i to string before appending
return new_a
The code meeting all the task criteria is rather something like:
def to_str(a):
return reduce(lambda x, y: x + str(y), a, '')
Which does things exactly in the mentioned way: first converts them to strings, then adds to the string made from already processed elements (which at the beginning is just emty string).
EDIT: The clearer (and supported by Python 3) way is to use explicit looping through elements. It does exactly the same, clarifying at the same time how reduce() works:
def to_str(a):
result = '' # third argument of reduce()
for item in a:
result += str(item) # does what reduce() lambda argument was doing
return result
the simplest way is:
[str(i) for i in a]
if you want a function:
def to_str(a):
return [str(i) for i in a]

Categories