100 examples of python 3.6 classic algorithm

#This article is based on python3.6

1. A 5-digit number to determine whether it is a palindrome.

x=input("please input:")
t=0
for i in range(int(len(x)/2)):
        if x[i] != x[-i-1]:
            print('this number is not a huiwen')
            t=1
            break
if t==0:
    print ('this is a huiwen shu')
2. With 1, 2, 3, and 4 numbers, how many three-digit numbers can be formed without repeating numbers? How much are they?
for i in range(1,5):
     for j in range(1,5):
        for k in range(1,5):
            if(i!=j)and(i!=k)and(j!=k):
                    print(str(i)+str(j)+str(k))
3. An integer plus 168 is a perfect square, plus 168 is a perfect square.
import math
    for i in range(10000):
        x=int(math.sqrt(i+100))
        y=int(math.sqrt(i+268))
        if(x*x==i+100)&(y*y==i+268):
             print(i)

4. Enter a certain month and a certain day of a certain year to determine the day of the year.

#method one:
year=int(input("year:"))
month=int(input("month:"))
day=int(input("day:"))
m=[31,30,31,30,31,31,30,31,30,31]
if month==1:
    s=day
if month==2:
    s=31+day
if month>=3:
    if(year%400==0)or(year%100!=0)and(year%4==0):
        s=sum(m[:month-3])+60+day
    else:
        s=sum(m[:month-3])+59+day
        
print('Today is the %d day of the year.'%s)
#Method Two:
import datetime
import time
year=int(input("year:"))
month=int(input("month:"))
day=int(input("day:"))
def function2(year, month, day): # Directly use the format conversion function of Python's built-in module datetime to get the result
  date = datetime.date(year, month, day)
  return date.strftime('%j')
print(function2(year, month, day))
5. Sort the numbers
l=[]
for i in range(3):
    x=int(input( 'the number is :\n'))
    l.append(x)
l.sort()
print(l)
6. Use * to output the letter C
print('*'*10)
for i in range(10):
    print('*')
print('*'*10)
7. Output the nine-nine multiplication table
for i in range(1,10):
    for j in range(1,i+1):
        print('%d * %d =%2d'%(i,j,i*j),end='')
    print('')

8. Ask to output a chess board.

import sys
for i in range(8):
    for j in range(8):
        if(i + j) % 2 == 0:
            sys.stdout.write(chr(219))
            sys.stdout.write(chr(219))
        else:
            sys.stdout.write(' ')   #some little question.
    print ('')
9. Print the stairs, and print two smiley faces on the stairs at the same time.
import sys
sys.stdout.write(chr(1))
sys.stdout.write(chr(1))     #Q
print('')
for i in range(1,11):
    for j in range(1,i):
        sys.stdout.write(chr(219))
        sys.stdout.write(chr(219))   
    print('')
10. The Classical Rabbit Problem
a=1; b=1
for i in range(1,21):
    print('%2d %2d'%(a,b))
    if i % 2==0:
        print('')
    a=a+b
    b=a+b

11. Determine how many prime numbers there are between 101-200, and output all prime numbers.

# A number that is only divisible by itself and 1 is called a prime number
sushi=[]
for i in range(101,201):  
    for j in range(2,i):
        if i%j==0:
            break
    else:    #Pay attention to indentation
        sushu.append(i)
print("The number of prime numbers between 101-200 is: %d"%len(sushu)) #Cannot    have characters in Chinese state, otherwise an error will be reported  
print("The prime numbers between 101-200 are:",sushu)      # List can't format output?

12. Print the number of daffodils

for i in range(100,1000):
    if i==((i//100)**3+(i%10)**3+(i//10%10)**3):
        print(i)
    continue #break is to jump out of the entire loop, for is to jump out of the current loop only

13. Ask for 1! +2! +...+n!.
s=0
def f(n):
    if n<=1:
        return 1
    else:
        return n*f(n-1)
j=int(input('my number is:\n'))
for i in range(1,j+1):
    s+=f(i)    
print(s)

14. Enter a number, find the total number of digits, and print it in reverse order.

strA=input("Please enter the string that needs to be flipped: ")  
order = []   
for i in strA:  
  order.append(i)  
order.reverse() #reverse the list  
print (''.join(order))
print(len(order))  

15. There is a sequence of fractions: 2/1, 3/2, 5/3, 8/5, 13/8, 21/13... Find the sum of the first 20 terms of this sequence.

from functools import reduce      
a = 2.0
b = 1.0
l = []
for n in range(1,21):
    b,a = a,a + b
    l.append(a / b)
print(reduce(lambda x,y:x+y,l))

16. Factor positive integers into prime factors.

from sys import stdout
n=input("the number is:")
n=(int(n))
for i in range(2,n+1):
    while n!=i:
        if n%i==0:
            stdout.write(str(i))
            stdout.write("*")
            n=n/i
        else:
            break
print("%d" % n)

17. Seek n!.

def f(n):
    if n<=1:
        return 1
    else:
        return n*f(n-1)
j=int(input('my number is:\n'))
print(j)

18. Randomly generate ten sieve numbers.

import random
for x in range(1,11):
    r_n = random.randint (1,6)
    print(r_n)

19. Pick words at random.

import random
words=['chicken','dog','cat','mouse','frog']  
def pick_a_word() :
    word_position = random.randint(0,len(words)-1)
    return words[word_position]
print(pick_a_word())
20. Use the nesting of conditional operators to complete the filtering of scores.
score =int(input('your score is:'))
if score>=90:
    print('your grade is:%s'%'A')
elif score >=80:
    print('your grade is:%s'%'B')
elif score>=60:
    print('your grade is:%s'%'C')
else:
    print('you are out!')

21: Input a line of string, and count the number of English letters, spaces, numbers and other characters in it.

import string
s=input('your string is:\n')
letters=0;space=0;digit=0;others=0;
for i in s:
    if i.isalpha():
        letters+=1
    elif i.isspace ():
        space+=1
    elif i.isdigit():
        digit+=1
    else:
        others+=1
print(letters);
print(space)
print(digit)
print(others)

22. Find the value of s=a+aa+aaa+aaaa+aaaaa+...+aa...a.

from functools import reduce
a=int(input('the number is:'))
n=int(input('the frequency is:'))
s=0
A=[]
for count in range(n):
    s=s+a
    a=a*10
    A.append(s)
print(s)
A=reduce(lambda x,y:x+y,A)
print(A)
23. Using tensor flow to generate QR code data, based on 2.7, 3.6 cannot import captcha Bag.
from captcha.image import ImageCaptcha   #pip install captcha
import numpy as np
import matplotlib.pyplot as plt
from PIL import Image
import random

number=['0','1','2','3','4','5','6','7','8','9']
alphabet=['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']
ALPHABET=['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']

def random_captcha_text(char_set=number+alphabet+ALPHABET,captcha_size=4):
   captcha_text=[]
   for i in range(captcha_size):
       c=random.choice(char_set)
       captcha_text.append(c)
   return captcha_text

def gen_captcha_text_and_image():
    image = ImageCaptcha()
    
    captcha_text=random_captcha_text()
    captcha_text=''.join(captcha_text)
    
    captcha = image.generate(captcha_text)
    captcha_image = Image.open(captcha)
    captcha_image = np.array(captcha_image)
    return captcha_text,captcha_image
if __name__=='__main__':
    
    text,image=gen_captcha_text_and_image()
    
    f=plt.figure()
    ax=f.add_subplot(111)
    ax.text(0.1,0.9,text,ha='center',va='center',transform=ax.transAxes)
    plt.imshow(image)
    plt.show()

24. Find the complete number within 1000.

from functools import reduce
b=[]
for i in range(1,1001):
    for j in (1,i):
        if i%j==0:
            b.append(j)
        k=reduce(lambda x,y:x+y,b)
if i == k:
   print(i)

25. The ball falls from a height of 100 meters. Each time it hits the ground, it bounces to half of its original height, and then falls again. Find how many meters it has passed when it hits the ground for the tenth time, and how high is the tenth rebound.

s=100
x=s/2
for i in range(2,10):
    s+=2*x
    x/=2
print('the total height is:\n%f'%s)
print('the tenth height is: \n%f'%x)

26. Monkey eats peach

x=1
for i in range(9,0,-1):
    s=(x+1)*2
    x=s
print(s)

27. Table tennis match



28. Print the rhombus.

s = '*'
for i in range(1, 8, 2):
    print((s*i).center(7))
for i in reversed(range(1, 6, 2)):
    print((s*i).center(7))


29. Select Sort.

list = [3, 1, 5, 7, 8, 6, 2, 0, 4, 9]
def choice(list):
    for i in range(0,len(list)-1):
        min_loc = i
        for j in range(i+1,len(list)-1):
            if list[min_loc]>list[j]: #Minimum traversal comparison
                min_loc = j
        list[i],list[min_loc] = list[min_loc],list[i]
    return list
print(choice(list))
30. Determine whether a five-digit number is a palindrome.
x=int(input("input a number:\n"))
x=str(x)
for i in range(len(x)):
    if x[i]!=x[-i-1]:
        print("this number is not a huiwenshu!")
        break
    else:
        print("right!")
        break #This is correct, pay attention to the usage of break

31. Enter the first letter of the day of the week to judge the day of the week. If the first letter is the same, look at the second letter




32. Text Color Control



33. Find the sum of the diagonal elements of a 3*3 matrix


34. Output an array in reverse order


35. There is an array that has been sorted, enter a number, and ask to insert it into the array according to the original law






Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325634226&siteId=291194637