Showing posts with label python. Show all posts
Showing posts with label python. Show all posts

Sunday, January 29, 2017

Longest Word in a List

Question::

Write a function find_longest_word() that takes a list of words and returns the length of the longest one

Code::
def longest(l):
    long=0
    word=""
    for j in l:
        if(long<len(j)):
            long=len(j)
            word=j
    return [word,long]

n=input("Enter words:")
nt=n.split(",")
long=longest(nt)

print("Longest Word with length:",long)

Output::

Mapping Python

Question::
Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words.

Code::

def mapping(l):
    mapped=[]
    for j in l:
        mapped.append(len(j))
    return mapped

n=input("Enter words:")
nt=n.split(",")
mapped=mapping(nt)

print("Another List:",mapped)

Output::

Saturday, January 28, 2017

More Operations on datetime :)

Suppose we want to Display only current Month, Year or Day. Python allows us to do this through some predefined Functions.
Following Program Illustrates it:

from datetime import datetime
current=datetime.now(); #assigning variable
print(current.year);    #Current year
print(current.month);    #Current month
print(current.day);    #Current date




Functions for Time:

print(current.hour);    #Current Hour
print(current.minute);    #Current Minute
print(current.second);    #Current Second



Date and Time in Python :)

Python contains Library datetime which allows us to keep track of current Time and Date.
Following Program shows the usage of datetime Library:

from datetime import datetime  #importing datetime library
current=datetime.now();  #assigning variable to current date and time
print(current);



datetime.now() Function is used to get the current date and time.

Note: # keyword is used for Comments.

Common Elements In Two Lists

Question::
Define a function is_common() that takes two lists and returns True if they have at least one member in common, False otherwise.

Code::

def is_common(d,n):
    for i in d:
        for j in n:
             if(j==i):
              return True
    return False 
n=input("Enter list: ")
nt=n.split(",")    
d=input("Enter another list: ")
dm=d.split(",")
if(is_common(dm,nt)):
    print("Yes There are Common Elements")
else:
    print("No There are no Common Elements")
    

Output::




Searching value in a List

Question::

Write a function is_member() that takes a value (i.e. a number, string, etc) x and a list of values a, and returns True if x is a member of aFalse otherwise.

Code::
def is_member(d,n):
    for i in n:
        if(d==i):
            return True
    return False 
n=input("Enter list:")
nt=n.split(",")    
d=input("Enter Value to be searched:")
if(is_member(d,nt)):
    print("Yes it is Present")
else:

    print("No it is not Present")


Output::


String Palindrome or Not Python

Question::

Define a function reverse() that computes the reversal of a string. For example, reverse("I am testing") should return the string "gnitset ma I".

Code::
def reverse(l):
    return"".join(l[i] for i in range(len(l)-1,-1,-1)) 
name=input("Enter String:")
rev=reverse(name)
print("Reverse is:",rev)
if(rev==name):
    print("String is Palindrome")
else:

    print("Not a Palindrome")

Output::


Addition and Product of a List Python

Question::
Define a function sum() and a function multiply() that sums and multiplies (respectively) all the numbers in a list of numbers. For example, sum([1, 2, 3, 4]) should return 10, and multiply([1, 2, 3, 4]) should return 24.


Code::

def add(l):
    s=0
    for j in l:
        s=s+int(j)
    return s

def multiply(l):
    m=1
    for j in l:
        m=m*int(j)
    return m

d=input("Enter List: ")
n=d.split(",")
print("Entered List=",n)
print("Addition is:",add(n))
print("Product is:",multiply(n))


Output::


Friday, January 27, 2017

"Rövarspråket" (Swedish for "robber's language")

Question:: Write a function translate() that will translate a text into "rövarspråket" (Swedish for "robber's language"). That is, double every consonant and place an occurrence of "o" in between. For example, translate("this is fun") should return the string "tothohisos isos fofunon".


Code::
def translate(str):
    consonants='bcdfghjklmnpqrstvwxyz'
    print("".join(l+'o'+l if l in consonants else l for l in str))

string=input("Enter Any String: ")

translate(string)


Output::


Length of a String in Python

Following code is used to calculate length of a string using user defined length function :

Code::

def length(l):
    count=0
    for j in l:
        count=count+1
    return count
    
a=input("Enter String:")
c=length(a)
print("Length is :",c)

Output:


Greater of three Number in Python


Functions are defined in python using def keyword .Following will illustrate the concept.

Code::

def max(a,b,c):
    if(a>b and a>c):
        print ("Greater is :",a)
    elif(b>c and b>a):
        print("Greater is : ",b)
    else:
        print("Greater is :",c)
        
     
a=input("Enter First No:")
b=input("Enter Second no.:")
c=input("Enter Third no:")

max(a,b,c)


Output:



List and Tuple Datatype in Python

List and Tuple Both are datatypes in Python .These are similar to each other and used to store data of different types.But the only difference in list and tuple is that we can edit data in list but we can not edit data in tuple


For Example:

List =['76','23','25','85']

Tuple=('75','6','7')


Question:
Write a program which accepts a sequence of comma-separated numbers from console and generate a list and a tuple which contains every number.
Suppose the following input is supplied to the program:
34,67,55,33,12,98
Then, the output should be:
['34', '67', '55', '33', '12', '98']
('34', '67', '55', '33', '12', '98')



Code::

var=input("Enter Values Using Comma ',':")
n=var.split(",") # for constructing list from sequence
d=tuple(n)        # for constructing tuple

print ("List is :",n)
print ("Tuple is :",d)



Output:




Thursday, January 26, 2017

Dictionary datatype Python

Question:
With a given integral number n, write a program to generate a dictionary that contains (i, i*i) such that is an integral number between 1 and n (both included). and then the program should print the dictionary.

Suppose the following input is supplied to the program:
8
Then, the output should be:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64}


Code::


dict={}              #dict is of type dictionary
i=input("Enter any Number:")
for j in (range(1,i+1)):
 dict[j]=j*j
print(dict)


Output:


Factorial of a Number Python

Following Code will Calculate the factorial of a number :

Code::

fact=1
i=input("Enter Any Number:")
for j in (range(1,i+1)):                #range function for iteration from 1 to i+1
 fact=fact*j

print(fact)



Note:   Take care of the space in the code which leads to formation of blocks

Output: