Question

In: Computer Science

1.Suppose a dictionary Groceries maps items to quantities.     Write a python to print the names...

1.Suppose a dictionary Groceries maps items to quantities.

    Write a python to print the names of the grocery items whose quantity exceeds 400.

    For example, if groceries = {‘cake mixes’: 430, ‘cheese’:312, ‘Orange’:525, ‘candy bars’: 217}

   

    The output will be

                                Cake mixes

                                Orange

2. which Python string method would be the best choice to print the number of time “the” occurs in a sentence entered by the user?

Provide a one word answer. Just name the string method.

3. write a python statement that print a massage about a persons bonus which is based on the number of years (assume its stored in numYears) that they have worked for a company?

0-5 years = “1% of gross pay”

6-10 years = “2% of gross pay”

More than 10 years = “5% of gross pay”

4. write a python state to decrement the item in the fourth position in myList by 2.

     myList=[10,20,30,40,50]

5. write a python code to print the number of even numbers of integers divisible by 3

Example someList= [10, 11, 22, 16, 9, 15]

Output should be:

                                      Number of even: 3

                                    Number of items divisible by three: 2

6. write a python statement to decrease salary by 5% when sales in below 100

7. write a python function called isValideNumber: which accepts 3 paramters:

   a. number can be any integer

b. lowerLimit can be any integer

c. upperLimit can be any integer

description:

  1. check the number to see if it is between and/or including the range from lowerLimit to upperLimit
  2. return True if the number is in the specified range
  3. return False if the number is not within the specified range
  4. note: there should not be any print statement in the function.

8. which string method would be used to create a list of words from a sentence entered by the use.

Note: just provide a one-word answer, just the name of the method

9. suppose a dictionary called Inventory pairs fruit with the quantity of that fruit. Print the Total of the quantities of the item in the dictionary.

Solutions

Expert Solution

Answers:

1:

code:

groceries = {'cake mixes': 430, 'cheese':312, 'Orange':525, 'candy bars': 217}

# iterate through all the groceries using for loop

for key in groceries:

# print if it's value is greater than 400

if(groceries[key] > 400):

print(key)

screenshot of the code:

sample output:

2:

We can use count() method. It will find all the occurrences of a substring.

Example code:

string = "the string with more than one the. one more the"

sub_str = "the"

res = string.count(sub_str) # count the total number of ccurences

print(res) # print result

screenshot of code:

3.

code:

#Assume a dictonary with names and yearsof experience of employes.

persons_with_years = {"alex":1,"bob":6,"smith": 11, "andrew":2,"williams":7}


# we can calculate the bonus based on if conditions

for key in persons_with_years:

if (persons_with_years[key] >= 0 and persons_with_years[key] <=5 ):

print(key+" will get bonus of 1% of gross pay")

elif(persons_with_years[key] >= 6 and persons_with_years[key] <=10 ):

print(key+" will get bonus of 2% of gross pay")

else:

print(key+" will get bonus of 5% of gross pay")

screenshot of code:

4.

code:

myList=[10,20,30,40,50]

# index starts form 0 so decrease 1

pos_to_decrement = 4-1

value_to_decrement = 2

# Now decrement the value in a given positoin from list

myList[pos_to_decrement] = myList[pos_to_decrement] - value_to_decrement

print(myList)


screenshot of the code:

output:

we can see 4th value is decreased by 2 (40 to 38)

5.

code:

someList= [10, 11, 22, 16, 9, 15]

evenNums = []

# find the even numbers from given list and append to eveNumbers list

for num in someList:

if(num % 2 == 0):

evenNums.append(num)

divisibleBy3 =[]

# now find the elements which are divisible by 3

for num in someList:

if(num % 3 ==0):

divisibleBy3.append(num)

print("count of Even Numbers:", len(evenNums))

print("count of Numbers divisible by 3:", len(divisibleBy3))

screenshot of the code:

output:

6.

code:

#initialize the salary

salary = 1000

#initialize the sales

sales = 90


# check if the sales are lees than 100

if(sales < 100):

# if sales are less than 100 then decrease the salary

updatedSalary = salary - (salary * (5/100))

else:

updatedSalary = salary

print("original salary:",salary)

print("sales:",sales)

print("updated salary:",updatedSalary)

screenshot of the code:

sample output-1:

Here sales is less than 100 so salary is decreased

sample output-2:

Here sales is above 100 so salary is not decreased

7.

code:

# isValidNumber function with 3 parameters

def isValidNumber(number,lowerLimit,upperLimit):

# condition to check the number is in between the given range or not

if(number >= lowerLimit and number <= upperLimit):

# if condition is true return true

return True

else:

#else return false

return False


# call the above function with the required arguments and store result.

result = isValidNumber(5,1,10)

# print the result

print(result)

screenshot of the code:

sample Output:

8.

split() -- this method can be used to split the words as a list.

Ex: split(str)

9.

code:

#take a dictonary with fruits and it's quantity

fruitsDictonary = {"apple":10,"orange":5, "banana":8,"melon": 20}

# Initialize total Quantity to zero

totalQuantity = 0

# Iterate through all the fruits using for loop

for fruit in fruitsDictonary:

#add the quantity of the each fruit to totalQuantity.

totalQuantity = totalQuantity + fruitsDictonary[fruit]

#print the totalQuantity.

print("total Quantity:",totalQuantity)

screenshot of the code:

sample output:

I hope this answer is helpful,

Thank you.


Related Solutions

Write a python program that keeps names and email addresses in a dictionary as key-value pairs....
Write a python program that keeps names and email addresses in a dictionary as key-value pairs. The program should display a menu that lets the user look up a person’s email address, add a new name and email address, change an existing email address, and delete an existing name and email address. The program should bind the dictionary and save it to a file when the user exits the program. Each time the program starts, it should retrieve the dictionary...
*Python* 1.1) Create an empty dictionary called 'addresses'. The dictionary you just created will map names...
*Python* 1.1) Create an empty dictionary called 'addresses'. The dictionary you just created will map names to addresses. A person's name (stored as a string) will be the KEY and that person's address (stored as a string) will be the VALUE. 1.2) Insert into the dictionary 'addresses' the names and addresses of two (possibly imaginary) friends of yours. 1.3) Create a second empty dictionary called 'ages'. The dictionary you just created will map names to ages. A person's name (stored...
Short Python 3 questions a. Create a dictionary that maps the first n counting numbers to...
Short Python 3 questions a. Create a dictionary that maps the first n counting numbers to their squares. Assign the dictionary to the variable squares b. Given the list value_list, assign the number of nonduplicate values to the variable distinct_values
Why do items in a Python dictionary NOT stay in the order in which they are...
Why do items in a Python dictionary NOT stay in the order in which they are added? Put another way, how are the values indexed?
Use Python for this quetions: Write a python functions that use Dictionary to: 1) function name...
Use Python for this quetions: Write a python functions that use Dictionary to: 1) function name it addToDictionary(s,r) that take a string and add it to a dictionary if the string exist increment its frequenc 2) function named freq(s,r) that take a string and a record if the string not exist in the dictinary it return 0 if it exist it should return its frequancy.
Python create a function tryhard and print out the dictionary as a string form. For example...
Python create a function tryhard and print out the dictionary as a string form. For example def tryhard(d:dict): #Code here input: d = {'first': {}, 'second': {'1': {'move'}, '0': {'move', 'slow'}}, 'third': {'1': {'stop'}}} output = " first movie: [ ]\n third movie: [('1', ['stop'])]\n second movie: [('0', ['slow', 'move']), ('1', ['move'])]\n"
Design and implement a program in python that takes a list of items along with quantities...
Design and implement a program in python that takes a list of items along with quantities or weights. The program should include at least two function definition that is called within the main part of your program. Each item has a price associated by quantity or weight. The user enters the item along with the quantity or weight and the program prints out a table for each item along with the quantity/weight and total price. Your program should be able...
Initialize an empty hashtable, programmatically add 5 items (colors, names, fruits, etc.), use Write-Host to print...
Initialize an empty hashtable, programmatically add 5 items (colors, names, fruits, etc.), use Write-Host to print the keys and values separately, then remove one of the items and print the entire hashtable POWERSHELL PLEASE!
Write code to create a Python dictionary called class. Add two entries to the dictionary: Associate...
Write code to create a Python dictionary called class. Add two entries to the dictionary: Associate the key 'class_name' with the value 'MAT123', and associate the key 'sect_num' with '211_145'
Write a program in python to read from a file the names and grades of a...
Write a program in python to read from a file the names and grades of a class of students to calculate the class average, the maximum, and the minimum grades. The program should then write the names and grades on a new file identifying the students who passed and the students who failed. The program should consist of the following functions: a) Develop a getGrades() function that reads data from a file and stores it and returns it as a...
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT