31.反转一个3位整数
def reverse_number(num):
if num < 100 or num > 999:
return "请输入一个3位整数"
else:
reverse_num = int(str(num)[::-1])
return reverse_num
num = 123
reverse_num = reverse_number(num)
print(reverse_num)
32.合并排序数组
def merge_sorted_arrays(arr1,arr2):
merged_array = sorted(arr1 + arr2)
return merged_array
arr1 = [1,3,5]
arr2 = [2,4,6]
merged_array = merge_sorted_arrays(arr1,arr2)
print(merged_array)
33.旋转字符串
def rotate_string(s,k):
k = k % len(s)
rotated_string = s[-k:] + s[:-k]
return rotated_string
s = "abcdefg"
k = 3
rotated_string = rotate_string(s,k)
print(rotated_string)
34.相对排名
def relative_ranks(scores):
ranks = sorted(scores, reverse=True)
rankings = ["Gold Medal", "Silver Medal", "Bronze Medal"] + list(map(str, range(4, len(scores) + 1)))
ranked_scores = []
for score in scores:
rank_index = ranks.index(score)
ranked_scores.append(rankings[rank_index])
return ranked_scores
scores = [10, 20, 30, 40, 50]
ranked_scores = relative_ranks(scores)
print(ranked_scores) # 输出:['Silver Medal', 'Bronze Medal', 4, 3, 'Gold Medal']
35.二分查找
def binary_search(nums,target):
low = 0
high = len(nums) - 1
while low <= high:
mid = (low + high) // 2
if nums[mid] == target:
return mid
elif nums[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
nums = [1,2,3,4,5]
target = 3
index = binary_search(nums,target)
print(index)
36.下一个更大的数
def next_greater_number(nums):
stack = []
result = [-1] * len(nums)
for i in range(len(nums)):
while stack and nums[stack[-1]] < nums[i]:
index = stack.pop()
result[index] = nums[i]
stack.append(i)
return result
nums = [4,5,2,25,10]
next_greater = next_greater_number(nums)
print(next_greater)
37.字符串中单词数
def count_words(s):
words = s.split()
return len(words)
s = "Hello, world! This is an example sentence."
word_count = count_words(s)
print(word_count)
38.勒索信
def can_construct_letter(magazine, letter):
magazine_chars = {}
for char in magazine:
magazine_chars[char] = magazine_chars.get(char, 0) + 1
for char in letter:
if char not in magazine_chars or magazine_chars[char] == 0:
return False
else:
magazine_chars[char] -= 1
return True
magazine = "aabccde"
letter = "abc"
can_construct = can_construct_letter(magazine, letter)
print(can_construct) # 输出:True
39.不重复的两个数
def find_unique_numbers(nums):
xor_result = 0
for num in nums:
xor_result ^= num
rightmost_set_bit = xor_result & -xor_result
num1 = 0
num2 = 0
for num in nums:
if num & rightmost_set_bit:
num1 ^= num
else:
num2 ^= num
return [num1,num2]
nums = [2, 4, 3, 6, 3, 2, 5, 5]
unique_nums = find_unique_numbers(nums)
print(unique_nums)
40.双胞胎字符串
def is_twin_string(str1,str2):
if len(str1) != len(str2):
return False
for char1,char2 in zip(str1,str2):
if char1 == char2 or (char1 in "aeiou" and char2 in "aeiou"):
continue
else:
return False
return True
str1 = "hello"
str2 = "holle"
is_twin = is_twin_string(str1,str2)
print(is_twin)