编程必背100个代码
编程必背100个代码详细介绍
1. Hello World程序(多种语言)
- Python
print("Hello, World!")
- Java
public class Main {
public static void main(String[] args) {
System.out.println("Hello, World!");
}
}
- C++
#include
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
2. 变量定义与赋值(以Python为例)
# 整数
age = 20
# 浮点数
height = 1.75
# 字符串
name = "John"
# 布尔值
is_student = True
3. 算术运算(以Python为例)
a = 5
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a % b)
4. 条件判断(以Java为例)
int score = 80;
if (score >= 90) {
System.out.println("优秀");
} else if (score >= 60) {
System.out.println("合格");
} else {
System.out.println("不合格");
}
5. 循环语句 - for循环(以Python为例)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
6. 循环语句 - while循环(以Python为例)
count = 0
while count < 5:
print(count)
count += 1
7. 函数定义与调用(以Python为例)
def add_numbers(a, b):
return a + b
result = add_numbers(3, 5)
print(result)
8. 列表操作(以Python为例)
my_list = [1, 2, 3, 4, 5]
print(my_list[0])
my_list[1] = 10
print(my_list)
sub_list = my_list[1:3]
print(sub_list)
my_list.append(6)
print(my_list)
9. 字典操作(以Python为例)
my_dict = {"name": "John", "age": 20}
print(my_dict["name"])
my_dict["age"] = 21
my_dict["city"] = "New York"
print(my_dict)
10. 字符串操作(以Python为例)
string = "Hello, World!"
print(string[0])
print(string.upper())
print(string.split(", "))
11. 文件读取(以Python为例)
try:
with open("example.txt", "r") as file:
content = file.read()
print(content)
except FileNotFoundError:
print("文件不存在")
12. 文件写入(以Python为例)
data = "这是要写入文件的内容"
with open("new_file.txt", "w") as file:
file.write(data)
13. 排序算法 - 冒泡排序(以Python为例)
def bubble_sort(num_list):
n = len(num_list)
for i in range(n):
for j in range(0, n - i - 1):
if num_list[j] > num_list[j + 1]:
num_list[j], num_list[j + 1] = num_list[j + 1], num_list[j]
return num_list
num_list = [5, 4, 3, 2, 1]
print(bubble_sort(num_list))
14. 简单的递归函数 - 计算阶乘(以Python为例)
def factorial(n):
if n == 0 or n == 1:
return 1
return n * factorial(n - 1)
print(factorial(5))
15. 类的定义与对象创建(以Java为例)
class Person {
String name;
int age;
void speak() {
System.out.println("我叫" + name + ",我" + age + "岁了。");
}
}
Person p = new Person();
p.name = "Alice";
p.age = 25;
p.speak();
16. 继承(以Java为例)
class Animal {
void sound() {
System.out.println("动物发出声音");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("汪汪汪");
}
}
Dog dog = new Dog();
dog.sound();
17. 多态(以Java为例)
class Shape {
void draw() {
System.out.println("绘制形状");
}
}
class Circle extends Shape {
@Override
void draw() {
System.out.println("绘制圆形");
}
}
class Square extends Shape {
@Override
void draw() {
System.out.println("绘制正方形");
}
}
Shape[] shapes = new Shape[2];
shapes[0] = new Circle();
shapes[1] = new Square();
for (Shape shape : shapes) {
shape.draw();
}
18. 异常处理(以Python为例)
try:
a = 5 / 0
except ZeroDivisionError:
print("除数不能为0")
19. 生成随机数(以Python为例)
import random
random_number = random.randint(1, 10)
print(random_number)
20. 列表推导式(以Python为例)
squares = [i * i for i in range(10)]
print(squares)
21. 元组操作(以Python为例)
my_tuple = (1, 2, 3)
print(my_tuple[0])
22. 集合操作(以Python为例)
my_set = {1, 2, 3, 3}
print(my_set)
my_set.add(4)
print(my_set)
another_set = {3, 4, 5}
union_result = my_set | another_set
print(union_result)
intersection_result = my_set & another_set
print(intersection_result)
23. 装饰器(以Python为例)
def my_decorator(func):
def wrapper():
print("在函数执行前")
func()
print("在函数执行后")
return wrapper
@my_decorator
def say_hello():
print("Hello!")
say_hello()
24. 迭代器(以Python为例)
my_list = [1, 2, 3]
my_iterator = iter(my_list)
print(next(my_iterator))
print(next(my_iterator))
print(next(my_iterator))
25. 生成器(以Python为例)
def my_generator():
for i in range(3):
yield i
gen = my_generator()
print(next(gen))
print(next(gen))
print(next(gen))
26. 枚举(以Python为例)
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(index, fruit)
27. 格式化输出(以Python为例)
name = "John"
age = 30
print("我的名字是{},我{}岁了。".format(name, age))
28. 深浅拷贝(以Python为例)
import copy
original_list = [[1, 2, 3], [4, 5, 6]]
shallow_copied_list = copy.copy(original_list)
deep_copied_list = copy.deepcopy(original_list)
original_list[0][0] = 0
print(shallow_copied_list)
print(deep_copied_list)
29. 模块导入(以Python为例)
import math
print(math.sqrt(9))
30. 时间处理(以Python为例)
import time
print(time.time())
31. 日期处理(以Python为例)
import datetime
current_date = datetime.date.today()
print(current_date)
32. 命令行参数(以Python为例)
import sys
print(sys.argv)
33. 网络请求 - 使用requests库(以Python为例)
import requests
response = requests.get("https://www.example.com")
print(response.text)
34. JSON数据处理(以Python为例)
import json
data = {"name": "John", "age": 30}
json_data = json.dumps(data)
print(json_data)
parsed_data = json.loads(json_data)
print(parsed_data)
35. 数据库连接 - 以MySQL为例(使用Python和pymysql库)
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='password', database='test')
try:
with conn.cursor() as cursor:
# 执行SQL查询
sql = "SELECT * FROM users"
cursor.execute(sql)
results = cursor.fetchall()
for row in results:
print(row)
finally:
conn.close()
36. 线程创建(以Python为例)
import threading
def print_numbers():
for i in range(10):
print(i)
thread = threading.Thread(target=print_numbers)
thread.start()
37. 进程创建(以Python为例)
import multiprocessing
def print_numbers():
for i in range(10):
print(i)
process = multiprocessing.Process(target=print_numbers)
process.start()
38. 排序算法 - 选择排序(以Python为例)
def selection_sort(num_list):
for i in range(len(num_list)):
min_idx = i
for j in range(i + 1, len(num_list)):
if num_list[j] < num_list[min_idx]:
min_idx = j
num_list[i], num_list[min_idx] = num_list[min_idx], num_list[i]
return num_list
num_list = [5, 4, 3, 2, 1]
print(selection_sort(num_list))
39. 排序算法 - 插入排序(以Python为例)
def insertion_sort(num_list):
for i in range(1, len(num_list)):
current_value = num_list[i]
position = i
while position > 0 and num_list[position - 1] > current_value:
num_list[position] = num_list[position - 1]
position -= 1
num_list[position] = current_value
return num_list
num_list = [5, 4, 3, 2, 1]
print(insertion_sort(num_list))
40. 动态规划 - 斐波那契数列(以Python为例)
def fibonacci(n):
if n <= 1:
return n
dp = [0] * (n + 1)
dp[0], dp[1] = 0, 1
for i in range(2, n + 1):
dp[i] = dp[i - 1] + dp[i - 2]
return dp[n]
print(fibonacci(10))
41. 贪心算法 - 找零问题(以Python为例)
def coin_change(coins, amount):
coins.sort(reverse=True)
count = 0
for coin in coins:
count += amount // coin
amount %= coin
return count if amount == 0 else -1
coins = [1, 2, 5]
amount = 11
print(coin_change(coins, amount))
42. 二分查找(以Python为例)
def binary_search(num_list, target):
low = 0
high = len(num_list) - 1
while low <= high:
mid = (low + high) // 2
if num_list[mid] == target:
return mid
elif num_list[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
num_list = [1, 3, 5, 7, 9]
target = 5
print(binary_search(num_list, target))
43. 栈的实现(以Python为例)
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
return self.items.pop()
def is_empty(self):
return len(self.items) == 0
stack = Stack()
stack.push(1)
stack.push(2)
print(stack.pop())
44. 队列的实现(以Python为例)
class Queue:
def __init__(self):
self.items = []
def enqueue(self, item):
self.items.append(item)
def dequeue(self):
return self.items.pop(0)
def is_empty(self):
return len(self.items) == 0
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
print(queue.dequeue())
45. 链表的实现(以Python为例)
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
return
current = self.head
while current.next:
current = current.next
current.next = new_node
def display(self):
current = self.head
while current:
print(current.data, end=" ")
current = current.next
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.display()
46. 树的遍历 - 前序遍历(以Python为例,二叉树)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorderTraversal(root):
if root is None:
return []
result = []
result.append(root.val)
result.extend(preorderTraversal(root.left))
result.extend(preorderTraversal(root.right))
return result
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
print(preorderTraversal(root))
47. 树的遍历 - 中序遍历(以Python为例,二叉树)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def inorderTraversal(root):
if root is None:
return []
result = []
result.extend(inorderTraversal(root.left))
result.append(root.val)
result.extend(inorderTraversal(root.right))
return result
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
print(inorderTraversal(root))
48. 树的遍历 - 后序遍历(以Python为例,二叉树)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def postorderTraversal(root):
if root is None:
return []
result = []
result.extend(postorderTraversal(root.left))
result.extend(postorderTraversal(root.right))
result.append(root.val)
return result
root = TreeNode(1)
root.right = TreeNode(2)
root.right.left = TreeNode(3)
print(postorderTraversal(root))
49. 图的表示 - 邻接矩阵(以Python为例)
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = [[0 for _ in range(vertices)] for _ in range(vertices)]
def add_edge(self, u, v):
self.graph[u][v] = 1
self.graph[v][u] = 1
graph = Graph(4)
graph.add_edge(0, 1)
graph.add_edge(0, 2)
graph.add_edge(1, 3)
print(graph.graph)
50. **图的遍历 - 深度优先搜索