给定一个包含表示数字间距的列表nums,其中间距是由2个数字构成的元组对象,并且元组中都按升序排列。例如:[(1, 5), (6, 10)]
表示有2个间距,第一个间距是(1, 5)
,长度为5-1=4
。同时,如果多个间距存在交叠,则在计算时应扣除交叠部分长度。
请编写一个函数,计算出列表中所有间距长度的总和。
示例:
输入:[(1, 5), (6, 10)]
,输出:8
。
输入:[(1, 4), (7, 10), (3, 5)]
,输出:7
。
题目难度:中等
题目来源:CodeWars:Sum of Intervals
def solution(nums: list) -> int:
# your code
assert solution([(1, 5)]) == 4
assert solution([(1, 5), (6, 10)]) == 8
assert solution([(1, 5), (1, 5)]) == 4
assert solution([(1, 4), (7, 10), (3, 5)]) == 7
nobugs
2021 年12 月 30 日 02:40
2
def solution(nums: list) -> int:
return len(set([i for n in nums for i in range(*n)]))
assert solution([(1, 5)]) == 4
assert solution([(1, 5), (6, 10)]) == 8
assert solution([(1, 5), (1, 5)]) == 4
assert solution([(1, 4), (7, 10), (3, 5)]) == 7
2 个赞
Kawi
2021 年12 月 30 日 06:54
3
def solution(nums: list) -> int:
set1 = set()
for j in nums:
for h in range(*j):
set1.add(h)
return len(set1)
Huis
2021 年12 月 30 日 07:23
4
def solution(nums: list) -> int:
new_list1,new_list2 = zip(*nums)
new_tup = zip(sorted(new_list1),sorted(new_list2))
result = 0
up = None
for tt in new_tup:
if up is not None and up[1]>tt[0]:
result += abs(tt[1]-up[1])
up[1]=tt[1]
else:
result += abs(tt[1]-tt[0])
up = list(tt)
return result
def solution(nums: list) -> int:
result = []
for i in nums:
# 元组解包
for j in range(*i):
result.append(j)
return len(set(result))
assert solution([(1, 5)]) == 4
assert solution([(1, 5), (6, 10)]) == 8
assert solution([(1, 5), (1, 5)]) == 4
assert solution([(1, 4), (7, 10), (3, 5)]) == 7
def solution(nums: list) -> int:
res = []
for i in nums:
for j in range(*i):
res.append(j)
return len(set(res))
assert solution([(1, 5)]) == 4
assert solution([(1, 5), (6, 10)]) == 8
assert solution([(1, 5), (1, 5)]) == 4
assert solution([(1, 4), (7, 10), (3, 5)]) == 7
Mooii
2021 年12 月 31 日 02:46
7
def solution(nums: list) -> int:
sum_list = []
for i in nums:
for j in range(*i):
sum_list.append(j)
return len(set(sum_list))
assert solution([(1, 5)]) == 4
assert solution([(1, 5), (6, 10)]) == 8
assert solution([(1, 5), (1, 5)]) == 4
assert solution([(1, 4), (7, 10), (3, 5)]) == 7
def solution12(ll: list):
return len(set([i for n in ll for i in range(*n)]))
assert solution12([(1, 4), (7, 10), (3, 5)]) == 7
lekaixin
(ALe阿乐)
2024 年11 月 13 日 08:55
9
def solution(nums: list) -> int:
res_list = []
for i in nums:
for j in range(*i):
res_list.append(j)
return len(set(res_list))
assert solution([(1, 5)]) == 4
assert solution([(1, 5), (6, 10)]) == 8
assert solution([(1, 5), (1, 5)]) == 4
assert solution([(1, 4), (7, 10), (3, 5)]) == 7