JNTUK R16 UNIX AND SHELL PROGRAMMING UNIT 1 - 3

R16 UNIX AND SHELL PROGRAMMING UNIT 1 - 3


UNIT-1-------------------------------->Download

UNIT-2--------------------------------->Download

UNIT-3 PART-1---------------------->Download

UNIT-3 PART-2---------------------->Download

netaji gandi Wednesday, July 31, 2019
Understanding List Comprehensions in Python 3




Introduction
List comprehensions offer a succinct way to create lists based on existing lists. When using list comprehensions, lists can be built by leveraging any iterable, including strings and tuples.

Syntactically, list comprehensions consist of an iterable containing an expression followed by a for clause. This can be followed by additional for or if clauses, so familiarity with for loops and conditional statements will help you understand list comprehensions better.


List comprehensions provide an alternative syntax to creating lists and other sequential data types. While other methods of iteration, such as for loops, can also be used to create lists, list comprehensions may be preferred because they can limit the number of lines used in your program.

List Comprehensions

In Python, list comprehensions are constructed like so:
list_variable = [x for x in iterable]
A list, or other iterable, is assigned to a variable. Additional variables that stand for items within the iterable are constructed around a for clause. The in keyword is used as it is in for loops, to iterate over the iterable.
Let’s look at an example that creates a list based on a string:
netaji_letters = [letter for letter in 'netaji']
print(netaji_letters)
Here, the new list is assigned to the variable netaji_letters, and letter is used to stand in for the items contained in the iterable string 'netaji'.
For us to confirm what the new list netaji_letters looks like, we call for it to print() and receive the following output:
Output
['n', 'e', 't', 'a', 'j' , 'i']
The list we created with the list comprehension is comprised of the items in the string 'shark', that is, one string for each letter.
List comprehensions can be rewritten as for loops, though not every for loop is able to be rewritten as a list comprehension.
Using our list comprehension that created the shark_letters list above, let’s rewrite it as a forloop. This may help us better understand how the list comprehension works.
netaji_letters = []
for letter in 'netaji':
    netaji_letters.append(letter)
 
print(netaji_letters)
When creating a list with a for loop, the variable assigned to the list needs to be initialized with an empty list, as it is in the first line of our code block. The for loop then iterates over the item, using the variable letter in the iterable string 'netaji'. Within the for loop, each item within the string is added to the list with the list.append(x) method.
Rewriting the list comprehension as a for loop provides us with the same output:
Output
['n', 'e', 't', 'a', 'j', 'i']
List comprehensions can be rewritten as for loops, and some for loops can be rewritten to be list comprehensions to make code more succinct.

Using Conditionals with List Comprehensions

List comprehensions can utilize conditional statements to modify existing lists or other sequential data types when creating new lists.
Let’s look at an example of an if statement used in a list comprehension:
fish_tuple = ('blowfish', 'clownfish', 'catfish', 'octopus')
 
fish_list = [fish for fish in fish_tuple if fish != 'octopus']
print(fish_list)
The list comprehension uses the tuple fish_tuple as the basis for the new list called fish_list. The keywords of for and in are used, as they were in the section above, and now an ifstatement is added. The if statement says to only add those items that are not equivalent to the string 'octopus', so the new list only takes in items from the tuple that do not match 'octopus'.
When we run this, we’ll see that fish_list contains the same string items as fish_tuple except for the fact that the string 'octopus' has been omitted:
Output
['blowfish', 'clownfish', 'catfish']
Our new list therefore has every item of the original tuple except for the string that is excluded by the conditional statement.
We’ll create another example that uses mathematical operatorsintegers, and the range()sequence type.
number_list = [x ** 2 for x in range(10) if x % 2 == 0]
print(number_list)
The list that is being created, number_list, will be populated with the squared values of each item in the range from 0-9 if the item’s value is divisible by 2. The output is as follows:
Output
[0, 4, 16, 36, 64]
To break down what the list comprehension is doing a little more, let’s think about what would be printed out if we were just calling x for x in range(10). Our small program and output would then look like this:
number_list = [x for x in range(10)]
print(number_list)
Output
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Now, let’s add the conditional statement:
number_list = [x for x in range(10) if x % 2 == 0]
print(number_list)
Output
[0, 2, 4, 6, 8]
The if statement has limited the items in the final list to only include those items that are divisible by 2, omitting all of the odd numbers.
Finally, we can add the operator to have each x squared:
number_list = [x ** 2 for x in range(10) if x % 2 == 0]
print(number_list)
So each of the numbers in the previous list of [0, 2, 4, 6, 8] are now squared:
Output
[0, 4, 16, 36, 64]
You can also replicate nested if statements with a list comprehension:
number_list = [x for x in range(100) if x % 3 == 0 if x % 5 == 0]
print(number_list)
Here, the list comprehension will first check to see if the number x is divisible by 3, and then check to see if x is divisible by 5. If x satisfies both requirements it will print, and the output is:
Output
[0, 15, 30, 45, 60, 75, 90]
Conditional if statements can be used to control which items from an existing sequence are included in the creation of a new list.

Nested Loops in a List Comprehension

Nested loops can be used to perform multiple iterations in our programs.
This time, we’ll look at an existing nested for loop construction and work our way towards a list comprehension.
Our code will create a new list that iterates over 2 lists and performs mathematical operations based on them. Here is our nested for loop code block:
my_list = []
 for x in [20, 40, 60]:
    for y in [2, 4, 6]:
        my_list.append(x * y)
 
print(my_list)
When we run this code, we receive the following output:
Output
[40, 80, 120, 80, 160, 240, 120, 240, 360]
This code is multiplying the items in the first list by the items in the second list over each iteration.
To transform this into a list comprehension, we will condense each of the lines of code into one line, beginning with the x * y operation. This will be followed by the outer for loop, then the inner for loop. We’ll add a print() statement below our list comprehension to confirm that the new list matches the list we created with our nested for loop block above:
my_list = [x * y for x in [20, 40, 60] for y in [2, 4, 6]]
print(my_list)
Output
[40, 80, 120, 80, 160, 240, 120, 240, 360]
Our list comprehension takes the nested for loops and flattens them into one line of code while still creating the exact same list to assign to the my_list variable.
List comprehensions provide us with a succinct way of making lists, enabling us to distill several lines of code into a single line. However, it is worth keeping in mind that the readability of our code should always take precedence, so when a list comprehension line becomes too long or unwieldy, it may be best to break it out into loops.

Conclusion

List comprehensions allow us to transform one list or other sequence into a new list. They provide a concise syntax for completing this task, limiting our lines of code.
List comprehensions follow the mathematical form of set-builder notation or set comprehension, so they may be particularly intuitive to programmers with a mathematical background.
Though list comprehensions can make our code more succinct, it is important to ensure that our final code is as readable as possible, so very long single lines of code should be avoided to ensure that our code is user friendly.
·        





netaji gandi Tuesday, July 30, 2019
45 Best Websites Which Teaches About Programming, Web Development, Networking and More..

netaji gandi Monday, July 29, 2019
Python Programing Lab R16 EXERCISE - 7(b)

Python Programing Lab R16 EXERCISE - 7(b)

Aim:

Write a program to compute the number of characters, words and lines in a file.

Description:

Traverse each character in the file so that we can find number of characters, words and lines in a text file. Here, We are using the some of the basic methods of files.
We already discussed about open() and close() in the previous programs.
read():
If we need to extract string that contains all characters in the file, We can use read(). TheSyntax for read() in Python is:
str = file_object.read()
Program:

lines=0
words=0
chars=0
f=open('netaji.txt','r')
for line in f:
    wordslist=line.split()
    lines+=1
    words+=len(wordslist)
    chars+=len(line)
print("no.of characters",chars)
print("no.of words",words)
print("no.of lines",lines)

Output:


netaji gandi Friday, July 26, 2019
Python Programing Lab R16 EXERCISE - 7(a)

Python Programing Lab R16 EXERCISE - 7(a)


Aim:


      Write a program to print each line of a file in reverse order.


Description:


Traverse each line of the file and we have to display every line contents in reverse order. Here, We are using the some of the basic methods of files and a string method strip().

Python provides basic functions and methods necessary to manipulate files by default. We can do most of the file manipulations using a file object.

open():
Before we can read or write a file, we have to open it using Python‟s built-in open(). This function creates a file object, which would be utilized to call other support methods associated with it.

The Syntax for opening a file object in Python is:

file_object = open(“Name of the file”,”Mode of the file”)


close():
This method of a file object flushes any unwritten information and closes the file object. Python automatically closes a file when the reference object of a file is reassigned to another file.
The Syntax for closing a file object in Python is: 
file_object.close()
readlines():


This method will returns every line of the file as a list. The Syntax for readlines() in Python is:
           file_lines = file_object.readlines()
strip():

This method returns a copy of the string in which all chars have been stripped from the beginning and end of the string (default whitespace characters).
The Syntax for strip() is Python is: 
str.strip([chars])
Program:
f=open('netaji.txt','r').read()
#print(f)
print(f[::-1])
f=open('netaji.txt','r').readlines()
print(f)
print(f[::-1])

Output:



netaji gandi
Python Programing Lab R16 EXERCISE - 6(b)

Python Programing Lab R16 EXERCISE - 6(b)

Aim:


Write a program to count frequency of characters in a given file. Can you use character frequency to tell whether the given file is a Python program file, C program file or a text file?

Description:


Traverse each character in the file and its occurrence is stored in the dictionary. Here, We are using the concept of files and a Dictionary.

Files:
         Python provides basic functions and methods necessary to manipulate files by default. Some of the useful functions in this program are:

open():
Before we can read or write a file, we have to open it using Python‟s built-in open(). This function creates a file object, which would be utilized to call other support methods associated with it.

The Syntax for opening a file object in Python is:


file_object = open(“Name of the file”,”Mode of the file”)


read():
If we need to extract string that contains all characters in the file, We can use read(). 
TheSyntax for read() in Python is:


str = file_object.read()
Dictionary:


The dictionary is Python‟s built-in mapping type. Dictionaries map keys to values and these <key,value> pairs provides a useful way to store data in python. The only way to access the value part of the dictionary is by using the key.
We can specify the dictionary <key,value> pairs between '{' and '}'. <key,value> pairs arespecified as a list(separated by commas).

Program:

from collections import Counter
with open('netaji.txt','r') as f:
     c=Counter()
     for x in f:
         print(x)
         c+=Counter(x.strip())
print(c)

Output:



netaji gandi
Python Programing Lab (R16) EXERCISE - 6(a)

Python Programing Lab (R16)  EXERCISE - 6(a)

Aim:

Write a program combine_lists that combines these lists into a dictionary.

Description:

Python offers a range of compound data types often referred to as Sequences. List is one of the most frequently used and very versatile data type used in Python.

In Python Programming, a List is created by placing all the elements inside a square bracket [ ], separated by commas. It can have any number of items and they may be of different types.

Examples:

list1 = [10,20,30,40]

list2 = [“Ram”,19,87.81]

Similar to string indices, list indices starts at 0 and lists can be sliced, concatenated and so on..

Here, The task is to combine 2 lists into a dictionary. That means, One list elements will become the keys and another list elements will become the values in the resultant dictionary.

Program:

lists=list()
n=int(input("Enter no.of lists u want to combine"))
for i in range(0,n):
    a=input("Enter the value")
    lists.append(a)
for b in lists:
    print b
dic=dict([(digit,[]) for digit in lists[:]])
print(dic)

Output:


netaji gandi
Python Programing Lab (R16) EXERCISE - 5(b)

Python Programing Lab (R16) EXERCISE - 5(b)


Aim:

Write a program to use split and join methods in the string and trace a birthday with a dictionary data structure.

Description:

Compare the entered birthdate with each and every person‟s date of birth in the dictionary and check whether the entered birthdate is present in the dictionary or not. Here, We are using two built-in methods of the string: split() and join().

split():
This method breaks up a string using the specified separator and returns a list of strings. The general form of split() is as follows:

str.split(separator)

join():
This method provides a flexible way to concatenate a string. This method returns a string inwhich the string elements of a sequence have been joined by „sep‟ separator. The general form of join() is as follows:
sep.join(sequence)

Here, sequence is the sequence of elements to be joined.

Program:

pen='+'
pin=['H','E','L','L','O']
print("Joining")
print(pen.join(pin))
c=pen.join(pin)
print("Splitting")
print(c.split('+'))
people={
   'Netaji':{
       'birthday':'Aug 15'
    },
   'Manaswi':{
       'birthday':'Mar 21'
    },
   'Chandrika':{
       'birthday':'July 7'
    }
}
labels={
    'birthday':'birth date'
}
name=input("Name:")
request=input('birthday(b)?')
if request=='b':
   key='birthday'
if name in people:
   print("%s's %s is %s." % (name, labels[key], people[name][key]))

Output:


netaji gandi
Python Programing Lab(R16) EXERCISE - 5(a)

  Python Programing Lab EXERCISE - 5(a)


Aim:

Write a program to count the numbers of characters in the string and store them in a dictionary data structure.

Description:

Traverse each character in the string and its occurrence is stored in the dictionary. Here, We are using a String and a Dictionary.

String:
        A String is a sequence of characters. Strings can be created by enclosing characters inside a single quote or double quotes. Even triple quotes can be used in Python but generally used to represent multiline strings and docstrings.
        For reading strings in Python2.7, we are using raw_input(). This function reads a line from input(i.e., the user) and returns a string by stripping a trailing new line.

Dictionary:

            The dictionary is Python's built-in mapping type. Dictionaries map keys to values and these <key,value> pairs provides a useful way to store data in python. The only way to access the value part of the dictionary is by using the key.
                We can specify the dictionary <key,value> pairs between '{' and '}'. <key,value> pairs arespecified as a list(separated by commas).

Program:

s=input("Enter ur name: ")
#print(len(s)) as length index starts with 1
p=len(s)
count=0
for i in range(0,p):
    count=count+1
print(count)
dic=dict([(letter,[]) for letter in s[:]])
print(dic)

Output:


netaji gandi

NPTEL Programming in Java Jan 2024 Week 11

  Week 11 : Programming Assignment 1 Due on 2024-04-11, 23:59 IST The following code is missing some information needed to run the code. Add...