以下是第31到40题的代码示例:
def is_valid_parentheses(s):
stack = []
parentheses_mapping = {")": "(", "]": "[", "}": "{"}
for char in s:
if char in parentheses_mapping.values():
stack.append(char)
elif char in parentheses_mapping.keys():
if stack and stack[-1] == parentheses_mapping[char]:
stack.pop()
else:
return False
return len(stack) == 0
string = input("请输入一个括号序列:")
if is_valid_parentheses(string):
print("是有效的括号序列")
else:
print("不是有效的括号序列")
from collections import Counter
num_list = [1, 2, 3, 4, 1, 2, 3, 2, 2, 2]
counter = Counter(num_list)
most_common = counter.most_common(1)[0][0]
print("出现次数最多的元素为:", most_common)
def is_perfect_square(num):
if num < 0:
return False
root = int(num ** 0.5)
return root * root == num
num = int(input("请输入一个整数:"))
if is_perfect_square(num):
print(num, "是完全平方数")
else:
print(num, "不是完全平方数")
num_list = [1, 2, 3, 4, 5]
total_sum = sum(num_list)
print("列表中所有元素的和为:", total_sum)
def find_missing_number(num_list):
n = len(num_list) + 1
expected_sum = (n * (n + 1)) // 2
actual_sum = sum(num_list)
return expected_sum - actual_sum
num_list = [1, 2, 4, 5, 6]
missing_number = find_missing_number(num_list)
print("缺失的数字为:", missing_number)
string = input("请输入一个字符串:")
word_list = string.split()
reversed_string = " ".join(word_list[::-1])
print("逆序输出的字符串为:", reversed_string)
def is_leap_year(year):
if year % 4 == 0:
if year % 100 == 0:
if year % 400 == 0:
return True
else:
return False
else:
return True
else:
return False
year = int(input("请输入一个年份:"))
if is_leap_year(year):
print(year, "是闰年")
else:
print(year, "不是闰年")
import string
import random
def generate_random_password(length):
characters = string.ascii_letters + string.digits + string.punctuation
password = ''.join(random.choice(characters) for _ in range(length))
return password
length = int(input("请输入密码的长度:"))
random_password = generate_random_password(length)
print("生成的随机密码为:", random_password)
decimal = int(input("请输入一个十进制数:"))
binary = bin(decimal)[2:]
print("转换为二进制数:", binary)
string = input("请输入一个字符串:")
capitalized_string = string.title()
print("首字母大写的字符串:", capitalized_string)
这是第31到40题的代码示例。希望对你有帮助!如果你还有其他问题,请随时提问。