Showing posts with label reverse. Show all posts
Showing posts with label reverse. Show all posts

Sep 19, 2019

python reverse vs reversed

"""
reverse() modifies the list itself, whereas
reversed() returns an iterator ready to traverse the list in reversed order.
"""

#string reverse (best way for string reverse using slicing)
s = 'string'
print(s[::-1]) #gnirts
print(s) #string

#string reversed
rs = reversed(s)
print(''.join(rs)) #gnirts
print(s) #string

#reverse list
l = [1,2,3]
l.reverse()
print(l) #[3,2,1]

#reversed list
ll = reversed(l)
print(ll) #<list_reverseiterator object at 0x7fa572312790>
print(list(ll)) #[1,2,3]


Jan 26, 2019

Python reverse a string

Python reverse a string

ss = 'Hello World'
print ss[::-1] #dlroW olleH
print reversed(ss)
print ''.join(reversed(ss)) #dlroW olleH



O/P:
dlroW olleH 
<reversed object at 0x7f5813ce73d0> 
dlroW olleH




Jun 22, 2008

reverse keyword

#!F:\Perl\bin\perl -w
use strict;

my $a=9;
print "Before Reverse:\n", (1..$a);
print "\nAfter Reverse:\n", reverse (1 .. $a);

How to reverse hash or Lookup a hash by value instead of key

But remember keys are uniue but values are not, so before reversinf the
original array values should be unique, after reverse these values become
keys of reversed array. Otherwise things will not work out in ur way.
Anyways just give a try
# Eg: %hash = ( a => 10, b => 10, c => 10, d => 10);

Example1:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is good and easy to use but not tat much efficient in terms of space,
as it needs to keep a copy of the hash.

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);

%reverse = reverse %hash; # It will reverse the hash

print "\n Hash after reverse :", Dumper(\%reverse);
print "\n";


Example2:
#########
#!F:\Perl\bin\perl -w
use Data::Dumper;

# The following is sapce efficient

%hash = ( a => 10, b => 20, c => 30, d => 40);
print "\n Hash before reverse:", Dumper(\%hash);
while (($key, $value) = each %hash) {
$hash{$value} = $key;
}
print "\n Hash after reverse :", Dumper(\%hash);
print "\n";