我正在处理以下codebat问题:
返回数组中数字的总和,除了忽略以6开头并延伸到下一个7的数字部分(每6个后跟至少7个)。返回0表示没有数字。
sum67([1, 2, 2]) → 5 sum67([1, 2, 2, 6, 99, 99, 7]) → 5 sum67([1, 1, 6, 7, 2]) → 4
我的解决方案是:
def sum67(nums):
sum = 0
throwaway = 0
for i in range(len(nums)):
if throwaway == 0:
if nums[i] == 6:
throwaway = 1
elif throwaway == 1 and i > 0 and nums[i-1] == 7:
throwaway = 0
if throwaway == 0:
sum += nums[i]
return sum
我完全知道这不是最好的解决方案,但我很想知道为什么这是错误的。你能否解释一下为什么这是错误的,在哪种特殊情况下它会给出错误的结果?
答案 0 :(得分:5)
好吧,你的程序有一个bug。检查以下结果:
print sum67([1,2,5])
print sum67([1,2,6,5,7])
print sum67([1,2,6,5,7,6,7])
这将打印:
8
3
16 <-- wrong
如果7之后立即显示6,您将添加6和所有后续数字。我不确定输入中是否允许有多个6 ... 7的范围,但如果是,则必须修复算法。
这个简单的实现确实返回了正确的数字:
def sum67(nums):
state=0
s=0
for n in nums:
if state == 0:
if n == 6:
state=1
else:
s+=n
else:
if n == 7:
state=0
return s
此外,如果由于某些不明原因而不需要使用索引,则可以直接迭代列表的元素(for element in list: ...
)。
答案 1 :(得分:2)
以下是我的解决方案供您参考:
def sum67(nums):
flag=False
sum=0
for num in nums:
if(num==6): #Turn the flag on if the number is 6
flag=True
continue
if(num==7 and flag is True): #Turn the flag Off when 7 is seen after 6
flag=False
continue
if(flag is False): #Keep on adding the nums otherwise
sum+=num
return sum
答案 2 :(得分:1)
我的方法是构建一个仅包含有效段的新列表,即没有以 6 开头并以 7 结尾的对应 6 的段。然后我简单地计算了该新列表的元素。在codingbat练习平台上完美运行
def sum67(nums):
lst =[] #holds result after discarding invalid segments
while 6 in nums: # Continue until no more 6's found in nums segment
#Find the first 6
idx6 = nums.index(6)
#Build list upto but excluding the first 6
lst += nums[:idx6]
#Find the next 7
idx7 = nums[idx6:].index(7) # this would be relative to nums[idx6:]
#slice
idx = idx6+idx7 # absolute position of 7 w.r.t nums
nums = nums[idx+1:] # slice from the position of the 7 to end
lst += nums # takes care of any leftovers after the last 7
return sum(lst)
可以压缩成更少的代码行,但我想保持代码的可读性。我想知道是否有递归的方法来解决这个问题。正在努力。
感谢大家提供出色的替代解决方案
答案 3 :(得分:1)
public int sum67(int[] nums) {
int sum=0;
for(int i=0; i<nums.length ; i++)
{
if(nums[i]==6)
for(int k=i+1 ; k<nums.length ; k++ )
{if(nums[k]==7)
{i=k; break;}
}
else if(nums[i]==6)
sum=sum+nums[i];
else
sum=sum+nums[i];
}
return sum;
}
答案 4 :(得分:1)
只需添加,如果最后一个元素是7,则不需要遍历每个元素。问题指出:“忽略以6开头并扩展到下一个7的数字部分(每6个数字后至少跟一个7)”。一旦找到6,就可以简单地检查最后一个元素是否为7,如果是,则简单地将其求和并返回;否则,您可以继续浏览其余元素。在数组中使用大量元素时,这很有用。 例如[1、2、2、6、99、99、2、99、99、2、99、99、2、99、99、7]
我的解决方案:
def sum67(arr):
sum = 0
tmp = 0
for n in arr:
if n == 6:
tmp = 6
continue
if tmp == 6:
if n == 7:
tmp = 0
continue
elif arr[-1] == 7:
break
else:
continue
sum += n
return sum
答案 5 :(得分:0)
def sum67(nums):
while nums.count(6) >= 1:
list = (nums[0:nums.index(6)]) + (nums[nums.index(7)+1:len(nums)])
nums = list
return sum(nums)
答案 6 :(得分:0)
def sum67(nums):
cnt = 0
ignore = False
for num in nums:
if not ignore and num == 6:
ignore = True
if not ignore:
cnt = cnt + num
if ignore and num == 7:
ignore = False
return cnt
答案 7 :(得分:0)
def sum_69(arr):
x=arr.index(6)
y=arr.index(9)
if 6 not in arr:
return sum(arr)
else:
sum1=arr[:x]
sum2=arr[y+1:]
sum3=sum1+sum2
return sum(sum3)
答案 8 :(得分:0)
def sum67(nums):
c=0
state=True
for i in nums:
if state:
if i==6:
state=False
else:
c+=i
else:
if i==7:
state=True
return c
答案 9 :(得分:0)
使用迭代器只是一种短而有效的(O(n)时间,O(1)空间)替代方法:
def sum67(nums):
it = iter(nums)
return sum(x for x in it if x != 6 or 7 not in it)
这主要是对值求和。但是无论何时遇到6,7 not in it
都会消耗所有值,直到下一个7(并且它是假的,因此从6到7的值都不会将其求和)。
答案 10 :(得分:0)
这可能不是最好的解决方案,但是它简单易行,并且在所有情况下都能正确输出
def sum67(nums):
sum = 0
i = 0
while( i < len(nums)):
if nums[i] == 6:
while(nums[i] != 7):
i += 1
else:
sum += nums[i]
i += 1
return sum
答案 11 :(得分:0)
def sum67(nums):
sum=0
sum6=0
for n in nums:
sum+=n
if nums.count(6) >= 1:
a=nums.index(6)
b=nums.index(7)+1
nums67=nums[a:b]
for i in nums67:
sum6 += i
return sum - sum6
答案 12 :(得分:0)
这是我的13行答案,它使用列表索引位置排除每对[6..7]对所包围的值。
技术:减去被排除的元素(之和)后,返回数组元素的总和。
def sum67(nums):
idx_list=[]
for i in range(len(nums)):
if nums[i]==6:
c_6 = i # index pos of 6
j = c_6+1 # counter to find index position of 7
while nums[j]!=7: # stop search when 7 spotted in list
j+=1
c_7 = j # index pos of 7
idx_list += list(range(c_6,c_7+1)) # list of index position(s) of elements to be excluded
idx_main = list(set(idx_list)) # set() removes repeated index positions captured while looping
del_val = [nums[i] for i in idx_main]
return sum(nums)-sum(del_val)
答案 13 :(得分:0)
也许是更Python化的方法?
def sum67(arr):
if (6 in arr):
i1 = arr.index(6)
i2 = arr[i1:].index(7)
res = sum(arr[0:i1]+arr[i1+i2+1:])
else:
res = sum(arr)
return res
答案 14 :(得分:0)
没有while和for循环的简化代码:
def summer_69(arr):
pos6 = 0;
pos9 = 0;
newArr = [];
if 6 in arr:
pos6 = arr.index(6);
if 9 in arr:
pos9 = arr.index(9);
if 6 in arr and 9 in arr :
newArr = arr[0:pos6] + arr[pos9+1:len(arr)];
else:
newArr = arr;
return sum(newArr);
pass
答案 15 :(得分:0)
var options = [{firstName:"John", lastName:"Doe", age:46}, {firstName:"Mike", lastName:"Smith", age:46}, {firstName:"Joe", lastName:"Dirt", age:46}];
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
var text = new Array();
for (var key in array[i]) {
// Set its contents:
text.push(array[i][key]);
}
item.appendChild(document.createTextNode(text.join(",")));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
// Add the contents of options[0] to #foo:
alert(makeUL(options).outerHTML);
答案 16 :(得分:0)
def sum67(nums):
sum = 0
sumbrake = False
for i in nums:
if i != 6 and sumbrake == False:
sum += i
else:
sumbrake = True
if i == 7:
sumbrake= False
return sum
答案 17 :(得分:0)
我希望这会有所帮助:)
def sum67(nums):
result = 0
inside = False
for i in range(len(nums)):
if not inside and nums[i] != 6:
result += nums[i]
if nums[i] == 6:
inside = True
if nums[i] == 7:
inside = False
return result
答案 18 :(得分:0)
为此,我的解决方案我知道这是易读的,但不是最好的代码:
def sum67(nums):
offcount = False
sum = 0
for i in range(len(nums)):
if offcount == False:
if nums[i] == 6:
offcount = True
else:
sum = sum + nums[i]
else:
if nums[i] == 7 :
offcount = False
return sum
答案 19 :(得分:0)
好吧,您可以使用嵌套循环。
def sum67(nums):
s=0
flag=1
for n in nums:
while flag:
if n!=6:
s+=n
break
else:
flag=0
while not flag:
if n!=9:
break
else:
flag=1
return s
答案 20 :(得分:0)
这是我的6班机答案。希望这会有所帮助
def summer_67(arr):
s = 0
for x in arr:
if x not in range(6,7+1):
s = s + x
return s
答案 21 :(得分:0)
这是我对@TheNeophyte代码的编辑。我喜欢这个解决方案,因为我可能会解决这个问题。唯一的编辑实际上是取出
if i<len(nums) and nums[i]!=6:
只是简单地说出一个elif声明
i<len(nums)
因为在第一个while循环之后不再需要它。
我在VVV下面的编辑
def sum67(anArray):
arrTotal = 0
n =0
while n < len(anArray):
if anArray[n] == 6:
while anArray[n] != 7:
n+=1
n+=1
elif anArray[n] != 6:
arrTotal += anArray[n]
n+=1
return arrTotal
答案 22 :(得分:0)
def detect67(nums):
count = nums.count(6)
pos6 = 0
pos7 = 0
sum1 = []
for i in range (len(nums)):
sum1.append(nums[i])
# if I do just sum1 = nums, they use SAME memory locations.
#print ("Count=",count)
for i in range (count):
pos6 = sum1.index(6)
pos7 = sum1.index(7)
if pos7<pos6:
sum1[pos7] = 0
pos7 = sum1.index(7)
del nums[pos6:pos7+1]
del sum1[pos6:pos7+1]
count = nums.count(6)
if count == 0:
return (nums)
return (nums)
def sum67(nums):
detect67(nums)
sums=0
if nums == []:
return 0
for i in range (len(nums)):
sums+=nums[i]
return sums
答案 23 :(得分:0)
我的解决方案:
def sum67(nums):
result = 0
flag = True
for num in nums:
if num == 6:
flag = False
if flag:
result += num
if num == 7:
flag = True
return result
答案 24 :(得分:0)
这是我对这个问题的解决方案。正如已经回答的那样,问题是当一个6在7之后立即发生时。我以稍微不同的方式解决了这个问题,所以我想我会发布它。
def sum67(nums):
total = 0
i=0
while i < len(nums):
if nums[i] == 6:
while nums[i] != 7:
i+=1
i+=1
if i<len(nums) and nums[i]!=6:
total+=nums[i]
i+=1
return total
答案 25 :(得分:-1)
这可能会帮助您:
def sum_67(arr):
while 6 in arr:
del arr[arr.index(6):arr.index(7)+1]
return sum(arr)