PHP, or JavaScript, or C++, Java, Python?
At the expert forum of programmers, hashCode is asked and answered by developers in PHP, JavaScript, C++, Java, Python and other languages. If you look at the topics for the last month, you can assume that those forum members who use the word PHP more often than JavaScript in their posts specialize in PHP. Those forum members whose posts contain the word JavaScript more often than PHP-specialize in JavaScript, and all the others - specialize in JavaScript. C++, or Java, or Python.
So the input is a text containing words in the Russian and English alphabets, including punctuation marks. You need to write code in any suitable programming language that defines the author's specialization.
12 answers
<?php
$string = 'i love java. only java java! i don\'t love javascript, c++, python or php...';
$specialization = array(
'php' => 'PHP-разработчик',
'javascript|js' => 'JavaScript-разработчик',
'c\+\+' => 'C++ разработчик', // для этого и последующих двух можно сделать одно значение, но мне кажется, что это бредовато
'java(?!script)' => 'JAVA-разработчик',
'python' => 'Python-разработчик'
);
$specialization_col = array();
foreach(array_keys($specialization) as $value) {
preg_match_all("/({$value})/", $string, $matches);
$specialization_col[$value] = count($matches[0]);
};
arsort($specialization_col);
echo $specialization_col[$key] > 0 ? $specialization[key($specialization_col)] : 'C++ / Java / Python разработчик';
?>
In 5 lines in Python:
import sys, re, collections
cnt = collections.Counter(re.findall('\w+', sys.stdin.read().lower()))
tpl = 'You are %s programmer'
if cnt['php'] == cnt['javascript']: print(tpl % 'C++, Java or Python')
else: print(tpl % ('PHP' if cnt['php'] > cnt['javascript'] else 'JavaScript'))
Checking it out:
$ echo JavaScript круче, чем PHP! Однако Python более лаконичный язык, чем JavaScript. | python counter.py
You are JavaScript programmer
Delphi
program for_tshirt;
var
s, k : string;
i, php, javascript : integer;
begin
readln(s);
k := '';
for i := 1 to length(s) do
if (s[i] = ' ') or (s[i] in ['a'..'z']) or (s[i] in ['A'..'Z']) then
k := k + upcase(s[i]);
php := 0;
javascript := 0;
k := ' ' + k + ' ';
for i := 1 to length(k) do begin
if (length(k) - i >= 4) then
inc(php, ord(copy(k, i, 5) = ' PHP ')));
if (length(k) - i >= 9) then
inc(javascript, ord(copy(k, i, 10) = ' JAVASCRIPT ')));
end;
if (php > javascript) then
writeln('PHP')
else
if (php < jvascript) then
writeln('JavaScript')
else
writeln('C++ or Java or Python');
end.
Python 2
#set coding=utf-8
s = raw_input()
punct = ".,?!:\"-';"
k = ''
for i in range(len(s)):
bad = False
for j in range(len(punct)):
if (punct[j] == s[i]):
bad = True
if not bad:
k = k + s[i]
else:
k = k + ' '
if (s.count(' PHP ') > s.count(' JavaScript ')):
print('PHP')
elif (s.count(' PHP ') > s.count(' JavaScript ')):
print('JavaScript')
else:
print('C++ or Java or Python.')
<?php
$i = 0;
$max = 0;
$str = "input text";
$langs = array('PHP', 'JavaScript', 'C++', 'Java', 'Python');
foreach($langs as $lang) {
if(substr_count($str, $lang) > $max) {
$max = substr_count($str, $lang);
$result = $lang;
}
if('JavaScript' == $lang) {
$str = str_replace('JavaScript', 'JS', $str);
}
}
print $lang;
?>
I'm not sure if I understood the problem correctly, but here's my solution on JavaScript
:
function count(str, sub) {
var n = 0;
for (str = str.toLowerCase(); str.indexOf(sub) != str.lastIndexOf(sub); n++, str = str.substr(str.indexOf(sub) + sub.length - 1));
if (str.indexOf(sub) > -1) n++;
return n;
}
var s = prompt('Введите сообщение пользователя', '') || '',
php = count(s, 'php'),
js = count(s, 'javascript');
alert('Специализация: ' + (php > js ? 'PHP' : php < js ? 'JavaScript' : 'C++, или Java, или Python') + '.');
#set coding=utf-8
def specialization(message):
punctuation = ".,?!:\"-';"
words = "".join([c for c in message if c not in punctuation]).split()
php = javascript = other = 0
for w in words:
if w == "PHP":
php += 1
elif w == "JavaScript":
javascript += 1
else:
other += 1
if php > javascript:
return u"PHP"
elif javascript < php:
return u"JavaScript"
else:
return u"C++, или Java, или Python"
Python
import sys
import string
js = 0
php = 0
data = sys.stdin.read().lower()
words = data.split(string.punctuation + string.whitespace)
for w in words:
if w == 'php':
php += 1
elif w == 'javascript':
js += 1
if js == php:
print 'C++, Java or Python'
elif js > php:
print 'JavaScript'
else:
print 'PHP'
JavaScript
function qwe(str) {
var res = [0,0,0];
str.replace(
/(php)|(javascript)|(java\b|python|c\+\+)/gi,
function(s, php, js, etc) {
php ? res[0]++ : js ? res[1]++ : res[2]++
});
pro = res[0]>res[1] && res[0]>res[2] ? 'PHP' : res[1]>res[2] ? 'JavaScript' : 'C++, Java or Python';
return "You are "+ pro +" programmer.";
}
console.log(
qwe("На экспертном форуме программистов ХэшКод задают вопросы и дают ответы разработчики на PHP, JavaScript, C++, Java, Python и других языках. Если просмотреть темы за последний месяц, то можно предположить, что те участники форума, в сообщениях которых чаще встречается слово PHP, чем JavaScript - специализируются на PHP. Те участники форума, в сообщениях которых чаще встречается слово JavaScript, чем PHP - специализируются на JavaScript, а все остальные - специализируются C++, или Java, или Python.")
);
// You are C++, Java or Python programmer.
Javascript + black voodoo magic (ternary operators, operator precedence, dynamic typing):
function printFavouriteLang(/* String*/ msg){
var m1,m2,x;
var PHP_REG = /\s?php\s|\s?php$/ig;
var JS_REG = /\s?javascript\s|\s?javascript$/ig;
((x = ((m1 = msg.match(PHP_REG)) ? m1.length : 0) - ((m2 = msg.match(JS_REG)) ? m2.length : 0)) > 0) ? console.log("php") : x == 0 ? console.log("other (java, c#, python)") : console.log("js");
}
I advise you to copy it to the console and play with the function.
Boundary conditions are taken into account:
- 0 or more tokens php
- 0 or more tokens javascript
- Tokens at the end of the message
ZY. Without declaring variables, the function body is placed in 1 line.
Russian letters can be ignored, because the names of programming languages are written in English. And, judging by the condition, you need to take into account only two words 'php', 'javascript'.
var c:char; f:text;
slovo:string;
php,javascript:longint;
{процедура проверки слова}
procedure proveri(s:string);
begin
if (s='php') or (s='Php') or (s='PHP') then inc(php) else
if (s='javascript') or (s='Javascript') or (s='JAVASCTIPT') then inc(javascript);
end;
begin
{связываение с файлом на жёстком диске}
assign(f,'input.txt'); reset(f);
{обнуляем все нужные переменные}
slovo:=''; php:=0; javascript:=0;
{рассматривание данного текста и выбор двух нужных слов 'php' и 'javascript'}
while not eof(f) do
begin
read(f,c);
if ((c>='A') and (c<='Z')) or ((c>='a') and (c<='z')) then slovo:=slovo+c else
if slovo<>'' then
begin
proveri(slovo);
slovo:='';
end;
end;
close(f);
{основное условие}
if php>javascript then writeln('PHP разработчик') else
if php<javascript then writeln('Javascript разработчик') else
writeln('C++ / Java / Python разработчик');
end.
inputStr = 'input text'.lower()
langs = ["php", "javaScript", "c++", "java", "python"]
l = []
for i in langs: l.append(inputStr.count(i))
print(langs[l.index(max(l))])
def rebuild=(level)
delta_attributes :level
scope :moderators, lambda { where("moderator_level > ?", level) }
end