Tuesday, 10 September 2019

The Joy of Computing using Python: Programming Assignment 1,2 & 3

You are provided with a playlist containing N songs, each has a unique positive integer length. Assume you like all the songs from this playlist, but there is a song, which you like more than others.
It is named "Computing Paradox".

You decided to sort this playlist in increasing order of songs length. For example, if the lengths of the songs in the playlist were {1, 3, 5, 2, 4} after sorting it becomes {1, 2, 3, 4, 5}.
Before the sorting, "Computing Paradox" was on the kth position (1-indexing is assumed for the playlist) in the playlist.

Your task is to find the position of "Computing Paradox" in the sorted playlist.

Input Format:
The first line contains two numbers N denoting the number of songs in the playlist.
The second line contains N space separated integers A1, A2, A3,..., AN denoting the lengths of songs.
The third line contains an integer k, denoting the position of "Computing Paradox" in the initial playlist.

Output Format:

Output a single line containing the position of "Computing Paradox" in the sorted playlist.


Program:

x=int(input())
lis=[int(i) for i in input().split(" ")]
sort=sorted(lis)
k=int(input())
pos=lis[k-1]
if pos in sort:
  ind=sort.index(pos)+1

  print(ind,end='')


2. Given a positive integer number n, you have to write a program that generates a dictionary d which contains (i, i*i*i) such that i is the key and i*i*i is its value, where i is from 1 to n (both included).
Then you have to just print this dictionary d.

Example:
Input: 4

will give output as
{1: 1, 2: 8, 3: 27, 4: 64}

Input Format:
Take the number n in a single line.

Output Format:
Print the dictionary d in a single line.


Example:

Input:
8

Output:
{1: 1, 2: 8, 3: 27, 4: 64, 5: 125, 6: 216, 7: 343, 8: 512}

Program:

n=int(input())
d={}
for i in range(n):
  d[i+1]=(i+1)**3

print(d,end="")

3. Given an integer number n, define a function named printDict() which can print a dictionary where the keys are numbers between 1 and n (both included) and the values are square of keys.
The function printDict() doesn't take any argument.

Input Format:
The first line contains the number n.

Output Format:
Print the dictionary in one line.

Example:

Input:
5

Output:
{1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

Program:

def printDict():
  x=int(input())
  d={}
  for i in range(x):
    d[i+1]=(i+1)**2
  print(d,end='') 
printDict()

2 comments: