In: Computer Science
In Python 3.6
Question 1 for strings
a) Write a function named longest_common_prefix that takes two strings and returns the longest common prefix of the two strings. For example, the longest common prefix of distance and disinfection is dis. If the two strings have no common longest common prefix, the method returns an empty string.
b) Write a function named reverse that takes a string argument and returns its reverse. For example, reverse(‘I am testing’) should return the string ‘gnitset ma I’. Use iteration for this and answers using slicing will not be accepted. Imma like... what.
c) Write a function named check_password that checks whether a string is a valid password. Return True if it is a valid password and False otherwise. The password rules are as follows:
• A password must have at least 8 characters.
• A password must consist of only letters and digits.
• A password must contain at least two digits.
Note : Both reverse() method works correctly. The only difference is one start traversing from string end and one from starting string.
CODE:
def longest_common_prefix(string1,string2):
minimum = min(len(string1),len(string2))
prefix = ''
for i in range(minimum):
if string1[i] == string2[i]:
prefix += string1[i]
else:
break
return prefix
print(longest_common_prefix('distance','disinfection'))
print(longest_common_prefix('distance','infection'))
print(longest_common_prefix('string1','string2'))
def reverse(string):
rev = ''
for i in range(len(string)-1,-1,-1):
rev += string[i]
return rev
def reverse(string):
rev = ''
for i in range(len(string)):
rev = string[i] + rev
return rev
print(reverse('I am testing!'))
def check_password(password):
if len(password) < 8: # if length is less than 8
return False
else:
c = 0 # counter for number of digits
for i in password:
if not(i.isdigit() or i.isalpha()): # If any of the character is neither number or alphabet
return False
if i.isdigit(): # Mainting count of numbers
c +=1
if c<2:
return False
else:
return True
print(check_password('maria1254'))
OUTPUT:
