Please use the Python Language, preferabally 2.7, to solve this two probem set a
ID: 3874399 • Letter: P
Question
Please use the Python Language, preferabally 2.7, to solve this two probem set about while loops. The parameters and answer template for the solution is also given beneath the problem descriptions.
#PROBLEM 1
def pair(l1):
list1 = l1
return 0
#YOUR CODE GOES HERE (indented)
return l1
#END YOUR CODE
#PROBLEM 2
def replace(l1,l2):
string1 = l1
string2 = l2
#YOUR CODE GOES HERE (indented)
return string1
#END YOUR CODE
Explanation / Answer
1.
def pair(l1): #function pair
list1 = l1 #creating temperory variable to store store list
l1 = [] #assigning list to null
i = 0 #variable to represent index of the list
while i<len(list1): #for looping through entire loop
if i < len(list1)-2: #if there are 2 elements to pair
s = str(list1[i]) + ',' + str(list1[i+2])
else: #if there are no two elements to pair
s = str(list1[i])
l1.append(s) #appending the variable to the list
i += 4 #incrementing array index by 4
return l1 #returning list
#END YOUR CODE
print pair([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) #calling the function
output:
2.
def replace(l1,l2):
string1 = l1 #temperory variables for mofidification
string2 = l2
i = 0 #initializing index to zero
while i < len(l1): #looping through the loop
if string1[i] == string2: #if the character is equal to the second passed character
string1 = string1[:i] + "Q" + string1[i+1:] #replacing the charcter if condition satisfies
i += 1 #incrementing loop by 1
#YOUR CODE GOES HERE (indented)
return string1 #returning string
#END YOUR CODE
s = raw_input("Enter String")
c = raw_input("Enter character")
print replace(s,c) #calling function
output: