NB 1
NB 1
Suppose you now want to know whether a certain value exists in this list. A simple way to do that in Python is as follows.
This method works fine and is reasonably fast on small lists. However, if the list is very large, this method can be wasteful, computationally spe
That's because it does not take advantage of the fact that A is already ordered. In such a case, it should be easier to determine whether the ele
(How?)
Exercise 0 (3 + 7 == 10 points). Write a function, ordered_contains(S, x), that takes an already sorted list, S, as input, and determines w
contains x. But there is one more condition: your method must be at least ten times faster than contains() for "large" lists!
In particular, there are two test codes for this exercise. The first one checks that your procedure does, indeed, return the correct result by comp
output to contains(), which we will assume is correct. Correctness is worth three (3) points of partial credit out of ten (10). The second test c
whether your implementation is faster than contains() for a relatively large, but ordered, list. If your implementation is slower for smaller lists
Hint. If you can find a standard Python library routine to help you, by all means, use it!
Try
# https://en.wikipedia.org/wiki/Binary_search_algorithm
#
# However, for a variety of implementation reasons, this
solution of
# implementation is unlikely to beat Version 0, above.
# Any ideas why not? the binary
#
THRESHOLD__1 = 128 # An "engineering" constant - use to tune speed
def ordered_contains__1(S, x):
search
if len(S) <= THRESHOLD__1:
return contains(S, x)
midpoint = int(len(S) / 2)
if x < S[midpoint]:
return ordered_contains__1(S[:midpoint], x)
if x > S[midpoint]:
return ordered_contains__1(S[midpoint+1:], x)
return True # Found it!
S = gen_sorted_list(13, 100)
print("Checking your code on this input: S = {}".format(S))
check_case(S, S[0])
check_case(S, S[0]-1)
check_case(S, S[-1])
check_case(S, S[-1]+1)
print("\nTiming `contains()`...")
x = randint(-100, 100)
%timeit contains(S, x)
print("\nTiming `ordered_contains()`...")
%timeit ordered_contains(S, x)
N_MIN = 1000000
N_MAX = 2*N_MIN
R_MAX = max(10*N_MAX, 1000000000)
n = randint(N_MIN, N_MAX)
print("Generating a list of size n={}...".format(n))
print("\nTiming `contains()`...")
t_baseline = %timeit -o contains(S_large, x)
print("\nTiming `ordered_contains()`...")
t_better = %timeit -o ordered_contains(S_large, x)
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Problem 1
This problem has 2 exercises, worth a total of 10 points.
Exercise 0 (2 points). Write a function, transform that takes a string and performs the following operations to it: converts the string to lower c
only and removes any spaces in the string.
In this problem, "space" means only the space character, not other forms of whitespace, such as tabs and newlines.
For example:
In [ ]: def transform(k):
### BEGIN SOLUTION
return (k.lower().replace(" ", ""))
###END SOLUTION
print(transform('Hello, World!'))
print("\n(Passed!)")
Exercise 1 (3 + 5 == 8 points). Write a function, remove_dups(S) that takes a list S and removes multiple occurrences of any element. The fu
a list with only one occurrence of each element.
For example, remove_dups(['cat', 'dog', 'sheep', 'dog']) would return ['cat', 'dog', 'sheep'].
This exercise has two test cells. The first checks that your implementation returns the right answer. The second tests your solution on a large lis
credit, your implementation must take less than a certain amount of time!
In [ ]: def remove_dups(S):
###BEGIN SOLUTION
return remove_dups_1(S)
your_listA = remove_dups(listA)
assert len(remove_dups(listA)) == 3 and set(your_listA) == {'cat', 'dog', 'sheep'}
your_listB = remove_dups(listB)
assert len(remove_dups(listB)) == 5 and set(your_listB) == set(range(1,6))
print("\n(Passed!)")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Each new term in the Fibonacci sequence is generated by adding the previous two terms. By starting with 1 and 1, the list of terms not exceed
That is, the next term, 55+89=144, exceeds 100, so we would stop at 89.
Your computational task is to calculate the sum of the even-valued terms that are less than a given number. In this example, if the given numb
then the sum of even-valued terms would be 2+8+34=44.
Exercise 0 (10 points). Write a function, even_fib_sum(n), that takes a specific value, n, as input, and returns the sum of the even-valued Fi
sequence terms that do not exceed n.
For example:
even_fib_sum(100) = 44 ( = 2 + 8 + 34)
even_fib_sum(200) = 188 ( = 2 + 8 + 34 + 144)
Keep in mind that we are not interested in the nth term in the sequence, but simply the Fibonacci numbers that are strictly less than n.
In [ ]: def even_fib_sum(n):
# You may assume that maximum > 0
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Problem 3
This problem has a single exercise worth a total of ten (10) points.
Exercise 0 (10 points). Define a function, UniqueCharacters(s), that given a string s returns a tuple of two elements: the first element is the
unique alphabetic characters in the string and the second is the number of unique digits (base-10) in the string.
For example, the string 'ewwwffioj122434' should output the following tuple: (6, 4). The 6 occurs because there are 6 unique letters ('e
'i', 'o', and 'j') and 4 because there are 4 unique numbers ('1', '2', '3', '4'). Special characters may appear in the string but do not co
or number.
In [ ]: def UniqueCharacters(s):
### BEGIN SOLUTION
return (len(set([i for i in s if i.isalpha()])),
len(set([i for i in s if i.isdigit()])))
### END SOLUTION
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Problem 4
This problem consists of a single exercise worth ten (10) points.
Exercise 0 (10 points). Complete the function flatten(L), which takes a "complex list," L, as input and returns a "flat" copy.
By complex, we mean that the input list L consists of arbitrarily nested lists of strings and integers. For instance, here is a complex list:
Observe that there are strings and integers, but that these may be embedded within lists inside lists inside lists...
Given such a list, your computational task is to extract all the strings and integers, and return them in a single flattened list. For example:
In your flattened version, the strings and integers must appear in the same "left-to-right" order as they do in the original list. For instance, if you
the square brackets in the definition of L above, then observe that 'cat' appears to the right of 'a', and 2 appears to the right of 'cat', and
the right of 2, etc.
Hint: One reasonable approach to this problem is to use recursion, that is, the idea of a function that calls itself to solve subproblems. S
"Recursive programs" at the Wikipedia page on Recursion as it is used in computer science
(https://en.wikipedia.org/wiki/Recursion_%28computer_science%29#Recursive_programs).
In [ ]: def flatten(L):
assert type(L) is list
### BEGIN SOLUTION
flatList = []
for i in L:
if type(i) is not list:
flatList
flatList += [i]
i My solution: with the unpacking operator: *
flatList += [i]
else:
flatList += flatten(i)
return flatList
### END SOLUTION
L = [['a',['cat'],2],[[[3]],'dog'],4,5]
FL = flatten(L)
True_L = ['a', 'cat', 2, 3, 'dog', 4, 5]
print("Your result: \n{}".format(FL))
print('True result: \n{}'.format(True_L))
assert type(FL) is list and FL == ['a', 'cat', 2, 3, 'dog', 4, 5]
print("\n")
L = [[1,[['b'],2],'t',[[3]],'snow'],'x',['hat',7]]
FL = flatten(L)
True_L = [1, 'b', 2, 't', 3, 'snow', 'x', 'hat', 7]
print("Your result: \n{}".format(FL))
print('True result: \n{}'.format(True_L))
assert type(FL) is list and FL == [1, 'b', 2, 't', 3, 'snow', 'x', 'hat', 7]
print("\n")
L = ['x',1,'z']
FL = flatten(L)
True_L = ['x',1,'z']
print("Your result: \n{}".format(FL))
print('True result: \n{}'.format(True_L))
assert type(FL) is list and FL == ['x',1,'z']
print("\n")
L = []
FL = flatten(L)
True_L = []
print("Your result: \n{}".format(FL))
print('True result: \n{}'.format(True_L))
assert type(FL) is list and FL == []
print("\n(Passed!)")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
In [ ]:
Exercise 0 (10 points). Given a list of integers, find the number of pairs that are consecutive.
the pairs that can be formed from the given list are (1, 2), (1, 5), (1, 8), (2, 5), (2, 8), (5, 8);
the only pair that has consecutive integers is (1, 2) and hence the value to be returned is one (1).
If elements in the list are repeated, they should be treated as members of a distinct pair. For instance, if the list were [1, 1, 1, 2, 2, 5, 8
there are three ways to choose 1 and two ways to choose 2, or a total of ways to choose the pair (1, 2), so that the answer would
be 6.
The first test case below tests for the correctness of the solution whereas the second one tests for the efficiency of the solution. That is, it shou
long for the second case to pass! (To get "full credit," try to find a method that takes less than two (2) seconds on the test input of the second t
Application note. Although this might seem like a toy problem to solve, its application forms the basis of pattern recognition. For examp
suppose you are trying to discover the buying pattern of products in a supermarket and want to figure out if placing two products next
each other impact each others' sales. (Does placing milk next to cereal drive both their sales upwards? Or if placing Muesli next to Cer
lead to additional Muesli sales, since people who buy cereal would anyway buy Milk even if it is in the other corner of the store?)
In mapping that concrete placement problem into this abstract analysis problem, you can think of the list of numbers as the shelf numb
products in a receipt and you are trying to find out the number of cases where the products were in adjacent shelves
products in a receipt, and you are trying to find out the number of cases where the products were in adjacent shelves.
def test_code1():
L1=[1,2,3,4,5,6,7,8,9]
L2=[1,1,1,2,2,3,4,10]
L3=[1,4,7,9]
L4=[]
assert count_pairs(L1)==8, "Test Case L1 failed"
assert count_pairs(L2)==9, "Test Case L2 failed"
assert count_pairs(L3)==0, "Test Case L3 failed"
assert count_pairs(L4)==0, "Test Case L4 failed"
print("\n(Passed!)")
test_code1()
# This test case will test the efficieny of your solution. If it takes too long (>2 min) to run
# please try improving your method.
import numpy as np
biglist = list(np.random.choice(100, 5000, replace=True))
print("\nChecking speed...")
timing = %timeit -o count_pairs(biglist)
assert timing.average < 2.0
print("(Passed timing check!)")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Problem 6: Anagram-orama
This problem consists of a single exercise worth ten (10) points.
The code below imports a list of 10,000 common words in the English language and saves it as "commonwordslist".
In [ ]: commonwordslist = ['aa', 'aaa', 'aaron', 'ab', 'abandoned', 'abc', 'aberdeen', 'abilities', 'abi
le', 'aboriginal', 'abortion', 'about', 'above', 'abraham', 'abroad', 'abs', 'absence', 'absent
le', 'whom', 'whore', 'whose', 'why', 'wi', 'wichita', 'wicked', 'wide', 'widely', 'wider', 'wid
'widespread', 'width', 'wife', 'wifi', 'wiki', 'wikipedia', 'wild', 'wilderness', 'wildlife', 'w
ll', 'william', 'williams', 'willing', 'willow', 'wilson', 'win', 'wind', 'window', 'windows',
indsor', 'wine', 'wines', 'wing', 'wings', 'winner', 'winners', 'winning', 'wins', 'winston', 'w
ire', 'wired', 'wireless', 'wires', 'wiring', 'wisconsin', 'wisdom', 'wise', 'wish', 'wishes',
'wit', 'witch', 'with', 'withdrawal', 'within', 'without', 'witness', 'witnesses', 'wives', 'wiz
, 'wma', 'wn', 'wolf', 'woman', 'women', 'womens', 'won', 'wonder', 'wonderful', 'wondering', 'w
den', 'woods', 'wool', 'worcester', 'word', 'wordpress', 'words', 'work', 'worked', 'worker', 'w
'workflow', 'workforce', 'working', 'workout', 'workplace', 'works', 'workshop', 'workshops', 'w
n', 'world', 'worldcat', 'worlds', 'worldsex', 'worldwide', 'worm', 'worn', 'worried', 'worry',
'worship', 'worst', 'worth', 'worthy', 'would', 'wound', 'wow', 'wp', 'wr', 'wrap', 'wrapped',
'wrestling', 'wright', 'wrist', 'write', 'writer', 'writers', 'writes', 'writing', 'writings',
'wrong', 'wrote', 'ws', 'wt', 'wto', 'wu', 'wv', 'ww', 'www', 'wx', 'wy', 'wyoming', 'x', 'xanax
'xerox', 'xhtml', 'xi', 'xl', 'xml', 'xnxx', 'xp', 'xx', 'xxx', 'y', 'ya', 'yacht', 'yahoo', 'ya
ha', 'yang', 'yard', 'yards', 'yarn', 'ye', 'yea', 'yeah', 'year', 'yearly', 'years', 'yeast',
'yemen', 'yen', 'yes', 'yesterday', 'yet', 'yield', 'yields', 'yn', 'yo', 'yoga', 'york', 'yorks
u', 'young', 'younger', 'your', 'yours', 'yourself', 'youth', 'yr', 'yrs', 'yu', 'yugoslavia',
'z', 'za', 'zambia', 'zdnet', 'zealand', 'zen', 'zero', 'zimbabwe', 'zinc', 'zip', 'zoloft', 'zo
s', 'zoning', 'zoo', 'zoom', 'zoophilia', 'zope', 'zshops', 'zu', 'zum', 'zus', "'"]
Exercise 0 (10 points). Your task is to write a function that takes any string as an input, and returns a list of any anagrams---that is, words mad
same letters---for that string that appear on the common words list.
If the string happens to be a word from the common words list, it should appear in the output. So, for instance, if the input were the string "wei
output should be ['weird', 'wider', 'wired']. If there are no anagrams for the given input, your function should return an empty list.
Bonus challenge. Can you augment your code to find the longest anagram pair in the common words list? What about the longest ana
triple, i.e., three words with exactly the same letters?
In [ ]: def anagram_check(word):
assert type(word) is str
### BEGIN SOLUTION
from collections import defaultdict
word_dic = defaultdict(list)
for aword in commonwordslist:
word_dic[''.join(sorted(aword))].append(aword)
sorted_word = ''.join(sorted(word))
return word_dic[sorted_word]
### END SOLUTION
print("\n(Passed!)")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Mysolution
Problem 7
Letter frequencies. This problem has three (3) exercises worth a total of ten (10) points.
Letter frequency in text has been studied in cryptoanalysis, in particular frequency analysis. Linguists use letter frequency analysis as a rudimen
technique for language identification, where it's particularly effective as an indicator of whether an unknown writing system is alphabetic, syllab
ideographic.
Primarily, three different ways exist for letter frequency analysis. Each way generally results in very different charts for common letters. Based o
text, the first method is to count letter frequency in root words of a dictionary. The second way is to include all word variants when counting, su
going and goes and not just the root word go. Such a system results in letters like "s" appearing much more frequently. The last variant is to co
based on their frequency in the actual text that is being studied.
Exercise 0 (2 points). First, given a string input, define a function preprocess that returns a string with non-alphabetic characters removed an
alphabets converted into a lower case.
For example, 'We are coding letter Frequency! Yay!" would be transformed into "wearecodingletterfrequencyyay"
solution islonger
my
In [ ]: def preprocess(S):
### BEGIN SOLUTION
s = ''.join([c.lower() for c in S if c.isalpha()])
return s
### END SOLUTION
def generate_str(n):
random_str = ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.
tring.punctuation) for _ in range(n))
return random_str
def check_preprocess_str(n):
random_str = generate_str(n)
print("Input String: ",random_str)
assert preprocess('random_str').islower() == True
assert preprocess(random_str).isalpha() == True
print("|----Your function seems to work correct for the string----|"+"\n")
check_preprocess_str(N_str)
check_preprocess_str(N_str)
check_preprocess_str(N_str)
print("\n(Passed)!")
Exercise 1 (4 points). With the necessary pre-processing complete, the next step is to write a function count_letters(S) to count the numb
occurrences of each letter in the alphabet.
You can assume that only letters will be present in the input string. It should output a dictionary and if any alphabet (a-z) is missing in the input
should still be a part of the output dictionary and its corresponding value should be equal to zero.
N_processed_str = 100
def generate_processed_str(n):
random_processed_str = ''.join(random.choice(string.ascii_lowercase) for _ in range(n))
return random_processed_str
def check_count_letters(S):
print("Input String: ",S)
random_char = chr(random.randint(97,122))
print("Character frequency evaluated for: ", random_char)
if(random_char in S):
assert count_letters(S)[random_char] == collections.Counter(S)[random_char]
print("|----Your function seems to return correct freq for the char----|"+"\n")
else:
assert count_letters(S)[random_char] == 0
print("|----Your function seems to return correct freq for the char----|"+"\n")
check_count_letters(generate_processed_str(N_processed_str))
check_count_letters(generate_processed_str(N_processed_str))
check_count_letters(generate_processed_str(N_processed_str))
print("\n(Passed)!")
Exercise 2 (4 points). The next step is to sort the distribution of a dictionary containing all the letters in the alphabet as keys and number of occ
text as associated value.
Sorting should be first done in decreasing order by occurrence count and for two elements with same count, the order should be alphabetic. Th
find_top_letter(d) should return the 1st character in the order.
In [ ]: def find_top_letter(d):
### BEGIN SOLUTION
My solution
t = [(l, o) for l,o in d.items()]
t.sort(key = lambda x: (x[1]*-1, x[0]))
return t[:1][0][0]
### END SOLUTION
def create_random_dict():
max_char_value = random.randint(5, 20)
random_dict = {c:random.randint(0,max_char_value-1) for c in string.ascii_lowercase}
random_letter1, random_letter2 = random.sample(string.ascii_lowercase, 2)
random_dict[random_letter1], random_dict[random_letter2] = max_char_value, max_char_value
if(random_letter1 < random_letter2):
return random_letter1, random_dict
else:
return random_letter2, random_dict
def check_top_letter():
top_letter, random_dict = create_random_dict()
user_letter = find_top_letter(random_dict)
assert user_letter == top_letter
print("Input Dictionary: ", random_dict)
print("Your function correctly returned most frequent letter: {} \n".format(user_letter))
check_top_letter()
check_top_letter()
check_top_letter()
print("\n(Passed)!")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Problem 8
This problem has three (3) exercises worth a total of ten (10) points.
Invert a dictionary. Suppose a group of student TAs have been asked to monitor the Piazza forums for your CSE6040x course. The assignmen
follows.
Exercise 0 (5 points). Write a function, invert_dict(d), that "inverts" a given dictionary d. The output should be another dictionary such tha
the TA names and their corresponding values should be a list which stores the days assigned to them.
For example, one of the keys of the returned dictionary should be "Jeh" with its corresponding list as ["Monday", "Thursday", "Sunday
import random
TA_list = ["Rachel", "Yandi", "Ben", "Jeh", "Evan", "Chinmay", "Shishir", "Raghav", "Samuel", "M
# Your solution
inv_dict = invert_dict(assignments)
random_TA = random.sample(TA_list, 5)
for TA in random_TA:
assigned_days = inv_dict[TA]
for days in assigned_days:
assert TA in assignments[days], "Incorrect inversion for TA {}".format(TA)
print("\n(Passed!)")
Suppose a pilot flies from one city to the next. He makes 7 such trips, which are stored in the list shown in the next cell. The first entry of each t
the origin, and the second denotes the destination. Also assume that the next flight a pilot makes must originate from the destination of her pre
Your task in this exercise is to write a function that finds the route followed by the pilot, given her first port of origin.
First, let segments be an unordered list of segments that the pilot flew.
In [ ]: segments = [("JFK", "DEN"), ("LAX", "ORD"), ("DEN", "SFO"), ("LAS", "LAX"), ("ORD", "ATL"), ("AT
), ("SFO", "LAS")]
Next, write a function find_dest(segs, origin) that returns the next destination of the pilot given one port of origin and an unordered list
segments. Example, if segs == segments as defined above, then for 'LAX', your function should return 'ORD' because there is the tuple, (
"ORD"), in segs.
You may assume that origin appears only once in the list of segments, segs.
Exercise 3 (3 points). Now write a function get route(segs, origin) that traces the complete itinerary of the pilot, given her first port of o
Exercise 3 (3 points). Now write a function get_route(segs, origin) that traces the complete itinerary of the pilot, given her first port of o
that the destination for a flight is the same as the origin for the next flight. The itinerary is completed when he arrives back at the starting port o
example, if the starting port is "JFK", your function should return the list: ["JFK", "DEN", "SFO", "LAS", "LAX", "ORD", "ATL"].
print("\n(Passed.)")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Problem 9
This problem consists of a single exercise worth ten (10) points.
Exercise 0 (10 points): Write a funtion, digitize(n), that, given a postive number n, returns the digits of n as the integer elements of a list in
order.
For example:
In [ ]: # Test_cell: test_digitize
assert digitize(1345328) == [8, 2, 3, 5, 4, 3, 1], 'Wrong output. Make sure your function return
ts in reverse order'
print("\n(Passed!)")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
Problem 10: Tic-Tac-Toe!
The objective of this exercise is to check whether you can declare a winner based on the current state of a Tic-Tac-Toe (TTT) game
(https://en.wikipedia.org/wiki/Tic-tac-toe (https://en.wikipedia.org/wiki/Tic-tac-toe)).
row0 0 0 -1
row1 1 -1 1
row2 -1 1 0
[[0,0,-1],
[1,-1,1],
[-1,1,0]]
Exercise 0 Write a function called check_ttt(game) that takes a list of 3 lists representing each row of a game's state and determines wheth
is a winner. In particular, it should return one of the following strings:
For example,
since there are three crosses (-1 values) along one of the diagonals of this board state.
You may assume that the input is a valid game state, i.e., a list representing a grid with all cells having values in and at most o
winner.
In [ ]: def check_ttt(game):
# Check that the input is valid
assert type(game) == list
assert all([type(row) == list for row in game])
assert all([[elem in [0,1,-1] for elem in row] for row in game])
# test 1
test_game1 = [[0,0,0] for elem in range(3)]
assert check_ttt(test_game1) == "No Result"
# test 2
test_game2 = [[1,1,1],[-1,-1,0],[0,0,0]]
assert check_ttt(test_game2) == "Circles (+1) Win"
# test 3
test_game3 = [[0,0,-1],[1,-1,1],[-1,1,0]]
assert check_ttt(test_game3) == "Crosses (-1) Win"
# test 4
test game4 [[0 0 1] [1 1 1] [1 1 1]]
test_game4 = [[0,0,-1],[1,-1,-1],[1,1,-1]]
assert check_ttt(test_game4) == "Crosses (-1) Win"
print("\n(Passed!)")
def test_check_ttt():
test_game_random = [[0,0,0] for elem in range(3)]
boxes_filled = random.randint(0,8)
num_circles = int(boxes_filled/2)
circle_ind = random.sample(range(9),num_circles)
cross_ind = random.sample([elem for elem in range(9) if elem not in circle_ind],(boxes_fille
les))
your_answer = check_ttt(test_game_random)
if 3 in np.sum(test_game_random,axis=0) & -3 in np.sum(test_game_random,axis=0): pass
elif 3 in np.sum(test_game_random,axis=1) & -3 in np.sum(test_game_random,axis=1): pass
elif 3 in np.sum(test_game_random,axis=0) & -3 in np.sum(test_game_random,axis=1): pass
elif 3 in np.sum(test_game_random,axis=0) & -3 in np.sum(test_game_random,axis=1): pass
elif 3 in np.sum(test_game_random,axis=0): assert your_answer == "Circles (+1) Win"
elif -3 in np.sum(test_game_random,axis=0): assert your_answer == "Crosses (-1) Win"
elif 3 in np.sum(test_game_random,axis=1): assert your_answer == "Circles (+1) Win"
elif -3 in np.sum(test_game_random,axis=1): assert your_answer == "Crosses (-1) Win"
elif np.trace(test_game_random) == 3: assert your_answer == "Circles (+1) Win"
elif np.trace(test_game_random) == -3: assert your_answer == "Crosses (-1) Win"
elif np.flipud(test_game_random).trace() == 3: assert your_answer == "Circles (+1) Win"
elif np.flipud(test_game_random).trace() == -3: assert your_answer == "Crosses (-1) Win"
else: assert check_ttt(test_game_random) == "No Result"
print("\n(Passed!)")
Fin! You've reached the end of this problem. Don't forget to restart the kernel and run the entire notebook from top-to-bottom to make sure you
everything correctly. If that is working, try submitting this problem. (Recall that you must submit and pass the autograder to get credit for your w
My attempt at sowing
or transpose s test the rows