Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
51 views

"Enter A Number:": Def If Return Else Return

The document contains Python code examples demonstrating various Python concepts like recursion, files, strings, lists, dictionaries, classes, inheritance, and multithreading. These include examples to find the factorial and Fibonacci sequence using recursion, reading and parsing text from files, sorting lists, calculating word counts in dictionaries, defining and overriding methods, using multithreading, and inheriting from parent classes.

Uploaded by

Aparna Pai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
51 views

"Enter A Number:": Def If Return Else Return

The document contains Python code examples demonstrating various Python concepts like recursion, files, strings, lists, dictionaries, classes, inheritance, and multithreading. These include examples to find the factorial and Fibonacci sequence using recursion, reading and parsing text from files, sorting lists, calculating word counts in dictionaries, defining and overriding methods, using multithreading, and inheriting from parent classes.

Uploaded by

Aparna Pai
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 5

In 

[5]: #factorial using recursion

def fact(n):

if (n == 0 or n == 1):

return 1

else:

return n * fact(n-1)

N = int(input("Enter a number:"))

print(fact(N))

Enter a number:6

720

In [6]: # fibonacci from another file

from fibonacci import fib

n = int(input("Enter a value for n:"))

result = fib(n)

print("nth fibonacci number :",result)

Enter a value for n:6

nth fibonacci number : 5

In [7]: # read from file and print unique words in sorted words

file = open("data.txt",'r')

rtext = file.read()

rtext = rtext.lower()

rwords = rtext.split()

rwords = [rwords.strip('.,!,(,),[,],?') for rwords in rwords]

unique = []

for rwords in rwords:

if rwords not in unique:

unique.append(rwords)

unique.sort()

print("\nThe sorted unique words are:")

print(unique)

The sorted unique words are:

['am', 'are', 'hello', 'how', 'hungry', 'i', 'yes', 'you']

In [8]: #polynomial solving

n = int (input ("Enter number of coefficients:"))

poly = []

for i in range (0, n) :

coefficient = int (input ("'Enter element " + str(i+1) + " : "))

poly.append (coefficient)

print ("Coefficients are:", poly)

x= int (input ("Enter a value for x : "))

result = 0

for i in range (n) :

sum = poly[i]

for j in range (n -i-1) :

sum = sum * x

result = result + sum

print (result)

Enter number of coefficients:4

'Enter element 1 : -2

'Enter element 2 : 6

'Enter element 3 : 2

'Enter element 4 : 1

Coefficients are: [-2, 6, 2, 1]

Enter a value for x : 2

13

In [1]: #sort list by length of elements

a = []

n = int (input ("Enter number of elements:"))

for i in range (0, n) :

b = input("Enter element " + str(i+1) + " : ")

a.append(b)

a.sort(key = len)

print(a)

Enter number of elements:4

Enter element 1 : hi

Enter element 2 : bye

Enter element 3 : hello

Enter element 4 : for

['hi', 'bye', 'for', 'hello']

In [4]: #print the longest word

a = []

n = int (input ("Enter number of elements:"))

for i in range (0, n) :

b = input("Enter element " + str(i+1) + " : ")

a.append(b)

max = len(a[0])

for x in a:

if len(x)>max :

max = len(x)

temp = x

print(temp)

Enter number of elements:4

Enter element 1 : hi

Enter element 2 : hello

Enter element 3 : why

Enter element 4 : bye

hello

In [12]: #function to find sum


def sum_of_digits(n):

sum = 0

while (n != 0):

sum = sum + n%10

n = n/10

return sum

In [14]: #perfect squares in a range with sum of digits < 10

l = int(input("Enter the lower limit:"))

u = int(input("Enter the upper limit:"))

a = []

a = [x for x in range(l,u+1) if (int(x**0.5))**2 == x and sum_of_digits(x) <= 10]

print(a)

Enter the lower limit:50

Enter the upper limit:100

[81, 100]

In [17]: #dictionary
test = input("Enter string:")

l = []

l = test.split()

words = [l.count(p) for p in l]

print(dict(zip(l,words)))

Enter string:Hello world Hello Hi

{'Hello': 2, 'world': 1, 'Hi': 1}

In [4]: #dictionary with key as 1st character and value as words starting with that character

string_input = '''BMSCE is a good university for computer enthusiasts.

The course structure is very well defined and explained in a systematic way.'''

words = string_input.split()

dictionary = {}

for word in words:

if word[0] not in dictionary.keys():

dictionary[word[0]] = []

dictionary[word[0]].append(word)

else:

if (word not in dictionary[word[0]]):

dictionary[word[0]].append(word)

print(dictionary)

{'B': ['BMSCE'], 'i': ['is', 'in'], 'a': ['a', 'and'], 'g': ['good'], 'u': ['universit
y'], 'f': ['for'], 'c': ['computer', 'course'], 'e': ['enthusiasts.', 'explained'], 'T':
['The'], 's': ['structure', 'systematic'], 'v': ['very'], 'w': ['well', 'way.'], 'd':
['defined']}

In [6]: #Binary Equivalent of a number

n = int(input("Enter a number:"))

a = []

while(n>0):

d = n%2

a.append(d)

n = n//2

a.reverse()

print("Binary Equivalent is:")

for i in a:

print(i,end="")

Enter a number:23

Binary Equivalent is:

10111

In [7]: #Capitalize first letter of every word

fname = input("Enter file name: ")

with open(fname, 'r') as f:

for line in f:

l=line.title()

print(l)

Enter file name: data.txt

Hello. How Are You? Are You Hungry? Yes I Am.

In [39]: #number of characters in a dictionary

str1 = input("Enter a String:")

dict1 = {}

for i in str1:

keys = dict1.keys()

if i in keys:

dict1[i]+=1

else:

dict1[i]=1

print (dict1)

Enter a String:Hello World

{'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'W': 1, 'r': 1, 'd': 1}

In [13]: #method overloading

def add(datatype, *args):

if datatype =='int':

answer = 0

if datatype =='str':

answer =''

for x in args:

answer = answer + x

print(answer)

add('int', 8, 9)

add('str', 'Hello ', 'World')

17

Hello World

In [14]: #method overridding

class Animal:

def walk(self):

print("Hello, I am the parent class")

class Dog(Animal):

def walk(self):

print("Hello, I am the child class")

print("The method walk here is overridden in the code")

r = Dog()

r.walk()

r = Animal()

r.walk()

The method walk here is overridden in the code

Hello, I am the child class

Hello, I am the parent class

In [19]: #Multithreading

import threading

def print_cube(num):

print("Cube: {}\n".format(num * num * num))

def print_square(num):

print("Square: {}\n".format(num * num))

if __name__ == "__main__":

t1 = threading.Thread(target=print_square, args=(6,))

t2 = threading.Thread(target=print_cube, args=(6,))

t1.start()

t2.start()

t1.join()

t2.join()

print("Done!")

Square: 36

Cube: 216

Done!

In [21]: #Inheritance

class Person(object):

def __init__(self, name, id):

self.name = name

self.id = id

print(self.name, self.id)

emp = Person("Kapilesh", 1234)

Kapilesh 1234

In [24]: #Number of characters,words and lines

def counter(fname):

num_words = 0

num_lines = 0

num_charc = 0

num_spaces = 0

with open(fname, 'r') as f:

for line in f:

num_lines += 1

word = 'Y'

for letter in line:

if (letter != ' ' and word == 'Y'):

num_words += 1

word = 'N'

elif (letter == ' '):

num_spaces += 1

word = 'Y'

for i in letter:

if(i !=" " and i !="\n"):

num_charc += 1

print("Number of words in text file: ", num_words)

print("Number of lines in text file: ", num_lines)

print('Number of characters in text file: ', num_charc)

print('Number of spaces in text file: ', num_spaces)

fname = input(("Enter a file:"))

counter(fname)

Enter a file:data.txt

Number of words in text file: 10

Number of lines in text file: 1

Number of characters in text file: 1

Number of spaces in text file: 9

In [38]: #Display each line in reverse order

f = input("Enter filename:")

file1 = open(f,"rt")

for line in file1.readlines():

for rev in line[::-1]:

print(rev,end = "")

Enter filename:sample.txt

hselipaK ma I

elif txeT ym si sihT

In [ ]:

You might also like