Python how to calculate average of range list? - python-3.x

Could somebody tell me what I am doing wrong?
I am gotting error Vidurkis = sum(B)/len(B)
TypeError: 'int' object is not callable
A = int(input('Betkoks skaicius'))
if A == 0:
print('Ačiū')
if A <= 10 and A>=-10:
if A<0:
print('Neigiamas vienženklis')
if A>0:
print('Teigiamas vienženklis')
else:
print('| {:^20} |'.format('Autorius: '))
for r in range(10,A,1):
Vidurkis = sum(r)/len(r)
print(Vidurkis)

after
sum = 0
sum is no longer the built-in sum function! You would have to rename that variable. The real error is, however, that you are applying functions that take iterables as arguments to integers (Your loop variable B is an int while sum and len would expect a list or similar). The following would suffice:
r = range(10, A, 1) # == range(10, A)
Vidurkis = sum(r)/len(r) # only works for A > 10, otherwise ZeroDivisionError

Related

Returning tuple instead of integer

def max_product(nums):
product = 1,
maxP = (min(nums))
print(type(maxP))
for n in nums:
print(type(n))
product *= n # here, product should be an integer but it is a tuple, don't know why
print(product)
print(type(product))
maxP = max(product, maxP) # here, it is giving this error: 'TypeError: '>' not supported between
instances of 'int' and 'tuple''
if n == 0:
product = 1
product = 1
for n in nums[::-1]:
product *= n # here also it is tuple
maxP = max(product, maxP)
if n == 0:
product = 1
return maxP
print(max_product([2, 3, -2, 4]))
# desired output: 6
I am trying to write a function in python that returns the maximum product of continuous elements in an array containing both positive and negative numbers. But the function is not returning the desired result. It is giving the error mentioned in the code. Please help me to find the error and solve the problem.
the type of 'product' should be integer, but it is of type 'tuple', as a result of that the 'max()' function is not able to work and giving the error.
I think that maybe you need to remove the comma , in the line: product = 1,, this makes the product variable of tuple type instead of int.

Convert list of integers to a single integer : ValueError

I am trying to convert a list of integers in Python into a single integer say for example [1,2,3,4] to 1234(integer). In my function, I am using following piece of code:
L = [1,2,3,4]
b = int(''.join(map(str, L)))
return b
The compiler throws a ValueError. Why so? How to rectify this issue?
You can do this like this also if that cause problems:
L = [1,2,3,4]
maxR = len(L) -1
res = 0
for n in L:
res += n * 10 ** maxR
maxR -= 1
print(res)
1234
another solution would be
L = [1,2,3,4]
digitsCounter = 1
def digits(num):
global digitsCounter
num *= digitsCounter
digitsCounter *= 10
return num
sum(map(digits, L[::-1]))
the digits() is a non pure function that takes a number and places it on place value depending on the iteration calling digits on each iteration
1. digits(4) = 4 1st iteration
2. digits(4) = 40 2nd iteration
3. digits(4) = 400 3rd iteration
when we sum up the array returned by map from the inverted list L[::-1] we get 1234 since every digit in the array is hoisted to it place value
if we choose not no invert L array to L[::-1] then we would need our digits function to do more to figure out the place value of each number in the list so we use this to take adv of language features

Python 3 index is len(l) conditional evaluation error

I have the following merge sort code. When the line if ib is len(b) or ... is changed to use double equal ==: if ib == len(b) or ..., the code does not raise an IndexError exception.
This is very unexpected because:
len(b) is evaluated to a number and is is equivalent to == for integers. You can test it out: a python expression
(1 is len([0]) )
is evaluated to be True.
the input to the function is range(1500, -1, -1), and range objects are handled differently in python3. I was suspecting that since the input was handled as a range instance, the length evaluation might have been an instance instead of a integer primitive. This is again strange because
1 is len(range(1))
also gives you True as the result.
Is this a bug with the conditional evaluation in Python3?
Tom Caswell supplied this following useful express in our discussion, I'm copy pasting it here for your notice:
tt = [j is int(str(j)) for j in range(15000)]
only the first 256 items are True. The rest are False hahahaha.
The original script:
def merge_sort(arr):
if len(arr) >= 2:
s = int(len(arr)/2)
a = merge_sort(arr[:s])
b = merge_sort(arr[s:])
ia = 0
ib = 0
new_arr = []
while len(new_arr) < len(arr):
try:
if ib is len(b) or a[ia] <= b[ib]:
new_arr.append(a[ia])
ia += 1
else:
new_arr.append(b[ib])
ib += 1
except IndexError:
print(len(a), len(b), ia, ib)
raise IndexError
return new_arr
else:
return arr
print(merge_sort(range(1500, -1, -1)))
Python does not guarantee that two integer instances with equal value are the same instance. In the example below, the reason the first 256 comparisons return equal is because Python caches -5 to 256 in Long.
This behavior is described here: https://docs.python.org/3/c-api/long.html#c.PyLong_FromLong
example:
tt = [j is int(str(j)) for j in range(500)]
plt.plot(tt)
IIRC that any of them pass the is test is an implementation-specific optimization detail.
is checks whether 2 arguments refer to the same object, == checks whether 2 arguments have the same value. You cannot assume they mean the same thing, they have different uses, and you'll get an error thrown if you attempt to use them interchangeably.

power (a, n) in PYTHON

POwer in Python. How to write code to display a ^ n using funсtion?
why doesn't this code working?
a = int(input())
n = int(input())
def power(a, n):
for i in range (n):
a=1
a *= n
print(power (a, n))
Few errors:
Changing a will lose your power parameter, use result (or something else).
Move setting result = 1 outside your loop to do so once.
Multiply by a not by n.
Use return to return a value from the function
def power(a, n):
result = 1 # 1 + 2
for _ in range (n):
result *= a # 3
return result # 4
Style notes:
Setting/mutating a parameter is considered bad practice (unless explicitly needed), even if it is immutable as is here.
If you're not going to use the loop variable, you can let the reader know by using the conventional _ to indicate it (_ is a legal variable name, but it is conventional to use it when not needing the variable).
Tip: you can simple use a**n
It doesn't work because your function doesn't return the end value. Add return a to the end of the function.
ALSO:
That is not how a to the power of n is is calculated.
A proper solution:
def power(a,n):
pow_a = a
if n is 0:
return 1
for _ in range(n-1): # Substracting 1 from the input variable n
pow_a *= a # because n==2 means a*a already.
return pow_a
and if you want to be really cool, recursion is the way:
def power_recursive(a,n):
if n is 0:
return 1
elif n is 1:
return a
else:
a *= power_recursive(a,n-1)
return a

sum even integer in a list of integer (without loop)

I have a task: create a function that takes a integer list as parameter and returns the sum of all even integer in an integer list, without using any kinds of loop. All addition must be done by + operator only. Below is my solution
def sumTest(list_Of_Integers):
return sum(list(filter(lambda x: x%2 == 0, list_Of_Integers)))
I want to ask if there is any better solution, like without using the built-in sum() of python.
Thanks
As stated above in the comments, a more pythonic way of doing this is to use a list comprehension:
def sumTest(list_Of_Integers):
return sum([x for x in list_Of_Integers where x % 2 == 0])
As #UloPe states, however, this sounds very much like a homework question, in which case a more recursive method may be expected (rather than using the sum() function):
def sumTest2(xs):
if len(xs) == 0:
return 0
total = xs[0] if xs[0] % 2 == 0 else 0
return total + sumTest2(xs[1:])
This will generate a function stack dependent on the size of the list.
If you want to generate a shallower stack, then you can do the following:
def sumTest3(xs):
if len(xs) == 0:
return 0
midpoint = len(xs) / 2
total = xs[midpoint] if xs[midpoint] % 2 == 0 else 0
return sumTest3(xs[:midpoint]) + total + sumTest3(xs[midpoint + 1:])
The stack depth of this version will be log(size of list)

Resources