blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
d3f03f00a5287051a9523c3e8b770475f355606f
igorkoury/cev-phyton-exercicios-parte-2
/Aula20 – Funções (Parte 1)/ex096 – Função que calcula área.py
470
4.28125
4
'''Exercício Python 096: Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.''' def area(larg, comp): a = larg * comp print(f'A área de um terreno de {l} x {c} = {a}m²') # Progrma principal print('-'*30) print('Controle de Terrenos:') print('-'*30) l = float(input('Largura (m): ')) c = float(input('Comprimento (m): ')) area(l, c)
90a24dc01a2530eac818646aa3b8c36eebcd27b6
Patrrickk/aprendendo_python
/ex044.py
1,043
3.984375
4
valor = float(input('Volor a ser pago: ')) print(""" [1] À vista dinheiro/cheque: 10% de desconto [2] À vista no cartão: 5% de desconto [3] Em até 2x no cartão sem juros [4] 3x ou mais no cartão: 20% de juros""") opcao = int(input('Escolha uma opção para pagamento: ')) if opcao == 1: desconto = valor - (valor * 10 / 100) print(f'Sua compra de {valor} vai custar R${desconto} no final.') elif opcao == 2: desconto = valor - (valor * 5 / 100) print(f'Sua compra de {valor} vai custar R${desconto} no final.') elif opcao == 3: desconto = valor / 2 print(f'Sua compra será parcelada em 2x de {desconto} sem juros') print(f'Sua compra de {valor} vai custar R${desconto} no final.') elif opcao == 4: x3 = int(input('Em quantas vezes: ')) desconto = valor / x3 juros = desconto + (desconto * 20 / 100) print(f'Sua compra será parcelada em {x3}x de {juros} com juros') print(f'Sua compra de {valor} vai custar R${juros * x3} no final.') else: print('Opção Inválida, Tente novamente')
1381c6f94e6e88edcc43430eb8b09e1825925a3e
vandanagarg/practice_python
/learning_python/hacker_rank/problem14.py
1,966
4.0625
4
''' Min cost to get the projects completed? ** Note: If any project has no bids, return -1 Example: numProjects = 3 projects. projectId = [2, 0, 1, 2] bid - [8, 7, 6, 9] • projectId[i] is aligned with bid[i] • The first web developer bid 8 currency units for project 2 • The second web developer bid 7 currency units for project O • The third web developer bid 6 currency units for project 1 • The fourth web developer bid 9 currency units for project 2 There is only one choice of who to hire for project 0, and it will cost 7. Likewise, there is only one choice for project 1, which will cost 6. For project 2, it is optimal to hire the first web developer, Instead of the fourth, hence will cost 8. So the final answer Is 7 + 6 + 8 = 21. If instead there were n=4 projects, the answer would be -1 since there were no bids received on the fourth project. Function Description: Complete the function mInCost in the editor below minCost has the following parameters: int numProjects: the total num. of projects posted by the client (labeled from 0 to n) int projectID[n]: an array of integers denoting the projects that the freelancers bid on int bid[n]: an array, Integers denoting the bid amounts posted by the freelancers Returns: long: the minimum cost the client can spend to complete all projects, or -1 if any project has no bids ''' from collections import defaultdict def min_cost(numProjects, project_id, bid): if numProjects != len(set(project_id)): return -1 else: project_bid_dict = defaultdict(lambda: []) for i in range(0, len(project_id)): project_bid_dict[project_id[i]].append(bid[i]) # return project_bid_dict total_bid = 0 for i in project_bid_dict: total_bid = total_bid + min(project_bid_dict[i]) print(project_bid_dict[i]) return total_bid numProjects = 3 project_id = [2, 0, 1, 2] bid = [8, 7, 6, 9] print(min_cost(numProjects, project_id, bid))
5ef97f9079314a7989719f322648b139d3b30561
PaulinaGuerrero/Mision_02
/clase.py
439
3.84375
4
# Autor: paulina guerrero Ruiz A01024519 # Calcular porcentajes print("Cantidad de mujeres inscritas") m = int(input("Teclea el numero de mujeres inscritas: ")) print("Cantidad de hombres inscritos") h = int(input("Teclea el numero de hombres inscritos: ")) t = (m+h) m1 = (m/t)*100 h1 = (h/t)*100 print("Total de alumnos inscritos: ", (t)) print("Porcentaje de mujeres: %.1f "% (m1)) print ("porcenatje de hombres: %.1f" % (h1))
7fc0078db10739781956851dbcfb69edfc2fdf0a
RevansChen/online-judge
/Codewars/7kyu/find-the-next-perfect-square/Python/solution1.py
123
3.5625
4
# Python - 2.7.6 def find_next_square(sq): num = int(sq ** 0.5) return (num + 1) ** 2 if (num ** 2) == sq else -1
d5b965430705876843d63c823c812fcb97c486e5
postiffm/usfmtools
/charmap.py
1,132
3.53125
4
#!/usr/bin/python3 import os import re import sys import io # Matt Postiff, 2020 # Take one or more text files and build a character map from it # Usage: python3 charmap.py learn.txt script = sys.argv.pop(0) if len(sys.argv) < 1: print(f"Usage: {script} file [file ...]\n") exit(1) charDict = {} def charmap(txt:str): # Count all the different characters in a string for c in txt: cnt = charDict.get(c, 0) charDict[c] = cnt+1 DEBUG = 1 def debug(msg:str, lineEnd=''): if (DEBUG): print(msg) # end=lineEnd) def error(msg:str): print(f"ERROR: {msg}") for file in sys.argv: debug("Processing " + file) if os.path.isdir(file): error("Cannot process directory " + file + "\n") continue fi = open(file, mode="r", newline='') for cnt, line in enumerate(fi): charmap(line) fi.close() for c in charDict: # if (c == "\n"): # cToPrint = "\\n" # elif (c == "\r"): # cToPrint = "\\r" # elif (c == " "): # cToPrint = "<spc>" # else: cToPrint = c; print(f"'{cToPrint}' : '{charDict[c]}',") # The end
82ec9291da70de221fd92620027ab54aa2891e2a
telecode-paris/concours-plateforme
/subjects/Mediane/solve.py
360
3.625
4
# simplement un tri baquet pour trouver la médiane def mediane(): N = int(input()) numbers = [0 for _ in range(10001)] for _ in range(N): numbers[int(input())] += 1 acc = 0 for i, e in enumerate(numbers): acc += e if acc > N / 2: print(i) return if __name__ == "__main__": mediane()
d7c74b39b292878b4b4bf1afe030b8f406cc5872
KCCTdensan/ProCon2017-Solver
/Search/Figure.py
656
3.5
4
class Figure: _vertexes: list # 頂点を格納したリスト :: [(int, int)] _angles: list # 角度を格納したリスト :: [float] def __init__(self, vertexes: list): if len(vertexes) < 3: raise FigureError("二次元図形には頂点が最低3つあるはずなんだよなぁ...") self._vertexes = vertexes def new(vertexes: list): return Figure(vertexes) def getVertexes(self) -> list: return self._vertexes def getAngles(self) -> list: return self._angles class FigureError (Exception): _message: str def __init__(self, message: str): self._message = message def getMessage(self) -> str: return self._message
d8c6a762f5b45f4703f58ae8be41390378b1447e
PedroCapa/SDLE
/Trabalho/RandomGraph.py
2,834
3.578125
4
import networkx as nx import Node from random import randrange from enum import Enum class Types(Enum): """ Type of aggregation functions """ SUM = 0 AVERAGE = 1 COUNT = 2 class RandomGraph: """ Class used to generate a graph with random connections between the nodes until it's a completed graph Attributes ---------- size: int number of nodes graph: Graph the generated graph """ def __init__(self, size): """ Parameters ---------- size: int number of nodes """ self.size = size self.graph = nx.Graph() def create_graph(self): """ Create a new graph """ H = nx.path_graph(self.size) self.graph.add_nodes_from(H) def add_connection(self): """ Add connection to the graph between random nodes """ x = randrange(0, self.size) y = randrange(0, self.size) while y == x: y = randrange(0, self.size) e = (x, y) if not self.graph.has_edge(*e): self.graph.add_edge(*e) else: self.add_connection() def add_connections(self): """ Add connections to the graph until it's complete """ while not nx.is_connected(self.graph): self.add_connection() def multiple_times(self, n): """ Generate some random graphs Parameters ---------- n: int number of nodes to generate Return ---------- float the average of connections created """ res = 0 for _ in range(0, n): self.create_graph() self.add_connections() res = res + len(self.graph.edges) res = res / n return res def edges_dic(self, distance): """ Create a dictionary from the edges of the graph Parameters ---------- distance: int the value of each connection Return ---------- list the list of average connections created to each size of graph """ res = {} for edge in self.graph.edges: res[edge] = distance res[tuple((edge[1], edge[0]))] = distance return res def nodes_list(self): """ Create a list from the nodes of the graph Return ---------- list list of nodes """ res = [] for node in self.graph.nodes: neighbors = list(self.graph.neighbors(node)) n = Node.PushSumProtocol(neighbors, node, (0, 0), 1, list(self.graph.nodes)) res.append(n) return res
0b413fb9194572435f51b8b3ae5fa90f8c529668
tanyavasilkova/lesson3
/old_dz/dz4.vasilkova.py
10,052
3.59375
4
data_users = {} log_pass = {} def main(): print('Выберите действие:\n\ 1. Зарегистрироваться\n\ 2. Войти') deistvie = str(input('Введите 1 либо 2: ')) if deistvie == '1': loginpassword(); elif deistvie == '2': autint() elif deistvie != '1' or deistvie != '2': print('Вы ввели неверный символ!') return main() def loginpassword(): # регистрация log = str(input('Введите логин: ')) password = str(input('Введите пароль: ')) password2 = str(input('Повторите пароль: ')) if log not in log_pass.keys() and password != password2: # проверка паролей print('Пароли не совпадат. Повторите ввод:'), return loginpassword() if log in log_pass.keys(): # проверка на отсутствие логина print('Такой логин уже существует, введите иной'), return loginpassword() if log not in log_pass.keys() and password == password2: log_pass[log] = password; print('Вы успешно зарегистрированы. Вы вошли в систему. Меню:'), menu(); # проверка условий логин-пароль и вход в систему def autint(): # войти по логину и паролю log2 = str(input('Login: ')) password2 = str(input('Password: ')) if log2 not in log_pass.keys(): print('Ошибка! Введите верный логин либо зарегистрируйтесь!') return main() if password2 != log_pass[log2]: print('Логин и пароль не совпадают. Повторите попытку либо зарегистрируйтесь!'), return main() if password2 == log_pass[log2]: menu() def menu():# меню t = 0 while t != 5: print('Выберите действие из возможных вариантов:\n\ 1. Вывести список пользователей\n\ 2. Добавить пользователя\n\ 3. Удалить пользователя\n\ 4. Выбрать пользователя\n\ 5. Выход') t = str(input('Введите число: ')) if t == '1': viewusers(); # вывести список elif t == '2': adduser(); # добавить пользователя elif t == '3': deleteuser(); # удалить пользователя elif t == '4': selectuser(); # выбрать пользователя elif t == '5': print('Вы вышли из симтемы'), main()# выход на логин и пароль\регистрацию elif t !='1' or t != '2' or t != '3' or t != '4' or t != '5': print('Неверно! ВВедите число от 1 до 5'), return menu() def viewusers(): # посмотреть список пользователей print('Список пользователей:') for i in data_users.keys(): print(i) def adduser(): # добавитьимя с данными a = str(input('Введите Ваше Имя: ')) v = int(input('Введите Ваш возраст: ')) while v < 18: print('Данное определение BMI предназначено для лиц старше 18 лет. Введите число больше 18.') v = int(input('Введите Ваш возраст: ')) p = str(input("Если вы мужчина, укажите 'm', если женщина - 'w' ")) while p != 'm' and p != 'w': print('Неверный ввод!') p = str(input("Если вы мужчина, укажите 'm', если женщина - 'w' ")) r = float(input('Введите Ваш рост в сантиметрах: ')) m = float(input('Введите Ваш вес в килограммах: ')) description_bmi = bmi(a, v, p, r, m) #d = {a : {'Возраст': v,'Пол': p, 'Рост': r, 'Вес': m, 'BMI': description_bmi+'\n'}} #data_users.append(d) data_users[a] = {'Возраст': v,'Пол': p, 'Рост': r, 'Вес': m, 'BMI': description_bmi+'\n'} def deleteuser(): # удалить имя с данными print('Выберите из списка Имя для удаления и введите его:') viewusers() del_user = str(input('ВВедите имя: ')) data_users.pop(del_user) def selectuser(): # посмотреть данные с именем print('Выберите из списка имя и введите его:') viewusers() imya_data = str(input('Введите имя: ')) znach = data_users[imya_data] for key in znach:#data_users[imya_data]: print(key, znach[key]) def bmi(a, v, p, r, m): # функция bmi w = m / ((r ** 2) * 0.0001) w = float('{:.2f}'.format(w)) if (p == 'w' and (((18 <= v < 31) and (w <= 16)) or (v >= 31 and w <= 17))) or \ (p == 'm' and (((18 <= v < 31) and (w <= 18)) or (v >= 31 and w <= 19))): f = 'У вас наблюдается дифицит массы.\n\ Оптимальный вес в соотвествии с вашим полом, возр астом и ростом: 53.09-62.35 кг.\n\ Необходима коррекция питания.' elif (p == 'w' and (((18 <= v < 31) and (16 < w < 19.6)) or (v >= 31 and 17 < w < 20))) or \ (p == 'm' and (((18 <= v < 31) and (18 < w < 21.5)) or (v >= 31 and 19 < w < 22))): f = 'У вас наблюдается недостаочная масса тела.\n\ Оптимальный вес в соотвествии с вашим полом, возрастом и ростом: 53.09-62.35 кг.\n\ Увеличьте калорийность рациона.' elif (p == 'w' and (((18 <= v < 31) and (19.6 <= w < 23)) or (v >= 31 and 20 <= w < 23.9))) or \ (p == 'm' and (((18 <= v < 31) and (21, 6 <= w < 25)) or (v >= 31 and 22 <= w < 26))): f = 'У вас нормальный вес. Занимайтесь спортом и физической активностю,\n\ ешьте больше овощей и фруктов, придерживайтель правильного питания. Будьте здоровы!' elif (p == 'w' and (((18 <= v < 31) and (23 <= w < 27.6)) or (v >= 31 and 23.9 <= w < 28))) or \ (p == 'm' and (((18 <= v < 31) and (25 <= w < 29.6)) or (v >= 31 and 26 <= w < 30.1))): f = 'У вас избыточная масса тела.\n\ Оптимальный вес в соотвествии с вашим полом, возрастом и ростом: 53.09-62.35 кг.\n\ Скорректируйте свое питание: ограничьте потребление высококалорийных продуктов, увеличьте потребление\n\ низкокалорийных продуктов (все виды зелени и овощи), фруктов и ягод.' elif (p == 'w' and (((18 <= v < 31) and (w >= 27.6)) or (v >= 31 and w >= 28.1))) or \ (p == 'm' and (((18 <= v < 31) and (w >= 29.6)) or (v >= 31 and w >= 30.1))): f = 'У вас ожирение!\n\ Оптимальный вес в соотвествии с вашим полом, возрастом и ростом: 53.09-62.35 кг.\n\ Необходимо изменить образ жизни. Обратитесь к диетологу\n\ для правильного составления рациона питания и физических нагрузок!' b = '\n Данные рекомендации носят приблизительный характер и не являются врачебным диагнозом.\n\ Обратитесь к доктору за точным определением состояния здоровья и назначением лечения, если \n\ оно требуется. Расчет индекса масы тела в данном примере не подходит для спортсменов, беременных \n\ женщин, подростков и детей.' if p == 'w': u = 'Уважаемая'; elif p == 'm': u = 'Уважаемый ' print(u, a, '!', 'Ваш возраст (в годах):', v, 'Ваш рост:', r, 'см', 'Ваш BMI:', w, f, b) print('График BMI') if w < 20: print( '0 %(resh)s %(BMI_w)d %(resh)s %(number1)d %(prob)s %(number2)d %(star)s %(number3)d' % {"resh": "#" * 5, "BMI_w": w, "resh": "#" * 5, "number1": 20, "prob": "_" * 15, "number2": 35, "star": "*" * 10, "number3": 45}) if 20 <= w < 30: print( '0 %(resh)s %(number1)d %(prob)s %(BMI_w)d %(prob)s %(number2)d %(star)s %(number3)d %(defis)s' % { "resh": "#" * 10, "number1": 20, "prob": "_" * 5, "BMI_w": w, "prob": "_" * 5, "number2": 30, "star": "*" * 10, "number3": 40, "defis": "-" * 10}) if 30 <= w < 40: print( '0 %(resh)s %(number1)d %(prob)s %(number2)d %(star)s %(BMI_w)d %(star)s %(number3)d %(defis)s' % { "resh": "#" * 10, "number1": 20, "prob": "_" * 10, "number2": 30, "star": "*" * 5, "BMI_w": w, "star": "*" * 5, "number3": 40, "defis": "-" * 10}) if w >= 40: print( '0 %(resh)s %(number1)d %(prob)s %(number2)d %(star)s %(number3)d %(defis)s %(BMI_w)d %(defis)s' % { "resh": "#" * 10, "number1": 20, "prob": "_" * 10, "number2": 30, "star": "*" * 10, "number3": 40, "defis": "-" * 5, "BMI_w": w, "defis": "-" * 5}) return str('Ваш BMI: ' + str(w)) main()
547d496f47e4e975ce5fd82d5f23443b534a936b
MikeCalabro/euler-everywhere
/Py-Solutions/Problem-27-2.py
826
3.8125
4
# Looked at the forum for the template for this answer # Modified it to my typical format def isPrime(num): if num < 2: return False elif num ==2: return True else: return sum([i for i in range(1, int(num**0.5) + 1) if num % i == 0]) == 1 def prime_counter(a, b): n = 0 while True: if not isPrime(n**2 + a*n + b): break n += 1 return n def maxPrimeFinder(limit): b_list = [i for i in range(2,limit) if isPrime(i)] a_list = range(-1*limit+1,limit,2) max_count = 0 for a in a_list: for b in b_list: count = prime_counter(a,b) if count > max_count: max_a = a max_b = b max_count = count return [max_a, max_b, max_a*max_b, max_count] def main(): print(maxPrimeFinder(1000)) if __name__ == "__main__": main()
771ac8e31a9fead113a89e987980f08a4b3ffd4c
tb0700372/special-Python
/Demo/test_0001.py
964
4.0625
4
# 小易喜欢的单词具有以下特性: # # 1.单词每个字母都是大写字母 # 2.单词没有连续相等的字母 # 3.单词没有形如“xyxy”(这里的x,y指的都是字母,并且可以相同)这样的子序列,子序列可能不连续。 # # 例如: # 小易不喜欢"ABBA",因为这里有两个连续的'B' # 小易不喜欢"THETXH",因为这里包含子序列"THTH" # 小易不喜欢"ABACADA",因为这里包含子序列"AAAA" # 小易喜欢"A","ABA"和"ABCBA"这些单词 # # 给你一个单词,你要回答小易是否会喜欢这个单词 import re if __name__ == "__main__": # 正则 re_1 = re.compile(r"[^A-Z]+") re_2 = re.compile(r"([A-Z])\1") re_3 = re.compile(r"([A-Z])[A-Z]*([A-Z])[A-Z]*\1[A-Z]*\2") # 输入 abc = input('输入单词:') # 判断 if re_1.search(abc) or re_2.search(abc) or re_3.search(abc): print("小明不喜欢") else: print("小明喜欢")
fec082441c46ff7d67cc0dd4df8c35bb45447e5f
jeyendhran/pythonLTT
/src/assessment_3.py
681
3.8125
4
INVALID_NEXT_IP = '255.255.255.255' def nextip(ipaddr): '''To find next possible IP address available''' # if the input IP is max IP then no addr other that it if ipaddr == INVALID_NEXT_IP: return "No more IP address available" ip = ipaddr.split(".") # convert the string list to int list ip = list(map(lambda x:int(x),ip)) ip[3]+= 1 # reverse the list for i in range(len(ip)-1,0,-1): if ip[i] > 255: ip[i-1] += 1 ip[i] = 0 # convert int list to a string nextipaddr = '.'.join(str(i) for i in ip) return nextipaddr myip = "255.252.255.255" print("Next IP address available is",nextip(myip))
1e2953ae5ca9a1fb08f637baca6e2164ac99d09f
jasonaibrahim/AcademicWorks
/Hog/hog.py
19,014
3.921875
4
"""The Game of Hog""" from math import * from dice import four_sided_dice, six_sided_dice, make_test_dice from ucb import main, trace, log_current_line, interact goal = 100 # The goal of Hog is to score 100 points. commentary = False # Whether to display commentary for every roll. # Taking turns def roll_dice(num_rolls, dice=six_sided_dice, who='Boss Hogg'): """Calculate WHO's turn score after rolling DICE for NUM_ROLLS times. num_rolls: The number of dice rolls that will be made; at least 1. dice: A function of no args and returns an integer outcome. who: Name of the current player, for commentary. """ roll_total = 0 got_a_one = False assert type(num_rolls) == int, 'num_rolls must be an integer.' assert num_rolls > 0, 'Must roll at least once.' for x in range (0,num_rolls): a = dice() if commentary: announce(a,who) if a == 1: got_a_one = True else: roll_total += a if got_a_one: return 1 else: return roll_total # Write your own prime functions here! def is_prime(a): return a in primes() def primes(): return (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101) def next_prime(a): for p in primes(): if p > a: return p # End prime functions here def take_turn(num_rolls, opponent_score, dice=six_sided_dice, who='Boss Hogg'): """Simulate a turn in which WHO chooses to roll NUM_ROLLS, perhaps 0. num_rolls: The number of dice rolls that will be made. opponent_score: The total score of the opponent. dice: A function of no args and returns an integer outcome. who: Name of the current player, for commentary. """ assert type(num_rolls) == int, 'num_rolls must be an integer.' assert num_rolls >= 0, 'Cannot roll a negative number of dice.' if commentary: print(who, 'is going to roll', num_rolls, 'dice') #Turn score turn_score = 0 def free_bacon(opponent_score): return (opponent_score // 10 + 1) if (opponent_score >= 10) else 1 #Roll the dice, keep track of the score, enforce free bacon rule if num_rolls == 0: turn_score = free_bacon(opponent_score) else: turn_score = roll_dice(num_rolls,dice,who) #Rules #Touchdown if turn_score % 6 == 0: turn_score += turn_score//6 #Hogtimus Prime if is_prime(turn_score): turn_score = next_prime(turn_score) return turn_score def take_turn_test(): """Test the roll_dice and take_turn functions using test dice.""" print('-- Testing roll_dice --') dice = make_test_dice(4, 6, 1) assert roll_dice(2, dice) == 10, 'First two rolls total 10' dice = make_test_dice(4, 6, 1) assert roll_dice(3, dice) == 1, 'Third roll is a 1' dice = make_test_dice(1, 2, 3) assert roll_dice(3, dice) == 1, 'First roll is a 1' print('-- Testing take_turn --') dice = make_test_dice(4, 6, 1) assert take_turn(2, 0, dice) == 10, 'First two rolls total 10' dice = make_test_dice(4, 6, 1) assert take_turn(3, 20, dice) == 1, 'Third roll is a 1' print('---- Testing Free Bacon rule ----') assert take_turn(0, 34) == 4, 'Opponent score 10s digit is 3' assert take_turn(0, 71) == 8, 'Opponent score 10s digit is 7' assert take_turn(0, 7) == 1, 'Opponont score 10s digit is 0' print('---- Testing Touchdown rule ----') dice = make_test_dice(6) assert take_turn(2, 0, dice) == 14, 'Original score was 12' assert take_turn(3, 0, dice) == 21, 'Original score was 18' print('---- Testing Hogtimus Prime rule ----') dice = make_test_dice(5, 6, 5, 2) assert take_turn(0, 42, dice) == 7, 'Opponent score 10s digit is 4' assert take_turn(2, 0, dice) == 13, 'Original score was 11' assert take_turn(0, 52, dice) == 11, 'Opponent score 10s digit is 5' assert take_turn(2, 0, dice) == 11, 'Original score was 7' print('Tests for roll_dice and take_turn passed.') '*** You may add more tests here if you wish ***' # Commentator def announce(outcome, who): """Print a description of WHO rolling OUTCOME.""" print(who, 'rolled a', outcome) print(draw_number(outcome)) def draw_number(n, dot='*'): """Return a text representation of rolling the number N. If a number has multiple possible representations (such as 2 and 3), any valid representation is acceptable. >>> print(draw_number(3)) ------- | * | | * | | * | ------- >>> print(draw_number(5)) ------- | * * | | * | | * * | ------- >>> print(draw_number(6, '$')) ------- | $ $ | | $ $ | | $ $ | ------- """ if n == 1: return draw_dice(1,0,0,0,dot) elif n == 2: return draw_dice(0,1,0,0,dot) elif n == 3: return draw_dice(1,1,0,0,dot) elif n == 4: return draw_dice(0,1,1,0,dot) elif n == 5: return draw_dice(1,1,1,0,dot) elif n == 6: return draw_dice(0,1,1,1,dot) else: return '' def draw_dice(c, f, b, s, dot): """Return an ASCII art representation of a die roll. c, f, b, & s are boolean arguments. This function returns a multi-line string of the following form, where the letters in the diagram are either filled if the corresponding argument is true, or empty if it is false. ------- | b f | | s c s | | f b | ------- The sides with 2 and 3 dots have 2 possible depictions due to rotation. Either representation is acceptable. This function uses Python syntax not yet covered in the course. c, f, b, s -- booleans; whether to place dots in corresponding positions. dot -- A length-one string to use for a dot. """ assert len(dot) == 1, 'Dot must be a single symbol' border = ' -------' def draw(b): return dot if b else ' ' c, f, b, s = map(draw, [c, f, b, s]) top = ' '.join(['|', b, ' ', f, '|']) middle = ' '.join(['|', s, c, s, '|']) bottom = ' '.join(['|', f, ' ', b, '|']) return '\n'.join([border, top, middle, bottom, border]) # Game simulator def num_allowed_dice(score, opponent_score): """Return the maximum number of dice allowed this turn. The maximum number of dice allowed is 10 unless the sum of SCORE and OPPONENT_SCORE has a 7 as its ones digit. >>> num_allowed_dice(1, 0) 10 >>> num_allowed_dice(5, 7) 10 >>> num_allowed_dice(7, 10) 1 >>> num_allowed_dice(13, 24) 1 """ return 1 if ( (opponent_score+score == 7) or (opponent_score+score) % 10 == 7 ) else 10 def select_dice(score, opponent_score): """Select 6-sided dice unless the sum of scores is a multiple of 7. >>> select_dice(4, 24) == four_sided_dice True >>> select_dice(16, 64) == six_sided_dice True """ return four_sided_dice if (opponent_score + score) % 7 == 0 else six_sided_dice def other(who): """Return the other player, for players numbered 0 or 1. >>> other(0) 1 >>> other(1) 0 """ return 1 - who def name(who): """Return the name of player WHO, for player numbered 0 or 1.""" if who == 0: return 'Player 0' elif who == 1: return 'Player 1' else: return 'An unknown player' def play(strategy0, strategy1): """Simulate a game and return 0 if the first player wins and 1 otherwise. A strategy function takes two scores for the current and opposing players. It returns the number of dice that the current player will roll this turn. If a strategy returns more than the maximum allowed dice for a turn, then the maximum allowed is rolled instead. strategy0: The strategy function for player 0, who plays first. strategy1: The strategy function for player 1, who plays second. """ who = 0 # Which player is about to take a turn, 0 (first) or 1 (second) score0 = 0 score1 = 0 while ((score0 < 100) and (score1 < 100)): if who == 0: x = strategy0(score0,score1) a = num_allowed_dice(score0,score1) if x > 10: score0 += take_turn(a, score1, select_dice(score0,score1), name(who)) elif a == 1 and x >= 1: score0 += take_turn(1, score1, select_dice(score0,score1), name(who)) elif a == 1 and x == 0: score0 += take_turn(0, score1, select_dice(score0,score1), name(who)) else: score0 += take_turn(x, score1, select_dice(score0,score1), name(who)) who = 1 else: y = strategy1(score1,score0) b = num_allowed_dice(score1,score0) if y > 10: score1 += take_turn(b, score0, select_dice(score1,score0), name(who)) elif b == 1 and y >= 1: score1 += take_turn(1, score0, select_dice(score1,score0), name(who)) elif b == 1 and y == 0: score1 += take_turn(0, score0, select_dice(score1,score0), name(who)) else: score1 += take_turn(y, score0, select_dice(score1,score0), name(who)) who = 0 if (score0 > score1): return 0 else: return 1 # Basic Strategy def always_roll(n): """Return a strategy that always rolls N dice. A strategy is a function that takes two game scores as arguments (the current player's score, and the opponent's score), and returns a number of dice to roll. If a strategy returns more than the maximum allowed dice for a turn, then the maximum allowed is rolled instead. >>> strategy = always_roll(5) >>> strategy(0, 0) 5 >>> strategy(99, 99) 5 """ def strategy(score, opponent_score): return n return strategy # Experiments (Phase 2) def make_average(fn, num_samples=100): """Return a function that returns the average_value of FN when called. To implement this function, you will have to use *args syntax, a new Python feature introduced in this project. See the project description. >>> dice = make_test_dice(3, 1, 5, 6) >>> avg_dice = make_average(dice, 100) >>> avg_dice() 3.75 >>> avg_score = make_average(roll_dice, 100) >>> avg_score(2, dice) 6.0 In this last example, two different turn scenarios are averaged. - In the first, the player rolls a 3 then a 1, receiving a score of 1. - In the other, the player rolls a 5 and 6, scoring 11. Thus, the average value is 6.0. """ def avg_fn(*args): i = 0 for x in range (0,num_samples): i += fn(*args) return i/num_samples return avg_fn def compare_strategies(strategy, baseline=always_roll(5)): """Return the average win rate (out of 1) of STRATEGY against BASELINE.""" as_first = 1 - make_average(play)(strategy, baseline) as_second = make_average(play)(baseline, strategy) return (as_first + as_second) / 2 # Average the two results def eval_strategy_range(make_strategy, lower_bound, upper_bound): """Return the best integer argument value for MAKE_STRATEGY to use against the always-roll-5 baseline, between LOWER_BOUND and UPPER_BOUND (inclusive). make_strategy -- A one-argument function that returns a strategy. lower_bound -- lower bound of the evaluation range. upper_bound -- upper bound of the evaluation range. """ best_value, best_win_rate = 0, 0 value = lower_bound while value <= upper_bound: strategy = make_strategy(value) win_rate = compare_strategies(strategy) print('Win rate against the baseline using', value, 'value:', win_rate) if win_rate > best_win_rate: best_win_rate, best_value = win_rate, value value += 1 return best_value def run_experiments(): """Run a series of strategy experiments and report results.""" if False: # Change to False when done testing always_roll result = eval_strategy_range(always_roll, 1, 10) print('Best always_roll strategy:', result) if False: # Change to True when ready to test make_comeback_strategy result = eval_strategy_range(make_comeback_strategy, 5, 15) print('Best comeback strategy:', result) if True: # Change to True when ready to test make_mean_strategy result = eval_strategy_range(make_mean_strategy, 1, 10) print('Best mean strategy:', result) "*** You may add additional experiments here if you wish ***" # Strategies def make_comeback_strategy(margin, num_rolls=5): """Return a strategy that rolls one extra time when losing by MARGIN.""" def s1(score,opponent_score): if ((opponent_score - score) >= margin): return num_rolls+1 else: return num_rolls return s1 def make_mean_strategy(min_points, num_rolls=5): """Return a strategy that attempts to give the opponent problems.""" def s2(score,opponent_score): x = take_turn(0,opponent_score) y = select_dice(x+score,opponent_score) z = num_allowed_dice(x+score,opponent_score) if (x >= min_points and (y == four_sided_dice or z == 1)): return 0 else: return num_rolls return s2 def final_strategy(score, opponent_score): """Write a brief description of your final strategy. First we compute the expected values of rolling up to 10 four sided or six sided dice and enter them into an array whose index refers to the number of dice rolled. The maximum of the expected scores is the default number of dice to roll. For certain circumstances, we apply strategies that enable us to use the special rules to our advantage. We roll zero dice if the result of rolling zero allows us to reach the goal, or if we are in the lead and rolling zero dice gives a competitive advantage by using the rules against the opponent. We apply the same procedure if the points scored from rolling zero dice is greater than a margin of 5 points. This value was taken from trials on make_mean_strategy and finding the margin with the highest win rate. If the opponent is in the lead, and the current player is about to roll a four sided dice, then a 3 is returned, since rolling a higher number of four sided dice has a higher probability of rolling a 1. Otherwise if the opponent is in the lead by a certain margin, the current player rolls 8 dice. This value is the highest acceptable risk, since the probability of not rolling a 1 with any number of rolls higher is very small. If the current player is in the lead, then the current player rolls 3 dice, so as not to take more risks than necessary. For all other situations, we roll the default. """ def E(n): """ Returns the expected score (without special rules applied) for rolling N six sided die """ return pow((5/6),n)*4*n def E_4(n): """ Returns the expected score (without special rules applied) for rolling N four sided die """ return pow((3/4),n)*3*n expected_scores = [] # array of expected values of scores. index refers to number of dice rolled d = select_dice(score,opponent_score) # which dice the current player will roll x = take_turn(0,opponent_score) # the points scored if the current player rolls 0 dice y = select_dice(x+score,opponent_score) # the dice the opponent must use if the current player rolls 0 dice z = num_allowed_dice(x+score,opponent_score) # the number of allowed dice the opponent will be allowed if the current player rolls 0 dice expected_scores.append(x) # simulate value of rolling zero dice and insert as first element of array # Fill in array of expected values for i in range(1,11): if d == six_sided_dice: expected_scores.append(floor(E(i))) else: expected_scores.append(floor(E_4(i))) m = max(expected_scores) # Find the maximum of the expected scores. if (x >= goal-score) or ((abs(score - opponent_score) < 12) and (y == four_sided_dice or z == 1)): return 0 elif ((x >= 5) and (y == four_sided_dice or z == 1)): return 0 elif ((opponent_score - score) >= 20) and (d == four_sided_dice): return 3 elif (opponent_score - score) >= 20: return 8 elif (score - opponent_score) >= 20: return 3 else: return expected_scores.index(m) # Return the index of the maximum expected score. def final_strategy_test(): """Compares final strategy to the baseline strategy.""" print('-- Testing final_strategy --') print('Win rate:', compare_strategies(final_strategy)) # Interaction. You don't need to read this section of the program. def interactive_strategy(score, opponent_score): """Prints total game scores and returns an interactive tactic. This function uses Python syntax/techniques not yet covered in this course. """ print('Current score:', score, 'to', opponent_score) while True: response = input('How many dice will you roll? ') try: result = int(response) except ValueError: print('Please enter a positive number') continue if result < 0: print('Please enter a non-negative number') else: return result def play_interactively(): """Play one interactive game.""" global commentary commentary = True print("Shall we play a game?") winner = play(interactive_strategy, always_roll(5)) if winner == 0: print("You win!") else: print("The computer won.") def play_basic(): """Play one game in which two basic strategies compete.""" global commentary commentary = True winner = play(always_roll(5), always_roll(6)) if winner == 0: print("Player 0, who always wants to roll 5, won.") else: print("Player 1, who always wants to roll 6, won.") @main def run(*args): """Read in the command-line argument and calls corresponding functions. This function uses Python syntax/techniques not yet covered in this course. """ import argparse parser = argparse.ArgumentParser(description="Play Hog") parser.add_argument('--take_turn_test', '-t', action='store_true') parser.add_argument('--play_interactively', '-p', action='store_true') parser.add_argument('--play_basic', '-b', action='store_true') parser.add_argument('--run_experiments', '-r', action='store_true') parser.add_argument('--final_strategy_test', '-f', action='store_true') args = parser.parse_args() for name, execute in args.__dict__.items(): if execute: globals()[name]()
e88eabdc52b8e1ead5e42fa45cd47afa049bf6b7
AnenaVictoriaSims/DataMiningLab1
/kmean.py
1,345
3.515625
4
#Anena Sims 1001138287 #Lab 1 import numpy as np import matplotlib.pyplot as plt import random import math #Randomly generate 2 sets of Gaussian data containing 500 samples using given parameters def genGauss2D(mean, cov, numSamples): x, y = np.random.multivariate_normal(mean, cov, numSamples).T return(x, y) #Cluster the data #Print graph data for problem 1 def printGraphData(set1, set2): #plt.plot(x, y, '*') # This is displayed in blue #plt.plot(a, b, '*') # This is displayed in orange #plt.axis('equal') #plt.show() plt.plot(set1[:,0], set1[:,1], '.') plt.plot(set2[:,0], set2[:,1], '.') #Properties for problem 1 & 2 given by the professor numSamples = 500 mean1 = np.array([1, 0]) #Problem 1 first mean property mean2 = np.array([0, 1.5]) #Problem 1 second mean property cov = np.array([[0.9, 0.4], [0.4, 0.9]]) #Probelm 1 diagonal covariance. cov1 & cov2 are the same #x, y = genGauss2D(mean1, cov, numSamples) set1 = genGauss2D(mean1, cov, numSamples) #a, b = genGauss2D(mean2, cov, numSamples) set2 = genGauss2D(mean2, cov, numSamples) printGraphData(set1, set2) print("Set One: ", set1) print("Set Two: ", set2)
b4461b175e2bdd16c2f620ff1c69f5a71fc4d439
aminelfc96/Anagram-Finder
/anagram_finder.py
881
3.890625
4
mon_dict = input("entrer l'emplacement du fichier : ") if len(mon_dict) == 0: mon_dict = './dico-fr.txt' # Juste pour cet exercice else: pass mot_pour_chercher_anagramme = input("entrer le mot pour chercher l'anagramme : ") __mot_pour_chercher_anagramme__ = list(mot_pour_chercher_anagramme.lower()) __mot_pour_chercher_anagramme__.sort() def chercheur_anagramme(): with open(mon_dict,'r') as dictionnaire: mots = dictionnaire.readlines() print("Tout les anagrammes du mot",mot_pour_chercher_anagramme,"sont :") for mot in mots: mot = mot.strip("\n") __mot__ = list(mot.lower()) __mot__.sort() if __mot_pour_chercher_anagramme__ == __mot__ : if mot == mot_pour_chercher_anagramme.lower(): pass else: print(mot) else: pass chercheur_anagramme()
225353f8a44e9ee41926c52b3e2280d0359266bf
tobyzhu/genesis-backend
/learnpython.py
139
3.53125
4
import math testlist=[1,2,3,4,5,6,7,'abd','hadsa'] for i in testlist: print(i) testlist[2] = 'asdfa' for i in testlist: print(i)
3cb05e8256254b55415a6ac8df7228797fd5998b
varshakabadi/GitDemo
/slicebackwards.py
117
3.65625
4
Letters= "abcdefghijklmnopqrstuvwxyz" backward=Letters[25::-1] print(backward) backward=Letters[::-1] print(backward)
65b5e38ccd05c00f0ec700ad986342db417880d6
vpalat/1073iOSExample
/Hardway/GameExample/21BlackJack.py
1,328
3.515625
4
import Deck import Hand cards = Deck.Deck() def showHands(): print "Dealer's Hand:" dealer.showHand() print "\nPlayer's Hand:" player.showHand() def findWinner(player, dealer): ptotal = player.total() dtotal = dealer.total() print "Player: ", ptotal print "Dealer: ", dtotal if ptotal > 21: print "Player busts. House wins." elif dtotal >21: print "House busts. Player wins." elif dtotal >= ptotal: print "House wins." else: print "Player wins!" #cards.display() cards.shuffle() dealer = Hand.Hand() player = Hand.Hand() dealer.addCard(cards.dealACard()) dealer.addCard(cards.dealACard()) player.addCard(cards.dealACard()) player.addCard(cards.dealACard()) showHands() player.total() playerOn = True dealerOn = True while playerOn or dealerOn: print "hit (h) or stay (s)" choice = raw_input("> ") if dealer.total() < 15 and dealerOn: dealer.addCard(cards.dealACard()) if dealer.total() > 21: dealerOn = False else: dealerOn = False if choice =='h': player.addCard(cards.dealACard()) if player.total() > 21: playerOn = False if choice =='s': print "Player stays." playerOn = False showHands() findWinner(player, dealer)
4e1c103337326d20a162044c028ede8f3f9fbae5
Esty-Hirshman/pokemon-project
/ex_2.py
409
3.6875
4
from config import connection def find_by_type(type): """ returns all of the pokemon names with given type """ with connection.cursor() as cursor: query = "SELECT name FROM pokemon WHERE type = %s" cursor.execute(query,type) result = cursor.fetchall() return [pokemon["name"] for pokemon in result] if __name__ == '__main__': print(find_by_type("grass"))
b95f3d00dba68e1113e6697bdbe5286c228510e7
ngthnam/Python
/Python Basics/19_Reading_CSV.py
332
3.984375
4
import csv with open('.\samplefiles\example.csv') as csvfile: # 'With' is used to take care of two simultaneous process, Open() and Close() readcsv = csv.reader(csvfile,delimiter=',') fruit = input('Enter a fruit to get its color: ') for row in readcsv: if row[0]==fruit: print(row[1].upper())
c8c3415de3c38ebc2281996afa28313faa6055ee
subsid/sandbox
/algos/sliding_window/non_repeat_substring.py
872
4.15625
4
# Given a string, find the length of the longest substring, which has no repeating characters. def non_repeat_substring(input_str): curr_chars = set() window_start = 0 longest = 0 curr_len = 0 for j in range(len(input_str)): c = input_str[j] if c not in curr_chars: curr_len += 1 longest = max(curr_len, longest) curr_chars.add(c) else: while (c in curr_chars): curr_chars.remove(input_str[window_start]) curr_len -= 1 window_start += 1 curr_chars.add(c) curr_len += 1 longest = max(curr_len, longest) return longest if __name__ == "__main__": assert(non_repeat_substring("aabccbb") == 3) assert(non_repeat_substring("abbbb") == 2) assert(non_repeat_substring("abccde") == 3)
6cdb3949f6efdef6ef6da2df022f5e39284abe7d
za3k/short-programs
/quiz
754
3.796875
4
#!/bin/python3 """ Usage: quiz FILE.csv Interactively prompt the user to fill out a questionnaire. Reads the questions and writes the results to a CSV. Intended use is for daily, weekly, etc logging of something. """ import csv, io, readline, subprocess, sys if __name__ == '__main__': if len(sys.argv) != 2: print("Usage: quiz FILE.csv") with open(sys.argv[1], 'r+', newline='') as csvfile: reader = csv.reader(csvfile) lines = list(reader) headers = lines[0] subprocess.run("tail -n 5 " + sys.argv[1] + " | csvunpipe", shell=True) entry = [input(question + " ? ") for question in headers] csvfile.seek(0, io.SEEK_END) csv.writer(csvfile).writerow(entry) print("Done.")
072414f6608077fd6c5c0aa6bcda1b90357bfdb6
florlema222/python-random-quote
/listatp.py
2,421
4.15625
4
''' Cree una lista con los siguientes elementos: conex=[ "127.0.0.1","root","123456","nomina"] a) Escriba un programa que imprima todos los elementos de la lista y la longitud total de la lista conex b) Escriba un programa que imprima los elementos ordenados de la lista. (presentación c) cree otra lista con los elementos en orden inverso (desde el último al 1ero) d) Encuentre el elemento “root” de la lista y contar cuantos hay? ''' '''''' # conex=["127.0.0.1" , "root" , "root" ,"123456", "nomina"] # print(conex) # print("Cantidad de elementos de la lista: " , len(conex)) # print(sorted(conex)) # listaNueva=[] # for i in reversed(conex): # listaNueva.append(i) # print(listaNueva) # cant=0 # for i in conex: # if i=="root": # cant+=1 # print('''Cantidad de veces que aparece el string "root": ''', cant) ''' a) cree una lista con los 4 nombres de usuarios del sistema “xxxx” b) muestre todos los nombres de usuarios. c) cree una nueva lista con: la lista ordenada, la lista invertida (del último al primero), los dos últimos elementos, los dos primeros elementos d) agregue un usuario más, y que ese nombre lo ingrese desde el teclado e) arme una función que le permita agregar usuarios a su lista. f) arme una función que le permita buscar un usuario en su lista. ''' def agregar(xxxx): agregNom=str(input("Ingrese el nombre a agregar: ")) xxxx.append(agregNom) return xxxx def buscar(xxxx): buscarNom=str(input("Ingrese el nombre a buscar: ")) buscarNom=buscarNom.capitalize() if buscarNom in xxxx: print("El nombre está en la lista") else: print("El nombre no se encuentra en la lista") xxxx=["Flor","Juan","Marce","Noe"] print("Los nombres de los usuarios son:") print(xxxx[0],"\n",xxxx[1],"\n",xxxx[2],"\n",xxxx[3]) nuevaLista=[] for i in (xxxx): nuevaLista.append(i) for i in reversed(xxxx): nuevaLista.append(i) for i in (xxxx[2:4]): nuevaLista.append(i) for i in (xxxx[0:2]): nuevaLista.append(i) print(nuevaLista) print(nuevaLista.index("Juan")) #muestra posicion del elemento exit=0 while exit==0: print("Para agregar un nombre ingrese 1, para buscar un nombre ingrese 2, para salir ingrese 3") opc=int(input("Ingrese una opcion: ")) if opc==1: agregar(xxxx) elif opc==2: buscar(xxxx) elif opc==3: exit+=1 else: print("Opción incorrecta")
c276065914aef65b69a3dd699a3c68433c997d61
novarac23/learn-python-the-hard-way
/ex32.py
415
3.921875
4
the_count = [1, 2, 3, 4, 5] fruits = ["apples", "oranges", "pears", "appricots"] change = [1, "pennies", 2, "dimes", 3, "quarters"] for number in the_count: print(f"this is for {number}") for fruit in fruits: print(f"this is for {fruit}") for i in change: print(f"tjis is a {i}") elements = [] for i in range(0, 10): elements.append(i) for element in elements: print(f"element {element}")
2ff5489304b31f1c74eebf12bb4d38d879789174
dkbarcla/variance
/final/models.py
8,030
3.828125
4
import random as rd from constants import * class Card: def __init__ (self, rank, suit): '''Implement a card with a rank and suit.''' self.rank = rank self.suit = suit self.ranking = list(RANKS.keys())[list(RANKS.values()).index(self.rank)] # checks if card is a valid card, raises error if not if not self.is_valid(): raise ValueError('Error: card object could not be instantiated; invalid rank or suit') self.value = self.ranking def __repr__(self): '''Returns the cards value.''' card_name = self.rank + self.suit return(card_name) def is_valid(self): '''Checks if rank and suit are valid.''' if self.rank in RANKS.values(): if self.suit in SUITS.values(): return(True) return(False) class HoleCards: def __init__(self, rank1, rank2, suit1, suit2): ''' Implements two hole cards.''' self.cards = [] # setting ranks and suits self.rank1 = rank1 self.rank2 = rank2 self.suit1 = suit1 self.suit2 = suit2 # creating cards from ranks and suits self.card1 = Card(rank1, suit1) self.card2 = Card(rank2, suit2) self.cards.append(self.card1) self.cards.append(self.card2) # creating rankings of each card from key values self.ranking1 = list(RANKS.keys())[list(RANKS.values()).index(self.rank1)] self.ranking2 = list(RANKS.keys())[list(RANKS.values()).index(self.rank2)] # checking if valid hole card if not self.is_valid(): raise ValueError('Error: hand object could not be instantiated, invalid rank or combo') self.value = self.value() def __repr__(self): '''Returns the value of the hand.''' hole_list = self.cards cards_string = ' '.join(str(card) for card in hole_list) return(cards_string) def is_valid(self): '''Checks if both ranks and combo are valid.''' if self.rank1 in RANKS.values(): if self.suit1 in SUITS.values(): if self.rank2 in RANKS.values(): if self.suit2 in SUITS.values(): return(True) return(False) def value(self): '''Evaluates both cards and determines a value for the hole cards''' if self.ranking1 > self.ranking2: if self.suit1 == self.suit2: # Adding the combo ranking here as suited cards are higher value than unsuited (check COMBOS list) return(self.ranking1 + 1) else: return(self.ranking1) if self.ranking2 > self.ranking1: # If the second card is larger than second card, switch their positions (poker convention) temp1 = self.rank2 self.rank2 = self.rank1 self.rank1 = temp1 temp2 = self.suit2 self.suit2 = self.suit1 self.suit1 = temp2 if self.suit1 == self.suit2: return(self.ranking2 + 1) else: return(self.ranking2) if self.ranking1 == self.ranking2: # Add 13 here if a pair so that the value will always be larger than any non-paired hand return(self.ranking1 + 41) # this is unused at the moment, but will be good for downstream use class Hand: def __init__(self, rank1, rank2, combo): ''' Implement a hand of two cards.''' self.rank1 = rank1 self.rank2 = rank2 self.combo = combo self.ranking1 = list(RANKS.keys())[list(RANKS.values()).index(self.rank1)] self.ranking2 = list(RANKS.keys())[list(RANKS.values()).index(self.rank2)] self.rankingC = list(COMBOS.keys())[list(COMBOS.values()).index(self.combo)] if not self.is_valid(): raise ValueError('Error: hand object could not be instantiated, invalid rank or combo') self.value = self.value() self.is_pair() def __repr__(self): '''Returns the value of the hand.''' hand_name = self.rank1 + self.rank2 + self.combo return(hand_name) def is_valid(self): '''Checks if both ranks and combo are valid.''' if self.rank1 in RANKS.values(): if self.rank2 in RANKS.values(): if self.combo in COMBOS.values(): return(True) return(False) def is_pair(self): '''Checks if cards are a pair.''' if self.rank1 == self.rank2: self.combo = '' def value(self): '''Checks each card's value and returns the higher value.''' if self.ranking1 > self.ranking2: # Adding the combo ranking here as suited cards are higher value than unsuited (check COMBOS list) return(self.ranking1 + self.rankingC) if self.ranking2 > self.ranking1: # If the second card is larger than second card, switch their positions (poker convention) temp = self.rank2 self.rank2 = self.rank1 self.rank1 = temp return(self.ranking2 + self.rankingC) if self.ranking1 == self.ranking2: # Add 13 here if a pair so that the value will always be larger than any non-paired hand return(self.ranking1 + 42) # this comparison is shit, hands are equal if suited cards have +1 added class Deck: def __init__(self): '''Implement a deck of cards''' self.deck = [] for suit in SUITS: for rank in RANKS: ranks = RANKS[rank] suits = SUITS[suit] new_card = Card(ranks, suits) self.deck.append(new_card) def __repr__(self): '''Returns the cards in the deck''' deck_list = self.deck deck_string = ''.join(str(card) for card in deck_list) return(deck_string) def forDisplay(self): '''Inverted implementation of a deck of cards''' self.deck = [] for rank in RANKS: for suit in SUITS: ranks = RANKS[rank] suits = SUITS[suit] new_card = Card(ranks, suits) self.deck.append(new_card) class Board: def __init__(self, passed_board, *args): '''Implement a new board''' # reads in cards from user into board object self.board = [] for card in range(len(passed_board)): self.board.append(passed_board[card]) def __repr__(self): '''Returns the string of the board.''' board_list = self.board board_string = ' '.join(str(card) for card in board_list) return(board_string) class random: def randomCard(self, deck): '''Define a random card''' new_card = deck[rd.randint(0, len(deck)-1)] # required that you remove the card from the deck so as to not get repeats deck.remove(new_card) return(new_card) def randomHoleCards(self, deck): '''Define two random holecards''' first_card = self.randomCard(deck) second_card = self.randomCard(deck) rank1 = first_card.rank rank2 = second_card.rank suit1 = first_card.suit suit2 = second_card.suit hole_cards = HoleCards(rank1, rank2, suit1, suit2) return(hole_cards) def randomHand(self, deck): '''Define a random hand''' # Pick a card from the deck and remove it first_card = self.randomCard(deck) # Pick a second card from the deck ands remove it second_card = self.randomCard(deck) # Call ranks for each card first_rank = first_card.rank second_rank = second_card.rank # Check if cards are suited or unsuited if first_card.suit == second_card.suit: combo = COMBOS[1] else: combo = COMBOS[0] # Return the hand return(Hand(first_rank, second_rank, combo))
34169b70be4b480ac31189611626955ef75d9bc8
codemossaka/searchAlgorithms
/methods.py
7,190
3.78125
4
import collections class search: def __init__(self): pass def dfs(self, graph, start, target, visited=None): if visited is None: # проверяем пустоту посешенный ход visited = set() # инициализируем неповторяемый массив посещаемых ходов if self.isTarget(start, target): print('Цель достигнута') return [] else: print('Цель не достигнута') visited.add(start) # добовляем вершину # print(start, end=" ") # отображаем ее for move in graph.getMoves(start): # цикл чтобы поторялось действие node = move['node'] if node in visited: continue path = self.dfs(graph, node, target, visited) # вызываем функцию опять (рекурсивная функцию) if path is not None: return [move['direction']] + path return None def isTarget(self,node, target): return node == target def bfs(self, graph, start, target): # Track the visited and unvisited nodes using queue seen, queue = set([start]), collections.deque([start]) #инициализируем path = {start: []} while queue: #проходим пока перемение не пустое vertex = queue.popleft() #убовляем с лево в перемение for move in graph.getMoves(vertex): node = move['node'] if node not in seen: seen.add(node) queue.append(node) path[node] = path[vertex] + [move['direction']] return path[target] # def bfst(self, graph, start, target): # def get_path(vertex): # curr_vertex = vertex # parents_data_list = collections.deque([vertex['node']]) # while curr_vertex.parent: # curr_vertex = curr_vertex.parent # parents_data_list.appendleft(curr_vertex['node']) # print(list(parents_data_list)) # return list(parents_data_list) # Vertex = collections.namedtuple('Vertex', ['node', 'parent']) # queue = collections.deque([Vertex(start, None)]) # инициализируем # while True: # vertex = queue.popleft() # убовляем с лево в перемение # for move in graph.getMoves(vertex['node']): # next_vertex = Vertex(move['node'], vertex) # if next_vertex['node'] == target: # return get_path(next_vertex) # queue.append(next_vertex) def equalCosts(self, graph, start, target): seen, queue = {start: 0}, collections.deque([start]) #seen - массив просмотренных вершин (ключ: наименование вершины, значение: наилучшая длина пути), queue - очередь смежных вершин path = {start: []} #path - массив для каждой вершины где содержится наилучший путь while queue: vertex = queue.popleft() #извлекаем очередную вершину из очереди for move in graph.getMoves(vertex): pathLength = seen[vertex]+1 # длина пути в вершину node через вершину vertex node = move['node'] if node not in seen: # добаляем вершину в очередь если она еще не была просмотрена queue.append(node) if (node not in seen) or (pathLength < seen[node]): # если найденый путь короче уже записанного для вершины (или она еще не была посещена) seen[node] = pathLength # добавляем вершину в список посещенных и записываем текущую длину пути path[node] = path[vertex] + [move['direction']] # записываем путь на основе пути для вершины vertex return path[target] def gradient(self, graph, start, target): self.start = start self.target = target def getXY(node): (x, y) = node.split(':') return (int(x), int(y)) def cost(node): (x, y) = getXY(node['node']) (targetX, targetY) = getXY(self.target) cost = max(abs(x-targetX), abs(y-targetY)) print("cost[{0}, {1}] = {2}".format(x, y, cost)) return cost def dfs(graph, node=None, visited=None): if visited is None: visited = set() if node is None: node = self.start if self.isTarget(node, self.target): print('Цель достигнута') return [] else: print('Цель не достигнута') visited.add(node) for move in sorted(graph.getMoves(node), key=cost): if move['node'] in visited: continue path = dfs(graph, move['node'], visited) if path is not None: return [move['direction']] + path return None return dfs(graph) # Более мощные алгоритмы поиска используют априорные # знания человека – эксперта об особенностях решения задач в заданной предметной # области. В эвристических программах эти знания реализуются с помощью оценочных # функций. Оценочной функцией называется функция от n аргументов, представляющие # собой некоторые числовые (или приведенные к числовым) параметры предметной # области и вычисляющая меру близости любой из текущих ситуаций к целевой. Можно # представить значения оценочной функции как точки N – мерного пространства. # Алгоритм заключается в использовании правила # максимизации с опорой на поиск в глубину. При этом, возможные ходы выбираются # не случайным образом, а в соответствии со значениями оценочной функцией. То # есть сначала выбирается наилучший ход, а потом другой, оцененный ранее как # менее предпочтительный.
ca275404cf4e0baa902b0873bbc1e2fa76346465
eternalseptember/CtCI
/05_bit_manipulation/03_flip_bit_to_win/flip_bit_to_win_sol_2.py
831
3.640625
4
# Optimal solution # Integer.BYTES = 32? # O(b) time, where b is the length of the sequence. # O(1) memory. def longest_sequence_of_ones(num): if num == -1: # -1 in binary is a string of all ones. # This is already the longest sequence. return "No bits are flipped." current_length = 0 previous_length = 0 max_length = 1 # We can always have a sequence of at least one 1. while (num != 0): if ((num & 1) == 1): # current bit is a 1 current_length += 1 elif ((num & 1) == 0): # current bit is a 0 # if next bit is 0, update to 0 # if next bit is 1, update current_length if ((num & 2) == 0): previous_length = 0 else: previous_length = current_length current_length = 0 max_length = max(previous_length + current_length + 1, max_length) num = num >> 1 return max_length
18df1fb940b039e388e483c79658765ccfd1c085
chao-ji/LeetCode
/python/linked_list/lc82.py
2,617
3.765625
4
"""82. Remove Duplicates from Sorted List II Given a sorted linked list, delete all nodes that have duplicate numbers, leaving only distinct numbers from the original list. Example 1: Input: 1->2->3->3->4->4->5 Output: 1->2->5 Example 2: Input: 1->1->1->2->3 Output: 2->3 """ # Definition for singly-linked list. # class ListNode(object): # def __init__(self, x): # self.val = x # self.next = None class Solution(object): def deleteDuplicates(self, head): """ :type head: ListNode :rtype: ListNode """ # KEY Insight: # # For each node `curr` in the input linked list, # 1. We find the next strictly greater node `next` # 2. If that node is the immediate successor of `curr`, # -we add `curr` to the growing list; # -otherwise we skip to `next` # Initially, we have # `dummy.next` points to the start of the growing list, initially empty. # `node` points to the last node of the growing list, initially empty. # [] =====> None # # dummy # node # [] ======> ... # # head # curr # To determine if a node has duplicates or not, we use a second pointer # `next`, starting from each pointer `curr`, and we move `next` until # `next.val` > `curr.val` # <---duplicate nums----> # # [] ====> ... ====> [2] ====> ... ====> [2] ====> [3] # curr next # # <----- skipped ----> # [] ====> ... ====> [2] ====> ... ====> [2] ====> [3] # next # curr # If `next` is not `curr.next`, then we skip to `next`, as shown above. # Otherwise, we disconnect `curr` from the remaining list and add # to the growing list node = dummy = ListNode(0) curr = head while curr: next = curr.next while next and next.val == curr.val: next = next.next # At this point, # `next` is None, or `next.val` > `curr.val` # If `next` is the immediate successor of `curr`, then `curr` # must be unique, so we add it to the growing list if curr.next == next: # disconnect `curr` from the remaining list curr.next = None # add to growing list node.next = curr node = node.next # `curr` points to the start of the remaining list curr = next return dummy.next
b2768b46bf055058df4a5576e005a78e37bae140
Shelby86/Python_Work
/review1_with_answers.py
4,981
4.4375
4
""" Questions What is a list? What is the difference between insert and append? What is the difference between remove and pop? What is join on a string? What is split on a string? Can you add a remove a value from a tuple? What is the difference between remove, del and pop? What is the difference between a set and a list? What is the difference between append and write? 9) What is union? 10) What is intersection? 11) What is difference? 12) What is Symmetric difference? 13) Can we use set operators with other collections? """ numbers = [1, 2, 3, 4, 5, 6, 7] # 1 Make a list letters = ['j', 'q', 'p', 'r', 'a'] # 2 Return a value from a list #print(letters[4]) # 3 Return multiple values from a list #print(letters[0:4]) # 4 Return the last value from a list #print(letters[-1]) # 5 Add a value to a list # letters.append('t') # print(letters) # 6 Add an item to the second index in a list # letters.insert(2,'u') # print(letters) # 7 Use remove # letters.remove('j') # print(letters) # 8 Use del # del(numbers[3]) # print(numbers) # 9 Use pop # numbers.pop() # print(numbers) # 10 Make an empty set # new_set = set() # print(type(new_set)) # 11 Print "Momento from the following" movies = [ ("Eternal Sunshine of a Spotless Mind", 2004), ("Momento", 2000), ("Requiem for a Dream", 2000) ] # print(movies[1][0]) # 12 use len # print(len(numbers)) # 13 Convert to a list into single and individual strings # single string str_of_numbers = str(numbers) # list of individual string # str_of_numbers = [] # # for number in numbers: # number = str(number) # str_of_numbers.append(number) # # print(str_of_numbers) # 13a For the single string, replace the commas with | # str_of_numbers = str_of_numbers.replace(","," | ") # print(str_of_numbers) # 14 Print the following on 2 lines "Hop on Pop. by Dr Seuss" # print("Hop on Pop. \n - by Dr Seuss") # 15 Unpack into 3 variables: # movie = ["The Dark Night", "Christophe Nolan", "2008"] # title, director, year = movie # print(title) # Prints <zip object at 0x107d9efc0> and not anything useful # 16 Pair these owners = ["Paul", "Andrea", "Frank"] pets = ["Fluffy", "Bubbles", "Captian Catsworth"] # for owner, pet in zip(owners,pets): # print(f'{owner} owns {pet}') # 17 Print owner owns pet # Dictionary for the following: operas = { "Aida": "Bel Canto: Verdi", "Turnadot": "Versimo: Puccini", "Armida": "Bel Canto: Rossini", "The Ring": "Romantic, Wagner", "Nabucco": "Bel Canto: Verdi" } # 18 Return a value from a dictionary # print(operas["Aida"]) # 19 Add an item to a dictionary # operas["The Magical Flute"] = "Mozart, Classical" # print(operas) # 20 Add multiple items to a dictionary # operas2 = { # "Carmen": "Versimo: Bizet", # "Norma": "Bel Canto: Bellini" # } # # operas.update(operas2) # print(operas) # 21 Modify a Value in a dictionary # operas["The Magical Flute"] = "Classical: Mozart" # # print(operas) # 22 Modify multiple values in a dictionary # 23 Return all keys # for key in operas.keys(): # print(key) # 24 Return all values # for value in operas.values(): # print(value) # 25 Use del # del(operas["The Ring"]) # print(operas) # 26 Use pop # 27 Check to see if a value is in a dictionary # print("La Sonambula" in operas) # Use these sets for the following bundle1 = {"Jet Force Gemini", "Zelda", "Mario"} bundle2 = {"Zelda", "Animal Crossing", "Mario"} # 28 Make a set # 29 Make an empty set # 30 Add an item to a set # bundle1.add("Donkey Kong Racing") # print(bundle1) # 31 Remove an item to a set # bundle1.remove("Donkey Kong Racing") # print(bundle1) # 32 Print unique values from 2 sets # print(bundle1.union(bundle2)) # 33 Print only common values from 2 sets # print(bundle1.intersection(bundle2)) # 35 Remove all common values from 2 sets # print(bundle1.difference(bundle2)) # 36, Given 2 sets, print all the values in one set except for valuest hat are in the other set # 37 Check if a value is in a set # 38 Sort a list pies = ["cherry", "apple", "coconut cream", "strawberry", "peach"] # pies.sort() # print(pies) # 39 Read a file # with open("iris.csv", "r") as file: # print(file.read()) # 40 Write to a file # with open("new_file.txt", "w") as file: # file.write("I am the first line") # 38 Append a file # with open("new_file.txt", "a") as file: # file.write("\nI am the second line") # 39 Print a csv # 40 Make a csv a dictionary with open("iris.csv", "r") as iris_csv: irises = iris_csv.readlines() headers = irises[0].strip('\n').split(",") entries = [] for iris in irises[1:]: iris = iris.strip('\n').split(',') entries.append(dict(zip(headers, iris))) print(entries) # Review # 41 Make a dictionary into a csv with open("back_to_csv.csv", "w") as back_to_csv: for iris in entries: back_to_csv.write(",".join(iris.values()) + "\n")
8c06ede63297bebdd7cf4fee84b3697c4664cb9c
libowei1213/LeetCode
/816. Ambiguous Coordinates.py
1,265
3.578125
4
class Solution: def judge(self, str): if "." in str: a, b = str.split(".") else: a = str b = '1' if ((len(a) == 1 and a == '0') or not a.startswith('0')) and not b.endswith('0'): return True else: return False def ambiguousCoordinates(self, S): """ :type S: str :rtype: List[str] """ S = S.replace("(", "").replace(")", "") size = len(S) ans = [] for i in range(1, size): num1, num2 = S[:i], S[i:] len1 = len(num1) len2 = len(num2) for l1 in range(0, len1): for l2 in range(0, len2): if l1 == 0: left = num1 else: left = num1[:l1] + "." + num1[l1:] if l2 == 0: right = num2 else: right = num2[:l2] + "." + num2[l2:] if self.judge(left) and self.judge(right): ans.append("(%s, %s)" % (left, right)) return ans if __name__ == '__main__': r = Solution().ambiguousCoordinates("(100)") print(r)
cbef406f02070da12f4906aae73affe062769688
C-N-G/j-m-c
/hello world.py
2,075
3.96875
4
import random def my_function(input): if input > 200: print("hello world") elif input < 200: print("goodbye world") else: print("you suck") def MYadd(): first_numberadsasdasdasd = input("enter a number ") second_numberasdasdasdasd = input("enter another number ") print(int(first_numberadsasdasdasd) + int(second_numberasdasdasdasd)) def subtract(): first_number = input("enter a number") second_number = input("SECOND NUMBER") print(int(first_number) - int(second_number)) def multiply(): first_number = input("FIRST NAMBER") second_number = input("SECOND NAMBER") print(int(first_number) * int(second_number)) def divide(): first_number = input("FIRST NAMBER") second_number = input("SECOND NAMBER") print(int(first_number) / int(second_number)) def jwajg(): # = assignment # == equivalent # input("TEXT PROMPT") # > INPUT SOMETHING # input dogsoup = input("asdfasdf") if dogsoup == "0": MYadd() if dogsoup =="1": subtract() if dogsoup =="3": multiply() if dogsoup =="2": divide() def guess(): myGuess = input("Guess a number ") number = random.randint(0, 10) if int(myGuess) == number: print("you win") else: print("you lose") print("the number was " + str(number)) choice = input("would you like to play again? yes/no: ") print(" ") if choice == "yes": guess() guess() # jwajg() myINT = 200 #integers 1 2 3 4 5 -1 -2 -3 -4 -5 myString = "200" #string myString = '200 a;dslhjfkal;kdsjhflakdjhsflaksdjhflaksjdhflaksdjhflaksjdhfalksdjhflakjsdhf' #string myString = """200 asdfsgadfsgsdfg sfdgsdfgsdf gsfgsdfg sdfgsgf sdfgsdfg""" #string myLong = 200.51234123 #long or double myBool = True alsoMyBool = False # my_function(myINT) # you suck # my_function(myINT+1) # hello world # my_function(myINT-1) # goodbye world # myList = ["apple", "banana", "pear", "orange"] # mylist = range(10) # [0,1,2,3,4,5,6,7,8,9] # for number in range(100): # print(number*" " + "star") # for number in range(100, 0, -1): # print(number*" " + "star") int(dog)
3dee80d0d43dfeedc7697a9f844a111bd304380e
guveni/RandomExerciseQuestions
/mirror_trees.py
1,526
4.03125
4
# !/usr/bin/env python # -*- coding: utf-8 -*- """ """ __author__ = 'guven' class TreeNode(object): def __init__(self, value): self.value = str(value) self.left = None self.right = None def traverse_tree(root): if not root: return '' left = traverse_tree(root.left) right = traverse_tree(root.right) return left + root.value + right def is_mirror_tree(root): if not root: return False tree_traversed = traverse_tree(root) start = 0 end = len(tree_traversed) - 1 while start < end: if tree_traversed[start] != tree_traversed[end]: return False start += 1 end -= 1 return True def is_symmetrical(root): if not root: return False def mirror_tree(root): if not root: return temp = root.left root.left = root.right root.right = temp if root.left: mirror_tree(root.left) if root.right: mirror_tree(root.right) root = TreeNode(8) root.left = TreeNode(6) root.right = TreeNode(10) root.left.left = TreeNode(5) root.left.right = TreeNode(7) root.right.left = TreeNode(9) root.right.right = TreeNode(11) print traverse_tree(root) mirror_tree(root) print traverse_tree(root) """ print is_mirror_tree(root) root = TreeNode(8) root.left = TreeNode(6) root.right = TreeNode(6) root.left.left = TreeNode(5) root.left.right = TreeNode(7) root.right.left = TreeNode(7) root.right.right = TreeNode(5) print is_mirror_tree(root) """
8e5821aac93e69f3eac0a177a1b86babf40a15f7
Sasikumar-s/Python-files
/List/6-sorted in increasing order by the last element in each tuple from a given list of non-empty tuples.py
419
4.21875
4
''' Write a Python program to get a list, sorted in increasing order by the last element in each tuple from a given list of non-empty tuples. Go to the editor Sample List : [(2, 5), (1, 2), (4, 4), (2, 3), (2, 1)] Expected Result : [(2, 1), (1, 2), (2, 3), (4, 4), (2, 5)]''' a=[] t=[] l=int(input("How many pairs")) for i in range(l): a.append([]) for j in range(2): ele=int(input()) a[i].append(j) print(a)
276f96b3b2f786503db722c6c4a78c43c372b041
14Praveen08/Python
/no_of_char.py
84
3.890625
4
word = input() char = 0 for i in word: if i != " ": char = char + 1 print(char)
fd24278816be2b651cda110d45262145b59d09ef
JunyaZ/algorithm-
/QuickSort.py
2,120
3.546875
4
#!/usr/bin/env python3 """ Created on Wed Oct 3 11:22:45 2018 @author: Junya Zhao """ import numpy as np import random Comparison=[] def readfile (filenemae): file = np.loadtxt(filename,delimiter='\n') data = list(file)[1:] inputData = list(map(lambda x:int(x),data)) return inputData def partition (array,left_index,right_index): pivot =array[left_index] i = left_index + 1 for j in range (left_index + 1, right_index): if array[j] < pivot: array[j], array[i] = array[i],array[j] i+=1 array[left_index],array[i-1] = array[i-1],array[left_index] return i-1, right_index-left_index def choose_pivot(A, left,right,variant): if variant == "first": pivot_index = left return pivot_index if variant == "median3": left_index =left right_index =right-1 middle_index = int((left + right-1)/2) if A[left_index] <= A[middle_index] <= A[right_index] or A[right_index] <= A[middle_index] <= A[left_index]: return middle_index elif A[middle_index] <= A[left_index] <= A[right_index] or A[right_index] <= A[left_index] <= A[middle_index]: return left_index else: return right_index if variant =="random": pivot_index = random.randint(left,right-1) return pivot_index def QuickSort(A,left,right,variant): if (left - right)==0: return A pivotIndex =choose_pivot(A,left,right,variant) A[pivotIndex],A[left] =A[left],A[pivotIndex] current_pivot,comparison = partition(A, left,right) global Comparison Comparison.append(comparison) QuickSort(A, left, current_pivot,variant) QuickSort(A, current_pivot + 1, right,variant) comparison +=comparison #print(comparison-len(A)) return A,sum(Comparison)-len(A) if __name__== "__main__": filename= input("Please enter a filename:") variant = input("Please enter a Quicksort variant :") array = readfile(filename) Sorted_A,Total_Compar= QuickSort(array,0,len(array), variant) print(Total_Compar)
176163f0ee72cf2f4ccadecd570df105fc982b95
KATO-Hiro/AtCoder
/ABC/abc101-abc150/abc146/b.py
405
3.65625
4
# -*- coding: utf-8 -*- def main(): from string import ascii_uppercase n = int(input()) s = input() alpha = ascii_uppercase ans = '' for si in s: for index, a in enumerate(alpha): if si == a: next_index = (index + n) % 26 ans += alpha[next_index] print(ans) if __name__ == '__main__': main()
c2805cfdbae3f8fd4ab3280d08d9afa734d54c3c
alei-num1/Git-hub
/Practice-program/Program3.py
1,569
4.125
4
# 这是一个猜字游戏 import random guess_number = random.randint(1, 20) print("I'm thinking of a number between 1 and 20.") # 向游戏者询问数字4次 for guess_counts in range(1, 5): print("Please take a guess.\n") try: number = int(input("Please tell me a number: ")) if number < guess_number: print("Your number is lower than guess_number.") elif number > guess_number: print("Your number is higher than guess_number.") else: break # 正确数字 except ValueError: print("The number is error.Please tell me a number again.") if number == guess_number: print("You are right! And you guessed my number in " + str(guess_counts) + " guesses!") else: print("Sorry,game over.") # 这是一个猜字游戏 # import random # # guess_number = random.randint(1, 20) # print("I'm thinking of a number between 1 and 20.") # # 向游戏者询问数字 直到猜对为止 # # for guess_counts in range(1, 5): # guess_counts = 0 # while True: # print("Please take a guess.\n") # guess_counts += 1 # number = int(input("Please tell me a number: ")) # if number < guess_number: # print("Your number is lower than guess_number.") # elif number > guess_number: # print("Your number is higher than guess_number.") # elif number == guess_number: # print("You are right! And you guessed my number in " # + str(guess_counts) + " guesses!") # break # else: # print("Sorry,game over.")
c05c3431ccbfc6778fc8bcb263d0bb942313b969
wwwhaleee/ZeNan
/hanoi.py
327
3.953125
4
def hanoi(n, A, B, C): if n > 0: hanoi(n-1, A, C, B) print("{} --> {}".format(A,C)) hanoi(n-1, B, A, C) m = int(input()) hanoi(m, 'A', 'B', 'C') print("just modify the code") print("just modify the code") print("just modify the code") print("just modify the code") print("just modify the code")
09b074479332026a8ce5cc6ebc2113aedf71737b
dwi859/tugas_pyton
/tugas_pyton.py
785
4
4
nilai1 = int(input("Masukan nilai diameter : ")) nilai2 = int(input("Masukan nilai tinggi : ")) volume = ((nilai1/2) * (nilai1/2)) * 3.14*nilai2 print("Maka Hasil Volume tabung adalah = " + str(volume)) print("\n") sisi = int(input("Masukan panjang Sisi segitiga : ")) keliling = sisi*3 print("Keliling dari segitiga adalah : " + str(keliling)) print("\n") angka1 = int(input("Masukan Angka 1 : ")) angka2 = int(input("Masukan Angka 2 : ")) perhitungan = input("Masukan Operator hitung : ") if (perhitungan == f"+"): hasil = angka1 + angka2 print(hasil) elif(perhitungan == f"-"): hasil = angka1 - angka2 print(hasil) elif(perhitungan == f"*"): hasil = angka1 * angka2 print(hasil) elif(perhitungan == f"/"): hasil = angka1 / angka2 print(hasil)
515199decd6f4a4ccd5911f4b074db4ad8c03e61
Raghu-vamsi-pav/dataanalytics_practice
/datastructure.py
3,540
4.09375
4
# -*- coding: utf-8 -*- """ Created on Mon Nov 30 20:09:38 2020 @author: Raghu """ print("hello world") #Numbers a=3 b=5 #a and b are number objects #String str1 = 'hello javatpoint' #string str1 str2 = ' how are you' #string str2 print (str1[0:5]) #printing first five character using slice operator print (str1[4]) #printing 4th character of the string print (str1*2) #printing the string twice print (str1 + str2) #printing the concatenation of str1 and str2 #Lists l = [1, "hi", "python", 2] print (l[3:]) print (l[0:2]) print (l); print (l + l); print (l * 3); print (type(l)) #Lets try mutation l[1] = "Bye" print (l) #Tuple t = ("hi", "python", 2, 4) print (t[1:]); print (t[0:2]); print (t); print (t + t) print (t * 3) print (type(t)) #Lets try mutation #t[1] = "Bye" print (t) #Dictionary d = {1:"Jimmy", 2:'Alex', 3:'john', 4:'mike'}; print("1st name is "+d[1]); print("2nd name is "+ d[4]); print (d); print (d.keys()); print (d.values()); #----ADVANCED---- #list #ordered collection of items; sequence of items in a list shoplist =['apple','carrot','mango', 'banana'] shoplist len(shoplist) print(shoplist) #run next 2 lines together for i in shoplist: print(i, end =' ') #add item to list shoplist.append('rice') shoplist #sort shoplist.sort() #inplace sort shoplist #index/select shoplist[0] shoplist[0:4] #delete item del shoplist[0] shoplist #Tuple #Used to hold multiple object; similar to lists; less functionality than list #immutable - cannot modify- fast ; ( ) zoo = ('python','lion','elephant','bird') zoo len(zoo) languages = 'c', 'java', 'php' #better to put (), this also works languages #Dictionary - like an addressbook. use of associate keys with values #key-value pairs { 'key1':value1, 'key2':value2} ; { } bracket, :colon student = {'A101': 'Abhinav', 'A102': 'Rohit', 'A103':'Rahul', 'A104': 'Karan'} student student['A103'] print('Name of rollno A103 is ' +student['A103']) del student['A104'] student len(student) for rollno, name in student.items(): print('name of {} is {} '.format(rollno, name) ) #Lets test Mutation: #adding a value student['A104'] = 'Hitesh' student #Set #Sets are unordered collections of objects; ( [ , ]) teamA = set(['india','england','australia','sri lanka','ireland']) teamA teamB = set(['pakistan', 'south africa','bangladesh','ireland']) teamB #Checking whether a data value exists in a set or not. 'india' in teamA 'india' in teamB #Adding values in a set teamA.add('china') teamA #puts in order teamA.add('india') teamA #no duplicates teamA.remove('australia') teamA #Create dataframe : import pandas as pd #Create a DataFrame d = {'Name':['Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine', 'Alisa','Bobby','Cathrine','Alisa','Bobby','Cathrine'], 'Exam':['Semester 1','Semester 1','Semester 1','Semester 1','Semester 1','Semester 1', 'Semester 2','Semester 2','Semester 2','Semester 2','Semester 2','Semester 2'], 'Subject':['Mathematics','Mathematics','Mathematics','Science','Science','Science', 'Mathematics','Mathematics','Mathematics','Science','Science','Science'], 'Score':[62,47,55,74,31,77,85,63,42,67,89,81]} df = pd.DataFrame(d,columns=['Name','Exam','Subject','Score']) df #View a column of the dataframe in pandas: df['Name'] #View two columns of the dataframe in pandas: df[['Name','Score']] #View first two rows of the dataframe in pandas: df[:2]
b72c8a7eac290a1bb11d2aee3db6b639b8a51bdd
chuxing/wechat
/datamigration/Trie.py
1,980
3.578125
4
# -*- coding:utf8 -*- class Trie(object): def __init__(self): self.root = dict() self.END = '\0' def insert(self, string): if string == '\0':return index, node,return_index, return_flag = self.findLastNode(string) # print index,node for char in string[index:]: node=node.setdefault(char,{}) node[self.END] = None def find(self, string): index, node,return_index,return_flag = self.findLastNode(string) # print index,self.END,self.END in node # if self.END in node: # print index,repr(node).decode('unicode-escape') # index == len(string) and return return_flag,return_index def findLastNode(self, string): # print string node = self.root index = 0 return_flag = False return_index = -1 while index < len(string): char = string[index] if char == ' ': index += 1 return_index = index continue if char != '' and (char in node): node = node[char] if self.END in node : return_flag = True return_index = index + 1 else: break index += 1 return (index, node,return_index,return_flag) def printTree(self, node, layer): if node == None: return '\n' res = [] items = sorted(node.items(), key=lambda x:x[0]) res.append(items[0][0]) res.append(self.printTree(items[0][1], layer+1)) for item in items[1:]: res.append('.' * layer) res.append(item[0]) res.append(self.printTree(item[1], layer+1)) return ''.join(res) def __str__(self): # print "asdfasdfasdf" # print self.printTree(self.root, 0).encode('gb2312') return unicode(self.printTree(self.root, 0)).encode('utf-8')
678eff5daeb7c8d35b0275791985d7d51f91c679
andrelsf/python
/scripts_python/livro_curso_intensivo_de_python/strings/name_cases.py
455
4.125
4
# # # 2.3 Mensagem Pessoal: Armazene o nome de uma pessoa em uma variável e apresente uma mensagem a esta pessoa. # Sua mensagem deve ser simples, como "Aló Eric, voce gostaria de aprender um pouco de python hoje?". # name = "Andre" print("Ola "+ name + " voce gostaria de trabalhar na SOLUTI.") resposta = input("Entre com sim ou não!") if resposta == "sim": print("Bem vindo a SOLUTI " + name) else: print("Deus tem o melhor para vc " + name)
4d8b4125ba0a95fb6448762db11c74bb41eeb994
osbetel/LeetCode
/problems/lc70 - Climbing Stairs.py
2,192
4.3125
4
# See lc746 for a similar problem # Given a staircase with n steps, if you can step up one step # or two steps at a time, how many distinct ways can you climb to the top? # # So if we have a staircase of 2 steps, we can do 1 step + 1 step, or 2 steps, making # 2 distinct ways we can get to the top. # # With 3 steps, this becomes # 1 + 1 + 1 # 1 + 2 # 2 + 1 # 3 total # # And with 4 steps # 1 + 1 + 1 + 1 # 1 + 2 + 1 # 1 + 1 + 2 # 2 + 1 + 1 # 2 + 2 # 5 total # # and with 5 steps... # 1 + 1 + 1 + 1 + 1 # 1 + 1 + 1 + 2 # 1 + 1 + 2 + 1 # 1 + 2 + 1 + 1 # 2 + 1 + 1 + 1 # 1 + 2 + 2 # 2 + 1 + 2 # 2 + 2 + 1 # Or 8 total # # so already we can see that there is a pattern, and the pattern is a combinatorics problem. # # Taking 5 steps as an example, we can get the number of distinct ways by # nCr(5,0) + nCr(4, 1) + nCr(3,2) # or 1 + 4 + 3 = 8 distinct ways to climb a staircase of 5 steps. # For some nCr(n,r), we're asking how many ways can we arrange n elements, if we must choose r? def factorial(x): import math return math.factorial(x) def nCr(n, r): # nCr(n, r) = n! / r! (n - r)! return int(factorial(n) / (factorial(r) * factorial(n - r))) def waysToClimbNStairs(x: int) -> int: ways = 0 for n in reversed(range(1, x + 1)): r = x - n if n < r: return ways ways += nCr(n,r) return int(ways) # We should also note the dynamic programming solution. # In order to get to some step s[i], you can either jump one step from s[i - 1] or two steps from s[i - 2] # So the number of ways to get to s[i] is equal to s[i - 1] + s[i - 2} def waysToClimbNStairsDynamicProg(x): if x == 2: return 2 else: return waysToClimbNStairsDynamicProg(x - 1) + waysToClimbNStairs(x - 2) x = 5 print(waysToClimbNStairs(x)) print(waysToClimbNStairsDynamicProg(x)) # We can also note that the sequence of ways to climb is the fibonacci sequence. # 0 steps ==> 1 way to climb # 1 step ==> 1 way # 2 steps ==> 2 ways # 3 steps ==> 3 ways # 4 steps ==> 5 ways # 5 steps ==> 8 ways # 6 steps ==> 13 ways # ... etc. So to find the num of ways for a staircase of length n, # we simply need to find the nth fibonacci number
2fbe2c4739dd410c36eee4aed489a16f2ebf5781
helbertsandoval/trabajo10_sandoval-sanchez-helbert_cesar_maira_paz
/menu.py
1,216
3.546875
4
import libreria def agregarBytes(): # 1. Pedir 2 bytes # 2. Guardar los datos en el archivo bytes.txt byte1=libreria.pedir_byte("Ingrese Byte 1:") byte2=libreria.pedir_byte("Ingrese Byte 2:") contenido=byte1 + "-" + byte2 + "\n" libreria.guardar_datos("bytes.txt", contenido, "a") print("Datos guardados") def enmascarar(): # 1. Abrir el archivo bytes.txt # 2. Mostrar los datos print("Byte 1 Byte2 Enmascamiento") datos=libreria.obtener_datos_lista("bytes.txt") # 3. Recorrer todos los elementos del archivo for linea in datos: linea = linea.replace("\n", "") byte1, byte2 = linea.split("-") mascara = libreria.enmascarar(byte1, byte2) print(byte1 + " - " + byte2 + " - " + mascara) opc=0 max=3 while(opc != max): print("######### MENU #########") print("# 1. Agregar Bytes #") print("# 2. Enmascarar #") print("# 3. Salir #") print("########################") opc=libreria.pedir_numero("Ingrese Opcion:", 1, 3) if ( opc == 1): agregarBytes() else: enmascarar() #fin_menu print("Programa finalizado")
9a6a377c4ad27e41292ae8be64b76946cc867dbc
FRadford/sage
/src/Timer.py
509
3.859375
4
import time class Timer: def __enter__(self): self.start = time.time() return self def __exit__(self, error_type, value, traceback): self.end = time.time() self.elapsed = self.end - self.start if self.elapsed > 3600: self.elapsed = str(self.elapsed / 3600) + " hours." elif 60 < self.elapsed < 3600: self.elapsed = str(self.elapsed / 60) + " minutes." else: self.elapsed = str(self.elapsed) + " seconds."
565359fb4969e9d0c3c34a21f62abfee03c34a66
Pranith1785/Algorithms
/Strings/Reverse_words_in_String.py
1,149
4.125
4
### Problem Statement ''' Function that takes the string of words separated by one or more spaces and returns the string with words in reverse order. Example : string = "Space b/w words is 4" Ans = "4 is words b/w Space" ''' ### Solution - 1 ## Time - O(n) | Space - O(n) n- length of the string def reverseWordsInString(string): words = string.split(" ") return " ".join(words[::-1]) ### Solution -2 ## Time - O(n) | Space - O(n) def reverseWordsInString2(string): wordList = [] startIdx = 0 for i in range(0,len(string)): currentChar = string[i] if currentChar == " ": wordList.append(string[startIdx:i]) startIdx = i elif string[startIdx] == " ": wordList.append(" ") startIdx = i wordList.append(string[startIdx:]) reverseList(wordList) return "".join(wordList) def reverseList(arrlist): start, end = 0, len(arrlist)-1 while start < end: arrlist[start], arrlist[end] = arrlist[end],arrlist[start] start += 1 end -= 1 print(reverseWordsInString2("saf afsjfa kfah"))
c382e12590d56eac3942833eeb89e5a281bffad9
Rockfish/PythonCourse
/04_SqlLite/movie_database.py
3,107
3.984375
4
import sqlite3 from movie_client import get_movie_data class MovieDatabase(object): def __init__(self): "Connects to the database or creates a new if needed." self.connection = sqlite3.connect("test.sqlite") def create_movie_table(self): "Creates the movie table in the database." create_movie_data_table_command = ''' CREATE TABLE Movies ( id integer primary key, title text, actors text, plot text);''' try: self.connection.execute(create_movie_data_table_command) except: "Table already exists" pass def delete_movie_table(self): "Drops the table if needed." self.connection.execute("DROP TABLE IF EXISTS Movies") self.connection.commit() def add_movie_data(self, title, actors, plot): "Saves the values to the database." values = (title, actors, plot) self.connection.execute('INSERT INTO Movies (title, actors, plot) VALUES (?, ?, ?)', values) def close_connection(self): "Closes the connection" self.connection.close() def download_movies(self, movie_titles): """"Downloads the movie data for the movies in the list. Saves the data to the database""" for title in movie_titles: # Call the client method to get a dictionary with the movies' data. data = get_movie_data(title) # Check to see if there is a key in the dictionary called 'Error' if not "Error" in data: title = data['Title'] actors = data['Actors'] plot = data['Plot'] # Add the values to the database. self.add_movie_data(title, actors, plot) else: print("Error getting: {0}. Please check the title.".format(title)) # Make sure to commit to save the data. self.connection.commit() def print_movies_with_actor(self, actor): "Searches the database for movies with the actor. Prints the result" command = "SELECT title FROM Movies WHERE actors LIKE '%{}%'".format(actor) cursor = self.connection.execute(command) for row in cursor: print(row) cursor.close() if __name__ == "__main__": favorite_movie_titles = ["Brazil", "The Fifth Element", "Spirited Away", "Princese Monoko", "The Guardians of the Galaxy"] # Create a movie database object to work with. movie_db = MovieDatabase() # Delete any old tables and create a new table. movie_db.delete_movie_table() movie_db.create_movie_table() # Download movie data from omdbapi.com and save it to the database. movie_db.download_movies(favorite_movie_titles) # Find the movies with the actor in it. movie_db.print_movies_with_actor('Bruce Willis') # Close the connection when we are done. movie_db.close_connection() print("Done")
e6398d8c1dd9ec3af700db33b9a1852587b3bb60
3l-d1abl0/DS-Algo
/py/oops/class-static-method-decorator.py
1,286
3.5
4
class NewClass(object): classy = 'class value!' def __init__(self): print('Initalized') count = 100 class InstanceCounter(object): count = 0 def __init__(self,val): self.val = self.filterint(val) InstanceCounter.count +=1 @staticmethod #any utility function that doesn't access any instance property directly def filterint(value): if not isinstance(value, int): return 0 else: return value def set_val(self, newval): self.val = newval def get_val(self): return self.val #Instance Method # def get_count(self): # return count @classmethod#decorator to specify if instace method or class method def get_count(cls):#receives the Class as argument return cls.count if __name__ == "__main__": # dd = NewClass() # print(dd.classy) # # dd.classy ="Instance Value" # # print(dd.classy) # # del dd.classy # # print(dd.classy) a = InstanceCounter(4) b = InstanceCounter(8) c = InstanceCounter(16) for obj in (a, b, c): print ("val of Obj : %s"%(obj.get_val())) print(" Count (from instance) : {} ".format(obj.count)) #print("val of obj : %s"%(obj.get_val())
0a088923728208c5b0bec6d40ee12508ebd0199c
chinmaey/CSSPythonPractice
/Exersise10_7.py
279
4.03125
4
def is_anagram(s1,s2): if s1==s2: return False elif len(s1)!=len(s2): return False else: cs1=sorted(s1) cs2=sorted(s2) if cs1!=cs2: return False else: return True import sys print(is_anagram(sys.argv[1], sys.argv[2]))
99e0a127384f68b42d905700d170e0468945f25a
dmaryanbarnes/Machine-Learning-2018
/playgound/calcComplete.py
664
3.71875
4
import sys import math def pythagoras(a, b): a_squared = math.pow(a, 2) b_squared = math.pow(b, 2) return math.sqrt(a_squared + b_squared) def main(): command = sys.argv[1] if command == "add": x = int(sys.argv[2]) y = int(sys.argv[3]) print(x + y) if command == "sub": x = int(sys.argv[2]) y = int(sys.argv[3]) print(x-y) if command == "countto": x = int(sys.argv[2]) for i in range(x): print(i) if command == "hypot": a = int(sys.argv[2]) b = int(sys.argv[3]) print(pythagoras(a, b)) if __name__ == "__main__": main()
fc7327b5d110a8e3bc4279532eb2b78fb8392829
BlueVelvetSackOfGoldPotatoes/medicalMRIcnn
/goncalo/thesis_project/files_for_thesis/scripts/distance_measure_control/distance_measure.py
1,310
4.03125
4
''' Methods that calculate the distance measure between two images ''' import numpy as np def calc_average_vector(li_images): ''' Calculate the average vector over all vectorized images ''' final_vector = [] total = len(li_img) # val_i should be a list - the vectorized image for i, val_i in enumerate(li_img): # val_c is each element of the vectorized image for c, val_c in enumerate(val_i): final_vector[c] += val_c # Element-wise average for i, val_i in enumerate(li_img): li_img[i] = val_i / total return li_img def calc_euclidean_distance(vector1, vector2): ''' Return euclidean distance between two vectors ''' a = np.array(vector1) b = np.array(vector2) # Euclidean distance is the l2 norm, since the default value of the ord parameter in numpy.linalg.norm is 2 np.linalg.norm works as the Euclidean distance distance = np.linalg.norm(a-b) print('Euclidean distance:' + distance) return distance def main(): """ Write code here for calculating distance across vectors and saving them. IMPORTANT: NEED A WAY OF KEEPING TRACK OF WHAT VECTOR BELONGS TO WHAT IMAGE: USE A TAG BEFORE THE VECTOR THAT FINISHES ON A SYMBOL THAT IS DETECTABLE """ if __name__ == '__main__': main()
db8fff37137829aaf2a7ba4cbd92386fcc7b12e3
kirtish16/My-Articles
/Que3.py
1,226
4.125
4
# Python3 implementation of the approach # Function to multiply two square matrices def multiplyMatrices(arr1, arr2): order = len(arr1) ans = [[0 for i in range(order)] for j in range(order)] for i in range(order): for j in range(order): for k in range(order): ans[i][j] += arr1[i][k] * arr2[k][j] return ans # Function to find all the pairs that # can be connected with exactly 'k' edges def solve(arr, k): res = [[0 for i in range(len(arr))] for j in range(len(arr))] # Copying arr to res, # which is the result for k=1 for i in range(len(arr)): for j in range(len(arr)): res[i][j] = arr[i][j] # Multiplying arr with itself # the required number of times for i in range(2, k+1): res = multiplyMatrices(res, arr) for i in range(len(arr)): for j in range(len(arr)): # If there is a path between 'i' # and 'j' in exactly 'k' edges if (res[i][j] > 0): print(i, "->", j, "in", res[i][j], "way(s)") # Driver Code if __name__ == "__main__": arr = [1, 2, 3, 4] arr = [[0 for i in range(5)] for j in range(5)] arr[0][1] = 1 arr[1][2] = 1 arr[2][3] = 1 arr[2][4] = 1 arr[3][0] = 1 arr[4][2] = 1 k = 3 solve(arr, k) # This code is contributed by kirtishsurangalikar
686d0d880fc1ac25f7ce4a726037b929c522fd89
Klooskie/mownit2
/lab4/lagrange_interpolation.py
4,806
3.59375
4
import numpy as np import matplotlib.pyplot as plt from math import sin, cos, pi, exp def maximum_norm(vector): m = 0 for x in vector: if abs(x) > m: m = abs(x) return m def newton_polynomial(x, n, factors, points): result = 0 for i in range(n): result += factors[i] for j in range(i + 1, n): factors[j] *= (x - points[i][0]) return result def newton_polynomial_for_domain(domain, n, points): result = [] difference = [] divided_differences_table = [] # obliczenie tablicy roznic dzielonych, zaczynamy od kolumny wypelnionej wartosciami w wezlach column_0 = [point[1] for point in points] divided_differences_table.append(column_0) # obliczenie kolejnych kolumn tablicy roznic dzielonych for i in range(1, n): column = [] for j in range(n - i): value = divided_differences_table[i - 1][j + 1] value -= divided_differences_table[i - 1][j] value /= (points[j + i][0] - points[j][0]) column.append(value) divided_differences_table.append(column) # wspolczynniki to pierwsze wartosci w kazdej z kolumn tablicy roznic dzielonych factors = [column[0] for column in divided_differences_table] for x in domain: result.append(newton_polynomial(x, n, factors.copy(), points)) difference.append(f(x) - result[-1]) print("norma maksimum roznicy wielomianu i funkcji (newton): " + str(maximum_norm(difference))) return result def lagrange_polynomial(x, n, points): result = 0 for i in range(n): l_factor = 1 for j in range(n): if i != j: l_factor = l_factor * (x - points[j][0]) / (points[i][0] - points[j][0]) result += points[i][1] * l_factor return result def lagrange_polynomial_for_domain(domain, n, points): result = [] difference = [] for x in domain: result.append(lagrange_polynomial(x, n, points)) difference.append(f(x) - result[-1]) print("norma maksimum roznicy wielomianu i funkcji (legrange): " + str(maximum_norm(difference))) return result def f(x): return sin(4 * x / pi) * exp(-0.2 * x / pi) def f_for_domain(domain): result = [] for x in domain: result.append(f(x)) return result def main(): for n in range(2, 22): if n == 21: n = 30 a = -5 b = 10 points = [] step = (b - a) / (n - 1) for i in range(n): x = a + i * step points.append((x, f(x))) domain = np.linspace(a, b, num=1500) print('\n\nWezly (' + str(n) + ') rozmieszczone rownomiernie na calym przedziale') fig = plt.figure(1) fig.canvas.set_window_title('Wezly (' + str(n) + ') rozmieszczone rownomiernie na calym przedziale') plt.subplots_adjust(hspace=0.5) plt.subplot(211) plt.grid(True) plt.plot(domain, lagrange_polynomial_for_domain(domain, n, points), 'k-') plt.plot([point[0] for point in points], [point[1] for point in points], 'ro') plt.plot(domain, f_for_domain(domain), 'b--') plt.title('Wizualizacja interpolowanego wielomianu Lagrange\'a') plt.subplot(212) plt.grid(True) plt.plot(domain, newton_polynomial_for_domain(domain, n, points), 'k-') plt.plot([point[0] for point in points], [point[1] for point in points], 'ro') plt.plot(domain, f_for_domain(domain), 'b--') plt.title('Wizualizacja interpolowanego wielomianu Newtona\'a') points = [] for i in range(1, n + 1): x = 0.5 * (a + b) + 0.5 * (b - a) * cos((2 * i - 1) * pi / (2 * n)) points.append((x, f(x))) print('\n\nWezly (' + str(n) + ') rozmieszczone zgodnie z zerami wielomianu Czebyszewa') fig = plt.figure(2) fig.canvas.set_window_title('Wezly (' + str(n) + ') rozmieszczone zgodnie z zerami wielomianu Czebyszewa') plt.subplots_adjust(hspace=0.5) plt.subplot(211) plt.grid(True) plt.plot(domain, lagrange_polynomial_for_domain(domain, n, points), 'k-') plt.plot([point[0] for point in points], [point[1] for point in points], 'ro') plt.plot(domain, f_for_domain(domain), 'b--') plt.title('Wizualizacja interpolowanego wielomianu Lagrange\'a') plt.subplot(212) plt.grid(True) plt.plot(domain, newton_polynomial_for_domain(domain, n, points), 'k-') plt.plot([point[0] for point in points], [point[1] for point in points], 'ro') plt.plot(domain, f_for_domain(domain), 'b--') plt.title('Wizualizacja interpolowanego wielomianu Newtona\'a') plt.show() if __name__ == '__main__': main()
0bc2a7a07ac3c230bc328b3c91fc8c6a7ddb5c9a
pgadds/Program-Design-and-Abstraction
/Problem Set 2.py
1,850
3.9375
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Fri Jul 12 23:18:30 2019 @author: navboi """ #Problem 1 month = 0 totalPay = 0 monthlyInterestRate = annualInterestRate / 12.0 while month <12: minPay = monthlyPaymentRate * balance unpayBal = balance - minPay totalPay += minPay balance = unpayBal + (monthlyInterestRate * unpayBal) month += 1 print('Month: ' + str(month)) print('Minimum monthly payment: ' + str(round(minPay,2))) print('Remaining balance: ' + str(round(balance,2))) print('Total paid: ' + str(round(totalPay,2))) print(' Remaining balance: ' + str(round(balance,2))) #Problem 2 balance = 3329 annualInterestRate = 0.2 initBalance = balance monthlyInterestRate = annualInterestRate / 12.0 month = 0 minPay = 10 def calculate(month, balance, minPay, monthlyInterestRate): while month <12: unpaidBalance = balance - minPay balance = unpaidBalance + (monthlyInterestRate * unpaidBalance) month += 1 return balance while calculate(month, balance, minPay, monthlyInterestRate) > 0: balance = initBalance minPay +=10 month = 0 calculate(month, balance, minPay, monthlyInterestRate) print('Lowest Payment: ' + str(minPay)) #Problem 3 init_balance = balance monthlyInterestRate = annualInterestRate/12 lower = init_balance/12 upper = (init_balance * (1 + monthlyInterestRate)**12)/12.0 epsilon = 0.03 while abs(balance) > epsilon: monthlyPaymentRate = (upper + lower)/2 balance = init_balance for i in range(12): balance = balance - monthlyPaymentRate + ((balance - monthlyPaymentRate) * monthlyInterestRate) if balance > epsilon: lower = monthlyPaymentRate elif balance < -epsilon: upper = monthlyPaymentRate else: break print('The Lowest Payment is:', round(monthlyPaymentRate, 2))
29ccadcb5a463d4cec162adbde567a75cbe63529
wilsonfr4nco/cursopython
/Modulo_Intermediario/Dicionarios/dicionários_04.py
386
3.859375
4
# fazendo cast com dicionário lista = [ ['c1', 1], ['c2', 2], ['c3', 3], ] # como tenho um par eu posso converter para dicionário. # posso também converter tuplas para dicionário, o que importa é ter chaves e valores. d1 = dict(lista) print(d1) d1.pop('c3') #removeu um ítem print(d1) d2 = { 1:2, 2:3, 4:5, } d1.update(d2) # contatenação print(d1)
32165c27cff89b19ec7f09fbdfdafdf3cb79eacd
nazaninsbr/Turtle-Drawings
/more-complex/two.py
391
3.703125
4
import turtle from random import randint NUMBER_OF_CIRCLES = 50 NUMBER_OF_GROUPS = 3 SPEED = 0 loadWindow = turtle.Screen() turtle.speed(SPEED) turtle.colormode(255) for i in range(NUMBER_OF_GROUPS): r = randint(0,255) g = randint(0,255) b = randint(0,255) for i in range(NUMBER_OF_CIRCLES): turtle.circle(i) turtle.left(i) turtle.pencolor(r, g, b) turtle.exitonclick()
5e8cf56b8cdbadc25fe2e70074e2278e744da075
jayendra-patil33/python_lab_programming
/Angstrom_4.py
320
3.921875
4
# Jayendra Patil # roll no: 19, gr no: 11810706 # To test for angstrom number # question: 4 num=int(input("Enter a number:")) sum = 0 temp = num while temp > 0: digit =temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num,"is an Angstrom number") else: print(num,"is not an Angstrom number")
ac03ecf5d6aefdf5b9c0de63c55e16c04aca96b2
rahulvshinde/Python_Playground
/Top_Leetcode/majority_elementII.py
556
3.984375
4
""" Given an integer array of size n, find all elements that appear more than ⌊ n/3 ⌋ times. Follow-up: Could you solve the problem in linear time and in O(1) space? Example 1: Input: nums = [3,2,3] Output: [3] Example 2: Input: nums = [1] Output: [1] Example 3: Input: nums = [1,2] Output: [1,2] """ nums = [3,2,3] from collections import Counter def majorityElementII(nums): res = [] for key, value in Counter(nums).items(): if value > len(nums)//2: res.append(key) return res print(majorityElementII(nums))
ca81410dd8ce2b51f5fe803f7e8b8417d4681135
kukukuni/Python_ex
/3day/Quiz01_2.py
520
3.71875
4
# Quiz01_2.py items = {"콜라":1000,"사이다":900,"씨그램":500,"우유":700,"활명수":800} print("=== 음료 자판기 입니다 ====") print("[콜라][사이다][씨그램][우유][활명수] 중 선택") print("복수 선택 시 --> 예) 사이다,우유 ") # 선택목록 item, 가격 price item = input() # 사이다,우유 items2 = item.strip().split(',') prices = [p for i,p in items.items() if i in items2] price = 0 for p in prices: price += p print("가격 : {0} 원".format(price) )
189f44ba0ef319b1188838898fefcf9f83394128
arnabs542/DataStructures_Algorithms
/bitwise/Single_Number_III.py
944
3.640625
4
''' Single Number III Given an array of numbers A , in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once. Note: Output array must be sorted. Input 1: A = [1, 2, 3, 1, 2, 4] Input 2: A = [1, 2] Output 1: [3, 4] Output 2: [1, 2] ''' class Solution: # we need to divide the arr into two parts # 1 numbers which have 1 in msb of xor of arr and 2 which have 0s def solve(self, a): xor = 0 for i in range(len(a)): xor = xor ^ a[i] xor2 = xor1 = 0 # msb of xor filter = (xor & (xor-1)) ^ xor # one of the numbers will be in xor1 and another in xor2 for i in range(len(a)): if filter & a[i]: xor1 = xor1^a[i] else: xor2 = xor2^a[i] if xor1 < xor2: return [xor1,xor2] return[xor2,xor1]
33fe6c1accd0e8d238e54aeb8de6cf1bbfecbb2f
Naazyon/RNG-Battle-Royale
/socket_client.py
1,672
3.8125
4
""" This is a simple example of a client program written in Python. Again, this is a very basic example to complement the 'basic_server.c' example. When testing, start by initiating a connection with the server by sending the "init" message outlined in the specification document. Then, wait for the server to send you a message saying the game has begun. Once this message has been read, plan out a couple of turns on paper and hard-code these messages to and from the server (i.e. play a few rounds of the 'dice game' where you know what the right and wrong dice rolls are). You will be able to edit this trivially later on; it is often easier to debug the code if you know exactly what your expected values are. From this, you should be able to bootstrap message-parsing to and from the server whilst making it easy to debug. Then, start to add functions in the server code that actually 'run' the game in the background. """ import socket import threading from time import sleep # Create a TCP/IP socket sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # Connect the socket to the port where the server is listening server_address = ('localhost', 4000) print ('connecting to %s port %s' % server_address) sock.connect(server_address) state = "RECEIVING" def listenSocket(): while(state != "SENDING"): data = sock.recv(1024) if (data): mess = data.decode() print(mess) listenThread = threading.Thread(target=listenSocket) listenThread.daemon = True listenThread.start() while True: message = input("").encode() if (message): state = "SENDING" sleep(1/100) sock.sendall(message) state = "RECEIVING"
440f0ed85eaf27f40c105df434437bd86d0b6e27
patrick-bedkowski/Sorting-Algorithms-Visualized
/selection_sort.py
761
3.859375
4
def selection_sort(data): if not data: return [] # by default minimum value of the list is set to be the first one indecies_length = len(data) - 1 # number of indecies to iterate through is smaller by one # iterate through the rest of the values # and compare them with minimum for index in range(indecies_length): # iterathe through indecies minimum_index = index for greater_index in range(index + 1, len(data)): # all elements to the right of the current iterating one if data[greater_index] < data[minimum_index]: minimum_index = greater_index if minimum_index != index: data[minimum_index], data[index] = data[index], data[minimum_index] return data
da984afae696a07340a05719ae411e62c1aa9e65
MengdiWang124/thinkcspy
/Chap_2/12_fahren_to_celsius.py
90
3.828125
4
fahrenheit=float(input("Degrees fahrenheit:")) Celsius=(fahrenheit-32)/1.8 print(Celsius)
a10f6e6c0a36c55aa7529a7cc4167228f749cb82
curlyae/DGSim
/function/write_into_database.py
13,590
3.984375
4
""" .. note:: This module provides methods to transfer data from JSON/TXT file into database """ import sqlite3 import json from data.connect_database import * from function.get_datainfo import * def icd10cm_info_json_into_database(database_name, table_name, json_file_path): """ Transfer icd10cm data from JSON file into database JSON file organizes data as directory format: e.g: { ... "ICD10CM:E88.9": { "mesh": [ "MESH:D008659" ], "do": [ "DOID:0014667" ], "gene_list": [ "3630", "2110", "5468", "1828", "1401", "196", "2101", "3356", "51733" ] }, ... } Each key in directory is a ICD10CM disease id, and it contains mesh_list , do_list and gene_list. Each ICD10CM disease id mappings several mesh, do and gene. :param database_name: string The database to connect to :param table_name: The database table name that store GDAs data :param json_file_path: The path of JSON file :return: """ conn = connect_database(database_name) c = conn.cursor() sql = "create table {0} (DISEASE_ID VARCHAR(50) PRIMARY KEY , MESH_LIST VARCHAR(255), " \ "DO_LIST VARCHAR(255), GENE_LIST VARCHAR(255))".format(table_name) c.execute(sql) with open(json_file_path) as f: file = json.load(f) for disease in file: mesh_info = file[disease]['mesh'] mesh_str = ','.join(mesh_info) do_info = file[disease]['do'] do_str = ','.join(do_info) gene_info = file[disease]['gene_list'] gene_str = ','.join(gene_info) # 用","连接元素,构建成新的字符串 sql = "insert into {0}(DISEASE_ID, MESH_LIST, DO_LIST, GENE_LIST) values ('%s','%s','%s','%s')".format( table_name) \ % (disease, mesh_str, do_str, gene_str) c.execute(sql) conn.commit() conn.close() # icd10cm_info_json_into_database('disease_gene', 'ICD10CMinfo', '../data/手工校验过的ICD数据一层分组.json') def icd10cm_gene_info_json_into_database(database_name, table_name, json_file_path): """ Transfer icd10cm and gene data from JSON file into database JSON file organizes data as directory format: e.g: { ... "ICD10CM:E88.9": { "mesh": [ "MESH:D008659" ], "do": [ "DOID:0014667" ], "gene_list": [ "3630", "2110", "5468", "1828", "1401", "196", "2101", "3356", "51733" ] }, ... } Each key in directory is a ICD10CM disease id, and it contains gene_list and numbers_of_gene Each ICD10CM disease id mappings several gene. :param database_name: string The database to connect to :param table_name: The database table name that store GDAs data :param json_file_path: The path of JSON file :return: """ conn = connect_database(database_name) c = conn.cursor() sql = "create table {0} (DISEASE_ID VARCHAR(50) PRIMARY KEY , " \ "GENE_LIST VARCHAR(255), NUM_OF_GENE INT(10))".format(table_name) c.execute(sql) with open(json_file_path) as f: file = json.load(f) for disease in file: gene_info = file[disease]['gene_list'] gene_str = ','.join(gene_info) # 用","连接元素,构建成新的字符串 sql = "insert into {0}(DISEASE_ID, GENE_LIST, NUM_OF_GENE) values ('%s','%s',%d)".format(table_name) \ % (disease, gene_str, len(file[disease]['gene_list'])) c.execute(sql) conn.commit() conn.close() # icd10cm_gene_info_json_into_database('disease_gene', 'ICD10CM_gene', '../data/手工校验过的ICD数据一层分组.json') def mesh_gene_info_txt_into_database(database_name, table_name, txt_file_path): """ Transfer MESH_GENE GDAs data from .txt file to database Every line in GDAs represents a gene-disease association e.g: 50518 MESH:D003920 50518 MESH:D003924 number string is the ID of gene MESH string is the ID of disease,obtained from MeSH(Medical Subject Headings) The degree of a disease is the number of genes associated with that disease, while the degree of a gene is the number of diseases annotated with that gene :param database_name: string The database to connect to :param table_name: string The database table name that store GDAs data :param txt_file_path: string The path of GDAs file :return: """ f = open(txt_file_path, 'r+') linelist = f.readlines() gdas_dt = {} for line in linelist: line = line.strip('\n') line = line.split(' ') if line[0].isdigit() is True: gdas_dt.setdefault('{0}'.format(line[1]), []).append(line[0]) if line[1].isdigit() is True: gdas_dt.setdefault('{0}'.format(line[0]), []).append(line[1]) # 将字典写入json文件中 # json_str = json.dumps(gdas_dt, indent=4) # with open('../data/{0}_dt.json'.format(table_name), 'w') as f: # f.write(json_str) conn = connect_database(database_name) c = conn.cursor() sql = "create table {0} (DISEASE_ID VARCHAR(50) PRIMARY KEY, GENE_LIST VARCHAR(255), NUM_OF_GENE INT(10))".format( table_name) c.execute(sql) for disease in gdas_dt: infolist = gdas_dt[disease] str = ','.join(infolist) # 用","连接元素,构建成新的字符串 sql = "insert into {0}(DISEASE_ID,NUM_OF_GENE,GENE_LIST) values('%s',%d,'%s')".format(table_name) \ % (disease, len(gdas_dt[disease]), str) c.execute(sql) conn.commit() conn.close() # mesh_gene_info_txt_into_database('disease_gene', 'mesh_gene', '../data/mesh_gene.txt') def group_info_txt_into_database(database_name, table_name, txt_file_path): """ Transfer ICD10CM group information from TXT into database Every line in txt contains a group information. e.g: ICD10CM:A48 ['MESH:D007877', 'MESH:D012772'] ICD10CM:A49 ['MESH:D001424'] ... The first string represents the name of this group. The second string represents diseases contains in this group :param database_name: string The database to connect to :param table_name: string The database table name that store group data :param txt_file_path: string The path of group information file :return: """ conn = connect_database(database_name) c = conn.cursor() sql = "create table {0} (GROUP_ID VARCHAR(50) PRIMARY KEY, DISEASE_LIST VARCHAR(255)," \ "NUM_OF_DISEASE INT(10))".format(table_name) c.execute(sql) f = open(txt_file_path, 'r+') linelist = f.readlines() for line in linelist: list = [] line = line.strip('\n') line = line.split(' ') group_name = line[0] disease_list = line[1] disease_list = disease_list.strip('[]') disease_list = disease_list.split(', ') for disease in disease_list: disease = eval(disease) # 去掉字符串两端的单引号 list.append(disease) num_of_disease = len(list) disease_str = ','.join(list) sql = "insert into {0} (GROUP_ID,DISEASE_LIST,NUM_OF_DISEASE) VALUES ('%s','%s',%d)".format(table_name) \ % (group_name, disease_str, num_of_disease) c.execute(sql) conn.commit() conn.close() # group_info_txt_into_database('disease_gene', 'group_info', '../data/手工矫正的ICD数据.txt') def write_indi_mathur_max_into_database(database_name, table_name, mathur_table_name): """ This function is used to write mathur number of individual disease into database table :param database_name: string The database to connect to :param table_name: string The database table to be queried :param mathur_table_name: string The database table used to store mathur data :return: """ conn = connect_database(database_name) c = conn.cursor() sql = "create table {0} (DISEASE_ID VARCHAR(50) PRIMARY KEY , MATHUR_NUM VARCHAR(10))".format(mathur_table_name) c.execute(sql) sql = ("select * from {}".format(table_name)) c.execute(sql) query_list = c.fetchall() all_gene_num = get_all_gene_num(database_name, table_name) for disease_info1 in query_list: max_mathur = 0 # 代表与disease1相似度最大的疾病,相似度的值 for disease_info2 in query_list: disease_a_name = disease_info1[0] disease_x_name = disease_info2[0] disease_a_genelist = disease_info1[1] disease_x_genelist = disease_info2[1] disease_a_genelistlen = disease_info1[2] disease_x_genelistlen = disease_info2[2] disease_a_genelist = disease_a_genelist.split(',') set_list1 = set(disease_a_genelist) disease_x_genelist = disease_x_genelist.split(',') set_list2 = set(disease_x_genelist) set1_and_set2_list = set_list1 & set_list2 # the intersection of set A and set B # print(set1_and_set2_list) set1_and_set2_list_len = len(set1_and_set2_list) # the size of the intersection of set A and set B mathur_num = (set1_and_set2_list_len / (disease_a_genelistlen + disease_x_genelistlen - set1_and_set2_list_len)) /\ ((disease_a_genelistlen / all_gene_num) * (disease_x_genelistlen / all_gene_num)) print(mathur_num) if mathur_num > max_mathur: max_mathur = mathur_num print('\t') sql = "insert into {0} (DISEASE_ID, MATHUR_NUM) values ('%s','%s')".format(mathur_table_name) % (disease_a_name, max_mathur) c.execute(sql) conn.commit() conn.close() # write_indi_mathur_max_into_database("disease_gene", "mesh_gene", "mesh_mathur") def write_group_mathur_max_into_database(database_name, table_name, group_mathur_table_name): """ This function is used to write mathur number of disease group into database table :param database_name: string The database to connect to :param table_name: :param group_mathur_table_name: :return: """ conn = connect_database(database_name) c = conn.cursor() sql = "create table {0} (GROUP_ID VARCHAR (50) PRIMARY key , MATHUR_NUM VARCHAR (10))".format(group_mathur_table_name) c.execute(sql) sql = ("select * from {}".format(table_name)) c.execute(sql) query_list = c.fetchall() all_gene_num = get_all_gene_num(database_name, "mesh_gene") for group_info1 in query_list: max_mathur = 0 for group_info2 in query_list: # if group_info1[0] is not group_info2[0]: group_a_name = group_info1[0] group_x_name = group_info2[0] group_a_genelist = get_icd_diseasegroup_geneinfo(database_name, table_name, "GROUP_ID", group_a_name)[1] group_x_genelist = get_icd_diseasegroup_geneinfo(database_name, table_name, "GROUP_ID", group_x_name)[1] group_a_genelistlen = get_icd_diseasegroup_geneinfo(database_name, table_name, "GROUP_ID", group_a_name)[2] group_x_genelistlen = get_icd_diseasegroup_geneinfo(database_name, table_name, "GROUP_ID", group_x_name)[2] group_a_genelist = group_a_genelist.split(',') set_list1 = set(group_a_genelist) group_x_genelist = group_x_genelist.split(',') set_list2 = set(group_x_genelist) set1_and_set2_list = set_list1 & set_list2 # the intersection of set A and set B set1_and_set2_list_len = len(set1_and_set2_list) # the size of the intersection of set A and set B mathur_num = (set1_and_set2_list_len / (group_a_genelistlen + group_x_genelistlen - set1_and_set2_list_len)) / \ ((group_a_genelistlen / all_gene_num) * (group_x_genelistlen / all_gene_num)) print(mathur_num) if mathur_num > max_mathur: max_mathur = mathur_num print('\t') sql = "insert into {0} (GROUP_ID, MATHUR_NUM) values ('%s', '%s')".format(group_mathur_table_name) % (group_a_name, max_mathur) c.execute(sql) conn.commit() conn.close() write_group_mathur_max_into_database("disease_gene", "group_info", "group_mathur")
6c9930479e1e3bd827cb72477f9039943e905650
here0009/LeetCode
/Python/1617_CountSubtreesWithMaxDistanceBetweenCities.py
5,574
3.71875
4
""" There are n cities numbered from 1 to n. You are given an array edges of size n-1, where edges[i] = [ui, vi] represents a bidirectional edge between cities ui and vi. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each d from 1 to n-1, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to d. Return an array of size n-1 where the dth element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to d. Notice that the distance between the two cities is the number of edges in the path between them. Example 1: Input: n = 4, edges = [[1,2],[2,3],[2,4]] Output: [3,4,0] Explanation: The subtrees with subsets {1,2}, {2,3} and {2,4} have a max distance of 1. The subtrees with subsets {1,2,3}, {1,2,4}, {2,3,4} and {1,2,3,4} have a max distance of 2. No subtree has two nodes where the max distance between them is 3. Example 2: Input: n = 2, edges = [[1,2]] Output: [1] Example 3: Input: n = 3, edges = [[1,2],[2,3]] Output: [2,1] Constraints: 2 <= n <= 15 edges.length == n-1 edges[i].length == 2 1 <= ui, vi <= n All pairs (ui, vi) are distinct. """ # https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/889070/C%2B%2BPython-Bitmask-try-all-subset-of-cities-Clean-and-Concise-O(2n-*-n) class Solution: def countSubgraphsForEachDiameter(self, n: int, edges): """ list all the combinations of nodes, use bitmask to represent the nodes. check the nodes and their conncetions and the max distance if connections == nodes - 1, then it is a tree use Floyd Warshall to calculate the distance between nodes """ def check(status): max_dist = 0 connections = 0 cities = 0 for i in range(n): if status >> i & 1 == 0: continue cities += 1 for j in range(i+1, n): if status >> j & 1 == 0: continue connections += dist[i][j] == 1 max_dist = max(max_dist, dist[i][j]) return max_dist if connections == cities-1 else 0 dist = [[float('inf')]*n for _ in range(n)] for i, j in edges: dist[i-1][j-1] = 1 dist[j-1][i-1] = 1 for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k]+dist[k][j]) res = [0]*(n-1) for status in range(1, 2**n): tmp = check(status) if tmp > 0: res[tmp-1] += 1 return res from collections import deque from collections import defaultdict class Solution: def countSubgraphsForEachDiameter(self, n: int, edges): """ two rounds of bfs to find the diameter of a tree """ def bfs(src, cities): i, d = src, 0 dq = deque([(src, 0)]) visited = {src} while dq: i, d = dq.popleft() for j in edges_dict[i]: if j not in visited and j in cities: dq.append((j, d+1)) visited.add(j) return i,d,visited def diameterTree(cities): node = cities.pop() cities.add(node) end_node, d, visited = bfs(node, cities) if len(visited) != len(cities): return 0 _, res, _ = bfs(end_node, cities) return res def maxDist(status): cities = set() for i in range(n): if (status >> i) & 1 == 1: cities.add(i) return diameterTree(cities) edges_dict = defaultdict(list) for i, j in edges: edges_dict[i-1].append(j-1) edges_dict[j-1].append(i-1) res = [0]*(n-1) for status in range(1, 2**n): tmp = maxDist(status) if tmp > 0: res[tmp-1] += 1 return res # https://leetcode.com/problems/count-subtrees-with-max-distance-between-cities/discuss/889400/C%2B%2BPython-Floyd-Warshall-%2B-Enumerate-Subsets-O(2N-*-N2) from itertools import combinations, permutations class Solution_1: def countSubgraphsForEachDiameter(self, n, edges): g = [[float('inf') for _ in range(n)] for _ in range(n)] for [i, j] in edges: g[i - 1][j - 1], g[j - 1][i - 1] = 1, 1 for k, i, j in permutations(range(n), 3): g[i][j] = min(g[i][j], g[i][k] + g[k][j]) ans = [0]*(n-1) for k in range(2, n + 1): for s in combinations(range(n), k): e = sum(g[i][j] for i, j in combinations(s, 2) if g[i][j] == 1) d = max(g[i][j] for i, j in combinations(s, 2)) if e == k - 1: ans[d - 1] += 1 return ans S = Solution() n = 4 edges = [[1,2],[2,3],[2,4]] print(S.countSubgraphsForEachDiameter(n, edges)) n = 2 edges = [[1,2]] print(S.countSubgraphsForEachDiameter(n, edges)) n = 3 edges = [[1,2],[2,3]] print(S.countSubgraphsForEachDiameter(n, edges))
0bdc57412c51eac8fc9459c4e16abd93489f8d81
LXZbackend/python
/数据结构/排序/sort.py
1,481
3.953125
4
# coding=utf-8 # 冒泡排序 def bobbleSort(list): # 首先设置外层循环 # 逐渐递减 最后也循环长度减1次 但是为内存循环提供了方便 for i in range(len(list) - 1, 0, -1): # 注意这里面循环只要到最后num 在下面的判断中 因为是上一个和下个匹配 当你到达前一个的时候其实 就可以对比到最后一个了。但那是选择排序不一样 所以得 加1 for j in range(i): if list[j + 1] < list[j]: temp = list[j + 1] list[j + 1] = list[j] list[j] = temp print "这是冒泡排序", list def selectSort(list): # 选择排序是对冒泡排序的更行 他不需要每次都换值 大大减小了 交换的开支,只执行一次交换 for i in range(len(list) - 1, 0, -1): maxindex = 0 # 这里是从列表中第二个开始的 因为以及标记每次第一个是最大的 所以从第二个开始,这里index+1 是为了能操作到最后一个 for j in range(1, i + 1): if list[maxindex] < list[j]: maxindex = j temp = list[i] list[i] = list[maxindex] list[maxindex] = temp print "这是选择排序", list def insertSort(list): # 插入排序就是 把第一个当做有序序列 从第二 if __name__ == '__main__': testlist = [54, 26, 93, 17, 77, 31, 44, 55, 20] bobbleSort(testlist) selectSort(testlist)
99defb0a781227421b12b4a315bba50f843d6929
Mosiv/Python-lissons
/game.py
596
3.875
4
'''Game: Guess the number''' import random random_number = random.randint(1,50) attempt_counter = 0 print('Игра, угадай число от 1 до 50') while attempt_counter < 6: number = int(input('Введите число: ')) attempt_counter+=1 if number == random_number: print('Угадал') break if number > random_number: print('Меньше') if number < random_number: print('Больше') if number != random_number and attempt_counter == 6: print(f'Ты проиграл число было: {random_number}')
655fe68b0b65ad8cf28428f9d1e81f0f48b1616e
paritabrahmbhatt/Python-for-Everybody
/Extra Problems/Easy/P006.py
226
4
4
#Python Program for simple interest p = int(input("Enter the amount of principle: ")) n = int(input("enter the number of years: ")) r = float(input("Enter the rate: ")) sr = (p*n*r)/100 print("Simple interest: ",sr)
ce84e3ceff75bc38bf506e1204e814bd019c6058
paulsobers23/steph-smith-school
/Jan-24-2020/coding-challenge.py
273
3.8125
4
def find_uniq(lst): dic = {}; for char in lst: if char not in dic: dic[char] = 1 else: dic[char] += 1 for char in dic: if dic[char] == 1: return char print(find_uniq([1, 1, 1, 2, 1, 1]))
df5b2fa97e00dc4e4c3d60b8218a23966a2d4dd3
romeorizzi/temi_prog_public
/2018.12.05.provetta/all-CMS-submissions-2018-12-05/2018-12-05.12:59:53.727460.VR429684.rank_unrank_ABstrings.py
715
3.734375
4
""" * user: VR429684 * fname: ERIKA * lname: ZOCCATELLI * task: rank_unrank_ABstrings * score: 0.0 * date: 2018-12-05 12:59:53.727460 """ #!/usr/bin/env python3 # -*- coding: latin-1 -*- # Template di soluzione per il problema rank_unrank_ABstrings def ABstring2rank(s): p=0 for i in range(len(s)): if (s[i]=='B'): p= p + (2)**(len(s)-i-1) return p def ABstring_of_len_and_rank(length, r): if (length==8)&(r==129) return "BAAAAAAB" input_string = input() if input_string[0] == 'A' or input_string[0] == 'B': print( ABstring2rank(input_string) ) else: length, r = input_string.split() print( ABstring_of_len_and_rank(int(length), int(r)) )
7d12fe31261e15910b7778846f396695bc25ef57
rebeccajohnson88/qss20
/mini_book/_build/jupyter_execute/docs/getting_started.py
9,332
4.6875
5
(getting_started)= # Setting up Your Python Environment ## Overview In this lecture, you will learn how to 1. get a Python environment up and running 2. execute simple Python commands 3. run a sample program 4. install the code libraries that underpin these lectures ## Anaconda The [core Python package](https://www.python.org/downloads/) is easy to install but *not* what you should choose for these lectures. These lectures require the entire scientific programming ecosystem, which - the core installation doesn\'t provide - is painful to install one piece at a time. Hence the best approach for our purposes is to install a Python distribution that contains 1. the core Python language **and** 2. compatible versions of the most popular scientific libraries. The best such distribution is [Anaconda](https://www.anaconda.com/what-is-anaconda/). Anaconda is - very popular - cross-platform - comprehensive - completely unrelated to the Nicki Minaj song of the same name Anaconda also comes with a great package management system to organize your code libraries. ```{note} All of what follows assumes that you adopt this recommendation! ``` (install_anaconda)= ### Installing Anaconda To install Anaconda, [download](https://www.anaconda.com/download/) the binary and follow the instructions. Important points: - Install the latest version! - If you are asked during the installation process whether you\'d like to make Anaconda your default Python installation, say yes. ### Updating Anaconda Anaconda supplies a tool called `conda` to manage and upgrade your Anaconda packages. One `conda` command you should execute regularly is the one that updates the whole Anaconda distribution. As a practice run, please execute the following 1. Open up a terminal 2. Type `conda update anaconda` For more information on `conda`, type `conda help` in a terminal. (ipython_notebook)= ## Jupyter Notebooks [Jupyter](http://jupyter.org/) notebooks are one of the many possible ways to interact with Python and the scientific libraries. They use a *browser-based* interface to Python with - The ability to write and execute Python commands. - Formatted output in the browser, including tables, figures, animation, etc. - The option to mix in formatted text and mathematical expressions. Because of these features, Jupyter is now a major player in the scientific computing ecosystem. {numref}`Figure %s <jp_demo>` shows the execution of some code (borrowed from [here](http://matplotlib.org/examples/pylab_examples/hexbin_demo.html)) in a Jupyter notebook ```{figure} /_static/lecture_specific/getting_started/jp_demo.png :scale: 50% :name: jp_demo A Jupyter notebook viewed in the browser ``` While Jupyter isn\'t the only way to code in Python, it\'s great for when you wish to - get started - test new ideas or interact with small pieces of code - share scientific ideas with students or colleagues ### Starting the Jupyter Notebook Once you have installed Anaconda, you can start the Jupyter notebook. Either - search for Jupyter in your applications menu, or - open up a terminal and type `jupyter notebook` - Windows users should substitute \"Anaconda command prompt\" for \"terminal\" in the previous line. If you use the second option, you will see something like this ```{figure} /_static/lecture_specific/getting_started/starting_nb.png :scale: 50% ``` The output tells us the notebook is running at `http://localhost:8888/` - `localhost` is the name of the local machine - `8888` refers to [port number](https://en.wikipedia.org/wiki/Port_%28computer_networking%29) 8888 on your computer Thus, the Jupyter kernel is listening for Python commands on port 8888 of our local machine. Hopefully, your default browser has also opened up with a web page that looks something like this ```{figure} /_static/lecture_specific/getting_started/nb.png :scale: 50% ``` What you see here is called the Jupyter *dashboard*. If you look at the URL at the top, it should be `localhost:8888` or similar, matching the message above. Assuming all this has worked OK, you can now click on `New` at the top right and select `Python 3` or similar. Here\'s what shows up on our machine: ```{figure} /_static/lecture_specific/getting_started/nb2.png :scale: 50% ``` The notebook displays an *active cell*, into which you can type Python commands. ### Notebook Basics Let\'s start with how to edit code and run simple programs. #### Running Cells Notice that, in the previous figure, the cell is surrounded by a green border. This means that the cell is in *edit mode*. In this mode, whatever you type will appear in the cell with the flashing cursor. When you\'re ready to execute the code in a cell, hit `Shift-Enter` instead of the usual `Enter`. ```{figure} /_static/lecture_specific/getting_started/nb3.png :scale: 50% ``` (Note: There are also menu and button options for running code in a cell that you can find by exploring) #### Modal Editing The next thing to understand about the Jupyter notebook is that it uses a *modal* editing system. This means that the effect of typing at the keyboard **depends on which mode you are in**. The two modes are 1. Edit mode - Indicated by a green border around one cell, plus a blinking cursor - Whatever you type appears as is in that cell 2. Command mode - The green border is replaced by a grey (or grey and blue) border - Keystrokes are interpreted as commands --- for example, typing `b` adds a new cell below the current one To switch to - command mode from edit mode, hit the `Esc` key or `Ctrl-M` - edit mode from command mode, hit `Enter` or click in a cell The modal behavior of the Jupyter notebook is very efficient when you get used to it. #### Inserting Unicode (e.g., Greek Letters) Python supports [unicode](https://docs.python.org/3/howto/unicode.html), allowing the use of characters such as $\alpha$ and $\beta$ as names in your code. In a code cell, try typing `\alpha` and then hitting the `tab` key on your keyboard. (a_test_program)= #### A Test Program Let\'s run a test program. Here\'s an arbitrary program we can use: <http://matplotlib.org/3.1.1/gallery/pie_and_polar_charts/polar_bar.html>. On that page, you\'ll see the following code import numpy as np import matplotlib.pyplot as plt %matplotlib inline # Fixing random state for reproducibility np.random.seed(19680801) # Compute pie slices N = 20 θ = np.linspace(0.0, 2 * np.pi, N, endpoint=False) radii = 10 * np.random.rand(N) width = np.pi / 4 * np.random.rand(N) colors = plt.cm.viridis(radii / 10.) ax = plt.subplot(111, projection='polar') ax.bar(θ, radii, width=width, bottom=0.0, color=colors, alpha=0.5) plt.show() Don\'t worry about the details for now --- let\'s just run it and see what happens. The easiest way to run this code is to copy and paste it into a cell in the notebook. Hopefully you will get a similar plot. ### Working with the Notebook Here are a few more tips on working with Jupyter notebooks. #### Tab Completion In the previous program, we executed the line `import numpy as np` - NumPy is a numerical library we\'ll work with in depth. After this import command, functions in NumPy can be accessed with `np.function_name` type syntax. - For example, try `np.random.randn(3)`. We can explore these attributes of `np` using the `Tab` key. For example, here we type `np.ran` and hit Tab ```{figure} /_static/lecture_specific/getting_started/nb6.png :scale: 50% ``` Jupyter offers up the two possible completions, `random` and `rank`. In this way, the Tab key helps remind you of what\'s available and also saves you typing. (gs_help)= #### On-Line Help To get help on `np.rank`, say, we can execute `np.rank?`. Documentation appears in a split window of the browser, like so ```{figure} /_static/lecture_specific/getting_started/nb6a.png :scale: 50% ``` Clicking on the top right of the lower split closes the on-line help. #### Other Content In addition to executing code, the Jupyter notebook allows you to embed text, equations, figures and even videos in the page. For example, here we enter a mixture of plain text and LaTeX instead of code ```{figure} /_static/lecture_specific/getting_started/nb7.png :scale: 50% ``` Next we `Esc` to enter command mode and then type `m` to indicate that we are writing [Markdown](http://daringfireball.net/projects/markdown/), a mark-up language similar to (but simpler than) LaTeX. (You can also use your mouse to select `Markdown` from the `Code` drop-down box just below the list of menu items) Now we `Shift+Enter` to produce this ```{figure} /_static/lecture_specific/getting_started/nb8.png :scale: 50% ``` ### Sharing Notebooks Notebook files are just text files structured in [JSON](https://en.wikipedia.org/wiki/JSON) and typically ending with `.ipynb`. You can share them in the usual way that you share files --- or by using web services such as [nbviewer](http://nbviewer.jupyter.org/). The notebooks you see on that site are **static** html representations. To run one, download it as an `ipynb` file by clicking on the download icon. Save it somewhere, navigate to it from the Jupyter dashboard and then run as discussed above.
b4e783deded3d274de02a07f2ec147afb1fa4907
anoopkumarcv/PythonScripts
/Fibonnici.py
597
4.40625
4
# -*- coding: utf-8 -*- """ Enter a number and have the program generate the Fibonacci sequence to that number or to the Nth number. """ def Fibonacci (num): num1=0 num2=1 for num in range(0,num): yield num1 num1,num2=num2,num2+num1 while(True): try: num=int(input ("Please enter a number till where to generate Fibonacci sequence:")) except: print("You have not entered an integer") else: print("Fibonacci sequence") for i in Fibonacci(num): print (i) break
0db0c89c0f86e9691b4d3c649cb50cd03760ccd2
cosmos-nefeli/practice_python
/maps.py
545
4.21875
4
""" Python Maps also called ChainMap is a type of data structure to manage multiple dictionaries together as one unit. """ import collections dict1 = {'day1': 'Mon', 'day2': 'Tue'} dict2 = {'day3': 'Wed', 'day1': 'Thu'} res = collections.ChainMap(dict1, dict2) # Creating a single dictionary print(res.maps,'\n') print('Keys = {}'.format(list(res.keys()))) print('Values = {}'.format(list(res.values()))) print() # print all the elements from results print('element') for key, val in res.items(): print('{} = {}'.format(key, val))
27fd7457caf11e26144eb02c78e9ce54ec5603ce
kanekyo1234/AtCoder_solve
/A other/三井住友信託銀行プログラミングコンテスト2019/B.py
195
3.59375
4
import math a=int(input()) if (a/1.08)%1==0: print (math.ceil(a/1.08)) else: m=math.ceil(a/1.08) if a==math.floor(m*1.08): print(math.floor(m)) else: print(":(")
d02141db3953a942302f600f60b8384d6b85c855
LucasHuls/OpdrachtenGroep5
/Bram van Nek/python/opdracht 3.py
216
3.6875
4
numbers=[1,2,3,5,7,10,44,2,5,11,2] print("grootste waarde is: ", max (numbers)) print("kleinste waarde is: ", min (numbers)) tellen = list.count (numbers, 2) print ("numbers twee komt", tellen, "keer voor.") input()
a22f2f389b26228790b0f9beb49614d1168faaf5
geodimitrov/Softuniada
/2017/04. snake.py
2,181
3.703125
4
def create_cube(size): result = [] for x in range(size): line = input().split(" | ") result.append([list(el) for el in line]) return result def read_commands(): result = [] while True: command = input() if command.startswith("end"): result.append(command) break result.append(command) return result def get_snakes_position(cube, size): for x in range(size): for y in range(size): for z in range(size): if cube[x][y][z] == "s": return x, y, z def get_next_move_dimensions(direction): res = None if direction == "up": res = (0, -1, 0) elif direction == "down": res = (0, +1, 0) elif direction == "forward": res = (-1, 0, 0) elif direction == "backward": res = (+1, 0, 0) elif direction == "right": res = (0, 0, +1) elif direction == "left": res = (0, 0, -1) return res def dimensions_in_range(x, y, z): return x in range(size) \ and y in range(size) \ and z in range(size) size = int(input()) cube = create_cube(size) commands = read_commands() curr_x, curr_y, curr_z = get_snakes_position(cube, size) points_collected = 0 is_dead = False for i in range(len(commands) - 1): if is_dead: break direction = commands[i].split()[0] steps = int(commands[i+1].split()[2]) next_move_dimensions = get_next_move_dimensions(direction) for step in range(steps): next_x = curr_x + next_move_dimensions[0] next_y = curr_y + next_move_dimensions[1] next_z = curr_z + next_move_dimensions[2] if not dimensions_in_range(next_z, next_y, next_z): is_dead = True break else: if cube[next_x][next_y][next_z] == "a": cube[next_x][next_y][next_z] = "0" points_collected += 1 curr_x = next_x curr_y = next_y curr_z = next_z if is_dead: print(f"Points collected: {points_collected}\nThe snake dies.") else: print(f"Points collected: {points_collected}")
ebfe55dff4ade40fcf6c44b5a5264f013a4492d0
huazai007/python
/day02/07.py
212
3.71875
4
arr = [] while True: input = raw_input('input: ') if input == 'add': detail = raw_input('detail.......:') arr.append(detail) print arr elif input == 'do': if len(arr) ==0: break print arr.pop(0)
64c937cb355dd0c7072bbf4225d54f4ee45f26ed
cybernuki/holbertonschool-higher_level_programming
/0x0A-python-inheritance/100-my_int.py
523
4.0625
4
#!/usr/bin/python3 # 100-my_int.py # Jhonatan Arenas <1164@holbertonschool.com> """ Defines a MyInt class that inherits by Int But has == and != operators inverted """ class MyInt(int): """Class that has == and != operators inverted Also, it inheritance by int """ def __eq__(self, other): """ compares if this instances is != of other instance""" return super().__ne__(other) def __ne__(self, other): """ compares if this instances is == of other instance""" return super().__eq__(other)
bda567dd1fa7c49f2557b470bc7faf1108410969
Sumit-daniel/Roll-the-dice-game
/Roll the dice.py
819
4.03125
4
___________ROLL The Dice___________ #Modules import tkinter as tk from PIL import Image, ImageTk import random #adding​ images dice=["dice1.png","dice2.png","dice3.png","dice4.png","dice5.png","dice6.png"] root=tk.Tk() root.title("Dice simulator") root.geometry("500x400") #label​ l1=tk.Label(root,text="Dice SImulator",fg="yellow",bg="black",font="Helvetica 16 bold ") l1.pack() img = ImageTk.PhotoImage(Image.open(random.choice(dice))) #Image​ label l2=tk.Label(root,image=img) l2.image=img l2.pack() def roll(): img = ImageTk.PhotoImage(Image.open(random.choice(dice))) l2.configure(image=img) l2.image = img #button​ button = tk.Button(root, text='Roll the Dice', fg='blue', command=roll) button.pack() root.mainloop()
52f18bfa1870212b5422ade88f59a5deab0cea33
kiilkim/book_duck
/pythonPractice/pnuPY/0708book.py
769
3.875
4
#자료형 변수와입력 pi=3.14159265 r = 10 print("원주율 = ",pi) print("반지름 =",r) print("원의둘레 =",2*pi*r) # 변수형을 설정안해줘서 좋긴 하지만, 팀프로젝트 할 떄 서로 충돌할 가능성 #복합 대입연산자 r +=10 print(r) #빼기, 곱하기, 나누기, 몫 등 에 제곱도 가능 '연산 후 대입!' #문자열도 가능하다. string = input("입력 >") print("자료 :",string) #090 문제 5 str_input = input("원의반지름입력>") num_input = int(str_input) print("반지름:",num_input) print("둘레:",2*3.14*num_input) print("넓이:",3.14*num_input**2) #format 함수로 숫자를 문자열로 반복 string_a ="{}".format(10) print(string_a) print(type(string_a))
5126ea5df3a6089c7d10d1393e93adbd87a062f5
Codechef-SRM-NCR-Chapter/30-DaysOfCode-March-2021
/answers/MridulMohanta/Day22/question2.py
714
3.6875
4
from queue import Queue def revque(k , Queue): if Queue.empty() == True or k > Queue.qsize(): return if k <= 0: return stack = [] for i in range(0 , k): stack.append(Queue.queue[0]) Queue.get() while (len(stack) != 0): Queue.put(stack[-1]) stack.pop() for i in range(Queue.qsize() - k): Queue.put(Queue.queue[0]) Queue.get() inp = int(input("Enter N: ")) k = int(input("Enter K: ")) Queue = Queue() for i in range(0 , inp): n = int(input("Enter Numbers: ")) Queue.put(n) revque(k , Queue) def printq(Queue): while (not Queue.empty()): print(Queue.queue[0] , end = " ") Queue.get() printq(Queue)
f2207b6224c2f45c7f3132433383c757087ec872
royashams/Restaurant-Simulator
/customer.py
4,406
4.15625
4
class Customer: """A Customer. This class represents a customer in the simulation. Each customer will enter the simulation at _entry_time, will wait at most _patience turns. The restaurant need _prepare_time turns to prepare this customer order, and will receive _profit if can serve this customer on time. Your main task is to implement the remaining methods. """ # === Private Attributes === # @:type _id: int # a unique integer that identifies each customer # @:type _entry_time int # the specific turn when customer has entered the simulation # @:type _patience: int # Maximum amount of turns a customer will wait for their order # @:type _prepare_time: int # The number of turns required to complete an order # @:type _profit: float # Amount of profit received from the customer's order def __init__(self, definition): """ Create a new Customer self, given a definition from a line from a scenario file. :param definition: The specific line in a file that carries information about a customer. :type definition: str :rtype: None """ # definition refers to the specific line of code which is read from # the file. it looks a little bit like '1\t23215\t13\t4\t8' # we need to split this into a list by removing the tab. c_lst = definition.split() self._entry_time = int(c_lst[0]) self._id = int(c_lst[1]) self._profit = float(c_lst[2]) self._prepare_time = int(c_lst[3]) self._patience = int(c_lst[4]) def id(self): """ return the id value of the customer. :rtype: int >>> c = Customer('1\t23215\t13\t4\t8') >>> c.id() 23215 """ return self._id def entry_turn(self): """ return the entry turn of the customer. :rtype: int >>> c = Customer('1\t23215\t13\t4\t8') >>> c.entry_turn() 1 """ return self._entry_time def patience(self): """ return the patience (max amount of time the customer is willing to wait :rtype: int >>> c = Customer('1\t23215\t13\t4\t8') >>> c.patience() 8 """ return self._patience def profit(self): """ return the profit a customer will give from their order. :rtype: float >>> c = Customer('1\t23215\t13\t4\t8') >>> c.profit() 13.0 """ return self._profit def prep(self): """ return the amount of prepare time a customer will need to wait for their order. :rtype: int >>> c = Customer('1\t23215\t13\t4\t8') >>> c.prep() 4 """ return self._prepare_time def __repr__(self): """ Represent Customer(self) as a string that can be evaluated to produce an equivalent Customer. @rtype: str >>> c = Customer('1\t23215\t13\t4\t8') >>> c 23215 """ return str(self._id) def __str__(self): """ Return a user-friendly string representation of Customer self. @:rtype: str >>> c = Customer('1\t23215\t13\t4\t8') >>> print(c) Id: 23215, Entry: 1, Profit: 13.0, Prep: 4, Patience: 8 """ return 'Id: {}, Entry: {}, Profit: {}, Prep: {}, Patience: {}' \ .format(self.id(), self._entry_time, self.profit(), self.prep(), self._patience) def __eq__(self, other): """ determine whether or not Customer self is equivalent to Other @:type other: Any Any object to compare with self @:rtype: bool >>> c1 = Customer('1\t23215\t13\t4\t8') >>> c2 = Customer('3\t22222\t11\t12\t13') >>> c3 = Customer('1\t23215\t13\t4\t8') >>> c1 == c2 False >>> c1 == c3 True """ return (type(self) == type(other)) and \ (self.id(), self.entry_turn(), self.profit(), self.prep(), self.patience()) == \ (other.id(), other.entry_turn(), other.profit(), other.prep(), other.patience()) if __name__ == '__main__': import doctest doctest.testmod()
d22208def77d5cba9de07162f1a9d7f84049455f
WilsonTandya/DedBot
/src/regex.py
2,937
3.515625
4
import re def regex_tanggal(tanggal): # Tanggal dengan format XX NAMA_BULAN YYYY tanggal = tanggal.lower() bulan = 'januari|februari|maret|april|mei|juni|juli|agustus|september|oktober|november|desember' pattern = r'[0-9]{1,2}\s(' + bulan + ')' + r'\s[0-9]{4,4}' x = re.search(pattern, tanggal) if x : return x.group() else: return "" def regex_kodekuliah(kode): kd = kode.lower() # Kode mata kuliah yang valid adalah IFXYAA, dimana X [1-9], Y [0-3], A [0-9] pattern = r'if[1-9][0-3][0-9][0-9]' x = re.search(pattern, kd) if x: return x.group() else: return "" def regex_katapenting(kata): kata = kata.lower() kata_penting = "kuis|ujian|tucil|tubes|praktikum" pattern = r'(' + kata_penting + r')' x = re.search(pattern, kata) if (x): return x.group() else: return "" def regex_topik(topik): # Asumsi panjang sebuah topik selalu dua kata # dan diawali dengan kata topik # contoh : Tubes IF2240 dengan topik String Matching pada tanggal 22/03/2021 # maka topik: String Matching topik = topik.lower() pattern = r'topik\s[a-zA-Z0-9-,_]+\s[a-zA-Z0-9-,_]+' x = re.search(pattern, topik) if x: return x.group() else: return "" def regex_lihattask(kalimat): kalimat = kalimat.lower() bulan = 'januari|februari|maret|april|mei|juni|juli|agustus|september|oktober|november|desember' pattern_date = r'[0-9]{1,2}\s(' + bulan + ')' + r'\s[0-9]{4,4}' pattern_periode = pattern_date + r'\ssampai\s' + pattern_date pattern_N_minggu = r'[1-9]{1,3}\sminggu\ske\sdepan' pattern_N_hari = r'[0-9]{1,9}\shari\ske\sdepan' pattern_hari_ini = r'hari\sini' a = re.search(pattern_periode, kalimat) b = re.search(pattern_N_minggu, kalimat) c = re.search(pattern_N_hari, kalimat) d = re.search(pattern_hari_ini, kalimat) status = [] extract = [] if a: status.append(True) extract.append(a.group()) else: status.append(False) extract.append("") if b: status.append(True) extract.append(b.group()) else: status.append(False) extract.append("") if c: status.append(True) extract.append(c.group()) else: status.append(False) extract.append("") if d: status.append(True) extract.append(d.group()) else: status.append(False) extract.append("") return status, extract def regex_get_nTask(kalimat): pattern = r'task\s[0-9]{1,5}' x = re.search(pattern, kalimat) if x: temp = x.group() temp = temp.split(" ")[1] return int(temp) else: return -1 def regex_tugas(kalimat): pattern = r'tugas' x = re.search(pattern, kalimat.lower()) if x: return x.group() else: return ""
8fba49bdde14ee42105b1fb166423d7dc713b028
ricardovergarat/1-programacion
/Python/Utilidad/Paquetes/Paquetes mios/paquetes de python/Modulos Paquetes y Namespaces/funciones/paquete1/matematica.py
156
3.5
4
def suma(numero1, numero2): resultado = numero1 + numero2 return resultado def resta(numero1, numero2): resultado = numero1 - numero2 return resultado
343ee055ff68588d94dfb2622fa088550a9828a4
dipalira/LeetCode
/String/345.py
513
3.6875
4
s = "leetcode" def reverseString(s): """ :type s: str :rtype: str """ start = 0 end = len(s) - 1 s = list(s) vowels = set(list("aeiou")) while (start < end): if (s[start] in "aeiou") and (s[end] in "aeiou" ): s[start], s[end] = s[end] ,s[start] start +=1 end-=1 elif s[start] not in "aeiou": start +=1 elif s[end] not in "aeiou": end -= 1 return ''.join(s) print(reverseString(s))
fc78249cea41af1185722f0ad3dd2683d66d39a9
ahmadzaidan99/Codewars
/Persistent_Bugger.py
236
3.5
4
def persistence(n): arr = [int(x) for x in str(n)] count = 0 while(len(arr)!=1): result=1 count += 1 for x in arr: result *= x arr = [int(x) for x in str(result)] return count
b8f3ccadb2536ca6e34d1159d23e0424541f7654
oolsson/oo_eclipse
/Practise_stuff/object/object2.py
761
3.984375
4
''' Created on Jan 29, 2012 @author: oo ''' class className: def createName(self,name): self.name=name def displayName(self): return self.name def saying(self): print 'hello %s' % self.name #creates the object first=className() #sets the name i to equal to oskar first.createName('oskar') #prints the value returned by desplay name which gets its name from the create name function print first.displayName() first.saying() #This will copy the blueprint from the firs class and create a second object from it class childclass(className): pass second=childclass() second.createName('hakan') second.saying() #you can also create multiple objects from same class FYI
c7a17c2445d3a9f32926e40293010f6041f242ca
lucatray/PythonPractice
/zillion.py
2,913
3.703125
4
class Zillion: def __init__(self, string): self.digits = [] if len(string) == 0: raise RuntimeError else: length = 0 while length < len(string): if string[length] >= '0' and string[length] <= '9': self.digits.append(string[length]) length = length + 1 elif string[length] == ' ' or string[length] == ',': pass else: raise RuntimeError def increment(self): b = len(self.digits) - 1 while b >= 0: if self.digits[b] == '9': self.digits[b] = '0' elif b == 0: if self.digits[0] == '9': self.digits[0] = '1' self.digits.append('0') else: self.digits[0] = self.digits[0] + 1 else: self.digits[b] = self.digits[b] + 1 break b = b - 1 def isZero(self): d = 0 while d <= len(self.digits) - 1: if self.digits[d] == 0: d += 1 else: return True return False def toString(self): return str(self.digits) try: z = Zillion('') except RuntimeError: print('Empty string') # It must print 'Empty string' without apostrophes. 2 points. try: z = Zillion(' , ') except RuntimeError: print('No digits in the string') # It must print 'No digits in the string' without apostrophes. 2 points. try: z = Zillion('1+0') except RuntimeError: print('Non-digit in the string') # It must print 'Non-digit in the string' without apostrophes. 2 points. try: z = Zillion('0') except RuntimeError: print('This must not be printed') # It must print nothing. 2 points. print(z.isZero()) # It must print True. 2 points. try: z = Zillion('000000000') except RuntimeError: print('This must not be printed') # It must print nothing. 2 points. print(z.isZero()) # It must print True. 2 points. try: z = Zillion('000 000 000') except RuntimeError: print('This must not be printed') # It must print nothing. 2 points. print(z.isZero()) # It must print True. 2 points. try: z = Zillion('997') except RuntimeError: print('This must not be printed') # It must print nothing. 2 points. print(z.isZero()) # It must print False. 2 points. print(z.toString()) # It must print 997. 2 points. z.increment() print(z.toString()) # It must print 998. 2 points. z.increment() print(z.toString()) # It must print 999. 2 points. z.increment() print(z.toString()) # It must print 1000. 2 points. try: z = Zillion('0 9,9 9') except: print('This must not be printed') # It must print nothing. 3 points. z.increment() print(z.toString()) # It must print 1000. 2 points.
7b623f77c74d4a6149653d5e0a45c4788a640e0d
correl/euler
/python/e040.py
985
4.1875
4
"""Finding the nth digit of the fractional part of the irrational number. An irrational decimal fraction is created by concatenating the positive integers: 0.12345678910[1]112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If dn represents the nth digit of the fractional part, find the value of the following expression. d1 * d10 * d100 * d1000 * d10000 * d100000 * d1000000 """ from e011 import product def irrational_generator(): i = 0 pos = 0 data = [] while True: i = i + 1 s = str(i) for c in s: yield int(c) def main(): values = [] counter = 0 stops = [10**n for n in range(7)] for i in irrational_generator(): counter = counter + 1 if counter in stops: values.append(i) if counter == max(stops): break print 'Values: ', values print 'Product: ', product(values) if __name__ == '__main__': main()
6be45a8a35fd10aca4db88e0984926485d4c68fb
CoderTag/Python
/Pract/find_prime.py
389
3.921875
4
# Find the number is prime or not import math import sys num = 100 sqrt_num = math.sqrt(num) int_num = int(sqrt_num) ceil_num = math.ceil(sqrt_num) if ceil_num == int_num: print("Not a Prime number. Perfect Square") else: for r in range(2, ceil_num + 1): if num % r == 0: print("Not a Prime number") break else: print("Prime number")
1ed79b6842e40c19e3a00d67f282804a66012384
eldojk/Workspace
/WS/DSTests/algos/math/factorial_tests.py
648
3.515625
4
from unittest import TestCase from DS.algos.math.factorial import iterative_factorial, recursive_factorial class FactorialTestCase(TestCase): def test_iterative_factorial(self): self.assertEqual(120, iterative_factorial(5)) self.assertEqual(1, iterative_factorial(0)) self.assertEqual(24, iterative_factorial(4)) self.assertEqual(1, iterative_factorial(1)) def test_recursive_factorial(self): self.assertEqual(120, recursive_factorial(5)) self.assertEqual(1, recursive_factorial(0)) self.assertEqual(24, recursive_factorial(4)) self.assertEqual(1, recursive_factorial(1))
8ee44b798ebb81abe979b4283ba421a306f0a6bd
snsokolov/contests
/codeforces/556A_zeroes.py
2,674
3.515625
4
#!/usr/bin/env python3 # 556A_zeroes.py - Codeforces.com/problemset/problem/556/A Zeroes quiz by Sergey 2015 # Standard modules import unittest import sys import re # Additional modules ############################################################################### # Zeroes Class ############################################################################### class Zeroes: """ Zeroes representation """ def __init__(self, args): """ Default constructor """ self.list = args def calculate(self): """ Main calcualtion function of the class """ result = 0 for n in self.list: result += 1 if n else -1 return str(abs(result)) ############################################################################### # Executable code ############################################################################### def get_inputs(test_inputs=None): it = iter(test_inputs.split("\n")) if test_inputs else None def uinput(): """ Unit-testable input function wrapper """ if it: return next(it) else: return input() # Getting string inputs num = int(uinput()) ints = [int(n) for n in uinput()] return ints def calculate(test_inputs=None): """ Base class calculate method wrapper """ return Zeroes(get_inputs(test_inputs)).calculate() ############################################################################### # Unit Tests ############################################################################### class unitTests(unittest.TestCase): def test_sample_tests(self): """ Quiz sample tests. Add \n to separate lines """ self.assertEqual(calculate("4\n1100"), "0") self.assertEqual(calculate("5\n01010"), "1") self.assertEqual(calculate("8\n11101111"), "6") str = "1\n" for i in range(2*pow(10, 5)): str += "0" self.assertEqual(calculate(str), "200000") def test_get_inputs(self): """ Input string decoding testing """ self.assertEqual(get_inputs("4\n1100"), [1, 1, 0, 0]) def test_Zeroes_class__basic_functions(self): """ Zeroes class basic functions testing """ # Constructor test d = Zeroes([1, 0, 0, 1]) self.assertEqual(d.list[0], 1) self.assertEqual(d.calculate(), "0") d.list = [1, 0, 0, 0] self.assertEqual(d.calculate(), "2") if __name__ == "__main__": # Avoiding recursion limitaions sys.setrecursionlimit(100000) if sys.argv[-1] == "-ut": unittest.main(argv=[" "]) # Print the result string print(calculate())
9996dac51bbe4a6faf3937ab2f6498b96c4274d6
Duome/data_structure
/queue01.py
1,174
4.03125
4
# -*- coding: utf-8 -*- #从头出,从尾进 class Squeue(object): def __init__(self): self.queue = [] def is_empty(self): return not self.queue def dnqueue(self): assert not self.is_empty() return self.queue.pop(0) def enqueue(self, item): self.queue.append(item) class Lqueue(object): def __init__(self): self.front = None self.rear = None self.size = 0 def is_empty(self): return not self.size def pop(self): assert not self.is_empty() info = self.front self.front = info.next return info.item def prepare(self, item): pin = Node(item) if self.is_empty(): self.front = self.rear = pin else: self.rear.next = pin self.rear = pin self.size += 1 class Node(object): def __init__(self, item): self.item = item self.next = None if __name__ == '__main__': q = Lqueue() print(q.is_empty()) q.prepare(1) print(q.is_empty()) q.prepare(2) print(q.is_empty()) print(q.pop()) print(q.pop()) print(q.is_empty())
88460421daf3cdc0cded2d8744b38eb0621cd00b
ssarup/covid19
/data/LocationDoNotUse.py
1,091
3.71875
4
class LocationDoNotUse(object): """ This class should not be used. It is unsafe. It does not support equality. """ def __init__(self): self._country = None self._state = None self._county = None self._city = None def country(self, country_): self._country = country_ return self def state(self, state_): self._state = state_ return self def county(self, county_): self._county = county_ return self def city(self, city_): self._city = city_ return self def __str__(self): retVal = ['['] if self._country is not None: retVal.append('country = {0}'.format(self._country)) if self._state is not None: retVal.append('state = {0}'.format(self._state)) if self._county is not None: retVal.append('county = {0}'.format(self._county)) if self._city is not None: retVal.append('city = {0}'.format(self._city)) retVal.append(']') return ' ,'.join(retVal)
4a788e1887175fe2f3a36028732348e6b9d665cc
teslamyesla/leetcode
/python/0494-target-sum.py
920
3.859375
4
""" DFS + memo Time complexity: O(l⋅n). The memo array of size l*n has been filled just once. Here, l refers to the range of sum and n refers to the size of nums array. Space complexity: O(l⋅n). The depth of recursion tree can go upto n. The memo array contains l⋅n elements. """ class Solution: def findTargetSumWays(self, nums: List[int], S: int) -> int: memo = {} return self.dfs(nums, 0, S, memo) def dfs(self, nums, idx, target, memo): if (target, idx) in memo: return memo[(target, idx)] if idx == len(nums): if target == 0: return 1 else: return 0 memo[(target, idx)] = self.dfs(nums, idx + 1, target - nums[idx], memo) +\ self.dfs(nums, idx + 1, target + nums[idx], memo) return memo[(target, idx)]
07bf558a32ef3fa977bc67860c7ed9c9159bf3f0
sroopsai/file-management-system
/commandhandler.py
12,688
3.59375
4
""" This program handles the commands passed by the client to server. """ import os import time import pandas class CommandHandler: """ Handles all the commands received from the client. Acts as helper program to the server. Attributes ---------- self.user_id : Username of registered user self.is_login : Login Status of the user self.registered_users : Container which stores usernames of registered users self.logged_in_users : list Container which stores usernames of logged in users Returns ------- Object CommandHandler Object """ ROOT_DIR = "Root/" REGISTERED_USERS_CSV_FILE = "AccessSession/registered_users.csv" LOGGED_IN_USERS_CSV_FILE = "AccessSession/logged_in_users.csv" CSV_HEADING = "username,password\n" def __init__(self): """ Parameters ---------- self.user_id : str Username of registered user self.is_login : bool Login status of the user self.registered_users : list Container which stores usernames of registered users self.logged_in_users : list Container which stores usernames of logged in users self.current_dir : str Current Directory Path of the user, by default this is set to Root/ self.char_count : int Number of characters should be read each time read_file() method is invoked. """ self.user_id = "" self.is_login = None self.registered_users = None self.logged_in_users = None self.current_dir = CommandHandler.ROOT_DIR self.read_index = {} self.char_count = 100 def commands(self): """ Returns ------- commands : str Returns a description of commands that can be exercised by the user while using this system. """ commands = ["""register : To register as a new user, command:register <username> <password> \n""", """login : To login, command:login <username> <password>""", """quit : To logout, command:quit\n""", """change_folder : To change the current path, command:change_folder <name>\n""", """list : Lists all files in the current path, command:list\n""", """read_file : To read content from the file, command:read_file <name>\n""", """write_file : To write content into the file, command:write_file <name> <content>\n""", """create_folder : To create new folder, command:create_folder <name>\n""" ] return "".join(commands) def access_user_info(self): """ Helper method """ if not os.path.exists("AccessSession"): os.mkdir("AccessSession") if not os.path.isfile(CommandHandler.REGISTERED_USERS_CSV_FILE): with open(CommandHandler.REGISTERED_USERS_CSV_FILE, "w") as writer: writer.write(CommandHandler.CSV_HEADING) if not os.path.isfile(CommandHandler.LOGGED_IN_USERS_CSV_FILE): with open(CommandHandler.LOGGED_IN_USERS_CSV_FILE, "w") as writer: writer.write(CommandHandler.CSV_HEADING) self.logged_in_users = pandas.read_csv(CommandHandler.LOGGED_IN_USERS_CSV_FILE) self.registered_users = pandas.read_csv(CommandHandler.REGISTERED_USERS_CSV_FILE) def register(self, user_id, password): """ Registers a new user. The password length specified by the user should be more than 8. Parameters ---------- user_id : str Username of the client password : str Password set by the client Returns ------- str Success! Registered <username> """ self.access_user_info() if user_id in self.registered_users['username'].tolist(): return "\nUsername not available" if len(password) < 8: return "\n Password length should be more than 8 characters." with open(CommandHandler.REGISTERED_USERS_CSV_FILE, "a") as writer: writer.write(user_id+","+password+"\n") if not os.path.exists(self.current_dir): os.mkdir(self.current_dir) os.mkdir(os.path.join(self.current_dir, user_id)) self.user_id = user_id return "\nSuccess! Registered " + self.user_id def login(self, user_id, password): """ Allow the user to login to the system Parameters ---------- user_id : str Username of the logged in user password : str Password of the logged in user Returns ------- str Success <username> Logged into the system """ self.access_user_info() if self.is_login: return "\nAlready logged in" if user_id not in self.registered_users['username'].tolist(): # print (self.registered_users) return "\nYou haven't registered! command: register <username> <password>" if password not in self.registered_users['password'].tolist() and user_id in self.registered_users['username'].tolist(): return "\nSorry, The password you entered is wrong. Please Try Again" if user_id in self.logged_in_users['username'].tolist(): self.is_login = True self.user_id = user_id self.current_dir = self.current_dir + self.user_id return "\nYou logged through another system" self.is_login = True self.user_id = user_id self.current_dir = self.current_dir + self.user_id with open(CommandHandler.LOGGED_IN_USERS_CSV_FILE, "a") as writer: writer.write(user_id + "," + password + "\n") return "Success " + self.user_id + " Logged into the system" def quit(self): """ Quits the client program. Returns ------- str Logged Out """ try: self.access_user_info() with open(CommandHandler.LOGGED_IN_USERS_CSV_FILE, "w") as file: file.write(CommandHandler.CSV_HEADING) user_ids = self.logged_in_users['username'].tolist() passwords = self.logged_in_users['password'].tolist() for index, user_id in enumerate(user_ids): if self.user_id != str(user_id): file.write(user_id +","+passwords[index]) self.is_login = False self.user_id = "" return "\nLogged Out" except KeyError: return "\nForced Logged Out through Keyboard Interruption (CTRL-C)" def create_folder(self, folder): """ Creates a new folder as specified by the logged in user. If specified folder already exists throws an error. Parameters ---------- folder : str Folder Name Returns ------- str Successfully created folder <folder-name> """ if not self.is_login: return "\nLogin to continue" self.access_user_info() path = os.path.join(self.current_dir) try: os.mkdir(os.path.join(path, folder)) except FileExistsError: return "\nThe folder already exists!" return "\nSuccessfully created folder " + folder def change_folder(self, folder): """ Change the current path to the path specified by the logged in user. If the specified path does not exist, throws an error. Parameters ---------- folder : str Folder name Returns ------- str Successfully moved to folder <current-folder> """ if not self.is_login: return "\nLogin to continue" self.access_user_info() if folder == ".." and self.current_dir != CommandHandler.ROOT_DIR + self.user_id: self.current_dir = os.path.dirname(os.path.join(self.current_dir)) return "\nSuccessfully moved to folder " + self.current_dir elif folder == ".." and self.current_dir == CommandHandler.ROOT_DIR + self.user_id: return "\nCannot Move Back from Root/" + self.user_id + " folder" if folder in os.listdir(self.current_dir): self.current_dir = os.path.join(self.current_dir, folder) return "\nSuccessfully Moved to folder " + self.current_dir return "\n No such folder exists" def write_file(self, filename, data): """ Creates a new file and write content to the created file by the logged in user. If the file already exists the content will be appended to the already existing file. Parameters ---------- filename : str Name of the name to which content to be written data : str Content to be written to a file Returns ------- str Created and Written data to file <filename> successfully """ self.access_user_info() if not self.is_login: return "\nLogin to Continue" t_file = [] for file in os.listdir(os.path.join(self.current_dir)): if os.path.isfile(os.path.join(self.current_dir, file)): t_file.append(file) writeable_data = "" path = os.path.join(self.current_dir, filename) for i in data: writeable_data += i if filename in t_file: with open(path, "a+") as file: file.write(writeable_data) return "\nSuccess Written data to file " + filename + " successfully" with open(path, "w+") as file: file.write(writeable_data) return "\nCreated and written data to file " + filename + " successfully" def read_file(self, filename): """ Read the content from the file specified by the logged in user. If the file path does not exist, it throws an error message stating No Such file <filename> exists Parameters ---------- filename : str Name of the file to be read Returns ------- str Read file from <old_index> to <current_index> are <content> """ self.access_user_info() if not self.is_login: return "\nLogin to Continue" try: t_path = os.path.join(self.current_dir, filename) if t_path not in list(self.read_index.keys()): self.read_index[t_path] = 0 with open(t_path, "r") as file: content = file.read() old_index = str(self.read_index[t_path]*self.char_count) index = self.read_index[t_path] data = content[index*self.char_count:(index+1)*self.char_count] self.read_index[t_path] += 1 self.read_index[t_path] %= len(content) // self.char_count + 1 return "\n" + "Reading file from " + old_index + " bytes to " + str(int(old_index)+self.char_count) + " bytes\n"+ data except FileNotFoundError: "\nNo Such file " + filename + "exists!" def list(self): """ Lists out all the files and folders in the user's current file path. Returns ------- str File | Size | Modified Date <file> | <size_of_file> | <time_file_modified> """ self.access_user_info() if not self.is_login: return "\nLogin to Continue!" path = os.path.join(self.current_dir) folders = [] try: for file_name in os.listdir(path): file_stats = os.stat(os.path.join(path, file_name)) folders.append([file_name, str(file_stats.st_size), str(time.ctime(file_stats.st_ctime))]) except NotADirectoryError: return "\nNot A Directory" details = "\nFile | Size | Modified Date" for folder in folders: line = " | ".join([folder[0], folder[1], folder[2]]) + "\n" details += "-----------------------\n" + line return details
4b19e47edf8a22cd98366ca2068d6345e3a839de
derick-droid/pythonbasics
/flags.py
253
3.78125
4
prompt = "\nenter your message here please:" prompt += "\n enter message:" # using flags in while loops active = True while active: message = input(prompt) if message.lower() == "quit": active = False else: print(message)
641711607a138ce1df44f996bca329d0810f65b8
syedareehaquasar/python
/encrypting string.py
1,356
3.859375
4
# def generate_encrypted_string (string): # new = "" # for x in string: # if ord(x)>=65 and ord(x)<=90 or ord(x)>=97 and ord(x)<=122: # if (ord(x)>=65 and ord(x)<=77) or (ord(x)>=97 and ord(x)<=110): # new += chr(ord(x)+13) # else: # new += chr(ord(x)-13) # else: # new += x # return new # print(generate_encrypted_string("this is a SENTENCE")) #.................................................................................................... # def encrypt(input_word): # x = input_word[::-1] # x = x.replace("a","0") # x = x.replace("e","1") # x = x.replace("o","2") # x = x.replace("u","3") # return str(x)+"aca" # def encode(ch : str) -> str: # Replace = {'a' : } # print(encrypt("apple")) #.................................................................................................... # def generate_encrypted_string (string): # new = "nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM" # alphabets = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" # ans = "" # for x in string: # if x in alphabets: # z = alphabets.index(x) # ans += new[z] # else: # ans += x # return ans # print(generate_encrypted_string("this is a SENTENCE"))
8981d1e20e26a2def75105b34768a289ba6de3f1
Splashbeats/EnglishGrammarBattle
/py/testScript.py
1,197
3.640625
4
# I'm expecting 2 breaks sentenceToTest = "Jack went to bed late last night because he studied _____ 1:00 a.m." print("---------------------------------------------------") print("------------------Test Script----------------------") print("---------------------------------------------------") print("Testing: " + sentenceToTest) print("Length:" + str(len(sentenceToTest))) maxCharsPerLine = 40 preferredCharsPerLine = 30 sentence = sentenceToTest length = len(sentence) if(length >= maxCharsPerLine): lines = length // preferredCharsPerLine + 1 print("Lines: " +str(lines)) newLength = length // lines print("Length Per Line: " +str(newLength)) indices = [] for i in range(1, lines): # When we replace the space with \n, it shifts the rest of the letters # so we need (+ i - 1) indices.append(sentence.find(" ", newLength * i - 1) + i - 1) for i in indices: sentence = sentence[0:i] + "\\n" + sentence[i+1:] print("EDIT COMPLETE: " + sentence) print("---------------------------------------------------") print("-------------Test Script COMPLETE------------------") print("---------------------------------------------------")