python programming code collection little turtle, what software to use to write python code

Hello everyone, the editor is here to answer the following questions for you, python programming code encyclopedia, little turtle, what software to use to write python code, let us take a look now!

Original title: 30 commonly used minimalist codes in Python, just take them and use them

Article reprinted from: Python Programmer

What is the fastest way to learn Python? Of course, it is to practice various small projects. Only by thinking and writing by yourself can you remember the rules. This article contains 30 minimalist tasks that beginners can try to implement on their own. This article also contains 30 code segments. Python developers can also see if there are any unexpected GPT modifications .

9c79ac41a249c74c78e08803ecbe4252.png

、1

Duplicate element determination

The following method checks if there are duplicate elements in a given list. It uses the set function to remove all duplicate elements.

def all_unique(lst):

return len(lst)== len(set(lst))

x = [ 1, 1, 2, 2, 3, 2, 3, 4, 5, 6]

y = [ 1, 2, 3, 4, 5]

all_unique(x) # False

all_unique(y)# True

2

Character element composition determination

Check whether the elements of two strings are the same.

from collections importCounter

def anagram(first, second):

return Counter(first)== Counter(second)

anagram( "abcd3", "3acdb") # True

3

Memory usage

importsys

variable = 30

print(sys.getsizeof(variable)) # 24

4

Bytes occupied

The following code block checks the number of bytes occupied by a string.

def byte_size(string):

return(len(string.encode( 'utf-8')))

byte_size( '')# 4

byte_size( 'Hello World')# 11

5

Print string N times

This code block prints the string N times without looping.

n = 2

s = "Programming"

print(s * n)

# ProgrammingProgramming

6 Capitalize the first letter

The following code block uses the title method to capitalize the first letter of each word in a string.

s = "programming is awesome"

print(s.title)

# Programming Is Awesome

7

Block

Given a specific size, define a function to cut the list according to this size.

from math importceil

def chunk(lst, size):

return list(

map(lambda x: lst[x * size:x * size + size],

list(range( 0, ceil(len(lst) / size)))))

chunk([ 1, 2, 3, 4, 5], 2)

# [[

Guess you like

Origin blog.csdn.net/mynote/article/details/133251189