Function which returns Sum of all arguments - python

I want bo create a function which returns sum of all passed arguments.
I found similar problem on forum, but It doesn't work with last case.
def sum_all(*args):
sum = 0
for num in args:
if not str(num).isdigit():
return False
else:
sum += int(num)
return sum
This code work with first and second case, but return false on third case.
sum_all(2,-3)
# -1
sum_all([3,4,5])
# 12
sum_all(1,2,[3,4,5])
# false
How can i make it work? To make it return 15 in last case?
Thanks!

In case of a list, just call the function recursively, example:
def sum_all(*args):
sum = 0
for num in args:
if type(num) is list:
sum += sum_all(*num)
else:
sum += int(num)
return sum

Can use this
def sum_all(*args):
s = 0
for a in args:
if type(a)==list:
s+=sum(a)
else:
s+=int(a)
return s
print(sum_all(2,-3))
print(sum_all([3,4,5]))
print(sum_all(1,2,[3,4,5]))

Related

How would I count the number of iterations of a Recursive Function in Python?

def solver():
empty_cell = empty_square()
counter = 0
if not empty_cell:
return True
i,j = empty_cell[0],empty_cell[1]
for num in range(1,10):
counter += 1
if constraint_check(num,i,j):
sudoku[i][j] = num
if solver():
return True
else:
sudoku[i][j] = 0
return False
Given the code above, how would I implement a counter to count how many iterations the recursive part of the function makes? As can be seen in the code I have attempted something above but I was not able to retrieve this variable to print it out and record the number.
set counter as function parameter -> solver(counter=1)
then when calling it again within your function add +1 -> solver(counter+1)

why is function returning a different thing when called alone VS when called twice

so i have a recursive function that i call 2 times with different arguments but the second time i call it, it doesnt give the correct result, it only gives the correct result when i call it the first time not the second time. Maybe a memoy or cache issue ?
def m(n):
s= [int(char) for char in str(n)]
product = 1
for x in s:
product *= x
return product
i = 0
def persistence(n):
global i
if len(str(n)) == 1:
return i
else:
j = m(n)
i+=1
s = persistence(j)
return s
print(persistence(39))
print(persistence(4)) #returns 3 when called with the top one but 0 when called alone
You have a condiction len(str(n)) in your function persistence, so that if n is a number between 0 and 9, you return global i.
When you call print(persistence(4)) alone, your function return global i (equal to 0).
When you call print(persistence(39)) first, and then print(persistence(4)), the first call set global i to 3, and the second call juste return the value value of global i, that as just been set to 3.
I don't really get what you want to do, but maybe your problem comes from the usage of global.
The problem is that you are using i as global variable. When you execute the method again, your i
def m(n):
s= [int(char) for char in str(n)]
product = 1
for x in s:
product *= x
return product
def persistence_recursive(n, i):
if len(str(n)) == 1:
return i
else:
j = m(n)
i+=1
s = persistence_recursive(j, i)
return s
def persistence(n):
return persistence_recursive(n, 0)
print(persistence(39)) # returns 3
print(persistence(4)) # returns 0

Python classes and definitions

Here is my python code:
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
s1.isPalindrome()
It checks to see if the input is a palindrome. I want to create a new object that has the x value 121 and when I execute the isPalindrom function, I want it to return either a true or false boolean answer.
Currently when I run this program, nothing gets outputted. I am a bit lost as to where to go from here, would appreciate help.
Just print out the return value of isPalindrome(), because if you have a line with only a return value (this case being a boolean), the compiler won't know what to do with it.
class Solution():
def isPalindrome(self):
return str(self.x) == str(self.x)[::-1]
s1 = Solution()
s1.x = 121
print(s1.isPalindrome())
You're not telling the program to print anything. Try using print to make it reveal the answer.
Along with printing results we can also make class more pythonic.
class Solution:
def __init__(self):
self.input = None
def is_palindrome(self):
if isinstance(self.input, str):
return self.input == self.input[::-1]
print("Error: Expects str input")
return False # or leave blank to return None
s1 = Solution()
print(s1.is_palindrome())
s1.input = "121"
print(s1.is_palindrome())
output
Error: Expects str input
False
True
The main idea here is divide number. let's take number 122. First of all you need store it in a variable, in this case r_num. While loop is used and the last digit of the number is obtained by using the modulus operator %. The last digit 2 is then stored at the one’s place, second last at the ten’s place and so on. The last digit is then removed by truly dividing the number with 10, here we use //. And lastly the reverse of the number is then compared with the integer value stored in the temporary variable tmp if both are equal, the number is a palindrome, otherwise it is not a palindrome.
def ispalindrom(x):
r_num = 0
tmp = x
while tmp > 0:
r_num = (r_num * 10) + tmp % 10
tmp = tmp // 10
if x == r_num:
return True
return False

Sorted values in increasing order and adjacent values

In python, I am trying to check if a given list of values is currently sorted in increasing order and if there are adjacent duplicates in the list. If there are, the code should return True. I am not sure why this code does not work. Any ideas? Thanks in advance!!
def main():
values = [1, 4, 9, 16, 25]
print("Return true if list is currently sorted in increasing order: ", increasingorder(values))
print("Return true if list contains two adjacent duplicate elements: ", twoadjacentduplicates(values))
def increasingorder(values):
hlist = values
a = hlist.sort()
if a == hlist:
return True
else:
return False
def twoadjacentduplicates(values):
ilist = values
true = 0
for i in range(1, len(ilist)-1):
if ilist[i] == ilist[i - 1] or ilist[i] == ilist[i + 1] :
true = true + 1
if true == 0:
return False
if true > 0:
return True
main()
Your increasingorder function will almost certainly not work, because Python uses references, and the sort function modifies a list in-place and returns None. That means that after your call a = hlist.sort(), both hlist will be sorted and a will be None. so they will not compare equal.
You probably meant to do the following, which will return a sorted list instead.
a = sorted(hlist)
This function works:
def increasingorder(values):
hlist = values
a = sorted(hlist)
if a == hlist:
return True
else:
return False
You can of course simplify this down to a single line.
def increasingorder(values):
return sorted(values) == values
Your second function looks logically correct, but can be simplified down to the following.
def twoadjacentduplicates(values):
for i in range(0, len(values)-1):
if values[i] == values[i + 1] :
return True
return False
Try creating a True False function for each value check operation you want done taking the list as a parameter. then call each function like "if 1 and 2 print 3" format. That may make thinking through the flow a little easier.
Is this kind of what you were wanting?
def isincreasing(values):
if values==sorted(values):
return True
return False
def has2adjdup(values):
for x in range(len(values)-1):
if values[x]==values[x+1]:
return True
return False
if isincreasing(values) and has2adjdup(values):
print "True"

Calling a function recursively in Python by passing a List

I know there are easier ways to create a function which gives you the largest number in a list of numbers but I wanted to use recursion. When I call the function greatest, i get none. For example greatest([1,3,2]) gives me none. If there are only two elements in the list, I get the right answer so I know the problem must be with the function calling itself. Not sure why though.
def compare(a,b):
if a==b:
return a
if a > b:
return a
if a < b:
return b
def greatest(x):
if len(x)==0:
return 0
i=0
new_list=[]
while i< len(x):
if len(x)-i>1:
c=compare(x[i],x[i+1])
else:
c=x[i]
new_list.append(c)
i=i+2
if len(new_list)>1:
greatest(new_list)
else:
return new_list[0]
print greatest([1,3,2])
This line:
if len(new_list)>1:
greatest(new_list) # <- this one here
calls greatest but doesn't do anything with the value it returns. You want
return greatest(new_list)
After fixing that, your function seems to behave (although I didn't look too closely):
>>> import itertools
>>> for i in range(1, 6):
... print i, all(max(g) == greatest(g) for g in itertools.product(range(-5, 5), repeat=i))
...
1 True
2 True
3 True
4 True
5 True
A simple recursion can be like this :
from random import *
def greatest(x,maxx=float("-inf")):
if len(x)>0:
if x[0] > maxx:
maxx=x[0]
return greatest(x[1:],maxx)
else:
return maxx
lis=range(10,50)
shuffle(lis)
print greatest(lis) #prints 49

Categories