# Character Input Solution
name = input("Enter you name: ")
print("You name is: "+ name)
# Divisors Solutions
num = int(input("Enter the valid number: "))
divlst = []
for n in list(range(1,num+1)):
if num % n == 0:
divlst.append(n)
print(divlst)
# find even list
a = [1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
evenlst = []
for num in a:
if num % 2 == 0:
evenlst.append(num)
print("the new even list is", evenlst)
or
evenlst = [number for number in a if number % 2 == 0]
print("the new even list is", evenlst)
# fibonacci series
def fib(num):
n1 = 0
n2 = 1
count = 0
if num <= 0:
print("Pelase enter positive number")
elif num == 1:
print("fibanacci series upto :", num , ":", n1)
else:
print('fibanacci series upto :', num , "is :")
while count < num:
print( n1, end= " ")
n3 = n1 + n2
n1 = n2
n2 = n3
count += 1
fib(5)
or
def fibonacci(n):
fib_sequence = []
if n <= 0:
return fib_sequence
elif n == 1:
fib_sequence.append(0)
return fib_sequence
else:
fib_sequence = [0, 1]
while len(fib_sequence) < n:
next_num = fib_sequence[-1] + fib_sequence[-2]
fib_sequence.append(next_num)
return fib_sequence
# Example usage:
num_terms = 10
fib_sequence = fibonacci(num_terms)
print("Fibonacci sequence with", num_terms, "terms:", fib_sequence)
# print list having numbers less than 10
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
numlst = []
for num in a:
if num < 10:
numlst.append(num)
print(numlst)
or
>>> numlst = [num for num in a if num < 10]
>>> numlst
[1, 1, 2, 3, 5, 8]
# find common elements between two lists
a = [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
# first convert the list to set
a = set([1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89])
print(type(a))
b = set([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13])
print(type(b))
res = a.intersection(b)
print("common elements: ", res)
or
>>> a = set(a)
>>> a
{1, 2, 3, 34, 5, 8, 13, 21, 55, 89}
>>>
>>> b = set(b)
>>> b
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13}
>>>
>>> res = a.intersection(b)
>>> res
{1, 2, 3, 5, 8, 13}
# find max of three values
def max_3(a,b,c):
if (a>b) and (a>c):
return a
if (b>a) and (b>c):
return b
if (c>a) and (c>b):
return c
print("Max value is : ", max_3(7,3,9))
# find new list having 1st and last element
newlst = []
def test(lst):
newlst.append(lst[0])
newlst.append(lst[-1])
print(newlst)
lst = [1,2,3,4,5,6,7]
test(lst)
# find odd or even number
num = int(input("Enter the number "))
if num %2 == 0:
print(num, "is the even number")
else:
print( num, "is the odd number")
# find if element is present in given list
def find(ordered_list, element_to_find):
for element in ordered_list:
if element == element_to_find:
return True
return False
l = [1,2,3,4,5]
print(find(l,10))
or
>>> def find(num, lst):
... if num in lst:
... return True
... else:
... return False
...
>>> lst = [1,2,3,4,5]
>>> find(2,lst)
True
>>>
>>> find(10,lst)
False
>>>
# find if given string is palindrome
name = input("Enter the string: ")
if name[::] == name[::-1]:
print(name, "is a palindrome")
else:
print(name, "is not a palindrome")
# find if number is prime or not
num = int(input("Enter a number: "))
if num %2 != 0 or num == 1:
print(num , "is a prime number")
else:
print(num, "is not a prime number")
# find the sum of two numbers
a = input ("Enter the value of a : ")
b = input ("Enter the value of b : ")
## by default input takes a string
res = int(a) + int(b)
print("Final ans = ", res)
>>> def sum(a,b):
... return (a+b)
...
>>> sum(0.3,5)
5.3
# remove duplicate values.
lst = [1,1,2,3,4,5,4,2,10,15,5,6]
newlst = set(lst)
print(newlst)
# reverse the order
def rev(str):
str = input("Enter the sentence: ")
new = str[::-1]
print(new)
rev(str)
>>> def rev(str):
... str = input("Enter the input:" )
... newstr = str[::-1]
... print(newstr)
...
>>> rev("str")
Enter the input: Hello Nawraj How are you?
?uoy era woH jarwaN olleH
# How to plot graph
import pandas as pd
import matplotlib.pyplot as plt
df = pd.read_csv("studs.csv")
df.plot()
plt.show()
# square of all numbers
numlst = [1,2,3,4,5,6,7,8]
reslst=list(map(lambda x : x*x, numlst))
print(reslst)
>>> res = list(map(lambda x:x*x, numlst))
>>> res
[1, 4, 9, 16, 25, 36, 49, 64]
# find missing number in list
def missing_no(lst):
#print(range(lst[0],lst[-1]+1))
return sum(range(lst[0],lst[-1]+1)) -sum(lst)
lst = [1,2,3,5,6]
print(missing_no(lst))
# Verify perfect square number
import math
def is_perfect_square(n):
return math.sqrt(n).is_integer()
print(is_perfect_square(56))
# compute power of 2
import math
def power2(n):
return math.pow(2,n)
print(power2(9))
or
import math
def power2(n):
return math.pow(2,n)
print(power2(9))
or
def powerof2(num):
return ((num & (num - 1)) == 0) and (num != 0) ## bitwise calculation
print(powerof2(8))
import calendar
y = int(input("Input the year: "))
m = int(input("Input the month: "))
print(calendar.month(y,m))
# Write a Python program to convert month name to a number of days.
print("List of months: January, February, March, April, May, June, July, August, September, October, November, December")
month_name = input("Enter the month name: ")
if month_name == "February":
print("No of days: 28/29 days")
elif month_name in ("April", "June", "September", "November"):
print("No of days: 30 days")
elif month_name in ("January", "March", "May", "July", "August", "October", "December"):
print("No of days: 31 days")
else:
print("Wrong month name")
## Write a Python program to check a triangle is equilateral, isosceles or scalene
print("Input the lengths of the triangle")
x = input("x:")
y = input("y:")
z = input("z:")
if x == y == z:
print("equilateral triangle")
elif x != y != z:
print("scalene triangle")
else:
print("Isoceles triangle")
# Write a Python program to calculate the sum and average of n integer numbers(input from the user). Input 0 to finish.
print("Input some integers to calculate the sum and average. Input 0 for exit")
sum = 0
count = 0
lst = [1,3,4,5,9]
for n in lst:
sum += n
count += 1
if count == 0:
print("Input some numbers")
else:
print("Average and sum of numbers: ", sum/count, sum)
## Write a Python program to create the multiplication table (from 1 to 10) of a number
n = int(input("input the number to create multiplication table: "))
for i in range(1,11):
print(n, 'x', i, "=", n*i)
#remember
n = 5 ## type is int
n = "5" ## type is str
# Write a Python program to construct the following pattern, using a nested loop number
1
22
333
4444
55555
666666
7777777
88888888
999999999
for i in range(1,10):
print(str(i)*i)
# Write a Python script to concatenate following dictionaries to create a new one
dic = {}
dic1 = {1:10,2:20}
dic2 = {3:30,4:40}
dic3 = {5:50,6:60}
for d in (dic1, dic2, dic3):
dic.update(d)
print(dic)
# Write a Python program to find those numbers which are divisible by 7 and multiple of 5, between 1500 and 2700 (both included)
lst = []
for n in range(1500,2701):
if n%7 == 0 and n%5 == 0:
lst.append(n)
print(lst)
# Write a Python program to guess a number between 1 to 9.
# Note : User is prompted to enter a guess. If the user guesses wrong then the prompt appears again until the guess is correct, on successful guess, user will get a "Well guessed!" message, and the program will exit.
import random
target_num, guess_num = random.randint(1,10), 0
while target_num != guess_num:
guess_num = int(input('Gues a number between 1 and 9 until u get it right: '))
print('well guessed')
# Write a Python program to construct the following pattern, using a nested for loop.
*
* *
* * *
* * * *
* * * * *
* * * *
* * *
* *
*
n = 5
for i in range(5):
for j in range(i):
print('* ', end='')
print("")
for i in range(n,0,-1):
for j in range(i):
print("* ", end="")
print('')
# Write a Python program that accepts a word from the user and reverse it
word = input("Enter the word: ")
res = word[::-1]
print(res)
# Write a Python program to count the number of even and odd numbers from a series of numbers
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even_num = []
odd_num = []
for n in numbers:
if n%2 == 0:
even_num.append(n)
else:
odd_num.append(n)
print("Number of even numbers: ", len(even_num))
print("Number of odd numbers: ", len(odd_num))
#or
numbers = (1, 2, 3, 4, 5, 6, 7, 8, 9)
even_count = 0
odd_count = 0
for n in numbers:
if n%2 == 0:
even_count += 1
else:
odd_count += 1
print("Number of even numbers: ", even_count)
print("Number of odd numbers: ", odd_count)
or
even_num = len([n for n in numbers if n % 2 == 0])
or
even_num = len([n for n in numbers if n % 2 == 0])
odd_num = len([n for n in numbers if n % 2 != 0])
# Write a Python program that prints each item and its corresponding type from the following list
datalist = [1452, 11.23, 1+2j, True, 'w3resource', (0, -1), [5, 12], {"class":'V', "section":'A'}]
print(datalist)
for item in datalist:
print(item, type(item))
# Write a Python program that prints all the numbers from 0 to 6 except 3 and 6
lst = []
for i in range(0,7):
if i == 3 or i == 6:
continue
lst.append(i)
print(lst)
# Write a Python program to get the Fibonacci series between 0 to 50
x,y=0,1
while y<50: div="">50:>
def res(n1,n2):
lst = list(range(n1, n2+1))
res = map(lambda x: x*x, lst)
return res
print(list(res(1,30)))
or
def sqr_num(n1,n2):
print(y)
x,y = y,x+y
#or
def fib(num):
a,b = 0,1
for num in range(num):
if a < num:
yield a
a,b =b,a+b
print(list(fib(50)))
# Write a Python program which takes two digits m (row) and n (column) as input and generates a two-dimensional array. The element value in the i-th row and j-th column of the array should be i*j
row_num = int(input("Input number of rows: "))
col_num = int(input("Input number of columns: "))
multi_list = [[0 for col in range(col_num)] for row in range(row_num)]
for row in range(row_num):
for col in range(col_num):
multi_list[row][col]= row*col
print(multi_list)
#or
row = 2
column = 3
a = [[i*j for j in range(column)] for i in range(row)]
print(a)
# Write a Python program that accepts a string and calculate the number of digits and letters
data = "Python 3.2"
d=l=0
for i in data:
if i.isdigit():
d += 1
elif i.isalpha():
l += 1
else:
pass
print("letters: ", l)
print("digits: ", d)
# Write a Python program to check whether an alphabet is a vowel or consonant
char = input("Input the letter of the alphabet: ")
if char in ('a','e','i','o','u'):
print("%s is a vowel " % char)
else:
print("%s is a consonant " % char)
## add key to dictionary
dict1 = {0:10, 1:20}
dict1[2] = "30"
print(dict1)
# Write a Python script to check if a given key already exists in a dictionary
dict={1:"one",2:"two",3:"three"}
print(dict)
print(dict.keys())
print(dict.values())
key = input("Enter the value of key ")
for k in dict:
if k == key:
print("Entered key %s is already there", key)
else:
print("Entered key is not present")
# Write a Python program to iterate over dictionaries using for loops
d = {"blue" : 1, "green" : 2, "yellow" : 3}
for key,value in d.items():
print(key, value)
#Write a Python program to map two lists into a dictionary
keys = ['1','2','3','4','5','6']
values = ['one','two','three','four','five','six']
d = dict(zip(keys, values))
print(d)
# Write a Python function to find the Max of three numbers
def sum(n1,n2,n3):
if n1>n2 and n1>n3:
print("max number is", n1)
elif n2>n1 and n2> n3:
print("max number is", n2)
else:
print("max number is", n3)
sum(3,1,7)
# Write a Python function to sum all the numbers in a list
def sum(lst):
res = 0
for i in lst:
res += i
return res
lst = [1,2,3,4,5,-1]
print(sum(lst))
# Write a Python function to multiply all the numbers in a list
def mul(lst):
res = 1
for i in lst:
res = res*i
return res
lst = [8, 2, 3, -1, 7]
print(mul(lst))
#Write a Python program to reverse a string
def rev(str):
res = str[::-1]
return res
str = "1234abcd"
print(rev(str))
#Write a Python function to calculate the factorial of a number
def fac(n):
if n <= 0:
return 1
else:
res = n* fac(n-1)
return res
print("factorial is :", fac(4))
# Write a Python function to check whether a number is in a given range
def test_range(n):
if n in range(3,9):
print("%s is in range"%n)
else:
print("number is outside of range")
test_range(5)
# Write a Python function that accepts a string and calculate the number of upper case letters and lower case letters
def string_test(s):
d={"UPPER_CASE":0, "LOWER_CASE":0}
for c in s:
if c.isupper():
d["UPPER_CASE"] += 1
elif c.islower():
d["LOWER_CASE"] += 1
else:
pass
print("No of upper case chars: ", d["UPPER_CASE"])
print("NO of lower case chars:", d["LOWER_CASE"])
string_test('The quick Brown Fox')
## Write a Python function that takes a list and returns a new list with unique elements of the first list
def unique_list(lst):
x = []
for a in lst:
if a not in x:
x.append(a)
return x
lst = [1,2,3,3,4,4,5]
print(unique_list(lst))
or
def unique_list(lst):
return list(set(lst))
lst = [1,2,3,3,4,4,5]
print(unique_list(lst))
or
def unique_list(lst):
return list(set(lst))
lst = [1,2,3,3,4,4,5]
print(unique_list(lst))
# Write a Python program to print the even numbers from a given list
def print_even(l):
even_list = []
for i in l:
if i % 2 == 0:
even_list.append(i)
return even_list
l = [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(print_even(l))
or
def print_even(lst):
evenlst = []
for n in lst:
if n % 2 == 0:
evenlst.append(n)
print(evenlst)
lst = [1,2,3,4,5,6,7,8]
print_even(lst)
or
def print_even(lst):
evenlst = []
for n in lst:
if n % 2 == 0:
evenlst.append(n)
print(evenlst)
lst = [1,2,3,4,5,6,7,8]
print_even(lst)
## Write a Python program that accepts a hyphen-separated sequence of words as input and prints the words in a hyphen-separated sequence after sorting them alphabetically
def input_str(s):
lst = s.split('-')
lst.sort()
print('-'.join(lst))
input_str("green-red-yellow-black-white")
# Write a Python function to create and print a list where the values are square of numbers between 1 and 30 (both included)
def res(n1,n2):
lst = list(range(n1, n2+1))
res = map(lambda x: x*x, lst)
return res
print(list(res(1,30)))
or
def sqr_num(n1,n2):
res_list = []
for i in range(n1,n2+1):
res_list.append(i**2)
return res_list
print(sqr_num(1,30))
# Write a Python program to access a function inside a function
def test(a):
def add(b):
nonlocal a
a += 1
return a+b
return add
func = test(4)
print(func(4))
#Write a Python script to merge two Python dictionaries
d1 = {"a": "100", "b": "200"}
d2 = {"x": "4", "y": "500"}
d = d1.copy()
d.update(d2)
print(d)
print(d1.keys())
print(d1)
print(d1.values())
#Write a Python program to get the maximum and minimum value in a dictionary.
my_dict = {'x':500, 'y':5874, 'z': 560}
key_max = max(my_dict.keys(), key=(lambda k: my_dict[k]))
key_min = min(my_dict.keys(), key=(lambda k: my_dict[k]))
print('Maximum Value: ',my_dict[key_max])
print('Minimum Value: ',my_dict[key_min])
#or
values = my_dict.values()
print(values)
min = sorted(values)[0]
max = sorted(values)[-1]
print(min)
print(max)
# Write a Python program to multiply all the items in a dictionary
#import math
d = {'n1': 5,'n2': 2,'n3': 3}
#print(mul.dict.vlaues())
res = 1
for key in d:
res= res*d[key]
print(res)
#or
d = {'n1': 5,'n2': 2,'n3': 3}
print(d.values())
res = 1
for i in d.values():
res=res*i
print(res)
print(d.items())
# Write a Python program to check that a string contains only a certain set of characters (in this case a-z, A-Z and 0-9).
import re
def match(str):
charRe = re.compile(r'[^a-zA-Z0-9.]')
str = charRe.search(str)
return not bool(str)
print(match("ABCDEFabcdef123450"))
print(match("*&%@#!}{"))
# Write a Python program that matches a string that has an a followed by zero or more b's
import re
def text_match(text):
patterns = 'ab*?'
if re.search(patterns, text):
return "match found"
else:
return "match not found"
print(text_match("ac"))
print(text_match("abc"))
print(text_match("abbc"))
print(text_match("bc"))
print(text_match("ababab"))
#for a followed by one or more b's
import re
def text_match(text):
patterns = 'ab+?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("ab"))
print(text_match("abc"))
##Write a Python program that matches a string that has an a followed by zero or one 'b'.
import re
def text_match(text):
patterns = 'ab??'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("ab"))
print(text_match("abc"))
print(text_match("abbc"))
print(text_match("aabbc"))
print(text_match("a"))
# Write a Python program that matches a string that has an a followed by three 'b'
import re
def text_match(text):
patterns = 'ab{3}?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("abbb"))
print(text_match("aabbbbbc"))
#Write a Python program that matches a string that has an a followed by two to three 'b' -
import re
def text_match(text):
patterns = 'ab{2,3}?'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("ab"))
print(text_match("aabbbbbc"))
# Write a Python program to find sequences of lowercase letters joined with a underscore
import re
def text_match(text):
patterns = '^[a-z]+_[a-z]+$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("aab_cbbbc"))
print(text_match("aab_Abbbc"))
print(text_match("Aaab_abbbc"))
# Write a Python program to find sequences of one upper case letter followed by lower case -
import re
def text_match(text):
patterns = '^[A-Z][a-z]+$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("bc"))
print(text_match("Abbbc"))
print(text_match("aabSBbbc"))
## Write a Python program that matches a string that has an 'a' followed by anything, ending in 'b'
import re
def text_match(text):
patterns = 'a.*?b$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("aabbbbd"))
print(text_match("aabAbbbc"))
print(text_match("accddbbjjjb"))
## Write a Python program that matches a word at the beginning of a string
import re
def text_match(text):
patterns = '^\w+'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("The quick brown fox jumps over the lazy dog."))
print(text_match(" The quick brown fox jumps over the lazy dog."))
#Write a Python program that matches a word at end of string, with optional punctuation
import re
def text_match(text):
patterns = '\w+\S*$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("The quick brown fox jumps over the lazy dog."))
print(text_match("The quick brown fox jumps over the lazy dog. "))
print(text_match("The quick brown fox jumps over the lazy dog "))
# Write a Python program that matches a word containing 'z'
import re
def text_match(text):
patterns = '\w*z.\w*'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("The quick brown fox jumps over the lazy dog."))
print(text_match("Python Exercises."))
# Write a Python program that matches a word containing 'z', not start or end of the word. -
patterns = '\Bz\B'
##Write a Python program to match a string that contains only upper and lowercase letters, numbers, and underscores
import re
def text_match(text):
patterns = '^[a-zA-Z0-9_]*$'
if re.search(patterns, text):
return 'Found a match!'
else:
return('Not matched!')
print(text_match("The quick brown fox jumps over the lazy dog."))
print(text_match("Python_Exercises_1"))
## Write a Python program where a string will start with a specific number
import re
def match_num(string):
text = re.compile(r"^5")
if text.match(string):
return True
else:
return False
print(match_num('5-2345861'))
print(match_num('6-2345861'))
# Write a Python program to remove leading zeros from an IP address.
import re
ip = "216.08.094.196"
string = re.sub('\.[0]*', '.', ip)
print(string)
# Write a Python program to check for a number at the end of a string
import re
def end_num(string):
text = re.compile(r".*[0-9]$")
if text.match(string):
return True
else:
return False
print(end_num('abcdef'))
print(end_num('abcdef6'))
# Write Python program to search the numbers (0-9) of length between 1 to 3 in a given string.
import re
results = re.finditer(r"([0-9]{1,3})", "Exercises number 1, 12, 13, and 345 are important")
print("Number of length 1 to 3")
for n in results:
print(n.group(0))
# Write a Python program to find the substrings within a string
import re
text = 'Python exercises, PHP exercises, C# exercises'
pattern = 'exercises'
for match in re.findall(pattern, text):
print('Found "%s"' % match)
# Write a Python program to find the occurrence and position of the substrings within a string
import re
text = 'Python exercises, PHP exercises, C# exercises'
pattern = 'exercises'
for match in re.finditer(pattern, text):
s = match.start()
e = match.end()
print('Found "%s" at %d:%d' % (text[s:e], s, e))
# Write a Python program to replace whitespaces with an underscore and vice versa
import re
text = 'Python Exercises'
text =text.replace (" ", "_")
print(text)
text =text.replace ("_", " ")
print(text)
# Write a Python program to extract year, month and date from an url.
import re
def extract_date(url):
return re.findall(r'/(\d{4})/(\d{1,2})/(\d{1,2})/', url)
url1= "https://www.washingtonpost.com/news/football-insider/wp/2016/09/02/odell-beckhams-fame-rests-on-one-stupid-little-ball-josh-norman-tells-author/"
print(extract_date(url1))
# Write a Python program to convert a date of yyyy-mm-dd format to dd-mm-yyyy format
import re
def change_date_format(dt):
return re.sub(r'(\d{4})-(\d{1,2})-(\d{1,2})', '\3-\2-\1', dt)
dt1 = "2026-01-02"
print("Original date in YYY-MM-DD Format: ",dt1)
print("New date in DD-MM-YYYY Format: ",change_date_format(dt1))
# Write a Python program to match if two words from a list of words starting with letter 'P'.
import re
# Sample strings.
words = ["Python PHP", "Java JavaScript", "c c++"]
for w in words:
m = re.match("(P\w+)\W(P\w+)", w)
# Check for success
if m:
print(m.groups())
# Write a Python program to separate and print the numbers of a given string
import re
# Sample string.
text = "Ten 10, Twenty 20, Thirty 30"
result = re.split("\D+", text)
# Print results.
for element in result:
print(element)
# Write a Python program to find all words starting with 'a' or 'e' in a given string
import re
# Input.
text = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly."
#find all the words starting with ‘a’ or ‘e’
list = re.findall("[ae]\w+", text)
# Print result.
print(list)
# Write a Python program to separate and print the numbers and their position of a given string.
import re
# Input.
text = "The following example creates an ArrayList with a capacity of 50 elements. Four elements are then added to the ArrayList and the ArrayList is trimmed accordingly."
for m in re.finditer("\d+", text):
print(m.group(0))
print("Index position:", m.start())
# Write a Python program to abbreviate 'Road' as 'Rd.' in a given string
import re
street = '21 Ramkrishna Road'
print(re.sub('Road$', 'Rd.', street))
# Write a Python program to replace all occurrences of space, comma, or dot with a colon -
import re
text = 'Python Exercises, PHP exercises.'
print(re.sub("[ ,.]", ":", text))
#Write a Python program to find all five characters long word in a string
import re
text = 'The quick brown fox jumps over the lazy dog.'
print(re.findall(r"\b\w{5}\b", text))
#Write a Python program to find all three, four, five characters long words in a string.
import re
text = 'The quick brown fox jumps over the lazy dog.'
print(re.findall(r"\b\w{3,5}\b", text))
#Write a Python program to remove multiple spaces in a string
import re
text1 = 'Python Exercises'
print("Original string:",text1)
print("Without extra spaces:",re.sub(' +',' ',text1))
#Write a Python program to remove all whitespaces from a string
import re
text1 = ' Python Exercises '
print("Original string:",text1)
print("Without extra spaces:",re.sub(r'\s+', '',text1))
# Write a Python program to implement pow(x, n).
class py_solution:
def pow(self, x, n):
if not n:
return 1
if n > 1:
return eval("{}{}".format(x,"*{}".format(x)*(n-1)))
if n < 1:
return eval("1/({}{})".format(x, "*{}".format(x) * (-n - 1)))
print(py_solution().pow(2, -3));
print(py_solution().pow(3, 5));
print(py_solution().pow(100, 0));
# Write a Python class named Circle constructed by a radius and two methods which will compute the area and the perimeter of a circle
class Circle():
def __init__(self,r):
self.radius = r
def area(self):
return self.radius**2*3.14
def perimeter(self):
return 2*self.radius*3.14
NewCircle = Circle(8)
print(NewCircle.area())
print(NewCircle.perimeter())
#Write a Python program to remove duplicates from Dictionary
dict = {'one': 1, 'two': 2, 'three': 3, 'four': 1}
#print(dict)
#print(dict.items())
res = {}
for key,value in dict.items():
if value not in res.values():
res[key] = value
print(res)
## Write a Python program to check a dictionary is empty or not.
my_dict = {}
if not bool(my_dict):
print("Dictionary is empty")
else:
print("Dictionary is not empty")
##Write a Python program to combine two dictionary adding values for common keys
from collections import Counter
d1 = {'a': 100, 'b': 200, 'c':300}
d2 = {'a': 300, 'b': 200, 'd':400}
d = Counter(d1) + Counter(d2)
print(d)
#Write a Python program to print all unique values in a dictionary.
L = [{"V":"S001"}, {"V": "S002"}, {"VI": "S001"}, {"VI": "S005"}, {"VII":"S005"}, {"V":"S009"},{"VIII":"S007"}]
print("Original List: ",L)
u_value = set( val for dic in L for val in dic.values())
print("Unique Values: ",u_value)
#Write a Python program to sort a dictionary by key.
color_dict = {'red' : 1, 'blue': 2, 'orange': 3}
print(color_dict)
print(sorted(color_dict))
for key in sorted(color_dict):
print("%s : %s" % (key, color_dict[key]))
#Write a Python program to sum all the items in a dictionary.
dict = {'n1': 1, 'n2': 2, 'n3': 3}
print(sum(dict.values()))
##lst=[1,2,3,0,5,6,0]. shift all 0's to left using python
You can achieve this by iterating through the list and moving all the zeros to the left while maintaining the order of the non-zero elements. Here's a Python code to do that:
```python
def move_zeros_to_left(lst):
# Initialize an empty list to store the result
result = []
# Count the number of zeros in the list
zero_count = lst.count(0)
# Add zeros to the result list
for i in range(zero_count):
result.append(0)
# Add non-zero elements to the result list
for num in lst:
if num != 0:
result.append(num)
return result
# Test the function
lst = [1, 2, 3, 0, 5, 6, 0]
result = move_zeros_to_left(lst)
print(result)
```
Output:
```
[0, 0, 1, 2, 3, 5, 6]
```
This code first counts the number of zeros in the list, then adds zeros to the result list followed by non-zero elements from the original list. This ensures that all zeros are shifted to the left while maintaining the order of the non-zero elements.
My pleasure. I am glad you liked it. Happy coding !!
ReplyDelete