python - how to use two variables in for loop? -
define function calls addfirstandlast(x) takes in list of numbers , returns sum of first , last numbers.
examples
>>> addfirstandlast([]) 0 >>> addfirstandlast([2, 7, 3]) 5 >>> addfirstandlast([10]) 10
my question can not use 2 variables in loop, should , how fix error. , improved code of problem.
def addfirstandlast(x): total = 0 total1 = 0 total2 = 0 pos_last = [] num, last in x: num = str(num) num = num[0] total1 += int(num) last = last % 10 pos_last = pos_last.append(last) total = sum(pos_last) total2 = total+total1 return total2 print addfirstandlast([2, 7, 3])
3 distinct cases: 1) list empty, 2) list has 1 element, 3) list has 2 or more elements.
try without loop:
def addfirstandlast(x): if len(x) == 0: return 0 elif len(x) < 2: return x[0] else: return x[0]+x[-1] >>> print addfirstandlast([2, 7, 3]) 5 >>> print addfirstandlast([2, 3]) 5 >>> print addfirstandlast([3]) 3
Comments
Post a Comment