Dmitry Telenkov před 1 rokem
rodič
revize
dba74ea30c

+ 7 - 4
codewars.code-workspace

@@ -1,8 +1,11 @@
 {
 	"folders": [
-		{
-			"path": "."
-		}
-	],
+        {
+            "path": "."
+        },
+        {
+            "path": "../tmp"
+        }
+    ],
 	"settings": {}
 }

+ 10 - 1
courses/python_for_begginers/func.py

@@ -744,4 +744,13 @@ def quick_sort(s):
 # print(starts_with("World"))
 
 # average = lambda *args: sum(*args)/len(*args) 
-# print(average((1, 3, 6, 3)))
+# print(average((1, 3, 6, 3)))
+
+def get_days(month):
+	if month in (1, 3, 5, 7, 8, 10, 12):
+		print(31)
+	elif month == 2:
+		print(28)
+	else:
+		print(30)
+	

+ 217 - 1
courses/python_for_begginers/misc.py

@@ -640,6 +640,222 @@ def print_digit_sum(num):
         num = num//10
     print(ret)
 
-print_digit_sum(1035)
+# print_digit_sum(1035)
 
+def get_factors(num):
+    l = []
+    for i in range(1, num + 1):
+        if num%i == 0:
+            l.append(i)
+    return l
 
+# print(get_factors(10))
+
+def number_of_factors(num):
+    return len(get_factors(num))
+               
+# print(number_of_factors(10))
+
+def find_all(target, symbol):
+    l = []
+    s = ""
+    for i in range(len(target)):
+        if target[i] == symbol:
+            l.append(i)
+    return l
+
+# print(find_all('sdfwerasdfqfaf', 's'))
+
+def merge(list1, list2):
+    list1.extend(list2)
+    list1.sort()
+    return list1
+
+# print(merge([1, 2, 3], [5, 6, 7, 8]))
+
+def is_prime(num):
+    cnt = 0
+    for i in range(1, num + 1):
+        if num%i == 0:
+            cnt += 1
+    return cnt == 2
+
+def get_next_prime(num):
+    index = 1
+    while is_prime(num + index) == False:
+        index += 1
+    return num + index
+
+# print(get_next_prime(7))
+
+
+# его длина не менее 8 символов; 
+# он содержит как минимум одну заглавную букву (верхний регистр); 
+# он содержит как минимум одну строчную букву (нижний регистр);
+# он содержит хотя бы одну цифру.
+
+def is_password_good(password):
+    up_flag = False
+    low_flag = False
+    dig_flag = False
+    for i in password:
+        if up_flag == False: up_flag = i.istitle()
+        if low_flag == False: low_flag = i.islower()
+        if dig_flag == False: dig_flag = i.isdigit()
+
+    return len(password) >= 8 and up_flag and low_flag and dig_flag
+
+# print(is_password_good("sfasddfDeqwe"))
+
+
+def is_one_away(word1, word2):
+    cnt = 0
+    len_flag = len(word1) == len(word2)
+
+    if len_flag:
+        for i in range(len(word1)):
+            if word1[i] != word2[i]:
+                cnt +=1
+
+    return len_flag and cnt == 1
+    
+# print(is_one_away("aab", "abc"))
+
+
+def is_palindrome(text:str):
+    s = ''
+    flag = True
+    for i in range(len(text)):
+        if text[i].isalpha():
+            s += text[i].lower()
+
+    for i in range(len(s)//2):
+        if s[i] != s[-1 - i]:
+            flag = False
+
+    return flag
+
+
+# print(is_palindrome("BEEGEEK"))
+
+
+
+    # число a – должно быть палиндромом;
+    # число b – должно быть простым;
+    # число c – должно быть четным.
+
+def is_number_palindrome(num):
+    orig = num
+    new = 0
+    while num:
+        num, d = divmod(num, 10)
+        new = new*10 + d
+
+    return new == orig
+
+def is_simple(num: int):
+    cnt = 0
+    for i in range(1, num + 1):
+        if num%i == 0:
+            cnt += 1
+    return cnt == 2
+
+
+def is_valid_password(password: str):
+    if password.count(":") != 2:
+        return False
+    a, b, c = map(int, password.split(":"))
+
+    return is_number_palindrome(a) and is_simple(b) and c%2 == 0
+
+# print(is_valid_password("24422442:181:890000"))
+
+
+# )(())()(()())((()))()(())
+def is_correct_bracket(text: str):
+    index = 0
+    for i in text:
+        if i == '(':
+            index += 1
+        elif i == ')':
+            index -= 1
+        if index < 0: return False
+    return index == 0
+
+# print(is_correct_bracket("()(())()((())((()))()(())"))
+
+
+def convert_to_python_case(text: str):
+    s = text[0].lower()
+    for i in text[1:]:
+        if i.isupper():
+            s = s + '_' + i.lower()
+        else:
+            s += i
+    return s
+
+# print(convert_to_python_case('ThisIsCamelCased'))
+# print(convert_to_python_case('IsPrimeNumber'))
+
+
+def solve(a, b, c):
+    d = b**2 - 4*a*c
+    if d == 0:
+        return -1*b/(2*a), -1*b/(2*a)
+    x1 = (-1*b + d**0.5)/(2*a)
+    x2 = (-1*b - d**0.5)/(2*a)
+    if x1 <= x2:
+        return x1, x2
+    else:
+        return x2, x1
+
+# вызываем функцию
+# x1, x2 = solve(1, 2, 1)
+# print(x1, x2)
+    
+
+def number_to_words(num):
+    d = {1: 'один', 2: 'два', 3: 'три', 4: 'четыре', 5: 'пять', 6: 'шесть', 7: 'семь', 8: 'восемь', 9: 'девять', 10: 'десять', 11: 'одиннадцать', 12: 'двенадцать', 13: 'тринадцать', 14: 'четырнадцать', 15: 'пятнадцать', 16: 'шестнадцать',17: 'семнадцать', 18: 'восемнадцать', 19: 'девятнадцать', 20: 'двадцать', 30: 'тридцать', 40: 'сорок', 50: 'пятьдесят', 60: 'шестьдесят', 70: 'семьдесят', 80: 'восемьдесят', 90: 'девяносто'}
+    ans = ""
+    f, s = num//10, num%10
+    if num > 20:
+        ans = d[f*10] + " "
+        if s:
+            ans += d[s]
+    else:
+        ans = d[num]
+    return ans
+   
+
+def get_month(language, number):
+    lng_ru = ['январь', 'февраль', 'март', 'апрель', 'май', 'июнь', 'июль', 'август', 'сентябрь', 'октябрь', 'ноябрь', 'декабрь']
+
+    lng_en = ['january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december']
+
+    if language == 'ru':
+        return lng_ru[number - 1]
+    else:
+        return lng_en[number - 1]
+    
+# print(get_month('ru', 1))
+
+def is_magic(date):
+    day, month, year = map(int, date.split('.'))
+    year = year%100
+    return day*month == year
+
+# print(is_magic('10.06.1960'))
+
+from string import ascii_lowercase
+
+def is_pangram(text):
+    flag = True
+    text = text.lower()
+    for i in ascii_lowercase:
+        if i not in text:
+            flag = False
+    return flag
+
+# print(is_pangram('Jackdaws love my big sphinx of quartz'))
+# print(is_pangram('The jay pig fox zebra and my wolves quack'))
+# print(is_pangram('Hello world'))

+ 7 - 0
courses/python_for_begginers/project.py

@@ -0,0 +1,7 @@
+from random import *
+
+print(random())
+print(uniform(1.0, 10.0))
+num = randint(1, 118)
+print(num)
+# print(randrange(1.0, 10.0))

+ 25 - 1
courses/python_for_begginers/sort.py

@@ -271,7 +271,31 @@ def sort_simple_insertion():
         # и вставляем его на индекс j в отсортированной части
         a[j] = elem
 
+    for i in range(1, n):
+        elem = a[1] # первый элемент
+        j = i       
+
 
     print('Отсортированный список:', a)
     
-sort_simple_insertion()
+# sort_simple_insertion()
+    
+#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    
+
+# Бинарный поиск
+def binary_search(list, key):
+    low = 0
+    high = len(list) - 1
+
+    while low <= high:
+        mid = (low + high) // 2
+        midVal = list[mid]
+        if midVal == key:
+            return mid
+        if midVal > key:
+            high = mid - 1
+        else:
+            low = mid + 1
+    return 'not found :('
+
+

+ 0 - 2
docs/arbiter_ip.txt

@@ -1,2 +0,0 @@
-jsonrpc server:
-	API

+ 22 - 0
jsonrpc/arb_test_req.py

@@ -0,0 +1,22 @@
+import jsonrpclib
+from jsonrpclib.SimpleJSONRPCServer import SimpleJSONRPCServer
+
+
+
+class JSONRPCClient:
+
+    def __init__(self):
+        self.client = jsonrpclib.Server("http://{0}:{1}".format("localhost", 8082))
+
+    def test(self):
+        print self.client.get_changes()
+
+client = JSONRPCClient()
+client.test()
+
+
+
+"""
+00000000-0000-0000-0000-000000000002
+
+"""

+ 25 - 2
jsonrpc/opcua_traffic.py

@@ -4,16 +4,39 @@ j_get_configuration = """{"jsonrpc": "2.0", "result": {"1ae20d4e-537b-443f-a494-
 
 jresp_sensors = """{"jsonrpc": "2.0", "result": {"AI4": [null, null, 0], "AI1": ["offline", 7103887, 192], "AI3": [null, null, 0], "AI2": ["offline", 7103887, 192], "DI8": ["0", 7103887, 192], "DI4": ["0", 7103887, 192], "DI5": ["0", 7103887, 192], "DI6": ["0", 7103887, 192], "DI7": ["0", 7103887, 192], "DI1": ["0", 7103887, 192], "DI2": ["0", 7103887, 192], "DI3": ["0", 7103887, 192]}, "id": 3}"""
 
+j_get_sensor_by_alias = """{'dim': '', 'group': 'Inputs', 'name': 'Digital Input #1', 'entrance_delay': 0, 'enabled': True, 'iface_spec': None, 'has_device': False, 'security_type': 'service', 'hysteresis': 0.0, 'states': [{'caption': 'opened', 'state': 'almaj', 'flag': 0, 'value': '0'}, {'caption': 'closed', 'state': 'norm', 'flag': 1, 'value': '1'}, {'caption': 'offline', 'state': 'offline', 'flag': 1, 'value': 'n/a'}], 'alias': 'DI1', 'prefix': '', 'web_name': u'\u0414\u0438\u0441\u043a\u0440\u0435\u0442\u043d\u044b\u0439 \u0432\u0445\u043e\u0434 #1', 'editable': None, 'hidden': False, 'state_template': {'caption': 'Caption of state', 'state': 'Sate of sensor', 'value': ['(0|1)', 'Binary value of sensor (0/1)']}, 'history': {'syslog': False, 'state': True, 'archive': False, 'value': False}}"""
+
+
 def jpars():
     # get_configuration = json.loads(j_get_configuration)
     
     # with open("req.json", 'w') as file:
     #     json.dump(get_configuration, file, indent=2)
 
-    get_configuration = json.loads(jresp_sensors)
+    get_configuration = json.loads(j_get_sensor_by_alias)
 
     with open("req.json", 'w') as file:
         json.dump(get_configuration, file, indent=2)
 
         
-jpars()
+#jpars()
+        
+def creat_resp_1():
+    r = {'dim': '', 'group': 'Inputs', 'name': 'Digital Input #1', 'entrance_delay': 0, 'enabled': True, 'iface_spec': None, 'has_device': False, 'security_type': 'service', 'hysteresis': 0.0, 'states': [{'caption': 'opened', 'state': 'almaj', 'flag': 0, 'value': '0'}, {'caption': 'closed', 'state': 'norm', 'flag': 1, 'value': '1'}, {'caption': 'offline', 'state': 'offline', 'flag': 1, 'value': 'n/a'}], 'alias': 'DI1', 'prefix': '', 'web_name': u'\u0414\u0438\u0441\u043a\u0440\u0435\u0442\u043d\u044b\u0439 \u0432\u0445\u043e\u0434 #1', 'editable': None, 'hidden': False, 'state_template': {'caption': 'Caption of state', 'state': 'Sate of sensor', 'value': ['(0|1)', 'Binary value of sensor (0/1)']}, 'history': {'syslog': False, 'state': True, 'archive': False, 'value': False}}
+    
+    alarm_0_name = ''
+    alarm_1_name = ''
+
+    for l in r["states"]:
+        value = l["value"]
+        if value == '0':
+            alarm_0_name = l['caption']
+        elif value == '1':
+            alarm_1_name = l['caption']
+
+    return [int(r['enabled']), r['web_name'], alarm_0_name, alarm_1_name]
+
+    # return resp
+    
+
+print(creat_resp_1())

+ 0 - 0
jsonrpc/resp.json


+ 23 - 1
leetcode.py

@@ -1,4 +1,5 @@
 # Проверка числа на полиндром
+# divmode(a, b) возвращает картеж: (целая часть от деления a на b, остаток)
 def is_polindrom(x: int) -> bool:
 
     if x < 0:
@@ -12,7 +13,28 @@ def is_polindrom(x: int) -> bool:
 
     return new == orig    
 
-print(is_polindrom(121))
+# print(is_polindrom(121))
 
 
+# Быстрое слияние двух отсортированных списков в один
+def quick_merge(list1, list2):
+    result = []
+    p1 = 0 # указатель на первый элемент списка list1
+    p2 = 0 # указатель на первый элемент списка list2
+
+    while p1 < len(list1) and p2 < len(list2):
+        if list1[p1] < list2[p2]:
+            result.append(list1[p1])
+            p1 += 1
+        else:
+            result.append(list2[p2])
+            p2 += 1
+
+    if p1 < len(list1):
+        result += list1[p1:]
+    else:
+        result += list2[p2:]
+
+    return result
+