I am trying to find the sum of the list in python; I have written a custom function and it is given below, I am facing a syntax error. How to overcome this
def summation(list):
j=0
for i in list:
sum=j+list[i]
return j=sum
k=[10,20,30]
summation(k)
You are using a Python Keyword as a variable name
try this
def summation(_list):
sum=0
for i in _list:
sum += i
return sum
k=[10,20,30]
summation(k)
a better solution would be this, use the builtin sum function, it is much faster than a loop
def summation(_list):
return sum(_list)
k=[10,20,30]
summation(k)
First of all, you should never use built in keywords like list or sum. This will shadow your code. Next, your for loop has a problem. You are iterating from the values in the list, and not the element index. Hence, it will give you an error.
def summation(list1):
j=0
for i in range(len(list1)):
sum1=j+list1[i]
return sum1
k=[10,20,30]
print(summation(k))
I suggest you should go with the built-in sum fucntion.
def summation(list1):
return sum(list1)
k=[10,20,30]
print(summation(k))
First of all, your code returns right after the first iteration of the for loop and returns an assignment which is invalid. This is what you needed:
def summation(list):
sum=0
for i in list:
sum += i
return sum
k=[10,20,30]
summation(k)
It would be better to name the variables differently, but this will work. Also a for loop in python doesn't iterate over indexes, it iterates over items. This means that when you say for i in list:, you get values 10, 20, 30 for your case, not 0, 1, 2 (the indexes). To get the indexes, use for i in range(len(list)):.
Related
Sorry if I'm asking a stupid question.
So I'm studying Python and my homework is to find the lowest and highest number from list and then insert it into a tuple.
Right now this is the code I have (highlighted is my code):
import random
**def minimum_maximum(integer_list):
l.sort()
l = [l[0], l[-1]]
minimum_maximum = tuple(l)**
l = []
for i in range(random.randint(15,25)):
l.append(random.randint(-150,150))
print ("List:", l)
print ("Minimum and maximum:",minimum_maximum(l))
I can edit only the highlighted code. Right now the problem is "local variable 'l' referenced before assignment" which I tried to google, but I simply don't understand how to fix this. How can I make this work?
In your function, the input parameter is integer_list but you use l that is undefined:
def minimum_maximum(integer_list):
l.sort()
l = [l[0], l[-1]]
minimum_maximum = tuple(l)
Corrected version:
def minimum_maximum(integer_list):
l = sorted(integer_list) # using `sorted` to create a copy
return (l[0], l[-1]) # returning the tuple directly
NB. note that sorting the full list is not the most efficient method (although probably the shortest code). Ideally you should loop over the elements once and update the minimum and maximum as you go
A couple of problems:
Your function receives the parameter integer_list but instead of using it, you're using l.
You're trying to assign the result to a variable that is named the same way the function is (minimum_maximum). Instead just return the result.
Just for clarity, you can immediately return (integer_list[0], integer_list[-1])
You can use the min() and max() functions, which return the lowest and highest values of your list respectively:
def maximum_minimum(integer_list):
return (min(integer_list), max(integer_list))
So i'm studying recursion and have to write some codes using no loops
For a part of my code I want to check if I can sum up a subset of a list to a specific number, and if so return the indexes of those numbers on the list.
For example, if the list is [5,40,20,20,20] and i send it with the number 60, i want my output to be [1,2] since 40+20=60.
In case I can't get to the number, the output should be an empty list.
I started with
def find_sum(num,lst,i,sub_lst_sum,index_lst):
if num == sub_lst_sum:
return index_lst
if i == len(sum): ## finished going over the list without getting to the sum
return []
if sub_lst_sum+lst[i] > num:
return find_sum(num,lst,i+1,sub_lst_sum,index_lst)
return ?..
index_lst = find_sum(60,[5,40,20,20,20],0,0,[])
num is the number i want to sum up to,
lst is the list of numbers
the last return should go over both the option that I count the current number in the list and not counting it.. (otherwise in the example it will take the five and there will be no solution).
I'm not sure how to do this..
Here's a hint. Perhaps the simplest way to go about it is to consider the following inductive reasoning to guide your recursion.
If
index_list = find_sum(num,lst,i+1)
Then
index_list = find_sum(num,lst,i)
That is, if a list of indices can be use to construct a sum num using elements from position i+1 onwards, then it is also a solution when using elements from position i onwards. That much should be clear. The second piece of inductive reasoning is,
If
index_list = find_sum(num-lst[i],lst,i+1)
Then
[i]+index_list = find_sum(num,lst,i)
That is, if a list of indices can be used to return a sum num-lst[i] using elements from position i+1 onwards, then you can use it to build a list of indices whose respective elements sum is num by appending i.
These two bits of inductive reasoning can be translated into two recursive calls to solve the problem. Also the first one I wrote should be used for the second recursive call and not the first (question: why?).
Also you might want to rethink using empty list for the base case where there is no solution. That can work, but your returning as a solution a list that is not a solution. In python I think None would be a the standard idiomatic choice (but you might want to double check that with someone more well-versed in python than me).
Fill in the blanks
def find_sum(num,lst,i):
if num == 0 :
return []
elif i == len(lst) :
return None
else :
ixs = find_sum(???,lst,i+1)
if ixs != None :
return ???
else :
return find_sum(???,lst,i+1)
I am trying to implement an incrementation to a previously defined variable called sum.
return [sum = sum + number for number in range(a,b)]
Of course this format brings up error but using the similar:
return [sum = number for number in range(a,b)]
The code is faulty but runs. If there's a way to implement it and return sum the code would work.
And also if someone could inform me about the nomenclature I'd forever be grateful.
Here are a few possible answers. What you are using is called a list comprehension.
s += (b*(b-1) - a*(a-1))//2
s += sum([n for n in range(a,b)])
for n in range(a,b):
s += n
It's not a good idea to name a variable sum as it is a built in Python function.
Try the following:
return sum([number for number in range(a,b)])
As said in the commentaries, sum is a python built-in function which, given an array, it returns the result of the addtion of all elements in it
You essentially reimplemented the built-in function sum. Just call the function directly:
return sum(range(a, b))
Please tell me why this sort function for Python isnt working :)
def sort(list):
if len(list)==0:
return list
elif len(list)==1:
return list
else:
for b in range(1,len(list)):
if list[b-1]>list[b]:
print (list[b-1])
hold = list[b-1]
list[b-1]=list[b]
list[b] = hold
a = [1,2,13,131,1,3,4]
print (sort(a))
It looks like you're attempting to implement a neighbor-sort algorithm. You need to repeat the loop N times. Since you only loop through the array once, you end up with the largest element being in its place (i.e., in the last index), but the rest is left unsorted.
You could debug your algorithm on your own, using pdb.
Or, you could use python's built-in sorting.
Lets take a look at you code. Sort is a built in Python function (at least I believe it is the same for both 2.7 and 3.X) So when you are making your own functions try to stay away from name that function with inbuilt functions unless you are going to override them (Which is a whole different topic.) This idea also applies to the parameter that you used. list is a type in the python language AKA you will not be able to use that variable name. Now for some work on your code after you change all the variables and etc...
When you are going through your function you only will swap is the 2 selected elements are next to each other when needed. This will not work with all list combinations. You have to be able to check that the current i that you are at is in the correct place. So if the end element is the lowest in the List then you have to have it swap all the way to the front of the list. There are many ways of sorting (ie. Quick sort, MergeSort,Bubble Sort) and this isnt the best way... :) Here is some help:
def sortThis(L):
if (len(L) == 0 or len(L) == 1):
return list
else:
for i in range(len(L)):
value = L[i]
j = i - 1
while (j >= 0) and (L[j] > value):
L[j+1] = L[j]
j -= 1
L[j+1] = value
a = [1,2,13,131,1,3,4]
sortThis(a)
print a
Take a look at this for more sorting Fun: QuickSort MergeSort
If it works, it would be the best sorting algotithm in the world (O(n)). Your algorithm only puts the greatest element at the end of the list. you have to apply recursively your function to list[:-1].
You should not use python reserved words
The input (list) would be a list similar to [[1,2],[5,6],[4,6]]. I am trying to add the whole row together to test if it is even or odd.
def evenrow(list):
for row in list:
for item in row:
newNums+=item
n=sum(newNums)
print(n)
First of all do not use 'list' as variable name. Second you calling sum for int value not for a list and that's why you getting error. Check your code please.
Not sure but your code can looks like:
def evenrow(list):
for row in list:
value = sum(row)
if values is even: # put your condition here
# do something
else:
print "Value is odd"
Just an alternate method:
def evenrow(lst):
return sum(map(sum,lst))%2 == 0 #True if even, False otherwise.
This works this way:
The outer sum adds up all items of the map, which applies sum to each item in lst. In python2, map returns a list object, while in python3, it returns a map object. This is passed to the outer sum function, which adds up all items in your map.
def evenrow(lst):
return sum(itertools.chain(*a)) % 2 == 0
This expands all the items in a (each of the sublists), and chains them together, as a chain object. It then adds together all the items and determines if the sum is even.
You don't need the following line of code: n=sum(newNums). You already summed up all the items of row in the newNums += item line. Second, you have to declare newNums before using it in your code. So, the fixed version of code will look like this:
def evenrow(list):
for row in list:
newNums = 0
for item in row:
newNums += item
print(newNums)
BTW: You should consider accepting answers to some of your previous questions, otherwise nobody will spend their time to answer your new questions.