This is a codewars challenge where you have to return the sum of the given arguments.
Instructions:
Calculate the sum of all the arguments passed to a function.
Note: If any of the arguments is not a finite number the function should return false/False instead of the sum of the arguments.
Here's my code:
def sum_all(*args):
sum = 0
for str(num) in args:
if not num.isdigit():
return False
else:
int(sum) += num
return sum
Currently I'm getting this error:
File "", line 9
SyntaxError: can't assign to function call
That error message is actually happening in two places:
Here:
for str(num) in args:
and here:
int(sum) += num
You cannot cast to string and int the way you are attempting to.
What you should do instead, is keep your iteration as:
for num in args:
Then, you can check if digit by doing this:
if not str(num).isdigit():
Finally, when you get to summing everything, simply cast num to int(num) to handle the case if you pass something like [1, 2, '3', 4] (not the 3 as a string):
sum += num
So, with that in mind, your code will look like this:
def sum_all(*args):
sum = 0
for num in args:
if not str(num).isdigit():
return False
else:
sum += int(num)
return sum
However, as you pointed out in your comment, there is a test case for negative numbers. This is where the above code breaks. Because, negative numbers as a string:
"-343"
Do not pass isdigit.
If you put this in your interpreter, it will return False:
"-343".isdigit()
So, with all this in mind, you can actually further simplify your code when you remove that to just have this:
def sum_all(*args):
try:
return sum(int(i) for i in args)
except:
return False
Demo:
print(sum_all(1,2,3,4,5))
Outputs:
15
First of all, don't overwrite existing functions such as sum. Use a different variable name (e.g. sum_). Second, your problem is on the for str(num) in args line. This needs to be for num in args:, with a modification of the following line for str(num).
def sum_all(*args):
sum_ = 0
for num in args:
if not str(num).isdigit():
return False
else:
sum_ += float(num)
return sum_
>>> sum_all('a', 2)
False
>>> sum_all(1, 2)
3.0
>>> sum_all(1, 2, '4')
7.0
Here is an alternative approach to coding the function that uses a generator comprehension to try and sum the arguments but returns False if it fails:
def sum_all2(*args):
try:
return sum(i for i in args)
except:
return False
>>> sum_all2(1, 2, '4.5')
False
>>> sum_all2(1, 2, '4') # I argue that '4' is a string, not a finite number.
False
>>> sum_all2(1, 2)
3
>>> sum_all2(1, 2, 3.5)
6.5
>>> sum_all2(1, 2, -3.5)
-0.5
You're overthinking this. There are two parts to this to note:
sum is a function that already takes in a collection and gives you its sum.
You want to reject the collection if none of them are numeric types.
Here's a start: this particular method will reject if none of the values are int. I leave expanding this out to float types as an exercise for the reader.
def sum_or_reject(li):
return sum(li) if all([isinstance(i, int) for i in li]) else False
The minimal change to make your logic run is:
def sum_all(*args):
sum = 0
for s in args:
num = str(s)
if not num.isdigit():
return False
else:
sum += int(num)
return sum
The line number in the question is misleading, and there are two issues: First, you need a variable for the iteration. Second, you need a variable for the += assignment. In both cases you try to apply a cast, bust the result of that would not longer be a variable and thus cannot be used as target for the assignment.
Likewise a minimal change to your code:
def sum_all(*args):
try:
return sum(int(i) for i in args)
except:
return False
print(sum_all(10,'-1',10))
Related
I have been working on spliting integers into the digits they are comprised of and then checking whether there are any repeated numbers in the list. However the code seems to always say there are no repeated numbers, even if there are.
My Code:
def repeatCheck(myList, repeatedNumber):
seen = set()
for number in myList:
if number in seen:
repeatedNumber = True
seen.add(number)
return repeatedNumber
def numberWorks(number, finalNumber):
digits = [int(n) for n in str(number)]
repeatedNumber = False
repeatCheck(digits, repeatedNumber)
if repeatedNumber == False:
print(number, "succeeded repeatedNumber")
found = True
else:
print(number, "failed repeatedNumber")
pass
return number
number = 1000000000
while found == False:
numberWorks(number, finalNumber)
number += 1
print(finalNumber)
With input number 1000000000, the output should be 1023456789
Please let me know of anything that could be done to solve it, or if the code I have given is not enough.
Thank you.
When you call the function repeatCheck() you don't pass a reference to the variable repeatedNumber, so any changes to the variable do not affect the original definition of repeatedNumber. Therefore, the repeatedNumber defined in numberWorks() is never updated.
what you could do instead is assign the return value of repeatCheck to repeatedNumber.
repeatedNumber = False
repeatedNumber = repeatCheck(digits)
and rewrite repeatCheck to return True or False upon seeing a repeat:
def repeatCheck(myList):
seen = set()
for number in myList:
if number in seen:
return True
seen.add(number)
return False
This way you circumvent the ambiguity of reusing the variable name repeatedNumber
If you would like to check for repeated digits inside a number here's a quick way to do it that returns a boolean.
def noRepeatedDigits(number:int) -> bool:
return all([str(number).count(i) == 1 for i in set(str(number))])
print(noRepeatedDigits(12344))
print(noRepeatedDigits(1234))
False #indicates it failed the check
True #indicates it passed the check
I would simply delete all your code and do this.
def repeatCheck(repeatedNumber):
numbersdub = list(str(repeatedNumber))
numbers = set(numbersdub)
for num in numbers:
numbersdub.remove(num)
return set(numbersdub)
print(repeatCheck(78788))
This will give you a set of all dubbels.
Alternative one-line solution:
finalNumber = next(n for n in range(1000000000, 2000000000) if len(set(s := str(n))) == len(s))
print(finalNumber)
# 1023456789
Explanation: len(str(n)) is the number of digits of n, whereas len(set(str(n))) is the number of unique digits of n. These two quantities are equal if an only if n doesn't have repeated digits.
The whole thing is wrapped in an iterator, and next( ) returns the first value of the iterator.
My teacher solved this question "Write a function which takes a n digits number as an input and return True if the biggest digit in this number is divisible by 3" like this:
def is_divisable(n):
a = str(n)
b = 0
for i in a:
if int(i)>b:
b = int(i)
if b % 3 == 0:
return "True"
print is_divisable(67479)
I have thought of it in another way but my code is not working and
I am getting an error says:
"TypeError: 'int' object is not iterable"
def is_dvo(n):
if max(n) % 3 == 0:
return True
print is_dvo(67479)
You don't quite say what your question is, but if you want another way to solve the problem,
def is_divisable(n):
return int(max(str(n))) % 3 == 0
This code converts the number to its decimal string representation, finds the largest digit (as a character), changes that digit to an integer, checks if that is divisible by 3, then returns that answer.
If your question is why you are getting that error, your parameter n is an integer, and you try to apply the max() function to that integer. However, max() is supposed to be used on iterable objects such as strings, lists, tuples, generators, and so on. My code changes the integer to a string before using max() so it does not have that problem, and it iterates over the digits in the string.
You can condense the code to a single line:
def is_divisable(n):
return max(map(int, str(n)))%3 == 0
Try:
max(str(n), key=int) in {'3', '6', '9'}
I am creating a program to figure out the highest number of decimals in a list of numbers. Basically, a list with [123, 1233] would return 4 because 1233 has four numbers in it and it is the largest. Another example would be that [12, 4333, 5, 555555] would return 6 because 555555 has 6 numbers.
Here is my code.
def place(listy):
if len(listy) == 1:
decimal = len(str(listy[0]))
print(decimal)
else:
if len(str(listy[0])) >= len(str(listy[1])):
new_list = listy[0:1]
for i in listy[2:]:
new_list.append(i)
place(new_list)
else:
place(listy[1:])
Now, when I use print(decimal) it works, but if I change print(decimal) to return decimal, it doesn't return anything. Why is this? How do I fix this? I have come across these return statements which doing run a lot of times. Thanks in advance!
When you do a recursive call (i.e. when place calls place, and the called place returns a value, then the calling place must return it as well (i.e. the return value "bubbles up" to the initial caller).
So you need to replace every recursive call
place(...)
with
return place(...)
As others have said, there are easier solutions, such as using max(). If you want to keep a recursive approach, I would refactor your code as follows:
def place2(listy):
if len(listy) < 1:
return None
elif len(listy) == 1:
return len(str(listy[0]))
else:
v0, v1 = listy[0], listy[1]
if v1 > v0:
return place2(listy[1:])
else:
return place2([listy[0]]+listy[2:])
Although this is tail-recursive, Python does not really care so this approach will be inefficient. Using max(), or using a loop will be the better solution in Python.
It's not that the return doesn't do anything, it's that you don't propagate the return from your recursive call. You need a few more returns:
def place(listy):
if len(listy) == 1:
decimal = len(str(listy[0]))
return decimal
else:
if len(str(listy[0])) >= len(str(listy[1])):
new_list = listy[0:1]
for i in listy[2:]:
new_list.append(i)
return place(new_list) # <-- return added
else:
return place(listy[1:]) # <-- return added
You can see the print at any level, but to get it back to the caller it needs to be propagated.
The function does return the value, but it's not printing it out.
A simple way to solve this is, just call the function within a print statement.
That is:
print(place(listy))
If all you want is to find the maximum length of a list of integers, consider:
max([len(str(n)) for n in N])
For example
N = [1,22,333,4444]
max([len(str(n)) for n in N]) # Returns 4
N = [12, 4333, 5, 555555]
max([len(str(n)) for n in N]) # Returns 6
Note: This will only work for positive integers.
Or more simply:
len(str(max(N)))
Which will also only work for positive integers.
Use ''global variable'' (google it) to access and change a variable defined outside of your function.
I have a function:
def containsNoDivisor(n, ps):
'''n is an integer and ps is a list of integers. Returns True if
and only if there is no integer in ps that divides n. '''
for p in ps:
if n % p == 0:
return False
print True
Then I need to create another function, that computes a list of primes < n, from the function above. So far I have:
def findPrimes(n):
primes = [2]
for i in range(3,n):
if containsNoDivisor(i, primes):
primes.append(i)
return primes
But it is returning True's instead of the primes?
It looks like you're printing True instead of returning it in your containsNoDivisor function. It should look like this:
def containsNoDivisor(n, ps):
'''n is an integer and ps is a list of integers. Returns True if
and only if there is no integer in ps that divides n. '''
for p in ps:
if n % p == 0:
return False
return True
The print statement simply outputs the value to the console - if you're trying each function in the interactive shell, it's an easy mistake to make. return will actually take the value and pass it back to whatever called it, allowing data to be used outside of the function that created or processed it.
def containsNoDivisor(n, ps):
'''n is an integer and ps is a list of integers. Returns True if
and only if there is no integer in ps that divides n. '''
for p in ps:
if n % p == 0:
return False
print True
^^^^^
should be return
You are testing every number from 3 to n. You don't need to test even numbers since all evens > 2 are composite. Try stepping 2 rather than 1: 3, 5, 7, 9, 11, ...
I've just started exploring the wonders of programming. I'm trying to write a code to identify numeric palindromes. Just looking at numbers and not texts. I'm trying to learn to use recursion here. But I'm just not getting anywhere and I can't figure out what's wrong with it.
My idea was to check first string vs the last, then delete these two if they match, and repeat. Eventually there'll be nothing left (implying it is a palindrome) or there will be a couple that doesn't match (implying the reverse).
I know there are better codes to finding palindromes in but I just wanted to try my hand at recursion.
So what's wrong?
def f(n):
global li
li=list(str(n))
if (len(li)==(1 or 0)):
return True
elif li[len(li)-1]==li[0]:
del li[0]
del li[len(li)-1]
if len(li)==0:
return True
if len(li)>0:
global x
x=''.join(li)
str(x)
f(x)
else:
return False
Thanks in advance!
A few comments
Why are x and li globals? In recursion, all variables should be local.
Why are you converting back and forth between str and list? You can subscript both of them
You need to return the result of your recursive call: return f(x)
Try these suggestions, and see how it works out.
Before looking into it too much, if (len(li)==(1 or 0)): doesn't do what you're expecting it to do. (1 or 0) will always evaluate to 1.
You probably want:
if len(li) in (1, 0):
There are a couple of problems with your solution. Let me analyse them line by line.
You don't need global statements if you don't intend to change variables outside of function scope. Thus, I removed two lines with global from your code.
li=list(str(n)): casting a string to a list is unnecessary, as a string in Python has a similar interface to an immutable list. So a simple li = str(n) will suffice.
if (len(li)==(1 or 0)):: although it looks OK, it is in fact an incorrect way to compare a value to a few other values. The or operator returns the first "true" value from its left or right operand, so in this case it always returns 1. Instead, you can use the in operator, which checks whether the left operand is an element of a right operand. If we make the right operand a tuple (1, 0), all will be well. Furthermore, you don't need parentheses around the if statement. You should write: if len(li) in (1, 0):
elif li[len(li)-1]==li[0]: is fine, but we can write this shorter in Python, because it supports negative list indexing: elif li[-1] == li[0]:
Because we don't use lists (mutable sequences) because of point 2., we can't do del li[0] on them. And anyway, removing the first element of a list is very inefficient in Python (the whole list must be copied). From the very same reason, we can't do del li[len(li)-1]. Instead, we can use the "splicing" operator to extract a substring from the string: li = li[1:-1]
if len(li)==0: is unnecessary long. In Python, empty strings and lists resolve to False if tested by an if. So you can write if not li:
if len(li)>0:: You don't have to check again if li is not empty -- you checked it in point 6. So a simple else: would suffice. Or even better, remove this line completely and unindent the rest of the function, because the body of the if in 6. contains a return. So if we didn't enter the if, we are in the else without writing it at all.
x=''.join(li): We don't need to convert our string to a string, because of the decision made in 2. Remove this line.
str(x): This line didn't do anything useful in your code, because str() doesn't modify its argument in place, but returns a new value (so x = str(x) would have more sense). You can also remove it.
f(x): This is a valid way to call a recursive function in Python, but you have to do something with its value. Return it perhaps? We'll change it to: return f(li) (as we don't have an x variable any more).
We end up with the following code:
def f(n):
li = str(n)
if len(li) in (1, 0):
return True
elif li[-1] == li[0]:
li = li[1:-1]
if not li:
return True
return f(li)
else:
return False
It's almost what we need, but still a little refinement can be made. If you look at the lines if not li: return True, you'll see that they are not necessary. If we remove them, then f will be called with an empty string as the argument, len(li) will equal 0 and True will be returned anyway. So we'll go ahead and remove these lines:
def f(n):
li = str(n)
if len(li) in (1, 0):
return True
elif li[-1] == li[0]:
li = li[1:-1]
return f(li)
else:
return False
And that's it! Good luck on your way to becoming a successful programmer!
Split the whole show out into a list, then just:
def fun(yourList):
if yourList.pop(0) == yourList.pop(-1):
if len(yourList) < 2:
return True # We're a palindrome
else:
return fun(yourList)
else:
return False # We're not a palindrome
print "1234321"
print fun(list("1234321")) # True
print "6234321"
print fun(list("6234321")) # False
def palindrome(n):
return n == n[::-1]
It's hard to tell what you intend to do from your code, but I wrote a simpler (also recursive) example that might make it easier for you to understand:
def is_palindrome(num):
s = str(num)
if s[0] != s[-1]:
return False
elif not s[1:-1]:
return True
else:
return is_palindrome(int(s[1:-1]))
number = int(raw_input("Enter a number: "))
rev = 0
neg = number
original = number
if (number < 0):
number = number * -1
else:
number = number
while ( number > 0 ):
k = number % 10
number = number / 10
rev = k + ( rev * 10 )
if (number < 1):
break
if ( neg < 0 ):
rev = ( rev * -1)
else:
rev = (rev)
if ( rev == original):
print "The number you entered is a palindrome number"
else:
print "The number you entered is not a palindrome number"
This code even works for the negative numbers i am new to programming in case of any errors
dont mind.