Nov 22, 2016

Nested Lists

Given the names and grades for each student in a Physics class of students, store them in a nested list and print the name(s) of any student(s) having the second lowest grade.
Note: If there are multiple students with the same grade, order their names alphabetically and print each name on a new line.
Input Format
The first line contains an integer, , the number of students.
The subsequent lines describe each student over lines; the first line contains a student's name, and the second line contains their grade.
Constraints
  • There will always be one or more students having the second lowest grade.
Output Format
Print the name(s) of any student(s) having the second lowest grade in Physics; if there are multiple students, order their names alphabetically and print each one on a new line.
Sample Input
5
Harry
37.21
Berry
37.21
Tina
37.2
Akriti
41
Harsh
39
Sample Output
Berry
Harry
Explanation
There are students in this class whose names and grades are assembled to build the following list:
students = [['Harry', 37.21], ['Berry', 37.21], ['Tina', 37.2], 
['Akriti', 41],['Harsh', 39]]
The lowest grade of belongs to Tina. The second lowest grade of belongs to both Harry and Berry, so we order their names alphabetically and print each name on a new line.

 Python code: 
inputsize=int(input())
students=[[input(),float(input())] for i in range(inputsize)]#for taking the input values
lnew=sorted(list(set([students[i][1] for i in range(inputsize)])),key=float)#for comparing float values
lnew1=sorted([students[i][0] for i in range(inputsize) if lnew[1]==students[i][1]])#list with names having second least score in sorted manner
for i in range(len(lnew1)):
    print(lnew1[i])

Nov 15, 2016

list comprehensions in python

List comprehensions in Python:
Let's learn about list comprehensions! You are given three integers and representing the dimensions of a cuboid along with an integer . You have to print a list of all possible coordinates given by on a 3D grid where the sum of is not equal to . Here,

Input Format

Four integers and each on four separate lines, respectively.

Constraints

Print the list in lexicographic increasing order.

Sample Input

1
1
1
2

Sample Output
[[0, 0, 0], [0, 0, 1], [0, 1, 0], [1, 0, 0], [1, 1, 1]]

Explanation

Concept

You have already used lists in previous hacks. List comprehensions are an elegant way to build a list without having to use different for loops to append values one by one. These examples might help.

The simplest form of a list comprehension is:

[ expression-involving-loop-variable for loop-variable in sequence ]

This will step over every element in a sequence, successively setting the loop-variable equal to every element one at a time. It will then build up a list by evaluating the expression-involving-loop-variable for each one. This eliminates the need to use lambda forms and generally produces a much more readable code than using map() and a more compact code than using a for loop.

>> ListOfNumbers = [ x for x in range(10) ] # List of integers from 0 to 9
>> ListOfNumbers
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

List comprehensions can be nested where they take the following form:

[ expression-involving-loop-variables for outer-loop-variable in outer-sequence for inner-loop-variable in inner-sequence ]

This is equivalent to writing:

results = []
for outer_loop_variable in outer_sequence:
    for inner_loop_variable in inner_sequence:
        results.append( expression_involving_loop_variables )


The final form of list comprehension involves creating a list and filtering it similar to using the filter() method. The filtering form of list comprehension takes the following form:

[ expression-involving-loop-variable for loop-variable in sequence if boolean-expression-involving-loop-variable ]

This form is similar to the simple form of list comprehension, but it evaluates boolean-expression-involving-loop-variable for every item. It also only keeps those members for which the boolean expression is True.

>> ListOfThreeMultiples = [x for x in range(10) if x % 3 == 0] # Multiples of 3 below 10
>> ListOfThreeMultiples
[0, 3, 6, 9]


PYTHON CODE:

X=int(input())
Y=int(input())
Z=int(input())
n=int(input())
ListOfNumbers =[]
ListOfNumbers = [[x,y,z] for x in range(0,X+1)for y in range(0,Y+1)for z in range(0,Z+1)if x+y+z!=n ]
print(ListOfNumbers)

Nov 11, 2016

Tuples

Tuples


Task
Given an integer, , and space-separated integers as input, create a tuple, , of those integers. Then compute and print the result of .
Note: hash() is one of the functions in the __builtins__ module, so it need not be imported.
Input Format
The first line contains an integer, , denoting the number of elements in the tuple.
The second line contains space-separated integers describing the elements in tuple .
Output Format
Print the result of .
Sample Input
2
1 2
Sample Output
3713081631934410656 
 
Solution:
inputvalue=int(input())
nlist=[]
mlist=[]
x=0
nlist=input().split()
while (x<inputvalue):
    mlist.insert(x,int(nlist[x]))
    x+=1;
contuple=tuple(mlist)
print(hash(contuple)) 

Lists

 Lists
 Consider a list (list = []). You can perform the following commands:
  1. insert i e: Insert integer at position .
  2. print: Print the list.
  3. remove e: Delete the first occurrence of integer .
  4. append e: Insert integer at the end of the list.
  5. sort: Sort the list.
  6. pop: Pop the last element from the list.
  7. reverse: Reverse the list.
Initialize your list and read in the value of followed by lines of commands where each command will be of the types listed above. Iterate through each command in order and perform the corresponding operation on your list.
Input Format
The first line contains an integer, , denoting the number of commands.
Each line of the subsequent lines contains one of the commands described above.
Constraints
  • The elements added to the list must be integers.
Output Format
For each command of type print, print the list on a new line.
Sample Input
12
insert 0 5
insert 1 10
insert 0 6
print 
remove 6
append 9
append 1
sort 
print
pop
reverse
print
Sample Output
[6, 5, 10]
[1, 5, 9, 10]
[9, 5, 1]
 
Solution: 
inputno=int(input())
newlist=[]
x=1
while (x<=inputno):
    temp=[]
    temp=input().split()
    if(temp[0]=="insert"):newlist.insert(int(temp[1]),int(temp[2]))
    if(temp[0]=="print"): print(newlist)
    if(temp[0]=="remove"):newlist.remove(int(temp[1]))
    if(temp[0]=="append"):newlist.append(int(temp[1]))
    if(temp[0]=="sort"):newlist.sort()
    if(temp[0]=="pop"):newlist.pop()
    if(temp[0]=="reverse"):newlist.reverse()
    x+=1; 

Nov 10, 2016

continue vs pass in python

    Python has two different statements that can be used in loops one is 'continue' and other is 'pass' statement.Most of the beginners get confused with this two thinking that these two are having the same functionality but actually there is a slight difference in between these two statements.Below is the example for each of the statement so that you can compare and learn.

Pass Statement:
     Below is the example of pass statement
  
for letter in 'Python':
   if letter == 'h':
      pass
      print ('This is pass block')
   print ('Current Letter :', letter)

print ("Good bye pass")
Output for the above pass statement code:
   
Current Letter : P
Current Letter : y
Current Letter : t
This is pass block
Current Letter : h
Current Letter : o
Current Letter : n
Good bye pass
 
 
Continue Statement:
     Below is the example of continue statement
  
for letter in 'Python':
   if letter == 'h':
      continue
      print ('This is pass block')
   print ('Current Letter :', letter)

print ("Good bye continue")
Output for the above Continue statement code:
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : o
Current Letter : n
Good bye continue

    -If you compare both of the example statements you can see that 'h' is not printed in continue statements whereas it is available in pass statement.

 

Nov 4, 2016

Write a function

We add a Leap Day on February 29, almost every four years. The leap day is an extra, or intercalary, day and we add it to the shortest month of the year, February.
In the Gregorian calendar three criteria must be taken into account to identify leap years:
  • The year can be evenly divided by 4;
  • If the year can be evenly divided by 100, it is NOT a leap year, unless;
  • The year is also evenly divisible by 400. Then it is a leap year.
This means that in the Gregorian calendar, the years 2000 and 2400 are leap years, while 1800, 1900, 2100, 2200, 2300 and 2500 are NOT leap years.Source
Task
You are given the year, and you have to write a function to check if the year is leap or not.
Note that you have to complete the function and remaining code is given as template.
Input Format
Read y, the year that needs to be checked.
Constraints
Output Format
Output is taken care of by the template. Your function must return a boolean value (True/False)
Sample Input
1990 
Sample Output
False  
Explanation
1990 is not a multiple of 4 hence it's not a leap year.


Python 3 Code:
def is_leap(year):
    leap = False
    if year%4 == 0 and (year%100 != 0 or year%400 == 0): leap = True
    return leap
year = int(input())
print(is_leap(year))
 
 

Output for Above code:

Input (stdin)
1990
Your Output (stdout)
False
Expected Output
False