Resolution of Hackerrank – Python exercises

This time I have completed the Easy difficulty exercises from Hackerranck Website:

Mod Divmod

from __future__ import division
a = int(raw_input())
b = int(raw_input())
print a//b
print a%b
print divmod(a,b)

Print Function

Read an integer N.

Without using any string methods, try to print the following:

1,2,3…..N

Note that “…..” represents the values in between.

from __future__ import print_function
n = int(raw_input())
for i in xrange(n):
  print (i+1,end="")

Lists

You have to initialize your list L = [] and follow the N commands given in N lines.

Each command will be 1 of the 8 commands given above. The method extend(L) will not be used. Each command will have its own value(s) separated by a space.

L = [] 
for i in range(int(raw_input())): 
     s = raw_input().split() 
     for i in range(1,len(s)): 
         s[i] = int(s[i]) 
     if s[0] == "append": 
           L.append(s[1]) 
     elif s[0] == "extend": 
           L.extend(s[1:]) 
     elif s[0] == "insert":  
           L.insert(s[1],s[2]) 
     elif s[0] == "remove": 
           L.remove(s[1]) 
     elif s[0] == "pop": 
           L.pop() 
     elif s[0] == "index": 
           print L.index(s[1]) 
     elif s[0] == "count": 
           print L.count(s[1]) 
     elif s[0] == "sort": 
           L.sort() 
     elif s[0] == "reverse": 
           L.reverse() 
     elif s[0] == "print": 
           print L

Interchange two numbers

#input of the elements of the tuple in a and then printing in You are given two integers. Store them into two variables and then exchange them. Rather than using any fancy logic, make sure to use a tuple to do the task. Print the two numbers.

a = (int(raw_input()), int(raw_input()))
print a[1]
print a[0]

Finding the percentage

You have a record of N students. Each record contains the student’s name, and their percent marks in Maths, Physics and Chemistry. The marks can be floating values. The user enters some integer N followed by the names and marks for N students. You are required to save the record in a dictionary data type. The user then enters a student’s name. Output the average percentage marks obtained by that student, correct to two decimal places.

N = int(raw_input())
record = {}
for i in range(0,N):
  student_info = raw_input()
name = student_info.split()
record[name[0]] = [float(name[1]),float(name[2]),float(name[3])]
find_name = raw_input()
if record.has_key(find_name):
    print "{0:.2f}".format(sum(record[find_name])/3.0)

Sets – Symmetric Difference

Let’s learn about a new datatype, sets. You are given 2 sets of integers M and N. You have to print their symmetric difference in ascending order. The term symmetric difference indicates those values that exist in either M or N but do not exist in both.

raw_input()
set_a = set(raw_input().split())
raw_input()
set_b = set(raw_input().split())

l = list(set_a.difference(set_b).union(set_b.difference(set_a)))
l = list(map(int, l))
l.sort()
for i in l:
  print i

List Comprehensions

Let’s learn about list comprehensions! You are given three integers X,Y and Z representing the dimensions of a cuboid. You have to print a list of all possible coordinates on a 3D grid where the sum of Xi + Yi + Zi is not equal to N. If X=2, the possible values of Xi can be 01 and 2. The same applies to Y and Z.

x = int(raw_input())
y = int(raw_input())
z = int(raw_input())
n = int(raw_input())

print [list([xx,yy,zz]) for xx in range(x+1) for yy in range(y+1) for zz in range(z+1) if xx+yy+zz !=n]

Find the Second Largest Number

N = raw_input()
if N >= 2 and N >= 10:
    A_s = raw_input()
    A = set([int(x) for x in A_s.split(" ")])
    if all( n >= -100 and n <= 100 for n in A):
        A.remove(max(A))
    print max(A)

Nested Lists

N = int(raw_input())
All = []
score = []
if N >=2 and N <=5:
 for i in range(N):
    All.append([raw_input(), float(raw_input())])
    score.append(All[i][1])
 firstLowest = []
 secondLowest = []
 for i in All:
    if i[1] == min(score):
       firstLowest.append(i)
 for x in firstLowest:
    del All[All.index(x)]
    del score[score.index(x[1])]
 for i in All:
    if i[1] == min(score):
       secondLowest.append(i)
 secondLowest.sort()
 for i in secondLowest:
    print i[0]

Tuples

N = int(raw_input())
T = raw_input()
T = T.split()
T = map(int,T)
print hash(tuple(T))

sWAP cASE

from __future__ import print_function
S = list(raw_input())
for s in S:
 if s == s.upper():
    print (s.lower(),end='')
 elif s == s.lower():
    print (s.upper(),end='')
 else:
    print (s,end='')

String Split and Join

words = raw_input()
words = words.split()
print "-".join(words)

Mutations

S = raw_input()
n = raw_input().split()
l = list(S)
l[int(n[0])] = n[1]
S = ''.join(l)
print S

Find a string

a = raw_input()
b = raw_input()
c =0
for i in range(len(a)):
  if a[i:].startswith(b):
     c += 1
print c

Text Wrap

import textwrap
S = raw_input()
w = int(raw_input())
print textwrap.fill(S,w)

Capitalize!

a=[word.capitalize() for word in raw_input().split(' ')]
print ' '.join(a)

String Validators

s = raw_input()
print any(c.isalnum() for c in s)
print any(c.isalpha() for c in s)
print any(c.isdigit() for c in s)
print any(c.islower() for c in s)
print any(c.isupper() for c in s)

Text Alignment

#Replace all ______ with rjust, ljust or center. 

thickness = int(raw_input()) #This must be an odd number
c = 'H'

#Top Cone
for i in range(thickness):
 print (c*i).rjust(thickness-1)+c+(c*i).ljust(thickness-1)

#Top Pillars
for i in range(thickness+1):
 print (c*thickness).center(thickness*2)+(c*thickness).center(thickness*6)

#Middle Belt
for i in range((thickness+1)/2):
 print (c*thickness*5).center(thickness*6) 

#Bottom Pillars
for i in range(thickness+1):
 print (c*thickness).center(thickness*2)+(c*thickness).center(thickness*6) 

#Bottom Cone
for i in range(thickness):
 print ((c*(thickness-i-1)).rjust(thickness)+c+(c*(thickness-i-1)).ljust(thickness)).rjust(thickness*6)

String Formatting

N = int(raw_input())
n = len(bin(N))-2
for i in range(1,N+1):
 print str(i).rjust(n) + " " + format(i,'o').rjust(n) + " " + format(i,'X').rjust(n) + " " + format(i,'b').rjust(n)

Introduction to Sets

N = int(raw_input())
L = set(map(int,raw_input().split()))
print float(sum(L)) / len(L)

Set .add()

L = set()
for i in range(int(raw_input())):
 L.add(raw_input())
print len(L)

Set .discard(), .remove() & .pop()

n = int(raw_input())
s = set(map(int,raw_input().split())) 
for i in range(0,int(raw_input())): 
  a = raw_input().split(" ")
  if a[0]=='pop':
     s.pop()
  elif a[0]=='discard':
     s.discard(int(a[1]))
  elif a[0]=='remove':
     s.remove(int(a[1]))
print sum(s)

Set .union() Operation

N = int(raw_input())
NL = set(raw_input().split())
M = int(raw_input())
ML = set(raw_input().split())
print len(NL.union(ML))

Set .intersection() Operation

N = int(raw_input())
N = set(raw_input().split())
M = int(raw_input())
M = set(raw_input().split())
print len(N.intersection(M))

Set .difference() Operation

N = int(raw_input())
N = set(raw_input().split())
M = int(raw_input())
M = set(raw_input().split())
print len(N.difference(M))

Set .symmetric_difference() Operation

N = int(raw_input())
NL = set(raw_input().split())
M = int(raw_input())
ML = set(raw_input().split())
print len(NL.symmetric_difference(ML))

The Minion Game

word = raw_input().upper()
vowels = 'AEIOU'
kevin = 0
stuart = 0
for i in range(len(word)):
 if word[i] in vowels:
 kevin += len(word) - i
 else:
 stuart += len(word) - i
if kevin > stuart:
 print "Kevin", kevin
elif stuart > kevin:
 print "Stuart", stuart
else:
 print "Draw"

Captain’ Room

n = int(raw_input())
nums = raw_input().split()
repeticiones = 0
nums.sort()
for i in range(len(nums)):
 if i + 1 < len(nums) and nums[i] == nums[i + 1]:
   repeticiones += 1
 elif repeticiones == 1:
   break
   repeticiones = 1
print(nums[i])

About Julita Inca

Ingeniero de Sistemas UNAC, Magíster en Ciencias de la Computación PUCP, OPW GNOME 2011, Miembro de la GNOME Foundation desde el 2012, Embajadora Fedora Perú desde el 2012, ganadora del scholarship of the Linux Foundation 2012, experiencia como Admin Linux en GMD y Especialista IT en IBM, con certificaciones RHCE, RHCSA, AIX 6.1, AIX 7 Administrator e ITILv3. Experiencia académica en universidades como PUCP, USIL y UNI. HPC researcher, a simple mortal, like you!
This entry was posted in τεχνολογια :: Technology. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s