Python数组中数字的总和,忽略特定数字的部分

时间:2019-10-10 14:27:13

标签: python

我对Python还是很陌生,并且已经经历了许多教程来变得更好。

我遇到了一个难题,并找到了解决方案。但是,感觉就像是新手一样。我认为我是为回答特定问题而量身定制的。

所以问题是:

'SUMMER OF '69:返回数组中数字的总和,但忽略以6开头并扩展到下一个9的数字部分(每6个字符后至少跟9个数字)。没有数字则返回0。

summer_69([1, 3, 5]) --> 9
summer_69([4, 5, 6, 7, 8, 9]) --> 9
summer_69([2, 1, 6, 9, 11]) --> 14

我要解决的代码是:

def summer_69(arr):
    list1 = arr
    summ = int()
    for i in range(0, len(arr)):
        if 6 in list1:
            listOfRange = range(list1.index(6), list1.index(9) + 1)
            for index in listOfRange:
                    print(listOfRange)
                    arr[index] = 0
            if 6 != arr[i]:
                summ += arr[i]
            else:
                continue
        else:
            summ += arr[i]
    return summ

这是一个非常基本的问题,我非常警觉,我已经在努力解决类似问题。

15 个答案:

答案 0 :(得分:1)

考虑使用python工具简化任务的另一种方法。

制作列表的副本,以便您可以修改副本。您不会修改这些项目,因此浅表副本就足够了。

检查列表中是否有6,如果是,则使用index查找6的第一个索引,然后查找6的索引之后的前9个索引。

然后删除与该范围相对应的切片(在列表的副本中)。

然后,当不再有6s时,您可以使用sum总结列表中剩余的所有内容,并返回结果。

切片部分是最棘手的部分,看起来像这样:

# pretend we already used index to get these 

indexof6 = 4 
indexofnext9 = 10
del copyoflist[indexof6:indexof9+1]

总共看起来像这样:

def summer_69(lst):
    copyoflist = lst[:] # makes shallow copy of list
    while True:
        if 6 not in copyoflist:
            return sum(copyoflist)

        indexof6 = copyoflist.index(6)
        indexof9 = copyoflist.index(9, indexof6+1) # begin search for 9 after 6
        del copyoflist[indexof6:indexof9+1] 
>>> summer_69([1,2,6,3,2,12,1234,9,3,6,345,6,6,9,2])
8
>>> summer_69([1,2,3])
6

答案 1 :(得分:1)

这是一个使用更可重用的pythonic惯用语,生成器函数的版本,并且更加紧凑(以额外比较的代价):

def yield_non_summer(series):
  in_summer = False
  def stateful_summer_predicate(v):
    nonlocal in_summer
    if in_summer and v == 9:
      in_summer = False
      return True  # 9 is still in summer
    elif not in_summer and v == 6:
      in_summer = True
    return in_summer
  return (v for v in series if not stateful_summer_predicate(v))

def summer_69(series):
  return sum(yield_non_summer(series))

或者,用更少的行:

def yield_non_summer(series):
  in_summer = False
  def stateful_summer_predicate(v):
    nonlocal in_summer
    in_summer = (in_summer or v == 6) and v != 9
    return in_summer
  return (v for v in series if not stateful_summer_predicate(v))

def summer_69(series):
  return sum(yield_non_summer(series))

答案 2 :(得分:1)

import {
  AdMobInterstitial,setTestDeviceIDAsync
} from 'expo-ads-admob';

export default class App extends Component {

 
  async componentDidMount(){
    await setTestDeviceIDAsync('EMULATOR');
      AdMobInterstitial.setAdUnitID('ca-app-pub-xxxxxxxxxxxxxxxxxxxxxxxx'); 
      await AdMobInterstitial.requestAdAsync({ servePersonalizedAds: true});
     await AdMobInterstitial.showAdAsync();
    
    
     const that = this;
     setTimeout(() => {
     // write your functions    
     that.componentDidMount();
   },60000);
    }
  


  render() {
    return (
    ---------
    ---------
    --------
    --------
       
    );
  }
}

答案 3 :(得分:1)

一种简单的方法是制作一个过滤器并对结果求和。

代码

def filter_substring(seq, start, end):
    """Yield values outside a given substring."""
    release = True

    for x in seq:

        if x == start:
            release = False
        elif x == end:
            release = True
        elif release:
            yield x


def summer(seq):
    """Return the sum of certain values."""
    return sum(filter_substring(seq, 6, 9))

演示

assert 0 == summer([])
assert 6 == summer([1, 2, 3])
assert 6 == summer([1, 2, 3, 6, 8, 7, 9])
assert 9 == summer([1, 3, 5])
assert 8 == summer([3, 5, 6, 7, 8, 9])
assert 15 == summer([2, 1, 6, 9, 12])
assert 16 == summer([2, 1, 6, 9, 1, 6, 6, 120, 9, 9, 12])


详细信息

filter_substring() +

这是一个生成器函数。迭代输入序列,仅在条件适当时(即,release保持True时才产生值。

>>> list(filter_substring("abcde", "c", "d"))
['a', 'b', 'e']
>>> list(filter_substring([0, 1, 2, 3, 10], 1, 3))
[0, 10]

summer()

在这里,我们简单地将filter_range()的收益相加。

+ 注意:substring是连续的subsequence;这可能会或可能不会在Python中包含字符串。

答案 4 :(得分:1)

将使用索引:

def summer_69(arr):
    y = []
    for x in arr:
        if 6 in arr:
            a = arr.index(6)
            b = arr.index(9)
            del arr[a:b+1]
            y = arr
        elif arr == []:
            return "0"
        else:
            return sum(arr)
    return sum(y)
print(summer_69([]))                                                          #0
print(summer_69([1, 3, 5]))                                                   #9
print(summer_69([4, 5, 6, 7, 8, 9]))                                          #9
print(summer_69([2, 1, 6, 9, 11]))                                            #14
print(summer_69([2, 1, 6, 9, 6, 11, 25, 36, 11, 9, 4, 6, 4, 6, 3, 9, 15]))    #22

答案 5 :(得分:0)

这是我的做法,首先是这样:

def summer_69(series):
  in_summer = False
  cur_sum = 0
  for v in series:
    if in_summer:
      if v == 9:
        in_summer = False
    else:
      if v == 6:
        in_summer = True
      else:
        cur_sum += v
  return cur_sum

答案 6 :(得分:0)

类似这样的东西:

def summer_69(lst):
  """Return the sum of the numbers in the array, 
     except ignore sections of numbers starting with a 6 and extending to the next 9 
     (every 6 will be followed by at least one 9). Return 0 for no numbers
  """
  if not lst:
    return 0
  else:
    _sum = 0
    active = True
    for x in lst:
      if active: 
        if x != 6:
          _sum += x
        else:
          active = False
      else:
        if x == 9:
          active = True
    return _sum

print(summer_69([1, 3, 5]))
print(summer_69([4, 5, 6, 7, 8, 9]))
print(summer_69([2, 1, 6, 9, 11]))

输出

9
9
14

答案 7 :(得分:0)

def summer_69(arr):
    if 6 in arr:
        c=arr[arr.index(6):arr.index(9)+1]
        for i in c:
            arr.remove(i)
        print(arr)
        return sum(arr)
    else:
        return sum(arr)

summer_69([1,2,3,4,5,6,7,8,9,10,11,12])

答案 8 :(得分:0)

这将起作用:

allDates: Array(65)
0: {date: "2/24/20", ricoverati_con_sintomi: 0, terapia_intensiva: 0, totale_ospedalizzati: 0, isolamento_domiciliare: 0, …}
1: {date: "2/25/20", ricoverati_con_sintomi: 0, terapia_intensiva: 0, totale_ospedalizzati: 0, isolamento_domiciliare: 0, …}

答案 9 :(得分:0)

def summer_69(arr):
    a = 0
    for nums in arr: 
        if nums == 6:
            for items in arr[arr.index(6):]:
                a = a+ items
                if items == 9:
                    break
    return sum(arr)-a

答案 10 :(得分:0)

def summer_69(arr):
        x = arr.count(6)
        y = arr.count(9)
        # to decide number of iteration required for loop
        z = min(x,y)
        k = 0
        while k < (z) :
            m = arr.index(6)
            n = arr.index(9)
            del arr[m:(n+1)]
            k = k + 1
        print(arr)
        return sum(arr)

答案 11 :(得分:0)

这也适用于summer_69问题,也可用于过滤子字符串

def filter_substring(seq, start, end):
flag = False
for char in seq:
    if char == start:
        flag = True
        continue
    elif flag:
        if char == end:
            flag = False 
        else:
            continue
    else:
        yield char

def summer_69(seq, start, end):
    return sum(filter_substring(seq, start, end))

def print_substring(string, start, end):
    return list(filter_substring(string, start, end))

示例::

seq = [4, 5, 9, 6, 2, 9, 5, 6, 1, 9, 2]
print(summer_69(seq, start=6, end=9))


string = "abcdef"
print(print_substring(string, start='c', end='e'))

答案 12 :(得分:0)

如果您是新手,这可能是最好的答案。我已经尽可能地简化了它。你只需要知道 enumerate、function、for 循环、tuple unpacking、if/else 语句和 break 函数。所以让我们直接进入答案。

def myfunc(a):
mylist=[]
sum1 = 0
for b,c in enumerate(a):
    if c==6:
       for d in  a[:b]:
           mylist.append(d)
for e,f in enumerate(a):
    if f==9:
       for j in a[e+1:]:
           mylist.append(j)
for y in a:
    if y==6:
      break
    else:
       mylist.append(y)
for k in mylist:
    sum1 = sum1+k
print(sum1)

myfunc([1,3,5])

答案 13 :(得分:0)

替换

list1.index(9)+1 
by 
list1.index(9,list1.index(6)+1)+1

在第 6 行。 这将在 6 之后开始搜索 9。

答案 14 :(得分:0)

对于那些感兴趣的人,这是我对这个问题的解决方案:

def summer_69(arr):
    skate = arr
    guitar = []
    for i in range(len(arr)):
        if 6 in arr:
            guitar = skate[skate.index(6):skate.index(9)+1]
            return abs(sum(skate) - sum(guitar))
        else:
            return sum(skate)