Last active
December 21, 2022 07:10
-
-
Save dineshTheCoder/d923fbff81ef1a523bad3c415f357947 to your computer and use it in GitHub Desktop.
TopGearPythonA1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Python Assignment | |
(Solved using Python 2.7) | |
======================================================================================================================== | |
1. Given a list, url = [www.annauniv.edu, www.google.com, www.ndtv.com, www.website.org, www.bis.org.in, www.rbi.org.in]; | |
Sort the list based on the top level domain (edu, com, org, in) using custom sorting | |
======================================================================================================================== | |
topDomainList=["edu","com","org","in"] | |
urlList = ["www.annauniv.edu", "www.google.com", "www.ndtv.com", "www.website.org", "www.bis.org.in", "www.rbi.org.in"] | |
def sortDomainNames(domainList,urlList): | |
tempDomainList = domainList | |
tempUrlList = urlList | |
sortedUrlList = [] | |
for i,v in enumerate(tempDomainList): | |
for i1,v1 in enumerate(tempUrlList): | |
if v1.endswith(v): | |
sortedUrlList.append(v1) | |
print sortedUrlList | |
sortDomainNames(topDomainList,urlList) | |
======================================================================================================================== | |
2. Given a list of strings, return the count of the number of strings where the string length is 2 or more and the first and last chars of the string are the same. | |
i. ['axa', 'xyz', 'gg', 'x', 'yyy'] | |
ii. ['x', 'cd', 'cnc', 'kk'] | |
iii. ['bab', 'ce', 'cba', 'syanora'] | |
======================================================================================================================== | |
list1=['axa', 'xyz', 'gg', 'x', 'yyy'] | |
list2=['x', 'cd', 'cnc', 'kk'] | |
list3=['bab', 'ce', 'cba', 'syanora'] | |
def specialStringCount(tlist): | |
sCount=0 | |
for ele in tlist: | |
if ( len(ele)>=2 ) and ( ele[0] == ele[-1] ): | |
sCount+=1 | |
return sCount | |
print specialStringCount(list1) | |
print specialStringCount(list2) | |
print specialStringCount(list3) | |
======================================================================================================================== | |
3. Given a list of strings, return a list with the strings in sorted order, except group all the strings that begin with 'x' first. e.g. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] yields | |
['xanadu', 'xyz', 'aardvark', 'apple', 'mix']. | |
Hint: this can be done by making 2 lists and sorting each of them before combining them. | |
i. ['bbb', 'ccc', 'axx', 'xzz', 'xaa'] | |
ii. ['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] | |
======================================================================================================================== | |
def customSort(lst): | |
tmpList=lst | |
Xlst=[];nonXlst=[] | |
for ele in tmpList: | |
if ele[0].lower() == "x" : | |
Xlst.append(ele) | |
else: | |
nonXlst.append(ele) | |
Xlst.sort(),nonXlst.sort() | |
return Xlst + nonXlst | |
#main program | |
lst1=['mix', 'xyz', 'apple', 'xanadu', 'aardvark'] | |
lst2=['bbb', 'ccc', 'axx', 'xzz', 'xaa'] | |
print lst1," is sorted as \n",customSort(lst1),"\n\n" | |
print lst2," is sorted as \n",customSort(lst2),"\n\n" | |
======================================================================================================================== | |
4. Given a list of non-empty tuples, return a list sorted in increasing order by the last element in each tuple. | |
e.g. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] yields [(2, 2), (1, 3), (3, 4, 5), (1, 7)] | |
Hint: use a custom key= function to extract the last element form each tuple. | |
i. [(1, 3), (3, 2), (2, 1)] | |
ii. [(1, 7), (1, 3), (3, 4, 5), (2, 2)] | |
======================================================================================================================== | |
def getLastEle(tup): | |
return tup[-1] | |
def customSort(lst): | |
tmplst=lst | |
tmplst.sort(key=getLastEle) | |
return tmplst | |
#main program | |
lst1=[(1, 7), (1, 3), (3, 4, 5), (2, 2)] | |
lst2=[(1, 3), (3, 2), (2, 1)] | |
print lst1,"\n is sorted as \n",customSort(lst1) | |
print "\n\n" | |
print lst2,"\n is sorted as \n",customSort(lst2) | |
======================================================================================================================== | |
5. Given a list of numbers, return a list where all adjacent == elements have been reduced to a single element, | |
so [1, 2, 2, 3] returns [1, 2, 3]. You may create a new list or modify the passed in list. | |
i. [1, 2, 2, 3], [2, 2, 3, 3, 3] | |
======================================================================================================================== | |
def lstWithNonSimilarAdjEle(lst): | |
index=0 | |
next=index+1 | |
tmplst=lst | |
l=len(tmplst) | |
finalLst=[] | |
maxI=len(tmplst)-1 | |
for i,v in enumerate(tmplst): | |
next=i+1 | |
if next>maxI: | |
finalLst.append(v) | |
break | |
if v != tmplst[next]: | |
finalLst.append(v) | |
return finalLst | |
lst=[2,3,4,3,3,3,2] | |
lst1=[1, 2, 2, 3] | |
lst2=[2, 2, 3, 3, 3] | |
print lst,"-->",lstWithNonSimilarAdjEle(lst),"\n\n" | |
print lst1,"-->",lstWithNonSimilarAdjEle(lst1),"\n\n" | |
print lst2,"-->",lstWithNonSimilarAdjEle(lst2),"\n\n" | |
======================================================================================================================== | |
6. Write a function to print the information in the dictionary(bookstore) in the given format | |
BOOKSTORE | |
'Learning XML', 'Erik T. Ray', '2003', '39.95' | |
'Everyday Italian', 'Giada De Laurent is', '2005', '30.00'] | |
'Harry Potter', 'J K. Rowling', '2005', '29.99'] | |
======================================================================================================================== | |
bookstore = {"New Arrivals":{"COOKING":["Everyday Italian","Giada De Laurentiis","2005","30.00"],"CHILDREN":["Harry Potter","J K.Rowling","2005","29.99"],"WEB":["Learning XML","Erik T. Ray","2003","39.95"]}} | |
print "\n\nBOOKSTORE\n\n" | |
for dic1 in bookstore.values(): | |
for lst in dic1.values(): | |
strn=str(lst) | |
strn=strn[1:len(strn)-1] | |
print strn | |
print "\n\n" | |
======================================================================================================================== | |
7. Given a string, | |
a. Build a dictionary, with "words as key" --> Frequency of occurrence as value | |
E.g. Python 7, is 3 | |
b. Print the top 5 words with their frequency of occurrence | |
======================================================================================================================== | |
str1="""Python is a widely used high-level programming langauage for general-purpose prograaming, created by Guido van Rossum and first released in 1991. An interpreted language, Python has a design philosophy which emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly braces or keywords), and a syntax which allows programmers to concpets in fewer lines of code than possible languages such as C++ or Java. The language provides constructs inteneded to enable writing clear programs on both a small scale and a large scale. Python featues a dynamic type system and sutomatic memory management and supports multiple programming paradgms,including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library. Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython , the reference implementation of Python, is opne source software and has a community-based development model, as do nearly all of its variant implementations. CPython os managed by the non-profit Python Software Foundation.""" | |
wordCountTable={} | |
wordList=str1.split() | |
for word in wordList: | |
wordCountTable[word]=str1.count(word) | |
values=wordCountTable.values() | |
values.sort() | |
values.reverse() | |
topFive=values[0:5] | |
printCount=0 | |
print "\n\nTop Five words in the given string with their occurrences" | |
print "\n\n---------------------------" | |
print "word\t\tcount" | |
print "---------------------------" | |
for v in topFive: | |
for word in wordCountTable: | |
if wordCountTable[word] == v: | |
print word,"\t\t",wordCountTable[word] | |
printCount+=1 | |
if printCount==5: | |
break | |
if printCount==5: | |
break | |
print "\n\n\n" | |
======================================================================================================================== | |
8. Given a string, str1=""”Python is a widely used high-level programming language for general-purpose programming, created by Guido van Rossum and first released in 1991. An interpreted language, Python has a design philosophy which emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly braces or keywords), and a syntax which allows programmers to express concepts in fewer lines of code than possible in languages such as C++ or Java. The language provides constructs intended to enable writing clear programs on both a small and large scale .Python features a dynamic type system and automatic memory management and supports multiple programming paradigms, including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library. Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython, the reference implementation of Python, is open source software and has a community-based development model, as do nearly all of its variant implementations. CPython is managed by the non-profit Python Software Foundation.""" | |
Hint: Assume that the first word is preceded by " " | |
a. Build a dictionary where the key is a word and the value is the list of words that are likely to follow. | |
i. E.g. Python [is, has, features, interpreters, code, Software]. In this example the words listed are likely to follow “Python” | |
b. Given a word predict the word that’s likely to follow. | |
======================================================================================================================== | |
str1="Python is a widely used high-level programming langauage for general-purpose prograaming, created by Guido van Rossum and first released in 1991. An interpreted language, Python has a design philosophy which emphasizes code readability (notably using whitespace indentation to delimit code blocks rather than curly braces or keywords), and a syntax which allows programmers to concpets in fewer lines of code than possible languages such as C++ or Java. The language provides constructs inteneded to enable writing clear programs on both a small scale and a large scale. Python featues a dynamic type system and sutomatic memory management and supports multiple programming paradgms,including object-oriented, imperative, functional programming, and procedural styles. It has a large and comprehensive standard library. Python interpreters are available for many operating systems, allowing Python code to run on a wide variety of systems. CPython , the reference implementation of Python, is opne source software and has a community-based development model, as do nearly all of its variant implementations. CPython os managed by the non-profit Python Software Foundation." | |
str2="Python is Python are Python was Python not Python yes Python no Python awesome Python abcd" | |
def getDic(strn): | |
dic={} | |
wordList=strn.split() | |
length=len(wordList) | |
for index,word in enumerate(wordList): | |
if dic.has_key(word): | |
continue | |
tmpList=[] | |
for i in range(index,length): | |
if index==length-1: | |
break | |
if word==wordList[i]: | |
nextWord=wordList[i+1] | |
tmpList.append(nextWord) | |
#print word,tmpList | |
dic[word]=tmpList | |
return dic | |
def predict(strn,word): | |
wordDictionary=getDic(strn) | |
print "in the given string, the word ' ",word,"' is likely followed by the list of words",wordDictionary[word] | |
#call the function | |
predict(str1,"Python") | |
======================================================================================================================== | |
9. Below is the output of # show ip interface brief command on a router | |
Interface IP-Address OK? Method Status Protocol | |
FastEthernet0/0 192.168.1.242 YES manual up up | |
FastEthernet1/0 unassigned YES unset down | |
Serial2/0 192.168.1.250 YES manual up up | |
Serial3/0 192.168.1.233 YES manual up up | |
FastEthernet4/0 unassigned YES unset down | |
FastEthernet5/0 unassigned YES unset down | |
a. Use regular expressions to extract and display Interface and method status for all the interfaces. | |
i. E.g. FastEthernet0/0, manual up | |
======================================================================================================================== | |
import re | |
str1="""Interface IP-Address OK? Method Status Protocol | |
FastEthernet0/0 192.168.1.242 YES manual up up | |
FastEthernet1/0 unassigned YES unset down | |
Serial2/0 192.168.1.250 YES manual up up | |
Serial3/0 192.168.1.233 YES manual up up | |
FastEthernet4/0 unassigned YES unset down | |
FastEthernet5/0 unassigned YES unset down""" | |
print "\n\n\n" | |
for line in str1.splitlines(): | |
matchObj = re.match( r'(\w+\d\/\d)\s+[.0-9a-z]+\s+\w+\s+(\w+\s?\w+?)\s+\w+', line, re.M|re.I) | |
if matchObj: | |
print matchObj.group(1),",",matchObj.group(2),"\n" | |
print "\n\n\n" |
jayasree995
commented
Aug 13, 2020
- Given a number line from -infinity to +infinity. You start at 0 and can go either to the left or to the right. The condition is that in i’th move, you take i steps. In the first move take 1 step, second move 2 steps and so on.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment