def formatted_print(dictionary): d = {key:value for key, value in dictionary.items()} lst = sorted(d.items(), key=lambda item:item[1], reverse=True) for i in range(len(lst)): print("{0:10s}{1:>6.2f}".format(lst[i][0], lst[i][1])) def main(): d = {} sentinel = '' for line in iter(input, sentinel): line = line.split(',') d[line[0]] = float(line[1]) formatted_print(d) main()
这段代码是一个Python程序,实现了一个函数formatted_print
,它接受一个字典作为输入,将字典中的键值对按照值的大小排序后,格式化输出每个键值对的键和值。该程序还定义了一个主函数main
,通过循环读取输入行,并将输入的键值对存储到一个字典中,最后调用formatted_print
函数将字典中的数据打印出来。
class Node: def __init__(self, data=None): self.data = data self.prev = None self.next = None def reverse_doubly_linked_list(head): current_node = head while current_node is not None: # Swap the prev and next pointers of the current node. temp_next = current_node.next current_node.next = current_node.prev current_node.prev = temp_next # Move to the original 'next' node (which was stored as a temporary variable). head = current_node # Update new head reference after reversing each step. current_node = temp_next return head # Return updated head which points to last processed element. # Example usage demonstrating how this works without causing an infinite loop. if __name__ == "__main__": nodes = [Node(i) for i in range(5)] # Linking all created nodes together into one continuous double-linked structure. for idx in range(len(nodes)-1): nodes[idx].next = nodes[idx+1] nodes[idx+1].prev = nodes[idx] reversed_head = reverse_doubly_linked_list(nodes[0]) # Verify correctness by traversing from both ends post reversal operation. curr = reversed_head result_forward = [] while curr: result_forward.append(curr.data) curr = curr.next print("Reversed List Forward:", result_forward),修改这段python代码,让他不会死循环
双链表反转逻辑修正
在 Python 中实现双链表并对其进行反转时,如果未正确处理指针方向的变化,则可能导致无限循环。以下是经过优化后的双链表反转函数及其解释。
问题分析
当执行双链表反转操作时,需要调整每个节点的 prev
和 next
指针指向关系。如果不小心遗漏某些指针更新或者错误地重复访问已翻转的部分,就可能引发死循环[^1]。
解决方案
通过迭代方式逐一改变当前节点与其前后节点的关系,并确保不会再次遍历已经完成转换部分即可有效解决此问题:
class Node:
def __init__(self, data=None):
self.data = data
self.prev = None
self.next = None
class DoublyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
new_node.prev = current
def reverse(self):
temp = None
current = self.head
# Swap the prev and next pointers of each node to reverse direction.
while current is not None:
temp = current.prev
current.prev = current.next
current.next = temp
current = current.prev # Move forward using original 'prev' which became 'next'.
if temp is not None:
self.head = temp.prev # Reset head after reversing all nodes.
def display_list(dllist):
result = []
current = dllist.head
while current:
result.append(current.data)
current = current.next
return "<->".join(map(str, result))
# Example Usage
dll = DoublyLinkedList()
for i in range(5):
dll.append(i)
print("Original List:", display_list(dll)) # Output Original list as string representation
dll.reverse() # Reverse operation on doubly linked list object
print("Reversed List:", display_list(dll)) # Print reversed version similarly formatted
上述代码片段展示了如何安全有效地逆转一个双向链表而无需担心陷入无尽循环之中。特别注意的是,在交换过程中我们临时保存了前驱节点以便继续移动至下一个待处理节点;最后一步重新设定头部位置也很重要,因为初始头结点现在变成了尾部[^2]。
注意事项
- 边界条件:对于空列表或仅有一个元素的情况需单独考虑。
- 内存管理:虽然这里没有显式的垃圾回收机制讨论,但在实际应用中应留意废弃对象是否会及时释放资源。
优化代码 def align_annotations(formatted_sql): lines = formatted_sql.split('\n') fields = [] ass=[] comments = [] for line in lines: if line.strip(): line=line.replace('\t',' ') if line.lower().startswith(("where", "left", "on","from","and","group")): fields.append(line) ass.append('') comments.append('') elif ' as ' in line.lower() and '--' in line : parts=line.replace(' as ',' -- ').replace(' AS ',' -- ').split('--') fields.append(parts[0]) ass.append(parts[1]) comments.append(parts[2]) elif ' as ' in line.lower() and '--' not in line : parts=line.replace(' as ',' AS ').split(' AS ') fields.append(parts[0]) ass.append(parts[1]) comments.append('') elif ' as ' not in line.lower() and '--' in line : parts=line.split('--') fields.append(parts[0]) ass.append('') comments.append(parts[1]) else: fields.append(line) ass.append('') comments.append('') # 计算每列的最大长度 max_field_length = max(len(field.strip()) for field in fields if not field.lower().strip().startswith(("where", "left", "on","from","and","group","inner"))) max_as_s_length = max(len(as_s.strip()) for as_s in ass) # 格式化字段、字段类型和注释,并生成新的建表语句 formatted_lines = [] for field,as_s, comment in zip(fields,ass, comments): formatted_field = f"{field.strip()}".ljust(max_field_length) if as_s.strip(): formatted_as_s = f"AS {as_s.strip()}".ljust(max_as_s_length+3) else: formatted_as_s=''.ljust(max_as_s_length+3 ) if comment.strip(): formatted_comment = f"-- {comment}" else: formatted_comment='' formatted_line = f" {formatted_field} {formatted_as_s} {formatted_comment}" formatted_lines.append(formatted_line) formatted_select_statement = "\n".join(formatted_lines) return formatted_select_statement
这个函数的作用是将一个 SQL 查询语句中的字段、字段别名和注释对齐,并生成一个新的 SQL 查询语句。针对代码的优化建议如下:
减少不必要的代码行数,比如可以将
fields
、ass
和comments
的初始化写在一行中,不需要每个变量单独占用一行。简化一些条件判断的逻辑,比如可以将
line.strip()
的结果直接作为判断条件,不需要再写一个 if 语句。使用列表推导式简化对
fields
、ass
和comments
列表的生成过程。将一些常量定义为函数参数或全局变量,比如
'where', 'left', 'on', 'from', 'and', 'group', 'inner'
这些字符串可以定义为全局变量或函数参数,方便维护和修改。
根据上述优化建议,可以得到下面的代码实现:
def align_annotations(formatted_sql, keywords=None):
if not keywords:
keywords = {'where', 'left', 'on', 'from', 'and', 'group', 'inner'}
lines = formatted_sql.split('\n')
fields, ass, comments = [], [], []
for line in lines:
if line.strip():
line = line.replace('\t', ' ')
if any(line.lower().startswith(kw) for kw in keywords):
fields.append(line)
ass.append('')
comments.append('')
elif ' as ' in line.lower():
parts = line.split(' as ')
if '--' in parts[1]:
parts = parts[0], *parts[1].split('--')
fields.append(parts[0])
ass.append(parts[1])
comments.append(parts[2] if len(parts) > 2 else '')
elif '--' in line:
parts = line.split('--')
fields.append(parts[0])
ass.append('')
comments.append(parts[1])
else:
fields.append(line)
ass.append('')
comments.append('')
max_field_length = max(len(field.strip()) for field in fields if not any(field.lower().strip().startswith(kw) for kw in keywords))
max_as_s_length = max(len(as_s.strip()) for as_s in ass)
formatted_lines = [f' {f"{field.strip()}".ljust(max_field_length)} '
f'{f"AS {as_s.strip()}".ljust(max_as_s_length+3) if as_s.strip() else "".ljust(max_as_s_length+3)} '
f'{f"-- {comment}" if comment.strip() else ""}'
for field, as_s, comment in zip(fields, ass, comments)]
return "\n".join(formatted_lines)
这样的代码更加简洁和易于维护,同时也不会影响函数的功能。
相关推荐















