100 python exercises (2)

  1. Write a program to determine whether a string is a valid bracket sequence.
def isValidParentheses(s):
    stack = []
    parentheses = {
    
    ')': '(', ']': '[', '}': '{'}
    for char in s:
        if char in parentheses.values():
            stack.append(char)
        elif char in parentheses.keys():
            if len(stack) == 0 or parentheses[char] != stack.pop():
                return False
    return len(stack) == 0

string = input("请输入一个括号序列:")
if isValidParentheses(string):
    print(string, "是有效的括号序列")
else:
    print(string, "不是有效的括号序列")
  1. Write a program to calculate the factorial of a number.
num = int(input("请输入一个正整数:"))

factorial = 1
for i in range(1, num+1):
    factorial *= i

print(num, "的阶乘为:", factorial)
  1. Write a program that generates all prime numbers in a specified range.
start = int(input("请输入范围的起始值:"))
end = int(input("请输入范围的结束值:"))

prime_numbers = []

for num in range(start, end+1):
    if num > 1:
        for i in range(2, int(num/2)+1):
            if (num % i) == 0:
                break
        else:
            prime_numbers.append(num)

print("指定范围内的素数为:", prime_numbers)
  1. Write a program to determine whether a number is a palindrome.
num = int(input("请输入一个整数:"))

if str(num) == str(num)[::-1]:
    print(num, "是回文数")
else:
    print(num, "不是回文数")
  1. Write a program to find all even numbers in a list.
num_list = [1, 2, 3, 4, 5, 6]

even_numbers = [num for num in num_list if num % 2 == 0]

print("列表中的偶数为:", even_numbers)
  1. Write a program that counts the number of occurrences of each word in a string.
string = input("请输入一个字符串:")

word_count = {
    
    }

words = string.split()

for word in words:
    word_count[word] = word_count.get(word, 0) + 1

print("每个单词出现的次数:")
for word, count in word_count.items():
    print(word, ":", count)
  1. Write a program to find the two largest numbers in a list.
num_list = [10, 5, 8, 2, 15, 3]

sorted_list = sorted(num_list, reverse=True)

max_numbers = sorted_list[:2]

print("列表中的最大的两个数为:", max_numbers)
  1. Write a program that flips an integer and outputs it.
num = int(input("请输入一个整数:"))

reversed_num = int(str(abs(num))[::-1])

if num < 0:
    reversed_num *= -1

print("翻转后的整数为:", reversed_num)
  1. Write a program to determine whether a string is a palindrome.
string = input("请输入一个字符串:")

string = ''.join(char.lower() for char in string if char.isalpha())

if string == string[::-1]:
    print("是回文句")
else:
    print("不是回文句")
  1. Write a program that moves all even numbers in a list to the end of the list.
num_list = [1, 2, 3, 4, 5, 6]

odd_numbers = [num for num in num_list if num % 2 != 0]
even_numbers = [num for num in num_list if num % 2 == 0]

new_list = odd_numbers + even_numbers

print("移动后的列表为:", new_list)

Here is the code sample for questions 11 to 20. If you need more code for practice questions, please feel free to let me know.

Guess you like

Origin blog.csdn.net/m0_55877125/article/details/132162914