blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
491c2742d15d8be5d872a4c59f3bb920afd8edd8
Lucas130/leet
/53-maxSubArray.py
659
3.671875
4
""" 给定一个整数数组 nums ,找到一个具有最大和的连续子数组(子数组最少包含一个元素),返回其最大和。 示例: 输入: [-2,1,-3,4,-1,2,1,-5,4] 输出: 6 解释: 连续子数组 [4,-1,2,1] 的和最大,为 6。 """ class Solution: def maxSubArray(self, nums) -> int: ans = nums[0] for i in range(1, len(nums)): if nums[i] + nums[i - 1] > nums[i]: nums[i] += nums[i - 1] if nums[i] > ans: ans = nums[i] return ans if __name__ == '__main__': s = Solution() nums = [-2,1,-3,4,-1,2,1,-5,4] print(s.maxSubArray(nums))
22c4d7e3bdb5779dba3b403c33c91956a05a9755
panthitesh6410/python-programs
/string-functions.py
622
4.65625
5
# String Functions : # join() : it joins items of a list with a particular symbol : print(",".join(["apple", "banana", "orange"])) # replace() : to replace certain old element with new element: print("hello world".replace("world", "John")) # startswith() - to check a string starts with a particular element newstr = "my name is" print(newstr.startswith("my")) # endwith() - to check a string ends with a particular element print(newstr.endswith("is")) # to convert a string into uppercase : print(newstr.upper()) # similarlly we have lower() to convert into lowercase: print(newstr.lower())
53d9410695649ae1cfe25deb11ecfff734fe6408
TrySickle/Saugus
/Euler/euler12.py
518
3.5625
4
import math def getFactors(x): factorList = [] factorList.append(1) factorList.append(x) for y in range (2, int(math.sqrt(x))): if x % y == 0: factorList.append(y) factorList.append(int(x / y)) return factorList factors = 0 counter = 1 while factors < 500: triangle = 0 for i in range(1, counter + 1): triangle += i factors = len(getFactors(triangle)) counter += 1 answer = 0 for i in range(1, counter): answer += i print answer
07caed184c85cf53485d6cbbd108a2e214ef2cc5
EliotRagueneau/OBIpython
/Kevin.py
5,409
3.875
4
from typing import * from Theo import read_flat_file def get_features(txt: str) -> str: """Extract features lines from flat text and return them This function is written by Kévin Merchadou. Args: txt: flat text with features to extract Returns: string of features """ lines = txt.split("\n") features = "" for i in range(len(lines)): if lines[i] == "FEATURES Location/Qualifiers": features = "".join(lines[i + 1:]) break return features def get_genes(features: str) -> [dict]: """Extract gene and CDS data from their section inside features table This function is written by Kévin Merchadou. Args: features: text with gene to extract Returns: list of ORF (either as ORF or as dict) """ list_cds = [] list_genes = [] bloc = "".join(features.split(" ")) bloc_cds = bloc.split(" ") for ligne in range(len(bloc_cds)): if bloc_cds[ligne][0:3] == "CDS": list_cds.append(ligne) for ligne in range(len(list_cds)): cds = {"start": None, "stop": None, "frame": None, "length": None, "name": "unknown", "protein": "xxx", "product": "unknown"} bloc_cleaned = bloc_cds[list_cds[ligne]].split("/") if bloc_cleaned[0][6:17] == "complement(": start = int((bloc_cleaned[0][17:].strip()).split("..")[0]) inter_stop = (bloc_cleaned[0][17:].strip()).split("..")[1] stop = int(inter_stop[:len(inter_stop) - 1]) cds["start"] = start cds["stop"] = stop cds["frame"] = 1 - (start % 3) cds["length"] = stop - start else: start = int((bloc_cleaned[0].strip()).split("..")[0][6:]) stop = int((bloc_cleaned[0].strip()).split("..")[1]) cds["start"] = start cds["stop"] = stop cds["frame"] = 1 + (start % 3) cds["length"] = stop - start for ligne2 in range(len(bloc_cleaned)): if bloc_cleaned[ligne2][:5] == "gene=": cds["name"] = (bloc_cleaned[ligne2][5:].split('"'))[1] elif bloc_cleaned[ligne2][:8] == "product=": cds["product"] = (bloc_cleaned[ligne2][8:].split('"'))[1] elif bloc_cleaned[ligne2][:12] == "translation=": sequence = (bloc_cleaned[ligne2][12:].split('"')[1]).split(" ") protein = "" for aa in range(len(sequence)): protein = protein + sequence[aa] cds["protein"] = protein list_genes.append(cds) return list_genes pass def read_gen_bank(filename: str) -> Dict[str, Union[str, List[dict]]]: """Parse a GenBank file This function is written by Kévin Merchadou. Args: filename: .gb file to parse Returns: dictionary of : features: description: entry title (genbank descriptor DEFINITION) type: myBio keywords only - dna, rna, or protein data: sequence data only if available otherwise set to ‘xxx’. When the sequence is too large the entry does not contain data. ID: Identifier (locus) length: sequence length gbtype: molecule type as described in a genbank entry. organism: organism codeTableID: NCBI genetic code table identifier list of gene = ORF (dict) start: start position (in bp) stop: stop position (in bp) frame: frame (1, 2, 3,- 1, -2, or -3) length: gene length (in bp) name: gene name if available. By default, ‘unknown’. protein: translated protein sequence if available. By default, ‘xxx’. product: product name if available. By default, ‘unknown’. """ features = {"Description": None, "ID": None, "length": None, "organism": None, "type": None, "genes": None, "sequence": None} genes = get_genes(get_features(read_flat_file(filename))) string = read_flat_file(filename) lignes = string.split("\n") for i in range(len(lignes)): mots = lignes[i].split(" ") for j in range(len(mots)): if mots[j] == "DEFINITION": features["Description"] = " ".join(mots[j + 2:]) elif mots[j] == "VERSION": features["ID"] = mots[j + 5] elif mots[j] == "bp": features["length"] = mots[j - 1] + " bp" elif mots[j] == "ORGANISM": features["organism"] = " ".join(mots[j + 2:]) elif mots[j] in ["DNA", "RNA", "Protein"]: features["type"] = mots[j] elif mots[j] == "ORIGIN": features["sequence"] = "\n".join(lignes[i + 1:-3][10:]) features["genes"] = genes return lignes
2d934868869909f1a4e2e8d9456fd8f97412fb54
kh4r00n/Aprendizado-de-Python
/ex011.py
228
3.71875
4
n1 = float(input('Digite a altura da parede')) n2 = float(input('Digite a largura da parede')) a = n1 * n2 b = a / 2 print('Será necessário {:.2f} litros de tinta para pintar uma parede com {:.2f} m2'.format(b, a))
344640c1eaadc03b106d41ff368fa18e68cebd7e
savi8sant8s/em-busca-das-nozes
/Em Busca das Nozes - V1/Em Busca das Nozes.py
4,069
3.59375
4
import random import time #Posição dos personagens posicao = [] #Movimentos quantpassos = 0 sementespegas = 0 #Mapa do jogo mapa = [[1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1], [1,1,1,1,1,1,1,1,1,1]] def boasvindas(): saudacao = print("Bem-vindo(a) ao jogo \"Em Busca das NOZES\".\nInfelizmente, todas as NOZES do mundo foram extintas", "e agora só restam 4\nvariedades de nozes escondidas em baixo de geleiras na Antártida, que", "foram\nguardadas por pesquisadores. Fizeram isso, porque premeditaram uma possível\nextinção", "de algumas espécies de plantas no futuro.", "\nEnfim. Encontre-as para replantá-las no mundo.\n", "\nVamos lá!!! Encontre as rotas mais rápidas\npara terminar o jogo com menos passos.\n") def instrucoes(): exemplo = print("Escreva o sentido que você quer fazer assim:", "\nExemplo: D (Mova para a direita).\n") comandos = print("D ou d - move para direita.\nE ou e - move para esquerda.\nC ou c - move para cima.\nB ou b - move para baixo.") def imprimirmapa(): for x in range(10): print(str(mapa[x][:]).strip("[]").replace(",","")) def posicaopersonagem(posicao): posicao = (random.sample(range(0,10),10)) return posicao posicao = posicaopersonagem(posicao) boasvindas() imprimirmapa() mapa[posicao[2]][posicao[3]] = 0 mapa[posicao[4]][posicao[5]] = 0 mapa[posicao[6]][posicao[7]] = 0 mapa[posicao[8]][posicao[9]] = 0 print("\nSe localizando no mapa... \nLembre-se você é o número 8 e as sementes os números 0.\n") time.sleep(4) inicio = input("Começar? sim ou nao: ") print("\n\n") if inicio == "SIM" or inicio == "sim" or inicio == "Sim": while True: mapa[posicao[0]][posicao[1]] = 8 instrucoes() print("\nPASSOS: {0}\n".format(quantpassos)) imprimirmapa() comandos = input("\nDigite o comando: ") if comandos == "D" or comandos == "d": casa1 = posicao[1] mapa[posicao[0]][casa1] = 1 if posicao[1] + 1 > 9: print("Não pode ultrapassar aqui.") time.sleep(2) else: posicao[1] += 1 quantpassos += 1 if comandos == "E" or comandos == "e": casa1 = posicao[1] mapa[posicao[0]][casa1] = 1 if posicao[1] - 1 < 0: print("Não pode ultrapassar aqui.") time.sleep(2) else: posicao[1] -= 1 quantpassos += 1 if comandos == "C" or comandos == "c": casa1 = posicao[0] mapa[casa1][posicao[1]] = 1 if posicao[0] - 1 < 0: print("Não pode ultrapassar aqui.") time.sleep(2) else: posicao[0] -= 1 quantpassos += 1 if comandos == "B" or comandos == "b": casa1 = posicao[0] mapa[casa1][posicao[1]] = 1 if posicao[0] + 1 > 9: print("Não pode ultrapassar aqui.") time.sleep(2) else: posicao[0] += 1 quantpassos += 1 for a in range(10): for b in range(10): if mapa[a][b] == 0: sementespegas += 1 if sementespegas == 0: print("\n\nFim de Jogo. Você conseguiu coletar todas as sementes.") print("\nQuantidade de passos: {0}".format(quantpassos)) time.sleep(5) break else: sementespegas = 0 else: print("Ok. Até mais!")
d12017d2423c8020f7d4f57b983aad4b34efc0af
penghaos/learn_python3_by_hardway_notes
/ex40_a.py
1,031
4
4
# dict mystuff = {'apple': "I AM APPLES!"} print(mystuff['apple']) # this goes in mystuff.py def apple(): print("I AM APPLES!") # so I can 'import mystuff.py' and use 'apple' function import mystuff mystuff.apple() # put a variable named tangerine def apple(): print("I AM APPLES!") tangerine = "Living reflection of a dream" # 调用 import mystuff mystuff.apple() print(mystuff.tangerine) # 知识点1:.(dot) -> mystuff.apple() # 调用dict和mystuff.xx的异同,[key]和.key 其实本质是一样的 mystuff['apple'] mystuff.apple() mystuff.tangerine # class的一个例子 class MyStuff(object): def __init__(self): self.tangerine = "And now a thousand years between" def apple(self): print("I AM CLASSy APPLES!") # class 类似下面三行 thing = MyStuff() thing.apple() print(thing.tangerine) # three ways to get things from things # dict style mystuff['apple'] # module style mystuff.apples() print(mystuff.tangerine) # class style thing = MyStuff() thing.apples() print(thing.tangerine)
1890cffdc871db396792a9ed1a17451a1e1f525b
bmanandhar/python_refresher
/palindrome.py
759
3.953125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Nov 3 19:39:33 2019 @author: bijayamanandhar """ class Solution(object): #code starts below def palindrome(self, string): i = 0 while i <= len(string)//2: if string[i] != string[len(string) - 1 - i]: return False i += 1 return True if __name__ == '__main__': string = [ 'rotator', 'country', 'repaper', 'kayak', 'house', 'sagas', 'malayalam' ] S = Solution() for i in range(len(string)): print(S.palindrome(string[i])) # Prints 'True' or 'False' #code ends here
1ba2269fe464dee7481e20adfbab9b0c1406fefe
lijinglj90/shop
/case/test_database.py
711
3.609375
4
""" 目标:自动化测试中操作项目数据库 案例: 判断用户id(1)是否收藏了id为2的文章 1--未收藏,0--收藏 """ # 导包 import pymysql # 获取连接对象 conn = pymysql.connect("127.0.0.1", "root", "123456", "hmtt", charset = "utf-8") # 获取游标对象 cursor = conn.cursor() # 执行方法sql sql = "select is_delect from news_collection where user_id =1 and acticle_id=2" cursor.execute(sql) # 获取结果并进行断言 print(cursor.fetchone()) result = cursor.fetchone() # 断言 assert 0 == result[0] # 关闭游标对象 cursor.close() # 关闭连接对象 conn.close()
776c7cc5e15d1f0038fabd943f819e33c748fe30
eronekogin/leetcode
/test_helper.py
6,863
3.765625
4
class ListNode: def __init__(self, x: int): self.val = x self.next: 'ListNode' | None = None def __repr__(self): nextVal = self.next.val if self.next else None return '{0} -> {1}'.format(self.val, nextVal) def create_node_list( self, start: int | None = None, stop: int | None = None, givenList: list[int] | None = None) -> 'ListNode': temp = self if givenList is None: if start is None or stop is None: return self for i in range(start, stop): temp.next = ListNode(i) temp = temp.next else: for i in givenList: temp.next = ListNode(i) temp = temp.next return self def create_cycle_list( self, givenList: list[int], cyclePos: int) -> 'ListNode': currNode, currList = self, [] for i in givenList: currNode.next = ListNode(i) currList.append(currNode.next) currNode = currNode.next currNode.next = currList[cyclePos] return self def print_single_list(self) -> list[int]: currNode, rslt = self, [] while currNode: rslt.append(currNode.val) currNode = currNode.next return rslt class TreeNode: def __init__(self, x: int): self.val = x self.left = None self.right = None def __repr__(self): left = self.left.val if self.left else None right = self.right.val if self.right else None return '{0} -> ({1}, {2})'.format(self.val, left, right) def create_tree(self, givenDict: dict[int, tuple[int | None, int | None]]): nodes = [self] while nodes: nextNodes = [] for node in nodes: left, right = givenDict.get(node.val, (None, None)) if left is not None: node.left = TreeNode(left) nextNodes.append(node.left) if right is not None: node.right = TreeNode(right) nextNodes.append(node.right) nodes = nextNodes return self def print_tree(self) -> dict[int, tuple[int, int]]: nodes, rslt = [self], {} while nodes: nextNodes = [] for node in nodes: left, right = None, None if node.left: left = node.left.val nextNodes.append(node.left) if node.right: right = node.right.val nextNodes.append(node.right) rslt[node.val] = (left, right) nodes = nextNodes return rslt class Node(TreeNode): def __init__(self, x: int): super().__init__(x) self.next = None def __repr__(self): return '{0}, next: {1}'.format(super().__repr__(), self.next) def create_tree(self, givenDict: dict[int, tuple[int, int]]): nodes = [self] while nodes: nextNodes = [] for node in nodes: left, right = givenDict.get(node.val, (None, None)) if left is not None: node.left = Node(left) nextNodes.append(node.left) if right is not None: node.right = Node(right) nextNodes.append(node.right) nodes = nextNodes def print_tree(self) -> dict[int, tuple[int, int, int]]: nodes, rslt = [self], {} while nodes: nextNodes = [] for node in nodes: left, right, nxt = None, None, None if node.left: left = node.left.val nextNodes.append(node.left) if node.right: right = node.right.val nextNodes.append(node.right) if node.next: nxt = node.next.val rslt[node.val] = (left, right, nxt) nodes = nextNodes return rslt class GraphNode: def __init__(self, val: int, neighbors: list['GraphNode']): self.val = val self.neighbors = neighbors class RandomNode: def __init__(self, val: int, next: 'RandomNode', random: 'RandomNode'): self.val = val self.next = next self.random = random def __repr__(self): next = self.next.val if self.next else None random = self.random.val if self.random else None return '{0}: (next: {1}, random: {2})'.format(self.val, next, random) class NestedInteger: def __init__(self, num: int | None = None): if num is None: self.num = None self.nestedList = [] else: self.num = num self.nestedList = None def isInteger(self) -> bool: return self.nestedList is None def getInteger(self) -> int | None: if self.num is not None: return self.num def add(self, elem: 'NestedInteger'): if self.nestedList is None: self.num = None self.nestedList = [] self.nestedList.append(elem) def setInteger(self, value: int): self.num = value self.nestedList = None def getList(self) -> list['NestedInteger']: if self.nestedList is not None: return self.nestedList return [self] def __repr__(self) -> str: if self.nestedList is None: return str(self.num) else: return str(self.nestedList) class QuadTreeNode: def __init__( self, val: bool, isLeaf: bool, topLeft: 'QuadTreeNode', topRight: 'QuadTreeNode', bottomLeft: 'QuadTreeNode', bottomRight: 'QuadTreeNode'): self.val = val self.isLeaf = isLeaf self.topLeft = topLeft self.topRight = topRight self.bottomLeft = bottomLeft self.bottomRight = bottomRight class NaryTreeNode: def __init__(self, val=None, children=None): self.val = val self.children = children class DoublyLinkedListNode: def __init__(self, val, prev, next, child): self.val = val self.prev = prev self.next = next self.child = child class Employee: def __init__(self, id: int, importance: int, subordinates: list[int]): self.id = id self.importance = importance self.subordinates = subordinates class MountainArray: def __init__(self, items: list[int]) -> None: self.items = items def get(self, index: int) -> int: return self.items[index] def length(self) -> int: return len(self.items)
cfd7692e4a9d358c38dba9d285a7a1a4a0a48c9c
BlendaBonnier/foundations-sample-website
/color_check/controllers/get_color_code.py
1,060
3.859375
4
# This file should contain a function called get_color_code(). # This function should take one argument, a color name, # and it should return one argument, the hex code of the color, # if that color exists in our data. If it does not exist, you should # raise and handle an error that helps both you as a developer, # for example by logging the request and error, and the user, # letting them know that their color doesn't exist. import json def get_color_code(color_name): #reading the data from the file and loop through and comapre keys with color_name try: color_name = color_name.lower().strip() except AttributeError: pass try: with open('color_check/data/css-color-names.json') as f: data = json.load(f) for key in data.keys(): if color_name == key: hex = data[key] return hex break color_hex_code = None return color_hex_code except FileNotFoundError: return "File can not be found"
00234e92b20dd30caa6db1f35e9aeb499d35a4a4
smazzone/python_playground
/toppings.py
1,515
4.09375
4
requested_toppings = 'mushrooms' if requested_toppings != 'anchovies': print(requested_toppings) else: print('oh oh') requested_toppings = ['mushrooms', 'onions', 'pineapple'] print('mushrooms' in requested_toppings) requested_toppings = ['mushrooms', 'onions', 'pineapple'] if 'mushrooms' in requested_toppings: print ('adding mushrooms...') if 'pineapple' in requested_toppings: print ('adding pineapple...') print("\nFinished making your pizza!") requested_toppings = ['mushrooms', 'onions', 'pineapple','green peppers'] for requested_topping in requested_toppings: if requested_topping == 'green peppers': print("sorry we are out of green peppers") else: print(f"adding {requested_topping}") print("\nFinished making your pizza!") requested_toppings = [] if requested_toppings: for requested_topping in requested_toppings: print(f"Adding {requested_topping}.") print("\nFinished making your pizza!") else: print("Are you sure you want a plain pizza without any toppings?") available_toppings = ['mushrooms', 'olives', 'green peppers', 'pepperoni', 'pineapple', 'extra cheese'] requested_toppings = ['mushrooms', 'french fries', 'extra cheese','nutella','ham','parmisan','got cheese','olives'] for requested_topping in requested_toppings: if requested_topping in available_toppings: print(f"Adding {requested_topping}.") else: print(f"Sorry, we don't have {requested_topping}.") print("\nFinished making your pizza!")
d1997cc360217d5afcb7e996bdddd1d698451a86
hkdahal/CodingProblem1
/Main.py
1,033
4.03125
4
import re def do_stuff(filename): highest = 0 the_word = "" with open(filename) as f: for line in f: line = line.strip().split() for word in line: # cleaned_word = clean_word(word) cleaned_word = clean_by_regex(word) value = common_value(cleaned_word) if value > highest: highest = value the_word = word return the_word def clean_word(word): word = word.lower() if word.isalpha(): cleaned_word = word else: cleaned_word = ''.join(ch for ch in word if ch.isalpha()) return cleaned_word def clean_by_regex(word): return re.sub("/[^a-z]/", "", word.lower()) def common_value(word): highest = 0 for ch in word: if word.count(ch) > highest: highest = word.count(ch) return highest def main(): filename = input("Enter the filename: ") print(do_stuff(filename)) if __name__ == '__main__': main()
ff081f501ecf253307a049dfba82118a486afc47
CrazyITDream/fullstacks
/week4/day1/fonction_Return.py
370
3.78125
4
#!/usr/bin/python #coding:utf-8 """ @author: 小火 @contact: xx@xx.com @software: PyCharm @file: fonction_Return.py @time: 2019/1/24 14:31 """ #函数有返回值 # def add(*args): # Sum=0 # for i in args: # Sum+=i # return (Sum) # f=add(1,2,3,4,5,6,4,7,8,9) # print(' %s ' %f) def foot(): return ['a','b','c','d','f'] C=foot() print('%s' %C)
bf3358d4a150cdbad04245047016df5affe5cce0
esrok/algo
/trees/__init__.py
5,231
3.578125
4
class BinaryTreeNode(object): def __init__(self, value, parent=None): self.value = value self.parent = parent self._left = self._right = None @property def left(self): return self._left @left.setter def left(self, node): self._left = node node.parent = self @property def right(self): return self._right @right.setter def right(self, node): self._right = node node.parent = self def replace(self, new_node): if self.parent is None: return if self.parent.right == self: self.parent.right = new_node else: self.parent.left = new_node class BinaryTree(object): PRE_ORDER = 'pre-order' IN_ORDER = 'in-order' POST_ORDER = 'post-order' TRAVERSE_TYPES = (PRE_ORDER, IN_ORDER, POST_ORDER) def __init__(self, root=None): self.root = root def add(self, node): raise NotImplementedError() def traverse_left_to_right(self): if self.root is None: return for node in self._traverse_left_to_right(self.root): yield node.value def _traverse_left_to_right(self, node, traverse_type=None): if traverse_type is None: traverse_type = self.IN_ORDER assert traverse_type in self.TRAVERSE_TYPES if traverse_type == self.PRE_ORDER: yield node if node.left is not None: for left_node in self._traverse_left_to_right(node.left): yield left_node if traverse_type == self.IN_ORDER: yield node if node.right is not None: for right_node in self._traverse_left_to_right(node.right): yield right_node if traverse_type == self.POST_ORDER: yield node class SearchTree(BinaryTree): def get_path(self, node): parent = node.parent while parent is not None: yield parent parent = parent.parent def search_node(self, value): if self.root is None: return None current_node = self.root while True: if value > current_node.value: if current_node.right is None: return None else: current_node = current_node.right elif value < current_node.value: if current_node.left is None: return None else: current_node = current_node.left else: return current_node def search(self, value): result = self.search_node(value) if result is not None: return result.value def add(self, node): if self.root is None: self.root = node return current_node = self.root while True: if node.value > current_node.value: if current_node.right is None: current_node.right = node break else: current_node = current_node.right elif node.value < current_node.value: if current_node.left is None: current_node.left = node break else: current_node = current_node.left else: # values are equal # so no need to add break def _check_invariant(self): if self.root is None: return for node in self._traverse_left_to_right(self.root): if node.parent is None: continue if node == node.parent.left: assert node.value < node.parent.value else: assert node.value > node.parent.value def _successor(self, node): current_node = node if current_node.right is not None: return next(self._traverse_left_to_right(node.right)) else: # child without right subtree while current_node is not None: parent = current_node.parent if parent is None: # node has maximum value in tree return None if parent.left == current_node: # left child return parent else: # right child without right subtree current_node = current_node.parent def remove(self, value): node = self.search_node(value) if node is None: raise Exception('trying to remove non-existing node') if node.right is None: # if node.left is None # node.parent.pointer will become None # and it is correct node.replace(node.left) elif node.left is None: node.replace(node.right) else: right = node.right left = node.left node.replace(right) right_left = next(self._traverse_left_to_right(right)) right_left.left = left self._check_invariant()
5dea3bc50aa229c114fb787095b5e7d752611d6d
Remus1992/PDXCGLabs
/day_10/word_count.py
2,456
3.5625
4
# book = open ("faust.txt", "r") # print (book.name) # book.close() # with open ("faust.txt", "r") as book: # print (book.name) # with open ("faust.txt", "r") as book: # book_contents = book.read() # print(book_contents) # with open ("faust.txt", "r") as book: # for line in book: # print(line, end="") # with open ("faust.txt", "r") as book: # # size_to_read = 10 # # book_contents = book.read(size_to_read) # # while len(book_contents) > 0: # print (book_contents, end='*') # book_contents = book.read(size_to_read) # searchfile = open("faust.txt", "r") # for line in searchfile: # if "Hurrah" in line: print (line) # searchfile.close() # f = open("faust.txt", "r") # searchlines = f.readlines() # f.close() # for i, line in enumerate(searchlines): # if "Hurrah!" in line: # for l in searchlines[i:i+3]: print (l), # print # file=open("faust.txt","r+") # # from collections import Counter # wordcount = Counter(file.read().split()) # for item in wordcount.items(): print("{}\t{}".format(*item)) # file.close(); # file=open("faust.txt","r+") # wordcount={} # for word in file.read().split(): # if word not in wordcount: # wordcount[word] = 1 # else: # wordcount[word] += 1 # print (word,wordcount) # file.close(); wordcount = {} with open('faust.txt') as file: # with can auto close the file for word in file.read().split(): word = word.lower() if word not in wordcount: wordcount[word] = 1 else: wordcount[word] += 1 wordcount = sorted(wordcount.items(), key=lambda x: x[1], reverse=True) for k, v in wordcount[:5]: print(k, v) ### # from collections import Counter # with open('faust.txt') as file: # with can auto close the file # wordcount = Counter(file.read().split()) # # for k, v in wordcount.most_common(5): # print(k, v) ### Mikey's # from collections import Counter # ctr = Counter() # token_ctr = 0 # with open('faust.txt', 'r') as f: # for line in f: # line_words = line.strip().split() # for word in line_words: # if len(word) > 4: # token_ctr += 1 # ctr[word] += 1 # # def mostcommon(): # print("The most common words are ", ctr.most_common(10)) # print("There are ",token_ctr, " words in 'Faust' by Goethe.") # print("There are ",len(ctr), " unique words therein.") # print(mostcommon())
57144a2fdb7f49cbfe4950d12ea49d01198437db
QuentinDuval/PythonExperiments
/arrays/HandsOfStraight_Interesting.py
1,446
3.859375
4
""" https://leetcode.com/problems/hand-of-straights Alice has a hand of cards, given as an array of integers. Now she wants to rearrange the cards into groups so that each group is size W, and consists of W consecutive cards. Return true if and only if she can. """ from typing import List class Solution: def isNStraightHand(self, hand: List[int], W: int) -> bool: """ The idea is to have a list of straight hand in constructions. Sorting the hand and moving through the list in increasing order: - if we have a list in construction whose last card is 2 back or more, we failed - if we have a list in construction whose last card is 1 back, complete it - else we create a new list To find the right list to append, we can use a queue to go through the list in construction in turns, and not loop through all of them. """ if W <= 1: return True stacks = deque() for card in sorted(hand): if stacks: s = stacks.popleft() if s[-1] == card: stacks.append(s) stacks.append([card]) elif s[-1] + 1 < card: return False elif len(s) < W - 1: s.append(card) stacks.append(s) else: stacks.append([card]) return not stacks
de25f5865dee2a36da2421b6bb319863df5779d3
Niki227/Nikhita-sPythonAssessmentTask
/99FinalTest.py
5,652
4.09375
4
# Assigns a function to the whole menu def my_menu(): import os # clear statement os.system('cls') print(" ------------------------------------------------") print("| |") print("| 99FinalTest |") print("| Name : Nikhita Arora |") print("| Version : 01 |") print("| |") print(" ------------------------------------------------") print("") # List print("1. Hello World") print("2. Goodbye World") print("3. Goodbye Person") print("4. Good Teacher") print("5. forLoop") print("6. whileLoop") print("7. string Loop") print("8. Convert to ascii") print("9. Encode a string") print("x. To Exit") answer = input("Enter an option ") # if...else statements for the output of each function (e.g. hello world- option 1, goodbye world- option2, etc.) # Hello World option if answer == "1": my_function1() my_functionRestart() # Goodbye World option elif answer == "2": my_function2() my_functionRestart() # Goodbye Person option elif answer == "3": my_function3() my_functionRestart() # Good Teacher Option elif answer == "4": my_function4() my_functionRestart() # For Loop option elif answer == "5": my_function5() my_functionRestart() # While Loop option elif answer == "6": my_function6() my_functionRestart() elif answer == "7": my_function7() my_functionRestart() elif answer == "8": my_function8() my_functionRestart() elif answer == "9": my_function9() my_functionRestart() # breaks the code elif answer == "x": my_functionX() # Invalid option else: my_functionInvalid() my_functionRestart() # Defining functions for each set of code def my_function1(): print("") print("----Start of Output ---------------------------") print("") print("Hello World") print("") print("----End of Output -----------------------------") def my_function2(): print("") print("----Start of Output ---------------------------") print("") print("Hello World") input("------> Program paused - press enter to continue") print("Goodbye World") print("") print("----End of Output -----------------------------") def my_function3(): print("") print("----Start of Output ---------------------------") print("") print("Hello") username = input("What is your name ? ") print("Goodbye " + username) print("") print("----End of Output -----------------------------") def my_function4(): print("") print("----Start of Output ---------------------------") print("") username = input("Teacher's name (try Mr Horan) ") x = "Mr Horan" if username == x: print("You are lucky, he is a great teacher.") else: print(username + " is an ok teacher") print("") print("----End of Output -----------------------------") def my_function5(): print("") print("----Start of Output ---------------------------") print("") for x in range(1, 500): print(x) print("") print("----End of Output -----------------------------") def my_function6(): print("") print("----Start of Output ---------------------------") print("") x = input("What is the name of this subject ") y = "IST" while x != y: print("Not Correct - try again") x = input("What is the name of this subject ") else: print("") print("") print(" Congratulations!!") print("") print("") print("") print("----End of Output -----------------------------") def my_function7(): print("") print("----Start of Output ---------------------------") print("") word = input("What is your string? ") for x in word: print(x) print("") print("----End of Output -----------------------------") def my_function8(): print("") print("----Start of Output ---------------------------") print("") word = input("What is your string? ") for x in word: print(x, "=", ord(x)) print("") print("----End of Output -----------------------------") def my_function9 (): print("") print("----Start of Output ---------------------------") print("") word = input("What is your string? ") ascii = "" for x in word: encode = chr(ord(x)+1) print(x, "=", encode, sep='') # seperate command gets rid of the space between the variables and quoted text ascii += encode print(ascii) print("") print("----End of Output -----------------------------") def my_functionX(): print("") print("----Start of Output ---------------------------") print("") print("") print("----End of Output -----------------------------") print("") print("") print("") input("Press Enter to continue") def my_functionInvalid(): print("") print("----Start of Output ---------------------------") print("") print("invalid option") print("") print("----End of Output -----------------------------") def my_functionRestart(): print("") print("") print("") input("Press Enter to continue") return my_menu() # loop my_menu()
21816f17050910e9e18ccd56d0411ceab4b65bd8
shambhand/pythontraining
/material/code/advanced_oop_and_python_topics/4_ManagedAttributeDemo/ManagedAttributeDemo2.py
649
3.8125
4
# Attribute properties are inherited by the # derived class import sys class Person: def __init__(self, name): self._name = name def getName(self): print('fetch...') return self._name def setName(self, value): print('change...') self._name = value def delName(self): print('remove...') del self._name name = property(getName, setName, delName, "name property docs") class Employee (Person): pass def main (): bob = Employee('Bob Smith') print(bob.name) bob.name = 'Robert Smith' print(bob.name) del bob.name print('-'*20) sue = Employee('Sue Jones') print(sue.name) print(Person.name.__doc__) sys.exit (0) main ()
305081295b34e634765d5bada0bf383082d08515
Ikshitkate/java-html-5-new-project
/python/checkAnagram.py
435
4.15625
4
def checkAnagram(str1, str2): len1 = len(str1) len2 = len(str2) if len1 != len2: return 0 str1 = sorted(str1) str2 = sorted(str2) for i in range(0, len(str1)): if str1[i] != str2[i]: return 0 return 1 str1 = input("Enter String 1: ") str2 = input("Enter String 2: ") if checkAnagram(str1, str2): print("Strings are ANAGRAM") else: print("Strings are NOT ANAGRAM")
9252f1de223cfea3c7031a5b22df080ea6b3c0bd
zoro666/Travelling_Santa_2018
/baseline.py
2,529
3.578125
4
# Load all the libraries import numpy as np import pandas as pd def find_closest_point(p1,p2): """ Finds the euclidean distance between 2 points""" xa = p1[1,] ya = p1[2,] xb = p2[1,] yb = p2[2,] dist = np.sqrt((xa-xb)**2 + (ya-yb)**2) return dist def nearest_point_in_array(ref_pt,arr): """ Finds the nearest point from the array relative to the reference point""" mindist = np.inf index = None for i in range(len(arr)): x = arr[i,0] if x != np.nan: dist = find_closest_point(ref_pt,arr[i,:]) if dist < mindist: mindist = dist index = i return index,mindist def baseline_model(start_pt,arrc,arrp,end_pt,verbose = False): """ Baseline model which utilizes nearest distance criteria""" l = len(arrc) l += len(arrp) start = start_pt route = [start_pt[0,]] path_dist = 0 for i in range(l): # Run for all the arrays if len(arrc) != 0: indc,mindistc = nearest_point_in_array(start, arrc) if len(arrp) != 0: indp,mindistp = nearest_point_in_array(start, arrp) # Find which index is closer if (len(arrc) != 0) and (len(arrp) != 0): if i%10 == 0: route.append(arrp[indp,0]) path_dist += mindistp start = arrp[indp,:] arrp = np.delete(arrp, indp, 0) elif (mindistc <= mindistp): route.append(arrc[indc,0]) path_dist += mindistc start = arrc[indc,:] arrc = np.delete(arrc, indc, 0) elif (mindistc > mindistp): route.append(arrp[indp,0]) path_dist += mindistp start = arrp[indp,:] arrp = np.delete(arrp, indp, 0) elif (len(arrc) == 0) and (len(arrp) != 0): route.append(arrp[indp,0]) path_dist += mindistp start = arrp[indp,:] arrp = np.delete(arrp, indp, 0) elif (len(arrc) != 0) and (len(arrp) == 0): route.append(arrc[indc,0]) path_dist += mindistc start = arrc[indc,:] arrc = np.delete(arrc, indc, 0) else: break if verbose: print('Step number is : ' + str(i) + '/'+str(l)) # Returning back to north pole diste = find_closest_point(start,end_pt) route.append(end_pt[0,]) path_dist += diste return route, path_dist
2fd22a779ca3a6c146eb1969c446b50f6d1d9fd1
xanderyzwich/Playground
/python/tools/games/tic_tac_toe.py
3,652
4.0625
4
""" # Find Winner on a Tic Tac Toe Game Tic-tac-toe is played by two players A and B on a 3 x 3 grid. Here are the rules of Tic-Tac-Toe: Players take turns placing characters into empty squares `(" ")`. The first player A always places "X" characters, while the second player B always places "O" characters. "X" and "O" characters are always placed into empty squares, never on filled ones. The game ends when there are 3 of the same (non-empty) character filling any row, column, or diagonal. The game also ends if all squares are non-empty. No more moves can be played if the game is over. Given an array moves where each element is another array of size 2 corresponding to the row and column of the grid where they mark their respective character in the order in which A and B play. Return the winner of the game if it exists (`A` or `B`), in case the game ends in a draw return `"Draw"`, if there are still movements to play return `"Pending"`. You can assume that moves is valid (It follows the rules of Tic-Tac-Toe), the grid is initially empty and A will play first. ### Constraints: 1 <= moves.length <= 9 moves[i].length == 2 0 <= moves[i][j] <= 2 There are no repeated elements on moves. moves follow the rules of tic tac toe. """ from unittest import TestCase from tools.decorators import function_details, function_details_concurrent @function_details def who_wins(move_list): # setup move_count = len(move_list) full_board = (move_count == 9) board = [[0, 0, 0], [0, 0, 0], [0, 0, 0]] # Fill the board with marks for i in range(0, move_count, 2): a_move = move_list[i] board[a_move[0]][a_move[1]] = 'A' if move_count > i+1: # confirm b move exists b_move = move_list[i + 1] board[b_move[0]][b_move[1]] = 'B' # Check for winner winning_arrangements = [ [(0, 0), (0, 1), (0, 2)], [(1, 0), (1, 1), (1, 2)], [(2, 0), (2, 1), (2, 2)], # Rows [(0, 0), (1, 0), (2, 0)], [(0, 1), (1, 1), (2, 1)], [(0, 2), (1, 2), (2, 2)], # Columns [(0, 0), (1, 1), (2, 2)], [(2, 0), (1, 1), (0, 2)], # Diagonals ] for left, middle, right in winning_arrangements: values = [board[row][col] for row, col in [left, middle, right]] # get values nonzero = values[0] != 0 match = len(set(values)) == 1 if match and nonzero: return values[0] # evaluate non-win return 'Draw' if full_board else 'Pending' class TestWhoWins(TestCase): def test_downhill_diagonal(self): moves = [[0, 0], [2, 0], [1, 1], [2, 1], [2, 2]] expected = 'A' assert who_wins(moves) == expected def test_uphill_diagonal(self): moves = [[0, 0], [1, 1], [0, 1], [0, 2], [1, 0], [2, 0]] expected = 'B' assert who_wins(moves) == expected def test_draw(self): moves = [[0, 0], [1, 1], [2, 0], [1, 0], [1, 2], [2, 1], [0, 1], [0, 2], [2, 2]] expected = 'Draw' assert who_wins(moves) == expected def test_pending_too_short(self): moves = [[0, 0], [1, 1]] expected = 'Pending' assert who_wins(moves) == expected def test_pending_with_enough(self): moves = [[1, 1], [0, 0], [1, 2], [1, 0], [2, 0], [0, 2]] expected = 'Pending' assert who_wins(moves) == expected def test_horizontal(self): moves = [[1, 1], [0, 0], [1, 0], [0, 1], [1, 2]] expected = 'A' assert who_wins(moves) == expected def test_vertical(self): moves = [[1, 1], [0, 2], [0, 0], [2, 2], [1, 0], [1, 2]] expected = 'B' assert who_wins(moves) == expected
ee5542d8b47d87f4e73ed20e8bc742567e858f31
RicardoAugusto-RCD/exercicios_python
/exercicios/ex091.py
795
3.59375
4
# Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatórios. Guarde esses resultados em um # dicionário. No final, coloque esse dicionário em ordem, sabendo que o vencedor tirou o maior número no dado. from random import randint from time import sleep jogada = dict() contador = 1 jogada['jogador1'] = randint(1, 6) jogada['jogador2'] = randint(1, 6) jogada['jogador3'] = randint(1, 6) jogada['jogador4'] = randint(1, 6) print(F'{" ↓ VALORES SORTEADOS ↓"}') for keys, valor in jogada.items(): print(f'{keys} tirou {valor} no dado') sleep(1) print() print(f'{"↓ RANKING DOS JOGADORES ↓"}') for jogador in sorted(jogada, key=jogada.get, reverse=True): print(f' {contador}ºlugar {jogador} com {jogada[jogador]}') sleep(1) contador += 1
820ee70774109fdb7c32b511f5f8ff281fa321c1
caw13/pi-top-sandbox
/name_game.py
386
4.125
4
name = input("What is you name?") if name == "Chad": print("That is the best name ever!!!") print("Hi %s" % name) else: print("Sorry you are not Chad") favorite_movie = input("What is your favorite movie? ") if favorite_movie == "Batman": print("Awesome!") elif favorite_movie == "The Breakfast Club": print("Nice") else: print("I haven't seen that one")
0f62098a7e7d3e87f3cbacebcea2776e7c355b5e
hyxmartin/LeetCode
/1-1000/0003-Longest_Substring_Without_Repeating_Characters.py
1,002
4.0625
4
""" Given a string, find the length of the longest substring without repeating characters. Example 1: Input: "abcabcbb" Output: 3 Explanation: The answer is "abc", with the length of 3. Example 2: Input: "bbbbb" Output: 1 Explanation: The answer is "b", with the length of 1. Example 3: Input: "pwwkew" Output: 3 Explanation: The answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring. """ class SolutionClassFinal: def lengthOfLongestSubstring(self, s): """ :param s: str :return: int """ map = {} maxlen = 0 for i, val in enumerate(s): if val not in map: map[val] = i else: maxlen = max(maxlen, i - map[val]) map[val] = i return maxlen # Space: O(1) # Time: O(N) if __name__ == "__main__": s = 'abcabcbb' print(SolutionClassFinal().lengthOfLongestSubstring(s))
9b81c4213c8241ba1c4e78941332c0e74e42fb43
matthewdargan/Cozmo-Capture-the-Flag
/common/setup.py
1,956
3.78125
4
import time from typing import List, Dict import cozmo from cozmo.objects import LightCube, LightCube1Id, LightCube2Id, LightCube3Id def setup(robot: cozmo.robot.Robot, cube_color: cozmo.lights.Light) -> (List[LightCube]): """ Setup up the cozmo program to run for each computer to use. :param robot robot to get cubes for :param cube_color color of this team's cubes """ # store all of the cube objects in a list robot_cubes: List[LightCube] = [robot.world.get_light_cube(LightCube1Id), robot.world.get_light_cube(LightCube2Id), robot.world.get_light_cube(LightCube3Id)] # set the colors for robot1's cubes to blue and robot2's to red for cube in range(len(robot_cubes)): robot_cubes[cube].set_lights(cube_color) # start the game once the master computer sends out the start message over the network print("Set Cozmo's in position to play.") # give a 10 second period for the users to set their robots in their bases and hide their cubes time.sleep(10) print("Start playing!") return robot_cubes def get_team_colors(teams: int) -> (Dict[int, cozmo.lights.Light], Dict[int, cozmo.lights.Light]): """ Gets the team colors and opponent colors based on the number of teams playing in the game. :param teams: number of teams playing in the game :return: the team colors and the opponent colors """ team_colors: Dict[int, cozmo.lights.Light] = {1: cozmo.lights.red_light, 2: cozmo.lights.blue_light} opponent_colors: Dict[int, cozmo.lights.Light] = {1: cozmo.lights.blue_light, 2: cozmo.lights.red_light} if teams == 3: team_colors[3] = cozmo.lights.green_light opponent_colors: Dict[int, cozmo.lights.Light] = {1: cozmo.lights.green_light, 2: cozmo.lights.red_light, 3: cozmo.lights.blue_light} return team_colors, opponent_colors
6a01da653a18c1d2bf1f683ac5f2cc84441529fb
gabriellaec/desoft-analise-exercicios
/backup/user_280/ch21_2020_03_04_02_27_34_915049.py
229
3.703125
4
dias = input('Quantos dias?') horas = input('Quantas horas?') minutos = input('Quantos minutos?') segundos = input('Quantos segundos?') total_segundos = (24*60*60*dias)+(60*60*horas)+(60*minutos)+(segundos) print(total_segundos)
1e8f6a2c67089ebf7562e9863ae2d7bacd19e118
Testudinate/Lectures
/Lectures/Lecture_13/cycled_queue.py
190
3.953125
4
A = [10, [20, [30, None]]] A[1][1][1] = A #зацикливание списка def print_list(A): p = A while p: #!=None print(p[0]) p = p[1] print_list(A)
8803245f15f19d637ee1f32922cf175a8beb018e
neilbd/Arithiga_Original
/ship.py
1,241
3.65625
4
import pygame from pygame.locals import * from sys import exit import os.path as osp class Ship(pygame.sprite.Sprite): def __init__(self, screen, ship_image, x, y): pygame.sprite.Sprite.__init__(self) self.screen = screen self.screen_width, self.screen_height = self.screen.get_size() self.image = ship_image self.rect = self.image.get_rect() self.lives = 3 self.rect.x = x self.rect.y = y # Updates location of ship depending on x and def update(self, x, y): if y <= 320: self.rect.y = 320 elif y + self.rect.height >= self.screen_height: self.rect.y == self.screen_height - self.rect.height else: self.rect.y = y if x + self.rect.width >= self.screen_width: self.rect.x = self.screen_width - self.rect.width elif x < 0: self.rect.x = 0 else: self.rect.x = x # Returns current x position of the ship def XPosition(self): return self.rect.x # Returns current y position of the ship def YPosition(self): return self.rect.y def getImage(self): return self.rect # Returns current number of lives of the ship def CurrentLives(self): return self.lives # Reduces number of lives of the ship when it hits a number or operator def ReduceLives(self): self.lives -= 1
029fe733593c597270b4da18cf51a18694b75c47
yanmarcossn97/Python-Basico
/Exercicios/exercicio042.py
720
4.0625
4
r1 = int(input('Comprimento reta r1(cm): ')) r2 = int(input('Comprimento reta r2(cm): ')) r3 = int(input('Comprimento reta r3(cm): ')) if r1 == r2 and r1 == r3: print('Esses valores foram um triângulo.') print('Tipo: Equilátero(todos os lados são iguais.).') elif abs(r2 - r3) < r1 < r2 + r3 and abs(r1 - r3) < r2 < r1 + r3 and abs(r1 - r2) < r3 < r1 + r2: if r1 == r2 or r1 == r3 or r2 == r3: print('Esses valores formam um triângulo.') print('Tipo: Isósceles(dois lados iguais).') else: print('Esses valores formam um triângulo.') print('Tipo: Escaleno(todos os lados são diferentes.).') else: print('Esses valores não formam um triângulo.')
c5d3b0558eeb456da2e89b9b9952cb850cb05d74
Er-Rakesh-Yadav/text-Editor
/editor.py
3,775
3.625
4
""" @author : Rakesh Yadav @task : To develop a text-editor """ from tkinter import * from tkinter.messagebox import showinfo from tkinter.filedialog import askopenfilename, asksaveasfilename import os def newFile(): global file editor_root.title("Untitled - Text-Editor") file = None TextArea.delete(1.0, END) def openFile(): global file file = askopenfilename(defaultextension=".txt", filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")]) if file == "": file = None else: editor_root.title(os.path.basename(file) + " - Notepad") TextArea.delete(1.0, END) f = open(file, "r") TextArea.insert(1.0, f.read()) f.close() def saveFile(): global file if file is None: file = asksaveasfilename(initialfile='Untitled.txt', defaultextension=".txt", filetypes=[("All Files", "*.*"), ("Text Documents", "*.txt")]) if file == "": file = None else: # Save as a new file f = open(file, "w") f.write(TextArea.get(1.0, END)) f.close() editor_root.title(os.path.basename(file) + " - Notepad") print("File Saved") else: # Save the file f = open(file, "w") f.write(TextArea.get(1.0, END)) f.close() def quitApp(): editor_root.destroy() def cut(): TextArea.event_generate("<>") def copy(): TextArea.event_generate("<>") def paste(): TextArea.event_generate("<>") def about(): showinfo("Text-Editor", "Text-Editor is Created by Rakesh Yadav & contact me at " "'https://github.com/Er-Rakesh-Yadav'") def themes(): showinfo("Themes", "Hye!! Theme section is under-development") if __name__ == '__main__': # Basic tkinter setup editor_root = Tk() editor_root.title("Untitled - Text-Editor") editor_root.wm_iconbitmap("icon1.png") editor_root.geometry("640x500") editor_root.minsize(400, 30) # Add TextArea bg_color = "#ccc" fg_color = "black" TextArea = Text(editor_root, bg=bg_color, fg=fg_color, font="lucida 13") file = None TextArea.pack(expand=True, fill=BOTH) # Lets create a menubar MenuBar = Menu(editor_root) # File Menu Starts FileMenu = Menu(MenuBar, tearoff=0) # To open new file FileMenu.add_command(label="New", command=newFile) # To Open already existing file FileMenu.add_command(label="Open", command=openFile) # To save the current file FileMenu.add_command(label="Save", command=saveFile) FileMenu.add_separator() FileMenu.add_command(label="Exit", command=quitApp) MenuBar.add_cascade(label="File", menu=FileMenu) # File Menu ends # Edit Menu Starts EditMenu = Menu(MenuBar, tearoff=0) # To give a feature of cut, copy and paste EditMenu.add_command(label="Cut", command=cut) EditMenu.add_command(label="Copy", command=copy) EditMenu.add_command(label="Paste", command=paste) MenuBar.add_cascade(label="Edit", menu=EditMenu) # Edit Menu Ends # Help Menu Starts HelpMenu = Menu(MenuBar, tearoff=0) HelpMenu.add_command(label="About Notepad", command=about) HelpMenu.add_command(label="Theme", command=themes) MenuBar.add_cascade(label="Help", menu=HelpMenu) # Help Menu Ends editor_root.config(menu=MenuBar) # Adding Scrollbar using rules from Tkinter lecture no 22 Scroll = Scrollbar(TextArea) Scroll.pack(side=RIGHT, fill=Y) Scroll.config(command=TextArea.yview) TextArea.config(yscrollcommand=Scroll.set) editor_root.mainloop()
3b2986bf081c44fd8e1e0642c665cd8a65caa8c2
Tititun/python-basics
/lesson_1/task_3.py
115
3.65625
4
n = input('Введите число\n') nn = n + n nnn = n * 3 result = int(n) + int(nn) + int(nnn) print(result)
1e3066998b166b55d950ee8fce25dbe41fed1cab
GodamSwapna/list-Question
/sumof 6.py
133
4.03125
4
n=int(input("enter you are number:")) i=1 sum=0 while i<=n: num=int(input("enter a number")) sum=sum+num i=i+1 print(sum)
674ac1dd6b509eed495b5e07f10d6bb541751003
Gavinee/Leetcode
/500 键盘行.py
1,497
3.515625
4
""" 给定一个单词列表,只返回可以使用在键盘同一行的字母打印出来的单词。 示例1: 输入: ["Hello", "Alaska", "Dad", "Peace"] 输出: ["Alaska", "Dad"] 注意: 你可以重复使用键盘上同一字符。 你可以假设输入的字符串将只包含字母。 """ __author__ = 'Qiufeng' class Solution: def findWords(self, words): """ :type words: List[str] :rtype: List[str] """ dict1 = {} tt1 = "QWERTYUIOPqwertyuiop" tt2 = "ASDFGHJKLasdfghjkl" tt3 = "ZXCVBNMzxcvbnm" list1 = [tt1,tt2,tt3] i = 0 j = 0 x = 0 while i<len(list1): while j<len(list1[i]): dict1[list1[i][j]] = x j += 1 x += 1 j = 0 i += 1 i = 0 j = 1 temp = [] while i<len(words): if len(words[i]) ==1: temp.append(words[i]) i += 1 continue while j<len(words[i]): if j == len(words[i])-1 and dict1[words[i][j-1]] == dict1[words[i][j]]: temp.append(words[i]) i += 1 j = 1 break if dict1[words[i][j-1]] != dict1[words[i][j]]: i += 1 j = 1 break else: j += 1 return temp
9e8ca9ebff179dd7569b772480fa5cdc0d819573
nitheeshmavila/practice-python
/Think Python Book/Conditionals-and-recursion/Exercise5.2.py
390
4
4
# Exercise 5.2. Write a function called do_n that takes a function object and a number, n , as arguments, and that calls the given function n times. square = lambda x: x*x def do_n(square, n): # return sum of squares of integers starting from 1 to n sumOfSquares = 0 for i in range(1, n+1): sumOfSquares += square(i) return sumOfSquares print(do_n(square, 1))
230c68de00e968fc7b665e41d9fc64caef652be7
chjlarson/Classwork
/python/hw3/print_bill.py
1,115
4
4
# Christopher Larson # CSCI 238 homework #3, Problem #4 # print_bill.py # 9/14/13 # # This program will calculate the sales tax and then the total bill. def main(): print('This program tests the print_bill function.\n') print('Calling print_bill with the arguments subtotal = 25 ' \ + 'and rate = 5.') print('The total should be $26.25.\n') print_bill(25, 5) print('\nCalling print_bill with the arguments subtotal = 15.47 ' \ + 'and rate = 7.5.') print('The total should be $16.63.\n') print_bill(15.47, 7.5) print('\nCalling print_bill with the argument subtotal = 125.82') print('The total should be $136.20.\n') print_bill(125.82) print('\nCalling print_bill with the argument subtotal = 982.82 ') print('The total should be $1063.90.\n') print_bill(982.82) def print_bill(subtotal, rate=8.25): actual_rate = rate / 100 sales_tax = subtotal * actual_rate total = subtotal + sales_tax print('%-9s $%7.2f' % ('Subtotal:', subtotal)) print('%-9s $%7.2f' % ('Tax:', sales_tax)) print('%-9s $%7.2f' % ('Total:', total)) main()
06dba562792e1abffbe8f6c6d451f4760b78162c
ranggaahsana/Basic-Python
/09 - Latihan Perhitungan Sederhana/Kelvin.py
446
4.125
4
#Latihan konversi satuan temperatur print('Program Konversi Temperatur Sederhana') kelvin = float(input("Masukan Suhu dalam kelvin: ")) print('Suhu dalam kelvin:', kelvin, "kelvin") #Reamur celcius = kelvin-273 print('Suhu dalam Celcius:', celcius, "Celcius") #Reamur reamur = (4/5)*(kelvin-273) print('Suhu dalam reamur:', reamur, "reamur") #Kelvin fahrenheit = ((9/5)*(kelvin-273))+32 print('Suhu dalam fahrenheit:', fahrenheit, "fahrenheit")
a7f38b036c6968fb3a81d18baddd1159b3440b0f
RomuloAS/TBFSBS
/parse.py
8,412
3.8125
4
#!/usr/bin/env python3 import os import argparse import textwrap from pathlib import Path from collections.abc import MutableSequence """ Parse TBFSBS (Text-Based Format for Storing Biological Sequences): The parser reads the file(s) and print the header and the sequence length of all sequences in the file(s). Parser also have the option to write the TBFSBS sequences back into an output file, with configurable maximum length of the sequence line. Header format: . begins with the percentage symbol (%) . the identifier: string . a numeric target value: integer or float or null . the description: string (can contain whitespace) """ class TBFSBS_Record(): """Class representing one sequence in TBFSBS format. This class represents one sequence in a TBFSBS file. The entry has the header with identifier, target value, and description, as well the biological sequence. The representation of the class objects as a string prints the TBFSBS record id, value, description and the sequence length. """ def __init__(self, identifier = None, target_value = None, description = None , sequence = None): """Initialize class TBFSBS Record. This function initialize the TBFSBS record object with the identifier, target value, description, and the sequence. Parameters ------------- identifier: str The identifier of the sequence target_value: float A numeric target value description: str A description for the record sequence: str The biological sequence """ self.identifier = identifier self.target_value = target_value self.description = description self.sequence = sequence def __str__(self): """Override representation of the class objects as a string. This function overrides the representation of the class objects as string in a format with the Id, value, description, and sequence length. See the example below: ID: Id1 Value: 2.5 Description: My description Sequence length: 502 """ value = self.target_value if self.target_value: value = round(self.target_value, 1) record_str = "ID: {ID}\n"\ "Value: {TARGET_VALUE}\n"\ "Description: {DESCRIPTION}\n"\ "Sequence length: {SEQ_LENGTH}\n".format( ID = self.identifier, TARGET_VALUE = value, DESCRIPTION = self.description, SEQ_LENGTH = len(self.sequence)) return record_str class TBFSBS(MutableSequence): """Class representing TBFSBS file sequences. This class represents all sequences in [a] TBFSBS file[s]. The class uses the TBFSBS Record class to represent each sequence in the file[s]. """ def __init__(self): """Initialize class TBFSBS. This function initialize the TBFSBS object with a list to store all sequence from the file[s]. """ super(TBFSBS, self).__init__() self._list = list() def __len__(self): return len(self._list) def __getitem__(self, i): return self._list[i] def __delitem__(self, i): del self._list[i] def __setitem__(self, i, value): self._list[i] = value def __str__(self): """Override representation of the class objects as a string. This function overrides the representation of the class objects as string with the list of TBFSBS records. """ records_str = "" for record in self._list: records_str += "{RECORD}\n".format(RECORD = record) return records_str def insert(self, i, value): self._list.insert(i, value) def append(self, value): self._list.append(value) def extend(self, value): self._list.extend(value) def parse(self, input_file): """Parse sequences from file. This function parses sequences from the file. It searches for the line that begins with the % character, which represents the header, and parses each part of the header structure (identifier, target value, and description) and sequence. Parameters ------------- input_file: str The input file name """ with open(input_file) as tbfsbs_file: header = "" for row in tbfsbs_file: if row.startswith("%"): if header: record = TBFSBS_Record(iD, target_value, description, seq) self.append(record) header = row.split() iD = header[1] try: target_value = float(header[2]) description = " ".join(header[3:]) except: target_value = None description = " ".join(header[2:]) seq = "" else: seq += row.rstrip() else: record = TBFSBS_Record(iD, target_value, description, seq) self.append(record) def write(self, output_file, wrap): """Write sequences to a file. This function writes all TBFSBS sequences parsed from the file[s] back into an output file with configurable maximum length of the sequence line. . Parameters ------------- output_file: str The output file name wrap: int Maximum length of the sequence line """ records_str = "" for record in self._list: value = "" if record.target_value: value = "{TARGET_VALUE} ".format( TARGET_VALUE = record.target_value) records_str += "% {ID} {TARGET_VALUE}"\ "{DESCRIPTION}\n{SEQUENCE}\n".format( ID = record.identifier, TARGET_VALUE = value, DESCRIPTION = record.description, SEQUENCE = textwrap.fill( record.sequence, wrap)) output_file.write(records_str[:-1]) def getArguments(): """Get arguments from terminal This function gets arguments from terminal via argparse Returns ------------- arguments: Namespace Namespace object with all arguments """ parser = argparse.ArgumentParser( description="Parse TBFSBS (Text-Based Format for" \ " Storing Biological Sequences) file[s].") parser.add_argument("input_files", nargs="+", type = str, help = "List of input file names or" \ " folder[s] with file[s]") parser.add_argument("-o", "--output", nargs = "?", type = argparse.FileType("w"), help = "Output file name.") parser.add_argument("-w", "--wrap", nargs = "?", const = float("inf"), type = int, default = float("inf"), help = "Maximum length of the sequence line.") return parser.parse_args() if __name__ == "__main__": args = getArguments() tbfsbs = TBFSBS() input_files = args.input_files for input_file in input_files: if os.path.isdir(input_file): files = list(Path(input_file).rglob("*")) input_files.extend(files) continue print("File: {FILE_NAME}\n".format( FILE_NAME = input_file)) file = TBFSBS() file.parse(input_file) print(file) tbfsbs.extend(file) if args.output: tbfsbs.write(args.output, args.wrap)
8604557faa012ff4806431d2aa2f72e1fd9f2b6a
BugliL/TDD_step_by_step
/Refactoring by Martin_Fowler/Theory/Encapsulate collection/example.py
934
3.609375
4
from dataclasses import dataclass, field from typing import List @dataclass class Course: __name: str __is_advanced: bool @property def name(self): return self.__name @property def is_advanced(self): return self.__is_advanced @dataclass class Person: __name: str __courses: List[Course] = field(default_factory=list) @property def name(self): return self.__name @property def courses(self): return self.__courses @courses.setter def courses(self, courses: List[Course]): self.__courses = courses def get_number_of_advanced_courses(person: Person): return len([c for c in person.courses if c.is_advanced]) if __name__ == '__main__': course1 = Course('Math', True) course2 = Course('English', False) x = Person("John Wick") x.courses = [course1, course2] n = get_number_of_advanced_courses(x) print(n)
a227045057ba43e38bee7f679c495a1a4e1f3521
KyleSMarshall/30-Day-LeetCoding-Challenge
/Day 16 - Valid Parenthesis String.py
2,598
4.21875
4
''' Given a string containing only three types of characters: '(', ')' and '*', write a function to check whether this string is valid. We define the validity of a string by these rules: Any left parenthesis '(' must have a corresponding right parenthesis ')'. Any right parenthesis ')' must have a corresponding left parenthesis '('. Left parenthesis '(' must go before the corresponding right parenthesis ')'. '*' could be treated as a single right parenthesis ')' or a single left parenthesis '(' or an empty string. An empty string is also valid. Ex: Input: "(*))" Output: True ''' # Solution: class Solution: def findMax(self, d, val, direction): res_max = None res_min = None for ind, value in enumerate(d): if value < val: res_max = ind else: res_min = ind break if direction == 'R': return res_max else: return res_min def checkValidString(self, s: str) -> bool: d = {'(': [], ')': [], '*': []} for ind, char in enumerate(list(s)): d[char].append(ind) while d['('] or d[')']: R, L, wild = None, None, None if d[')']: R = d[')'].pop(0) if d['(']: if R is not None: ind = self.findMax(d['('], R, 'R') if ind is not None: L = d['('].pop(ind) else: L = d['('].pop(0) if R is not None and L is not None: if R < L: d[')'].append(R) if d['*']: wild = d['*'].pop(0) if wild > R: return False else: return False elif R is not None and L is None: if d['*']: ind = self.findMax(d['*'], R, 'R') if ind is None: return False wild = d['*'].pop(ind) else: return False elif L is not None and R is None: if d['*']: ind = self.findMax(d['*'], L, 'L') if ind is None: return False wild = d['*'].pop(ind) else: return False return True
78d45ae88ae98b016853d7e7beee71605bc87e8e
mattsinbot/DataStructures-Algorithms
/Lesson1_PythonRefresher/Project0/Task2.py
1,343
3.875
4
""" Read file into texts and calls. It's ok if you don't understand how to read files """ import csv import operator max_duration = 0 phonedict = {} with open('calls.csv', 'r') as f: reader = csv.reader(f) calls = list(reader) for one_record in calls: if one_record[0] in phonedict: phonedict[one_record[0]] += int(one_record[3]) else: phonedict[one_record[0]] = int(one_record[3]) if one_record[1] in phonedict: phonedict[one_record[1]] += int(one_record[3]) else: phonedict[one_record[1]] = int(one_record[3]) # Find the key with maximum value max_time_phone = max(phonedict.iteritems(), key=operator.itemgetter(1))[0] print("%s spent the longest time, %2.4f seconds, on the phone during September 2016" % (max_time_phone, phonedict[max_time_phone])) """ TASK 2: Which telephone number spent the longest time on the phone during the period? Don't forget that time spent answering a call is also time spent on the phone. Print a message: "<telephone number> spent the longest time, <total time> seconds, on the phone during September 2016.". """ """ O(N) -> for reading the file O(N^2) -> O(N) computations for "for loop" * O(N) computations for fetching the keys from the dictionary Total = O(N) + O(N^2) ~ O(N^2) """
ecb3da4d78e19573868b0e1aedf8b03436ee256d
limwonki0619/Python-lecture
/Notebook/Unit17_while.py
1,525
3.921875
4
# Unit 17. while 반복문으로 Hello, world! 100번 출력하기 i = 0 while i < 100: print('hello, world', i) i += 1 # 17.1.1 초깃값을 1부터 시작하기 i = 1 while i <= 100: print(i) i += 1 # 17.1.2 초깃값을 감소시키기 i = 100 while i > 0: print(i) i -= 1 # 17.1.3 입력한 횟수대로 반복하기 count = int(input('반복할 횟수를 입력하세요: ')) i = 0 while i < count: print(i) i += 1 count = int(input('반복할 횟수를 입력하세요: ')) while count > 0: print(count) count -= 1 # 17.2 반복 횟수가 정해지지 않은 경우 --------------------------------------- import random as rd # random 모듈을 가져와 rd라는 이름으로 사용 rd.random() rd.randint(1, 6) # 1 ~ 6사이의 정수를 출력합니다. i = 0 while i != 3: # 3이 아닐 때 계속 반복한다. i = rd.randint(1, 6) # randint를 사용하요 1과 6사이의 난수 생성 (정수) print(i) # 참고 : random.choice 함수를 사용하면 시퀀스 객체에서 요소를 무작위로 선택할 수 있다. dice = [1, 2, 3, 4 ,5 ,6] rd.choice(dice) # random.choice 함수는 시퀀스 객체를 받으므로 리스트뿐만 아니라 튜플, range, 문자열 등을 넣어도 된다. # 17.3 while 반복문으로 무한 루프 만들기 ------------------------------------ while True: # while에 True를 지정하면 무한루프, True 대신 True로 취급하는 값을 사용해도 동작한다. print('hello world')
0499ac082aea8d76f3035f80af817d0bf6347496
fernandochimi/Intro_Python
/Exercícios/042_Tabuada_Inicio_Fim.py
219
3.828125
4
n = int(input("Tabuada de: ")) comeca_em = int(input("Começa em: ")) termina_em = int(input("Termina em: ")) while comeca_em <= termina_em: print("%d X %d = %d" % (n, comeca_em, (n*comeca_em))) comeca_em=comeca_em+1
1b5cab645fcfa693d065cc83f4bfa75c6777d619
sankumsek/assorted-python
/Regular Expressions HW.py
419
3.8125
4
#Regular Expressions HW #1 s = "3.1415, -2,71828, 4.0, 8.9, the value is 3.2, etc." import re def findfloats(s): return re.findall("-?[0-9]+[0.-9.]+",s) #2 prices = open("print.txt").read() def findPrices(prices): return re.findall("\$[0-9\.]+", prices) #3 def findCapitalizedWords(s): return re.findall("[A-Z]+[a-z]+",s) #4 def findSentences(s): return re.findall("[A-Z]+[A-Za-z\s\,\-]+[\.]",s)
6686a49cda6e0f5d9a494ba4be711b5658b7ea50
Erschwe/Python-Learning
/CelsiusConverter.py
226
4.03125
4
Celsius = int(input("Enter a temperature to be converted to Fahrenheit: ")) #Fahrenheit = 9.0/5.0 * Celsius + 32 #print ("Temperature:", Celsius, "Celsius =", Fahrenheit, " F") far = (Celsius * (9.0/5.0)) + 32 print (far)
d3015e3ad1beb585c61b85f32a25be5b34114946
smoulinos/Chapter-4-Even
/Squares.py
363
3.796875
4
import turtle wn=turtle.Screen() bob=turtle.Turtle() wn.bgcolor("lightgreen") bob.color("hotpink") def make_square (length): for i in range(4): bob.forward(length) bob.left(90) length=20 for j in range(5): bob.pensize(3) make_square(length) length=length+20 bob.penup() bob.goto(-10 + -10*j, -10+ -10*j) bob.pendown()
006e5a130f3f3789ff182f789c8b1056aab957a7
robinsharma1911/pythonfiles
/ada/binary.py
584
4.15625
4
#Binary Search program using recursive method... def binarysearch(arr, low, high, x): if high >= low: mid = (high + low) // 2 if arr[mid] == x: return mid elif arr[mid] > x: return binarysearch(arr, low, mid-1, x) else: return binarysearch(arr, mid+1, high, x) else: return -1 arr = [4 ,6, 8, 13, 26, 27, 32] print("array elements is:\n", arr) x = int(input("enter element to be search:")) result = binarysearch(arr, 0, len(arr)-1, x) if result != -1: print("element is present in array at index", result) else: print("element is not present in this array")
ad55a21c492832cd968e7b3fe8c9034c8dd3dfd2
GitKurmax/coursera-python
/week01/task21.py
658
3.671875
4
# Улитка ползет по вертикальному шесту высотой H метров, поднимаясь за день на A метров, а за ночь спускаясь на B метров. На какой день улитка доползет до вершины шеста? # Формат ввода # Программа получает на вход целые H, A, B. Гарантируется, что A > B ≥ 0. # Формат вывода # Программа должна вывести одно натуральное число. H, A, B = int(input()), int(input()), int(input()) print((H - A - 1)//(A - B) + 2)
0713a0e0aabb364a24d1dc588824915930871c77
bwisgood/leetcode
/Hash/group_words.py
706
3.578125
4
class Solution: def groupAnagrams(self, strs: list) -> list: def cal(str_): # list(str_).sort() c = list(str_) c.sort() return "".join(c) c = list(map(cal, strs)) d = {} for i in range(len(c)): if c[i] in d: d[c[i]].append(i) else: d[c[i]] = [i] base = [] for k, v in d.items(): temp = [] for index in v: temp.append(strs[index]) base.append(temp) return base if __name__ == '__main__': s = Solution() r = s.groupAnagrams(["eat", "tea", "tan", "ate", "nat", "bat"]) print(r)
8e3fd92ad88ed670b724cab7731eac7d01a2c488
jrahm/DuckTest
/writeup/examples/duck.py
467
3.578125
4
class Person: def walk(self): print("I walk") def talk(self): print("I talk") def think(self): print("I think") class Duck: def walk(self): print("Waddle") def talk(self): print("Quack!") def swim(self): print("I swim") def tryToSwim(duck): duck.swim() def doStuff(duck): duck.walk() duck.talk() tryToSwim(duck) duck = Duck() person = Person() doStuff(duck) doStuff(person)
00f6eac17cca0bf19f9f5471fbccd7a5aefbe6c9
Lslonik/python_algorithm
/HW_3/HW_3.6.py
1,389
4.0625
4
# В одномерном массиве найти сумму элементов, находящихся между минимальным и максимальным элементами. # Сами минимальный и максимальный элементы в сумму не включать import random SIZE = int(input('Введите размер массива: ')) MIN_ITEM = 0 MAX_ITEM = 100 array = [random.randint(MIN_ITEM, MAX_ITEM) for _ in range(SIZE)] print(f'Сгенерированный массив: {array}.') min_el, max_el = array[0], array[0] min_el_index, max_el_index = 0, 0 my_sum = 0 for el in array: if min_el > el: min_el = el min_el_index = array.index(el) if max_el < el: max_el = el max_el_index = array.index(el) print(f'Минимальный элемент: {min_el}\nМаксимальный элемент: {max_el}') if max_el_index - min_el_index < 0: for el in range(max_el_index+1, min_el_index): my_sum += array[el] print(f'Сумма чисел массива между максимальным и минимальным числами {my_sum}') else: for el in range(min_el_index+1, max_el_index): my_sum += array[el] print(f'Сумма чисел массива между минимальным и максимальным числами {my_sum}')
8ae43ae93dd1cfd569610948dd8d9d88855174c7
ChiaJung1031/WeekTwo
/two.py
404
4.03125
4
def avg(data): # 請用你的程式補完這個函式的區塊 count = data["count"] sum=0 averge=0 for i in range(3): salary = data["employees"][i]["salary"] sum += salary averge = sum / count print(averge) avg({ "count":3, "employees":[ { "name":"John", "salary":30000 }, { "name":"Bob", "salary":60000 }, { "name":"Jenny", "salary":50000 } ] }) # 呼叫 avg 函式
182fd95f2b9f3cff0c38bef5f040eed73aefa299
JSwidinsky/CompetitiveProgramming
/MAPS2020/J.py
476
3.640625
4
from fractions import Fraction as frac n = input() n = int(n) A = [] for i in range(n) : A.append(input()) curr = frac(0) p = 0 val = frac(4, 5) for x in A: x = int(x) curr += (x * val**p) p += 1 print("{0:.8f}".format(float(curr*frac(1,5)))) average = frac(0) for i in range(n) : p = 0 ans = frac(0) for j in range(n) : if j != i : ans += (int(A[j]) * val**p) p += 1 average += frac(1,5)*ans print ("{0:.8f}".format(float(average/n)))
a1ee9009295bb28fc1c7a5fa604f176782347e5d
marcosaraujo2020/ifpi-ads-algoritmos2020
/Lista_Prof_Fabio/Fabio01_Parte02/f1_q23_loja.py
702
3.984375
4
from time import sleep print('---'*13) print(' LOJA DA ALEGRIA ') print('---'*13) # ENTRADA valor_mercadoria = float(input('Informe o valor da compra: R$ ')) # PROCESSAMENTO valor_entrada = (valor_mercadoria // 3) + (valor_mercadoria % 3) valor_parcelas = valor_mercadoria // 3 # SAÍDA print('') print("Processando as informações.....") sleep(3) print('') print('---'*13) print(' RESUMO DA COMPRA ') print('---'*13) print('Valor total da compra: R$ {:.2f}'.format(valor_mercadoria)) print('Entrada: R$ {:.2f}'.format(valor_entrada)) print('Parcelas: 2 x de R$ {:.2f}'.format(valor_parcelas)) print('---'*13) print('Obrigado pela escolha, volte sempre!!!!') print('---'*13)
a6570d63ef2c6e4a144d2462367db690c75a85e5
Jor0Stam/HackBulgaria
/week03/Polynomials.py
2,524
3.515625
4
from Monomials import Monomial class Polynom: def __init__(self, poly): self.poly = poly self.poly_monomials = self.to_monomials(poly) self.first_derivativ = self.get_first_derivativ() def __str__(self): return "The derivative of f(x) = {domain} is :\nf'(x) = {equasion}".format( domain=self.poly, equasion=self.first_derivativ) def get_first_derivativ(self): first_derivativ = [] for mono in self.poly_monomials: if mono.is_constant: continue if mono.exponent != "": if mono.constant != "": mono.constant = str(int(mono.constant) * int(mono.exponent[1:])) mono.exponent = "^" + str(int(mono.exponent[1:]) - 1) if mono.exponent == "^1": mono.exponent = "" else: mono.variable = "" mono.constant = 1 * mono.get_constant() first_derivativ.append(mono) # return "+".join([el.__str__() for el in first_derivativ]) result = "+".join([el.__str__() for el in self.simplify_by_exponents(first_derivativ)]) if result == "": return 0 return result def simplify_by_exponents(self, equasion): simple_eq = {} for ind in range(self.greatest_exponent(equasion) + 1): simple_eq[ind] = self.get_by_exponent(equasion, ind) return list(simple_eq.values()) def get_by_exponent(self, equasion, exp): if exp == 0: result = Monomial("0") for el in equasion: if el.variable == "": result.add_to_const(str(int(el.get_constant()))) if result == 0: return "" return result elif exp == 1: result = Monomial("x") else: result = Monomial("x{exp}".format(exp="^" + str(exp))) for el in equasion: if el.get_exponent() == exp: result.add_to_const(int(el.get_constant())) return result def greatest_exponent(self, equasion): max = 0 for el in equasion: if max < el.get_exponent(): max = el.get_exponent() return max def to_monomials(self, equasion): to_mono = [] for el in equasion.split("+"): to_mono.append(Monomial(el)) return to_mono # p = Polynom("3x+4x^2") q = Polynom("3x^2+4x+3") print(q.__str__())
35e8fcdf41ecc2e9785ff2f63e3ca953966de5ee
KokoShterev/python
/201120/1120_3.py
131
3.578125
4
def my_f(a): count = 0 while a >= 2: a = a**0.5 count += 1 return count a = int(input()) print(my_f(a))
007daacd9d034c42d90c0c165d70cb2ed71bb6e1
lmontopo/Text-Adventure-Game
/MyGameClasses.py
7,549
4
4
from sys import exit from random import randint x = 0 y = 0 s = 0 # Here I define arrays of acceptable user inputs call_out = ["call", "calling", "yell"] walking = ["continue", "walking", "walk"] run = ["run", "running", "away"] ask = ["ask", "asking"] dig = ["dig", "digging", "hole"] would_not = ["wouldn't", "not", "don't"] possibilities = [call_out, walking, run, ask, dig, would_not] # This is an array for the jelly beans jelly = ['green', 'orange', 'red', 'black'] # Here are two global functions which are called in some classes: def get_direction(): global x global y direction = raw_input('> ').lower() if direction == "east": x += 1 elif direction == "west": x -= 1 elif direction == "north": y += 1 elif direction == "south": y -= 1 else: print "I don't recognize that." print "Please type in 'east', 'west', north', or 'south'." return get_direction() return x,y def get_action(): action = raw_input("> ").lower() action = action.split() for act in action: if act in possibilities[5]: print "Please don't tell me what you WOULDN'T do." print "Just tell me what you WOULD do." return get_action() if act in call_out: return "call" if act in walking: return "walk" if act in run: return "run" if act in ask: return "ask" if act in dig: return "dig" print "That was not an option. Lets assume you keep walking." return "walk" def call_or_walk(action): if action in call_out: print "After calling out 'hello! is anybody here?' you get a jiberish response." return insane_man.enter() elif (action in walking): return a_map.enter() else: print "Sorry, I don't recognize that as an option." print "Lets assume you continue walking." return a_map.enter() # Here are all the different "scenes" that one can encounter in the game: class Death(object): def enter(self): print "You Died." exit(1) class Death_Other(object): #here we have an array, which can be indexed. dicts can't be?!! ways_to_die = [ "You walked over a landmine and die. Game Over.", "You become dehydrated and die. Game Over.", "You die from a random heart attack. Game Over." ] def enter(self): print Death_Other.ways_to_die[randint(0, len(self.ways_to_die)-1)] exit(1) class Lost(object): def enter(self): print "You have been walking in a forest for a few hours." print "You realize now that you are completely lost and dont' know" print "how to get home. You are scared because it will soon be getting dark." print "You can call out for help or continue walking." print "What do you do?" action = get_action() return call_or_walk(action) class InsaneMan(object): def __init__(self): self.a = 0 def enter(self): self.a += 1 print self.a if self.a == 1: print "A man appears, walking towards you." print "His shirt is torn, his hair is ratty and he is saying nonsense words." else: print "You see the same insane man as before." print "Again, he is saying nonsense words." print "Do you run away or ask for help?" action = get_action() if (action in run): return a_map.enter() elif ((action not in ask) and (action not in run)): return a_map.enter() else: print "The man takes your hand in his and leads you through the forest..." return shovel.enter() class Shovel(object): def __init__(self): self.a = 0 def enter(self): global s s += 1 self.a += 1 if (s > 1 and self.a == 1): print "You find another shovel beside another half dug hole." print "It seems there are more than one around here." elif (s == 1 and self.a ==1): print "You find a shovel leaning against a tree." print "Beside it is a hole that is half dug." elif (s > 1 and self.a > 1): print "You are back at the same shovel and half dug hole as before." print "Do you start digging the hole, or do you continue walking in hopes" print "of finding your way home?" action = get_action() if action in dig: print "You find a bag of jelly beans in the hole. There are 4 of them." print "A green one, an orange one, a red one and a black one." print "Which kind of jelly bean do you eat?" action = raw_input('> ').lower() if action == jelly[3]: print "Nice! After eating the jelly bean a giant beanstock growns," print "right next to you!" return beanstalk.enter() else: print "uh oh! That one was poisonous!" return death.enter() else: return a_map.enter() class CellPhone(object): def enter(self): print "You find a cellphone on the ground." print "Do you pick it up and try to call home?" while True: decide = raw_input('> ').lower() if decide == "no": print "Would you like to continue walking or call for help?" action = get_action() return call_or_walk(action) elif decide == "yes": print "You pick it up and try to call home." print "It explodes in your ear!" return death.enter() else: print "Please just type 'yes' or 'no'." class Beanstalk(object): def enter(self): print "You climb to the top of the beanstalk." print "From there you have a great view!" print "You can see where the park ends, and you now know how to get home!" print "You now climb down and successfully find your way home." print "WELL DONE! YOU WIN!" exit(0) class Nothing(object): def enter(self): print "You walk around for a while, but you see nothing." print "You are getting very tired." print "Do you keep walking or call for help?" action = get_action() return call_or_walk(action) class Home(object): def enter(self): print "You arrive home safe and sound. You win!" exit(0) class Note(object): def __init__(self): self.a = 0 def enter(self): self.a += 1 if self.a < 2: print "You find a note that reads: 'black magic is good'." else: print "You are back at the same spot where you found the note." print "Would you like to keep walking or call for help?" action = get_action() if action in call_out: "After calling out 'hello! is anybody here?' you get a jiberish response." return insane_man.enter() elif (action in walking): return a_map.enter() insane_man = InsaneMan() shovel1 = Shovel() shovel2 = Shovel() shovel3 = Shovel() note = Note() class Map(object): places = { (0,0) : Lost(), (1,0): note, (2,0): Nothing(), (3,0): Death_Other(), (-1,0): Nothing(), (-2,0): Nothing(), (-3,0): Home(), (0, -1): CellPhone(), (0,-2): Nothing(), (0,-3): Death_Other(), (0,1): shovel2, (0,2): Nothing(), (1,1): shovel1, (1,2): Nothing(), (-1,1): shovel3, (-1,2): Nothing(), (-2,1): insane_man, (2,1): insane_man, (0,3): Nothing(), (-1,-1): Nothing(), (-2,-1): CellPhone(), (-1,-2): Nothing(), (1,-1): Nothing(), (2,-1): Nothing(), (1,-2): Nothing() } def next_scene(self): global x global y if abs(x)+ abs(y) < 4: next = a_map.places.get((x,y)) return next.enter() else: return Death_Other().enter() def enter(self): global x global y print "which direction would you like to go?" get_direction() return a_map.next_scene() # Here we create instances for all of the "scenes" cell_phone = CellPhone() beanstalk = Beanstalk() death = Death_Other() keep_walking = Nothing() lost = Lost() a_map = Map() home = Home() if __name__ == "__main__": lost.enter()
eb82b5ed24d525aac9abf0a8b2fad1eed8e6a3eb
Arthur-Lozano/data-structures-and-algorithms-1
/python/code_challenges/linked_list/linked_list.py
4,016
4.375
4
# Create a node class, which is essentially a sub-class on the LinkedList class. # Node class next is initialized with None # The last element/node in a linked list will always be None class Node: def __init__(self, value, next=None): self.value = value self.next = next # Create a Linked List(singly) class, which is bascially a wrapper that wraps over the node class # This function creates the head node # This is used as a placeholder node to point to first element in the list and doesn't actually contain any data # The user will not be able to access or interact with the head node # The head node isn't a data node and doesn't count as a node in the LL class LinkedList: def __init__(self, head=None): self.head = head def insert(self, value): # creating a new node in front of the Linked List new_node = Node(value) # node that comes next will become the head if self.head is not None: new_node.next = self.head # setting new node to head self.head = new_node # return self def includes(self, value): # define the head, which is the current variable current = self.head while current is not None: if current.value == value: return True current = current.next return False def __str__(self): string = "" current = self.head while current != None: string += f"{ {current.value} } -> " current = current.next string += f"NULL" return string def append_end(self, value): new_node = Node(value) current = self.head if current is None: current = new_node else: while current.next is not None: current = current.next current.next = new_node def insert_before(self, value, new_value): new_node = Node(new_value) current = self.head if current is None: current = new_node while current.next is not None: if current.next == value: current.next = new_node else: current = current.next def insert_after(self, value, new_value): new_node = Node(new_value) current = self.head if current is None: current = new_node while current.next is not None: if current.next == value: current.next = new_node else: current = current.next def kth_from_end(self, k): length = -1 temp = self.head while temp is not None: temp = temp.next length += 1 if length < 2: return "List only has 1 item" elif k < 0: return "Please choose a positive number" elif k >= length: return "The linked list is not that long. Please choose a smaller number" else: temp = self.head target = length - k for i in range(0, target): temp = temp.next return temp.value def middle_node(self): length = -1 temp = self.head while temp is not None: temp = temp.next length += 1 if length < 2: return "List only has 1 item" else: temp = self.head target = int(length/2) for i in range(0, target): temp = temp.next return temp.value def zip_list(list1, list2): list1_current = list1.head list2_current = list2.head while list1_current != None and list2_current != None: #Save next pointers list1_next = list1_current.next list2_next = list2_current.next list2_current.next = list1_next list1_current.next = list2_current list1_current = list1_next list2_current = list2_next list2.head = list2_current
663ad60d4d50dfce36b2339e2c3e0bbdeb1d3ba9
Daniellau331/Sudoku
/GUI.py
7,034
3.609375
4
# GUI.py # There are two classes in this program # Grid and Cube # Grid holds 9 Cubes import pygame from solver import checker, solver, print_board pygame.font.init() class Grid: board = [ [7, 8, 0, 4, 0, 0, 1, 2, 0], [6, 0, 0, 0, 7, 5, 0, 0, 9], [0, 0, 0, 6, 0, 1, 0, 7, 8], [0, 0, 7, 0, 4, 0, 2, 6, 0], [0, 0, 1, 0, 5, 0, 9, 3, 0], [9, 0, 4, 0, 6, 0, 0, 0, 5], [0, 7, 0, 3, 0, 0, 0, 1, 2], [1, 2, 0, 0, 0, 7, 4, 0, 0], [0, 4, 9, 2, 0, 6, 0, 0, 7] ] def __init__(self, rows, cols, width, height): self.rows = rows self.cols = cols self.width = width self.height = height self.selected = None self.model = None self.cubes = [[Cube(self.board[i][j], i, j, width, height) for j in range(cols)] for i in range(rows)] self.model = None def update_model(self): self.model = [[self.cubes[i][j].value for j in range(self.cols)] for i in range(self.rows)] def sketch(self, value): row, col = self.selected self.cubes[row][col].set_temp(value) def draw(self, screen): # draw 9 grids to hold the cubes thick, thin = 4, 3 unit = self.width / 9 # draw lines for i in range(self.rows + 1): if i % 3 == 0 and i != 0: # draw thick lines pygame.draw.line(screen, (0, 0, 0), (0, i * unit), (self.width, i * unit), thick) pygame.draw.line(screen, (0, 0, 0), (i * unit, 0), (i * unit, self.height), thick) else: # draw thin lines pygame.draw.line(screen, (0, 0, 0), (0, i * unit), (self.width, i * unit), thin) pygame.draw.line(screen, (0, 0, 0), (i * unit, 0), (i * unit, self.height), thin) # draw cubes for i in range(self.rows): for j in range(self.cols): self.cubes[i][j].draw(screen) # clear selected box def clear(self): row, col = self.selected if self.cubes[row][col].value == 0: self.cubes[row][col].set_temp(0) def put(self, val): row, col = self.selected if self.cubes[row][col].value == 0: self.cubes[row][col].set_value(val) self.update_model() if solver(self.model) and checker(self.model, val, row, col): return True else: self.cubes[row][col].set_value(0) self.cubes[row][col].set_temp(0) self.update_model() return False def is_finished(self): for i in range(self.rows): for j in range(self.cols): if self.cubes[i][j].value == 0: return False return True def click(self, position): if position[0] < self.width and position[1] < self.height: gap = self.width / 9 x = position[0] // gap y = position[1] // gap return (int(x), int(y)) else: return None def sketch(self, key): row, col = self.selected self.cubes[row][col].set_temp(key) def select(self, col, row): # reset all cubes for i in range(self.rows): for j in range(self.cols): self.cubes[i][j].selected = False self.cubes[row][col].selected = True self.selected = (row, col) def solve(self): solver(self.board) print_board(self.board) self.cubes = [[Cube(self.board[i][j], i, j, self.width, self.height) for j in range(self.cols)] for i in range(self.rows)] class Cube: rows = 9 cols = 9 def __init__(self, value, row, col, width, height): self.value = value self.row = row self.col = col self.width = width self.height = height self.selected = False self.temp = 0 def draw(self, screen): font = pygame.font.SysFont("comicsans", 50) gap = self.width / 9 x = self.col * gap y = self.row * gap if self.temp != 0 and self.value == 0: text = font.render(str(self.temp), 1, (128, 128, 128)) screen.blit(text, (x + 5, y + 5)) elif not (self.value == 0): text = font.render(str(self.value), 1, (0, 0, 0)) screen.blit(text, (x + (gap / 2 - text.get_width() / 2), y + (gap / 2 - text.get_height() / 2))) if self.selected: pygame.draw.rect(screen, (255, 0, 0), (x, y, gap, gap), 3) def set_value(self, value): self.value = value def set_temp(self, temp): self.temp = temp def redraw(screen, board): # background color screen.fill((255, 255, 255)) board.draw(screen) def main(): screen = pygame.display.set_mode((540, 600)) pygame.display.set_caption("Sudoku") board = Grid(9, 9, 540, 540) run = True while run: for event in pygame.event.get(): if event.type == pygame.QUIT: run = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_1: key = 1 if event.key == pygame.K_2: key = 2 if event.key == pygame.K_3: key = 3 if event.key == pygame.K_4: key = 4 if event.key == pygame.K_5: key = 5 if event.key == pygame.K_6: key = 6 if event.key == pygame.K_7: key = 7 if event.key == pygame.K_8: key = 8 if event.key == pygame.K_9: key = 9 if event.key == pygame.K_DELETE: board.clear() key = None if event.key == pygame.K_RETURN: i, j = board.selected if board.cubes[i][j].temp != 0: # if temp value is correct if board.put(board.cubes[i][j].temp): print("Correct") else: print("Wrong") key = None if board.is_finished(): print("Game Over") run = False if event.key == pygame.K_SPACE: board.solve() print("space") if event.type == pygame.MOUSEBUTTONDOWN: position = pygame.mouse.get_pos() print(position) clicked = board.click(position) print(clicked) if clicked: board.select(clicked[0], clicked[1]) key = None if board.selected and key is not None: board.sketch(key) redraw(screen, board) pygame.display.update() main() pygame.quit()
f17fcc440548ac9f545e475306fcc34c6a77e521
anishLearnsToCode/python-workshop-8
/day_2/inbuilt_functions.py
364
3.5625
4
def abs(x: str) -> float: return x if x > 0 else -x # print(abs(10)) # print(abs(-10)) x = set() # print(type(x)) x.add(10) x.add(10) x.add(10) # print(x) # print(len(x)) # print([ord(character) for character in input()]) # print(x.__repr__()) # var = map(int, input().split()) # print(var) n = int(input()) print(sum(x ** 2 for x in range(1, n + 1)))
6c756e2b22c29a295a112a5f2712deb810b04050
shrutijain0/python-small-projects
/GuessTheWord.py
1,924
4.1875
4
import random #FOR WELCOME SCREEN def welcome(): print("**********WELCOME TO GUESSING GAME**********") print("________________GAME DESCRIPTION_____________") print("YOU WILL BE GIVEN A CHANCE TO GUESS A NUMBER AND IF YOUR NUMBER IS SAME AS THE NUMBER SLELCTED BY COMPUTER THEN YOU WIN OR ELSE YOU LOOSE") print("SO WHAT ARE WE WAITING FOR LETS GET STARTED") #FOR SINGLE/TWO PLAYERS def choose(): x=input("THERE IS TWO OPTION 1.SINGLE PLAYER TYPE 'S' 2.TWO PLAYER TYPE 'D'") return x #for single player def single(): score=0 r=int(input("enter the last value of range:")) guess=int(input("GUESS THE NUMBER:")) num=random.randint(1,r) if guess==num: print("YOU GUESSED IT RIGHT!!!!") score=+1 print("score:",score) else: print("YOU GUESSED IT WRONG :(") print("THE NUMBER WAS:",num) print("TRY AGAIN NEXT TIME") #for two player def double(): p1=input("ENTER THE NAME OF PLAYER1:") p2=input("ENTER THE NAME OF PLAYER2") dr=int(input("ENTER THE LAST NUMBER OF RANGE")) dguess1=int(input("ENTER THE GUESS NUMBER PLAYER1:")) dguess2=int(input("ENTER THE GUESS NUMBER PLAYER2:")) dnum=random.randint(1,dr) if dguess1==dguess2==dnum: print("!!!!YOU BOTH WON!!!!!") elif dguess1==dnum: print("!!PLAYER 1 WON!!!!") elif dguess2==dnum: print("!!!PLAYER 2 WON!!!!") else: print("YOU BOTH LOOSE :(") print("the number was:",dnum) #CALLING THE FUNCTION #FIRST WELCOME SCREEN welcome() #WETHER SHINGLE OT TWO PLAYER play=choose() #S FOR SINGLE ELSE TWO PLAYERS if play=="S": single() else: double() #IF THEY WANNA PLAY AGIN THEN REPEAT THE PROCESS OR THANK YOU STATEMENT jn=input("WANNA PLAY THE GAME AGAIN Y/N") if jn=="Y": if play=="S": single() else: double() else: print("~~~~~~~~~~~THANK YOU FOR PLAYING~~~~~~~~~~~~")
f6717e29d46f0e277be4099dae42447aaf1561c8
coltonneil/IT-FDN-100
/Assignment 6/hw6.py
3,868
4.28125
4
#!/usr/bin/env python3 import math """ python 3 this script calculates and splits the cost of a pizza order based on the number of slices, it will read names and slice amount from a file named "order.txt" that is stored in its local directory, if that file is not found it will calculate based off of a default order """ # establish static variables cost = 10.00 slices_per_pizza = 8 tax_rate = 9.6 tip_rate = 15 delivery_fee = 3.99 # main function where other functions are called and final results are printed def main(): order_dict = get_order_dict() num_pizzas, left_over_slices = number_pizzas(order_dict) total_cost, tip_total = total(num_pizzas) tip_by_slice, tip_by_person = get_tip_data(tip_total, order_dict) cost_per = round(total_cost / len(order_dict), 2) print("You need {} pizzas, there will be {} left over slices".format(num_pizzas, left_over_slices)) print("The total cost is: ${:.2f}".format(total_cost)) print("The average cost per person is: ${:.2f}".format(cost_per)) print("The tip per slice is: ${:.2f}".format(tip_by_slice)) print("The tip per person, based on their number of slices is as follows:") for name, tip in tip_by_person.items(): print("{} - ${:.2f}".format(name, tip)) # get dict with customer names and slice amounts either from txt file or from dict literal if txt file is missing def get_order_dict(): order_data = {} try: with open("order.txt", 'r') as order_file: for line in order_file: line = line.strip('\n').split(", ") order_data[line[0]] = int(line[1]) except IOError: # use default data if file does not exist order_data = {"Dave": 2, "Jessica": 3, "Tom": 4, "Susan": 3, "Bill": 2, "Emily": 4, "Kaycee": 6, "John": 1} return order_data # take dict containing order information and return the number of pizzas and left over slices def number_pizzas(order_data): num_slices = sum(order_data.values()) num_pizzas = math.ceil(num_slices / slices_per_pizza) slice_remainder = num_slices % slices_per_pizza if slice_remainder > 0: left_over_slices = 8 - (num_slices % slices_per_pizza) else: left_over_slices = 0 return num_pizzas, left_over_slices # take in the number of pizzas need and return the cost of the order (which includes the tip) and the tip amount def total(num_pizzas): pizza_amount = num_pizzas * cost tax_amount = pizza_amount * (tax_rate / 100) tip_amount = (pizza_amount + tax_amount) * (tip_rate / 100) order_cost = pizza_amount + tax_amount + tip_amount + delivery_fee return order_cost, tip_amount # take in the tip amount and the dict storing the order info return a dict key,value = name, tip based on slices def get_tip_data(tip, order): tip_per_slice = round(tip / sum(order.values()), 2) tip_dict = {} for name, slices in order.items(): tip_dict[name] = slices * tip_per_slice return tip_per_slice, tip_dict # takes in a prompt which should state what the user is entering, for instance prompt="Enter the number of slices", # returns the validated number, this is not used in the txt based version of this script def get_number(prompt, minimum=1, allow_float=False): while True: temp_num = input(prompt) if allow_float: try: temp_num = float(temp_num) except ValueError: print("Please input a valid number") continue else: try: temp_num = int(float(temp_num)) except ValueError: print("Please input a valid number") continue if temp_num < minimum: print("The number must be greater than {}".format(minimum)) continue break return temp_num main()
f46d95f5c4f3db62c19dd1851db97f47c3ea678e
beautytiger/project-euler
/problem-012.py
1,300
3.5625
4
#!/usr/bin/python # -*- coding: utf-8 -*- from tools.runningTime import runTime def fn(number): stop = int(pow(number, 0.5)) # always including 1 and the number itself # but if number=1, return 1 count = 1 for i in xrange(2, stop+1): if number%i == 0: count += 1 return count*2 - (1 if stop**2 == number else 0) @runTime def brute_force_method(limit=500): s , natural= 1, 1 while fn(s) <= limit: natural += 1 s += natural print "Result: {}".format(s) cache = {} # memory version of above fn(). def factors(number): global cache if number in cache: return cache[number] stop = int(pow(number, 0.5)) # always including 1 and the number itself # but if number=1, return 1 count = 1 for i in xrange(2, stop+1): if number%i == 0: count += 1 result = count*2 - (1 if stop**2 == number else 0) cache[number] = result return result @runTime def light_use_formula(limit=500): fn, n = 0, 0 while fn<limit: tri = n*(n+1)/2 fn = factors((n+1)/2)*factors(n) if n%2 else\ factors(n/2)*factors(n+1) n += 1 print "Result: {}".format(tri) if __name__ == "__main__": brute_force_method() light_use_formula()
ec4bc256618a6d450180a8e832dd791ef1da8a06
Wizdave97/Algorithms-and-Data-Structures
/linked_lists/even_after_odd.py
1,873
4.21875
4
class Node: def __init__(self, value): self.value = value self.next = None def __repr__(self): return str(self.value) class LinkedList: def __init__(self, head=None): self.head = head def append(self, value): if self.head is None: self.head = Node(value) return node = self.head while node.next is not None: node = node.next node.next = Node(value) def __iter__(self): current=self.head while current: yield current.value current=current.next def even_after_odd(l_list): """ This function takes a linkedlist of integer values and rearranges it such that all even numbers come after all odd numbers in the same relative order of the original list Args: arg1: linked list with integer node values """ current=l_list.head if current is None: return while current.next: if (current.value%2==0) and (current.next.value%2!=0): current_value=current.value next_value=current.next.value current.value=next_value current.next.value=current_value current=l_list.head current=current.next return l_list """ Time complexity for even_after_odd algorithm the loop resets back to the head after every rearrangement so the in the worst case scenario there exists an even interger after every odd integer If k is a constant that depends on the degree of sorting the number of odd numbers in the list f(n)=kn O(f(n))=>O(n) """ arr = [1, 2, 3, 4, 5, 6,9,8,11,12,14,16,17] solution = [1, 3, 5,9,11,17, 2, 4, 6,8,12,14,16] l_list=LinkedList() for i in arr: l_list.append(i) print(list(l_list)) even_after_odd(l_list) print(list(l_list)) print('Pass' if list(l_list)==solution else "Fail")
5d9bbc0b6535cfb1635ecf275817d5fddb3264d2
ccampion/predicting-crime
/references/analysis-notes/multi-class-auc-roc-functions.py
10,352
3.796875
4
################################################################## # DEFINE FUNCTIONS FOR CALCULATING ROC AND AUC AND PLOTTING CURVES ################################################################## # MULTI-CLASS AUC REQUIRES scikit-learn v0.22 # required imports import numpy as np import geopandas as gpd import matplotlib.pyplot as plt from sklearn.metrics import roc_curve, auc, roc_auc_score def generate_roc_auc(y_values_actual, predicted_probabilities, class_dict): """ Creates a dictionary of ROC curve values generated using sklearn.metrics.roc_curve for every outcome class in a multi-class problem NOTE: multi-class AUC requires scikit-learn>=v0.22 y_values_actual: np.array, the 1-dimensional array containing the multi-classs true y values against which you are evaluating the predicted probabilities (i.e. y_test) predicted_probabilities: np.array, the 2-dimensional array generated using sklearn's "model.predict_proba()" method (i.e. test set predicted probabilities) returns: tuple(float, float, dict), (1) a float representing the average macro AUC for all classes, (2) a float representing the average weighted AUC (weighted by the number of true samples for each class to account for class imbalance) and (3) a dictionary of dictionaries, where each top level key represents a different y class, and the value for each y class key is a dictionary containing the corresponding frp, tpr, threshold, and individual class AUC values for that particular y class outcome. Example output format shown below: ( auc_average, auc_weighted_average, output_dict = { 0: { 'frp': np.array of shape (n,) 'tpr': np.array of shape (n,) 'threshold': np.array of shape (n,) 'auc': float of micro auc for individual class 'name': str name of class } 1: { 'frp': ... ... } ... } ) """ # create sorted list of all class labels class_labels = sorted(list(set(y_values_actual))) # convert y_values to binary indicators for each class and store as 2D # array of dimensions (n_classes, n_y_values), with each row containing one # set of class indicators y_class_array = np.vstack( [ (y_values_actual==class_val).astype(int) for class_val in class_labels ] ) # create roc curve dictionary roc_curve_dict = { crime_class: { key: value for key, value in zip( ['fpr', 'tpr', 'thresholds'], roc_curve(y_class, predicted_probs_class) ) } for (crime_class, predicted_probs_class), y_class in zip( enumerate(predicted_probabilities.T), y_class_array ) } # add individual class auc's and class names to dictionary for crime_class in class_labels: roc_curve_dict[crime_class]['auc'] = roc_auc_score( y_class_array[crime_class], predicted_probabilities[:,crime_class] ) roc_curve_dict[crime_class]['name'] = class_dict[crime_class] # generate overall average auc's for all classes, weighted and unweighted auc_avg = roc_auc_score( y_values_actual, predicted_probabilities, multi_class='ovr', average='macro' ) auc_weighted_avg = roc_auc_score( y_values_actual, predicted_probabilities, multi_class='ovr', average='weighted' ) return auc_avg, auc_weighted_avg, roc_curve_dict def plot_roc_all_classes(overall_auc, overall_auc_weighted, roc_curve_dict, title='ROC plotted for all crime type TEST classes', savepath=None): """ Generates a plot of ROC curves for all responses classes overall_auc: float, an overall average auc generated using the 'generate_roc_auc' function overall_auc_weighted: float, an overall weighted auc generated using the 'generate_roc_auc' function roc_curve_dict: dict, an roc_curve dict generated using the 'generate_roc_auc' function title: str, specifies the title used for the plot savepath: None or str, if none, .png file is NOT saved, otherwise, input the "filepath.png" string, indicating where you would like the image saved returns: A plotted image and saved .png file (if savepath is not None) """ fig, ax = plt.subplots(figsize=(12, 7)) plt.title( ''.join( [title, '\n(overall AUC, avg.: {:.3f}; weighted avg.: {:.3})'.format( overall_auc, overall_auc_weighted ) ] ), fontsize=20, ) rate_values=np.arange(0,100)/100 ax.plot(rate_values, rate_values, ':', color='k', linewidth=2, alpha=1) for key in roc_curve_dict.keys(): plt.plot( roc_curve_dict[key]['fpr'], roc_curve_dict[key]['tpr'], label='{} : {:.3f}'.format( key, roc_curve_dict[key]['auc'] ) ) plt.legend( fontsize=14, title='class : AUC', title_fontsize=14, edgecolor='k', framealpha=1, loc=4 ) ax.tick_params(labelsize=16) ax.set_ylabel("TRUE positive rate", fontsize=18) ax.set_xlabel("FALSE positive rate", fontsize=18) ax.grid(':', alpha=0.4) plt.tight_layout() if savepath: plt.savefig(savepath) plt.show(); def plot_roc_all_classes_individual(overall_auc, overall_auc_weighted, roc_curve_dict, title='ROC plotted by crime type TEST class', savepath=None, subplots=(5,2), fig_height=15, suptitle_spacing=0.91): """ Generates a set of subplot of ROC curves for all responses classes, each plotted individually overall_auc: float, an overall average auc generated using the 'generate_roc_auc' function overall_auc_weighted: float, an overall weighted auc generated using the 'generate_roc_auc' function roc_curve_dict: dict, an roc_curve dict generated using the 'generate_roc_auc' function title: str, specifies the title used for the plot savepath: None or str, if none, .png file is NOT saved, otherwise, input the "filepath.png" string, indicating where you would like the image saved subplots: tuple, default=(5,2) to plot each of the 9 crime classes, provides the dimension of subplots for the figure (NOTE: currently this function is only configured to plot 2 columns of subplots, therefore no other value other than two is accepted for the subplots width dimension) fig_height: int or float, default=15, this value is passed directly to the 'figsize' parameter of plt.subplots() and determines the overall height of your plot suptitle_spacing: float between 0 and 1, default=0.91, this value is passed to the 'rect' parameter for plt.tight_layout() to specify the proportion of the overall plot space to reserve for the plt.suptitle() text. If you change the fig_height parameter from the default, you may find that you need to adjust suptitle_spacing to adjust the position of your suptitle. The larger your fig_height value, the larger suptitle_spacing you will need and vice versa. returns: A plotted image and saved .png file (if savepath is not None) """ if type(subplots)!=tuple: raise TypeError("'subplots' parameter must be entered as a tuple, e.g. subplots=(3,2)") if subplots[1]!=2: raise ValueError( "'subplots' parameter columns dimension must be value=2, e.g. subplots=(5,2). "\ "This function is not configured to handle more or less than 2 subplots." ) fig, axes = plt.subplots(*subplots, figsize=(12, fig_height)) plt.suptitle( ''.join( [title, '\n(overall AUC, avg.: {:.3f}; weighted avg.: {:.3})'.format( overall_auc, overall_auc_weighted ) ] ), fontsize=20, ) rate_values=np.arange(0,100)/100 for (i, ax), (j, key) in zip(enumerate(axes.flat), enumerate(roc_curve_dict.keys())): ax.set_title('class {}: {}'.format(key, roc_curve_dict[key]['name']), fontsize=16) ax.plot(rate_values, rate_values, ':', color='k', linewidth=2, alpha=.3) ax.plot( roc_curve_dict[key]['fpr'], roc_curve_dict[key]['tpr'], label='{} ({:.4f})'.format( key, roc_curve_dict[key]['auc'] ), color='k' ) ax.text(0.7, 0.1, 'AUC = {:.3f}'.format(roc_curve_dict[key]['auc']), fontsize=14) ax.tick_params(labelsize=14) ax.set_ylabel("TRUE positive rate", fontsize=14) ax.set_xlabel("FALSE positive rate", fontsize=14) ax.grid(':', alpha=0.4) # hide all markings for axes if there is no corresponding subplot if i < np.product(subplots)-1: for pos in ['right','top','bottom','left']: axes[subplots[0]-1, 1].spines[pos].set_visible(False) axes[subplots[0]-1, 1].tick_params( axis='x', which='both', bottom=False, top=False, labelbottom=False ) axes[subplots[0]-1, 1].tick_params( axis='y', which='both', right=False, left=False, labelleft=False ) plt.tight_layout(rect=[0, 0.03, 1, suptitle_spacing]) if savepath: plt.savefig(savepath) plt.show();
a5dc998f2fce218c3f7f85cc211d1a9fffdb4b49
harshildp/python_oct_2017
/eric.jones/Mathdojo/mathdojo.py
822
3.796875
4
class MathDojo(object): def __init__(self): self.result = 0 def add(self, arg1, *arg2): self.result += arg1 for idx in list(self.recursetree(arg2, (list, tuple))): self.result += idx return self def subtract(self, arg1, *arg2): self.result -= arg1 for idx in list(self.recursetree(arg2, (list, tuple))): self.result -= idx return self def recursetree(self, tuplemix, datatypes): if isinstance(tuplemix, datatypes): for value in tuplemix: for subvalue in self.recursetree(value, datatypes): yield int(subvalue) else: yield int(tuplemix) md = MathDojo() print md.add(5, (6,7), [1, 4, 9, (3, [5, 7, (11, 18)])]).subtract(8, [-1, -4, (3, 5)]).result
6872f5a7e94b5921960b6113c630c852beabdd6a
TahuraShaikh/Python_Scripts
/convert_temperture.py
129
3.71875
4
# convert celcius to farhenheit: def farh(cel): return(cel*(9/5))+32 c=37 f=farh(c) print(f"farhenheit temperature is : {f}")
dbeaae64e885db91481d94faa67b26e93c8b1ca0
guilhermemaas/guanabara-pythonworlds
/exercicios/ex091.py
983
3.609375
4
""" Crie um programa onde 4 jogadores joguem um dado e tenham resultados aleatorios. Guarde esses resultados em um dicionario. No final, coloque esse dicionario em ordem, sabendo que o vencedor tirou o maior numero no dado. """ from random import randint from time import sleep import operator rpg_rodada = [] jogador = {} for indice in range(0, 4): print(f'Jogando dados do jogar {indice + 1}') jogador['jogador'] = indice + 1 jogador['dado'] = randint(1, 6) rpg_rodada.append(jogador.copy()) print('...') sleep(0.5) print('\n' + '=' * 30) print('RESULTADO') print('=' * 30 + '\n') print(f'Dados da partida: {rpg_rodada}') rpg_rodada.sort(key=operator.itemgetter('dado'), reverse=True) #guanabara #joga numa lista e ordena. #ranking = sorted(rpg_rodada.items(), key=itemgetter(1), reverse=True) #print(ranking) #faz for pra exibir os itens da lista print('\n') for jogador in rpg_rodada: print(f'Jogador {jogador["jogador"]} - {jogador["dado"]}')
c513416dc1b7a5f1c9c0ef5819aba2e8d6d21521
andrei541/PEP21G01
/communicator/modul6_1.py
1,312
3.59375
4
# # #classes # # # # class Object: # # variable="this is my text" # # def print_var(self): # # print(self.variable) # # def change_var(self): # # self.variable="this is another text" # # # # Object1=Object() # # Object1.print_var() # # Object1.change_var() # # print("class variable:",Object.variable) # # print("instance variable:",Object1.variable) # # import random # # class Object2: # # variable=[1,2,3] # # def change_var(self): # # self.variable.append(random.randint(1,100)) # # # # Object2=Object2() # # print("class variable:",Object2.variable) # # print("instance variable:",Object2.variable) # # Object2.change_var() # # print("-----------------") # # print("class variable:",Object2.variable) # # print("instance variable:",Object2.variable) # # Object3=Object2 # # print(Object3.variable) # # # class Cars: # # counter=[0] # # def __init__(self): # # self.counter.insert(0,self.counter.pop(0)+1) # # # # car1=Cars() # # car2=Cars() # # car3=Cars() # # car4=Cars() # # print(car1.counter) # #host si port # # class Conector: # def __init__(self,host,port): # self.port=port # self.host=host # # class Client(Conector): # pass # # # # class Server(Conector): # pass # # # conector_obj=Conector("localhost",8080)
e0a7ead3b4702d848914fd1052390f0cff4564f5
CagiriciOzlem/GlobalAIHubMachineLearningCourse
/Homeworks/HW_2.py
5,098
3.984375
4
# -*- coding: utf-8 -*- """ Course Date: 22.03.2021 Name: Özlem Surname: Çağırıcı Email: ozlemilgun@gmail.com """ **************************HOMEWORK - 2 ************************* # Import boston dataset and convert it into pandas dataframe from sklearn.datasets import load_boston import pandas as pd X , Y = load_boston(return_X_y=True) print(X.head()) print(Y.head()) df = pd.DataFrame(X,columns = load_boston().feature_names) print(df.head()) # Check duplicate values and missing data df.info() df.duplicated().sum() df.isna().sum() """No dublicated value/no missing value""" # Visualize data for each feature (pairplot,distplot) df.describe() df.columns import seaborn as sns sns.pairplot(df) # Draw correlation matrix import seaborn as sns import matplotlib.pyplot as plt corr = df.corr() plt.figure(figsize=(10, 10)) ax = sns.heatmap( corr, vmin=-1, vmax=1, center=0, cmap=sns.diverging_palette(20, 220, n=200), square=True, annot = True ) sns.set(font_scale=0.5) ax.set_xticklabels( ax.get_xticklabels(), rotation=45, horizontalalignment='right',size=8 ) ax.set_yticklabels( ax.get_yticklabels(), rotation=0, size=8 ) ax.set_ylim(len(corr)+0.5, -0.5) # Drop correlated features (check correlation matrix) """There is a high negative correlation between the DIS & Nox There is a high negative correlation between the DIS & Age """ df.drop("DIS",axis=1,inplace=True) df.drop("INDUS",axis=1,inplace=True) df.columns # Handle outliers (you can use IsolationForest) # Outlier detection with Z-Score from scipy import stats import numpy as np z = np.abs(stats.zscore(df)) z outliers = list(set(np.where(z > 3)[0])) new_df = df.drop(outliers,axis = 0).reset_index(drop = False) display(new_df) Y_new = Y[list(new_df["index"])] len(Y_new) # Normalize data X_new = new_df.drop('index', axis = 1) X_new.shape Y_new.shape from sklearn.preprocessing import StandardScaler, MinMaxScaler X_scaled = StandardScaler().fit_transform(X_new) # Split dataset into train and test set from sklearn.model_selection import train_test_split X_train, X_test, Y_train, Y_test = train_test_split(X_scaled,Y_new, test_size=0.3, random_state=42) X_train.shape Y_train.shape X_test.shape Y_test.shape # Import ridge and lasso models from sklearn import numpy as np from sklearn.linear_model import LinearRegression from sklearn.linear_model import Ridge,Lasso from sklearn.linear_model import RidgeCV,LassoCV from sklearn.metrics import mean_squared_error # Define 5 different alpha values for lasso and fit them. Print their R^2 sore on both # train and test. ridge_obj = Ridge() alpha_Val = np.random.randint(1,200,5) for i in alpha_Val: ridge_obj.set_params(alpha=i) Ridge_Model = ridge_obj.fit(X_train,Y_train) Y_pred = Ridge_Model.predict(X_test) RMSE = np.sqrt(mean_squared_error(Y_test, Y_pred)) print("for alpha = "+ str(i) + " : "+ str(format(RMSE,".2f"))) """ for alpha = 159 : 4.52 for alpha = 74 : 4.37 for alpha = 167 : 4.54 for alpha = 64 : 4.35 for alpha = 42 : 4.32 """ ls_obj = Lasso() alpha_Val = np.random.randint(0,20,5) for i in alpha_Val: ls_obj.set_params(alpha=i) Lasso_Model = ls_obj.fit(X_train,Y_train) Y_pred = Lasso_Model.predict(X_test) RMSE = np.sqrt(mean_squared_error(Y_test, Y_pred)) print("for alpha = "+ str(i) + " : "+ str(format(RMSE,".2f"))) """ for alpha = 6 : 7.07 for alpha = 5 : 6.41 for alpha = 13 : 7.38 for alpha = 7 : 7.38 for alpha = 7 : 7.38 """ # Make comment about results. Print best models coefficient. """ - Best alpha value is :42 for alpha = 159 : 4.52 for alpha = 74 : 4.37 for alpha = 167 : 4.54 for alpha = 64 : 4.35 for alpha = 42 : 4.32 """ #RIDGE MODEL : ridge_obj_tunned = Ridge(alpha=42) Ridge_Model = ridge_obj.fit(X_train,Y_train) Y_pred_train=Ridge_Model.predict(X_train) RMSE_train = np.sqrt(mean_squared_error(Y_train, Y_pred_train)) Y_pred_test=Ridge_Model.predict(X_test) RMSE_test = np.sqrt(mean_squared_error(Y_test, Y_pred_test)) print(RMSE_train) print(RMSE_test) """ 4.3221870898383505 4.321378925425808 """ #LASSO MODEL : """ - Best alpha value is :5 for alpha = 6 : 7.07 for alpha = 5 : 6.41 for alpha = 13 : 7.38 for alpha = 7 : 7.38 for alpha = 7 : 7.38 """ ls_obj_tunned = Lasso(alpha=5) Lasso_Model = ridge_obj.fit(X_train,Y_train) Y_pred_train=Lasso_Model.predict(X_train) RMSE_train = np.sqrt(mean_squared_error(Y_train, Y_pred_train)) Y_pred_test=Lasso_Model.predict(X_test) RMSE_test = np.sqrt(mean_squared_error(Y_test, Y_pred_test)) print(RMSE_train) print(RMSE_test)
6a1107e4c75596975bcb3f5098224afda098d0bf
eric-czech/portfolio
/functional/ml/python/py_utils/zip_utils.py
797
3.5
4
# Utilities for processing zip archives import zipfile def _validate_archive(zip_filepath): assert zip_filepath.endswith('.zip'), \ 'File should have a .zip extension (filepath given = "{}")'.format(zip_filepath) def get_zip_archive_files(zip_filepath): _validate_archive(zip_filepath) with zipfile.ZipFile(zip_filepath, "r") as zfile: return zfile.namelist() def get_zip_archive_file_data(zip_filepath, filename): _validate_archive(zip_filepath) with zipfile.ZipFile(zip_filepath, "r") as zfile: filenames = zfile.namelist() assert filename in filenames, \ 'Failed to find file "{}" in zip archive "{}" (filenames available = "{}")'\ .format(filename, zip_filepath, filenames) return zfile.read(filename)
3c871b9cf4b59477171a62a7f41692e763e3194b
rwieckowski/project-euler-python
/euler371.py
754
3.75
4
""" Oregon licence plates consist of three letters followed by a three digit number each digit can be from 09<BR />While driving to work Seth plays the following game<BR />Whenever the numbers of two licence plates seen on his trip add to 1000 thats a win Eg MIC012 and HAN988 is a win and RYU500 and SET500 too as long as he sees them in the same trip Find the expected number of plates he needs to see for a win<BR />Give your answer rounded to 8 decimal places behind the decimal point <b>Note</b> We assume that each licence plate seen is equally likely to have any three digit number on it</P> """ def euler371(): """ >>> euler371() 'to-do' """ pass if __name__ == "__main__": import doctest doctest.testmod()
28b14ef27fbf56b02b3eb7f9d482231a966fd2a8
StarliteOnTerra/csci127-Assignments
/lab_04/mad.py
1,161
3.921875
4
import random adj = ["beautiful", "aggressive", "calm", "delightful", "silly"] noun = ["tiger", "cat", "house", "banana", "music"] verb = ["running", "jumping", "swimming", "laughing", "skating"] pnoun = ["tigers", "cats", "houses", "bananas", "musics"] game = ["Scrabble", "Twister", "Tag", "Digging"] statement = "A vacation is when you take a trip to some <adj> place with your <adj> family. Usually you go to some place that is near a/an <noun> or up on a/an <noun> . A good vacation place is one where you can ride <pnoun> or play <game> or go hunting for <pnoun> . I like to spend my time <verb> or <verb> . When parents go on a vacation, they spend their time eating three <pnoun> a day, and fathers play golf and mothers <verb> ." subs = ['<adj>', '<noun>', '<verb>', '<pnoun>', '<game>'] words = [adj, noun, verb, pnoun, game] d = {} d[0] = words for i, l in zip(subs, words): d[i] = l def madlibs(statement, d): list = [] for i in statement.split(): if i in d: list.append(random.choice(d[i])) else: list.append(i) return ' '.join(list) print(madlibs(statement, d))
0dc632b6d270dfb5732ad6b1b1390ee0eaa84a3b
longchushui/How-to-think-like-a-computer-scientist
/exercise_03070_0308.py
1,351
4.4375
4
# A drunk pirate makes a random turn and then takes 100 steps forward, makes another # random turn, takes another 100 steps, turns another random amount, etc. A social # science student records the angle of each turn before the next 100 steps are taken. # Her experimental data is [160, -43, 270, -97, -43, 200, -940, 17, -86]. # (Positive angles are counter-clockwise.) Use a turtle to draw the path taken by our # drunk friend. import turtle # so we can use the turtle module wn = turtle.Screen() # create a screen for the turtles pirate = turtle.Turtle() # create a turtle, assign to pirate data = [160, -43, 270, -97, -43, 200, -940, 17, -86] # assign experimental data to data for i in data: pirate.left(i) # positive angles are counter-clockwise so use left() pirate.forward(100) wn.mainloop() # wait for user to close window # Enhance your program above to also tell us what the drunk pirate’s heading is after # he has finished stumbling around. (Assume he begins at heading 0). total = 0 # assign zero to total # use a for loop to add up all angles for i in data: total = total + i # to get the direction the drunk pirate is heading use modulo direction = total % 360 print("The drunk pirate is heading after" + str(direction) + " degrees.")
ab461793e6af592d270fdfeece93dba38136c7aa
btwmendes/Data-Structures-Algorithms
/section_3_recursion/power_of_number.py
369
4.21875
4
def power(base, exponent): assert exponent >= 0 and int(exponent) == exponent, "The exponent must be greater than or equal to zero" \ " and an integer." if exponent == 0: return 1 if exponent == 1: return base else: return base * power(base, exponent-1) print(power(2,.5))
4b55269c3cfcbda637d05e02421866d8f5fd37ea
Ankong0914/mancala
/play.py
2,511
4
4
from hole import PlayerHole, SideHole import sys class Play(): def __init__(self, num_hole, init_stone): """initial function in Play class Arguments: num_hole {int} -- the number of holes on one side except side holes init_stone {int} -- the number of stones that is put on each hole by default """ self.num_hole = num_hole self.init_stone = init_stone self.turn = "Player" self.player_side = [PlayerHole(init_stone, "Player", position) for position in range(1, num_hole+1)] self.opponent_side = [PlayerHole(init_stone, "Opponent", position) for position in range(1, num_hole+1)] self.right_hole = SideHole("right") self.left_hole = SideHole("left") self.board = self.player_side + [self.right_hole] + self.opponent_side + [self.left_hole] def sowing(self): print(f"<{self.turn}'s turn>") print("please input the position number where you want to move stones there") position = int(input("position number>> ")) active_board = self.player_side if self.turn=="Player" else self.opponent_side selected_hole = active_board[position-1] num_sowed_stone = selected_hole.num_stone selected_hole.sow(self.board, position, self.num_hole, self.turn) self.does_game_finish(active_board) self.change_turn(position, num_sowed_stone) def change_turn(self, position, num_sowed_stone): distance_to_sidehole = self.num_hole - position + 1 if(distance_to_sidehole == num_sowed_stone): pass else: self.turn = "Player" if self.turn=="Opponent" else "Opponent" self.view_board() self.sowing() def does_game_finish(self, active_board): if all(hole.num_stone==0 for hole in active_board): self.view_board() print(f"{self.turn} Wins!") sys.exit() def view_board(self): for hole in reversed(self.opponent_side): print(" ", hole.num_stone, end="") print("") print(self.left_hole.num_stone, " "*self.num_hole, self.right_hole.num_stone) for hole in self.player_side: print(" ", hole.num_stone, end="") print("") def start_game(self): self.view_board() self.sowing() if __name__ == "__main__": num_hole = 3 init_stone = 2 play = Play(num_hole, init_stone) play.start_game()
6d17e4d59b55518fc1ff965ae2160cd2b398c606
arumakan1727/sudoku-solver
/validator/validator.py
1,398
3.84375
4
#!/usr/bin/env python3 from typing import List, Iterator N = 9 def main(): mat = [[int(e) for e in input().split()] for _ in range(N)] assert_board_validity(mat) def is_valid_sequence(seq: List[int]) -> bool: n = len(seq) return all(seq.count(i + 1) == 1 for i in range(n)) def assert_board_validity(board: List[List[int]]) -> None: assert len(board) == N assert all(len(row) == N for row in board) assert all(1 <= e <= 9 for e in cells(board)) assert all(is_valid_sequence(row) for row in rows(board)) assert all(is_valid_sequence(col) for col in cols(board)) assert all(is_valid_sequence(square) for square in squares_3x3(board)) def cells(mat: List[List[int]]) -> Iterator[int]: for row in mat: for cell in row: yield cell def rows(mat: List[List[int]]) -> Iterator[List[int]]: for row in mat: yield row def cols(mat: List[List[int]]) -> Iterator[List[int]]: H = len(mat) W = len(mat[0]) for x in range(W): yield [mat[y][x] for y in range(H)] def squares_3x3(mat: List[List[int]]) -> Iterator[List[int]]: for top in range(0, 9, 3): for left in range(0, 9, 3): seq = [] for dy in range(3): for dx in range(3): seq.append(mat[top + dy][left + dx]) yield seq if __name__ == "__main__": main()
317033e4b836413c86c0bc3cdf1c4ab2dc29dfdd
SangYong-Park/python_practice
/Day1/print_sample.py
404
3.734375
4
s = '서울' d = '대전' g = '대구' b = '부산' print(s,d,g,b, sep = ' , ') print (b) a = input("당신의 나이는?") print (a) print('당신의 나이는', a, '살 입니다') # 5년 뒤 나이 표시 print("당신의 나이는 5년 뒤에 " , int(a)+5 , "살입니다.") #casting : 하나의 데이터 타입에서 다른 데이터 타입으로 바꿈. a = "first\nsecond" print(a)
8d7dfe835540f9ca0d4a17f596b0fd47c4e7797e
cmychina/Leetcode
/leetcode_链表_16.重排链表.py
1,719
3.75
4
""" 给定一个单链表 L:L0→L1→…→Ln-1→Ln , 将其重新排列后变为: L0→Ln→L1→Ln-1→L2→Ln-2→… 给定链表 1->2->3->4, 重新排列为 1->4->2->3. 思路:快慢指针找到中点Lm,然后将Lm后面的翻转得 Ln,Ln-1,Ln-2 然后得到两个序列L0,L1,...Lm和Ln,Ln-1,Ln-2,然后交替连接即可 #交替连接,首先保存左右的next,然后将左指针连接到右指针,把右指针和左next连接 然后更新左右指针 """ from linklist import * class Solution: def reorderList(self, head: ListNode) -> None: if head==None or head.next==None: return head #快慢指针找中点 slow,fast=head,head while fast.next and fast.next.next: slow=slow.next fast=fast.next.next right_reverse=slow.next slow.next=None right_reverse=self.reverse(right_reverse)##4->3 #指针 left_cur=head right_cur=right_reverse while left_cur and right_cur: #保存右侧指针 right_next=right_cur.next left_next=left_cur.next #连接 right_cur.next=left_cur.next left_cur.next=right_cur #更新指针 left_cur=left_next right_cur=right_next return head def reverse(self, head: ListNode): if head == None or head.next == None: return head tmp = head.next cur = self.reverse(tmp) tmp.next = head head.next = None return cur if __name__=="__main__": a=[1,2,3,4,5,6] l1=convert.list2link(a) s=Solution() out=s.reorderList(l1) print(convert.link2list(out))
6975866b9af860e45f618fc58f3a99b3ef08876f
mocorr/algorithm013
/Week_09/day61_[151]翻转字符串里的单词_homework.py
2,800
3.890625
4
# 给定一个字符串,逐个翻转字符串中的每个单词。 # # # # 示例 1: # # 输入: "the sky is blue" # 输出: "blue is sky the" # # # 示例 2: # # 输入: "  hello world!  " # 输出: "world! hello" # 解释: 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 # # # 示例 3: # # 输入: "a good   example" # 输出: "example good a" # 解释: 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 # # # # # 说明: # # # 无空格字符构成一个单词。 # 输入字符串可以在前面或者后面包含多余的空格,但是反转后的字符不能包括。 # 如果两个单词间有多余的空格,将反转后单词间的空格减少到只含一个。 # # # # # 进阶: # # 请选用 C 语言的用户尝试使用 O(1) 额外空间复杂度的原地解法。 # Related Topics 字符串 # 👍 225 👎 0 # leetcode submit region begin(Prohibit modification and deletion) class Solution: def reverseWords(self, s: str) -> str: """ 手写api """ def trim_spaces(): left, right = 0, len(s) - 1 # 去掉字符串头尾的空白字符 while left <= right and s[left] == ' ': left += 1 while left <= right and s[right] == ' ': right -= 1 # 将字符串间多余的空白字符去除 output = [] while left <= right: if s[left] != ' ': output.append(s[left]) elif output[-1] != ' ': output.append(s[left]) left += 1 return output def reverse(left, right): while left < right: s[left], s[right] = s[right], s[left] left += 1 right -= 1 def reverse_each_word(): n = len(s) start = end = 0 while start < n: # 找到每个单词的末尾 while end < n and s[end] != ' ': end += 1 # 翻转当前单词 reverse(start, end - 1) # 更新start,去找下一个单词 start = end + 1 end += 1 s = trim_spaces() reverse(0, len(s) - 1) print(s) reverse_each_word() return ''.join(s) def reverseWords1(self, s: str) -> str: """ 将s按空格分割 --> (使用.split(' ')还需滤去list中的空字符串) --> 翻转list --> 转回string """ return ' '.join(s.split()[::-1]) # leetcode submit region end(Prohibit modification and deletion)
5b7d181931d190982e3d1eb103994135c079ac6f
alaz1812/My_Homework
/Pack_2/Task_1.py
271
3.90625
4
def recfact (x): if x == 0: return 1 else: return x * recfact(x - 1) def factorial(x): mult = 1 for i in range (2,x+1): mult = mult * i return mult x = int(input("Inputn the number: ")) print (recfact(x)) print (factorial(x))
6148b3ae7f62d4683972d50935bdfd9255af8ae2
NaiveMonkey/Datastructure_HackerRank
/linkedlist/insert_node_tail.py
749
4.1875
4
""" Insert Node at the end of a linked list head pointer input could be None as well for empty list Node is defined as class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node return back the head of the linked list in the below method """ class Node(object): def __init__(self, data=None, next_node=None): self.data = data self.next = next_node def Insert(head, data): if head is None: head = Node(data, None) return head else: head.next = Insert(head.next, data) return head head = Insert(None, 4) head = Insert(head, 5) head = Insert(head, 2) while head is not None: print(head.data) head = head.next
37a4c9e6c70905be4c5670345959451aade22ef7
skybohannon/python
/PracticeExercises/question35.py
504
4.4375
4
# Question: # Define a function which can generate a list where the values are square of numbers between # 1 and 20 (both included). Then the function needs to print all values except the first 5 # elements in the list. # # Hints: # # Use ** operator to get power of a number. # Use range() for loops. # Use list.append() to add values into a list. # Use [n1:n2] to slice a list def squarelist(a, b): s = [] for i in range(a, b+1): s.append(i ** 2) print(s[5:]) squarelist(1, 20)
2828ac8e13c93c95169b653048efdda51479b40f
dpdahal/python6am
/introduction.py
1,816
4
4
# print("Hello", "Welcome", "Python") # print('mother\'s') # print('mother"s') # print("mother's") # print(1+5) """ Here is a list of the Python keywords. Enter any keyword to get more help. False break for not None class from or True continue global pass __peg_parser__ def if raise and del import return as elif in try assert else is while async except lambda with await finally nonlocal yield """ # Name = "Sophia" # print(Name) # &*/<> # letter = '' # _ = '' # Camel Case = userName, nameOfStudent # Pascal Case = UserName, NameOfStudent # Snake Case = user_name, name_of_student # variable name = value # userName = "Sneha" # print("My name is: " + userName) # name = "Sneha" # address = "Kathmandu" # print("My name is: " + name + " Address:" + address) # name = "Sophia" # phone = 876787 # print("Name: ", name, " Phone", phone) # Python old # print("Name: {} Phone {}".format(name, phone)) # Python New # print(f"Name:{name} Phone: {phone}") # Max len = 79 # userName = 1234 # data = "Ram" # data = "Mother's" # data = "Sophia" # print(type(data)) # print(id(data)) # print(dir(data)) # Number - integer,float,complex # Sequence - String,List,Tuple # Boolean - True or False,Null # Dictionary # Set # x = 1234567654323456765432112345678 # print(x) # a = 45.67 # print(type(a)) print("Enter number:") x = input() x = int(x) print("Enter number:") y = input() y = int(y) print(x + y) a = '2' # str a = int(a) # int
717a80c36df3ed38c778a9ba128fd8f09ed727ec
DiksonSantos/Curso_Intensivo_Python
/Pagina_83_Exemplo_Concatenação_Listas.py
1,846
3.90625
4
'''bike = ['trek', 'cannodale','redline','specialized'] messege = "My Favorite bicycle Was a: " + bike[-2].title()+'.' print(messege)''' #3.2 Nomes: '''friends = ['joão', 'maria', 'josé bonifacio','bono vox','madalena'] message = 'Tempim Bãao Hein: ' + friends[-4].title() message_2 = 'The Rain Drops Is Falling On My Head: -> ' + friends[2].title() print(message+'\n',message_2)''' #3.3 Frases sobre Itens da Lista: '''inserir = str(input("Qual O Avião? ")) jatos = ['F-16 Fighting Falcon', 'Sukoi-SU_37 Terminator','Su-27_Flanker','MiG-29-Fulcrum','F-22-Raptor','Mig-25-FoxBat'] for i in range(len(jatos)): if inserir == jatos[0]: print('Agil e Manobravél, Espetacular') elif inserir ==jatos[1]: print('Poderoso Passaro de Guerra') elif inserir == jatos[2]: print("The Red Terror") elif inserir == jatos[3]: print('The Paper Tiger?') elif inserir == jatos[4]: print('Caught By Surprise in Siria...') elif inserir == jatos[5]: print('The Flash') break else: print('{} Is Not in this List'.format(inserir.title())) ___________________________//______________________________________''' jatos = ['F-16', 'Sukoi-SU-37','Su-27','MiG-29','F-22','Mig-25'] jatos.append('Arphia-X') ww2 =[] ww2 [1:1] = ["Prototipo-01", "Prototipo-02", "Experimental-04"] # ww2.insert(2,'P-40'), ww2.insert(3,'ZERO') , ww2.insert(4,'MIG-1') print(jatos,"\n",ww2) '''O Insert demostrou Prioridade\superioridade sobre os parametros de inserção [1:1] (que são posições indicadas de onde eles devem ser colocados na lista Então: Os Parametros\posições [2:2 ou neste caso 1:1] ocupam somente as posições que não forem reivindicadas pelo comando INSERT. Este ultimo sempre terá prioridade na inserção de dados em listas'''
9eacdc0ae6443db7c66c4b5f45614121c176677f
Ratajq/coffee-machine
/coffee-machine.py
4,045
3.59375
4
class MyCoffee: water = 400 milk = 540 coffee_b = 120 cups = 9 money = 550 state = 'menu' end = 1 #ending condiotion def remaining(self): print('The coffee machine has:') print(f'{self.water} of water') print(f'{self.milk} of milk') print(f'{self.coffee_b} of coffeee beans') print(f'{self.cups} of disposable cups') print(f'${self.money} of money') return def buy_esp(self): self.state = 'menu' res = [self.water, self.coffee_b, self.cups] res_name = ['water', 'coffee beans', 'cups'] esp_ing = [250, 16, 1] for i in range(len(res)): if res[i] < esp_ing[i]: print('Sorry, not enough', res_name[i]+'!') break i += 1 else: self.water -= 250 self.coffee_b -= 16 self.cups -= 1 self.money += 4 print('I have enough resources, making you a coffee!') return def buy_lat(self): self.state = 'menu' res = [self.water, self.milk, self.coffee_b, self.cups] res_name = ['water', 'milk', 'coffee beans', 'cups'] lat_ing = [350, 75, 20, 1] for i in range(len(res)): if res[i] < lat_ing[i]: print('Sorry, not enough', res_name[i]+'!') break i += 1 else: self.water -= 350 self.coffee_b -= 20 self.milk -= 75 self.cups -= 1 self.money += 7 print('I have enough resources, making you a coffee!') def buy_cap(self): self.state = 'menu' res = [self.water, self.milk, self.coffee_b, self.cups] res_name = ['water', 'milk', 'coffee beans', 'cups'] cap_ing = [200, 100, 12, 1] for i in range(len(res)): if res[i] < cap_ing[i]: print('Sorry, not enough', res_name[i]+'!') break i += 1 else: self.water -= 200 self.milk -= 100 self.coffee_b -= 12 self.cups -= 1 self.money += 6 print('I have enough resources, making you a coffee!') return def back(self): self.state = 'menu' return def fill(self): global water, milk, coffee_b, cups, money print('Write how many ml of water do you want to add:') self.water += int(input()) print('Write how many ml of milk do you want to add:') self.milk += int(input()) print('Write how many grams of coffee beans do you want to add:') self.coffee_b += int(input()) print('Write how many disposable cups of coffee do you want to add:') self.cups += int(input()) return def take(self): print('I gave you $', self.money) self.money = 0 def buy(self): self.state = 'buy' def back(self): self.state = 'menu' def exit(self): self.end = 0 def start(self): while (self.end != 0): if self.state == 'menu': print('Write action (buy, fill, take, remaining, exit):') action = input() if action == 'buy': self.buy() elif action == 'fill': self.fill() elif action == 'take': self.take() elif action == 'remaining': self.remaining() elif action == 'exit': self.exit() else: print('wrong aciton!') else: print('What do you want to buy? 1 - espresso, 2 - latte, 3 - cappuccino, back - to main menu:') action = input() if action == '1': self.buy_esp() elif action == '2': self.buy_lat() elif action == '3': self.buy_cap() elif action == 'back': self.back() else: print('wrong action!') MyCoffee().start()
5b6e9d55beb5fd5f8e1fdc490fe0429d914a1871
itcsoft/itcpython
/python/day14/dict_1.py
1,522
3.953125
4
# Наши Аккаунты в банках accounts = [ { "name": 'Demir Bank', "balance": 500000.00, "valuta": "KGS", "password": 1994 }, { "name": 'Optima Bank', "balance": 9654321, "valuta": "RUS", "password": 1995 }, { "name": 'KICB', "balance": 978423.15, "valuta": "USD", "password": 1996 }, { "name": 'Dos-Credo Bank', "balance": 75542.65, "valuta": "EUR", "password": 1997 } ] # Курс валют curs = { "EUR": 101.65, "USD": 84.80, "RUS": 1.23, "KZT": 0.010 } print('Мои аккаунты в банках:') for index in range(len(accounts)): print(index + 1, accounts[index]['name']) aindex = int(input('Выберите Аккаунт: ')) if aindex < 5 and aindex >= 1: rindex = aindex - 1 print(accounts[rindex]['name']) pin = int( input('Банкка тиешелуу PIN кодунузду териниз: ') ) if pin == accounts[rindex]['password']: print( 'Добро пожаловать в', accounts[rindex]['name'] ) print( 'Ваш баланс: ', accounts[rindex]['balance'] ) else: print('Ваш PIN не правильно!!!') else: print('Андай аккаунтум жоккоо((')
a8dc7fa9206db42300345aba27c1e6425edc4591
edson-onishi/cursoemvideo
/088.py
670
4.03125
4
''' Faça um programa que ajude um jogador da MEGA SENA a criar palpites. O programa vai perguntar quantos jogos serão gerados e vai sortear 6 números entre 1 e 60 para cada jogo, cadastrando tudo em uma lista composta.''' import random lista = list() jogos = list() qtdjogos = int(input("Quantos jogos: ")) total = 1 while total <= qtdjogos: cont = 0 while True: n = random.randint(1,60) if n not in lista: lista.append(n) cont += 1 if cont >= 6: break lista.sort() jogos.append(lista[:]) lista.clear() total +=1 for i, l in enumerate(jogos): print(f'{i+1}º jogo: {l}')
7f544df4669dfdc444e5662f1c2cdb1e37fbfe9a
ingridsor/number_extraction
/baseline_extraction.py
2,652
3.71875
4
# Number recognition project, Speech Technology DT2112 # By Ingrid Sör, Manon Knoertzer and Carina Rawein # A script for acquiring a "baseline" of number extraction from ASR # For filesystem support import os, re def cut_extras(number): number_cut = number.replace(' ','').replace('(','').replace(')','') return number_cut # Folder where the transcriptions reside as xml files # TO BE ADAPTED TO YOUR OWN COMPUTER folder = "/home/ingrid/Documents/Utbildning/MPLT/speech/project/xml_data" files = os.listdir(folder) # To remove possible ~-files from Emacs made when making test files... files = [x for x in files if x.endswith('.b.xml')] j = 0 # Counter for found numbers res_file = 'results_baseline.txt' # file for results print("Transcript files to go through: ",files) # For all transcript files in folder for file in files: # Setting empty transcription string for each file transcription = '' number = '' # Change directory to the path with xml files os.chdir(folder) with open(file, 'r', encoding='ISO-8859-1') as fin: print("Now looking at file: ", file) # Finding name of subject for saving of result. s = re.search(r'(.*)\.b\.xml',file) subject = s.group(1) print('Subject: ', subject) for line in fin: # Finding transcription if re.search(r"<t>.*</t>",line) != None: t = re.search(r"<t>(?P<trans>.*)</t>",line) # Concatenating recognised words with spaces in between transcription += t.group('trans') + ' ' print('Transcription: ', transcription) # Find number # Needs to find numbers with spaces in between as the numbers # are sometimes split up by the ASR and then separated by spaces # in script when finding transcription n = re.search(r"\d+(?: \d+)*", transcription) if n != None: number = cut_extras(n.group()) ##### Printing results ##### # Check results folder exists or create if not os.path.isdir('../results'): os.makedirs('../results') os.chdir('../results') # If a result file exists, give new name (first time only) i = 1 while os.path.isfile(res_file) and j == 0: res_file = 'results_baseline' + str(i) + '.txt' i += 1 # Appending phone number to result file to_print = subject + ', ' + number + '\n' with open(res_file,'a') as fout: fout.write(to_print) j += 1 if number != '': print("Phone number found: ",number,'\n') else: print('No phone number found.\n')
20cf5b34e570d982ae6a87c47d62ddab00c2b011
DayGitH/Python-Challenges
/DailyProgrammer/DP20130701A.py
2,368
3.875
4
""" [07/01/13] Challenge #131 [Easy] Who tests the tests? https://www.reddit.com/r/dailyprogrammer/comments/1heozl/070113_challenge_131_easy_who_tests_the_tests/ # [](#EasyIcon) *(Easy)*: Who tests the tests? [Unit Testing](http://en.wikipedia.org/wiki/Unit_testing) is one of the more basic, but effective, tools for [software testing](http://en.wikipedia.org/wiki/Software_testing) / quality assurance. Your job, as an expert test-engineer, is to double-check someone else's test data, and make sure that the expected output is indeed correct. The two functions you are testing is string-reversal and string-to-upper functions. For each line of input, there are three space-delimited values: the first being the test index (as either 0 or 1), then the test input string, and finally the "expected" output. You must take the test input string, run it through your implementation of the appropriate function based on the test index, and then finally compare it to the "expected" output. If you are confident your code is correct and that the strings match, then the "expected" output is indeed good! Otherwise, the "expected" output is bad (and thus invalid for unit-testing). *Author: nint22* # Formal Inputs & Outputs ## Input Description You will be given an integer N on the first line of input: it represents the following N lines of input. For each line, you will be given an integer T and then two strings A and B. If the integer T is zero (0), then you must reverse the string A. If the integer T is one (1), then you must upper-case (capitalize) the entire string A. At the end of either of these operations, you must test if the expected result (string B) and the result of the function (string A) match. ## Output Description If string A, after the above described functions are executed, and B match, then print "Good test data". Else, print "Mismatch! Bad test data". "Matching" is defined as two strings being letter-for-letter, equivalent case, and of the same length. # Sample Inputs & Outputs ## Sample Input 6 0 Car raC 0 Alpha AhplA 0 Discuss noissucsiD 1 Batman BATMAN 1 Graph GRAPH 1 One one ## Sample Output Good test data Mismatch! Bad test data Mismatch! Bad test data Good test data Good test data Mismatch! Bad test data """ def main(): pass if __name__ == "__main__": main()
dae26d8bb27c6615529675bb00e572161a7eb496
YotamZiv298/cyber-python
/persian_box.py
1,952
4.21875
4
import argparse FILE_NAME = __file__.split('/')[-1] OPERATION = 'operation' OPERATION_HELP = 'math function' OPERATION_TYPE = str PARAM1 = 'first_number' PARAM1_HELP = 'first number' PARAM1_TYPE = int PARAM2 = 'second_number' PARAM2_HELP = 'second number' PARAM2_TYPE = int def add(a, b): """ Prints addition between two parameters. :param a: Number. :param b: Number. """ print(a + b) def multiply(a, b): """ Prints multiplication between two parameters. :param a: Number. :param b: Number. """ print(a * b) def subtract(a, b): """ Prints subtraction between two parameters. :param a: Number. :param b: Number. """ print(a - b) def divide(a, b): """ Prints division between two parameters. :param a: Number. :param b: Number. """ print(a / b) def check_operation(): """ Checks operation based on script parameters and activate functions accordingly. """ if args['w']: print("Good morning :)") if args[OPERATION] == add.__name__: add(args[PARAM1], args[PARAM2]) elif args[OPERATION] == subtract.__name__: subtract(args[PARAM1], args[PARAM2]) elif args[OPERATION] == multiply.__name__: multiply(args[PARAM1], args[PARAM2]) elif args[OPERATION] == divide.__name__: divide(args[PARAM1], args[PARAM2]) # Creating parser parser = argparse.ArgumentParser(FILE_NAME) # Adding arguments parser.add_argument(OPERATION, choices=[add.__name__, subtract.__name__, multiply.__name__, divide.__name__], help=OPERATION_HELP, type=OPERATION_TYPE) parser.add_argument(PARAM1, help=PARAM1_HELP, type=PARAM1_TYPE) parser.add_argument(PARAM2, help=PARAM2_HELP, type=PARAM2_TYPE) parser.add_argument('-w', action='store_true') args = vars(parser.parse_args()) check_operation()
21ad6107640ceaefef25e436d6d6248bed644929
wanqizhu/finitefield
/utils.py
6,191
3.765625
4
""" Perform Gaussian Elimation on the input matrix. Elements of this matrix need to support +, *, /, and identity checking with 0. If the matrix is non-square, reduction is performed on as many rows/columns as possible. @param A Input matrix, of any dimension @return A', input matrix transformed to reduced row echelon form """ def gaussian_elimination(A): num_rows = len(A) num_cols = len(A[0]) r = 0 c = 0 # forward scan, creating matrix in row echelon form while r < num_rows and c < num_cols: # if this column has a nonzero entry below row r, # row-operate so that everything below row 'r' # is 0 for column 'c' # find the nonzero entry pivot_row = r pivot = A[pivot_row][c] while pivot == 0 and pivot_row < num_rows - 1: pivot_row += 1 pivot = A[pivot_row][c] if pivot == 0: # column c is entirely of zeros; move to next col c += 1 else: # swap pivot_row and r tmp = A[r] A[r] = A[pivot_row] A[pivot_row] = tmp # reduce # for each i>r, subtract a multiplier of row r # onto row i, making A[i][c] == 0 for i in range(r+1, num_rows): if A[i][c] == 0: continue multiplier = A[i][c] / A[r][c] for j in range(c, num_cols): A[i][j] -= multiplier * A[r][j] # make row r's leading nonzero entry == 1 divisor = A[r][c] for j in range(c, num_cols): A[r][j] /= divisor c += 1 r += 1 # backward scan, reducing to unique reduced row echelon form # for each column, find the last row which is non-zero, and # then zero-out all the earlier rows # we can start at (r, c) from before # every column from last to first, the last non-zero row must be strictly decreasing r -= 1 c -= 1 while r >= 0 and c >= 0: i = r last_non_zero = A[i][c] while i > 0 and last_non_zero == 0: i -= 1 last_non_zero = A[i][c] if last_non_zero == 0: c -= 1 # go to next column else: for j in range(i): # zero out A[j][c] by subtracting row i for all previous rows # row i only has non-zero entries after column c multiplier = A[j][c] / A[i][c] for k in range(c, num_cols): A[j][k] -= multiplier * A[i][k] r -= 1 c -= 1 return A """ Solves the exact linear system Ax = b using Gaussian Elimination. A should be a n-by-n square matrix and b a 1-by-n vector. Elements in A and b need to support arithmetic operations (+, *, /) with each other. Throws ValueError if there's no solution or if there are multiple solutions. @param A Matrix of dimension n x n, specifying n linear constraints @param b Vector of dimension n, specfying the constant term of each constraint @return Unique solution x of dimension n, such that A*x = b """ def solve_lin_sys(A, b): num_rows = len(A) if len(b) != num_rows: raise ValueError(f"Unmatched dimension in linear system: {num_rows} and {len(b)}") if len(A[0]) != num_rows: raise ValueError("Expected A to be a square matrix.") A_aug = [A[i] + [b[i]] for i in range(num_rows)] A_reduced = gaussian_elimination(A_aug) solution = [None] * num_rows for i in range(num_rows): # if there's an unique solution, A_reduced[i][i] should be 1 if A_reduced[i][i] == 0: if b[i] == 0: raise ValueError("A is not full rank, no unique solution.") else: raise ValueError("No solution exist for this system.") if A_reduced[i][i] != 1: raise ValueError("Unknown error happened, corrupted result from " + "Gaussian Elimination.") solution[i] = A_reduced[i][-1] return solution ''' Divides f by g. Solves the equation f(x) = g(x)q(x) + r(x) for some r with degree strictly less than deg(g). @param f Divident polynomial, represented as a list of coefficients (lower degree first) @param g Divisor polynomial, same format as f @return (q, r), where q is the quotient polynomial and r is the reminder, same formats as f ''' def poly_div(f, g): n = len(f) k = len(g) reminder = f quotient = [] # each loop iter correspond to one long division step for x_pow in range(n-k, -1, -1): quotient_term = reminder[-1] / g[-1] quotient.append(quotient_term) # multiply g by divisor_term * x^{x_pow}, then # subtract from reminder to get new reminder for i in range(k): reminder[x_pow + i] -= quotient_term * g[i] # last term of reminder should be 0 now; trim reminder = reminder[:-1] # long division gets back quotient with leading coefficient first quotient = quotient[::-1] # trim zeros in reminder while len(reminder) > 0 and reminder[-1] == 0: reminder = reminder[:-1] return (quotient, reminder) ''' Evaluate f(x). @param f Coefficients of the polynomial, with the lowest ordered term first @param x Point at which to evaluate the polynomial @return Result f(x) ''' def poly_eval(f, x): return sum([f[i] * x**i for i in range(len(f))]) ''' Given a list of n points x, y, finds the unique polynomial f of degree n-1 such that f(x_i) = y_i for all i. @param X List of n evaluation points @param Y List of n values @return List of n coefficients, representing the polynomial f with lowest ordered term first, such that f(X_i) = Y_i for all i. ''' def poly_interpolation(X, Y): n = len(X) if len(Y) != n: raise ValueError("Expected X, Y to be of the same length.") # f(x_i) = y_i gives us a set of n linear equations A = [[X[i]**j for j in range(n)] for i in range(n)] b = Y f = solve_lin_sys(A, b) return f
800a14b341863b8531a87ad4d2afdd8ff5112a9d
zsmountain/lintcode
/python/161_rotate_image.py
876
4.25
4
''' You are given an n x n 2D matrix representing an image. Rotate the image by 90 degrees (clockwise). Have you met this question in a real interview? Example Example 1: Input:[[1,2],[3,4]] Output:[[3,1],[4,2]] Example 2: Input:[[1,2,3],[4,5,6],[7,8,9]] Output:[[7,4,1],[8,5,2],[9,6,3]] Challenge Do it in-place. ''' class Solution: """ @param matrix: a lists of integers @return: nothing """ def rotate(self, matrix): # write your code here n = len(matrix) for i in range(n): for j in range(i+1, n): matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j] for i in range(n): matrix[i].reverse() s = Solution() matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] s.rotate(matrix) print(matrix) matrix = [[1, 2], [3, 4]] s.rotate(matrix) print(matrix)
6386e839f671f844a58bb26f731493d14dc8be4c
jazzmanmike/python-intro
/solutions/2_1.py
224
4.125
4
bases = ['A', 'T', 'T', 'C', 'G', 'G', 'T', 'C', 'A', 'T', 'G', 'C', 'T', 'A', 'A'] print "All bases:" for base in bases: print base print "Every 3rd base:" pos = 2 while pos <= 12: print bases[pos] pos += 3
ae988d82f2f6ccc1b798307086bb9e4095e1e1a7
arch1904/Python_Programs
/count_vowels.py
642
4.34375
4
# Count Vowels # # For our purposes a vowel is either a, e, i, o, or u. Iterate through # a string and return the number of vowels in it. Case does not matter. # # Example(s) # ---------- # Example 1: # Input: aAaeeizzzzz # This string contains 3 a's, 2 e's, 1 i. So 5 vowels. # Output: # 5 # # Parameters # ---------- # str_in : str # A mixed case single line string. # # Returns # ------- # int # Number of vowels. # def count_vowels(str_in): vowels=['a','e','i','o','u'] count=0 str_in=str_in.lower() for c in str_in: if c in vowels: count+=1 else: pass return(count)
36af996fb77849baff38a00eb170f7c6629daf7a
Amudha2019/INeuron-Assignment-1
/ex3.py
245
3.5
4
names1=['Amir','Bear','Charlton','Daman'] names2=names1 names3=names1[:] names2[0]='Alice' names3[1]='Bob' sum=0 for ls in (names1,names2,names3): if ls[0]=='Alice': sum+=1 if ls[1]=='Bob': sum+=10 print(sum)
4ba52dc43dbc0755c13ac42da5d393c94e0311cc
marcfies/Classroom-Scheduler
/faculty_test.py
1,321
3.8125
4
import faculty import csv faculty_file = open('test_faculty.txt', 'r') ################################# PART ONE ##################################### """ Part one uses faculty input file to creat list of faculty members """ data = faculty_file.readlines() #read in faculty file faculty_file.close() dataSplit = [] #list for individual faculty members from file Facultylist = [] #list of Faculty objects # """for loop to split individual faculty members from file""" for i in range(len(data)): dataSplit.append(data[i].split()) del dataSplit[0] #delete headings from file # """for loop to create individual faculty objects and store them in list""" for i in range(len(dataSplit)): dataSplit2 = dataSplit[i] facName = dataSplit2[0] facFullTime = dataSplit2[1] facClasses = dataSplit2[2] facExpertise1 = dataSplit2[4] facExpertise2 = dataSplit2[5] facExpertise3 = dataSplit2[6] Facultylist.append(faculty.Faculty(facName,facFullTime,facClasses, \ facExpertise1,facExpertise2,facExpertise3)) # """Displays all faculty member objects""" for i in range(len(Facultylist)): print Facultylist[i].display() print class Tests(object): def test_adding_a_course(): pass def test_showing_a_schedule(): pass
096aacaa4996064d040fcda8dd6e27abe927260c
rishuraj1857/Python
/factorial.py
262
4.125
4
x = int(input("Please enter a number:=>")) y=1 if x > 0: for i in range (1,x+1): y=y*i print(f"factorial of {x} is {y}") elif x==0: print("Factorial of 0 is 1") else: print("Sorry, Factorial of Negative number does not exit")
1e54636829408e5566b2e1cb58e4d7d5e824c9b7
J14032016/LeetCode-Python
/leetcode/algorithms/p0037_sudoku_solver.py
1,202
3.5625
4
from typing import List class Solution: def solveSudoku(self, board: List[List[str]]) -> None: self._solve(board) def _solve(self, board: List[List[str]]) -> bool: for row in range(9): for column in range(9): if board[row][column] != '.': continue for number in range(1, 10): if self._is_valid(board, row, column, str(number)): board[row][column] = str(number) if self._solve(board): return True else: board[row][column] = '.' return False return True def _is_valid(self, board: List[List[str]], row: int, column: int, number: str) -> bool: for i in range(9): if board[i][column] == number: return False if board[row][i] == number: return False box_row = 3 * (row // 3) + i // 3 box_column = 3 * (column // 3) + i % 3 if board[box_row][box_column] == number: return False return True
707d534117c0bbc35346edaba69913b7ff18aba1
franzleeyan/PCC
/name_cases.py
1,131
4.40625
4
# 赋值名字 # first_name = "eric" # 用名字首字母大写的方式拼接短语 # hello_message = "Hello " + first_name.title() + ", would you like to learn some Python today?" # 打印短语 # print(hello_message) # 分别打印名字首字母大写,全小写,全大写 # print(first_name.title()) # print(first_name.lower()) # print(first_name.upper()) # 打印双引号的语句"A person who never made a mistake never tried anything new." # said_message: str = 'Albert Einstein once said,"A person who never made a mistake never tried anything new."' # # print(said_message) # 将名人名称赋值famous_person,并和名言拼接打印 # famous_person = "Albert Einstein" # famous_person_said_message = '"A person who never made a mistake never tried anything new."' # # print(famous_person + "once said," + famous_person_said_message) # 赋值人名,前空格或者后空格 first_name = ' \tFranz' second_name = '\nEric ' # 打印\n \t 的人名输出模式 # print(first_name) # print(second_name) # 打印取消取消空格的赋值人名 print(first_name.lstrip()) print(second_name.rstrip()) print(second_name.strip())