Vous êtes sur la page 1sur 20

1-Define a function generate_n_chars() that takes an integer n and a

character c and returns a string, n characters long, consisting only of


c:s. For example, generate_n_chars(5,"x") should return the string
"xxxxx". (Python is unusual in that you can actually write an
expression 5 * "x" that will evaluate to "xxxxx". For the sake of the
exercise you should ignore that the problem can be solved in this
manner.)
>>> def generate_n_chars(a,b):

return a*b

>>> generate_n_chars(5,"y")

'yyyyy'
2-The function max() from exercise 1) and the function max_of_three()
from exercise 2) will only work for two and three numbers,
respectively. But suppose we have a much larger number of numbers,
or suppose we cannot tell in advance how many they are? Write a
function max_in_list() that takes a list of numbers and returns the
largest one.
>>> def max_in_list( list ):

max=list[0]

for i in list:

if i > max:

max = i

return max

>>> print(max_in_list([5,3,1,-6]))

5
3- Write a program that maps a list of words intoa list of integers representing the lengths of the
correponding words.
>>> def len_words(arr):

temp=[]

for i in arr:

temp.append(len(i))

return temp

>>> n=int(input("Enter the no. of entities: "))

Enter the no. of entities: 3

>>> arr=[(input())for i in range(n)]

Riya

Aparna

Isha

>>> print(arr)

['Riya', 'Aparna', 'Isha']

>>> print(len_words(arr))

[4, 6, 4]

>>>
4-Write a function find_longest_word() that takes a list of words and
returns the length of the longest one. Modify the same to do with
lambda expression.

>>> def find_longest_word(arr):

max=len(arr[0])

temp=arr[0]

for i in arr:

if (len(i)>max):

max=len(i)

temp=i

print(temp+",",max)

>>> n=int(input("Enter the no. of entities: "))

Enter the no. of entities: 3


>>> arr=[input()for i in range(n)]

Riya

Aparna

Isha

>>> find_longest_word(arr)

Aparna, 6
5- Write a function filter_long_words() that takes a list of words and an integer n and returns the
list of words that are longer than n. Modify the same to do with lambda expression.
>>> def filter_long_words(arr,a):

for i in range(0,len(arr)):

if (len(arr[i])>a):

print(arr[i])

>>> n=int(input("Enter the no. of entities: "))

Enter the no. of entities: 3

>>> arr=[input()for i in range(n)]

Riya

Riya Aparna

Riya Aparna Isha

>>> a=int(input("Enter the integer: "))

Enter the integer: 4

>>> filter_long_words(arr,a)

Riya Aparna

Riya Aparna Isha

>>>
6- Write a version of a palindrome recognizer that also accepts phrase palindromes such as
"Go hang a salami I'm a lasagna hog.", "Was it a rat I saw?", "Step on no pets", "Sit on a potato
pan, Otis", "Lisa Bonet ate no basil", "Satan, oscillate my metallic sonatas", "I roamed under it
as a tired nude Maori", "Rise to vote sir", or the exclamation "Dammit, I'mmad!". Note that
punctuation, capitalization, and spacing are usually ignored.
>>> def palindrome(str):

l=0

h=len(str)-1

s=str.lower()

while(l<=h):

if (not(s[l]>='a' and s[l]<='z')):

l += 1

elif (not(s[h]>='a' and s[h]<='z')):

h -= 1

elif (s[l]==s[h]):

l += 1

h -= 1

else:

return False

return True

>>> str=input("Enter the string: ")

Enter the string: was it a rat I saw?

>>> if(palindrome(str)==True):

print("It is palindrome")

It is palindrome

>>>
7- A pangram is a sentence that contains all the letters of the English alphabet at least once, for
example: The quick brown fox jumps over the lazy dog. Your task here is to write a function to
check a sentence to see if it is a pangram or not.
>>> import string

>>> def pangram(str):

alpha="abcdefghijklmnopqrstuvwxyz"

for i in alpha:

if i not in str.lower():

return False

return True

>>> str=input("Enter the string: ")

Enter the string: The quick brown fox jumps over the lazy dog

>>> if(pangram(str)==True):

print("Yes,it is pangram")
Yes,it is pangram

>>>

8- Represent a small bilingual lexicon as a Python dictionary in the following fashion


{"merry":"god", "christmas":"jul", "and":"och", "happy":gott", "new":"nytt", "year":"år"} and use it
totranslate your Christmas cards from English into Swedish. That is, write a function translate()
that takes a list of English words and returns a list of Swedish words.
>>> my_dict={

"merry":"god",

"christmas":"jul",

"and":"och",

"and":"och",

"happy":"gott",

"new":"nytt",

"year":"ar"
}

>>> str="marry christmas and happy new year"

>>> for i in my_dict.keys():

if i in str:

str=str.replace(i,my_dict[i])

>>> print(str)

marry jul och gott nytt ar

>>>
9- Write a function char_freq() that takes a string and builds a frequency listing of thecharacters
contained in it. Represent the frequency listing as a Python dictionary. Try it with something
likechar_freq("abbabcbdbabdbdbabababcbcbab").
>>> def frequency(str):

freq={}

for i in str:

keys=freq.keys()

if i in keys:
freq[i] += 1

else:

freq[i] = 1

return freq

>>> str=input("Enter the string: ")

Enter the string: aabbaacccdeeddf

>>> print(frequency(str))

{'a': 4, 'b': 2, 'c': 3, 'd': 3, 'e': 2, 'f': 1}

>>>
12- Create a Date class, which represents the Date with its attributes. Write a UseDate class,
which makes use of the Date class to instantiate, and call methods on the object.
>>> class Date:

def __init__(self,hours,mins,sec):

self.hours=hours

self.mins=mins

self.sec=sec

def fulltime(self):

print(f"{self.hours}:{self.mins}:{self.sec}")

>>> class UseDate(Date):

pass

>>> d1=UseDate(4,32,22)

>>> d2=UseDate(8,27,44)

>>> print(d1.fulltime())

4:32:22

None

>>> print(d2.fulltime())

8:27:44

None

>>>
13- WAP to read data from one file and writes in second file.
>>> file1=open("riya.txt","r")

>>> print(file1.read())

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license()" for more information.

>>> MY NAME IS RIYA

>>> with open("riya.txt") as f:

with open("priya.txt","w") as f1:

for i in f:

f1.write(i)

95
73

19

>>> file2=open("priya.txt","r")

>>> print(file2.read())

Python 3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 22:45:29) [MSC v.1916 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license()" for more information.

>>> MY NAME IS RIYA

>>>
14- WAP which will display diffrenent function of mathand numpy library.

Numpy-
>>> import numpy

>>> arr = numpy.array([[1,2,3],[4,2,5]])

>>> print("Array is of type: ",type(arr))

Array is of type: <class 'numpy.ndarray'>

>>> print("No. of dimensions: ",arr.ndim)

No. of dimensions: 2

>>> print("Shape of array: ",arr.shape)

Shape of array: (2, 3)

>>> print("Size of array: ",arr.size)

Size of array: 6

>>> print("Array stores elements oftype: ",arr.dtype)

Array stores elements oftype: int32

>>>
MATH-
>>> import math

>>> print(math.pow(2,4))

16.0

>>> print(math.sqrt(100))

10.0

>>> print(math.ceil(4.5876))

>>> print(math.floor(4.5876))

Vous aimerez peut-être aussi