blob_id
stringlengths
40
40
repo_name
stringlengths
5
127
path
stringlengths
2
523
length_bytes
int64
22
545k
score
float64
3.5
5.34
int_score
int64
4
5
text
stringlengths
22
545k
3ec338e1d1aa30d5d25657ee7d7722791b478d5e
BenjaminFu1/Python-Prep
/cube area calculator.py
138
4.0625
4
width=float(input("Give me the width of your cube")) area=(width) * (width) * 6 print("{0:.1f} is the area of your cube".format(area))
a11e6981301bbdc6a6f55ac7853598ad3b61ede9
BenjaminFu1/Python-Prep
/square area calculator.py
205
4.1875
4
length=float(input("Give me the lenth of your rectangle")) width=float(input("Give me the width of your rectangle")) area=(length) * (width) print("{0:.1f} is the area of your rectangle".format(area))
3f620cb320f89f4e0f19bd2d09a30a9b9402b98f
tu-nguyen/linkedinlearning
/Master Python for Data Science/Python Essential Training 1/Chap11/hello.py
453
4.15625
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ # print('Hello, World.'.swapcase()) # print('Hello, World. {}'.format(42 * 7)) # print(""" # Hello, # World. # {} # """.format(42 * 7)) # s = 'Hello, World. {}' # print(s.format(42 * 7)) # class MyString(str): # def __str__(self): # return self[::-1] # s = MyString('Hello, World.') # print(s) x = 42 # y = 73 print(f"The number is {x:.3f}") # .format(x))
f59fc77f6136f93879b9426fbcc4e4777cc0025b
tu-nguyen/linkedinlearning
/Master Python for Data Science/Python Essential Training 1/Chap08/dict.py
537
4.09375
4
#!/usr/bin/env python3 # Copyright 2009-2017 BHG http://bw.org/ def main(): # animals = { 'kitten': 'meow', 'puppy': 'ruff!', 'lion': 'grrr', # 'giraffe': 'I am a giraffe!', 'dragon': 'rawr' } animals = dict( kitten= 'meow', puppy= 'ruff!', lion= 'grrr', giraffe= 'I am a giraffe!', dragon= 'rawr' ) # print(animals["lion"]) # print_dict(animals) def print_dict(o): # for x in o: print(f'{x}: {o[x]}') for k, v in o.items(): print(f"{k}: {v}") if __name__ == '__main__': main()
27a9e19391c5cd966fd132ad08e56139a890064b
fyiidk/ITT109-GROUP_ASSIGNMENT
/Group 10.py
439
3.53125
4
from tkinter import filedialog from tkinter import * def mainscreen (): print ("Main Program") game = Tk() game.title ("Bouncing Ball") game.minsize (500,500) lblimage = PhotoImage(file="Basketball.png") Label(game, text="Welcome to Bouncing Ball", bg="white", fg="black", font="none 20 bold"). grid(row=1, column =0, sticky=S) Label(game, image=lblimage, bg="white").grid(row = 6, column = 1, sticky=W)
1f5f0706f9b59da69a727bc528f761b076f2bfbe
CarlosCBar/Funciones
/Funciones.py
6,594
3.984375
4
# Reusando codigo con funciones # Siempre se usa snake_case # --- : ---- Marca el inicio del bloque de código def saluda_usuario(): #para definir una función print("Buenos días Krillin") #Puedes realizar cualquier acción print("Es hora de entrenar") # Para llamar la función escribiendo la función ----- saluda_usuario() -------- def weather_update(): print ("Weather update") print ("Rainy daya are comming") def rutina_mañanera(): print ("Levantate") print ("Estirate") print ("Relajate") print ("Bebe mucha agua") def nombre_completo(): # se pueden guaradar variables dentro de una función nombre = ("Jorge") apellido = (" Rocha") print (nombre + apellido) def saluton(): nomo = "Ludwing" print (f"Saluton, {nomo}") def saluti(Nomo): print(f"Hello, {Nomo}") saluti("Samenhoff") # ----- recicla la función;; dentro del parentesis sustituye a {Nomo} def USUARIO(): estado = "Activo" usantnomo = "Bob" print(f"{usantnomo} is {estado}") def usant_nomo(estas): print(f"Bob: {estas}") usant_nomo("Activista") usant_nomo("Pacifista") def duono(nombro): # Para dividir un número entre 2 micha = nombro / 2 print(micha) def multiplicar(nombro): # Para multiplicar un número entre 2 doble = nombro * 2 print (doble) # --------- Returning values ----------- # Si no se usa el comando 'return' el programa despliega 'None' def age_label(age): label = "User age: " + age return label print(age_label("22")) """ También se puede crear una variable para guardar el resultado Ej: result = age_label("22") print(result) """ def quieroDiez(): return 10 print(quieroDiez()) def enojo(usador): basura = "No te quiero volver a ver" + usador + ". Eres terrible." return basura sal = enojo("Peterson") print(sal) def multiples_operaciones(numero): suma = numero + 96 resta = suma - 529 multiplicación = resta * -24 division = multiplicación / 12 return division # Se puede cambiar 'division' de 'return' y poner cualquier otra operación y no se ejecutaran las acciones que hay después, se detiene en la variable que le asignas a 'return' RESULT = multiples_operaciones(4) def el_doble(chichiton): dos = 2 * chichiton return dos print(el_doble(20)) # ------------ USANDO MULTIPLES PARAMETROS ------------------ def muestra(unua, lasta): print(unua+" "+lasta) muestra("Luffy", "Monkey") # ------------ def create_email(name): return name + "@outlook.com" email = create_email("jonas") print(email) def is_freezing(temperature): return temperature < 0 freezing = is_freezing(6) def display_item_price(item, price): print (f"{item}: ${price}") display_item_price("Chocolate", 4) def generate_username(name, character): return (f"{name}-/&{character}") usantnomo = generate_username("Jal", 482) def get_free_seats(booked, total): return total - booked freeS = get_free_seats(40,56) def Total_score(score, bonus): print(score + bonus) Total_score(623, 96) def error_sum(a,b): return (a+b) using_strings= error_sum("53","20") # Usar strings en lugar de integers generará un error en la operación # se pueden comparar valores # Local scope def add_bonus(SALARY): bonus = 200 print(SALARY + bonus) add_bonus(2096) #Global scope price = 100 for i in range(2): discount = 10 price = price - discount print(f"Discount: {discount}") # DECISIONES CON FUNCIONES def add_shipping(cart): if cart < 200: #cuando se usa una condicional dentro de una función se pone a 2 espacios del borde inicial print (f"Total: {cart + 10}") add_shipping(16) def can_drive(age): if age >= 18: print (f"Tu edad es: {age} por su pollo puedes") else: print(f"Tu edad es: {age} no puedes manejar") can_drive(24) def calculate (operator, x, y): if operator == "+": print(x+y) elif operator == "/": print(x/y) else: print(f"unknown: {operator}") calculate ("/",50,8) def show_status(inbox): if inbox > 606: print("Inbox full!") print("You have new message!") show_status(67) # FUNCIONES + LISTAS def is_multiplayer(players): print(len(players) > 1 ) players = ["Amy", "Rory", "Dr. Donna"] is_multiplayer(players) def movies_forTonight(pelis): print("Airing tonight:") print(pelis) The_list = ["Fido", "Guardians", "Troll hunter"] movies_forTonight(The_list) def booked(passengers): print(len(passengers) > 3) Pasajeros = ["Juny", "Porfirio", "Stan Lee"] booked(Pasajeros) def the_winner(Best_player): winner = Best_player[1] print(f"El mejor del mundo es: {winner}") Players = ["Juny", "Porfirio", "Stan Lee"] the_winner(Players) # PARA SUSTITUIR UN ELEMENTO DE LA LISTA def sustitution_of_player(leaderboard, player): leaderboard[0]=player return leaderboard leaderboard = ["Juny", "Porfirio", "Stan Lee"] leaderboard = sustitution_of_player(leaderboard,"Teresa") print(leaderboard) # DENTRO DE UNA FUNCIÓN SE PUEDEN USAR CULQUIER TIPO DE OPERADORES: count(), sum(), len(), replace() # Loop WHILE def onboard_passengers(bookings): counter = 1 while counter <= bookings: print(f"Passenger {counter} on board") counter += 1 #onboard_passengers(CUALQUIER NÚMERO) def display_progress(total_files): for i in range(total_files): print(f"Downloading file {i} out of {total_files}") display_progress(5) def countdown(counter): while counter > 0: print(counter) counter -= 1 print("Go!") def display_progress(): for i in range(4): print(f"Downloading file {i} out of 3") display_progress() def Luffy(total_files): for i in range(total_files): print(f"Downloading file {i} out of {total_files}") Luffy(3) def halve_price(cart): for price in cart: print(f"New price: {price/2}") cart_list = [69, 369, 19, 24, 50] halve_price(cart_list) def show_next_track(): playlist = ["Hey Jude", "Helter Skelter", "Rosana"] for track in playlist: print(f"Next song: {track}") def next_track(playlist): for track in playlist: print(f"Next song: {track}") songs = ["Hey Jude", "Helter Skelter", "Rosana"] next_track(songs)
330b70a5f8e0ec9d0af07da1422697fcdf5738ef
friedrich-schotte/Lauecollect
/is_method.py
593
3.671875
4
""" Check if method is static https://stackoverflow.com/questions/8727059/python-check-if-method-is-static Author: Friedrich Schotte Date created: 2022-03-28 Date last modified: 2022-03-28 Revision comment: """ __version__ = "1.0" def is_method(f): import types return isinstance(f, types.MethodType) if __name__ == '__main__': # for testing class A: def f(self): return 'this is f' @staticmethod def g(): return 'this is g' a = A() print(f"is_method({a.f}): {is_method(a.f)}") print(f"is_method({a.g}): {is_method(a.g)}")
fcc3df6bede7af239904e6f04332dfe35146e9c1
bhaveshAn/carport
/src/parked_car.py
358
3.609375
4
class ParkedCar(object): def __init__(self, reg_id, slot, colour): """ Class used to create an entry of car to be parked with reg_id [STRING]: registration id slot [INT]: slot number colour [STRiNG]: colour of the car """ self.reg_id = reg_id self.slot = slot self.colour = colour
77e9a95fd36b6b17a3c2a23206bc13f58ddb4cef
Romamart/-Course-work
/Simulation/src/main/blockchain/Block.py
657
3.546875
4
class Block: def __init__(self, previousBlock, mineBy, blockValue): self.__previousBlock = previousBlock self.__height = 0 if previousBlock is None else previousBlock.__height + 1 self.__mineBy = mineBy self.__blockValue = blockValue def getPreviousBlock(self): return self.__previousBlock def getHeight(self): return self.__height def getBlockValue(self): return self.__blockValue def getMinedBy(self): return self.__mineBy def __str__(self): return 'Block[height={0},blockValue={1},minedBy={2}]'.format(self.__height, self.__blockValue, self.__mineBy)
97fbe7d23827a18c5e4b5f2ad79458635cef4c16
dupandit/Datastructure-and-Algorithms
/quicksort.py
984
3.625
4
import sys sys.setrecursionlimit(1500) def partition(arr,start,end): pivot=arr[end] print 'Before Partition : ',arr i=start-1 j=start while j < l: if arr[j]>=pivot : pass else : i=i+1 arr[i],arr[j]=arr[j],arr[i] j=j+1 arr[i+1],arr[end]=arr[end],arr[i+1] print 'After partition :',arr print 'index : ',i+1 return i+1 def Quicksort(arr,low,high): print "Our array is : ", arr if low < high or len(arr)<=1 : l=len(arr) index=partition(arr,low,high) #print index,arr,'1' Quicksort(arr,low,index-1) #l=len(arr) #print index,arr,'2' Quicksort(arr,index+1,high) #while True : # x=raw_input('Enter number and type done at the end\n') # if x == 'done': # break # else : # arr.append(int(x)) #l=len(arr) arr=[60,75,30,80,40,90,120,70] l=len(arr) Quicksort(arr,0,l-1) print arr #partition(arr,arr[l-1])
aace893c2574b7983ef558b15bed5eb73dda8ccd
Location-Artistry/Simple-Stock-Viewer
/StockTicks.py
1,371
3.59375
4
import yfinance as yf import streamlit as st import pandas as pd import datetime as dt import numpy as np today = dt.date.today() # Simple streamlit app using python & yfinance to get information on stock highlighted in selectbox # Working as a streamlit app test deploy to Heroku st.write(""" # Stock Selector ""","""Date:""",today) tickerSymbols = ['JD','BABA','AAPL','TSLA','PFE','XLNX','CLNE','AAPL','NVDA','MAT','AMD','UPWK','ZNGA','ROBO','WORK','GOOGL'] option = st.sidebar.selectbox( 'CHOOSE STOCK TO SHOW INFO', tickerSymbols) tickerDatas = [] tickerDFs = [] def getStock(tickName): stockData = yf.Ticker(tickName) stockHistory = stockData.history(period='ytd') st.write(""" ## SYMBOL: **""", stockData.info['symbol'], """** NAME: **""", stockData.info['shortName'],"""**""") st.write(""" ## Closing Price: """,stockData.info['regularMarketPreviousClose'], """Current Price:""",stockData.info['regularMarketPrice']) st.line_chart(stockHistory.Close) st.write("""Website: """,stockData.info['website'],""" City: """,stockData.info['city'], """ Country: """,stockData.info['country']) st.write("""**RECOMMENDATIONS: **""", stockData.recommendations) st.sidebar.image(stockData.info['logo_url']) #st.sidebar("""**RECOMMENDATIONS: **""") #st.write(stockData.info) getStock(option)
d9d77e9c498f1a109352bf5b712af3f3f408d549
imrehg/AdventOfCode2020
/day06/day06.py
884
3.609375
4
import sys def read_customs_file(filename): declarations = [] with open(filename, "r") as f: buff = [] for line in f.readlines(): if line.strip() == "" and buff: declarations.append(buff) buff = [] else: buff += [{answer for answer in line.strip()}] if buff: declarations.append(buff) return declarations def any_counts(declarations): return sum([len(set.union(*group)) for group in declarations]) def all_counts(declarations): return sum([len(set.intersection(*group)) for group in declarations]) if __name__ == "__main__": input_file = sys.argv[1] declarations = read_customs_file(input_file) result1 = any_counts(declarations) print(f"Result1: {result1}") result2 = all_counts(declarations) print(f"Result2: {result2}")
77311aaf7fe45fb27ba6d1e8f0e9ef7e416d8aa6
croeder/Dataframes-Polyglot
/dataframes.py
604
3.75
4
#!/usr/bin/env python3 import pandas as pd df = pd.read_csv("data.csv") print(type(df)) print(df) print("============1") # key error, this isn't a dictionary in python, so square brackets here don't work #print(type(df[1])) #print(df[1]) print("============2") # column, but they are implemented by column name print(type(df['lname'])) print(df['lname']) print("============3") # row # For some reason, iloc looks like afunction but square brackets print(type(df.iloc[1])) print(df.iloc[1]) print("============4") # row # cell print(type(df.iloc[1,3])) print(df.iloc[1,3]) print("============4")
ecabe706a40628f8c87e4217ca084a044b880af4
DemetreJou/AdventOfCode2018
/13/solution.py
2,552
3.859375
4
import fileinput # first time using a class! # each cart object represents what turn cycle it's on # where it is # has method to move and check collision # define up, down, left, right directions for ease U, D, L, R = (0, -1), (0, 1), (-1, 0), (1, 0) # convert symbols to directions directions = {'^': U, 'v': D, '<': L, '>': R} # maps for directions straight = {U: U, D: D, L: L, R: R} left_turn = {U: L, D: R, L: D, R: U} right_turn = {U: R, D: L, L: U, R: D} forward_slash_turn = {U: R, D: L, L: D, R: U} back_slash_turn = {U: L, D: R, L: U, R: D} class Cart: def __init__(self, p, d): # p and d are in the form (x,y) self.p = p self.d = d self.turns = 0 self.ok = True def step(self, grid): # moves one step self.p = (self.p[0] + self.d[0], self.p[1] + self.d[1]) # adds card to grid c = grid[self.p] # if at intersection figure out turn if c == '+': turn = [left_turn, straight, right_turn][self.turns % 3] # turns are in cycles of 3 self.d = turn[self.d] # apply appropriate turn self.turns += 1 elif c == '/': self.d = forward_slash_turn[self.d] elif c == '\\': self.d = back_slash_turn[self.d] def collide(self, other): # returns True if two cards collide return self != other and self.ok and other.ok and self.p == other.p print('0') # populate the grid grid = {} # grid maps (x, y) positions to characters from the input carts = [] # carts is a list of Cart instances for y, line in enumerate(fileinput.input()): for x, c in enumerate(line): grid[(x, y)] = c if c in directions: carts.append(Cart((x, y), directions[c])) # it solves both parts at same time # easier to run simulation once and just keep track of part 1 while doing part 2 part1 = part2 = None while True: # for each new tick, sort the carts by Y and then X carts = sorted(carts, key=lambda x: (x.p[1], x.p[0])) for cart in carts: # update this cart cart.step(grid) # check for collisions for other in carts: if cart.collide(other): cart.ok = other.ok = False # first collision is our part 1 result part1 = part1 or cart.p # remove carts that crashed carts = [x for x in carts if x.ok] # if only one cart is left, part 2 is done if len(carts) == 1: part2 = carts[0].p break print(part1) print(part2)
637d088be0dd075129ba9732ffb5482038776e8a
DemetreJou/AdventOfCode2018
/9/solution.py
760
3.703125
4
# deque.rotate(n) shifts everything n units to the right from collections import deque import fileinput import re # reads the only two numbers num_players, num_marbles = map(int, re.findall(r'\d+', next(fileinput.input()))) def playgame(num_players, num_marbles): circle = deque([0]) scores = [0] * num_players for i in range(1, num_marbles + 1): if i % 23 == 0: circle.rotate(7) # updates respective score scores[i % num_players] += i + circle.pop() # rotate left by 1 circle.rotate(-1) else: circle.rotate(-1) circle.append(i) return max(scores) print(playgame(num_players, num_marbles)) print(playgame(num_players, num_marbles * 100))
cdf147a2c526c31f8f8850e79d3444bf86d67972
WindTalker22/Data-Structures
/binary_search_tree/tempCodeRunnerFile.py
593
3.578125
4
# Print the value of every node, starting with the given node, # # in an iterative breadth first traversal # def bft_print(self, node): # pass # # Print the value of every node, starting with the given node, # # in an iterative depth first traversal # def dft_print(self, node): # pass # # Stretch Goals ------------------------- # # Note: Research may be required # # Print Pre-order recursive DFT # def pre_order_dft(self, node): # pass # # Print Post-order recursive DFT # def post_order_dft(self, node): # pass
866c36768b1363d7cd4adef7212458a470e6b0fd
kayshale/ShoppingListApp
/main.py
1,196
4.1875
4
#Kayshale Ortiz #IS437 Group Assignment 1: Shopping List App menuOption = None mylist = [] maxLengthList = 6 menuText = ''' 1.) Add Item 2.) Print List 3.) Remove item by number 4.) Save List to file 5.) Load List from file 6.) Exit ''' while menuOption != '6': print(menuText) menuOption = input('Enter Selection\n') print(menuOption) if menuOption == '1': #print('Add Item') item = '' while item == '': item = input("Enter your new item: ") mylist.append(item) #temp = input('Enter Item\n') #mylist.append(temp) print(mylist) elif menuOption == '2': #print(mylist) n = 1 for item in mylist: print (str(n) + ".)" + item) n+=1 #print(mylist) elif menuOption == '3': req = None while req == None: req = input('Enter item number to delete\n') index = None try: index = int(req) - 1 except: print('Invalid Selection') if index >= 0 and index <= 5: del(mylist[index]) else: print('Your selection was not recognized')
a22a1b2aec36a61acffd689b25f8466f2f8446f8
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily17.py
4,155
4.15625
4
""" Suppose we represent our file system by a string in the following manner: The string "dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext" represents: dir subdir1 subdir2 file.ext The directory dir contains an empty sub-directory subdir1 and a sub-directory subdir2 containing a file file.ext. The string "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" represents: dir subdir1 file1.ext subsubdir1 subdir2 subsubdir2 file2.ext The directory dir contains two sub-directories subdir1 and subdir2. subdir1 contains a file file1.ext and an empty second-level sub-directory subsubdir1. subdir2 contains a second-level sub-directory subsubdir2 containing a file file2.ext. We are interested in finding the longest (number of characters) absolute path to a file within our file system. For example, in the second example above, the longest absolute path is "dir/subdir2/subsubdir2/file2.ext", and its length is 32 (not including the double quotes). Given a string representing the file system in the above format, return the length of the longest absolute path to a file in the abstracted file system. If there is no file in the system, return 0. Note: The name of a file contains at least a period and an extension. The name of a directory or sub-directory will not contain a period. """ import time def longest_path_tree(input): files = input.split("\n") fs = {} current_path = [] for f in files: indentations = 0 while '\t' in f: indentations += 1 f = f[1:] current_node = fs for subdir in current_path[:indentations]: current_node = current_node[subdir] if '.' in f: current_node[f] = True else: current_node[f] = {} current_path = current_path[:indentations] current_path.append(f) return fs def count_length(tree): #recursion paths = [] for key, node in tree.items(): if node == True: paths.append(key) else: paths.append(key + '/' + count_length(node)) paths = [path for path in paths if '.' in path] if paths: return max(paths, key=lambda path:len(path)) #returns max based on path length else: return "" def solution1(input): return len(count_length(longest_path_tree(input))) def construct_directory_tree(input): files = input.split("\n") fs = {} current_path = [] max_length = 0 for f in files: indentations = 0 while '\t' in f: indentations += 1 f = f[1:] current_node = fs for subdir in current_path[:indentations]: current_node = current_node[subdir] if '.' in f: current_node[f] = True max_length = sum([len(x) for x in current_path]) + len(f) + indentations else: current_node[f] = {} current_path = current_path[:indentations] current_path.append(f) return max_length def solution2(input): max_length = construct_directory_tree(input) if max_length != 0: return max_length return '' start1 = time.process_time() str = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" print(solution1(str)) time1 = time.process_time()-start1 print(time1) start2 = time.process_time() str = "dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext" print(solution2(str)) time2 = time.process_time()-start2 print(time2) if time1 < time2: print (f'solution1 quicker by {((time2-time1)/time2)*100}%') else: print (f'solution2 quicker by {((time1-time2)/time1)*100}%') # assert solution1("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext") == 20 # # assert solution1("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext") == 32 # # assert solution2("dir\n\tsubdir1\n\tsubdir2\n\t\tfile.ext") == 20 # # assert solution2("dir\n\tsubdir1\n\t\tfile1.ext\n\t\tsubsubdir1\n\tsubdir2\n\t\tsubsubdir2\n\t\t\tfile2.ext") == 32
a576ce778630dca3e72be470b615100b528e2cf8
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily55.py
1,342
3.78125
4
# Implement a URL shortener with the following methods: # shorten(url), which shortens the url into a six-character alphanumeric string, such as zLg6wl. # restore(short), which expands the shortened string into the original url. If no such shortened string exists, return null. # Hint: What if we enter the same URL twice? import random import string class URLShortener: def __init__(self): self.short_to_url = {} self.url_to_short = {} def _generate_short(self): return ''.join(random.choice(string.ascii_lowercase + string.ascii_uppercase + string.digits) for _ in range(6)) def _generate_unused_short(self): t = self._generate_short() while t in self.short_to_url: t = self._generate_short() return t def shorten(self, url): short = self._generate_unused_short() if url in self.url_to_short: return self.url_to_short[url] self.short_to_url[short] = url self.url_to_short[url] = short return short def restore(self,short): return self.short_to_url.get(short, None) shortener = URLShortener() short = shortener.shorten("example.com/vjklasd43") print (short) print (shortener.restore(short)) print (shortener.shorten("example.com/vjklasd43")) print (shortener.shorten("rhys.com/48dkc"))
b0b67fba426642ef56a1cfa5d5e6a65a0286dacb
Rhysoshea/daily_coding_challenges
/other/sort_the_odd.py
612
4.3125
4
''' You have an array of numbers. Your task is to sort ascending odd numbers but even numbers must be on their places. Zero isn't an odd number and you don't need to move it. If you have an empty array, you need to return it. Example sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] ''' def sort_array(source_array): odds = [x for x in source_array if x%2!=0] return [x if x%2==0 else odds.pop() for x in source_array ] assert sort_array([5, 3, 2, 8, 1, 4]) == [1, 3, 2, 8, 5, 4] assert sort_array([5, 3, 1, 8, 0]) == [1, 32, 5, 8, 0] assert sort_array([]) ==[] # sort_array([5, 3, 2, 8, 1, 4])
6a02c3fe5111ddf6690e5a060a543164b2db0563
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily25.py
1,686
4.5
4
""" Implement regular expression matching with the following special characters: . (period) which matches any single character * (asterisk) which matches zero or more of the preceding element That is, implement a function that takes in a string and a valid regular expression and returns whether or not the string matches the regular expression. For example, given the regular expression "ra." and the string "ray", your function should return true. The same regular expression on the string "raymond" should return false. Given the regular expression ".*at" and the string "chat", your function should return true. The same regular expression on the string "chats" should return false. """ def solution(input, regex): regex_alpha = ''.join([x for x in regex if x.isalpha()]) if not regex_alpha in input: return False regex_split = regex.split(regex_alpha) input_split = input.split(regex_alpha) # print (regex_split) # print (input_split) for i, j in zip(regex_split, input_split): if not len(i) == len(j): if '*' in i: if '.' in i: return False continue return False return True def test(input, regex, ans): assert (solution(input, regex) == ans) str1 = "ray" regex1 = "ra." str2 = "raymond" regex2 = ".*at" str3 = "chat" str4 = "chats" str5 = "at" regex3 = ".at" regex4 = "*at." print (solution(str4, regex2)) test(str1, regex1, True) test(str2, regex1, False) test(str3, regex2, True) test(str4, regex2, False) test(str5, regex2, False) test(str5, regex3, False) test(str4, regex4, True) test(str3, regex3, False) test(str3, regex4, False)
be3a184aecc35085a7d69bc447eeaf99d5c2320b
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily44.py
1,329
4.1875
4
# We can determine how "out of order" an array A is by counting the number of inversions it has. Two elements A[i] and A[j] form an inversion if A[i] > A[j] but i < j. That is, a smaller element appears after a larger element. # Given an array, count the number of inversions it has. Do this faster than O(N^2) time. # You may assume each element in the array is distinct. # For example, a sorted list has zero inversions. The array [2, 4, 1, 3, 5] has three inversions: (2, 1), (4, 1), and (4, 3). The array [5, 4, 3, 2, 1] has ten inversions: every distinct pair forms an inversion. def mergeSort(left, right): counter = 0 newArr = [] while left and right: if right[0] < left[0]: newArr.append(right[0]) del right[0] counter += len(left) else: newArr.append(left[0]) del left[0] newArr.extend(left) newArr.extend(right) return newArr, counter def solution (arr, counter): if len(arr)==1: return arr,0 n = len(arr)//2 leftArr,leftCount = solution(arr[:n], counter) rightArr,rightCount = solution(arr[n:], counter) newArr, add = mergeSort(leftArr, rightArr) counter=add+leftCount+rightCount return newArr, counter print (solution([5,4,3,2,1], 0)) print (solution([2,4,1,3,5], 0))
0f01a1e6aa57c4ed9dccf237df27db0465bae2cc
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily27.py
848
4.15625
4
""" Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). For example, given the string "([])[]({})", you should return true. Given the string "([)]" or "((()", you should return false. """ def solution(input): stack = [] open = ["{", "(", "["] close = ["}", ")", "]"] matcher = dict(zip(close,open)) for i in input: # print (stack) if i in open: stack.append(i) elif i in close: if not stack: return False if stack.pop() != matcher.get(i): return False return len(stack) == 0 def test(input, ans): assert (solution(input) == ans) input1 = "([])[]({})" input2 = "([)]" input3 = "((()" test(input1, True) test(input2, False) test(input3, False)
be54b12d47844ada5311c08172c1222c7a84e90c
Rhysoshea/daily_coding_challenges
/leetcode/merge_two_sorted_lists.py
1,187
4.09375
4
""" Merge two sorted linked lists and return it as a new sorted list. The new list should be made by splicing together the nodes of the first two lists. Example: Input: 1->2->4, 1->3->4 Output: 1->1->2->3->4->4 Accepted """ # Definition for singly-linked list. class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next class Solution: def __init__(): pass def mergeTwoLists(l1, l2): """ use nodes in place as they are create a new list by referencing nodes in order """ p = l3 = ListNode(0) while l1 and l2: if l1.val <= l2.val: l3.next = l1 l1 = l1.next else: l3.next = l2 l2 = l2.next l3 = l3.next l3.next = l1 or l2 # collects remaining nodes of any lists that aren't fully referenced return p.next solve = Solution l1 = ListNode(1) l1.next = ListNode(2) l1.next.next = ListNode(4) l2 = ListNode(1) l2.next = ListNode(3) l2.next.next = ListNode(4) # solve.mergeTwoLists(l1,l2) l1 = None l2 = ListNode() print(solve.mergeTwoLists(l1,l2))
1a7a90ea15fe4667345bda7154b3506edc315ba6
Rhysoshea/daily_coding_challenges
/cracking_coding_interview/recursion_dp/triple_step.py
360
3.984375
4
# there are n steps, can take 1,2 or 3 steps at a time # how many different ways are there to get up the steps def staircase(n, X): cache = [0 for x in range(n+1)] cache[0] = 1 for i in range(len(cache)): for x in X: if i-x >= 0: cache[i] += cache[i-x] return(cache[-1]) print (staircase(10, [1,2,3]))
e7bda5729093eb653d5912529dedfd08089fc192
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily22.py
1,974
4
4
""" Given a dictionary of words and a string made up of those words (no spaces), return the original sentence in a list. If there is more than one possible reconstruction, return any of them. If there is no possible reconstruction, then return null. For example, given the set of words 'quick', 'brown', 'the', 'fox', and the string "thequickbrownfox", you should return ['the', 'quick', 'brown', 'fox']. Given the set of words 'bed', 'bath', 'bedbath', 'and', 'beyond', and the string "bedbathandbeyond", return either ['bed', 'bath', 'and', 'beyond] or ['bedbath', 'and', 'beyond']. """ def solution(dict_input, str_input): positions = [] for word in dict_input: print(word) for i, letter in enumerate(str_input): if word == str_input[i:i+len(word)]: positions.append((word,i)) positions = sorted(positions, key=lambda x:x[1]) print(positions) if not positions: return "" if sum([len(x[0]) for x in positions]) > len(str_input): new_positions = [] current_length = 0 print('here') for i, tuple in enumerate(positions): # print (positions[i+1][1]) if current_length > positions[i+1][1]: continue new_positions.append(tuple[0]) current_length += len(tuple[0]) if (i+1) == len(positions): new_positions.append(positions[i+1][0]) i +=1 return [x[0] for x in positions] def test(input, str, ans): assert (solution(input, str) == ans) dict1 = {'quick', 'brown', 'the', 'fox'} str1 = "thequickbrownfox" ans1 = ['the', 'quick', 'brown', 'fox'] dict2 = {'bed', 'bath', 'bedbath', 'and', 'beyond'} str2 = "bedbathandbeyond" ans2 = ['bedbath', 'and', 'beyond'] ans2 = ['bed', 'bath', 'and', 'beyond'] print (solution(dict2, str2)) # test(dict1, str1, ans1) # test(dict2, str2, ans2)
2fc536fe0a6e2100cdafea50d4bbdf27074fb229
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily58.py
1,447
3.765625
4
# An sorted array of integers was rotated an unknown number of times. # Given such an array, find the index of the element in the array in faster than linear time. If the element doesn't exist in the array, return null. # For example, given the array [13, 18, 25, 2, 8, 10] and the element 8, return 4 (the index of 8 in the array). # You can assume all the integers in the array are unique. # doesn't work if list is sorted, assuming rotation has happened def search(arr, num): i = len(arr)//2 dist = i//2 #jumps around at first and narrows down progressively while True: if arr[i] == num: return i elif arr[i] > arr[0] and arr[i-1] > arr[i]: break elif arr[i] > arr[0]: i = i + dist elif arr[i] > arr[i-1]: i = i - dist elif dist == 0: break else: break dist = dist//2 # now perform binary search with offset of i applied low = i high = i - 1 dist = len(arr)//2 while True: if dist == 0: return None x = (low + dist) % len(arr) if arr[x] == num: return x if arr[x] < num: low = (low + dist) % len(arr) elif arr[x] > num: high = (len(arr) + high - dist) % len(arr) dist = dist//2 print (search([13,18,25,2,8,10], 8)) print (search([13,18,25,27,81,100], 81))
830adc77a4c5f9a880b0026f07392e5417664a72
Rhysoshea/daily_coding_challenges
/daily_coding_problems/daily6.py
5,437
4.09375
4
''' An XOR linked list is a more memory efficient doubly linked list. Instead of each node holding next and prev fields, it holds a field named both, which is an XOR of the next node and the previous node. Implement an XOR linked list; it has an add(element) which adds the element to the end, and a get(index) which returns the node at index. If using a language that has no pointers (such as Python), you can assume you have access to get_pointer and dereference_pointer functions that converts between nodes and memory addresses. ''' ''' Daily Coding problem solution ''' import ctypes #provides C compatible data types class Node(object): def __init__(self, val): self.val = val self.both = 0 class XorLinkedList(object): def __init__(self): self.head = self.tail = None self.__nodes = [] # Prevents garbage collection def add(self, node): print ('node: ', node.val) if self.head is None: self.head = self.tail = node else: # the ^, caret symbol is an XOR bitwise operator # print (self.tail.val) # The id() function returns identity of the object. This is an integer which is unique for the given object and remains constant during its lifetime. # print ('id node: ', id(node)) # print ('self tail both: ', self.tail.both) self.tail.both = id(node) ^ self.tail.both # print ('self tail both: ', self.tail.both) node.both = id(self.tail) self.tail = node self.__nodes.append(node) def get(self, index): prev_id = 0 node = self.head for i in range(index): next_id = prev_id ^ node.both if next_id: prev_id = id(node) node = __get_obj(next_id) else: raise IndexError('Linked list index out of range') return node def output_list(self): for n in self.__nodes: print (n.val) def __get_obj(id): # this is the opposite of id() to find out what object is associated to an id number # cast() is used for assigning pointers between a value and a type return ctypes.cast(id, ctypes.py_object).value node1 = Node('A') node2 = Node('B') node3 = Node('C') track = XorLinkedList() for current_node in [node1, node2, node3]: track.add(current_node) # print (track.output_list()) track.output_list() ''' Alternative more involved solution ''' # class ListNode: # def __init__(self, data): # "constructor class to initiate this object" # # # store data # self.data = data # # # store reference (next item) # self.next = None # # # store reference (previous item) # self.previous = None # return # # def has_value(self, value): # "method to compare the value with the node data" # if self.data == value: # return True # else: # return False # # class DoubleLinkedList: # def __init__(self): # "constructor to initiate this object" # # self.head = None # self.tail = None # return # # def list_length(self): # "returns the number of list items" # # count = 0 # current_node = self.head # # while current_node is not None: # # increase counter by one # count = count + 1 # # # jump to the linked node # current_node = current_node.next # # return count # # def output_list(self): # "outputs the list (the value of the node, actually)" # current_node = self.head # # while current_node is not None: # print(current_node.data) # # # jump to the linked node # current_node = current_node.next # # return # # def unordered_search (self, value): # "search the linked list for the node that has this value" # # # define current_node # current_node = self.head # # # define position # node_id = 1 # # # define list of results # results = [] # # while current_node is not None: # if current_node.has_value(value): # results.append(node_id) # # # jump to the linked node # current_node = current_node.next # node_id = node_id + 1 # # return results # # def add_list_item(self, item): # "add an item at the end of the list" # # if isinstance(item, ListNode): # if self.head is None: # self.head = item # item.previous = None # item.next = None # self.tail = item # else: # self.tail.next = item # item.previous = self.tail # self.tail = item # # return # # # # create three single nodes # node1 = ListNode(15) # node2 = ListNode(8.2) # node3 = ListNode("Berlin") # node4 = ListNode(15) # # track = DoubleLinkedList() # print("track length: %i" % track.list_length()) # # for current_node in [node1, node2, node3, node4]: # track.add_list_item(current_node) # print("track length: %i" % track.list_length()) # track.output_list() # results = track.unordered_search(15) # print(results) # # track.remove_list_item_by_id(4) # track.output_list()
644db35d54066608b71f08932348352cc19d3e58
lailson/uri
/python/1020.py
185
3.546875
4
tempo = int(input()) anos = tempo // 365 meses = (tempo % 365) // 30 dias = ( tempo % 365 ) - (30 * meses) print(f'{anos} ano(s)') print(f'{meses} meses(es)') print(f'{dias} dias(s)')
3b2ac1a78612657c7afe392d0e91bdb45149acae
hs929kr/study-algorithm
/basic_algorithm1/11_sum_of_matrix.py
249
3.609375
4
def solution(arr1, arr2): answer = [] for i in range(len(arr1)): row=[] row1=arr1[i] row2=arr2[i] for j in range(len(row1)): row.append(row1[j]+row2[j]) answer.append(row) return answer
8c18b80187b13cbcdbee6c169ad5b311e6ea4f47
hs929kr/study-algorithm
/algorithm5_Hash/03_telephon_number_list.py
409
3.71875
4
from collections import deque def solution(phone_book): answer = True phone_book=sorted(phone_book,key=lambda x:x) phone_book=deque(phone_book) now=phone_book.popleft() while(True): if(len(phone_book)==0): break new=phone_book.popleft() if(new[0:len(now)]==now): answer=False break now=new return answer
246af78ee61f1079a14b08bda5e7361525c296d8
xanwerneck/analisedealgoritmos
/sscm.py
411
3.625
4
def ssctf(lista, n): c = 1 for x in xrange(n-1, 0, -1): if lista[x-1] <= lista[n-1]: d = ssctf(lista, x) if (d+1) > c: c = d + 1 return c def sscm(lista): maior_tamanho = 0 for x in xrange(0,len(lista)): tamanho = ssctf(lista, x + 1) if tamanho >= maior_tamanho: maior_tamanho = tamanho return maior_tamanho maior = sscm([9,5,6,3,9,6,4,7]) print 'Maior subsequencia: ' + str(maior)
593e4d4643c9d81098828b22bc68e46c373ffa2c
pbuzzo/backend-katas-functions-loops
/main.py
1,858
4.375
4
#!/usr/bin/env python """Implements math functions without using operators except for '+' and '-' """ """ """ __author__ = "Patrick Buzzo" def add(x, y): new_num = x + y return new_num def multiply(x, y): new_num = 0 if y >= 0: for index in range(y): new_num += x else: for index in range(-y): new_num -= x return new_num # new_num = 0 # count = 0 # if (x < 0) and (y >= 0): # while count < y: # new_num = new_num + x # count += 1 # elif (x >= 0) and (y < 0): # y = -y # while count < y: # new_num = new_num + x # count += 1 # elif (x >= 0) and (y >= 0): # while count < y: # new_num = new_num + x # count += 1 # elif (x < 0) and (y < 0): # x = -x # y = -y # while count < y: # new_num = new_num + x # count += 1 # return new_num def power(x, n): """Raise x to power n, where n >= 0""" if n == 0: return 1 elif x == 0: return 0 else: new_num = x if n == 1: return x else: for index in range(n-1): new_num = multiply(new_num, x) return new_num def factorial(x): """Compute factorial of x, where x > 0""" new_num = x if x == 0 or x == 1: return 1 if x > 1: count = x - 1 while count > 0: new_num = multiply(new_num, count) count -= 1 return new_num def fibonacci(n): """Compute the nth term of fibonacci sequence Resources: http://bit.ly/2P5asH2 , http://bit.ly/2vOJDji """ a, b = 0, 1 for index in range(n): a, b = b, a + b return a if __name__ == '__main__': # your code to call functions above pass
06c3afda9608357987bb82366928845a7624b102
LifeJunkieRaj/LinkedLists
/LinkedLists/ZipLinkedList.py
1,637
3.96875
4
# This is an input class. Do not edit. class LinkedList: def __init__(self, value): self.value = value self.next = None # O(n) time | O(1) space - where n is the length of the Linked List def zipLinkedList(linkedList): if linkedList.next is None or linkedList.next.next is None: return linkedList firstHalfHead = linkedList secondHalfHead = splitLinkedList(linkedList) reversedSecondHalfHead = reverseLinkedList(secondHalfHead) return interweaveLinkedLists(firstHalfHead, reversedSecondHalfHead) def splitLinkedList(linkedList): slowIterator = linkedList fastIterator = linkedList while fastIterator is not None and fastIterator.next is not None: slowIterator = slowIterator.next fastIterator = fastIterator.next.next secondHalfHead = slowIterator.next slowIterator.next = None return secondHalfHead def interweaveLinkedLists(linkedList1, linkedList2): linkedList1Iterator = linkedList1 linkedList2Iterator = linkedList2 while linkedList1Iterator is not None and linkedList2Iterator is not None: linkedList1IteratorNext = linkedList1Iterator.next linkedList2IteratorNext = linkedList2Iterator.next linkedList1Iterator.next = linkedList2Iterator linkedList2Iterator.next = linkedList1IteratorNext linkedList1Iterator = linkedList1IteratorNext linkedList2Iterator = linkedList2IteratorNext return linkedList1 def reverseLinkedList(linkedList): previousNode, currentNode = None, linkedList while currentNode is not None: nextNode = currentNode.next currentNode.next = previousNode previousNode = currentNode currentNode = nextNode return previousNode
e3c99fec8c179734cefc17df3277ac264051fc76
BohaoTang/Stock
/ShareCompute.py
302
3.765625
4
#!/usr/bin/env python #ShareCompute.py def Profit(shares): if shares: count = 0 profit = 0 for share in shares: profit += share['holdingQuantity'] * share['price_change'] count += 1 return "Profit rate yesterday is :{0}".format(profit / count) else: return "Please choose shares ASAP."
961840f1415ee7b2e6e4698bb4987f6ddde7aeb5
bionboy/SMQ
/Graphical/SMQ_graphical.py
3,592
3.59375
4
from graphics import * win = GraphWin("SMQ", 1000, 500) win.setBackground('green') def textInput (x, y, promptText, x1, y1): textBox = Rectangle(Point(100, 50), Point(900, 150)) textBox.setFill('white') textBox.draw(win) textPrompt = Text(Point(x, y), promptText) textPrompt.draw(win) textField = Entry(Point(x1, y1), 50) textField.draw(win) win.getMouse() textPrompt.undraw() textIn = textField.getText() textBox.undraw() testText = Text(Point(500, 200), textIn) return textIn def errorMessage (): message = "Please input a integer between 0 and 100." textInput(500, 100, message, 500, 400) def SMQ(): data = open('smqLog.txt', 'a') prompt1 = "{Consent} \n Do I have any reason to believe that " + \ "anyone involved here is or would be unwilling? " + \ "[Yes/No]: \n (Click on the window to continue)" LA = textInput(500, 100, prompt1, 500, 400) while LA.isalpha() != True: LA = textInput(500, 100, "Please input yes or no.", 500, 400) while LA.upper() != 'YES' and LA.upper() != 'NO': LA = textInput(500, 100, "Input Yes or no.", 500, 400) while LA.upper() == 'YES': textInput(500, 200, "Any form of sex without consent is immoral.", 500, 400) win.close() data.write('0\n') # data.write('0\n0\n0\n0\n0\n') break else: LAval = 1 while True: try: prompt2 = "If it weren’t sex would I act this way? [0-100]: " MC = int(textInput(500, 100, prompt2, 500, 400)) except ValueError: errorMessage() continue else: break while True: try: prompt3 = "{Exploitation} Would this be happening if " + \ "they weren’t in such a state of misfortune? [0-100]: " SE = int(textInput(500, 100, prompt3, 500, 400)) except ValueError: errorMessage() continue else: break while True: try: prompt4 = "{Third Party} (Am I/Are we) affecting anyone who is not involved? [0-100]: " TP = int(textInput(500, 100, prompt4, 500, 400)) except ValueError: errorMessage() continue else: break while True: try: prompt5 = "{Social Context} (Am I/Are we) reproducing " + \ "or reinforcing broader social injustices? [0-100]: " SC = int(textInput(500, 100, prompt5, 500, 400)) except ValueError: errorMessage() continue else: break smq = LAval * (MC + SE + TP + (SC/2)) # data.write('1\n') # data.write(str(MC) + '\n') # data.write(str(SE) + '\n') # data.write(str(TP) + '\n') # data.write(str(SC) + '\n') data.write(str(smq) + '\n') calculation = str(LAval) + ' * (' + str(MC) + ' + ' + str(SE) + ' + ' + str(TP) + \ ' + (' + str(SC) + '/2))' + ' = ' + str(smq) textInput(500, 200, calculation, 500, 400) data.write('\n') data.close() win.close() SMQ() # add file logging # add an arguement to SMQ() that will either run the questions or show you the data.
c17f7c3412e332cac2664c7ec67f06ae32bf9ccd
splitio/python-client
/splitio/tasks/util/asynctask.py
6,140
3.515625
4
"""Asynchronous tasks that can be controlled.""" import threading import logging import queue __TASK_STOP__ = 0 __TASK_FORCE_RUN__ = 1 _LOGGER = logging.getLogger(__name__) def _safe_run(func): """ Execute a function wrapped in a try-except block. If anything goes wrong returns false instead of propagating the exception. :param func: Function to be executed, receives no arguments and it's return value is ignored. """ try: func() return True except Exception: # pylint: disable=broad-except # Catch any exception that might happen to avoid the periodic task # from ending and allowing for a recovery, as well as preventing # an exception from propagating and breaking the main thread _LOGGER.error('Something went wrong when running passed function.') _LOGGER.debug('Original traceback:', exc_info=True) return False class AsyncTask(object): # pylint: disable=too-many-instance-attributes """ Asyncrhonous controllable task class. This class creates is used to wrap around a function to treat it as a periodic task. This task can be stopped, it's execution can be forced, and it's status (whether it's running or not) can be obtained from the task object. It also allows for "on init" and "on stop" functions to be passed. """ def __init__(self, main, period, on_init=None, on_stop=None): """ Class constructor. :param main: Main function to be executed periodically :type main: callable :param period: How many seconds to wait between executions :type period: int :param on_init: Function to be executed ONCE before the main one :type on_init: callable :param on_stop: Function to be executed ONCE after the task has finished :type on_stop: callable """ self._on_init = on_init self._main = main self._on_stop = on_stop self._period = period self._messages = queue.Queue() self._running = False self._thread = None self._stop_event = None def _execution_wrapper(self): """ Execute user defined function in separate thread. It will execute the "on init" hook is available. If an exception is raised it will abort execution, otherwise it will enter an infinite loop in which the main function is executed every <period> seconds. After stop has been called the "on stop" hook will be invoked if available. All custom functions are run within a _safe_run() function which prevents exceptions from being propagated. """ try: if self._on_init is not None: if not _safe_run(self._on_init): _LOGGER.error("Error running task initialization function, aborting execution") self._running = False return self._running = True while True: try: msg = self._messages.get(True, self._period) if msg == __TASK_STOP__: _LOGGER.debug("Stop signal received. finishing task execution") break elif msg == __TASK_FORCE_RUN__: _LOGGER.debug("Force execution signal received. Running now") if not _safe_run(self._main): _LOGGER.error("An error occurred when executing the task. " "Retrying after perio expires") continue except queue.Empty: # If no message was received, the timeout has expired # and we're ready for a new execution pass if not _safe_run(self._main): _LOGGER.error( "An error occurred when executing the task. " "Retrying after perio expires" ) finally: self._cleanup() def _cleanup(self): """Execute on_stop callback, set event if needed, update status.""" if self._on_stop is not None: if not _safe_run(self._on_stop): _LOGGER.error("An error occurred when executing the task's OnStop hook. ") self._running = False if self._stop_event is not None: self._stop_event.set() def start(self): """Start the async task.""" if self._running: _LOGGER.warning("Task is already running. Ignoring .start() call") return # Start execution self._thread = threading.Thread(target=self._execution_wrapper, name='AsyncTask::' + getattr(self._main, '__name__', 'N/S'), daemon=True) try: self._thread.start() except RuntimeError: _LOGGER.error("Couldn't create new thread for async task") _LOGGER.debug('Error: ', exc_info=True) def stop(self, event=None): """ Send a signal to the thread in order to stop it. If the task is not running do nothing. Optionally accept an event to be set upon task completion. :param event: Event to set when the task completes. :type event: threading.Event """ if event is not None: self._stop_event = event if not self._running: if self._stop_event is not None: event.set() return # Queue is of infinite size, should not raise an exception self._messages.put(__TASK_STOP__, False) def force_execution(self): """Force an execution of the task without waiting for the period to end.""" if not self._running: return # Queue is of infinite size, should not raise an exception self._messages.put(__TASK_FORCE_RUN__, False) def running(self): """Return whether the task is running or not.""" return self._running
de329425df3f2082bbf90c6b1cf98a7d83f373f5
splitio/python-client
/splitio/engine/hashfns/legacy.py
725
3.515625
4
"""Legacy hash function module.""" def as_int32(value): """Handle overflow when working with 32 lower bits of 64 bit ints.""" if not -2147483649 <= value <= 2147483648: return (value + 2147483648) % 4294967296 - 2147483648 return value def legacy_hash(key, seed): """ Generate a hash for a key and a feature seed. :param key: The key for which to get the hash :type key: str :param seed: The feature seed :type seed: int :return: The hash for the key and seed :rtype: int """ current_hash = 0 for char in map(ord, key): current_hash = as_int32(as_int32(31 * as_int32(current_hash)) + char) return int(as_int32(current_hash ^ as_int32(seed)))
c58c08253a70be56d77b540329420a21f7f6bdb8
shreyashetty207/python_internship
/Task 4/Prb 2.py
159
4.375
4
# Create a tuple and print the reverse of the created tuple #create another tuple x = (5, 10, 15, 20) # Reversed the tuple y = reversed(x) print(tuple(y))
8e3f51ca47d9937f5aae6b56f81bfdba273d3336
shreyashetty207/python_internship
/Task 4/Prb1.py
616
4.28125
4
#1. Write a program to create a list of n integer values and do the following #• Add an item in to the list (using function) #• Delete (using function) #• Store the largest number from the list to a variable #• Store the Smallest number from the list to a variable S = [1, 2, 3,4] S.append(56) print('Updated list after addition: ', S) (S .pop(2)) print('Updated list after deletion:',S) # sorting the list S.sort() # printing the largest element print(" Largest element ,x=", max(S)) # sorting the list S.sort() # printing the smallest element print("Smallest element, y=", min(S))
080b45684e8d98e2149bcba8f68fd62e4f763018
shreyashetty207/python_internship
/Task 6.py
2,274
4.09375
4
# Write a program to loop through a list of numbers and add +2 to every value to elements in list num= [1, 2, 3, 4, 5] result = [] for i in range (0,len(num)): result.append(num[i] + 2) print("result:" +str(result)) # write a program in given pattern # 54321 # 4321 # 321 # 21 # 1 for i in range(5,0,-1): for j in range (i,0,-1): print(j, end="") print() # program to print fibonacci sequence def fibbo(n): if n <= 1: return n else: return(fibbo(n-1) + fibbo(n-2)) n = int(input("no of terms:")) if n <= 0: print("Enter a positive integer") else: print("fibonacci sequence:") for i in range(n): print(fibbo(i)) # Python program to check if the number is an Armstrong number or not num = int(input("Enter a number: ")) sum = 0 temp = num while temp > 0: digit = temp % 10 sum += digit ** 3 temp //= 10 if num == sum: print(num,"is an Armstrong number") else: print(num,"is not an Armstrong number") #Multiplication table of 9 in Python num = 9 for i in range(1, 11): print(num, 'x', i, '=', num*i) # tto check number is positive or negative num = float(input("Enter a number: ")) if num > 0: print("Positive number") else: print("Negative number") #convert number of days to ages no_of_days = int(input()) if (no_of_days % 365 == 0): print(f"{no_of_days} Days = ", no_of_days // 365, "Year") else: year = no_of_days // 365 remaining_days = no_of_days % 365 print(f"{no_of_days} Days = ", year, "Year", f"{remaining_days} Days") # solve trignometric function using math function import math as mt print(mt.sin(90),mt.cos(30)) # basic arithmetic calculator n1 = int(input("Enter First Number: ")) n2 = int(input("Enter Second Number: ")) operator = input("Enter Arithmetic Operator: ") if operator == '+': print(n1, "+", n2, "=", n1 + n2) elif operator == '-': print(n1, "-", n2, "=", n1 - n2) elif operator == '*': print(n1, "*", n2, "=", n1 * n2) elif operator == '/': print(n1, "/", n2, "=", n1 / n2) elif operator == '%': print(n1, "%", n2, "=", n1 % n2) else: print("Invalid Operator")
68365d11cc574b9236848dcf1f69b7ba2a9d7ad3
thibaudatl/SoftwareDesign
/homeworks/hw2/FermaFunction.py
706
4
4
# -*- coding: utf-8 -*- """ Created on Tue Sep 14 09:20:49 2014 @author: leo """ def fermat(q, w, e, r): s = q**r f = w**r d = e**r t = s + f print "%d + %d = %d = %d" % (s, f, t, d) if r > 1: if t == d: print 'Fermat was wrong!' else: print "No that doesn't work" else: print 'No that doesnt work, n<2' def ask_inputs(): print "WELCOME TO THE FERMAT CHECKER!\n" q = raw_input('what is a?\n') q = int(q) w = raw_input('what is b?\n') w = int(w) e = raw_input('what is c?\n') e = int(e) r = raw_input('what is n?\n') r = int(r) fermat(q, w, e, r) ask_inputs()
9abd43bb4bceb59b3e0513262f909a1aa2acbce1
frogsicle/abstractr
/abstractr.py
3,560
3.546875
4
""" The whole goal is to make papers more fun to read, but harder to understand =D """ __author__ = 'ali' import random import nltk INTERESTING_TAGS = ['JJ', 'JJR', 'JJS', 'NN', 'NNP', 'NNPS', 'NNS', 'RB', 'RBR', 'RBS', 'VB', 'VBD', 'VBG', 'VBN', 'VBP', 'VBZ'] class Paper(): def __init__(self, text): self.text = text self.tokens = nltk.word_tokenize(text) self.tagged = nltk.pos_tag(self.tokens) self.tagged = [x for x in self.tagged if x[1] in INTERESTING_TAGS] def madlib(self, madtext): madtokens = nltk.word_tokenize(madtext) madtags = nltk.pos_tag(madtokens) madtags = [x for x in madtags if x[1] in INTERESTING_TAGS] max_replace = min(len(self.tagged) / 5, len(madtags)) for i in range(max_replace): current_tag = madtags[i][1] matching_tags = [x for x in self.tagged if x[1]==current_tag] word_to_replace = random.choice(matching_tags) self.text = self.text.replace(word_to_replace[0], madtags[i][0]) # print("replacing: " + word_to_replace[0] + " with: " + madtags[i][0]) def __str__(self): return self.text def test(): thetext = """Abstract BACKGROUND: Gene duplication provides raw material for the evolution of functional innovation. We recently developed a phylogenetic method that classifies evolutionary processes driving the retention of duplicate genes by quantifying divergence between their spatial gene expression profiles and that of their single-copy orthologous gene in a closely related sister species. RESULTS: Here, we apply our classification method to pairs of duplicate genes in eight mammalian genomes, using data from 11 tissues to construct spatial gene expression profiles. We find that young mammalian duplicates are often functionally conserved, and that expression divergence rapidly increases over evolutionary time. Moreover, expression divergence results in increased tissue specificity, with an overrepresentation of expression in male kidney, underrepresentation of expression in female liver, and strong underrepresentation of expression in testis. Thus, duplicate genes acquire a diversity of new tissue-specific functions outside of the testis, possibly contributing to the origin of a multitude of complex phenotypes during mammalian evolution. CONCLUSIONS: Our findings reveal that mammalian duplicate genes are initially functionally conserved, and then undergo rapid functional divergence over evolutionary time, acquiring diverse tissue-specific biological roles. These observations are in stark contrast to the much faster expression divergence and acquisition of broad housekeeping roles we previously observed in Drosophila duplicate genes. Due to the smaller effective population sizes of mammals relative to Drosophila, these analyses implicate natural selection in the functional evolution of duplicate genes.""" themadtext = """Scientists have discovered a winged dinosaur - an ancestor of the velociraptor - that they say was on the cusp of becoming a bird. The 6ft 6in (2m) creature was almost perfectly preserved in limestone, thanks to a volcanic eruption that had buried it in north-east China. And the 125-million year-old fossil suggests many other dinosaurs, including velociraptors, would have looked like "big, fluffy killer birds". But it is unlikely that it could fly.""" paper = Paper(thetext) paper.madlib(themadtext) print(paper) if __name__ == "__main__": test() # todo: get
7d61a5d609915587cbc22b9397f1f19706e61a69
MJAFort/SoftwareDesign
/hw02/problem3.5b.py
749
3.5625
4
# -*- coding: utf-8 -*- """ Created on Mon Feb 3 02:39:33 2014 @author: madeleine """ def make_grid(): #starting the function rows = "|" horiz = ("+" + "----" + "+" + "----" + "+" + "----"+"+" +"----"+"+") side = (rows + " " + rows + " " + rows + " " + rows + " " + rows) print horiz print side print side print side print side print horiz print side print side print side print side print horiz print side print side print side print side print horiz print side print side print side print side print horiz make_grid()
ea780b1776ff950bbd1037e90c42cf6e520ac87b
alvinwan/materials
/src/problems/modulararithmetic/extended-gcd.py
318
3.5625
4
def extended_gcd(x, y): print('x:', x, 'y:', y) if y == 0: ### start a ### return (x, 1, 0) ### end a ### else: ### start b ### d, a, b = extended_gcd(y, x % y) print('d:', d, 'a:', a, 'b:', b) return (d, b, a - (x // y)*b) ### end b ###
424d810d8f77e5d0a2aed7eb5d750ca8e3ac4b11
huderlem/ToadsTool
/util.py
1,480
3.5625
4
# This file holds various utility functions. import os import sys quiet = False def print_info(message): """ Prints informational content to the console. """ if not quiet: print(message) def fatal_error(message): """ Exits the program with the given error message. """ sys.exit("ERROR: %s" % message) def assert_dir_exists(directory): """ Checks if the given directory exists. If it doesn't, then the program is terminated. """ if not os.path.isdir(directory): fatal_error("Directory '%s' doesn't exist." % directory) def assert_dirs_exist(*directories): """ Checks if the given directories exist. If any doesn't, then the program is terminated. """ for directory in directories: assert_dir_exists(directory) def assert_file_exists(filepath): """ Checks if the given filepath exists. If it doesn't, then the program is terminated. """ if not os.path.exists(filepath): fatal_error("File '%s' doesn't exist." % filepath) def read_c_ascii_string(buff, offset): """ Reads a C-style (null-terminated) string from a buffer decoded as ASCII. """ s = "" while buff[offset] != 0: s += chr(buff[offset]) offset += 1 return s def to_c_ascii_string(value): """ Converts a Python string to a C-style (null-terminated) ASCII bytearray. """ s = bytearray(value, 'ASCII') s.append(0) return s
dd70e9c9291611fd469418fef7df160b818c851e
terriwong/underpaid-customers
/find_underpaid_customer.py
660
3.859375
4
def underpaid_customer(): """go through every line in the log to find underpaid customer""" melon_cost = 1 the_file = open("customer-orders.txt") for line in the_file: tokens = line.split("|") customer_name = tokens[1] customer_melon = tokens[2] customer_paid = tokens[3] customer_expected = customer_melon * melon_cost if customer_expected != customer_paid: customer_paid = float(customer_paid) customer_expected = float(customer_expected) print customer_name, "paid {:.2f}, expected {:.2f}".format(customer_paid, customer_expected) underpaid_customer()
4ff05ce103e2efb079454848662ca09b080016c8
omkumar40/Python-Learning
/sp.py
565
3.625
4
#program to find the sum and average in an web page of span element from urllib.request import urlopen from bs4 import BeautifulSoup import ssl ctx = ssl.create_default_context() ctx.check_hostname = False ctx.verify_mode = ssl.CERT_NONE #url=http://py4e-data.dr-chuck.net/comments_862639.html url = input('Enter - ') html = urlopen(url, context=ctx).read() soup = BeautifulSoup(html, "html.parser") tags=soup('span') num=list() for tag in tags: num.append(tag.contents[0]) num=list(map(int,num)) print('Count',len(num)) print('Sum',sum(num))
ac595131e11cb058b77fab48a955d96d971f28f0
micdean19/MNIST-Fashion-Covnet-Mini-Project
/train-model.py
2,787
3.546875
4
# %% import tensorflow as tf import tensorflow.keras as keras import matplotlib.pyplot as plt import pandas as pd import pickle # Importing the MNIST data and preprocessing it from API (x_train, y_train), (x_test, y_test) = keras.datasets.fashion_mnist.load_data() print(x_train.shape, y_train.shape, x_test.shape,y_test.shape) # Class labels class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat', 'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot'] # %% # Splitting training set into training and validation and also feature scaling the images (including the test set) # Will be using 5% of training set as validation x_train, x_valid, x_test= x_train[3000:]/255.0, x_train[:3000]/255, x_test/255.0 y_train, y_valid = y_train[3000:], y_train[:3000] # Model model = keras.models.Sequential([ # Usually i'd reccomend doing a few convolution and pooling for larger images. # however those are already reduced and simplified so just flatten and scale. keras.layers.Flatten(input_shape = [28,28]), keras.layers.Dense(256, activation="relu"), keras.layers.Dense(128, activation = "relu"), keras.layers.Dense(32, activation = "relu"), # Since the classes are mutually exclusive (can only have 1 for each picture, use softmax) keras.layers.Dense(len(class_names), "softmax") ]) # Compile the model (As well as assigning hyperparameters such as cost function, which optimizer, learnign rate..etc) model.compile(loss = "sparse_categorical_crossentropy", # Generic Cost functions for CNN optimizer = keras.optimizers.SGD(learning_rate=0.02), # Using Stochastic Gradient descent with a 0.2 learning rate metrics = ['accuracy']) # Creating model trained_model = model.fit(x=x_train, y=y_train, epochs = 30, # Just based trial and error, 30 seemed to be fine as it's about to converge. # Anything higher seems to be overfitting. And anything below isn't as accurate. validation_data=(x_valid, y_valid)) # %% Result print(model.evaluate(x_test,y_test)) # %% Saving Figures and Exporting model # Layers Overview keras.utils.plot_model(model, to_file="CNN model.png", show_shapes=True) # Cost and Accuracy at each epoch pd.DataFrame(trained_model.history).plot(figsize=(8,5)) plt.gca().set_ylim(0,1) plt.title("Cost/Accuracy Chart for training and validation set as a function of epochs") plt.savefig("processing.png") # Exporting model and predictions predictions = model.predict(x_test) model.save('Keras_CNN_model.h5') with open("variable.pkl", "wb") as f: pickle.dump([predictions, x_test, y_test],f)
0487862c2daa0792a0c4b57cadbff95a3429cba0
mf-2021/python_tutorial
/py_tuto_5.py
4,203
3.625
4
# 5.1 リストについての補足 # a = [66.25, 333, 333, 1, 1234.5] # print(a.count(333), a.count(66.25), a.count('x')) # a.insert(2, -1) # a.append(333) # print(a) # print(a.index(333)) # a.remove(333) # print(a) # a.reverse() # print(a) # a.sort() # print(a) # a.pop() # print(a) # 5.1.1 リストをスタックとして使う # stack = [3, 4, 5] # stack.append(6) # stack.append(7) # print(stack) # print(stack.pop()) # print(stack) # print(stack.pop()) # print(stack.pop()) # print(stack) # 5.1.2 リストをキューとして使う # from collections import deque # queue = deque(["Eric", "John", "Michael"]) # queue.append("Terry") # print(queue) # queue.append("Graham") # print(queue.popleft()) # print(queue.popleft()) # print(queue) # 5.1.3 リスト内包 # squares = [] # for x in range(10): # squares.append(x**2) # print(squares) # squares = list(map(lambda x: x**2, range(10))) # print(squares) # squares = [x**2 for x in range(10)] # print(squares) # print([(x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x != y]) # combs = [] # for x in [1, 2, 3]: # for y in [3, 1, 4]: # if x != y: # combs.append((x, y)) # print(combs) # vec = [-4, -2, 0, 2, 4] # print([x*2 for x in vec]) # print([x for x in vec if x >= 0]) # print([abs(x) for x in vec]) # freshfruit = [' banana ', ' loganberry ', 'passion fruit '] # print([weapon.strip() for weapon in freshfruit]) # print([(x, x**2) for x in range(6)]) # # print(x, x**2 for x in range(6)) # vec = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] # print([num for elem in vec for num in elem]) # from math import pi # print([str(round(pi, i)) for i in range(1, 6)]) # 5.1.4 入れ子のリスト内包 # matrix = [ # [1, 2, 3, 4], # [5, 6, 7, 8], # [9, 10, 11, 12] # ] # print([[row[i] for row in matrix] for i in range(4)]) # transposed = [] # for i in range(4): # transposed.append([row[i] for row in matrix]) # print(transposed) # transposed = [] # for i in range(4): # transposed_row = [] # for row in matrix: # transposed_row.append(row[i]) # transposed.append(transposed_row) # print(transposed) # print(list(zip(*matrix))) # del文 # a = [-1, 1, 66.25, 333, 333, 1234.5] # del a[0] # print(a) # del a[2:4] # print(a) # del a[:] # print(a) # del a # print(a) # 5.3 タブルとシーケンス # t = 12345, 54321, 'hello!' # print(t[0]) # print(t) # u = t, (1, 2, 3, 4, 5) # print(u) # # t[0] = 88888 # v = ([1, 2, 3], [3, 2, 1]) # print(v) # empty = () # singleton = 'hello', # print(len(empty)) # print(len(singleton)) # print(singleton) # 集合(set) # basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} # print(basket) # print('orange' in basket) # print('crabgrass' in basket) # a = set('abracadabra') # b = set('alacazam') # print(a) # print(a - b) # print(a | b) # print(a & b) # print(a ^ b) # a = {x for x in 'abracadabra' if x not in 'abc'} # print(a) # 5.5 ディクショナリ # tel = {'jack': 4098, 'sape': 4139} # tel['guido'] = 4127 # print(tel) # print(tel['jack']) # del tel['sape'] # tel['irv'] = 4127 # print(tel) # print(list(tel.keys())) # print(sorted(tel.keys())) # print('guido' in tel) # print('jack' not in tel) # print(dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])) # print({x: x**2 for x in (2, 4, 6)}) # print(dict(sape=4139, guido=4127, jack=4098)) # 5.6 ループのテクニック # knights = {'gallahad': 'the pure', 'robin': 'the brave'} # for k, v in knights.items(): # print(k, v) # for i, v in enumerate(['tic', 'tac', 'toe']): # print(i, v) # questions = ['name', 'quest', 'favorite color'] # answers = ['lancelot', 'the holy grail', 'blue'] # for q, a in zip(questions, answers): # print('What is your {0}? It is {1}.'.format(q, a)) # for i in reversed(range(1, 10, 2)): # print(i) basket = {'apple', 'orange', 'apple', 'pear', 'orange', 'banana'} for f in sorted(set(basket)): print(f) import math raw_data = [56.2, float('NaN'), 51.7, 55.3, 52.5, float('NaN'), 47.8] filtered_data = [] for value in raw_data: if not math.isnan(value): filtered_data.append(value) print(filtered_data)
0ea59dff442189f4f05326f201bf1b783a294930
janeite/learnpythonthehardway
/Ex15_reading_files.py
366
3.890625
4
#coding=UTF-8 #导入sys中的参数 #from sys import argv #分解两个参数 #script,filename = argv #函数open(文件名,打开权限) #txt = open(filename) #print "Here is your file %r:" % filename #read()读出文件内容 #print txt.read() print "Type the filename again:" file_again = raw_input(">") txt_again = open(file_again) print txt_again.read()
4baf15d94bb722e6233b901d421738e9ab6cdfef
ZiadGold/good_morning
/good_morning.py
98
3.84375
4
msg = input("Good Morning") if msg.lower() == "good morning": print(":)") else: print("-_-")
842925c8114b2ef21081a188beb897c876ff52a0
mgongguy/Daily-Python-Script
/day10/todo
448
3.703125
4
#!/usr/bin/env python import sys from array import * print "*" * 60 print "Todo List - Version 1.0" print "Mark Gong-Guy" print "*" * 60 #Initalizes todo list array todo_list = [] while 1 == 1: for todo in todo_list: print "Todo Item : ", todo choose = raw_input("New item(n) or quit(q):") if choose == "n": newItem = raw_input("New todo item: ") todo_list.append(newItem) if choose == "q": sys.exit()
d62c4c46bd51183ddd687473f6b94fc0c3498f5b
mgongguy/Daily-Python-Script
/day11/budget
984
3.703125
4
#! /usr/bin/env python import sys from array import * print "*" * 60 print "Personal Budget - Version 1.0" print "Mark Gong-Guy" print "*" * 60 #Global Variables balance = raw_input("Enter current balance: ") running = 1 ntrans = [] #Functions def addTrans(name): ntrans.append(name) print "Added: ", name def remTrans(pos): del ntrans[pos] print "Deleted Item #", pos #Menu Item while running == 1: print "Current Balance: $", balance print "*" * 60 print "Transaction Name" print '\n'.join(ntrans) print "*" * 60 print "Add Transaction - 1" print "Remove Transaction - 2" print "Quit - 3" entered = input("Enter Option(1-3):") if entered == 1: enteredName = raw_input("Name of transaction: ") addTrans(enteredName) if entered == 2: enteredLoc = input("What transaction number would you like to remove: ") remTrans(enteredLoc) if entered == 3: sys.exit()
c5d047304387c73bf2d52deb855dba19a2754eb4
brityboy/python-workshop
/day3/test_lecture.py
706
3.859375
4
import unittest from lecture import foo, median_after_throwing_out_outliers class ScratchTests(unittest.TestCase): def test_foo(self): expected = 7 result = foo(6) self.assertEqual(expected, result) def test_foo_negative_numbers(self): expected = -7 result = foo(-8) self.assertEqual(expected, result) def test_median(self): l = [1, 3, 5] expected = 3 result = median_after_throwing_out_outliers(l) self.assertEqual(expected, result) def test_median_even(self): l = [1, 3, 5, 7] expected = 4 result = median_after_throwing_out_outliers(l) self.assertEqual(expected, result)
55dca8c77d3eed88301fd93979dbd1b6b4ad657f
brityboy/python-workshop
/day2/exchange.py
2,914
4.125
4
# def test(): # return 'hello' # this is the game plan # we are going to make # a function that will read the data in # built into this, we are going to make functions that # 1. creates a list of the differences <- we will use from collections # Counter in order to get the amounts # 2. We are going to create a function MAX that gets the max differences # and saves the date # 3. Clearly, we need a function that will read the data # 4. and a function that will hold all of the other functions and # print everything properly # def exchange_rate_csv_reader(filename): # ''' # INPUT: csv file of exchange rate data # OUTPUT: list of changes between exchange rates day to day # this file skips bank holidays # ''' # with open(filename) as f: # result = [] # line_info = [] # todaysrate = 0 # for i, line in enumerate(f): # if 'Bank holiday' not in line: # line_info = line.replace(',', ' ').split() # if i == 4: # todaysrate = round(float(line_info[2]), 2) # elif i > 4 and len(line_info)==4: # result.append(round(todaysrate - round(float(line_info[2]), 2), 2)) # todaysrate = round(float(line_info[2]), 2) # return result def exchange_rate_csv_reader(filename): ''' INPUT: csv file of exchange rate data OUTPUT: list of changes between exchange rates day to day this file skips bank holidays ''' with open(filename) as f: differences = [] dates = [] line_info = [] result = [] todaysrate = 0 for i, line in enumerate(f): if 'Bank holiday' not in line: line_info = line.replace(',', ' ').split() if i == 4: todaysrate = round(float(line_info[2]), 2) elif i > 4 and len(line_info)==4: differences.append(round(todaysrate - round(float(line_info[2]), 2), 2)) dates.append(line_info[0]) todaysrate = round(float(line_info[2]), 2) result.append(differences) result.append(dates) return result def summarize_csv_info(list): ''' INPUT: list of exchange rate differences OUTPUT: summarized count information as a string ''' from collections import Counter info_dict = dict(Counter(list[0])) sortedkeys = sorted(info_dict.keys()) result = '' print_line = '{}: {}\n' for key in sortedkeys: result += print_line.format(key, info_dict[key]) return result def get_max_change(list): ''' INPUT: list of lists where list[0]=inter-day changes and list[1]=date OUTPUT: string indicating max change and date of max change ''' max_change = max(list[0]) indices = [i for i, x in enumerate(list[0]) if x == max_change] for index in indices:
fbf19ba46bc93a50dac5dd82c8a425c116b27254
Kokitis/pyregions
/pyregions/utilities/table_column_utilities.py
7,514
3.6875
4
from typing import List, Union, Tuple, Iterable, Any from itertools import filterfalse from pyregions.standard_definition import RequiredColumns def parse_keywords(columns: Iterable[Any], candidates: List[str]): """ Matches values in `columns` that are present in `candidates` Parameters ---------- columns: Iterable[str] A list of the columns in the table. candidates: List[str] A list of the possible column names that hold the desired information. Ex. `country`, `regionName`, `countryName` to extract the column with the region's name """ candidates = [col for col in columns if col in candidates] if len(candidates) == 0: value = None else: value = candidates[0] return value def is_number(value: Union[int, float, str]) -> bool: """ Checks if a value is a numeric type or if all characters in the string are digits. Parameters ---------- value: int, float, str """ is_numeric_type = isinstance(value, (int, float)) is_all_digit = is_numeric_type or (isinstance(value, str) and value.isdigit()) return is_all_digit def separate_table_columns(columns: List[Any]) -> Tuple[List[Any], List[Any]]: """ Separates a list of columns into 'years' and 'other'. The `years` list conserves the column type as represented in the original table. Parameters ---------- columns: list<str,int> The column list. Year columns may be represented by either number or strings of numeric digits. Returns ------- years, other_columns: Tuple[List[Any], List[Any]] """ years = filter(is_number, columns) other_columns = filterfalse(is_number, columns) return list(years), list(other_columns) def _getColumnName(columns, keys): if len(keys) == 0: return None elif len(keys) == 1: return keys[0] if keys[0] in columns else None elif keys[0] in columns: return keys[0] else: return _getColumnName(columns, keys[1:]) def get_required_columns(table_columns: Iterable[Any], **kwargs)->RequiredColumns: """ Attempts to retrieve the required columns that are needed to import a table into the database. Parameters ---------- table_columns: Iterable[Any] Keyword Arguments ----------------- - `regionCodeColumn` - `regionNameColumn` - `seriesCodeColumn` - `seriesNameColumn` - `seriesNoteColumn` - `unitNameColumn` - `unitCodeColumn` - `scaleColumn` - `seriesDescriptionColumn` """ region_code_column = parse_keywords(table_columns, [ 'regionCode', 'countryCode', 'isoCode', 'fipsCode', 'stateCode', kwargs.get('regionCodeColumn') ]) region_name_column = parse_keywords(table_columns, [ 'regionName', 'countryName', 'state', 'countyName', 'cityName', kwargs.get('regionNameColumn') ]) series_code_column = parse_keywords(table_columns, [ 'seriesCode', 'subjectCode', 'variable', 'subjectCodeColumn', 'subjectCodeColumn', 'seriesCodeColumn', kwargs.get('seriesCodeColumn') ]) series_name_column = parse_keywords(table_columns, [ 'seriesName', 'subjectName', 'subjectNameColumn', 'seriesNameColumn', kwargs.get('seriesNameColumn') ]) series_note_column = parse_keywords(table_columns, [ 'notes', 'subjectNotes', 'seriesNotes', kwargs.get('seriesNoteColumn') ]) series_scale_column = parse_keywords(table_columns, [ 'scale', 'multiplier', 'seriesScale', kwargs.get('scaleColumn') ]) series_unit_name_column = parse_keywords(table_columns, [ 'units', 'unit', 'Unit', 'Units', 'seriesUnit', 'seriesUnits', 'subjectUnits', 'subjectUnit', kwargs.get('unitNameColumn') ]) series_unit_code_column = parse_keywords(table_columns, [ 'unitCode', 'seriesUnitCode', kwargs.get('unitCodeColumn') ]) series_description_column = parse_keywords(table_columns, [ 'seriesDescription', 'subjectDescription', 'description', kwargs.get('seriesDescriptionColumn') ]) series_tag_column = parse_keywords(table_columns, [ 'seriesTags', 'subjectTags', 'tags' ]) result = RequiredColumns( region_code_column, region_name_column, series_code_column, series_name_column, series_note_column, series_scale_column, series_unit_name_column, series_unit_code_column, series_description_column, series_tag_column ) return result def column_heuristic(columns, **kwargs): """ Classifies the key columns that *must* be present in order to import a spreadhseet. Parameters ---------- columns: list<str> The columns present in the table. Keyword Arguments ----------------- Notes ----- This method identifies which columns contain information related to the region and subject. """ detected_columns = get_required_columns(columns, **kwargs) region_code_column = detected_columns['regionCodeColumn'] region_name_column = detected_columns['regionNameColumn'] series_code_column = detected_columns['seriesCodeColumn'] series_name_column = detected_columns['seriesNameColumn'] series_note_column = detected_columns['seriesNoteColumn'] series_tag_column = detected_columns['seriesTagColumn'] series_unit_column = detected_columns['seriesUnitNameColumn'] series_scale_column = detected_columns['seriesScaleColumn'] series_description_column = detected_columns['seriesDescriptionColumn'] # Check if any selection methods were included as kwargs _region_code_column_keyword = kwargs.get('regionCodeColumn') _region_name_column_keyword = kwargs.get('regionNameColumn') _series_code_column_keyword = kwargs.get('seriesCodeColumn', kwargs.get('subjectCodeColumn')) _series_name_column_keyword = kwargs.get('seriesNameColumn', kwargs.get('subjectNameColumn')) # Check if any of the column keywords is overridden by kwargs. if _region_code_column_keyword: region_code_column = _region_code_column_keyword if _region_name_column_keyword: region_name_column = _region_name_column_keyword if _series_code_column_keyword: series_code_column = _series_code_column_keyword if _series_name_column_keyword: series_name_column = _series_name_column_keyword series_note_map = kwargs.get('seriesNoteMap') series_tag_map = kwargs.get('seriesTagMap') series_description_map = kwargs.get('seriesDescriptionMap') series_scale_map = kwargs.get('seriesScaleMap') series_unit_map = kwargs.get('seriesUnitMap') if series_note_map: series_note_column = series_note_map if series_tag_map: series_tag_column = series_tag_map if series_description_map: series_description_column = series_description_map if series_scale_map: series_scale_column = series_scale_map if series_unit_map: series_unit_column = series_unit_map column_config = { 'regionCodeColumn': region_code_column, 'regionNameColumn': region_name_column, 'seriesCodeColumn': series_code_column, 'seriesNameColumn': series_name_column, 'seriesNoteColumn': series_note_column, 'seriesTagColumn': series_tag_column, 'seriesDescriptionColumn': series_description_column, 'seriesScaleColumn': series_scale_column, 'seriesUnitColumn': series_unit_column, 'seriesNoteMap': series_note_map, 'seriesTagMap': series_tag_map, 'seriesDescriptionMap': series_description_map, 'seriesScaleMap': series_scale_map, 'seriesUnitMap': series_unit_map } return column_config if __name__ == "__main__": pass
a7eccff12bec7115ab2652a9e16630d68f656aa9
Sarah-HP/ed-elect
/scripts/tweet_filter.py
9,013
3.765625
4
#this code filters for tweets related to education and college #affordability and outputs csvs of education tweets, affordability #tweets, and csvs of the percentage of tweets about those subjects #to feed into charts #I've set up the file names with ../data in the expectation the #program is run while in the scraping folder (this is a copy that I #put in the scripts folder) #import packages import csv from operator import itemgetter #Read in Tweets from aggregated csv of all candidate tweets with open('aggregated.csv','r') as f: reader = csv.DictReader(f) rows = list(reader) #make list to throw those tweets in tweets = [] #Make each tweet a dictionary in a list of dictionaries for row in rows: tweets.append(dict(row)) #filter to education tweets edu_tweets = [] #Make list of terms to search for to classify this as an #education Tweet: #I came up with these terms by first thinking of common ones, #then reading through tweets for ideas #then checking how the filter did and adjusting/adding terms to #improve performance edu_terms = ['Education', 'Parkland', 'school', 'teacher', 'student', 'Sandy Hook', 'Newtown', 'Columbine', 'Stoneman Douglas', '#edpolicy', '#edreform', '#ESSA', '#putkidsfirst', '#achievementgap', '#edgap', '#literacy', '#nclb', '#essea', 'college', 'devos', 'highered', 'tuition', 'pre-k', 'kindergarten', 'achievement gap', 'K-12', 'k12', '#parentalchoice', '#parentpower', '#titleix', 'Title ix'] #search through all tweets' text and add the ones with text from the term list to a new list for tweet in tweets: for term in edu_terms: #use lower case everything so that case won't matter if term.lower() in tweet[' Tweet Text'].lower(): edu_tweets.append(tweet) #break so that a tweet won't get added multiple times #if it has multiple terms (I wish I could say I thought) #of that in advance) break #write the list of educational tweets to a csv attrib = edu_tweets[0].keys() with open('edu_tweets.csv','w') as f: d_wr = csv.DictWriter(f, attrib) d_wr.writeheader() d_wr.writerows(edu_tweets) #filter the educational tweets to ones dealing with college #affordability--sorry for the mess of terms #I didn't want generic uses of "college", for example, #to get added to this, so I required mixes of terms, except #for some specific stuff (e.g. Pell Grant, Bloomberg's #hashtag ActivateTalent about a college affordability program) #that could only really be about college affordability #I came up with these terms by first thinking of common ones, #then reading through tweets for ideas #then checking how the filter did and adjusting/adding terms to #improve performance #make empty list to put tweets in college_aff_tweets = [] #loop through tweets to look for terms for tweet in edu_tweets: if ('afford' in tweet[' Tweet Text'].lower()) and ('higher education' in tweet[' Tweet Text'].lower() or 'college' in tweet[' Tweet Text'].lower() or 'university' in tweet[' Tweet Text'].lower() or 'education' in tweet[' Tweet Text'].lower() or 'tuition' in tweet[' Tweet Text'].lower()): college_aff_tweets.append(tweet) #all these things could've gone in one long if statement, but #it involved too much scrolling right and this might save #some computing power I think if the first statement #happens to be true else: if ('tuition' in tweet[' Tweet Text'].lower()) and ('higher education' in tweet[' Tweet Text'].lower() or 'college' in tweet[' Tweet Text'].lower() or 'university' in tweet[' Tweet Text'].lower() or 'education' in tweet[' Tweet Text'].lower() or 'free' in tweet[' Tweet Text'].lower()): college_aff_tweets.append(tweet) else: if ('free' in tweet[' Tweet Text'].lower()) and ('college' in tweet[' Tweet Text'].lower() or 'higher education' in tweet[' Tweet Text'].lower() or 'university' in tweet[' Tweet Text'].lower() or 'education' in tweet[' Tweet Text'].lower()): college_aff_tweets.append(tweet) else: if ('student' in tweet[' Tweet Text'].lower()) and ('loan' in tweet[' Tweet Text'].lower() or 'debt' in tweet[' Tweet Text'].lower()): college_aff_tweets.append(tweet) else: if ('cost' in tweet[' Tweet Text'].lower() or 'lower-income' in tweet[' Tweet Text'].lower()) and ('higher education' in tweet[' Tweet Text'].lower() or 'college' in tweet[' Tweet Text'].lower() or 'university' in tweet[' Tweet Text'].lower()): college_aff_tweets.append(tweet) else: if 'pell grant' in tweet[' Tweet Text'].lower(): college_aff_tweets.append(tweet) else: if ('for-profit' in tweet[' Tweet Text'].lower()) and ('school' in tweet[' Tweet Text'].lower() or 'college' in tweet[' Tweet Text'].lower() or 'university' in tweet[' Tweet Text'].lower() or 'higher education' in tweet[' Tweet Text'].lower()): college_aff_tweets.append(tweet) else: if 'financial aid' in tweet[' Tweet Text'].lower(): college_aff_tweets.append(tweet) else: if '#activatetalent' in tweet[' Tweet Text'].lower(): college_aff_tweets.append(tweet) else: if 'loan' in tweet[' Tweet Text'].lower() and ('education' in tweet[' Tweet Text'].lower() or 'college' in tweet[' Tweet Text'].lower() or 'higher education' in tweet[' Tweet Text'].lower()): college_aff_tweets.append(tweet) #Write affordability tweets to CSV #used this when writing summary of candidate positions with open('college_aff_tweets.csv','w') as f: d_wr = csv.DictWriter(f, attrib) d_wr.writeheader() d_wr.writerows(college_aff_tweets) #Count tweets about affordability by candidate cand_coll_aff_count = {} for tweet in college_aff_tweets: cand = tweet['Candidate'] if cand in cand_coll_aff_count: cand_coll_aff_count[cand] += 1 else: cand_coll_aff_count[cand] = 1 #Count tweets about education by candidate cand_edu_tweet_count = {} for tweet in edu_tweets: cand = tweet['Candidate'] if cand in cand_edu_tweet_count: cand_edu_tweet_count[cand] += 1 else: cand_edu_tweet_count[cand] = 1 #Count total number of tweets by candidate cand_tweet_count = {} for tweet in tweets: cand = tweet['Candidate'] if cand in cand_tweet_count: cand_tweet_count[cand] += 1 else: cand_tweet_count[cand] = 1 #Create list of lists with list for each candidate with # of aff tweets, # of edu tweets, and # of total tweets #First make list of candidates - there are more efficient #ways of doing this, but just in case there's one with no #tweets about edu or something I'll use the complete list #of aggregated tweets: cand_list=[] for tweet in tweets: cand = tweet['Candidate'] if cand not in cand_list: cand_list.append(cand) #now make list of lists: cand_summary = [] #avoid any key errors in case a candidate has no #entries in either the edu tweet count or aff tweet #count (looking at you, Ojeda): for i in cand_list: if i not in cand_edu_tweet_count: cand_edu_tweet_count[i] = 0 if i not in cand_coll_aff_count: cand_coll_aff_count[i] = 0 #now pull together cand name, edu tweet count, and #college aff tweet count for i in cand_list: cand_summary.append([i, cand_tweet_count[i], cand_edu_tweet_count[i], cand_coll_aff_count[i]]) #Write candidate summary to a CSV #I basically just made this out of curiosity with open('edu_tweet_counts_by_cand.csv','w') as f: writer = csv.writer(f) writer.writerow(['candidate','tweets','education_tweets','college_affordability_tweets']) for j in cand_summary: writer.writerow(j) #Create list with education tweet % for each candidate edu_tweet_perc = [] for i in cand_summary: edu_tweet_perc.append([i[0],i[2]/i[1]]) #Write percentage of educational tweets to tsv as data for #plot of candidate tweet % #this one actually got cut and I ended up using the sorted one #below instead with open ('../data/cand_2020.tsv','w') as f: tsv_writer = csv.writer(f, delimiter = '\t') tsv_writer.writerow(['candidate', 'ed_perc']) for i in edu_tweet_perc: tsv_writer.writerow(i) #sort data by education tweet percentage edu_tweet_perc_sorted = sorted(edu_tweet_perc, key = itemgetter(1)) #Make TSV of same data but sorted alphabetically by candidate #this is what went into the chart we ultimately used on the # 2020 candidates page with open ('../data/cand_2020_sorted.tsv','w') as f: tsv_writer = csv.writer(f, delimiter = '\t') tsv_writer.writerow(['candidate', 'ed_perc']) for i in edu_tweet_perc_sorted: tsv_writer.writerow(i) #Create list with % of educ tweets addressing affordability #for each candidate: aff_over_educ_tweet_perc = [] for i in cand_summary: aff_over_educ_tweet_perc.append([i[0],i[3]/i[2]]) #sort data by affordability tweet percentage aff_over_educ_tweet_perc_sorted = sorted(aff_over_educ_tweet_perc, key = itemgetter(1)) #Write percentage of educational tweets to tsv as data #for plot of candidate tweet % with open ('../data/cand_aff_2020.tsv','w') as f: tsv_writer = csv.writer(f, delimiter = '\t') tsv_writer.writerow(['candidate', 'aff_perc']) for i in aff_over_educ_tweet_perc_sorted: tsv_writer.writerow(i)
5f45056f5ca184fde07e69288e33b67b5c573946
ShadowElf37/2DEquationMapper
/main.py
2,467
3.5625
4
import pygame from math import * def clamp(x, mn=0, mx=255): if x < mn: x = mn elif x > mx: x = mx return x def load_data(): global equation, size, screensize, inputs, screen, vscreensize data = open('equation', 'r').read().split('\n') size = int(data[0]) screensize = vscreensize = int(data[1]) equation = data[2].replace('^', '**') inputs = [] i = -1 for j in range(-size // 2, size // 2 + 1): i += 1 inputs.append([]) for k in range(-size // 2, size // 2 + 1): x = j + k * 1j inputs[i].append(x) screen = pygame.display.set_mode((screensize, screensize)) load_data() def pixel(surface, color, pos): surface.fill(color, (pos, (1, 1))) def calc(): global outputs, inputs outputs = {} for row in inputs: for x in row: r = eval(equation) r = round(r.real)%(screensize) + round(r.imag)%(screensize)*1j if outputs.get(r) is None: outputs[r] = 1 else: outputs[r] += 1 def draw(): screen.fill((0, 0, 0)) for k in outputs.keys(): # Color calculation c = round(outputs[k]**2*10 % 255) b = clamp(abs(c-255//3), mx=255//3)*3 g = clamp(abs(c-255*2//3)-b, mx=255//3)*3 r = clamp(abs(c-255)-g-b, mx=255//3)*3 #print(r,g,b) cl = pygame.Color(r, g, b, 255) s = screensize/2 pixel(screen, cl, (round((k.real-s)*scale+s), round((k.imag-s)*scale+s))) pygame.init() screen = pygame.display.set_mode((screensize, screensize)) clock = pygame.time.Clock() done = False scale = 1 calc() draw() print('Entering loop...') while not done: for event in pygame.event.get(): if event.type == pygame.QUIT: done = True elif event.type == pygame.KEYDOWN: if event.key == pygame.K_r: screen.fill((0, 0, 0)) pygame.display.flip() load_data() print('Inputs reloaded.') calc() print('Output recalculated.') scale = 1 draw() elif event.key == pygame.K_UP: print('Scale up.') scale *= 1.1 draw() elif event.key == pygame.K_DOWN: print('Scale down.') scale *= 0.9 draw() clock.tick(10) pygame.display.flip()
5b495d8513ac730326b12bbc3c673628e14395ff
miranas/python
/funkcije/drzava_u.py
943
3.703125
4
podatki = { "Slovenija":"Ljubljana", "Avstrija":"Dunaj", "Italija":"Rim" } def izpisi_gl_mesto(drzava): return podatki[drzava] def izpisi_drzavo(mesto): for drzava in podatki.keys(): if (mesto == podatki[drzava]): return drzava # else namenoma manjka (da gre zanka naprej) return "Nisem nasel :)" def preveri(mesto, drzava): pravilno_mesto = izpisi_gl_mesto(drzava) return mesto == pravilno_mesto def izpisi_vse(): print podatki if __name__ == "__main__": izpisi_vse() stevilka = 4 print podatki.keys() for drzava in podatki.keys(): a = 3 while a != 0: drzava1 = izpisi_drzavo(mesto) print "D: {}".format(drzava1) pravilno = preveri(mesto, drzava) if pravilno: print "Pravilno" break else: print "Narobe" a -= 1
d53ad7f648e3ad58a7226c607a22734df800c1c8
INF1007-2021A/2021a-c01-ch6-supp-2-exercices-Julien9969
/exercice.py
1,767
3.71875
4
#!/usr/bin/env python # -*- coding: utf-8 -*- import math import copy import itertools def get_even_keys(dictionary): return {k for k in dictionary if k%2==0} def join_dictionaries(dictionaries): return { key : value for d in dictionaries for key, value in d.items() } def dictionary_from_lists(keys, values): return {keys[i] : values[i] for i in range(min(len(keys), len(values)))} # return {dict(zip(keys, values))} # dictionnary.values() --> dict_value avec les valeur du dict # dictionnary.keys() --> dict_key avec les clé du dict __> list() pour convertir def get_greatest_values(dictionnary, num_values): return sorted([n[1] for n in dictionnary.items()], reverse=True )[0:num_values] def get_sum_values_from_key(dictionnaries, key): return sum([d[key] for d in dictionnaries if key in d]) if __name__ == "__main__": yeet = { 69: "Yeet", 420: "YeEt", 9000: "YEET", } print(get_even_keys(yeet)) print() yeet = { 69: "Yeet", 420: "YeEt", 9000: "YEET", } doot = { 0xBEEF: "doot", 0xDEAD: "DOOT", 0xBABE: "dOoT" } print(join_dictionaries([yeet, doot])) print() doh = [ "D'OH!", "d'oh", "DOH!" ] nice = [ "NICE!", "nice", "nIcE", "NAIIIIICE!" ] print(dictionary_from_lists(doh, nice)) print() nums = { "nice": 69, "nice bro": 69420, "AGH!": 9000, "dude": 420, "git gud": 1337 } print(get_greatest_values(nums, 1)) print(get_greatest_values(nums, 3)) print() bro1 = { "money": 12, "problems": 14, "trivago": 1 } bro2 = { "money": 56, "problems": 406 } bro3 = { "money": 1, "chichis": 1, "power-level": 9000 } print(get_sum_values_from_key([bro1, bro2, bro3], "problems")) print(get_sum_values_from_key([bro1, bro2, bro3], "money")) print()
8d8ced3e693b0ba0763dd9b1861c896097bf7f3b
RomeLeader/Project-Euler-Problems
/largest_palindrome_product.py
433
3.96875
4
#!/usr/bin/python def largest_palindrome_product(): current_largest = 0 for i in range(999, 1, -1): for j in range(999, 1, -1): product = i*j if (str(product) == str(product)[::-1]): #Palindrome check on stringified numbers if product > current_largest: current_largest = product print(product) return largest_palindrome_product()
de2d98dd58260e03a19d91e59ef1dc75091de366
suneelkanthala/olympics-data-analysis
/Code_Analysis.py
2,708
3.578125
4
#Importing header files import pandas as pd import numpy as np import matplotlib.pyplot as plt #Path of the file is stored in the variable path data = pd.read_csv(path) #Code starts here # Data Loading data = data.rename(columns={"Total": "Total_Medals"}) #print(data.head(10)) # Summer or Winter data['Better_Event'] = np.where(data['Total_Summer'] > data['Total_Winter'], 'Summer', 'Winter') #print(data.head(10)) # Top 10 def top_ten(df, col): country_list = [] top_t = df.nlargest(10, col) country_list = list(top_t['Country_Name']) return country_list top_countries = data[['Country_Name','Total_Summer', 'Total_Winter','Total_Medals']].copy() #print(top_countries.tail(1)) #top_countries.drop(top_countries.iloc[-1]) top_countries.drop(top_countries.tail(1).index, inplace = True) #print(top_countries.tail(1)) top_10_summer = top_ten(top_countries, 'Total_Winter') top_10_winter = top_ten(top_countries, 'Total_Summer') top_10 = top_ten(top_countries, 'Total_Medals') common = list(set(top_10_summer) & set(top_10_winter) & set(top_10)) print(common) # Plotting top 10 summer_df = data[data['Country_Name'].isin(top_10_summer)] winter_df = data[data['Country_Name'].isin(top_10_winter)] top_df = data[data['Country_Name'].isin(top_10)] # Top Performing Countries ax = summer_df.plot.bar(x='Country_Name', y='Total_Summer', rot=0, figsize=(20,10)) ax = winter_df.plot.bar(x='Country_Name', y='Total_Winter', rot=0, figsize=(20,10)) ax = top_df.plot.bar(x='Country_Name', y='Total_Medals', rot=0, figsize=(20,10)) # Best in the world summer_df['Golden_Ratio'] = summer_df['Gold_Summer'] / summer_df['Total_Summer'] summer_max_ratio = max(summer_df['Golden_Ratio']) summer_country_gold = summer_df.loc[summer_df['Golden_Ratio'].idxmax(),'Country_Name'] winter_df['Golden_Ratio'] = winter_df['Gold_Winter']/winter_df['Total_Winter'] winter_max_ratio = max(winter_df['Golden_Ratio']) winter_country_gold = winter_df.loc[winter_df['Golden_Ratio'].idxmax(),'Country_Name'] top_df['Golden_Ratio'] = top_df['Gold_Total']/top_df['Total_Medals'] top_max_ratio = max(top_df['Golden_Ratio']) top_country_gold = top_df.loc[top_df['Golden_Ratio'].idxmax(),'Country_Name'] data_1 = data[:-1] data_1['Total_Points'] = data_1['Gold_Total'] * 3 + data_1['Silver_Total'] * 2 + data_1['Bronze_Total'] most_pints = max(data_1['Total_Points']) best_country = data_1.loc[data_1['Total_Points'].idxmax(),'Country_Name'] print(most_pints, best_country) # Plotting the best best=data[data['Country_Name']==best_country] best=best[['Gold_Total','Silver_Total','Bronze_Total']] best.plot.bar(stacked=True) plt.xticks(rotation=45) plt.xlabel('United States') plt.ylabel('Medals Tally') plt.show()
06ba577a4a7ae06eb86f33c4eac43a7c7cb9e3ec
brunpersilva/python-treino2
/ex22.py
189
3.921875
4
n = int(input('Digite um número: ')) n1 = str(n) print('unidade: {} '.format(n1[3])) print('dezena: {}'.format(n1[2])) print('centena: {}'.format(n1[1])) print('milhar: {}'.format(n1[0]))
16a69e78c954bdc7407e0cfb1243f93ccc69be66
brunpersilva/python-treino2
/ex5.py
135
3.6875
4
n1= int(input('Qual a sua primeira nota?')) n2= int(input('Qual a sua segunda nota?')) print('A sua média é de:{}'.format((n1+n2)/2))
8c9a9616f3c0766d4b78a550b3d0f0c98f7126ff
brunpersilva/python-treino2
/ex8.py
91
3.984375
4
x=int(input('Digite um número: ')) for i in range(11): print('{}x{}='.format(x,i),i*x)
72f840a7c5240bde039940e66c802a1fd2c2b37a
Shivanshgarg-india/pythonprogramming-day-3
/list comprehesion/question 2.py
148
3.90625
4
# Find all of the words in a string that are less than 5 letters words = string.split(" ") q5_answer = [word for word in words if len(word) < 5]
9ea8bab5006bab192380d8edbdd87aec931654f2
Shivanshgarg-india/pythonprogramming-day-3
/list comprehesion/question 3.py
154
3.828125
4
# Remove all of the vowels in a string string = 'my anme is shivansh ' answer = "".join([char for char in string if char not in ["a","e","i","o","u"]])
cd74e9f3c1a3cfcf339b601d3f1c83884fd27b2e
king1991wbs/WeldSeam
/python/plotwelddata_csv.py
2,449
3.515625
4
#-*- coding:utf-8 -*- """ version: python 2.7.8 win8 x64 author: wilson email: wison_91@foxmail.com date: 20140928 Descriptionl: This python program is aimming at read data from a Excel file,and then plot those data in diagram. copyright reserved by CAD Center of Tongji University """ import csv #import xlrd import matplotlib.pyplot as plt #data_file_name = raw_input('input your data file name with full path:') def plotdata(data_file_name): #data_file_name = 'C:\\Users\\KING\\Desktop\\data_v_i\\20141016_ban1\\数据日志 0 (18).xls' path = unicode(data_file_name, 'utf-8') #path = u'C:\\Users\\KING\\Desktop\\测试.txt' time = []; electricity = []; voltage = []; offset = []#时间,电流,电压,位移 data_csv = open(path, 'rb') csvdatareader = csv.reader(data_csv) csvdatareader.next() for row in csvdatareader: time.append(row[0]) voltage.append(row[1]) electricity.append(row[2]) offset.append(row[3]) data_csv.close() time.reverse(), electricity.reverse(), voltage.reverse(), offset.reverse() ''' data = xlrd.open_workbook(path) #read data from Excel and save it in tables table = data.sheets()[0] #get value of time,voltage and electricity time = range(1, len(table.col_values(0))) #time = [int(table.col_values(0)[t]) for t in range(1, len(table.col_values(0)))] voltage = [int(table.col_values(1)[v]) for v in range(1, len(table.col_values(1)))]#这样得到的数据是逆序的 voltage.reverse() #voltage = [int(v) for v in table.col_values(1)] electricity = [int(table.col_values(2)[e]) for e in range(1, len(table.col_values(2)))] electricity.reverse() ''' fig1 = plt.figure('1') #plt.scatter(voltage, electricity, color='red', marker='.') plt.plot(voltage, label = 'voltage') plt.plot(electricity, label = 'electrictiy') #plt.xlabel('voltage') #plt.ylabel('electricity') plt.xticks(range(0, len(voltage), 5)) plt.yticks(range(0, 110, 5)) plt.xlim(20,250)#限制x轴的区间 plt.grid(True)#绘制背景格子 plt.legend(loc = 'upper left')#设置图例标签显示位置 plt.title('relatioship of v & e') fig1.autofmt_xdate() #plt.savefig('C:\\Users\\KING\\Desktop\\data_v_i\\1.png') plt.show() ''' plt.figure('2') plt.plot(voltage, electricity) plt.xlabel('voltage') plt.ylabel('electricity') plt.title('t & v') plt.figure('3') plt.scatter(time, electricity, color='red', marker='*') plt.xlabel('time') plt.ylabel('electricity') plt.title('t & e') plt.show() '''
b67b1ae1028d01051e0ea355e587aeb928f87a32
yangjiao2/leetcode-playground
/hashtable/560_equal-sum-k-array.py
725
3.578125
4
# Given an array of integers and an integer k, you need to find the total number of continuous subarrays whose sum equals to k. # Example 1: # Input:nums = [1,1,1], k = 2 # Output: 2 class Solution: def subarraySum(self, nums: List[int], k: int) -> int: acc, result = 0, dict() counter = 0 for i in range(len(nums)): num = nums[i] acc += num temp = (len(result[acc - k]) if acc - k in result else 0) temp1 = (1 if acc == k else 0) if acc not in result: result[acc] = [i] else: result[acc].append(i) print(temp, temp1) counter += temp + temp1 return counter
85ff05c6aa5a189ba98df91b0d7ca4689fb3e3a9
yangjiao2/leetcode-playground
/greedy/45_jump-game-1and2.py
974
3.75
4
# Given an array of non-negative integers, you are initially positioned at the first index of the array. # Each element in the array represents your maximum jump length at that position. # Your goal is to reach the last index in the minimum number of jumps. # Example: # Input: [2,3,1,1,4] # Output: 2 class Solution: def jump(self, nums: List[int]) -> int: i = curmax = end = step = 0 for i in range(len(nums) - 1): curmax = max(curmax, i + nums[i]) print(i, end, curmax) if i == end: print('step', step) step += 1 end = curmax return step def canJump(self, nums: List[int]) -> bool: i = curmax = end = step = 0 for i in range(len(nums)): curmax = max(curmax, i + nums[i]) print(i, end, curmax) if i == end: step += 1 end = curmax return end >= len(nums) - 1
acc861f7666ec2291bcdf8ca8720282bf332eff3
Astrolopithecus/Final-Project-prog-120
/Final Project/Miles_Philips_objects_Phase_1.2.py
3,032
3.90625
4
# Miles Philips # Prog 120 # Final ProjectProject Phase 1.2 # objects # 5-31-19 #!/usr/bin/env python3 import random CARDS_CHARACTERS = {"Spades": "♠", "Hearts": "♥", "Diamonds": "♦", "Clubs": "♣"} ########################################################################## ## Definitions for the classes: Card, Deck and Hand ########################################################################## #create Card class class Card: # initialize def __init__(self, rank, suit): self.__rank = rank self.__suit =suit # define value property @property def value(self): if self.__rank == "Ace": v = 11 elif self.__rank in ("Jack", "Queen", "King"): v = 10 else: v = int(self.__rank) return v # define displayCard module def displayCard(self): card = str(self.__rank) + " of " + str(self.__suit) + CARDS_CHARACTERS[self.__suit] return card #create Deck class class Deck: # initialize a deck of 52 cards def __init__(self): self.__deck = [] suits = ["Hearts", "Spades", "Diamonds", "Clubs"] ranks = ["Ace", "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King"] for s in suits: for r in ranks: c = Card(r,s) self.__deck.append(c) # define count property @property def count(self): self.__count = len(self.__deck) return self.__count # define shuffle property def shuffle(self): random.shuffle(self.__deck) # define dealCard property def dealCard(self): return self.__deck.pop() # create Hand class class Hand: # initialize def __init__(self): self.__cards = [] # define count property @property def count(self): count = len(self.__cards) return count # define points property @property def points(self): points = 0 for c in self.__cards: points += c.value return points # define addCard method def addCard(self,card): self.__cards.append(card) return self.__cards # define displayHand method def displayHand(self): for h in self.__cards: h.displayCard() # define main function def main(): print("Cards - Tester") print() # test deck print("DECK") deck = Deck() print("Deck created.") deck.shuffle() print("Deck shuffled.") print("Deck count:", deck.count) print() # test hand print("HAND") hand = Hand() for i in range(4): hand.addCard(deck.dealCard()) hand.displayHand() print() print("Hand points:", hand.points) print("Hand count:", hand.count) print("Deck count:", deck.count) if __name__ == "__main__": main()
6a7e62f9592f2224ce6f7a8821775a12e80a4acd
TheHuessy/KeyLogger
/KeyLogger.py
2,512
3.59375
4
from pynput.keyboard import Listener def write_to_file(key): letter = str(key) letter = letter.replace("'", "") # Need to set up handlers for non-character keys # There are a few of them... if letter == 'Key.space': letter = " " if letter == 'Key.alt': letter = " [alt] " if letter == 'Key.alt_gr': letter = " [alt] " if letter == 'Key.alt_l': letter = " [alt] " if letter == 'Key.alt_r': letter = " [alt] " if letter == 'Key.backspace': with open('KeyLog.txt', mode='r') as rf: te = rf.read() te = te[:-1] with open('KeyLog.txt', mode='w') as bf: bf.write(te) letter = "" if letter == 'Key.caps_lock': letter = " [CAPS] " if letter == 'Key.cmd': letter = " [cmd] " if letter == 'Key.cmd_l': letter = " [cmd] " if letter == 'Key.cmd_r': letter = " [cmd] " if letter == 'Key.ctrl_l': letter = " [ctrl] " if letter == 'Key.ctrl_r': letter = " [ctrl] " if letter == 'Key.delete': letter = "[delete] " if letter == 'Key.down': letter = " [down] " if letter == 'Key.end': letter = " [end] " if letter == 'Key.enter': letter = "\n" if letter == 'Key.esc': letter = " [esc] " if letter == 'Key.f1': letter = " [F1] " if letter == 'Key.home': letter = " [home] " if letter == 'Key.insert': letter = " [ins] " if letter == 'Key.left': letter = " [left] " if letter == 'Key.menu': letter = " [menu] " if letter == 'Key.num_lock': letter = " [num_lock] " if letter == 'Key.page_down': letter = " [page_down] " if letter == 'Key.page_up': letter = " [page_up] " if letter == 'Key.pause': letter = " [pause] " if letter == 'Key.print_screen': letter = " [print_screen] " if letter == 'Key.right': letter = " [right] " if letter == 'Key.scroll_lock': letter = " [scroll_lock] " if letter == 'Key.shift': letter = "" if letter == 'Key.shift_l': letter = "" if letter == 'Key.shift_r': letter = "" if letter == 'Key.tab': letter = " " if letter == 'Key.up': letter = " [up] " with open('KeyLog.txt', mode='a') as f: f.write(letter) with Listener(on_press=write_to_file) as l: l.join()
1ca8a404e0e7f7eccfdbb9ecbcf78ad792fd5cc8
tmavre/blackjack
/blackjack.py
1,946
3.6875
4
import sys from libs import deck from libs import chips from libs import hand from libs import steps def new_game(bet): # Create & shuffle the deck, deal two cards to each player initial_deck = deck.Deck() # Set up the Player's chips player_chips = chips.Chips() # Prompt the Player for their bet while not player_chips.take_bet(bet): pass player_hand = hand.Hand() player_hand.add_card(initial_deck.deal()) player_hand.add_card(initial_deck.deal()) dealer_hand = hand.Hand() dealer_hand.add_card(initial_deck.deal()) dealer_hand.add_card(initial_deck.deal()) init_steps = steps.Steps( initial_deck, player_chips, player_hand, dealer_hand) return init_steps def start_game(): # Print an opening statement print('Welcome to BlackJack! Get as close to 21 as you can without going over!\n\ Dealer hits until she reaches 17. Aces count as 1 or 11.') init_steps = new_game(int(input( 'How many chips would you like to bet? '))) while True: # recall this variable from our hit_or_stand function init_steps.show_some() # Prompt for Player to Hit or Stand while init_steps.hit_or_stand(input( "Would you like to Hit or Stand? Enter 'h' or 's' ")): # Implement the steps of the game. if not init_steps.operator(): break pass # inform Player of their chips total print(init_steps.show_total_chips()) # ask to play again ask_for_new_game = input( "Would you like to play another hand? Enter 'y' or 'n' ") if ask_for_new_game.lower() == 'y': init_steps = new_game(int(input( 'How many chips would you like to bet? '))) continue else: print("Thanks for playing!") sys.exit(0) if __name__ == '__main__': start_game()
cffe7cb9f8ca4f65af36abcf8b26d44c9ac76da6
linaresdev/cursoPY3
/src/practicing/job4/item_10.py
183
3.59375
4
def max_count_item(N=0, lists=[]): out = [] for row in lists: if len(row) > N: out.append(row) return out print(max_count_item(4, ["hola", "que tal", "hola mundo"]))
b83ab1e7568eb9603e03f690df2656bccdcc6a56
linaresdev/cursoPY3
/src/exercise/day3/funtion.py
750
3.84375
4
## FUNCIONES ## Funcion saludar sin parametro def saludar(): print("Hola Mundo") ## Funcion saludar con parametro def hello(nombre): print("Hola ", nombre) ## Crear una funcion que le permita ingresar un numero y que retorne su tabla def verTabla(numero): for row in range(1,10): print(row, "X", numero, "=", (row*numero) ) def duplicar(n): resul = n*2 return resul def operation(x, y, opt): if opt == 1: return x+y elif opt == 2: return x-y elif opt == 3: return x*y elif opt == 4: return x/y while True: print("1 - Sumar") print("2 - Restar") print("3 - Multiplicar") print("4 - Dividir") out = "" opt = int(input("Ingrese el numero de la opcion requerida : ")) print() print("Resultado: ", menu(4, 2) )
e71f1186e900a609cfba091f9b972f80222a0a3b
linaresdev/cursoPY3
/src/practicing/job1/item_3.py
416
4.15625
4
# Realizar un programa en Python que calcule el peso molecular (peso por cantidad de atomos solicitado # por teclado) de una molecula compuesta de dos elementos print("CARCULADORA DE PESO MOLECULAR"); peso = ( float(input("Introdusca peso del elemento a calcular:")) * int(input("Indique la cantidad del elemento espesificado:")) ) print("Peso total de la cantidad del elemento espesificado es:", peso, "g/mol" )
208b505cf4993dc9956437039e3b81df7f509d08
cuicaihao/aerial-image-converter
/utils/invertBW.py
644
3.546875
4
# Resize and Preserve Aspect Ratio import cv2 input_GT = "PNG/GT.png" output_GT_invert = "PNG/GT_INV.png" def invertBW(input, output): ''' 20% percent of original size ''' image = cv2.imread(input, 0) print('Original Dimensions : ', image.shape) # resize image invert = cv2.bitwise_not(image) print('Resized Dimensions : ', invert.shape) # save image status = cv2.imwrite(output, invert) print("Inverted Image written to file-system : ", status) return status if __name__ == '__main__': print("Resize the PNG image with OpenCV:") invertBW(input_GT, output_GT_invert) print("Done")
4e0dadf45d7c14b80b155a9c16ae3a1c6b2e686f
StepanBkv/Pythonlesson
/venv/Database.py
943
3.53125
4
def intersection(lang1, lang2): result = [] for i in range(0, len(lang1)): for j in range(0, len(lang2)): if(lang1[i] == lang2[j]): if(lang1[i] != ''): result += lang1[i] return result if __name__ == '__main__': languages = [] line = '' max = 0 try: with open("input.txt", 'r') as file: # languages = [i.strip() for i in file] # languages = [(i[0: -1], int(i[-1])) for i in languages] languages += [i.replace("\n", " ").split(" ") for i in file] print(languages) except: pass for i in range(0, len(languages) - 1): for j in range(i + 1, len(languages)): intersect = intersection(languages[i], languages[j]) if(len(intersect) + 1 > max): max = len(intersect) + 1 with open("output.txt", 'w') as file: file.write(str(max))
178592a57ce09b002482bc4e7638d25730b323ce
Smrcekd/HW070172
/L03/Excersise 4.py
385
4.34375
4
#convert.py #A program to convert Celsius temps to Fahrenheit #reprotudcted by David Smrček def main(): print("This program can be used to convert temperature from Celsius to Fahrenheit") for i in range(5): celsius = eval(input("What is the Celsius temperature? ")) fahrenheit = 9/5*celsius+32 print("The temperature is", fahrenheit, "degrees Fahrenheit.") main()
46ec97e1477d1632b36816724c2b5ab77000437c
Smrcekd/HW070172
/L05/Chapter 6/Excersise 2.py
874
3.890625
4
#Ants_Go_Marching.py def ants(): ant = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'] add = ['suck his thumb','tie his shoe','steer the wheel', '','tie the rope','regain hope', 'give a bump','stop his lump', 'drum his drum', 'ant the ant'] for i in range (10): print("The ants go marching {0} by {0}, hurrah! hurrah!".format(str(ant[i]))) print("The ants go marching {0} by {0}, hurrah! hurrah!".format(str(ant[i]))) print("The ants go marching {0} by {0},".format(str(ant[i]))) print("The little one stops to {0},".format(str(add[i]))) print("And they all go marching down...") print("Into the ground...") print("To get out...") print("Of the rain.") print("Boom! Boom! Boom!") print() def main(): ants() main()
ac4e2b8034d0c78d302a02c03fdb45ecb3026b56
Smrcekd/HW070172
/L04/Chapter 3/Excersise 15.py
421
4.21875
4
# Program approximates the value of pi # By summing the terms of series # by David Smrček import math#Makes the math library available. def main(): n = eval(input("Number of terms for the sum: ")) x = 0 m = 1 for i in range (1,2 * n + 1, 2): x = x + (m *4/i) m = -m result = math.pi - x print("The approximate value of pi is: ", result) main()
1cf8ef62ec43030d280a4de5c0722cff05ba079c
Smrcekd/HW070172
/L06/Chapter 8/excersise5.py
460
3.875
4
#Prime value determinator import math as m def main(): n = eval(input("Write a positive whole number: ")) while (n < 1) or (n % 1 != 0): n = eval(input("Error, write a positive whole number: ")) for i in range (int(m.sqrt(n))): i = 2 if (n % (i)) != 0: i = i+1 if i > m.sqrt(n): exit() else: break print("Your number is prime.") main()
b0088796e78a725b07d544a0491e59f316dd80a0
Smrcekd/HW070172
/L03/Excersise 11.py
305
4
4
#convert € to CZK.py #A program to convert Euro to Czech Crowns #by David Smrček def main(): print("This program can be used to convert sum from Euros to Czech Crowns") Euro = eval(input("What is the sum in Euros? ")) CZK = 27.28 * Euro print("The sum is", CZK ,"CZK.") main()
9116e73c00624fbd0b8b3488c7d41c722ddef3c8
Smrcekd/HW070172
/L05/Chapter 7/quadratic5.py
571
4.0625
4
#quadratic5.py import math def main(): print("This program finds the real solutions to a quadratic\n") a= float(input("Enter coefficient a: ")) b= float(input("Enter coefficient b: ")) c= float(input("Enter coefficient c: ")) discRoot = math.sqrt(b*b-4*a*c) root1 = (-b + discRoot) / (2*a) root2 = (-b - discRoot) / (2*a) print("\nThe solutions are:", root1, root2) except ValueError: print("\nNo real roots") main()
6e5f674528d0a086e7d974f86b2440994650a047
Smrcekd/HW070172
/L05/Chapter 7/excersise 1.py
391
3.890625
4
#excersise1.py def main(): hours = int(input("How many hours have you worked? ")) wage = int(input("How much do you earn per hour? ")) wph = hours * wage if hours <= 40: final = wph print(final) else: final = 40* wage final = (hours - 40) * 1.5 * wage + final print(final) main()
baf6d63b75ccf61540ffc32f91a10b48547e953c
Smrcekd/HW070172
/L04/Chapter 5/Excersise 3.py
372
3.984375
4
#Examscore_to_grade_convertor.py #by David Smrček def main(): scale = "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFDDDDDDDDDDCCCCCCCCCCBBBBBBBBBBAAAAAAAAAAA" grade1 = int(input("Please enter the quiz grade on a scale from 0 to 100: ")) grade2 = scale[grade1] print("Your number of points ({0}) is {1}.". format(grade1, grade2)) main()
34419d4f60cbbd2b2625ff1d8eae8b878610660c
LuizTiberio/Aula_Python_Maua_IOT
/Ex_pratico1.py
415
3.9375
4
import math def distancia( p1,p2): aux = (p2[0]-p1[0])**2+(p2[1]-p1[1])**2 dist= math.sqrt(aux) return dist p1=[] p2=[] p1.append(float( input("Por favor, digite o x do ponto 1: "))) p1.append(float( input("Por favor, digite o y do ponto 1: "))) p2.append(float( input("Por favor, digite o x do ponto 2: "))) p2.append(float( input("Por favor, digite o y do ponto 2: "))) print(distancia(p1,p2))
d4202797cf6864c8c908e07a53d19ba8a78ec41c
TanyaSinha550/Complete-ML
/Multiple_Linear_Regression_Code1.py
1,912
3.796875
4
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('50_Startups.csv') X = dataset.iloc[:, :-1].values y = dataset.iloc[:, 4].values # Encoding the categorical data # Encoding the Independent Variable from sklearn.preprocessing import OneHotEncoder from sklearn.compose import ColumnTransformer ct=ColumnTransformer([('encoder',OneHotEncoder(),[3])],remainder='passthrough') X=np.array(ct.fit_transform(X),dtype=np.float) # Avoiding the Dummy Variable Trap X = X[:, 1:] # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) #Fitting Multiple Linear Regression to the Training Set from sklearn.linear_model import LinearRegression regressor=LinearRegression() regressor.fit(X_train,y_train) # Predicting the Test set results y_pred=regressor.predict(X_test) ''' we are selecting only the statistically significant independent variable to build our model using p-values we are appending the bo cofficient which is 1 in X ''' #Building the optimal model using Backward Elimination import statsmodels.api as sm X = np.append(arr = np.ones((50, 1)).astype(int), values = X, axis = 1) X_opt = X[:, [0, 1, 2, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 1, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 3, 4, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 3, 5]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary() X_opt = X[:, [0, 3]] regressor_OLS = sm.OLS(endog = y, exog = X_opt).fit() regressor_OLS.summary()
03f21363f201898a868ffd9636fcb46da6cd48e1
emlslxl/myPython3
/base/list.py
384
3.671875
4
# -*- coding: utf-8 -*- # @Author: emlslxl # @Date: 2016-12-12 13:37:20 # @Last Modified by: emlslxl # @Last Modified time: 2016-12-12 13:53:58 my_list = ["emlslxl",30,173] print("my name is",my_list[0] + ", my age is",str(my_list[1]) + ", my height is",str(my_list[2])+"cm") my_list.append('basketball') print("I like play",my_list[3]) print("my_list size is",len(my_list))
0a054d104f3fff2b5def95f0c3bfbd15d37197aa
emlslxl/myPython3
/function/var_args.py
458
3.8125
4
# -*- coding: utf-8 -*- # @Author: emlslxl # @Date: 2016-09-26 16:26:52 # @Last Modified by: emlslxl # @Last Modified time: 2016-09-26 17:11:52 #args 可变长参数,不带有key值 def say_hello(greeting,*args): if len(args) == 0: print("%s!" %(greeting)) print() else: print("len(args) = %d" %(len(args))) print('%s, %s!' % (greeting, ','.join(args))) print() say_hello("hello") say_hello("hello","allen") say_hello("hello","1","2","3")
af92632b0665d96267df3bbcf22af66fa2286d84
Sma6500/Tinyclues_test
/similarity/similarity.py
926
3.6875
4
""" This file contains the abstract class Recommendation """ ### Import import pandas as pd import numpy as np from abc import ABC, abstractmethod ### the abstract class for different recommendations class Recommendation(ABC) : def __init__(self, items : pd.DataFrame, users : pd.DataFrame, ratings : pd.DataFrame, item_keys): self.items=items self.users=users self.ratings=ratings self.item_keys=item_keys @abstractmethod def __similarity_matrix__(self): #this function build the matrix of the metric we use to recommend the items. pass @abstractmethod def get_most_similar(self, items_id): #this function get the most similar items given a specific item pass @abstractmethod def get_recommendations(self, user_id): #this function get the recommendations for a given user pass
623e3a9f11289a040faa5e70ae0678739b5c6b94
BoyOoka/Python36
/Hello.py
1,480
4.0625
4
# -*- coding: utf-8 -*- print("Hello World!") print("中文") #中文注释 if True: print ("Answer") print ("True") else: print ("Answer") print ("False") # 缩进不一致,会导致运行错误 total = 'item_one' + \ 'item_two' + \ 'item_three' total2 = ['item_one', 'item_two', 'item_three', 'item_four', 'item_five'] total3 = {'item1','item2','item3'} print(total,total2,total3) word = '字符串' sentence = "这是一个句子。" paragraph = """这是一个段落, 可以由多行组成""" str='Runoob' print(str) # 输出字符串 print(str[0:-1]) # 输出第一个到倒数第二个的所有字符 print(str[0]) # 输出字符串第一个字符 print(str[2:5]) # 输出从第三个开始到第五个的字符 print(str[2:]) # 输出从第三个开始的后的所有字符 print(str * 2) # 输出字符串两次 print(str + '你好') # 连接字符串 print(paragraph[0:-1],end="")#不换行 print('------------------------------') print('hello\nrunoob') # 使用反斜杠(\)+n转义特殊字符 print(r'hello\nrunoob') # 在字符串前面添加一个 r,表示原始字符串,不会发生转义 #input("\n按下 enter 键后退出。") import sys print('================Python import mode=========================='); print ('命令行参数为:') for i in sys.argv: print (i) print ('\n python 路径为',sys.path)
8002ee891e29a1b8d96186ce36a9c543ec1c9211
BoyOoka/Python36
/function.py
1,874
4.09375
4
def add(a,b): print(a + b) c = a+b return c add(3,4) print(add(2,3)) def ChangeInt( a ): a = 10 return a # print(a) b=2 print(ChangeInt(b)) print( b ) # 结果是 2 def changeme( mylist ): "修改传入的列表" mylist.append([1,2,3,4]) print ("函数内取值: ", mylist) return # 调用changeme函数 mylist = [10,20,30] changeme( mylist ) print ("函数外取值: ", mylist) def printme( str ): "打印任何传入的字符串" print (str) return #调用printme函数 printme(str="菜鸟教程") #可写函数说明 def printinfo( name, age ): "打印任何传入的字符串" print ("名字: ", name) print ("年龄: ", age) return #调用printinfo函数 printinfo( age=50, name="runoob" ) #可写函数说明 def printinfo2( name, age = 35 ): "打印任何传入的字符串" print ("名字: ", name) print ("年龄: ", age) return #调用printinfo函数 printinfo2( age=50, name="runoob" ) print ("------------------------") printinfo2( name="runoob" ) # 可写函数说明 def printinfo( arg1, *vartuple ): "打印任何传入的参数" print ("输出: ") print (arg1) for var in vartuple: print (var) return # 调用printinfo 函数 printinfo( 10 ) printinfo( 70, 'ttt',456,'法施工' ) # 可写函数说明 sum = lambda arg1, arg2,arg3: arg1 + arg2 + arg3 # 调用sum函数 print("相加后的值为 : ", sum(10, 20,arg3=5)) print("相加后的值为 : ", sum(20, 20,9)) #-----------------global和nonlocal--------------------------------------- num = 1 def fun1(): global num # 需要使用 global 关键字声明 print(num) num = 123 print(num) fun1() def outer(): num = 10 def inner(): nonlocal num # nonlocal关键字声明 num = 100 print(num) inner() print(num) outer()
a33f0548e4ab60c73bd27068eef0fd0dcf89a324
w1033834071/qz2
/oldboy/thread lock/Pool模块.py
1,342
3.546875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- from multiprocessing import Pool, TimeoutError import time import os def f(x): return x*x if __name__ == '__main__': #创建4个线程 with Pool(processes=4) as pool: # 打印 "[0,1,2,3,4,5.......81]" print(pool.map(f,range(10))) # 使用任意顺序输出相同的数字 for i in pool.imap_unordered(f,range(10)): print(i) #异步执行“f(20)” res = pool.apply_async(f,args=(20,)) #只运行一个进程 print(res.get(timeout=1)) # 输出400 # 异步执行"os.getpid()" res = pool.apply_async(os.getpid,()) #只运行一个进程 print(res.get(timeout=1)) #输出进程的pid #运行多个异步执行可能会使用多个进程 multiple_results = [pool.apply_async(os.getpid,()) for i in range(4)] print([res.get(timeout=1) for res in multiple_results]) #是一个进程睡10秒 res = pool.apply_async(time.sleep,(10,)) try: print(res.get(timeout=1)) except TimeoutError: print("发现一个multiprocessing.TimeoutError异常") print("目前,池中还有其他的工作") #退出with块中已经停止的池 print("Now the pool is closed and no longer is available")
f35b9f213a9f87930f82c3a264bfe07ca1ac16db
w1033834071/qz2
/oldboy/day08/装饰器.py
773
3.921875
4
#!/usr/bin/env python # -*- coding:utf-8 -*- # 作用: # 不改变原函数 在函数之前或之后再做点操作 # 装饰器原理 # 1、 将outer函数与需要的函数进行捆绑 # 2、 执行outer函数,并且将其下面的函数名当做参数 # 3、 将outer的返回值重新赋值给f100 = outer的返回值 # 新f100函数 = inner def outer(func): def inner(): print("hello") print("hello") print("hello") r = func() print("end") print("end") print("end") return r return inner #假设有核心代码 100个 不易做修改 def f1(): print("f1") def f2(): print("f2") def f3(): print("f3") def f4(): print("f4") @outer def f100(): print("f100") f100()
dec5d647b9225b0a2863702d69e45118cd17e4cf
w1033834071/qz2
/oldboy/day04/homework.py
709
4.03125
4
#!/usr/bin/env python # -*- coding -*- #列出商品 选商品 # li = ['手机','电脑','鼠标垫','游艇'] # for i,j in enumerate(li): # print(i+1,j) # num = int(input("num:")) # if num > 0 and num <= len(li): # good = li[num-1] # print(good) # else: # print('商品不存在') dic = { "河北":{ "石家庄":["鹿泉","真诚","元氏"], "邯郸":["永年","涉县","磁县"] }, "河南":{ "郑州":["1","2","3"], "开封":["4","5","6"] } } #循环输出所有的省 for p in dic: print(p) str1 = input("请输入省份:") for c in dic[str1]: print(c) str2 = input("请输入城市:") for d in dic[str1][str2]: print(d)
d8824bc95ba88d0ac03380b7cd4547a8f4d3b86c
w1033834071/qz2
/oldboy/基础题考试/e2.py
589
3.890625
4
#!/usr/bin/env python # -*- coding:utf-8 -*- s = " Edward 2222211" # 其实返回的是一个元组或字典 并不是返回多个值 def c(string): blank_space = 0 upper_case = 0 lower_case = 0 num = 0 for i in s: if i.isspace(): blank_space += 1 elif i.islower(): lower_case += 1 elif i.isupper(): upper_case += 1 elif i.isnumeric(): num += 1 return blank_space,upper_case,lower_case,num blank_space,upper_case,lower_case,num = c(s) print(blank_space,upper_case,lower_case,num)
07cc3322a5f81a2f56ebdf99d489a5823e6b4198
mttymtt/DrawBot-Sketchbook
/Classes/Andy-Clymer/2019-07-30/07_interpolate.py
520
3.5625
4
def interpolate(percent, start, end): value = start + (end - start) * percent return value total_frames = 10 for frame in range(total_frames): percent = frame / (total_frames - 1) print(frame, "-", percent) newPage(300, 300) x_1, y_1 = 30, 200 x_2, y_2 = 250, 19 new_x = interpolate(percent, x_1, x_2) new_y = interpolate(percent, y_1, y_2) oval(x_1, y_1, 5, 5) oval(x_2, y_2, 5, 5) oval(new_x, new_y, 5, 5) fontSize(100) text("3", (new_x, new_y))
3c56c31fb089c81cf46b815c6df76385b1505c61
mttymtt/DrawBot-Sketchbook
/Classes/Andy-Clymer/2019-07-02/01_basics.py
197
3.84375
4
# Text = strings print("Hello") # Math print(5 * 2) print(40 / 3) # Math with strings print("Hello\r" * 5) #Variables nameFirst = "Matthew" nameLast = "Smith" print(nameFirst + " " + nameLast)