Empire of Code Python solutions
[Python], [code], [edu], [solutions]Here is a gist with my Empire of Code solutions in Python programming language:
To check an automated sieve for ore we use a variety of sample sets to find the smallest and the largest stones. The difference between these values is then used to decide if the sample is worth checking.
You are given an array of numbers from which you must find the difference between the maximum and minimum elements. Your function should be able to handle an undefined amount of arguments. For an empty argument list, the function should return 0
.
Floating-point numbers are represented in computer hardware as base 2
(binary) fractions, since this is the case, we should check that the result is within 0.001
precision.
An arbitrary number of arguments as numbers.
The difference between the maximum and minimum as a number.
most_difference(1, 2, 3) == 2
most_difference(5, -5) == 10
most_difference(10.2, -2.2, 0, 1.1, 0.5) == 12.4
most_difference() == 0
0 ≤ |arguments| ≤ 20
The important concept to learn from this mission is about passing an undefined amount of arguments to functions.
def most_difference(*args): | |
if args: | |
return max(args) - min(args) | |
else: | |
return 0 |
def simple_areas(*args): | |
if len(args) == 1: | |
return 3.14159265*(args[0]/2)**2 | |
elif len(args) == 2: | |
return args[0]*args[1] | |
elif len(args) == 3: | |
p = (args[0]+args[1]+args[2])/2 | |
return (p*(p-args[0])*(p-args[1])*(p-args[2]))**0.5 | |
else: | |
return 0 |
def check_line(line): | |
if len(line) < 2: | |
return True | |
elif len(line) == 2: | |
if line[0] == line[1]: | |
return False | |
else: | |
return True | |
else: | |
res = True | |
for i in range(len(line)-1): | |
if line[i] == line[i+1]: | |
res = False | |
break | |
return res |
def fizz_buzz(number): | |
res = [] | |
if number % 3 == 0: | |
res.append('Fizz') | |
if number % 5 == 0: | |
res.append('Buzz') | |
if res: | |
return ' '.join(res) | |
return str(number) |
If you have 50 different plug types, appliances wouldn’t be available and would be very expensive. But once an electric outlet becomes standardized, many companies can design appliances, and competition ensues, creating variety and better prices for consumers.
You are given a non-empty list of integers (X). For this task, you should return a list consisting of only the non-unique elements in this list. To do so you will need to remove all unique elements (elements which are contained in a given list only once). When solving this task, do not change the order of the list. Example: [1, 2, 3, 1, 3] 1 and 3 non-unique elements so the result will be [1, 3, 1, 3].
nonUnique([1, 2, 3, 1, 3]) # [1, 3, 1, 3]
nonUnique([1, 2, 3, 4, 5]) # []
nonUnique([5, 5, 5, 5, 5]) # [5, 5, 5, 5, 5]
nonUnique([10, 9, 10, 10, 9, 8]) # [10, 9, 10, 10, 9]
Rank 2:
An array can contain Latin letters. Letters are counted as case
insensitive, so "a" == "A"
, so in ["d", "D", "A"]
only one
unique element - "A"
.
Precondition Rank 2
data contains only numbers or letters (one symbol string).
This mission will help you to understand how to use manipulate arrays, giving you a foundation for solving more complex tasks. The concept can be easily generalized for real world tasks. For example; it allows you to clarify data by removing low frequency elements (noise).
def non_unique(data): return [e for e in data if data.count(e) > 1] |
def count_ingots(report): | |
import string | |
m = [] | |
for x in string.ascii_uppercase: | |
for y in range(1,10): | |
m.append("%s%d" % (x, y)) | |
c = 0 | |
for i in report.split(","): | |
c += (m.index(i)+1) | |
return c |
Sometimes the robots mix up their coordinates and use other Numeral systems. Let's try to sort this out and see what could be going on.
You are given a positive number as a string along with the radix for it. Your function should convert it into decimal form. The radix is less than 37 and greater than 1. The task uses digits and the letters A-Z for the strings.
Watch out for cases when the number cannot be converted. For example: "1A" cannot be converted with radix 9. For these cases your function should return -1.
Two arguments. A number as string and a radix as an integer.
The converted number as an integer.
convert("AF", 16) == 175
convert("101", 2) == 5
convert("101", 5) == 26
convert("Z", 36) == 35
convert("AB", 10) == -1
re.match("\A[A-Z0-9]\Z", str_number)
0 < len(str_number) <= 10
2 <= radix <= 36
Here you will learn how to work with the various numeral systems and handle exceptions.
def convert(str_number, radix): | |
try: | |
return int(str_number, radix) | |
except ValueError: | |
return -1 |
def count_units(number): | |
return sum(map(int, list(bin(number)[2:]))) |
def even_last(array): | |
if array: | |
return sum(array[::2]) * array[-1] | |
return 0 |
def check_pangram(text): | |
return len({i.lower() for i in text if 'a' <= i.lower() <= 'z'}) == 26 |
We need an accurate census of our troops as this data is vital to our security in the region. To get started, let's make sure that our census takers are up on their statistics skills.
A median is a numerical value separating the upper half of a sorted array of numbers from the lower half. In a list where there are an odd number of entities, the median is the number found in the middle of the array. If the array contains an even number of entities, then there is no single middle value, instead the median becomes the average of the two numbers found in the middle.
For this mission, you are given a non-empty array of natural numbers (X). With it, you must separate the upper half of the numbers from the lower half and find the median.
Input: An array as a list or a tuple of integers.
Output: The median as a float or an integer.
median([1, 2, 3, 4, 5]) == 3
median([3, 1, 2, 5, 3]) == 3
median([1, 300, 2, 200, 1]) == 2
median((3, 6, 20, 99, 10, 15)) == 12.5
1 < |data| ≤ 1000
How it is used:
The median has usage for Statistics and Probability theory, it has especially significant value for skewed distribution. Here's an example: we want to know the average income of people from a set of data and 100 people earn $100 in month while 10 people earn $1,000,000. If we average it out we get $91,000. This is weird value and does nothing to show us the real picture. In this case the median would give to us more useful value and a better picture. The Article at Wikipedia.
def median(data): | |
data.sort() | |
l = len(data) | |
if l%2 == 1: | |
return data[l//2] | |
else: | |
return (data[l//2] + data[l//2-1])/2 |
"Where does a wise man hide a leaf? In the forest. But what does he do if there is no forest? ... He grows a forest to hide it in."
-- Gilbert Keith Chesterton
Have you ever tried to send a secret message to someone without using the encrypted channel? You could conceivably use the public communication channels to tell your secret. Even if someone finds your message, it’s easy to just brush them off and tell them it's paranoia or some bogus conspiracy. That's why we're goingt to try and use this method for squad communication.
You are given a chunk of text. Gather all of the capital letters in one word in the order that they appear in the text.
For example: text = "How are you? Eh, ok. Low or Lower? Ohhh.", if we collect all of the capital letters, we get the message "HELLO".
A text as a string.
The secret message as a string or an empty string.
findMessage("How are you? Eh, ok. Low or Lower? Ohhh.") == "HELLO"
findMessage("hello world!") == ""
0 < |text| ≤ 1000
This type of communication has been used to send secret messages, or even tell jokes. But the skills behind it show you how to find specific types of information or patterns hidden within larger chunks of data that would be difficult to find by hand.
import re | |
def find_message(text): | |
return ''.join(re.findall('[A-Z]', text)) |
You are given a string with words and numbers separated by whitespaces (one space). The words contains only letters. You should check if the string contains three words in succession. For example, the string "start 5 one two three 7 end" contains three words in succession.
A string with words.
The answer as a boolean.
threeWords("Hello World hello") == True
threeWords("He is 123 man") == False
threeWords("1 2 3 4") == False
threeWords("bla bla bla bla") == True
threeWords("Hi") == False
The input contains words and/or numbers. There are no mixed words (letters and digits combined).
0 < |words| < 100
This teaches you how to work with strings and introduces some useful functions.
def three_words(words): | |
a = words.split() | |
c = 0 | |
for w in a: | |
if w.isdigit(): | |
c=0 | |
else: | |
c+=1 | |
if c>=3: | |
return True | |
return False; |
There is a list which contains integers or other nested lists which may contain yet more lists and integers which then… you get the idea. You should put all of the integer values into one flat list. The order should be as it was in the original list with string representation from left to right.
A nested array with arrays or integers.
The one-dimensional array with integers.
flatList([1, 2, 3]) # [1, 2, 3]
flatList([1, [2, 2, 2], 4]) # [1, 2, 2, 2, 4]
flatList([[[2]], [4, [5, 6, [6], 6, 6, 6], 7]]) # [2, 4, 5, 6, 6, 6, 6, 6, 7]
flatList([-1, [1, [-2], 1], -1]) # [-1, 1, -2, 1, -1]
depth < 10
This concept is useful for parsing and analyzing files with complex structures and the task challenges your creativity in writing short code.
def flat_list(array): | |
t = [] | |
for i in array: | |
if isinstance(i, list): | |
t = t + flat_list(i) | |
else: | |
t.append(i) | |
return t |
All of the refined ingots should be sorted by size in each lot while passing by on a conveyor. Because the conveyor is already running, our robots needs to quickly swap neighboring ingots.
You are given the size and initial order of the ingots as an array of numbers. Indexes are their position, values are their sizes. You should order this array from the smallest to the largest in size.
For each action a Robot can swap two neighboring elements. Each action should be represented as a string with two digits - indexes of the swapped elements (ex, "01" - swap 0th and 1st ingots). The result should be represented as a string that contains the sequence of actions separated by commas. If the array does not require sorting, then return an empty string.
And you can swap only N*(N-1)/2 times, where N - is a quantity of ingots.
Initial 6 ============
position 4 ========
2 ====
Swap 4 ========
0 - 1 6 ============
2 ====
Swap 4 ========
1 - 2 2 ====
6 ============
Swap 2 ====
0 - 1 4 ========
6 ============
swap_sort([6, 4, 2]) # "01,12,01"
swap_sort([1, 2, 3, 4, 5]) # ""
swap_sort([1, 2, 3, 5, 3]) # "43"
1 ≤ |array| ≤ 10
This mission will show you how to work the simplest sorting algorithms. It also models one of the game mechanics in the classic puzzle game "Tetris Attack".
def swap_sort(array): | |
result = '' | |
array = list(array) | |
for p_left in range(len(array)-1, 0, -1): | |
for index in range(p_left): | |
if array[index] > array[index + 1]: | |
array[index], array[index + 1] = array[index + 1], array[index] | |
result += str(index) + str(index + 1) + ',' | |
return result[:-1] |
Most of the facets on a crystal are triangle. Since these crystals are vital to our base, we should attempt to learn more about this shape.
You are given the lengths for each side of a triangle. You need to find all three of the angles for this triangle. If the given side lengths cannot form a triangle (or form a degenerated triangle), then you must return all angles as 0 (zero). The angles should be represented as a list of integers in ascending order. Each angle is measured in degrees and rounded to the nearest integer number using standard mathematical rounding.
The lengths of the sides of a triangle as integers.
Angles of a triangle in degrees as sorted array of integers.
angles(4, 4, 4) # [60, 60, 60]
angles(3, 4, 5) # [37, 53, 90]
angles(2, 2, 5) # [0, 0, 0]
0 < a ≤ 1000
0 < b ≤ 1000
0 < c ≤ 1000
This is a classical geometry problem. With this concept you can measure an angle without the need for a protractor for use in fields such as topography or architecture.
import math | |
def angles(a, b, c): | |
a,b,c = sorted([a,b,c]) | |
if c >= b+a: | |
return [0]*3 | |
else: | |
return [round(x) for x in sorted([ math.degrees(math.acos( (a*a + b*b - c*c)/(2*a*b)) ), | |
math.degrees(math.acos( (a*a - b*b + c*c)/(2*a*c)) ), | |
math.degrees(math.acos( (-a*a + b*b + c*c)/(2*b*c)) )])] |
Sir, we've got enemies incoming. Should we shoot at the robot over there OR this robot? Skip that 'bot AND shoot later? Wait reinforcement XOR cover fire? Oh blasted bolts, it looks like we have problems with the logic module.
In mathematics and mathematical logic, Boolean algebra is a sub-area of algebra in which the values of the variables are true
or false
, typically denoted with 1 or 0 respectively. Instead of elementary algebra where the values of the variables are numbers and the main operations are addition and multiplication, the main operations of Boolean algebra are the conjunction (denoted ∧
), the disjunction (denoted ∨
) and the negation (denoted ¬
).
In this mission you should implement some boolean operations:
-
"conjunction" denoted
x ∧ y
, satisfiesx ∧ y = 1
ifx = y = 1
andx ∧ y = 0
otherwise. -
"disjunction" denoted
x ∨ y
, satisfiesx ∨ y = 0
ifx = y = 0
andx ∨ y = 1
otherwise. -
"implication" (material implication) denoted
x → y
and can be described as¬ x ∨ y
. Ifx
istrue
then the value ofx → y
is taken to be that ofy
. But ifx
isfalse
then the value ofy
can be ignored; however the operation must return some truth value and there are only two choices, so the return value is the one that entails less, namely true. -
"exclusive" (exclusive or) denoted
x ⊕ y
and can be described as(x ∨ y)∧ ¬ (x ∧ y)
. It excludes the possibility of bothx
andy
. Defined in terms of arithmetic it is additionmod 2
where1 + 1 = 0
. -
"equivalence" denoted
x ≡ y
and can be described as¬ (x ⊕ y)
. It's true just whenx
andy
have the same value.
Here you can see the truth table for these operations:
x | y | x∧y | x∨y | x→y | x⊕y | x≡y |
---|---|---|---|---|---|---|
0 | 0 | 0 | 0 | 1 | 0 | 1 |
1 | 0 | 0 | 1 | 0 | 1 | 0 |
0 | 1 | 0 | 1 | 1 | 1 | 0 |
1 | 1 | 1 | 1 | 1 | 0 | 1 |
You are given two boolean values x and y as 1 or 0 and you are given an operation name as described earlier. You should calculate the value and return it as 1 or 0.
Three arguments. X and Y as 0 or 1. An operation name as a string.
The result as 1 or 0.
boolean(1, 0, "conjunction") == 0
boolean(0, 1, "exclusive") == 1
x in (0, 1)
y in (0, 1)
operation in ("conjunction", "disjunction", "implication", "exclusive", "equivalence")
Fixing our defense bot's logic modules gets you working with boolean values and operators, a core concept in many programming languages.
OPERATION_NAMES = ("conjunction", "disjunction", "implication", "exclusive", "equivalence") | |
def boolean(x, y, operation): | |
if operation == "conjunction": | |
return x and y | |
elif operation == "disjunction": | |
return x or y | |
elif operation == "implication": | |
return not x or y | |
elif operation == "exclusive": | |
return x is not y | |
elif operation == "equivalence": | |
return x is y |
We've installed a new vault to contain our valuable resources and treasures, but before we can put anything into it, we need a suitable password for our new vault. One that should be as safe as possible.
The password will be considered strong enough if its length is greater than or equal to 10 characters, it contains at least one digit, as well as at least one uppercase letter and one lowercase letter. The password may only contain ASCII latin letters or digits, no punctuation symbols.
You are given a password. We need your code to verify if it meets the conditions for a secure password.
In this mission the main goal to make your code as short as possible. The shorter your code, the more points you earn. Your score for this mission is dynamic and directly related to the length of your code.
A password as a string.
A determination if the password safe or not as a boolean, or any data type that can be converted and processed as a boolean. When the results process, you will see the converted results.
golf('A1213pokl') == False
golf('bAse730onE') == True
golf('asasasasasasasaas') == False
golf('QWERTYqwerty') == False
golf('123456123456') == False
golf('QwErTy911poqqqq') == True
0 < |password| ≤ 64
password matches by regexp expression "[a-zA-Z0-9]+
"
Scoring in this mission is based on the number of characters used in your code (comment lines are not counted).
Any code length.
Your code should be shorter than 200 characters.
Your code should be shorter than 100 characters.
If you are worried about the security of your app or service, you can use this handy code to personally check your users' passwords for complexity. You can further use these skills to require that your users passwords meet or include even more conditions, punctuation or unicode.
golf=lambda d:9<len(d)and all(any(map(t,d))for t in(str.isdigit,str.isupper,str.islower)) |
def count_inversion(sequence): | |
return sum([1 | |
for i in range(len(sequence) - 1, -1, -1) | |
for j in range(i - 1, -1, -1) | |
if sequence[i] < sequence[j]]) |
from itertools import combinations_with_replacement | |
from fractions import Fraction | |
def CreatePosibilityDict(pearls): | |
PosibleCombinations = list(combinations_with_replacement([0, 1], pearls)) | |
result = {} | |
for i in PosibleCombinations: | |
if i not in result: | |
result[i] = {} | |
for j in PosibleCombinations: | |
if j not in result: | |
result[j] = {} | |
if i == j: | |
continue | |
else: | |
if sum([1 for k0, k1 in enumerate(i) if j[k0] != k1]) == 1: | |
if sum(i) > sum(j): | |
result[i][j] = Fraction(sum(i), pearls) | |
else: | |
result[i][j] = 1 - Fraction(sum(i), pearls) | |
return result | |
def probability(marbles, step): | |
PosibilityDict = CreatePosibilityDict(len(marbles)) | |
CurrentStatus = [(tuple(sorted([1 if i == 'b' else 0 | |
for i in list(marbles)])), 1)] | |
NextStatus = [] | |
for counter in range(step - 1): | |
for i in CurrentStatus: | |
for j in PosibilityDict[i[0]]: | |
NextStatus.append((j, i[1] * PosibilityDict[i[0]][j])) | |
CurrentStatus = NextStatus | |
NextStatus = [] | |
result = [] | |
for i in CurrentStatus: | |
for j in PosibilityDict[i[0]]: | |
if sum(i[0]) < sum(j): | |
result.append(i[1]*PosibilityDict[i[0]][j]) | |
return round(float(sum(result)), 2) |
How do we measure an angle without a protractor? Sometime in battles things get complicated and we need to use the things around us in creative ways. To get the degrees of an angle, a simple analog clock can help us out here.
Analog clocks display time with an analog clock face, which consists of a round dial with the numbers 1 through 12, the hours in the day, around the outside. The hours are indicated with an hour hand, which makes two revolutions in a day, while the minutes are indicated by a minute hand, which makes one revolution per hour. In this mission we will use a clock without second hand. The hour hand moves smoothly and the minute hand moves step by step.
You are given a time in 24-hour format and you should calculate a lesser angle between the hour and minute hands in degrees. Don't forget that clock has numbers from 1 to 12, so 23 == 11. The time is given as a string with the follow format "HH:MM", where HH is hours and MM is minutes. Hours and minutes are given in two digits format, so "1" will be writen as "01". The result should be given in degrees with precision ±0.1.
For example, on the given image we see "02:30" or "14:30" at the left part and "01:42" or "13:42" at the right part. We need to find the lesser angle.
A time as a string.
The lesser angle as a number.
clockAngle("02:30") == 105
clockAngle("13:42") == 159
clockAngle("01:43") == 153.5
Input time matches by regexp expression "\A((2[0-3])|([0-1][0-9])):[0-5][0-9]\Z"
Simple mathematics and skill to built a model for various things from real world.
def clock_angle(time): | |
hour, minute = time.split(':') | |
hour = int(hour)%12 | |
minute = int(minute) | |
hourAngle = 30.0*(hour+minute/60.0) | |
minuteAngle = 6.0 * minute | |
angle = (minuteAngle - hourAngle) % 360 | |
if angle > 180: | |
angle = 360 - angle | |
return angle |
VOWELS = "aeiouy" | |
def translate(phrase): | |
x = 0 | |
output = "" | |
while x < len(phrase): | |
if phrase[x] == " ": | |
output += phrase[x] | |
x += 1 | |
elif phrase[x] not in VOWELS: | |
output += phrase[x] | |
x += 2 | |
elif phrase[x] in VOWELS: | |
output += phrase[x] | |
x += 3 | |
return output |
def index_power(array, n): | |
if len(array) <= n: | |
return -1 | |
return array[n] ** n |
def hamming(n, m): | |
return str(bin(n ^ m)).count("1") |
def count_words(text, words): | |
return [w in text.lower() for w in words].count(True) |
def count_words(text, words): | |
counter = 0 | |
for word in words: | |
if text.lower().find(word) != -1: | |
counter += 1 | |
return counter |
import datetime | |
import re | |
count_ingots=lambda r: sum([(ord(x[0])-65)*9+int(x[1])for x in r.split(',')]) | |
def count_reports(full_report, from_date, to_date): | |
dFrom = datetime.datetime.strptime(from_date, "%Y-%m-%d") | |
dTo = datetime.datetime.strptime(to_date, "%Y-%m-%d") | |
reports = re.findall('\d{4}-\d{2}-\d{2} .*', full_report) | |
x = [ count_ingots(report.split()[1]) for report in reports if dFrom <= datetime.datetime.strptime(report.split()[0], "%Y-%m-%d") <= dTo] | |
return sum(x) |
def transpose(matrix): | |
return [list(i) for i in zip(*matrix)] |
import re, math | |
class Point: | |
def __init__(self, x, y): | |
self.x = float(x) | |
self.y = float(y) | |
def __repr__(self): | |
return "Point(%.2f, %.2f)" % (self.x, self.y) | |
P = re.compile(r'\([0-9],[0-9]\)') | |
def circle_equation(note): | |
a, b, c = [Point(x[1], x[3]) for x in P.findall(note)] | |
# find line between a and b: s1 + k * d1 | |
s1 = Point((a.x + b.x)/2.0, (a.y + b.y)/2.0) | |
d1 = Point((b.y - a.y), -(b.x - a.x)) | |
# find line between a and c: s2 + k * d2 | |
s2 = Point((a.x + c.x)/2.0, (a.y + c.y)/2.0) | |
d2 = Point((c.y - a.y), -(c.x - a.x)) | |
# intersection of both lines: | |
# s1 + k * d1 == s2 + l * d2 | |
l = d1.x * (s2.y - s1.y) - d1.y * (s2.x - s1.x) | |
l = l / (d2.x * d1.y - d2.y * d1.x) | |
# circle center | |
center = Point(s2.x + l * d2.x, s2.y + l * d2.y) | |
dx = center.x - a.x | |
dy = center.y - a.y | |
radius = math.sqrt(dx * dx + dy * dy) | |
x = str("%.2f" % center.x).rstrip('0').rstrip('.') | |
y = str("%.2f" % center.y).rstrip('0').rstrip('.') | |
r = str("%.2f" % radius).rstrip('0').rstrip('.') | |
eq = "(x-%s)^2+(y-%s)^2=%s^2" % (x, y, r) | |
return eq |
def check_grid(grid): | |
if any(check_row(row) for row in grid): | |
return False | |
if any(check_row(row) for row in zip(*grid)): | |
return False | |
return True | |
def check_row(row): | |
# True if INVAL | |
for i,el in enumerate(row[:-1]): | |
if el == row[i+1]: | |
return True | |
return False |
def golf(n): | |
v=[0] | |
for i in range(len(n)): | |
v += [n[i] + max(v[i-1],v[i])] | |
return max(v[-2:]) |
def golf(b): | |
k=0 | |
for g in b: | |
for r in g: | |
c=0 | |
for v in r: | |
if k<2: | |
t=0 | |
for l in g if k else b : | |
z=l[c] | |
if t==z: | |
return 0 | |
t=z | |
c+=1 | |
k+=1 | |
return 1 |
import re | |
golf=lambda r:sum([ord(a)*9-585+int(b) for a,b in re.findall('[A-Z][1-9]',r)]) |
def golf(m): | |
r = [sum(i) for i in m] | |
c = [sum(i) for i in zip(*m)] | |
return [r.index(min(r)), c.index(min(c))] |
import math | |
def super_root(number): | |
x = 0 | |
base = 1.0 | |
while not number - 0.001 < x ** x < number + 0.001: | |
if x ** x <= number - 0.001: | |
x += base | |
else: | |
base /= 2 | |
x -= base | |
return x |
COLS = "abcdefgh" | |
ROWS = "12345678" | |
THREATS = {c + r: set( | |
[c + ROWS[k] for k in range(8)] + | |
[COLS[k] + r for k in range(8)] + | |
[COLS[k] + ROWS[i - j + k] for k in range(8) if 0 <= i - j + k < 8] + | |
[COLS[k] + ROWS[- k + i + j] for k in range(8) if 0 <= - k + i + j < 8]) | |
for i, r in enumerate(ROWS) for j, c in enumerate(COLS)} | |
def invalid_queens(placed): | |
for p in placed: | |
if any( pl in THREATS[p] for pl in placed if pl != p ): | |
return True | |
return False | |
def get_first_row_not_occupied(placed): | |
occupied_rows = [x[1] for x in placed] | |
for r in ROWS: | |
if r not in occupied_rows: return r | |
return str(len(ROWS)+1) # all rows are occupied | |
def place_queens(placed): | |
res = set() | |
if invalid_queens(placed): return res | |
row = get_first_row_not_occupied(placed) | |
if int(row) > len(ROWS): | |
res = placed | |
else: | |
for col in COLS: | |
res = place_queens(placed.union({col+row})) | |
if res: break; | |
return res |
from collections import defaultdict | |
def dfs(placed, p, cur, ans): | |
if cur == 8: | |
if placed.issubset(ans): | |
yield ans | |
else: | |
for i in range(1, 9): | |
place = chr(cur + ord('a')) + str(i) | |
if not p[place[0]] and not p[place[1]] and not p[(ord(place[0]) - ord('a')) + int(place[1])] and not p[ord(place[0]) - ord('a') - int(place[1]) - 6]: | |
p[place[0]] = p[place[1]] = p[(ord(place[0]) - ord('a')) + int(place[1])] = p[ord(place[0]) - ord('a') - int(place[1]) - 6] = True | |
ans.add(place) | |
for y in dfs(placed, p, cur + 1, ans): | |
yield y | |
ans.remove(place) | |
p[place[0]] = p[place[1]] = p[(ord(place[0]) - ord('a')) + int(place[1])] = p[ord(place[0]) - ord('a') - int(place[1]) - 6] = False | |
def place_queens(placed): | |
p = defaultdict(bool) | |
try: | |
return next(dfs(placed, p, 0, set())) | |
except StopIteration: | |
return set() |
from collections import defaultdict | |
def dfs(placed, p, cur, ans): | |
if cur == 8: | |
if placed.issubset(ans): | |
yield ans | |
else: | |
for i in range(1, 9): | |
place = chr(cur + ord('a')) + str(i) | |
if not p[place[0]] and not p[place[1]] and not p[(ord(place[0]) - ord('a')) + int(place[1])] and not p[ord(place[0]) - ord('a') - int(place[1]) - 6]: | |
p[place[0]] = p[place[1]] = p[(ord(place[0]) - ord('a')) + int(place[1])] = p[ord(place[0]) - ord('a') - int(place[1]) - 6] = True | |
ans.add(place) | |
for y in dfs(placed, p, cur + 1, ans): | |
yield y | |
ans.remove(place) | |
p[place[0]] = p[place[1]] = p[(ord(place[0]) - ord('a')) + int(place[1])] = p[ord(place[0]) - ord('a') - int(place[1]) - 6] = False | |
def place_queens(placed): | |
p = defaultdict(bool) | |
try: | |
return next(dfs(placed, p, 0, set())) | |
except StopIteration: | |
return set() | |
if __name__ == '__main__': | |
# These "asserts" using only for self-checking and not necessary for auto-testing | |
from itertools import combinations | |
COLS = "abcdefgh" | |
ROWS = "12345678" | |
THREATS = {c + r: set( | |
[c + ROWS[k] for k in range(8)] + | |
[COLS[k] + r for k in range(8)] + | |
[COLS[k] + ROWS[i - j + k] for k in range(8) if 0 <= i - j + k < 8] + | |
[COLS[k] + ROWS[- k + i + j] for k in range(8) if 0 <= - k + i + j < 8]) | |
for i, r in enumerate(ROWS) for j, c in enumerate(COLS)} | |
def check_coordinate(coor): | |
c, r = coor | |
return c in COLS and r in ROWS | |
def checker(func, placed, is_possible): | |
user_set = func(placed.copy()) | |
if not all(isinstance(c, str) and len(c) == 2 and check_coordinate(c) for c in user_set): | |
print("Wrong Coordinates") | |
return False | |
threats = [] | |
for f, s in combinations(user_set.union(placed), 2): | |
if s in THREATS[f]: | |
threats.append([f, s]) | |
if not is_possible: | |
if user_set: | |
print("Hm, how did you place them?") | |
return False | |
else: | |
return True | |
if not all(p in user_set for p in placed): | |
print("You forgot about placed queens.") | |
return False | |
if is_possible and threats: | |
print("I see some problems in this placement.") | |
return False | |
return True |
import math | |
FONT = ("--X--XXX-XXX-X-X-XXX--XX-XXX-XXX--XX-XX--" | |
"-XX----X---X-X-X-X---X-----X-X-X-X-X-X-X-" | |
"--X---XX--X--XXX-XX--XXX--X--XXX-XXX-X-X-" | |
"--X--X-----X---X---X-X-X-X---X-X---X-X-X-" | |
"--X--XXX-XXX---X-XX---XX-X---XXX-XX---XX-") | |
S_LEN = 3 | |
S_NUM = 10 | |
FONT_SHIFT = 41 | |
def recognize(image): | |
# Parse image to get font characters | |
s_l = [] | |
step = 0 | |
k = 1 | |
for i in range(math.ceil(len(image[0]) / 4 - 1)): | |
s = [] | |
for j in range(len(image)): | |
s.append(''.join(map(str, image[j][k + step:S_LEN + k + step]))) | |
step += S_LEN | |
k += 1 | |
s_l.append(''.join([i.replace('0', '-').replace('1', 'X') for i in s])) | |
# Parse FONT to get decimal values for each character | |
shift = 0 | |
f_l = [] | |
l_offset = 0 | |
for i in range(S_NUM): | |
f = [] | |
for j in range(len(image)): | |
f.append(FONT[1 + shift + l_offset: shift + S_LEN + 1 + l_offset]) | |
shift += FONT_SHIFT | |
shift = 0 | |
l_offset += 4 | |
f_l.append(''.join(i for i in f)) | |
# Create dictionary {'character': 'decimal_value'} | |
d = {f_l[-1]: '0'} | |
for i, c_val in enumerate(f_l[:-1]): | |
d.update({c_val: str(i + 1)}) | |
# Recognize character | |
d_val = '' | |
for v in s_l: | |
for key in d: | |
# Generate list with differences | |
if len([i for i in range(len(v)) if v[i] != key[i]]) <= 1: | |
d_val += d.get(key) | |
break | |
return int(d_val) |
from cmath import * | |
def golf(h,w):e=sqrt(1-w*w/h/h);return(round(w*w*h*pi/6,2),round(pi*w*w*((1+h/w/e*asin(e))/2).real if h!=w else pi*h*h,2)) |
from fractions import Fraction as F | |
def divide_pie(groups): | |
den = sum(x if x > 0 else -x for x in groups) | |
pie = F(den, den) | |
for num in groups: | |
pie = pie - F(num, den) if num > 0 else pie * (1 - F(-num, den)) | |
return (pie.numerator, pie.denominator) if pie.numerator else (0, 1) |
def xo_referee(result): | |
array = [] | |
# Add rows | |
array.extend(result) | |
# Add columns | |
for j in range(len(result)): | |
m = '' | |
for i in range(len(result)): | |
m += result[i][j] | |
array.append(m) | |
# Add main diagonals | |
array.append(''.join([str(result[i][i]) for i in range(len(result[0]))])) | |
array.append(''.join([str(result[len(result[0]) - 1 - i][i]) | |
for i in range(len(result[0]) - 1, -1, -1)])) | |
if any('XXX' in x for x in array) and any('OOO' in o for o in array): | |
return 'D' | |
for item in array: | |
if 'XXX' in item: | |
return 'X' | |
if 'OOO' in item: | |
return 'O' | |
return 'D' |
from itertools import groupby | |
SEQ_LENGTH = 4 | |
def is_in_matrix(m): | |
len_list = [[len(list(group)) for key, group in groupby(j)] for j in m] | |
if any(map(lambda x: [i for i in x if i >= SEQ_LENGTH], len_list)): | |
return True | |
return False | |
def get_diagonals(m): | |
d = [] | |
for o in range(-len(m) + SEQ_LENGTH, len(m) - SEQ_LENGTH + 1): | |
d.append([r[i + o] for i, r in enumerate(m) if 0 <= i + o < len(r)]) | |
return d | |
def has_sequence(matrix): | |
if is_in_matrix(matrix): | |
return True | |
if is_in_matrix(map(lambda *row: list(row), *matrix)): | |
return True | |
if is_in_matrix(get_diagonals(matrix)): | |
return True | |
if is_in_matrix(get_diagonals(list(reversed(matrix)))): | |
return True | |
return False |
def reconstruct(n): | |
divider = 0 | |
arr = [] | |
for i in range(9,2,-1): | |
if n%i == 0: | |
divider1 = i | |
divider2 = int(n / float(divider1)) | |
arr.append(divider1) | |
arr.append(divider2) | |
break; | |
arr = list(sorted(arr)) | |
if len(arr) == 0: | |
return 0 | |
result = '' | |
for l in arr: | |
if l >= 10: | |
l = reconstruct(l) | |
if l == 0: | |
return 0 | |
result = result + str(l) | |
result = ''.join(sorted(result)) | |
return int(result) |
def friendly_number(number, base=1000, decimals=0, suffix='', | |
powers=['', 'k', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y']): | |
prefix, zn = '', '' | |
if number < 0: | |
zn = "-" | |
number, answer = abs(number), number | |
for i, power in enumerate(powers): | |
if number // (base**i) > 0: | |
answer = number // (base**i) | |
prefix = powers[i] | |
if decimals: | |
i = powers.index(prefix) | |
frac = round(float(number) / (base**i), decimals) | |
a_lst = str(frac).split(".") | |
answer = a_lst[0] + "." + a_lst[1].zfill(decimals) | |
return zn+str(answer)+prefix+suffix |
def convert(numerator, denominator): | |
p, r = divmod(numerator, denominator) | |
main = str(p) + '.' | |
if r == 0: | |
return main | |
# fraction part | |
remainder, digits = [r], [] | |
while r: | |
p, r = divmod(r*10, denominator) | |
digits.append(str(p)) | |
if r in remainder: | |
idx = remainder.index(r) # index for the repeating remainder | |
strx = ''.join(digits[:idx]) + '(' + ''.join(digits[idx:]) + ')' | |
return main + strx | |
remainder.append(r) | |
return main + ''.join(digits) |
roman_rules = ( | |
('M' , 1000), | |
('CM', 900), | |
('D' , 500), | |
('CD', 400), | |
('C' , 100), | |
('XC', 90), | |
('L' , 50), | |
('XL', 40), | |
('X' , 10), | |
('IX', 9), | |
('V' , 5), | |
('IV', 4), | |
('I' , 1)) | |
def roman_numeral(n): | |
for rule in roman_rules: | |
roman, value = rule[0], rule[1] | |
if n // value: | |
return roman + roman_numeral(n - value) | |
return '' | |
def roman(n): | |
return roman_numeral(n) |
def count_neighbours(grid, row, col): | |
return sum(sum(i[max(col-1, 0):col+2]) | |
for i in | |
grid[max(row-1, 0):row+2]) - \ | |
grid[row][col] |
golf=lambda s,a=0,b=0:min(abs(a-x[0]+1j*(b-x[1]))+golf(s-{x},*x)for x in s)if s else 0 |
def m(x, i, j): | |
y = x[:] | |
del (y[i - 1]) | |
y = list(zip(*y)) | |
del (y[j - 1]) | |
return list(zip(*y)) | |
def golf(d): | |
if len(d) == 1: | |
return d[0][0] | |
return sum([(-1) ** i * d[i][0] * golf(m(d, i + 1, 1)) | |
for i in range(len(d))]) |
def two_monkeys(asmile, bsmile): | |
return asmile == bsmile |
def list_combination(list1, list2): | |
return [j for i in list(zip(list1, list2)) for j in i] |
from itertools import groupby | |
def total_cost(calls): | |
total = 0 | |
for k,g in groupby(calls, lambda x:x[:10]): | |
minutes = sum(-(-int(l[20:])//60) for l in g) | |
total += (minutes, 2*minutes-100)[minutes>100] | |
return total |
def letter_queue(commands): | |
letter_queue = [] | |
for command in commands: | |
if "PUSH" in command: | |
letter = command.split()[1] | |
letter_queue.append(letter) | |
elif "POP" in command and letter_queue: | |
letter_queue.pop(0) | |
return ''.join(letter_queue) |