for i in range(3):
print(i)
print("Bye!")
What country are you from? Sweden
I have heard that Sweden is a beautiful country.
What country are you from? Chile
I have heard that Chile is a beautiful country.
input1=str(input("What country are you from? "))
str1="I have heard that "
str2=" is a beautiful country."
print(str1+input1+str2)
In mathematics, the quadratic equation $ax^2+bx+c=0$ can be solved with the formula $x=\frac{−b±\sqrt{b^2−4ac}}{2a}$.
Write a function solve_quadratic
, that returns both solutions of a generic quadratic as a pair (2-tuple) when the coefficients are given as parameters. It should work like this:
print(solve_quadratic(1,-3,2))
(2.0,1.0)
print(solve_quadratic(1,2,1))
(-1.0,-1.0)
Hint: use the math.sqrt
function from the math
module in your solution.
def solve_quadratic(a,b,c):
from math import sqrt
return (-b+sqrt(b**2-4*a*c))/(2*a),(-b-sqrt(b**2-4*a*c))/(2*a)
print(solve_quadratic(1,-3,2))
print(solve_quadratic(1,2,1))
L1
and L2
that contain integers which are sorted in ascending order. Create a function merge
that gets these lists as parameters and returns a new sorted list L
that has all the elements of L1
and L2
. So, len(L)
should equal to len(L1)+len(L2)
. Do this using the fact that both lists are already sorted. You can’t use the sorted
function or the sort
method in implementing the merge method. You can however use these sorted
in the main
function for creating inputs to the merge
function.def merge(L1,L2):
L_re=[]
while L1 and L2 :
if L1[0]>=L2[0]:
L_re.append(L2[0])
L2.pop(0)
else:
L_re.append(L1[0])
L1.pop(0)
L_re+=L1
L_re+=L2
return L_re
L1=[1,4,7,9,3,5,8]
L2=[5,3,6,7,0,3]
L1.sort()
L2.sort()
merge(L1,L2)
detect_ranges
that gets a list of integers as a parameter. The function should then sort this list, and transform the list into another list where pairs are used for all the detected intervals. So 3,4,5,6
is replaced by the pair (3,7)
. Numbers that are not part of any interval result just single numbers. The resulting list consists of these numbers and pairs, separated by commas. An example of how this function works:
print(detect_ranges([2,5,4,8,12,6,7,10,13]))
[2,(4,9),10,(12,14)]
Note that the second element of the pair does not belong to the range. This is consistent with the way Python’s range
function works. You may assume that no element in the input list appears multiple times.def detect_ranges(L):
L.sort()
from itertools import groupby
fun = lambda x: x[1]-x[0]
L_re=[]
for k, g in groupby(enumerate(L), fun):
L_tem = [j for i, j in g]
if len(L_tem) > 1:
L_re.append((min(L_tem),max(L_tem)+1))
else:
L_re.append(L_tem[0])
return L_re
print(detect_ranges([2,5,4,8,12,6,7,10,13]))
Write function distinct_characters
that gets a list of strings as a parameter. It should return a dictionary whose keys are the strings of the input list and the corresponding values are the numbers of distinct characters in the key.
Use the set container to temporarily store the distinct characters in a string. Example of usage: distinct_characters(["check", "look", "try", "pop"])
should return { "check" : 4, "look" : 3, "try" : 3, "pop" : 2}
.
def distinct_characters(L):
dic_L={}
for i in L:
dic_L[i]=len(set(i))
return dic_L
distinct_characters(["check", "look", "try", "pop"])
d
be a dictionary that has English words as keys and a list of Chinese words as values. So, the dictionary can be used to find out the Chinese equivalents of an English word in the following way:
d["six"]
["六"]
d["apple"]
["苹果"]
Make a function reverse_dictionary
that creates a Chinese to English dictionary based on a English to Chinese dictionary given as a parameter. The values of the created dictionary should be lists of words. It should work like this:
d={`six`:[`六`], `apple`:[`苹果`], `statistics`:[`统计`], `software`:[`软件`], }
reverse_dictionary(d)
{`六`:[`six`], `苹果`:[`apple`], `统计`:[`statistics`], `软件`:[`software`], }
def reverse_dictionary(dic):
r_d={}
for key,value in dic.items():
r_d[str(value[0])]=[key]
return r_d
d={'six':['六'], 'apple':['苹果'], 'statistics':['统计'], 'software':['软件'],}
reverse_dictionary(d)
Write function find_matching
that gets a list of strings and a search string as parameters. The function should return the indices to those elements in the input list that contain the search string. Use the function enumerate
.
An example: find_matching(["sensitive", "engine", "rubbish", "comment"], "en")
should return the list [0, 1, 3]
.
def find_matching(L,str):
L_re=[]
for i,seq in enumerate(L):
if str in seq:
L_re.append(i)
return L_re
find_matching(["sensitive", "engine", "rubbish", "comment"], "en")
for
loop in your solution.4 multiplied by 0 is 0
4 multiplied by 1 is 4
4 multiplied by 2 is 8
4 multiplied by 3 is 12
4 multiplied by 4 is 16
4 multiplied by 5 is 20
4 multiplied by 6 is 24
4 multiplied by 7 is 28
4 multiplied by 8 is 32
4 multiplied by 9 is 36
4 multiplied by 10 is 40
for i in range(11):
print("4 multiplied by %d is %d" %(i,4*i))
print("method 2:")
for i in range(11):
print(f"4 multiplied by {i} is {4*i}")
In the main function print a multiplication table, which is shown below:
1 2 3 4 5 6 7 8 9 10
2 4 6 8 10 12 14 16 18 20
3 6 9 12 15 18 21 24 27 30
4 8 12 16 20 24 28 32 36 40
5 10 15 20 25 30 35 40 45 50
6 12 18 24 30 36 42 48 54 60
7 14 21 28 35 42 49 56 63 70
8 16 24 32 40 48 56 64 72 80
9 18 27 36 45 54 63 72 81 90
10 20 30 40 50 60 70 80 90 100
Use two nested for loops to achive this. Print the numbers in a field with width four, so that the numbers are nicely aligned. Note that you can use the following form to stop the print
function from automatically starting a new line:
def main():
for i in range(1,11):
for j in range(1,11):
print("%4d"%(i*j),end=" ")
print(" ")
main()
for
loops in the main
function to iterate through all possible combinations the pair of dice can give. There are 36 possible combinations. Print all those combinations as (ordered) pairs that sum to 5. For example, your printout should include the pair (2,3)
. Print one pair per line.def main():
for j in range(1,7):
for i in range(1,7):
if i+j==5:
print(f"({i},{j})")
main()
Write two functions: triple
and square
. Function triple
multiplies its parameter by three. Function square
raises its parameter to the power of two. For example, we have equalities triple(5)==15
and square(5)==25
.
a) In the main
function write a for
loop that iterates through values 1 to 10, and for each value prints its triple and its square. The output should be as follows:
triple(1)==3 square(1)==1
triple(2)==6 square(2)==4
b) Now modify this for
loop so that it stops iteration when the square of a value is larger than the triple of the value, without printing anything in the last iteration.
def triple(x):
return 3*x
def square(x):
return x*x
def main():
for i in range(1,11):
print(f"triple({i})=={triple(i)} square({i})=={square(i)}")
main()
print("Answer b")
for i in range(1,11):
if triple(i)<square(i):
break
else:
print(f"triple({i})=={triple(i)} square({i})={square(i)}")
Create a program that can compute the areas of three shapes, triangles, rectangles and circles, when their dimensions are given.
An endless loop should ask for which shape you want the area be calculated. An empty string as input will exit the loop. If the user gives a string that is none of the given shapes, the message “unknown shape!” should be printed. Then it will ask for dimensions for that particular shape. When all the necessary dimensions are given, it prints the area, and starts the loop all over again. Use format specifier f for the area.
Example interaction:
Choose a shape (triangle, rectangle, circle): triangle
Give base of the triangle: 20
Give height of the triangle: 5
The area is 50.000000
Choose a shape (triangle, rectangle, circle): rectangel
Unknown shape!
Choose a shape (triangle, rectangle, circle): rectangle
Give width of the rectangle: 20
Give height of the rectangle: 4
The area is 80.000000
Choose a shape (triangle, rectangle, circle): circle
Give radius of the circle: 10
The area is 314.159265
Choose a shape (triangle, rectangle, circle):
while 1>0:
geo=str(input("Choose a shape (triangle, rectangle, circle): "))
L=["triangle", "rectangle", "circle"]
if geo==" ":
break
elif geo not in L:
print("Unknown shape!")
elif geo=="triangle":
b=float(input("Give base of the triangle: "))
h=float(input("Give height of the triangle: "))
print(f"The area is {b*h/2}")
elif geo=="rectangle":
w=float(input("Give width of the triangle: "))
h=float(input("Give height of the triangle: "))
print(f"The area is {w*h}")
elif geo=="circle":
r=float(input("Give radius of the circle: "))
print(f"The area is {r*r*3.1415926}")
Write a function positive_list
that gets a list of numbers as a parameter, and returns a list with the negative numbers and zero filtered out using the filter
function.
The function call positive_list([2,-2,0,1,-7])
should return the list [2,1]
.
def positive_list(L):
def pos(x):
return x>0
return list(filter(pos,L))
# Hint: filter function is different in Python 2.7 and 3.x.
positive_list([2,-2,0,1,-7])