欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Python文档整理

程序员文章站 2024-03-21 13:32:10
...

 

ternary operator 三目运算符

a=int(input("a="))
b=int(input("b="))
max=a if a>b else b
print(max)

https://www.runoob.com/python/python-func-enumerate.html

__init__

https://www.zhihu.com/question/46973549/answer/767530541

Python中 __init__的通俗解释是什么? - 追远·J的回答 - 知乎 https://www.zhihu.com/question/46973549/answer/767530541

while

https://blog.csdn.net/qdPython/article/details/110133545

算法

两数之和

import json
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:  #要求返回list格式
        tmp = {}
        for k, v in enumerate(nums):  # k从0开始,v从num[0]开始
            print(k,v)
            tmp[v] = k #将list的下标和值存入字典,因为字典下标可以方便目标值和移动取值v做差
            if target - v in tmp:
                return [tmp[target - v], k] #tmp[target - v]为一个数的下标,k为另一个数的下标
            # tmp[v] = k  #关键点,利用下标来确定tmp字典里的值是来自list的

def stringToIntegerList(input):
    return json.loads(input)

def integerListToString(nums, len_of_list=None):
    if not len_of_list:
        len_of_list = len(nums)
    return json.dumps(nums[:len_of_list])

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n') #换行终止该行输入(改行字符串属于一个单独的lines)

    lines = readlines()
    while True:
        try:
            line = next(lines) #继续下一行输入
            nums = stringToIntegerList(line);
            line = next(lines)
            target = int(line);

            ret = Solution().twoSum(nums, target)

            out = integerListToString(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

两数之和

定义一个单链表


import json
from Cython.Compiler.ExprNodes import ListNode

# Definition for singly-linked list.
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val #可变,数值
        self.next = next  #节点,指向列表的下一个数字

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        header = ListNode() #实例化一个"加和(链表)"对象
        p = header #现在"加和(链表)"是p
        carry = 0 #商初始化为0
        print(carry,l1,l2)
        while carry or l1 or l2: #or其中有一个为真可符合往下(不符合时结束)
            print(type(l1), type(l2))
            var = carry    ###此处是关键点:商传给余值
            print(carry, var,l1.val)  #l1.val表示l1[],即2,4,3
            if l1:
                var = l1.val + var #这里+var余值,是满十加一
                print("var1=",var)
                l1 = l1.next #去找到下一个l1.val
            if l2:
                var = l2.val + var #这里+var是,两个链表对应位数相加
                print("+",l2.val,"=var2=", var)
                l2 = l2.next
            print(carry,var)
            carry, var = divmod(var, 10) #var/10= 商,余值 (每轮得到新的)
            print(carry,var)
            p.next = ListNode(var) #把余值存入新的链表中
            p = p.next #"加和(链表)"指向下一个,构成循环
        return header.next #逐个输出 "加和(链表)"的内容(注意有点像list,但不是list)

def stringToIntegerList(input):
    return json.loads(input)

def stringToListNode(input):
    # Generate list from the input
    numbers = stringToIntegerList(input)

    # Now convert that list into linked list
    dummyRoot = ListNode(0)
    ptr = dummyRoot
    for number in numbers:
        ptr.next = ListNode(number)
        ptr = ptr.next

    ptr = dummyRoot.next
    return ptr

def listNodeToString(node):
    if not node:
        return "[]"

    result = ""
    while node:
        result += str(node.val) + ", "
        node = node.next
    return "[" + result[:-2] + "]"

def main():
    import sys
    import io
    def readlines():
        for line in io.TextIOWrapper(sys.stdin.buffer, encoding='utf-8'):
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = next(lines)
            l1 = stringToListNode(line);
            line = next(lines)
            l2 = stringToListNode(line);

            ret = Solution().addTwoNumbers(l1, l2)

            out = listNodeToString(ret);
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()

运行

[2,4,3]
[8,1,1]
0 <__main__.ListNode object at 0x159dece50> <__main__.ListNode object at 0x159dfd040>
<class '__main__.ListNode'> <class '__main__.ListNode'>
0 0 2
var1= 2
+ 8 =var2= 10
0 10
1 0
<class '__main__.ListNode'> <class '__main__.ListNode'>
1 1 4
var1= 5
+ 1 =var2= 6
1 6
0 6
<class '__main__.ListNode'> <class '__main__.ListNode'>
0 0 3
var1= 3
+ 1 =var2= 4
0 4
0 4
[0, 6, 4]

 

相关标签: 算法 python