Python Ass 2
Python Ass 2
1. Write a python script which accepts 5 integer values and prints “DUPLICATES” if any of the
values entered are duplicates otherwise it prints “ALL UNIQUE”. Example: Let 5 integers are
(32,
Solution:
print('Enter 6 numbers..')
a=list()
for i in range(6):
a.append(int(input('Enter:
')))
if len(set(a))!=len(a):
print('DUPLICATES.')
else:
print('Unique.')
2. Write a python script to count the number of characters (character frequency) in a string.
Sample
String : google.com'. Expected Result : {'o': 3, 'g': 2, '.': 1, 'e': 1, 'l': 1, 'm': 1, 'c': 1}
Sol:1
test_str = "google.com"
all_freq = {}
for i in test_str:
if i in all_freq:
all_freq[i] += 1
else:
all_freq[i] = 1
print("Count of all characters in GeeksforGeeks is :\n "
+ str(all_freq)
# printing result
print("Count of all characters in GeeksforGeeks is :\n
"+ str(res))
3. Write a Python program to remove the characters which have odd index values of a given
string.
def odd_values_string(str):
result = ""
for i in range(len(str)):
if i % 2 == 0:
result = result + str[i]
return result
print(odd_values_string('abcdef'))
print(odd_values_string('python'))
stack = []
print('Initial stack')
print(stack)
5. Write a Python program to get a string from a given string where all occurrences of its first
char have been changed to '$', except the first char itself. Sample String: 'restart'
Expected Result :
'resta$t'
def change_char(str1):
char = str1[0]
str1 = str1.replace(char, '$')
str1 = char + str1[1:]
return str1
print(change_char('restart'))
Set B
1. Write a Python program to get a string made of the first 2 and the last 2 chars from a given a string.
If the string length is less than 2, return instead of the empty string.
18
def string_both_ends(str):
if len(str) < 2:
return ''
return str[0:2] + str[-2:]
print(string_both_ends('General12'))
print(string_both_ends(''ka'))
print(string_both_ends('k'))
2. Write a Python program to get a single string from two given strings, separated by a space and
def word_count(str):
counts = dict()
words = str.split()
return counts
print( word_count('the quick brown fox jumps over the lazy dog.'))
Expected output:
o4
e3
u2
h2
r2
t2
count = 1;
count = count + 1;
print(string[i]);