Question

In: Computer Science

THANK YOU FOR ANSWERING THE 4 QUESTIONS Q3. Create a function in Python called sum_list_div2 which...

THANK YOU FOR ANSWERING THE 4 QUESTIONS

Q3. Create a function in Python called sum_list_div2 which takes as input a list of integers and returns the sum of the elements of the list which divide by 2.

Examples of tests in the Python interpreter:

>>> sum_list_div2 ([1,4,3,8,5])

12

>>> sum_list_div2 ([])

0

>>> sum_list_div2 ([4, -10,7])

-6

--------------------------------------------------------------------------------------------------------------------------------------------------------------

Q5. Imagine a customer at a bank who must enter a number that represents their money. There are people who type spaces to separate the thousand, millions, etc. The bank needs this number without the spaces.

Create a function in Python named number which takes as input a string of characters s. The function returns an integer that represents the number. If s contains characters other than numbers and spaces, the function returns None. If it only contains numbers and

spaces, we assume that the spaces are well placed. For example, s might be '119 189 000' but not '1345'.

Examples of tests in the Python interpreter:

>>> number ("251")

251

>>> number ("1 abc 340")

>>> number ("1250")

1250

>>> number ("- 97,500")

-97500

>>> number ("1000 001") 1000001

>>> number ("999 999 100 102") 999999100102

>>> number ("")

0

--------------------------------------------------------------------------------------------------------------------------------------------------------------

Q8. Create a function in Python named encrypt which takes as input a string of characters s and returns an encrypted version of s. A simple encryption system writes the message beginning with the characters at the end, in reverse order. For example, 'Hello, world' becomes 'dlrow, olleH'. To make the system more difficult to decode, the function starts when standing and at the end, at the same time. The first and last character become the first and second character in the new string, the second and penultimate character become the third and fourth, etc. For example, 'Hello, world' becomes 'dHlerlolwo', (specious characters, punctuation marks, spaces, etc. are treated the same) and '0123456789' becomes '9081726354'.

Examples of tests in the Python interpreter:

>>> encrypt ("Hello, world")

'dHlerlolwo,'

>>>> encrypt ("1234")

'4132'

>>> encrypt ("12345")

'51423'

>>> encrypt ("1")

'1'

>>> encrypt ("123")

'312'

>>> encrypt ("12")

'21'

>>> encrypt ("Secret Message")

'eSgeacsrseetM'

>>> encrypt (", '4'r")

"r, '' 4"

--------------------------------------------------------------------------------------------------------------------------------------------------------------

Q10. This question is difficult to resolve. Use fragments of the strings (operator :) and test the equality of the two strings if necessary (s1 == s2).

A word has the property squarefree if it does not contain the same subword twice in a row. Examples:

ana is squarefree.

borborygmus is not squarefree, there are bor twice in a row.

abracadabra is squarefree.

repetitive is not squarefree because ti is repeated twice in a row.

grammar is not squarefree because m is repeated twice in a row

gaga is not squarefree because ga is repeated twice in a row

rambunctious is squarefree.

abcab is squarefree.

abacaba is squarefree.

zrtzghtghtghtq is not squarefree because ght is repeated twice in a row (three times, friends twice is enough to return False).

aa is not squarefree because a is repeated twice in a row

zatabracabrac is not squarefree because abrac is repeated twice in a row

Create a function in Python named squarefree which takes as input a string of characters s and returns True if s has the property squarefree and False otherwise.

Examples of tests in the Python interpreter:

>>> squarefree ("")

True

>>> squarefree ("a")

True

>>> squarefree ("zrtzghtghtghtq")

False

>>> squarefree ("abcab")

True

>>> squarefree ("12341341")

False

>>> squarefree ("44")

False

Solutions

Expert Solution

CODE FOR EVERY QUESTION WITH PROGRAM SNIPPET AND OUTPUT IS GIVEN BELOW

Q3:

CODE:

def sum_list_div2(list_of_int):

  dividebytwo=[]

  for i in list_of_int:

    if i%2==0:

      dividebytwo.append(i)

  return sum(dividebytwo)

print(sum_list_div2([1,4,3,8,5]))

CODESNIPPET

def sum_list_div2(list_of_int):
  dividebytwo=[]
  for i in list_of_int:
    if i%2==0:
      dividebytwo.append(i)
  return sum(dividebytwo)

print(sum_list_div2([1,4,3,8,5]))

OUTPUT

12

Q5.

CODE:

def number(s):

  s=s.replace(" ","") #REMOVE ALL THE SPACES IN THE STRING

  list1=list(s) #CONVERT TO LIST FOR EASY PROCESSING

  listofnum=""

  for i in list1: #SCAN EACH CHARACTER IN THE STRING

    if i.isalpha()==False: #CHECK IF THE CHARACTER IS ALPHABET OR NOT

      if i!=",": #DONT PRINT , IF FOUND IN THE STRING

        listofnum+=i

    else:

      return None #IF ALPHABET FOUND THAN RETURN NONE

  return listofnum

print(number("-1,0000 0009"))

CODE SNIPPET

def number(s):
  s=s.replace(" ","") #REMOVE ALL THE SPACES IN THE STRING
  list1=list(s) #CONVERT TO LIST FOR EASY PROCESSING
  listofnum=""
  for i in list1: #SCAN EACH CHARACTER IN THE STRING
    if i.isalpha()==False: #CHECK IF THE CHARACTER IS ALPHABET OR NOT
      if i!=",": #DONT PRINT , IF FOUND IN THE STRING
        listofnum+=i
    else:
      return None #IF ALPHABET FOUND THAN RETURN NONE
  return listofnum

print(number("-1,0000 0009"))

OUTPUT

-100000009

Q8.

CODE:

def encrypt(s):

  s=list(s) #Convert string to list so that we can process easily

  slen=len(s)-1

  encryptedtext=""

  for ind in range(len(s)): #we will take 2 points one from start and another from end to encrypt first and last letters

    if ind>slen: #check if the 2 indexes crosses each other at any point as one is moving from index 0 and another from last index of string

      break

    if ind==slen: #if string length is odd than at last both counters will point to the same element

      encryptedtext+=s[ind]

      break

    encryptedtext+=s[slen] #append letter from the front

    encryptedtext+=s[ind] #append letter from the last

    slen-=1

  return encryptedtext

print(encrypt("SecretMessage"))

print(encrypt("12345"))

CODE SNIPPET

def encrypt(s):
  s=list(s) #Convert string to list so that we can process easily
  slen=len(s)-1
  encryptedtext=""
  for ind in range(len(s)): #we will take 2 points one from start and another from end to encrypt first and last letters
    if ind>slen: #check if the 2 indexes crosses each other at any point as one is moving from index 0 and another from last index of string
      break
    if ind==slen: #if string length is odd than at last both counters will point to the same element
      encryptedtext+=s[ind]
      break
    encryptedtext+=s[slen] #append letter from the front
    encryptedtext+=s[ind] #append letter from the last
    slen-=1
  return encryptedtext
print(encrypt("SecretMessage"))
print(encrypt("12345"))

OUTPUT

eSgeacsrseetM
51423

Q10.

CODE:

def square_free(func_str):

    result = True         #CREATING A RESULT VARIABLE THAT WILL BE RETURNED

    str_len = len(func_str)     #CALCULATING THE LENGTH OF THE PASSED STRING

    for p in range(str_len):    #LOOPING THROUGH THE LENGTH OF THE STRING

        for q in range(p+1, str_len):

            if func_str[p:q] == func_str[q:q+(q-p)]: #check second occurence of every possible substring from the first index

                result = False

    return result

print(square_free("zrtzghtghtghtq"))

print(square_free("abcab"))

print(square_free("12341341"))

CODE SNIPPET

def square_free(func_str):

    result = True         #CREATING A RESULT VARIABLE THAT WILL BE RETURNED
    str_len = len(func_str)     #CALCULATING THE LENGTH OF THE PASSED STRING

    for p in range(str_len):    #LOOPING THROUGH THE LENGTH OF THE STRING
        for q in range(p+1, str_len):
            if func_str[p:q] == func_str[q:q+(q-p)]: #check second occurence of every possible substring from the first index
                result = False
    return result

print(square_free("zrtzghtghtghtq"))
print(square_free("abcab"))
print(square_free("12341341"))

OUTPUT

False
True
False

SUMMARY:

All of the above codes are witten with the comments. Hence the explaination is given in the comments. The first code gets the list of numbers and check if it is even by dividing by 2 and sum all the numbers which are divided exactly by 2. The second code finds if string contains any alphabet or not and if found than return None else the entire string with only numbers. The third code takes an input string and loops from start and maintains a variable which decrements from the last index of string. We increment and decrement in every iteration with appending the characters in encrypted text. The last code finds all the possible substrings and checks if similar another substring is found consecutively in a row or not.

Note: If you have any queries than let me know in the comments. If you find it helpful than a Like would be appreciated.


Related Solutions

In Python Create a function called ℎ?????. The function has as arguments a list called ??????...
In Python Create a function called ℎ?????. The function has as arguments a list called ?????? and a list call center. • List ?????? contains lists that represent points. o For example, if ?????? = [[4,2], [3,2], [6,1]], the list [4,2] represents the point with coordinate ? at 4 and y coordinate at 2, and so on for the other lists. Assume that all lists within points contain two numbers (that is, they have x, y coordinates). • List ??????...
In Python Create a function called ????. The function receives a "string" that represents a year...
In Python Create a function called ????. The function receives a "string" that represents a year (the variable with this "String" will be called uve) and a list containing "strings" representing bank accounts (call this list ????). • Each account is represented by 8 characters. The format of each account number is "** - ** - **", where the asterisks are replaced by numeric characters. o For example, “59-04-23”. • The two central characters of the "string" of each account...
IN PYTHON Create a function called biochild.  The function has as parameters the number m...
IN PYTHON Create a function called biochild.  The function has as parameters the number m and the lists biomother and biofather.  The biomother and biofather lists contain 0’s and 1’s.  For example: biomother = [1,0,0,1,0,1] and biofather = [1,1,1,0,0,1]  Both lists have the same length n.  The 0's and 1's represent bits of information (remember that a bit is 0 or 1).  The function has to generate a new list (child).  The child...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called...
Using Python create a script called create_notes_drs.py. In the file, define and call a function called main that does the following: Creates a directory called CyberSecurity-Notes in the current working directory Within the CyberSecurity-Notes directory, creates 24 sub-directories (sub-folders), called Week 1, Week 2, Week 3, and so on until up through Week 24 Within each week directory, create 3 sub-directories, called Day 1, Day 2, and Day 3 Bonus Challenge: Add a conditional statement to abort the script if...
Please solve questions in C++ ASAP!! thank you (a) Write a function in C++ called readNumbers()...
Please solve questions in C++ ASAP!! thank you (a) Write a function in C++ called readNumbers() to read data into an array from a file. Function should have the following parameters: (1) a reference to an ifstream object (2) the number of rows in the file (3) a pointer to an array of integers The function returns the number of values read into the array. It stops reading if it encounters a negative number or if the number of rows...
Python pls create a function called search_position. This function returns a list. team1 = {'Fiora': {'Top':...
Python pls create a function called search_position. This function returns a list. team1 = {'Fiora': {'Top': 1, 'Mid': 4, 'Bottom': 3},'Olaf': {'Top': 3, 'Mid': 2, 'Support': 4},'Yasuo': {'Mid': 2, 'Top': 5},'Shaco': {'Jungle': 4, 'Top': 2, 'Mid': 1}} def search_position(team1): returns [(5, [('Top', ['Yasuo'])]), (4, [('Mid', ['Fiora']), ('Support',['Olaf']), ('Jungle',['Shaco'])])   (3, [('Bottom', ['Fiora']), ('Top', ['Olaf'])]), (2, [('Mid', ['Olaf','Yasuo']), ('Top', ['Shaco'])]), (1, [('Mid', ['Shaco'])])]
Python pls create a function called search_position. This function returns a dictionary. team1 = {'Fiora': {'Top':...
Python pls create a function called search_position. This function returns a dictionary. team1 = {'Fiora': {'Top': 1, 'Mid': 4, 'Bottom': 3},'Olaf': {'Top': 3, 'Mid': 2, 'Support': 4},'Yasuo': {'Mid': 2, 'Top': 5},'Shaco': {'Jungle': 4, 'Top': 2, 'Mid': 1}} def search_position(team1): should return {'Top': {'Fiora': 1, 'Yasuo':5,'Olaf':3,'Shaco':}, 'Jungle': {'Shaco': 4}, 'Mid': {'Yasuo', 2, 'Fiora': 4,'Olaf':2}, 'Bottom': {'Fiora': 3}, 'Support': {'Olaf': 4}} *******IMPORTANT*************** The result should be alphabetical order.
PYTHON: This is the posted problem: General Instructions Create a function called DeterminePrice that will determine...
PYTHON: This is the posted problem: General Instructions Create a function called DeterminePrice that will determine the cost of purchased software. The price is of the software is $350 per license. However, when purchased in larger quantities a discount is given. For quantites less than 10 copies, there is no discount. For quantities greater than 10 and less than and including 20, a 10% discount is given. For quantities greater than 20 and less than and including 30, a discount...
Python Create a move function that is only defined in the base class called Objects. The...
Python Create a move function that is only defined in the base class called Objects. The move function will take two parameters x,y and will also return the updated x,y parameters.
'PYTHON' 1. Write a function called compute_discount which takes a float as the cost and a...
'PYTHON' 1. Write a function called compute_discount which takes a float as the cost and a Boolean value to indicate membership. If the customer is a member, give him/her a 10% discount. If the customer is not a member, she/he will not receive a discount. Give all customers a 5% discount, since it is Cyber Tuesday. Return the discounted cost. Do not prompt the user for input or print within the compute_discount function. Call the function from within main() and...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT