100% found this document useful (2 votes)
196 views7 pages

Assig 2 Soln

The document contains solutions to 15 programming assignments involving writing Python functions. The functions cover a range of tasks like computing squares, string concatenation, determining even/odd numbers, generating dictionaries and lists from inputs, sorting words in a string, and playing rock-paper-scissors.

Uploaded by

program program
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
196 views7 pages

Assig 2 Soln

The document contains solutions to 15 programming assignments involving writing Python functions. The functions cover a range of tasks like computing squares, string concatenation, determining even/odd numbers, generating dictionaries and lists from inputs, sorting words in a string, and playing rock-paper-scissors.

Uploaded by

program program
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

12/9/2019 Assignment_II_solution

1. Write a python function that computes the square of a number. The function should return the
output as a tuple in the following form: (a, a^2 ) where a is the input value to the function.

In [1]:

def square(x):
return (x,x**2)

In [2]:

square(4) # testing the function

Out[2]:

(4, 16)

2. Write a function that can accept two strings as input and concatenate them and then print it as an
output.

In [3]:

def string_concat(strA, strB):


joined_str = strA + strB
print(joined_str)

In [4]:

string_concat("Welcome ", "Home!")

Welcome Home!

3. Write a function that can accept an integer number as an input and print "Even number" if the
number is even, otherwise print "Odd number".

In [5]:

def even_odd(x):
if x % 2 == 0:
print("Even number")
else:
print("Odd number")

In [6]:

even_odd(3)

Odd number

In [7]:

even_odd(10)

Even number

http://localhost:8888/nbconvert/html/Assignment_II_solution.ipynb?download=false 1/7
12/9/2019 Assignment_II_solution

4. Write a function that can print a dictionary where the keys are numbers between 1 and 20 (both
included) and the values are square of keys.

In [8]:

def print_dict():
d = {}
for i in range(21):
d[i] = i**2
return(d)

In [9]:

print_dict()

Out[9]:

{0: 0,
1: 1,
2: 4,
3: 9,
4: 16,
5: 25,
6: 36,
7: 49,
8: 64,
9: 81,
10: 100,
11: 121,
12: 144,
13: 169,
14: 196,
15: 225,
16: 256,
17: 289,
18: 324,
19: 361,
20: 400}

5. Write a function to compute the square-root of a given number. If the given number is negative,
your function should give an error message.

In [10]:

def square_root(x):
if x >= 0:
return(x**(1/2))
return ("You entered an invalid value!")

In [11]:

square_root(25)

Out[11]:

5.0

http://localhost:8888/nbconvert/html/Assignment_II_solution.ipynb?download=false 2/7
12/9/2019 Assignment_II_solution

In [12]:

square_root(-3)

Out[12]:

'You entered an invalid value!'

6. Write a function to input two separate lists, one with names (name_list) and another with numbers
(number_list). Your function should then output another list (output_list) which contains tuples of
names and number.

In [13]:

def name_number(ListA, ListB):


return list(zip(ListA, ListB))

In [14]:

name_list = ["Dan Mace", "Connor Meyer", "Adam Smith", "John Watson"]


number_list = [98980000, 777890879, 123087699, 960008779]

output_list = name_number(name_list, number_list)

In [15]:

print(output_list)

[('Dan Mace', 98980000), ('Connor Meyer', 777890879), ('Adam Smith',


123087699), ('John Watson', 960008779)]

7. With a given tuple (1,2,3,4,5,6,7,8,9,10), write a program to print the first half values in one line and
the last half values in another line.

In [16]:

mytuple = (1,2,3,4,5,6,7,8,9,10)
midpoint = int(len(mytuple)/2)
print("{}\n{}".format(mytuple[:midpoint],mytuple[midpoint:]))

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

8. Write a function that takes in a list of usernames of students. The function should then output
another list which returns the email addresses by adding @thebritishcollege.edu.np” to the
usernames in the list. The output of your function should be a list.

In [17]:

def out_email(usernames):
out_list = []
for n in usernames:
out_list.append(str(n)+"@thebritishcollege.edu.np")
return out_list

http://localhost:8888/nbconvert/html/Assignment_II_solution.ipynb?download=false 3/7
12/9/2019 Assignment_II_solution

In [18]:

student_username = ["ksmith", "rsouza", "lgarber", "aghods", "shassan", "proy"]


out_email(student_username)

Out[18]:
['[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]',
'[email protected]']

9. In the list given below, use a while loop to print the output. Your loop should run until all the items
in the list have been printed.

In [19]:

name_list = [('Dan Mace', 98980000), ('Connor Meyer', 777890879), ('Adam Smith',


123087699), ('John Watson', 960008779)]

In [20]:

i = 0
while i < len(name_list):
print("Name: ", name_list[i][0])
print("Contact no: ", name_list[i][1])
i = i + 1

Name: Dan Mace


Contact no: 98980000
Name: Connor Meyer
Contact no: 777890879
Name: Adam Smith
Contact no: 123087699
Name: John Watson
Contact no: 960008779

10. Write a function that accepts a list of tuples as an input, and outputs the values as a dictionary
shown below:

In [21]:

def tuple_to_dict(inList):
out_d = {}
for i,j in inList:
out_d[i] = j
return out_d

http://localhost:8888/nbconvert/html/Assignment_II_solution.ipynb?download=false 4/7
12/9/2019 Assignment_II_solution

In [22]:

input_list = [ ("Dan Mace", 98980000), ("Connor Meyer", 777890879), ("Adam Smit


h", 123087699), ("John Watson", 960008779)]

tuple_to_dict(input_list)

Out[22]:

{'Dan Mace': 98980000,


'Connor Meyer': 777890879,
'Adam Smith': 123087699,
'John Watson': 960008779}

11. Write a function to go through a string and count the number of words in the given string.

In [23]:

def count_words(s):
word_list = s.split(" ")
return("number of words: {}".format(len(word_list)))

In [24]:

input_str = "If you count the words in this sentence you will get twelve"
count_words(input_str)

Out[24]:
'number of words: 12'

12. Write a function to print Fibonacci sequence up-to the given term.

In [25]:

def fibonacci(N):
x = 1
y = 1
print (1)
for i in range(N-1):
x,y = y,x+y
print (x)

# test
fibonacci(7)

1
1
2
3
5
8
13

13. Write a program to play a game of rock, paper and scissor between two players. Take two user
inputs from the keyboard and according to user's choice decide who wins.

http://localhost:8888/nbconvert/html/Assignment_II_solution.ipynb?download=false 5/7
12/9/2019 Assignment_II_solution

In [27]:

userA_choice = input("User 1, please choose between 'ROCK', 'PAPER', and 'SCISSO


R': ")
userB_choice = input("User 2, please choose between 'ROCK', 'PAPER', and 'SCISSO
R': ")

choices = ["rock", "paper", "scissor"]

if userA_choice.lower() in choices and userB_choice.lower() in choices:

if userA_choice.lower() == userB_choice.lower():
print("It is a tie! Please play again!")

elif userA_choice.lower() == "rock":


if userB_choice.lower() == "scissor":
print("User 1 wins!")
else:
print("User 2 wins!")

elif userA_choice.lower() == "paper":


if userB_choice.lower() == "scissor":
print("User 2 wins!")
else:
print("User 1 wins!")

elif userA_choice.lower() == "scissor":


if userB_choice.lower() == "rock":
print("User 2 wins!")
else:
print("User 1 wins!")
else:
print("Unrecognized Input!")

User 1, please choose between 'ROCK', 'PAPER', and 'SCISSOR': RocK


User 2, please choose between 'ROCK', 'PAPER', and 'SCISSOR': SciSSo
R
User 1 wins!

14. Write a Python program to construct the following pattern.

1
22
333
4444
55555
666666
7777777
88888888
999999999

http://localhost:8888/nbconvert/html/Assignment_II_solution.ipynb?download=false 6/7
12/9/2019 Assignment_II_solution

In [28]:

num = 1
for i in range(1,10):
for j in range(1,i+1):
print(num, end = " ")
print("\n")
num = num + 1

2 2

3 3 3

4 4 4 4

5 5 5 5 5

6 6 6 6 6 6

7 7 7 7 7 7 7

8 8 8 8 8 8 8 8

9 9 9 9 9 9 9 9 9

15. Write a Python function that accepts a hyphen-separated sequence of words as input and prints
the words in a hyphen-separated sequence after sorting them alphabetically.

For example:

If your input is : s-i-t-c-o-m

Your output should be : c-i-m-o-s-t

In [29]:

def sort_words(word):
wordlist = word.split("-")
return "-".join(sorted(wordlist))

In [30]:

sort_words("s-i-t-c-o-m")

Out[30]:
'c-i-m-o-s-t'

http://localhost:8888/nbconvert/html/Assignment_II_solution.ipynb?download=false 7/7

You might also like