Python学习 ——enumerate函数

本文介绍了一种在给定节点的情况下删除链表中该节点的方法,通过将当前节点的值替换为下一个节点的值,然后删除下一个节点的方式实现,适用于除尾节点外的所有情况。

237. Delete Node in a Linked List

Write a function to delete a node (except the tail) in a singly linked list, given only access to that node.

Supposed the linked list is 1 -> 2 -> 3 -> 4 and you are given the third node with value 3, the linked list should become 1 -> 2 -> 4 after calling your function.

We cannot get the previous node but only the given node, so we can replace this node with the val of node.next, then delete the next node.

class Solution(object):
    def deleteNode(self, node):
        node.val = node.next.val
        node.next = node.next.next
### Python 函数用于计算思维训练 #### 方法和示例 Python 提供了一种强大的方式来进行计算思维训练,特别是通过函数的设计与实现。函数不仅有助于代码的模块化设计,还促进了逻辑思考能力的发展。 #### 问题分解 一个问题可以被拆解成更小的部分以便更容易解决。例如,在处理复杂的数据集时,可以通过编写多个小型专用功能来逐步解决问题[^1]。下面是一个具体的例子: 假设有一个需求是要找出列表中所有偶数的位置索引。这个问题可以通过构建辅助函数 `is_even` 来判断单个数字是否为偶数,再利用另一个遍历整个列表并收集符合条件项位置的功能完成最终目标。 ```python def is_even(number): """Check if a number is even.""" return number % 2 == 0 def find_indices_of_evens(lst): """Find indices of all even numbers in the list.""" result = [] for index, value in enumerate(lst): if is_even(value): result.append(index) return result ``` 这段代码展示了如何将大任务分割成易于管理和理解的小部分——这正是计算思维的核心之一。 #### 自定义函数的应用 除了上述提到的问题分解技巧外,还可以创建自定义函数以满足特定的需求。比如想要统计一段文字里单词的数量,就可以按照以下步骤操作[^3]: 1. 定义一个新的函数接受字符串作为输入; 2. 使用内置 split() 方法把句子切分成词组; 3. 计算得到的结果集合大小即代表总共有多少个不同词语; 这里给出完整的解决方案如下所示: ```python def word_count(text): words = text.split() unique_words = set(words) return len(unique_words) example_text = "This is an example sentence with some repeated words like this and that" print(word_count(example_text)) ``` 此程序片段说明了怎样运用自定义函数有效地解决了实际生活中的一个小挑战。 #### 实现加法运算器 为了进一步展示 Python 函数对于培养计算思维方式的重要性,考虑这样一个场景:开发一个简单的计算器应用程序,其中一部分负责执行两数值相加的任务。该过程涉及到了基本算法的理解以及良好的编码习惯养成等方面[^4]。 ```python def add_numbers(a, b): """Add two given numbers together""" sum_result = a + b return sum_result num1 = float(input("Enter first number: ")) num2 = float(input("Enter second number: ")) result = add_numbers(num1, num2) print(f"The addition of {num1} and {num2} equals to {result}") ``` 以上实例强调了函数在简化重复工作流程方面的作用,同时也体现了结构清晰、易于调试的优点。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值