mirror of
https://github.com/theoludwig/programming-challenges.git
synced 2024-12-08 00:45:29 +01:00
refactor: usage of built-in type hinting in Python solutions
This commit is contained in:
parent
64c5d41358
commit
34644bd333
@ -1,7 +1,6 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
@ -1,7 +1,7 @@
|
||||
from typing import List, TypedDict
|
||||
from typing import TypedDict
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
@ -11,8 +11,8 @@ class ShiftedLetter(TypedDict):
|
||||
shifted: str
|
||||
|
||||
|
||||
def shift_alphabet(shift: int) -> List[ShiftedLetter]:
|
||||
result: List[ShiftedLetter] = []
|
||||
def shift_alphabet(shift: int) -> list[ShiftedLetter]:
|
||||
result: list[ShiftedLetter] = []
|
||||
alphabet = 'A B C D E F G H I J K L M N O P Q R S T U V W X Y Z'.split(' ')
|
||||
is_negative_shift = shift < 0
|
||||
if is_negative_shift:
|
||||
|
@ -1,4 +1,3 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
maximum_number_of_cake_possible = None
|
||||
|
@ -1,16 +1,15 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
||||
def consecutive_numbers(numbers: List[int], couple_length: int) -> List[List[int]]:
|
||||
result: List[List[int]] = []
|
||||
def consecutive_numbers(numbers: list[int], couple_length: int) -> list[list[int]]:
|
||||
result: list[list[int]] = []
|
||||
numbers_length = len(numbers)
|
||||
for index in range(numbers_length):
|
||||
consecutive: List[int] = [numbers[index]]
|
||||
consecutive: list[int] = [numbers[index]]
|
||||
for couple_index in range(1, couple_length, 1):
|
||||
is_last_number = index + couple_index == numbers_length
|
||||
if is_last_number:
|
||||
@ -23,7 +22,7 @@ def consecutive_numbers(numbers: List[int], couple_length: int) -> List[List[int
|
||||
return result
|
||||
|
||||
|
||||
numbers: List[int] = []
|
||||
numbers: list[int] = []
|
||||
for value in input_values[1].split(' ; '):
|
||||
numbers.append(int(value))
|
||||
|
||||
|
@ -1,8 +1,7 @@
|
||||
from typing import List
|
||||
import sys
|
||||
import math
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
@ -28,7 +27,7 @@ class Position:
|
||||
|
||||
|
||||
class Defibrillator:
|
||||
def __init__(self, strings: List[str], user_position: Position) -> None:
|
||||
def __init__(self, strings: list[str], user_position: Position) -> None:
|
||||
self.id = strings[0]
|
||||
self.name = strings[1]
|
||||
self.address = strings[2]
|
||||
@ -41,7 +40,7 @@ class Defibrillator:
|
||||
longitude = convert_string_to_float(input_values[0])
|
||||
latitude = convert_string_to_float(input_values[1])
|
||||
user_position = Position(longitude, latitude)
|
||||
defibrillators: List[Defibrillator] = []
|
||||
defibrillators: list[Defibrillator] = []
|
||||
|
||||
for index in range(3, len(input_values), 1):
|
||||
line = input_values[index].split(';')
|
||||
|
@ -1,7 +1,6 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
@ -1,13 +1,12 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
||||
def divider_list(number: int) -> List[int]:
|
||||
number_list: List[int] = []
|
||||
def divider_list(number: int) -> list[int]:
|
||||
number_list: list[int] = []
|
||||
for index in range(1, number + 1):
|
||||
if number % index == 0:
|
||||
number_list.append(index)
|
||||
|
@ -1,12 +1,11 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
||||
def get_is_valid_subsequence(array: List, sequence: List):
|
||||
def get_is_valid_subsequence(array: list, sequence: list):
|
||||
index_to_check = 0
|
||||
for index in range(len(array)):
|
||||
if index_to_check < len(sequence) and array[index] == sequence[index_to_check]:
|
||||
|
@ -1,7 +1,6 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
@ -1,7 +1,13 @@
|
||||
from typing import List
|
||||
from typing import TypedDict
|
||||
import sys
|
||||
|
||||
matches_roman_arabic = [
|
||||
|
||||
class RomanArabicMatch(TypedDict):
|
||||
arabic: int
|
||||
roman: str
|
||||
|
||||
|
||||
matches_roman_arabic: list[RomanArabicMatch] = [
|
||||
{'arabic': 1000, 'roman': 'M'},
|
||||
{'arabic': 900, 'roman': 'CM'},
|
||||
{'arabic': 500, 'roman': 'D'},
|
||||
@ -42,7 +48,7 @@ def convert_roman_to_arabic(roman_number: str) -> int:
|
||||
return arabic_number
|
||||
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
@ -1,8 +1,7 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
|
||||
def bubble_sort(numbersInput: List[int]) -> List[int]:
|
||||
def bubble_sort(numbersInput: list[int]) -> list[int]:
|
||||
numbers = list(numbersInput)
|
||||
length = len(numbers)
|
||||
for index_1 in range(length):
|
||||
@ -14,7 +13,7 @@ def bubble_sort(numbersInput: List[int]) -> List[int]:
|
||||
return numbers
|
||||
|
||||
|
||||
numbers: List[int] = []
|
||||
numbers: list[int] = []
|
||||
for value in sys.stdin:
|
||||
numbers.append(int(value.rstrip('\n')))
|
||||
|
||||
|
@ -1,7 +1,6 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
numbers: List[int] = []
|
||||
numbers: list[int] = []
|
||||
for value in sys.stdin:
|
||||
numbers.append(int(value.rstrip('\n')))
|
||||
|
||||
|
@ -1,8 +1,7 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
|
||||
def insertion_sort(numbersInput: List[int]) -> List[int]:
|
||||
def insertion_sort(numbersInput: list[int]) -> list[int]:
|
||||
numbers = list(numbersInput)
|
||||
for index_1 in range(1, len(numbers)):
|
||||
current = numbers[index_1]
|
||||
@ -14,7 +13,7 @@ def insertion_sort(numbersInput: List[int]) -> List[int]:
|
||||
return numbers
|
||||
|
||||
|
||||
numbers: List[int] = []
|
||||
numbers: list[int] = []
|
||||
for value in sys.stdin:
|
||||
numbers.append(int(value.rstrip('\n')))
|
||||
|
||||
|
@ -1,20 +1,22 @@
|
||||
from typing import List, Any
|
||||
from typing import TypeVar
|
||||
import sys
|
||||
|
||||
T = TypeVar('T')
|
||||
|
||||
def divide_list(values: List[Any]) -> List[Any]:
|
||||
|
||||
def divide_list(values: list[T]) -> tuple[list[T], list[T]]:
|
||||
middle = len(values) // 2
|
||||
left = values[middle:]
|
||||
right = values[:middle]
|
||||
return [left, right]
|
||||
return (left, right)
|
||||
|
||||
|
||||
def merge(numbers_1: List[int], numbers_2: List[int]) -> List[int]:
|
||||
def merge(numbers_1: list[int], numbers_2: list[int]) -> list[int]:
|
||||
length_numbers_1 = len(numbers_1)
|
||||
length_numbers_2 = len(numbers_2)
|
||||
index_numbers_1 = 0
|
||||
index_numbers_2 = 0
|
||||
result: List[int] = []
|
||||
result: list[int] = []
|
||||
while index_numbers_1 < length_numbers_1 and index_numbers_2 < length_numbers_2:
|
||||
if numbers_1[index_numbers_1] < numbers_2[index_numbers_2]:
|
||||
result.append(numbers_1[index_numbers_1])
|
||||
@ -29,7 +31,7 @@ def merge(numbers_1: List[int], numbers_2: List[int]) -> List[int]:
|
||||
return result
|
||||
|
||||
|
||||
def merge_sort(numbers: List[int]) -> List[int]:
|
||||
def merge_sort(numbers: list[int]) -> list[int]:
|
||||
if len(numbers) <= 1:
|
||||
return numbers
|
||||
left, right = divide_list(numbers)
|
||||
@ -37,7 +39,7 @@ def merge_sort(numbers: List[int]) -> List[int]:
|
||||
return merge(left, right)
|
||||
|
||||
|
||||
numbers: List[int] = []
|
||||
numbers: list[int] = []
|
||||
for value in sys.stdin:
|
||||
numbers.append(int(value.rstrip('\n')))
|
||||
|
||||
|
@ -1,13 +1,11 @@
|
||||
from typing import List
|
||||
|
||||
from Cell import Cell
|
||||
|
||||
|
||||
class Grid:
|
||||
def __init__(self, grid: List[List[int]]) -> None:
|
||||
data: List[List[Cell]] = []
|
||||
def __init__(self, grid: list[list[int]]) -> None:
|
||||
data: list[list[Cell]] = []
|
||||
for x in range(len(grid)):
|
||||
column: List[Cell] = []
|
||||
column: list[Cell] = []
|
||||
for y in range(len(grid[x])):
|
||||
column.append(Cell(grid[x][y], y, x))
|
||||
data.append(column)
|
||||
|
@ -1,13 +1,12 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
from Sudoku import Sudoku
|
||||
from Grid import Grid
|
||||
|
||||
grid_values: List[List[int]] = []
|
||||
grid_values: list[list[int]] = []
|
||||
for value in sys.stdin:
|
||||
row_values = value.rstrip('\n').split(' ')
|
||||
current_row: List[int] = []
|
||||
current_row: list[int] = []
|
||||
for row_value in row_values:
|
||||
current_row.append(int(row_value))
|
||||
grid_values.append(current_row)
|
||||
|
@ -50,7 +50,9 @@ export class RunTestCommand extends Command {
|
||||
console.log()
|
||||
try {
|
||||
if (this.programmingLanguage != null) {
|
||||
await template.verifySupportedProgrammingLanguage(this.programmingLanguage)
|
||||
await template.verifySupportedProgrammingLanguage(
|
||||
this.programmingLanguage
|
||||
)
|
||||
}
|
||||
if (this.all) {
|
||||
return await Test.runAllTests(this.programmingLanguage)
|
||||
|
@ -21,7 +21,9 @@ export class Challenge implements ChallengeOptions {
|
||||
constructor(options: ChallengeOptions) {
|
||||
const { name } = options
|
||||
this.name = name
|
||||
this.path = fileURLToPath(new URL(`../../challenges/${name}`, import.meta.url))
|
||||
this.path = fileURLToPath(
|
||||
new URL(`../../challenges/${name}`, import.meta.url)
|
||||
)
|
||||
}
|
||||
|
||||
static async generate(options: GenerateChallengeOptions): Promise<Challenge> {
|
||||
|
@ -40,10 +40,14 @@ export class Docker {
|
||||
return stdout
|
||||
} catch (error: any) {
|
||||
if (!isValid) {
|
||||
throw new Error(`Timeout: time limit exceeded (${Docker.MAXIMUM_TIMEOUT}), try to optimize your solution.`)
|
||||
throw new Error(
|
||||
`Timeout: time limit exceeded (${Docker.MAXIMUM_TIMEOUT}), try to optimize your solution.`
|
||||
)
|
||||
}
|
||||
if (error.exitCode === Docker.SIGSEGV_EXIT_CODE) {
|
||||
throw new Error('Docker run failed: SIGSEGV indicates a segmentation fault (attempts to access a memory location that it\'s not allowed to access).')
|
||||
throw new Error(
|
||||
"Docker run failed: SIGSEGV indicates a segmentation fault (attempts to access a memory location that it's not allowed to access)."
|
||||
)
|
||||
}
|
||||
throw new Error(`Docker run failed: ${error.message as string}`)
|
||||
}
|
||||
|
@ -3,11 +3,14 @@ import { execaCommand } from 'execa'
|
||||
import { Challenge } from './Challenge.js'
|
||||
import { Solution } from './Solution.js'
|
||||
|
||||
const solutionsRegex = /challenges\/[\S\s]*\/solutions\/(c|cpp|cs|dart|java|javascript|python|rust|typescript)\/[\S\s]*\/(.*).(c|cpp|cs|dart|java|js|py|rs|ts)/
|
||||
const solutionsRegex =
|
||||
/challenges\/[\S\s]*\/solutions\/(c|cpp|cs|dart|java|javascript|python|rust|typescript)\/[\S\s]*\/(.*).(c|cpp|cs|dart|java|js|py|rs|ts)/
|
||||
|
||||
const dockerRegex = /templates\/docker\/(c|cpp|cs|dart|java|javascript|python|rust|typescript)\/(.*)/
|
||||
const dockerRegex =
|
||||
/templates\/docker\/(c|cpp|cs|dart|java|javascript|python|rust|typescript)\/(.*)/
|
||||
|
||||
const inputOutputRegex = /challenges\/[\S\s]*\/test\/(.*)\/(input.txt|output.txt)/
|
||||
const inputOutputRegex =
|
||||
/challenges\/[\S\s]*\/test\/(.*)\/(input.txt|output.txt)/
|
||||
|
||||
export interface GitAffectedOptions {
|
||||
isContinuousIntegration: boolean
|
||||
@ -49,8 +52,11 @@ export class GitAffected implements GitAffectedOptions {
|
||||
}
|
||||
|
||||
public async getLatestPushedCommit(): Promise<string> {
|
||||
const latestCommit = this.isContinuousIntegration ? '~1' : ''
|
||||
const { stdout } = await execaCommand(`git rev-parse origin/master${latestCommit}`)
|
||||
const latestCommit =
|
||||
this.isContinuousIntegration || this.base != null ? '~1' : ''
|
||||
const { stdout } = await execaCommand(
|
||||
`git rev-parse origin/master${latestCommit}`
|
||||
)
|
||||
return stdout
|
||||
}
|
||||
|
||||
@ -61,7 +67,9 @@ export class GitAffected implements GitAffectedOptions {
|
||||
)
|
||||
}
|
||||
|
||||
public async getAffectedSolutionsFromFiles (files: string[]): Promise<Solution[]> {
|
||||
public async getAffectedSolutionsFromFiles(
|
||||
files: string[]
|
||||
): Promise<Solution[]> {
|
||||
const affectedSolutionsPaths = files.filter((filePath) => {
|
||||
return solutionsRegex.test(filePath)
|
||||
})
|
||||
@ -69,18 +77,26 @@ export class GitAffected implements GitAffectedOptions {
|
||||
return dockerRegex.test(filePath)
|
||||
})
|
||||
const affectedLanguages = affectedDockerPaths.map((filePath) => {
|
||||
const [,, programmingLanguageName] = filePath.replaceAll('\\', '/').split('/')
|
||||
const [, , programmingLanguageName] = filePath
|
||||
.replaceAll('\\', '/')
|
||||
.split('/')
|
||||
return programmingLanguageName
|
||||
})
|
||||
const affectedInputOutput = files.filter((filePath) => {
|
||||
return inputOutputRegex.test(filePath)
|
||||
})
|
||||
const affectedChallengesFromInputOutput = affectedInputOutput.map((filePath) => {
|
||||
const affectedChallengesFromInputOutput = affectedInputOutput.map(
|
||||
(filePath) => {
|
||||
const [, challengeName] = filePath.replaceAll('\\', '/').split('/')
|
||||
return new Challenge({ name: challengeName })
|
||||
})
|
||||
const solutionsChallenges = await Solution.getManyByPaths(affectedSolutionsPaths)
|
||||
const solutionsDocker = await Solution.getManyByProgrammingLanguages(affectedLanguages)
|
||||
}
|
||||
)
|
||||
const solutionsChallenges = await Solution.getManyByPaths(
|
||||
affectedSolutionsPaths
|
||||
)
|
||||
const solutionsDocker = await Solution.getManyByProgrammingLanguages(
|
||||
affectedLanguages
|
||||
)
|
||||
const solutions: Solution[] = [...solutionsDocker, ...solutionsChallenges]
|
||||
for (const challenge of affectedChallengesFromInputOutput) {
|
||||
const solutionsByChallenge = await Solution.getManyByChallenge(challenge)
|
||||
|
@ -113,7 +113,9 @@ export class Solution implements SolutionOptions {
|
||||
)
|
||||
const paths: string[] = []
|
||||
for (const language of languagesSolution) {
|
||||
const solutionPath = (await fs.promises.readdir(path.join(solutionsPath, language))).map((solutionName) => {
|
||||
const solutionPath = (
|
||||
await fs.promises.readdir(path.join(solutionsPath, language))
|
||||
).map((solutionName) => {
|
||||
return `challenges/${challenge.name}/solutions/${language}/${solutionName}`
|
||||
})
|
||||
paths.push(...solutionPath)
|
||||
@ -121,20 +123,27 @@ export class Solution implements SolutionOptions {
|
||||
return await Solution.getManyByPaths(paths)
|
||||
}
|
||||
|
||||
static async getManyByProgrammingLanguages (programmingLanguages?: string[]): Promise<Solution[]> {
|
||||
const languages = programmingLanguages ?? await template.getProgrammingLanguages()
|
||||
const challengesPath = fileURLToPath(new URL('../../challenges', import.meta.url))
|
||||
static async getManyByProgrammingLanguages(
|
||||
programmingLanguages?: string[]
|
||||
): Promise<Solution[]> {
|
||||
const languages =
|
||||
programmingLanguages ?? (await template.getProgrammingLanguages())
|
||||
const challengesPath = fileURLToPath(
|
||||
new URL('../../challenges', import.meta.url)
|
||||
)
|
||||
const challenges = await fs.promises.readdir(challengesPath)
|
||||
const paths: string[] = []
|
||||
for (const challenge of challenges) {
|
||||
const solutionsPath = path.join(challengesPath, challenge, 'solutions')
|
||||
const languagesSolution = (await fs.promises.readdir(solutionsPath)).filter(
|
||||
(name) => {
|
||||
const languagesSolution = (
|
||||
await fs.promises.readdir(solutionsPath)
|
||||
).filter((name) => {
|
||||
return name !== '.gitkeep' && languages.includes(name)
|
||||
}
|
||||
)
|
||||
})
|
||||
for (const language of languagesSolution) {
|
||||
const solutionPath = (await fs.promises.readdir(path.join(solutionsPath, language))).map((solutionName) => {
|
||||
const solutionPath = (
|
||||
await fs.promises.readdir(path.join(solutionsPath, language))
|
||||
).map((solutionName) => {
|
||||
return `challenges/${challenge}/solutions/${language}/${solutionName}`
|
||||
})
|
||||
paths.push(...solutionPath)
|
||||
|
@ -99,7 +99,9 @@ export class Test implements TestOptions {
|
||||
const name = `${solution.challenge.name}/${solution.programmingLanguageName}/${solution.name}`
|
||||
const testsPath = path.join(solution.challenge.path, 'test')
|
||||
const testsFolders = await fs.promises.readdir(testsPath)
|
||||
const testsNumbers = testsFolders.map((test) => Number(test)).sort((a, b) => a - b)
|
||||
const testsNumbers = testsFolders
|
||||
.map((test) => Number(test))
|
||||
.sort((a, b) => a - b)
|
||||
const tests: Test[] = []
|
||||
console.log(`${chalk.bold('Name:')} ${name}\n`)
|
||||
for (const testNumber of testsNumbers) {
|
||||
|
@ -1,7 +1,6 @@
|
||||
from typing import List
|
||||
import sys
|
||||
|
||||
input_values: List[str] = []
|
||||
input_values: list[str] = []
|
||||
for value in sys.stdin:
|
||||
input_values.append(value.rstrip('\n'))
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user