Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 4 months ago.
Improve this question
Could anyone please help with one right solution?
Convert to english with certain spaces between every letter and words.
l did:
eng_dict = {'.-': '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', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
nomorse = input("Enter your code here: ")
nomorse_list = nomorse.split(' ')
text = ''
morse= True
for letter in nomorse_list:
for key in morse_eng_dict.keys():
if letter == key:
text = text + str(morse_eng_dict[key])
if letter == '':
text = text + " "
if morse == True:
string = "".join(text)
print(string)
the problem.. Sometimes there can be not possible conversion of some coded symbols. that symbols can be displayed like " * "
for example: "- .... .. ....... - . .- --" should be "thi* team"
if try to put like
if letter != key:
letter = '*'
text = text + str(morse_eng_dict[key] + '*')
that shows * after every doubled letter
the rest of my attempts all resulted text with spaces in every certain letters.
You can specifically check if a given key is present in the dictionary; you don't have to loop through all possible keys.
if letter in morse_eng_dict:
# letter is in the dict. handle appropriately
else:
# letter is not in the dict. handle appropriately
A couple of notes on the code above. When trying to access the value of a dictionary instead of this...
for key in morse_eng_dict.keys():
if letter == key:
text = text + str(morse_eng_dict[key])
try
if letter in morse_eng_dict:
text = text + str(morse_eng_dict[letter])
This will accomplish the same thing in a much more efficient way.
If you want to only replace dots and dashes, you have a few options. One would be this...
if letter in morse_eng_dict:
text += str(morse_eng_dict[letter])
else:
text += letter
Alternatively, you can use regular expressions to match values and substitute them. In this case r'[\.-]*' can be used to match words morse code words.
Here is a runnable example!
#!/usr/bin/env python
import re
morse_eng_dict = {'.-': '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', '-----': '0',
'.----': '1', '..---': '2', '...--': '3',
'....-': '4', '.....': '5', '-....': '6',
'--...': '7', '---..': '8', '----.': '9'
}
nomorse = input("Enter your Morse code here:")
def replacer(match: re.Match):
m = match.group()
return morse_eng_dict.get(m, m)
text = re.sub(r'[\.-]*', replacer, nomorse)
morse = text != nomorse
if morse:
string = "".join(text)
print(string)
<script src="https://modularizer.github.io/pyprez/pyprez.min.js"></script>
Related
Trying to create a simple caesar cipher ... It fails to work on all characters i.e {,},& etc. How can I modify my code to accomodate all characters possible including Chinese characters
String caesar(String text, int key, int encrypt) {
String result = "";
for (var i = 0; i < text.length; i++) {
int ch = text.codeUnitAt(i), offset, x;
if (ch >= 'a'.codeUnitAt(0) && ch <= 'z'.codeUnitAt(0))
offset = 97;
else if (ch >= 'A'.codeUnitAt(0) && ch <= 'Z'.codeUnitAt(0))
offset = 65;
else if (ch == ' '.codeUnitAt(0)) {
result += " ";
continue;
}
if (encrypt == 1)
x = (ch + key - offset) % 26;
else
x = (ch - key - offset) % 26;
result += String.fromCharCode(x + offset);
}
return result;
}
You'd need to create an alphabet, consisting of a string of all possible characters, and replace 26 with the size of that alphabet (the ABC is just one Western oriented alphabet). Then you can use the zero-based index in the alphabet instead of ch - offset for each character.
You cannot use the same trick with the comparison with A and Z as the code points are not a continuous string of printable characters. That means that adding the key may result in a non-existent or unprintable character value. You could create two methods: toIndex(codeUnit) and toCodeUnit(index) so you can perform any calculation you wish though.
I presume you have enough characters within the normal Chinese character range. If you want to use rare Chinese characters that have a code point higher than 0xFFFF then you may have another problem to solve.
Try it! This only works in english.
import 'dart:io';
// the preset alphabet
List<String> 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'
];
void main() {
stdout.write("Enter the Caesar key: ");
// if the entered k is null, then set k as 0
var k = int.parse(stdin.readLineSync() ?? "0");
stdout.write("Enter the plaintext: ");
// not including the uppercase
var plaintext = (stdin.readLineSync() ?? "").toLowerCase();
var ciphertext = "";
for (var char in plaintext.split('')) {
// if the char is a letter, then match the alphabet
if (char.contains(RegExp(r'[a-z]'))) {
for (var i = 0; i < 26; i++) {
if (alphabet[i] == char) {
// if the matched letter is 26-k below, then find the letter over k interval
if (i < 26 - k) {
ciphertext += alphabet[i + k];
} else {
// if above, return the start point
ciphertext += alphabet[i + k - 26];
}
}
}
} else {
// if not, then simply add it
ciphertext += char;
}
}
print("The ciphertext is: $ciphertext");
}
I need a smart solution for such situation. I have a list of values such as:
{'a', 'b', 'abc', 'd', 'e', 'abc'}
As you can see, the string 'abc' comes twice. I need to delete all elements before first 'abc' and all elements after last 'abc'.
local list = {'a', 'b', 'abc', 'd', 'e', 'abc'}
local doubled_value = get_doubled_value (list) -- returns 'abc'
for i = 1, #list do
if not (list[1] == doubled_value) then
table.remove(list, 1)
else
break
end
end
table.remove is very slow, the easiest way is to create an index for values and make new list:
<script src="https://github.com/fengari-lua/fengari-web/releases/download/v0.1.4/fengari-web.js"></script>
<script type="application/lua">
function doubled_list(list)
local index = {}
for i,n in ipairs(list) do
if index[n] then
local newlist = {}
for j = index[n],i do
newlist[#newlist + 1] = list[j]
end
return newlist
end
index[n] = i
end
return list
end
local list = doubled_list({'a', 'b', 'abc', 'd', 'e', 'abc', 'f', 'g'})
print(table.concat(list,','))
</script>
I've been playing around with arrays, and I don't understand where Nil is coming from and why the a[4] isn't being overwritten. Please see my example below.
a = Array.new
a[5] = '5';
a[0, 3] = 'a', 'b', 'c', 'd';
a[4] = 'hello'
template = ERB.new "<%= a %>"
puts template.result(binding)
Returns me the result
["a", "b", "c", "d", "hello", nil, "5"]
and
a = Array.new
a[4] = '5';
a[0, 3] = 'a', 'b', 'c', 'd';
a[4] = 'hello'
template = ERB.new "<%= a %>"
puts template.result(binding)
Returns me the result
["a", "b", "c", "d", "hello", "5"]
Thanks in advance for the help!
In Ruby when you say:
a[0, 3] = a, b, c
it means that starting from the index 0 start inserting 3 objects into the array. but if you say
a[0, 3] = a, b, c, d
since they are more than three elements, another element is inserted after the third object, therefore shifting 5 and its preceding nil to the next positions.
actually it's:
a[start, length]
not
a[start, end]
The problem (as Pedram explained while I typed this) is that a[0, 3] = 'a', 'b', 'c', 'd' does not replace values from a[0] to a[3]. It replaces 3 values beginning at a[0] (a[0], a[1], and a[2]), but since you are giving it 4 values, it inserts the fourth one as a new element after a[2].
If you want to use a range of indexes, use a[0..3]. Or you can use a[0, 4].
This is simple.
You are defining an Array which is empty at first. In Ruby, if you are inserting a value into an out-of-bound array it will fill all the other past indexes with nil.
For example, if I do:
a = []
a[9] = '10'
puts a
The output will be:
[nil, nil, nil, nil, nil, nil, nil, nil, nil, "10"]
All nine indexes before the one I inserted will be filled with nil. Which is the representation of nothing.
I have a big array of hashes:
array = [
{color: '5 absolute', ... },
{color: '5.0', ... },
{color: '5.1', ... },
{color: 'last', ... },
{color: '50', ... },
{color: '5 elite', ... },
{color: 'edge'}
]
I need colors to ordered:
5 absolute
5 elite
5.0
5.1
50
edge
last
The priority is:
first going spaces ' ',
then dots '.',
then digits '7',
then other 'string'
This is like SQL activerecord analog query, but I don't want that difficult query in the background. I want this logic. How can I do this using AR query?
You could always just sort the array of hashes.
array.map{|h| h[:color]}.sort
=> ["5 absolute", "5 elite", "5.0", "5.1", "50", "edge", "last"]
The following first sorts by number and then by the string after the number.
array = [{color: '5 absolute'}, {color: '5.0'}, {color: '5.1'},
{color: 'last'}, {color: '50'}, {color: '5 elite'},
{color: 'edge'}, {color: '6 absolute'}, {color: '7'}]
array.map{|h| h[:color]}.sort_by do |s|
n = s.to_f
if n == 0 && s.match(/\d/).nil?
n = Float::INFINITY
end
[n, s.split(" ")[-1]]
end
=> ["5.0", "5 absolute", "5 elite", "5.1", "6 absolute", "7", "50", "edge", "last"]
so like this?
h = [{:color=>"5 absolute"},
{:color=>"5.0"},
{:color=>"5.1"},
{:color=>"last"},
{:color=>"50"},
{:color=>"5 elite"},
{:color=>"edge"}]
h.map(&:values).flatten.sort
# => ["5 absolute", "5 elite", "5.0", "5.1", "50", "edge", "last"]
or all the other answers...
From you question it is very hard to tell what you want. Especially since the order you ask for is exactly the same one a normal sort would create.
I any case, here is a way of creating a "custom sort" order the way you wanted. The difference between this and a regular sort is that in this sort can make certain types of characters or sets of characters triumph others.
array = [
{color: '5 absolute'},
{color: '5.0'},
{color: '50 hello'},
{color: 'edge'}
]
p array.sort_by{|x| x[:color]} #=> [{:color=>"5 absolute"}, {:color=>"5.0"}, {:color=>"50 hello"}, {:color=>"edge"}]
# '50 hello' is after '5.0' as . is smaller than 0.
Solving this problem is a bit tricky, here is how I would do it:
# Create a custom sort order using regexp:
# [spaces, dots, digits, words, line_endings]
order = [/\s+/,/\./,/\d+/,/\w+/,/$/]
# Create a union to use in a scan:
regex_union = Regexp.union(*order)
# Create a function that maps the capture in the scan to the index in the custom sort order:
custom_sort_order = ->x{
x[:color].scan(regex_union).map{|x| [order.index{|y|x=~y}, x]}.transpose
}
#Sort:
p array.sort_by{|x| custom_sort_order[x]}
# => [{:color=>"5 absolute"}, {:color=>"50 hello"}, {:color=>"5.0"}, {:color=>"edge"}]
I have a variable called letters which in this instance equals the following:
["a", "e"]
Basically, how can I perform an active record query on my Item's model to find all Items that start with A, B, C, D & E?
Following this link: http://programming-tut.blogspot.ca/2009/10/ruby-on-rails-loop-alphabet-to-z.html
You could do that:
range = [ 'A', 'E' ]
conditions = (range.first..range.last).to_a.map{ |letter| " name ILIKE '#{letter}%' " }.join('OR')
Item.where(conditions)
Or like Vimsha pointed out:
letters = ('A'..'E').to_a
Item.where("substr(name, 1, 1) IN (?)", letters)
Item.where("substr(name, 1, 1) in ('A', 'B', 'C', 'D', 'E')")