Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # ტესტი N1
- """
- Author: Luka Tavkhelidze
- Date: 17/10/2020
- """
- # imported modules
- from random import *
- # main function
- def main():
- """
- :description: just wrapps tasks for visual puposes
- :return: Doesn't return anything
- """
- task1()
- task2()
- dict_task3 = task3()
- task4(dict_task3["dict"])
- task5(dict_task3["string"])
- # დავალება N1
- def task1():
- def compare(num):
- compNum = str(sum([int(n) for n in str(num)][:2]))[-1]
- return True if compNum == str(num)[-1] else False
- a = 100
- b = 999
- N = 5000
- nums = [num for _ in range(N) if compare(num := randint(a, b))]
- print("დავალება N1 შედეგი:")
- print(f"\t{nums[:20]}\n" if nums else "\tThere is no number like that\n")
- # დავალება N2
- def task2():
- def compare(num):
- counter = 0
- tmp = []
- for n in str(num):
- if counter < 3:
- tmp.append(int(n))
- counter += 1
- else:
- if str(sum(tmp[:2]))[-1] == str(tmp[-1]):
- tmp = [int(n)]
- counter = 1
- else:
- return False
- return True
- def splitByDigit(num):
- return [int(n) for n in str(num)]
- N = 20
- a = 10 ** 14
- b = int("9" * 15)
- nums = [num for _ in range(N) if compare(num := randint(a, b))]
- result = len([num for num in nums if
- sorted(splitByDigit(num)) == splitByDigit(num)])
- print("დავალება N2 შედეგი:")
- print(f"\t{result}\n" if result else "\tThere is no such number!\n")
- # დავალება N3
- def task3():
- def getkeyname(s):
- if s[0].isdigit() and s[-1].isdigit():
- return tuple([s[0], s[-1]])
- elif s[0].isdigit():
- return s[0]
- elif s[-1].isdigit():
- return s[-1]
- else:
- return 'other'
- alfa = ['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', ' ', '.', ',', ':', ';']
- N = 10000
- punctuation = alfa[-4:]
- string = [choice(alfa) for _ in range(N)]
- tmp_list = []
- dict_strings = {}
- for c in string:
- if c in punctuation:
- c = ' '
- tmp_list.append(c)
- string = ''.join(tmp_list)
- return_string = string
- tmp_list.clear()
- strings = string.split(' ')
- for s in strings:
- if len(s) == 0:
- continue
- key_name = getkeyname(s)
- if key_name in dict_strings.keys():
- dict_strings[key_name].append(s)
- else:
- dict_strings[key_name] = [s]
- for key in dict_strings.keys():
- dict_strings[key] = [int(s) for string in dict_strings[key]
- if (s := ''.join([char for char in string if char.isdigit()]))]
- biggest = []
- key_name = ''
- for key in dict_strings.keys():
- if len(key) == 2:
- if len(dict_strings[key]) > len(biggest):
- biggest = dict_strings[key].copy()
- key_name = key
- print("დავალება N3 შედეგი:")
- print(f"""
- Key: {key_name} Value: {biggest}
- """)
- return_value = {"dict": dict_strings["other"], "string": return_string}
- return return_value
- # დავალება N4
- def task4(other):
- otherlength = len(other) - len(other) // 2
- s1 = set(sample(other, len(other) // 2))
- s2 = set(choice(other) for _ in range(otherlength))
- avg1 = s1.difference(s2)
- avg1 = sum(avg1) / len(avg1)
- avg2 = s2.difference(s1)
- avg2 = sum(avg2) / len(avg2)
- avg3 = s1.intersection(s2)
- avg3 = sum(avg3) / len(avg3)
- largest = {"value": avg1, "text": "s1 - s2"} if avg1 < avg2 else {"value": avg2, "text": "s2 - s1"}
- largest = {"value": avg3, "text": "s1 intersection s2"} if largest["value"] < avg3 else largest
- print("\nდავალება N4 შედეგი:")
- print(f"""\tLargest average is: {largest['text']}
- """)
- # დავალება N5
- def task5(string):
- def getkeyname(s):
- """
- :param s: string value which's first and last values will be
- taken, in order to create a key tuple pair
- :return: it'll return other if string doesn't starts with
- alphanumerical value and ends with digit
- """
- if s[0].isalpha() and s[-1].isdigit():
- return tuple([s[0], s[-1]])
- return "other"
- # temporary list to save sting list "sdfad asdf3 234d" =>["sdfad", "asdf3", "234d"]
- tmp_list = string.split(' ')
- dict_strings = {}
- for string in tmp_list:
- # if string is empty we don't need that so we skip it
- if not string:
- continue
- # here we will get generated key name
- key_name = getkeyname(string)
- # if key exists in dictionary we will add new value to the list
- if key_name in dict_strings.keys():
- dict_strings[key_name].append(string)
- # if it doesn't exists we will the create new one
- else:
- dict_strings[key_name] = [string]
- tmp_dict = {}
- for key in dict_strings.keys():
- if key == "other":
- continue
- # this will clear temporary dictionary
- tmp_dict.clear()
- # this will get key last char, number in this case
- key_name = key[-1]
- for string in dict_strings[key]:
- # this will check if key exists in temporary dictionary
- if key_name in tmp_dict.keys():
- tmp_dict[key_name].append(string)
- else:
- tmp_dict[key_name] = [string]
- # this will overwrite on original dictionary key with temporary dictionary
- dict_strings[key] = tmp_dict.copy()
- def createNumbers(l):
- """
- :param l: it's a list full of string
- example: ["aefueh3", "afe5fuy2r3" ,...]
- :return: result [3, 523, ...] it will take only integer values from string
- and it'll return the list
- """
- #return list with numbers
- return [int(s) for string in l
- if (s := ''.join([c for c in string if c.isdigit()]))]
- for key in dict_strings.keys():
- if key == "other":
- # here we will get "intified" string for key: "other"
- dict_strings[key] = createNumbers(dict_strings[key])
- continue
- for key_name in dict_strings[key]:
- dict_strings[key][key_name] = createNumbers(dict_strings[key][key_name])
- maximum = 0
- m_outer_key = ''
- m_inner_key = ''
- """
- this will find biggest list in dictionary
- """
- for key in dict_strings.keys():
- if key == "other":
- continue
- for key_name in dict_strings[key]:
- if maximum < max(dict_strings[key][key_name]):
- maximum = max(dict_strings[key][key_name])
- m_inner_key = key_name
- m_outer_key = key
- # this is bool function which will check if number on even place is even
- def bool_function(num):
- """
- :param num: takes number as an parameter
- takes digits placed on even indexes
- :return: returns True of False depending wether
- digits on even indexes were even
- """
- if len(str(num)) > 2:
- tmp_num = str(num)[::2]
- for n in tmp_num:
- # checks if digit is even
- if int(n) % 2 != 0:
- return False
- # if number has only one digit it will check if it's an even
- return True if int(str(num)[0]) % 2 == 0 else False
- smallest = sum(dict_strings[m_outer_key][m_inner_key]) / len(dict_strings[m_outer_key][m_inner_key])
- s_inner_key = m_outer_key
- s_outer_key = m_inner_key
- s_value = []
- for key in dict_strings:
- if key == "other":
- continue
- for inner_key in dict_strings[key]:
- """
- CalculatedAvg will get an dictionary pair
- example: {averageValue: 2, acceptable: True}
- acceptable means if list passed passed bool function statement
- """
- calculatedAvg = task6(dict_strings, key, inner_key, bool_function)
- if smallest > calculatedAvg["val"] and calculatedAvg["acceptable"]:
- smallest = calculatedAvg["val"]
- s_inner_key = inner_key
- s_outer_key = key
- s_value = dict_strings[key][inner_key]
- break
- print("დავალება N5 შედეგი:")
- print(f"""
- Outer key: {m_outer_key}:
- Inner key: {m_inner_key}:
- maximum value: {maximum}
- """)
- print("დავალება N6 შედეგი:")
- if smallest != 0:
- print(f"""
- Outer key: {s_outer_key}
- Inner key: {s_inner_key}
- Value: {s_value}
- Average: {smallest}""")
- else:
- print("Couldn't find that kind of elements")
- # დავალება N6
- def task6(dictionary, key="other", inner_key='', function_bool=None):
- def calcAvg(list_name):
- """
- :param list_name: this will get a list from dictionary
- example: {('a', '1'): {'1': [this list]}}
- :return: it will return average of list, which is shown above
- """
- if function_bool:
- """
- if function_bool will be passed
- it will execute the action, it'll take numbers
- from the list test them and return True or False
- """
- list_name = [num for num in list_name if function_bool(num)]
- return sum(list_name) / len(list_name) if list_name else 0
- if isinstance(key, tuple):
- """
- if second argument is a pair of tuple,
- code block will be executed,
- it will initialize inner key and calculate average
- example: {('a', '1'): {'this is inner key': [1,2,3,4]}}
- """
- inner_key = key[-1]
- avg = calcAvg(dictionary[key][inner_key])
- else:
- """
- if passed argument isn't a pair of tuple,
- or it isn't passed at all
- function will calculate average of other in
- dictionary
- example: {"other": [1,2,3,4,5]}
- """
- avg = calcAvg(dictionary[key])
- """
- it will return average value and wether list passed statement in
- passed bool function
- """
- return {"val": int(avg), "acceptable": True} if avg != 0 else {"val": avg, "acceptable": False}
- main()
- """ for key in dict_strings.keys():
- tmp_list2 = []
- for string in dict_strings[key]:
- tmp_list.clear()
- for c in string:
- if c.isdigit():
- tmp_list.append(c)
- if tmp_list:
- tmp_string = ''.join(tmp_list)
- tmp_list2.append(int(tmp_string))
- dict_strings[key] = tmp_list2.copy()"""
Advertisement
Add Comment
Please, Sign In to add comment