Download as pdf or txt
Download as pdf or txt
You are on page 1of 6

Python Module Test

In [1]:

# Write a program which takes 2 digits, X, Y as input and generates a 2-dimensional array.
# The element value in the ith row and jth column of the array should be i*j.

# Note: i = 0 to X-1; j = 0 to Y-1.

# Example:
# Suppose the following inputs are given to the program: 3,5

# Then, the output of the program should be:


# [[0, 0, 0, 0, 0],
# [0, 1, 2, 3, 4],
# [0, 2, 4, 6, 8]]

def creatematrix(x, y):

x = int(x)
y = int(y)

matx = [[0 for cols in range(y)] for rows in range(x)]

for rows in range(x):


for cols in range(y):
matx[rows][cols] = rows* cols

return matx

for i in creatematrix(3, 5):


print(i)

[0, 0, 0, 0, 0]

[0, 1, 2, 3, 4]

[0, 2, 4, 6, 8]

In [2]:

# Given a number, write a function to output its reverse digits. (e.g., given 123 the answe

# Make sure that if it is a negative number, you keep the negative in the front (-123 becom

def reverse_number(num):
num = str(num)
if num[0] == "-":
revnum = int('-' + num[-1:0:-1])
return revnum
else:
revnum = int(num[::-1])
return revnum

print(reverse_number(12345))
print(reverse_number(-12345))

54321

-54321

In [3]:

# You are given a sentence and want to shift each letter by 2 in alphabet to create a secre
# The sentence you want to encode is "the lazy dog jumped over the quick brown fox"
# and the output should be ’vjg ncba fqi lworgf qxgt vjg swkem dtqyp hqz’

alphabets = 'a b c d e f g h i j k l m n o p q r s t u v w x y z'


letters = alphabets.split()

numl = {}
lnum = {}

inum = 0

for i in letters:
numl[inum] = i
lnum[i] = inum
inum = inum + 1

def switchl(text, num):


encodedtext = ''
for i in text:
if i in lnum:
newp = lnum[i] + 2

if newp == 26:
newp = 0
elif newp == 27:
newp = 1

encodedtext = encodedtext + numl[newp]

return encodedtext

text = "the lazy dog jumped over the quick brown fox"

switchl(text, 2)

Out[3]:

'vjggncbaafqiilworgffqxgttvjggswkemmdtqypphqz'
In [4]:

# Create a function is_leap_year to check if a given year is a leap year or not.


# The function should return True/False.
# Note: To be a leap year, the year number must be divisible by four – except for end-of-ce
# which must be divisible by 400.
# This means that the year 2000 was a leap year, although 1900 was not.

def leapyearcheck(year):
if year % 400 == 0:
return True
elif year % 100 == 0:
return False
elif year % 4 == 0:
return True
else:
return False

print(leapyearcheck(2000))
print(leapyearcheck(1900))
print(leapyearcheck(2022))

True

False

False

In [5]:

# Consider a number N. Take all the numbers from 1 to N*2, and split them in two lists, wit

# Example:
# If N is 3, then the output lists are [1,3,5] and [2,4,6]

def separatenums(startnum, endnum):


numlist = []
for i in range(startnum, endnum*2 + 1):
numlist.append(i)

oddlist = []
evenlist = []

for num in numlist:


if num % 2 == 0:
evenlist.append(num)
else:
oddlist.append(num)

return oddlist, evenlist

print(separatenums(1, 3))

([1, 3, 5], [2, 4, 6])

In [6]:

# Extract the data from the below API for below given Lat and Lon in json format, normalize

# Endpoint/URL : http://www.7timer.info/bin/astro.php
# Method : GET
# Variables : lon, lat, ac=0, lang=en, unit=metric, tzshift=0, output=json

# lat lon
# 57.9 2.3
# 34.55 138.4
# 36.5 3.5

import requests
import json
import urllib
import pandas as pd

url = 'http://www.7timer.info/bin/astro.php'

def apitojson(url):
response = urllib.request.urlopen(url)
data = json.loads(response.read())
return data

# print(apitojson(url))
In [7]:

# Assume there’s a CSV file employees.csv with data as below,

# ID FIRST_NAME LAST_NAME PHONE_NUMBER


# 198 Donald OConnell 650.507.9833
# 199 Douglas Grant 650.507.9844
# 200 Jennifer Whalen 515.123.4444
# 201 Michael Hartstein 515.123.5555
# 202 Pat Fay 603.123.6666

# Read the file as a Pandas DataFrame and create another DataFrame with the following colum
# ID – No change
# NAME – New column by concatenating FIRST_NAME and LAST_NAME
# PHONE_NUMBER – Replace all ‘.’ with ‘-’

# Write the DataFrame to a table named tgt_employees in SQL Server.

import pandas as pd
import numpy as np

file = open('data.csv', 'r')

df = pd.read_csv(file)

df = pd.DataFrame(df)

df['NAME'] = df['FIRST_NAME'] + " " + df['LAST_NAME']

finaldf = df

finaldf['PHONE_NUMBER'] = finaldf['PHONE_NUMBER'].str.replace('.', '-')

finaldf = finaldf.drop(['FIRST_NAME', 'LAST_NAME'], axis=1)

finaldf = finaldf [['ID', 'NAME', 'PHONE_NUMBER']]

print(finaldf.head())

ID NAME PHONE_NUMBER

0 198 Donald OConnell 650-507-9833

1 199 Douglas Grant 650-507-9844

2 200 Jennifer Whalen 515-123-4444

3 201 Michael Hartstein 515-123-5555

4 202 Pat Fay 603-123-6666

C:\Users\PGosavi\AppData\Local\Temp\ipykernel_10212\3838715516.py:30: Future
Warning: The default value of regex will change from True to False in a futu
re version. In addition, single character regular expressions will *not* be
treated as literal strings when regex=True.

finaldf['PHONE_NUMBER'] = finaldf['PHONE_NUMBER'].str.replace('.', '-')

You might also like