Showing posts with label while loop. Show all posts
Showing posts with label while loop. Show all posts

Mar 29, 2020

Python Puzzle Remove even numbers

Python Puzzle Remove even numbers


# Wrong approach (incorrect - using For loop)
def removeEven(List):
    print(id(List)) # 139909029905664
    for each in List:
       i f each % 2 == 0:
          List.remove(each)


myList = [152, 168, 154, 32, -55, 81, 146, -34, -124, -9, 4, -31, -131, -86, -190, -38]
print(id(myList)) # 139909029905664
print(myList) # [1, 2, 4, 5, 10, 6, 3]
removeEven(myList)
print(myList) # [168, 32, -55, 81, -34, -9, -31, -131, -190]
# Wrong as when element gets deleted, index goes down

print('-' * 60)

# Correct approach (using While loop)
def removeEvenNew(List):
    print(id(List))
    i = 0
    while i < len(List):
      if List[i] % 2 == 0:
          List.remove(List[i])
      else:
          i += 1 


myList = [152, 168, 154, 32, -55, 81, 146, -34, -124, -9, 4, -31, -131, -86, -190, -38]
print(id(myList))
print(myList) # 
removeEvenNew(myList)
print(myList) # [-55, 81, -9, -31, -131]


Output:
140407115793920
[152, 168, 154, 32, -55, 81, 146, -34, -124, -9, 4, -31, -131, -86, -190, -38]
140407115793920
[168, 32, -55, 81, -34, -9, -31, -131, -190]
------------------------------------------------------------
140407114861888
[152, 168, 154, 32, -55, 81, 146, -34, -124, -9, 4, -31, -131, -86, -190, -38]
140407114861888
[-55, 81, -9, -31, -131]


Jul 2, 2018

Learning control flow statements in Python

#!/usr/local/bin/python2.7

'''
    #Learning control flow statements in Python
    File name: python_control_flow_statements.py
    Author: Prabhath Kota
    Date: June 29, 2018
    Python Version: 2.7
'''

'''
Sequential
Selection (Python Conditional Statements) 
if
if...else
if..elif..else statements
nested if statements
not operator in if statement
and operator in if statement
in operator in if statement
Repetetion
for loop
while loop
'''

print('-------------------Python if statements----------------')
x=20
y=10
if x > y :
  print("X is bigger")
#X is bigger

print('-------------------Python if...else statements----------------')
x=10
y=20
if x > y :
  print("X is bigger")
else :
  print("Y is bigger")
#Y is bigger

print('-------------------Python if...else...else statements----------------') 
x=500
if x > 500 :
  print("X is greater than 500")
elif x < 500 :
  print("X is less than 500")
elif x == 500 :
  print("X is 500")
else :
  print("X is not a number")
#X is 500

print('-------------------Python Nested if statements----------------') 
mark = 72
if mark > 50:
  if mark >= 80:
    print ("You got A Grade !!")
  elif mark >= 60 and mark < 80 :
    print ("You got B Grade !!")
  else:
    print ("You got C Grade !!")
else:
  print("You failed!!")
#You got B Grade !!

print('-------------------not operator in if statement----------------') 
mark = 100
if mark != 100: #mark != 100
  print("mark is not 100")
else:
  print("mark is 100")
#mark is 100

print('-------------------and operator in if statement----------------') 
mark = 72
if mark > 80:
  print ("You got A Grade !!")
elif mark >= 60 and mark < 80 :
  print ("You got B Grade !!")
elif mark >= 50 and mark < 60 :
  print ("You got C Grade !!")
else:
  print("You failed!!")
#You got B Grade !!

print('-------------------in operator in if statement----------------') 
color = ['Red','Blue','Green']
selColor = "Red"
if selColor in color:
  print("Red is in the list")
else:
  print("Not in the list")
#Red is in the list4

print '----------------For loop---------------------'
freedom_fighters = ["Lala Lajipati Rai", "Dadabhai Naoroji", "Rajendra Prasad", "Sarojini Naidu", "Dadabhai Naoroji", "Lal Bahadur Shastri"]
print freedom_fighters
for each in freedom_fighters:
print each

#['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
#Lala Lajipati Rai
#Dadabhai Naoroji
#Rajendra Prasad
#Sarojini Naidu
#Dadabhai Naoroji
#Lal Bahadur Shastri

print '----------------While loop---------------'
#Try to avoild While loops, use only unless otherwise reequired
#If you sometimes don't handle it, it may end up in infinite loop
i = 0
squares = []
while(i < 10):
squares.append(i**2)
i += 1
print squares
#[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

Jun 23, 2018

Learning For While loops in Python

#!/usr/local/bin/python2.7

'''
    Learning For/While loops in Python
    File name: for_while_loop_python.py
    Author: Prabhath Kota
    Date: June 22, 2018
    Python Version: 2.7
'''

'''
Topics:
For loop
While loop
range
break
continue
enumerate
'''

print '----------------For loop---------------------'
freedom_fighters = ["Lala Lajipati Rai", "Dadabhai Naoroji", "Rajendra Prasad", "Sarojini Naidu", "Dadabhai Naoroji", "Lal Bahadur Shastri"]
print freedom_fighters
for each in freedom_fighters:
print each

print '----------------For loop Break---------------------'
print freedom_fighters
#Print only first 4 elements using Break statement
#Enumerate will get you index of the element as well - starting from 0
#enumerate(freedom_fighters) will start the index from 0
#enumerate(freedom_fighters, 1) will start the index from 1
for index,each in enumerate(freedom_fighters, 1):
print index, each
if index == 4:
break
print '----------------For loop Continue---------------------'
print freedom_fighters
#Print only even elements from the list
for index,each in enumerate(freedom_fighters, 1):
if index % 2 == 1: #Odd elements
continue
else: #Even Elements
print index, each

print '----------------For loop Range---------------' 
squares = []
print range(1,10)
for x in range(0,10):
squares.append(x**2)
print (squares)

print '----------------While loop---------------'
#Try to avoild While loops, use only unless otherwise reequired
#If you sometimes don't handle it, it may end up in infinite loop
i = 0
squares = []
while(i < 10):
squares.append(i**2)
i += 1
print squares

Output:

----------------For loop---------------------
['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
Lala Lajipati Rai
Dadabhai Naoroji
Rajendra Prasad
Sarojini Naidu
Dadabhai Naoroji
Lal Bahadur Shastri
----------------For loop Break---------------------
['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
1 Lala Lajipati Rai
2 Dadabhai Naoroji
3 Rajendra Prasad
4 Sarojini Naidu
----------------For loop Continue---------------------
['Lala Lajipati Rai', 'Dadabhai Naoroji', 'Rajendra Prasad', 'Sarojini Naidu', 'Dadabhai Naoroji', 'Lal Bahadur Shastri']
2 Dadabhai Naoroji
4 Sarojini Naidu
6 Lal Bahadur Shastri
----------------For loop Range---------------
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
----------------While loop---------------
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
[Finished in 0.2s]

Jun 22, 2008

While loop in Perl

We can loop through For/Foreach/While in Perl.

We can discuss while loop now with the following example.



use strict;
use warnings;
use Data::Dumper;

my @names = ("Mother Teresa", "Abraham Lincoln", "Winston Churchill", "Mahathma Gandhi");

print "\n Looping While using counter";

my $i=0;

print "\n Scalar Array Size " . scalar(@names) . "\n";

while ($i <= $#names) {
   print "\n Looping ... " . $names[$i] . "\n";
   $i++;
}

print "\n";
  

Output :
 Looping While using counter
 Scalar Array Size 4

 Looping ... Mother Teresa

 Looping ... Abraham Lincoln

 Looping ... Winston Churchill

 Looping ... Mahathma Gandhi
 


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton


Hash in Perl

Hashes are like named key value pairs.
Keys are always unique, Values can be anything.
It's best practice to use hashes, they are efficient.

 

use strict;
use warnings;
use Data::Dumper;

my %hash = (a => 10,
            e => 40,
            c => 30,
            d => 40,
            b => 20,
            a => 100);

#Print Keys
print "\n Only Keys:\n" . Dumper(keys %hash);

print "\n\n";
#Print Values
print "\n Only Values:\n" . Dumper(values %hash);


print "\n\n";
#Print Keys and Values
while ( my ($key, $value) = each %hash)
{
   print "$key => $value\n";
}

print "\n\n";



#Print Keys
print "\n Sorted Keys:\n" . Dumper(sort keys %hash);

print "\n\n";
#Print Values
print "\n Sorted Values:\n" . Dumper(sort values %hash);
  
Output:

 Only Keys:
$VAR1 = 'e';
$VAR2 = 'c';
$VAR3 = 'a';
$VAR4 = 'b';
$VAR5 = 'd';



 Only Values:
$VAR1 = 40;
$VAR2 = 30;
$VAR3 = 100;
$VAR4 = 20;
$VAR5 = 40;


e => 40
c => 30
a => 100
b => 20
d => 40



 Sorted Keys:
$VAR1 = 'a';
$VAR2 = 'b';
$VAR3 = 'c';
$VAR4 = 'd';
$VAR5 = 'e';



 Sorted Values:
$VAR1 = 100;
$VAR2 = 20;
$VAR3 = 30;
$VAR4 = 40;
$VAR5 = 40;
  


Please refer to other topics in Perl like :
How to read command line arguments in Perl
How to pass command line arguments to perl script
Loop through Directory and read the files in Perl
How to create excel report in Perl


Please refer to other topics on Unix like :
Unix Delete Duplicated Lines in a File
Unix Unique Lines in a File
Unix Grep Examples
Unix Cut Command Examples
Search a Directory in Unix
Unix For Loop
pushd & popd in Unix
Find Size of Directory
Word Count


Please refer to other topics on AWK like :
Awk Examples
Print First Two Columns of File
Print Last Two Columns of File


Please refer to other topics on Dict like :
Dict in Python
Dict keys and values in Python


Please refer to other topics on List like :
List in Python
Append to list in Python
Delete the last name from the list in Python
Remove an element from List in Python
Check an element exists in an list in Python
Python Filter Vs Map Vs List Comprehension


Please refer to other topics on File Concepts like :
Print File Content in Python
Print File in Reverse Order in Python


Please refer to Regular Expressions Concepts :
Brief on Regular Expressions
Greedy Operators in Regular Expressions in Perl
Modifiers in Regular Expressions in Perl
Capturing concept in Regular Expressions in Perl
Capture Pre Match ,Post Match, Exact match in Regular Expressions in Perl
Non Capturing Paranthesis in Regular Expressions in Perl
Substitute nth occurance in Regular Expressions in Perl
All Topics in Regular Expressions in Perl


You might also wish to read other topics on Python like :
Python Class and Object Example
Inheritance in Python
Packages in Python
Exceptions in Python
How to remove duplicate lines from a file in Perl
How to remove duplicate lines from a file in Pyhton