I'm new to python and my professor gave us the assignment to write different functions. Writing the function is easy but he gave us examples of what the output should be and it kind of threw me off.
>>> average([])
0.0
>>> average([1.0])
1.0
>>> average([5.0, 10.0, 20.0])
11.666666666666666
This was the example. How can I place square brackets around my input like that?
def average(inputlist)
return sum(inputlist)/len(inputlist)
If you do this
average([2, 4, 5])
The function will know you are passing a list parameter since python is a dynamically typed language, that is - the type of the parameter inputlist will be determined at runtime.
Alternatively, you could just define your list first, then pass it to the function like this.
inputValues = [2, 4, 5]
average(inputValues)
Create a list and then append your inputs to the list and then apply the function
Try this code:
nums = []
n = int(input())
for i in range(n):
nums.append(int(input()))
average(nums)
This above code will take an input n and then it takes n input numbers and then applies the average (any mathematical function).
Square parenthesis in python signify that your function is taking in an list as one of it's arguments.
You would take multiple inputs and append them to a list, which later you would input in the function.
Therefore your code will look like this:
def average(listOfNumbers):
total = sum(listOfNumbers)
return float(total)/len(listOfNumbers)
numOfInputs = int(input("Number of inputs: "))
numbers = []
for i in range(numOfInputs):
numbers.append(int(input("Enter Number: ")))
print(average(numbers))
def average(*args):
for i in args:
return sum(i)/len(i)
print(average([42,67,23,89]))
That means that your function has to take a list as an input. Therefore, you should assume your function is like below:
def average(input):
# input looks like [0,5,6]
I hope this helps.
Related
I'm new to python and just starting to learn the basics.
I have defined a function recursively and I want to print a list of function outputs.
This is the code:
def x(n):
assert n>=0, "Only non-negative integers n are allowed"
if n == 0:
return 5
else:
return (x(n-1)+5)/x(n-1)
print([x(0),x(1),x(2)])
for k in range(0,9,1):
print(x(k))
So my question is: say I want to print a list of the first 10 outputs of the sequence/function, i.e. x(0),...,x(9), how do I do this without actually listing each output manually? I want them to be in the form "[x(0),...,x(9)]", just like I did for the first 3 values. My attempt is in the last command of the program, where k moves from 0 to 9. The last command clearly prints the first 10 outputs, but not as a list, i.e. in [] brackets.
Any input is greatly appreciated.
One Solution:
I replaced the code
for k in range(0,9,1):
print(x(k))
with
print([x(k) for k in range(9)])
This puts the outputs in a list, i.e. in the [ ] brackets. Worked wonderfully!
You can use list comprehension.
print([x(n) for n in range(9)])
# outputs: [5, 2.0, 3.5, 2.4285714285714284, 3.058823529411765, 2.634615384615384, 2.8978102189781025, 2.72544080604534, 2.83456561922366]
Explanation:
We're making a list out by calling the function x() for each of the numbers (n) that are in the range from 0 to 9 (not included).
Please note that it is implicit that the starting point of the range() function is 0, that the step is 1, and the endpoint (9) is not included.
Here's a solution for a beginner (not an one-liner, should be easier to understand):
myarray = []
for i in range(9):
myarray.append(x(i))
Just to show the alternative to a list comprehension using map, since this is practically the scenario that map was made for:
xs = map(x, range(9))
map takes a function, and applies it to each member of the supplied iterable.
The main difference between this and using a comprehension is this returns a lazy iterable (a map object), not a list. x will not be applied to an element until you request the element.
Use of a list comprehension/generator expression is preferable in the majority of scenarios, but map is nice if you need/can tolerate a lazy result, and you already have a predefined function.
I am a first time programmer learning Python and need to receive input from the user and return the input along with the sum and square of the entered data. I have prompted for the input and can print that but not sure how to pass the input to the sum function and square function.
Here is what I have:
def sum(list):
data = input("Enter a list of numbers or enter to quit: ")
for data in list():
return sum(list) # Not sure how to make it x*y for my list of values?
print("The sum of your list is: ", list)
and this is the same for my square function. not sure how to make:
return(list**2) #return each number in list by **2?
Your code has a lot of problems, but they're mostly pretty simple ones that trip a lot of people up their first time. Don't let them get you down.
First, you shouldn't reuse names that already have meaning like list and sum. Basically, any of the names in the table at the top of this page.
Second, you are taking in two "lists" (Not really, but we'll get there). One is being passed into your function as an argument (list in def sum(list):). The other is data in the line
data = input("Enter a list of numbers or enter to quit: ")
Third, data in the above line isn't really a list, it's a string. If you want to split data from that input up and use it as numbers later, you'll have to do that manually.
Fourth, when you use the name data again in the line for data in list() you're overwriting the information contained in the existing data variable with the elements in list(). At least you would be except that.
Fifth, list() is a function call. There is a list function in Python, and this would work, but I think you probably expect this to iterate through the list you passed into the function.
Sixth, return sum(list) will call this function again, potentially forever.
Now, how do we go about fixing this?
Thankfully, the built-in function sum can add up lists for us if we want, but first we have to get the list from the user.
def input_list():
s = input("Enter integers separated by spaces:\n")
return [int(x) for x in s.split()]
The [int(x) for x in ...] bit is something called a list comprehension
. You'll see another in a second.
This function takes input like
23 45 12 2 3
and turns it into a list of ints.
Then we can just
print(sum(input_list()))
The squares are a bit more difficult, but list comprehensions make them easy. Just
print([x**2 for x in input_list()])
Feel free to ask any followup questions if any of this is unclear.
repl for code below:
def square(numbers):
squared = []
for number in numbers:
squared.append(number**2)
return(squared)
str_of_numbers = input("Enter a list of numbers or enter to quit: ")
print("input (string):", str_of_numbers)
numbers_as_strings = str_of_numbers.split(' ') # now have a list of strings
print("list of numbers (as strings):", numbers_as_strings)
# turn list of strings into list of numbers
numbers_list = []
for number_as_string in numbers_as_strings:
numbers_list.append(int(number_as_string))
print("list of numbers: ",numbers_list, "\n")
print("The sum of your numbers is: ", sum(numbers_list)) # uses built in `sum` function
print("The squares of your numbers are:", square(numbers_list))
Output of code above:
Enter a list of numbers or enter to quit: 1 2 3
input string: 1 2 3
numbers as a list of strings: ['1', '2', '3']
list of numbers: [1, 2, 3]
The sum of your numbers is: 6
The squares of your numbers are: [1, 4, 9]
This can also be done more succinctly using map, reduce and list comprehensions.
However, this seems more appropriate, based on content of OP's question.
Firstly, you shouldn't use list as a variable name as it is actually a data type (https://docs.python.org/3/library/stdtypes.html#list).
As for doing mathematical operations on a list of numbers, I would recommend looking into numpy. It allows you to do operations on arrays as well as a lot more varied and useful mathematical functions.
For your squaring each item in the list, you could simply do the following:
import numpy as np
myList = [1,2,3,4]
print(np.square(myList))
The above code would print [ 1 4 9 16].
More information on numpy (http://www.numpy.org/) and the square function (https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.square.html).
Here is the question, I'm trying to define a function sample_mean that takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list. Here is what I have so far, but I'm not sure it is totally right.
def sample_mean(list):
""" (list) -> number
takes in a list of numbers as a parameter and returns the sample mean of the the numbers in that list
sample_mean =
sample_mean =
"""
mean = 0
values = [list]
for list in values:
print('The sample mean of', values, 'is', mean(list))
Firstly, don't use list as a name because it shadows/hides the builtin list class for the scope in which it is declared. Use a name that describes the values in the list, in this case samples might be a good name. The function could be implemented with something like this:
def sample_mean(samples):
total = 0
for value in samples:
total = total + value
return total / float(len(samples))
Or a shorter version which avoids writing your own loop by making use of Python's sum() function :
def sample_mean(samples):
return sum(samples) / float(len(samples))
Call the function like this:
>>> print(sample_mean([1,2,3,4,5]))
3.0
Note the use of float() to ensure that the division operation does not lose the fractional part. This is only an issue in Python 2 which uses integer division by default. Alternatively you could add this to the top of your script:
from __future__ import division
If you are sure that you only need to support Python 3 you can remove the float() and ignore the above.
As stated above by #idjaw, don't use list as a parameter instead use listr (for example). Your values = [list] is erroneous (also stated by #idjaw) and should be removed.
Also, according to PEP257, you should not use "(list) -> number" in your docstrings as that should only be used for builtins.
Finally, your loop should look like for l in listr: and then you add values to your mean variable. divide it by the number of values in the list and print the result.
So i have a function which takes multiple values:
def kgV(a,b, *rest):
#the function itself doesnt matter for the question
#beside that it returns an int no matter how many arguments where passed
now i have a list or range():
# for example
myRange = range(2, 10)
myList = [2,9,15]
Now i want it to possible to give my Function the list or range as parameter so that it works as if i had given the every int of the range or list as parameter.
#how can i make this work?
kgV(myRange)
kgV(myList)
i tried some things like: for i in a etc
but they all returned errors :-/
edit: i just solved it using a help function but it seems a very un pythonic way of doing it, so is there a more pythonic / generic way of doing it?
def kgVList(liste):
result = liste[0]
for i in liste:
result = kgV(i, result)
return result
You can simply unpack the values like this:
kgV(*a)
I want function to take the last digit of each number in the list and sum them up all together. So forexample, the function below would return "10".
def getSumOfLastDigits(numList):
x = sum(int(num[-1:]) for num in numList)
print x
getSumOfLastDigits([1, 23, 456])
>>>10
Here is what i receive instead of the expected out "10"
def getSumOfLastDigits(numList):
x = sum(int(num[-1:]) for num in numList)
print x
getSumOfLastDigits([1, 23, 456])
Too much work.
def getSumOfLastDigits(numList):
return sum(x % 10 for x in numList)
x = sum(num%10 for num in numList)
You can't index into a number; a number isn't a sequence of digits (internally, it isn't represented in base 10). You can obtain the last digit of a number using mathematical manipulation instead: take the remainder when dividing by 10. We do this with the % operator.
Also:
Don't print the value in your function, return it. Let the calling code decide what to do with the value. Calculation and output are separate tasks, and should be kept separate.
Avoid indicating data types in variable names - yes, even in Python. It's not a good idea to build in assumptions that aren't actually necessary. You could use any kind of sequence here, for example. The simplest way to indicate that you have more than one number is to use the plural, numbers. That also means you use a full word, and people don't have to think about what 'num' is short for.
There is no need to assign the result of an expression to a temporary variable, if you are just going to use it once, and right away. The name x doesn't tell us anything, so cut it out.
get is considered an ugly prefix for function names by most Pythonistas. It should already be obvious that the function calculates and returns a value. Use noun-type names for those functions, and verb-type names for functions that are primarily intended to manipulate some existing data.
Thus:
def sum_of_last_digits(numbers):
return sum(number % 10 for number in numbers)
def getSumOfLastDigits(numList):
total=0
for item in numList:
newItem=str(item)
length=newItem[len(newItem)-1]
total+=int(length)
return total