Tavxela

Untitled

Oct 18th, 2020 (edited)
633
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # ტესტი N1
  2. """
  3.    Author: Luka Tavkhelidze
  4.    Date:   17/10/2020
  5. """
  6. # imported modules
  7. from random import *
  8.  
  9.  
  10. # main function
  11. def main():
  12.     """
  13.    :description: just wrapps tasks for visual puposes
  14.    :return: Doesn't return anything
  15.    """
  16.     task1()
  17.     task2()
  18.     dict_task3 = task3()
  19.     task4(dict_task3["dict"])
  20.     task5(dict_task3["string"])
  21.  
  22.  
  23. # დავალება N1
  24. def task1():
  25.     def compare(num):
  26.         compNum = str(sum([int(n) for n in str(num)][:2]))[-1]
  27.  
  28.         return True if compNum == str(num)[-1] else False
  29.  
  30.     a = 100
  31.     b = 999
  32.     N = 5000
  33.  
  34.     nums = [num for _ in range(N) if compare(num := randint(a, b))]
  35.  
  36.     print("დავალება N1 შედეგი:")
  37.     print(f"\t{nums[:20]}\n" if nums else "\tThere is no number like that\n")
  38.  
  39.  
  40. # დავალება N2
  41. def task2():
  42.     def compare(num):
  43.         counter = 0
  44.         tmp = []
  45.         for n in str(num):
  46.             if counter < 3:
  47.                 tmp.append(int(n))
  48.                 counter += 1
  49.             else:
  50.                 if str(sum(tmp[:2]))[-1] == str(tmp[-1]):
  51.                     tmp = [int(n)]
  52.                     counter = 1
  53.                 else:
  54.                     return False
  55.         return True
  56.  
  57.     def splitByDigit(num):
  58.         return [int(n) for n in str(num)]
  59.  
  60.     N = 20
  61.     a = 10 ** 14
  62.     b = int("9" * 15)
  63.     nums = [num for _ in range(N) if compare(num := randint(a, b))]
  64.     result = len([num for num in nums if
  65.                   sorted(splitByDigit(num)) == splitByDigit(num)])
  66.  
  67.     print("დავალება N2 შედეგი:")
  68.     print(f"\t{result}\n" if result else "\tThere is no such number!\n")
  69.  
  70.  
  71. # დავალება N3
  72. def task3():
  73.     def getkeyname(s):
  74.         if s[0].isdigit() and s[-1].isdigit():
  75.             return tuple([s[0], s[-1]])
  76.         elif s[0].isdigit():
  77.             return s[0]
  78.         elif s[-1].isdigit():
  79.             return s[-1]
  80.         else:
  81.             return 'other'
  82.  
  83.     alfa = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u',
  84.             'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ' ', '.', ',', ':', ';']
  85.     N = 10000
  86.     punctuation = alfa[-4:]
  87.     string = [choice(alfa) for _ in range(N)]
  88.     tmp_list = []
  89.     dict_strings = {}
  90.  
  91.     for c in string:
  92.         if c in punctuation:
  93.             c = ' '
  94.         tmp_list.append(c)
  95.     string = ''.join(tmp_list)
  96.     return_string = string
  97.     tmp_list.clear()
  98.     strings = string.split(' ')
  99.  
  100.     for s in strings:
  101.         if len(s) == 0:
  102.             continue
  103.         key_name = getkeyname(s)
  104.         if key_name in dict_strings.keys():
  105.             dict_strings[key_name].append(s)
  106.         else:
  107.             dict_strings[key_name] = [s]
  108.  
  109.     for key in dict_strings.keys():
  110.         dict_strings[key] = [int(s) for string in dict_strings[key]
  111.                              if (s := ''.join([char for char in string if char.isdigit()]))]
  112.  
  113.     biggest = []
  114.     key_name = ''
  115.     for key in dict_strings.keys():
  116.         if len(key) == 2:
  117.             if len(dict_strings[key]) > len(biggest):
  118.                 biggest = dict_strings[key].copy()
  119.                 key_name = key
  120.  
  121.     print("დავალება N3 შედეგი:")
  122.     print(f"""
  123.    Key: {key_name}     Value: {biggest}
  124. """)
  125.  
  126.     return_value = {"dict": dict_strings["other"], "string": return_string}
  127.     return return_value
  128.  
  129.  
  130. # დავალება N4
  131. def task4(other):
  132.     otherlength = len(other) - len(other) // 2
  133.     s1 = set(sample(other, len(other) // 2))
  134.     s2 = set(choice(other) for _ in range(otherlength))
  135.  
  136.     avg1 = s1.difference(s2)
  137.     avg1 = sum(avg1) / len(avg1)
  138.  
  139.     avg2 = s2.difference(s1)
  140.     avg2 = sum(avg2) / len(avg2)
  141.  
  142.     avg3 = s1.intersection(s2)
  143.     avg3 = sum(avg3) / len(avg3)
  144.     largest = {"value": avg1, "text": "s1 - s2"} if avg1 < avg2 else {"value": avg2, "text": "s2 - s1"}
  145.     largest = {"value": avg3, "text": "s1 intersection s2"} if largest["value"] < avg3 else largest
  146.  
  147.     print("\nდავალება N4 შედეგი:")
  148.     print(f"""\tLargest average is: {largest['text']}
  149. """)
  150.  
  151.  
  152. # დავალება N5
  153. def task5(string):
  154.     def getkeyname(s):
  155.         """
  156.        :param s: string value which's first and last values will be
  157.            taken, in order to create a key tuple pair
  158.        :return: it'll return other if string doesn't starts with
  159.            alphanumerical value and ends with digit
  160.        """
  161.         if s[0].isalpha() and s[-1].isdigit():
  162.             return tuple([s[0], s[-1]])
  163.         return "other"
  164.  
  165.     # temporary list to save sting list "sdfad asdf3 234d" =>["sdfad", "asdf3", "234d"]
  166.     tmp_list = string.split(' ')
  167.     dict_strings = {}
  168.     for string in tmp_list:
  169.         # if string is empty we don't need that so we skip it
  170.         if not string:
  171.             continue
  172.         # here we will get generated key name
  173.         key_name = getkeyname(string)
  174.         # if key exists in dictionary we will add new value to the list
  175.         if key_name in dict_strings.keys():
  176.             dict_strings[key_name].append(string)
  177.         # if it doesn't exists we will the create new one
  178.         else:
  179.             dict_strings[key_name] = [string]
  180.  
  181.     tmp_dict = {}
  182.     for key in dict_strings.keys():
  183.         if key == "other":
  184.             continue
  185.         # this will clear temporary dictionary
  186.         tmp_dict.clear()
  187.         # this will get key last char, number in this case
  188.         key_name = key[-1]
  189.         for string in dict_strings[key]:
  190.             # this will check if key exists in temporary dictionary
  191.             if key_name in tmp_dict.keys():
  192.                 tmp_dict[key_name].append(string)
  193.             else:
  194.                 tmp_dict[key_name] = [string]
  195.         # this will overwrite on original dictionary key with temporary dictionary
  196.         dict_strings[key] = tmp_dict.copy()
  197.  
  198.     def createNumbers(l):
  199.         """
  200.        :param l: it's a list full of string
  201.            example: ["aefueh3", "afe5fuy2r3" ,...]
  202.        :return: result [3, 523, ...] it will take only integer values from string
  203.            and it'll return the list
  204.        """
  205.         #return list with numbers
  206.         return [int(s) for string in l
  207.         if (s := ''.join([c for c in string if c.isdigit()]))]
  208.  
  209.     for key in dict_strings.keys():
  210.         if key == "other":
  211.             # here we will get "intified" string for key: "other"
  212.             dict_strings[key] = createNumbers(dict_strings[key])
  213.             continue
  214.         for key_name in dict_strings[key]:
  215.             dict_strings[key][key_name] = createNumbers(dict_strings[key][key_name])
  216.  
  217.     maximum = 0
  218.     m_outer_key = ''
  219.     m_inner_key = ''
  220.     """
  221.        this will find biggest list in dictionary
  222.    """
  223.     for key in dict_strings.keys():
  224.         if key == "other":
  225.             continue
  226.         for key_name in dict_strings[key]:
  227.             if maximum < max(dict_strings[key][key_name]):
  228.                 maximum = max(dict_strings[key][key_name])
  229.                 m_inner_key = key_name
  230.                 m_outer_key = key
  231.  
  232.     # this is bool function which will check if number on even place is even
  233.     def bool_function(num):
  234.         """
  235.        :param num: takes number as an parameter
  236.            takes digits placed on even indexes
  237.        :return: returns True of False depending wether
  238.            digits on even indexes were even
  239.        """
  240.         if len(str(num)) > 2:
  241.             tmp_num = str(num)[::2]
  242.             for n in tmp_num:
  243.                 # checks if digit is even
  244.                 if int(n) % 2 != 0:
  245.                     return False
  246.         # if number has only one digit it will check if it's an even
  247.         return True if int(str(num)[0]) % 2 == 0 else False
  248.  
  249.     smallest = sum(dict_strings[m_outer_key][m_inner_key]) / len(dict_strings[m_outer_key][m_inner_key])
  250.     s_inner_key = m_outer_key
  251.     s_outer_key = m_inner_key
  252.     s_value = []
  253.     for key in dict_strings:
  254.         if key == "other":
  255.             continue
  256.         for inner_key in dict_strings[key]:
  257.             """
  258.                CalculatedAvg will get an dictionary pair
  259.                example: {averageValue: 2, acceptable: True}
  260.                acceptable means if list passed passed bool function statement
  261.            """
  262.             calculatedAvg = task6(dict_strings, key, inner_key, bool_function)
  263.             if smallest > calculatedAvg["val"] and calculatedAvg["acceptable"]:
  264.                 smallest = calculatedAvg["val"]
  265.                 s_inner_key = inner_key
  266.                 s_outer_key = key
  267.                 s_value = dict_strings[key][inner_key]
  268.  
  269.             break
  270.  
  271.     print("დავალება N5 შედეგი:")
  272.     print(f"""
  273.    Outer key: {m_outer_key}:
  274.        Inner key: {m_inner_key}:
  275.            maximum value: {maximum}
  276. """)
  277.  
  278.     print("დავალება N6 შედეგი:")
  279.     if smallest != 0:
  280.         print(f"""
  281.    Outer key: {s_outer_key}
  282.        Inner key: {s_inner_key}
  283.            Value:  {s_value}
  284.            Average: {smallest}""")
  285.     else:
  286.         print("Couldn't find that kind of elements")
  287.  
  288.  
  289. # დავალება N6
  290. def task6(dictionary, key="other", inner_key='', function_bool=None):
  291.     def calcAvg(list_name):
  292.         """
  293.        :param list_name: this will get a list from dictionary
  294.            example: {('a', '1'): {'1': [this list]}}
  295.        :return: it will return average of list, which is shown above
  296.        """
  297.         if function_bool:
  298.             """
  299.                if function_bool will be passed
  300.                it will execute the action, it'll take numbers
  301.                from the list test them and return True or False
  302.            """
  303.             list_name = [num for num in list_name if function_bool(num)]
  304.         return sum(list_name) / len(list_name) if list_name else 0
  305.  
  306.     if isinstance(key, tuple):
  307.         """
  308.            if second argument is a pair of tuple,
  309.            code block will be executed,
  310.            it will initialize inner key and calculate average
  311.            example: {('a', '1'): {'this is inner key': [1,2,3,4]}}
  312.        """
  313.         inner_key = key[-1]
  314.         avg = calcAvg(dictionary[key][inner_key])
  315.     else:
  316.         """
  317.            if passed argument isn't a pair of tuple,
  318.            or it isn't passed at all
  319.            function will calculate average of other in
  320.            dictionary
  321.            example: {"other": [1,2,3,4,5]}
  322.        """
  323.         avg = calcAvg(dictionary[key])
  324.  
  325.     """
  326.        it will return average value and wether list passed statement in
  327.        passed bool function
  328.    """
  329.     return {"val": int(avg), "acceptable": True} if avg != 0 else {"val": avg, "acceptable": False}
  330.  
  331.  
  332. main()
  333.  
  334.  
  335. """    for key in dict_strings.keys():
  336.        tmp_list2 = []
  337.        for string in dict_strings[key]:
  338.            tmp_list.clear()
  339.            for c in string:
  340.                if c.isdigit():
  341.                    tmp_list.append(c)
  342.            if tmp_list:
  343.                tmp_string = ''.join(tmp_list)
  344.                tmp_list2.append(int(tmp_string))
  345.  
  346.        dict_strings[key] = tmp_list2.copy()"""
  347.  
RAW Paste Data