python函数习题
时间: 2023-11-30 11:01:56 浏览: 100
python习题
这些是Python函数的一些习题,请参考下面的解答:
1. 编写一个函数,计算斐波那契数列的前n项和。
```python
def fibonacci_sum(n):
if n <= 0:
return 0
elif n == 1:
return 1
else:
fib_list = [0, 1]
for i in range(2, n+1):
fib_list.append(fib_list[i-1] + fib_list[i-2])
return sum(fib_list)
result = fibonacci_sum(n)
print("斐波那契数列的前n项和为:", result)
```
2. 编写一个函数,实现折半查找。
```python
def binary_search(arr, target):
low = 0
high = len(arr) - 1
while low <= high:
mid = (low + high) // 2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
arr = [0, 1, 2, 11, 20, 101]
target = 20
index = binary_search(arr, target)
print("在数组中的位置索引为:", index)
```
3. 编写一个函数,反转输入字符串中的字符,但保持标点符号不变。
```python
def reverse_string(s):
punctuation = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''
words = s.split()
reversed_words = []
for word in words:
if len(word) > 1 and any(char not in punctuation for char in word):
reversed_word = word[::-1]
reversed_words.append(reversed_word)
else:
reversed_words.append(word)
return ' '.join(reversed_words)
string = "I enjoy reading!"
reversed_string = reverse_string(string)
print("颠倒后的字符串为:", reversed_string)
```
阅读全文