What would be the simplest way to get the next value based on a sorted list?
Sorted list with unique numbers:
If the number n is not found in the list, return n+1,
if is found, find in the last number that does not breaks an incremental sequence, return num+1.
num=1, for the list [1,2,3,6] would return 4.
num=10, for the list [1,2,3,6] would return 11.
num=5, for the list [1,2,3,6] would return 7.
I tough about a recursive call, something like:
def nextn(num,listnums):
if(num not in listnums): return num+1
return nextn(num+1,listnums)
listnums=[1,2,3,6]
n=1
nn = nextn(n,listnums)
print("n=%d nn=%d" %(n,nn))
Your if-statement is wrong, it is according to your text but not according to your examples.
I found, reversing the if is easier to understand:
def nextn(num,listnums):
if (num+1 in listnums):
return nextn(num+1,listnums)
else:
return num+1
listnums=[1,2,4]
for n in range(10):
print("n=%d nn=%d" %(n, nextn(n, listnums)))
Related
def find_highest(lst):
if lst[0] < lst[-1]:
return find_highest(lst.pop(0))
elif lst[0] > lst[-1]:
return find_highest(lst.pop())
else: return lst
This code raises TypeError.
Can anyone tell why is this happening?
You code has the problem that it will raise IndexError. You are pulling elements out of the list using pop, so at some point the list will be empty.
You should check for the list length.
Here you have the solution using a different approach - I still use pop but always on the same end of the list. -
def find_largest(target_list):
# If the len of list is 0, we have consume all numbers.
if len(target_list) == 0:
return None
# Just get a number from the list, no matter which ...
number = target_list.pop()
# ... then recursively call the function to get the largest among the
# remaining numbers in the list.
largest = find_largest(target_list)
# Compare the number you pull out the list with the "largest" of the remaining and
# keep the largest.
if largest is None or number >= largest :
return number
return largest
if __name__ == "__main__":
import random
target_list = [random.randint(0, 10) for i in range(10)]
print(f"Target list: {target_list}")
largest = find_largest(target_list)
print(f"Largest number: {largest}")
The positive_numbers function should return a list containing numbers that are non-negative (>=0).
However, currently, it returns only the [3] instead of a list of values.
I tried different ways to make this work I'm currently a beginner in python and I don't have anyone to ask that's why I'm sorry if this is too basic for you just want to learn and see my mistake
def positive_numbers(numbers):
for number in numbers:
result = []
result = result + [number]
if number < 0:
continue
return result
Expected: The function should return a list of numbers
Actual: returns list with the only value being 3
Error: The call positive_numbers([1, 2, 3]) should return [1, 2, 3], but it returned [3]
You reset the list each iteration of the loop because of result = [].
Try this:
def positive_numbers(numbers):
result = []
for number in numbers:
if number > 0:
result = result + [number]
return result
Also, debugging would make this very clear. Try to debug your code to get a better understanding of it.
You have to declare result outside of your for loop.
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result.append(number)
return result
As already stated, you are setting results no a new empty string at every iteration of your for loop. Also, the if statement does not make any change, since by the time is evaluated, the new number is appended to the result.
So the minimal working change is:
def positive_numbers(numbers):
result = []
for number in numbers:
if number 0:
continue
result = result + [number]
return result
Besides, note that you could use a list comprehension for that:
positive_numbers = [number for number in numbers if number >= 0]
Or using filter:
positive_numbers = list(filter(lambda num: num>=0, numbers))
Note that in the latter case, if you don't need your output to be a list but an iterable, you can remove the list(...) part
You have all of the pieces, just not necessarily in the right order. Here is an amended version:
def positive_numbers(numbers):
result = []
for number in numbers:
if number < 0:
continue
result = result + [number]
return result
With result = [] inside the for loop as you had it, you were emptying the result on each iteration. Then you were unconditionally adding the number to the list instead of checking if it is negative first. In this amended first, the loop skips to the next number if the current number is not non-negative.
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)
I need help creating a list of iterated values. In this example, I want to get all odd numbers in the range of x. Then make a list from it:
def x_list(x):
for i in range(x):
if x%2==0:
return i
Since return stops the function after iterating through the first object, I'm unable to get the rest of the values and create a list from it.
Could you advice what I should use instead of "return"?
Thank you.
If you use yield instead of return, then you should be able to iterate through the whole range. This example will print out the even numbers.
def x_list(x):
for i in range(x):
if i%2==1:
yield i
for n in x_list(10):
print(n)
I also assume you want if i%2==1: not if x%2==0:, otherwise you'll get every number instead of just the odd ones.
Based on hop's suggestion, you could also do this:
evens = range(0, 10, 2)
for n in evens:
print(n)
Where the 3rd parameter in range is the step size
Define ret as a list at the top of the function, fill it within the loop.
After the loop ends, return it.
def x_list(x):
ret = []
for i in range(x):
if i%2==0:
ret.append(i)
return ret
With range, you can specify a stepping.
Therefore, all you need to do is:
def oddlist(x):
return list(range(1, x, 2))
If you don't actually need a list, and just an iterable will do, you could omit the list generation:
def oddlist(x):
return range(1, x, 2)
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!