The fourth day of learning python --- basics (2)

1. Triangle type

insert image description here

n=list(map(float,input().split()))
c,b,a=sorted(n)
if a>=b+c:
    print("NAO FORMA TRIANGULO")
    exit()
if a**2==b**2+c**2:
    print("TRIANGULO RETANGULO")
elif a**2>b**2+c**2:
    print("TRIANGULO OBTUSANGULO")
elif a**2<b**2+c**2:
    print("TRIANGULO ACUTANGULO")
if a==b==c:
    print("TRIANGULO EQUILATERO")
elif a==b or a==c or b==c:
    print("TRIANGULO ISOSCELES")

How to read and sort an array

n=list(map(float,input().split())) c,b,a=sorted(n)

list_1 = list(map(float, input().split())) list_1.sort() list_1.reverse()

lengths=sorted(map(float,input().split(" ")),reverse=True)

2. Animals

insert image description here

Writing method one:

d={" “:{” “},” “:{” "}}

This is a nested dictionary data structure that contains animal categories and animal names for different categories. Animal names can be obtained through the nested structure of dictionaries.

d = {
    
    "vertebrado":{
    
    "ave":{
    
    "carnivoro":"aguia","onivoro":"pomba"},"mamifero":{
    
    "onivoro":"homem","herbivoro":"vaca"}},"invertebrado":{
    
    "inseto":{
    
    "hematofago":"pulga","herbivoro":"lagarta"},"anelideo":{
    
    "hematofago":"sanguessuga","onivoro":"minhoca"}}}
a,b,c = input(),input(),input()
print(d[a][b][c])

Writing method 2: nested if

s1 = input()
s2 = input()
s3 = input()

if s1 == "vertebrado":
    if s2 == "ave":
        if s3 == "carnivoro":
            print("aguia")
        else:
            print("pomba")
    else:
        if s3 == "onivoro":
            print("homem")
        else:
            print("vaca")
else:
    if s2 == "inseto":
        if s3 == "herbivoro":
            print("lagarta")
        else:
            print("pulga")
    else:
        if s3 == "onivoro":
            print("minhoca")
        else:
            print("sanguessuga")

Writing method three: index()

one = ["vertebrado","invertebrado"]
two = ["ave","mamifero","inseto","anelideo"]
three = ["carnivoro","onivoro","herbivoro","hematofago"]
a = one.index(input())
b = two.index(input())
c = three.index(input())
d = {
    
    "000":"aguia","001":"pomba","011":"homem","012":"vaca","123":"pulga",
"122":"lagarta","133":"sanguessuga","131":"minhoca"}
# print(a,b,c)
print(d[str(a)+str(b)+str(c)])

3. Rhombus

insert image description here

n = int(input())
c = n // 2
for i in range(n):
    for j in range(n):
        if abs(i - c) + abs(j - c) <= c:
            print('*', end = '')
        else:
            print(' ', end = '')
    print()

4. Prime numbers

insert image description here

n=int(input())
for i in range(n):
    x=int(input())
    flag=True
    for i in range(2,int(x**0.5)+1):
        if x%i==0:
            flag=False
            break
    if flag:
        print("%d is prime"%x)
    else:
        print("%d is not prime"%x)

5. Perfect number

insert image description here

n=int(input())
for i in range(n):
    ans=0
    x=int(input())
    for j in range(1,x):
        if j**2>x:#剪枝,我一开始没有这句话tle了
            break
        if x%j==0:
            if j<x:
                ans+=j
            if j!=x/j and x/j<x:#如果i**2不等于x
                ans+=int(x/j)
    if ans==x:
        print("%d is perfect"%x)#print("{} is perfect".format(x))
    else: print("%d is not perfect"%x)

6. Number sequence and its sum

insert image description here

Writing method one:

while True:
    a, b = map(int, input().split())
    if a<=0 or b<=0:
        exit()
    if a>b:
     a,b=b,a
    sum=0
    for i in range(a,b+1):
        print(i,end=' ')
        sum+=i
    print("Sum={}".format(sum))

Writing method two:

while True:
    a,b=map(int,input().split(' '))
    if a<=0 or b <= 0:
        break
    y=max(a,b)
    x=min(a,b)
    sum=0
    for i in range(x,y+1):
        print(i,end=' ')
        sum+=i
        pass
    print("Sum=%d"%sum)

Seven, consecutive odd numbers and 2

insert image description here

Writing method 1: My writing is complicated, and direct violence is enough

Then it should be noted that the array should be larger, the method of creating and reading the array.

a=[0]*1005
a[0]=0
for i in range(1,1005):
    if (i-1)&1:
        a[i]=a[i-1]+i-1
    else:
        a[i]=a[i-1]
n=int(input())
for _ in range(n):
    d,b=map(int,input().split())
    if d>b:
        d,b=b,d
    if d==b:
        print(0)
    elif d>0 and b>0:
        print(a[b]-a[d+1])
    elif d<0 and b<0:
        print(-a[-d]+a[-b+1])
    elif d<0 and b>0:
        print(-a[-d]+a[b])

Writing method two:

for j in range(a[i2]+1,a[i2+1],1):

The range() function here uses the form of three parameters, where the first parameter is the loop start value, the second parameter is the loop end value (not included), and the third parameter is the loop step size. Therefore, range(a[i 2]+1, a[i 2+1], 1) means starting from a[i 2]+1 and increasing by 1 each time until a[i 2+1], the loop ends.
for example:

a = [[0, 5], [10, 15], [20, 25]]

for i in range(len(a)):
    for j in range(a[i][0] + 1, a[i][1], 1):
        # 在这里写需要执行的操作,例如打印 j 的值
        print(j)

This code will print the numbers 1 to 4, 11 to 14, and 21 to 24 in sequence, because they belong to the three intervals in a.

n = int(input())
a = []
for i in range(n):
    b = [int(x) for x in input().split()]
    a = a + b#把他一个个存入到a中
for i in range(n):
    count = 0
    if a[i*2] > a[i*2+1]:
        p = a[i*2]
        a[i*2] = a[i*2+1]
        a[i*2+1] = p
    for j in range(a[i*2]+1,a[i*2+1],1):
        if j % 2 == 1:
           count += j
    print(count)

I think the idea of ​​this writing method is very clever!

Writing method three: Violent law

n=int(input())
for i in range(n):
    s=0
    x,y=map(int,input().split())
    if x>y:x,y=y,x
    for j in range(x+1,y):
        if j%2==1:
            s+=j
    print(s)

8. Experiment

dictionary

A dictionary is used here! ! !

n = int(input())
res = 0
data = {
    
    }
for i in range(n):
    a,b = input().split(" ")
    # print(a,b)
    a = int(a)
    if data.get(b,False):
        data[b] = data[b] + a
    else:
        data[b] = a
    res+=a

print("Total: {} animals".format(res))
print("Total coneys: {}".format(data["C"]))
print("Total rats: {}".format(data["R"]))
print("Total frogs: {}".format(data["F"]))
print("Percentage of coneys: {:.2f} %".format(data["C"]/res*100))
print("Percentage of rats: {:.2f} %".format(data["R"]/res*100))
print("Percentage of frogs: {:.2f} %".format(data["F"]/res*100))

Nine, snake matrix

insert image description here
I often wrote it when I was learning C++, it was a bit raw, and I wrote it for a while

n,m=map(int,input().split())
dx=[0,1,0,-1]
dy=[1,0,-1,0]
a=[[0 for j in range(m)] for i in range(n)]
x,y,t=0,0,0
for i in range(1,n*m+1):
    a[x][y]=i
    x1,y1=x+dx[t],y+dy[t]
    if x1<0 or x1>=n or y1>=m or y1<0 or a[x1][y1]:
        t=(t+1)%4
        x1,y1=x+dx[t],y+dy[t]
    x,y=x1,y1

for i in range(n):
    for j in range(m):
        print(a[i][j],end=' ')
    print()

Guess you like

Origin blog.csdn.net/qq_51408826/article/details/129342220