Python:每日一题 176
本帖最后由 冬雪雪冬 于 2018-4-13 15:05 编辑我们的玩法做了一下改变:
1. 楼主不再提供答案。
2. 请大家先独立思考,再参考其他鱼油的解答,这样才有助于自己编程水平的提高。开始阶段是看不到其他人的回帖的,等答题完成,开始评分时再取消限制。
3. 鼓励大家积极答题,奖励的期限为出题后24小时内。
4. 根据答案的质量给予1~3鱼币的奖励。
题目:
将一个整数列表分隔为两个列表,使两个列表数字之和的差值的绝对值最小。
例如列表为
可以分割为和
也可以分割为和
即可以在数字之间分隔,也可以在数字内部按位分隔。
注:分隔不能调整前后的次序,-12不能分割为-和12 本帖最后由 塔利班 于 2018-4-13 18:21 编辑
def ssum(s):
if s=='':
return 0
else:
return eval(s)
def cut(x):
L=[]
for i in range(len(x)):
a=x
l=len(str(a))
if a>=0:
for j in range(0,l+1):
L.append((i,j,abs(sum(x[:i])+ssum(str(a)[:j])-ssum(str(a))-sum(x))))
else:
for j in range(2,l+1):
L.append((i,j,abs(sum(x[:i])+ssum(str(a)[:j])-ssum(str(a))-sum(x))))
a,b=sorted(L,key=lambda s:s)[:2]
if b==0:
return x[:a],x
elif b==len(str(x)):
return x[:a+1],x
else:
return x[:a]+)[:b])],))]+x
print(cut())
print(cut(list(range(10))))
print(cut())
print(cut())
print(cut())
print(cut())
print(cut())
本帖最后由 第四时空 于 2018-4-12 23:17 编辑
def func(li: list) -> tuple:
max_abs = abs(max(li))
min_abs = abs(min(li))
difference_value = max_abs if max_abs > min_abs else min_abs
result_left_list = []
result_right_list = []
for list_index, elem in enumerate(li):
left_list = li[:list_index]
right_list = li
str_elem = str(elem)
for elem_index, e in enumerate(str_elem):
if e == "-":
continue
left_elem = str_elem[:elem_index + 1]
right_elem = str_elem
value = sum(left_list, int(left_elem or 0)) - sum(right_list, int(right_elem or 0))
if abs(value) <= difference_value:
difference_value = abs(value)
result_left_list = left_list + ( if left_elem != "" else [])
result_right_list = ( if right_elem != "" else []) + right_list
return result_left_list, result_right_list
if __name__ == "__main__":
list_1 =
list_2 =
list_3 =
list_4 = [-2, -2, -2, -2]
list_5 =
list_6 =
list_7 =
list_8 =
for i in :
print(*func(i))
本帖最后由 shigure_takimi 于 2018-4-16 09:05 编辑
def f(aList):
list1 = []
list2 = []
b = str(aList)
b = ''.join(b.split())# 去除空格
length = len(b)
minSub = float('inf')
for i in range(2,length-1):
x = b[:i]+']'
y = '['+b
if x[-2] == '-' or y == ',' or y == '0':
continue
else:
x = eval(x)
y = eval(y)
sub = abs(sum(x) - sum(y))
if sub < minSub:
minSub = sub
list1, list2 = x, y
return list1, list2
list1 =
print(f(list1))
>>>(, ) 本帖最后由 晓屁屁 于 2018-4-13 11:50 编辑
数字之和是个数之和还是相加之和?
arr=
xmax=sum(arr)
for k in range(len(arr)):
s1,s2=sum(arr[:k]),sum(arr)
x=str(arr)
for i in range(len(x)+1):
m1,m2=x[:i],x
if m1=='-':
continue
n1=0 if m1=='' else int(m1)
n2=0 if m2=='' else int(m2)
tmp=abs(s1+n1-s2-n2)
if xmax>=tmp:
xmax=tmp
res1,res2=arr[:k],arr
if m1!='':
res1.append(n1)
if m2!='':
res2.insert(0,n2)
print(res1,res2,xmax) 本帖最后由 天圆突破 于 2018-4-13 14:30 编辑
import re
from functools import reduce
def num(string):
return list(map(lambda x: int(x),re.findall('[-\d]+',string)))
def main(lst):
lst = reduce(lambda x,y:x+'+'+y,map(lambda x:'('+str(x)+')',lst))
n, alllst= len(lst), list()
for i in range(1,n):
lsta,lstb = lst[:i],lst
try:
if lsta[-1] == '+':lsta = lsta[:-1]
else:lsta,lstb = lsta+')','('+lstb
a, b, c, d = eval(lsta), eval(lstb), num(lsta), num(lstb)
e = abs(a - b)
alllst.append()
except:pass
n = min(list(i for i in alllst))
result = list(filter(lambda x: x == n,alllst))
print('共有%d种分割,最小值为%d,分割方法如下:'%(len(result),n))
for each in result:
print(each,each)
if __name__ == '__main__':
lst =
main(lst) a=
tt=[]
qq=[]
b=str(a).replace(' ','')
for i in range(len(b)-3):
b_zuo=b[:(i+2)]+']'
b_you='['+b[(i+2):]
if b_zuo[-2]=='-':
continue
elif b_you==',':
continue
else:
b_zuo=eval(b_zuo)
b_you=eval(b_you)
num=abs(sum(b_zuo)-sum(b_you))
tt.append(num)
qq.append()
xx=tt.index(min(tt))
print(qq ,qq) 本帖最后由 达锅 于 2018-4-13 23:56 编辑
这么快就公开了??
不理解差值最小,意思是切分后右边的和尽可能比左边大,还是左右两边尽可能接近?
反正就一个绝对值符号的差别,我就按绝对值最小计算了
这是转字符版的
def main(mlist):
mtxt="".join(map(lambda x: str(x)+"p",mlist))#转换为字符,以p间隔
def mc(mstr):#把字符重新转化为数字
return #会存在空字符,需要过滤
temp=((mc(mtxt[:i]),mc(mtxt)) for i in range(1,len(mtxt))if mtxt!="-")#储存每一种可能,过滤负号
return (min(temp,key=lambda x:abs(sum(x)-sum(x))))#返回差值
print(main())
这是转字符版第二稿,居然忘记eval函数了~
感谢@lan358088 提醒
def main(mlist):
mtxt="".join(map(lambda x: str(x)+"+",mlist))[:-1]#转换为字符,以p间隔
temp=[(mtxt[:i],mtxt) for i in range(1,len(mtxt)) if mtxt not in '-+']
return min(temp,key=lambda x:abs(eval(x)-eval(x)))
print(main())
这是直接计算的
def main(mlist):
mmin=
for mnum,mcont in enumerate(mlist):#循环读取列表
for i in range(1,len(str(abs(mcont)))):#最高支持99位数
mleft,mright=divmod(abs(mcont),10**i)#整除数为跟左边的列表,余数跟右边
temp=mlist[:mnum]+,+mlist#中间有一个数的整除是取符号,应该有一个函数的,找不到
msum=abs(sum(temp)-sum(temp))#是不是应该求差值的绝对值最小?在公式前面加一个abs就行了
mmin=(msum,temp) if msum<mmin else mmin
return mmin
print(main())
还没评分呢,不知道作对没,有什么提高建议。 好像都没考虑存在一个最小值多个分割方式的情况啊,例如:
[-631, 998, 509, -551, 546, 946, 37, -8, 40, -883]
[, ], , ]]
[, ], , ]]
[, ], , ]]
[, ], , ]]
[-655, -814, -296, 470, 275, 58, -173, 873, -847, -560]
[, ], , ]]
[-675, -10, 68, -772, -879, 877, -630, 622, -3, -550]
[, ], , ]]
[, ], , ]]
[, [-693, -350, 897, 864, 526, 194, 471]], , ]]
[, ], , ]]
[-554, -782, 302, -793, 816, -363, -827, 816, 135, 883]
[, ], , ]]
[, ], , ]]
[-306, 807, -36, -122, -290, -19, -996, -209, -483, 289]
[, ], , ]]
[, ], , ]]
[-417, 771, -344, -669, -381, -384, 132, 691, 355, -390]
[, ], , ]]
[-438, 449, -637, -356, 780, 831, -663, 213, -505, -665]
[, ], , ]]
[, ], , ]]
[, ], , ]]
[, ], , ]]
[-556, -298, 30, -747, -346, 927, 668, -747, 122, 355]
[, ], , ]]
[, [-359, -280, 743, 724, 326, -849, 172]], , ]]
[, ], , ]]
[-313, -776, -569, -725, 615, -516, -735, 412, 662, 406]
[, ], , ]]
[-199, -993, -149, -829, -25, 903, -156, 330, -391, 519]
[, ], , ]]
[, ], , ]]
[-443, -799, 435, -736, 376, -768, 747, 333, 416, -92]
[, ], , ]]
[-863, 469, 659, -635, 271, -408, -667, -168, -502, -120]
[, ], , ]]
[, ], , ]]
[-116, -811, -27, -991, -489, 546, -966, -84, -457, 79]
[, ], , ]]
[-380, 979, 233, -810, 322, -663, -152, -202, 732, -110]
[, ], , ]]
这些? 本帖最后由 柯基不是天然卷 于 2018-4-13 23:06 编辑
list =
list_a=[]
list_b=[]
answer_a=[]
answer_b=[]
answer1 = []
answer2 = []
last_answer1 = []
last_answer2 = []
def create_hanshu():
for i in range(len(list)+1):
list_a.append(list[:i])
list_b.append(list)
list_a.pop(0)
list_b.pop(-1)
def add_list():
for i in list_a:
answer1.append(sum(i))
for i in list_b:
answer2.append(sum(i))
def main():
create_hanshu()
add_list()
last_answer1 = answer1
last_answer2 = answer2
biggest_answer = 0
for i in range(1,len(answer1)):
if abs(answer1+answer2) > abs(biggest_answer):
biggest_answer = abs(answer1+answer2)
last_answer1 = list_a
last_answer2 = list_b
print(last_answer1)
print(last_answer2)
main()
def split_num1(lstd):
a = b = c = 0
l = []
uu = []
SUM = sum(lstd)
count = 0
for i in lstd:
a += i
b = SUM - a - a
c = abs(b)
l.append(c)
x = min(l)
#考虑是否有两个及两个以上分割点
for i in range(len(l)):
if l == x:
count += 1
uu.append(i)
if count == 1:
return lstd[:l.index(x)+2], lstd
else:
#考虑到有些列表的分割点可能会很多,如[-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1],就不逐一返回了
print('分割点集合为:', uu)
lstd =
s1 = split_num1(lstd)
s2 = split_num1(lstd)
天圆突破 发表于 2018-4-13 21:59
好像都没考虑存在一个最小值多个分割方式的情况啊,例如:
这些?
只要能找到最小值,找到最小值一样的也不难了 def depart(datalist):
if len(datalist) == 1 and abs(datalist) < 10:
print("No solution!")
return
leftlist = []
sumleft = 0
sumright = sum(datalist)
minDiffer = abs(2 * datalist - sumright)
minleftlist = ]
minrightlist = datalist
if minDiffer == 0:
print(], '\n', datalist, '\n', "minDiffer is 0!")
return
for k in range(len(datalist[:])):
num = datalist.pop(0)
sumright -= num
if abs(num) >= 10:
j = 0 if num >= 0 else 1
for i in range(1 + j, len(str(num))):
leftnum = int(str(num)[:i])
sumleft += leftnum
rightnum = int(str(num))
sumright += rightnum
if abs(sumleft - sumright) == 0:
leftlist.append(leftnum)
datalist.insert(0, rightnum)
print(leftlist, '\n', datalist, '\n', "minDiffer is 0!")
return
elif abs(sumleft - sumright) < minDiffer:
minDiffer = abs(sumleft - sumright)
minleftlist = leftlist[:]
minleftlist.append(leftnum)
minrightlist = datalist[:]
minrightlist.insert(0, rightnum)
sumleft -= leftnum
sumright -= rightnum
sumleft += num
else:
sumleft += num
if abs(sumleft - sumright) < minDiffer:
minDiffer = abs(sumleft - sumright)
minleftlist = leftlist[:] +
minrightlist = datalist[:]
leftlist.append(num)
print(minleftlist, '\n', minrightlist, '\n', "minDiffer is %d" % minDiffer)
return
if __name__ == "__main__":
depart( 塔利班 发表于 2018-4-12 21:55
多敲代码才是硬道理,,,,对 本帖最后由 凌九霄 于 2018-4-15 16:38 编辑
import random
absresult = 10000
lsta = []
lstb = []
lst = random.sample(, 10)
strnum = str(lst).replace('[', '').replace(']', '').replace(' ', '')
for i in range(1, len(strnum)):
if strnum not in [',', '-']:
xlst = list(map(int, strnum.split(',')))
if strnum != ',':
ylst = list(map(int, strnum.split(',')))
else:
ylst = list(map(int, strnum.split(',')))
tmp = abs(sum(xlst) - sum(ylst))
if absresult > tmp:
absresult = tmp
lsta = xlst
lstb = ylst
print('\n原列表:\n{0}\n\n按要求分割后的两个列表为:\n{1}\n{2}\n\n两个列表的和的差的最小绝对值为:{3}'.format(lst, lsta, lstb, absresult))
本帖最后由 坑得飞起 于 2018-4-15 23:35 编辑
def bijiao(a,b):
if a=='q' : return b
if b=='q' : return a
a2,b2=a,b
if a<0 : a=-a
if b<0 : b=-b
if a<b :
return a
return b
ss=input()
an,ans1,ans2,ss='q',[],[],ss
for i in range(len(ss)):
if ss=='-' or ss==',' :
continue
s1=ss[:i+1].split(',')
for j in range(len(s1)):
s1=int(s1)
s2=ss.split(',')
if s2=='' :
s2=s2
for j in range(len(s2)):
s2=int(s2)
if an!=bijiao(an,sum(s1)-sum(s2)):
an,ans1,ans2=bijiao(an,sum(s1)-sum(s2)),s1,s2
print(an,',',ans1,',',ans2) 最近太忙了,一直没时间做题,今天抽点空,感觉自己写得好麻烦啊!有空了再优化吧……{:5_111:}
l1 =
tmp = []
for i, each in enumerate(l1):
if i == 0:
front = []
back = l1
elif i == len(l1) - 1:
front = l1[:i]
back = []
else:
front = l1[:i]
back = l1
x1 = str(each)
if x1 != '-':
for s in range(len(x1)):
if s != len(x1) - 1:
sf = front + )]
sb = )] + back
else:
sf = front +
sb = back
tmp.append()
else:
for s in range(1, len(x1)):
if s != len(x1) - 1:
sf = front + )]
sb = )] + back
else:
sf = front +
sb = back
tmp.append()
m = min( for sub in tmp])
for i in tmp:
if i == m:
print(i, i) python每日一题好几个星期没有更新了。大神。
页:
[1]
2