TYL - P3(Lists : remove even numbers, first and last 5, generate permutations, append a list, frequency in a list)

TYL P3 Lists (remove even numbers, first and last 5, generate permutations, append a list, frequency in a list)

4. Write a Python program to print the numbers of a specified list after removing even numbers from it.

This is a good program to practice list comprehension.

Without list comprehension:

1. def removeEven(t):
2.
3.    woeven=[]
4.    for e in t:
5.        if e%2!=0:
6.            woeven.append(e)

7.    t=woeven
8.    print("Without even numbers", t)

lst=[1,2,3,4,5,6,7,8]
lst2=[2,4,6,1]
removeEven(lst)
removeEven(lst2)

With list comprehension

lines 3 to 7 gets compressed to a single line

t=[e for e in t if e%2!=0]

Another alternate solution

If you wanted to remove items from the original list, we can make a copy of the original list, then remove the even numbers by using remove() function.
Remember that if you did lst=t, this would just create an alias.
The slice operator would return a new list that would effectively be a separate object copy of the original one.

def removeEven(t):

    lst = t[:]
    for e in lst:
        if e%2==0:
            t.remove(e)
         
    print("Without even numbers", t)

Output:

Without even numbers [1, 3, 5, 7]
Without even numbers []

5. Write a Python program to generate and print a list of first and last 5 elements where the values are square of numbers between 1 and 30 (both included).


First we generate the list and then print the values.
we need to generate from 1 to 30 both inclusive so we use range(1,31) so that 1 to 30 can be generated.
square of a number, i can be realized by either doing i*i or i**2.

This line, lst=[i*i for i in range(1,31)] is equivalent to
lst=[]
for i in range(1,31):
    lst.append(i*i)

For the first five items we need to display items in index position 0 to 4 hence using slicing on the list object, we do [:5], i.e., from the beginning to the element at index position 4.

For the last five items we can use the len() function to trace back on the list object [len(lst)-5:len(lst)]
or
we can just go backwards from the end using negative indices [-5:]

Program:


lst=[i*i for i in range(1,31)]
    print("The entire list",lst)
    print("First five:",lst[:5])
    print("Last five:",lst[-5:])

Output:

The entire list [1, 4, 9, 16, 25, 36, 49, 64, 81, 100, 121, 144, 169, 196, 225, 256, 289, 324, 361, 400, 441, 484, 529, 576, 625, 676, 729, 784, 841, 900]
First five: [1, 4, 9, 16, 25]
Last five: [676, 729, 784, 841, 900]

6. Write a Python program to generate all permutations of a list in Python.


The concept of generating is the same as for string. It is explained here:
https://py2020ps.blogspot.com/2020/03/5-questions-for-tyl-on.html

def permutation(a,n,k=0):

    if k == n-1:
        print(a)
        return;

    for i in range(k,n):
        a[k], a[i] = a[i],a[k]
        permutation(a,n,k+1)
        a[k], a[i] = a[i],a[k]

elements=['A','B','C']
permutation(elements,3)

Using itertools


pl = list(it.permutations(elements) returns a list of tuples.
[('A', 'B', 'C'), ('A', 'C', 'B'), ('B', 'A', 'C'), ('B', 'C', 'A'), ('C', 'A', 'B'), ('C', 'B', 'A')]
If you wanted a list of each permutation, you need to unpack a tuple in each iteration.  To do this,
we can either append it one by one to a list or convert it to a string and then to a tuple or convert it to a tuple back to a list.

 for a,b,c in pl:
        tup=(a,b,c)
        print(list (tup))

Program:


import itertools as it
elements=['A','B','C']

pl = list(it.permutations(elements))

for a,b,c in pl:
    print(list((a,b,c)))

7. Write a Python program to append a list to the second list.

The extend() function modifies a list and adds another list to it separately as elements.
In the following program, observe that t1 is an alias of lst1 and t2 is an alias of lst2.

Program:

def glue(t1, t2):
    t2.extend(t1)

lst1 = [4,5]
lst2 = [1,2,3]
glue(lst1,lst2)
print(lst2)

Output:

[1, 2, 3, 4, 5]


If you wanted a new list that will not modify the existing two lists, use the + operator.

def glue(t1, t2):
    t2 = t2 +t1
    return t2

lst1 = [4,5]
lst2 = [1,2,3]
gl = glue(lst1,lst2)

print(gl)

If you wanted to add an entire list as a whole, i.e. as an element to the second list, then you can use the append function.

>>> lst1=[4,5]
>>> lst2=[1,2,3]
>>> lst1.append(lst2)
>>> lst1
[4, 5, [1, 2, 3]]


8. Write a Python program to get the frequency of the elements in a list.


The way to do this is by using a dictionary, but without it, it can be done.
pop() removes the last element from a list
then we recursively remove the popped element from the list.
We do this until the list is empty.

Program:


def frequency(lst):

    while lst:
        el = lst.pop()
        count=1
        while el in lst:
            lst.remove(el)
            count+=1
            
        print(el,":",count)

Output:

lst = [1,3,2,1,1,2,3,3,2,2]
frequency(lst)
2 : 4
3 : 3
1 : 3

The dictionary implementation


This line, d[el]=d.get(el,0)+1 is the shorter form of writing

if el in d:
    d[el] + =1
else:
    d[el]=1


def freq_dict(lst):

    d=dict()
    for el in lst:
        d[el]=d.get(el,0)+1

    print(d)


Comments

Popular posts from this blog

TYL - Food Corner Program

Classes and objects solution

TYL - Salary Hike - Python Problem