blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
08db9c054d738f65c7743e8c29df5b9b08d08e75
Pitrified/snippet
/python/logger-example/logger_main.py
3,655
3.75
4
# good guides # https://www.pylenin.com/blogs/python-logging-guide/ # https://realpython.com/python-logging/ import logging from logger_module import * from logger_class import * def setup_logger(): """setup the loggers for the main module a main_logger that prints to file a console_logger that prints to console """ ########################################################################### # get the main logger main_logger = logging.getLogger(__name__) # To override the default severity of logging main_logger.setLevel("DEBUG") # Use FileHandler() to log to a file file_handler = logging.FileHandler("main_logs.log", mode="w") # default is 'a' # set a specific format for this log (better for this handler) log_format_file = ( "%(asctime)s::%(levelname)s::%(name)s::" "%(filename)s::%(lineno)d::%(message)s" ) formatter = logging.Formatter(log_format_file) file_handler.setFormatter(formatter) # Don't forget to add the file handler main_logger.addHandler(file_handler) main_logger.info("I am a separate main_logger") ########################################################################### # setup the console logger console_logger = logging.getLogger(f"{__name__}.console") console_logger.setLevel("INFO") # we need to stop the propagation of the messages to the parent logger console_logger.propagate = False # StreamHandler to print to console console_handler = logging.StreamHandler() # format the console output log_format_console = "%(asctime)s - %(name)s - %(levelname)s - %(message)s" formatter = logging.Formatter(log_format_console) console_handler.setFormatter(formatter) # add the handler to the logger console_logger.addHandler(console_handler) # this will not be printed console_logger.debug(f"My name is {__name__}") # this will be printed console_logger.info(f"My name is {__name__}!!!") def test_child_logger(): """show an example of child logger it inherits all the properties of the parents, so no setup is needed this is very useful to turn on/off debug statement on a per function basis """ # .child will have .console as parent child_logger = logging.getLogger(f"{__name__}.console.child") child_logger.setLevel("DEBUG") child_logger.debug(f"Debug me") def test_verbose_logger(): """show a second console logger to have different print stream just raise the level above any message you print with the verbose logger """ # you can have as many as you want # I have doubts: is making this a child of console useful at all? verbose_logger = logging.getLogger(f"{__name__}.console.verbose") # but don't propagate up this messages verbose_logger.propagate = False verbose_logger.setLevel("DEBUG") # change the formatting as needed, you need a new handler verbose_handler = logging.StreamHandler() log_format_verbose = "Verbose:\n%(message)s" formatter = logging.Formatter(log_format_verbose) verbose_handler.setFormatter(formatter) # and remember to add it to the logger verbose_logger.addHandler(verbose_handler) from random import random long_list = [f"{random():.4f}" for _ in range(10)] verbose_logger.debug(long_list) def main(): """examples of logging modules """ setup_logger() test_child_logger() test_verbose_logger() test_exception_logger() setup_module_logger() test_multiple_handlers() myclass = sample_class() myclass2 = sample_class() if __name__ == "__main__": main()
1f8dbde509272c7403244a7133dded6ee6355ad9
ericosur/ericosur-snippet
/Topics/boshiamy/find_spell.py
1,915
4.0625
4
#!/usr/bin/env python3 # coding: utf-8 ''' search radicals from Boshiamy.txt and show unicode code point ''' import sys import re from typing import List import unicode_blocks class Solution: ''' solution ''' def __init__(self): self.data_file = 'boshiamy_radicals.txt' self.fileobj = None self.block_obj = unicode_blocks.UnicodeBlock() self.lineno = 0 def __enter__(self): #print('__enter__') self.fileobj = open(self.data_file, 'rt', encoding='utf8') return self def __exit__(self, exc_type, exc_value, traceback): #print('__exit__') self.fileobj.close() def split_line(self, s: str) -> (str, str): ''' split line into two part ''' #print(s) arr = s.split(' ') if len(arr) != 2: print(f'[WARN][{self.lineno}] cannot split into two parts: {s}') return (None, None) #print(arr) return (arr[0], arr[1]) def show_ans(self, p: str, q: str): ''' show answer [in] p is the boshiamy radicals [in] q is the CJK characters ''' print(f'{p:6s} {q:4s} {ord(q):5X} @{self.lineno} ', end='') print(self.block_obj.block(q)) def find_ch(self, regexp: str): ''' find character ''' print(f'=====> regexp: __{regexp}__') self.fileobj.seek(0) self.lineno = 0 for ll in self.fileobj.readlines(): self.lineno += 1 (pp, qq) = self.split_line(ll.strip()) if pp: m = re.search(regexp, pp) if m: self.show_ans(pp, qq) def main(argv: List[str]): ''' main ''' with Solution() as s: for rr in argv: s.find_ch(rr) print('*' * 55) if __name__ == '__main__': if len(sys.argv) == 1: main([r'jzez']) else: main(sys.argv[1:])
08cf6d58b1803a2025e3e50dad74fea1ff188c5b
Krosenblad/dataprocessing
/homework/scraper/tvscraper.py
4,807
3.84375
4
#!/usr/bin/env python # Name: Kajsa Rosenblad # Student number: 11361840 """ This script scrapes IMDB and outputs a CSV file with highest rated tv series. """ import csv from requests import get from requests.exceptions import RequestException from contextlib import closing from bs4 import BeautifulSoup import re TARGET_URL = "http://www.imdb.com/search/title?num_votes=5000,&sort=user_rating,desc&start=1&title_type=tv_series" BACKUP_HTML = 'tvseries.html' OUTPUT_CSV = 'tvseries.csv' def extract_tvseries(dom): """ Uses Beautiful Soup library to scrape information from IMDB, appending it to separate lists, then lastly joining lists and returning the information. """ # Create list for all movie titles, check for missing values title_list =[] for title in dom('h3', 'lister-item-header'): text = title.contents[3] name = empty(text.string) title_list.append(name) # Create list for all ratings, check for missing values rate_list = [] for rate in dom('span', 'value'): rating = empty(rate.text) rate_list.append(rating) # Create list for all genres, strip \n and blank spaces, check for missings genre_list = [] for genre in dom('span', 'genre'): genres = genre.string.strip('\n') genres = empty(genres.strip()) genre_list.append(genres) # Access info per movie (chunk), create two lists to append actors in chunks movie_actor = [] all_actors = [] for chunk in dom('div', 'lister-item-content'): for actor in chunk(href = re.compile('adv_li_st')): movie_actor.append(actor.string) # Create empty string to store lists of actors in string = '' for i in range (len(movie_actor)): # Use length of list to access individual actors string += str(movie_actor[i]) if i != len(movie_actor) - 1: string += ', ' # Check for missing values string = empty(string) all_actors.append(string) movie_actor = [] # Create list for runtime, check for missing values runtime_list = [] for runtime in dom('span', 'runtime'): run = empty(runtime.text.strip('min')) runtime_list.append(run) # Collect all data per series, using two lists tvseries = [] series = [] # Append information per series, create a list for i in range(50): series.append(title_list[i]) series.append(rate_list[i]) series.append(genre_list[i]) series.append(all_actors[i]) series.append(runtime_list[i]) # Append all information from list to master-list, empty initial list tvseries.append(series) series = [] return tvseries # Function to check for missing values def empty(item): if not item: string = 'No information' return string else: return item def save_csv(outfile, tvseries): """ Output a CSV file containing highest rated TV-series. """ writer = csv.writer(outfile) writer.writerow(['Title', 'Rating', 'Genre', 'Actors', 'Runtime']) for i in range (50): writer.writerow(tvseries[i]) def simple_get(url): """ Attempts to get the content at `url` by making an HTTP GET request. If the content-type of response is some kind of HTML/XML, return the text content, otherwise return None """ try: with closing(get(url, stream=True)) as resp: if is_good_response(resp): return resp.content else: return None except RequestException as e: print('The following error occurred during HTTP GET request to {0} : {1}'.format(url, str(e))) return None def is_good_response(resp): """ Returns true if the response seems to be HTML, false otherwise """ content_type = resp.headers['Content-Type'].lower() return (resp.status_code == 200 and content_type is not None and content_type.find('html') > -1) if __name__ == "__main__": # get HTML content at target URL html = simple_get(TARGET_URL) # save a copy to disk in the current directory, this serves as an backup # of the original HTML, will be used in grading. with open(BACKUP_HTML, 'wb') as f: f.write(html) # parse the HTML file into a DOM representation dom = BeautifulSoup(html, 'html.parser') # extract the tv series (using the function you implemented) tvseries = extract_tvseries(dom) # write the CSV file to disk (including a header) with open(OUTPUT_CSV, 'w', newline='') as output_file: save_csv(output_file, tvseries)
fb475df49cb549bdf1215266960cd30e7efde11d
cassianomaia/falsa-posicao
/posicao_falsa.py
1,063
3.859375
4
import math # Constante que define o numero máximo de iterações que o método irá realizar MAX_ITER = 1000000 # Função que será analisada def func(x): return (math.pow(x,3) - math.pow(x,2) + 2) # Função x³ - x² + 2 # Calcula a raiz da função(x) dado o intevalo [a,b] def posicaoFalsa(a, b): if func(a) * func(b) >= 0: print("Você assumiu valores errados para a e b") return -1 c = a # Inicia o resultado com o valor de a for i in range(MAX_ITER): # Procura o ponto que toca o eixo x c = b - (func(b) * (b - a)) / (func(b) - func(a)) # Verifica se o ponto calculado é raiz if func(float('%.4f' % c)) == 0: print("Parou na interação: ", '%f' % i) break elif func(c) * func(a) < 0: b = c else: a = c print("O valor da raiz é : ", '%.4f' % c) # Função principal if __name__ == '__main__': a = int(input("Digite o valor de a:")) b = int(input("Digite o valor de b:")) posicaoFalsa(a, b)
1bdc2f86719334f08d7afa6c4345cecb0c0d406f
CodersInSeattle/InterviewProblems
/problems/sorting/pancake_sort.py
815
4.25
4
""" Given an unsorted array, sort the given array using only a flip() operation: flip(arr, i): Reverse arr from 0 to i """ def flip(arr, i): # Implemented only for testing low, high = 0, i while low < high: arr[low], arr[high] = arr[high], arr[low] low += 1 high -= 1 def pancake_sort(arr): for i in xrange(len(arr)-1, -1, -1): best_index = _find_max_up_to(arr, i) flip(arr, best_index) flip(arr, i) return arr def _find_max_up_to(arr, right_bound): best_index = 0 max_val = None for i in range(right_bound + 1): if arr[i] > max_val: best_index = i max_val = arr[i] return best_index if __name__ == '__main__': NUMS = [-3, 2, 23, 5, 8, 2, 9, 0, 0, -2, -4] print pancake_sort(NUMS)
808bae2834c04f1816c468f094115e02bbb007a0
green-fox-academy/Angela93-Shi
/week-03/day-04/movies_info.py
1,556
3.609375
4
movie_dict = {} movie_list = [ { "id":1, "title":"Glass", "year": 1987, "description":"Security guard David Dunn uses his supernatural abilities to track Kevin Wendell Crumb, a disturbed man who has twenty-four personalities." }, { "id":2, "title":"The Kid Who Would Be King", "year": 1990, "description":"A band of kids embark on an epic quest to thwart a medieval menace." }, { "id":3, "title":"Miss Bala", "year": 2005, "description":"Gloria finds a power she never knew she had when she is drawn into a dangerous world of cross-border crime. Surviving will require all of her cunning, inventiveness, and strength. Based on the Spanish-language film." }, { "id":4, "title":"The Lego Movie 2: The Second Part", "year": 2010, "description":"It's been five years since everything was awesome and the citizens are facing a huge new threat: Lego Duplo invaders from outer space, wrecking everything faster than they can rebuild." }, { "id":5, "title":"What Men Want", "year": 2010, "description":"A woman is boxed out by the male sports agents in her profession, but gains an unexpected edge over them when she develops the ability to hear men's thoughts." }, ] for movie in movie_list: movie_dict['id'] = movie['id'] movie_dict['title'] = movie['title'] movie_dict['year'] = movie['year'] movie_dict['description'] = movie['description'] print(movie_dict)
cf8bff9829bc8c6e40ac3dacdc7a0d3ad320c4c0
Aasthaengg/IBMdataset
/Python_codes/p02406/s370570836.py
126
3.84375
4
n = int(input()) for i in range(1, n+1): if i%3 == 0 or str(i).find('3') != -1: print(f" {i}", end = '') print()
e26cef09e1b49c1a34fb1b5b435b00475ec21182
Iwata-Factory/IwataProject
/PYTHON/get_gps_for_plot.py
623
3.5
4
#!/user/bin/env python # coding: utf-8 def main(): f = open('gpslog.txt') data = f.read() # ファイル終端まで全て読んだデータを返す f.close() # 区切り文字はmacとwindowsで違うかも lines = data.split('\n') # 改行で区切る(改行文字そのものは戻り値のデータには含まれない) lat = [] lng = [] for i, line in enumerate(lines): if line == '*': lat.append(lines[i + 2]) lng.append(lines[i + 3]) for j in range(0, len(lat)): print(lat[j] + " " + lng[j]) if __name__ == '__main__': main()
5f6ccab9deb209f4ceb68892a6732d39897c7f58
jorgeiksdh/HouseTextGame
/roomGenerator.py
2,790
3.703125
4
globalFlag = 1 points = [] area = [] doors = [(-2,3),(0,0)] entrance = () out = () while globalFlag == 1: print("1. Obtener las coordenadas del muro y del área del cuarto") print("2. Salir") choice = int(input("Selección: ")) if choice == 1: choiceFlag = 1 while choiceFlag == 1: x1 = int(input("Introduzca el primer valor de x, el menor: ")) x2 = int(input("Introduzca el segundo valor de x, el mayor: ")) y1 = int(input("Introduzca el primer valor de y, el menor: ")) y2 = int(input("Introduzca el segundo valor de y, el mayor: ")) pointBuffer = [(x,y) for x in range(x1,x2+1) for y in range(y1,y2+1)] areaBuffer = [(x,y) for x in range(x1+1,x2) for y in range(y1+1,y2)] print("Area = ",areaBuffer) for i in pointBuffer[:]: if i in area: pointBuffer.remove(i) points.append(pointBuffer) print("Walls: ",points) wallsFlag = 1 while wallsFlag == 1: print("De la lista de coordenadas selecciona la o las puertas del cuarto") selectionX = int(input("Coordenada x: ")) selectionY = int(input("Coordenada y: ")) coord = (selectionX, selectionY) doors.append(coord) for i in points[:]: if i in doors: points.remove(i) print("Walls: ",points) print("\n1. Ingresar otra puerta\n2. Siguiente paso") option = int(input("Selección: ")) if option == 1: continue else: wallsFlag = 0 print("\n1. Ingresar otro cuarto\n2. Seleccionar entradas y salidas") selection = int(input("Selección: ")) if selection == 1: continue else: choiceFlag = 0 print("Walls: ",points) print("De la lista de coordenadas selecciona la entrada") selectionX = int(input("Coordenada x: ")) selectionY = int(input("Coordenada y: ")) coord = (selectionX, selectionY) entrance = coord print("De la lista de coordenadas selecciona la salida") selectionX = int(input("Coordenada x: ")) selectionY = int(input("Coordenada y: ")) coord = (selectionX, selectionY) out = coord for i in puntos[:]: if i in entrance or i in out: puntos.remove(i) print("walls = ",points) print("area = ",area) print("doors = ",doors) print("in = ",entrance) print("out = ",out) elif choice == 2: globalFlag = 0
aa619eedc1911033b079bafe6392e98246a87ef9
Jongveloper/hanghae99_algorithm_class
/algorithm_practice/2609.py
722
3.578125
4
# 두 개의 자연수를 입력받아 최대 공약수와 최소 공배수 구하기 # 문제 접근 방식 : # 최대공약수: a 와 b의 최대공약수는 b 와 a를 나눈 나머지의 최대공약수와 같다. # 최소공배수: a 와 b의 최소공배수는 a*b/최대공약수(a,b)를 해주면 최수 공배수가 된다. # 최소공배수가 되는 이유는 이 수를 a와 b 모두 나누어떨어지고 나누어 떨어지는 수 중 가장 작은 수이기 때문이다. l, r = map(int, input().split(' ')) def gcd(a, b): mod = a % b while mod > 0: a = b b = mod mod = a % b return b def lcm(a, b): return a * b // gcd(a, b) print(gcd(l, r)) print(lcm(l, r))
c649f6449fce38e22bec8258d8621c32f18dc6a6
MultiRRomero/lightwall-pong
/server/game.py
1,730
3.625
4
#!/usr/bin/python import time """ This represents a ball object in pong """ class Ball: def __init__(self, position_x, position_y, direction, speed): self.px = position_x # x coordinate (in pixels) self.py = position_y # y coordinate (in pixels) self.dir = direction # ball direction (in degrees) self.vel = speed # ball velocity (in pixels per second) def update(self): print 'update' def serialize(self): return ','.join([str(self.px), str(self.py)]) """ This represents a player object in pong """ class Player: def __init__(self, section_id, paddle_place, paddle_size, player_id): self.sid = section_id # Section enum representing where we are self.place = paddle_place # Place of the paddle relative to the section self.size = paddle_size # Size of the paddle, this is for the future self.id = player_id # ID of the player, preferably FBID def serialize(self): return ','.join([str(self.place), str(self.size)]) """ This keeps track of the game state for pong """ class GameState: def __init__(self, num_players): self.players = [ Player(i, 0, 0, 0) for i in range(num_players) ] self.ball = Ball(0, 0, 0, 0) def runInstance(self): self.ball.update(); def run(self): # Wake up every 10ms while True: self.runInstance() time.sleep(.01) def serialize(self): parts = [ self.ball.serialize() ] for player in self.players: parts.append(player.serialize()) return '\n'.join(parts) """ TESTING """ if __name__ == '__main__': plr = Player(10, 0, 0, 0) print plr.sid
ee68d0b52e43c6d61bc1f7496a9c63222f2c653f
alrahimi/PythonAbstractAlgebra
/FieldABC/GroupMultipicative/Semigroup.py
482
3.6875
4
from abc import ABCMeta, abstractmethod class Semigroup(metaclass=ABCMeta): @abstractmethod def mulop(self,x): pass def __init__(self,value): self.v=value def __mul__(self,rhs): print("SemigroupMul rhs=",rhs,"type(rhs)=",type(rhs)) #r = Semigroup(self.mulop(rhs)) #return r return self.mulop(rhs) def __str__(self): s = "%s" % (self.v) return s
2eaad41d0bd687c9c8cd816bc723a95e5838e8ef
chantigit/pythonbatch1_june2021data
/Python_9to10_June21Apps/project1/functionapps/tasks.py
548
3.890625
4
#Task2: Power of a number def power(a,b): res=a**b print(res) #Task3: Biggest of 4 numbers def largestNumber(n1,n2,n3,n4): if n1>n2 and n1>n3 and n1>n4: print(n1,' is big') #Task4: Find factorial of a number def fact(n): f=1 for i in range(1,n+1): f=f*i print(f) #Task5: Print reverse of a number def reverse(n): rev=0 while n>0: rem=n%10 rev=(rev*10)+rem n=n//10 print(rev) #Calling Functions power(2,10) #1024 largestNumber(100,10,20,30) #100 fact(5) #120 reverse(123)
873658fb8d3233b62319ab25ac806b7336b54cc9
RonsonGallery/Steganography
/CaesarCipher.py
1,872
4.09375
4
#--------------------------------------- #-----------Caesar Cipher--------------- #--------------------------------------- # Ceaser Cipher class class CaesarCipher: # this method encrypt the plain text @staticmethod def encrypt(string,key): result = "" for char in string: if char == " ": result += " " continue if ord(char) > 96 : result += chr((ord(char) + key - 97) % 26 + 97) else: result += chr((ord(char)+ key - 65) % 26 +65) # acsii_value = ord(char) # temp = acsii_value - 97 if acsii_value > 96 else acsii_value - 65 # new_ascii = (temp + key) % 26 # new_char = chr(new_ascii+97) if acsii_value > 96 else chr(new_ascii+65) # result += new_char return result # this method decrypt cipher text @staticmethod def decrypt(string,key): result = "" for char in string: if char == " ": result += " " continue if ord(char) > 96 : result += chr((ord(char) - key - 97) % 26 + 97) else: result += chr((ord(char) - key -65) % 65 +65) # acsii_value = ord(char) # temp = acsii_value - 97 if acsii_value > 96 else acsii_value - 65 # new_ascii = (temp - key) % 26 # new_char = chr(new_ascii+97) if acsii_value > 96 else chr(new_ascii+65) # result += new_char return result #----Testing------- if __name__ == "__main__": String = "Hey i am a plain text" key = 3 encrypted = CaesarCipher.encrypt(String,key) decrypted = CaesarCipher.decrypt(encrypted,key) print("Plain Text : ", String) print("Encrypted : ", encrypted) print("Decrypted : ", decrypted)
b21fb237714fa95523c292371984d174953a62de
souravs17031999/100dayscodingchallenge
/heaps_and_priorityQueues/check_binary_heap.py
739
3.96875
4
# Program for checking if given array forms binary heap or not. # idea is to check from last internal node that is at n//2 - 1 , to check # if at any node up the tree, we have if any voilation of heapify depending on # whether we are checking min-heap, or max-heap. # TIME : 0(N), space : 0(1). def left(i): return 2 * i + 1 def right(i): return 2 * i + 1 def Check_Heap(arr): n = len(arr) for i in range(n//2 - 1, -1, -1): if arr[i] < arr[left(i)]: return False if arr[i] < arr[right(i)]: return False return True if __name__ == '__main__': arr = [90, 15, 10, 7, 12, 2] print(Check_Heap(arr)) arr1 = [90, 15, 10, 7, 12, 2, 7, 3] print(Check_Heap(arr1))
d4e244e3e61f34a7c9c534c6b2545fc1dce60269
adeneviyani/keamanan-perangkat-lunak
/Tugas program sederhana revisi.py
2,328
3.828125
4
# Tugas program sederhana # Nama : Ade Neviyani # Nim : 19051397018 # IDENTITAS MAHASISWA nama = input ("nama : ") nim = input ("nim : ") # deklarasi fungsi operator def fungsi_total_nilai (Nilai_Partisipasi,Nilai_Tugas,Nilai_UTS,Nilai_UAS): Nilai_Partisipasi = int (Nilai_Partisipasi) *0.2 Nilai_Tugas = int (Nilai_Tugas) *0.3 Nilai_UTS = int (Nilai_UTS) *0.4 Nilai_UAS = int (Nilai_UAS) *0.5 Nilai_Akhir = Nilai_Partisipasi + Nilai_Tugas + Nilai_UTS + Nilai_UAS if Nilai_Partisipasi <0 or Nilai_Tugas <0 or Nilai_Tugas <0 or Nilai_UTS <0 or Nilai_UAS <0: raise ValueError return Nilai_Akhir # deklarasi fungsi percabangan def fungsi_percabangan (var_Nilai) : var_indeks = "" if (var_Nilai >= 0 and var_Nilai < 40) : var_indeks = "E" elif (var_Nilai >= 40 and var_Nilai < 55) : var_indeks = "D" elif (var_Nilai >= 55 and var_Nilai < 60) : var_indeks = "C" elif (var_Nilai >= 60 and var_Nilai < 65) : var_indeks = "C+" elif (var_Nilai >= 65 and var_Nilai <70) : var_indeks = "B-" elif (var_Nilai >= 70 and var_Nilai <75) : var_indeks = "B" elif (var_Nilai >= 75 and var_Nilai <80) : var_indeks = "B+" elif (var_Nilai >= 80 and var_Nilai < 85) : var_indeks = "A-" elif (var_Nilai >= 85 and var_Nilai < 100) : var_indeks = "A" return var_indeks #output: Decimal('0.40') print(D('0.00') * D('0.40')) # deklarasi pengrulangan def fungsi_pengulangan () : var_hasil_perulangan = 0 for i in range (1,3) : print ("..........Nilai ke" ,i, "..........") var_Partisipasi = input ("Nilai_Partisipasi :") var_Tugas = input ("Nilai_Tugas :") var_UTS = input ("Nilai_UTS :") var_UAS = input ("Nilai_UAS :") # pemanggilan fungsi penjumlahan var_hasil_perulangan += (int(fungsi_total_nilai(var_hasil_perulangan,var_Tugas,var_UTS,var_UAS))) return var_hasil_perulangan / i # pemanggilan fungsi perulangan var_total = fungsi_pengulangan () print ("..........TOTAL NILAI..........") print ("TOTAL NILAI AKHIR YANG DIDAPAT : ", var_total) # pemanggilan fungsi percabangan print ("TOTAL NILAI AKHIR YANG DIDAPAT : ", fungsi_percabangan(var_total))
72d89cda8da425b14453ec1b612eb658608a1a63
huanglun1994/learn
/python编程从入门到实践/第六章/6-7.py
812
3.953125
4
# -*- coding: utf-8 -*- my_girlfriend = { 'relationship': "My girlfriend's", 'first_name': 'Wang', 'last_name': 'Di', 'age': 23, 'city': 'Cheng Du', } me = { 'relationship': 'My', 'first_name': 'Huang', 'last_name': 'Lun', 'age': 23, 'city': 'Cheng Du', } my_friend = { 'relationship': "My friend's", 'first_name': 'Ran', 'last_name': 'Ming', 'age': 24, 'city': 'Ning Bo', } people = [me, my_girlfriend, my_friend] for person in people: print('\n' + person['relationship'] + " first_name is " + person['first_name'] + '.') print(person['relationship'] + " last_name is " + person['last_name'] + '.') print(person['relationship'] + " age is " + str(person['age']) + '.') print(person['relationship'] + " city is " + person['city'] + '.')
9306a590261d23bcc5b3ecaa53d633392200444a
KennyMC155/JustTom.py
/main.py
469
3.765625
4
from funk import searchingGame, mathematicOper, main_menu import time print("Hello, my name is Tom, let's play") time.sleep(2) main_menu() gamenumber = int(input()) while gamenumber != 3: if gamenumber == 1: searchingGame() time.sleep(3) main_menu() gamenumber = int(input()) elif gamenumber == 2: time.sleep(3) mathematicOper() main_menu() gamenumber = int(input()) else: print("Ok, bye")
aa4b1db7e0b217bb4563c2cb7f0646774d08f1f9
jacquerie/leetcode
/leetcode/0766_toeplitz_matrix.py
586
3.578125
4
# -*- coding: utf-8 -*- class Solution: def isToeplitzMatrix(self, matrix): for i in range(1, len(matrix)): for j in range(1, len(matrix[0])): if matrix[i - 1][j - 1] != matrix[i][j]: return False return True if __name__ == "__main__": solution = Solution() assert solution.isToeplitzMatrix( [ [1, 2, 3, 4], [5, 1, 2, 3], [9, 5, 1, 2], ] ) assert not solution.isToeplitzMatrix( [ [1, 2], [2, 2], ] )
8497a5bddc903b2af7fc14238d63be18de7aad29
aravind-sundaresan/python-snippets
/Interview_Questions/Goldman_Sachs_palindrome.py
1,440
3.9375
4
#!/bin/python3 import math import os import random import re import sys # Complete the detector function below. def detector(tweets): for tweet in tweets: cardinality = 0 suffix = tweet[-3:] tweet = tweet[:-3] length = len(tweet) palindrome_count = 0 if length > 240 or length < 1: print(suffix + " Ignore") return if tweet.isalnum() is False: print(suffix + " Ignore") return for i in range(3, length+1): for j in range(0, length-i+1): if palindrome_check(tweet[j:j+i]) is True: palindrome_count += 1 cardinality += len(tweet[j:j+i]) if palindrome_count >= 2: if cardinality in range(1, 11): print(suffix + " Possible") elif cardinality in range(11, 41): print(suffix + " Probable") elif cardinality in range(41, 151): print(suffix + " Escalate") else: print(suffix + " Ignore") else: print(suffix + " Ignore") return def palindrome_check(substring): return (substring == substring[::-1]) if __name__ == '__main__': tweets_count = int(input().strip()) tweets = [] for _ in range(tweets_count): tweets_item = input() tweets.append(tweets_item) detector(tweets)
d0af27f195c5445a729ae353470db9b36b8b2367
jacksonyoudi/python-note
/notebook/3-tier_architecture/python/object13.py
1,227
3.625
4
#!/usr/bin/env python # coding: utf8 class Employee(object): def __init__(self, name, job=None, pay=0): self._name = name self._job = job self._pay = pay def giveRaise(self, percent): self._pay = int(self._pay * (1 + percent)) def __str__(self): return '[Employee:%s,%s,%s]' % (self._name, self._job, self._pay) class Manager(Employee): def __init__(self, name, pay): Employee.__init__(self, name, 'mgr', pay) def giveRaise(self, percent, bonus=.10): Employee.giveRaise(self, percent + bonus) class Department(object): def __init__(self, *args): self.members = list(args) def addMember(self, person): self.members.append(person) def showAll(self): for person in self.members: print person def giveRaise(self, percent): for person in self.members: person.giveRaise(percent) if __name__ == '__main__': a = Employee("xiaoli", "sw_engince", 10000) b = Employee("xiaowang", "hw_engince", 12000) c = Manager("xiaozhang", 8000) d = Department(a, b, c) d.showAll() d.giveRaise(0.1) d.showAll()
1affb86447c912cf3edf945a5a6ce58745b7e1b3
JJUMPING/study_cs
/intro.py
7,681
4
4
# -*- coding: utf-8 -*- """ Spyder Editor This is a temporary script file. """ a=3-2 type(a) print('jumping',a) b='23' bint=int(b) print(b*3) #%% def fc(C): f=1.8*C+32 print(str(f) + 'F') return str(f) + 'F' c2f=fc(35) print(c2f) #%% calculate the third side of a triangle #to be fixed import math def hypotenuse(a,b): hypo=math.sqrt(math.pow(a,2)+math.pow(b,2)) return 'hypo =' + str(hypo) c=hypotenuse(3,4) #%% #transfer g to kg def g2kg(g): return str(g/1000) + 'kg' print(g2kg(2000)) #calculate the third side of a triangle def Pythagorean_theorem(a,b): return 'the third side of a triangle is '+ str((a**2+b**2)**0.5) print(Pythagorean_theorem(3,4)) PI=3.1415926 a=PI b=4 str='the third side of a triangle is {}'.format((a**2+b**2)**0.5) print(str); print('{1},{1}'.format(4,3))#index #%% bool operator T= 1==1.0 F= 1 is 1.0 True and True True or False #bool value is true/false bool(0) #False bool([]) #False bool('') #False bool(False) #False bool(None) #False 1<2 and 3<4 1<2<3 2>1.5>1#true :not judging from front by step 1<2>1.5#true :not judging from end by step not False not None#true None and 0#None and 0 'M' in 'Magic' #%% print(r'\\n\\n')#r'XXX' no escape char print('\\\n\\n\\') print(''' ...abc ...def''')#new line, ... is prompt str='abc' print(str) print(' *',' * *','* * *',' |',sep='\n') #define seperate #%% a=9/3 b=10/3 c=10//3# division #%%write down a message after filtered def text_create(name,msg): folder='/Users/jumping/Desktop/learn python/study_cs' full_path=folder+name+'.txt' file=open(full_path,'w') file.write(msg) file.close() print('done') def filter(word, censored_word= 'shit', changed_word='gold'): return word.replace(censored_word, changed_word) d=filter('programming is shit') def text_clean(name, msg): clean_msg=filter(msg) text_create(name,clean_msg) msg='programming is shit' text_clean('clean', msg) #%% for for i in range(1,10): for j in range(1,10): print('{} X {} = {}'.format(i, j, j*j)) if j==9: print('\n') #%% big or small guess game def roll_sum(count=3, points=[]): import random print('>> ROLL THE DICE <<') while count > 0:#'>' not supported between instances of 'list' and 'int'????? point=random.randrange(1,7) points.append(point) count = count-1 tot=sum(points) return tot g=roll_sum() #%% big or small guess game import random def roll_dice(count=3, points=None): print('<<<<< ROLL THE DICE! >>>>>') if points is None: points = [] while count > 0: point = random.randrange(1,7) points.append(point) count = count - 1 return points #g=roll_dice() def result(tot): if tot >10: return 'Big' else: return 'Small' def start_game(): print('>> START GAME <<') yourmoney=1000 while yourmoney>0: yourchoice=input('Big or Small\n') choices=['Big','Small'] if yourchoice in choices: bet=int(input('How much you wanna bet\n')) points=roll_dice() tot=sum(points) if result(tot) == yourchoice: # what if "is" instead of "==" identities are not same print('The points are {},You win!'.format(points)) print('You gain {}, Now you have {}'.format(bet, yourmoney + bet)) yourmoney=yourmoney + bet else: print('The points are {},You lose'.format(points)) print('You lose {}, Now you have {}'.format(bet, yourmoney - bet)) yourmoney=yourmoney - bet else: print('invalid guess') print('Continue Game') else: print('game over') start_game() #%% A=[1,2,3,4] A.insert(1,2) A[1:1]=[4] A[1]='apple' del A[0] #%% phoneNum='17812345678' search='345' print(search + ' is from ' +str(phoneNum.find(search))+' to '+str(phoneNum.find(search)+len(search))) #%% compound interest principleAmount=10000 rate=0.1 for i in range(1,10): principleAmount=principleAmount*(1+rate) print(f'you own {principleAmount} in year {i}') #%%list fruit=['apple', 'banana'] fruit.insert(0,'grape') print(fruit) fruit.remove('banana') print(fruit) fruit[0:0] = ['Orange'] print(fruit) #fruit=['apple', 'banana'] #fruit[0:1] = 'Oran'# 0:? doesn't matter if ?<len('Oran') #fruit=['apple', 'banana'] #fruit[0:3] = 'Oran' #cover all and extend fruit[0:0] = 'Orange'#insert to the first as separate str print(fruit) del fruit[0:5] print(fruit) fruit[0]='banana'#replace the first print(fruit) fruit[-1]='Orange' fruit.extend(['pear']) #%%dic NASDAQ_code = {'BIDU':'Baidu','SINA':'Sina'} NASDAQ_code['YOKU'] = 'Youku' print(NASDAQ_code) NASDAQ_code.update({'FB':'Facebook','TSLA':'Tesla'}) del NASDAQ_code['FB'] NASDAQ_code['TSLA'] #%%tuple letters = ('a','b','c','d','e','f','g') letters[0] #%% set a_set = {1,2,3,4,'6'} a_set.add(5) a_set.discard(5) #%% data_stracture trick num_list = [6,2,7,4,1,3,5] print(sorted(num_list)) sorted(num_list,reverse=True) for a,b in zip(num_list,str): print(b,'is',a) a = [] for i in range(1,11): a.append(i) b = [i for i in range(1,11)]#列表解析式 import time a = [] t0 = time.clock() for i in range(1,20000): a.append(i) print(time.clock() - t0, "seconds process time") t0 = time.clock() b = [i for i in range(1,20000)] print(time.clock() - t0, "seconds process time") a = [i**2 for i in range(1,10)] c = [j+1 for j in range(1,10)] k = [n for n in range(1,10) if n % 2 ==0] z = [letter.lower() for letter in 'ABCDEFGHIGKLMN'] #dic d = {i:i+1 for i in range(4)} g = {i:j for i,j in zip(range(1,6),'abcde')}#mapping one by one g = {i:j.upper() for i,j in zip(range(1,6),'abcde')} x = [1, 2, 3] y = [4, 5, 6] zipped = zip(x, y) list(zipped) letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']#获取元素索引 for num,letter in enumerate(letters): print(letter,'is',num + 1) #%%class class CocaCola: formula = ['caffeine','sugar','water','soda'] def drink(coke): # HERE print('Energy!') coke_for_China = CocaCola() coke_for_China.local_logo = '可口可乐' # print(coke_for_China.local_logo) # coke=CocaCola()#'CocaCola' object has no attribute 'local_logo' #print(coke.local_logo) cause error coke = CocaCola() coke.drink() coke = CocaCola coke.drink() == CocaCola.drink(coke) #%%class2 class CocaCola: formula = ['caffeine','sugar','water','soda'] caffeine=140 def __init__(self,logo_name): self.local_logo = logo_name def drink(coke): # HERE print('Energy!') coke=CocaCola('可口可乐') coke.caffeine=0# change the attr of the instance print(coke.caffeine) print(CocaCola.caffeine)#attr of the class unchanged #%% class CocaCola: formula = ['caffeine','sugar','water','soda'] caffeine=140 def __init__(self,logo_name): self.local_logo = logo_name def drink(coke): # HERE print('Energy!') class CaffeineFree(CocaCola): caffeine=0 coke_a=CaffeineFree('free')#??free coke_a.drink() #%% TEST class TestA: attr = 1 obj_a = TestA() TestA.attr = 42 print(obj_a.attr)#42 class TestB: attr = 1 obj_a = TestB() obj_b = TestB() obj_a.attr = 42 print(obj_b.attr)#class unchanged, obj_b unchanged #%% from bs4 import beautifulsoup4 soup = BeautifulSoup print(type(soup)) #%% #%% #%% #%%
446f52d457672ae9ef6536dceedade37605e59e3
gayathri1997/Python-Programming
/Strings/isAnagram.py
139
4.0625
4
string1 = 'abcdefg' string2 = 'gfedcba' if sorted(string1) == sorted(string2): print('anagram') else: print('not anagram')
e0bfc48f55be38e38c7c2396ef7a1fe194220653
dmunozbarras/Pr-ctica-5-python
/ej5-9.py
823
3.984375
4
# -*- coding: cp1252 -*- """DAVID MUÑOZ BARRAS - 1º DAW - PRACTICA 5 - EJERCICIO 9 Escriu un programa que et demani noms de persones i els seus números de telèfon. Per a terminar de escriure nombres i numeros s'ha de pulsar Intro quan et demani el nom. El programa termina escribint noms i números de telèfon. Nota: La llista en la que es guarden els noms i números de telèfon és [ [nom1, telef1], [nom2, telef2], [nom3, telef3], etc] """ nom=raw_input("Escribe un nombre ") telef=raw_input("Escriba un numero de telefono ") lista= [] guia=[] while nom <> "": lista.append(nom) lista.append(int(telef)) guia.append(lista) lista=[] nom=raw_input("Escribe otro nombre ") telef=raw_input("Escribe otro telefono ") print "Los nombres y telefonos son: " for i in guia: print (i)
e341a7d93fda1682d07d4226d396c120c334000e
981377660LMT/algorithm-study
/7_graph/环检测/1559. 二维网格图中探测环-并查集无向图环检测.py
1,808
3.78125
4
from typing import List # 你需要检查 grid 中是否存在 相同值 形成的环。 # 一个环是一条开始和结束于同一个格子的长度 大于等于 4 的路径 # 也可并查集(每次只并两个方向) class UnionFind: def __init__(self, n: int): self.n = n self.setCount = n self.parent = list(range(n)) self.size = [1] * n def findset(self, x: int) -> int: if self.parent[x] == x: return x self.parent[x] = self.findset(self.parent[x]) return self.parent[x] def unite(self, x: int, y: int): if self.size[x] < self.size[y]: x, y = y, x self.parent[y] = x self.size[x] += self.size[y] self.setCount -= 1 def findAndUnite(self, x: int, y: int) -> bool: parentX, parentY = self.findset(x), self.findset(y) if parentX != parentY: self.unite(parentX, parentY) return True return False class Solution: def containsCycle(self, grid: List[List[str]]) -> bool: m, n = len(grid), len(grid[0]) uf = UnionFind(m * n) for i in range(m): for j in range(n): if i > 0 and grid[i][j] == grid[i - 1][j]: if not uf.findAndUnite(i * n + j, (i - 1) * n + j): return True if j > 0 and grid[i][j] == grid[i][j - 1]: if not uf.findAndUnite(i * n + j, i * n + j - 1): return True return False print( Solution().containsCycle( grid=[ ["a", "a", "a", "a"], ["a", "b", "b", "a"], ["a", "b", "b", "a"], ["a", "a", "a", "a"], ] ) )
e20f449601c10ecc3b21a9c44a692512f6c61290
Amr-Dweikat/Rest-Soap-api-testing-robot-framework
/venv/Lib/site-packages/JsonToDict/convertJsonToDict.py
1,473
3.828125
4
import json class ConvertJsonToDict(object): def __init__(self): pass import json def convert_json_to_dictionary(self,json_string): ''' Convert from Json To Dictionary. ''' dictData = json.loads(json_string) return dictData def __str__(self): return "This is a function that converts json to dictionary." if __name__ == '__main__': json_string=''' { "SuperMarket": { "Fruit": [ { "Name": "Apple", "Manufactured":"USA", "price": 7.99 }, { "Name": "Banana", "Manufactured":"Japan", "price": 3.99 } ], "Drink": { "SoftDrink":{ "Cola": [ { "Color":"Red", "Price":15.00 }, { "Color":"Green", "Price":17.99 } ], "Coffee": { "Hot":[ { "Type":"Espresso", "Price":15.90 }, { "Type":"Cappuccino", "Price":10.90 } ], "Ice":[ { "Type":"Espresso", "Price":20.90 }, { "Type":"Cappuccino", "Price":15.90 } ] } } } } } ''' jsonString=ConvertJsonToDict() dataDict=jsonString.convert_json_to_dictionary(json_string) print(dataDict["SuperMarket"])
736475ae8596c8b6e8ce19a258dd1ca6868a5205
sinhasaroj/Python_programs
/SerializationandDeserialization/json_serialization.py
581
3.5625
4
import json d1 = {'a':100 , 'b':20} d1_json = json.dumps(d1) # dumps the dict object to a string loads does the vice versa print(d1_json) print( json.dumps(d1, indent=2)) d_json = ''' { "name":"John Clesse", "age":39, "height":4.5, "walksFunny":true, "sketches":[ { "title":"Dead Parrot", "costars":["Saroj Sinha"] }, { "title":"Ministry of silly walks", "costars":["Manoj Sinha","Smita Jha","Dorsey pathinate"] } ], "boring": null } ''' d = json.loads(d_json) print(d)
f2a818e9a21dbfd1a24c2e5f2f0aeed52bec701a
zhweiliu/learn_leetcode
/Top Interview Questions Easy Collection/Strings/Reverse Integer/solution.py
1,021
4.5
4
from typing import List ''' Given a signed 32-bit integer x, return x with its digits reversed. If reversing x causes the value to go outside the signed 32-bit integer range [-231, 231 - 1], then return 0. Assume the environment does not allow you to store 64-bit integers (signed or unsigned). Example 1: Input: x = 123 Output: 321 Example 2: Input: x = -123 Output: -321 Example 3: Input: x = 120 Output: 21 Example 4: Input: x = 0 Output: 0 ''' def reverse(x: int) -> int: singed = -1 if x < 0 else 1 rev = 0 based = 10 posi_bound = (2 ** 31 - 1) / based neg_bound = (-2 ** 31) / based while x != 0: pop = x % 10 if pop > 0 and singed < 0: pop -= 10 x = int(x / 10) if rev > posi_bound or (rev == posi_bound and pop > 7): return 0 if rev < neg_bound or (rev == neg_bound and pop < -8): return 0 rev = rev * 10 + pop return rev if __name__ == '__main__': x = -123 print(reverse(x))
419800d2294dc499a406721c1c0c0ca06e886253
SivaBackendDeveloper/Python-Assessments
/3.Loops/3qs.py
283
4.09375
4
#Program to equal operator and not equal 2.Operators def eane(a): while True: if a%2==0: # equal operator print(a," is even number") break elif a%2!=0: # not equal operator print(a,"is odd number") break eane(12)
4df908c5c1fd18b3cf46c84c850ded175acc7cf4
polynn970/challenges
/after17.py
635
3.734375
4
import re l = "Beautiful is beetter than ugly" matches = re.findall("Beautiful", l) print(matches) match = re.findall("beautiful", l, re.IGNORECASE) print(match) zen = """Although never is often better than *right* now. If the implementation is hard to explain, it's a bad idea. If the implementation is easy to explain, it may be a good idea. Namespaces are one honking great idea -- let's do more of those!""" m= re.findall("^If", zen, re.MULTILINE) print(m) string = "Two too." ma = re.findall("t[ow]o", string, re.IGNORECASE) print(ma) line = "123 hi 34 hello." man = re.findall("\d", line, re.IGNORECASE) print(man)
0a3c976891136245c8882e76b802253428e5f786
ramonvaleriano/python-
/Livros/Livro-Introdução à Programação-Python/Capitulo 5/Exemplos 5/Listagem5_6.py
206
3.75
4
# Program: Listagem5_6.py # Author: Ramon R. Valeriano # Description: # Developed: 28/03/2020 - 21:16 # Update: end = int(input("Enter with number: ")) number = 1 while number<=end: print(number) number+=1
eb49b6b6d663cabb2dae61bf260fde6bb06fd1d7
Taylor-Zapalac/School
/Fall2018/FutureBalance.py
304
4
4
curBalance = float(input("Enter current bank balance:")) interestRate = float(input("Enter interest rate:")) time = int(input("Enter the amount of time that passes:")) def calcMoney(value, interest, time): return value * (1 + interest) ** time print(calcMoney(curBalance, interestRate, time))
7c9344867c71938fe2fa4c14465e70252db12983
Umang070/Python_Programs
/string_list & dictionary manipulatioin.py
1,319
4.0625
4
#!/usr/bin/env python # coding: utf-8 # ### String Manipulation # In[1]: st = "umang" type(st) # In[2]: #how many methods and functions are associated with string class dir(st) # In[10]: ste = "umang " ste.strip() #both side ste.rstrip() #right side ste.startswith('u') ste.find("g",2) #find "g" start with 2 # In[59]: file_content_obj = open(r"C:\Users\UMANG PATEL\Desktop\Data Science\DS.txt") cnt = 0 # file_content = file_content_obj.read() #we read whole file in a single string including spaces and "\n" # file_content for content in file_content_obj: # cnt+=1 # if content.startswith("import"): if not 'pd' in content: print(content, end="") # print("There are {} lines in file".format(cnt)) # ### List & Dictionary Manipulation # In[77]: l1 = [1,20,3] l2 = [4,50,6] # print(l1+l2) # dir(l1) l2.extend([10,11])#insert element not list l2.append([1,2])#insesrt as a list l1.sort() # In[78]: friends = [ 'Joseph', 'Glenn', 'Sally' ] friends.sort() print(friends[0]) # In[1]: stuff = dict() # stuff['candy']=0 # print(stuff['candy']) #this gives errors # print(stuff.get('candy',-1)) #this gives o/p 1 stuff['one'] = 1 stuff['two'] = 2 for i,j in stuff.items(): #if not items then it print only key print(i,j) # In[ ]:
54ecd51699f3fd77c68e21b6258060416b7331ea
Lalcenat/python-challenge
/PyBank/main.py
3,278
3.890625
4
import os # Module for reading CSV files import csv month_list = [] profit_loss_list = [] csvpath = os.path.join('Resources', 'budget_data.csv') with open(csvpath, newline='') as csvfile: csvreader = csv.reader(csvfile, delimiter=',') csv_header = next(csvreader) for row in csvreader: # print(row) #loop through and count/add the number of months month_list.append(row[0]) profit_loss_list.append(int(row[1])) #print(profit_loss) month_total = len(month_list) profit_loss_total = sum(profit_loss_list) ##profit_loss_mean = profit_loss_total/month_total print("Financial Analysis") print("---------------------") #print(f"Total Months: {month_total}") #print(f"Total: ${profit_loss_total}") #averagech = profit_loss_total/month_total ##print(f"Average Change:{profit_loss_mean}") #print(max(profit_loss_list)) change_list = [] for i in range(len(profit_loss_list)-1): change_list.append(profit_loss_list[i+1]-profit_loss_list[i]) average_change = round(sum(change_list)/len(change_list),2) #totalmonth = ["Total Months:", "Total:"{month_total}") total= print(f"Total: ${profit_loss_total}") average = print(f"Average Change: ${average_change}") maxy = print(f"Greatest Increase in Profits: {month_list[change_list.index(max(change_list))+1]} (${max(change_list)})") minx = print(f"Greatest Decrease in Profits: {month_list[change_list.index(min(change_list))+1]} (${min(change_list)})") #results = [totalmonth,total,average,maxy,minx] #results = print(f"Total Months: $"{month_total}, "Average Change": round(average_change,2)} #print(f"Total: ${profit_loss_total}") #print(f"Average Change: ${round(average_change,2)}") #print(f"Greatest Increase in Profits: {month_list[change_list.index(max(change_list))+1]} (${max(change_list)})") #print(f"Greatest Decrease in Profits: {month_list[change_list.index(min(change_list))+1]} (${min(change_list)})") # Zip lists together #print(results) #cleaned_csv = zip(title, price, subscribers, reviews, review_percent, length) # Set variable for output file output_file = os.path.join("Resources","Pybank_LSA.txt") output_file.write("Financial Analysis") output_file.write("---------------------") output_file.close() with open(output_file, "w", newline="") as datafile: writer = csv.writer(datafile) # Write the header row writer.writerow(["Title", "Course Price", "Subscribers", "Reviews Left", "Percent of Reviews", "Length of Course"]) # Write in zipped rows writer.writerows(cleaned_csv) # Open the output file #with open(output_file, "w", newline="") as datafile: #writer = csv.writer(datafile) # Write the header row #writer.writerows(results) # writer.writerows(print(f"Total Months: {month_total}")) #writer.writerows(print(f"Total: ${profit_loss_total}")) #writer.writerows(print(f"Average Change: ${round(average_change,2)}")) #writer.writerows(print(f"Greatest Increase in Profits: {month_list[change_list.index(max(change_list))+1]} (${max(change_list)})")) #writer.writerows(print(f"Greatest Decrease in Profits: {month_list[change_list.index(min(change_list))+1]} (${min(change_list)})")) # Write in zipped rows # writer.writerows(cleaned_csv)
751cf75236891de8709d56d683f18aaa10c1177d
Maleriandro/sokoban
/deshacer.py
1,225
3.671875
4
from data_structures import Pila class Deshacer: '''Almacena historial de estados en forma de pila. Se puede agregar estados, sacar estados, comprobar si hay estados disponibles para deshacer, y vaciar el historial.''' def __init__(self): '''Inicializa historial de estados vacio''' self.acciones = Pila() def agregar_estado(self, estado): '''Agrega el estado del nivel al historial de acciones. Si el estado enviado es el mismo que el anterior, no hace nada''' if self.acciones.esta_vacia() or not self.acciones.ver_tope() == estado: self.acciones.apilar(estado) def deshacer_movimiento(self): '''pre: El historial de movimientos debe tener por lo menos 1 elemento Devuelve el ultimo estado almacenado.''' if self.acciones.esta_vacia(): raise ValueError('No Existe ningun valor que deshacer') return self.acciones.desapilar() def se_puede_deshacer(self): '''Devuelve si se se puede deshacer al estado anterior.''' return not self.acciones.esta_vacia() def vaciar(self): '''Vacia el historial de estados''' self.acciones = Pila()
7473eb8a9ea9d4675bd2fbc33a82cf3364a44cb5
Axdliu/Hacker_ank
/Algorithms/Strings/Pangrams.py
227
3.578125
4
# -*- coding: utf-8 -*- """ Created on Fri Mar 03 22:34:22 2017 @author: User """ s = set(list(reduce(lambda x,y:x+y, raw_input().strip().split()).lower())) if len(s) == 26: print 'pangram' else: print 'not pangram'
d0dc1af5abd1bd35d60e5c309cc90ce0f9481e19
bibongbong/pythonCookBook
/src/2.4.StrSearchAndMatch.py
1,314
4.0625
4
# 字面字符串: str.find(), str.endswith(), str.startswith() # 复杂的匹配: 正则表达式和re模块 text1 = '11/27/2012' text2 = 'Nov 27, 2012' import re # \d+ 表示多个数字,\d+/表示多个数字加上/ # print yes if re.match(r'\d+/\d+/\d+', text1): print('yes') else: print('no') # 如果需要用同一个模式去匹配多个字符串,需要将模式字符串预编译为一个模式对象 # 同时利用括号去捕获分组,第一个括号group(1),第二个group(2),第三个括号group(3),第0个group(0)表示整个匹配到的 # print no datePat = re.compile('(\d+)/(\d+)/(\d+)') if datePat.match(text2): print('yes') else: print('no') # 捕获分组可以使后面的处理更加方便 m = datePat.match('11/27/2018') print(m.group(0)) # 11/27/2018 print(m.group(1)) # 11 print(m.group(2)) # 27 print(m.group(3)) # 2018 print(m.groups()) # ('11', '27', '2018') month, day, year = m.groups() # match() 只能一次寻找匹配,如果想寻找多次匹配可以用findall() text3 = 'Today is 11/27/2012. PyCon starts 3/13/2013.' for month, day, year in datePat.findall(text3): print('{}-{}-{}'.format(year,month,day)) # 2012-11-27 # 2013-3-13 for m in datePat.finditer(text3): print(m.groups())
8f7b0569fac8719b50951e5f29ef78d65a39c2a9
ER-Ameya/Chat-appication
/server.py
761
3.625
4
import socket s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) #socket.AF_INET is used to load family address and socket.stream is use to stream the data host = socket.gethostname() #to get host name port = 4321 #To define port s.bind((host,port)) s.listen() print("Waiting for connection...") while True: #for connecting to server cs,addr = s.accept() #to accept the connection from the client as we have only one client hence at print we use addr[0] print("Connecting received from",addr[0]) msg = "Thankyou for connecting" cs.send(msg.encode("UTF")) #to encode msg Universal transfer function while True: #to reply to connection msg2 = cs.recv(1024) print(msg2.decode("UTF-8")) msg1 = input() cs.send(msg1.encode("UTF-8"))
5af9c4c9b5d62b7349f1994751ed488489e5353d
sumanthneerumalla/Leetcode
/TwoSum.py
788
3.5625
4
#https://leetcode.com/problems/two-sum/ class Solution: def twoSum(self, nums, target): """ :type nums: List[int] :type target: int :rtype: List[int] """ locations = {} for i in range(len(nums)): num = nums[i] match = target - num if locations.get(num) == None : # if the latest item isn't in the hashmap we add it locations[num] = i # now all unique numbers should be in the locations # then check to see if the match is in there if match in locations: # if the target number is in the hashmap, then it will return a number if locations[match] != i: #dont choose the same index twice return [i,locations[match]]
aef1bd3647a266a8cbfb8904440d05807ffb9b5d
sympy/sympy
/examples/intermediate/differential_equations.py
583
4.03125
4
#!/usr/bin/env python """Differential equations example Demonstrates solving 1st and 2nd degree linear ordinary differential equations. """ from sympy import dsolve, Eq, Function, sin, Symbol def main(): x = Symbol("x") f = Function("f") eq = Eq(f(x).diff(x), f(x)) print("Solution for ", eq, " : ", dsolve(eq, f(x))) eq = Eq(f(x).diff(x, 2), -f(x)) print("Solution for ", eq, " : ", dsolve(eq, f(x))) eq = Eq(x**2*f(x).diff(x), -3*x*f(x) + sin(x)/x) print("Solution for ", eq, " : ", dsolve(eq, f(x))) if __name__ == "__main__": main()
1e7523050bb0c08143f74c6f5311b0db5e3c5f36
Hardcore30005/pythonintask
/PMIa/2014/PAVLINOV_G_P/Задание 6.py
790
3.890625
4
# 6. 14. # , 2014 , . # # 4.06.2016 import random mascots = ['','',' '] progSel = mascots[random.randint(0,2)] userSel = input(" . ? ") if userSel==progSel: print("! " + userSel) else: print("! " + userSel) input()
74dddb4286f56524bb8694fe11f35e44de52fb14
minhuan520/MH
/Day1/test07_yh.py
432
3.71875
4
import random root = random.randint(0, 2) a = '恭喜你,你赢了' b = '不好意思,你输了' player = int(input('请输入 0 剪刀 1石头 2布:')) while player == root: print('打平了,决战到天亮') player = int(input('请输入 0 剪刀 1石头 2布:')) else: if (player == 0 and root == 1) or (player == 1 and root == 2) or (player == 2 and root == 0): print(b) else: print(a)
288f23c256702dc86dfdbba940268cc6e7d326ac
alimaan2935/LOLO-Game
/highscores.py
4,288
3.984375
4
import json class HighScoreManager: """A HighScoreManager manages the recording of highscores achieved to a highscore file. """ _data = None def __init__(self, file="highscores.json", gamemode='regular', auto_save=True, top_scores=10): """Constructs a HighScoreManager using the provided json file. Parameters: file (str): The name of the json file which stores the highscore information. gamemode (str): The name of the gamemode to load highscores from. auto_save (bool): If true the manager saves the scores automatically when a record is added. top_scores (int): The number of high scores to store to file. """ self._file = file self._top_scores = top_scores self._auto_save = auto_save self._gamemode = gamemode if self._auto_save: self.load() def _load_json(self): """Loads the highscore json file.""" try: with open(self._file) as file: try: data = json.load(file) except json.JSONDecodeError: # Failed to decode the json file # Default to empty leaderboard data = {} except IOError: # Could not locate the json file # Default to empty leaderboard data = {} if self._gamemode not in data: data[self._gamemode] = [] return data def load(self): """Loads the highscore information from the highscores file into the manager. """ data = self._load_json() self._data = data[self._gamemode] def save(self): """Saves the information added to the highscore manager to the file.""" data = self._load_json() with open(self._file, "w") as file: data[self._gamemode] = self._data file.write(json.dumps(data, indent=2)) def record(self, score, grid, name=None): """Makes a record of a gameplay based on the score, final grid and name. Parameters: score (int): The top score of the gameplay. grid (LoloGrid): A grid to be serialized into the file. name (str): The name of the player who played the recorded game. """ scores = self.get_scores() data = {"score": score, "name": str(name), "grid": grid.serialize()} if len(scores) < self._top_scores: self._data.append(data) elif score > min(scores): self.replace_record(min(scores), data) if self._auto_save: self.save() def replace_record(self, old_score, new_data): """Replaces a record based by finding the old score Parameters: old_score (int): The score of the record to replace. new_data (dict<str, *>): The record to replace the old record with. """ min_score_index = self.get_scores().index(old_score) self._data[min_score_index] = new_data def __iter__(self): """Loop through each record in the highscores file. Yield: record (dict<str, int>): The record being yielded """ for record in self.get_sorted_data(): yield record def __len__(self): return len(self.get_data()) def get_data(self): """(list<dict<str, *>>) Returns a list of all the records in the file""" return self._data def get_sorted_data(self): """(list<dict<str, *>>) Returns a sorted list of records in the file.""" return sorted(self._data, key=lambda x: -x["score"]) def get_scores(self): """(list<int>) Returns a list of all the scores in the file.""" return [player['score'] for player in self._data] def get_names(self): """(list<str>) Returns a list of all the scores in the file.""" return [player['name'] for player in self._data] def get_grids(self): """(list<list<list<tuple<int, int>>>>) Returns a list of all the scores in the file.""" return [player['grid'] for player in self._data]
6143a448b47af4db2b76ca66fcdeee3d03842c54
Larissa-D-Gomes/CursoPython
/introducao/exercicio024.py
365
4.15625
4
""" EXERCÍCIO 024: Verificando as Primeiras Letras de um Texto Crie um programa que leia o nome de uma cidade e diga se ela começa ou não com o nome "SANTO". """ def main(): cidade = input('Digite o nome da cidade: ') print("O nome da cidade comeca com 'Santo'?",cidade.split(" ", 1)[0].upper() == 'SANTO') if __name__ == '__main__': main()
7429ef6a8c2382dfbcc832d898502c064bebc76a
hateka/python_training
/python_training/1-6.py
176
3.703125
4
import sys param = sys.argv if param[1] < param[2] and param[1] < param[3]: print 'Yes' elif param[1] < param[2] and param[2] < param[3]: print 'Yes' else: print 'No'
96704c270d3948c5ece24ef0da787397c2633d67
kavyababuk/NewPython
/Languagefundamentals/age.py
145
4
4
#create new variable age25,name=ajay #print ajay is 25 years old age=input("enter age") name=input("ener name") print(name,"is",age,"years old")
ac3e4d4c735c7759581b578aa4d905b142836f1c
miha6644/SecretNumberGame
/main.py
139
3.75
4
secret = "7" guess = input("What's the secret number between 1-15? ") if guess == secret: print("Correct!") else: print("Wrong!")
a154800314683ca377dbb5f85c1cc9144a1852ad
GolamRabbani20/PYTHON-A2Z
/PYTHON_TIPS&TRICKS/Loop.py
177
3.78125
4
odd_square = [] for k in range(50): if k % 2 == 1: odd_square.append(k**2) print(odd_square) odd_squares = [k**2 for k in range(51) if k % 2 == 1] print(odd_squares)
3623ff2f89f6e93d234e7ba8be62434c23f161d3
nmasamba/learningPython
/25_lambda_expressions.py
1,000
4.40625
4
""" Author: Nyasha Masamba Based on the lessons from Codecademy at https://www.codecademy.com/learn/python This Python program is introduces lambda expressions in Python. A lambda expression is simply an anonymous function. In Python, anonymous function is a function that is defined without a name. While normal functions are defined using the def keyword, in Python anonymous functions are defined using the lambda keyword. Hence, anonymous functions are also called lambda functions. They are typically used in situations where encapsulated behaviour is required but without the need to write a named function as the anonymous function won't be called or re-used again. Create a list, squares, that consists of the squares of the numbers 1 to 10. A list comprehension could be useful here! Use filter() and a lambda expression to print out only the squares that are between 30 and 70 (inclusive). """ squares = [x**2 for x in range(1,11)] print filter(lambda x: x >= 30 and x <= 70, squares)
9a6191f1dfbbf79c9b28a1a3922a3b7ed6a0ff2e
qeetw/design_pattern
/signleton/app.py
659
3.734375
4
from singletion import Singleton def main(): first_instance = Singleton() second_instance = Singleton() if first_instance is second_instance: print('Same Instance') else: print('Difference Instance') print('first_data:', first_instance.get_data()) print('second_data:', second_instance.get_data()) first_instance.set_data(10) print('first_data:', first_instance.get_data()) print('second_data:', second_instance.get_data()) second_instance.set_data(15) print('first_data:', first_instance.get_data()) print('second_data:', second_instance.get_data()) if __name__ == '__main__': main()
83ce18fd76ed28ef27475fd0f26be647d0d95d80
andydevs/tketris
/tketris/game/mino.py
3,414
3.78125
4
""" Tketris Tetris using tkinter Author: Anshul Kharbanda Created: 10 - 11 - 2018 """ import numpy as np from random import choice as random_choice from ..numpy_algorithms import transform_tileset """ The tetris mino classes. In tketris, Minos are represented as objects containing the basic set of tiles comprising the mino shape, as well as the current position and orientation of the Mino. Mino objects have a method which automatically calculates the tiles to draw when rendering. """ class Mino: """ Mino abstraction. This class contains the class method 'new_mino' which generates a new subclass for a particular mino type given the type's information, used below. This method also appends the new mino type to the minos array, which is used in the 'random' method. The 'random' method returns a random mino at the given position and orientation (default at the top middle at orientation 0). """ DEBUG = False # The minos array. 'random' picks a mino type from this array minos = [] @classmethod def new_type(cls, name, color, shape): """ Creates a new mino type and saves it to the minos array. :param name: the name of the new mino type :param color: the tile color of the mino type :param shape: the shape tileset of the mino type (centered at 0,0) """ mtype = type(name, (Mino,), { 'color':color, 'shape':np.array(shape, dtype=int) }) cls.minos.append(mtype) return mtype @classmethod def random(cls, position=(0, 4), orientation=0, debug=False): """ Returns a random new mino at the given position and orientation :param position: initial position of new mino (default to top center) :param orientation: orientation of new mino (default to top center) :return: random new mino at position and orientation """ return random_choice(cls.minos)(position, orientation, debug) def __init__(self, position=(0, 4), orientation=0, debug=False): """ Initializes new Mino at given position and orientation :param position: initial position of new mino (default to top center) :param orientation: orientation of new mino (default to top center) """ self.position = np.array(position) self.orientation = orientation self.DEBUG = debug @property def tiles(self): """ The absolute tile positions of the mino """ # Transform tileset return transform_tileset( self.position, self.orientation, self.shape, debug=self.DEBUG) # Mino types IMino = Mino.new_type('IMino', '#00bbff', [ [-1, 0], [ 0, 0], [ 1, 0], [ 2, 0] ]) JMino = Mino.new_type('JMino', '#3300ff', [ [-1, 0], [ 0, 0], [ 1, 0], [ 1, -1] ]) LMino = Mino.new_type('LMino', '#ff6600', [ [-1, 0], [ 0, 0], [ 1, 0], [ 1, 1] ]) TMino = Mino.new_type('TMino', '#ff00ff', [ [0, -1], [0, 0], [0, 1], [1, 0] ]) SMino = Mino.new_type('SMino', '#ff0000', [ [1, -1], [1, 0], [0, 0], [0, 1] ]) ZMino = Mino.new_type('ZMino', '#00aa00', [ [0, -1], [0, 0], [1, 0], [1, 1] ]) OMino = Mino.new_type('OMino', '#999900', [ [0, -1], [0, 0], [1, -1], [1, 0] ])
e7b355c55713274ab2a8cfc6b848c5357a0e70f1
nioanna/python-helper-functions
/string/string.py
928
3.625
4
# Funkcija izdvaja ceo broj iz stringa from _typeshed import ReadableBuffer def izdvoji_int(a_string): numbers = [] for word in a_string.split(): if word.isdigit(): numbers.append(int(word)) return numbers # Ova funkcija iz datog stringa izdvaja cele brojeve def izdvoji_ceo_broj(test_string): res = [int(i) for i in test_string.split() if i.isdigit()] return res # Funkcija vraća ceo broj izdvojen iz stringa def ceo_broj(string1): return int(ReadableBuffer.search(r'\d+', string1).group()) # Funkcija obrće string def obrni_string(string): if len(string) == 0: return string else: return obrni_string(string[1:]) + string[0] # Funkcija vraća string u obrnutom redosledu def reverse_string(x): return x[::-1] # Python kod za obrtanje stringa koristeći petlju def reverse(s): str = "" for i in s: str = i + str return str
bf9286fb55b2a56883f0d48090eae880cf6541c2
darrencheng0817/AlgorithmLearning
/Python/leetcode/WiggleSortIi.py
732
4.03125
4
''' Created on 1.12.2016 @author: Darren ''' ''' Given an unsorted array nums, reorder it such that nums[0] < nums[1] > nums[2] < nums[3].... Example: (1) Given nums = [1, 5, 1, 1, 6, 4], one possible answer is [1, 4, 1, 5, 1, 6]. (2) Given nums = [1, 3, 2, 2, 3, 1], one possible answer is [2, 3, 1, 3, 1, 2]. Note: You may assume all input has valid answer. Follow Up: Can you do it in O(n) time and/or in-place with O(1) extra space? ''' class Solution(object): def wiggleSort(self, nums): nums.sort() half = len(nums[::2]) nums[::2], nums[1::2] = nums[:half][::-1], nums[half:][::-1] nums=[1, 2, 3, 4, 5, 6] print(nums[::2])
d991feb2e8c26ced330674dca2a27c80ee3972a5
Eroica-cpp/LeetCode
/021-Merge-Two-Sorted-Lists/solution01.py
1,367
4.0625
4
#!/usr/bin/python # ============================================================================== # Author: Tao Li (taoli@ucsd.edu) # Date: May 3, 2015 # Question: 021-Merge-Two-Sorted-Lists # Link: https://leetcode.com/problems/merge-two-sorted-lists/ # ============================================================================== # Merge two sorted linked lists and return it as a new list. The new list should # be made by splicing together the nodes of the first two lists. # ============================================================================== # Method: Two pointers # Time Complexity: O(n) # Space Complexity: O(1) # ============================================================================== # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} l1 # @param {ListNode} l2 # @return {ListNode} def mergeTwoLists(self, l1, l2): head = ListNode(0) ptr = head while l1 and l2: if l1.val <= l2.val: ptr.next = l1 l1 = l1.next else: ptr.next = l2 l2 = l2.next ptr = ptr.next if l1 is None: ptr.next = l2 else: ptr.next = l1 return head.next
4ee00049fd00a80a6e6553196166c12a89e88974
mbk282/PycharmProjects
/Homework/silvan_hw2.py
5,824
4.4375
4
#Assignment 2, Basic Probability Programming, November 2016 #------------------------------------------------------------ #1. Ask user for path to file and read file into text memory #take user input concerning the path to the file print("Hello, welcome to the wonderful world of counting words. Please tell me exactly where I can find the text file you would like to have words counted in.") path_to_text=input(">>>") #open the file for reading initial_text=open(path_to_text, 'r') #prepare file by making it into list of strings (list of the individual words) text_natural=[] #empty list in which we write the initial_text for line in initial_text: #write each line in text file as element of a list zeile = line.strip() text_natural.append(zeile) text_natural=str(text_natural).lower() #convert list to string so it becomes splitable delimiter = ' ' #define space as delimiter text_individual_words = text_natural.split(delimiter) #text_individual_words is now a list of strings, ready to count #2. counting words #use Counter module to count the words in text_individual_words so the data is ready for interact with the user in point 3 import collections counter=collections.Counter(text_individual_words) #the following defines a function that gets the least n elements from counter, it will be used below when interacting with the user from operator import itemgetter import heapq import collections def least_common(array, to_find=None): counter = collections.Counter(array) if to_find is None: return sorted(counter.items(), key=itemgetter(1), reverse=False) return heapq.nsmallest(to_find, counter.items(), key=itemgetter(1)) #3. Ask user what she wants to do. The options are: getting most/least frequent words; get count of specific word; exit. print("What would you like to know about this text. I have four wonderful options for you:") print("1. Show the most frequent words.") print("2. Show the least frequent words.") print("3. Obtain the number of times a word appears in the text.") print("4. Exit this little interaction.") print("Please indicate your preference by writing 1,2,3 or 4:") initial_decision=input(">>>") initial_decision=int(initial_decision) #process input to make sure it has the right type while initial_decision!=4: #if user's input equals 4 program stops running, otherwise it goes to the corresponding option if initial_decision==1: print("Up to how many words do you want to know this?") decision_one=input('>>>') print('Most frequent:') for string, count in counter.most_common(int(decision_one)): #this function was already built-in print('\'{}\' {:>7}'.format(string, count)) print("What else would you like to know about this text. The options haven't changed:") #going back to 4 options again print("1. Show the most frequent words.") print("2. Show the least frequent words.") print("3. Obtain the number of times a word appears in the text.") print("4. Exit this little interaction.") print("Please indicate your preference by writing 1,2,3 or 4:") initial_decision=input('>>>') initial_decision=int(initial_decision) if initial_decision==2: print("Up to how many words do you want to know this?") decision_two=input('>>>') decision_two=int(decision_two) print('Least frequent:') for letter, count in least_common(counter, decision_two): #for argument1(=database counter) and argument2(=length of list) look for the n elements with the least frequency print('\'{}\' {:>7}'.format(letter, count)) print("What else would you like to know about this text. The options haven't changed:") #going back to 4 options again print("1. Show the most frequent words.") print("2. Show the least frequent words.") print("3. Obtain the number of times a word appears in the text.") print("4. Exit this little interaction.") print("Please indicate your preference by writing 1,2,3 or 4:") initial_decision=input('>>>') initial_decision=int(initial_decision) if initial_decision==3: print("Which word would you like to know about?") decision_three=input('>>>') keyword=str(decision_three).lower() if keyword in text_individual_words: print('\'{}\' {}'.format(keyword, counter[keyword])) else: print("Sorry, this word does not appear in the text.") print("What else would you like to know about this text. The options haven't changed:") #going back to 4 options again print("1. Show the most frequent words.") print("2. Show the least frequent words.") print("3. Obtain the number of times a word appears in the text.") print("4. Exit this little interaction.") print("Please indicate your preference by writing 1,2,3 or 4:") print(">>>") initial_decision=input('>>>') initial_decision=int(initial_decision) if initial_decision!= (1 or 2 or 3 or 4): #handling the case where input is invalid print("Scusi, I do not understand this. Please choose again. The options haven't changed:") #going back to 4 options again print("1. Show the most frequent words.") print("2. Show the least frequent words.") print("3. Obtain the number of times a word appears in the text.") print("4. Exit this little interaction.") print("Please indicate your preference by writing 1,2,3 or 4:") print(">>>") initial_decision=input('>>>') initial_decision=int(initial_decision) print("It has been delightful to interact with you! Can't wait for you to use this program again soon! Doei!") #output in case user wishes to exit
d9510f7b2ea49c13697bbcfdafe5706f16bfd2bc
Shargarth/Python_exercises
/Tahtikuvio.py
103
3.671875
4
j = 1 for i in range(0,7): for i in range(0,j): print("*", end="") print("") j += 1
fb94008b187f52ec249e92030202e3ef91639778
riterdba/magicbox
/3.py
515
4.15625
4
#!/usr/bin/python3 # Простейшие арифметические операции. def arithmetic(x,y,z): if z=='+': return x+y elif z=='-': return x-y elif z=='*': return x*y elif z=='/': return x/y else: return print('Неизвестная операция') arif=arithmetic a=int(input('Введите первое число')) b=int(input('Введите второе число')) c=input('Введите оперцию') print(arif(a,b,c))
830813767f150596bc4444e1b7c7bfba4326520d
BetterJiang/LeetCodeQuestions
/MaxCrossingSum.py
1,617
3.828125
4
# -*- coding: utf-8 -*- """ Created on Fri Nov 23 21:18:50 2018 @author : HaiyanJiang @email : jianghaiyan.cn@gmail.com """ # -*- coding: utf-8 -*- """ Created on Fri Nov 23 20:54:29 2018 @author: HaiyanJiang @email: jianghaiyan.cn@gmail.com """ # A Divide and Conquer based program for maximum subarray sum problem # Find the maximum possible sum in arr[] such that arr[m] is part of it def maxCrossingSum(arr, s, m, h): # Include elements on left of mid [s, h]. sm = 0 left_sum = -10000 for i in range(m, s-1, -1): sm = sm + arr[i] if (sm > left_sum): left_sum = sm # Include elements on right of mid sm = 0 right_sum = -1000 for i in range(m + 1, h + 1): sm = sm + arr[i] if (sm > right_sum): right_sum = sm # Return sum of elements on left and right of mid return left_sum + right_sum def maxSubArraySum(arr, s, h): # Returns sum of maxium sum subarray in aa[l..h] # Base Case: Only one element if s == h: return arr[s] # Find middle point m = (s + h) // 2 # Return maximum of following three possible cases # a) Maximum subarray sum in left half (both begins and ends in the left) # b) Maximum subarray sum in right half # c) Maximum subarray sum such that the subarray crosses the midpoint return max(maxSubArraySum(arr, s, m), maxSubArraySum(arr, m+1, h), maxCrossingSum(arr, s, m, h)) # Driver Code arr = [2, 3, -4, 5, 7] n = len(arr) max_sum = maxSubArraySum(arr, 0, n-1) print("Maximum contiguous sum is ", max_sum) # This code is contributed by Nikita Tiwari.
50c357e9201f6f686191696395b12f4b765ffcb3
rakesh-chinta/calculator-app
/calculator.py
764
4.125
4
def add(x, y): return x + y def subtract(x, y): return x - y def multiply(x,y): return x * y def divide(x, y): return x / y print("1 for addition,2 for subtraction,3 for multiplication,4 for division") choice=input("enter your choice(1/2/3/4): ") num1=int(input("enter the first number: ")) num2=int(input("enter the second number: ")) if choice == '1' : print(num1,"+",num2,"=", add(num1,num2)) elif choice == '2' : print(num1,"-",num2,"=",subtract(num1,num2)) elif choice == '3' : print(num1,"*",num2,"=",multiply(num1,num2)) elif choice == '4' : print(num1,"/",num2,"=",divide(num1,num2)) else: print("invalid input")
143b7c0660b7f2450644e380a5184ebfcf20cfb8
kien6034/CSFoundation
/1_Array/8_zero_matrix/main.py
1,133
3.75
4
#write an algorithm such that if an element in an MxN matrix is zero, its entire row and column are set to zero import numpy as np M = 8 N = 6 def find_zero(mtx): row = False col = False for i in range(0, M): for j in range(0, N): if mtx[i,j] == 0: if i == 0: row = True if j == 0: col = True mtx[0, j] = 0 mtx[i, 0] = 0 return row, col def zerorize_col(mtx, j): for i in range(1, M): mtx[i, j] = 0 def zerorize_row(mtx, i): for j in range(1, N): mtx[i, j] = 0 def zerorize(mtx, row, col): for j in range(1, N): if mtx[0, j] == 0: zerorize_col(mtx, j) #second row for i in range(1, M): if mtx[i, 0] == 0: zerorize_row(mtx, i) if row: zerorize_row(mtx, 0) if col: zerorize_col(mtx,0) mtx = np.where(np.random.rand(M,N) > 0.2, 4 ,0) print(mtx) row, col = find_zero(mtx) print("=====================") print(mtx) zerorize(mtx, row, col) print("=====================") print(mtx)
470c0c3879cfc06c82780441ab64777d6139b471
liyaSileshi/CS-1.2-Intro-Data-Structures
/Code/sample.py
1,226
4.0625
4
import sys from word_count import hist_dictionary import random from tokenize_word import tokens def sample_by_frequency(histogram): """ Input: dictionary histogram of a text file Return: a weighed random word """ tokens = sum(histogram.values()) rand = random.randrange(tokens) for key, value in histogram.items(): if rand < value: return key rand -= value def test(): """ A test for sample_by_frequency histogram """ list_of_output = [] words_list = tokens(sys.argv[1]) print(words_list) #change the text file to a dictionary histogram histogram = hist_dictionary(words_list) #takes a random weighed sample from the histogram 1000x #appends it to a list (list_of_output) for _ in range(1000): list_of_output.append(sample_by_frequency(histogram)) #changes the list_of_output list to a dictionary histogram #prints out the result final = hist_dictionary(list_of_output) for key in final.keys(): print(f"{key}: {final[key]}") if __name__ == '__main__': dictionary_histogram = hist_dictionary(sys.argv[1]) sample = sample_by_frequency(dictionary_histogram) # test()
55c0bd78c570c434ba02fec397da17cbcd915b9f
tmz22/Financial_and_Poll_analysis
/PyPoll/main.pypoll.py
1,734
3.734375
4
import os import csv #Variables candidates = [] number_votes = [] percent_votes = [] total_votes = 0 #Path csvpath=os.path.join("Resources", "election_data.csv") #Csv reader with open(election_data,"") as csvfile: csvreader = csv.reader(csvfile, delimiter = ",") csv_header = next(csvreader) #for row in csvreader: #vote-counter total_votes += 1 #Testing code if row[2] not in candidates: candidates.append(row[2]) index = candidates.index(row[2]) num_votes.append(1) else: index = candidates.index(row[2]) num_votes[index] += 1 #List of percent votes for votes in num_votes: percent_votes.append(percentage) percentage = (votes/total_votes) * 100 for row in csvreader: candidate=row[2] if candidate in candidates: vote_counter[candidate]+=1 else: candidates.append(candidate) vote_counter[candidate]=1 total_votes+=1 #Testing code for i in range(len(candidates)): vote_share = round((vote_counter[candidates[i]]/total_votes)*100, 3) vote_percentage.append(vote_share) if vote_counter[candidates[i]] > max_vote: max_vote = vote_counter[candidates[i]] winner = candidates[i] #Winner winner = max(number_votes) winner_candidate = candidates[index] #Results print("Election Results") print("--------------------------") print(f"Total Votes: {str(total_votes)}") print("--------------------------") print(f"{candidates[i]}: {str(percent_votes[i])} ({str(number_votes[i])})") print(f"Winner: {winning_candidate}")
cb6350e4c192dd5fcb9030dc5d70cb51f2e72088
divyamvpandian/MyLearning
/Practice/mandn.py
524
3.625
4
import math def main(): t = int(input()) while(t>0): strin = input() m = strin.split(" ")[0] n = strin.split(" ")[1] result=addmandn(int(m),int(n)) print(result) t-=1 def countDigit(n): return math.floor(math.log(n, 10)+1) def addmandn(m,n): x=m+n if(countDigit(x)==countDigit(n)): return n else: return x return 0 # # def countSquares(b): # b = b-2 # b= b/2 # return b *(b-1) if __name__ == '__main__': main()
65f3d58264e3991d7f912eef63bebfffa8c984c4
jaysiyaram/Geeks_for_geeks-Placement_track_solutions
/max_absolute_diff.py
1,123
3.5625
4
#code import sys def calc_sum(arr): max_val = arr[0] tmpMax = [] curr_val = 0 for value in arr: curr_val = max(value, curr_val + value) if curr_val > max_val: max_val = curr_val tmpMax.append(max_val) return tmpMax def calc_max_absolute_diff(arr, arr_len): import pdb; pdb.set_trace() leftMax = calc_sum(arr) rightMax = calc_sum(arr[::-1]) rightMax = rightMax[::-1] tmpArr = [-1*value for value in arr] leftMin = calc_sum(tmpArr) rightMin = calc_sum(tmpArr[::-1]) leftMin = [-1*value for value in leftMin] rightMin = [-1*value for value in rightMin] rightMin = rightMin[::-1] maxVal = -sys.maxsize - 1 for i in range(arr_len-1): result = max(abs(leftMin[i] - rightMax[i+1]), abs(leftMax[i] - rightMin[i+1])) if result > maxVal: maxVal = result return maxVal test_cases = int(input()) for _ in range(test_cases): arr_len = int(input()) arr = list(map(int, input().split())) answer = calc_max_absolute_diff(arr, arr_len) print(answer)
a0f1b8b151f1625d08d6884064f95fe3d41c5d20
ThanhThi94/baitap6
/chuyendoitiente/main.py
209
3.5625
4
import math usd = float(input("Nhập số USD cần đổi: ")) tg = float(input("Nhập tỉ giá USD/VND: ")) vnd = tg*usd print("Với {usd} USD sẽ đổi ra được {vnd} VND".format(usd=usd, vnd=vnd))
b6f5844c03c8ced466728257e5dcad29125bf91a
privateHmmmm/leetcode
/532-k-diff-pairs-in-an-array/k-diff-pairs-in-an-array.py
2,572
4.0625
4
# -*- coding:utf-8 -*- # # Given an array of integers and an integer k, you need to find the number of unique k-diff pairs in the array. Here a k-diff pair is defined as an integer pair (i, j), where i and j are both numbers in the array and their absolute difference is k. # # # # Example 1: # # Input: [3, 1, 4, 1, 5], k = 2 # Output: 2 # Explanation: There are two 2-diff pairs in the array, (1, 3) and (3, 5).Although we have two 1s in the input, we should only return the number of unique pairs. # # # # Example 2: # # Input:[1, 2, 3, 4, 5], k = 1 # Output: 4 # Explanation: There are four 1-diff pairs in the array, (1, 2), (2, 3), (3, 4) and (4, 5). # # # # Example 3: # # Input: [1, 3, 1, 5, 4], k = 0 # Output: 1 # Explanation: There is one 0-diff pair in the array, (1, 1). # # # # Note: # # The pairs (i, j) and (j, i) count as the same pair. # The length of the array won't exceed 10,000. # All the integers in the given input belong to the range: [-1e7, 1e7]. # # class Solution(object): def findPairs(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ """ if k < 0: return 0 elif k == 0: total=0 dicts={} for num in nums: if num in dicts: if dicts[num]==1: total+=1 dicts[num]=-1 else: dicts[num]=1 return total dict_p = {} dict_n = {} total = 0 flag1=True flag2=True for i in range(0, len(nums)): flag1=True flag2=True if nums[i] in dict_p: # find one that is k bigger than self total+=1 del dict_p[nums[i]] flag2=False if nums[i] in dict_n: # find one tha is k smaller than self total +=1 del dict_n[nums[i]] flag1=False if flag2==True: key = nums[i] - k dict_n[key]=i if flag1==True: key = nums[i] + k dict_p[key] = i return total """ if k>0: return len(set(nums)&set(n+k for n in nums)) elif k==0: return sum(v>1 for v in collections.Counter(nums).values()) else: return 0
30981b8a49cce692b4fd9279b1f7525b11d55526
gabriel-valenga/CursoEmVideoPython
/ex010.py
572
4.25
4
numero = int(input('Digite um número: ')) print('Tabuada do {}:'.format(numero)) print(' {} x 1 = {:2}'.format(numero,numero*1)) print(' {} x 2 = {:2}'.format(numero,numero*2)) print(' {} x 3 = {:2}'.format(numero,numero*3)) print(' {} x 4 = {:2}'.format(numero,numero*4)) print(' {} x 5 = {:2}'.format(numero,numero*5)) print(' {} x 6 = {:2}'.format(numero,numero*6)) print(' {} x 7 = {:2}'.format(numero,numero*7)) print(' {} x 8 = {:2}'.format(numero,numero*8)) print(' {} x 9 = {:2}'.format(numero,numero*9)) print(' {} x 10 = {:2}'.format(numero,numero*10))
d55263edb2c44653a1ae3ca2ee6170cc87977764
Akankshya-ap/Pattern-Recognition
/practice/linear_reg.py
383
3.65625
4
import numpy as np import matplotlib.pyplot as plt x=np.random.normal(3.0,1.0,1000) y=100-(x+np.random.normal(0,0.1,1000))*3 plt.scatter(x,y) #plt.show() from scipy import stats slope,intercept,r_value,p_value,std_err=stats.linregress(x,y) print r_value**2 def predict(p) : return slope*p+intercept line=predict(x) plt.plot(x,line,c='r') plt.show()
6222a619fbfed08723e11870d312c6b4f87227ee
kenwoov/PlayLeetCode
/Algorithms/Easy/507. Perfect Number/answer.py
476
3.625
4
from typing import List class Solution: def checkPerfectNumber(self, num: int) -> bool: if num <= 0: return False sum = 0 i = 1 while i * i <= num: if num % i == 0: sum += i if i * i != num: sum += num // i i += 1 return sum - num == num if __name__ == "__main__": s = Solution() result = s.checkPerfectNumber(28) print(result)
3bc7a18ddbf5280769e54b4efefc1a0f3858062b
Filipchi/MisionTIC2022
/Ciclo l/Semana 4/Ejercicios_4_p1.py
3,558
3.796875
4
import os os.system("cls") from functools import reduce print("\n\t\t\t Funciones para Colecciones de Datos\n") # Problema # 1: # Utilizar la función incorporada map() para crear una función que retorne una lista con la longitud de cada palabra(separadas por espacios) de una frase. La función recibe una cadena de texto y retornará una lista. def problema1 (): frase = str(input("\t 1) Ingrese la frase a validar: ")) # respuesta = list(map(lambda entrada: len(entrada), frase1.split())) # JH respuesta = list(map(len, frase.split())) # o también return respuesta # print(problema1()) # Problema # 2: # Crear una función que tome una lista de dígitos y devuelva al número al que corresponden. # Por ejemplo[1, 2, 3] corresponde a el número ciento veintitrés(123). Utilizar la función reduce. def problema2(): cantidad = int(input("\t 2) Ingrese la cantidad de dígitos a validar: ")) digitos = [int(input(f"\t\t Ingrese el {x+1} dígito: ")) for x in range(cantidad)] print("\t Digitos ingresados: ", digitos) respuesta = reduce(lambda y, z: y * 10 + z, digitos) return respuesta # print(problema2()) # Problema # 3: # Crear una función que retorne las palabras de una lista de palabras que comience con una letra en específico. Utilizar la función filter. def problema3(): frase = str(input("\t 3) Ingrese la frase a validar: ")) letra = str(input("\n\t\t Ingrese la letra inicial que desea filtrar: ")) respuesta = list(filter(lambda x: x[0] == letra, frase.split())) return respuesta # print(problema3()) # Problema # 4: # Realizar una función que tome una lista de comprensión para devolver una lista de la misma longitud donde cada valor son las dos cadenas de L1 y L2 concatenadas con un conector entre ellas. Ejemplo: Listas: ['A', 'a']['B', 'b'] Conector: '-' Salida: ['A-a']['B-b']. Utilizar la función zip. def problema4(): longitud = int(input("\t 4) Ingrese la longitud de las listas: ")) print("\n\t Lista 1:") lista1 = [str(input(f"\t\t Ingrese el {x+1} elemento: ")) for x in range(longitud)] print("\n\t Lista 2:") lista2 = [str(input(f"\t\t Ingrese el {x+1} elemento: ")) for x in range(longitud)] # for L1, L2 in zip (lista1, lista2): print("{} - {}".format(L1, L2)) return [L1 + "-" + L2 for (L1, L2) in zip(lista1, lista2)] # print(problema4()) # La función enumarate es otra de las herramientas para manipulación de colecciones de datosl en Python. Consultar cuál es su finalidad y una vez teniendo claro su comportamiento, resolver los dos siguientes problemas propuestos: # Problema # 5: # Realizar una función que tome una lista y retorne un diccionario que contenga los valores de la lista como clave y el índice como el valor. Utilizar la función enumerate. def problema5(): longitud = int(input("\t 5) Ingrese la longitud de la lista: ")) lista = [str(input(f"\t\t Ingrese el {x+1} elemento: ")) for x in range(longitud)] return {clave: valor for valor, clave in enumerate(lista)} # print(problema5()) # Problema # 6: # Realizar una función que retorne el recuento de la cantidad de elementos en la lista cuyo valor es igual a su índice. Utilizar la función enumerate. def problema6(): longitud = int(input("\t 5) Ingrese la longitud de la lista: ")) lista = [str(input(f"\t\t Ingrese el {x+1} elemento: ")) for x in range(longitud)] return len([num for count, num in enumerate(lista) if num == count]) # print(problema5())
6e1e2e3fb745317ecf51a6073eb1810411fb53b1
ssj018/homelab
/study/search_records.py
2,650
3.515625
4
import re import sys # 2014 # %book% # %title%abc%title% # %publish%2011%publish% # %author%qwer%author% # %book% # %book% # %title%def%title% # %publish%2012%publish% # %author%asdf%author% # %book% # %book% # %title%ghi%title% # %publish%2014%publish% # %author%zxcv%author% # %book% # %book% # %title%back to 2014%title% # %publish%1999%publish% # %author%poiu%author% # %book% class book: def __init__(self, title, publish, author): self.title = title self.publish = publish self.author = author def search(self, key): found = False if self.title == None: pass else: if re.search(r'{}'.format(key), self.title): found = True return found if self.publish == None: pass else: if re.search(r'{}'.format(key), self.publish): found = True return found if self.author == None: pass else: if re.search(r'{}'.format(key), self.author): found = True return found return found def main(): print('type your input, stop with \'...\'') key = input() book_tags = 0 title = publish = author = None booklist = [] while True: line = input() if line == '...': if book_tags % 2 != 0: print('book_tags are not double') sys.exit(1) break elif re.match(r'^\s*$',line): continue elif re.match(r'%book%$', line) and book_tags % 2 == 0: book_tags += 1 elif re.match(r'%book%$', line) and book_tags % 2 != 0: tbook = book(title, publish, author) booklist.append(tbook) book_tags +=1 elif re.search(r'%title%', line) and book_tags % 2 != 0: title = re.findall(r'''%title%(.*)%title%''', line)[0] elif re.search(r'publish', line) and book_tags % 2 != 0: publish = re.findall(r'''%publish%(.*)%publish%''', line)[0] elif re.search(r'author', line) and book_tags % 2 != 0: author = re.findall(r'''%author%(.*)%author%''', line)[0] else: print('wrong Input') sys.exit(1) for i in booklist: if i.search(key): print('title: {}, publish: {} , author: {}'.format(i.title, i.publish, i.author)) if __name__ == "__main__": main() # line = input() # book_tag = 0 # if re.search(r'%book%', line) and book_tag % 2 == 0: # print('book')
42cfe8b33ed3a4e10a8786ec13f97f5c627e2bb4
SubhamSingh1/star
/PycharmProjects/asssgn4.py
210
3.8125
4
cp = int(input("Enter the cost price.")) sp = int(input("Enter the sale price.")) if cp>sp: print("The seller has incurred loss of rs.", (cp-sp)) else: print("The seller has made profit of rs.",sp-cp)
4b40c968d854821a5aa7955aade3cc03d299efb4
silastsui/interview-practice
/interview/zenefits_cardinality_sorting.py
645
4.15625
4
# Complete the function below. def cardinalitySort(nums): def get_binary_cardinality(num): """Gets binary cardinality of a number""" bin_rep = bin(num)[2:] return bin_rep.count('1') sorted_nums = [] binary_nums = {} for num in nums: num_ones = get_binary_cardinality(num) if num_ones in binary_nums.keys(): binary_nums[num_ones].append(num) else: binary_nums[num_ones] = [num] binary_keys = sorted(binary_nums.keys()) for key in binary_keys: for num in sorted(binary_nums[key]): sorted_nums.append(num) return sorted_nums
ce1ed7c25a35ded729ff7b3b45bb03c17185782e
Wubuntu88/boolEQ
/boolEQ.py
13,805
4.1875
4
#!/usr/bin/python """ Author: William Gillespie Course: COSC 321 Date: 2015-04-18 This program accepts two inputs that are boolean expressions, prints out the truth tables for those functions, and prints out whether those functions are equal. The two inputs must have the same set of variables. Parentheses are permitted. The NOT is denoted by the # after the variable or parenthesized expression. The AND is denoted by two variables next to each other (or a variable next to a parenthesis, or two parenthesized expressions next to each other). The OR is denoted by +. Here is an example: A#B#+(AC)# ----> (not A) and (not B) or (not (A and B)) """ import re # import the regular expression library def eval_func(expr): """ This function returns true or false depending on what the expression evals to. It is a recursive function that evals boolean expressions in string format. It uses the information of the values for keys in the dictionary to return the correct answer. The dictionary it uses is the symbol_table dictionary, which contains the current values of the keys. This method is called by iterate(). The function iterate iterates over all the possible combinations that the symbol_table dictionary could store and calls this function for every possible combination. :param expr: The boolean expression to evaluate. Type: string :return: True if the expression is true, false if it is false """ expr_ls = list(expr) # expression list # check if incoming expression is surrounded fully by parens # if so, eval it, if not, let the below code handle it. if expr_ls[0] == '(' and expr_ls[-1] == ')': middle_expr = expr_ls[1:-1] parenStack = [] highestLevelParenthesizedExpressionFound = True for local_char in middle_expr: if local_char == '(': parenStack.append(local_char) elif local_char == ')': if len(parenStack) == 0: highestLevelParenthesizedExpressionFound = False else: parenStack.pop() if highestLevelParenthesizedExpressionFound: expr = "".join(middle_expr) return eval_func(expr) # end of checking if expression is surrounded by parens # find the top level or, if there is one. If so, eval the expressions # separated by the or or_paren_stack = [] index_at_which_to_slice = 0 top_level_or_was_found = False for item in expr_ls: if item == "(": or_paren_stack.append(item) elif item == ")": or_paren_stack.pop() elif item == '+' and len(or_paren_stack) == 0: top_level_or_was_found = True index_at_which_to_slice += 0 if top_level_or_was_found else 1 # if the top level or was found, eval each of the surrounding expressions if top_level_or_was_found: part1 = expr[:index_at_which_to_slice] part2 = expr[index_at_which_to_slice+1:] return eval_func(part1) or eval_func(part2) # end of code to check if there was a top level or # if code passes this part, we can assume there is no or at the top level. # find parens group for and anding of parens expr and a variable # I can assume that there will be and anding of two things. # This complicated block of code figures out whether to and a variable and # another variable, or a variable and a parenthesized expression. and_stack = [] parens_found_to_left = False letter_was_found_at_top_level = False index_where_stack_became_zero_first = 0 index_at_which_to_slice = 0 for item in expr_ls: if item == '(': and_stack.append(item) parens_found_to_left = True elif item == ')': and_stack.pop() if len(and_stack) == 0 and index_where_stack_became_zero_first == 0: index_where_stack_became_zero_first = index_at_which_to_slice # In this elif, we know there will be an anding of a letter (variable) and an # expression in parenthesis elif item.isalpha() and len(and_stack) == 0 and re.search("\(.*\)", expr): letter_was_found_at_top_level = True if parens_found_to_left: # var found right of the parens () part1 = expr[:index_at_which_to_slice] part2 = expr[index_at_which_to_slice:] return eval_func(part1) and eval_func(part2) else: # if the var is left of the parens if expr[index_at_which_to_slice+1] == '#': # the var is "not var" part1 = expr[:index_at_which_to_slice+2] part2 = expr[index_at_which_to_slice+2:] return eval_func(part1) and eval_func(part2) else: # the var is a plain old var with no "not" part1 = expr[:index_at_which_to_slice+1] part2 = expr[index_at_which_to_slice+1:] return eval_func(part1) and eval_func(part2) index_at_which_to_slice += 1 # if there was no var found at top level, we are anding two paren exprs: (A+B)(B+C) # or we are anding two parens, one or both notted, (A+B)#(B+C)# # or we are notting a group in parens (A+B)# # I can assume it will not be a singe paren group : (A+B) if not letter_was_found_at_top_level and parens_found_to_left: if expr[index_where_stack_became_zero_first+1] == '#': part1 = expr[:index_where_stack_became_zero_first+1] if len(expr) == index_where_stack_became_zero_first+2: return not eval_func(part1) else: part2 = expr[index_where_stack_became_zero_first+1:] return not eval_func(part1) and eval_func(part2) else: # if there are two paren groups: (A+B)(B+C) part1 = expr[:index_where_stack_became_zero_first+1] part2 = expr[index_where_stack_became_zero_first+1:] return eval_func(part1) and eval_func(part2) # end of code to see if there was and anding of a variable and # a parenthesized expression. # code to check for if we need to and a variable and something else, # or not a variable and and it with something else. if expr[0].isalpha() and len(expr) > 1: if expr[1] == '#': if len(expr[2:]) == 0: return not eval_func(expr[0]) else: return not eval_func(expr[0]) and eval_func(expr[2:]) else: return eval_func(expr[0]) and eval_func(expr[1:]) # end of code to check for an anding of a variable and something else, # or not a variable and and it with something else. # BASE CASE: This is the base case where we finally get to return # the value for a given key in the symbol table. if len(expr) == 1: return symbol_table[expr] # end of the eval_func method def create_symbol_table(expr): """ This method creates a symbol table from the input of a boolean expression :param expr: The boolean expression to be evaluated. Type: string :return: returns the symbol table dictionary. Type: dictionary """ temp_symbol_table = {} for local_char in expr: if local_char.isalpha() and local_char not in temp_symbol_table: c = local_char.upper() temp_symbol_table[c] = 0 # fill with junk return temp_symbol_table def isCorrectBoolExpression(expr): """ determines whether the expression is correctly formatted. This method checks all the ways a boolean function could be formatted, and outputs False if it is incorrectly formatted. Otherwise returns True. :param expr: the boolean expression; type: string :return: True if it is correctly formatted, False otherwise; Type bool """ parenStack = [] charStack = [] for theChar in expr: if theChar.isalpha(): pass elif theChar == '(': parenStack.append(theChar) elif theChar == ')': if len(parenStack) == 0: return False elif charStack[-1] == '(': return False elif charStack and charStack[-1] == '+': return False parenStack.pop() elif theChar == '+': if len(charStack) == 0: return False elif charStack[-1] == '+': return False elif len(parenStack) and charStack[-1] == '(': return False elif theChar == '#': if len(charStack) == 0: return False elif charStack[-1] == '(': return False else: return False charStack.append(theChar) if len(parenStack): return False return True # end of method isCorrectBoolExpression(expr) """ These lists contain snapshots of the dictionaries for a given loop iteration (corresponding to a combination of values in the truth table) These Ivars are used in the printing of the truth table. They are mutated in iterate() and that is why they are above that method. """ dict_snapshots = [] # contains the snapshots of the dictionaries in each iteration # to be used for the output of the truth table dict1_eval_results = [] dict2_eval_results = [] def iterate(item, my_list): # string and list for parameters """ Description: this methods iterates through all of the possible values that the keys in the symbol table can have. It is equivalent to iterating over all the combinations of a boolean truth table. :param item: the key in the symbol table that we are currently iterating through the values of :param my_list: the rest of the keys in the symbol table we have yet to iterate through. """ for index in range(0, 2): symbol_table[item] = index if len(my_list) == 0: # BASE CASE my_copy = dict(symbol_table) dict_snapshots.append(my_copy) result1 = eval_func(expr1) dict1_eval_results.append(result1) result2 = eval_func(expr2) dict2_eval_results.append(result2) if result1 != result2: result[0] = False else: # RECURSIVE CASE # if there are still symbols to iterate over, we call iterate on the # next symbols as first parameter, and the rest of the symbols as the # second parameter, if there are any. if len(my_list): iterate(my_list[0], my_list[1:]) # if result[0] is false, we return, go up to higher recursive level # and eventually get out of the recursive calls. Outside this method, # we will see that the result[0] == False, meaning that the bool exprs # are not equal. # end of iterate() # -----------start of script----------- symbol_table = {} result = [True] expr1 = '' expr2 = '' while True: # keep looping until user wants to quit. expr1 = raw_input("Enter first boolean expression: ") expr1 = expr1.translate(None, " ") # strips out whitespaces expr1 = expr1.upper() symbol_table = create_symbol_table(expr1) expr2 = raw_input("Enter second boolean expression: ") expr2 = expr2.translate(None, " ") expr2 = expr2.upper() second_symbol_table = create_symbol_table(expr2) # if both bool expressions are not correctly formatted, tell user to re-enter if not (isCorrectBoolExpression(expr1) and isCorrectBoolExpression(expr2)): print 'boolean expressions not formatted correctly; please re-enter.' continue first_set = set(symbol_table) second_set = set(second_symbol_table) intersection = first_set.intersection(second_set) # if the boolean expressions do not have the same symbols, tell user to re-enter if len(intersection) != len(first_set): print 'you did not input expressions with the same set of variables' print 'please do that.' continue if not (len(expr1) and len(expr2)): # if the user entered the empty string print 'you must enter two boolean expressions' continue # continue because one or both contain nothing for character in list(expr2): if character.isalpha() and character.upper() not in symbol_table: print 'symbols sets are not the same; re-enter expressions' continue # puts all the keys in the symbol table into a list expr_list = [key for key in symbol_table.keys()] # iterates over all of the possibilities for the variables, # prints the truth table with the results. iterate(expr_list[0], expr_list[1:]) # <--NOTE: computations done here # prints out the truth tables print '------expr 1 truth table------' i = 0 for dictionary in dict_snapshots: res1 = '1' if dict1_eval_results[i] else '0' print str(dictionary) + "; result: " + res1 i += 1 print '------expr 2 truth table------' i = 0 for dictionary in dict_snapshots: res2 = '1' if dict2_eval_results[i] else '0' print str(dictionary) + "; result: " + res2 i += 1 # reset vars for next iteration dict_snapshots = [] dict1_eval_results = [] dict2_eval_results = [] symbol_table = {} # prints out whether the results are equal or not. if result[0]: print "boolean expressions are equal" else: print "boolean expressions are not equal" # reset result to True result[0] = True # ask user if they want to continue if raw_input("CONTINUE? Y/N: ").upper() != 'Y': break
d784c7310908825f371cd1e33c3eb64557b2aa0e
vik-tort/hillel
/Test/Task_7(TEST).py
256
3.875
4
n=10 fibonnachi=[1,1,2] for num in range(3,n): fibonnachi.append(fibonnachi[num-1]+fibonnachi[num-2]) print(fibonnachi) sum_of_fib=sum(fibonnachi) print("Сумма первых 10 чисел ряда Фибоначчи равна %d" % (sum_of_fib))
fe7879d5a63dba07630206d20d53fb282468700b
gopinathdee/Python
/Basic/02-SimpleInterest.py
313
3.90625
4
intPrincipal = input("\nEnter Principal: ") intNumberOfYears = input("Enter Number of Years: ") floatRateOfInterest = input("Enter Rate of Interest: ") floatSimpleInterest = (int(intPrincipal) * int(intNumberOfYears) * float(floatRateOfInterest))/100 print ("Simple Interest is: %0.2f" %floatSimpleInterest)
2a2e15015f7ac190d804b8938060a3d0e35050fb
khasherr/SummerOfPython
/ReplacePI.py
590
4.125
4
#Sher Khan #This program replaces occurence of PI with 3.14 recursivelye def replacePI(s): #This checks if the the string is either empty or has 1 character returns the string itself if len(s) == 0 or len(s) == 1: return s #returns the string because its empty or has 1 character #If the index at 0th is p char and at 1st is i char then cho if ((s[0] == 'p' and s[1] == 'i')): smallStr = replacePI(s[2:]) return '3.14' + smallStr else: smallStr = replacePI(s[1:]) return s[0] + smallStr print(replacePI("pipip")) print(replacePI("PIPIP"))
49f73092445c6e802699d34d1d07fcb60f4bd671
juanducal/glassnode
/glassnode.py
2,177
3.515625
4
import requests as req import datetime as dt import pandas as pd def date_to_unix( year = 2010, month = 1, day = 15, ): '''Returns the date (UTC time) in Unix time''' time = int((dt.datetime(year, month, day, 0, 0, 0).timestamp())) return time def glassnode( endpoint, start, until, api_key = 'a2b123be-2c50-4dc9-bdf4-cded52c3d1fc', # Insert your own API key here, this one is only illustrative. asset = 'BTC', status = False, headers = False, resolution = '24h', wait = 10 ): '''Returns a Dataframe of time, value pairs for a metric from the Glassnode API. Parameters ---------- endpoint : str Endpoint url after https://api.glassnode.com, corresponding to some metric (ex. '/v1/metrics/indicators/puell_multiple' ) start : list Start date as a list in decreasing order (ex. [2015, 11, 27] ) until : list End date as a list in decreasing order (ex. [2018, 5, 13] ) api_key : str Your API key (ex. 'a2b123be-2c50-4dc9-bdf4-cded52c3d1fc' ) asset : str Asset to which the metric refers. (ex. BTC ) status : bool Option to print HTTP status code. '<Response [200]>' means success. headers : bool Option to print HTTP headers. Contains REST API request and response metadata. resolution : str Temporal resolution of the data received. Can be '10m', '1h', '24h', '1w' or '1month'. wait : float Seconds until the connection timeouts. ALWAYS specify a period. Returns ------- DataFrame List of {'t' : unix-time, 'v' : 'metric-value'} pairs ''' s = date_to_unix(year=start[0], month=start[1], day=start[2]) u = date_to_unix(year=until[0], month=until[1], day=until[2]) response = req.get( f'https://api.glassnode.com{endpoint}', { 'api_key': api_key, 'a': asset, 's': s, 'u': u, 'i': resolution }, timeout = wait) df = pd.DataFrame(response.json()) if status: print(response) if headers: print(response.headers) return df
6a863e8a911281bab429ca287d9a0f63d4912a3c
Anthonina/lesson1
/training_while_loop.py
524
3.953125
4
find_name = ['Вася', 'Маша', 'Петя', 'Валера', 'Саша', 'Даша'] print(find_name) x = 0 while x < len(find_name): # Пока индекс меньше количества элементов в списке... if find_name[x] == 'Валера': # Если элемент с индексом X равен значению "Валера" valera = find_name.pop(x) # Заводим переменную print('{} нашёлся'.format(valera)) x = x + 1 print(find_name)
78383c459dc59b059ef3e99d0b16176d4bcff283
ohdnf/algorithms
/leetcode/819_most_common_word.py
478
3.828125
4
from collections import defaultdict, Counter import re def most_common_word(paragraph: str, banned) -> str: counts = defaultdict(int) words = [word for word in re.sub(r'[^\w]', ' ', paragraph).split() if word not in banned] for word in words: counts[word.lower()] += 1 print(counts) return max(counts, key=counts.get) if __name__ == "__main__": print(most_common_word("Bob hit a ball, the hit BALL flew far after it was hit.", ["hit"]), "ball")
133634207573fa7c3e921e76f08cfa60583b07d0
stephanbos96/programmeren-opdrachten
/school/les8/8.3.py
307
3.71875
4
def code(invoerstring): waarde = '' for c in invoerstring: o = ord(c) o += 3 nieuwe_char = chr(o) waarde += nieuwe_char return waarde text = input('Geef naam begin station en eindstation: ') antwoord = code(text) print('code is {}'.format(antwoord))
10e2ab5d028bf42dbec39e83a0272faa73994291
elenaborisova/Python-Advanced
/04. Tuples and Sets - Exercise/06_longest_intersection.py
913
4
4
def find_range_values(curr_range): return list(map(int, curr_range.split(","))) def find_set(curr_range): start_value, end_value = find_range_values(curr_range) curr_set = set(range(start_value, end_value + 1)) return curr_set def find_longest_intersection(n): longest_intersection = set() for _ in range(n): first_range, second_range = input().split("-") first_set = find_set(first_range) second_set = find_set(second_range) curr_intersection = first_set.intersection(second_set) if len(curr_intersection) > len(longest_intersection): longest_intersection = curr_intersection return list(longest_intersection) def print_result(longest_intersection): print(f"Longest intersection is {longest_intersection} " f"with length {len(longest_intersection)}") print_result(find_longest_intersection(int(input())))
702af67e205ca4594eb0a585aa7f0a60fdb9342a
yutanov/python-project-lvl1
/brain_games/games/brain_gcd.py
391
3.90625
4
import random COND = "Find the greatest common divisor of given numbers." def gcd(a, b): return gcd(b, a % b) if b else a def get_answer(): num_one = int(random.randint(1, 100)) num_two = int(random.randint(1, 100)) print("Question: {} {}".format(num_one, num_two)) divisor = gcd(num_one, num_two) answer = int(input("Your answer: ")) return divisor, answer
8bc048cb658fde7125a191a77aeca46afc4f8057
Nazanin1369/miniFlow
/src/linear.py
732
3.53125
4
from node import Node class Linear(Node): """ Linear Transform function """ def __init__(self, inputs, weights, bias): Node.__init__(self, [inputs, weights, bias]) # NOTE: The weights and bias properties here are not # numbers, but rather references to other nodes. # The weight and bias values are stored within the # respective nodes. def forward(self): """ Set self.value to the value of the linear function output. """ inputs = self.inbound_nodes[0].value weights = self.inbound_nodes[1].value self.value = bias = self.inbound_nodes[2].value for x, w in zip(inputs, weights): self.value += x * w
ea349c92e4aff08ee0495d05ed7bf7a012ade899
opaulocrispim/criptografia_de_cifra
/criptografia.py
3,147
3.515625
4
import string from unidecode import unidecode def run(): contador = 0 alfabeto = ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'] alfabeto_chave = [] chave = str(input("Digite a chave: ")) #Definir a chave chave = unidecode(chave).replace(" ", "").replace("ç", "c").upper() frase = [] mensagem_criptografada = [] contador_crip = 0 contador_escreve = 0 contador_alfabeto = 0 for letra in chave: #Pegando os caracteres, sem repetir nenhuma letra if letra not in alfabeto_chave: alfabeto_chave.append(letra) ultima_letra = (alfabeto_chave[-1]) if ultima_letra in alfabeto: #Verifico qual o último caractere num = (alfabeto.index(ultima_letra)+1) contador = int(num) cont = alfabeto[contador:] #continução da lista for letra in cont: #Verifica caracteres após o fim da chave if letra not in alfabeto_chave: alfabeto_chave.append(letra) cont2 = alfabeto_chave if len(alfabeto_chave) <= 26: #Completa os 26 caracteres do alfabeto for letra1 in alfabeto: if letra1 not in cont2: cont.append(letra1) resultado = cont2 print(f"Seu alfabeto criptografado é: ", end='') #Imprime o 'alfabeto criptografado' sem as aspas while contador_alfabeto <= len(resultado): atual = print(alfabeto_chave[contador_alfabeto], end='') contador_alfabeto += 1 if contador_alfabeto == len(resultado): break mensagem = str(input("\nInsira a frase que será criptografada: ")) #Recebe a mensagem que sera criptografada mensagem = unidecode(mensagem).replace(" ", "").replace("ç", "c").upper() for letra in mensagem: #Fatia as letras da mensagem frase.append(letra) prim_let = frase[contador_crip] #Busca a letra em x posição pos = alfabeto.index(prim_let) #Procura a posição no alfabeto letra_crip = alfabeto_chave[pos] #Procura a posição no 'alfabeto criptografado' mensagem_criptografada.append(letra_crip) #Adiciona a 'letra criptografada' a lista contador_crip += 1 print('Sua mensagem criptografada é: ', end='') #Imprime a mensagem sem as aspas while contador_escreve <= len(frase): atual = print(mensagem_criptografada[contador_escreve], end='') contador_escreve += 1 if contador_escreve == len(frase): break if (__name__ == '__main__'): #Rodar escolha run()
75d1a544e03efe812c087be56e4ea7440783bc84
kangli-bionic/algorithm
/lintcode/1479.py
1,315
3.78125
4
""" 1479. Can Reach The Endpoint https://www.lintcode.com/problem/can-reach-the-endpoint/description """ from collections import deque DIRECTIONS = [ (0, 1), (0, -1), (-1, 0), (1, 0) ] class DataType: ENDPOINT = 9 OBSTACLE = 0 class Solution: """ @param map: the map @return: can you reach the endpoint """ def reachEndpoint(self, map): # Write your code here if not map or not map[0]: return False queue = deque([(0, 0)]) visited = set([(0, 0)]) while queue: x, y = queue.popleft() for delta in DIRECTIONS: next_x = x + delta[0] next_y = y + delta[1] if not self.is_valid(next_x, next_y, map, visited): continue if map[next_x][next_y] == DataType.ENDPOINT: return True queue.append((next_x, next_y)) visited.add((next_x, next_y)) return False def is_valid(self, x, y, map, visited): n = len(map) m = len(map[0]) if (x, y) in visited: return False if not (0 <= x < n and 0 <= y < m): return False if map[x][y] == DataType.OBSTACLE: return False return True
4ff7875d4c0fef6509fc8d79b6331a875341afc1
fabioconde/desafio
/questao_1.py
763
3.921875
4
""" Dado um array de números inteiros, retorne os índices dos dois números de forma que eles se somem a um alvo específico. Você pode assumir que cada entrada teria exatamente uma solução, e você não pode usar o mesmo elemento duas vezes. EXEMPLO Dado nums = [2, 7, 11, 15], alvo = 9, Como nums[0] + nums[1] = 2 + 7 = 9, return [0, 1]. """ def soma_alvo(nums, alvo): resultado = [] num_total = len(nums) for i in range(0, num_total): for j in range(i + 1, num_total): if nums[i] != nums[j]: if int(nums[i]) + int(nums[j]) == alvo: resultado.append([i, j]) return resultado def main(): entrada = [2, 7, 11, 15] alvo = 9 print(soma_alvo(entrada, alvo)) main()
c3aff3210a727a2f3a89afd37ca315dcc373eca3
Vixus/LeetCode
/PythonCode/Monthly_Coding_Challenge/May2020/ImplementTrie.py
2,115
4.21875
4
class Trie: """ Implement a trie with insert, search, and startsWith methods. Trie trie = new Trie(); trie.insert("apple"); trie.search("apple"); // returns true trie.search("app"); // returns false trie.startsWith("app"); // returns true trie.insert("app"); trie.search("app"); // returns true """ def convertToNum(self, letter): return ord(letter)-ord('a') def __init__(self): """ Initialize your data structure here. """ self.children = [None]*26 self.endOfWord = False def insert(self, word: str) -> None: """ Inserts a word into the trie. """ ptr = self for x in word: index = ptr.convertToNum(x) if not ptr.children[index]: ptr.children[index] = Trie() ptr = ptr.children[index] ptr.endOfWord = True def search(self, word: str) -> bool: """ Returns if the word is in the trie. """ ptr = self found = False for i, x in enumerate(word): index = ptr.convertToNum(x) if ptr.children[index]: ptr = ptr.children[index] if i == len(word)-1: if ptr.endOfWord: found = True else: break return found def startsWith(self, prefix: str) -> bool: """ Returns if there is any word in the trie that starts with the given prefix. """ ptr = self found = False for i, x in enumerate(prefix): index = ptr.convertToNum(x) if ptr.children[index]: ptr = ptr.children[index] if i == len(prefix)-1: found = True else: break return found def main(): # Your Trie object will be instantiated and called as such: obj = Trie() obj.insert('apple') print(obj.search('app')) print(obj.startsWith('app')) if __name__ == '__main__': main()
9f84bb67de030e6765f6cc05c6e99f17dedb65ae
Nithya1999/project
/inn.py
173
3.5
4
#Nithya n=input().split() a=input().split() b=input().split() l=[] for i in a: if i in b: l.append(i) if(len(b)==len(l)): print('YES') else: print('NO')
3ff9daaafbf98110b26acfc83f0d0e5a410fb03f
kelpasa/Code_Wars_Python
/6 кю/Compare Versions.py
1,524
3.875
4
''' Karan's company makes software that provides different features based on the version of operating system of the user. For finding which version is more recent, Karan uses the following method: While this function worked for OS versions 10.6, 10.7, 10.8 and 10.9, the Operating system company just released OS version 10.10. Karan's function fails for the new version: compare_versions ("10.9", "10.10"); # returns True, while it should return False Karan now wants to spend some time to right a more robust version comparison function that works for any future version/sub-version updates. ''' from distutils.version import LooseVersion def compare_versions(version1,version2): return LooseVersion(version1) >= LooseVersion(version2) ''' try: ver_1 = float(version1) ver_2 = float(version2) print(ver_1), print(ver_2) return ver_1 >= ver_2 except: ver_1 = version1.replace('.','') ver_2 = version2.replace('.','') if len(ver_1) == len(ver_2): return int(ver_1) >= int(ver_2) else: if len(ver_1) < len(ver_2): ver_1 = ver_1 + ('0'*(len(ver_2)-len(ver_1))) print(ver_1),print(ver_2) return int(ver_1) >= int(ver_2) if len(ver_1) > len(ver_2): ver_2 = ver_2 + ('0'*(len(ver_1)-len(ver_2))) print(ver_1), print(ver_2) return int(ver_1) >= int(ver_2) '''
4f16492049a00cb0482ef34b05ec3b622b5c2648
Max5249/tstp
/part_IV/algorithms/sequential_search.py
528
3.953125
4
# IF YOU ARE READING THIS YOU ARE READING # AN OUTDATED VERSION OF THE BOOK. # I am working with Amazon to resolve this. # The new version is much better and has correctly formatted code examples # In the book. # Please email me at cory@theselftaughtprogrammer.io # For an updated version def sequential_search(number_list, number): found = False for i in number_list: if i == number: found = True break return found print(sequential_search(range(0, 100), 2)) print(sequential_search(range(0, 100), 202))
20dec344b403f8bc2bfe057a00e0c67278a46f09
ieeecomputeruni/taller-python
/archivos/11.py
655
4
4
# Listas L.append(object) #Añade un objeto al final de la lista. L.count(value) #Devuelve el número de veces que se encontró value en la lista. L.extend(iterable) #Añade los elementos del iterable a la lista. L.insert(index, object) #Inserta el objeto object en la posición index. L.pop([index]) #Devuelve el valor en la posición index y lo elimina de la lista. Si no se especifica la posición, se utiliza el último elemento de la lista. L.remove(value) #Eliminar la primera ocurrencia de value en la lista. L.reverse() #Invierte la lista. Esta función trabaja sobre la propia lista desde la que se invoca el método, no sobre una copia.
ac653131cf052f16efe4470692a1c14d651d9a98
mas41672/Python
/ex8.py
737
3.8125
4
# -- coding: utf- 8 - formatter = "%r %r %r %r" # als prints are made of a str, percentage (%) and the input print formatter % (1, 2, 3, 4) # prints ints into the raw str print formatter % ("one", "two", "three", "four") #3 # prints str into raw formatter print formatter % (True, False, False, True) # # the %r prin format accepts bool values print formatter % (formatter, formatter, formatter, formatter) print formatter % ( # it is possible to write the parameters in the next line "I had this thing.", #str with comma to avoid long line "That you could type up right.", #str with comma to avoid long line "But it didn't sing.", #str with comma to avoid long line "So I said goodnight." #str with comma to avoid long line )
0f9d6f596970ebfe42fbc3396c458e3118d171e7
vlgandara/programas-.py
/buzz.py
98
3.859375
4
n = int(input("Digite um número:")) if(n%5==0): print("Buzz") else: if(n%5!=0): print(n)
0e8ed33ac7e5043001467ccd5735844a27a8e8fc
ymadh/python-practice
/script.py
205
3.765625
4
students_count: int = 1000 print(type(students_count)) if students_count == 1000: print('yes') else: print('no') guess = 0 answer = 5 while answer != guess: guess = int(input("Guess: " ))
953775012d4026e812357a22f40eee49f18118ba
yuchen352416/leetcode-example
/chapter_01/example_0002.py
486
3.625
4
#!/usr/bin/python3 # 买卖股票的最佳时机2 def maxProfit(prices: list) -> int: if prices.__len__() < 2: return 0 sum = 0 for i in range(prices.__len__() - 1): if prices[i] < prices[i + 1]: sum += prices[i + 1] - prices[i] return sum if __name__ == '__main__': # arr = [7, 1, 5, 3, 6, 4] # arr = [6, 1, 3, 2, 4, 7] # arr = [1, 2, 3, 4, 5] arr = [3, 3, 5, 0, 0, 3, 1, 4] print(arr) p = maxProfit(arr) print(p)
e065555c5f291f462cfccbc461106026f6c0aa9f
snlab/odl-summit-2016-tutorial-vm
/utils/Maple_Topo_Scripts/exampletopo.py
1,676
3.640625
4
"""Custom topology example Two directly connected switches plus a host for each switch: host --- switch --- switch --- host Adding the 'topos' dict with a key/value pair to generate our newly defined topology enables one to pass in '--topo=mytopo' from the command line. """ from mininet.topo import Topo from mininet.util import quietRun class MyTopo( Topo ): "Simple topology example." def __init__( self ): "Create custom topo." # Initialize topology Topo.__init__( self ) # Add hosts and switches Host1 = self.addHost( 'h1' ) Host2 = self.addHost( 'h2' ) Host3 = self.addHost( 'h3' ) Host4 = self.addHost( 'h4' ) Host6 = self.addHost( 'h6' ) Switch1 = self.addSwitch( 's1' ) Switch2 = self.addSwitch( 's2' ) Switch3 = self.addSwitch( 's3' ) Switch4 = self.addSwitch( 's4' ) # Add links self.addLink( Host1, Switch1 ) self.addLink( Host3, Switch1 ) self.addLink( Host2, Switch4 ) self.addLink( Host4, Switch4 ) self.addLink( Host6, Switch4 ) self.addLink( Switch1, Switch2 ) self.addLink( Switch1, Switch3 ) self.addLink( Switch2, Switch4 ) self.addLink( Switch3, Switch4 ) # h1 = nt.get('h1') # h1.cmd( 'ifconfig h1-eth0 192.168.1.10' ) # Host2.cmd( 'ifconfig h2-eth0 192.168.1.20' ) # Host3.cmd( 'ifconfig h3-eth0 10.0.0.2' ) # Host4.cmd( 'ifconfig h4-eth0 10.0.0.3' ) # leftSwitch.cmd( 'ifconfig s1-eth2 192.168.1.1' ) # rightSwitch.cmd( 'ifconfig s2-eth2 192.168.1.2' ) topos = { 'mytopo': ( lambda: MyTopo() ) }
64eb29c7fe8b5ecfd600cd788ac7c00dc1d62c24
jeremy24/python-file-handling
/src/read_input.py
1,416
3.515625
4
# reads in the json data, and builds it into an object import json import os class Data: def __init__(self): self.data = [] self.length = 0 self.current_id = 0 def __str__(self): return "Data obj of length " + str(self.data.__len__()) def update(self): self.length = self.data.__len__() def sort(self, cm): self.data = sorted(self.data, cm) def add(self, other_list): self.data += other_list self.update() def push(self, item, given_id): item["data_id"] = given_id self.data.append(item) self.update() def dump(self): for item in self.data: print item["data_id"] print self.data.__len__() def read_orders(): i = 0 d = Data() for data_file in os.listdir("./test-data/orders"): name = "./test-data/orders/" + data_file file_data = open(name).read() json_data = json.loads(file_data) for item in json_data: d.push(item, i) i += 1 return d def read_tests(): i = 0 d = Data() for data_file in os.listdir("./test-data/tests"): name = "./test-data/tests/" + data_file file_data = open(name).read() json_data = json.loads(file_data) for item in json_data: d.push(item, i) i += 1 return d # test = read() # # print test
04ee555d3793396e25a2a0883ad4ef827ede61dc
cvsogor/Algorithms
/ESG_tests.py
6,008
3.96875
4
from unittest import TestCase # reverse all words in the sentence # ie.. I am a developer => developer a am I def reverse_sentence(sentence): words = sentence.split() words.reverse() return ' '.join(words) class TestReverseSentence(TestCase): def test_reverses_sentences_correctly(self): test_data = "I am a developer" expected = "developer a am I" self.assertEqual(expected, reverse_sentence(test_data)) # ############################################### test_trades = [ {"trader_id": 1, "value": -100.0, "date": "2016-06-01"}, {"trader_id": 1, "value": 50, "date": "2016-06-01"}, {"trader_id": 1, "value": 50, "date": "2016-06-02"}, {"trader_id": 1, "value": 50, "date": "2016-06-02"}, {"trader_id": 2, "value": 50, "date": "2016-06-02"} ] test_traders = [ {"id": 1, "name": "Rob"}, {"id": 2, "name": "John"} ] def calculate_trade_total(trades): trades_sum = 0 for trade in trades: trades_sum += trade["value"] return trades_sum def calculate_trade_by_id(trades, id): trades_sum = 0 for trade in trades: if trade["trader_id"] == id: trades_sum += trade["value"] return trades_sum def calculate_trader_totals(trades, traders): result = {} for trade in traders: val = calculate_trade_by_id(trades, trade["id"]) result[trade["name"]] = val return result def calculate_trade_by_id_and_date(trades, id, date): trades_sum = 0 for trade in trades: if trade["trader_id"] == id and trade["date"] == date: trades_sum += trade["value"] return trades_sum def calculate_trader_totals_for_date(trades, traders, date): result = {} for trade in traders: val = calculate_trade_by_id_and_date(trades, trade["id"], date) result[trade["name"]] = val return result class TestTradeAnalysis(TestCase): def test_calculate_trade_total_calculates_correct_value(self): result = calculate_trade_total(test_trades) expected = 100 self.assertEqual(expected, result) def test_calculate_trader_totals_calculates_correct_values(self): result = calculate_trader_totals(test_trades, test_traders) expected = {"Rob": 50, "John": 50} self.assertEqual(expected, result) def test_calculate_trader_totals_for_date_works_for_1st_june(self): result = calculate_trader_totals_for_date(test_trades, test_traders, "2016-06-01") expected = {"Rob": -50, "John": 0} self.assertEqual(expected, result) def test_calculate_trader_totals_for_date_works_for_2nd_june(self): result = calculate_trader_totals_for_date(test_trades, test_traders, "2016-06-02") expected = {"Rob": 100, "John": 50} self.assertEqual(expected, result) # ################################################ def rle_encode(string): if not string: return "" ch = string[0] n = 0 result = "" for c in string: if ch != c: result += str(ch) result += str(n) n = 1 ch = c else: n += 1 result += str(ch) result += str(n) return result class TestRleEncode(TestCase): def test_encodes_the_input_correctly(self): test_data = "bbxxxxyeebbbbxool" expected = "b2x4y1e2b4x1o2l1" self.assertEqual(expected, rle_encode(test_data)) # ################################################ def find_matching_parenthesis2(text, parenthesis_index): n = 1 for i in range(parenthesis_index + 1, len(text)): c = text[i] if c == '(': n += 1 if c == ')': n -= 1 if n == 0: return i return -1 def find_matching_parenthesis(text, parenthesis_index): n = 1 if text[parenthesis_index] == '(': for i in range(parenthesis_index + 1, len(text)): c = text[i] if c == '(': n += 1 if c == ')': n -= 1 if n == 0: return i if text[parenthesis_index] == ')': for i in reversed(range(0, parenthesis_index )): c = text[i] if c == ')': n += 1 if c == '(': n -= 1 if n == 0: return i return -1 class TestFindMatchingParenthesis(TestCase): def test_return_index_of_matching_parenthesis(self): test_text = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing." test_index = 10 expected = 79 self.assertEqual(expected, find_matching_parenthesis(test_text, test_index)) def test_bonus_question_for_clever_clogs(self): test_text = "Sometimes (when I nest them (my parentheticals) too much (like this (and this))) they get confusing." test_index = 79 expected = 10 self.assertEqual(expected, find_matching_parenthesis(test_text, test_index)) print("Executing Tests") TestReverseSentence().test_reverses_sentences_correctly() print("Reverse Sentence Test Completed") TestTradeAnalysis().test_calculate_trade_total_calculates_correct_value() print("Trade Analysis Test 1 Complete") TestTradeAnalysis().test_calculate_trader_totals_calculates_correct_values() print("Trade Analysis Test 2 Complete") TestTradeAnalysis().test_calculate_trader_totals_for_date_works_for_1st_june() print("Trade Analysis Test 3 Complete") TestTradeAnalysis().test_calculate_trader_totals_for_date_works_for_2nd_june() print("Trade Analysis Test 4 Complete") TestRleEncode().test_encodes_the_input_correctly() print("Run Length Encoder Test Complete") TestFindMatchingParenthesis().test_return_index_of_matching_parenthesis() print("Parenthesis Test 1 Complete") TestFindMatchingParenthesis().test_bonus_question_for_clever_clogs() print("Parenthesis Test 2 Complete")
3ec40f7176e89a4a88962f7302628cbcaf89b0c8
FishingOnATree/LeetCodeChallenge
/algorithms/151_reverse_words_in_string.py
303
3.53125
4
import re class Solution(object): def reverseWords(self, s): """ :type s: str :rtype: str """ return " ".join(re.sub(r"\s+", r" ", s.strip()).strip().split(" ")[::-1]) a = Solution() print(a.reverseWords(" the sky is blue ")) print(a.reverseWords(" a b "))