python入门题目三(ZZULIOJ数组和函数练习)

个人练习

  • 数组
    • 1115: 数组最小值
    • 1125: 上三角矩阵的判断
    • 1163: 亲和串(字符串)
  • 函数专题
    • 1106: 回文数(函数专题)
    • 1091: 童年生活二三事(多实例测试)

数组

一维数组输入方法:

    len = int(input())#输入数组长度
    arr = input("")
    a = [int(n) for n in arr.split()]

二维数组输入方法:

    for i in range(n):
        a = list(map(int,input().split()))

字符串输入方法:

str = input()

1115: 数组最小值

手写最小值代码:

mi = 1e9
index = -1
if __name__ == '__main__':
    len = int(input())
    arr = input("")
    #a = input().split()
    a = [int(n) for n in arr.split()]
    for i in range(len):
        if mi > a[i] :
            mi = a[i]
            index = i
    print(mi,index)

内置函数版本:

a=int(input())
b=input().split()
d=min(b)
e=b.index(d)
print(d,e)

1125: 上三角矩阵的判断

二维数组小练习
代码:


if __name__ == '__main__':
    n = int(input())
    flag = 1
    for i in range(n):
        a = list(map(int,input().split()))
        for j in range(n):
            if j < i and a[j]!=0 :
                flag = 0
                break
    if flag:
        print("YES")
    else:
        print("NO")

1163: 亲和串(字符串)

思路:就是复制一份s1连接到s1后面,查找子串
资料链接:python中字符串的定义和操作
代码:


if __name__ == '__main__':
    while True:
        try:
            str = input()
            str1 = input()
            if len(str) < len(str1) :
                print("no")
                continue
            str = str * 2
            index = str.find(str1)
            #print(str)
            #print(len(str))
            if index != -1 :
                print("yes")
            else:
                print("no")
        except:
            break

函数专题

资料链接:
https://www.runoob.com/python/python-functions.html

1106: 回文数(函数专题)

代码:

def solve(x):
    st = x
    st1 = 0
    while x:
        st1 = st1*10 + x%10
        x //= 10

    if st == st1 :
        return 1
    else :
        return 0
if __name__ == '__main__':
    a,b = map(int,input().split())
    for i in range(a,b+1):
        t = solve(i)
        if t:
            print(i,end=" ")

1091: 童年生活二三事(多实例测试)

代码:

a = [0]*100
# 递归函数,会时间超限
# def f(x):
#     if x==1:
#         return 1
#     elif x==2 :
#         return 1
#     else :
#         return f(x-1)+f(x-2)
def init():
    a[1]=1
    a[2]=2
    for i in range(3,41):
        a[i] = a[i-1] + a[i-2]
if __name__ == '__main__':
    init()
    while True:
        n = int(input())
        if n==0:
            break
       # t = f(n)
        print(a[n])

你可能感兴趣的:(python,算法,leetcode)