Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a list of integers for example: [30,21,32,32,41,20,21,32,21,20]
I have a variable of X, X has a value within the range of the list.
How can I find the sum of all the elements in the list to the number of X.
For example if x was 4 I would want: 30+21+32+32
Another way to go is to use the takewhile function from itertools:
>>> import itertools
>>> sum(itertools.takewhile(lambda x: x<5, range(10)))
10
In your case:
>>> l = [1,2,3,4,5,6,7,8,9]
>>> x = 5
>>> sum(itertools.takewhile(lambda i: i < x, l))
10
if you want till the 5th element, maybe use enumerate and zip:
>>> sum(zip(*(itertools.takewhile(lambda i: i[0]<x-1, enumerate(l))))[1])
10
If you're a beginner, you should learn that the common way to carry out a task is to define a function
A function needs a name and usually needs one or more arguments, in this example sum_until is the name and l and n are the arguments.
Following the definition, there is some code that does the task for generical values of l and n. Eventually the function returns the result of the computation, here the statement return sum.
Note the commented # return sum at the end of the function definition. You should try to control what to do in exceptional cases, here what we want to do when n is not found into l. One option is to return the sum of all the numbers in l, another one is to return a value that is impossible for a summation, and the second one is exactly my choice.
def sum_until(l,n):
"returns the sum of the numbers in l that occur before the appearance of n"
sum = 0:
for num in l:
if num == n:
return sum
sum = sum + num
# return sum
return None
Now, we have to use the function. This is achieved calling the function, that is you call its name and tell it on which actual values you need to operate the sum:
print(sum_until([2,4,6,8,5,10,12], 5))
print(sum_until([2,4,6,8,5,10,12], 3))
Output
20
None
If you want to sum the x first elements:
>>> l = [1,2,3,4,5,6,7,8,9]
>>> x = 5
>>> result = sum(l[:x])
>>> result
15
My answer may be not efficient, but I it is very straightforward.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 months ago.
Improve this question
My teacher gave me an exercise during the computing lesson in week 2:
Write a Python program to create and print a list where the values are first N square of numbers. You are REQUIRED to implement a function named printSquare() to take n where n is an positive integer.
I'mm trying to writing a function called printSquare().
for example, the expected output of printSquare(5) is [1, 4, 9, 16, 25].
def getList(num):
list=[]
for i in range(int(num)):
list.append(i)
return list
def printSquare(num):
wholeList = list(getList(num))
wholeList.pop(0)
wholeList.append(num)
tmp=[]
for i in wholeList:
x = wholeList[i]**2
tmp.append(x)
return tmp
printSquare(5)
I'm struggling in the following part, I don't know why the tmp.append(x) doesn't work.
for i in wholeList:
x = wholeList[i]**2
tmp.append(x)
return tmp
The second question is that is there any faster way to write this code.
There are couple of mistakes and lack of understanding in the code. Let me try and explain mistakes and lack of understanding i found.
you are using range(num) which will give you a list from 0 to num-1. Hence you do wholeList.pop(0) to remove 0 from the list and wholeList.append(num) to then add the last num in.
Instead of that, you can do
range(1,int(num)+1)
This will return you a list from 1 to number, solving both the issue, and not needing to pop and add extra number to list
secondly
for i in wholeList:
x = wholeList[i]**2
That is not how looping over list works
for i in wholeList:
Will return you the element of the list, not its index. Here you are assuming i is the index of elements in list. So wholeList[i]**2 is where your code fails, since you try to access elements at index position that does not exist.
If you want to get index position you have to do
for index, value in enumerate(wholeList):
This will return you the index, and the value associated with the index in the list.
I hope, all of that helped you understand things better. Here is a code that works
def getList(num):
list=[]
for i in range(1,int(num)+1):
list.append(i)
return list
def printSquare(num):
wholeList = getList(num)
tmp=[]
for i in wholeList:
tmp.append(i**2)
return tmp
printSquare(5)
If you look at the error message it states that IndexError: list index out of range meaning that the index isn't in the range of your list. What you could do is try to use the range function over the length of the list: for i in range(1, len(wholeList)), this ensures that the index is always within the range.
when you use for..in you are directly getting elements, not indexes. So to solve the problem write
for i in wholeList:
x = i**2
tmp.append(x)
return tmp
Also, you can write this way more clearly with list comprehensions (and it is a nice tool to have)
def get_list(n):
return [i**2 for i in range(1, n+1)]
You have made this far more complicated than it really is. You can (should) use a list comprehension thus:
def printSquare(n):
print([x*x for x in range(1, n+1)])
printSquare(5)
Output:
[1, 4, 9, 16, 25]
The i in the for loop is the value, not the index. You should either write x=i**2, or in the for loop you should specify it differently:
for i, value in enumerate(wholeList):
x = value**2
tmp.append(x)
The tmp list now includes the square values of the wholeList.
Also, you are not printing anything somewhere.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 months ago.
Improve this question
The following code snippet takes two numbers from the user. Each number is made from digits 0 or 1. The program should write a new number corresponding to the given pair of numbers. The rule is simple: The i-th digit of the answer is 1 if and only if the i-th digit of the two given numbers differ. In the other case the i-th digit of the answer is 0.
This was my approach to solving the problem which gives me the desired output:
s1 = input()
s2 = input()
s = ''
for i in range(len(s1)):
if s1[i] != s2[i]:
s += '1'
else:
s += '0'
print(s)
This one-line approach is producing the same output, and I am just curious to know how it is doing so but couldn't figure it out. So here I am on Stackoverflow.
i=input;print(''.join('01'[a!=b]for a,b in zip(i(),i())))
Explained step by step:
i=input - storing the function in i to be called later
zip(i(),i()) - if the user entered 1010 and 1101, this would return [(1, 1), (0, 1), (1, 0), (0, 1)] - the elements of both strings paired up
for a,b in - a and b are the pair from the zip (in the example they are first set to a=1 and b=1, then a=0 and b=1, etc.)
'01'[a!=b] - a!=b will return a boolean - either True or False. True = 1 and False = 0 so you can use this for indexing. Basically this says if a!=b: '1', if a==b: '0'
''.join - finally, join all the '0's and '1's together to make one string and print
If you really want to make it a oneliner, remove the semicolon and do it like this:
print(''.join('01'[a!=b] for a, b in zip(input(), input())))
Python will ask the user for two input strings
zip creates an iterable with tuples, so "hi" and "ho" will become [(h,h), (i,o)]
in the list comprehension, you've got a string '01' that can be indexed with either 0 or 1
that is what your expression [a!=b] does, it evaluates to either True (1) or False (0)
because you loop over all tuples, this happens for every character in your input strings
finally, ''.join concatenates all elements in your list, and this gets printed
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I got stuck by finding out how to build a recursive function
that sums the elements in a list form a specific starting point
to the end of the list.
for example when list a[1,2,3,4,5,6,7,8,9,10] and starting point is Index 5
I want to get the sum of 6+7+8+9+10.
For me it is quite difficult to understand the whole concept of recursive functions. Maybe you can help me to get a step further understanding the concept.
Many thanks in advance
Define a function that normally computes the sum recursively.
To compute sum of a subsequence of a list, use list slicing.
def recsum(num_list):
if len(num_list) == 0:
return 0
return num_list[0] + recsum(num_list[1:])
a = [1,2,3,4,5]
recsum(a)
>>> 15
# It means 1+2+3+4+5
recsum(a[1:])
>>> 14
# It means 2+3+4+5
recsum(a[2:4])
>>> 7
# It means 3+4
It's difficult to describe a recursive function in short. Please read the comments carefully.
my_recursive_function will take the list and the index from which I want to calculate the sum
If the index==list_length then I already traversed the list so in this case I shall return 0.
If I have not completed traversing the list then I shall take the value of that index call my_recursive_function again from the next index. This is where recursion starts.
Then return the sum of current index and value of next indices.
For recursion we should place the recursion braking condition at the first portion of the function.Otherwise it may run infinitely.
def my_recursive_sum(my_list, index):
list_length = len(my_list)
if index == list_length: # If i am next to the last element then return 0 and I won't go next and I shall go back
return 0
return my_list[index] + my_recursive_sum(my_list, index + 1) # value of current index+value of next indices.
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = my_recursive_sum(a, 3)
print(result)
this is how I interpreted the code delivered by Taohidul Islam:
might be right?
recursion
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 years ago.
Improve this question
I have this code , and it is not mine , I saw it online and i am wondering how is the recursion working , can someone please explain !
(this function accepts a list of integers(distances) and a value 'r' lets say 10) and it returns all the possibilities of how we can reach 100 using the distances) lets say the list is [3,5,2,5] and the value r is 10 ! so to make 10 we need [5,5] or [3,2,5] ,this is the code:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for last_distance in d:
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions
i hope i made my self clear
I'd suggest using python print function
print("")
At multiple locations to actually see the recursion happening. You would get a better idea than someone trying to explain it to you.
Although the function itself is quite simple. For every element in distances, the function subtracts the element from the required r value and checks the value with the if conditions.
If r value is zero ie, the for some elements in distance, their sum is r, a multi list is returned, which furthermore has the said elements.
At the end, the complete list of elements whose sum adds to r are appended to solution list and returned.
Say that given a list distances0 of length n, you are able to return all tuples i1,..,infrom the list that sums to a number r for any number r.
You would like to do the same for a list distances of length n+1.
Since you know how to solve the problem for a list of size n, you will do the following: for every element last_distance of distances, return all tuples i1,...,in that sums to r-last_distance from a list distances0 which is similar to distances but without the element last_distance (and hence of length n).
I think there might be some mistakes in the code, here should be a working version:
def greedy(r, distances):
if r < 0:
return []
if r == 0:
return [[]]
solutions = []
for i in range(len(distances)):
d = distances[:i]+distances[i+1:]
last_distance = distances[i]
combos = greedy(r - last_distance, d)
for combo in combos:
combo.append(last_distance)
if(not solutions.__contains__(combo)):
solutions.append(combo)
return solutions
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions must demonstrate a minimal understanding of the problem being solved. Tell us what you've tried to do, why it didn't work, and how it should work. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
Write a function called squares that takes in a parameter named n. If n is a positive integer, the function returns a list consisting of the squares of the numbers from 1 through n. Otherwise (i.e., if n is not a positive integer) the function should return an empty list.
This function to work correctly even if the function is called with nonsensical arguments. In other words, function calls such as squares('Iowa'), squares(range(10)), and squares([1, 2, 3]) should return an empty list.
def sqrt(x):
ans = 0
if x >= 0:
while ans*ans < x:
ans+=1
if ans *ans == x:return ans;
return -1;
def square(n):
i=0
blist= []
ans = list(range(1, n ))
if (n < 0):
return blist
if isinstance(ans, str):
return blist
while( i < len(ans)):
if(sqrt(ans[i])!= -1):
blist.append(ans[i])
i = i+1
return blist
i = square('boy')
print(i)
To define a function, you do
def squares(n): # Where n is the parameter/argument
To check if n is an integer or a string (like Iowa) or a list (like range(10)), use isinstance (Hint: the function returns True or False). Use an if/else statement here to determine the function either returns an empty list [] or to continue:
Use another if/else statement to determine whether a number is positive or negative (if it's bigger than 0 it's positive, else it's negative)
To get the squares of a number, well, how would you figure out what two squared is? Or three squared?
**
You can then use a list comprehension to get the squares of every number between one and n (but how would you get a list of numbers between one and n? You'll need a range or something)
Don't forget to return the items ;)