'Coding Bat python Logic 2 question 3 Lucky_sum
https://codingbat.com/prob/p107863
Given 3 int values, a b c, return their sum. However, if one of the values is 13 then it does not count towards the sum and values to its right do not count. So for example, if b is 13, then both b and c do not count.
This is my code what's wrong with it? Need Help THX
def lucky_sum(a, b, c):
sum = a + b + c
if a == 13:
sum = sum - a - b
if b == 13:
sum = sum - b - c
if c == 13:
sum = sum - c
return sum
Solution 1:[1]
Might be overkill but you could use itertools.takewhile
to continue summing values excluding a 13
if encountered and on. This would generalize to any number of arguments in an *args
type of approach.
from itertools import takewhile
def lucky_sum(a, b, c):
return sum(takewhile(lambda i: i != 13, [a, b, c]))
Some examples
>>> lucky_sum(1, 2, 3)
6
>>> lucky_sum(1, 2, 13)
3
>>> lucky_sum(1, 13, 3)
1
Solution 2:[2]
if one of the values is 13 then it does not count towards the sum and values to its right do not count
Your code only handles the immediate value to 13
's right, but the spec indicates that you should exclude all values to its right.
def lucky_sum(a, b, c):
sum = a + b + c
if a == 13:
sum = sum - a - b - c
if b == 13:
sum = sum - b - c
if c == 13:
sum = sum - c
return sum
However if you could add an abitrary number of numbers, this becomes untenable. Consider instead something that scales:
def lucky_sum(*addends):
sum_ = 0
for n in addends:
if n == 13:
break # stop summing immediately
sum_ += n
return sum_
Solution 3:[3]
can try this:
def lucky_sum(a, b, c):
if a==13:
return 0
elif b==13:
return a
elif c==13:
return a+b
else:
return a+b+c
Solution 4:[4]
I tried this logic in java
#logic 1 : using loop
public int luckySum(int a, int b, int c) {
int[] arr = {a,b,c};
int sum = 0;
for (int i = 0; i< arr.length; i++){
if(arr[i] == 13){
break;
}
sum += arr[i];
}
return sum;
}
#logic 2 : without using loop
public int luckySum(int a, int b, int c) {
if(a==13) return 0;
else if(b==13) return a;
else if(c==13) return a+b;
return a+b+c;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Cory Kramer |
Solution 2 | Adam Smith |
Solution 3 | |
Solution 4 | Gautam Kumar |