Taking the sum of a list without sum() - python

I have a list that gets generated when a user inputs a random number they want. I want to add the sum together with out using sum(). How could I do this?
xAmount = int(input("How man numbers would you like to input: "))
numList = []
for i in range(0, xAmount):
numList.append(int(input("Enter a number: ")))
print(numList)
From here

Store the sum in a temp variable. Keep adding the input numbers to the temp variable:
xAmount = int(input("How man numbers would you like to input: "))
numList = []
numList_sum = 0
for i in range(0, xAmount):
inputted_number = int(input("Enter a number: "))
numList_sum += inputted_number
numList.append(inputted_number)
print(numList)
print(numList_sum)

You don't need a list at all.
xAmount = int(input("How man numbers would you like to input: "))
result = 0
for i in range(0, xAmount):
result = result + int(input("Enter a number: "))
print(result)

To sum a list just iterate over the list, adding up the individual values:
num_total = 0
for value in numList:
num_total += value
You could also use reduce but this might not meet your h/w requirements either:
from functools import reduce
from operator import add
num_total = reduce(add, numList, 0)

Related

removing numbers form list by python

Take 5 integer input from the user.
Remove all numbers less than 9.
Calculate the sum of remaining numbers
python
n = int(input("Enter number of elements : "))
a = list(map(int,input("\nEnter the numbers : "). strip(). split()))
for i in range(len(a)):
if a[i]>9:
a.remove(a[i])
b=sum(a)
print(b)
When you remove from same list, of course the index will be out of range items from list,
BUT you really don't need to remove those items from list, just don't include them in your sum calculation:
n = int(input("Enter number of elements : "))
a = list(map(int, input("\nEnter the numbers : ").strip().split()))
b = sum([num for num in a if num<= 9])
print(b)
You can use this if you want to remove numbers less than 10 from the list and Calculate the sum of the remaining numbers
n = int(input("Enter number of elements : "))
a = list(map(int, input("\nEnter the numbers : ").strip().split()))
if len(a) == n:
for num in a:
if num < 9:
a.remove(num)
print('sum',sum(a))
else:
print(f"You must enter {n} number")

Adding elements to list after get 2 or more inputs on Python

def take_info(arr2,arr, number):
arr[0] = number
name = input()
arr[1] = name
grade = int(input())
arr[2] = grade
second_grade = int(input())
arr[3] = second_grade
arr2. append(arr)
def main():
number = int(input())
arr = [0] * 4
count =1
arr2 = // ? I dont know how to do it, range must be equal to count but how? Thats the point 1.
while number>0:
take_info(arr2,arr,number)
count +=1
number = int(input())
main()
take_info function must return while ' number >0 ', when the number is 0 or less than 0 loop would end. And I want to add these values and name to a list and the other list's each element should be list. Could anyone can help me ?
Any time you're repeating something, you probably want to use a loop. If you're using a loop to build a list, you probably want to use a list comprehension.
arr = [input() for _ in range(3)]
Given your updated question, I might do it like this:
def take_info(number):
return [number, input(), int(input()), int(input())]
def main():
return [take_info(number) for number in range(int(input()))]
print(main())
If it's important that the numbers count down instead of up, you can do that by modifying the range call so that it goes from N-1 to 0 instead of 0 to N-1.
Alternatively, if you want to have space separated inputs in one line, you can use this:
my_list = list(map(str,input().split()))
for i in range(len(my_list)):
if (isinstance(my_list(i), int)):
temp = int(my_list(i))
my_list.pop(i)
my_list.insert(i, temp)
Input: Car Hockey Cricket
my_list = ['Car', 'Hockey', 'Cricket']
Ofcourse, the data type would be the same here. You'd need to make changes after appending incase of int, float, etc.
The stereotype of Python is that “everything is a dict”. Your application might be such a case.
One way to organize the data you have coming in might be a dict where each entry is also a dict.
def take_info():
record = dict()
record['name'] = input('Name: ')
record['grade'] = int(input('Grade: '))
record['second_grade'] = int(input('Second grade: '))
return record
def main():
course_records = dict()
count = 0
number = int(input('ID number: '))
while number > 0:
course_records[number] = take_info()
count +=1
number = int(input('ID number: '))

Python 2D lists appending data to a location

Wondering if someone can help me on this. I know I can append data to a 1D list by using .append. What I am having trouble figuring out is how to append data to a 2D list and have Python place the data in the right list in the right spot.
I need to create a program that runs x times (with each name having 2 pairs of values), and after each time append the user input to a list. So at the end, I need something like this:
[[Name] [1,2] [3,4]]
[[Name] [4,5] [6,7]]
etc….
How do I tell Python which List and position to place the Names and values in ?
This is what I have so far for code.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = [ [], [] ]
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
counter = counter + 1
main()
OK - so I modified the code and added in a line to append the data, after the line with the counter + 1.
list.append([[name],[first_val,first_val2], [sec_val,sec_val2]])
What I would now like to do is print the list out (via rows and columns), but am getting a IndexError. This occurs when I try to enter/print out more than 4 values. The error appears to be in the last line. Is there a way I can modify the code to stop this and print out as many values as have been requested by the user ?
for r in range(how_many):
for c in range (how_many):
print list [r][c]
And yes, I will look into using tuples as well at some point.
def main():
how_many = int(raw_input("How many to enter? "))
counter = 0
list = []
while counter < how_many:
name = raw_input("Enter the Name ")
first_val = int(raw_input("Enter first_val "))
first_val2 = int(raw_input("Enter first_val2 "))
sec_val = int(raw_input("Enter sec_val "))
sec_val2 = int(raw_input("Enter sec_val2 "))
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
counter = counter + 1
Assume we are reading the values from stdin (as in the question body)
you can use lists:
list = []
....
list.append([[name], [first_val, first_val2], [sec_val, sec_val2]])
but a tuple seems to be a better fit here:
t = (name, (first_val, first_val2), (sec_val, sec_val2))
list.append(t)
Since the values are not likely to change, a tuple feels like the better choice.
Think about how a field would be accessed in each case:
list:
name = list[i][0][0]
tuple:
name = list[i][0]
Again...it just seem more natural...

How to calculate the average number of random numbers generated?

I have written a FOR loop to call a function 100 times to get 100 random numbers, I now need to calculate the average number of all the random numbers generated. How can I do this? This is where I got up to so far
import random
num1 = int(input("Input First number "))
num2 = int(input("Input Second number "))
for i in range(10):
print(random.uniform(num1, num2), end = "\t")
First of all, your function is only being run 10 times. You need to store the values you're generating, rather than printing them to the screen. You can do this by storing it in a list.
To get a list of 100 random variables, you could do [random.uniform(num1, num2) for i in range(100)].
Then, you need to find the average of this. To get a total sum, you can do sum(list). To get the number of values, do len(list). If we combine this all together, we get:
import random
num1 = int(input("Input First number: "))
num2 = int(input("Input Second number: "))
random_numbers = [random.uniform(num1, num2) for i in range(100)]
print(sum(random_numbers)/len(random_numbers))
Output is:
>>> import random
>>> num1 = int(input("Input First number: "))
Input First number: 10
>>> num2 = int(input("Input Second number: "))
Input Second number: 20
>>> random_numbers = [random.uniform(num1, num2) for i in range(10)]
>>> random_numbers
[13.083389212287019, 12.551686149990369, 13.881302022239865, 12.5156539109837, 12.340949073439575, 13.693758114264867, 13.972147752101735, 14.111313446849902, 11.693700678679372, 18.136716333128035]
>>> print(sum(random_numbers)/len(random_numbers))
13.5980616694
import random
rand_nums = [random.uniform(num1, num2) for i in range(10)]
average = sum(rand_nums) / len(rand_nums)
Or if you prefer to use numpy
import numpy as np
rand_nums = np.random.uniform(num1,num2,10)
average = rand_nums.mean()
I think you have to store the numbers somewhere, not print them. If you use a list, you can calculate the sum and then divide by the length.
import random
num1 = int(input("Input First number "))
num2 = int(input("Input Second number "))
numbers = []
for i in range(10):
numbers.append(random.uniform(num1, num2))
print(numbers)
print(sum(numbers)/len(numbers))
This is very basic stuff, hope this helps:
import random
num1 = int(input("Input First number "))
num2 = int(input("Input Second number "))
sum = 0
numbers = 100
for i in range(numbers):
random_number = random.uniform(num1, num2)
sum += random_number
avarage = sum/numbers
print(avarage)

How do I sort the results of this Python program from lowest to highest values?

Below is my code, which generates X instances of random numbers between 0 and 101.
import random
x = int(raw_input("Enter desired number: "))
def randoTaker():
print(random.randint(0, 101))
randoTaker()
for i in range(x-1):
randoTaker()
My question: how do I sort these results from low to high? For example: let's say my current output for an input of value of 4 is 12, 34, 5, 45. My desired result would be 5, 12, 34, 45.
Any help would be very appreciated!
How about the below;
import random
x = int(raw_input("Enter desired number: "))
def randoTaker():
return random.randint(0, 101)
for j in sorted([randoTaker() for i in range(x)]):
print j
The problem is that you are printing your results rather than storing them. You probably want to save them in a list, then sort the list:
import random
x = int(raw_input("Enter desired number: "))
def randoTaker():
return random.randint(0, 101)
results = []
for i in range(x-1):
results.append(randoTaker())
results.sort()
print results
If you really want, you can use a list comprehension:
import random
x = int(raw_input("Enter desired number: "))
def randoTaker():
return random.randint(0, 101)
print sorted([randoTaker() for i in range(x-1)])
First of all, you are just printing the value inside your function. If you want to sort the random numbers generated, you should consider returning the numbers and then adding them to a list.
Once you have added all the numbers to a list, you can then use list.sort() function or sorted() function to sort the list.
Example:
import random
x = int(raw_input("Enter desired number: "))
def randoTaker():
return random.randint(0, 101)
print(randoTaker())
randlst = []
for i in range(x-1):
randlst.append(randoTaker())
randlst.sort()
print(randlst)

Categories

Resources