1025. 反转链表 (25)----Python

我发现用Python写的题不多,所以看了别的语言写的代码,找了找问题,测试时主要是测试点6和测试点5一直提示运行超时,应该是有两种情况没有考虑到,参考了别人的博文后,发现的情况如下:

(1)测试点6:是因为没有考虑到输入的节点不在链中的情况,就是说输入的数据的地址并没有其他的数据指向它,当添加了这种情况的考虑后,测试点6即通过了;

(2)测试点5:没有发现错出在哪,可能是程序太冗杂,使得运行速度过慢,有知道测试点5是测试的什么的,麻烦留个言,过不了的感觉扎心

      

def get_key_list(num, first_key, count):
	key_2 = first_key
	num = int(num)		
	while num:
	
		if key_2 in key_list:
			my_list.append(key_2)
			key_2 = address[key_2]
			num -= 1
			count += 1
		else:
			num -= 1
	return count
	
def get_out(key, ver_num, flag):
	ver_num = int(ver_num)
	my_num = ver_num * flag
	flag_1 = 0

	while ver_num:
		if ver_num < 2:
			return key
		else:
			print('{:<5}'.format(key) + ' ' + directory[key] + ' ' + '{:<5}'.format(my_list[my_num - 2 - flag_1]))
			key = my_list[my_num - 2 - flag_1]
			ver_num -= 1
			flag_1 += 1
			
def get_key_add(circles, remainder):
	my_num = int(ver_num)
	flag = 1
	flag_2 = 1
	
	while circles:
		key = my_list[my_num * flag - 1]
		key_1 = get_out(key, ver_num, flag)
		circles -= 1  
		if circles == 0:
			if remainder == 0:
				print('{:<5}'.format(key_1) + ' ' + directory[key_1] + ' ' + '-1')
			else:
				print('{:<5}'.format(key_1) + ' ' + directory[key_1] + ' ' + format(my_list[my_num * flag]))
				key_num = my_num * flag
				key_1 = my_list[key_num]
				while remainder != 1:      
					print('{:<5}'.format(key_1) + ' ' + directory[key_1] + ' ' + '{:<5}'.format(my_list[key_num + flag_2]))
					key_1 = my_list[key_num + flag_2]
					remainder -= 1
					flag_2 += 1
				print('{:<5}'.format(key_1) + ' ' + directory[key_1] + ' ' + '-1')
		else:
			print('{:<5}'.format(key_1) + ' ' + directory[key_1] + ' ' + '{:<5}'.format(my_list[my_num * (flag + 1) - 1]))
			
		flag += 1
    
first_key, num, ver_num = input().split()


directory = {}
address = {}
key_list = []
my_list = []
count = 0

my_num_1 = num
while num:
	key, value, next_key = input().split()      
	directory[key] = value
	address[key] = next_key
	key_list.append(key)
	num = int(num) - 1
if first_key != '-1':
	
	num = get_key_list(my_num_1, first_key, count)
	circles = int(num) // int(ver_num)
	remainder = int(num) % int(ver_num)
	if num < int(ver_num):
		flag = 1
		key = my_list[0]
		while num:
			if num > 1:
				print('{:<5}'.format(key) + ' ' + directory[key] + ' ' + '{:<5}'.format(my_list[flag]))
				key = my_list[flag]
			else:
				print('{:<5}'.format(key) + ' ' + directory[key] + ' ' + '-1')	
			flag += 1
			num -= 1
			
	else:
		get_key_add(circles, remainder)  

else:
	print("-1\n")

你可能感兴趣的:(python,练习)