how to print only the total after computing? - python

I'm trying to write a code that would add the total of all the values from 0 to 100 and printing only the total after computing with any loop structure.
For another one I did it was short so I did this
def listsum(numList):
iSum = 0
for i in numList:
iSum = iSum + i
return iSum
print(listsum([1,2,3,4,5,6,7,8,9,10]))
but 0 to 100 is too much ,, is there another way?

Use a range:
print(listsum(list(range(101))))

Using range:
def listsum(numList):
iSum = 0
for i in range(1, numList+1):
iSum += i
return iSum
You would just pass the max value that you want the count up to (e.g. print(listsum(100))).

The built-in sum() function gives the total value of all numbers in a list, so your listsum() function is not needed.
list(range(101)) gives you a list of all numbers from 1-100 (inclusive)
Putting those together you get
print(sum(list(range(101))))
Which adds the total of all the values from 0 to 100
The range function is much more powerful than this, here's a good reference for using it it's something you really need to know how to use well!

Related

How do i sum from one to million using min,max,and sum? (in loop)

the question: Make a list of the numbers from one to one million, and then use
min() and max() to make sure your list actually starts at one and ends at one million. Also, use
the sum() function to see how quickly Python can add a million numbers.
So here's my initial code, I do not know how to use min max or sum in this case:
one_million = []
for numbers in range(0,1000000):
counting = numbers+1
one_million.append(counting)
print(one_million)
Do it step by step.
Make a list of the numbers from one to one million
numbers = list(range(1, 1000000 + 1)) # add 1 to upper bound since range is inclusive-exclusive
and then use min() and max() to make sure your list actually starts at one and ends at one million
assert min(numbers) == 1
assert max(numbers) == 1000000
Also, use the sum() function to see how quickly python can add a million numbers
total = sum(numbers)
print(total)
range supports min, max and sum, so you don't need any loop to do this:
numbers = range(1,1000001) #Note that range gives you a number UP TO the last number
print(max(numbers))
print(min(numbers))
print(sum(numbers))
Easy
million = [n for n in range(0, 1000000 + 1)]
million_sum = sum(million)
print(million_sum)
assert min(numbers) == 1
assert max(numbers) == 1000000
I'm assuming you're doing the Python Crash Course book because this is project 4-5. I came across your post while I was looking for documentation on min and max. I thought it was great to see someone else working on the same problem so I thought I would share my code. I came up with this:
million_list = []
for num in range(1,1_000_001):
million_list.append(num)
print(min(million_list))
print(max(million_list))
print(sum(million_list))
JeffUK's answer is nice. Thanks for the info about range not requiring a for loop.
numbers = list(range(1,1000001))
print(min(numbers))
print(max(numbers))
print(sum(numbers))
#also reading the book!

Python sorting arrays to get two digit values

I have an array A = [1 - 100] and I need to find the sum of all the two digit values in this array. How would I approach this? I have tried :
def solution(A):
A =array[0-100])
while A > 9 & A < 99
total = sum(A)
print "%s" % total
)
Is there a function that given an array consisting of N integers returns the sum of all two digit numbers i.e A = [1,1000,80, -91] the function should return -11(as the two are 80 and -91). not a range, multiple array
You can use a list comprehension and check if the length of the string-format is equal to 2, like so:
sum([x if len(str(x))==2 else 0 for x in xrange(1,101)])
Use the keyword and rather than the bitwise &.
Edit: a fuller answer, as that's not the only thing wrong:
def solution():
A = range(101)
total = sum([a for a in A if 9 < a <= 99])
print total
This uses list comprehension and chained inequalities, so is pretty 'pythonic'.
There is tons of errors in your code, please next time before posting,spend some time try to figure it out yourself and be sure that your code at lest doesn't contain any obvious syntax error.
By array, I assume you're talking about a list. And change it to range(101) for every number from 0 to 100
def solution(A):
return sum([x for x in range(A) if len(str(abs(x))) == 2])
print(solution(101))
As a side note, use and instead of & since that's a bitwise-or sign.
Here are a couple of ways to go about the problem, the first is most similar to the approach you appear to be trying:
def solution1(array):
total = 0
for a in array:
if 9 < a < 100:
total += a
return total
print(solution1(range(101)))
And here's a more compact solution using a comprehension (actually, a generator expression):
def solution2(array):
return sum(a for a in array if 9 < a < 100)
print(solution2(range(101)))
Note that in your original you're confusing loops and conditionals.

How can I Improve this Code, using While Loop?

Create a function addNumbers(x) that takes a number as an argument and adds all the integers between 1 and the number (inclusive) and returns the total number.
Examples :
addNumbers(10)
55
addNumbers(1)
1
So this is a question, I have done using while loop , and it worked fine. But I am not satisfied with my code, I also did this problem using for loop and that's okay for me, but I want to know what could be the best way to improve dis code using while loop.
def addNumbers(num):
total = 1
i = 1
while i < num:
i += 1
total += i
return total
print addNumbers(10)
And here is my for loop answer :
def addNumbers(num):
my_list = list(range(num+1) )
for i in my_list:
my_list.append(i)
return sum(my_list)
If you want an O(1) algorithm that isn't brute-force, you can use Gauss's method:
def sum_numbers(n):
return (n+1)*n//2
Usually SO isn't the place for such questions, but anyway..
You can use sum() and range(). range() will return a list of numbers from 0 to n and sum will, well, sum it.
def sumNumbers(n):
return sum(range(n+1))
EDIT: And using while loop:
def sumNumbers(n):
i = 0
sum = 0
while i <= n:
sum += i
i += 1
return sum
Make use of numpy's sum routine and a generator like so,
import numpy as np
maxNumber = 10
sumOfNumbers = np.sum([(x) for x in xrange(1, maxNumber+1)])
print sumOfNumbers
The generator gives you the list of numbers & the routine adds them for you.

Python - explain function parameters

So I understand this simple for loop:
sum = 0
for number in {1,2,3,4}:
sum = sum + number
print sum
>>>
1
3
6
10
>>>
Then here is a neat little code that combines a for loop and a function I found on the interwebs:
def sum_list(l):
sum = 0
for number in l:
sum = sum + number
return sum
print sum_list([1, 7, 4])
>>>
12
What I don't understand is how python interprets this code (rather how Python knows to add the 3 arguments 1,7,4 together).
I would really help if you can break it down for me!
To tack on another question for you guys to review:
sum = 0
for number in {1,2,3,4}:
sum = sum + number
return sum
Spits out an error. print sum will list the results as 1,3,6,10
Error says: Syntaxerror: 'return' outside of function
[EDIT] #sshashank124
For example: This code spits out 3 answers. It prints out:
sum = 0
for number in {1,7,4}:
sum = sum + number
print sum
>>>
1
8
12
>>>
But this:
def sum_list(l):
sum= 0
for number in l:
sum = sum + number
print sum
print sum_list([1, 7, 4])
>>>
12
none
Spits out only 1 answer, 12. My question is why that occurs.
for number in l:
This iterates over the l, and number will have each and every element of l on every iteration. You can check that like this
for number in l:
print number
# 1
# 7
# 4
You are adding those numbers to the sum variable. You can check that like this
sum = 0
for number in l:
sum = sum + number
print sum
# 1
# 8
# 12
I believe you are doing this for educational purpose. If you actually wanted to find the sum of an iterable, then you can use the builtin sum function, like this
sum([1, 7, 4])
It knows to add them together, because you tell it to do that.
Let me rewrite the code a bit to show what's happening. Rewrite one, adding 1,7,4 and then 2,8,5, but adding more numbers requires more lines:
sum = 0
sum = sum + 1
sum = sum + 7
sum = sum + 4
print sum
sum = 0
sum = sum + 2
sum = sum + 8
sum = sum + 5
print sum
Rewrite two - using a loop. Two lines shorter, but it can now handle lists of more items - adding four, five, even ten numbers, without adding more lines of code, just by making the lists longer:
sum = 0
for number in [1,7,4]:
sum = sum + number
print sum
sum = 0
for number in [2,8,5]:
sum = sum + number
print sum
Rewrite three - moving the lists out of the loop. The code got longer again, but something interesting happened - see how the loop code is now identical both times:
myList = [1,7,4]
sum = 0
for number in myList:
sum = sum + number
print sum
myList = [2,8,5]
sum = 0
for number in myList:
sum = sum + number
print sum
Rewrite four - now it's identical, why does it have to be there twice? Can't we ... write it once, and use it twice? That way if we need to change it, we only have to change it in one place. Yes - make it a function and call the function:
def sum_list():
sum = 0
for number in myList:
sum = sum + number
print sum
myList = [1,7,4]
sum_list()
myList = [2,8,5]
sum_list()
Rewrite five - what's happening above works fine, because you called everything 'myList' it all works. But if you write bigger programs like that it gets messy fast - one myList could be several pages of code away from another, we'll tend to forget that something pages and pages away could be affecting things. So we humans can keep track of what's going on, we need to clearly and explicitly give the function something to work on, and not have it just reaching far away and pulling things out of the rest of the code.
def sum_list(working_list): # working_list is whatever the function gets
sum = 0 # by a different name
for number in working_list:
sum = sum + number
print sum
myList1 = [1,7,4]
sum_list(myList1)
myList2 = [2,8,5]
sum_list(myList2)
See in the above code, I've called them myList1 and myList2 - yet whatever you give to the function, the function sees it called 'working_list'. The names don't have to match.
But because sum_list has it's own name for whatever you give it, you don't have to have a name for what you give it. You can just give it a list directly without a name:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
print sum
sum_list([1,7,4])
sum_list([2,8,5])
The next move is, once you're feeding things into sum_list, sum_list is looking away and writing to the screen. We can't have that. For the sake of humans tracking what's happening, that's a bad idea - you want to give functions some work to do and have them give you back an answer. That way you know you can use them anytime you need, without worrying about them printing to the screen unexpectedly. That's where 'return' comes in:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
return sum
result = sum_list([1,7,4])
print result
result = sum_list([2,8,5])
print result
Now sum_list is a self contained adder, it does nothing else. You can trust it. It's not reading from names all over your code, it's only reading explicitly what you gave to it. It's not writing to the screen at surprise times, or anything. You give it a list, you get a result, it's isolated, limited, controlled, predictable, easy to work with, easy to reuse. And like the list names, if all you do is get the result and print it, you don't need to give that a name either:
def sum_list(working_list):
sum = 0
for number in working_list:
sum = sum + number
return sum
print sum_list([1,7,4])
print sum_list([2,8,5])
Edit: I hope that explains several of your questions.
What that code is doing
Why it prints one answer instead of three - because you are giving it one thing (a list).
Why it makes no sense to use return on its own - because you have to call a function and then return from the function, and you can bring something back with you or you can go somewhere and bring nothing back (function with no return). But you can't bring something back if you don't go anywhere first.
In Python you will realise that when you initialise a variable you don't need to assign a type to it, you can just initialise anything in there.
in this case l was interoperated as an object, or an array to be specific.
as for the loop.
for number in l:
is like a for each statement, it goes through each of the elements. and stores it in number, then iterates after the block is executed, moving on to the next l.
Hope that helped? (if i understand your question.
The for number in l: line takes each of the elements in [1,7,4] and adds them to the sum variable which represents the total sum of the elements in the list.
This is what it looks like:
Take first element of l: 1
Add to sum --> sum is now 1
Take second element of l: 7
Add to sum --> sum is now 8
Take third element of l: 4
Add to sum --> sum is now 12
Return sum --> sum is 12
Might I suggest that sum([1,7,4]), the builtin python method would also work.

Python: simplifying nested FOR loop?

I am wondering if there is a way to simplify the nested loop below. The difficulty is that the iterator for each loop depends on things from the previous loops. Here is the code:
# Find the number of combinations summing to 200 using the given list of coin
coin=[200,100,50,20,10,5,2,1]
total=[200,0,0,0,0,0,0,0]
# total[j] is the remaining sum after using the first (j-1) types of coin
# as specified by i below
count=0
# count the number of combinations
for i in range(int(total[0]/coin[0])+1):
total[1]=total[0]-i*coin[0]
for i in range(int(total[1]/coin[1])+1):
total[2]=total[1]-i*coin[1]
for i in range(int(total[2]/coin[2])+1):
total[3]=total[2]-i*coin[2]
for i in range(int(total[3]/coin[3])+1):
total[4]=total[3]-i*coin[3]
for i in range(int(total[4]/coin[4])+1):
total[5]=total[4]-i*coin[4]
for i in range(int(total[5]/coin[5])+1):
total[6]=total[5]-i*coin[5]
for i in range(int(total[6]/coin[6])+1):
total[7]=total[6]-i*coin[6]
count+=1
print count
I recommend looking at http://labix.org/python-constraint which is a Python constraint library. One of its example files is actually permutations of coinage to reach a specific amount, and it all handles it for you once you specify the rules.
You can get rid of all the int casting. An int/int is still an int in python ie integer division.
it looks like Recursion would clean this up nicly
count = 0
coin=[200,100,50,20,10,5,2,1]
total=[200,0,0,0,0,0,0,0]
def func(i):
global count,total,coin
for x in range(total[i-1]/coin[i-1]+1):
total[i]=total[i-1]-x*coin[i-1]
if (i == 7):
count += 1
else:
func(i+1)
func(1)
print count
combinations = set()
for i in range(len(coins)):
combinations = combinations | set(for x in itertools.combinations(coins, i) if sum(x) == 200)
print len(combinations)
It's a little slow, but it should work.

Categories

Resources