Test the length of elements in a list - python

def lengthgood(x):
for i in x:
if len(i)<13
return i
else:
pass
def makeproperlist(x):
return x.split(',')
attendancelist=makeproperlist(input("attendee list:"))
final_list=list(filter(lengthgood,attendancelist))
for i in finallist:
print (i)
I want to write a programme of which I create a list in which only elements shorter than 14 can be a part of.
This is my code, but it keeps returning all the elements I put in, even if some of them are longer than 14?
I tried to print the len(i) and it says that it is 1 for every element in the list?
How do I solve this?

You shouldn't put a return within a loop; it'll only return the first element that matches your condition.
You also shouldn't be looping within your filter function, because you're actually looping over characters of strings, which are all length 1.
Therefore, the first character is always returning a truthy value, giving you back the initial input after filtering
You only need to check the input length, and filter functions should ideally return appropriate boolean conditions rather than truthy values (in your case return i is returning a non-empty string)
def lengthgood(x):
return len(x)<13
If you don't need to use filter(), you can write a list comprehension
final_list=[a if len(a) < 13 for a in attendancelist]

may be like that
flst = []
def croper(lst):
for i in lst:
flst.append(i) if len(i) < 13 else 0
lst = input("attendee list:").split(',')
croper(lst)
print(flst)
or shorter
def croper(lst):
return [i for i in lst if len(i) < 13]
lst = input("attendee list:").split(',')
print(croper(lst))

You want to create a list but you not define it anywhere in program simply done it with simply one function makeproperlist(x).
Try this code bro this will help you.
attendancelist=[]
while (True):
ch=input("Enter c for continue and e for exit : ")
if (ch=='c'):
def makeproperlist(x):
if x<=13:
attendancelist.append(x)
else:
print("Enter number which is <= to 13.")
makeproperlist(int(input("attendee list:")))
elif (ch=='e'):
break;
print("Your attendece list : ",attendancelist)

Related

function that uses a while loop to return characters in a list while also being subject to other conditions

To preface, because I’m learning to use while loops, I want to write this function with only if statements, in statements, and while loops. I think I may also need to use break or continue. I don’t want to use for loops or forms of list comprehension.
the function itself should looks like take_last(lst)
It should normally take in a list of words and returns the last value in the list with the first and last characters of it removed.
for instance,
take_last[“Fish”, “Meat”, “Fruit”, “Cake”]
will return “ak” as this is the last word in the list with the characters, “C” and “e” removed. This part of the function is relatively simple. I think it can be done with
return (lst[-1])[slice(1,-1)]
However, it is subject to two different conditions that may make writing the function difficult.
if the first name in the list has less than 3 characters, the function will stop and return “finished”
i.e take_list([“SH”, “Meat”]) will stop at “SH” and instead returns “finished”.
otherwise, if this condition is not fulfilled and the first word has 3 or more characters, the function will continue iterating through the list until it finds another word with less than 3 characters. it will then stop at this point and return the previous character in the list with the first and last character in it removed.
I.e if the input is take_last([“Fish”, “Meat”, “Fruit”, “SH”, “Cake”]) the function breaks at “SH” and instead “rui” is returned. (Fruit without the ‘F
What I am Trying
Although I am not sure how to structure the while loop, I have written the function with the first condition already fulfilled.
def take_last(lst):
if len(lst[0]) < 3:
return "finished"
else:
return (lst[-1])[slice(1,-1)]
take_last([“Fish”, “Meat”, “Fruit”, “Cake”]) will return “ake”
and take_last([“Fi”, “Meat”, “Fruit”, “Cake”]) will return
“finished”
I know that somewhere in my function I will need an elif statement followed by a while loop but I’m not sure how this would look. Any help would be appreciated.
Here's a simple way to do it.
def take_last(lst):
i = 0
while i < len(lst) and len(lst[i]) >= 3:
i += 1
if i == 0:
return "finished"
else:
return lst[i-1][1:-1]
The while loop repeats as long as the string at index i is at least 3 characters long. So when it's done, i contains the index of the first short string; if there are no short elements, it will contain the length of the list.
If the first string is short, i will be 0, so there's no element before it and we return finished.
Otherwise we return the slice of the element before i. This will be the last element when there are no short elements.
So returning the last word with 1st and 3rd chars removed is the last possible thing we can do. There may be conditions before it which may cause the the function to stop early.
So, now we know what becomes our default return
return (lst[-1])[slice(1,-1)]
Similarly, the first condition you are checking is correct as well. So that fixes our starting if.
if len(lst[0]) < 3:
return "finished"
Now the condition 2. We can tackle this in the else clause. We need to iterate through the list looking for a word less than 3 chars. If we find it, we return the element just before it after truncation .
else:
i = 1
while (i < len(lst)):
if len(lst[i]) < 3:
return (lst[i-1])[slice(1,-1)]
i += 1
Everything put together:
def take_last(lst):
if len(lst[0]) < 3:
return "finished"
else:
i = 1
while (i < len(lst)):
if len(lst[i]) < 3:
return (lst[i-1])[slice(1,-1)]
i += 1
return (lst[-1])[slice(1,-1)]
You can easily do this with a regular for loop in a way that, to me, feels a lot more natural than doing it with a while loop:
def take_last(lst):
prev = None
for val in lst:
if len(val) < 3:
break
prev = val
if prev is None:
return "finished"
else:
return prev[1:-1]

What is wrong with this function, and how can I make it work?

def func(sentence):
sumn = sentence.split()
if len(sumn) >= 5:
return sumn
plswork = func("me name goooose")
print(plswork)
When I use this if statement with a list outside of a function, it returns the element in the list that is 5 characters or greater. When applied to this function, it fails.
Essentially I am trying to create a function that identifies elements of a certain length, reverses these specific elements, and prints the new list. Though, I have not yet gotten to the reverse portion of my function yet.
This is what you want:
def func(sentence):
sumn = sentence.split()
for i in sumn:
if len(i) >= 5:
print(i)
func("me name goooose")

return a new list that interleaves the two lists but with a twist

def back_interleave(first, second):
if first == [] and second == []:
return []
elif first == []:
return second[::-1]
elif second == []:
return first[::-1]
else:
newlist = []
for i in range(len(first)-1, 0,-1):
newlist.append(first[i])
newlist.append(second[i])
for j in range(len(second)-len(first)-1,0,-1):
newlist.append(second[i])
return newlist
can anybody tells me what's wrong with my code towards this question.
I'm not exactly sure what's wrong with your code, but the second and third if-statements appear to use built-in list reversing functionality which the original problem forbids.
What I would do is determine the length of the longer list, then iterate through both lists backwards.
def back_interleave(first, second):
newlist = []
# You want to iterate through the length of the longer list
length = max(len(first), len(second))
for x in range(length):
# start appending elements from the back of the list
index = -1*(x+1)
if x < len(first):
newlist.append(first[index])
if x < len(second):
newlist.append(second[index])
return newlist
The problem in your code is when you use the range function, the stop value is exclusive i.e., the index 0 is becoming exclusive in your case. And also in the j loop the values at index i are being stored instead of the values at index j.
#CyanideTesla has given the code that works pretty well for your problem

Add all numbers that are in a list

So if I have a list, let's say: [1,2,'hello'] and I want to add all the numbers in a list, (strings should be ignored). I want it to return the number 3 (1+2). And the function must be recursive.
This is what I have come up with:
import numbers
def isnumber(x):
return isinstance(x, numbers.Number)
def sum_first(list):
if not list:
return 0
elif isnumber(list[-1]):
return list[-1] + sum_first(list[:-1])
list=eval(input("Enter a list: "))
print(sum_first(list))
This only works if the last element in the list is a number. Let's assume it's a string, how could I change it?
You are only handling two cases:
the list is empty
the last element is a number
Your example list doesn't fit either case, so you end up returning None.
Add a third branch:
def sum_first(lst):
if not lst:
return 0
elif isnumber(lst[-1]):
return lst[-1] + sum_first(lst[:-1])
else:
return sum_first(lst[:-1])
Now you handle the case where the last element is not a number; you handle it by ignoring it; recursing with the list without that one element.
I renamed your list variable to lst to avoid masking the built-in type.
reduce can be seen as a form of recursive function. If you don't intend to write your own recursive function then may be you could do this
import operator as op
def silent_int(v):
try:
return int(v)
except ValueError:
return 0
xs = [1, 2, 'hello', '4']
print reduce(op.add, map(silent_int, xs))
Obviously the correct way of counting numbers should be using sum but with the recursion restriction you could use reduce or build your own trampoline!

printing list in python after a function

I have been trying to print the results of a function that happen to be in a list. If this doesn't make sense.
In print_long.py, define a Python function print_long(list) that takes a list of strings called list and prints out each string in list that has a length greater than or equal to 6.
That is the original question. I tried doing
def print_long(list):
for i in print_long(list):
if len(list) > 6:
print (i)
else:
return None
but that is clearly wrong since it infinitely loops it. Or it seems to appear to do that.
help.
Your code appears to be a recursive call with no base (terminating) condition. That is, when you first call print_long() you are immediately calling print_long(), which calls print_long() ad infinitum.
The code you were probably attempting is something like:
def greater_than(mylist, n):
for item in mylist:
if len(item) > n:
print item
mylist = ["hello", "foo", "bar", "testing", "world"]
greater_than(mylist, 4) # Prints: hello, testing, world
Or, more simply:
mylist = ["hello", . . ., "world"] # Same as above
n = 4
[x for x in mylist if len(x) > n] # ['hello', 'testing', 'world']
I think this is what you are trying to do:
def print_long(in_list): # define your function
for i in in_list: # loop over the input list
if len(i) > 6: # test the length of the elements
print (i) # if true print it out
else: # you don't need this else, as you really just want
pass # to do nothing if len(i) < 6
Name your parameter something other than list. Jonathon Reinhart gave a good suggestion: mylist.
The other code examples above also provide good suggestions for writing your for loop better:
for i in mylist:
You might also need to change the len() to => 6.
if len(i) >= 6
From what you wrote, it look says, "prints out each string in list that has a length greater than or equal to 6." So you'll need the equal to make sure you capture lengths equal to 6
A short one:
def print_greater_or_equal_than(mylist, n):
print '\n'.join(filter(lambda i: len(i) >= n, mylist))
You are making a recursive call to your function without reducing your list input, first. Therefore, it will continue to make recursive calls to infinity.
To avoid the infinite stack of recursion, print the item in the list & remove it before recursing :
def print_long(list):
i = list.pop(0)
if len(list) > 6:
print (i)
else:
return None
if len(list):
print_long(list)
First, list is a reserved keyword in Python, so don't use it as a parameter or variable name. I usually use lst. Anyway, there are a few other issues to work out here.
def print_long(lst):
for i in lst:
if len(i) >= 6:
print i
print_long(['foo','bar','hello','johnny'])
Before, you were trying to iterate through your function:
for i in print_long(lst)
This is incorrect, you simply want to iterate through the list, as shown in the first example above. A more pythonic way of achieving the result you are looking for is:
print ' '.join([i for i in lst if len(i) >= 6])
Look up Python list comprehensions if you don't understand.

Categories