Python Tutorial 3
Python Tutorial 3
def letter2number(x):
grades = 4 - (ord(x[0]) - ord("A"))
if len(x)> 1:
if x [1] == "+":
grades += 0.3
else:
grades-= 0.3
return grades
print(letter2number(x))
Output:
(a). (b).
(c)
Write function geometric that takes a list of integers as input and returns True if the
integers in the List from a geometric sequence. A sequence a0, a1, a2, a3, …,an2,
an 1 is a geometric sequence if the ratios a1/a0, a2/a1, a3/a2, a4/a3,…, an1/ an2 are
all equal.
def geometric(list):
for x in range(1,len(list)):
if list[x]/list[x - 1] != list[1]/list[0]:
return False
return True
print(geometric(list))
Output:
(a). (b).
Write Function lastfirst() that takes one argument ---a list of stringsnof the format
<LastName, FirstName>---and returns a list consisting two lists (a) A list of all the
first names (b) A list of all the last names
Output:
Develop the function many() that takes as input the name of a file in the current
directory (as a string) and outputs the number of words of length 1, 2, 3, and 4.
Test your function on file sample.txt
>>>many (‘sample.txt’)
Words of length 1:2
Words of length 2:5
Words of length 3:1
Words of length 4: 10
filename=input("enter filename:")
def many(filename):
list = []
with open(filename, 'r') as y:
for length in y:
list += map(lambda x :
x.strip(',?.'),length.split())
dict = {}
for word in list:
if len(word) not in dict:
dict[len(word)] = 1
else:
dict[len(word)]+= 1
for x in dict:
print("words of length",x, ":-",dict[x])
print(many(filename))
Output:
Write a function subset Sum() that takes as input a list of positive numbers and a
positive number target. Your function should return True if there are three numbers
in the list that add up to target. For example, if the input list is[5, 4, 10,20,15, 19]
and target is 38, then True should be returned since 4 + 15 + 19 = 38. However, if
the input list is the same but the target value is 10, then the returned value should
be False because 10 is not the sum of any three numbers in the given list.
def subsetSum(list,integer):
for x in range(0, len(list)):
for y in range (x, len(list)):
for z in range (y,len(list)):
if list[x] + list [y] + list[z] == integer:
return True
return False
print(subsetSum(list,integer))
Output:
(a). (b).
Implement function fib() that takes a nonnegative integer n as input and returns the
nth Fibonacci number.
>>>fib(0)
1
>>>fib(4)
5
>>>fib(8)
34
n=int(input("Enter n:"))
def fib(n):
if n < 2:
return 1
a = 1
b = 1
for x in range(1, n):
b = b + a
a = b - a
return b
print(fib(n))
>>>mystery(4)
2
>>>mystery(11)
3
>>>mystery(25)
4
n=int(input("Enter n:"))
def mystery (n):
x = 0
while n > 1:
x = x + 1
n = int(n / 2)
return x
print(mystery(n))
Output: