Welcome, Guest: Register On Nairaland / LOGIN! / Trending / Recent / New
Stats: 3,153,012 members, 7,817,985 topics. Date: Sunday, 05 May 2024 at 01:41 AM

Python 3: Exercises And Solutions. - Programming (5) - Nairaland

Nairaland Forum / Science/Technology / Programming / Python 3: Exercises And Solutions. (8902 Views)

Salesforce Rest API Example Using Python 3 / Consume Kibana Rest API Using Python 3 / How To Write A Guessing Game Program In Python 3 (2) (3) (4)

(1) (2) (3) (4) (5) (6) (Reply) (Go Down)

Re: Python 3: Exercises And Solutions. by HappyPagan: 1:28am On May 25, 2020
jayphe:
[left]
Collinsanele Taofeekdboy kensmoney Daddyshome Zabiboy

Write a Python program that accepts the name of a student, matric number, course code and the score he/she got in the course. E.g
Name: John Alfred
Matric. No.: MUC/CS/014/0882
Course Code: CMP 212
Score: 100


def printStudentDetails():
grade = getGrade(int(score))

print(f'{name}, {matNo}, {courseCode}, {grade}')

def getGrade(s):
if s<49:
return 'F'
elif s<59:
return 'E'
elif s<69:
return 'D'
elif s<84:
return 'C'
elif s<94:
return 'B'
else:
return 'A'

name = input('Enter name:\t')
matNo = input('Enter mat. no.:\t')
courseCode = input('Enter course code:\t')
score = input('Enter score: ')
grade = ''

printStudentDetails()

2 Likes

Re: Python 3: Exercises And Solutions. by SKYQUEST(m): 9:40pm On May 28, 2020
nwele2017:


Using Pandas read it in as CSV then convert it to xlsx using data name .to_excel.(ie. name of data .yo_excel("name.xlsx"wink

lets try this!
Re: Python 3: Exercises And Solutions. by SKYQUEST(m): 9:58pm On May 28, 2020
SKYQUEST:
what python code would you run on a table with data separated by spaces as shown in the image below to convert it in into a readable excel table; the raw data is also given in the attachment below (ben2):

how about this:

import pandas as pd
from pandas import DataFrame
df = pd.read_excel('ben2.xlsx',names=['Benf'])
#seperate each of the column elements into different list
a = df.Benf.str.split().str[0].tolist()
b = df.Benf.str.split().str[1].tolist()
c = df.Benf.str.split().str[2].tolist()
d = df.Benf.str.split().str[3].tolist()
df=pd.DataFrame() #create an empty dataframe
df['First Digit']=a #add the first column to the dataframe and name it First Digit
df["Benford's Set"]=b
df['Data Set X']=c
df['Deviations']=d
df

....to yield this:

Re: Python 3: Exercises And Solutions. by iCode2: 1:30pm On Jun 03, 2020
For this code:
text = input('Enter a string: ')
for i in range(len(text)):
if text[i] == a:
print(i, end=',')


If i type in 'amalgamate', I'll get the following output: 0,2,5,7,

Question: How can I discard that comma after 7?
Re: Python 3: Exercises And Solutions. by HappyPagan: 3:57pm On Jun 03, 2020
@iCode2

The comma is there because you use

end = ','


On line 4.

If you want to remove the final comma, you can save the final output in a string and use one of the string methods to remove the last comma.

If you want to remove all the commas, maybe you prefer spaces, use

end = ' ' #there is a space between both quotes.
Re: Python 3: Exercises And Solutions. by Shepherdd(m): 4:39pm On Jun 03, 2020
@ jayphe Collinsanele gbolly1151 kensmoney StevDesmond
Please let's roll in more exciting challenges. The thread is winding down.
Re: Python 3: Exercises And Solutions. by gbolly1151(m): 7:30pm On Jun 03, 2020
Shepherdd:
@ jayphe Collinsanele gbolly1151 kensmoney StevDesmond
Please let's roll in more exciting challenges. The thread is winding down.

Write a recursive function to reverse a list
Re: Python 3: Exercises And Solutions. by iCode2: 7:57pm On Jun 03, 2020
HappyPagan:
@iCode2

The comma is there because you use

end = ','


On line 4.

If you want to remove the final comma, you can save the final output in a string and use one of the string methods to remove the last comma.

If you want to remove all the commas, maybe you prefer spaces, use

end = ' ' #there is a space between both quotes.
Thanks a lot. I'll try that string method and see.
Re: Python 3: Exercises And Solutions. by HappyPagan: 8:03pm On Jun 03, 2020
iCode2:
Thanks a lot. I'll try that string method and see.
No wahala. I think rstrip will work.

'astring'.rstrip(',')



I'm not on my PC now. Will try it once I get home.
Re: Python 3: Exercises And Solutions. by Shepherdd(m): 8:36pm On Jun 03, 2020
gbolly1151:


Write a recursive function to reverse a list

Nice one

def reverse(data):
if len(data) == 0:
return data
else:
return [data[-1]] + reverse(data[:-1])

or

def reverse(data):
return [data[-1]] + reverse(data[:-1]) if len(data) > 0 else data
Re: Python 3: Exercises And Solutions. by gbolly1151(m): 9:01pm On Jun 03, 2020
Shepherdd:


Nice one

def reverse(data):
if len(data) == 0:
return data
else:
return [data[-1]] + reverse(data[:-1])

or

def reverse(data):
return [data[-1]] + reverse(data[:-1]) if len(data) > 0 else data


Good job boss....i will be back with graph question

1 Like

Re: Python 3: Exercises And Solutions. by Shepherdd(m): 9:08pm On Jun 03, 2020
gbolly1151:


Can you share screenshot of your run

I did some renaming after prototyping inside IDLE.

Re: Python 3: Exercises And Solutions. by gbolly1151(m): 9:12pm On Jun 03, 2020
Guy...this is advance question and it is base on graph data structure,i myself haven't try to solve it but you can give it a try and test your data structure skill



Write a program that builds the routing tables for the nodes in a computer network, based on shortest-path routing, where path distance is measured by hop count, that is, the number of edges in a path. The input for this problem is the connectivity information for all the nodes in the network, as in the following example:
241.12.31.14:
241.12.31.15
241.12.31.18
241.12.31.19

which indicates three network nodes that are connected to 241.12.31.14, that is, three nodes that are one hop away. The routing table for the node at address A is a set of pairs (B,C), which indicates that, to route a message from A to B, the next node to send to (on the shortest path from A to B) is C. Your program should output the routing table for each node in the network, given an input list of node connectivity lists, each of which is input in the syntax as shown above, one per line.
Re: Python 3: Exercises And Solutions. by iCode2: 11:42pm On Jun 03, 2020
HappyPagan:

No wahala. I think rstrip will work.

'astring'.rstrip(',')



I'm not on my PC now. Will try it once I get home.
I don't know this astrip kini yet. I'll read up on it.
Re: Python 3: Exercises And Solutions. by modash(m): 3:01am On Jun 04, 2020
Taofeekdboy:

I saw this late, I have been busy with my project and it took a lot of my time.
I will leave it here for who is interested to check..
It is a social media clone I made.
http://mysocialapp.pythonanywhere.com

Looking forward to your comments

The site looks real good.

1 Like

Re: Python 3: Exercises And Solutions. by iCode2: 4:04pm On Jun 04, 2020
I've tried my hands on this though. I want to see if someone can answer it a different way. Maybe yours will be better.

Write a program that asks the user to enter a list of integers. Do the following:
(a) Print the total number of items in the list.
(b) Print the last item in the list.
(c) Print the list in reverse order.
(d) Print Yes if the list contains a 5 and No otherwise.
(e) Print the number of fives in the list.
(f) Remove the first and last items from the list, sort the remaining items, and print the result.
(g) Print how many integers are less than 5
Re: Python 3: Exercises And Solutions. by scarplanet(m): 7:28pm On Jun 04, 2020
iCode2:
I've tried my hands on this though. I want to see if someone can answer it a different way. Maybe yours will be better.

Write a program that asks the user to enter a list of integers. Do the following:
(a) Print the total number of items in the list.
(b) Print the last item in the list.
(c) Print the list in reverse order.
(d) Print Yes if the list contains a 5 and No otherwise.
(e) Print the number of fives in the list.
(f) Remove the first and last items from the list, sort the remaining items, and print the result.
(g) Print how many integers are less than 5

.
Re: Python 3: Exercises And Solutions. by scarplanet(m): 7:31pm On Jun 04, 2020
class Solution:

def __init__(self, n):
self.n = list(n)

def prog(self):
print("Total Number: ", len(self.n))
print("Last Item: ", self.n[-1])
print("Reverse List: ", self.n[::-1])
l = filter(lambda x: x == 5, self.n)
print("YES List Contains 5" if 5 in list(l) else "NO List does not contain 5" )
print("Number of fives in list: ", self.n.count(5))
_, *b, _ = self.n
print("Sorted list minus first and last elements: ", sorted([*b]))
y = filter(lambda x: x < 5, self.n)
print("Number less than five: ", len(list(y)))

list_elements = eval(input("Enter desired integers separated by comma: " ))
sol = Solution(list_elements)
sol.prog()
Re: Python 3: Exercises And Solutions. by Taofeekdboy(m): 9:52pm On Jun 04, 2020
modash:


The site looks real good.
Thank you bro...
Re: Python 3: Exercises And Solutions. by iCode2: 10:58pm On Jun 04, 2020
scarplanet:
class Solution:

def __init__(self, n):
self.n = list(n)

def prog(self):
print("Total Number: ", len(self.n))
print("Last Item: ", self.n[-1])
print("Reverse List: ", self.n[::-1])
l = filter(lambda x: x == 5, self.n)
print("YES List Contains 5" if 5 in list(l) else "NO List does not contain 5" )
print("Number of fives in list: ", self.n.count(5))
_, *b, _ = self.n
print("Sorted list minus first and last elements: ", sorted([*b]))
y = filter(lambda x: x < 5, self.n)
print("Number less than five: ", len(list(y)))

list_elements = eval(input("Enter desired integers separated by comma: " ))
sol = Solution(list_elements)
sol.prog()
Chai! Yours looks so advanced. grin I still have a long way to go. Here's my solution

myList = eval(input('Enter a list of integers)) #Enter the numbers as well as the square brackets.

print(len(myList))
print(myList[-1])
myList.reverse()
if 5 in myList:
print(' Yes')
else:
print('It doesn\' t contain a 5')

count = 0
for i in range(len(myList)):
if myList[i] < 5:
count += 1
print('There are', count, 'integers less than 5')

del myList[0]
del myList[-1]
myList.sort()
print(myList)

LessThanFive = []
for i in range (len(myList)):
if 5 == myList[i]:
LessThanFive.append(myList.count(i))
print('5 appeared', len(LessThanFive), 'times.')
Re: Python 3: Exercises And Solutions. by Shepherdd(m): 11:38pm On Jun 04, 2020
gbolly1151:
Guy...this is advance question and it is base on graph data structure,i myself haven't try to solve it but you can give it a try and test your data structure skill



Write a program that builds the routing tables for the nodes in a computer network, based on shortest-path routing, where path distance is measured by hop count, that is, the number of edges in a path. The input for this problem is the connectivity information for all the nodes in the network, as in the following example:
241.12.31.14:
241.12.31.15
241.12.31.18
241.12.31.19

which indicates three network nodes that are connected to 241.12.31.14, that is, three nodes that are one hop away. The routing table for the node at address A is a set of pairs (B,C), which indicates that, to route a message from A to B, the next node to send to (on the shortest path from A to B) is C. Your program should output the routing table for each node in the network, given an input list of node connectivity lists, each of which is input in the syntax as shown above, one per line.

I was once asked a question similar to this and I failed graciously. Now let me tackle it again!!

1 Like

Re: Python 3: Exercises And Solutions. by gbolly1151(m): 10:03pm On Jun 05, 2020
Give a recursive algorithm to compute the product of two positive integers, m and n, using only addition and subtraction.
Re: Python 3: Exercises And Solutions. by IamGoke(m): 4:35pm On Jun 07, 2020
jayphe:

Exercise 1

Write a python program that obtains the domain name (thapar.edu) from the URL
http://www.thapar.edu/index.php/about-us/mission
Nice initiative bro.
I was able to extract 'www.thapar.edu' with regex.

import re
pattern = r"(\w+)(\.)(\w+)(\.(\w+))" str = 'http://www.thapar.edu/index.php/about-us/mission' match = re.search(pattern, str) if match: print(match.group()) else: print('Not found!')
Re: Python 3: Exercises And Solutions. by Jummate(m): 11:57pm On Jun 08, 2020
gbolly1151:
Give a recursive algorithm to compute the product of two positive integers, m and n, using only addition and subtraction.

def product(m, n):

if n == 0:

return 0

else:

return m + product(m, n-1)

1 Like

Re: Python 3: Exercises And Solutions. by Jummate(m): 12:12am On Jun 09, 2020
Jummate:


def product(m, n):

if n == 0:

return 0

else:

return m + product(m, n-1)

I indented lines 2 and 4 to be under the function declaration.

I indented lines 3 to be under the if statement and line 5 to be under the else statement but I don't know why these are not reflecting as such........
Re: Python 3: Exercises And Solutions. by IamGoke(m): 2:29pm On Jun 09, 2020
Jummate:


I indented lines 2 and 4 to be under the function declaration.

I indented lines 3 to be under the if statement and line 5 to be under the else statement but I don't know why these are not reflecting as such........


If you are writing code, you need to format your text in code format.

[Code]

#Your code here

[/Code]

Change the C to c

Example below:

 print('hello word')
Re: Python 3: Exercises And Solutions. by Jummate(m): 3:47pm On Jun 09, 2020
IamGoke:



If you are writing code, you need to format your text in code format.

[Code]

#Your code here

[/Code]

Change the C to c

Example below:

 print('hello word')


def appreciation():
print("Thanks bro" )

Re: Python 3: Exercises And Solutions. by Shepherdd(m): 9:21pm On Jun 09, 2020
gbolly1151:
Guy...this is advance question and it is base on graph data structure,i myself haven't try to solve it but you can give it a try and test your data structure skill



Write a program that builds the routing tables for the nodes in a computer network, based on shortest-path routing, where path distance is measured by hop count, that is, the number of edges in a path. The input for this problem is the connectivity information for all the nodes in the network, as in the following example:
241.12.31.14:
241.12.31.15
241.12.31.18
241.12.31.19

which indicates three network nodes that are connected to 241.12.31.14, that is, three nodes that are one hop away. The routing table for the node at address A is a set of pairs (B,C), which indicates that, to route a message from A to B, the next node to send to (on the shortest path from A to B) is C. Your program should output the routing table for each node in the network, given an input list of node connectivity lists, each of which is input in the syntax as shown above, one per line.

Although this question does not provide the routing table I made some assumptions.

routing_table = {
'a': {'c': 5, 'b': 1},
'b': {'a': 1, 'd': 4, 'c': 2},
'c': {'e': 3, 'b': 2, 'd': 2},
'd': {'b': 4, 'c': 2, 'e': 8, 'g': 1},
'e': {'c': 3, 'f': 2, 'd': 8, 'g': 1},
'f': {'e': 2, 'g': 1},
'g': {'d': 1, 'e': 1, 'f': 1},
}

def grade_route (vertex, links, total_cost, previous):
for destination, cost in links.items():
previous_cost = total_cost[destination]
potential_cost = cost + total_cost[vertex]

if potential_cost < previous_cost:
total_cost[destination] = potential_cost
previous[destination] = vertex

def shortest_path(graph, source, destination):
previous = {}
total_cost = {vertex: (lambda x : float('inf') if x != source else 0)(vertex) for vertex in graph.keys()}
route = [destination]

for vertex, links in graph.items():
grade_route (vertex, links, total_cost, previous)

trace = destination
while True:
pth = previous[trace]
route.append(pth)
trace = pth
if pth == source:
return [total_cost[destination], route[::-1]]

print(shortest_path(routing_table , 'a', 'c'))
### ===> [3, ['a', 'b', 'c']]


Although their might be multiple route to a destination I avoided implementing this for brevity. DS & Algo questions sometimes aren't easy!!!

1 Like

Re: Python 3: Exercises And Solutions. by gbolly1151(m): 3:55am On Jun 10, 2020
Shepherdd:


Although this question does not provide the routing table I made some assumptions.

routing_table = {
'a': {'c': 5, 'b': 1},
'b': {'a': 1, 'd': 4, 'c': 2},
'c': {'e': 3, 'b': 2, 'd': 2},
'd': {'b': 4, 'c': 2, 'e': 8, 'g': 1},
'e': {'c': 3, 'f': 2, 'd': 8, 'g': 1},
'f': {'e': 2, 'g': 1},
'g': {'d': 1, 'e': 1, 'f': 1},
}

def grade_route (vertex, links, total_cost, previous):
for destination, cost in links.items():
previous_cost = total_cost[destination]
potential_cost = cost + total_cost[vertex]

if potential_cost < previous_cost:
total_cost[destination] = potential_cost
previous[destination] = vertex

def shortest_path(graph, source, destination):
previous = {}
total_cost = {vertex: (lambda x : float('inf') if x != source else 0)(vertex) for vertex in graph.keys()}
route = [destination]

for vertex, links in graph.items():
grade_route (vertex, links, total_cost, previous)

trace = destination
while True:
pth = previous[trace]
route.append(pth)
trace = pth
if pth == source:
return [total_cost[destination], route[::-1]]

print(shortest_path(routing_table , 'a', 'c'))
### ===> [3, ['a', 'b', 'c']]


Although their might be multiple route to a destination I avoided implementing this for brevity. DS & Algo questions sometimes aren't easy!!!
You have done a great job here bro....graph and tree questions aren't friendly
Re: Python 3: Exercises And Solutions. by razboy20: 7:30am On Jun 10, 2020
input = str(input("Enter a string: "wink)
arr = input.split(" "wink
print(join(arr,"_"wink)

(1) (2) (3) (4) (5) (6) (Reply)

Mobile Phone Apps For Nigeria / Why Is Programming Difficult? / Lets Post Ideas Here 4 Other Programmers

(Go Up)

Sections: politics (1) business autos (1) jobs (1) career education (1) romance computers phones travel sports fashion health
religion celebs tv-movies music-radio literature webmasters programming techmarket

Links: (1) (2) (3) (4) (5) (6) (7) (8) (9) (10)

Nairaland - Copyright © 2005 - 2024 Oluwaseun Osewa. All rights reserved. See How To Advertise. 56
Disclaimer: Every Nairaland member is solely responsible for anything that he/she posts or uploads on Nairaland.