I've written code to find the median of a list but I'm unsure how to display it when I run the code.
I've tried the print function but I'm not sure what to print.
My code is:
wages = [1,2,3]
def median(wages):
sorted_list = sorted(wages)
length = len(sorted_list)
center = length // 2
if length == 1:
return sorted_list[0]
elif length % 2 == 0:
return sum(sorted_list[center - 1: center + 1]) / 2.0
else:
return sorted_list[center]
Any help would be appreciated.
You can just call your function in the print statement:
print(median(wages))
or
print(median([1,2,3])
You might be confused because you labelled wages as the array and put it in the definition of your function, but there is no connection between the two wages in your code. The line
wages = [1,2,3]
creates a variables called wages but it doesn't impact the wages in the line:
def median(wages):
or inside your function definition. To read more have a look into variable scopes in python.
For example, you could call your function on any array such as,
test_array = [1,2,3,4]
print(median(test_array))
You can just print the return value of your median method.
def median():
your code here
print(median())
PS : There are some indentation errors in your code.
Related
def myNames():
b = []
while True:
a = input("whats the name: ")
if a != "done":
b.append(a)
elif a == "done":
break
return b
x = myNames()
print (x)
def getAverageLength(myNames):
total = 0
for i in myNames: #This line of code gives me an error and I cant figure it out
total = total + len(i)
average = float(total) / float(len(myNames))
return average
getAverageLength(myNames)
It takes my first function (myNames) as an argument. Ive been trying to figure this error out but have no idea what to do here
Your last line: getAverageLength(myNames), like you said in your description, is using myNames as a parameter which is only present as a function in the current scope.
This means when you reach your for loop, you end up trying to iterate over a function, since that is what was passed into getAverageLength
Maybe you meant getAverageLength(x)?
Or perhaps getAverageLength(myNames()) since myNames() passes the result of the function as opposed to the function itself.
To correctly calculate the average length of the strings, you could use the following:
averageLength = sum(map(len, x)) / len(x)
So I have written a function which calculates the sum of the digits when a number is input to the function. Now I am trying to write another function which would return a dictionary with the values from my digitsum function as the keys and the values would be how many times the count of that specific digitsum has occurred. Any ideas on how to go about writing the second function?
def digitsum(x):
if x < 10:
return x
else:
return (x%10) + digitsum(x//10)
def digitsumdictionary(lnum=0, hnum=100):
L =[digitsum(num) for num in range(100)]
counter = Counter(L).items()
return counter
Digitsum function is called depending on the length of the number.
You can simply find it by using len(list(str(num))). But if you want to count as the function calls itself, Then try this,
def digitsum(x, count=1):
if x < 10:
return { x : count }
else:
return {(x%10) + int(list(digitsum(x//10 , count+1).keys())[0]) : int(list(digitsum(x//10 , count+1).values())[0])}
Setting the count to 1 or 0 initially, includes or excludes the first call respectively.
The below code returns a list of dictionaries of the desired output.
[digitsum(i) for i in range(10)]
I have a program where by a teahcer can view the her student's squiz results and sort them in a avruiety way:
if role == 2:
class_number = prompt_int_big("Which class' scores would you like to see? Press 1 for class 1, 2 for class 2 or 3 for class 3")
filename = (str(class_number) + "txt")
sort_or_not = prompt_int_small("Would youlike to sort these scores in any way? Press 1 if the answer is no or 2 if the answer is yes")
if sort_or_not == 1:
f = open(filename, "r")
lines = [line for line in f if line.strip()]
lines.sort()
for line in lines:
print (line)
if sort_or_not == 2:
type_of_sort = prompt_int_big("How would you like to sort these scores? Press 1 for scores in alphabetical order with each student's highest score for the tests, 2 if you would like to see the students' highest scores sorted from highest to lowest and 3 if you like to see these student's average scores sorted from highest to lowest")
if type_of_sort == 1:
with open(filename , 'r') as r:
for line in sorted(r):
print(line, end='')
if type_of_sort == 2:
with open (filename,'r') as r:
def score(line):
return int(line.split(':')[1])
for line in sorted(r, key=score, reverse = True):
print(line)
if type_of_sort == 3:
with open (filename,'r') as r:
def score(line):
returnint(line.split(':')[1])
average = sum(map(int, score))/len(score)
print(name,"--",average)
However when the third option is selected an error comes up:
average = sum(map(int, score))/len(score)
TypeError-'function' object is not iterable
map() in Python-3.x returns an iterator (unlike Python-2.x where it returns a list of the result). Hence, you need to generate the list from the iterator and then pass it to the sum() function.
average = sum(list(map(int, score)))/len(score)
In the above, example score should be iterable like a list or a tuple.
EDIT: Well, map takes an iterable as an argument (like list, tuple) but in this case the argument passed, score, is a function. And you are passing the function name and not calling the function. Hence, a function gets passed to the map() function. So, you need to call the function. Eg:
score_list = score(r.readline())
average = sum(list(map(int, score_list)))/len(score_list)
def areaOfRectangle (length,width):
area = length*width
sqArea = length**2
return area,sqArea
def areaOfSquare (length,):
areaOfRectangle (length,width)
return sqArea
#def radiusOfCircle (radius):
area = 3.14*(radius**2)
return area
#def volumeOfCylinder (radius,height):
volume = 3.14*(radius**2)*height
return volume
length = int(input("Input length: "))
width = int(input("Input width: "))
print()
print(areaOfRectangle (10,20))
print()
print(areaOfRectangle (24.3,6))
print()
print(areaOfRectangle (34.9,17.4))
print()
print(areaOfRectangle (length,width))
print()
print(areaOfSquare (10.3))
I need to make two functions, the first function to calculate the area of a rectangle given the length and width. The second function needs to calculate the area of a square given the length of one of its sides. The second function should call the previous function to perform the calculation. I know how to call a function within another function however I don't know how to bring a variable from the first function to the second.
I don't know how to bring a variable from the first function to the second
Typically, this is done through the use of parameters. Let's say you have a value x:
x = 0
You can pass the value to a function by inserting it into the call itself:
f(x)
Lastly, the function needs to be able to handle the parameter you give it:
def f(y): pass
A working example of what you describe:
def f2(y):
return y + 1
def f1():
x = 2
print(f2(x))
f1()
3 is printed.
my question is basically this: Create a recursion function that takes a nested list as a
parameter and returns the sub-list that has minimum difference between its maximum and minimum elements.
For example: Function should return [1,2] for input [[1,199,59],[1,2],[3,8]]
I searched Google and stackoverflow, but i could not find this specific example.
What i would like to get help is with iteration. I want to, using recursion, iterate over each sub-list(can be as many as possible). I have achieved this with a for loop, but i cannot grasp the idea of iteration by using recursion method.
So far, i have this:
def sublist(mylist):
if len(mylist) == 0:
return []
elif len(mylist) == 1:
return mylist
else:
a = (mylist[0][0]) - (mylist[0][-1])
if a < sublist(mylist[1:]):
return mylist[0]
sublist([[1,199,58],[1,2],[3,8]])
This part, ( sublist(mylist[1:]) ) i know is clearly wrong. I'm trying to compare the value a, with the values from the mylist[1:]. I would appreciate much advice here.
Updated:
def differences(mylist):
diff = max(mylist) - min(mylist)
return diff
def sublist(nestedlist):
if len(nestedlist) == 1:
return nestedlist[0]
else:
if differences(nestedlist[0]) < differences(sublist(nestedlist[1:])):
return nestedlist[0]
else:
return sublist(nestedlist[1:])
print(sublist([[1,199,59],[1,2],[3,8]]))
i am assuming that you want to use recursion for the first level of the list. So, without giving you the code 100%, you have to do something like that:
1) create a method e.g diferences(list) that calculates the differences of a list and returns a list with the parameter list and the min difference i.e differences([1,2]) should return [1, [1,2]]. call it once on the first sublist i.e min = differences(mylist[0])
2) create your sublist method like this:
def sublist(initial_list):
# 1) call differences() method for the first sublist of the 'initial_list'
# 2) update 'min' with differences(initial_list[0])if differences(inilitial_list[0])[0] < min[0];
# 3) call sublist() again now removing the sublist you checked before from the arguement
# 4) (the following should be at the start of your sublist() method)
if len(initial_list) = 1:
if differences(initial_list) < min:
return initial_list
else: return min[1]
Hope that helps