验证IP地址
分类别进行筛选,注意IPv4是以.
为分割符,而IPv6是以:
为分隔符。
def confine_ip_address(seq):
if not seq:
return 'Neither'
if '.' in seq:
seq = seq.split('.')
# print('.', seq)
if len(seq) == 4:
return find_ipv4(seq)
if ':' in seq:
seq = seq.split(':')
# print(':', seq)
if len(seq) == 8:
return find_ipv6(seq)
if len(seq) != 4 or len(seq) != 6:
return 'Neither'
def find_ipv4(seq):
for su in seq:
# print(su)
if len(su) > 1 and su.startswith('0'):
return 'Neither'
if su < '0' or su > '255':
return 'Neither'
return 'IPv4'
def find_ipv6(seq):
values = set(list(map(str, range(10))) + list('abcedfABCDEF'))
for su in seq:
# print(su)
if len(su) > 1 and set(su) == {'0'}:
return 'Neither'
for s in su:
if s not in values:
return 'Neither'
return 'IPv6'
if __name__ == '__main__':
seq = input().strip()
res = confine_ip_address(seq)
print(res)
'''
172.16.254.1
2001:0db8:85a3:0:0:8A2E:0370:7334
256.256.256.256
'''
字母组合
小灵通的键盘,有意思。每次只对两个数字分别代表的意思进行组合,依次遍历下去。
def alpha_combine(seq):
phone = ['abc', 'def', 'ghi', 'jkl', 'mno', 'pqrs', 'tuv', 'wxyz']
values = {nu: pu for nu, pu in zip(range(2, 10), phone)}
pre = values[seq[0]]
for su in seq[1:]:
left, right = pre, values[su]
current = []
for lu in left:
for ru in right:
current.append(''.join([lu, ru]))
pre = current
return pre
if __name__ == '__main__':
seq = list(map(int, list(input().strip())))
seq = [su for su in seq if su != 1]
res = alpha_combine(seq)
print('[', end='')
print(', '.join(res), end='')
'''
23
92
458
'''
集合划分问题
懒人模式,暴力求解。通过率为57.13%,栈溢出,很正常的现象。
from itertools import permutations
def split_set_problem(seq, n):
index = []
for nu in range(1, n):
index.extend(list(permutations(range(n), nu)))
# print(index)
res = float('inf')
for idx in index:
left = [seq[si] for si in idx]
right = [seq[ri] for ri in range(n) if ri not in idx]
current = abs(sum(left)-sum(right))
if current < res:
res = current
return res
if __name__ == '__main__':
n = int(input().strip())
seq = list(map(int, input().strip().split()))
res = split_set_problem(seq, n)
print(res)
'''
5
2 4 5 6 9
4
1 1 1 999
'''
最长等差数列
再次懒人模式,暴力求解。通过率80%,超时,太正常了。
def longest_array_for_equal(seq):
if not seq:
return 0
seq.sort()
res = 0
left, right = 0, seq[-1]-seq[0]
for si in range(len(seq)):
idx, cur = si, 0
su = seq[si]
cur = su
for iu in range(left, right+1):
count = 1
idx = si
while True:
# print(cur, count, idx)
if cur+iu in seq[idx+1:]:
idx = seq[idx+1:].index(cur + iu)
cur += iu
count += 1
else:
break
if count > res:
res = count
return res
if __name__ == '__main__':
n = int(input().strip())
seq = list(map(int, input().strip().split()))
res = longest_array_for_equal(seq)
print(res)
'''
5
1 4 2 5 3
5
1 4 7 2 6
'''
(最近更新:2019年09月16日)