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}")
I have a function that is to take a list as an argument and add the highest and next highest integers in said list and then append it to a new list. Here is my attempt at it. I believe there should be some recursion or looping at some point but I am not too sure. Any pointers will be appreciated.
#1. Defining the function:
def function_name(list_to_accept):
#2. Checking that the list_to_accept is a list:
if type(list_to_accept) != list:
raise TypeError ('function argument is not a list')
else:
#3.this confirms entry is a list, now check that it's not an empty list
if len(list_to_accept) == 0:
raise TypeError ('the list you entered is empty')
else:
#4. check that the elements in the list are integers
for integers in list_to_accept:
if type(integers) != int:
raise TypeError ('element is not an integer')
#5.the addition that's required takes place here.
addition_list = []
clone_list_to_accept = []
#6.find max(list_to_accept), its index value, pop it out and append to clone list, save it in a variable.
highest = max(list_to_accept)
list_to_accept.remove(highest)
clone_list_to_accept.append(highest)
# 7.find the next highest and repeat the move above
next_highest = max(list_to_accept)
list_to_accept.remove(next_highest)
clone_list_to_accept.append(next_highest)
#8. sum the two highest integers
integer_sum = highest + next_highest
#9. append to addition_list
addition_list.append(integer_sum)
print (clone_list_to_accept)
print (addition_list)
integer_list = [1, 2, 3, 4, 5]
function_name(integer_list)
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)))
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!
I am new to Python and need some help writing a function that takes a list as an argument.
I want a user to be able to enter a list of numbers (e.g., [1,2,3,4,5]), and then have my program sum the elements of the list. However, I want to sum the elements using a for loop, not just by using the built in sum function.
My problem is that I don't know how to tell the interpreter that the user is entering a list. When I use this code:
def sum(list):
It doesn't work because the interpreter wants just ONE element that is taken from sum, but I want to enter a list, not just one element. I tried using list.append(..), but couldn't get that to work the way I want.
Thanks in anticipation!
EDIT: I am looking for something like this (thanks, "irrenhaus"):
def listsum(list):
ret=0
for i in list:
ret += i
return ret
# The test case:
print listsum([2,3,4]) # Should output 9.
I'm not sure how you're building your "user entered list." Are you using a loop? Is it a pure input? Are you reading from JSON or pickle? That's the big unknown.
Let's say you're trying to get them to enter comma-separated values, just for the sake of having an answer.
# ASSUMING PYTHON3
user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number
def sum(lst):
accumulator = 0
for element in lst:
accumulator += element
return accumulator
The top three lines are kind of ugly. You can combine them:
user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))
But that's kind of ugly too. How about:
raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
processed_in = map(float, raw_in)
# if you specifically need this as a list, you'll have to do `list(map(...))`
# but map objects are iterable so...
except ValueError:
# not all values were numbers, so handle it
The for loop in Python is exceptionally easy to use. For your application, something like this works:
def listsum(list):
ret=0
for i in list:
ret+=i
return ret
# the test case:
print listsum([2,3,4])
# will then output 9
Edit: Aye, I am slow. The other answer is probably way more helpful. ;)
This will work for python 3.x, It is similar to the Adam Smith solution
list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
try:
value = int(value) #Check if it is number
except:
continue
total += value
print(total)
You can even write a function that can sum elements in nested list within a list. For example it can sum [1, 2, [1, 2, [1, 2]]]
def my_sum(args):
sum = 0
for arg in args:
if isinstance(arg, (list, tuple)):
sum += my_sum(arg)
elif isinstance(arg, int):
sum += arg
else:
raise TypeError("unsupported object of type: {}".format(type(arg)))
return sum
for my_sum([1, 2, [1, 2, [1, 2]]])
the output will be 9.
If you used standard buildin function sum for this task it would raise an TypeError.
This is a somewhat slow version but it works wonders
# option 1
def sumP(x):
total = 0
for i in range(0,len(x)):
total = total + x[i]
return(total)
# option 2
def listsum(numList):
if len(numList) == 1:
return numList[0]
else:
return numList[0] + listsum(numList[1:])
sumP([2,3,4]),listsum([2,3,4])
This should work nicely
user_input = input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")
print ("The list of numbers entered by user:" user_list)
ds = 0
for i in user_list:
ds += int(i)
print("sum = ", ds)
}
Using accumulator function which initializes accumulator variable(runTotal) with a value of 0:
def sumTo(n):
runTotal=0
for i in range(n+1):
runTotal=runTotal+i
return runTotal
print sumTo(15)
#outputs 120
If you are using Python 3.0.1 or above version then use below code for Summing list of numbers / integer using reduce
from functools import reduce
from operator import add
def sumList(list):
return reduce(add, list)
def oper_all(arr, oper):
sumlist=0
for x in arr:
sumlist+=x
return sumlist
Here the function addelements accept list and return sum of all elements in that list only if the parameter passed to function addelements is list and all the elements in that list are integers. Otherwise function will return message "Not a list or list does not have all the integer elements"
def addelements(l):
if all(isinstance(item,int) for item in l) and isinstance(l,list):
add=0
for j in l:
add+=j
return add
return 'Not a list or list does not have all the integer elements'
if __name__=="__main__":
l=[i for i in range(1,10)]
# l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
print addelements(l)
Output:
45
import math
#get your imput and evalute for non numbers
test = (1,2,3,4)
print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why?
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)]
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33