加拿大瑞尔森大学 Python习题 Lab 3
Lab 3 – CPS 106
This lab helps you practice string manipulation and recursive implementation.
1. You have written an essay that should be at least five pages long, but it is only 4.5 pages. You decide to use your new python skills to stretch it out by putting spaces between each letter and the next. Write a function that takes a string and a number and prints out the string with number of spaces between each pair of letters.
def spacedout(str, numSpaces)
For example spacedout(“It was a dark and stormy night”, 1) returns
“I t w a s a d a r k a n d s t o r m y n i g h t”
2. Write a python program that returns the reverse of a given string.
def reverse(str1)
For example reverse(“I am here”) returns “ereh ma I”. Using this, write a function that checks if a given string is a palindrome.
def isPalindrome(str1)
3. Write a recursive function that prints all the permutations of a given string. For example, for the input “abcd” the function should print:
abcd, abdc, acbd, acdb, adbc, adcb, bacd, badc, bcad, bcda, bdac, bdca, cabd, cadb, cbad, cbda, cdab, cdba, dabc, dacb, dbac, dbca, dcab, dcb
4. Given an integer n, write a python program that finds the digit with the highest number of
occurrences in n. For example, for n = 823778823478234768238 the program should return 8.
def findHighestOccur(n)
Test your program on the following inputs:
n = 983254682376587235235
n = 767347657623764765766665
n = 923740923466234678666872628347666
代码:
#3-1
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 10:17:36 2023
@author: pc
"""
str1 ='It was a dark and stormy night'
space2 = ' '
def spacedout(str, space):
strResult = ''
for a in str:
a = a + space
strResult = strResult + a
print(strResult)
print(str1)
spacedout(str1, space2)
#3-1-2
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 10:29:47 2023
@author: pc
"""
s = 'It was a dark and stormy night'
def spacedout(str):
addspace = ' '
return addspace.join('It was a dark and stormy night')
print(spacedout(s))
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 10:49:56 2023
@author: pc
"""
# 3-2
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 10:17:36 2023
@author: pc
"""
str1 ='It was a dark and stormy night'
space2 = ' '
def spacedout(str, space):
strResult = ''
i = 0
for i in range(len(str)):
a = str[len(str) - i - 1]
strResult = strResult + a
print(strResult)
print(str1)
spacedout(str1, space2)
#3-2 reverse
# -*- coding: utf-8 -*-
"""
Created on Sun Jan 8 10:54:17 2023
@author: pc
"""
s = "I am here"
def reverse(str):
n = len(str)
l = ' '
for i in range(n):
l = l + str[n-i-1]
return l
print(reverse(s))