-
Notifications
You must be signed in to change notification settings - Fork 8
Homework2 #9
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Homework2 #9
Changes from all commits
8afb0b8
20eb867
8c25815
13fb73c
9c16473
498677b
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,22 @@ | ||
(ns otus-02.homework.palindrome) | ||
(ns otus-02.homework.palindrome | ||
(:require [clojure.string :as str])) | ||
|
||
(defn is-palindrome [test-string] | ||
(let [original (str/lower-case | ||
(str/replace test-string #",|!|\?|\.|\s" "")) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. хорошее решение There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Согласен, я переусложнил. Фиксить не вижу смысла сейчас) |
||
reversed (str/reverse original)] | ||
(= original reversed))) | ||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
|
||
(defn is-palindrome [test-string]) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,10 @@ | ||
(ns otus-02.homework.pangram) | ||
(ns otus-02.homework.pangram | ||
(:require [clojure.string :as str])) | ||
|
||
(defn is-char [ch] (Character/isLetter ch)) | ||
|
||
(defn is-pangram [test-string]) | ||
(defn is-pangram [test-string] | ||
(let | ||
[tested-char-set (set (filter is-char (str/lower-case test-string))) | ||
all-chars (set (map char (range (int \a) (inc (int \z)))))] | ||
(= tested-char-set all-chars))) |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,4 +1,5 @@ | ||
(ns otus-02.homework.square-code) | ||
(ns otus-02.homework.square-code | ||
(:require [clojure.string :as str])) | ||
|
||
;; Реализовать классический метод составления секретных сообщений, называемый `square code`. | ||
;; Выведите закодированную версию полученного текста. | ||
|
@@ -13,6 +14,9 @@ | |
;; нормализуется в строку: | ||
"ifmanwasmeanttostayonthegroundgodwouldhavegivenusroots" | ||
|
||
(defn is-letter [c] (Character/isLetter c)) | ||
(defn normalize [s] (filter is-letter (str/lower-case s))) | ||
|
||
;; Разбиваем текст в виде прямоугольника. | ||
;; Размер прямоугольника (rows, cols) должен определяться длиной сообщения, | ||
;; так что c >= r и c - r <= 1, где c — количество столбцов, а r — количество строк. | ||
|
@@ -26,15 +30,51 @@ | |
"vegivenu" | ||
"sroots " | ||
|
||
;; Чтение стобцов слева-направо в строку | ||
(defn read-rectangle [rectangle] | ||
(apply str | ||
(loop [result '() | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. если список пустой кавычку можно не ставить это специальный случай There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Спасибо, приму к сведению, переделывать не вижу смысла сейчас) |
||
rectangle rectangle] | ||
(if (empty? (first rectangle)) | ||
result | ||
(recur | ||
(concat result (map first rectangle)) | ||
(map rest rectangle)))))) | ||
|
||
;; Закодированное сообщение получается путем чтения столбцов слева направо. | ||
;; Сообщение выше закодировано как: | ||
"imtgdvsfearwermayoogoanouuiontnnlvtwttddesaohghnsseoau" | ||
(defn encode-helper [input] | ||
(let [normalized (normalize input) | ||
cnt (count normalized) | ||
r (int (Math/sqrt cnt)) | ||
c (if (< (* r r) cnt) (inc r) r) | ||
rectangle (partition-all c normalized)] | ||
(read-rectangle rectangle))) | ||
|
||
;; Полученный закодированный текст разбиваем кусками, которые заполняют идеальные прямоугольники (r X c), | ||
;; с кусочками c длины r, разделенными пробелами. | ||
;; Для фраз, которые на n символов меньше идеального прямоугольника, | ||
;; дополните каждый из последних n фрагментов одним пробелом в конце. | ||
"imtgdvs fearwer mayoogo anouuio ntnnlvt wttddes aohghn sseoau " | ||
(defn encode-string [input] | ||
(let [ | ||
input (encode-helper input) | ||
cnt (count input) | ||
cols-cnt (int (Math/sqrt cnt)) | ||
rows-cnt (if (< (* cols-cnt cols-cnt) cnt) (inc cols-cnt) cols-cnt) | ||
incomplete-cnt (- (* rows-cnt cols-cnt) cnt) | ||
complete-cnt (- rows-cnt incomplete-cnt) | ||
sub-str-cnt (* complete-cnt cols-cnt) | ||
complete-sub-str (subs input 0 sub-str-cnt) | ||
incomplete-sub-str (subs input sub-str-cnt) | ||
complete-slices (partition-all cols-cnt complete-sub-str) | ||
incomplete-slices (partition-all (dec cols-cnt) incomplete-sub-str)] | ||
Comment on lines
+71
to
+72
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. тут можно немного упростить если использовать There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Спасибо за замечание - буду иметь в виду, что есть такая функция) Переделывать не вижу смысла сейчас) |
||
(str/join | ||
" " | ||
(concat | ||
(map #(apply str %) complete-slices) | ||
(map #(apply str (concat % '(\space))) incomplete-slices))))) | ||
|
||
;; Обратите внимание, что если бы мы сложили их, | ||
;; мы могли бы визуально декодировать зашифрованный текст обратно в исходное сообщение: | ||
|
@@ -48,9 +88,6 @@ | |
"aohghn " | ||
"sseoau " | ||
|
||
(defn decode-string [input] | ||
(read-rectangle (str/split input #"\s+"))) | ||
|
||
|
||
(defn encode-string [input]) | ||
|
||
|
||
(defn decode-string [input]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
хорошее решение
есть один совет по стилю. это не ошибка, но иногда приводит в замешательство
y-seq
у вас и имя аргумента и имя переменной в циклеэто еще называется variable shadowing - https://en.wikipedia.org/wiki/Variable_shadowing
во многих компаниях это считается не очень хорошим стилем и программисты стараются этого избегать
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Приму к сведению - переделывать не вижу смысла сейчас)