Loading...
Please wait while we prepare your content
Please wait while we prepare your content
Solutions for Computer Science, Class 12, CBSE
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
Lists and tuples are similar sequence types in python, but they are distinct data types. Both are used to store collections of items, but they have different properties and use cases. Lists are mutable, meaning you can add, remove, or modify elements after the list is created. Tuples, on the other hand, are immutable, meaning once a tuple is created, its contents cannot be changed.
(b)
Both Assertion and Reason are true but Reason is not the correct explanation of Assertion.
Explanation
In Python, strings are immutable, meaning once they are created, their contents cannot be changed. Whenever we modify a string, python creates a new string object to hold the modified contents, leaving the original string unchanged. On the other hand, lists in python are mutable, meaning we can modify their contents after they have been created. When we modify a list, python does not create a new list object. Instead, it modifies the existing list object in place. Strings are sequences of characters, and each character in a string can be accessed by its index. Lists, on the other hand, can store any type of data, including integers, floats, strings.
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
In Python, strings are immutable, meaning once they are created, their contents cannot be changed. Whenever we modify a string, python creates a new string object to hold the modified contents, leaving the original string unchanged. On the other hand, lists in python are mutable, meaning we can modify their contents after they have been created. When we modify a list, python does not create a new list object. Instead, it modifies the existing list object in place.
(d)
Assertion is false but Reason is true.
Explanation
Dictionaries are indexed by keys and each key must be immutable and unique. However, the dictionary itself is mutable, meaning that we can add, remove, or modify key-value pairs within the dictionary without changing the identity of the dictionary object itself. Mutability refers to the ability to change a value in place without creating a new storage location for the changed value.
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
A dictionary is a unordered set of key : value pairs and are indexed by keys. The values of a dictionary can change but keys of dictionary cannot be changed because through them data is hashed. Hence dictionaries are mutable but keys are immutable and unique.
(a)
Both Assertion and Reason are true and Reason is the correct explanation of Assertion.
Explanation
Insertion sort is a sorting algorithm that builds a sorted list, one element at a time from the unsorted list by inserting the element at its correct position in sorted list. In Insertion sort, each successive element is picked and inserted at an appropriate position in the previously sorted array.
tuple
Reason — For creating a tuple, enclosing the elements inside parentheses is optional. Even if parentheses are omitted as shown here, still this statement will create a tuple.
del AL[2]
AL[2:3] = []
AL.remove(3)
Reason — del AL[2]
— The del
keyword deletes the element from the list AL
from index 2.AL[2:3]
= [] — The slicing of the list AL[2:3]
begins at index 2 and ends at index 2. Therefore, the element at index 2 will be replaced by an empty list [].AL.remove(3)
— The remove()
function removes an element from the list AL
from index 3."
'1' + 2
Reason — The + operator has to have both operands of the same type either of number type (for addition) or of string type (for concatenation). It cannot work with one operand as string and one as a number.
Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'}
Reason — The syntax of dictionary declaration is:
<dictionary-name> = {<key>:<value>, <key>:<value>}
According this syntax, Day = {1:'Monday', 2:'Tuesday', 3:'wednesday'} is the correct answer.
False
Reason — Lists are ordered sequences. In the above two lists, even though the elements are same, they are at different indexes (i.e., different order). Hence, they are two different lists.
False
Reason — The + operator has to have both operands of the same type either of number type (for addition) or both of string type (for concatenation). It cannot work with one operand as string and one as a number.
True
Reason — The clear() method removes all items from the dictionary and the dictionary becomes empty dictionary post this method. del statement removes the complete dictionary as an object.
False
Reason — In Python, a list of characters and a string type are not similar. Strings are immutable sequences of characters, while lists are mutable sequences that can contain various data types. Lists have specific methods and behaviors that differ from strings, such as append(), extend(), pop() etc.
True
Reason — s[:n] — The slicing of a string starts from index 0 and ends at index n-1.
s[n:] — The slicing of a string starts from index n and continues until the end of the string.
So when we concatenate these two substrings we get original string s.
Strings in python are stored as individual characters in contiguous memory locations, with two-way index for each location. The index (also called subscript) is the numbered position of a letter in the string. Indices begin 0 onwards in the forward direction up to length-1 and -1,-2, .... up to -length in the backward direction. This is called two-way indexing.
A list is a standard data type of python that can store a sequence of values belonging to any type. Lists are mutable i.e., we can change elements of a list in place. Their dynamic nature allows for flexible manipulation, including appending, inserting, removing, and slicing elements. Lists offer significant utility in data storage, iteration, and manipulation tasks.
Mutability means that the value of an object can be updated by directly changing the contents of the memory location where the object is stored. There is no need to create another copy of the object in a new memory location with the updated values. Examples of mutable objects in python include lists, dictionaries.
In python, "in place" tasks refer to operations that modify an object directly without creating a new object or allocating additional memory. For example, list methods like append(), extend(), and pop() perform operations in place, modifying the original list, while string methods like replace() do not modify the original string in place but instead create a new string with the desired changes.
listA = [8, 9, 10]
a[x:y] returns a slice of the sequence from index x to y - 1. So, a[1 : 1] will return an empty list irrespective of whether the list has two elements or less as a slice from index 1 to index 0 is an invalid range.
The two methods to add something to a list are:
append method — The syntax of append method is list.append(item)
.
extend method — The syntax of extend method is list.extend(<list>)
.
Difference
The difference between the append() and extend() methods in python is that append() adds one element at the end of a list, while extend() can add multiple elements, given in the form of a list, to a list.
Example
append method:
lst1 = [10, 12, 14]
lst1.append(16)
print(lst1)
Output — [10, 12, 14, 16]
extend method:
t1 = ['a', 'b', 'c']
t2 = ['d', 'e']
t1.extend(t2)
print(t1)
Output — ['a', 'b', 'c', 'd', 'e']
The two ways to remove something from a list are:
pop method — The syntax of pop method is List.pop(<index>)
.
del statement — The syntax of del statement is
del list[<index>] # to remove element at index
del list[<start>:<stop>] # to remove elements in list slice
Difference
The difference between the pop() and del is that pop() method is used to remove single item from the list, not list slices whereas del statement is used to remove an individual item, or to remove all items identified by a slice.
Example
pop() method:
t1 = ['k', 'a', 'e', 'i', 'p', 'q', 'u']
ele1 = t1.pop(0)
print(ele1)
Output — 'k'
del statement:
lst = [1, 2, 3, 4, 5]
del lst[2:4]
print(lst)
Output — [1, 2, 5]
List | Tuple |
---|---|
Lists are mutable sequences of Python i.e., we can change elements of a list in place. | Tuples are immutable sequences of Python i.e., we cannot change elements of a tuple in place. |
The syntax to create list is <list-name> = [value,.....] | The syntax to create tuple is <tuple-name> = (value, ....) |
Lists cannot be used as keys in dictionary. | Tuples can be used as keys in dictionary. |
Lists cannot be used as elements of a set. | Tuples can be used as elements of a set. |
Lists are slower compared to tuples. | Tuples are faster compared to lists. |
In the Python shell, do the following :
Tuples are used to store multiple items in a single variable. It is a collection which is ordered and immutable i.e., the elements of the tuple can't be changed in place. Tuples are useful when values to be stored are constant and need to be accessed quickly.
If a is (1, 2, 3)
Answer
What is the difference between (30) and (30,) ?
Answer
a = (30) ⇒ It will be treated as an integer expression, hence a stores an integer 30, not a tuple.
a = (30,) ⇒ It is considered as single element tuple since a comma is added after the element to convert it into a tuple.
A dictionary is termed as an unordered collection of objects because the elements in a dictionary are not stored in any particular order. Unlike string, list and tuple, a dictionary is not a sequence. For a dictionary, the printed order of elements is not the same as the order in which the elements are stored.
For a tuple to be used as a key in a dictionary, all its elements must be immutable as well. If a tuple contains mutable elements, such as lists, sets, or other dictionaries, it cannot be used as a key in a dictionary.
Yes, we can modify the contents of a dictionary.
Values of key-value pairs are modifiable in dictionary. New key-value pairs can also be added to an existing dictionary and existing key-value pairs can be removed.
However, the keys of the dictionary cannot be changed. Instead we can add a new key : value pair with the desired key and delete the previous one.
For example:
d = { 1 : 1 }
d[2] = 2
print(d)
d[1] = 3
print(d)
d[3] = 2
print(d)
del d[2]
print(d)
{1: 1, 2: 2}
{1: 3, 2: 2}
{1: 3, 2: 2, 3: 2}
{1: 3, 3: 2}
d is a dictionary which contains one key-value pair.d[2] = 2
adds new key-value pair to d.d[1] = 3
modifies value of key 1
from 1 to 3.d[3] = 2
adds new key-value pair to d.del d[2]
deletes the key 2
and its corresponding value.
del D
deletes the entire dictionary D. After executing del D
, the variable D is no longer defined, and any attempt to access D
will result in a NameError
.del D[<key>]
deletes the key-value pair associated with the specified key from the dictionary D
. After executing del D[<key>]
, the dictionary D
still exists, but the specified key and its corresponding value are removed from the dictionary.
For example:
d = {1: 'a' , 2 : 'b'}
del d[2]
print(d)
del d
print(d)
{1:'a'}
NameError: name 'd' is not defined.
D = {'a' : 1, 'b' : 2, 'c' : 3}
D['d'] = 'spam'
D = {'a' : 1, 'b' : 2, 'c' : 3, 'd' : 'spam'}
Sorting refers to arranging elements of a sequence in a specific order — ascending or descending.
Sorting Techniques are as follows :
Bubble Sort :
In Bubble sort, the adjoining values are compared and exchanged if they are not in proper order. This process is repeated until the entire array is sorted.
Insertion Sort :
Insertion sort is a sorting algorithm that builds a sorted list one element at a time from the unsorted list by inserting the element at its correct position in sorted list.
hellohellohello 123
10 helloworld
str(123) converts the number 123 to string and stores in y so y becomes "123". "hello" * 3 repeats "hello" 3 times and stores it in x so x becomes "hellohellohello".
"hello" + "world" concatenates both the strings so x becomes "helloworld". As "helloworld" contains 10 characters so len(x) returns 10.
h : e : l : l : o : t : o : : P : y : t : h : o : n : w : o : r : l : d :
The code concatenates three strings "hello", "to Python", and "world" into the variable x
. Then, it iterates over each character in x
using a for
loop. For each character, it assigns it to the variable y
and prints y
followed by a colon and space, all on the same line due to the end=" "
parameter.
he hello wor ld
w ll
llo wo or
print(x[:2], x[:-2], x[-2:])
—
x[:2] extracts the substring from the beginning of x up to index 1, resulting in "he".
x[:-2] extracts the substring from the beginning of x up to the third last character, resulting in "hello wor".
x[-2:] extracts the substring from the last two characters of x until the end, resulting in "ld".
Hence, output of this line becomes he hello wor ld
print(x[6], x[2:4])
—
x[6] retrieves the character at index 6, which is 'w'.
x[2:4] extracts the substring from index 2 up to index 3, resulting in "ll".
Hence, output of this line becomes w ll
print(x[2:-3], x[-4:-2])
—
x[2:-3] extracts the substring from index 2 up to the fourth last character, resulting in "llo wo".
x[-4:-2] extracts the substring from the fourth last character to the third last character, resulting in "or".
Hence, output of this line becomes llo wo or
word_list = eval(input("Enter a list of words: "))
total_length = 0
for word in word_list:
total_length += len(word)
average_length = total_length / len(word_list)
print("Average length of words:", average_length)
Enter a list of words: ["apple", "banana", "orange", "kiwi"]
Average length of words: 5.25
word_list
.word_list
using for
loop. Inside the loop, length of each word gets added to total_length
variable.total_length
by the number of words in word_list
.[4, 3, 2]
The slicing notation a[start:stop:step]
extracts a portion of the list from index start
to stop-1
with a specified step. In the slicing part a[3:0:-1]
:
start
is 3, which corresponds to the element with value 4.stop
is 0, but as element at stop index is excluded so slicing goes up to index 1.step
is -1, indicating that we want to step backward through the list.Putting it together:
a[3:0:-1]
This extracts elements from index 3 to (0+1) in reverse order with a step of -1.
The output of the code will be:
[4, 3, 2]
234566
arr
is initialised as a list with elements [1, 2, 3, 4, 5, 6].for
loop iterates over the indices from 1 to 5. For each index i
, it assigns the value of arr[i]
to arr[i - 1]
, effectively shifting each element one position to the left. After this loop, the list arr
becomes [2, 3, 4, 5, 6, 6]
.arr
without newline characters because of end=""
parameter. Then it prints the elements of the modified list arr
, resulting in 234566
.
1 #
1 # 2 #
1 # 2 # 3 #
Numbers
is a list containing the numbers 9, 18, 27, and 36.Numbers
.t[0] = "H"
will raise an error because strings in python are immutable, meaning we cannot change individual characters in a string after it has been created. Therefore, attempting to assign a new value to t[0] will result in an error.
The errors in this code are:
[Amar, Shveta, Parag]
, each element should be enclosed in quotes because they are strings.There are two issue in range(len(words), 0, -1)
:
len(words)
is invalid for the list words
as it will have indexes from 0 to len(words) - 1
.The corrected python code is :
for i in range(len(words)-1, -1, -1):
print(words[i], end=' ')
a is: Hello
b is: Nita
c is: How's
d is: life ?
Hi Nita
ntpl is a tuple containing 4 elements. The statement (a, b, c, d) = ntpl
unpacks the tuple ntpl into the variables a, b, c, d. After that, the values of the variables are printed.
The statement ntpl = (a, b, c, d)
forms a tuple with values of variables a, b, c, d and assigns it to ntpl. As these variables were not modified, so effectively ntpl still contains the same values as in the first statement.
ntpl[0] ⇒ "Hello"
∴ ntpl[0][0] ⇒ "H"
ntpl[1] ⇒ "Nita"
∴ ntpl[1][1] ⇒"i"
ntpl[0][0]
and ntpl[1][1]
concatenates to form "Hi". Thus ntpl[0][0]+ntpl[1][1], ntpl[1]
will return "Hi Nita ".
True
Tuples can be declared with or without parentheses (parentheses are optional). Here, tuple_a is declared without parentheses where as tuple_b is declared with parentheses but both are identical. As both the tuples contain same values so the equality operator ( == ) returns true.
What will be the output of the following code snippet ?
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}
id1 = id(rec)
del rec
rec = {"Name" : "Python", "Age" : "20", "Addr" : "NJ", "Country" : "USA"}
id2 = id(rec)
print(id1 == id2)
True
In the given python code snippet, id1
and id2
will point to two different objects in memory as del rec
deleted the original dictionary whose id is stored in id1
and created a new dictionary with the same contents storing its id in id2
. However, id1 == id2
will compare the contents of the two dictionaries pointed to by id1
and id2
. As contents of both the dictionaries are same hence it returns True
. If in this code we add another line print(id1 is id2)
then this line will print False
as id1
and id2
point to two different dictionary objects in memory.
dict_items([('name', 'Aman'), ('age', 27), ('address', 'Delhi')])
A dictionary my_dict
with two key-value pairs, 'name': 'Aman' and 'age': 26 is initialized. Then updates the value associated with the key 'age' to 27. Then adds a new key-value pair 'address': 'Delhi' to the dictionary my_dict
. The items()
method returns all of the items in the dictionary as a sequence of (key, value) tuples. In this case, it will print [('name', 'Aman'), ('age', 27), ('address', 'Delhi')].
Write a method in python to display the elements of list thrice if it is a number and display the element terminated with '#' if it is not number.
For example, if the content of list is as follows :
List = ['41', 'DROND', 'GIRIRAJ', '13', 'ZARA']
The output should be
414141
DROND#
GIRIRAJ#
131313
ZAR#
def display(my_list):
for item in my_list:
if item.isdigit():
print(item * 3)
else:
print(item + '#')
display(my_list = eval(input("Enter the list :")))
Enter the elements of the list separated by spaces:41 DROND GIRIRAJ 13 ZARA
414141
DROND#
GIRIRAJ#
131313
ZARA#
my_list
.new_list
.isdigit()
method is used to check if all characters in the string are digits. If it's true (i.e., if the element consists only of digits), then it prints the element concatenated with itself three times. Otherwise, if the element contains non-digit characters, it prints the element concatenated with the character '#'.(i) isupper() method is used to check if a string contains only uppercase letters.
(ii) len() gives the total length of the list.
30
{(1, 2, 4): 8, (4, 2, 1): 10, (1, 2): 12}
my_dict
is initialized.my_dict[(1,2,4)] = 8, my_dict[(4,2,1)] = 10, my_dict[(1,2)] = 12
these lines assign values to the dictionary my_dict
with keys as tuples. Since tuples are immutable, so they can be used as keys in the dictionary.for
loop iterates over the keys of the dictionary my_dict
. Inside the loop, the value associated with each key k is added to the variable sum
.sum
and my_dict
are printed.Write a program that prompts for a phone number of 10 digits and two dashes, with dashes after the area code and the next three numbers. For example, 017-555-1212 is a legal input.
Display if the phone number entered is valid format or not and display if the phone number is valid or not (i.e., contains just the digits and dash at specific places).
phNo = input("Enter the phone number: ")
length = len(phNo)
if length == 12 \
and phNo[3] == "-" \
and phNo[7] == "-" \
and phNo[:3].isdigit() \
and phNo[4:7].isdigit() \
and phNo[8:].isdigit() :
print("Valid Phone Number")
else :
print("Invalid Phone Number")
Enter the phone number: 017-555-1212
Valid Phone Number
=====================================
Enter the phone number: 017-5A5-1212
Invalid Phone Number
Write a program that should prompt the user to type some sentence(s) followed by "enter". It should then print the original sentence(s) and the following statistics relating to the sentence(s):
Hints
str = input("Enter a few sentences: ")
length = len(str)
spaceCount = 0
alnumCount = 0
for ch in str :
if ch.isspace() :
spaceCount += 1
elif ch.isalnum() :
alnumCount += 1
alnumPercent = alnumCount / length * 100
print("Original Sentences:")
print(str)
print("Number of words =", (spaceCount + 1))
print("Number of characters =", (length))
print("Alphanumeric Percentage =", alnumPercent)
Enter a few sentences: Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its implementation began in December 1989. Python 3.0 was released on 3 December 2008.
Original Sentences:
Python was conceived in the late 1980s by Guido van Rossum at Centrum Wiskunde & Informatica (CWI) in the Netherlands. Its implementation began in December 1989. Python 3.0 was released on 3 December 2008.
Number of words = 34
Number of characters = 205
Alphanumeric Percentage = 80.48780487804879
Write a program that takes any two lists L and M of the same size and adds their elements together to form a new list N whose elements are sums of the corresponding elements in L and M. For instance, if L = [3, 1, 4] and M = [1, 5, 9], then N should equal [4, 6, 13].
print("Enter two lists of same size")
L = eval(input("Enter first list(L): "))
M = eval(input("Enter second list(M): "))
N = []
for i in range(len(L)):
N.append(L[i] + M[i])
print("List N:")
print(N)
Enter two lists of same size
Enter first list(L): [3, 1, 4]
Enter second list(M): [1, 5, 9]
List N:
[4, 6, 13]
Write a program that rotates the elements of a list so that the element at the first index moves to the second index, the element in the second index moves to the third index, etc., and the element in the last index moves to the first index.
l = eval(input("Enter the list: "))
print("Original List")
print(l)
l = l[-1:] + l[:-1]
print("Rotated List")
print(l)
Enter the list: [8, 10, 13, 25, 7, 11]
Original List
[8, 10, 13, 25, 7, 11]
Rotated List
[11, 8, 10, 13, 25, 7]
Write a short python code segment that prints the longest word in a list of words.
my_list = eval(input("Enter the list : "))
longest_word = ""
max_length = 0
for word in my_list:
if len(word) > max_length:
max_length = len(word)
longest_word = word
print("Longest word:", longest_word)
Enter the list : ['red', 'yellow', 'green', 'blue']
Longest word: yellow
Enter the list : ['lion', 'elephant', 'tiger', 'monkey', 'hippopotamus']
Longest word: hippopotamus
Write a program that creates a list of all the integers less than 100 that are multiples of 3 or 5.
a = []
for i in range(0,100):
if (i % 3 == 0) or (i % 5 == 0) :
a.append(i)
print(a)
[0, 3, 5, 6, 9, 10, 12, 15, 18, 20, 21, 24, 25, 27, 30, 33, 35, 36, 39, 40, 42, 45, 48, 50, 51, 54, 55, 57, 60, 63, 65, 66, 69, 70, 72, 75, 78, 80, 81, 84, 85, 87, 90, 93, 95, 96, 99]
Define two variables first and second so that first = "Jimmy" and second = "Johny". Write a short python code segment that swaps the values assigned to these two variables and prints the results.
first = "Jimmy"
second = "Johny"
temp = first
first = second
second = temp
print("first =", first)
print("second =", second)
first = Johny
second = Jimmy
Write a python program that creates a tuple storing first 9 terms of Fibonacci series.
lst = [0,1]
a = 0
b = 1
c = 0
for i in range(7):
c = a + b
a = b
b = c
lst.append(c)
tup = tuple(lst)
print("9 terms of Fibonacci series are:", tup)
9 terms of Fibonacci series are: (0, 1, 1, 2, 3, 5, 8, 13, 21)
Create a dictionary whose keys are month names and whose values are the number of days in the corresponding months.
(a) Ask the user to enter a month name and use the dictionary to tell them how many days are in the month.
(b) Print out all of the keys in alphabetical order.
(c) Print out all of the months with 31 days.
(d) Print out the (key-value) pairs sorted by the number of days in each month.
days_in_months = {
"january":31,
"february":28,
"march":31,
"april":30,
"may":31,
"june":30,
"july":31,
"august":31,
"september":30,
"october":31,
"november":30,
"december":31
}
m = input("Enter name of month: ")
if m not in days_in_months:
print("Please enter the correct month")
else:
print("There are", days_in_months[m], "days in", m)
print("Months in alphabetical order are:", sorted(days_in_months))
print("Months with 31 days:", end=" ")
for i in days_in_months:
if days_in_months[i] == 31:
print(i, end=" ")
day_month_lst = []
for i in days_in_months:
day_month_lst.append([days_in_months[i], i])
day_month_lst.sort()
month_day_lst =[]
for i in day_month_lst:
month_day_lst.append([i[1], i[0]])
sorted_days_in_months = dict(month_day_lst)
print()
print("Months sorted by days:", sorted_days_in_months)
Enter name of month: may
There are 31 days in may
Months in alphabetical order are: ['april', 'august', 'december', 'february', 'january', 'july', 'june', 'march', 'may', 'november', 'october', 'september']
Months with 31 days: january march may july august october december
Months sorted by days: {'february': 28, 'april': 30, 'june': 30, 'november': 30, 'september': 30, 'august': 31, 'december': 31, 'january': 31, 'july': 31, 'march': 31, 'may': 31, 'october': 31}
Write a function called addDict(dict1, dict2) which computes the union of two dictionaries. It should return a new dictionary, with all the items in both its arguments (assumed to be dictionaries). If the same key appears in both arguments, feel free to pick a value from either.
def addDict(dict1, dict2):
union_dict = {}
for key, value in dict1.items():
union_dict[key] = value
for key, value in dict2.items():
union_dict[key] = value
return union_dict
dict1 = {'a': 1, 'b': 2}
dict2 = {'b': 3, 'c': 4}
result = addDict(dict1, dict2)
print("Union of dict1 and dict2:", result)
Union of dict1 and dict2: {'a': 1, 'b': 3, 'c': 4}
Write a program to sort a dictionary's keys using Bubble sort and produce the sorted keys as a list.
my_dict = eval(input("Enter the dictionary: "))
keys = list(my_dict.keys())
l = len(keys)
for i in range(l):
for j in range(0, l - i - 1):
if keys[j] > keys[j + 1]:
keys[j], keys[j + 1] = keys[j + 1], keys[j]
print("Sorted keys:",keys)
Enter the dictionary: {'c':10, 'f':87, 'r':23, 'a':5}
Sorted keys: ['a', 'c', 'f', 'r']
Write a program to sort a dictionary's values using Bubble sort and produce the sorted values as a list.
my_dict = eval(input("Enter the dictionary: "))
values = list(my_dict.values())
l = len(values)
for i in range(l):
for j in range(0, l - i - 1):
if values[j] > values[j + 1]:
# Swap values
values[j], values[j + 1] = values[j + 1], values[j]
print("Sorted values:", values)
Enter the dictionary: {'w':34, 'a':5, 'g':45, 't':21}
Sorted values: [5, 21, 34, 45]