Python Program-Set 5(P41-P50)

Write a program to traverse a string.

Solution: 

str1= input('Enter a string\t:')

for i in str1:

print('Character \t:',i)

Write a program to find the length of the string entered by the user.

name=input('Enter your name\t');

length=0 for i in name:

length=length +1

print('The length of ',name,' is ',length)

Consider you have to enter a string and displace two characters to the right.How will you do it?

str1=input('Enter the string\t:')

i=0

str2=""

while i<len(str1):

str2[i]=str1[(i+2)%len(str1)]

print(str2)

Write a program to create a set of 5 randomly generated numbers in the range 10 to 30. Find how many of these numbers are less than 20. Delete all numbers which are greater than 25.
s = set()
while True:
 s.add(random.randint(10, 30))
 if len(s) == 5:
    break
print('set:', s)
t = set()
count = 0
for item in s:
if item < 20:
   count += 1
if item <= 25:
   t.add(item)

s = t
print('Count of nos. less than 20:', count)
print('Set after deleting elements > 25: ', s)
What is the difference between add() and update() functions in set?

We can use add() to add individual item to the Set,where as we can use update() function to add multiple items to Set.add() function can take only one argument where as update() function can take any number of arguments but all arguments should be iterable objects.

How will you use remove function in Python?
  • It removes specified element from the set.
  • If the specified element not present in the Set then we will get KeyError.
  • s={40,10,30,20} s.remove(60) print(s) —error
How will you use discard function in Python?
  • It removes the specified element from the set.
  • If the specified element not present in the set then we won’t get any error.
  • s={10,20,40} s.discard(10) print(s) ===>{20, 40} s.discard(50) print(s) ==>{20, 40}
A set contains names which begin either with A or with B. write a program to separate out the names into two sets, one containing names beginning with A and another containing names beginning with B.

# Split given set into two sets

lst = {‘Adi’, ‘Amit’, ‘Amar’, ‘Babu’, ‘cat’, ‘baba’, ‘baat’}

x = set()

y = set()

for item in lst:

  if item.startswith(‘A’):

     x.add(item)

  elif item.startswith(‘B’):

     y.add(item)

print(x)

print(y)

What is the difference between the two set functions— discard() and remove()
remove() raises an exception when the element which we are trying to remove is not present in the set, whereas, discard() doesn’.t.
How will you remove all duplicate elements present in a string

s = ‘vikas’
s = ”.join(sorted(set(s), key = s.index))

How will you remove all duplicate elements present in a list?

lst = list(sorted(set(lst), key = lst.index))