Quiz
Quiz 1
See https://en.wikipedia.org/wiki/Deterministic_finite_automaton
We consider as alphabet a set of digits.
We accept partial transition functions (that is, there might be no transition for a given state and symbol).
With the accepts() function, we will deal with a single accept state rather than a set of accept states.
In the test cases below, transitions_2 is the wikipedia example (with 'S1' and 'S2' renamed as 'state_1' and 'state_2', respectively), so the automaton that with 'state_1' as both initial and unique accept state, accepts words with an even number of occurrences of 0's.
See comments and test cases in stub.
# Written by *** and Eric Martin for COMP9021
'''
See https://en.wikipedia.org/wiki/Deterministic_finite_automaton
We consider as alphabet a set of digits.
We accept partial transition functions (that is, there might be no transition
for a given state and symbol).
With the accepts() function, we will deal with a single accept state rather than
a set of accept states.
In the test cases below, transitions_2 is the wikipedia example
(with 'S1' and 'S2' renamed as 'state_1' and 'state_2', respectively),
so the automaton that with 'state_1' as both initial and unique accept state,
accepts words with an even number of occurrences of 0's.
'''
def describe_automaton(transitions):
for key in transitions.keys():
print(f'When in state "{key[0]}" and processing "{key[1]}", automaton\'s state becomes "{transitions[key]}".')
#for i in transitions.items():
#print(f'When in state "{i[0][0]}" and processing "{i[0][1]}", automaton\'s state becomes "{i[1]}".')
#for key,values in transitions.items():
#print(f'When in state "key[0]" and processing "key[1]", automaton\'s state becomes "values".')
def transitions_as_dict(transitions_as_list):
transitions = {}#string->dictionary
for x in transitions_as_list:
s1, s2=x.split(':')
s3, s4=s1.split(',')
if s4=='0':
tup1=(s3,0)
elif s4=='1':
tup1=(s3,1)
else:
return False
transitions[tup1]=s2
return transitions
def accepts(transitions, word, initial_state, accept_state):
current_state=initial_state
for x in word:
flag=0
current_lab=int(x)
for key in transitions.keys():
if key==(current_state,current_lab):
#if key[0]==current_state and key[1]==current_lab:
current_state=transitions[key]
flag=1
break
if flag==0:
return False
if current_state==accept_state:
return True
else:
return False
if __name__ == '__main__':
import doctest
doctest.testmod()
answer from others
# Written by *** and Eric Martin for COMP9021
# 仅供学习交流,不得作为作业提交,被查重本人概不负责
'''
See https://en.wikipedia.org/wiki/Deterministic_finite_automaton
We consider as alphabet a set of digits.
We accept partial transition functions (that is, there might be no transition
for a given state and symbol).
With the accepts() function, we will deal with a single accept state rather than
a set of accept states.
In the test cases below, transitions_2 is the wikipedia example
(with 'S1' and 'S2' renamed as 'state_1' and 'state_2', respectively),
so the automaton that with 'state_1' as both initial and unique accept state,
accepts words with an even number of occurrences of 0's.
'''
def describe_automaton(transitions):
'''
The output is produced with the print() function.
>>> transitions_1 = {('q0', 0): 'q1', ('q1', 1): 'q0'}
>>> describe_automaton(transitions_1)
When in state "q0" and processing "0", automaton's state becomes "q1".
When in state "q1" and processing "1", automaton's state becomes "q0".
>>> transitions_2 = {('state_1', 0): 'state_2', ('state_1', 1): 'state_1',\
('state_2', 0): 'state_1', ('state_2', 1): 'state_2'}
>>> describe_automaton(transitions_2)
When in state "state_1" and processing "0", automaton's state becomes "state_2".
When in state "state_1" and processing "1", automaton's state becomes "state_1".
When in state "state_2" and processing "0", automaton's state becomes "state_1".
When in state "state_2" and processing "1", automaton's state becomes "state_2".
'''
for i in transitions.items():
print(f'When in state "{i[0][0]}" and processing "{i[0][1]}", automaton\'s state becomes "{i[1]}".')
# REPLACE pass ABOVE WITH YOUR CODE
def transitions_as_dict(transitions_as_list):
'''
transitions_as_list is a list of strings of the form 'state_1,symbol:state_2'
where 'state_1' and 'state_2' are words and 'symbol' is one of the 10 digits.
We assume that there is at most one 'state_2' for given 'state_1' and 'symbol'.
>>> transitions_as_dict(['q0,0:q1', 'q1,1:q0'])
{('q0', 0): 'q1', ('q1', 1): 'q0'}
>>> transitions_as_dict(['state_1,0:state_2', 'state_1,1:state_1',\
'state_2,0:state_1', 'state_2,1:state_2'])
{('state_1', 0): 'state_2', ('state_1', 1): 'state_1', \
('state_2', 0): 'state_1', ('state_2', 1): 'state_2'}
'''
transitions = {}
# INSERT YOUR CODE HERE
for i in transitions_as_list:
s1, s2 = i.split(':')
key = (s1.split(',')[0], int(s1.split(',')[1]))
transitions[key] = s2
return transitions
def accepts(transitions, word, initial_state, accept_state):
'''
Starting in 'initial_state', if the automaton can process with 'transitions'
all symbols in 'word' and eventually reach 'accept_state', then the function
returns True; otherwise it returns False.
>>> transitions_1 = {('q0', 0): 'q1', ('q1', 1): 'q0'}
>>> accepts(transitions_1, '00', 'q0', 'q1')
False
>>> accepts(transitions_1, '2', 'q0', 'q0')
False
>>> accepts(transitions_1, '0101010', 'q0', 'q0')
False
>>> accepts(transitions_1, '01010101', 'q0', 'q0')
True
>>> not accepts(transitions_1, '01', 'q0', 'q1') and\
accepts(transitions_1, '010', 'q0', 'q1')
True
>>> transitions_2 = {('state_1', 0): 'state_2', ('state_1', 1): 'state_1',\
('state_2', 0): 'state_1', ('state_2', 1): 'state_2'}
>>> accepts(transitions_2, '011', 'state_1', 'state_1')
False
>>> accepts(transitions_2, '001110000', 'state_1', 'state_1')
True
>>> accepts(transitions_2, '1011100101', 'state_1', 'state_1')
True
>>> accepts(transitions_2, '10111000101', 'state_1', 'state_1')
False
'''
current_state = initial_state
for w in word:
try:
current_state = transitions[(current_state, int(w))]
except KeyError:
return False
if current_state == accept_state:
return True
else:
return False
# REPLACE pass ABOVE WITH YOUR CODE
if __name__ == '__main__':
import doctest
doctest.testmod()
Challenges
1.
Temperature conversion tables
Study the program fahrenheit_to_celsius.py and run it in the Terminal window, executing "python3 fahrenheit_to_celsius.py". Then complete the program celsius_to_fahrenheit.py that displays a conversion table from Celsius degrees to Fahrenheit degrees, with the former ranging from 0 to 100 in steps of 10; run it and check your solution with the Run and Submit buttons, respectively.
See commands_and_expected_outputs.txt for expected output.
华氏度转温度公式记一下C= 5/9×([F-32]
'''python---已给
Prints out a conversion table of temperatures from Fahrenheit to Celsius degrees,
with the former ranging from 0 to 300 in steps of 20.
'''
min_temperature = 0
max_temperature = 300
step = 20
# \t: A tab
print('Fahrenheit\tCelsius')
# We let fahrenheit take the values
# - min_temperature
# - min_temperature + step
# - min_temperature + 2 * step
# - min_temperature + 3 * step
# ...
# up to the largest value smaller than max_temperature + step
for fahrenheit in range(min_temperature, max_temperature + step, step):
celsius = 5 * (fahrenheit - 32) / 9
# {:10d} or {:10}: fahrenheit as a decimal number in a field of width 10
# {:7.1f}: celsius as a floating point number in a field of width 7
# with 1 digit after the decimal point
print(f'{fahrenheit:10}\t{celsius:7.1f}')
# {:10d} or {:10}: fahrenheit as a decimal number in a field of width 10
# {:7.1f}: celsius as a floating point number in a field of width 7
# with 1 digit after the decimal point
'''python---我
Prints out a conversion table of temperatures from Celsius to Fahrenheit degrees,
the former ranging from 0 to 100 in steps of 10.
'''
# Insert your code here
min_temperature = 0
max_temperature = 100
step = 10
# \t: A tab
print('Celsius\tFahrenheit')
for celsius in range(min_temperature, max_temperature + step, step):
fahrenheit = 9 * celsius / 5 +32
print(f'{celsius:7}\t{fahrenheit:10.0f}')
Max element and span in a list
Study the program max_in_list.py and run it in the Terminal window, executing "python3 max_in_list.py". Then complete the program span.py that prompts the user for a seed for the random number generator, and for a strictly positive number, nb_of_elements, generates a list of nb_of_elements random integers between 0 and 99, prints out the list, computes the difference between the largest and smallest values in the list without using the builtins min() and max(), prints it out, and check that the result is correct using the builtins; run it and check your solution with the Run and Submit buttons, respectively.
See commands_and_expected_outputs.txt for expected outputs and sample inputs.
已给
try:
arg_for_seed = int(input('Input a seed for the random number generator: '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
try:
nb_of_elements = int(input('How many elements do you want to generate? '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 0:
print('Input should be strictly positive, giving up.')
sys.exit()
# Generates a list of nb_of_elements random integers between 0 and 99.
seed(arg_for_seed)
L = [randint(0, 99) for _ in range(nb_of_elements)]
# Prints out the list, computes the maximum element of the list, and prints it out.
print('\nThe list is:', L)
max_element = 0
for e in L:
if e > max_element:
max_element = e
print('\nThe maximum number in this list is:', max_element)
# Of course there is an easier way; as so often, Python just makes it too easy!
print('Confirming with builtin operation:', max(L))
'''我
Prompts the user for a seed for the random number generator,
and for a strictly positive number, nb_of_elements.
Generates a list of nb_of_elements random integers between 0 and 99, prints out the list,
computes the difference between the largest and smallest values in the list without using
the builtins min() and max(), prints it out, and check that the result is correct using
the builtins.
'''
from random import seed, randint
import sys
try:
arg_for_seed = int(input('Input a seed for the random number generator: '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
try:
nb_of_elements = int(input('How many elements do you want to generate? '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 0:
print('Input should be strictly positive, giving up.')
sys.exit()
# Generates a list of nb_of_elements random integers between 0 and 99.
seed(arg_for_seed)
L = [randint(0, 99) for _ in range(nb_of_elements)]
# Prints out the list, computes the maximum element of the list, and prints it out.
print('\nThe list is:', L)
max_element = 0
min_element = 99
for e in L:
if e > max_element:
max_element = e
if e < min_element:
min_element = e
print('\nThe maximum difference between largest and smallest values in this list is:', max_element-min_element)
# Of course there is an easier way; as so often, Python just makes it too easy!
print('Confirming with builtin operations:', max(L)-min(L))
1try&except ValueError的使用
try:
arg_for_seed = int(input('Input a seed for the random number generator: '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
(需导入包randint)
randint(0, 99)
Classifying elements in a list
The operators /, // and % are used for floating point division, integer division, and remainder, respectively. Study the program modulo_4.py and run it in the Terminal window, executing "python3 modulo_4.py". Then complete program intervals.py that prompts the user for a strictly positive integer, nb_of_elements, generates a list of nb_of_elements random integers between 0 and 19, prints out the list, computes the number of elements strictly less than 5, 10, 15 and 20, and prints those out; run it and check your solution with the Run and Submit buttons, respectively.
See commands_and_expected_outputs.txt for expected outputs and sample inputs.
已给
# Written by Eric Martin for COMP9021
'''
Prompts the user for a strictly positive integer, nb_of_elements,
generates a list of nb_of_elements random integers between 0 and 99, prints out the list,
computes the number of elements equal to 0, 1, 2 3 modulo 4, and prints those out.
'''
from random import seed, randrange
import sys
# Prompts the user for a seed for the random number generator,
# and for a strictly positive number, nb_of_elements.
try:
arg_for_seed = int(input('Input a seed for the random number generator: '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
try:
nb_of_elements = int(input('How many elements do you want to generate? '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 0:
print('Input should be strictly positive, giving up.')
sys.exit()
# Generates a list of nb_of_elements random integers between 0 and 99.
seed(arg_for_seed)
L = [randrange(100) for _ in range(nb_of_elements)]
print('\nThe list is:' , L)
print()
# - remainders_modulo_4[0] to record the number of elements equal to 0 modulo 4,
# - remainders_modulo_4[1] to record the number of elements equal to 1 modulo 4,
# - remainders_modulo_4[2] to record the number of elements equal to 2 modulo 4,
# - remainders_modulo_4[3] to record the number of elements equal to 3 modulo 4.
remainders_modulo_4 = [0] * 4
for e in L:
remainders_modulo_4[e % 4] += 1
for i in range(4):
if remainders_modulo_4[i] == 0:
print('There is no element', end = ' ')
elif remainders_modulo_4[i] == 1:
print('There is 1 element', end = ' ')
else:
print(f'There are {remainders_modulo_4[i]} elements', end = ' ')
print(f'equal to {i} modulo 4.')
(需导入包seed)from random import seed, randrange
seed(arg_for_seed) 一个让随机序列更加’科学‘的方法
randrange(100) for _ in range(nb_of_elements):生成后面range长度个数个随机数可以直接赋值给列表
1 数据没有完全通过
'''
Prompts the user for a strictly positive integer, nb_of_elements,
generates a list of nb_of_elements random integers between 0 and 19, prints out the list,
computes the number of elements strictly less 5, 10, 15 and 20, and prints those out.
'''
from random import seed, randrange
import sys
try:
arg_for_seed = int(input('Input a seed for the random number generator: '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
try:
nb_of_elements = int(input('How many elements do you want to generate? '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 0:
print('Input should be strictly positive, giving up.')
sys.exit()
seed(arg_for_seed)
L = [randrange(0,19) for _ in range(nb_of_elements)]
print('\nThe list is:' , L)
print()
countL5=0
count5to10=0
count10to15=0
count15to20=0
for e in L:
if e < 20:
if e < 15:
if e < 10:
if e <5:
countL5= countL5 + 1
else:
count5to10 = count5to10 + 1
else:
count10to15 = count10to15 + 1
else:
count15to20 = count15to20 + 1
if countL5 ==0:
print('There is no element between 0 and 4.')
elif countL5==1:
print('There is 1 element between 0 and 4.')
elif countL5 > 1:
print(f'There are {countL5} elements between 0 and 4.' )
if count5to10 ==0:
print('There is no element between 5 and 9.')
elif count5to10==1:
print('There is 1 element between 5 and 9.')
else:
print(f'There are {count5to10} elements between 5 and 9.' )
if count10to15 ==0:
print('There is no element between 10 and 14.')
elif count10to15==1:
print('There is 1 element between 10 and 14.')
else:
print(f'There are {count10to15} elements between 10 and 14.')
if count15to20 ==0:
print('There is no element between 15 and 19.')
elif count15to20==1:
print('There is 1 element between 15 and 19.')
else:
print(f'There are {count15to20} elements between 15 and 19.')
Statistics on numbers in a list
Complete the program mean_median_standard_deviation.py that prompts the user for a strictly positive integer, nb_of_elements, generates a list of nb_of_elements random integers between - 50 and 50, prints out the list, computes the mean, the median and the standard deviation in two ways, that is, using or not the functions from the statistics module, and prints them out.
To compute the median, the easiest way is to first sort the list with the builtin sort() method.
See commands_and_expected_outputs.txt for expected outputs and sample inputs.
'''我
Prompts the user for a strictly positive integer, nb_of_elements,
generates a list of nb_of_elements random integers between -50 and 50, prints out the list,
computes the mean, the median and the standard deviation in two ways,
that is, using or not the functions from the statistics module, and prints them out.
'''
from random import seed, randint
from math import sqrt,pow,fabs
from statistics import mean, median, pstdev
import sys
try:
arg_for_seed = int(input('Input a seed for the random number generator: '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
try:
nb_of_elements = int(input('How many elements do you want to generate? '))
except ValueError:
print('Input is not an integer, giving up.')
sys.exit()
if nb_of_elements <= 0:
print('Input should be strictly positive, giving up.')
sys.exit()
# Generates a list of nb_of_elements random integers between 0 and 99.
seed(arg_for_seed)
L = [randint(-50,50) for _ in range(nb_of_elements)]
print('\nThe list is:' , L)
print()
'''
The mean is -1.00.
The median is -1.00.
The standard deviation is 0.00.
'''
sum=0
m=0
for x in L:
sum=x+sum
m=sum/nb_of_elements
print(f'The mean is {m:.2f}.')
x=int(nb_of_elements/2)
L.sort(reverse = False)
if(nb_of_elements%2==0):
print(f'The median is {(L[x-1]+L[x])/2:.2f}.')
else:
print(f'The median is {L[x]:.2f}.')
sum=0
for x in L:
sum=sum+pow(x-m,2)
print(f'The standard deviation is {fabs(sqrt(sum/nb_of_elements)):.2f}.')
print()
print(f'Confirming with functions from the statistics module:')
print(f'The mean is {mean(L):.2f}.')
print(f'The median is {median(L):.2f}.')
print(f'The standard deviation is {pstdev(L):.2f}.')
网友评论