blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
3.06M
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
3.06M
217f36600e8b9ab1a86d6324347e9ebddcaf1ea7
MisterHat-89/geekBrainsPython
/lesson_1/exam_3.py
197
3.796875
4
numbers = int(input("Введите число > ")) print(f"{numbers}", "+", f"{numbers}" * 2, "+", f"{numbers}" * 3, "=", int(f"{numbers}") + int(f"{numbers}" * 2) + int(f"{numbers}" * 3))
5867f763f39af1f44c8805e01235068fa92cb1f7
MisterHat-89/geekBrainsPython
/lesson_3/exam_2.py
1,021
3.59375
4
# 2. Реализовать функцию, принимающую несколько параметров, # описывающих данные пользователя: имя, фамилия, год рождения, город проживания, # email, телефон. Функция должна принимать параметры как именованные аргументы. # Реализовать вывод данных о пользователе одной строкой. def base_data(name, surname, date, city, mail, phone): return f"{name} {surname} {date} года рождения, проживает в городе {city}. Email {mail}, Телефон {phone}" print("Результат >> " + base_data(name="Иван", surname="Иванов", date="1989", mail="ivan@mail.ru", city="Москва", phone="8800200"))
6f6a83c6661a2d80a173c1e8b069004e7e8ca744
MisterHat-89/geekBrainsPython
/Lesson_5/exam_2.py
577
4.21875
4
# 2. Создать текстовый файл (не программно), сохранить в нем несколько строк, # выполнить подсчет количества строк, количества слов в каждой строке. text = "" f_file = open(r'dz2.txt', 'r') print(f_file.read()) print("") count_words = 0 lines = 0 f_file.seek(0) for line in f_file.readlines(): lines += 1 count_words = len(line.split(" ")) print(f"В строке {lines} - {count_words} слов") f_file.close() print(f"Строк {lines}")
fe48ded497a4392d05c2d4135d752fe33a92bb13
MisterHat-89/geekBrainsPython
/lesson_4/exam_2.py
846
4.09375
4
# 2. Представлен список чисел. Необходимо вывести элементы исходного списка, # значения которых больше предыдущего элемента. # Подсказка: элементы, удовлетворяющие условию, оформить в виде списка. # Для формирования списка использовать генератор. # Пример исходного списка: [300, 2, 12, 44, 1, 1, 4, 10, 7, 1, 78, 123, 55]. # Результат: [12, 44, 4, 10, 78, 123]. import random first_list = random.sample(range(1000), 15) print(f"Исходный список {first_list}") two_list = [elem for ind, elem in enumerate(first_list) if ind > 0 and elem > first_list[ind-1]] print(f"Результат {two_list}")
68ef6e343455f73bc4af601651462ffaa6c6131f
MisterHat-89/geekBrainsPython
/Lesson_5/exam_6.py
1,734
3.71875
4
# 6. Необходимо создать (не программно) текстовый файл, где каждая строка описывает учебный # предмет и наличие лекционных, практических и лабораторных занятий по этому предмету и их количество. # Важно, чтобы для каждого предмета не обязательно были все типы занятий. Сформировать словарь, содержащий # название предмета и общее количество занятий по нему. Вывести словарь на экран. # Примеры строк файла: # Информатика: 100(л) 50(пр) 20(лаб). # Физика: 30(л) — 10(лаб) # Физкультура: — 30(пр) — # Пример словаря: {“Информатика”: 170, “Физика”: 40, “Физкультура”: 30} def clean_words(string): return "".join(filter(str.isdigit, string)) print("") dicter = {} sum_m = 0 try: with open(r"dz6.txt", "r", encoding="utf-8") as my_file: for line in my_file: clean_line = line.replace("\n", "") lister = clean_line.split(" ") if lister[1] != "—" and lister[1] != "-": sum_m += int(clean_words(lister[1])) if lister[2] != "—" and lister[2] != "-": sum_m += int(clean_words(lister[2])) if lister[3] != "—" and lister[3] != "-": sum_m += int(clean_words(lister[3])) dicter[lister[0][:-1]] = sum_m sum_m = 0 except IOError: print("Error") print(dicter)
642b1efa89b997f236872f4fcb1e7b14281661fe
emrecelik95/CSE321-Homeworks
/HW4/find_kth_book_2_141044024.py
833
3.578125
4
# Emre Celik - 141044024 , CSE 321 - HW4, Part4 # """ find_kth_book_2 fonksiyounda onceki parttan farkli olarak, oncekinde midlerin toplamina bagli olarak ikisini ayri ayri olarak boluyorduk(logm + logn).Burada ikisini ayni birlikte gibi dusunup bolme islemi yapiyoruz(log k). """ def find_kth_book_2(m, n, k): if(len(m) == 0): return n[k - 1] if (len(m) > len(n)): return find_kth_book_2(n, m, k); if(k == 1): return min(m[0], n[0]) i = min(len(m), k//2) j = min(len(n), k//2) if(m[i - 1] > n[j - 1]): return find_kth_book_2(m, n[j:], k - j) return find_kth_book_2(m[i:], n, k - i) m = ["algotihm", "programminglanguages", "systemsprogramming"] n = ["computergraphics", "cprogramming","oop"] book = find_kth_book_2(m,n,6) print(book) #Output: systemsprogramming
3a8034bdfa8a15f2c01b1adc065f5b956874a302
rssbrrw/PythonProgrammingPuzzles
/generators/compression.py
5,928
3.71875
4
"""Puzzles relating to de/compression.""" from puzzle_generator import PuzzleGenerator from typing import List # See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles def _compress_LZW(text): # for development index = {chr(i): i for i in range(256)} seq = [] buffer = "" for c in text: if buffer + c in index: buffer += c continue seq.append(index[buffer]) index[buffer + c] = len(index) + 1 buffer = c if text != "": seq.append(index[buffer]) return seq def _decompress_LZW(seq: List[int]): # for development index = [chr(i) for i in range(256)] pieces = [""] for i in seq: pieces.append(pieces[-1] + pieces[-1][0] if i == len(index) else index[i]) index.append(pieces[-2] + pieces[-1][0]) return "".join(pieces) class LZW(PuzzleGenerator): """ We have provided a simple version of the *decompression* algorithm of [Lempel-Ziv-Welch](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch) so the solution is the *compression* algorithm. """ # _compress_LZW("Hellooooooooooooooooooooo world!") is length-17 @staticmethod def sat(seq: List[int], compressed_len=17, text="Hellooooooooooooooooooooo world!"): """ Find a (short) compression that decompresses to the given string for the provided implementation of the Lempel-Ziv decompression algorithm from https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ index = [chr(i) for i in range(256)] pieces = [""] for i in seq: pieces.append((pieces[-1] + pieces[-1][0]) if i == len(index) else index[i]) index.append(pieces[-2] + pieces[-1][0]) return "".join(pieces) == text and len(seq) <= compressed_len @staticmethod def sol(compressed_len, text): # compressed_len is ignored index = {chr(i): i for i in range(256)} seq = [] buffer = "" for c in text: if buffer + c in index: buffer += c continue seq.append(index[buffer]) index[buffer + c] = len(index) + 1 buffer = c if text != "": seq.append(index[buffer]) return seq def gen(self, _target_num_instances): self.add({"text": "", "compressed_len": 0}) self.add({"text": "c" * 1000, "compressed_len": len(_compress_LZW("c" * 1000))}) def gen_random(self): max_len = self.random.choice([10, 100, 1000]) text = self.random.pseudo_word(0, max_len) self.add({"text": text, "compressed_len": len(_compress_LZW(text))}) class LZW_decompress(PuzzleGenerator): """We have provided a simple version of the [Lempel-Ziv-Welch](https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch) and the solution is the *decompression* algorithm. """ @staticmethod def sat(text: str, seq=[72, 101, 108, 108, 111, 32, 119, 111, 114, 100, 262, 264, 266, 263, 265, 33]): """ Find a string that compresses to the target sequence for the provided implementation of the Lempel-Ziv algorithm from https://en.wikipedia.org/wiki/Lempel%E2%80%93Ziv%E2%80%93Welch """ index = {chr(i): i for i in range(256)} seq2 = [] buffer = "" for c in text: if buffer + c in index: buffer += c continue seq2.append(index[buffer]) index[buffer + c] = len(index) + 1 buffer = c if text != "": seq2.append(index[buffer]) return seq2 == seq @staticmethod def sol(seq): index = [chr(i) for i in range(256)] pieces = [""] for i in seq: pieces.append(pieces[-1] + pieces[-1][0] if i == len(index) else index[i]) index.append(pieces[-2] + pieces[-1][0]) return "".join(pieces) def gen(self, _target_num_instances): for s in ['', 'a', 'b' * 1000, 'ab' * 1000 + '!']: self.add({"seq": _compress_LZW(s)}) def gen_random(self): max_len = self.random.choice([10, 100, 1000]) text = self.random.pseudo_word(0, max_len) self.add({"seq": _compress_LZW(text)}) class PackingHam(PuzzleGenerator): """ This packing problem a [classic problem](https://en.wikipedia.org/wiki/Sphere_packing#Other_spaces) in coding theory. """ @staticmethod def sat(words: List[str], num=100, bits=100, dist=34): """Pack a certain number of binary strings so that they have a minimum hamming distance between each other.""" assert len(words) == num and all(len(word) == bits and set(word) <= {"0", "1"} for word in words) return all(sum([a != b for a, b in zip(words[i], words[j])]) >= dist for i in range(num) for j in range(i)) @staticmethod def sol(num, bits, dist): import random # key insight, use randomness! r = random.Random(0) while True: seqs = [r.getrandbits(bits) for _ in range(num)] if all(bin(seqs[i] ^ seqs[j]).count("1") >= dist for i in range(num) for j in range(i)): return [bin(s)[2:].rjust(bits, '0') for s in seqs] def gen_random(self): bits = self.random.randrange(1, self.random.choice([10, 100])) num = self.random.randrange(2, self.random.choice([10, 100])) def score(seqs): return min(bin(seqs[i] ^ seqs[j]).count("1") for i in range(num) for j in range(i)) # best of 5 seqs = min([[self.random.getrandbits(bits) for _ in range(num)] for _ in range(5)], key=score) dist = score(seqs) if dist > 0: self.add(dict(num=num, bits=bits, dist=dist)) if __name__ == "__main__": PuzzleGenerator.debug_problems()
55f5872fdfa74dc1e61764d2fe484e45be400652
rssbrrw/PythonProgrammingPuzzles
/generators/study.py
12,865
4.15625
4
""" Puzzles used for the study. """ from puzzle_generator import PuzzleGenerator from typing import List # See https://github.com/microsoft/PythonProgrammingPuzzles/wiki/How-to-add-a-puzzle to learn about adding puzzles class Study_1(PuzzleGenerator): @staticmethod def sat(s: str): """Find a string with 1000 'o's but no two adjacent 'o's.""" return s.count('o') == 1000 and s.count('oo') == 0 @staticmethod def sol(): return ('h' + 'o') * 1000 class Study_2(PuzzleGenerator): @staticmethod def sat(s: str): """Find a string with 1000 'o's, 100 pairs of adjacent 'o's and 801 copies of 'ho'.""" return s.count('o') == 1000 and s.count('oo') == 100 and s.count('ho') == 801 @staticmethod def sol(): return 'ho' * (800 + 1) + 'o' * (100 * 2 - 1) class Study_3(PuzzleGenerator): @staticmethod def sat(li: List[int]): """Find a permutation of [0, 1, ..., 998] such that the ith element is *not* i, for all i=0, 1, ..., 998.""" return sorted(li) == list(range(999)) and all(li[i] != i for i in range(len(li))) @staticmethod def sol(): return [((i + 1) % 999) for i in range(999)] class Study_4(PuzzleGenerator): @staticmethod def sat(li: List[int]): """Find a list of length 10 where the fourth element occurs exactly twice.""" return len(li) == 10 and li.count(li[3]) == 2 @staticmethod def sol(): return list(range(10 // 2)) * 2 class Study_5(PuzzleGenerator): @staticmethod def sat(li: List[int]): """Find a list integers such that the integer i occurs i times, for i = 0, 1, 2, ..., 9.""" return all([li.count(i) == i for i in range(10)]) @staticmethod def sol(): return [i for i in range(10) for j in range(i)] class Study_6(PuzzleGenerator): @staticmethod def sat(i: int): """Find an integer greater than 10^10 which is 4 mod 123.""" return i % 123 == 4 and i > 10 ** 10 @staticmethod def sol(): return 4 + 10 ** 10 + 123 - 10 ** 10 % 123 class Study_7(PuzzleGenerator): @staticmethod def sat(s: str): """Find a three-digit pattern that occurs more than 8 times in the decimal representation of 8^2888.""" return str(8 ** 2888).count(s) > 8 and len(s) == 3 @staticmethod def sol(): s = str(8 ** 2888) return max({s[i: i + 3] for i in range(len(s) - 2)}, key=lambda t: s.count(t)) class Study_8(PuzzleGenerator): @staticmethod def sat(ls: List[str]): """Find a list of more than 1235 strings such that the 1234th string is a proper substring of the 1235th.""" return ls[1234] in ls[1235] and ls[1234] != ls[1235] @staticmethod def sol(): return [''] * 1235 + ['a'] class Study_9(PuzzleGenerator): @staticmethod def sat(li: List[int]): """ Find a way to rearrange the letters in the pangram "The quick brown fox jumps over the lazy dog" to get the pangram "The five boxing wizards jump quickly". The answer should be represented as a list of index mappings. """ return ["The quick brown fox jumps over the lazy dog"[i] for i in li] == list( "The five boxing wizards jump quickly") @staticmethod def sol(): return ['The quick brown fox jumps over the lazy dog'.index(t) for t in 'The five boxing wizards jump quickly'] class Study_10(PuzzleGenerator): @staticmethod def sat(s: str): """Find a palindrome of length greater than 11 in the decimal representation of 8^1818.""" return s in str(8 ** 1818) and s == s[::-1] and len(s) > 11 @staticmethod def sol(): s = str(8 ** 1818) return next(s[i: i + le] for le in range(12, len(s) + 1) for i in range(len(s) - le + 1) if s[i: i + le] == s[i: i + le][::-1] ) class Study_11(PuzzleGenerator): @staticmethod def sat(ls: List[str]): """ Find a list of strings whose length (viewed as a string) is equal to the lexicographically largest element and is equal to the lexicographically smallest element. """ return min(ls) == max(ls) == str(len(ls)) @staticmethod def sol(): return ['1'] class Study_12(PuzzleGenerator): @staticmethod def sat(li: List[int]): """Find a list of 1,000 integers where every two adjacent integers sum to 9, and where the first integer plus 4 is 9.""" return all(i + j == 9 for i, j in zip([4] + li, li)) and len(li) == 1000 @staticmethod def sol(): return [9 - 4, 4] * (1000 // 2) class Study_13(PuzzleGenerator): @staticmethod def sat(x: float): """Find a real number which, when you subtract 3.1415, has a decimal representation starting with 123.456.""" return str(x - 3.1415).startswith("123.456") @staticmethod def sol(): return 123.456 + 3.1415 class Study_14(PuzzleGenerator): @staticmethod def sat(li: List[int]): """Find a list of integers such that the sum of the first i integers is i, for i=0, 1, 2, ..., 19.""" return all([sum(li[:i]) == i for i in range(20)]) @staticmethod def sol(): return [1] * 20 class Study_15(PuzzleGenerator): @staticmethod def sat(li: List[int]): """Find a list of integers such that the sum of the first i integers is 2^i -1, for i = 0, 1, 2, ..., 19.""" return all(sum(li[:i]) == 2 ** i - 1 for i in range(20)) @staticmethod def sol(): return [(2 ** i) for i in range(20)] class Study_16(PuzzleGenerator): @staticmethod def sat(s: str): """Find a real number such that when you add the length of its decimal representation to it, you get 4.5. Your answer should be the string form of the number in its decimal representation.""" return float(s) + len(s) == 4.5 @staticmethod def sol(): return str(4.5 - len(str(4.5))) class Study_17(PuzzleGenerator): @staticmethod def sat(i: int): """Find a number whose decimal representation is *a longer string* when you add 1,000 to it than when you add 1,001.""" return len(str(i + 1000)) > len(str(i + 1001)) @staticmethod def sol(): return -1001 class Study_18(PuzzleGenerator): @staticmethod def sat(ls: List[str]): """ Find a list of strings that when you combine them in all pairwise combinations gives the six strings: 'berlin', 'berger', 'linber', 'linger', 'gerber', 'gerlin' """ return [s + t for s in ls for t in ls if s != t] == 'berlin berger linber linger gerber gerlin'.split() @staticmethod def sol(): seen = set() ans = [] for s in 'berlin berger linber linger gerber gerlin'.split(): t = s[:3] if t not in seen: ans.append(t) seen.add(t) return ans class Study_19(PuzzleGenerator): """ 9/15/2021 Updated to take a list rather than a set because it was the only puzzle in the repo with Set argument. """ @staticmethod def sat(li: List[int]): """ Find a list of integers whose pairwise sums make the set {0, 1, 2, 3, 4, 5, 6, 17, 18, 19, 20, 34}. That is find L such that, { i + j | i, j in L } = {0, 1, 2, 3, 4, 5, 6, 17, 18, 19, 20, 34}. """ return {i + j for i in li for j in li} == {0, 1, 2, 3, 4, 5, 6, 17, 18, 19, 20, 34} @staticmethod def sol(): return [0, 1, 2, 3, 17] class Study_20(PuzzleGenerator): """A more interesting version of this puzzle with a length constraint is ShortIntegerPath in graphs.py""" @staticmethod def sat(li: List[int]): """ Find a list of integers, starting with 0 and ending with 128, such that each integer either differs from the previous one by one or is thrice the previous one. """ return all(j in {i - 1, i + 1, 3 * i} for i, j in zip([0] + li, li + [128])) @staticmethod def sol(): return [1, 3, 4, 12, 13, 14, 42, 126, 127] class Study_21(PuzzleGenerator): @staticmethod def sat(li: List[int]): """ Find a list integers containing exactly three distinct values, such that no integer repeats twice consecutively among the first eleven entries. (So the list needs to have length greater than ten.) """ return all([li[i] != li[i + 1] for i in range(10)]) and len(set(li)) == 3 @staticmethod def sol(): return list(range(3)) * 10 class Study_22(PuzzleGenerator): @staticmethod def sat(s: str): """ Find a string s containing exactly five distinct characters which also contains as a substring every other character of s (e.g., if the string s were 'parrotfish' every other character would be 'profs'). """ return s[::2] in s and len(set(s)) == 5 @staticmethod def sol(): return """abacadaeaaaaaaaaaa""" class Study_23(PuzzleGenerator): @staticmethod def sat(ls: List[str]): """ Find a list of characters which are aligned at the same indices of the three strings 'dee', 'doo', and 'dah!'. """ return tuple(ls) in zip('dee', 'doo', 'dah!') @staticmethod def sol(): return list(next(zip('dee', 'doo', 'dah!'))) class Study_24(PuzzleGenerator): @staticmethod def sat(li: List[int]): """Find a list of integers with exactly three occurrences of seventeen and at least two occurrences of three.""" return li.count(17) == 3 and li.count(3) >= 2 @staticmethod def sol(): return [17] * 3 + [3] * 2 class Study_25(PuzzleGenerator): @staticmethod def sat(s: str): """Find a permutation of the string 'Permute me true' which is a palindrome.""" return sorted(s) == sorted('Permute me true') and s == s[::-1] @staticmethod def sol(): s = sorted('Permute me true'[1:])[::2] return "".join(s + ['P'] + s[::-1]) class Study_26(PuzzleGenerator): @staticmethod def sat(ls: List[str]): """Divide the decimal representation of 8^88 up into strings of length eight.""" return "".join(ls) == str(8 ** 88) and all(len(s) == 8 for s in ls) @staticmethod def sol(): return [str(8 ** 88)[i:i + 8] for i in range(0, len(str(8 ** 88)), 8)] class Study_27(PuzzleGenerator): @staticmethod def sat(li: List[int]): """ Consider a digraph where each node has exactly one outgoing edge. For each edge (u, v), call u the parent and v the child. Then find such a digraph where the grandchildren of the first and second nodes differ but they share the same great-grandchildren. Represented this digraph by the list of children indices. """ return li[li[0]] != li[li[1]] and li[li[li[0]]] == li[li[li[1]]] @staticmethod def sol(): return [1, 2, 3, 3] class Study_28(PuzzleGenerator): """9/15/2021: updated to a list since sets were removed from puzzle formats""" @staticmethod def sat(li: List[int]): """Find a list of one hundred integers between 0 and 999 which all differ by at least ten from one another.""" return all(i in range(1000) and abs(i - j) >= 10 for i in li for j in li if i != j) and len(set(li)) == 100 @staticmethod def sol(): return list(range(0, 1000, 10)) class Study_29(PuzzleGenerator): """9/15/2021: updated to a list since sets were removed from puzzle formats""" @staticmethod def sat(l: List[int]): """ Find a list of more than 995 distinct integers between 0 and 999, inclusive, such that each pair of integers have squares that differ by at least 10. """ return all(i in range(1000) and abs(i * i - j * j) >= 10 for i in l for j in l if i != j) and len(set(l)) > 995 @staticmethod def sol(): return [0, 4] + list(range(6, 1000)) class Study_30(PuzzleGenerator): @staticmethod def sat(li: List[int]): """ Define f(n) to be the residue of 123 times n mod 1000. Find a list of integers such that the first twenty one are between 0 and 999, inclusive, and are strictly increasing in terms of f(n). """ return all([123 * li[i] % 1000 < 123 * li[i + 1] % 1000 and li[i] in range(1000) for i in range(20)]) @staticmethod def sol(): return sorted(range(1000), key=lambda n: 123 * n % 1000)[:21] @staticmethod def sol_surprisingly_short(): return list(range(1000))[::8][::-1] if __name__ == "__main__": PuzzleGenerator.debug_problems()
85f39d8cbab6bad1e778bea01c132b931b15e21b
benmazur/Arithmetic-Tutor-Python-Program
/program1.py
13,572
4.34375
4
# Stephen Buchanan, Benjamin Mazur, Section 20L, 10/12/13 # Program 1 # Program 6-13 #imporing libraries from cisc106_32 import* import random # seting a globle variable for Random Number RANDOM_NUMBER1 = random.randint(1, 100) RANDOM_NUMBER2 = random.randint(1, 100) # Choices for the Menu ADDITION = "a" SUBTRACTION = "s" MULTIPLICATION = "m" DIVISION = "d" EXPONENTIATION = "e" RANDOMIZE = "r" QUIT_PROGRAM = "q" # The operation functions def Addition(): """ adds two random integers and checks if the inputted answer is correct and if not asks again for the answer 3 times before giving the answer. It will also ask 4 random addition questions from being called till it returns to the main function parameters: none Variables first - a random integer from the random library second - a random integer from the random library add - adds the first and second random integers together input_answer - the users answer """ print("\nYou have selected addition \n") for number_of_problems in range(0,4,1): first = random.randint(1, 100) second = random.randint(1, 100) add = first + second print("How much is", first," plus ", second, "?") input_answer = int(input()) if (input_answer == add): print("\tCorrect!") if ( input_answer != add): for number_of_answer in range(1,3,1): if ( input_answer != add): print("Incorrect, please try again: \n") print("How much is", first," plus ", second, "?") input_answer = int(input()) if input_answer != add: print("\tSorry, you missed this one. The correct answer is",add, ".\n ") else: print("\tCorrect!\n") input("Please press enter for another question \n") print("You have completed all 4 practice problems for this section. Redirecting you back to the main menu.\n") input("Please press enter to select another operation\n") return(Main_Body_Function()) # The Function for subtraction def Subtraction(): """ subtracts two random integers and checks if the inputted answer is correct and if not asks again for the answer 3 times before giving the answer. It will also ask 4 random subtraction questions from being called till it returns to the main function. parameters: none Variables first - a random integer from the random library second - a random integer from the random library sub - subtracts the second random integer from the first input_answer - the users answer """ print("\nYou have selected subtraction \n") for number_of_problems in range(0,4,1): first = random.randint(1, 100) second = random.randint(1, 100) subtract = first - second print("How much is", first," minus ", second, "?") input_answer = int(input()) if (input_answer == subtract): print("\tCorrect!") if ( input_answer != subtract): for number_of_answer in range(1,3,1): if ( input_answer != subtract): print("Incorrect, please try again: \n") print("How much is", first," minus ", second, "?") input_answer = int(input()) if input_answer != subtract: print("\tSorry, you missed this one. The correct answer is", subtract, ".\n ") else: print("\tCorrect!\n") input("Please press enter for another question \n") print("You have completed all 4 practice problems for this section. Redirecting you back to the main menu.\n") input("Please press enter to select another operation\n") return(Main_Body_Function()) #The Function for Multiplication def Multiplication(): """ multiplies two random integers and checks if the inputted answer is correct and if not asks again for the answer 3 times before giving the answer. It will also ask 4 random multiplication questions from being called till it returns to the main function. Parameters: none Variables first - a random integer from the random library second - a random integer from the random library multiply - the first random integer times the second input_answer - the users answer """ print("\nYou have selected multiplication \n") for number_of_problems in range(0,4,1): first = random.randint(1, 100) second = random.randint(1, 100) multiply = first * second print("How much is", first," times ", second, "?") input_answer = int(input()) if (input_answer == multiply): print("\tCorrect!") if ( input_answer != multiply): for number_of_answer in range(1,3,1): if ( input_answer != multiply): print("Incorrect, please try again: \n") print("How much is", first," times ", second, "?") input_answer = int(input()) if input_answer != multiply: print("\tSorry, you missed this one. The correct answer is", multiply , ".\n ") else: print("\tCorrect!\n") input("Please press enter for another question \n") print("You have completed all 4 practice problems for this section. Redirecting you back to the main menu.\n") input("Please press enter to select another operation\n") return(Main_Body_Function()) #The Function for division def Division(): """ divides two random integers and checks if the inputted answer is correct and if not asks again for the answer 3 times before giving the answer. It will also ask 4 random multiplication questions from being called till it returns to the main function. There is also a while loop that makes sure that the function will not randomly select problems with answers that are not integers. Parameters: none Variables first - a random integer from the random library second - a random integer from the random library divide - the first random integer divided by the second input_answer - the users answer """ print("\nYou have selected division \n") for number_of_problems in range(0,4,1): first = random.randint(1, 100) second = random.randint(1, 100) divide = first / second int_dividing = int(divide) while divide != int_dividing: first = random.randint(1, 100) second = random.randint(1, 100) divide = first / second int_dividing = int(divide) print("How much is", first," divided by ", second, "?") input_answer = int(input()) if (input_answer == divide): print("\tCorrect!") if ( input_answer != divide): for number_of_answer in range(1,3,1): if ( input_answer != divide): print("Incorrect, please try again: \n") print("How much is", first," divided by ", second, "?") input_answer = int(input()) if input_answer != divide: print("\tSorry, you missed this one. The correct answer is", int(divide) , ".\n ") else: print("\tCorrect!\n") input("Please press enter for another question \n") print("You have completed all 4 practice problems for this section. Redirecting you back to the main menu.\n") input("Please press enter to select another operation\n") return(Main_Body_Function()) # The Function for Exponetiation def Exponentiation(): """ Uses one random integer and raises it to the power of another random integer and checks if the inputted answer is correct and if not asks again for the answer 3 times before giving the answer. It will also ask 4 random multiplication questions from being called till it returns to the main function. there is a while loop that makes sure that the answer does not exceed 2500 to make the questions easier. Parameters: none Variables first - a random integer from the random library second - a random integer from the random library power - the first random integer to the power of the second input_answer - the users answer """ print("\nYou have selected exponentiation \n") for number_of_problems in range(0,4,1): first = random.randint(1, 100) second = random.randint(1, 100) power = first ** second while (power > 2500): first = random.randint(1, 100) second = random.randint(1, 100) power = first ** second print("How much is", first," to the power of ", second, "?") input_answer = int(input()) if (input_answer == power): print("\tCorrect!") if ( input_answer != power): for number_of_answer in range(1,3,1): if ( input_answer != power): print("Incorrect, please try again: \n") print("How much is", first," to the power of ", second, "?") input_answer = int(input()) if input_answer != power: print("\tSorry, you missed this one. The correct answer is", power , ".\n ") else: print("\tCorrect!\n") input("Please press enter for another question \n") print("You have completed all 4 practice problems for this section. Redirecting you back to the main menu.\n") input("Please press enter to select another operation\n") return(Main_Body_Function()) def Randomize(): """ Randomly selects an operation from the main menu so that the user can do a random problem. Parameters None Variables None """ print("\nYou have selected randomize \n") #choices = [, SUBTRACTION, MULTIPLICATION, DIVISION, EXPONENTIATION, QUIT_PROGRAM] #random.shuffle(choices) random_choice = random.sample(["a","s","m","d","e"], 1) if random_choice == ["a"]: Addition() return(None) elif random_choice == ["s"]: Subtraction() return(None) elif random_choice == ["m"]: Multiplication() return(None) elif random_choice == ["d"]: Division() return(None) elif random_choice == ["e"]: Exponentiation() return(None) # The menue def display_menu(): """ Displays the main mein whenever called. Parameters None Variables None """ print("Type any of the following single letter operations to start the designated math problems.\ {a, s, m, d, e, q}\n") print("\ta for addition") print("\ts for subtraction") print("\tm for mulitplication") print("\td for division") print("\te for exponentiation") print("\tr for random") print("\tq to quit the program\n") #The Welcome def Welcome(): """ Prints a welcome statement that explains what the function is. """ print("Welcome to the CISC 106 Basic Math Instructor. \ This program allows you to practice your math skills in addition, \ subtraction, multiplication, division and exponentiation.\n") #return and main body function def Main_Body_Function(): """ This is what would normally be written into the ‘main’ function of the program but is displayed as a separate function so as to be called by other functions. Parameters None Variables None """ #display menu display_menu() # Get users choice operation = input("Type in operation now: \n") while operation != QUIT_PROGRAM: # Finding and Running the operation of choice if operation == ADDITION: Addition() return(None) elif operation == SUBTRACTION: Subtraction() return(None) elif operation == MULTIPLICATION: Multiplication() return(None) elif operation == DIVISION: Division() return(None) elif operation == EXPONENTIATION: Exponentiation() return(None) elif operation == RANDOMIZE: Randomize() return(None) else: print("Error: You have selected an invalid option.") operation = input("Please try again: \n") else: print("Thank you for using the CISC 106 Basic Math Instructor. Please Come again.") # The body of the program def main(): """ where the program starts executing and where all the functions are called from. Parameters None Variables None """ #Say welcome Welcome() #Calling the Main Body Function Main_Body_Function() main()
f91c87f85bb2a97e6dea6d3e0d622ad4b003e239
rasooll/Python-Learning
/azmoon4/part2.py
364
4.34375
4
def find_longest_word(input_string): maxlen = 0 maxword = "" input_list = input_string.split() #print (input_list) for word in input_list: #print (len(word)) if len(word) >= maxlen: maxlen = len(word) maxword = word #print (maxlen, maxword) return maxword print (find_longest_word("salam in ye matn azmayeshi baraye test matnibebozorgiein ast"))
da7f8c996bf6f38707729fbd13cce8140fa1a23d
rasooll/Python-Learning
/week6/Tamrin/vowels.py
233
3.703125
4
def _vowels_ (simple_string): number = 0 simple_string = simple_string.lower() vowels_character_list = ['a', 'e', 'o', 'i', 'u'] for char in simple_string: if char in vowels_character_list: number = number + 1 return number
7ade4f97ff1803bbe46d68add6243f30e80823bd
rasooll/Python-Learning
/week7/dict.p6.py
489
3.765625
4
def _dictionary_of_vowel_counts_sample_(sample_string): sample_string_nospace = sample_string.replace(' ', '') sample_string_nospace_lower = sample_string_nospace.lower() vowels_character_list = ['a', 'e', 'o', 'i', 'u'] out_dict = {} for character in sample_string_nospace_lower: if character in vowels_character_list: out_dict[character] = sample_string_nospace_lower.count(character) return out_dict print (_dictionary_of_vowel_counts_sample_("salam in ye payame test ast."))
0bde03414b3719f3371f80a58e28891d0656ed43
rasooll/Python-Learning
/Tamrin_Lists/Adad-zoj-beyn-a-b.py
131
3.5625
4
def adadezoj(a, b): i = a mylist = [] while (i >= a) and (i < b): if (i%2) == 0 : mylist.append(i) i = i+1 return mylist
8f2063568eb595274faa40e44467ad465f459b2d
rasooll/Python-Learning
/mian-term/barname4.py
388
3.625
4
# Type your code here def crazy_list(some_list): mylist = some_list lenlist = len(mylist) aval = 0 akhar = -1 natije = 0 for i in range(0,lenlist): if mylist[aval] != mylist[akhar]: natije = natije + 1 aval = aval + 1 akhar = akhar - 1 if natije == 0: return True else: return False listam = [5, 6, 8, 7, 'PYTHON', 9, 8, 6, 5] print (crazy_list(listam))
05bcd827387fb6eb5e287f015f3a2f37d8e34bba
rasooll/Python-Learning
/Taklif2/part2.py
227
3.71875
4
def single_insert_or_delete(s1,s2): if len(s1) == len(s2): s1 = s1.lower() s2 = s2.lower() if s1 == s2: return 0 else: return 2 elif (len(s1) == len(s2)-1) or (len(s1) == len(s2)+1): return 1 else: return 2
cce4f590479204726328e9c785ca28c44afd9e23
rasooll/Python-Learning
/Tamrin_Lists/unique_list_sample2.py
155
3.6875
4
def unique_list_sample(A, B): mylist = A + B newlist = [] for element in mylist: if element not in newlist: newlist.append(element) return newlist
ccca796e469d40985f53e3665c8a054ffdeae183
rasooll/Python-Learning
/week6/methods/5.py
239
4.03125
4
#x="hello are you there" #print (x.split()) #my_str = "hello hello" #print (my_str.split('l')) my_str='Computer science' print (my_str.split ('e')) x="frequency of letters" print (x.split("e",2)) x="Mississippi" print (x.split("s",3))
0607152164dde883d6aa224c21964f90b80de5b9
sorb999/machine-Learning
/others/dataframe.py
437
4.09375
4
# dataframe import numpy import pandas myarray = numpy.array([[1, 2, 3], [4, 5, 6]]) rownames = ['a', 'b'] colnames = ['one', 'two', 'three'] mydataframe = pandas.DataFrame(myarray, index=rownames, columns=colnames) print('myarray:') print(myarray) print('rownames:') print(rownames) print('colnames:') print(colnames) print('mydataframe:') print(mydataframe) print('return first 2 rows:') rows = mydataframe.head(2); print(rows)
0104bed0a328f02fdd5a350ce42f1cbbfb3c6714
FajnyNick2121/wd_zaocznie_1
/start.py
279
3.609375
4
print("Hello world!") # def main(): # for elem in kolekcja: # costam() # lancuchy znakow liczba = "ala" liczba = 0 liczba = 0.01 # PEP8 imie = "ala" print(imie) print(type(imie)) print(type(5)) print(type(5.5)) print(type(True)) imie= str("Ala") liczba= str(100)
1269f7390bfc63e8962b3bda78a114500e5f03fa
Nilesh2000/CollegeRecordWork
/Semester 2/Ex12d.py
1,087
4.25
4
myDict1 = {'Name':'Nilesh', 'RollNo':69, 'Dept':'IT', 'Age':18} #print dictionary print("\nDictionary elements : ", myDict1) #Printing Values by passing keys print("Student department : ", myDict1['Dept']) #Editing dictionary elements myDict1['Dept']="CSE" print("After Editing dictionary elements : " , myDict1) #Adding a element myDict1['College'] = 'SVCE' print("After appending : ", myDict1) #Number of dictionary elements print("Number of dictionary elements : ", len(myDict1)) #string representation of the dictionary print("String representation : ", str(myDict1)) #Returning correseponding value of the passed key print("College is : ", myDict1.get('College')) #List of keys print("The keys in the dictionary are : ", myDict1.keys()) #List of values print("The values in the dictionary are : ", myDict1.values()) #deleting dictionary elements del myDict1['RollNo'] print("Dictionary after deleting key RollNo : ", myDict1) #Deleting using pop() myDict1.pop('Age') print("Dictionary after popping key Age is : ", myDict1) #Deleting complete dictionary myDict1.clear()
38d36983198c2526c4979fc7f1fc30883f19bb8f
Nilesh2000/CollegeRecordWork
/Semester 2/Ex10a.py
496
3.671875
4
class Student: def get_details(self): self.name = input("Enter you name : ") self.rollNo = input("Enter roll number : ") self.dept = input("Enter Department : ") def show_details(self): print("\nStudent name : ", self.name) print("Student roll number : ", self.rollNo) print("Student Department : " , self.dept) def main(): Obj = Student() Obj.get_details() Obj.show_details() if __name__ == "__main__": main()
fe6020694e7d2a60f3543d99df991d97a00563cc
Nilesh2000/CollegeRecordWork
/Semester 2/Ex11a.py
528
3.921875
4
class Base: def __init__(self, a, b): self.a = a self.b = b class Derived(Base): def addNumbers(self): self.Add = self.a + self.b return self.Add def subNumbers(self): self.Diff = self.a - self.b return self.Diff def main(): Obj = Derived(5, 2) print("A = ", Obj.a) print("B = ", Obj.b) print("Sum of A and B is : ", Obj.addNumbers()) print("Difference of A and B is : ", Obj.subNumbers()) if __name__ == "__main__": main()
44012b8dd752a03b4f333c055d6fcdb4ecf136ed
paradisees/test
/interview/tree.py
1,137
3.984375
4
class TreeNode(object): def __init__(self,data=0,left=0,right=0): self.data=data self.left=left self.right=right class BTree(object): def __init__(self,root=0): self.root=root def preOrder(self,treenode): if treenode is 0: return print(treenode.data) self.preOrder(treenode.left) self.preOrder(treenode.right) def inOrder(self,treenode): if treenode is 0: return self.inOrder(treenode.left) print (treenode.data) self.inOrder(treenode.right) def postOrder(self,treenode): if treenode is 0: return self.postOrder(treenode.left) self.postOrder(treenode.right) print (treenode.data) n1 = TreeNode(data=1) n2 = TreeNode(2,n1,0) n3 = TreeNode(3) n4 = TreeNode(4) n5 = TreeNode(5,n3,n4) n6 = TreeNode(6,n2,n5) n7 = TreeNode(7,n6,0) n8 = TreeNode(8) root = TreeNode('root',n7,n8) bt = BTree(root) print ('preOrder......') print (bt.preOrder(bt.root)) print ('inOrder......') print (bt.inOrder(bt.root)) print ('postOrder.....') print (bt.postOrder(bt.root))
1a6ac55613557bcf7fba290cc6dbe335fbaf4031
Kanrail/5143_Shell_Project
/cmd_pkg/chmod.py
804
3.734375
4
import os def chmod (**kwargs): """ CHMOD User Commands CHMOD NAME chmod - changes the permissions of file or directory SYNOPSIS chmod MODIFIER [FILE...] DESCRIPTION chmod changes the permissions of FILE, or directory, with MODIFIER, 1st digit is owner, 2nd is group, 3rd is anyone. If no FILE is given,it will return an error. OPTIONS 777 Modifier must be given as a number value EXAMPLE chmod 777 file.txt """ if 'params' in kwargs: params = kwargs['params'] else: return 'Error: No or incorrect parameters given.' if 'path' in kwargs: path = kwargs['path'] try: os.chmod(path[1]+params[1], int(params[0],8)) except: return 'ERROR: No incorrect parameters given.'
2d3e32a6c4ae3116a6bc7827a20ab6eca7a1af5c
kingdehu/CourseraML_PY
/basicFunction/softmax_F.py
423
3.53125
4
#calculates the probabilities distribution of the event over n different events import numpy as np import matplotlib.pyplot as plt def softmax(inputs): softmax_scores = [np.exp(x)/float(np.sum(np.exp(inputs))) for x in inputs] return softmax_scores def plot(x,y): plt.plot(x, y, 'r--') plt.show() t = np.arange(-10., 10., 0.1) print(t) print(softmax(t)) print(np.sum(softmax(t))) plot(t,softmax(t))
774fc16ce9d5e591f88d58e1e26586c9dafe422d
CaptianZhangg/gitt
/practice/class.py
541
3.703125
4
class A(object): def __init__(self): self.n = 10 def minus(self, m): self.n -= m class B(A): def __init__(self): self.n = 7 def minus(self, m): super(B, self).minus(m) self.n -= 2 class C(A): def __init__(self): self.n = 12 def minus(self, m): super(C, self).minus(m) self.n -= 5 class D(B, C): def __init__(self): self.n = 15 def minus(self, m): super(D, self).minus(m) self.n -= 2 d = D() d.minus(2) print(d.n)
f0778146abc57271d1587461b9893289fd65dc86
bedoyama/python-crash-course
/basics/ch4__WORKING_WITH_LISTS/2_first_numbers.py
358
4.375
4
print("range(1,5)") for value in range(1, 5): print(value) print("range(0,7)") for value in range(0, 7): print(value) print("range(7)") for value in range(7): print(value) print("range(3,7)") for value in range(3, 7): print(value) print("range(-1,2)") for value in range(-1, 2): print(value) numbers = list(range(4)) print(numbers)
8b8e3c886a6d3acf6a0c7718919c56f354c3c912
bedoyama/python-crash-course
/basics/ch5__IF_STATEMENTS/3_age.py
338
4.15625
4
age = 42 if age >= 40 and age <= 46: print('Age is in range') if (age >= 40) and (age <= 46): print('Age is in range') if age < 40 or age > 46: print('Age is older or younger') age = 39 if age < 40 or age > 46: print('Age is older or younger') age = 56 if age < 40 or age > 46: print('Age is older or younger')
4477730632e14ec304e08b7bdb5124fc85feb3d7
DianeDeeDee/Python_Machine_Learning
/Yazabi/Python-curriculum /Inermediate_Py/Dic_Obj_List_Excep_Gene.py
7,617
4.84375
5
#import beginner_python_1 as bp1 print("--------------------Dictionaries") """ When to Use It: When describing what you want to do, if you use the word "map" (or "match"), chances are good you need a dictionary. Use whenever a mapping from a key to a value is required. """ state_capitals={ 'New York': 'Albany', #"New York" is a key and "Albany" is a value 'New Jersey': 'Trenton', 'France': 'Paris', 'UK': 'London', 'Canada': 'Ottawa' } print("Items=",state_capitals.items()) #for key, value in state_capitals.items(): NewYork_capital = 'Albany' print("state_capitals=", state_capitals) print("NewYork_capital=", NewYork_capital) print("Other way to get NewYork_capital=" , state_capitals["New York"]) print("Keys of state_capitals=", state_capitals.keys()) #for value in state_capitals.values(): print("values of state_capitals=", state_capitals.values()) print("\n") """ If you're searching for a value in a dictionary and you use a for loop, you're doing it wrong. Use the below statement instead: """ valueNY = state_capitals['New York'] print("valueNY=", valueNY) print("Other way to get the value of NY=", state_capitals.get('New York', None)) print("\n") Copy_state_capitals=state_capitals.copy() print("Cp state_capitals: Copy_state_capitals=", Copy_state_capitals) #state_capitals.clear() #print("Removing state_capitals:",state_capitals) print("The the number of stored items:", len(state_capitals)) del state_capitals["New York"] #print("Removing NY:", del state_capitals["New York"]) print("After removing NY, state_capitals=", state_capitals) print("\n") my_list = [1, 2, 3] my_dictionary = dict.fromkeys(my_list, 0) print("my_dictionary with with all values initialized to 0=", my_dictionary) my_dictionary1 = {1: 1, 2: 2, 3: 3} my_dictionary1 = dict.fromkeys(my_dictionary1, None) new_dictionary1 = dict.fromkeys(my_dictionary1) print("my_dictionary with all values automatically initialized to None=", my_dictionary1) my_dictionary2 = {'hello': 1, 'goodbye': 2} foo_value = my_dictionary2.pop('hello', None) print("foo_value=", foo_value) print("then my_dictionary2=", my_dictionary2) print("\n") """ Pop (i.e. delete and return) a random element from the dictionary (d) Returns a (key, value) tuple if d is not empty. Raises KeyError if d is empty. """ try: key, value = state_capitals.popitem() print('Got the random element from state_capitals = {}: {}'.format(key, value)) except KeyError: print('Done') """ Count the number of times each word is seen in a file: Question: #words = {} #for number in bp1: # occurrences = words.setdefault(number, 0) # words[number] = occurrences + 1 How do I import bp1 from another location? The code is not working: for number in bp1: TypeError: 'module' object is not iterable """ first = {'a': 1} second = {'b': 2} third = {'c': 3} fourth = {'d': 4} first.update(second) first.update(fourth) first.update(third) print ("updated first=",first) print("second=",second) print( "Another way using keyargument for other:" ) first = {'a': 1} first.update( b=2, d=4, c=3 ) print( "New first=",first ) print( "\n" ) print( "--------------------Objects" ) """ In Python the basic elements of programming are things like strings, dictionaries, integers, functions, and so on... They are all objects. This means they have certain things in common. """ original_string = ' some text ' # remove leading and trailing whitespace #fonction strip, cette fonction supprime les espaces en début # et en fin de chaîne. string1 = original_string.strip() print( "string1=", string1 ) # make uppercase string2 = string1.upper() print( "string2=", string2 ) # make lowercase string2.lower() == string1 True # create a dictionary the normal way a_dict = { 'key' : 'value', 'key2' : 'value2' } # use 'dict' to create one list_of_tuples = [('key', 'value'), ('key2', 'value2') ] a_dict_2 = dict(list_of_tuples) print ( "a_dict=", a_dict ) print ( "a_dict_2=", a_dict_2 ) # print ( "Hola=", a_dict == a_dict_2) True """ #Functions are Objects if value == 'one': # do something function1() elif value == 'two': # do something else function2() elif value == 'three': # do something else function3() """ def function1(): print 'You chose one.' def function2(): print 'You chose two.' def function3(): print 'You chose three.' # # switch is our dictionary of functions switch = { 'one': function1, 'two': function2, 'three': function3, } # # choice can eithe be 'one', 'two', or 'three' choice = input( 'Enter one, two, or three :' ) # # call one of the functions try: result = switch[choice] except KeyError: print( 'I didn\'t understand your choice.' ) else: result() print( "choice=",choice ) print("\n") print("An Exmeple of Class: ") """ The real trick is that we can create our own blueprints.These are called classes. We can define our own class of object - and from this create as many instances of this class as we want. All the instances will be different - depending on what data they are given when they are created. They will all have the methods (and other properties) from the blueprint - the class. So lets look at a simple example. We define our own class using the class keyword. Methods are defined like functions - using the def keyword. They are indented to show that they are inside the class. """ class OurClass(object): def __init__(self, arg1, arg2): """ The __init__ method (init for initialise) is called when the object is instantiated. Instantiation is done by (effectively) calling the class. the arguments are: 'arg1' and 'arg2' When we access attributes of an object we do it by name (or by reference). Here instance is a reference to our new object. We access the printargs method of the instance object using instance.printargs. In order to access object attributes from within the __init__ method we need a reference to the object. Whenever a method is called, a reference to the main object is passed as the first argument. By convention you always call this first argument to your methods self: self.arg1 = arg1 self.arg2 = arg2 The 'functions' that are part of an object are called methods. The values are called 'attributes'. """ self.arg1 = arg1 self.arg2 = arg2 def printargs(self): """ This method doesn't take any arguments - so when we define it, we only need to specify the self parameter which is always passed to object methods. When this method is called it looks up (and prints) the original arguments which were saved as object attributes by __init__. """ print( "self.arg1=", self.arg1 ) print( "self.arg2=", self.arg2 ) instance = OurClass('arg1', 'arg2') #instance of OurClass print( "type(instance)=", type(instance)) print( "instance.arg1=", instance.arg1 ) instance.printargs() #When we call instance.printargs() these original arguments are printed. #You can examine all the methods and attributes that are associated with an object using the dir command: print(dir(OurClass)) """ There is lots more still to learn. Some subjects I could expand this tutorial to cover include : inheritance class attributes __dict__ subclassing built in types __new__ __getattr__ and __setattr__ private attributes (single and double underscore) classmethods and staticmethods """
85a1bf1bca9d44da7acd6e0ca060a452e82db171
Qeinayd/playground
/codewars/kyu_6/python/unique_in_order.py
323
3.84375
4
# https://www.codewars.com/kata/unique-in-order/ def unique_in_order(iterable): if not iterable: return [] if len(iterable) < 2: return list(iterable) result = [iterable[0]] for x in iterable[1:]: if result[-1] != x: result.append(x) return result
24d53b20741289a05b2e54e4df85941ef67af0ef
Qeinayd/playground
/codewars/kyu_5/python/simple_pig_latin.py
226
3.9375
4
# https://www.codewars.com/kata/simple-pig-latin/ def pig_it(text): return ' '.join( word[1:] + word[0] + 'ay' if all(x.isalpha() for x in word) else word for word in text.split(' ') )
a6d80b5bf212c2ad8acd27da0ac2cf1a1a6f2782
botaor/Python-Samples
/TextFiles.py
2,871
4.0625
4
#!/usr/bin/python # -*- coding: latin-1 -*- "Module to show how to handle text files" # This line must be at the beginning of the file from __future__ import print_function import sys import codecs def ReadFileComplete( filename ): "Read the whole contents of the file to a variable" f = open( filename, 'rU' ) lines = f.read() f.close() return lines def ReadFileList( filename ): "Read the file and return a list of lines. Each line has '\n' at the end" f = open( filename, 'rU' ) lines = f.readlines() f.close() return lines def ReadFileLinesFor( filename ): "Read the file and return a list of lines. The lines do note end with '\n'. Use a for loop" f = open( filename, 'rU' ) lines = [] for line in f: lines.append( line[:-1] ) f.close() return lines def ReadFileLinesWhile( filename ): "Read the file and return a list of lines. The lines do note end with '\n'. Use a while loop" f = open( filename, 'rU' ) lines = [] while True: line = f.readline() if not line: break lines.append( line[:-1] ) f.close() return lines def ReadFileUnicode( filename ): "Read a unicode file. The result is a list of unicode strings" f = codecs.open( filename, 'rU', 'cp1252' ) lines = f.readlines() f.close() return lines def WriteFile( filename, lines ): "write a list of strings to a text file" f = open( filename, 'w' ) for li in lines: f.write( li ) if li[-1] != '\n': f.write( '\n' ) ; f.close() def AppendFile( filename, lines ): "Append a list of strings to a text file" f = open( filename, 'a' ) for li in lines: f.write( li ) if li[-1] != '\n': f.write( '\n' ) ; f.close() def WriteFileUnicode( filename, lines ): "write a list of unicode strings to a text file" f = codecs.open( filename, 'w', 'cp1252' ) for li in lines: f.write( li ) if li[-1] != '\n': f.write( '\n' ) ; f.close() def main(): "The main function called when the utility is run." print( 'Text files test' ) print() lines = ReadFileComplete( "samples/text.txt" ) print( lines ) print() lines = ReadFileList( "samples/text.txt" ) print( lines ) print() lines = ReadFileLinesFor( "samples/text.txt" ) print( lines ) print() lines = ReadFileLinesWhile( "samples/text.txt" ) print( lines ) print() lines = ReadFileUnicode( "samples/text.txt" ) print( lines ) print() lines = ['1', '2', 'abc', '0' ] WriteFile( 'out.txt', lines ) AppendFile( 'out.txt', lines ) lines = ReadFileUnicode( "samples/textutf8.txt" ) WriteFileUnicode( 'outunicode.txt', lines ) return 0 # This is the standard boilerplate that calls the main() function. if __name__ == '__main__': rc = main() # This function will set the result value of this utility sys.exit( rc )
5bdecfc8658edb6c4bbeaa46048aa70f752f039f
xxzzxxzzzzs/pythonDemo
/venv/list.py
1,271
3.71875
4
# -*- coding: UTF-8 -*- import time; # 引入time模块 # ticks = time.time() # print "当前时间戳为:", ticks # str='''sdasda123 # 123]@@!3 # 213!@ # @!31#12#12''' # list=str.split("@"); # print str.split("@") # c=0 # for s in list: # if len(s)>0: # c+=1 # print c # list2=str.splitlines() # print list2 # str3= " ".join(list2) # print str3 # # print str3.replace("2","22222") # # str4=str.maketrans("good","nice") # str5="good good man nice" # str6=str5.translate(str4) # print str6 # d={} # str="dasdas asdasda adasdas asd asd asdas dasd asd sad asd as" # list= str.split(" ") # # print list # for v in list: # c=d.get(v) # if c==None: # d[v]=1 # else: # d[v]+=1 # print d # # s4=set([1,2,2,2,3,4,5]) # print s4 # s4.add(6) # print s4 # s4.add((1,5,8)) # print s4 # s4.update([10,22]) # print s4 # !/usr/bin/python # -*- coding: UTF-8 -*- def ChangeInt(a): a = 10 b = 2 ChangeInt(b) print b # 结果是 2 # !/usr/bin/python # -*- coding: UTF-8 -*- # 可写函数说明 def changeme(mylist): "修改传入的列表" mylist.append([1, 2, 3, 4]); print "函数内取值: ", mylist return # 调用changeme函数 mylist = [10, 20, 30]; changeme(mylist); print "函数外取值: ", mylist
13cedc7bf113d6b698adb0c166482918fa687b47
xxzzxxzzzzs/pythonDemo
/单元测试/Person.py
220
3.515625
4
class Person(object): def __init__(self,name,age,): self.name=name self.age=age def getVar(self,v): print(self(v)) return self(v) def getName(self): return self.name
67a07d319635ecf8f5aa98be3653e129e50a4309
Mi1ind/RSA-Encryption
/RSA/Encryption.py
704
3.515625
4
import Keys txtInput = input() class Encrypt(object): # def __init__(self, txt): # self.txt = txt # self.asciiTxt = asciiTxt def strToNum(self, txt): num = [] a = '' for i in range(len(txt)): num.append(ord(txt[i])) a = a.join(map(str, num)) return int(a) def encMaths(self, asciiTxt): nums = pow(asciiTxt, Keys.publicKey[1], Keys.publicKey[0]) return (nums) def encAnswer(self): Inst = Encrypt() cipherTxt = Inst.encMaths(Inst.strToNum(txtInput)) return cipherTxt newInstance = Encrypt() print('\n', newInstance.strToNum(txtInput), '\n') print(newInstance.encAnswer())
488ed434fcc8916937bbe2c0acffbff9cf3f30f9
angelavuong/python_exercises
/coding_challenges/exceptions.py
340
4.03125
4
''' Name: Exceptions Tasks: Read a string, S, and print its integer value; if S cannot be converted to an integer, print Bad String. Sample Input: 3 Sample Output: 3 Sample Input: za Sample Output: Bad string ''' #!/bin/python3 import sys S = input().strip() try: value = int(S) print (S) except: print ('Bad String')
2b03e816c33cfdcfd9b5167de46fda66c7dda199
angelavuong/python_exercises
/coding_challenges/grading_students.py
981
4.125
4
''' Name: Grading Students Task: - If the difference between the grade and the next multiple of 5 is less than 3, round grade up to the next multiple of 5. - If the value of grade is less than 38, no rounding occurs as the result will still be a failing grade. Example: grade = 84 will be rounded to 85 grade = 29 will not be rounded because it is less than 40 ''' #!/bin/python3 import sys def solve(grades): # Complete this function new_list = [] for each in grades: if (each < 38): pass else: if (each%5 >= 3): remainder = 5 - (each%5) each = remainder + each elif(each%5 == 0): pass else: pass new_list.append(each) return new_list n = int(input().strip()) grades = [] grades_i = 0 for grades_i in range(n): grades_t = int(input().strip()) grades.append(grades_t) result = solve(grades) print ("\n".join(map(str, result)))
18b519a9ad9b8f05b3df2ca0d4537bd7ac0b8abc
angelavuong/python_exercises
/coding_challenges/bon_appetit.py
1,545
3.828125
4
''' Name: Bon Appetit Task: Anna and Brian order n items at a restaurant, but Anna declines to eat any of the kth item (where 0 <= k <= n) due to an allergy. When the check comes, they decide to spit the cost of all the items they shared; however, Brian may have forgotten that they didn't split the kth item and accidentally charged Anna for it. Input: The first line contains two space-separated integers denoting the respective values of n (number of items ordered) and k(the 0-based index of the item that Anna did not eat) The second line contains n space-separated integers where each integer i denotes the cost, c[i], of item i The third line contains an integer, b-charged, denoting the amount of money that Brian charged Anna for her share of the bill. Output: You are given n, k, the cost of each of the n items, and the total amount of money that Brian charged Anna for her portion of the bill. If the bill is fairly split, print Bon Appetit; otherwise, print the amount of money that Brian must refund to Anna. ''' #!/bin/python3 import sys def bonAppetit(n, k, b, ar): # Complete this function total = 0 for i in range(n): if(i != k): total = total + ar[i] else: pass shared_amount = total/2 if(shared_amount == b): return 'Bon Appetit' else: return int(b - shared_amount) n, k = input().strip().split(' ') n, k = [int(n), int(k)] ar = list(map(int, input().strip().split(' '))) b = int(input().strip()) result = bonAppetit(n, k, b, ar) print(result)
8de678a955de6c29c84b43e6f27b1f2c027cffcd
angelavuong/python_exercises
/coding_challenges/legos.py
737
3.640625
4
#!/bin/python3 import sys def productOfPages(a, b, c, d, p, q): # Return the product of the page counts of the missing books if(p == a): a = 1 elif(p == b): b = 1 elif(p == c): c = 1 elif(p == d): d = 1 if(q == a): a = 1 elif(q == b): b = 1 elif(q == c): c = 1 elif(q == d): d = 1 product = a * b * c * d return product if __name__ == "__main__": t = int(input().strip()) for a0 in range(t): a, b, c, d = input().strip().split(' ') a, b, c, d = [int(a), int(b), int(c), int(d)] p, q = input().strip().split(' ') p, q = [int(p), int(q)] answer = productOfPages(a, b, c, d, p, q) print(answer)
570b9f3e710d94baf3f4db276201a9c484da4a71
angelavuong/python_exercises
/coding_challenges/count_strings.py
573
4.125
4
''' Name: Count Sub-Strings Task: Given a string, S, and a substring - count the number of times the substring appears. Sample Input: ABCDCDC CDC Sample Output: 2 ''' def count_substring(string,sub_string): counter = 0 length = len(sub_string) for i in range(len(string)): if (string[i] == sub_string[0]): if (string[i:(i+length)] == sub_string): counter += 1 else: pass return counter string = input().strip() sub_string = input().strip() count = count_substring(string,sub_string) print(count)
aa378a188bce0e97a0545221e65f148838b3650c
angelavuong/python_exercises
/coding_challenges/whats_your_name.py
536
4.1875
4
''' Name: What's Your Name? Task: You are given the first name and last name of a person on two different lines. Your task is to read them and print the following: Hello <firstname> <lastname>! You just delved into python. Sample Input: Guido Rossum Sample Output: Hello Guido Rossum! You just delved into python. ''' def print_full_name(a, b): print("Hello " + a + " " + b + "! You just delved into python.") if __name__ == '__main__': first_name = raw_input() last_name = raw_input() print_full_name(first_name, last_name)
fb5fb443047d66da08a71087282dd3070a543a14
lukes-tauafiafiiutoi/PROGRAMMING
/lucky unicorn/testing/test.py
408
3.84375
4
def yes_no show_instructions ="" show_instructions = input("Have you played this game before? ").lower() if show_instcutions == "yes": print("program continues") elif show_instrctions == "y": print("program continues") if show_instcutions == "no": print("display instructions") elif show_instrctions == "n": print("display instructions") elif show_instructions == "n" print("program continues")
c694ab63a24674646d5309e4f18076b400b522e9
develly/CodingTest
/etc/add.py
407
3.625
4
#-*- encoding: utf-8 -*- # 두개 뽑아서 더하기 def solution(numbers): answer = [] for i in range(len(numbers)-1): for num in numbers[i+1:]: tmp = numbers[i] + num if tmp not in answer: answer.append(tmp) answer.sort() return answer if __name__ == "__main__": numbers = [2,1,3,4,1] answer = solution(numbers) print(answer)
f5c55ca26fb5eb99b71586a04149648f3c363f5c
develly/CodingTest
/etc/Sorting/sorting.py
561
3.953125
4
#-*- encoding: utf-8 -*- # K번째 수 # solution 1 def solution(array, commands): answer = [] for i,j,k in commands: answer.append(sorted(array[i-1:j])[k-1]) return answer # solution 2 def solution2(array, commands): answer = [] for i, j, k in commands: target = array[i-1:j] target.sort() answer.append(target[k-1]) return answer if __name__ == "__main__": array = [1, 5, 2, 6, 3, 7, 4] commands = [[2, 5, 3], [4, 4, 1], [1, 7, 3]] answer = solution(array, commands) print(answer)
be619de8667ab89766b5cf43c9f266b1644570f9
develly/CodingTest
/etc/ternery.py
283
3.859375
4
def solution(n): ternery = "" answer = 0 while n > 2: n, rest = divmod(n, 3) ternery += str(rest) ternery += str(n) answer = int(ternery, 3) return answer if __name__ == "__main__": n = 45 answer = solution(n) print(answer)
56fb9aa4cdc33a99c0adb576f0c180d697cec594
develly/CodingTest
/programmers/level1/추억 점수.py
760
3.546875
4
def solution(name, yearning, photo): answer = [] for people in photo: score = 0 for j in people: try: score += yearning[name.index(j)] except ValueError: continue answer.append(score) return answer def shorten(name, yearning, photo): """Summarize the code in one line.""" return [sum(yearning[name.index(j)] for j in people if j in name) for people in photo] if __name__ == '__main__': name = ["may", "kein", "kain", "radi"] yearning = [5, 10, 1, 3] photo = [["may", "kein", "kain", "radi"], ["may", "kein", "brin", "deny"], ["kon", "kain", "may", "coni"]] print(solution(name, yearning, photo)) print(shorten(name, yearning, photo))
70d4723b6527d07696d9f6bf74965eee7e97946c
noahp/adventofcode
/2022/01/aoc.py
3,520
3.78125
4
#!/usr/bin/env python """ --- Day 1: Calorie Counting --- Santa's reindeer typically eat regular reindeer food, but they need a lot of magical energy to deliver presents on Christmas. For that, their favorite snack is a special type of star fruit that only grows deep in the jungle. The Elves have brought you on their annual expedition to the grove where the fruit grows. To supply enough magical energy, the expedition needs to retrieve a minimum of fifty stars by December 25th. Although the Elves assure you that the grove has plenty of fruit, you decide to grab any fruit you see along the way, just in case. Collect stars by solving puzzles. Two puzzles will be made available on each day in the Advent calendar; the second puzzle is unlocked when you complete the first. Each puzzle grants one star. Good luck! The jungle must be too overgrown and difficult to navigate in vehicles or access from the air; the Elves' expedition traditionally goes on foot. As your boats approach land, the Elves begin taking inventory of their supplies. One important consideration is food - in particular, the number of Calories each Elf is carrying (your puzzle input). The Elves take turns writing down the number of Calories contained by the various meals, snacks, rations, etc. that they've brought with them, one item per line. Each Elf separates their own inventory from the previous Elf's inventory (if any) by a blank line. For example, suppose the Elves finish writing their items' Calories and end up with the following list: 1000 2000 3000 4000 5000 6000 7000 8000 9000 10000 This list represents the Calories of the food carried by five Elves: The first Elf is carrying food with 1000, 2000, and 3000 Calories, a total of 6000 Calories. The second Elf is carrying one food item with 4000 Calories. The third Elf is carrying food with 5000 and 6000 Calories, a total of 11000 Calories. The fourth Elf is carrying food with 7000, 8000, and 9000 Calories, a total of 24000 Calories. The fifth Elf is carrying one food item with 10000 Calories. In case the Elves get hungry and need extra snacks, they need to know which Elf to ask: they'd like to know how many Calories are being carried by the Elf carrying the most Calories. In the example above, this is 24000 (carried by the fourth Elf). Find the Elf carrying the most Calories. How many total Calories is that Elf carrying? --- Part Two --- By the time you calculate the answer to the Elves' question, they've already realized that the Elf carrying the most Calories of food might eventually run out of snacks. To avoid this unacceptable situation, the Elves would instead like to know the total Calories carried by the top three Elves carrying the most Calories. That way, even if one of those Elves runs out of snacks, they still have two backups. In the example above, the top three Elves are the fourth Elf (with 24000 Calories), then the third Elf (with 11000 Calories), then the fifth Elf (with 10000 Calories). The sum of the Calories carried by these three elves is 45000. Find the top three Elves carrying the most Calories. How many Calories are those Elves carrying in total? """ import sys def get_cals(elfs): return [sum([int(x) for x in y.split()]) for y in elfs] def main(): with open(sys.argv[1], "r") as f: data = f.read().split("\n\n") cals = get_cals(data) max_cal = max(cals) print(f"part one: {max_cal}") print(f"part two: {sum(sorted(cals)[-3:])}") if __name__ == "__main__": main()
bbea8b19027cebe3f46d441f9d012584cc3dc75b
matthew99carroll/VoronoiDiagram
/Event.py
278
3.5
4
import abc class Event(object): __metaclass__ = abc.ABCMeta def __init__(self, x, y): self.x = x self.y = y @abc.abstractmethod def Handle(self, queue, beachline, dcel): return def ToString(self): return '("+x+", "+y+")'
adec6702a83b1676b337082d7eab0980b5c71cde
mo7amed3umr/new-task-sbme
/mtplt.py
600
3.53125
4
from numpy import * import plotly as py from plotly.graph_objs import * #just a sphere theta = linspace(0,2*pi,100) phi = linspace(0,pi,100) x = outer(cos(theta),sin(phi)) y = outer(sin(theta),sin(phi)) z = outer(ones(100),cos(phi)) # note this is 2d now data = Data([ Surface( x=x, y=y, z=z ) ]) layout = Layout( title='Bloch sphere', autosize=False, width=500, height=500, margin=Margin( l=65, r=50, b=65, t=90 ) ) fig = Figure(data=data, layout=layout) print (py.plot(fig, filename='bloch-sphere-surface'))
c3e852fa1059dd903585a226979c8f5e884e5597
riverfour1995/Leetcode
/451. Sort Characters By Frequency.py
298
3.546875
4
import collections class Solution(object): def frequencySort(self, s): """ :type s: str :rtype: str """ set = collections.Counter(s) return ''.join([n * m for m, n in sorted([(k, j) for j, k in list(zip(set.keys(), set.values()))], reverse=-1)])
63c3767f80315d510c3bc3170a04e37693e2d344
riverfour1995/Leetcode
/268. Missing Number.py
329
3.5
4
class Solution(object): def missingNumber(self, nums): """ :type nums: List[int] :rtype: int """ self.value = nums number = len(self.value) + 1 whole_list = list(range(number)) return int(list(set(whole_list)-set(self.value))[0]) #set can be used to substract
1abcd78ccecb92bf2e13d174ef63b5688f0a54aa
matali1/adventofcode
/day09/garbage.py
3,228
4.15625
4
import click # A large stream blocks your path. According to the locals, it's not safe to cross the stream at the moment because it's full of garbage. You look down at the stream; rather than water, you discover that it's a stream of characters. # # You sit for a while and record part of the stream (your puzzle input). The characters represent groups - sequences that begin with { and end with }. Within a group, there are zero or more other things, separated by commas: either another group or garbage. Since groups can contain other groups, a } only closes the most-recently-opened unclosed group - that is, they are nestable. Your puzzle input represents a single, large group which itself contains many smaller ones. # # Sometimes, instead of a group, you will find garbage. Garbage begins with < and ends with >. Between those angle brackets, almost any character can appear, including { and }. Within garbage, < has no special meaning. # # In a futile attempt to clean up the garbage, some program has canceled some of the characters within it using !: inside garbage, any character that comes after ! should be ignored, including <, >, and even another !. # # You don't see any characters that deviate from these rules. Outside garbage, you only find well-formed groups, and garbage always terminates according to the rules above. # # Here are some self-contained pieces of garbage: # # <>, empty garbage. # <random characters>, garbage containing random characters. # <<<<>, because the extra < are ignored. # <{!>}>, because the first > is canceled. # <!!>, because the second ! is canceled, allowing the > to terminate the garbage. # <!!!>>, because the second ! and the first > are canceled. # <{o"i!a,<{i<a>, which ends at the first >. @click.command() @click.option('--file', help='File to read the lines') def compute_total_score_from_file(file): if file: with open(file) as myfile: line = myfile.readline() parse_string(line) else: print "Provide input file --file" return 0 def parse_string(line): print line nesting_group_level = 0 score = 0 is_garbage = False skip_character = False garbage_char_cnt = 0 for char in line: if skip_character: skip_character = False continue if char == '{': if not is_garbage: nesting_group_level = nesting_group_level + 1 score += nesting_group_level else: garbage_char_cnt += 1 elif char == '}': if not is_garbage: nesting_group_level -= 1 else: garbage_char_cnt += 1 elif char == '<': if is_garbage: garbage_char_cnt += 1 is_garbage = True elif char == '!': skip_character = True elif char == '>': is_garbage = False elif is_garbage: garbage_char_cnt += 1 # print (char, garbage_char_cnt) print "Score: ",score print "Garbage charcters: ", garbage_char_cnt return score, garbage_char_cnt if __name__ == '__main__': compute_total_score_from_file()
e9146fd8cc88e10a9d44ec8c34cb748cfa8e22a9
matali1/adventofcode
/day05/cpu.py
2,053
4.09375
4
import click @click.command() @click.option('--file', help='File to read the lines') def leave_the_maze(file): steps = 0 if file: with open(file) as myfile: steps = calculate_steps(myfile) print steps print 'THERE ARE %d steps to leave the maze' % steps def calculate_steps(myfile): instructions = [int(line) for line in myfile if line != ""] steps = 0 start = instructions[0] current_idx = 0 step_further = True while step_further: print '\nCurrent_idx ',current_idx if current_idx>len(instructions)-1: break move = instructions[current_idx] print 'Move to',move previous_idx = current_idx previous_value = instructions[current_idx] current_idx = current_idx + move steps+=1 #part2 if move >=3: instructions[previous_idx] = previous_value + -1 else: instructions[previous_idx] = previous_value+1 print 'steps =',steps print "STEPS is",steps return steps def check_if_valid(tokens): tokens_set = list(set(tokens)) if len(tokens)!= len(tokens_set): return False return True def check_if_valid_no_anagrams(tokens): sorted_letters_tokens = set() #sort letters in the word for word in tokens: letters = [] for letter in word: letters.append(letter) sorted_letters_tokens.add(''.join(sorted(letters))) if len(tokens) != len(sorted_letters_tokens): print sorted_letters_tokens print tokens return False return True def get_valid_passhprases(lines): valid_lines = [] for line in lines: print line.replace("\n", "") tokens = line.replace("\n", "").split(" ") if check_if_valid(tokens) and check_if_valid_no_anagrams(tokens): valid_lines.append(line) print '\tVALID' else: print '\tNOT VALID' return valid_lines if __name__ == '__main__': leave_the_maze()
830488612df7dcb44dcff1a04c3fa1f04c54f30a
martingms/aoc
/2018/day10.py
1,230
3.515625
4
#!/usr/bin/env python3 from itertools import count inp = open('day10.input').read().strip().split('\n') class Point: def __init__(self, x, y, vx, vy): self.x, self.y, self.vx, self.vy = x, y, vx, vy def parse(inp): for line in inp: line = line[10:].split(',') x = int(line[0]) y = int(line[1].split('>')[0]) vx = int(line[1].split('<')[-1]) vy = int(line[2][:-1]) yield Point(x, y, vx, vy) points = list(parse(inp)) def pp(points): xpoints = sorted(points, key=lambda p: p.x) minx, maxx = xpoints[0].x, xpoints[-1].x ypoints = sorted(points, key=lambda p: p.y) miny, maxy = ypoints[0].y, ypoints[-1].y point_coords = {(p.x, p.y) for p in points} for y in range(miny, maxy+1): for x in range(minx, maxx+1): if (x, y) in point_coords: print('#', end='') else: print(' ', end='') print() for sec in count(1): ys = set() for p in points: p.x += p.vx p.y += p.vy ys.add(p.y) # Character height found by trial and error :shrug: if len(ys) == 10: # 1 pp(points) # 2 print(sec) break
531a8d56b426d44e8afa7be24874a3dad5b3d6e3
feliperi1/ProyectoM1Python
/consola_calculo_porcentaje_grasa.py
389
3.5
4
import calculadora_indices as calc peso=float(input("Ingrese el peso de la persona en kilogramos:")) altura=float(input("Ingrese la altura de la persona en metros:")) edad=int(input("Ingrese la edad de la persona: ")) v_genero=float(input("Ingrese el 10.8 si el genero es masculino o de lo contrario cero:")) print(str(calc.calcular_porcentaje_grasa(peso,altura,edad,v_genero))+"%")
9062cf160a34e6c0501408383d71bc73a55d0a05
blodstone/summarization
/structure/document.py
1,030
3.5625
4
from typing import List from structure.sentence import Sentence class Document: def __init__(self): self._id = '' self._bodies: List[Sentence] = list() self._gold_summaries: List[Example] = list() @property def gold_summaries(self)->list: return self._gold_summaries @property def bodies(self)->list: return self._bodies def append_bodies(self, sentence: Sentence): sentence.pos = len(self._bodies) self._bodies.append(sentence) def add_gold_summary_example(self, sentences: List[Sentence]): ex = Example() sentence: Sentence for sentence in sentences: sentence.pos = len(ex.sentences) ex.append_sentence(sentence) self._gold_summaries.append(ex) class Example: def __init__(self): self._sentences = list() @property def sentences(self): return self._sentences def append_sentence(self, sentence:Sentence): self._sentences.append(sentence)
d5d229788bf6391a3be21f75c54166a1b836b3e4
6reg/pc_func_fun
/rev_and_normalized.py
519
4.15625
4
def reverse_string(s): reversed = "" for i in s: reversed = i + reversed return reversed def normalize(s): normalized = "" for ch in s: if ch.isalpha(): normalized += ch.lower() return normalized def is_palindrome(s): normalized = normalize(s) rev = reverse_string(normalized) return normalized == rev print(is_palindrome("Hello")) print(is_palindrome("A man, a plan, a canal - Panama!")) print(is_palindrome("kayak")) print(is_palindrome("Goodbye"))
2025d813e4f4f8dc43e5b1391db65fc0fce3071f
6reg/pc_func_fun
/comb.py
227
3.671875
4
s = ['a','b','c'] def get_cmb(s): r = [] for i in range(len(s)-1): for y in range(i+1,len(s)): v = [s[i],s[y]] if v not in r: r.append(v) return r print(get_cmb(s))
c9b55e36a7c775becaedf05e581baf1da1af2a79
tkieft/adventofcode-2016
/day01/day01.py
859
3.96875
4
import sys def grid_distance(location): return abs(location[0]) + abs(location[1]) input = open(sys.argv[1], 'r').readlines()[0] directions = input.split(", ") heading = 90 current = (0, 0) headquarters = None visited = [] visited.append(current) for direction in directions: # Turn in new direction heading += -90 if direction[0] == "R" else 90 heading %= 360 # Walk steps = int(direction[1:]) for i in range(steps): delta = 1 if heading <= 90 else -1 current = ( current[0] + (delta if heading % 180 == 90 else 0), current[1] + (delta if heading % 180 == 0 else 0) ) if headquarters == None and current in visited: headquarters = current else: visited.append(current) print(grid_distance(current)) print(grid_distance(headquarters))
d953788ac89aa22b29a4b5cacc8ee97721e3aa03
PavelescuVictor/KnapsackProblem
/Classes/Backpack.py
474
3.578125
4
class Backpack: def __init__(self): self.backpack_storage = [] self.max_weight = 0 def get_element_by_index(self, index): return self.backpack_storage[index] def add_item(self, item): self.backpack_storage.append(item) def get_backpack(self): return self.backpack_storage def get_max_weight(self): return self.max_weight def set_max_weight(self, max_weight): self.max_weight = max_weight
8344f3ec431ff5589df6cfbdfdd6343d67130311
samurainote/OOP
/data_member.py
765
4.03125
4
print("\tI'm\tyours") # class method # cls means class itself class TaxCalc: @classmethod def class_method(cls, price): assert cls.__name__ == TaxCalc.__name__ return int(price * 0.08) @staticmethod def static_method(price): return int(price * 0.08) print(TaxCalc.class_method(1000)) print(TaxCalc.static_method(1000)) # if __name__ == '__main__': # publicとprivate # クラス内部に閉じたアクセス class Sample: num1 = 100 __num2 = 200 def __init__(self): self.__num3 = 300 def show_num(self): print(Sample.__num2) print(self.__num3) print(Sample.num1) s = Sample() s.show_num() # アンダースコア2個で始まるクラス変数やインスタンス変数
43268d590c2115b33e05ff12d69e72239436c5f4
Talux-QsO/curso_python
/numbers.py
419
3.84375
4
# operaciones basicas # suma print(1 + 2.4) print(1 + 3,4) # resta print(1.5 - 0.5) #mutiplicacion print(45 * 2.4) #division print(12.0 / 4.0 ) # modulo muestra el residuo print(12.0 % 4.0) #muestra de parte entera de la division print(12.0 / 7.0 ) print(12.0 // 7.0) age = int(input("Inserta de tu edad: "), 12) print(age) new_age = age + 5 print(f"Dentro de un lustro tendras estas {new_age} edad")
4624da42ac42e7952dce35ff6498ba932e2d2fff
Talux-QsO/curso_python
/datetype.py
510
3.71875
4
# Strings print("Hola mundo") print(type("hola mundo")) # Concatenacion print("hola mundo " + "Yolo") # Numbers a=10 print(a); print(type(a)) # Float b=12.5 print(b); print(type(b)) # Boolean True False print(type(True)) # List (Datos varibles) [10 ,20 ,12,True] ["Hola", "adios" , "buema suerte"] print(type([12 , -3])) # Tuples (Datos no varian) (10,34,5) () print(type((4,6))) #Dictorianies print(type( { "name":'Cristhian', "nickname":'Conejo', "age":'18' #calve:valor })) #none none
cf78d68dd19488159065cbdf6fa127690a43f7a8
eunseo5355/python_school
/lab6_2.py
813
3.84375
4
""" 사용자로부터 점수를 입력받아, 이를 리스트에 저장하고, 평균을 출력하라. 입력된 점수는 list 형식으로 출력한다. 점수의 끝은 음수로 확인한다. """ Score = [] # 리스트 초기화 sum =0 # 합 구하기 count =0 # 점수 개수를 세기 위한 변수 while True: # 음수가 들어올 때까지 반복 num = int(input("점수: ")) # 점수 입력 받기 if num < 0: # 음수이면 반복문 탈출 break sum += num # 점수 합하기 count += 1 # 갯수 증가 Score.append(num) # 리스트 추가 print("입력된 점수:", Score) # 리스트 출력 if count != 0: print("평균: %.2f" % (sum/count)) # 평균 출력 else: print("입력된 점수가 없습니다.") print(Score[::2]) print(Score.index(80))
fe5f85c9b9444ec6dcf74cb854ad7ac7ca8253a8
eunseo5355/python_school
/list2_13.py
606
4.0625
4
""" 매장에서 주문 가능한 메뉴를 리스트로 정의한다.(햄버거, 샌드위치, 콜라, 사이다) 이를 화면에 이를 화면에 출력한다. 사용자로부터 메뉴의 번호(0~3)를 입력받고, 갯수를 입력 받아서 선택된 메뉴와 총 가격을 출력한다. 각 메뉴의 가격은 3000원으로 동일하다고 가정한다. """ order_list = ['햄버거', '샌드위치', '콜라', '사이다'] print(order_list) a = int(input("메뉴의 번호(0~3):")) b = int(input("갯수:")) print("선택된 메뉴: %s" % (order_list[a])) print("총가격: %d원" % (b*3000))
923889a7f368d5ccb686186bb469dcfb492a24ed
eunseo5355/python_school
/list3_2(2_13의 수정).py
1,067
4.09375
4
""" 매장에서 주문 가능한 메뉴를 리스트로 정의한다.(햄버거, 샌드위치, 콜라, 사이다) 이를 화면에 이를 화면에 출력한다. 사용자로부터 메뉴의 번호(0~3)를 입력받고, 갯수를 입력 받아서 선택된 메뉴와 총 가격을 출력한다. 각 메뉴의 가격은 햄버거는 3000원, 샌드위치는 2000원, 콜라와 사이다는 1000원이다. """ order_list = ['햄버거', '샌드위치', '콜라', '사이다'] print("메뉴", order_list) a = int(input("메뉴번호(0~3):")) b = int(input("갯수:")) print("선택된 메뉴:", order_list[a]) if a == 0: print("총가격:%d원" % (3000*b)) if a == 1: print("총가격:%d원" % (2000*b)) if a == 2: print("총가격:%d원" % (1000*b)) if a == 3: print("총가격:%d원" % (1000*b)) """ price = [3000, 2000, 1000, 1000] print("총가격: %d" %(price[a]*b)) """ """ if a == 0: price = 3000 if a == 1: price = 2000 if a == 2: price = 1000 if a == 3: price = 1000 else: price = 0 print("총가격: %d" %(price*b)) """
64e3642c06a80b4f90108995bc82db833233a1a7
eunseo5355/python_school
/compare.py
620
3.671875
4
def min_max(li): """ 매개변수로 넘어온 리스트에서 최소값과 최대값을 반환하는 함수 :param li: 리스트 :return: 최소값, 최대값 """ # min 와 max 를 리스트 0번째 요소로 초기화 min = li[0] max = li[0] # 반복문을 돌면서 최소, 최대값 찾기 for i in range(len(li)): if min > li[i]: # 현재 값이 min 보다 작으면 min = li[i] # 최소값 변경 elif max < li[i]: # 현재 값이 max 보다 크면 max = li[i] # 최대값 변경 return min, max # 최소, 최대값을 반환
b4806b7a18128f909770cb668ec4a326469f1eb6
eunseo5355/python_school
/lab3_1.py
363
3.953125
4
""" 문제: 점수를 입력받아서, 60점 이상이면 합겻, 이하면 불합격을 출력하라. 작성자: 배은서 작성일: 2019. 9. 10. """ score = int(input("점수:")) if score >= 60: print("합격!!") print("축하합니다.") else: print("불합격!!") print("더 분발하세요.") """ if score < 60: print("불합격") """
a3286a50d4f3c572bc5176896cb4657ae4b86452
FraiVadim/Introducere_Afi-are_Calcule
/Problema_7.py
146
3.640625
4
v=int(input("dati varsta Anei ")) print ("greutatea perfecta a Anei este de",2*v+8,"kg") print ("inaltimea perfecta a Anei este de",5*v+80,"cm")
cd916150b60d80e1def43eb10aaafd65429badb1
lumeng/repogit-mengapps
/data_mining/wordcount.py
2,121
4.34375
4
#!/usr/bin/python -tt ## Summary: count words in a text file import sys import re # for normalizing words def normalize_word(word): word_normalized = word.strip().lower() match = re.search(r'\W*(\w+|\w\W+\w)\W*', word_normalized) if match: return match.group(1) else: return word_normalized def count_word_in_file(filename): #my_file = open(filename, 'rU', 'utf-8') my_file = open(filename, 'rU') word_dict = {} for line in my_file: words = line.split() for w in words: # mengToDo: improve word normalization logic # What Google's n-gram data set uses? w_normalized = normalize_word(w) if w_normalized in word_dict: word_dict[w_normalized] += 1 else: word_dict[w_normalized] = 1 return word_dict def print_word_count(filename): """counts how often each word appears in the text and prints: word1 count1 word2 count2 ... in order sorted by word. 'Foo' and 'foo' count as the same word """ word_count_dict = sorted(count_word_in_file(filename).items()) for word, count in word_count_dict: print word, count return word_count_dict def get_count(word_count_tup): return word_count_tup[1] def print_top_words(filename, size=50): """prints just the top 20 most common words sorted by sizeber of occurrences of each word such that the most common word is first.""" word_count_dict = count_word_in_file(filename) sorted_word_count_dict = sorted(word_count_dict.items(), key=get_count, reverse=True) for word, count in sorted_word_count_dict[:size]: print word, count ### def main(): if len(sys.argv) != 3: print 'usage: ./wordcount.py {--count | --topwords} file' sys.exit(1) option = sys.argv[1] filename = sys.argv[2] if option == '--count': print_word_count(filename) elif option == '--topwords': print_top_words(filename) else: print 'unknown option: ' + option sys.exit(1) if __name__ == '__main__': main() # END
7d577aff08bce823aee2e6e83a3fef942d78cdfd
chandan-kv/TR_Assessment
/palindrome.py
172
4.03125
4
x = int(input(("Enter a name: ")) if (x == x[::-1]): print("THis is Palindrome") else: print("This is not palindrome")
516721a52862c9532385d52da79d11085a759181
EvgenyMinikh/Stepik-Course-431
/task17.py
1,250
4.1875
4
""" Напишите программу, которая шифрует текст шифром Цезаря. Используемый алфавит − пробел и малые символы латинского алфавита: ' abcdefghijklmnopqrstuvwxyz' Формат ввода: На первой строке указывается используемый сдвиг шифрования: целое число. Положительное число соответствует сдвигу вправо. На второй строке указывается непустая фраза для шифрования. Ведущие и завершающие пробелы не учитывать. Формат вывода: Единственная строка, в которой записана фраза: Result: "..." , где вместо многоточия внутри кавычек записана зашифрованная последовательность. """ alphabet = ' abcdefghijklmnopqrstuvwxyz' shift = int(input()) source_string = input().strip() print('Result: "', end='') for letter in source_string: position = alphabet.find(letter) new_position = (position + shift) % 27 print(alphabet[new_position], end='') print('"', end='')
a72e0f000a7aeb985531d6a52d0622b4bdc0ce2a
graysoncroom/PythonGraphingPlayground
/histogram.py
325
3.65625
4
#!/bin/python import matplotlib.pyplot as plt population_ages = [22, 55, 62, 45, 34, 77, 4, 8, 14, 80, 65, 54, 43, 48, 24, 18, 13, 67] min_age = 0 max_age = 140 age_step_by = 20 bins = [x for x in range(0, 141, 20)] plt.hist(population_ages, bins, histtype='bar', rwidth=0.8) plt.xlabel('x') plt.ylabel('y') plt.show()
0dc8a38b8d32c4208430cb0049ae113f1ea9c321
zhtsh/Learning-Algorithms
/python/List.py
4,365
3.828125
4
#! /usr/bin/python # coding=utf8 class Node(object): def __init__(self, data, next_node=None): self.data = data self.next_node = next_node def get_data(self): return self.data def set_data(self, data): self.data = data def get_next(self): return self.next_node def set_next(self, next_node): self.next_node = next_node class List(object): def __init__(self): self.root = None def is_empty(self): return self.root is None def __len__(self): size = 0 node = self.root while node is not None: size +=1 node = node.get_next() return size def add(self, data): node = self.root pre_node = None while node is not None: pre_node = node node = node.get_next() current_node = Node(data) if pre_node is None: self.root = current_node else: pre_node.set_next(current_node) def remove(self, data): node = self.root pre_node = None while node is not None: if node.get_data() == data: if pre_node is None: self.root = node.get_next() else: pre_node.set_next(node.get_next()) pre_node = node node = node.get_next() def search(self, data): node = self.root while node is not None: if node.get_data() == data: return True node = node.get_next() return False class BidNode(object): def __init__(self, data, pre_node=None, next_node=None): self.data = data self.pre_node = pre_node self.next_node = next_node def get_data(self): return self.data def set_data(self, data): self.data = data def get_pre(self): return self.pre_node def set_pre(self, pre_node): self.pre_node = pre_node def get_next(self): return self.next_node def set_next(self, next_node): self.next_node = next_node class BidList(object): def __init__(self): self.root = None def is_empty(self): return self.root is None def __len__(self): size = 0 node = self.root while node is not None: size +=1 node = node.get_next() return size def add(self, data): node = self.root pre_node = None while node is not None: pre_node = node node = node.get_next() current_node = BidNode(data) if pre_node is None: self.root = current_node else: pre_node.set_next(current_node) current_node.set_pre(pre_node) def remove(self, data): node = self.root while node is not None: if node.get_data() == data: if node.get_pre() is None: self.root = node.get_next() else: node.get_pre().set_next(node.get_next()) if node.get_next(): node.get_next().set_pre(node.get_pre()) node = node.get_next() def search(self, data): node = self.root while node is not None: if node.get_data() == data: return True node = node.get_next() return False if __name__ == '__main__': # single list l = List() l.add(1) l.add(2) l.add(3) l.add(1) l.add(4) l.add(3) l.add(5) print('size: {}'.format(len(l))) print('search node 3: {}'.format(l.search(3))) print('search node 6: {}'.format(l.search(6))) l.remove(1) print('size: {}'.format(len(l))) l.remove(5) print('size: {}'.format(len(l))) l.remove(7) print('size: {}'.format(len(l))) # bidrectional list bl = BidList() bl.add(1) bl.add(2) bl.add(3) bl.add(1) bl.add(4) bl.add(3) bl.add(5) print('size: {}'.format(len(bl))) print('search node 3: {}'.format(bl.search(3))) print('search node 6: {}'.format(bl.search(6))) bl.remove(1) print('size: {}'.format(len(bl))) bl.remove(5) print('size: {}'.format(len(bl))) bl.remove(7) print('size: {}'.format(len(bl)))
f65486941b6ee5852a4aaf2bf6547b7d5d863dd9
blei7/Software_Testing_Python
/mlist/binary_search.py
1,682
4.3125
4
# binary_search.py def binary_search(x, lst): ''' Usage: The function applies the generic binary search algorithm to search if the value x exists in the lst, and returns a list contains: TRUE/FAlSE depends on whether the x value has been found, x value, and x position indice in list Argument: x: numeric lst: sorted list of numerics Return: a list contains: - first element is a logical value (TRUE/FALSE) - second element is a numeric value of x - third element is a numeric in range of 0 to length(list) where 0 indicates the element is not in the list Examples: binary_search(4, [1,2,3,4,5,6]) >>> [TRUE,4,3] binary_search(5, [10,100,200,300]) >>> [FALSE,5,0] ''' # Raise error if input not a list if type(lst) != list: raise TypeError("Input must be a list") # Raise error if input is not integer (eg. float, string...) for i in lst: if type(i) != int: raise TypeError("Input must be list of intergers") # Raise error if input values less than 1000 if max(lst) >= 1000: raise ValueError("Input values exceed 1000. Please limit range of input values to less than 1000.") #binary search algorithm #empty list if len(lst) == 0: return [False, x, 0] low = 0 high = len(lst)-1 while low <= high: mid = (low + high) //2 if lst[mid] < x: low = mid + 1 elif x < lst[mid]: high = mid - 1 else: return [True, x, mid] return [False, x, 0]
418ad60a363bbae94511bb675c71204b18077086
no7dw/py-practice
/class/mixin.py
784
3.5
4
class Displayer(): def display(self, message): print(message) class LoggerMixin(): def log(self, message, filename='logfile.txt'): message ='\n' + message with open(filename, 'a') as fh: fh.write(message) def display(self, message): super().display(message) self.log(message) class MySubClass(LoggerMixin, Displayer): def log(self, message): super().log(message, filename='subclasslog.txt') class MySubClass2(Displayer, LoggerMixin): def log(self, message): super().log(message, filename='subclasslog.txt') subclass = MySubClass() subclass.display("This string will be shown and logged in subclasslog.txt") subclass2 = MySubClass2() subclass2.display("This string will be shown in stdout print")
c797f2b44d77aa811df5c4c1cef78586ba6255f5
beadoer1/algorithm
/HelloCodingAlg/practice_py/factorial.py
105
3.734375
4
def fact(x): if x == 1: return 1 else: return x * fact(x-1) x = fact(5) print(x)
8ce37389202f6c13c77bb05259daa3244ac846e6
beadoer1/algorithm
/20210319/week2_test/15649.py
2,811
3.5625
4
# 문제 # 자연수 N과 M이 주어졌을 때, 아래 조건을 만족하는 길이가 M인 수열을 모두 구하는 프로그램을 작성하시오. # 1부터 N까지 자연수 중에서 중복 없이 M개를 고른 수열 # 입력 # 첫째 줄에 자연수 N과 M이 주어진다. (1 ≤ M ≤ N ≤ 8) # 출력 # 한 줄에 하나씩 문제의 조건을 만족하는 수열을 출력한다. # 중복되는 수열을 여러 번 출력하면 안되며, 각 수열은 공백으로 구분해서 출력해야 한다. # 수열은 사전 순으로 증가하는 순서로 출력해야 한다. # 설명 : 1~N의 숫자로 이루어진(중복 X) M의 길이를 가진 수열들을 오름차순 출력 # n,m 을 입력 받았을 때 for i in range(1,n+1): print(i, end = ' ') for j in range(1,n+1): if j == i: continue print(j, end = ' ') for k in range(1,n+1): if k == i or k == j: continue print(k, end = ' ') for l in range(1,n+1): if l == i or l == j or l == k: continue print(l, end = ' ') ... ... # m번 만큼 (재귀의 탈출 조건) # 풀이 import sys def print_all_seq(visited_arr,n,m): # 탈출 조건 if len(visited_arr) == m: # m개의 자릿수를 모두 채웠을 때 탈출한다. print(' '.join(map(str,visited_arr))) return # mutable for i in range(1,n+1): if i in visited_arr: continue visited_arr.append(i) # 이미 사용한 값을 넣은 list를 주고 받는 과정이 가장 어려웠다. print_all_seq(visited_arr,n,m) visited_arr.pop() # list 는 mutual 특성을 갖는 자료형으로 N,M = map(int,sys.stdin.readline().split()) print_all_seq([],N,M) # immutable(str) 15650 문제 풀이 import sys # 1,3 -> 2,4 -> 3,5 -> 4,6 -> 5,7 -> 6,8(출력) # start_num, max_num def back_track(_str,start_num,max_num,n): # str은 결과 출력,n은 재귀 종료 조건을 만들기 위함 if max_num == n: # 재귀 종료 조건 : max_num이 가장 끝 숫자와 같아지는 경우 for i in range(start_num,max_num+1): print(_str+str(i)) # 여태까지 더해 온 결과값을 출력 return # immutable tmp = _str -> tmp = '1' , _str = '1,2' for i in range(start_num,(max_num)+1): # 수열의 첫 번째 수를 결정 _str = _str + str(i) + ' ' back_track(_str,i+1,max_num+1,n) # 수열의 다음 번째 수를 결정하기 위한 재귀 _str = tmp return N,M = map(int,sys.stdin.readline().split()) max_possible_num = N-M+1 back_track('',1,max_possible_num,N)
d874434056ddb0a1898aaca8e0143c9372fa618e
beadoer1/algorithm
/programmersPython/lengthOfArrays.py
896
3.625
4
# 정수를 담은 이차원 리스트, mylist 가 solution 함수의 파라미터로 주어집니다. # mylist에 들은 각 원소의 길이를 담은 리스트를 리턴하도록 solution 함수를 작성해주세요. # 제한 조건 # mylist의 길이는 100 이하인 자연수입니다. # mylist 각 원소의 길이는 100 이하인 자연수입니다. # 예시 # input output # [[1], [2]] [1,1] # [[1, 2], [3, 4], [5]] [2,2,1] # 풀이 1 : low level에 가까운 답이라고 한다. # def solution(mylist): # answer = [] # for i in range(len(mylist)): # answer.append(len(mylist[i])) # return answer # 풀이 2 : 프로그래머스 강의 답안(파이썬다운 답이라고..) def solution(mylist): return list(map(len,mylist)) # test case testa = [[1], [2]] testb = [[1, 2], [3, 4], [5]] print(solution(testa)) print(solution(testb))
f4a43398ef50e08a5fd6d4f74d7ebbe081dcc763
beadoer1/algorithm
/spartacodingclub/week_3/02_selections_sort.py
353
3.609375
4
input = [4, 6, 2, 9, 1] def selection_sort(array): n = len(array) for i in range(n-1): min = array[i] for j in range(i,n): if min > array[j]: min = j array[i], array[min] = array[min], array[i] return array selection_sort(input) print(input) # [1, 2, 4, 6, 9] 가 되어야 합니다!
71883f776d1c5ad55cd75f50adba33ee13468f96
anna-yankovskaya/ann-yankovskaya
/test2.py
207
3.90625
4
def name (x) if x == "Вячеслав": print ("Привет, Вячеслав") else: print ("Нет такого имени") name(Вячеслав) name(Вечеслав) name(вячеслав)
9d7a5d0c0ff06d8b69fde92457d9fc71d4bb0a7c
k-kushal07/Algo-Daily
/Day 42 - Two Sum (sorted).py
500
3.828125
4
def two_sum(arr, key): left = 0 right = len(arr) - 1 while left < right: if arr[left] + arr[right] == key: return [left+1, right+1] elif arr[left] + arr[right] > key: right -= 1 elif arr[left] + arr[right] < key: left += 1 inpArray = [int(ele) for ele in input('Enter the array elements: ').split()] key = int(input('Enter the target value: ')) print(two_sum(inpArray, key))
a2b0ea08fd042d1da4835e37422434229b70c17e
k-kushal07/Algo-Daily
/Day 26 - Intersection Two Linked List.py
740
3.5
4
class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def Intersect(self, headA, headB): c1 = headA c2 = headB len1, len2 = 0 while c1: len1 = len1 + 1 c1 = c1.next while c2: len2 = len2 + 1 c2 = c2.next if len1 > len2: for i in range(len1-len2): headA = headA.next else: for i in range(len2-len1): headB = headB.next while headA and headB: if headA == headB: return headA headA = headA.next headB = headB.next return None
0425b8fc9bb8397be051b0216061489cb2889d99
k-kushal07/Algo-Daily
/Day 4 - Reverse Alpha.py
523
3.640625
4
def reverse_alpha(string): newList = list(string) rightptr = len(newList)-1 leftptr = 0 while leftptr < rightptr: if not newList[leftptr].isalpha(): leftptr +=1 elif not newList[rightptr].isalpha(): rightptr -=1 else: newList[leftptr], newList[rightptr] = newList[rightptr], newList[leftptr] leftptr +=1 rightptr -=1 return ''.join(newList) inp = input() print(reverse_alpha(inp))
ee3232f678a26cd9685307c790ba10986e42c073
k-kushal07/Algo-Daily
/Day 35 - Mean per Level.py
763
3.5
4
class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def averageOfLevels(self, root: TreeNode) -> List[float]: if root is None: return [] this_level =[root] next_level = [] result = [] while this_level: total=0 for n in this_level: total = total + n.val if n.left is not None: next_level.append(n.left) if n.right is not None: next_level.append(n.right) print(total) result.append(total/ len(this_level) ) this_level = next_level next_level = [] return result
5cdfa411d2291fc96f9c39809dbca9a5129579a1
k-kushal07/Algo-Daily
/Day 5 - Anagram.py
477
4.09375
4
def anagram(str1, str2): if(len(str1) != len(str2)): return False count = 0 for i in str1: count += ord(i) for i in str2: count -= ord(i) return (count==0) input1, input2, *rest = [word for word in input('Enter the strings to compare: ').split()] print(input1) print(input2) if anagram(input1, input2): print('Yes, the strings are anagram of each other.') else: print('No, the strings are not anagram.')
2a135ffbe1ab2cf748ba75914b6f2626f6774eac
KVonY/11775-HW1
/scripts/stopword.py
276
3.703125
4
import nltk from nltk.corpus import stopwords stop_words = set(stopwords.words('english')) file = open("vocab-1", "rb") output = open("vocab", "w") for i in file: word = i.strip() if word not in stop_words: output.write(word+"\n") output.close() file.close()
cfa49df838598ce1289e236b2904f5cf03043484
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/max-path-sum/main.py
3,238
3.90625
4
def describe(): desc = """ Problem : Given a non-empty binary tree root, return the maximum path sum. Note that for this problem, a path goes from one node to another by traversing edges. The path must have at least one edge and it does not have to pass by the root. NOTE : When we say that the path does not have to pass through the root, it implies that a subtree can also have the max path. ------------------- """ print(desc) class Tree: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right def maxPathSum(root): globalMaxSum = [float("-inf")] dfs(root, globalMaxSum) return globalMaxSum[0] # Time complexity is O(n) def dfs(root, globalMaxSum): if root is None: return float("-inf") else: # We need to find the max paths when we go to the left and when we go to the right # So, we store those 2 values in variables left and right left = dfs(root.left, globalMaxSum) right = dfs(root.right, globalMaxSum) # Now, we have 2 types of max sum. One, where the path originates from the top and goes down a subtree, ie left or right. # And another possibility is one where the path does not originate from the root. # In that case the path can go through both left and right subtrees. # When we consider the situation where the path is from root and goes down a subtree, there are 3 possibilities only # - data at root is a higher value than left or right subtree because there can be negative nodes # - data at root + left subtree is high value # - data at root + right subtree is high value maxFromTop = max(root.data, root.data + left, root.data + right) # When we consider the situation where the path does not originate from root and can go from left subtree to the right subtree, there are 4 possibilities # - data at root is a higher value than left or right subtree because there can be negative nodes # - data at root + left subtree is high value # - data at root + right subtree is high value # - data at root + max from left subtree + max from right subtree is a higher value maxNoTop = max(maxFromTop, root.data + left + right) # And finally we keep track of the global sum as we recurse # It is the maximum between whatever is the current global max sum and the max sum of this current subtree # Also, note that we use an array here to pass global max sum around by reference globalMaxSum[0] = max(globalMaxSum[0], maxNoTop) # Finally return maxFromTop because that's what we need when we backtrack to the parent at any stage. # This value is used above by the recusive calls to get the max from top for left and right subtrees. return maxFromTop def main(): describe() root = Tree(11) root.left = Tree(1) root.right = Tree(2) root.left.left = Tree(4) root.left.left.right = Tree(2) root.right.left = Tree(5) root.right.right = Tree(10) root.right.left.right = Tree(8) print("Result : " + str(maxPathSum(root))) main()
0b5b637e9a7ecfbfe4951932a757074faab74821
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/dfs/binary-tree-all-path-sum/main.py
2,608
3.90625
4
class TreeNode(): def __init__(self, val): self.value = val self.left = None self.right = None def describe(): desc = """ Problem : Given a binary tree and a number S, find all paths from root-to-leaf such that the sum of all the node values of each path equals S -------------- """ print(desc) # currentPath maintains the current state of the pointer in the callstack, as in, how deep we are down a path # allPaths is being passed around like a global # Time complexity of this is O(n^2) def find_paths_recursive(root, target, currentPath, allPaths): # This guard clause handles the case when the left child or right child is None for a node and this func has been called if root is None: return currentPath.append(root.value) if root.left is None and root.right is None and root.value == target: # If a path is found at this point append it to the list of possible paths # But do not return from here. Continue on in the function. You want to remove this node from # the currrentPath before you return so that other paths can also be explored. # Remember that recursion does not stop as soon as a match is found. allPaths.append(list(currentPath)) # This is just a nuisance i think - having to convert the currentPath to a list before appending else: find_paths_recursive(root.left, target - root.value, currentPath, allPaths) find_paths_recursive(root.right, target - root.value, currentPath, allPaths) # If the path led to a successful search, then that currentPath would have been appended to allPaths by now. # This statement is simply a reverse of currentPath.append(root.value) before this function returns in the recursive callstack. # Say we found a path [12, 7, 4] and we are in the call stack for the node with value 4. Then that path # would have been added to allPaths. Now, we can remove 4 from current path and return the call stack, # ie currentPath would be [12, 7]. And the call returns to the parent node of 4, so that it can continue down the path of the other child. del currentPath[-1] def find_paths(root, s): allPaths = [] find_paths_recursive(root, s, [], allPaths) return allPaths def main(): describe() root = TreeNode(12) root.left = TreeNode(7) root.right = TreeNode(1) root.left.left = TreeNode(4) root.right.left = TreeNode(10) root.right.right = TreeNode(5) s = 23 print("Tree paths with sum " + str(s) + ": " + str(find_paths(root, s))) main()
612c8ca841d8da2fc2e8e00f1a14fb22126d1277
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/ways-to-climb-stairs/main.py
2,336
4.1875
4
# Problem : Given a staircase of n steps and a set of possible steps that we can climb at a time # named possibleSteps, create a function that returns the number of ways a person can take to reach the # top of the staircase. # Ex : Input : n = 5, possibleSteps = {1,2} # Output : 8 # Explanation : Possible ways are - 11111, 1112, 1121, 1211, 2111, 122, 212, 221 # Think recursively with a few examples and see if there is any pattern to the solution # When n=0 , possibleSteps = {1,2} - Output = 1 # When n = 1, possibleSteps = {1,2} - Output = 1 # When n = 2, possibleSteps = {1,2} - Output = 2 # When n = 3, possibleSteps = {1,2} - Output = 3 # When n = 4, possibleSteps = {1,2} - Output = 5 # When n = 5, possibleSteps = {1,2} - Output = 8 # The output is a fibonacci sequence : 1,1,2,3,5,8 # The recursive relation here is f(n) = f(n-1) + f(n-2) # # This is because to climb any set of steps n, if the solution is f(n), # then we can find f(n) by finding the solution to climb n-1 steps + 1 step OR n-2 steps and 2 steps, # ie to reach the top we must be either 1 step away from it or 2 steps away from it. # That's why f(n) = f(n-1) + f(n-2) # # Similarly when possibleSteps = {2,3,4}, then to reach any step n, we must be either 2 steps # away from it or 3 steps away from it or 4 steps away from it. # f(n) = f(n-2) + f(n-3) + f(n-4) # If the set of possibleSteps is of length m, then the time complexity is O(m^n) # This can be improved with dynamic programing def waysToClimb01(n, possibleSteps): if n == 0: return 1 noWays = 0 for steps in possibleSteps: if n-steps > 0: noWays += waysToClimb01(n-steps, possibleSteps) return noWays # With dynamic programming consider an array that holds the number of ways to climb n steps. # So, for possibleSteps = {2,3,4} # arr[i] = arr[i-2] + arr[i-3] + arr[i-4] # # arr = 1 0 1 1 2 2 4 5 # n=0 n=1 n=2 n=3 n=4 n=5 n=6 n=7 def waysToClimb02(n, possibleSteps): arr = [0] * (n+1) # n+1 because to consider n steps we need to also consider the 0th step arr[0] = 1 for i in range(1,n+1): for j in possibleSteps: if i-j >= 0: arr[i] += arr[i-j] return arr[n]
2a43e68d93886047dc1df86a45da8a9e135c2a36
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/binary-search/order-agnostic-binary-search/main.py
2,596
3.90625
4
def describe(): desc = """ Problem : Given a sorted array of numbers, find if a given number 'key' is present in the array. Though we know that the array is sorted, we don't know if it's sorted in ascending or descending order. You should assume that the array can have duplicates. Write a function to return the index of the 'key' if it is present in the array, otherwise return -1. Example : Input: [4, 6, 10], key = 10 Output: 2 ------------- """ print(desc) def recursive_binary_search(arr, key, start = 0, stop = -1): # Take care of initialization if stop == -1: stop = len(arr) if len(arr) == 0: return -1 if stop == start: if arr[start] == key: return start else: return -1 # One way to calculate mid is : mid = int((start + stop)/2) # However, this might result in integer overflow if both start and stop indices are very high # The process below is a much safer way to do the same mid = start + (stop-start)//2 if key == arr[mid]: return mid idx_left, idx_right = -1, -1 idx_left = recursive_binary_search(arr, key, start, mid) if mid+1 < stop: idx_right = recursive_binary_search(arr, key, mid+1, stop) if idx_left >= 0: return idx_left elif idx_right >= 0: return idx_right else: return -1 # Iterative binary search def binary_search(arr, key): start, end = 0, len(arr)-1 is_ascending = arr[start] < arr[end] while start <= end: mid = start + (end - start)//2 if key == arr[mid]: return mid if is_ascending: if key < arr[mid]: end = mid - 1 else: start = mid + 1 else: if key < arr[mid]: start = mid + 1 else: end = mid - 1 return -1 # Since the search range is getting reduced by 1/2 on each iteration or recursive call the time complexity is O(logn) def main(): describe() input = [1, 2, 3, 4, 5, 6, 7] key = 5 print("Input : " + str(input) + " , " + str(key)) print(recursive_binary_search(input, key)) input = [4, 6, 10] key = 10 print("Input : " + str(input) + " , " + str(key)) print(binary_search(input, key)) input = [10, 6, 4] key = 10 print("Input : " + str(input) + " , " + str(key)) print(binary_search(input, key)) input = [10, 6, 4] key = 4 print("Input : " + str(input) + " , " + str(key)) print(binary_search(input, key)) main()
dad6411cd63d2f083c537a34d20376cb9b395fa3
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/longest-substring-without-repeating-chars/main.py
4,287
4.1875
4
# Problem : Given a string with alphabetical characters only create a function that # returns the length of the longest substring without repeating characters. # Ex : "abcdbeghef" # Output : 6 -> because the longest substring without repeating characters is "cdbegh" # The brute force solution is to find all possible substrings with no repeating characters # and return the length of the substring whose length is maximum # However the time complexity of this is O(n^3) def longestSubstringWithoutRepeating01(str): if len(str) <= 1: return len(str) def hasNoRepeatingChars(str): charCount = [0] * 128 # Initialize an array for all the ascii chars upto code 128 with char count set to 0 for char in str: charCount[ord(char)] = charCount[ord(char)] + 1 if charCount[ord(char)] > 1: return False return True maxLen = 0 # Keep 2 loops - one for tracking the start of the index from where we want to take the substrings # and in a nested loop for each starting index get all possible substrings till the end of the string for i in range(len(str)): for j in range(i,len(str)): substr = str[i:j+1] # Get the substring from index i upto index j if hasNoRepeatingChars(substr): maxLen = max(maxLen, len(substr)) return maxLen def longestSubstringWithoutRepeating02(str): if len(str) <= 1: return len(str) dp = [] # Stores the local maximum substring upto index i dp.append(str[0]) maxSubstr = dp[0] for i in range(1, len(str)): # If you found a char that is already present in the previous longest substring without repeating chars # you want to find the part of the substring that is after that repeated character for the new sequence of chars if str[i] in dp[i-1]: strSinceLastOccuranceOfChar = dp[i-1].split(str[i])[-1] dp.append(strSinceLastOccuranceOfChar + str[i]) else: dp.append(dp[i-1] + str[i]) if len(dp[i]) > len(maxSubstr): maxSubstr = dp[i] return len(maxSubstr) # We maintain 2 pointers - one for start of the substring and one for the end of the substring # We maintain an array of ascii codes of chars where we store the index of the last occurance of a character. # The start pointer of the substrings begin at 0 and the stop pointer keeps moving forward # as long as there is no repeating char which we can find from the array maintaining the last seen position of char. # If a repeating char is encountered, it means the sliding window needs to move, as in the start pointer # needs to move after the repeated char. # Time complexity of this traversal technique is O(n) def longestSubstringWithoutRepeating03(str): if len(str) <= 1: return len(str) charMap = [-1] * 128 # For each character store the index of the latest occurance of that character start = 0 stop = 0 maxLen = 0 while stop < len(str): # If the char at stop pointer exists in the charMap, ie, it is not -1 # that means there is a repeated char. And the new start has to be moved to the position after the # occurance of that character. if charMap[ord(str[stop])] >= start: start = charMap[ord(str[stop])] + 1 charMap[ord(str[stop])] = stop substr = str[start:stop+1] maxLen = max(len(substr),maxLen) stop += 1 return maxLen # This is exactly like the previous solution except that it is using a for loop for moving the stop pointer ahead def longestSubstringWithoutRepeating04(str): if len(str) <= 1: return len(str) charMap = [-1] * 128 # For each character store the index of the latest occurance of that character start = 0 maxLen = 0 for i in range(len(str)): # If the char at i exists in the charMap, ie, it is not -1 # that means there is a repeated char. And the new start has to be moved to the position after the # occurance of that character. if charMap[ord(str[i])] >= start: start = charMap[ord(str[i])] + 1 charMap[ord(str[i])] = i maxLen = max(maxLen, i+1-start) return maxLen
f7d450ccb704ac45e68680b97c363f6eef9e0185
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/in-place-reverse-linkedlist/reverse-every-k-elm-sublist/main.py
3,385
4.15625
4
from __future__ import print_function class Node(): def __init__(self, value, node=None): self.value = value self.next = node def print_list(self): node = self while node is not None: print(node.value, end='->') node = node.next print('null') print() def describe(): desc = """ Problem : Given the head of a Singly LinkedList, and a number k, reverse every k sized sub-list starting from the head. If, in the end, you are left with a sub-list with less than k elements, reverse that too. Example : Input : 1->2->3->4->5->6->7->8->null Output: 3->2->1->6->5->4->8->7->null ----------------- """ print(desc) def reverse_every_k_elements(head, k): new_head = None sublist_start = None end_of_prev_sublist = None while head is not None: sublist_start = head # This section locally reverses the sublist # By the time the loop here exits, local_prev represents the head of the reversed sublist # And the head represents the next node after the sublist ends local_prev = None count = 0 while head is not None and count < k: node = head.next head.next = local_prev local_prev = head head = node count += 1 sublist_start.next = head # Make the new sublist_start as the current position of head # If the end of previous sublist is null, then this is the first sublist reversal and will be the new head # Otherwise the next node of the end of previous sublist will be the node representing the beginning of the reversed sublist if end_of_prev_sublist is None: new_head = local_prev else: end_of_prev_sublist.next = local_prev # Reposition the end of previous sublist end_of_prev_sublist = sublist_start return new_head def alternate_impl_reverse_every_k_elements(head, k): if k <= 1 or head is None: return head current, previous = head, None while True: last_node_of_previous_part = previous # after reversing the LinkedList 'current' will become the last node of the sub-list last_node_of_sub_list = current next = None # will be used to temporarily store the next node i = 0 while current is not None and i < k: # reverse 'k' nodes next = current.next current.next = previous previous = current current = next i += 1 # connect with the previous part if last_node_of_previous_part is not None: last_node_of_previous_part.next = previous else: head = previous # connect with the next part last_node_of_sub_list.next = current if current is None: break previous = last_node_of_sub_list return head def main(): describe() head = Node(1) head.next = Node(2) head.next.next = Node(3) head.next.next.next = Node(4) head.next.next.next.next = Node(5) head.next.next.next.next.next = Node(6) head.next.next.next.next.next.next = Node(7) head.next.next.next.next.next.next.next = Node(8) print("Nodes of original LinkedList are: ", end='') head.print_list() result = reverse_every_k_elements(head, 3) print("Nodes of reversed LinkedList are: ", end='') result.print_list() main()
27071dd477e491361bca5574ff2c5ed4c9a9efcb
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/subsets/distinct-subsets/main.py
1,244
4.09375
4
def describe(): desc = """ Problem : Given a set of elements find all it's distinct subsets. Example: Input : [1,3] Output : [], [1], [3], [1,3] ---------------- """ print(desc) # Follow the BFS approach # start with an empty set. # Iterate over the given list of numbers and add the number at current index to all the elements of the existing subsets. # # In each set the number of elements double. So we have a total of 2^n subsets, ie, representing all the permutations. # Time complexity is O(n* 2^n) def find_subsets(nums): subsets = [] if len(nums) == 0: return subsets subsets.append([]) for i in range(0, len(nums)): for j in range(0, len(subsets)): # Remember that python references list by pointers # So do not append to an existing list. But, rather copy it to a new list and append it. subset = subsets[j].copy() # This also creates a new list - list(subsets[i]) subset.append(nums[i]) subsets.append(subset) return subsets def main(): describe() print("Here is the list of subsets: " + str(find_subsets([1, 3]))) print("Here is the list of subsets: " + str(find_subsets([1, 5, 3]))) main()
819f6f6246c99bc7e296e81825840829074892e9
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/sliding-window/avg-subarr-size-k/main.py
2,210
3.78125
4
def describe(): desc = """ Problem : Given an array, find the average of all subarrays of K contiguous elements in it. Ex : Given Array: [1, 3, 2, 6, -1, 4, 1, 8, 2], K=5 Output: [2.2, 2.8, 2.4, 3.6, 2.8] """ print(desc) # Time complexity = O(n^2) def brute_force_find_averages_of_subarrays(K, arr): result = [] print("Length of arr is : {}, K is : {}, Var i will iterate upto (not including) : {}".format(len(arr), K, len(arr)-K+1)) for i in range(len(arr)-K+1): # find sum of next 'K' elements _sum = 0.0 for j in range(i, i+K): _sum += arr[j] result.append(_sum/K) # calculate average return result # Time complexity = O(n) # Maintain a container for collecting the result # Maintain a pointer for the start of the window and one for the end of the window # Move end pointer from start one by one UNTIL it is of the length of the sliding window # Calculate aggregate, and insert into the results collection # Move end pointer by one element right and start pointer by one element right def find_averages_of_subarrays(K, arr): result = [] windowSum, windowStart = 0.0, 0 for windowEnd in range(len(arr)): # add the next element - keep adding the next element until you hit the length of the sliding window windowSum += arr[windowEnd] # slide the window, we don't need to slide if we've not hit the required window size of 'k' # ie, the index of the end pointer of the window should be start of window + K or more. # if windowEnd >= windowStart + K - 1: if windowEnd >= windowStart + K - 1: result.append(windowSum / K) # calculate the average windowSum -= arr[windowStart] # subtract the element going out windowStart += 1 # slide the window ahead return result def main(): describe() result1 = brute_force_find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2]) print("Averages of subarrays of size K (solution 1): " + str(result1)) result2 = find_averages_of_subarrays(5, [1, 3, 2, 6, -1, 4, 1, 8, 2]) print("Averages of subarrays of size K (solution 2): " + str(result2)) main()
c7f8f20059820e7a98f97e7045cf5aa8a3c98cef
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/remove_dupes/main.py
1,458
3.859375
4
# Problem : Given an array of integers create a fucntion that returns an array # containing the values of the array without duplicates - order doesnt matter # One solution is to traverse the array and push the element into an output array if it already doesnt exist in the output array. # The time complexity of this is O(n^2) def removeDuplicates01(arr): res = [] for elm in arr: if elm not in res: res.append(elm) return res # Sort the array and then traverse it. If element does not exist in the resulting array's last element # then insert it into the resulting element. # Time complexity is O(nlogn) for sort and O(n) for traversal -> O(nlogn) def removeDuplicates02(arr): arr.sort() res = [] for i in range(len(arr)): if len(res) == 0 or res[len(res)-1] != arr[i]: res.append(arr[i]) return res # Same solution as above, but with a slightly different implementation def removeDuplicates03(arr): if len(arr) == 0: return [] arr.sort() res = [arr[0]] for i in range(1, len(arr)): if arr[i] != arr[i-1]: res.append(arr[i]) return res # This solution leverages the fact that if you insert the same key in a hash table with some value it will simply get overriden # The time complexity of this is O(n) def removeDuplicates04(arr): visited = {} for elm in arr: visited[elm] = True return list(visited.keys())
1f90abdf8b6e6696fd9fb977e322588e02036ca5
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/n-queens/main.py
3,636
3.9375
4
def describe(): desc = """ Problem : Find the number of ways possible to place n queens on a n x n chess board such that no 2 queens can attack each other. The queens attack each other when they are placed on the same row, same column or placed diagonal to each other. Example : Input : n = 4 Output : 2 -------------------- """ print(desc) # The approach to this problem is to choose a place where a queen can be placed in each row. # So, we can keep going 1 queen per row and find possible spots. # - For possible spots start going column by column in each row. # - Place a queen in each column and check if it is a feasible solution. If yes, continue to next row. Else backtrack. # As we move on to next rows, it is possible that due to the placement of queens in the previous rows, all possible columns in the current row will get attacked. # In this case we backtrack to the previous row and try the next column in the previous row. # # Time complexity is O(n^2 * n!) def nQueens(n): board = [['.'] * n for i in range(n)] return _nQueens(n, board, 0) def _nQueens(n, board, row): # If we have reached past the last row then we have already found a solution, so return back 1 -> because you have found 1 way to put n queens on the board if row >= n: return 1 # Otherwise iterate over all the cells in the row to find possible solutions # Once you find a solution add it to sumWays and then remove the queen from that row, because you want to continue exploring other solutions # ie this is the part where you get to backtrack sumWays = 0 for col in range(n): # If placing the queen in the current cell is safe, then explore this solution further by considering next rows. # Regardless of whether a solution is found or not remove the queen from that cell and explore the next cell in the row. if isNotAttacked(board, row, col): board[row][col] = 'Q' sumWays += _nQueens(n, board, row+1) board[row][col] = '.' # Remove the queen after finding possible solutions because yiou want to exp[lore solutions by placing queen in another cell return sumWays # How to check if a queen is attacked. # - We are not putting 2 queens in the same row, so we dont have to check the rows. # - We havent placed anything in the board beyond the current row, so, we dont need to check the bottom half of the board. # - We only need checking the column and the 2 diagonals and that too only on the part of the board above the current row. # The time complexity of this section is O(n) def isNotAttacked(board, row, col): i = row-1 # Represents the row above the current row we want to check jLeft = col-1 # On the ith row, jLeft represents the cell diagonal from the current cell in consideration jRight = col+1 # On the ith row, jRight represents the cell in the other diagonal from the current cell in consideration # Starting with the previous row of the current row, keep going up a row and keep checking the column in the rows above and the diagonal cells in the rows above while i >= 0: if board[i][col] == 'Q' or (jLeft >= 0 and board[i][jLeft] == 'Q') or (jRight < len(board) and board[i][jRight] == 'Q'): return False else: i -= 1 jLeft -= 1 jRight += 1 return True def main(): describe() print("Input : ", 4) print("Output : ", nQueens(4)) print("\n\n") print("Input : ", 8) print("Output : ", nQueens(8)) print("\n\n") main()
2137855080a086d767c6c1c750a92e2c50e47f5a
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/sort/main.py
1,234
4.28125
4
# Problem : Sort an array # Time complexity O(n^2) def bubbleSort(arr): if len(arr) <= 1: return arr # Run an outer loop len(arr) times i = 0 while i < len(arr): # Keep swapping adjacent elements, ie sort adjacent elements in the inner loop j = 1 while j < len(arr): if arr[j-1] > arr[j]: arr[j-1], arr[j] = arr[j], arr[j-1] j += 1 i += 1 return arr # Time complexity of merge sort is O(nlogn) def mergeSort(arr): if len(arr) <= 1: return arr def merge(left, right): if len(left) == 0: return right if len(right) == 0: return left res = [] i = 0 j = 0 while i < len(left) and j < len(right): if left[i] <= right[j]: res.append(left[i]) i += 1 else: res.append(right[j]) j += 1 if i < len(left): res = res + left[i:len(left)] if j < len(right): res = res + right[j:len(right)] return res mid = len(arr)//2 l = mergeSort(arr[0:mid]) r = mergeSort(arr[mid:len(arr)]) return merge(l, r)
b87e71043ec03bb7d40b33b697c7d5adc1e985ad
sumanmukherjee03/practice-and-katas
/python/top-50-interview-questions/product-arr-except-self/main.py
1,198
3.796875
4
# Problem : Given an array of integers write a function to return an array which # at arr[i] contains the product of all elements except element at index i # For ex : With input array [2,5,3,4] # Output : [60,24,40,30] # Precompute the products from the left and from the right, ie cumulative products from left and right. # Time complexity is O(n) def productExceptSelf(arr): if len(arr) == 0: return [] if len(arr) == 1: return [1] leftCumulativeProduct = [1] * len(arr) leftCumulativeProduct[0] = arr[0] for i in range(1, len(arr)): leftCumulativeProduct[i] = leftCumulativeProduct[i-1] * arr[i] rightCumulativeProduct = [1] * len(arr) rightCumulativeProduct[len(arr)-1] = arr[len(arr)-1] for i in range(len(arr)-2,-1,-1): rightCumulativeProduct[i] = rightCumulativeProduct[i+1] * arr[i] out = [1] * len(arr) for i in range(len(arr)): p = 1 if i == 0: p *= rightCumulativeProduct[i+1] elif i == len(arr)-1: p *= leftCumulativeProduct[i-1] else: p *= (leftCumulativeProduct[i-1] * rightCumulativeProduct[i+1]) out[i] = p return out
e0852864241832608165933832d2dfdc4f12177e
sumanmukherjee03/practice-and-katas
/python/grokking-coking-interview/top-k-elements/k-largest-numbers/main.py
1,874
4.03125
4
import heapq def describe(): desc = """ Problem : Given an unsorted array find the K largest numbers in it. Example : Input : [3, 1, 5, 12, 2, 11], K = 3 Output : [5, 12, 11] --------------- """ print(desc) # The bruteforce solution is to sort the given array and return the k largest numbers from the end. # A better solution is to iterate from the array and keep inserting the numbers into a max heap and then pop k times from the heap def unoptimized_find_k_largest_numbers(nums, k): res = [] maxheap = [] for i in range(0, len(nums)): heapq.heappush(maxheap, -nums[i]) for j in range(0, k): res.append(-heapq.heappop(maxheap)) return res # Another more optimized solution is to maintain a min heap of k elements as we iterate through the given array. # As we encounter numbers, we take out the smallest element from the maxheap and insert the larger of the 2 numbers, # ie the smallest from the heap and the new number in the iteration into the heap. # That way at the end of the iteration even though it is a minheap it will contain the largest elements of the array. # Time complexity for this is O(k log(k) + (n-k) log(k)) def find_k_largest_numbers(nums, k): minheap = [] for i in range(0, len(nums)): if len(minheap) < k: heapq.heappush(minheap, nums[i]) else: if nums[i] > minheap[0]: heapq.heappop(minheap) heapq.heappush(minheap, nums[i]) return minheap def main(): describe() input, key = [3, 1, 5, 12, 2, 11], 3 print("Input : " + str(input) + " , " + str(key)) print("Output : " + str(find_k_largest_numbers(input, key))) input, key = [5, 12, 11, -1, 12], 3 print("Input : " + str(input) + " , " + str(key)) print("Output : " + str(find_k_largest_numbers(input, key))) main()