Trying to average a list of numbers using functions [closed] - python

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
First and foremost, I am new to python. As of such, I only know for loops, range, lens, and sum to do this problem. I am having difficulty trying to make a function that can average list of numbers.
This is my code so far:
def ave(L):
L = list(range(len(L))
for a in range(len(L)):
if len(L) == 0: return 0
else: return float((sum(L))/len(L))
So far, I am getting a syntax error on my third line with range(L).

All you need to do is return the sum of L divided by the length of L:
def ave(L):
if not L:
return 0
return sum(L) / len(L)
No range() or float() or for required.
In Python 3, / always produces a floating point number. sum() will do all the looping for you. The only thing you need to take care of, is returning 0 if the list is empty.

Following line is missing a ):
L = list(range(len(L)))
^

Because average of empty list is undefined, you should rather return None instead of '0'.
And instead checking for length, it is better to catch potential error, according to EAFP principle. It makes also more clear what are you doing, as error is self-descriptive.
def ave(L):
try:
return sum(L) / len(L)
except ZeroDivisionError:
return None

Related

why is my recursion not returning the desired output? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am writing a recursion function that simply returns x^n:
def myPow(x,n) -> float:
def recurs_n(x,n):
if n==1:
return x
if n>1:
result = myPow(x,n-1)
return result
return recurs_n(x,n)
print(myPow(2,5))
The output that I am getting for the above is 2, which isn't correct obviously. Any idea where I am going wrong?
Your inner function calls the outer function, that should not be allowed. Furthermore, there is no logic applied anywhere for the multiplication when going to the n-1 step. So when n>1 you need to return x*myPow(x,n-1)
I should also mention, that in your case there is no real need to have an inner and outer function, one function should be enough. Like so;
def myPow(x,n) -> float:
if n == 1:
return x
if n > 1:
return x*myPow(x,n-1)
print(myPow(2,5))
Your code runs until power n=5 reaches 1, where it activates the first if condition where x is returned (here x=2) without continuing onwards.
An alternative is presented below:
def power(N, P):
# if power is 0 then return 1
if P == 0:
return 1
# if power is 1 then number is
# returned
elif P == 1:
return N
else:
return (N*power(N, P-1))

Can you find the even number problem using with try / except? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I didn't understand this thing:
list1 = [34,2,1,3,33,100,61,1800]
for n in list1:
try:
n%2 == 0
print(n)
except:
pass
The output of the code above shows every number, but I need just even numbers.
What is my mistake?
I suspect you are missing a basic idea somewhere. try / except is used for catching errors. In order to use this in the way you are trying to, you need to cause an error under some condition. One easy way is to assert the number is even. assert n % 2 == 0 says if n is not even, raise an exception. Then you can catch the exception and skip it with a pass
list1 = [34,2,1,3,33,100,61,1800]
for n in list1:
try:
assert n % 2 == 0 # cause an error if `n` is not even
print(n)
except AssertionError:
pass
You were missing a condition if
list1 = [34,2,1,3,33,100,61,1800]
for n in list1:
try:
if n%2 == 0:
print(n)
except:
pass
Two things. You forgot an if statement before preforming n%2
Second thing is, what is the point of the try and except. You don't need it.
Below is an example of your code in
list comprehension.
list1 = [34,2,1,3,33,100,61,1800]
even = [n for n in list1 if n%2 == 0]
output
[34, 2, 100, 1800]
simplified code
list1 = [34,2,1,3,33,100,61,1800]
even = []
for n in list1:
if n%2 == 0:
even.append(n)
output
[34, 2, 100, 1800]

basic question about python for loop and enumerate [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I am trying to build a function that will return the sum of the first item in the data list and every tenth item after, so I write the script below, however, the result is always the first data in my list. How should I modify my code and fix it?
def Sum10th(data):
sum=0
for i,d in enumerate(data):
if (i % 10 == 0): sum = sum+d
return sum
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
print(Sum10th(p))
The desired result should be 31, however the computer only returns the value of 1.
You can try
p = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
def Sum10th(data):
return sum([v for i, v in enumerate(p) if (i + 1) % 10 == 0 or i == 0])
print(Sum10th(p))
Output
31
By using the list comprehension with an if, at the end of it, you can get all the first item with the tenth item following it from a list.
Try this way:
def sum10thdata(data):
sum = 0
l = len(data)
for i in range(0,l,10):
sum+=data[i]
return sum

Printing to stdout gives the correct list, but appending to a list does not [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
I working on this problem on leetcode:
Given a collection of distinct integers, return all possible permutations.
If I iteratively print my results I get the correct values. As soon as I add it to a list the results are incorrect. What is happening?
class Solution:
def permute(self, nums):
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
if len(nums) == 1:
return nums
permutations = list()
import math
max_swaps = math.factorial(len(nums))
pair = [0,1]
for i in range(max_swaps):
if pair[1] == len(nums):
pair[0] = 0
pair[1] = 1
p = self.swap(nums, pair[0], pair[1])
print("Adding %s to the list" % p)
permutations.append(p)
pair[0] += 1
pair[1] += 1
return permutations
def swap(self, nums, index1, index2):
tmp = nums[index2]
nums[index2] = nums[index1]
nums[index1] = tmp
return nums
I should get:
[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]
But instead I get:
[[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3],[1,2,3]]
You keep adding a reference to the same list to permutations.
When you call:
permutations.append(p)
Python doesn't take a copy of the list, it adds a reference. You only have one list.
What you want to do is:
permutations.append(p[:])
Which will take a copy.
When you return nums from swap, you're not making a copy, you're returning the same list that will be modified later. You can make a copy either at the return or when you append the list to your result.
This is a common bug in a lot of code. The bug you're seeing here is a symptom of having the values returned from swap be the same as nums. This means that you're appending nums over and over into the permutations list. If you were to print the entire permutations list instead of only p you'd see that they were always the same.
The solution is rather simple: At some point in your code (likely in swap or something) you need to make a copy of the nums list.

Check for palindrome using recursion [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I have used the following code for checking whether a string is palindrome. However it is returning None when a string is palindrome.
def check(a):
if len(a)==1 or len(a)==0:
return True
if a[0]==a[len(a)-1]:
check(a[1:len(a)-1])
else:
return False
print check("radar")
You need to return the result of the recursion in your function:
def check(a):
# Base Case
if len(a) < 2:
return True
# Recursive Call
if a[0] == a[-1]:
check(a[1:-1])
else:
return False
return check(a[1:-1])
print check("radar")
Bonus Info
Your function performs duplicate work as it checks the string a. To avoid duplicate function calls and greatly improve the performance of your algorithm, you might consider memoization. Otherwise, you could build up a large call stack and potentially cause a stack overflow error (hey, that's the name of the website...).
Here's one possible way to implement memoization, by constructing a class around your function:
class check:
def __init__(self):
self.memo = {}
def Check(self, a):
# Base Case
if len(a) < 2:
return True
# Check Memo
if a in self.memo:
return self.memo[a]
# Recursive Call
if a[0] == a[-1]:
self.Check(a[1:-1])
else:
return False
# Memoize
self.memo[a] = True
return self.Check(a[1:-1])
print check().Check("rats live on no evil star")

Categories

Resources