blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
56ba48cf0244dd48af12d3d2c0d12f88b522ed89
nrshrivatsan/vatsanspiral
/go/primes.py
695
3.546875
4
#Thanks to http://users.softlab.ece.ntua.gr/~ttsiod/primes.html import math import itertools #Thanks to http://users.softlab.ece.ntua.gr/~ttsiod/primes.html #Generates Primes def _primes(): yield 2 primesSoFar = [2] for candidate in itertools.count(3, 2): for prime in (i for i in primesSoFar if i <= int(math.sqrt(candidate))): if 0 == candidate % prime: break else: primesSoFar.append(candidate) yield candidate def main(): pz = [] for p in _primes(): if p > 150000001: break # print p, pz.append(p) return pz if __name__ == "__main__": print main()
eeedc1b6f423c40eeea03cf26eb19a36393ca24e
pavitrawalia/CodeChef_Solutions
/https:/www.codechef.com/problems/TWOSTR.py
286
3.59375
4
# cook your dish here t=int(input()) for tc in range(t): str1=input() str2=input() count=0 for i in range(len(str1)): if str1[i]!=str2[i] and str1[i]!="?" and str2[i]!="?": count+=1 if count==0: print("Yes") else: print("No")
6cefb06721eeb73b5ef54882e6a083360072d7c1
tylerkf/hashcode18
/simulation.py
2,911
3.5
4
class Simulator: # Problem Parameters R = 0 # Number of rows in Grid C = 0 # Number of columns in Grid F = 0 # Number of vehicles in fleet N = 0 # Number of rides B = 0 # Per ride bonus for starting the ride on time T = 0 # Number of steps in simulation # Array storing rides rides = [] # Get length of ride def getRideLength(self,ride): start = rides[ride][0] end = rides[ride][1] return abs(start[0] - end[0]) + abs(start[1] - end[1]) # Loads in problem parameters and rides def loadProblem(filename): f = open(filename, "r", encoding="utf-8") # Loading parameters paramsData = list(map(int,f.readline().split(' '))) # R,C,F,N,B,T Simulator.R = paramsData[0] Simulator.C = paramsData[1] Simulator.F = paramsData[2] Simulator.N = paramsData[3] Simulator.B = paramsData[4] Simulator.T = paramsData[5] # Loading rides Simulator.rides = [0] * Simulator.N for i in range(0,Simulator.N): raw = list(map(int,f.readline()[:-1].split(' '))) ride = [] ride.append([raw[0],raw[1]]) # Start coords ride.append([raw[2],raw[3]]) # End coords ride.append(raw[4]) # Earliest start ride.append(raw[5]) # Latest finish Simulator.rides[i] = ride; # Scores given solution def simulate(solution, inSubmissionFormat=False): score = 0 if len(solution) > Simulator.F: print("That many taxis does not exist!") print(Simulator.F,"<", len(solution)) if len(solution) < Simulator.F: print("Note that the problem allows", Simulator.F, "taxis but the given solution only utilises", len(solution)) for i in range(0, min(Simulator.F,len(solution))): schedule = 0 if inSubmissionFormat: schedule = solution[i][1:] else: schedule = solution[i] t = 0 pos = [0,0] for j in range(0, len(schedule)): if schedule[j] >= Simulator.N: #print("Tried to get ride that doesn't exist", schedule[j], ">= N", Simulator.N) continue ride = Simulator.rides[schedule[j]] # Coordinates start = ride[0] end = ride[1] # Times earliest = ride[2] latest = ride[3] journey_length = abs(start[0] - end[0]) + abs(start[1] - end[1]) start_length = abs(pos[0] - start[0]) + abs(pos[1] - start[1]) total_length = start_length + journey_length end_t = max(earliest + journey_length, t + total_length) if end_t >= Simulator.T: break if end_t <= latest: score += journey_length if t + start_length <= earliest: score += Simulator.B t = end_t pos = end return(score)
977cebe39d0ccdbddedf445b49df79410e1ce2e5
daniel-reich/ubiquitous-fiesta
/fJaZYmdovhzHa7ri3_24.py
174
3.859375
4
def max_collatz(num): results = [num] while num != 1: if num % 2: num = (num * 3) + 1 else: num /= 2 results.append(num) return max(results)
108f13080d0ff9a0666f1ece1d6b32de0de96fb6
shillerben/EncryptedText
/send_text_by_email.py
979
3.578125
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- ''' Created on Jul 10, 2012 Send text message via email @author: user352472 ''' from smtplib import SMTP_SSL as SMTP from email.mime.text import MIMEText def send_text(text, phone, smtp, email, password): numFail = 0 msg = MIMEText(text, 'plain') me = phone msg['To'] = me try: conn = SMTP(smtp) conn.set_debuglevel(True) conn.login(email, password) try: conn.sendmail(me, me, msg.as_string()) finally: conn.close() except KeyboardInterrupt: numFail += 1 if numFail < 3: print('\nTrying again...') send_text(text, phone, smtp, email, password) else: print('\nSending email failed 3 times.') except Exception: numFail += 1 if numFail < 3: send_text(text, phone, smtp, email, password) else: print('Sending email failed 3 times.')
a3657a79f8ddf4af25725878a661439f2a2e0dd2
Tubomi/python3
/廖雪峰python教程习题.py
2,535
3.6875
4
#yield 知识点 def fib(max): n,a,b=0,0,1 while n <max: yield b a,b=b,a+b n=n+1 for i in fib(6): print(i) #map 练习 def normal(n): return n.capitalize() list(map(tiger,['adam','LISA','barT']))#没明白为什么map需要加list才显示,reduce不用) #reduce from functools import reduce def multip(x,y): return x*y reduce(multip,[1,2,3,4,5]) #filter 清除素数 def Prime_number(n): if n<=1: return False for i in range(2,n): if n%i==0: return True #这样写展示的是合数 list(filter(Prime_number,range(1,101))) #二 def Prime_number(n): if n<=1: return False for i in range(2,n): return n%i==0 #这样写展示的是除2以外的偶数 list(filter(Prime_number,range(1,101))) # 取素数 def Prime_number(n): if n<=1: return False for i in range(2,n): if n%i==0: return False return True list(filter(Prime_number,range(1,101))) # 排序 升序降序复杂排序 见网址:http://www.cnblogs.com/whaben/p/6495702.html #装饰器:https://www.cnblogs.com/Egbertbaron/p/7242515.html ______________________________________________ import functools def log(func): @functools.wraps(func) def wrapper(*args, **kw): print('call %s():' % func.__name__) return func(*args, **kw) return wrapper —————————————————————————— @log def now(): print("123") —————————————————————————— now.__name__ **************************************************** import functools def log(text): def decorator(func): @functools.wraps(func) def wrapper(*args, **kw): print ('%s %s():' % (text, func.__name__)) return func(*args, **kw) return wrapper return decorator ——————————————————————————— @log('xad')#非常有意思的一个地方如果为@log 则now1.__name__返回的是decorator def now1(): print("123") —————————————————————————— now1.__name__#log('xad')有text内容 则now1.__name__返回的是now1 #关于小结:https://blog.csdn.net/gba_eagle/article/details/80764749 #函数只在返回时调用 ********************************** #class 类 #python中hasattr()、getattr()、setattr()函数的使用 #https://www.cnblogs.com/zanjiahaoge666/p/7475225.html
ecf85c1268905e465c630c7051dd5ee3ed82f4e4
perrutbruno/change-aws-instancetype
/removequebra.py
254
3.515625
4
# Open the file with read only permit f = open('lista.txt', "r") # use readlines to read all lines in the file # The variable "lines" is a list containing all lines in the file lines = f.readlines() # close the file after reading the lines. f.close()
cd7bf209adac2eabc09dc10e0325844758008719
marimatos/curso-em-video
/tuplas/maior_menor_em tupla.py
433
4.21875
4
''' Programa que gere 5 numeros aleatórios e coloque em uma tupla Depois, mostre a listagem de numeros gerados e tbm indique o menor e maior valor que estão na tupla''' from random import randint numeros = (randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10), randint(1, 10)) print(f'Os números sorteados foram {numeros}') print(f'O maior número é {max(numeros)}') print(f'O menor número é {min(numeros)}')
89c6b08d39402907c4964318076843927f2ff4f6
ytatus94/Leetcode
/lintcode/lintcode_0515_Paint_House.py
3,308
3.625
4
# 序列型 DP, 最值型 DP # 轉移方程: # f[i][0] = min( f[i-1][1]+cost[i-1][0], f[i-1][2]+cost[i-1][0] ) # f[i][0] = 油漆前 i 棟房子,最後一棟房子 (i-1) 顏色是 0 的最小花費 # 房子的編號是從 0 開始,所以油漆前 i 棟房子,那最後一棟房子的編號是 i-1 # f[i-1][1] = 油漆前 i-1 棟房子,最後一棟房子 (i-2) 顏色是 1 的最小花費 # cost[i-1][0] = 當前房子 i-1 漆成顏色 0 的費用 # 需要把各種顏色分開討論 # 初始條件: # f[0][0] = f[0][1] = f[0][2] = 0 # 油漆前 0 棟房子,不用任何花費 # TC = O(N), SC = O(N) from typing import ( List, ) class Solution: """ @param costs: n x 3 cost matrix @return: An integer, the minimum cost to paint all houses """ def min_cost(self, costs: List[List[int]]) -> int: # write your code here number_of_houses = len(costs) # Create an array to save the minimum cost # for painting in 3 different colors # We want to know the minimum cost, so we initialize to infinity f = [ [float('inf'), float('inf'), float('inf')] for i in range(number_of_houses + 1) ] # initialize f[0][0], f[0][1], f[0][2] = 0, 0, 0 # f[i] = minimum cost of painting from house 0 to house i-1 (total i houses) # so the for loop starts from 1 (paint 1 house, which house index = 0) for i in range(1, number_of_houses + 1): f[i][0] = min(f[i-1][1] + costs[i-1][0], f[i-1][2] + costs[i-1][0]) f[i][1] = min(f[i-1][0] + costs[i-1][1], f[i-1][2] + costs[i-1][1]) f[i][2] = min(f[i-1][0] + costs[i-1][2], f[i-1][1] + costs[i-1][2]) return min(f[number_of_houses]) # 改寫一下 from typing import ( List, ) class Solution: """ @param costs: n x 3 cost matrix @return: An integer, the minimum cost to paint all houses """ def min_cost(self, costs: List[List[int]]) -> int: # write your code here number_of_houses = len(costs) # Create an array to save the minimum cost # for painting in 3 different colors # We want to know the minimum cost, so we initialize to infinity f = [ [float('inf'), float('inf'), float('inf')] for i in range(number_of_houses + 1) ] # initialize f[0][0], f[0][1], f[0][2] = 0, 0, 0 colors = [0, 1, 2] # f[i] = minimum cost of painting from house 0 to house i-1 (total i houses) # so the for loop starts from 1 (paint 1 house, which house index = 0) for i in range(1, number_of_houses + 1): # the current house index = i - 1 for current_house_color in colors: # the cost of painting current house = cost[i-1][current_house_color] for previous_house_color in colors: # the color cannot be the same if current_house_color != previous_house_color: f[i][current_house_color] = min( f[i][current_house_color], f[i-1][previous_house_color] + costs[i-1][current_house_color] ) return min(f[number_of_houses])
73cd43f3c2091d1eec866e77778f3568bf2ee00b
kamalvhm/PySparkBasics
/venv/pySpark/Concepts/DateTime.py
3,254
3.828125
4
from pyspark.sql import SparkSession from pyspark.sql.functions import * from pyspark.sql.functions import col # Create SparkSession spark = SparkSession.builder \ .appName('DateTime') \ .getOrCreate() data=[["1","2020-02-01"],["2","2019-03-01"],["3","2021-03-01"]] df=spark.createDataFrame(data,["id","input"]) df.show() #current_date() df.select(current_date().alias("current_date") ).show(1) #date_format() The below example uses date_format() to parses the date and converts from yyyy-dd-mm to MM-dd-yyyy format. df.select(col("input"), date_format(col("input"), "MM-dd-yyyy").alias("date_format") ).show() #to_date() :-Below example converts string in date format yyyy-MM-dd to a DateType yyyy-MM-dd using to_date() # . You can also use this to convert into any specific format. df.select(col("input"), to_date(col("input"), "yyy-MM-dd").alias("to_date") ).show() #datediff():-The below example returns the difference between two dates using datediff(). df.select(col("input"), datediff(current_date(),col("input")).alias("datediff") ).show() #months_between():-The below example returns the months between two dates using months_between(). df.select(col("input"), months_between(current_date(),col("input")).alias("months_between") ).show() #trunc() :-The below example truncates the date at a specified unit using trunc(). df.select(col("input"), trunc(col("input"),"Month").alias("Month_Trunc"), trunc(col("input"),"Year").alias("Month_Year"), trunc(col("input"),"Month").alias("Month_Trunc") ).show() #add_months() , date_add(), date_sub():-Here we are adding and subtracting date and month from a given input. df.select(col("input"), add_months(col("input"),3).alias("add_months"), add_months(col("input"),-3).alias("sub_months"), date_add(col("input"),4).alias("date_add"), date_sub(col("input"),4).alias("date_sub") ).show() #year(), month(), month(),next_day(), weekofyear() df.select(col("input"), year(col("input")).alias("year"), month(col("input")).alias("month"), next_day(col("input"),"Sunday").alias("next_day"), weekofyear(col("input")).alias("weekofyear") ).show() #current_timestamp():-Following are the Timestamp Functions that you can use on SQL and on DataFrame. Let’s learn these with examples. data=[["1","02-01-2020 11 01 19 06"],["2","03-01-2019 12 01 19 406"],["3","03-01-2021 12 01 19 406"]] df2=spark.createDataFrame(data,["id","input"]) df2.show(truncate=False) #current_timestamp():-Below example returns the current timestamp in spark default format yyyy-MM-dd HH:mm:ss df2.select(current_timestamp().alias("current_timestamp") ).show(1,truncate=False) #to_timestamp():-Converts string timestamp to Timestamp type format. df2.select(col("input"), to_timestamp(col("input"), "MM-dd-yyyy HH mm ss SSS").alias("to_timestamp") ).show(truncate=False) #hour, minute,second data=[["1","2020-02-01 11:01:19.06"],["2","2019-03-01 12:01:19.406"],["3","2021-03-01 12:01:19.406"]] df3=spark.createDataFrame(data,["id","input"]) df3.select(col("input"), hour(col("input")).alias("hour"), minute(col("input")).alias("minute"), second(col("input")).alias("second") ).show(truncate=False)
99954e55b1e28b688c0e0254a134fbe12d878883
dr-dos-ok/Code_Jam_Webscraper
/solutions_python/Problem_75/64.py
2,424
3.96875
4
#!/usr/bin/env python3 """Google Code Jam Submission Problem: 2011 Qualification Round B Author: Matt Giuca """ import sys import collections def parse_input(infile): """Consume input for a single case from infile. Return (combiners, destructors, invocation), where: - combiners is a dict mapping two-element strings onto chars, in both directions. For example, 'QFT' creates two map entries 'QF': 'T' and 'FQ': 'T'. - destructors is a multidict mapping chars to sets of chars, in both directions. For example, 'RF' creates two map entries 'R': 'F' and 'F': 'R'. - invocation is a string. """ data = infile.readline().split() c = int(data[0]) combiner_source = data[1:1+c] d = int(data[1+c]) destructor_source = data[1+c+1:1+c+1+d] n = int(data[1+c+1+d]) invocation = data[1+c+1+d+1] assert n == len(invocation) # Build the maps combiners = {} for c in combiner_source: src = c[0:2] dst = c[2] combiners[src] = dst combiners[src[::-1]] = dst destructors = collections.defaultdict(set) for d in destructor_source: destructors[d[0]].add(d[1]) destructors[d[1]].add(d[0]) return combiners, destructors, invocation def handle_case(data): """Given the data structure returned by parse_input, return the answer as a string or stringable value. If parse_input is a generator, should manually call list() on data. """ combiners, destructors, invocation = data stack = [] for e in invocation: # Does this element combine with the one on top of the stack? if len(stack) > 0 and (stack[-1] + e in combiners): # Pop the stack and replace with the combined element stack[-1] = combiners[stack[-1] + e] # Does this element destroy any other in the stack? elif any(d in stack for d in destructors[e]): # Wipe the stack stack = [] else: # Just push the element stack.append(e) # Print the final stack return '[{}]'.format(', '.join(stack)) def main(): numcases = int(sys.stdin.readline()) for casenum in range(numcases): data = parse_input(sys.stdin) answer = handle_case(data) print("Case #{0}: {1}".format(casenum+1, answer)) if __name__ == "__main__": sys.exit(main())
6c60746c3f399ffb87e60c10a6bea0ddff484343
joserequenaidv/my-eoi
/pysp/11-videogames/arkanoid/igame.py
1,456
3.546875
4
import pygame from settings import * class Game: # __INIT__ def __init__(self): pygame.init() pygame.display.set_caption(GAME_TITLE) self.screen = pygame.display.set_mode([WIDTH, HEIGHT]) self.clock = pygame.time.Clock() # START GAME def start_game(self): self.all_sprites = pygame.sprite.Group() self.balls = pygame.sprite.Group() self.bricks = pygame.sprite.Group() self.player = Pad(self, WIDTH // 2, HEIGHT - 64) self.ball = Ball(self, WIDTH // 2, HEIGHT - 128) self.build_brick_wall() self.run() # BRICK WALL def build_brick_wall(self): for x in range(13): for y in range(7): brick_x = 80 + BRICK_WIDTH * x brick_y = 40 + 40 + BRICK_HEIGHT * y + 2*y Brick(self, brick_x, brick_y) # RUN def run(self): self.playing = True while self.playing: self.dt = self.clock.tick(FPS) / 1000 self.events() self.update() self.draw() # EVENTS def events(self): for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() quit() # UPDATE def update(self): self.all_sprites.update() hits = pygame.sprite.spritecollide(self.player, self.balls, False) for ball in hits: game = Game() game.run()
a5c139bdb82bf4080299f9d8e9a89469cd2cacf7
Vaibhav3M/Coding-challenges
/SortingAlgos/InsertionSort.py
473
4.03125
4
class InsertionSort(object): def sort(self, arr): for firstUnsortedIndex in range(1, len(arr)): currElement = arr[firstUnsortedIndex] i = firstUnsortedIndex while (i > 0 and arr[i-1] > currElement): arr[i] = arr[i-1] i-=1 arr[i] = currElement return arr arr = [20, 35, -15, 7, 55, 1, -22] insertionSort = InsertionSort() print(insertionSort.sort(arr))
031c44d38cd34a12c0ea0d442b04dd0a1aba5531
subashhumagain/testgithub
/class.py
1,550
3.53125
4
class Employee: raise_amount=1.04 def __init__(self, first, last, pay): self.first= first self.last = last self.pay = pay self.email = first+ '.'+ last+ '@company' def fullname(self): return '{} {}'.format(self.first, self.last) def apply_raise(self): self.pay = int(self.pay*self.raise_amount) class Developer (Employee): raise_amount=1.10 def __init__(self, first, last, pay, prog_lang): super().__init__(first, last,pay) self.prog_lang=prog_lang class Manager (Employee): def __init__(self, first, last, pay, employees=None): super().__init__(first, last,pay) if employees is None: self.employees = [] else: self.employees= employees def add_emp(self, emp): if emp not in self.employees: self.employees.append(emp) def remove_emp(self, emp): if emp not in self.employees: self.employees.remove(emp) def print_emps(self): for emp in self.employees: print('-->', emp.fullname()) #print(help(Developer)) dev_1= Developer('subash', 'Humagain', 50000, 'python') dev_2= Developer('Test', 'User', 80000, 'java') # mgr_1.add_emp(dev_2) # mgr_1.remove_emp(dev_1) # mgr_1.print_emps() # print(dev_1.pay) # dev_1.apply_raise() # print(dev_1.pay) #print(dev_1.prog_lang) #print(Employee.fullname(emp_1)) #print(isinstance(mgr_1, Developer)) print(issubclass(Developer, Employee))
f3cc5d754dbbbf84801dbf5979253b32d3b1a660
RombosK/GB_1824
/Kopanev_Roman_DZ_9/dz_9_2.py
1,267
4.3125
4
# Реализовать класс Road (дорога). # определить атрибуты: length (длина), width (ширина); # значения атрибутов должны передаваться при создании экземпляра класса; # атрибуты сделать защищёнными; # определить метод расчёта массы асфальта, необходимого для покрытия всей дороги; # использовать формулу: длина * ширина * масса асфальта для покрытия одного кв. метра дороги асфальтом, толщиной в 1 см * число см толщины полотна; # проверить работу метода. # Например: 20 м*5000 м*25 кг*5 см = 12500 т. class Road: _length: int _width: int def __init__(self, length: int, width: int): self._length = length self._width = width def mass(self): m_square = 25 thickness = 5 x = self._length * self._width * m_square * thickness res = f'{x/1000} т' return res road = Road(5000, 20) print(road.mass()) road = Road(3000, 20) print(road.mass())
b9fe5932a2cbf8bdc21a088ab4c5ee1590e7102e
brinel/AdventOfCode
/day1/day1_2.py
471
3.59375
4
import csv # Original code to calculate fuel needed for just the modules def fuel_calc(input): x = open(input) input = csv.reader(x) totalFuel = 0 for mass in input: fuel = 0 modMass = int(mass[0]) while modMass > 8: fuel = fuel + (modMass // 3 - 2) modMass = (modMass // 3 - 2) totalFuel = totalFuel + fuel print(totalFuel) # TODO: Build loop that calculates fuel needed to launch the fuel fuel_calc('inputs_mass.csv')
8da31fc6f1905447b54e91f3672ffa0515c4cfad
TaurusOlson/Infiniworld
/src/config.py
4,766
3.71875
4
#!/usr/bin/python """Key bindings configuration""" # For now this 'configuration manager' only deals with keys defined by the # user. import pygame def read_config(fname): """Read the configuration file and return a dictionary. Parameters: `fname`: the name of the configuration file Returns: A dictionary whose keys are the name of the parameters used in the source code and values are the custom values defined by the user. """ with open(fname, "r") as f: # A bit of pipelining... # Filter out comments lines = [l for l in f.read().split("\n") if not l.startswith("#")] # Lists of parameters and values params_vals = [p.split("=") for p in lines if len(p) > 1] # Clean up the parameters and the values game_params = [x[0].strip() for x in params_vals] custom_vals = [x[1].strip().lower() for x in params_vals] return dict(zip(game_params, custom_vals)) class KeysConfig(object): """This class manages all the keys defined by the user in the configuration file Usage: # Create the instance: >>> keys = KeysConfig('config.txt') # Read the configuration file, convert the keys and attach them to the # instance: >>> keys.run() The config_keys and pygame_keys attribute give respectively access to the keys defined by the user and the Pygame keys >>> print keys.config_keys >>> print keys.pygame_keys """ def __init__(self, config_file): object.__init__(self) self.config_file = config_file def __str__(self): return "KeysConfig object converting config_keys to pygame_keys" def __repr__(self): return "%s" % repr(self) def convert_to_pygame_keys(self): """docstring for convert_to_pygame_keys""" config = read_config(self.config_file) # Keep only configuration keys self.keys_ = [kb for kb in config if kb.startswith('K_')] self.config_keys = {} for key_ in self.keys_: self.config_keys.__setitem__(key_, config[key_]) self.pygame_keys = {"backspace":pygame.K_BACKSPACE, "tab":pygame.K_TAB, "return":pygame.K_RETURN, "^[": pygame.K_ESCAPE, "esc":pygame.K_ESCAPE, "escape":pygame.K_ESCAPE, "colon": pygame.K_COLON, ":":pygame.K_COLON, "hash":pygame.K_HASH, "#":pygame.K_HASH, "caret": pygame.K_CARET, "^":pygame.K_CARET, "period":pygame.K_PERIOD, ".":pygame.K_PERIOD, "space":pygame.K_SPACE, "!":pygame.K_EXCLAIM, "$":pygame.K_DOLLAR, "&":pygame.K_AMPERSAND, "'":pygame.K_QUOTE, "(":pygame.K_LEFTPAREN, ")":pygame.K_RIGHTPAREN, "*":pygame.K_ASTERISK, "+":pygame.K_PLUS, ",":pygame.K_COMMA, "-":pygame.K_MINUS, "/":pygame.K_SLASH, "\\":pygame.K_BACKSLASH, ";":pygame.K_SEMICOLON, "semicolon":pygame.K_SEMICOLON, "<":pygame.K_LESS, "=":pygame.K_EQUALS, ">":pygame.K_GREATER, "?":pygame.K_QUESTION, "@":pygame.K_AT, "[":pygame.K_LEFTBRACKET, "]":pygame.K_RIGHTBRACKET, "_":pygame.K_UNDERSCORE, "`":pygame.K_BACKQUOTE} # Let's be lazy alphanum = 'abcdefghijklmnopqrstuvwxyz0123456789' alphanum_pygame_values = map(lambda x: pygame.__getattribute__("K_%s" %x), alphanum) alphanum_pygame_keys = dict(zip(alphanum, alphanum_pygame_values)) self.pygame_keys.update(alphanum_pygame_keys) def attach_keys(self): """Attach the defined keys to the KeysConfig object. """ for k_game, k_custom in self.config_keys.items(): setattr(self, k_game, self.pygame_keys[k_custom]) def run(self): """Run the convertion and attach the keys to the KeysConfig object""" self.convert_to_pygame_keys() self.attach_keys() return self if __name__ == '__main__': keys = KeysConfig('config.txt').run() print "Keys used:" for k,v in keys.config_keys.items(): print "%24s: %s" % (k, v)
13008e21be4368f4ed3b327777cf70e187eb4a83
pkss123/python2
/print_ex01.py
1,000
3.765625
4
# 파이썬의 표준 출력함수는 print()이며 # 괄호 안에 출력하고 싶은 변수, 상수, 수식 등을 적습니다 # value = 1234; #코드 실행 단축키는 Ctrl + F11 입니다 # print("value") # print(value * 2) # print("3+4") # # 4 * 5 #print()로 감싸지 않으면 계산을 하지만 결과를 출력하지않음 # 변수와 문자열을 함께 출력하려면 + 기호로 연결하면됩니다 #혹은 ,로 나열해도 됩니다 # a="10" # print("a에 저장된 값은" + a + "입니다") # print("a에 저장된 값은", a, "입니다") # print()구문은 자동으로 마지막에 커서가 다음줄로 넘어가도록 # 설정되어 있습니다. 그러나 다음줄로 커서를 넘기기 싫다면 # end 라는 요소를 이용합니다 print(123, end=",") print(456) # 퀴즈 print("서울",end=" ") print("대전",end=" ") print("대구",end=" ") print("부산",end=" ") print("광주",end=" ") print("제주",end=" ")
82b7f26d03d77f4eb2e54a00ffbda2bbbdc76e1b
benbendaisy/CommunicationCodes
/python_module/examples/248_Strobogrammatic_Number_III.py
3,101
3.515625
4
from typing import List class Solution: def compareTwoStrs(self, str1: str, str2: str): return int(str1) >= int(str2) def strobogrammaticInRange(self, low: str, high: str) -> int: n1, n2 = len(low), len(high) res = [] oddArray = ["0", "1", "8"] evenArray = [""] def generateStroboGrammatic(n: int, arr: List, isOdd: bool): reversePairs = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"} currentLength = 1 if isOdd else 0 currentArray = oddArray if isOdd else evenArray while currentLength < n: currentLength += 2 newQ = [] for item in currentArray: for key in reversePairs: temp = key + item + reversePairs[key] if self.compareTwoStrs(temp, low) and self.compareTwoStrs(high, temp) and temp[0] != "0": arr.append(temp) newQ.append(temp) currentArray = newQ for x in oddArray: if self.compareTwoStrs(x, low) and self.compareTwoStrs(high, x): res.append(x) generateStroboGrammatic(n2, res, True) generateStroboGrammatic(n2, res, False) return len(res) def strobogrammaticInRange1(self, low: str, high: str) -> int: def compareTwoStrs(str1: str, str2: str): return int(str1) >= int(str2) reversePairs = {"0":"0", "1":"1", "6":"9", "8":"8", "9":"6"} n1, n2 = len(low), len(high) oddArray = ["0", "1", "8"] if n2 < 2: return len([x for x in oddArray if x <= high and x >= low]) evenArray = [""] res = [] for item in oddArray: if compareTwoStrs(item, low) and compareTwoStrs(high, item): res.append(item) currentLength = 1 while currentLength < n2: currentLength += 2 newQ = [] for item in oddArray: for key in reversePairs: if key != 0 or currentLength < n2: temp = key + item + reversePairs[key] if compareTwoStrs(temp, low) and compareTwoStrs(high, temp) and temp[0] != "0": res.append(temp) newQ.append(temp) oddArray = newQ currentLength = 0 while currentLength < n2: currentLength += 2 newQ = [] for item in evenArray: for key in reversePairs: if key != 0 or currentLength < n2: temp = key + item + reversePairs[key] if compareTwoStrs(temp, low) and compareTwoStrs(high, temp) and temp[0] != "0": res.append(temp) newQ.append(temp) evenArray = newQ return len(res) if __name__ == "__main__": low = "0" high = "100" solution = Solution() ret = solution.strobogrammaticInRange(low, high) print(ret)
f6d6e2eaafb2d5428134063134c1f9b095b28e41
hhlp/Number-Systems
/Main.py
5,203
3.65625
4
import os import sys import time import keyboard from BinaryToDecimal import BinaryToDecimal from DecimalToBinary import DecimalToBinary from DecimalToHex import DecimalToHex from HexToDecimal import HexToDecimal base_menu = str(""" [ Number System Converter ] [0] Exit [1] Binary [2] Hexadecimal """) def base_selection(): bases = { "0": sys.exit, "1": binary, "2": hexadecimal } while True: os.system("cls") print(base_menu) print("[ Base Selection ]") try: choice = str(int(input(" >> "))) if -1 > int(choice) > 2: print("Please enter a number between 0 and 2") time.sleep(2) continue except TypeError: print("Please enter a number") time.sleep(2) continue method = bases[choice] return method() def binary(): methods = {"0": base_selection, "1": BinaryToDecimal, "2": DecimalToBinary} while True: os.system("cls") print("[ Binary Convertion ]\n\n[0] Back\n[1] Convert Binary\n[2] Convert Decimal\n") try: print("[ Base Selection ]") choice = str(int(input(" >> "))) if -1 > int(choice) > 2: print("Please enter a number between 0 and 2") time.sleep(2) continue except TypeError: print("Please enter a number") time.sleep(2) continue method = methods[choice] if method == base_selection: return base_selection() elif method == BinaryToDecimal: while True: os.system("cls") print("[ Binary to Decimal Convertion ]\nEnter Binary:") try: convert_me = str(input(" >> ")) except: print("Enter a binary string please..") time.sleep(2) continue os.system("cls") print(f"\nResult: {BinaryToDecimal(convert_me)}") return continue_or_stop() elif method == DecimalToBinary: while True: os.system("cls") print("[ Decimal to Binary Convertion ]\nEnter Decimal:") try: convert_me = str(input(" >> ")) except: print("Enter a numerical string please..") time.sleep(2) continue os.system("cls") print(f"\nResult: {DecimalToBinary(convert_me)}") return continue_or_stop() def hexadecimal(): methods = {"0": base_selection, "1": HexToDecimal, "2": DecimalToHex} while True: os.system("cls") print("[ Hexadecimal Convertion ]\n\n[0] Back\n[1] Convert Hexadecimal\n[2] Convert Decimal\n") try: print("[ Base Selection ]") choice = str(int(input(" >> "))) if -1 > int(choice) > 2: print("Please enter a number between 0 and 2") time.sleep(2) continue except TypeError: print("Please enter a number") time.sleep(2) continue method = methods[choice] if method == base_selection: return base_selection() elif method == HexToDecimal: while True: os.system("cls") print("[ Hexadecimal to Decimal Convertion ]\nEnter Hexadecimal:") try: convert_me = str(input(" >> ")) except: print("Enter a hexadecimal string please..") time.sleep(2) continue os.system("cls") print(f"\nResult: {HexToDecimal(convert_me)}") return continue_or_stop() elif method == DecimalToHex: while True: os.system("cls") print("[ Decimal to Hexadecimal Convertion ]\nEnter Decimal:") try: convert_me = str(input(" >> ")) except: print("Enter a numerical string please..") time.sleep(2) continue os.system("cls") print(f"\nResult: {DecimalToHex(convert_me)}") return continue_or_stop() def continue_or_stop(): try: print("\nConvertion Complete...\n\n" "Press Space to continue\n" "Press Escape to exit\n") while True: if keyboard.is_pressed("space"): base_selection() elif keyboard.is_pressed("escape"): break except: while True: if keyboard.is_pressed("space"): base_selection() elif keyboard.is_pressed("escape"): break if __name__ == "__main__": base_selection()
5d756474142bc98db0106d40e9228a7b26572062
takat0m0/MIP_formalism_examples
/lot_sizing/other_formalism/demands.py
493
3.640625
4
# -*- coding:utf-8 -*- import os import sys import numpy as np from days import Days MAX_DEMAND = 30 class Demands(object): def __init__(self, days): self.__data = [0 for _ in days.get_all_days_list()] for day in days.get_target_days_list(): self.__data[day] = np.random.randint(0, MAX_DEMAND) def __getitem__(self, day): return self.__data[day] if __name__ == '__main__': days = Days() d = Demands(days) print(d[20])
a59ae8c6d2c7e7ea826fcde5d075f938147300a9
shen-huang/selfteaching-python-camp
/19100201/wiltonwung/d3_exercise_calculator.py
1,354
4.09375
4
#自学训练营第一个程序,献给非常喜欢计算器的王有梧。 #1.定义四则运算 def plus(a ,b): #定义加法 return a + b #输出结果 def minus(a , b): #定义减法 return a - b #得出结果 def by(a ,b ):#定义乘法 return a*b def div(a ,b):#定义除法 return a/b #2.给出运算选项 print("可进行的运算行:") print("1.加") print("2.减") print("3.乘") print("4.除") #给出四则运算选项 choice = input("请选择要进行的运算(1,2,3,4): ") numb1 = float(input("请输入要运算的数字1:"))#要求输入要运算的第一个数字 numb2 = float(input("请输入要运算的数字2:"))#要求输入要运算的第二个数字 if choice == '1':#如果选择加法运算 print(numb1 ,"+" ,numb2,"=", plus(numb1,numb2) )#列出计算式和计算出的结果 elif choice == '2':#如果选择减法哟算 print(numb1, "-", numb2,"=", minus(numb1,numb2))#列出计算式和计算出的结果 elif choice == '3':#如果选择乘法 print(numb1 ,"x" ,numb2 ,"=", by(numb1,numb2))#列出计算式和计算出的结果 elif choice== '4':#如果选择除法 print(numb1, "➗" ,numb2 ,"=", div(numb1,numb2))#列出计算式和计算出的结果 else: print("请输入正确的数字或选择给定的运算方式")#如果输入错误的给出处理建议
0d5679e034771d07a4787cddc863de0974810746
behrouzmadahian/python
/python-Interview/12-graphs/9-find-kCores.py
3,542
3.59375
4
''' Given an Undirected graph G and an integer K, K-cores of the graph are connected components that are left after all vertices of degree less than k have been removed. The standard algorithm to find a k-core graph is to remove all the vertices that have degree less than- ‘K’ from the input graph. We must be careful that removing a vertex reduces the degree of all the vertices adjacent to it, hence the degree of adjacent vertices can also drop below-‘K’. And thus, we may have to remove those vertices also. To implement above algorithm, we do a modified DFS on the input graph and delete all the vertices having degree less than ‘K’, then update degrees of all the adjacent vertices, and if their degree falls below ‘K’ we will delete them too. O(V + E) where V is number of vertices and E is number of edges. ''' from collections import defaultdict class Graph: def __init__(self, verticies): self.V = verticies # number of vertices self.graph = defaultdict(list) # function to add an edge to undirected graph def addEdge(self, u, v): self.graph[u].append(v) self.graph[v].append(u) # a recursive function to call DFS starting from v. # it returns true if vDegree of v after processing is less than k else False # also, updates vDegree of adjacent if vDegree of v is less than k # and if vDegree of a processed adjacent becomes less than k, then it reduces vDegree of v also def DFSUtil(self, v, visited, vDegree, k): # mark the current node as visited visited[v] = True # recur for all vertices adjacent to v # if vDegree of v is less than k, then vDegree of adjacent must be reduced( since later we remove v!) for node in self.graph[v]: if vDegree[v] < k: vDegree[node] -= 1 if visited[node] == False: # If vDegree of adjacent after processing becomes # less than k, then reduce vDegree of v also if self.DFSUtil(node, visited, vDegree, k): vDegree[v] -=1 return vDegree[v] < k # TRUE if degree of v less than k def printKCores(self, k): # initialization: visited = [False]* self.V # store vDegrees of al verticies: vDegree = [0] * self.V for i in self.graph: vDegree[i] = len(self.graph[i]) # choose any vertex as starting vertex self.DFSUtil(0, visited, vDegree, k) # DFS traversal to update vDegree of all vertices in case they are unconnected for i in range(self.V): if visited[i] == False: self.DFSUtil(i, visited, vDegree, k) #printing k cores: for v in range(self.V): if vDegree[v] >= k: print(str("\n [ ") + str(v) + str(" ]")) # Traverse adjacency list of v and print only # those adjacent which have vvDegree >= k # after DFS for i in self.graph[v]: if vDegree[i] >= k: print( "-> " + str(i)) k = 3 g1 = Graph (9) g1.addEdge(0, 1) g1.addEdge(0, 2) g1.addEdge(1, 2) g1.addEdge(1, 5) g1.addEdge(2, 3) g1.addEdge(2, 4) g1.addEdge(2, 5) g1.addEdge(2, 6) g1.addEdge(3, 4) g1.addEdge(3, 6) g1.addEdge(3, 7) g1.addEdge(4, 6) g1.addEdge(4, 7) g1.addEdge(5, 6) g1.addEdge(5, 8) g1.addEdge(6, 7) g1.addEdge(6, 8) g1.printKCores(k)
dc1c538124a113ff4941972b0b0d9416beba2d6a
IP-Algorithmics/Udacity
/Course/Data structures and algorithms/3.Basic algorithm/1.Basic algorithms/6.trie_introduction.py
7,422
4.5
4
#!/usr/bin/env python # coding: utf-8 # # Trie # You've learned about Trees and Binary Search Trees. In this notebook, you'll learn about a new type of Tree called Trie. Before we dive into the details, let's talk about the kind of problem Trie can help with. # # Let's say you want to build software that provides spell check. This software will only say if the word is valid or not. It doesn't give suggested words. From the knowledge you've already learned, how would you build this? # # The simplest solution is to have a hashmap of all known words. It would take O(1) to see if a word exists, but the memory size would be O(n\*m), where n is the number of words and m is the length of the word. Let's see how a Trie can help decrease the memory usage while sacrificing a little on performance. # # ## Basic Trie # Let's look at a basic Trie with the following words: "a", "add", and "hi" # In[ ]: basic_trie = { # a and add word 'a': { 'd': { 'd': {'word_end': True}, 'word_end': False}, 'word_end': True}, # hi word 'h': { 'i': {'word_end': True}, 'word_end': False}} print('Is "a" a word: {}'.format(basic_trie['a']['word_end'])) print('Is "ad" a word: {}'.format(basic_trie['a']['d']['word_end'])) print('Is "add" a word: {}'.format(basic_trie['a']['d']['d']['word_end'])) # You can lookup a word by checking if `word_end` is `True` after traversing all the characters in the word. Let's look at the word "hi". The first letter is "h", so you would call `basic_trie['h']`. The second letter is "i", so you would call `basic_trie['h']['i']`. Since there's no more letters left, you would see if this is a valid word by getting the value of `word_end`. Now you have `basic_trie['h']['i']['word_end']` with `True` or `False` if the word exists. # # In `basic_trie`, words "a" and "add" overlapp. This is where a Trie saves memory. Instead of having "a" and "add" in different cells, their characters treated like nodes in a tree. Let's see how we would check if a word exists in `basic_trie`. # In[ ]: def is_word(word): """ Look for the word in `basic_trie` """ current_node = basic_trie for char in word: if char not in current_node: return False current_node = current_node[char] return current_node['word_end'] # Test words test_words = ['ap', 'add'] for word in test_words: if is_word(word): print('"{}" is a word.'.format(word)) else: print('"{}" is not a word.'.format(word)) # The `is_word` starts with the root node, `basic_trie`. It traverses each character (`char`) in the word (`word`). If a character doesn't exist while traversing, this means the word doesn't exist in the trie. Once all the characters are traversed, the function returns the value of `current_node['word_end']`. # # You might notice the function `is_word` is similar to a binary search tree traversal. Since Trie is a tree, it makes sense that we would use a type of tree traversal. Now that you've seen a basic example of a Trie, let's build something more familiar. # ## Trie Using a Class # Just like most tree data structures, let's use classes to build the Trie. Implement two functions for the `Trie` class below. Implement `add` to add a word to the Trie. Implement `exists` to return `True` if the word exist in the trie and `False` if the word doesn't exist in the trie. # # In[ ]: class TrieNode(object): def __init__(self): self.is_word = False self.children = {} class Trie(object): def __init__(self): self.root = TrieNode() def add(self, word): """ Add `word` to trie """ pass def exists(self, word): """ Check if word exists in trie """ pass # <span class="graffiti-highlight graffiti-id_h7y0qpa-id_pncadbt"><i></i><button>Show Solution</button></span> # In[ ]: word_list = ['apple', 'bear', 'goo', 'good', 'goodbye', 'goods', 'goodwill', 'gooses' ,'zebra'] word_trie = Trie() # Add words for word in word_list: word_trie.add(word) # Test words test_words = ['bear', 'goo', 'good', 'goos'] for word in test_words: if word_trie.exists(word): print('"{}" is a word.'.format(word)) else: print('"{}" is not a word.'.format(word)) # In[ ]: class TrieNode(object): def __init__(self): self.is_word = False self.children = {} class Trie(object): def __init__(self): self.root = TrieNode() def add(self, word): """ Add `word` to trie """ current_node = self.root for char in word: if char not in current_node.children: current_node.children[char] = TrieNode() current_node = current_node.children[char] current_node.is_word = True def exists(self, word): """ Check if word exists in trie """ current_node = self.root for char in word: if char not in current_node.children: return False current_node = current_node.children[char] return current_node.is_word # ## Trie using Defaultdict (Optional) # This is an optional section. Feel free to skip this and go to the next section of the classroom. # # A cleaner way to build a trie is with a Python default dictionary. The following `TrieNod` class is using `collections.defaultdict` instead of a normal dictionary. # In[ ]: import collections class TrieNode: def __init__(self): self.children = collections.defaultdict(TrieNode) self.is_word = False # Implement the `add` and `exists` function below using the new `TrieNode` class. # In[ ]: class Trie(object): def __init__(self): self.root = TrieNode() def add(self, word): """ Add `word` to trie """ pass def exists(self, word): """ Check if word exists in trie """ pass # <span class="graffiti-highlight graffiti-id_158726u-id_461jk1b"><i></i><button>Hide Solution</button></span> # In[ ]: class Trie(object): def __init__(self): self.root = TrieNode() def add(self, word): """ Add `word` to trie """ current_node = self.root for char in word: current_node = current_node.children[char] current_node.is_word = True def exists(self, word): """ Check if word exists in trie """ current_node = self.root for char in word: if char not in current_node.children: return False current_node = current_node.children[char] return current_node.is_word # In[ ]: # Add words valid_words = ['the', 'a', 'there', 'answer', 'any', 'by', 'bye', 'their'] word_trie = Trie() for valid_word in valid_words: word_trie.add(valid_word) # Tests assert word_trie.exists('the') assert word_trie.exists('any') assert not word_trie.exists('these') assert not word_trie.exists('zzz') print('All tests passed!') # The Trie data structure is part of the family of Tree data structures. It shines when dealing with sequence data, whether it's characters, words, or network nodes. When working on a problem with sequence data, ask yourself if a Trie is right for the job.
2c59840ac0e1da14d058442465933b46e93bc5b2
HelenaJanda/pyladies-7
/soubory/domaci-ukoly/08_kostky.py
1,612
3.75
4
# -*- coding: UTF-8 -*- # Napiš program, který simuluje tuto hru: # První hráč hází kostkou (t.j. vybírají se náhodná čísla od 1 do 6), dokud nepadne šestka. Potom hází další hráč, # dokud nepadne šestka i jemu. Potom hází hráč třetí, a nakonec čtvrtý. Vyhrává ten, kdo na hození šestky # potřeboval nejvíc hodů. (V případě shody vyhraje ten, kdo házel dřív.) # Program by měl vypisovat všechny hody, a nakonec napsat, kdo vyhrál. import random def hazej_dokud_nepadne_6(): pocet_hodu = 0 while True: pocet_hodu = pocet_hodu + 1 hod = random.randrange(6) + 1 print("Hrac hodil {}".format(hod)) if hod == 6: print("Hraci se podarilo hodit 6 na pocet hodu: {}".format(pocet_hodu)) return pocet_hodu def hraj(pocet_hracu): vitezny_hrac = 0 vitezny_pocet_hodu = 0 for cislo_hrace in range(1, pocet_hracu+1): print("Hraje hrac cislo {}".format(cislo_hrace)) pocet_hodu = hazej_dokud_nepadne_6() if pocet_hodu < vitezny_pocet_hodu or vitezny_pocet_hodu == 0: print("Hrac {} je nyni aktualni vitez s poctem hodu {}".format(cislo_hrace, pocet_hodu)) vitezny_hrac = cislo_hrace vitezny_pocet_hodu = pocet_hodu else: print ("{} neni dost dobry vysledek aby prekonal {}".format(pocet_hodu, vitezny_pocet_hodu)) print("---------------------------------") print ("Vitezi hrac {} s poctem hodu {}".format(vitezny_hrac, vitezny_pocet_hodu)) pocet_hracu = int(input("Zadej pocet hracu ")) hraj(pocet_hracu)
2678d6dbf56499f48d5780852a40446057c43457
SamuelNarciso/Analizador_Sintactico
/AnalizadorSintactico/Logic.py
7,473
3.828125
4
import Search import alphabet class Logic: def CheckSintax(self, string, var, errores): if self.SintaxLogic(string): simbol = self.CheckTypes(string) # now we have de simbol and split the string aux = string.split(simbol) # search the vars result, T, index = Search.Search().Search_Name(var, aux[0]) if result: if T == 'int' or T == 'float': self.ComapareteNumber(aux,var,string,index,errores,simbol) pass else: self.ComparateSring(simbol,aux,errores,string,var,index,T) pass else: errores.append('Error variable no declarada '+aux[0]) else: errores.append('Error de sintaxis '+string) return errores def ComparateSring(self,simbol,aux,errores,string,var,index,T): if simbol=='==' or simbol=='<>': if self.IsNumber(aux[1]) and ("'" in aux[1] or '"' in aux[1])==False: errores.append( 'Error no se permite esa operacion '+ string ) else: #check if the thing has any " or ' if '"' in aux[1] or "'" in aux[1]: #Comparate var with a value #now we have to check that the sintax value if self.SintaxValue(aux[1]): errores.append('Cadena correcta '+string+' '+ str(self.OperationSimbols(simbol, var[index].value, aux[1] ) )) pass else: errores.append('Error en la comparacion '+string) pass else: #here is for comparete var #search the second var re, t, indice = Search.Search().Search_Name(var, aux[1]) if re: if t==T: errores.append('Cadena correcta '+string+ ' '+ str( self.OperationSimbols( simbol, var[index].value, var[indice].value ) ) ) pass else: errores.append( 'Error las variables no son del mismo'+ 'Tipo '+string ) pass else: errores.append('Error variable no delclarda '+aux[1]) pass pass else: errores.append('Error no se permite esa operacion '+string) def SintaxValue(self,value): number_simbol=0 for x in value: if '"' in x or "'" in x: number_simbol+=1 return number_simbol==2 def OperationSimbols(self,simbol,value1,value2): if simbol=='==': return value1==value2 if simbol=='<>': return value1!=value2 return False def ComapareteNumber(self,aux,var,string,index,errores,simbol): # see if the value after the simbol is a var or a number if self.IsNumber(aux[1]): if var[index].value != None: errores.append('Cadena correcta '+string) else: errores.append('Error la variable ' + string+' No tiene un valor definido') else: # search the bar re, t, indice = Search.Search().Search_Name(var, aux[1]) if re: if var[index].value != None and var[indice].value != None: errores.append('Cadena correcta '+string+' ' + str(self.DoOperation( int(var[index].value), simbol, int(var[indice].value)))) else: errores.append('Error varibale sin valor '+string) else: errores.append('Error Variable no declarada '+string) def DoOperation(self, data1, l, data2): if '<' in l and ('=' in l or '>' in l) == False: return data1 < data2 if '>' in l and ('=' in l or '<' in l) == False: return data1 > data2 if '<=' in l: return data1 <= data2 if '>=' in l: return data1 >= data2 if '<>' in l: return data1 != data2 if '==' in l: return data1 == data2 pass def CheckTypes(self, l): simbol = '' if '<' in l and ('=' in l or '>' in l) == False: simbol = '<' if '>' in l and ('=' in l or '<' in l) == False: simbol = '>' if '<=' in l: simbol = '<=' if '>=' in l: simbol = '>=' if '<>' in l: simbol = '<>' if '==' in l: simbol = '==' return simbol def IsNumber(self, value): for e in value: if (e in alphabet.Alphabet().NumberDecimal()) == False: return False return True def SintaxLogic(self, cadena): c = [0, 0, 0, 0, 0, 0] s = [0, 0, 0, 0, 0, 0] s[0] = len(list(filter(None, cadena.split('<')))) s[1] = len(list(filter(None, cadena.split('>')))) s[2] = len(list(filter(None, cadena.split('<=')))) s[3] = len(list(filter(None, cadena.split('>=')))) s[4] = len(list(filter(None, cadena.split('==')))) s[5] = len(list(filter(None, cadena.split('<>')))) if len(cadena) < 3: return False for letra in cadena: if letra == '<': c[0] = c[0]+1 if letra == '>': c[1] = c[1]+1 for x in range(len(cadena)-1): if cadena[x]+''+cadena[x+1] == '<=': c[2] = c[2]+1 if cadena[x]+''+cadena[x+1] == '>=': c[3] = c[3]+1 if cadena[x]+''+cadena[x+1] == '==': c[4] = c[4]+1 if cadena[x]+''+cadena[x+1] == '<>': c[5] = c[5]+1 if(c[0] == 1 and c[1] == 0 and c[2] == 1 and c[3] == 0 and c[4] == 0 and c[5] == 0 and s[2] == 2): return True if(c[0] == 1 and c[1] == 1 and c[2] == 0 and c[3] == 0 and c[4] == 0 and c[5] == 1 and s[5] == 2): return True if(c[0] == 1 and c[1] == 0 and c[2] == 0 and c[3] == 0 and c[4] == 0 and c[5] == 0 and s[0] == 2): return True if(c[0] == 0 and c[1] == 1 and c[2] == 0 and c[3] == 1 and c[4] == 0 and c[5] == 0 and s[3] == 2): return True if(c[0] == 0 and c[1] == 1 and c[2] == 0 and c[3] == 0 and c[4] == 0 and c[5] == 0 and s[1] == 2): return True if(c[0] == 0 and c[1] == 0 and c[2] == 0 and c[3] == 0 and c[4] == 1 and c[5] == 0 and s[4] == 2): return True return False
1464c22dd956d5b0960710759981df37cb2e073a
zjxpirate/Daily-Upload-Python
/Linked_Lists/Linked_Lists_singly_linked_list_basic_1.py
3,243
4
4
class Node: def __init__(self, data): self.data = data self.next = None class LinkedList: def __init__(self): self.head = None def listLength(self): currentNode = self.head length = 0 while currentNode is not None: length += 1 currentNode = currentNode.next return length def isListEmpty(self): if self.listLength() == 0: return True else: return False def insertHead(self, newNode): temporaryNode = self.head self.head = newNode self.head.next = temporaryNode del temporaryNode def insertBetween(self, newNode, position): if position < 0 or position > self.listLength(): print("Invalid position") return if position is 0: self.insertHead(newNode) return currentNode = self.head currentPosition = 0 while True: if currentPosition == position: previousNode.next = newNode newNode.next = currentNode break previousNode = currentNode currentNode = currentNode.next currentPosition += 1 def insertEnd(self, newNode): if self.head is None: self.head = newNode else: lastNode = self.head while True: if lastNode.next is None: break lastNode = lastNode.next lastNode.next = newNode def deleteHead(self): if self.isListEmpty() is False: previousHead = self.head self.head = self.head.next previousHead.next = None else: print("List is empty delete failed") def deleteBetween(self, position): if position < 0 or position >= self.listLength(): print("Invalid position") return if self.isListEmpty() is False: if position is 0: self.deleteHead() return currentNode = self.head currentPosition = 0 while True: if currentPosition == position: previousNode.next = currentNode.next currentNode.next = None break previousNode = currentNode currentNode = currentNode.next currentPosition += 1 def deleteEnd(self): lastNode = self.head while lastNode.next is not None: previousNode = lastNode lastNode = lastNode.next previousNode.next = None def printList(self): if self.head is None: print("List is empty") return currentNode = self.head while True: if currentNode is None: break print(currentNode.data) currentNode = currentNode.next l1 = LinkedList() firstNode = Node("John") l1.insertEnd(firstNode) secondNode = Node("name in the head") l1.insertHead(secondNode) thirdNode = Node("name in between") l1.insertBetween(thirdNode, 1) l1.printList()
89b65bd9103b6465e5f70b3cfeb4a4f444de6cb1
AmRiyaz-py/Python-Arsenal
/All about Looping in python/problem2A3CO.py
185
4.46875
4
''' Program :- print the half pyramid of A using for loop Author :- AmRiyaz Last Modified :- April 2021 ''' n = 5 a = "" for i in range(1,n+1): a = a + "A" print(a)
fdc28b2b0f7060a57015043997de6fcc4d3403c4
lholliger/ShiftPass
/shiftpass.py
2,867
3.734375
4
import string import sys current_arg_pos = 0 import binascii current_version = "01" # THIS CHANGES WITH EVERY ENCODING UPDATE TO PREVENT ERRORS askpass = True askstr = True asktype = True force = False for x in sys.argv: if (x == "-e" or x == "--encrypt"): fc = "-e" asktype = False; if (x == "-d" or x == "--decrypt"): fc = "-d" asktype = False; if (x == "-p" or x == "--password"): askpass = False password = sys.argv[current_arg_pos+1] if (x == "-s" or x == "--string"): askstr = False tocrypt = sys.argv[current_arg_pos+1] if (x == "-f" or x == "--force"): force = True if (x == "-h" or x == "--help"): print(""" ShiftPass Encryption System by DatOneLefty help usage: python shiftpass [args] arguments: -e: encrypt string -d: decrypt string -f: force decoding an older version -p [password] define password to use instead of asking in the script -s [string] define string to use instead of asking in the script """) current_arg_pos = current_arg_pos + 1 if asktype == True: ect = input("encrypt or decrypt (e/d): ") if (ect == "e"): fc = "-e" elif (ect == "d"): fc = "-d" else: sys.exit("invalid answer. must be e or d") if askpass == True: password = input("password: ") if askstr == True: if (fc == "-e"): tocrypt = input("string to encrypt: ") if (fc == "-d"): tocrypt = input("string to decrypt: ") if (fc == "-d"): enc1 = tocrypt; tocrypt = enc1.split("=")[1] version = enc1.split("=")[0] tocrypt = binascii.unhexlify(tocrypt).decode('utf8') if (force == False): if (version != current_version): sys.exit("Fatal Error: the string to decrypt was encrypted using an old version and will not work! add -f to the command to force decoding"); cplace = -1 plen = len(password) crypted = "" all_string_pos = [] all_pass_pos = [] for pc in password: all_pass_pos.append(ord(pc)) for tc in tocrypt: all_string_pos.append(ord(tc)) pos = -1 for piece in all_string_pos: cplace = cplace + 1 pos = pos + 1 if cplace == plen: cplace = 0 if fc == "-e": all_string_pos[pos] = (all_string_pos[pos] + all_pass_pos[cplace]) % 255 if fc == "-d": all_string_pos[pos] = (all_string_pos[pos] - all_pass_pos[cplace]) % 255 if fc == "-e": for piece in all_string_pos: crypted = crypted + chr(piece) if fc == "-d": for piece in all_string_pos: crypted = crypted + chr(piece) if (fc == "-e"): print("01=" + binascii.hexlify(crypted.encode('utf8')).decode("utf-8")) if (fc == "-d"): print(crypted)
80d043074d8f403a1b2c27682accd8d58eb416ad
agnesliszka/Python-for-Web---infoShare-Academy
/my_own_projects/theday06/3.allegro_parsel_css_&_xpath/beautiful_soup_example.py
1,047
3.609375
4
import os import requests from bs4 import BeautifulSoup # Function to get page from url if file does not exist, if file exists open the file def get_page(url, filename): if os.path.isfile(filename): with open(filename, 'r', encoding='utf-8') as input_data: content = input_data.read() else: response = requests.get(url) content = response.text with open(filename, 'w', encoding='utf-8') as output_data: output_data.write(content) return content # Function to get all searched instances from the content of the file def find_all_links(content, soup_instance): return soup_instance.find_all('a') # return soup_instance.find_all('img') # Get page from url and get all searched instances from the content of the file if __name__ == '__main__': url = 'https://www.wakacyjnipiraci.pl/' filename = 'wakacyjnipiraci.html' html_content = get_page(url, filename) soup = BeautifulSoup(html_content, 'html.parser') print(find_all_links(html_content, soup))
50bba9bc900810afef9f531c664bb52f93cb7192
roguishmountain/dailyprogrammer
/miniChallenge24Ramp.py
517
4
4
__author__ = 'srs' ''' Ramp Numbers - A ramp number is a number whose digits from left to right either only rise or stay the same. 1234 is a ramp number as is 1124. 1032 is not. Given: A positive integer, n. Output: The number of ramp numbers less than n. ''' import sys n = sys.argv[1] def ramp(n): count = 0 for num in range(0, n): splitNum = list(str(num)) if "".join(sorted(splitNum)) == str(num): count += 1 print "there were", count, "ramp numbers" ramp(int(n))
ecc5ae4c24b61bcc5084932639b6ca6129e3559d
dlwnstjd/python
/pythonex/0811/conprehensionex1.py
859
4
4
''' Created on 2020. 8. 11. @author: GDJ24 컴프리헨션 예제 패턴이 있는 list, dictionary, set을 간편하게 작성할 수 있는 기능 ''' numbers = [] for n in range(1,11): numbers.append(n) print(numbers) #컴프리헨션 표현 print([x for x in range(1,11)]) clist = [x for x in range(1,11)] print(clist) #1~10까지의 짝수 리스트 생성 evenlist = [] for n in range(1,11): if n % 2 == 0: evenlist.append(n) print(evenlist) #컴프리헨션 표현 evenlist = [x for x in range(1,11) if x % 2 == 0] print(evenlist) #2의 배수이고, 3의 배수인 값만 리스트에 추가하기 evenlist = [x for x in range(1,11) if x % 2 == 0 if x % 3 == 0] print(evenlist) #중첩사용 컴프리 헨션 사용하기 matrix = [[1,2,3],[4,5,6],[7,8,9]] print(matrix) list1 = [x for row in matrix for x in row] print(list1)
51da6a0b75d83fd09872fb423cca06f7a7b4ceb3
Stanford-ILIAD/Learn-Imperfect-Varying-Dynamics
/imperfect_envs/driving/agents.py
1,986
3.546875
4
from driving.entities import RectangleEntity, CircleEntity from driving.geometry import Point # For colors, we use tkinter colors. See http://www.science.smith.edu/dftwiki/index.php/Color_Charts_for_TKinter class Car(RectangleEntity): def __init__( self, center: Point, heading: float, color: str = "red", min_acc: float = -4.0, max_acc: float = 4.0, ): size = Point(2.0, 1.0) movable = True friction = 0.06 super(Car, self).__init__( center, heading, size, movable, friction, min_acc=min_acc, max_acc=max_acc ) self.color = color self.collidable = True class Pedestrian(CircleEntity): def __init__(self, center: Point, heading: float, color: str = "LightSalmon2"): radius = 0.4 movable = True friction = 0.2 super(Pedestrian, self).__init__(center, heading, radius, movable, friction) self.color = color self.collidable = True class Building(RectangleEntity): def __init__(self, center: Point, size: Point, color: str = "gray26", heading=0.0): movable = False friction = 0.0 super(Building, self).__init__(center, heading, size, movable, friction) self.color = color self.collidable = True class Painting(RectangleEntity): def __init__(self, center: Point, size: Point, color: str = "gray26"): heading = 0.0 movable = False friction = 0.0 super(Painting, self).__init__(center, heading, size, movable, friction) self.color = color self.collidable = False class Goal(RectangleEntity): def __init__(self, center: Point, radius: float, heading: float, color: str = "LightSalmon2"): size = Point(radius, radius) movable = False friction = 0.2 super(Goal, self).__init__(center, heading, size, movable, friction) self.color = color self.collidable = True
aeb8036f667b8d579939bc394da2545c727b32f2
anton-dovnar/LeetCode
/String/Easy/657.py
453
3.703125
4
""" Robot Return to Origin """ class Solution: def judgeCircle(self, moves: str) -> bool: x_axis = 0 y_axis = 0 table_moves = { "U": 1, "D": -1, "L": -1, "R": 1 } for move in moves: if move in "LR": x_axis += table_moves[move] else: y_axis += table_moves[move] return (x_axis, y_axis) == (0, 0)
eb5a2e547e9a993dd5e7452bf8fc42791323ff72
djreiss/pynkey
/plot.py
7,900
3.609375
4
import pandas as pd import numpy as np from matplotlib import pyplot as plt print 'importing plot' import globals import params def setup_text_plots(fontsize=8, usetex=True): """ This function adjusts matplotlib settings so that all figures in the textbook have a uniform format and look. """ import matplotlib matplotlib.rc('legend', fontsize=fontsize, handlelength=3) matplotlib.rc('axes', titlesize=fontsize, labelsize=fontsize) matplotlib.rc('xtick', labelsize=fontsize) matplotlib.rc('ytick', labelsize=fontsize) matplotlib.rc('text', usetex=usetex) ## see https://stackoverflow.com/questions/12322738/how-do-i-change-the-axis-tick-font-in-a-matplotlib-plot-when-rendering-using-lat ##matplotlib.rc('text.latex', preamble=r'\usepackage{cmbright}') matplotlib.rc('mathtext', fontset='stixsans') matplotlib.rc('font', size=fontsize, family='sans-serif', style='normal', variant='normal', stretch='normal', weight='normal') def plot_stats(): stats = globals.stats_df ##print stats.tail() ## This is a good intro to pandas dataframes ## http://pandas.pydata.org/pandas-docs/stable/10min.html ## try plotting it. using astroML/book_figures/chapter1/fig_SDSS_imaging.py as an example ## this fuinction sets up the plots to look the same as in the astroML text ## Quick and dirty way to plot: ## glb.stats_df[['iter','ROWS','COLS','RESID','STRING_DENS','MEME_PVAL','CLUSTS_PER_ROW','CLUSTS_PER_COL','N_MOVES','N_IMPROVEMENTS','N_CLUSTS_CHANGED_ROWS','N_CLUSTS_CHANGED_COLS']].plot(x='iter',subplots=True, layout=(3,4), figsize=(8,8), sharex=True, legend=False) setup_text_plots(fontsize=8, usetex=True) ##plot_kwargs = dict(color='k', linestyle='none', marker=',') plot_kwargs = dict(color='k', marker=',') plt.close() ## close previous window if exists fig = plt.figure(figsize=(10, 8)) # Now plot with matplotlib ax1 = fig.add_subplot(3,3,1) ax1.plot(stats.iter, stats.RESID, **plot_kwargs) ax1.set_ylabel('Residual') ax1.set_xlabel('Iteration') ax2 = fig.add_subplot(3,3,2) ##, sharex=ax1) vals = stats[["iter", "MEME_PVAL"]].dropna(how="any").values ax2.plot(vals[:, 0], vals[:, 1], **plot_kwargs) ax2.set_ylabel('Motif p-value') ax2.set_xlabel('Iteration') ax3 = fig.add_subplot(3,3,3) vals = stats[["iter", "STRING_DENS"]].dropna(how="any").values ax3.plot(vals[:, 0], vals[:, 1], **plot_kwargs) ax3.set_ylabel('Avg STRING Network Density') ax3.set_xlabel('Iteration') ax4 = fig.add_subplot(3,3,4) plot_kwargs = dict(marker=',') vals = stats[["iter", "r0"]].dropna(how="any").values ax4.plot(vals[:, 0], vals[:, 1], color='k', **plot_kwargs) vals = stats[["iter", "m0"]].dropna(how="any").values ax4.plot(vals[:, 0], vals[:, 1], color='r', **plot_kwargs) vals = stats[["iter", "n0"]].dropna(how="any").values ax4.plot(vals[:, 0], vals[:, 1], color='g', **plot_kwargs) vals = stats[["iter", "c0"]].dropna(how="any").values ax4.plot(vals[:, 0], vals[:, 1]/10.0, color='b', **plot_kwargs) vals = stats[["iter", "v0"]].dropna(how="any").values ax4.plot(vals[:, 0], vals[:, 1], color='c', **plot_kwargs) vals = stats[["iter", "g0"]].dropna(how="any").values ax4.plot(vals[:, 0], vals[:, 1], color='m', **plot_kwargs) ax4.set_xlabel('Iteration') ax4.set_ylabel('Scaling') text_kwargs = dict(transform=plt.gca().transAxes, ha='center', va='bottom') ax4.text(0.12, 0.9, 'r0', color='k', **text_kwargs) ax4.text(0.24, 0.9, 'm0', color='r', **text_kwargs) ax4.text(0.36, 0.9, 'n0', color='g', **text_kwargs) ax4.text(0.48, 0.9, 'c0/10', color='b', **text_kwargs) ax4.text(0.60, 0.9, 'v0', color='c', **text_kwargs) ax4.text(0.72, 0.9, 'g0', color='m', **text_kwargs) ax2a = fig.add_subplot(3,3,5) ##, sharex=ax1) vals = stats[["iter", "ROWS"]].dropna(how="any").values ax2a.plot(vals[:, 0], vals[:, 1], color='b', **plot_kwargs) vals = stats[["iter", "COLS"]].dropna(how="any").values ax2a.plot(vals[:, 0], vals[:, 1], color='r', **plot_kwargs) ax2a.set_ylabel('Avg Number') text_kwargs = dict(transform=plt.gca().transAxes, ha='center', va='bottom') ax2a.text(0.25, 0.9, 'Rows', color='b', **text_kwargs) ax2a.text(0.75, 0.9, 'Cols', color='r', **text_kwargs) ax2a.set_xlabel('Iteration') ## Plot histograms of #genes, #conds in each bicluster ax4a = fig.add_subplot(3,3,6) nrows = np.array( [len(c.rows) for c in globals.clusters.values()] ) plt.hist( nrows, 20 ) ax4a.set_xlabel('Number per cluster') ax4a.set_ylabel('Count') ncols = np.array( [len(c.cols) for c in globals.clusters.values()] ) plt.hist( ncols, 20, color='r' ) text_kwargs = dict(transform=plt.gca().transAxes, ha='center', va='bottom') ax4a.text(0.20, 0.9, 'Rows', color='b', **text_kwargs) ax4a.text(0.80, 0.9, 'Cols', color='r', **text_kwargs) ax5 = fig.add_subplot(3,3,7) vals = stats[["iter", "N_MOVES"]].dropna(how="any").values ax5.plot(vals[:, 0], vals[:, 1], color='k', **plot_kwargs) vals = stats[["iter", "N_IMPROVEMENTS"]].dropna(how="any").values ax5.plot(vals[:, 0], vals[:, 1], color='r', **plot_kwargs) text_kwargs = dict(transform=plt.gca().transAxes, ha='center', va='bottom') ax5.text(0.20, 0.9, 'Num Moves', color='k', **text_kwargs) ax5.text(0.70, 0.9, 'Num Improvements', color='r', **text_kwargs) ax5.set_xlabel('Iteration') ax5.set_ylabel('Count') ax5a = fig.add_subplot(3,3,8) resids = np.array( [c.resid for c in globals.clusters.values()] ) resids = resids[ resids > 0.001 ] if len(resids) > 0: plt.hist( resids, 20 ) ax5a.set_xlabel('Cluster Residuals') ax5a.set_ylabel('Count') ax6 = fig.add_subplot(3,3,9) pclusts = np.array( [c.meanp_meme for c in globals.clusters.values()] ) pclusts = pclusts[ ~np.isnan(pclusts) & ~np.isinf(pclusts) ] if len(pclusts) > 0: plt.hist( pclusts, 20 ) ax6.set_xlabel('Cluster Mean log10(P-value)s') ax6.set_ylabel('Count') plt.show() # def plot_scores(scores): ## plot scores dataframe from floc.get_scores_all() # setup_text_plots(fontsize=8, usetex=True) # ##plot_kwargs = dict(color='k', linestyle='none', marker=',') # plot_kwargs = dict(color='k', marker=',') # plt.close() ## close previous window if exists # fig = plt.figure(figsize=(10, 8)) # ax1 = fig.add_subplot(3,3,1) # ax1.plot(stats.iter, stats.RESID, **plot_kwargs) # ax1.set_ylabel('Residual') # ax1.set_xlabel('Iteration') def plot_motif_logo( memeOut, motInd=1 ): import meme import matplotlib.image as mpimg record = meme.parseMemeOut( memeOut ) kwargs = dict(color_scheme='classic') record[motInd].weblogo('file.png', color_scheme='color_classic') ## note, can use format='PDF' img = mpimg.imread('file.png') imgplot = plt.imshow( img ) if __name__ == '__main__': ## see https://docs.python.org/2/library/optparse.html from optparse import OptionParser parser = OptionParser() parser.add_option("-o", "--organism", dest="organism", help="input organism [default: %default]", metavar="ORGANISM", default='Hpy') parser.add_option("-i", "--iter", dest="iter", type=int, help="desired iteration to plot [default: %default]", metavar="ITER", default='100') (options, args) = parser.parse_args() import init import os.path try: iter = options.iter #if os.path.exists( 'output/%s_%04d.pkl' % (options.organism, iter) ): init.init( 'output/%s_%04d.pkl' % (options.organism, iter) ) except: init.init( 'output/%s.pkl' % options.organism ) plot_stats()
21303aaa45fe0d86146faad076187e4bc5429222
bmontambault/LDA
/models.py
8,177
3.53125
4
import numpy as np """ This file defines the Model class, which defines utilities for evaluating error rate and generating learning curves, and class for Bayesian logistic regression """ class Model(object): """ Parent class for models. Defines evaluation utilities """ def test(self, X, y, add_dim=False): """ Evaluate error rate of trained model Parameters: array X: (N,M) data with N instances and M features array y: (N,) labels bool add_dim: concatenate column of 1's to fit intercept if true """ if add_dim: X = X.copy() X = np.hstack((np.ones(len(X))[:,None], X)) pp = self.predict(X, add_dim=False).ravel() pp_pred = (pp >=.5).astype(int) return (pp_pred != y).astype(int).sum() / len(y) def learning_curve(self, X, y, args={}, other_params=[], runs=30, m=10, test_size=.4, add_dim=False, max_train_size=np.inf): """ Generate learning curve for model Parameters: array X: (N,M) data with N instances and M features array y: (N,) labels dict args: parameters to pass to models fit function list other_params: other parameters to keep track of int runs: number of runs to generate average error int m: number of training sizes to test bool add_dim: concatenate column of 1's to fit intercept if true """ n = X.shape[0] test_size = int(n*test_size) train_size = min(n - test_size, max_train_size) min_size = int(n/m) step = (train_size - min_size)/(m-1) train_sizes = np.arange(min_size, train_size+step, step).astype(int) all_error_rates = [] all_params = {k:[] for k in other_params} i = 0 while i < runs: try: random_idx = np.arange(len(X)) np.random.shuffle(random_idx) shuffled_X = X[random_idx,:] shuffled_y = y[random_idx] testX = shuffled_X[:test_size] testy = shuffled_y[:test_size] error_rates = [] params = {k:[] for k in other_params} for j in train_sizes: trainX = shuffled_X[test_size: test_size+j] trainy = shuffled_y[test_size: test_size+j] self.fit(trainX, trainy, **args) error_rate = self.test(testX, testy, add_dim=add_dim) error_rates.append(error_rate) for param in other_params: params[param].append(getattr(self, param)) all_error_rates.append(error_rates) for param in other_params: all_params[param].append(params[param]) #restart run if ipdb import error from GPy except Exception as e: if e.msg == "No module named 'ipdb'": continue else: raise e i+=1 all_error_rates = np.array(all_error_rates) self.learning_curve_mean = all_error_rates.mean(axis=0) self.learning_curve_std = all_error_rates.std(axis=0) self.learning_curve_sizes = train_sizes self.all_params_mean = {k: np.array(all_params[k]).mean(axis=0) for k in all_params.keys()} self.all_params_std= {k: np.array(all_params[k]).std(axis=0) for k in all_params.keys()} class LogisticRegression(Model): """ Bayesian logistic regression """ def prob(self, X, w, add_dim=False): """ Get predictive probability for X given w array X: (N,M) data with N instances and M features array w: (M,) weights bool add_dim: concatenate column of 1's to fit intercept if true """ if add_dim: X = X.copy() X = np.hstack((np.ones(len(X))[:,None], X)) z = np.dot(X, w) p = np.exp(z) return p / (1. + p) def grad_log_posterior(self, X, y, w, alpha): """ Return gradient of the log map likelihood array X: (N,M) data with N instances and M features array y: (N,) labels array w: (M,) weights float alpha: prior (precision) on weights """ mu = self.prob(X, w) H = np.eye(X.shape[1])*alpha grad = np.dot(X.T, (mu - y)) + np.dot(H, w) return grad def hess_log_posterior(self, X, y, w, alpha): """ Return Hessian of the log map likelihood array X: (N,M) data with N instances and M features array y: (N,) labels array w: (M,) weights float alpha: prior (precision) on weights """ mu = self.prob(X, w) S = np.eye(X.shape[1])*alpha R = mu * (1. - mu) hess = np.dot(X.T, X * R[:,None]) + S return hess def newton_raphson(self, X, y, alpha, maxiter=100): """ Perform newton-raphson optimization to find the optimal value of w array X: (N,M) data with N instances and M features array y: (N,) labels float alpha: prior (precision) on weights int maxiter: maximum number of iterations """ w = np.zeros(X.shape[1]) for i in range(maxiter): grad = self.grad_log_posterior(X, y, w, alpha) hess = self.hess_log_posterior(X, y, w, alpha) inv_hess = np.linalg.inv(hess) delta = np.dot(inv_hess, grad) new_w = w - delta eps = ((new_w - w)**2).sum() / (new_w**2).sum() if eps < 10**-3: w = new_w break w = new_w #print ('Newton-Raphson converged in ' + str(i) + ' iterations') return w def fit(self, X, y, alpha=1, maxiter=100, maximize_evidence=False): """ Fit logistic regression model Parameters: array X: (N,M) data with N instances and M features array y: (N,) labels float alpha: prior (precision) on weights int maxiter: maximum number of iterations bool maximize_evidence: find optimal value of alpha if true """ if maximize_evidence: self.maximize_evidence(X, y) else: X = X.copy() X = np.hstack((np.ones(len(X))[:,None], X)) w = self.newton_raphson(X, y, alpha, maxiter) S = self.hess_log_posterior(X, y, w, alpha) self.w = w self.S = S def predict(self, X, add_dim=True): """ Get p(y=1|X) for new X Parameters: array X: (N,M) data with N instances and M features array y: (N,) labels bool add_dim: concatenate column of 1's to fit intercept if true """ if add_dim: X = X.copy() X = np.hstack((np.ones(len(X))[:,None], X)) S_inv = np.linalg.inv(self.S) sig = np.sum(X * np.dot(S_inv, X.T).T, axis=1) noise = 1. / np.sqrt(1. + 0.125 * np.pi * sig) z = np.dot(X, self.w) post_z = z * noise pr = np.exp(post_z) return pr / (1 + pr) def maximize_evidence(self, X, y): """ Find optimal prior alpha Parameters: array X: (N,M) data with N instances and M features array y: (N,) labels """ alpha = 1 for l in range(10): self.fit(X, y, alpha) mu = self.prob(X, self.w, add_dim=True) S = mu * (1. - mu) H = np.dot(X.T, X * S[:, np.newaxis]) eigenvals = np.linalg.eigvals(H).astype(float) gamma = (eigenvals / (eigenvals + alpha)).sum() alpha = gamma / (mu**2).sum() self.fit(X, y, alpha) self.alpha = alpha
9c7672eedc378ed61d7c9c7cf0add503c7c36cfa
DanielPascualSenties/pythonw3
/w3resource/Pandas/DataSeries/DataSeries08.py
276
3.859375
4
import pandas s = {'Name': ['Dani', 'Juancho', 'Carol'], 'Age': [30, 33, 31], 'Position': ['Data Engineer', 'DevOps', 'Data Analyst']} print(s) df = pandas.DataFrame(s) print(df) gender = ['M','M', 'F'] df['Gender'] = gender print(df) names = df['Name'] print(names)
ad479feeec683f4791da3daa54f1aefbfc850e96
yash2708/Text-Summarization-ML
/Text_Summarization_final.py
3,720
3.671875
4
# -*- coding: utf-8 -*- """ Created on Mon Oct 19 11:12:21 2020 @author: yashj """ #TEXT SUMMARIZATION #!pip install beautifulsoup4 #Needed to extract the data from website which is in html and xml format #!pip install lxml #Fetching article from wikipedia #Import Libraries # import bs4 as bs #beautifulsoup4 import urllib.request #To extract data from website, also useful for web scrapping import re #regular expression(NLP),to remove unnecessary things from data import nltk #natural language tool kit #nltk.download() #Data Collection/Extraxtion web_url=input() scrapped_data=urllib.request.urlopen(web_url) #print(scrapped_data) #urlopen() to open particular website article = scrapped_data.read() #read() to convert data into readble format #print(article) #data contains HTML tags and attributes #To remove HTML tags beautifulsoup4 library is used. It is very strong library for web scrapping based projects parsed_article=bs.BeautifulSoup(article,'lxml') #print(parsed_article) #Data Preprocessing - I #data is present in paragraph form paragraphs = parsed_article.find_all('p') #paragraph tag #print(paragraphs) article_text="" for p in paragraphs: article_text+=p.text #print(article_text) #Data is free from HTML tags #It is a form of web scrapping #Data Preprocessing - II #Lower Case # #article_text=article_text.lower() #Punctuation Removal # #from string import punctuation #def remove_punctuation(s): # return ''.join(c for c in s if c not in punctuation) ##text="Hello! how are you doing?" ##text=remove_punctuation(text) ##print(text) #article_text=remove_punctuation(article_text) ##print(article_text) #Removal of Numeric Digits # ##To remove the numbers, you can use .isnumeric() or .isdigit() #output=''.join(c for c in article_text if not c.isdigit()) ##print(article_text) #Removing Other things using re # #Removing Square Brackets and extra spaces article_text=re.sub(r'\[[0-9]*\]', ' ',article_text) article_text=re.sub(r'\s+', ' ',article_text) #print(article_text) # Removing Special characters and digits formatted_article_text=re.sub('[^a-zA-Z]',' ',article_text) formatted_article_text=re.sub(r'\s+',' ',formatted_article_text) #print(formatted_article_text) #Tokenization #Converting text to sentences #sentence tokenization sentence_list=nltk.sent_tokenize(article_text) len(sentence_list) #print(sentence_list) #Removing Stopwards #Stopward removal #nltk.download('stopwords') stopwords=nltk.corpus.stopwords.words('english') #Frequencies of words # #Collect the frequency of words word_freq={} for word in nltk.word_tokenize(formatted_article_text): if word not in stopwords: if word not in word_freq.keys(): word_freq[word]=1 else: word_freq[word]+=1 #print(word_freq) #word_freq #Normalization of frequencies #Scaling of frequencies max_freq=max(word_freq.values()) for word in word_freq.keys(): word_freq[word]=(word_freq[word]/max_freq) #print(word_freq[word]) #Calculationg the sentence score # sentence_score = {} #print(sentence_list) for sent in sentence_list: for word in nltk.word_tokenize(sent.lower()): if word in word_freq.keys(): if len(sent.split(' ')) < 30: if sent not in sentence_score.keys(): sentence_score[sent] = word_freq[word] else: sentence_score[sent] += word_freq[word] #print(sentence_score[sent]) #Getting Summary import heapq summary_sentences=heapq.nlargest(7, sentence_score, key=sentence_score.get) summary = ' '.join(summary_sentences) print(summary)
609aced9aa165cf110e6cc9236986443404be1e8
yuyanf/skolePython
/utskriftsfunksjon.py
710
3.5
4
#Programmet skal stille samme spørsmål 3 ganger og skriver ut det brukere har svart til terminalen def utskrift(): #først lager jeg en vanlig input-funksjon kode og gir kode navn som utskrift. siden det brukere skriver inn er tekst, så jeg kan bare legger til utropstegn og punktum ved slutten av input navn = input("Skriv inn navn: ")+"!" bosted = input("Hvor kommer du fra? ")+"." print("Hei,",navn,"Du er fra",bosted) def linjeskift():#navngi kode 2 som linjeskif siden denne er for linjeskift print() utskrift() #nå kjører jeg prosedyren 3 ganger ved å kun skriver navn til kode1 og 2. Her er det viktig å fjerne kolon. linjeskift() utskrift() linjeskift() utskrift()
c137216419d3cce08061f01962a5177319f33bf9
lsh971108/myedu-1904
/day03/for_demo.py
824
3.96875
4
def for_demo(): for dome in range(6,10): print('3.1415926') print(dome) def for_demo1(): for dome in range(6,10,1): print(dome) def for_demo1(): for dome in range(100,10,-10): print(dome) def for_list(): x =[1,2,3,4,5,6,7,8,9] # for p in x: # print(p) for p in range(len(x)): print(x[p]) def for_for(): for i in range(3): print('梁善辉') for j in range(3): print('牛逼',end=',') print('') print('\n') def break_continue(): for i in range(6): print(i) if i ==3: break for i in range(6): if i==3: continue print(i) if __name__ == '__main__': # for_demo() # for_demo1() # for_list() # for_for() break_continue()
00effa8cc2b727cf77bad51ead0712c61306a468
jb3/aoc-2019
/day-1/python/main.py
626
3.9375
4
"""Solution for AoC 2019 day 1.""" part1_fuel = 0 part2_fuel = 0 def calculate_fuel(mass: int) -> int: """Calculate required fuel given mass.""" mass //= 3 mass -= 2 return mass with open("../input") as f: for mass in f: fuel = calculate_fuel(int(mass)) part1_fuel += fuel part2_fuel += fuel last = fuel while True: fuel_for_fuel = calculate_fuel(last) if fuel_for_fuel <= 0: break part2_fuel += fuel_for_fuel last = fuel_for_fuel print(f"Part 1: {part1_fuel}") print(f"Part 2: {part2_fuel}")
c9e0bcb997df6f9d09f70238db49315d010ae7c9
karbekk/Python_Data_Structures
/Interview/Python_Excercises/Generators/Generator_Object.py
697
4.1875
4
# Generator object can be used only once. SO no reuse # If called again its not gonna return anything, it has been already exhausted. Note # it doesnt throw any exception # If next method is called on generator object that has no value, stopiteration expection will # be raised # we can create new generator object to yield the values again def gen(n): for i in range(1,n): if i % 2 == 0: yield i # gen() -> returns a generator object assigned to gen_object variable gen_object = gen(10) # print gen_object.next() # OR # This for loop internally calls the next method on gen_object for value in gen_object: print value for value in gen_object: print value
2852c66ab269d3b2513efedb6cf8dabf403145f5
PriceHardman/ProjectEuler
/16_power_digit_sum/problem_16.py
585
3.8125
4
# Problem 16: Power Digit Sum # 2^15 = 32768, and the sum of its digits is 3+2+7+6+8=26 # What is the sum of the digits of 2^1000? ################################################################################ def digits_of_power(base,power): digits = [1] while power > 0: carry,keep = 0,0 for i,d in enumerate(digits): carry,keep = divmod(base*d+carry,10) digits[i] = keep if carry > 0: digits.append(carry) power -= 1 return list(reversed(digits)) print(sum(digits_of_power(2,1000))) # => 1366
381eac5d581c5392e467024ab13f1e4f3a2b6723
Gaming32/Python-AlgoAnim
/algoanim/sorts/insertion.py
413
3.578125
4
from algoanim.array import Array from algoanim.sort import Sort class InsertionSort(Sort): name = 'Insertion Sort' def run(self, array: Array) -> None: for i in range(1, len(array)): v = array[i] j = i - 1 while j > -1 and array[j] > v: array[j + 1] = array[j] j -= 1 array[j + 1] = v SORT_CLASS = InsertionSort
94ff2cce5f161f45c8f7698ca0cfe744eb8155ec
pqrst/MachineLearningPractice
/Part 1 - Data Preprocessing/dataProcessing.py
2,270
3.640625
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ import numpy as np #any math import matplotlib.pyplot as plt import pandas as pd # variable explorer dataset = pd.read_csv('C:\c\Rawls\online_courses\Machine Learning A-Z Template Folder\Part 1 - Data Preprocessing\Data.csv') # creating a matrix with iloc for all the independent variables X = dataset.iloc[:, :-1].values #first : means all rows, :-1 means all columns except the last one # dependent variables y = dataset.iloc[:, 3].values # in R we dont need to distinguish between dependent variables vactor and matrix of features #Taking care of missing data from sklearn.preprocessing import Imputer #imputer class takes care of missing data imputer = Imputer(missing_values = 'NaN', strategy = 'mean', axis = 0) #ctrl+i for details imputer = imputer.fit(X[:,1:3]) #taking indexes 1 & 2, 3 is the upper bound X[:, 1:3] = imputer.transform(X[:, 1:3]) #missing data is replaced by the means #Encoding categorical data from sklearn.preprocessing import LabelEncoder, OneHotEncoder #for dummy variables labelencoder_X = LabelEncoder() X[:, 0] = labelencoder_X.fit_transform(X[:,0]) #getting encoded values of texts onehotencoder = OneHotEncoder(categorical_features = [0]) X = onehotencoder.fit_transform(X).toarray() #purchased is dependent, so we dont need OneHotEncoder, because the machine knows labelencoder_y = LabelEncoder() y = labelencoder_y.fit_transform(y) #splitting the dataset into Training set and Test set from sklearn.cross_validation import train_test_split #machine learning model will understand the correlation between independent & dependent variables X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) #Feature Scaling from sklearn.preprocessing import StandardScaler #stabdardization or normalization of data sc_X = StandardScaler() X_train = sc_X.fit_transform(X_train) X_test = sc_X.transform(X_test) #we dont need to fit this because sc_X is already fitted to the trainibg set # can you scale dummy variables? it depends # do we need to scale dependent variables? not here, but for regression we will need to scale it
04af8752884223d06051e78229247c39550aeb8d
Soulor0725/PycharmProjects
/python3/南京大学/第二周/lazying_example.py
115
3.75
4
# 列表解析 list1 = [i for i in range(10)] print(list1) list2 = [i+1 for i in range(10) if i%2==0] print(list2)
0e2855ec17e80856b11d94b24cde6b9962807ed2
codewithmojo/social_spider
/spider.py
1,192
3.59375
4
import requests import json def read_username(): username = input("Please insert the username that you want to search: ") if username is None or len(username) == 0: print("The username can't be blank") read_username() else: return username def read_json(filename): with open(filename) as json_file: data = json.load(json_file) return data def check_profile(username, sm_name, url): request = requests.get(url + username) if request.status_code == 200: return sm_name + " : " + url + username else: return (sm_name) print("Welcome to CodeWithMojo Social Spider") print("*************************************") username = read_username() social_media_list = read_json("assets/social_media_urls.json") success = "" fails = [] print("Username: " + username) for social_media in social_media_list: r = check_profile(username, social_media['name'], social_media['url']) + "\n" if (":" in r): success += r else: fails.append(r) if len(fails) > 0: success += "\nNot found username " + username + " in : \n" for fail in fails: success += fail print (success)
f0367f3df4f0d2a04fe1c8f7a4f75673628378ba
fffk3045167/desktop_WSL
/python/binarySearch.py
807
3.703125
4
# 二分搜索是一种在有序数组中查找某一特定元素的搜索算法。 # 返回x在arr中的索引,如果不存在返回-1 def binarySearch(arr, l, arrlen, x): if arrlen >= l: mid = int(l + (arrlen - l) / 2) # 元素正好在中间位置 if arr[mid] == x: return mid elif arr[mid] > x: return binarySearch(arr, l, mid-1, x) else: return binarySearch(arr, mid+1, arrlen, x) else: return -1 def show(index): if index == -1: print("元素不在数组中") else: print("元素在数组中的索引为: {}".format(index)) # 测试数组 arr = [1, 3, 4, 6, 7, 8, 10, 13, 14] x = 10 # 调用函数 show(binarySearch(arr, 0, len(arr)-1, x))
53bc7e154c68665b590468dd9a78b2bc31d024b0
ckidckidckid/leetcode
/LeetCodeSolutions/739.daily-temperatures.python3.py
1,214
4
4
# # [739] Daily Temperatures # # https://leetcode.com/problems/daily-temperatures/description/ # # algorithms # Medium (52.96%) # Total Accepted: 15K # Total Submissions: 28.3K # Testcase Example: '[73,74,75,71,69,72,76,73]' # # # Given a list of daily temperatures, produce a list that, for each day in the # input, tells you how many days you would have to wait until a warmer # temperature. If there is no future day for which this is possible, put 0 # instead. # # For example, given the list temperatures = [73, 74, 75, 71, 69, 72, 76, 73], # your output should be [1, 1, 4, 2, 1, 1, 0, 0]. # # # Note: # The length of temperatures will be in the range [1, 30000]. # Each temperature will be an integer in the range [30, 100]. # # class Solution: def dailyTemperatures(self, temperatures): """ :type temperatures: List[int] :rtype: List[int] """ n = len(temperatures) st = [] ans = [0]*n for idx in range(n-1, -1, -1): t = temperatures[idx] while len(st) > 0 and t >= st[-1][0]: st.pop() ans[idx] = st[-1][1]-idx if len(st)>0 else 0 st.append((t, idx)) return ans
c7f69ed355eee737c19b6baabf2f32a1c1d6eae6
GCatSword/m02_boot_0
/funciones1nivel.py
411
3.65625
4
def normal(x): return x def cuadrado(y): return y * y def cubo(x): return x**3 #Admite funciones como parametros de entrada def sumaTodos(limitTo, f): resultado = 0 for i in range(limitTo +1): resultado += f(i) return resultado if __name__ == '__main__': print(sumaTodos(100, normal)) print(sumaTodos(3, cuadrado)) print(sumaTodos(3, cubo))
9bbb2c57d5042a7f24b718416d11aea47f038053
driverevil/serpento
/hello_2/hello.py
169
3.734375
4
import sys if len(sys.argv) > 1: name = sys.argv[1] else: name = input("Bonvolu diru min vian nomo") if name == '': name = 'Gogeta tiam' print("Saluton", name)
4bc36dc3bc080922ccc14fc4b174976e41a6055d
snaveen1856/Python_Revised_notes
/Core_python/_09_Data_Structures/_03_Sets/_00_Set_methods.py
1,542
4.0625
4
""" Python has a set of built-in methods that you can use on sets. Method Description ------------------------------------------------------------------------------------------------------------ 1.add()=================> Adds an element to the set 2.clear()===============> Removes all the elements from the set 3.copy()================> Returns a copy of the set 4.difference()==========> Returns a set containing the difference between two or more sets 5.difference_update()===> Removes the items in this set that are also included in another, specified set 6.discard()=============> Remove the specified item 7.intersection()========> Returns a set, that is the intersection of two other sets 8.intersection_update()==> Removes the items in this set that are not present in other, specified set(s) 9.isdisjoint()===========> Returns whether two sets have a intersection or not 10.issubset()=============> Returns whether another set contains this set or not 11.issuperset()===========> Returns whether this set contains another set or not 12.pop()==================> Removes an element from the set 13.remove()===============> Removes the specified element 14.symmetric_difference()==> Returns a set with the symmetric differences of two sets 15.symmetric_difference_update()===> inserts the symmetric differences from this set and another 16.union()========================> Return a set containing the union of sets 17.update()=========================> Update the set with the union of this set and others """
62d7634f8e687ad03074cdf464359e8de9e63258
jaegyeongkim/Today-I-Learn
/알고리즘 문제풀이/프로그래머스/Level 2/124 나라의 숫자.py
236
3.5625
4
def solution(n): answer = '' while n > 0: rest = n%3 n = n//3 if rest == 0: n -= 1 rest = 4 print(rest) answer = str(rest) + answer return answer
a88487d219b819247cce6f701b48ff4640d5a5c7
Williamcassimiro/Programas_Basicos_Para_Logica
/Desafio 50.py
220
3.828125
4
soma = 0 cont = 0 for c in range(1 , 7): num = int(input("Informe uma numero:")) if num % 2 == 0: soma = soma + num cont = cont + 1 print("Voce informou só {} numero pares, Soma {}".format(cont, soma))
44f24d749e07871cf8730bb58e12241b31d25667
joomab/python-basics
/adivina_el_numero.py
455
3.9375
4
import random def run(): random_number = random.randint(1,100) number = int(input("Elige un número del 1 al 100: ")) while number != random_number: if number < random_number: print("Pon un número más grande") else: print("Es un número más pequeño") number = int(input("Elige otro número: ")) print("Ganaste") if __name__ == "__main__": run()
056095b8933c21e0523e044b422d5f98ba2febb2
aserran/Python-Game-Portfolio
/Python Othello/OthelloLogic.py
11,609
4.21875
4
# Othello Logic and Console Interface class Game: """ An Othello game. """ color_dict = {'black': 'B', 'white': 'W', 'none': ' '} def __init__(self, rows: int=8, cols: int=8, win_option: str='most', starting_player: str='black', corner_color: str='white'): self.board = self._create_new_board(rows, cols, self.color_dict[corner_color]) self.boardrows = rows self.boardcols = cols self.current_player = starting_player self.winstate_option = win_option self.current_player_piece = self.color_dict[self.current_player] self.black_score = 0 self.white_score = 0 self.update_player_scores() def printboard(self) -> None: """ Prints a textual representation of the board to the console. Includes both players' scores. """ print(' ', end=' ') # print out column guides at the top for i in range(self.boardcols): print(i + 1, end=' ') print() cnt = 1 for row in self.board: print('{} '.format(cnt), end='') # print out row guides at the left cnt += 1 for col in row: if col == ' ': print('.', end=' ') else: print(col, end=' ') print() print('Black: {} White: {}'.format(self.black_score, self.white_score)) def move_phase(self, row: int, col: int) -> None: """ Puts down a piece for the current player in space (row, col). If the space is already occupied, raises an OverlapError exception. If the move is invalid, raises InvalidMoveError. """ if self.board[row][col] != ' ': raise OverlapError elif not self._piece_check(row, col, 'move'): raise InvalidMoveError else: # This block can raise an IndexError if row or col exceeds the board's coordinates self.board[row][col] = self.current_player_piece def flip_phase(self, row: int, col: int) -> None: """ Goes through the board and flips all the lines that the piece played at (row, col) has created. """ inline_pieces_list = self._get_valid_lines(row, col, self.current_player_piece) for rowcol in inline_pieces_list: self._flip_line(row, col, rowcol[0], rowcol[1]) def change_player_phase(self) -> None: """ Changes all current-player-related variables to the next player ( """ self.current_player = self._flip_color(self.current_player) self.current_player_piece = self.color_dict[self.current_player] def player_has_moves(self) -> bool: """ Looks at the current player's pieces and sees if there are any moves available """ result = False for row_index in range(self.boardrows): for col_index in range(self.boardcols): if self.board[row_index][col_index] == self.current_player_piece: result = self._piece_check(row_index, col_index, 'open') if result: return result return result def determine_winner(self) -> str: """ Take the selected game mode into account and returns the winner of the game at the time it's called """ if self.black_score > self.white_score: if self.winstate_option == 'most': return 'Black is the winner!' elif self.winstate_option == 'least': return 'White is the winner!' elif self.black_score < self.white_score: if self.winstate_option == 'most': return 'White is the winner!' elif self.winstate_option == 'least': return 'Black is the winner!' elif self.black_score == self.white_score: return 'It\'s a tie!' def update_player_scores(self) -> None: """ Goes through the board and counts the total number of pieces of both colors """ b_total = 0 w_total = 0 for row in self.board: for col in row: if col == 'B': b_total += 1 elif col == 'W': w_total += 1 self.black_score = b_total self.white_score = w_total def _piece_check(self, row: int, col: int, mode: str) -> bool: """ Looks at all 8 directions from a piece. If mode == 'open', comparator = ' ' and function checks for valid open spaces for the current player. If mode == 'move', comparator = current_player and function checks for pieces of the same color in line with the piece. """ comparator = None if mode == 'open': comparator = ' ' elif mode == 'move': comparator = self.current_player_piece lines_list = self._get_valid_lines(row, col, comparator) if len(lines_list) > 0: return True else: return False def _get_valid_lines(self, row: int, col: int, comparator: str) -> [tuple]: """ Checks for valid pieces in line with the piece at (row, col) and returns their coordinates. If no valid lines were created, returns an empty list. """ return_list = [] left_check = self._single_direction_check(row, col, 0, -1, comparator) right_check = self._single_direction_check(row, col, 0, 1, comparator) up_check = self._single_direction_check(row, col, -1, 0, comparator) down_check = self._single_direction_check(row, col, 1, 0, comparator) upright_check = self._single_direction_check(row, col, -1, 1, comparator) downright_check = self._single_direction_check(row, col, 1, 1, comparator) downleft_check = self._single_direction_check(row, col, 1, -1, comparator) upleft_check = self._single_direction_check(row, col, -1, -1, comparator) temp_list = [left_check, right_check, up_check, down_check, upright_check, downright_check, downleft_check, upleft_check] for item in temp_list: if len(item) > 0: return_list.append(item) return return_list def _single_direction_check(self, row: int, col: int, row_change: int, col_change: int, comparator: str) -> tuple: """ Using row_change and col_change to determine the direction. If there is a valid space/piece to move in that column, returns those coordinates as a tuple. If the move is not valid, returns an empty tuple """ valid_spot = tuple() opposite_color = self.color_dict[self._flip_color(self.current_player)] opposite_color_line = False col_index = col row_index = row # can optimize? while 0 <= col_index < self.boardcols and 0 <= row_index < self.boardrows: if self.board[row_index][col_index] == opposite_color: opposite_color_line = True elif self.board[row_index][col_index] == comparator and opposite_color_line: valid_spot = (row_index, col_index) break # When searching for possible moves ('open'), if after finding an opposite-color piece the next one is not # still opposite-color, then it's as if there was no opposite-color piece in between; returns (), "false" elif self.board[row][col] == self.board[row_index][col_index] and opposite_color_line and comparator == ' ': break # return nothing (false) if the next same-color piece is right next to to the spot being checked elif (abs(row_index - row) == 1 or abs(col_index - col) == 1) and not opposite_color_line: break # return nothing (false) if there is a blank space in the line elif self.board[row_index][col_index] == ' ' and row_index != row or col_index != col: break row_index += row_change col_index += col_change return valid_spot def _flip_line(self, row1: int, col1: int, row2: int, col2: int) -> None: """ Takes the coordinates of 2 pieces of the same color (must be in a row with each other) and flips the color of any pieces in between. Starts at (row1, col1) and moves towards (row2, col2) """ row_change = 0 col_change = 0 row_index = row1 col_index = col1 if row1 - row2 < 0: row_change = 1 elif row1 - row2 > 0: row_change = -1 if col1 - col2 < 0: col_change = 1 elif col1 - col2 > 0: col_change = -1 while min(row1, row2) <= row_index <= max(row1, row2) and min(col1, col2) <= col_index <= max(col1, col2): self.board[row_index][col_index] = self.current_player_piece row_index += row_change col_index += col_change def update_score(self) -> None: """ Counts the number of black and white pieces on the board and stores those in self.black_score and self.white_score """ bscore = 0 wscore = 0 for row in self.board: for col in row: if col == 'B': bscore += 1 elif col == 'W': wscore += 1 self.black_score = bscore self.white_score = wscore # -------- Static Methods -------- @staticmethod def _flip_color(color: str) -> str: """ Returns the opposite color of the string passed. (used for changing self.current_player and flipping pieces) """ if color == 'black': return 'white' elif color == 'white': return 'black' @staticmethod def _create_new_board(row_amt: int, col_amt: int, left_corner_color: str) -> [[str]]: """ Creates a new board with specified starting gamestate :param row_amt: integer from 4 to 16 divisible by 2 :param col_amt: integer from 4 to 16 divisible by 2 :param left_corner_color: 'B' or 'W'; determines the starting layout of the game board :return: 2 dimensional list with 2 black and 2 white pieces arranged for a new game; top left is (0, 0) """ board = [] for i in range(row_amt): row = [] for j in range(col_amt): row.append(' ') board.append(row) right_corner_color = None if left_corner_color == 'B': right_corner_color = 'W' elif left_corner_color == 'W': right_corner_color = 'B' board[row_amt // 2 - 1][col_amt // 2 - 1] = left_corner_color board[row_amt // 2 - 1][col_amt // 2] = right_corner_color board[row_amt // 2][col_amt // 2 - 1] = right_corner_color board[row_amt // 2][col_amt // 2] = left_corner_color return board # -------- Exceptions -------- class OverlapError(Exception): def __str__(self): return 'OverlapError: A piece has already been placed at this location.' class InvalidMoveError(Exception): def __str__(self): return 'InvalidMoveError: Piece cannot be placed at this location.'
a4193b6dfb6f55d8b1142fc442fd84a9191ab182
Kavinelavu/codekata
/alphabet1.py
115
3.96875
4
de=raw_input() if(de>=('a' and de<='Z') or (de>='A' and de<='Z')): print("Alphabet") else: print("No")
c3a179979429225c5721c69c03afaa02bce75130
mturke/StringCalculator
/StringCalculatorTest.py
1,480
3.609375
4
##### Test import unittest from StringCalculator import StringCalculator class Test_StringCalculator(unittest.TestCase): def testAdd_EmptyString_Returns0(self): calc = StringCalculator() result = calc.add("") self.assertEqual(0, result) def testAdd_Zero(self): calc = StringCalculator() result = calc.add("0") self.assertEqual(0, result) def testAdd_One(self): calc = StringCalculator() result = calc.add("1") self.assertEqual(1, result) def testAdd_Numbers(self): calc = StringCalculator() result = calc.add("1,2") self.assertEqual(result, 3) def testAllow_UnknownAmountOfNumbers(self): calc = StringCalculator() result = calc.add("1,2,3,4,5,6") self.assertEqual(result, 21) def testNegative_NotAllowed(self): calc = StringCalculator() with self.assertRaises(ValueError): result = calc.add("-1") def testNegativeInputs_NotAllowed(self): calc = StringCalculator() with self.assertRaises(ValueError): result = calc.add("1000, -1") def testIgnore_NumsGreaterThan1000(self): calc = StringCalculator() result = calc.add("1001, 2") self.assertEqual(result, 2) if __name__ == "__main__": unittest.main()
5aa70c9f56759ff49c692a63748b9b4e8b1440fb
Nischal47/Python_Exercise
/#21.py
1,086
4.46875
4
''' Question: A robot moves in a plane starting from the original point (0,0). The robot can move toward UP, DOWN, LEFT and RIGHT with a given steps. The trace of robot movement is shown as the following: UP 5 DOWN 3 LEFT 3 RIGHT 2 The numbers after the direction are steps. Please write a program to compute the distance from current position after a sequence of movement and original point. If the distance is a float, then just print the nearest integer. Example: ''' import math Org_Pos=[0,0] while True: s=(input("Enter movement of robot as UP, DOWN, LEFT, RIGHT followed by length:")) if(not s): break inputlist=s.split(' ') direction = inputlist[0] steps = int(inputlist[1]) if(direction=="UP"): Org_Pos[1]+=steps elif(direction=="DOWN"): Org_Pos[1]-=steps elif(direction=="LEFT"): Org_Pos[0]-=steps elif(direction=="RIGHT"): Org_Pos[0]+=steps else: pass distance=int(math.sqrt(Org_Pos[0]**2+Org_Pos[1]**2)) print("The distance covered by robot is:{}".format(distance))
bad357e547032486bc7e5b04b7b92351148a2b19
21milushcalvin/grades
/Grades.py
1,649
4.25
4
#--By Calvin Milush, Tyler Milush #--12 December, 2018 #--This program determines a test's letter grade, given a percentage score. #--Calvin Milush #-Initializes variables: score = 0 scoreList = [] counter = 0 total = 0 #--Calvin Milush #-Looped input for test scores: while (score != -1): score = input("Input test score (-1 to exit loop): ") if (score != -1): scoreList.append(score) counter += 1 total += score else: break #--Tyler Milush #-Assigns a letter grade to each inputted score: letterList = [] for i in range(counter): if scoreList[i] >= 90: letterList.append("A") elif scoreList[i] >= 80 and scoreList[i] <= 89: letterList.append("B") elif scoreList[i] >= 70 and scoreList[i] <= 79: letterList.append("C") elif scoreList[i] >= 60 and scoreList[i] <= 69: letterList.append("D") elif scoreList[i] < 60: letterList.append("F") print print "List of scores: ", scoreList print "Grade of each score: ", letterList print #--Calvin Milush #-Calculates and prints average (if greater than 0): if (counter > 0): avg = total / float(counter) print "%0s %0.2f" % ("Average test score: ", avg) else: print "Error: Requires at least one test score." #--Tyler Milush #-Assigns a letter grade to the average: avgLetter = "" if(avg >= 90): avgLetter = "A" elif(avg >= 80 and avg <=89): avgLetter = "B" elif(avg >= 70 and avg <=79): avgLetter = "C" elif(avg >= 60 and avg <=69): avgLetter = "D" elif(avg < 60): avgLetter = "F" print "Letter grade of average: ", avgLetter
ae854aed8339a36f06c151b68a9965f54134439e
ngladkoff/2019FDI
/SimulacroAmbulancia.py
717
3.671875
4
def CalcularTiempo (var1,var2): if var2 == 1: ## print("Ambulancia llega en 15m,") return "Ambulancia llega en 15m" elif var2 == 2: #print("Ambulancia llega en 30m.") return "Ambulancia llega en 30m." elif var1 >= 59 and var2 == 3: #print("Ambulancia llega en 2 horas.") return "Ambulancia llega en 2 horas." elif var1 < 59 and var2 == 3: #print("Ambulancia llega en 4 horas.") return "Ambulancia llega en 4 horas." edad = 0 while edad >=0: edad= int(input("Edad del paciente: ")) if edad >= 0: gravedad= int(input("Codigo de gravedad: ")) tiempo= CalcularTiempo(edad,gravedad) print("Tiempo: ", tiempo)
813910455e4c059e5c72404204dc0a5d0adde5ee
nicholas1026/PythonStudy
/chapter08/e8-12.py
197
3.5625
4
def show_stuff(*stuffs): for stuff in stuffs: print("There are "+stuff+" in the sandwichs") show_stuff("apple") show_stuff("banana","orange") show_stuff("berry","watermelon","lemon")
0da375dfb55ff8ba9e5f3347ca56eb0de8715ece
psukhomlyn/HillelEducation-Python
/Lesson3/HW-3-4.py
781
3.84375
4
""" Task 4 """ first_value_str: str = input('Input first value: ') second_value_str: str = input('Input second value: ') my_list: list = [] try: first_value_int: int = int(first_value_str) second_value_int: int = int(second_value_str) except ValueError as ex: print(f'Both values should be a digits') raise ex if second_value_int <= first_value_int: raise NameError(f'Second value should be bigger then the first value') for item in range(first_value_int, second_value_int): if item % 5 == 0: my_list.append(item) print(f'Your list is {my_list}') """ Task 5 """ total_value = 0 for element in my_list: total_value += element print(f'Min value is {min(my_list)}') print(f'Max value is {max(my_list)}') print(f'Total value is {total_value}')
22c8aed1804b9605a8e9a724e60dab541622c9dd
jithendaraa/RoboTutor-Analysis
/helper.py
8,153
3.859375
4
import numpy as np import math import matplotlib.pyplot as plt import os def remove_spaces(elements): """ Given A list elements = ["Orienting to Print", "Listening Comprehension"] Returns elements = ["OrientingtoPrint", "ListeningComprehension"] """ for i in range(len(elements)): elements[i] = (elements[i].replace(" ", "")) return elements def rmse(a, b): """ Calculates Root Mean Square Error between 2 arrays or lists """ if isinstance(a, list): a = np.array(a) if isinstance(b, list): b = np.array(b) squared_error = (a - b)**2 mse = np.mean(squared_error) rmse_val = mse**0.5 return rmse_val def sigmoid(x): """ Given x: int or float Returns The sigmoid (or inverse logit) of x = 1/1+e^(-x) """ return 1/(1+np.exp(-x)) def remove_iter_suffix(tutor): """ Given: A string tutor = "something__it_(number)" or list of tutor Returns: String tutor = "something" or list of tutor """ if isinstance(tutor, list): for i in range(len(tutor)): idx = tutor[i].find("__it_") if idx != -1: tutor[i] = tutor[i][:idx] return tutor elif isinstance(tutor, str): idx = tutor.find("__it_") if idx != -1: tutor = tutor[:idx] return tutor else: print("ERROR: remove_iter_suffix") return None def skill_probas(activityName, tutorID_to_kc_dict, kc_list, p_know): """ Given: ActivityName, TutorID to KC skill mapping Returns: P_know of those skills exercised by Activity Name """ # returns list of P(Know) for only those skills that are exercised by activityName proba = [] skillNames = tutorID_to_kc_dict[activityName] skillNums = [] for skillName in skillNames: skill_num = kc_list.index(skillName) skillNums.append(skill_num) for skill in skillNums: proba.append(p_know[skill]) return proba def clear_files(algo, clear, path='logs/', type=None): """ Empties all txt files under algo + "_logs" folder if clear is set to True Returns nothing """ if clear == False: return log_folder_name = path + algo.lower() + "_logs" files = os.listdir(log_folder_name) text_files = [] for file in files: if type == None: if file[-3:] == "txt": text_files.append(file) else: if file[-10:] == "_type" + str(type) + ".txt": text_files.append(file) for text_file in text_files: file = open(log_folder_name + "/" + text_file, "r+") file.truncate(0) file.close() def output_avg_p_know(episode_num, avg_over_episodes, scores, filename, avg_p_know): if episode_num % avg_over_episodes == 0 and episode_num > 0: avg_score = np.mean(scores[max(0, episode_num-avg_over_episodes): episode_num+1]) with open(filename, "a") as f: text = str(episode_num/avg_over_episodes) + ", Avg P(Know)" + str(avg_p_know) + ", Avg score:" + str(avg_score) + "\n" f.write(text) def plot_learning(learning_progress, student_ids, timesteps, new_student_avg, algo, xs=None, threshold_ys=None, lenient_threshold_ys=None): """ Given learning_progress, student_ids etc., Plots: Avg. P Know vs #opportunities for each student in student_ids. Also plots in the same graph, Avg P Know vs #opportunities for an imaginary student who is asked questions from the learned tutor policy of the RL agent """ colors = ["red", "green", "yellow", "purple", "blue", "violet", "orange", "brown"] for i in range(len(student_ids)): student_id = student_ids[i] x = [] y = [] for j in range(len(learning_progress[student_id])): p_know = learning_progress[student_id][j] p_avg_know = np.mean(np.array(p_know)) x.append(j+1) y.append(p_avg_know) plt.plot(x, y, label=student_id) if xs != None: plt.plot(xs, threshold_ys, color='r', label="Current RT Thresholds") plt.plot(xs, lenient_threshold_ys, color='b', label="Current lenient RT Thresholds") x = np.arange(1, len(new_student_avg) + 1).tolist() plt.plot(x, new_student_avg, label="RL Agent", color="black") plt.legend() plt.xlabel("# Opportunities") plt.ylabel("Avg P(Know) across skills") plt.title("Avg P(Know) vs. #opportunities") plt.ticklabel_format(style='sci', axis='y', scilimits=(0,0), useMathText=True) # plt.savefig("plots/" + algo + '_results.jpg') plt.grid() plt.show() def slurm_output_params(path, village="130", slurm_id="10301619"): slurm_filename = "slurm-" + slurm_id + ".txt" path_to_slurm_file = path + "/" + slurm_filename slurm_file_lines = open(path_to_slurm_file, "rb").read().decode("utf-8").split("\n") theta = [] lambda0 = [] lambda1 = [] learn = [] g = [] ss = [] for line in slurm_file_lines: line_vals = line.split(" ") line_vals = list(filter(("").__ne__, line_vals)) param_name = line_vals[0] if len(param_name) > 5: if param_name[:5] == "theta": student_num = len(theta) theta.append(float(line_vals[1])) elif param_name[:5] == "learn": learn.append(float(line_vals[1])) elif param_name[:7] == "lambda0": lambda0.append(float(line_vals[1])) elif param_name[:7] == "lambda1": lambda1.append(float(line_vals[1])) if param_name[:1] == "g": g.append(float(line_vals[1])) if param_name[:2] == "ss": ss.append(float(line_vals[1])) slurm_params_dict = { 'theta': theta, 'learn': learn, 'b': lambda0, 'a': lambda1, 'g': g, 'ss': ss } return slurm_params_dict def evaluate_performance_thresholds(student_simulator, tutor_simulator, CONSTANTS=None, prints=True): student_id = CONSTANTS['NEW_STUDENT_PARAMS'] if student_id == None: student_id = 'new_student' student_num = student_simulator.uniq_student_ids.index(student_id) uniq_activities = student_simulator.uniq_activities student_model_name = CONSTANTS['STUDENT_MODEL_NAME'] if student_model_name == 'hotDINA_skill' or student_model_name == 'hotDINA_full': prior_know = np.array(student_simulator.student_model.alpha[student_num][-1]) prior_avg_know = np.mean(prior_know) activity_num = None response = "" ys = [] ys.append(prior_avg_know) for _ in range(CONSTANTS['MAX_TIMESTEPS']): if activity_num != None: p_know_activity = student_simulator.student_model.get_p_know_activity(student_num, activity_num) else: p_know_activity = None x, y, area, activity_name = tutor_simulator.get_next_activity(p_know_prev_activity=p_know_activity, prev_activity_num=activity_num, response=str(response), prints=prints) activity_num = uniq_activities.index(activity_name) response = student_simulator.student_model.predict_response(activity_num, student_num, update=True) if prints: print('ASK QUESTION:', activity_num, uniq_activities[activity_num]) print('CURRENT MATRIX POSN (' + str(area) + '): ' + "[" + str(x) + ", " + str(y) + "]") print('CURRENT AREA: ' + area) print() if student_model_name == 'hotDINA_skill' or student_model_name == 'hotDINA_full': posterior_know = np.array(student_simulator.student_model.alpha[student_num][-1]) posterior_avg_know = np.mean(posterior_know) ys.append(posterior_avg_know) return ys
eea2a0419976deca35211da9d35c9178d66ee01a
19sblanco/cs1-projects
/blanco-steven-assn15/assn15-task1.py
278
3.78125
4
def main(): baseList = list(range(1, 101)) list1 = [x for x in baseList if x % 2 == 0] print(list1) list2 = [x for x in baseList if x % 3 == 0 and x < 50] print(list2) list3 = [x * 10 for x in baseList if x % 5 == 0 and x > 50] print(list3) main()
d6ee95d6fd19549bb499042714d5225c9bc2d5cf
randaghaith/Python-Course
/Week 1/practise1-a.py
484
4.09375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: name=input("enter your name = ") x=float(input("enter the first number : ")) y=float(input("enter the second number : ")) print(f"hi mr/mrs , {name}" ) print(f"the sum of {x} and {y} is : {x+y} ") print(f"the sub of {x} and {y} is : {x-y} ") print(f"the mul of {x} and {y} is : {x*y} ") print(f"the div of {x} and {y} is : {x/y} ") print(f"the reminder of {x} and {y} is : {x%y} ") print(f"the exponent of {x} and {y} is : {x**y} ")
aa3b3b8513736803577a3c47d4635386cd48e51a
kaiopomini/PythonExercisesCursoEmVideo
/ex066.py
555
4.03125
4
'''Exercício Python 066: Crie um programa que leia números inteiros pelo teclado. O programa só vai parar quando o usuário digitar o valor 999, que é a condição de parada. No final, mostre quantos números foram digitados e qual foi a soma entre elas (desconsiderando o flag).''' contador = soma = 0 while True: numero = int(input('Informe um numero inteiro, ou "999" para sair: ')) if numero == 999: break contador += 1 soma += numero print(f'Foram lidos {contador} número(s) que somados resultam em {soma}')
998d6989b04880e01448158c998e6702f9809910
bglynch/code_scratchpad
/python/general/regex/regex.py
7,152
3.96875
4
import re # will be searching this multiline string text_to_search = ''' abcdefghijklmnopqurtuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 1234567890 Ha HaHa MetaCharacters (Need to be escaped): . ^ $ * + ? { } [ ] \ | ( ) coreyms.com 321-555-4321 123.555.1234 123*555*1234 800-555-1234 900-555-1234 Mr. Schafer Mr Smith Ms Davis Mrs. Robinson Mr. T cat mat pat bat ''' sentence = 'Start a sentence and then bring it to an end' # ============================================================================== def string_vs_raw_string(): # raw string - does not handle '\' in any way print('\t tab') print(r'\t tab') ''' will use the re.compile() method to write our patterns allows us to extract patterns out to variable make its eaasier to reuse patterns ''' def match_phoneNumbers(text_to_search): pattern = re.compile(r'\d\d\d.\d\d\d.\d\d\d\d') matches = pattern.finditer(text_to_search) # finditer - returns an iterator that contains all of the matches for match in matches: print(match) # >>> <_sre.SRE_Match object; span=(1, 4), match='abc'> def match_phoneNumbers_from_an_other_file(): with open('data.txt') as f: contents = f.read() pattern = re.compile(r'\d\d\d.\d\d\d.\d\d\d\d') matches = pattern.finditer(contents) for match in matches: print(match) def match_phoneNumbers_with_character_set(text_to_search): pattern = re.compile(r'\d\d\d[.-]\d\d\d[.-]\d\d\d\d') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_800_900_phoneNumbers(text_to_search): # match only 800 and 900 numbers pattern = re.compile(r'[89]00[.-]\d\d\d[.-]\d\d\d\d') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_digit_range_1_to_5(text_to_search): pattern = re.compile(r'[^1-5]') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_anything_but_letters(text_to_search): pattern = re.compile(r'[^a-zA-Z]') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_phoneNumbers_with_exact_quantifier(text_to_search): pattern = re.compile(r'\d{3}.\d{3}.\d{4}') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_men_names(text_to_search): pattern = re.compile(r'Mr\.?\s[A-Z]\w*') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_all_names_using_Group(text_to_search): pattern = re.compile(r'(Mr|Ms|Mrs)\.?\s[A-Z]\w*') matches = pattern.finditer(text_to_search) for match in matches: print(match) # ============================================================================== emails = ''' [email protected] [email protected] [email protected] ''' def match_first_email(text_to_search): pattern = re.compile(r'[a-zA-Z]+@[a-zA-Z]+\.com') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_first_two_email(text_to_search): pattern = re.compile(r'[a-zA-Z.]+@[a-zA-Z]+\.(com|edu)') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_all_email(text_to_search): pattern = re.compile(r'[a-zA-Z0-9.-]+@[a-zA-Z-]+\.(com|edu|net)') matches = pattern.finditer(text_to_search) for match in matches: print(match) # ============================================================================== urls = ''' https://www.google.com http://coreyms.com https://youtube.com https://www.nasa.gov ''' def match_all_urls(text_to_search): pattern = re.compile(r'https?://(www\.)?\w+\.\w+') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_all_urls_as_groups(text_to_search): pattern = re.compile(r'https?://(www\.)?(\w+)(\.\w+)') matches = pattern.finditer(text_to_search) for match in matches: print(match) print(match.group(0)) print(match.group(1)) print(match.group(2)) print(match.group(3)) def match_all_urls_as_subbed_groups(text_to_search): # create a patterns pattern = re.compile(r'https?://(www\.)?(\w+)(\.\w+)') # use the pattern to sub out group 2 and 3 for all matches in 'urls' subbed_urls = pattern.sub(r'\2\3', text_to_search) print(subbed_urls) # ============================================================================== ''' for all previous example we used the finditer() method there are other methods available ''' pattern = re.compile(r'\.') matches = pattern.findall(text_to_search) # will just return matches as a list of strings. # Note that is there is groups it will only return the group matches = pattern.match(text_to_search) # returns the first match # only matches things that are at the begining of strings # same as using the carrot(^) in your regex matches = pattern.search(text_to_search) # returns the first match # returns None if no match found # ============================================================================== def match_start_for_uppercase_or_lowercase(text_to_search): pattern = re.compile(r'[Ss][Tt][Aa][Rr][Tt]') matches = pattern.finditer(text_to_search) for match in matches: print(match) def match_start_for_uppercase_or_lowercase_with_FLAG(text_to_search): pattern = re.compile(r'start', re.IGNORECASE) matches = pattern.finditer(text_to_search) for match in matches: print(match) # ============================================================================== lines = ''' 04/20/2009; 04/20/09; 4/20/09; 4/3/09 Mar-20-2009; Mar 20, 2009; March 20, 2009; Mar. 20, 2009; Mar 20 2009; 20 Mar 2009; 20 March 2009; 20 Mar. 2009; 20 March, 2009 Mar 20th, 2009; Mar 21st, 2009; Mar 22nd, 2009 Feb 2009; Sep 2009; Oct 2010 6/2008; 12/2009 2009; 2010 ''' def match_with_f_string(text_to_search): regex = fr'(\d{{1,2}})/(\d{{1,2}})/(\d{{4}}|\d{{2}})' date_found = re.findall(regex, lines) print(date_found) var = 'March' regex2 = fr'({var})' march_found = re.findall(regex2, lines) print(march_found) match_with_f_string(lines) # searching for strings containing MetaCharacters - characters which need to be escaped pattern = re.compile(r'\.') # '.' pattern = re.compile(r'coreyms\.com') # 'coreyms.com' pattern = re.compile(r'\d\d\d.\d\d\d.\d\d\d\d') # 'match phone numbers' pattern = re.compile(r'\d\d\d[.-]\d\d\d[.-]\d\d\d\d') # matches numbers that are seperated with either '.' or '-' pattern = re.compile(r'[1-5]') # any digits between 1 and 5 pattern = re.compile(r'[a-z]') # any lowercase letter between a and z pattern = re.compile(r'[a-zA-Z]') # any lowercase and uppercase letter between a and z pattern = re.compile(r'[^a-zA-Z]') # any non lowercase and uppercase letter between a and z pattern = re.compile(r'[^b]at') # match cat,mat,pat but not bat
262e86fc8156eed6e203e20d3352e5b3950dee29
erin-koen/Data-Structures
/classNotes.py
4,410
4.28125
4
# linked lists class Node: def __init__(self, value=None, next_node=None): self.value = value self.next_node = next_node def get_value(self): return self.value def get_next(self): return self.next_node def set_next(self, new_next): self.next_node = new_next def set_value(self, value): self.value = value # we'll be figuring out how adding a previous_node property works with a doubly linked list class LinkedList: def __init__(self): self.head = None self.tail = None def add_to_tail(self, value): # wrap the value in a node new_node = Node(value) # check if we're in an empty list state if not self.head and not self.tail: # set the list's head ref to the new node self.head = new_node # set the list's tail ref to the new node self.tail = new_node else: # updtae the old tail's next reference to refer to the new node self.tail.set_next(new_node) # update the LinkedList's 'tail' reference self.tail = new_node def remove_head(self): # what if our list is empty? if not self.head and not self.tail: return None # what if our list only contains a single node? if self.head is self.tail: old_head = self.head self.head = None self.tail = None return old_head.get_value else: # store a reference to the node we're removing old_head = self.head # update the head reference to refer to the old head's next node self.head = old_head.get_next() # return the old head's value return old_head.get_value() def contains(self, target): #what if our list is empty? if not self.head and not self.tail: return False # get another ref that initially starts at the head of the list current = self.head # loop so long as 'current' is a valid Node while current: if current.get_value() == target: return True #update the current to refer to current's next node current = current.get_next() #we've looped through the whole list and haven't found what we're looking for return False ''' Tuesday Text Buffer ----------- 1) add characters from front and back 2) remove chars from front and back 3) render the contents of buffer 4) concatenate two buffers together (userful for copy/paste What data structure should we use? What are the trade offs? prepend append delete_front delete_back join print DLL O(1) O(1) O(1) O(1) O(1) O(n) Array O(n) O(1) O(n) O(1) O(n) O(n) ''' # import doubly_linked_list class TextBuffer: def __init__(self, init=None): self.contents = DoublyLinkedList if init: for char in init: self.contents.add_to_tail(char) def __str__(self): s="" current = self.contents.head while current: s+= current.value current = current.next return s # no idea what this does, will have to watch again def append(self, str_to_add): for char in str_to_add: self.contents.add_to_tail(char) def prepend(self, str_to_add): for char in str_to_add[::-1]: self.contents.add_to_head(char) def delete_front(self, chars_to_remove): for _ in range(chars_to_remove): self.contents.remove_from_head() def delete_back(self, chars_to_remove): for _ in range(chars_to_remove): self.contents.remove_from_tail() def join(self, other_buffer): # Connect the tail of this buffer with the head of the other buffer self.contents.tail.next = other_buffer.contents.head # Set the other buffer's head's previous to be self.tail other_buffer.contents.head.prev = self.contents.tail # Update other buffer's head to be this buffer's head other_buffer.contents.head = self.contents.head # Update this buffer's tail to be the other's tail self.contents.tail = other_buffer.contents.tail
abcbaeee18f81efea2309abb4d6615a795e7b36b
AlexanderIvanofff/Python-OOP
/DataStructures/hash_table.py
2,438
4.0625
4
# Liner approach implementation of hashing class HashTable: """ Hashable representation a custom dictionary implementation where we use two private lists to achieve storing and hashing of key-value pairs functionality """ def __init__(self): self.max_capacity = 8 self.__keys = [None] * self.max_capacity self.__values = [None] * self.max_capacity def __getitem__(self, key): index = self.__keys.index(key) return self.__values[index] def resize(self): self.__keys = self.__keys + [None] * self.max_capacity self.__values = self.__values + [None] * self.max_capacity self.max_capacity = self.max_capacity * 2 def __setitem__(self, key, value): if key in self.__keys: index = self.__keys.index(key) self.__values[index] = value return if self.length == self.max_capacity: self.resize() index = self.hash(key) self.__keys[index] = key self.__values[index] = value def get(self, key): try: index = self.__keys.index(key) return self.__values[index] except ValueError: return None def add(self, key, value): self[key] = value def check_available_index(self, index): if index == len(self.__keys): return self.check_available_index(0) if self.__keys[index] is None: return index return self.check_available_index(index + 1) def hash(self, key): index = sum([ord(char) for char in key]) % self.max_capacity available_index = self.check_available_index(index) return available_index def __len__(self): return self.max_capacity @property def length(self): return len([el for el in self.__keys if el is not None]) def __repr__(self): result = [ f"{self.__keys[index]}: {self.__values[index]}" for index in range(len(self.__keys)) if self.__keys[index] is not None ] return "{" + "{}".format(", ".join(result)) + "}" hash_table = HashTable() hash_table["name"] = "Peter" hash_table["age"] = 25 hash_table["color"] = "blue" hash_table["animal"] = "Dog" hash_table["course"] = "Python" print(hash_table["name"]) print(hash_table.get(5)) print(hash_table["age"]) print(hash_table.length) print(hash_table)
611cdfaf0c866be3aaaded54d067894c4d840ce1
EKrzych/codecool_projects_python
/Python/2018_02_05_SI/Algorithms_flowchart/erp_by_myself_hr.py
2,035
3.921875
4
# the question: Who is the oldest person ? # return type: list of strings (name or names if there are two more with the same value) def get_table(): with open ("persons.csv", "r") as f: table = [] for line in f: table.append(line.strip("\n").split(";")) return table def find_max(table): max = table[0][2] row_index = 0 for counter, record in enumerate(table): if max < record[2]: max = record[2] row_index = counter return row_index def get_oldest_person(table): oldest_person_index = find_max(table) oldest_person = [row[1] for row in table if row[2] == table[oldest_person_index][2]] print(oldest_person) return oldest_person # the question: Who is the closest to the average age ? # return type: list of strings (name or names if there are two more with the same value) def get_average(table): current_year = 2018 total = 0 for record in table: record.append(current_year - int(record[2])) total += record[3] return table, total / len(table) def find_min(table,column): min = table[0][column] row_index = 0 for counter, record in enumerate(table): if min > record[column]: min = record[column] row_index = counter return row_index def sort_table(table): sorted_table = [] while table: sorted_table.append(table.pop(find_min(table,3))) print(sorted_table) def get_persons_closest_to_average(table): table, average = get_average(table) print(table) print(average) for record in table: record.append(abs(average - record[3])) print("______") closest = find_min(table,4) print(closest) closest_list = [row[1] for row in table if row[4] == table[closest][4]] print(table) print(closest_list) return closest_list def main(): table = get_table() get_oldest_person(table) get_persons_closest_to_average(table) if __name__ == "__main__": main()
fc58be5e9f980fb047220a57acca709e9001de6b
Win-Htet-Aung/kattis-solutions
/crackingRSA.py
397
3.65625
4
def is_prime(num): if num > 1: for i in range(2, int((num ** 0.5) + 1)): if num % i == 0: return i break # return True, 0 else: return False, 2 t = int(input()) for i in range(t): st = input() n = int(st.split()[0]) e = int(st.split()[1]) p = is_prime(n) # print(p, n) q = n // p pq = (p-1) * (q-1) j = 1 while (pq * j + 1) % e != 0: j += 1 print((pq * j + 1) // e)
7c75f0d406fb326ecdd253100d72f04bb014d651
dfidalg0/ces22python2
/wordtools.py
2,479
3.953125
4
# Exercício 3 def cleanword (string): s = '' for char in string: if char.isalpha(): s += char return s def has_dashdash (string): return '--' in string def extract_words (string): s = '' for char in string: if char.isalpha(): s += char.lower() else: s += ' ' return s.split() def wordcount (word, string_list): n = 0 for string in string_list: if string == word: n += 1 return n def wordset (string_list): return sorted(set(string_list)) def longestword (string_list): n = 0 for string in string_list: size = len(string) if size > n: n = size return n def _tests (): # cleanword tests assert cleanword('what?') == 'what' assert cleanword("'now!'") == 'now' assert cleanword("?+='w-o-r-d!,@$()'") == 'word' # has_dashdash tests assert has_dashdash('distance--but') assert not has_dashdash('several') assert has_dashdash('spoke--') assert not has_dashdash('-yo-yo-') # extract_words tests assert extract_words("Now is the time! 'Now', is the time? Yes, now.") == \ ['now','is','the','time','now','is','the','time','yes','now'] assert extract_words('she tried to curtsey as she spoke--fancy') == \ ['she','tried','to','curtsey','as','she','spoke','fancy'] # wordcount tests assert wordcount( "now", ["now","is","time","is","now","is","is"] ) == 2 assert wordcount( "is", ["now","is","time","is","now","the","is"] ) == 3 assert wordcount( "time", ["now","is","time","is","now","is","is"] ) == 1 assert wordcount( "frog", ["now","is","time","is","now","is","is"] ) == 0 # wordset tests assert wordset( ["now", "is", "time", "is", "now", "is", "is"] ) == ["is", "now", "time"] assert wordset( ["I", "a", "a", "is", "a", "is", "I", "am"] ) == ["I", "a", "am", "is"] assert wordset( ["or", "a", "am", "is", "are", "be", "but", "am"] ) == ["a", "am", "are", "be", "but", "is", "or"] # longestword tests assert longestword(["a", "apple", "pear", "grape"]) == 5 assert longestword(["a", "am", "I", "be"]) == 2 assert longestword(["this","supercalifragilisticexpialidocious"]) == 34 assert longestword([ ]) == 0 print('All tests passed') if __name__ == '__main__': _tests()
0a55036095f5f10473496bb67d5970d32dacb632
3l-d1abl0/DS-Algo
/py/oops/inner_class.py
408
3.53125
4
class College: def __init__(self): print('Outer Class Constructor') def displayC(self): print('College Method') class Student: def __init__(self): print('Inner Class Constructor') def displayS(self): print('Student Method') C = College() C.displayC() #C.displayS() S = C.Student() S.displayS() S= College().Student() S.displayS()
c1cf5e02b7633979955e42fde325a8cd278925ca
varshaammucmr/varshapython
/negative.py
349
4
4
a=int(input("enter value of a:")) b=int(input("enter value of b:")) if(a>b): print(a,"is negative") elif(b>a): print(b,"is negative") dl211@soetcse:~/varsha$ python negative.py enter value of a:67 enter value of b:56 (67, 'is negative') dl211@soetcse:~/varsha$ python negative.py enter value of a:78 enter value of b:90 (90, 'is negative')
e4f5a3b824d6322cc45450eeee5e86701f8171bb
coolmich/py-leetcode
/solu/329. Longest Increasing Path in a Matrix.py
1,109
3.53125
4
class Solution(object): def longestIncreasingPath(self, matrix): """ :type matrix: List[List[int]] :rtype: int """ if not matrix: return 0 dp = [[0 for i in range(len(matrix[0]))] for j in range(len(matrix))] def traverse(matrix, r, c, dp): if dp[r][c]: return dp[r][c] if r > 0 and matrix[r - 1][c] > matrix[r][c]: dp[r][c] = max(dp[r][c], traverse(matrix, r - 1, c, dp)) if r < len(matrix) - 1 and matrix[r + 1][c] > matrix[r][c]: dp[r][c] = max(dp[r][c], traverse(matrix, r + 1, c, dp)) if c > 0 and matrix[r][c - 1] > matrix[r][c]: dp[r][c] = max(dp[r][c], traverse(matrix, r, c - 1, dp)) if c < len(matrix[0]) - 1 and matrix[r][c + 1] > matrix[r][c]: dp[r][c] = max(dp[r][c], traverse(matrix, r, c + 1, dp)) dp[r][c] += 1 return dp[r][c] for r in range(len(matrix)): for c in range(len(matrix[0])): traverse(matrix, r, c, dp) return max(map(max, dp))
068af85eee72c080a8901afda501c608a7678cf8
satishkr39/MyFlask
/Python_Demo/Bank_Account.py
776
4
4
class Bank: def __init__(self, name, balance): self.name = name self.balance = balance def deposit(self, deposit): print("Deposit in Account") self.balance = self.balance + deposit print("Balance is: {}".format(self.balance)) def withdraw(self, amount): if amount > self.balance: print("Amount can't exceed balance") else: print("Withdrawn Amount : {}".format(amount)) self.balance = self.balance - amount print("Balance is: {}".format(self.balance)) def __repr__(self): return f"The Person Name is : {self.name} and Balance is : {self.balance}" p1 = Bank("satish", 1000) print(p1) p1.deposit(500) p1.withdraw(100) p1.withdraw(200) print(p1)
7c1064cda385681135fd33e4993814938a8cd9e4
arironman/MSU-Computer-Network-Lab
/lab-1/1.py
449
3.921875
4
# Objective: Implement a program that takes bit stream and input and applies even parity scheme on it. num = int(input("Enter the Unsigned Integer: ")) binary_num = bin(num) unsigned_binary_num = binary_num[2:] print(unsigned_binary_num) str_num = str(unsigned_binary_num) no_of_one = 0 for i in str_num: if i == '1': no_of_one += 1 if no_of_one%2 == 0: pass else: str_num = str_num +'1' print(str_num)
11ea93aa86d26175f468cb3e5f81c8b9600a77a2
Jalbanese1441/Waterloo-CS-Circles-Solutions
/14 The Replacements.py
107
3.578125
4
def replace(list, X, Y): while list.count(X)>0: list.insert(list.index(X),Y) list.remove(X)
0cb8649c62922c630d148518182f726e60ac7cb5
santosalves/python-curso-em-video
/exer113.py
953
3.8125
4
def leiaInt(msg): while True: try: num = int(input(msg)) except (ValueError, TypeError): print('\033[0;31mERRO! Digite um número inteiro válido.\033[m') continue except KeyboardInterrupt: print('\n\033[0;31mEntrada de dados interrompida pelo usuário.\033[m') return 0 else: return num def leiaFloat(msg): while True: try: num = float(input(msg)) except (ValueError, TypeError): print('\033[0;31mERRO! Digite um número real válido.\033[m') continue except KeyboardInterrupt: print('\n\033[0;31mEntrada de dados interrompida pelo usuário.\033[m') return 0 else: return num n_int = leiaInt('Digite um Inteiro: ') n_float = leiaFloat('Digite um Real: ') print(f'Você acabou de digitar o valor inteiro {n_int} e o Real {n_float}')
f9f1290d2b74c3184bc568e8586b7285638d875b
OceaneL/dypl
/week03/rockPaperScissors.py
2,596
3.78125
4
import random class Result: def __init__(self, value, name): self.value = value self.name = name def __eq__(self, other): return self.value == other.value Result.LOSE = Result(1,"Your opponent wins!") Result.WIN = Result(2,"You win!") Result.TIE = Result(3,"It's a tie!") class Weapon(object): def __str__(self): return self.__class__.__name__.lower class Paper(Weapon): def attack(self, weapon): return weapon.evalPaper(self, weapon) def evalPaper(self, weapon): return Result.TIE def evalScissors(self, weapon): return Result.WIN def evalRock(self, weapon): return Result.LOSE class Scissors(Weapon): def attack(self, weapon): return weapon.evalScissors(self, weapon) def evalPaper(self, weapon): return Result.LOSE def evalScissors(self, weapon): return Result.TIE def evalRock(self, weapon): return Result.WIN class Rock(Weapon): def attack(self, weapon): return weapon.evalRock(self, weapon) def evalPaper(self, weapon): return Result.WIN def evalScissors(self, weapon): return Result.LOSE def evalRock(self, weapon): return Result.TIE def main(): Weapons = Weapon.__subclasses__() nbRound = -1 while nbRound <= -1: try : nbRound = int(input("How many rounds ?")) except ValueError: print("You have to put a positive number !") iRound = 1 nbWin = 0 nbLose = 0 while iRound <= nbRound : nameWeapon = "" while nameWeapon not in map(lambda x : x.__name__, Weapons) : if nameWeapon != "": print(nameWeapon+ " is an incorrect weapon : choose scissors or rock or paper"); nameWeapon = input("Make your choice for round "+str(iRound)+": ") nameWeapon = nameWeapon.title() weapon1 = eval(nameWeapon) weapon2 = random.choice(Weapons) result = weapon1.attack(weapon1, weapon2) print("You chose ", weapon1.__name__, ", your opponent chose ", weapon2.__name__, "."); print(result.name) if result == Result.WIN : nbWin += 1 elif result == Result.LOSE : nbLose += 1 iRound += 1 print("Result: You won ",nbWin," time, your opponent won ", nbLose, " time. "); if nbWin > nbLose : resultFinal = Result.WIN elif nbWin < nbLose : resultFinal = Result.LOSE else : resultFinal = Result.TIE; print(resultFinal.name); if __name__ == '__main__': main()
1c023f82579284f3b95654768aad6da62f011c07
romanazaruk/algorithms
/algo_lab_3/algo.py
961
3.59375
4
from collections import defaultdict class Graph: def __init__(self, graph): self.graph = graph self.visited = {} # to separate elements of graph self.list = [] # stack for result for i in graph.copy(): #Why i cant use .keys??? if i not in self.visited: self.topological_sort(i) def topological_sort(self, vertex): self.visited[vertex] = True for i in self.graph[vertex]: if i not in self.visited.copy(): self.topological_sort(i) self.list.append(vertex) if __name__ == "__main__": documents = defaultdict(list) for line in open("in.txt"): docs = line.split() if len(docs) != 2: break documents[docs[0]].append(docs[1]) result_stack = Graph(documents).list print(result_stack) out = open("out.txt", 'w') for result in result_stack: out.write(result + "\n")
43a2a58e017220c16ce9f57996206a66725745b5
HanChen1988/BookExercise_02
/Chapter_07/Page_100/greeter.py
1,735
3.765625
4
# -*- coding: utf-8 -*- # @Time : 2020/4/12 2:43 下午 # @Author : hanchen # @File : greeter.py # @Software: PyCharm # ------------------ example01 ------------------ # # 准确地指出你希望用户提供什么样的信息 # name = input("Please enter your name: ") # print("Hello, " + name + "!") # ------------------ example01 ------------------ # print("*" * 20) # ------------------ example02 ------------------ # # 准确地指出你希望用户提供什么样的信息 # # 提示超过一行,可将提示存储在一个变量中 # prompt = "If you tell us who you are, we can personalize the messages you " \ # "see." # # 运算符+=在存储在prompt中的字符串末尾附加一个字符串 # prompt += "\nWhat is your first name? " # # name = input(prompt) # print("\nHello, " + name + "!") # ------------------ example02 ------------------ # print("*" * 20) # ------------------ example03 ------------------ # # 使用int()来获取数值输入 # age = input("How old are you? ") # print(age) # print(type(age)) # ------------------ example03 ------------------ # print("*" * 20) # ------------------ example04 ------------------ # 使用int()来获取数值输入 age = input("How old are you? ") # 函数int()将数字的字符串表示转换为数值表示 age = int(age) print(age >= 18) # ------------------ example04 ------------------ # print("*" * 20) # ------------------ error01 ------------------ # 报错信息: # Traceback (most recent call last): # --snip-- # print(age >= 18) # TypeError: '>=' not supported between instances of 'str' and 'int' # 解决方法: # 1.将字符串转换为整数,再进行比较 # age = int(age) # ------------------ error01 ------------------
d6d264bc85fa6ef5b3cf0c5abfa93ecd6a10a867
kyle-cryptology/crypto-algorithms
/Commitment/Commitment.py
3,770
3.515625
4
# -*- coding: utf-8 -*- """ .. module:: Commitment :synopsis: The cryptographic commitment. .. moduleauthor:: Kyle """ from Essential import Groups, Utilities as utils import abc class Commitment(object): """Cryptographic Commitment""" def __init__(self, arg): raise NotImplementedError("DigitalSignature is abstract.") @abc.abstractmethod def commit(self, m): """ The prover inputs a message m, it outputs commitment com corresponding to m and a random number r; and the later two parameters are kept secret in this phase. """ raise NotImplementedError( "The commitment algorithm has not been implemented.") def open(self): """ The prover opens the message m and the randomness r to the verifier where m and r were kept in the previous phase. """ return self.m, self.r @abc.abstractmethod def verify(self, m, r, com): """ The verifier verifies the message m, the randomness r and the commitment com and returns its validity. """ raise NotImplementedError( "The verification algorithm has not been implemented.") def demo(self, message): com = self.commit(message) m, r = self.open() self.params['message'] = m self.params['randomness'] = r self.params['commitment'] = com self.params['verification'] = self.verify(m, r, com) utils.show('%s commitment' % self.name, self.params) class HashCommit(Commitment): def __init__(self, security): self.security = security self.name = 'Hash-based' self.params = {'security': security} def commit(self, m): self.m = m self.r = utils.random_bits(self.security) return utils.hash([self.m, self.r], self.security) def verify(self, m, r, com): return com == utils.hash([m, r], self.security) class RSA(Groups.RSA, Commitment): def __init__(self, security): super(RSA, self).__init__(security) self.params['g'] = self.g = utils.coprime(security, self.n) def commit(self, m): self.m = m self.r = utils.random_bits(self.security, self.n) return (pow(self.g, m, self.n) * pow(self.r, self.e, self.n)) % self.n def verify(self, m, r, com): return (com == (pow(self.g, m, self.n) * pow(r, self.e, self.n)) % self.n) def add(self, c1, c2): return (c1 * c2) % self.n class ElGamal(Groups.PrimeOrder, Commitment): def __init__(self, security): super(ElGamal, self).__init__(security, True, 'ElGamal') def commit(self, m): self.m = m self.r = utils.random_bits(self.security, self.q) return [pow(self.g, self.r, self.p), (pow(self.g, m, self.p) * pow(self.h, self.r, self.p)) % self.p] def verify(self, m, r, com): return (com[0] == pow(self.g, r, self.p)) and (com[1] == ((pow(self.g, m, self.p) * pow(self.h, self.r, self.p) % self.p))) def add(self, c1, c2): return (c1[0] * c2[0]) % self.p, (c1[1] * c2[1]) % self.p def multiply(self, c, a): return pow(c, a, self.p) class Pedersen(Groups.PrimeOrder, Commitment): def __init__(self, security): super(Pedersen, self).__init__(security, True, 'Pedersen') def commit(self, m): self.m = m self.r = utils.random_bits(self.security, self.q) return (pow(self.g, m, self.p)) * (pow(self.h, self.r, self.p)) % self.p def verify(self, m, r, com): return com == ((pow(self.g, m, self.p)) * (pow(self.h, r, self.p)) % self.p) def add(self, c1, c2): return (c1 * c2) % self.p def multiply(self, c, a): return pow(c, a, self.p)
1990080a6d195acef0fb9514554f92d2c7f55274
segunar/BIG_data_sample_code
/3. Temperatures - Good/my_python_mapreduce/my_reducer.py
4,072
4.1875
4
#!/usr/bin/python # -------------------------------------------------------- # PYTHON PROGRAM # Here is where we are going to define our set of... # - Imports # - Global Variables # - Functions # ...to achieve the functionality required. # When executing > python 'this_file'.py in a terminal, # the Python interpreter will load our program, # but it will execute nothing yet. # -------------------------------------------------------- import sys import codecs #--------------------------------------- # FUNCTION get_key_value #--------------------------------------- def get_key_value(line): # 1. We create the output variable res = () # 2. We remove the end of line char line = line.replace('\n', '') # 3. We get the key and value words = line.split('\t') key_value = words[1] # 4. As the value is a tuple, we extract its components too key_value = key_value.rstrip(')') key_value = key_value.strip('(') components = key_value.split(',') city = components[0] year = int(components[1]) temp = float(components[2]) # 5. We assign res res = (city, year, temp) # 6. We return res return res # ------------------------------------------ # FUNCTION my_reduce # ------------------------------------------ def my_reduce(my_input_stream, my_output_stream, my_reducer_input_parameters): # 1. We unpack my_mapper_input_parameters pass # 2. We create 3 variables: # 2.1. The name of the city best_city = "" # 2.2. The best year best_year = 10000 # 2.3. The best temp best_temp = 10000.0 # 3. We read one by one the pairs key-value passed from the mapper for line in my_input_stream: # 1.1. We extract the key and the value (new_city, new_year, new_temp) = get_key_value(line) # 1.2. We compare the new temperature with the best we have so far. If it is better, we update it if (new_temp < best_temp): best_city = new_city best_year = new_year best_temp = new_temp # 4. We print the result my_str = best_city + '\t' + '(' + str(best_year) + ',' + str(best_temp) + ')' + '\n' my_output_stream.write(my_str) # ------------------------------------------ # FUNCTION my_main # ------------------------------------------ def my_main(local_False_Cloudera_True, my_reducer_input_parameters, input_file_example, output_file_example ): # 1. We select the input and output streams based on our working mode my_input_stream = None my_output_stream = None # 1.1: Local Mode --> We use the debug files if (local_False_Cloudera_True == False): my_input_stream = codecs.open(input_file_example, "r", encoding='utf-8') my_output_stream = codecs.open(output_file_example, "w", encoding='utf-8') # 1.2: Cloudera --> We use the stdin and stdout streams else: my_input_stream = sys.stdin my_output_stream = sys.stdout # 2. We trigger my_reducer my_reducer(my_input_stream, my_output_stream, my_reducer_input_parameters) # --------------------------------------------------------------- # PYTHON EXECUTION # This is the main entry point to the execution of our program. # It provides a call to the 'main function' defined in our # Python program, making the Python interpreter to trigger # its execution. # --------------------------------------------------------------- if __name__ == '__main__': # 1. Local Mode or Cloudera local_False_Cloudera_True = False # 2. Debug Names input_file_example = "../my_result/my_sort_results.txt" output_file_example = "../my_result/my_reducer_results.txt" # 3. my_reducer.py input parameters # We list the parameters here # We create a list with them all my_reducer_input_parameters = [] # 4. We call to my_main my_main(local_False_Cloudera_True, my_reducer_input_parameters, input_file_example, output_file_example )
3b62576d4caf5fc06c02dc15dbf97ef0f5829786
GhiffariCaesa/basic-python-b7-b
/list.py
305
3.75
4
mylist = [] mylist.append("a") mylist.append(12) mylist.append(20) print(mylist) print(len(mylist)) del mylist[2] print(mylist) # [a, 12, 20] # [0 1 2] mylist[2]=30 #mengedit isi list print(mylist) a = int(input("Masukkan data ke dalam mylist : ")) mylist.append(a) print(mylist) print(len(mylist))
6a85e3bbc4f85a829b329ca216628a840c050e65
xingzuolin/logsitic_chi_woe_py3
/func.py
385
3.5
4
#!/usr/bin/env python # -*- coding: utf-8 -*- # @Time : 2018/3/28 11:14 # @Author : Jun # @File : func.py import pandas as pd def read_path(path, sep): data = pd.read_csv(path, sep=sep) return data def convert_upper(data): if isinstance(data,list): data = [var.upper() for var in data] elif isinstance(data,str): data.upper() return data
9ead11fd9f66723fadb44da4e5cd73efa6b4896b
Akshay199456/100DaysOfCode
/Topics/Topic/Data Structures and Alogrithms (Topic)/Grokking the Coding Interview/26(Merge Intervals).py
4,947
3.96875
4
""" Problem statement: Given a list of intervals, merge all the overlapping intervals to produce a list that has only mutually exclusive intervals. Example 1: Intervals: [[1,4], [2,5], [7,9]] Output: [[1,5], [7,9]] Explanation: Since the first two intervals [1,4] and [2,5] overlap, we merged them into one [1,5]. svg viewer Example 2: Intervals: [[6,7], [2,4], [5,9]] Output: [[2,4], [5,9]] Explanation: Since the intervals [6,7] and [5,9] overlap, we merged them into one [5,9]. Example 3: Intervals: [[1,4], [2,6], [3,5]] Output: [[1,6]] Explanation: Since all the given intervals overlap, we merged them into one. """ """ ------------------------- My Approaches: 1. using the merge interval technique we can use the merge interval technique to solve this problem. if we are to sort the intervals based on their start time, it becomees easier to comapre if two intervals are merged worthy. if they are, then we combine them else if one interval is withing the other interval, the larger interval remains. when we come across an interval with which we dont merge, we push the interval we are hoilding into the new list and continue the same process till the end of the list Time complexity: O(n log n) wjere n is the number of intervals Space complexity: O(n) */ """ """ ------------------------- Other Approaches 1. Time complexity: O() Space complexity: O() """ """ ------------------------- Notes let's take example of two intervals (a and b) usch that a.start <= b.start. there are 4 possible scenariops: 1. a and b dont overlap 2. some part of b overlaps with a 3. a fully overlaps b 4. b fully overalps a but both have same start time goal is to merge intervals whenever they overlap for scenarios 2,3 and 4 this is how we will merge them 2. c = (a.start, b.end) 3. c = (a.start, a.end) 4. c = (a.start, b.end) algorithm looks like this 1. sport the intervals on the start time to ensure a.start <= b.start 2. if a overlaps b (i.e. b.start <= a.end), we need to merge them into a new interval c such that c.start = a.start c.end = max(a.end, b.end) 3. will keep repeeating the above two steps to merge c with the new interval if it overlaps with c. """ # My approaches(1) from __future__ import print_function class Interval: def __init__(self, start, end): self.start = start self.end = end def print_interval(self): print("[" + str(self.start) + ", " + str(self.end) + "]", end='') def merge_intervals(intervals, merged): new_interval = intervals[0] for i in range(1, len(intervals)): curr_interval = intervals[i] if curr_interval.start <= new_interval.end: if curr_interval.end > new_interval.end: new_interval = Interval(new_interval.start, curr_interval.end) else: merged.append(new_interval) new_interval = intervals[i] merged.append(new_interval) def merge(intervals): merged = [] # TODO: Write your code here intervals.sort(key=lambda x: x.start) merge_intervals(intervals, merged) return merged def main(): print("Merged intervals: ", end='') for i in merge([Interval(1, 4), Interval(2, 5), Interval(7, 9)]): i.print_interval() print() print("Merged intervals: ", end='') for i in merge([Interval(6, 7), Interval(2, 4), Interval(5, 9)]): i.print_interval() print() print("Merged intervals: ", end='') for i in merge([Interval(1, 4), Interval(2, 6), Interval(3, 5)]): i.print_interval() print() main() # Other Approaches(1) from __future__ import print_function class Interval: def __init__(self, start, end): self.start = start self.end = end def print_interval(self): print("[" + str(self.start) + ", " + str(self.end) + "]", end='') def merge(intervals): if len(intervals) < 2: return intervals # sort the intervals on the start time intervals.sort(key=lambda x: x.start) mergedIntervals = [] start = intervals[0].start end = intervals[0].end for i in range(1, len(intervals)): interval = intervals[i] if interval.start <= end: # overlapping intervals, adjust the 'end' end = max(interval.end, end) else: # non-overlapping interval, add the previous internval and reset mergedIntervals.append(Interval(start, end)) start = interval.start end = interval.end # add the last interval mergedIntervals.append(Interval(start, end)) return mergedIntervals def main(): print("Merged intervals: ", end='') for i in merge([Interval(1, 4), Interval(2, 5), Interval(7, 9)]): i.print_interval() print() print("Merged intervals: ", end='') for i in merge([Interval(6, 7), Interval(2, 4), Interval(5, 9)]): i.print_interval() print() print("Merged intervals: ", end='') for i in merge([Interval(1, 4), Interval(2, 6), Interval(3, 5)]): i.print_interval() print() main()
dee202f0dd33fc6f5533040f0b746ac50d1e6c05
AndruhaGit/labs-Python
/lab 8/1.py
2,047
3.859375
4
# 1. Створіть клас з ім'ям student, що містить поля: прізвище та ініціали, номер групи, # успішність (масив з п'яти елементів). Створити масив з десяти елементів такого типу, # впорядкувати записи за зростанням середнього бала. # Додати можливість виведення прізвищ і номерів груп студентів, які мають оцінки, рівні тільки 4 або 5. class Student: def __init__(self, full_name="", group_number=0, progress=[]): self.full_name = full_name self.group_number = group_number self.progress = progress def __repr__(self): return repr(("Student: " + self.full_name + " Group: " + self.group_number)) def set_full_name(self, full_name): self.full_name = full_name def set_group_number(self, group_number): self.group_number = group_number def set_progress(self, progress): self.progress = progress def get_full_name(self): return self.full_name def get_group_number(self): return self.group_number def get_progress(self): return self.progress st_size = 10 students = [] for i in range(st_size): st = Student() print("Введіть ім'я: ") st.full_name = input() print("Введіть номер групи: ") st.group_number = input() print("Введіть 5 оцінок: ") st.progress = [] for i in range(5): score = int(input()) st.progress.append(score) students.append(st) students = sorted(students, key=lambda student: student.full_name) print("Sorted students:") for st in students: print(st) print("bad students:") bad_studs = [stu for stu in students if any(x in stu.progress for x in [0, 1, 2])] if len(bad_studs) > 0: for st in bad_studs: print(st) else: print("no matches were found.")
a6bcfb3641874c3f7b440ea893c37893445c1119
BANDI-NAVEENKUMAR/palle_tech_programs
/some eg pro/b.py
127
3.515625
4
salary = 300 if salary > 500000: salary = salary - (10/100*salary) else: salary = salary - (5/100*salary) print(salary)
4b624d88b8886439d2ea8a87bf96ba00703707c5
ARundle01/brewery-tracking
/csv_prediction.py
11,732
3.75
4
""" This module is responsible for handling the data found within the provided CSV, to make predictions about sales in any given month in the future. It can also sort the data by month, by recipe and calculate figures such as percentage growth between months and the Average Annual Growth Rate. """ # Imports import csv from datetime import datetime import brewery_monitoring as b_m # Constants VALID_RECIPE: set = {"Organic Pilsner", "Organic Red Helles", "Organic Dunkel"} VALID_MONTH: list = [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" ] def import_to_dicts(file_name: str = "Barnabys_sales_fabriacted_data.csv") -> list: """ A function which imports the chosen CSV file into a list of dictionaries. :param file_name: str :return: orders: list """ with open(file_name, mode="r") as csv_file: csv_reader = csv.reader(csv_file, delimiter=",") orders: list = [] for row in csv_reader: order: dict = {"date": row[2], "quantity": row[5], "recipe": row[3]} orders.append(order) return orders def sort_by_month(orders: list) -> tuple: """ A function which sorts the contents of the CSV file into months. :param orders: List :return: tuple """ jan: list = [] feb: list = [] mar: list = [] apr: list = [] may: list = [] jun: list = [] jul: list = [] aug: list = [] sep: list = [] _oct: list = [] nov: list = [] dec: list = [] for order in orders: if "Jan" in order["date"]: jan.append(order) elif "Feb" in order["date"]: feb.append(order) elif "Mar" in order["date"]: mar.append(order) elif "Apr" in order["date"]: apr.append(order) elif "May" in order["date"]: may.append(order) elif "Jun" in order["date"]: jun.append(order) elif "Jul" in order["date"]: jul.append(order) elif "Aug" in order["date"]: aug.append(order) elif "Sep" in order["date"]: sep.append(order) elif "Oct" in order["date"]: _oct.append(order) elif "Nov" in order["date"]: nov.append(order) elif "Dec" in order["date"]: dec.append(order) return jan, feb, mar, apr, may, jun, jul, aug, sep, _oct, nov, dec def get_month_data(month: str, file_name: str) -> list: """ A month which gets the data for a specified month. :param month: str :param file_name: str :return: list """ jan, feb, mar, apr, may, jun, jul, aug, sep, _oct, nov, dec = \ sort_by_month(import_to_dicts(file_name)) if month == "Jan": return jan elif month == "Feb": return feb elif month == "Mar": return mar elif month == "Apr": return apr elif month == "May": return may elif month == "Jun": return jun elif month == "Jul": return jul elif month == "Aug": return aug elif month == "Sep": return sep elif month == "Oct": return _oct elif month == "Nov": return nov elif month == "Dec": return dec def calc_month_quantity_by_recipe(month: str, recipe: str, file_name: str) -> int: """ A function which calculates the quantity of a specific recipe for a specific month. :param month: str :param recipe: str :param file_name: str :return: int """ if month not in VALID_MONTH: raise ValueError("Date must be one of %s." % VALID_MONTH) elif recipe not in VALID_RECIPE: raise ValueError("Recipe must be one of %s." % VALID_RECIPE) else: month_data: list = get_month_data(month, file_name) total_quantity: int = 0 for order in month_data: if order.get("recipe") == recipe: total_quantity: float = total_quantity + int(order.get("quantity")) return total_quantity def calc_recipe_quantity_ratio( first_month: str, first_recipe: str, second_recipe: str, file_name: str, second_month: str = None) -> float: """ A function which calculates the ratio of quantity between two months. :param first_month: str :param first_recipe: str :param second_recipe: str :param file_name: str :param second_month: str :return: ratio: float """ if first_month not in VALID_MONTH: raise ValueError("Date must be one of %s." % VALID_MONTH) elif first_recipe not in VALID_RECIPE or second_recipe not in VALID_RECIPE: raise ValueError("Recipe must be on of %s." % VALID_RECIPE) else: if second_month is None: second_month: str = first_month first_quantity: int = calc_month_quantity_by_recipe(first_month, first_recipe, file_name) second_quantity: int = calc_month_quantity_by_recipe(second_month, second_recipe, file_name) ratio = round(first_quantity / second_quantity, 2) return ratio def calc_percent_growth_rate( last_month: str, this_month: str, recipe: str, file_name: str) -> float: """ A function which calculates the percentage growth between two months. :param last_month: str :param this_month: str :param recipe: str :param file_name: str :return: percent_growth_rate: float """ if last_month not in VALID_MONTH or this_month not in VALID_MONTH: raise ValueError("Date must be one of %s." % VALID_MONTH) elif recipe not in VALID_RECIPE: raise ValueError("Recipe must be one of %s." % VALID_RECIPE) else: last_month_quantity: int = calc_month_quantity_by_recipe(last_month, recipe, file_name) this_month_quantity: int = calc_month_quantity_by_recipe(this_month, recipe, file_name) percent_growth_rate: float = round(((this_month_quantity / last_month_quantity) - 1), 2) return percent_growth_rate def calc_annual_growth_rate(recipe: str, file_name: str) -> float: """ A function which calculates the Average Annual Growth Rate. :param recipe: str :param file_name: str :return: annual_growth_rate: float """ if recipe not in VALID_RECIPE: raise ValueError("Recipe must be one of %s." % VALID_RECIPE) else: total_growth: float = ( calc_percent_growth_rate("Nov", "Dec", recipe, file_name) + calc_percent_growth_rate("Dec", "Jan", recipe, file_name) + calc_percent_growth_rate("Jan", "Feb", recipe, file_name) + calc_percent_growth_rate("Feb", "Mar", recipe, file_name) + calc_percent_growth_rate("Mar", "Apr", recipe, file_name) + calc_percent_growth_rate("Apr", "May", recipe, file_name) + calc_percent_growth_rate("May", "Jun", recipe, file_name) + calc_percent_growth_rate("Jun", "Jul", recipe, file_name) + calc_percent_growth_rate("Jul", "Aug", recipe, file_name) + calc_percent_growth_rate("Aug", "Sep", recipe, file_name) + calc_percent_growth_rate("Sep", "Oct", recipe, file_name) ) annual_growth_rate: float = round((total_growth / 11), 2) return annual_growth_rate def predict_for_given_month(recipe: str, month: str, file_name: str) -> float: """ A function which predicts a quantity for a specific recipe for a specific month in the next year. :param recipe: str :param month: str :param file_name: str :return: predict_quantity: float """ if recipe not in VALID_RECIPE: raise ValueError("Recipe must be one of %s." % VALID_RECIPE) elif month not in VALID_MONTH: raise ValueError("Month must be one of %s." % VALID_MONTH) else: annual_growth_rate: float = calc_annual_growth_rate(recipe, file_name) month_quantity: int = calc_month_quantity_by_recipe(month, recipe, file_name) predict_quantity: float = round(month_quantity + (month_quantity * annual_growth_rate)) return predict_quantity def predict_on_current_stock() -> tuple: """ A function which can predict which beer should be made next based on sales figures and current batches of beer. :return: tuple """ dunkel = 0 helles = 0 pilsner = 0 current_month = datetime.now().strftime("%b") current_month_index = VALID_MONTH.index(current_month) if current_month_index == 10: in_two_month_index = 0 elif current_month_index == 11: in_two_month_index = 1 else: in_two_month_index = current_month_index + 2 in_two_month = VALID_MONTH[in_two_month_index] helles_predict = predict_for_given_month("Organic Red Helles", in_two_month, b_m.CSV_FILE[0]) dunkel_predict = predict_for_given_month("Organic Dunkel", in_two_month, b_m.CSV_FILE[0]) pilsner_predict = predict_for_given_month("Organic Pilsner", in_two_month, b_m.CSV_FILE[0]) predict_stock = [helles_predict, dunkel_predict, pilsner_predict] print(predict_stock[0]) for batch in b_m.view_all_batches_as_list(): if batch.recipe == "Organic Pilsner": pilsner = pilsner + batch.quantity elif batch.recipe == "Organic Dunkel": dunkel = dunkel + batch.quantity elif batch.recipe == "Organic Red Helles": helles = helles + batch.quantity stock = [dunkel, helles, pilsner] current_max = max(stock) current_min = min(stock) predict_max = max(predict_stock) predict_min = min(predict_stock) if current_max != 0: if stock.index(current_max) != 0 and predict_stock.index(predict_max) == 0: return "Dunkel", stock[0], predict_max elif stock.index(current_max) != 1 and predict_stock.index(predict_max) == 1: return "Red Helles", stock[1], predict_max elif stock.index(current_max) != 2 and predict_stock.index(predict_max) == 2: return "Pilsner", stock[2], predict_max elif current_min < predict_min: if stock.index(current_min) == 0: return "Dunkel", stock[0], predict_min elif stock.index(current_min) == 1: return "Red Helles", stock[1], predict_min elif stock.index(current_min) == 2: return "Pilsner", stock[2], predict_min else: return True, False, False else: if predict_stock.index(predict_max) == 0: return "Dunkel", stock[0], predict_max elif predict_stock.index(predict_max) == 1: return "Red Helles", stock[1], predict_max elif predict_stock.index(predict_max) == 2: return "Pilsner", stock[2], predict_max print(current_max, current_min, predict_max, predict_min) if __name__ == "__main__": b_m.create_new_batch("Batch 1", "Organic Dunkel", 100) b_m.create_new_batch("Batch 2", "Organic Dunkel", 100) b_m.create_new_batch("Batch 3", "Organic Dunkel", 100) b_m.create_new_batch("Batch 4", "Organic Dunkel", 100) b_m.create_new_batch("Batch 5", "Organic Dunkel", 100) b_m.create_new_batch("Batch 6", "Organic Dunkel", 100) b_m.create_required_tanks() predict_on_current_stock()
5073cd99bc8e8f1a1deecd262c2ade7a4466f7b7
Drake-Firestorm/Think-Python
/code/ackermann_memo.py
1,046
3.84375
4
import pprint known1 = dict() known2 = dict() # using nested dictionary def ack1(m, n): if not isinstance(m, int) or not isinstance(n, int) or m < 0 or n < 0: print("m and n should be non-negative integers") return None elif m == 0: return known1.setdefault(m, {}).setdefault(n, n+1) elif m > 0 and n == 0: return known1.setdefault(m, {}).setdefault(n, ack1(m-1, 1)) else: return known1.setdefault(m, {}).setdefault(n, ack1(m-1, ack1(m, n-1))) # using dual key def ack2(m, n): if not isinstance(m, int) or not isinstance(n, int) or m < 0 or n < 0: print("m and n should be non-negative integers") return None elif m == 0: return known2.setdefault((m, n), n+1) elif m > 0 and n == 0: return known2.setdefault((m, n), ack2(m-1, 1)) else: return known2.setdefault((m, n), ack2(m-1, ack2(m, n-1))) # 3,4 = 125; 3,6 = 509 m = 3; n = 6 print("W/ Nested Dict:", ack1(m, n)) print("W/ dual key Dict:", ack2(m, n)) pprint.pprint(known2)
b7f5748bdfec01da3656e6d67994f43a07cfbdc4
DesAbdWis/cw-python-temelleri
/notes.py
276
4.1875
4
notes = int(input("please enter your note : ")) if notes > 90: if notes >= 95: print("A+") else: print("A") elif notes >= 80 and notes < 90 : if notes >=85: print("B+") else : print("B") else : print("Below B")
67534f534e776a6e534eacca0f3c73b56eac765e
LayicheS/python_alg
/1189. “气球” 的最大数量.py
624
3.5
4
import queue import copy import time class Solution: def get_dict(self, text: str): d = {k: 0 for k in text} for each in text: d[each] += 1 return d def maxNumberOfBalloons(self, text: str) -> int: d1 = self.get_dict(text) d2 = self.get_dict('balloon') rst = len(text) // 7 for k, v in d2.items(): if k not in d1: return 0 rst = min(rst, d1[k] // v) return rst def main(): test = 'nlaebolko' rst = Solution() print(rst.maxNumberOfBalloons(test)) if __name__ == '__main__': main()
f3f647f27f7514aba6570bda12bc8a35e7972394
SergiodeGrandchant/introprogramacion
/practico/ejercicio13.py
255
3.671875
4
# https://bit.ly/36LtifW num = int(input("Dame los terminos a usar")) suma = 0 for i in range(1, num + 1): if i % 2 == 0: signo = -1 else: signo = 1 res = signo / (1 + 2 * (i - 1)) suma = suma + res pi = 4 * suma print(pi)
5b09debf4d04fcc7dabcecfeb836a56a7a5e8046
LuxAter/Aetas
/test.py
3,411
3.640625
4
#!/usr/bin/env python3 from snake import * import numpy as np import time import copy N = 20 def user_input(position, N): while True: move = input() if move == 'w': return 0 elif move == 's': return 1 elif move == 'd': return 2 elif move == 'a': return 3 elif move == 'q': return -1 elif move == 'r': print(apple_ray(position, N)) def get_vec_in(position): rays = [1 if x < N**2 else 0 for x in apple_ray(position, N)] + [1/(x+1) for x in wall_ray(position, N)] + [1/(x+1) for x in snake_ray(position, N)] return np.asarray(rays) def snake2(N, get_move, W, max_turn = 0, display=False, sleep=None): score = 0 turn = 0 length = 1 position = [[(N //2, N//2)], (np.random.randint(1, N - 1), np.random.randint(1, N - 1))] for i in range(3): position[0].append(position[0][0]) # position = [[(np.random.randint(1, N - 1), np.random.randint(1, N - 1))], # (np.random.randint(1, N - 1), np.random.randint(1, N - 1))] while (True): if sleep: time.sleep(sleep) if display: draw(position, N) move = get_move(position, N) if move < 0: break prev_len = len(position[0]) pos_copy = copy.deepcopy(position) position = update(position, move, N) if prev_len != len(position[0]): apple_stuff(pos_copy,W) if max_turn < 0 and len(position[0]) != length: length = len(position[0]) turn = -1 if not valid(position, N): break turn += 1 if max_turn > 0 and turn >= max_turn: break if max_turn < 0 and turn >= abs(max_turn): break return pos_copy #return losing position if __name__ == "__main__": #randomize weights num_games = 1 #for i in range(num_games): #intialize game #losing_pos = snake2(N,user_input,100,True,0) ######## # weights = np.array( # [[0.6, 0, 0, 0, -1.3, 0, 0, 0, -1.3, 0, 0.5, 0], # [0, 0, 0.6, 0, 0, 0, -1.3, 0, 0.5, 0, -1.3, 0], # [0, 0.6, 0, 0, 0, -1.3, 0, 0, 0, -1.3, 0, 0.5], # [0, 0, 0, 0.6, 0, 0, 0, -1.3, 0, 0.5, 0, -1.3]]) #weights = np.random.rand(4,12) weights = np.zeros((4,12)) print(weights) def net_move(position,N): inp = get_vec_in(position) probs = np.matmul(weights,inp) return np.random.choice([i for i, x in enumerate(probs) if x == max(probs)]) def apple_stuff(apple_pos,weights): apple_move = np.zeros(4) index = net_move(apple_pos,N) apple_move[index] = 1 apple_inp = get_vec_in(apple_pos) M = np.asmatrix(apple_move) I = np.asmatrix(apple_inp) weights += 0.05*M.T@I ####### for i in range(10000): if i%100 == 0: losing_pos = snake2(N,net_move,weights,-100,True,0.01) else: losing_pos = snake2(N,net_move,weights,-100,False,0) #vec:t losing_move = np.zeros(4) index = net_move(losing_pos,N) losing_move[index] = 1 losing_inp = get_vec_in(losing_pos) M = np.asmatrix(losing_move) I = np.asmatrix(losing_inp) #test = losing_move@losing_inp weights -= 0.1*M.T@I
63bfb3f7e87284dcbc1ba32f7e0cab935d66e68e
north314star/Weather-Final
/weather.py
1,243
3.5
4
import requests start_over = 'true' while start_over == 'true': city = input('Enter a city name you want to look at:') api_key ='dd29fda4360eb6271e53bbe6a6e445ce' def get_weather(api_key, city): url = f"http://api.openweathermap.org/data/2.5/weather?q={city}&units=imperial&appid={api_key}" r = requests.get(url) res = r.json() temp = res ['main']['temp'] temp_min = res['main']['temp_min'] temp_max = res['main']['temp_max'] feels_like = res['main']['feels_like'] humidity = res ['main']['humidity'] condition = res['weather'][0]['main'] description = res['weather'][0]['description'] print(f"Condition: {condition}\nTemp: {temp}'F\nTemp Max: {temp_max}'F\nTemp Min: {temp_min}'F\nFeels Like: {feels_like}'F\nHumidity: {humidity}%\nDescription: {description}") get_weather(api_key, city) print('to restart type y or to quit type Enter') redo_program = input() if redo_program == 'y': start_over = 'true' else: start_over = 'null' exit
a6fea334dafbd4ea80330873947b7cf8068d2387
sajithgowthaman/GA---All-Exercises-
/hw-09-inheritance-and-file-io/exercise3.py
1,798
3.515625
4
import csv # Employees is a list of dictionaries. # The keys in these dictionaries will be the header fields of your spreadsheet. employees = [ { 'first_name': 'Bill', 'last_name': 'Lumbergh', 'job_title': 'Vice President', 'hire_date': 1985, 'performance_review': 'excellent' }, { 'first_name': 'Michael', 'last_name': 'Bolton', 'job_title': 'Programmer', 'hire_date': 1995, 'performance_review': 'poor' }, { 'first_name': 'Peter', 'last_name': 'Gibbons', 'job_title': 'Programmer', 'hire_date': 1989, 'performance_review': 'poor' }, { 'first_name': 'Samir', 'last_name': 'Nagheenanajar', 'job_title': 'Programmer', 'hire_date': 1974, 'performance_review': 'fair' }, { 'first_name': 'Milton', 'last_name': 'Waddams', 'job_title': 'Collator', 'hire_date': 1974, 'performance_review': 'does he even work here?' }, { 'first_name': 'Bob', 'last_name': 'Porter', 'job_title': 'Consultant', 'hire_date': 1999, 'performance_review': 'excellent' }, { 'first_name': 'Bob', 'last_name': 'Slydell', 'job_title': 'Consultant', 'hire_date': 1999, 'performance_review': 'excellent' } ] for items in employees: items["review_finished"] = "yes" for items in employees: if items['first_name'] == 'Bill' and items['last_name'] == 'Lumbergh' or items['job_title'] == 'Consultant': items["performance_review"] = "Poor" else: items["performance_review"] = "Excellent" def main(): # Write your code here with open('tps_report.csv', 'w') as csv_file: dict_writer = csv.DictWriter(csv_file, employees[0].keys()) dict_writer.writeheader() dict_writer.writerows(employees) main()
30fbd39a29c38c7600ab041e227bbe4abe5d4f61
shadow99chen/CF2
/ex1.py
967
3.5
4
#对cars赋值 cars = 100 #对spase_in_a_car赋值 space_in_a_car = 4.0 #对drivers赋值 drivers = 30 #对pasengers赋值 pasengers = 90 #对cars_not_driven赋值 cars_not_driven = cars - drivers #对cars_driven赋值 cars_driven = drivers #对carpool_capacity赋值 carpool_capacity = cars_driven * space_in_a_car #对average_passengers_per_car赋值 average_passengers_per_car = pasengers / cars_driven #输出可提供的车辆数目 print("There are",cars,"cars available.") #输出可供使用的司机人数 print("There are only",drivers,"drivers available.") #输出空车辆的数目 print("There will be",cars_not_driven,"empty cars today.") #输出能运输的总人数 print("We can transport",carpool_capacity,"people today.") #输出我们需要运输总人数 print("We have",pasengers,"to carpool today.") #输出我们每车平均需要装载的人数 print("We need to put about",average_passengers_per_car,"in each car.")
c6917ee6b5916a0c28e594219482d5ba392e4b6d
Mudrobot/Python-Crawler
/Requests/Xpath basic.py
730
3.6875
4
# Xpath是在xml文档中搜索内容的一种语言 # html是xml的一个子集 html=""" <book> <id>1</id> <name>野花遍地香</name> <price>1.23</price> <nick>臭豆腐</nick> <author> <nick id="10086">王者荣耀</nick> <nick id="10010">和平精英</nick> <nick class="game">原神</nick> <nick class="joy">使命召唤</nick> <div> <nick>真的好玩!!!</nick> </div> </author> <partner> <nick id="LBW">卢本伟</nick> <nick id="DSM">大司马</nick> </partner> </book> """ from lxml import etree tree=etree.XML(html) #result=tree.path("/book") result=tree.xpath("/book/author/*/nick/text()") print(result)