blob_id
stringlengths
40
40
repo_name
stringlengths
5
119
path
stringlengths
2
424
length_bytes
int64
36
888k
score
float64
3.5
5.22
int_score
int64
4
5
text
stringlengths
27
888k
271a1acd635adb0a0cdc6093d00a0320d6a010ab
pxliang/Leetcode
/String/670_Maximum_Swap.py
1,084
3.640625
4
class Solution: def maximumSwap(self, num: int) -> int: string = str(num) current = 0 pre = current for t, sub in enumerate(string[:-1]): if int(string[t + 1]) > int(sub): current = t break max_num = int(string[current]) max_point = current for j in range(current + 1, len(string)): if int(string[j]) >= max_num: max_num = int(string[j]) max_point = j start = 0 for j in range(current + 1): if int(string[j]) < max_num: start = j break result = '' for t in range(len(string)): if t == start: result += string[max_point] elif t == max_point: result += string[start] else: result += string[t] return int(result) ''' comments: 1. Find the first increasing number 2. swap the largest number in the latter part with the first smaller number in the previous part '''
4485520094907f764f6899b3ebacd87ca9d26207
zimolzak/Raspberry-Pi-newbie
/fake_meter.py
892
3.828125
4
#!/usr/bin/env python """Mimic a one-dimensional bar graph. Control an arbitrary number of LEDs. Make them light up or turn off, one at a time, starting at one end of the list. Randomly decide whether to go up or down. """ import RPi.GPIO as GPIO from time import sleep from random import randint pins = [5, 22, 27, 17, 12, 25, 23, 18] #pins = [26, 6, 13, 22] npins = len(pins) GPIO.setmode(GPIO.BCM) # GPIO.BOARD GPIO.setup(pins, GPIO.OUT) # requires root def display(value): assert 0 <= value <= npins for p in pins: GPIO.output(p, GPIO.LOW) # reset them all for p in pins[:value]: GPIO.output(p, GPIO.HIGH) # turn on the few x = 2 try: while(True): x = x + randint(-1,1) if x > npins: x = npins if x < 0: x = 0 display(x) sleep(0.2) except KeyboardInterrupt: pass GPIO.cleanup()
b07250ab7c114d7209f12f4762d148c779fdbc53
unssfit/python-programming-work-
/Gui_Calculator.py
3,609
3.84375
4
from tkinter import * from functools import partial # clculator # https://www.youtube.com/watch?v=_1tTS638xUQ root = Tk() root.title('First Program') frame = Frame(root) frame.pack(side=TOP) num_input = Entry(frame,border=10,width=25,insertwidth=1,font=30) num_input.pack(side=TOP) def Calculator(num): if num == 'CLEAR': num_input.delete(0,END) else: string = num_input.get() if num != '=': num_input.insert(len(string),num) if num == '=': num1, index, num2, operator = '', 0, '', '' for i in range(len(string)): if string[i].isdigit(): num1 += string[i] else: operator = string[i] index = i break num2 = string[index+1:] if operator == '+': num_input.delete(0,END) num_input.insert(0,int(num1)+int(num2)) elif operator == '-': num_input.delete(0,END) num_input.insert(0,int(num1)-int(num2)) elif operator == '*': num_input.delete(0,END) num_input.insert(0,int(num1)*int(num2)) elif operator == '%': num_input.delete(0,END) num_input.insert(0,int(num1)%int(num2)) else: num_input.delete(0,END) num_input.insert(0,int(num1)//int(num2)) button = Button(frame,text='0',padx=30,pady=10,bd=6,command=partial(Calculator,0)) button.pack(side=LEFT) button = Button(frame,text='1',padx=30,pady=10,bd=6,command=partial(Calculator,1)) button.pack(side=LEFT) button = Button(frame,text='2',padx=30,pady=10,bd=6,command=partial(Calculator,2)) button.pack(side=LEFT) frame1 = Frame(root,bg='red') frame1.pack() button1 = Button(frame1,text='3',padx=30,pady=10,bd=6,command=partial(Calculator,3)) button1.pack(side=LEFT) button1 = Button(frame1,text='4',padx=30,pady=10,bd=6,command=partial(Calculator,4)) button1.pack(side=LEFT) button1 = Button(frame1,text='5',padx=30,pady=10,bd=6,command=partial(Calculator,5)) button1.pack(side=LEFT) frame2 = Frame(root) frame2.pack() button2 = Button(frame2,text='6',padx=30,pady=10,bd=6,command=partial(Calculator,6)) button2.pack(side=LEFT) button2 = Button(frame2,text='7',padx=30,pady=10,bd=6,command=partial(Calculator,7)) button2.pack(side=LEFT) button2 = Button(frame2,text='8',padx=30,pady=10,bd=6,command=partial(Calculator,8)) button2.pack(side=LEFT) frame3 = Frame(root) frame3.pack() button3 = Button(frame3,text='9',padx=30,pady=10,bd=6,command=partial(Calculator,9)) button3.pack(side=LEFT) addition_button = Button(frame3,text='+',padx=30,pady=10,bd=6,command=partial(Calculator,'+')) addition_button.pack(side=LEFT) subs_button = Button(frame3,text='-',padx=30,pady=10,bd=6,command=partial(Calculator,'-')) subs_button.pack(side=LEFT) frame4 = Frame(root) frame4.pack() multi_button = Button(frame4,text='*',padx=30,pady=10,bd=6,command=partial(Calculator,'*')) multi_button.pack(side=LEFT) divi_button = Button(frame4,text='/',padx=30,pady=10,bd=6,command=partial(Calculator,'/')) divi_button.pack(side=LEFT) perc_button = Button(frame4,text='%',padx=30,pady=10,bd=6,command=partial(Calculator,'%')) perc_button.pack(side=LEFT) frame5 = Frame(root) frame5.pack() resu_button = Button(frame5,text='=',width=10,padx=30,pady=10,bd=6,command=partial(Calculator,'=')) resu_button.pack(side=LEFT) clear = Button(frame5,text='CLEAR',padx=30,pady=10,bd=6,command=partial(Calculator,'CLEAR')) clear.pack(side=LEFT) root.mainloop()
268d24cae8949edbc347065c1a85415f9374aa2b
jordanbsandoval/python3_al-descubierto
/capituloDos/diccionarios/acceso-insercion-borrados/modificar-element-diccionario.py
205
4.09375
4
#!/usr/bin/python3 """ Modificando el valor de un elemento del diccionario, atraves de la clave """ dicc = {'edad': 28, 'nombre':"jordan", 'peso':"67.2"} print(dicc) dicc['nombre'] = "Ronaldo" print(dicc)
6f61ee306cee7191ec69789b404dadbd703f74cf
bopopescu/PycharmProjects
/Class_topic/16.py
232
3.5625
4
class ParentA: def __init__(self,a,b): self.a = a self.b = b def setInfo(self): return complex(self.a) * int(self.b) class Child: pass obj = ParentA('10','50') temp = obj.setInfo() print(temp)
a197c94f5eb02413bae678fc826efea002544f02
Aaronphilip2003/Python_Aaron
/Palin_number.py
179
3.9375
4
num=int(input("Enter a number:")) temp=num rev=0 r=0 while num>0: r=num%10 rev=rev*10+r num//=10 if rev==temp: print("Palin") else: print("NOT")
5779779497fdd911f8781f48e89126e76382e22f
johnmorgan123/python_projects
/WebScraping/BookScraping.py
905
3.53125
4
#getting the title of every book with a 3 star rating import requests import bs4 base_url = 'https://books.toscrape.com/catalogue/page-{}.html' page_number = 13 res = requests.get(base_url.format(page_number)) soup = bs4.BeautifulSoup(res.text, 'lxml') products = soup.select(".product_pod") example = products[0] #[] == example.selsect(".star-rating.Three") title = example.select('a')[1]['title'] print(title) print("----------") three_star_titles = [] for i in range(1, 51): scrape_url = base_url.format(i) res = requests.get(scrape_url) soup = bs4.BeautifulSoup(res.text, 'lxml') books = soup.select(".product_pod") for book in books: if len(book.select('.star-rating.Three')) != 0: book_title = book.select('a')[1]['title'] three_star_titles.append((book_title)) #print(three_star_titles) for item in three_star_titles: print(item)
077ca8dfb25e031accbf863ad806ea46a6a28061
Yannyezixin/python-study-trip
/stack-qa/string/re_split_str.py
260
3.609375
4
#coding: utf-8 import re s = 'words, names, yes, sex, book.' gbk = '中文, name, 名字.' print re.split('\W+', s) print re.split('\W+', gbk) print re.split('\W+', s, 2) print re.split('\W+', s, 3) print re.split('(\W+)', s) print re.split('(\W+)', gbk)
4a66e9497721b61820cb8187192308fa60794b9f
codacy-badger/pythonApps
/dayOfWeek.py
448
3.828125
4
import re #regular expression import calendar import datetime def processDate(userInput): userInput = re.sub(r"/"," ",userInput) userInput = re.sub(r"-"," ",userInput) return userInput def findDay(date): born = datetime.datetime.strptime(date, '%d %m %Y').weekday() return (calendar.day_name[born]) userInput = str(input("enter date : ")) date = processDate(userInput) print("Day On : "+userInput +" is "+findDay(date))
6f3d57523a6f0a7048654f86c444162af7a17188
weizhuowang/Racecar
/libMPPlot.py
4,571
3.59375
4
import matplotlib import multiprocessing import time import random import numpy as np import matplotlib.pyplot as plt import matplotlib.animation as animation import math def main(): #Create a queue to share data between process q = multiprocessing.Queue() #Create and start the simulation process simulate=multiprocessing.Process(target=getdata1,args=(q,)) #Create the base plot plot() simulate.start() #Call a function to update the plot when there is new data status = 0 while status == 0: status = updateplot(q) print('Done') # ====================================================== # ====================================================== # ====================================================== def plot(): #Function to create the base plot, make sure to make global the lines, axes, canvas and any part that you would want to update later global line1,line2,line3,line4,ax1,ax2,ax3,fig size = 50 x_vec = np.linspace(0,0.0001,size+1)[0:-1] y_vec = np.zeros(len(x_vec)) # this is the call to matplotlib that allows dynamic plotting plt.ion() fig = plt.figure(figsize=(13,6)) ax1 = fig.add_subplot(221) plt.grid() ax2 = fig.add_subplot(222) plt.grid() ax3 = fig.add_subplot(223) plt.grid() # create a variable for the line so we can later update it line1, = ax1.plot(x_vec,y_vec,'-o',alpha=0.8) line2, = ax2.plot(x_vec,y_vec,'-o',alpha=0.8) line3, = ax3.plot(x_vec,y_vec,'-o',alpha=0.8) line4, = ax3.plot(x_vec,y_vec,'-o',alpha=0.8) #update plot label/title # plt.ylabel('Y Label') # plt.title('Title: {}'.format(identifier)) # ========== BLIT ========= # cache the background # ax1bg = fig.canvas.copy_from_bbox(ax1.bbox) # ax2bg = fig.canvas.copy_from_bbox(ax2.bbox) # ========================= plt.show() def redraw_figure(): fig.canvas.flush_events() # plt.show(block=False) # plt.show(block=False) # # ==========BLIT=========== # fig.canvas.restore_region(ax1bg) # fig.canvas.restore_region(ax2bg) # # redraw just the points # ax1.draw_artist(line1) # ax2.draw_artist(line2) # # fill in the axes rectangle # fig.canvas.blit(ax1.bbox) # fig.canvas.blit(ax2.bbox) # plt.pause(0.00000001) def update_plot_info(ax,line,xlist,ylist,xlabel='time (s)',ylabel=''): xdata = line.get_xdata(orig=False) xdata = np.append(xdata[len(xlist):],np.array(xlist)) ydata = line.get_ydata(orig=False) ydata = np.append(ydata[len(ylist):],np.array(ylist)) line.set_xdata(xdata) line.set_ydata(ydata) ax.set_xlabel(xlabel) ax.set_ylabel(ylabel) # adjust limits if new data goes beyond bounds ax.set_xlim([np.min(xdata),np.max(xdata)]) if np.min(ydata)<=line.axes.get_ylim()[0] or np.max(ydata)>=line.axes.get_ylim()[1]: ax.set_ylim([np.min(ydata)-np.std(ydata),np.max(ydata)+np.std(ydata)]) def updateplot(q): try: #Try to check if there is data in the queue xlist,ylist = [[],[]] for items in range(0, q.qsize()): datachuck = q.get_nowait() xlist.append(datachuck[0]) ylist.append(datachuck[1:]) if (len(ylist)>0): ylist = np.array(ylist) if (ylist[-1,-1] !='Q'): ax1.set_ylim([-3,3]) update_plot_info(ax1,line1,xlist,ylist[:,0],ylabel='torque (N*cm)') update_plot_info(ax2,line2,xlist,ylist[:,1],ylabel='RPM') update_plot_info(ax3,line3,xlist,ylist[:,2]) update_plot_info(ax3,line4,xlist,ylist[:,3],ylabel='Current & Voltage') ax3.set_ylim([-15,15]) ax3.legend(['Current (A)','Voltage (V)'],loc='upper right') redraw_figure() return 0 else: print('done') return 1 else: return 0 except: # print("empty") # redraw_figure() return 0 def getdata1(q): iterations = range(300) for i in iterations: rand_val = math.sin(0.1*i) #np.random.randn(1) timeval = i #here send any data you want to send to the other process, can be any pickable object time.sleep(0.02) print(i,rand_val) q.put([timeval,rand_val,rand_val**2-rand_val,rand_val,rand_val+2,rand_val**2]) q.put(['Q','Q','Q','Q','Q','Q']) if __name__ == '__main__': main()
4b5997f55fe73a6494750c5a1503dd888e49a91a
erikamaylim/Python-CursoemVideo
/ex084.py
1,040
3.765625
4
"""Faça um programa que leia nome e peso de várias pessoas, guardando tudo em uma lista. No final, mostre: A) Quantas pessoas foram cadastradas. B) Uma listagem com as pessoas mais pesadas. C) Uma listagem com as pessoas mais leves.""" galera = [] dados = [] peso = [] resp = 'S' while resp in 'Ss': dados.append(str(input('Nome: ')).strip()) dados.append(float(input('Peso: '))) galera.append(dados[:]) dados.clear() resp = str(input('Quer continuar? [S/N] ')).strip()[0] if resp in 'Nn': break elif resp not in 'SsNn': resp = str(input('Inválido. Responda com S ou N. Quer continuar? [S/N] ')).strip()[0] print('--' * 20) print(f'{len(galera)} pessoas foram cadastradas.') for n, p in galera: peso.append(p) print(f'Maior peso registrado foi {max(peso)}Kg de ', end='') for n, p in galera: if p == max(peso): print(f'[{n}]', end=' ') print(f'\nMenor peso registrado foi {min(peso)}Kg de ', end='') for n, p in galera: if p == min(peso): print(f'[{n}]', end=' ')
33420e9e12d2ace81f7646eda0e52cb4ad4af996
yenner123/BigDataAnalyticsCourse
/Proyecto/utils.py
1,557
3.578125
4
import math def removeSymbols(word): word = word.replace("==", " ") word = word.replace("(", " ") word = word.replace(")", " ") word = word.replace(".", " ") word = word.replace(",", " ") word = word.replace(" =", " ") word = word.replace("\n", " ") word = word.replace("\r", " ") word = word.replace("\t", " ") word = word.replace(":", " ") word = word.replace("*", " ") word = word.replace("[", " ") word = word.replace("]", " ") word = word.replace(">", " ") word = word.replace("<", " ") word = word.replace('"\"', ' ') word = word.replace("/", " ") word = word.replace("«", " ") word = word.replace("»", " ") word = word.replace("—", " ") word = word.replace(" ", " ") word = word.replace(" ", " ") word = word.replace(" ", " ") word = word.replace(" ", " ") word = word.replace(' "', " ") word = word.replace('" ', " ") word = word.replace(' " ', " ") word = word.replace('""', " ") word = word.replace('" "', " ") word = word.replace(' "" ', " ") word = word.replace('\u200b', " ") return word def isNotEmpty(s): return bool(s and s.strip()) def cosineSimilarity(vectorSpace1, vectorSpace2): numerator = 0 sumxx, sumyy = 0, 0 for i in range(len(vectorSpace1)): x = vectorSpace1[i] y = vectorSpace2[i] sumxx += x*x sumyy += y*y numerator += x*y return numerator/math.sqrt(sumxx*sumyy)
43b979cb23e92fc98e92a26e589c29fa93111563
bernardosequeir/CTFSolutions
/project_euler/Problem20/p20.py
184
3.734375
4
from math import factorial def factorial_digit_sum(number): return sum([int(i) for i in str(factorial(number))]) if __name__ == "__main__": print(factorial_digit_sum(100))
57261c7c2900d65b32ec7316edf015b7703727bf
siddharthadtt1/Leet
/HiredInTech/09-simplify_fraction.py
440
4.0625
4
def simplify_fraction(numerator, denominator, result): # Write your code here # result[0] = ... # result[1] = ... x, y = max(numerator, denominator), min(numerator, denominator) # finding the greated common divisor, which will be x after the while loop while y != 0: x, y = y, x % y result[0] = numerator/x result[1] = denominator/x result = [0, 0] simplify_fraction(77, 22, result) print result
65064e3c33410e3ec527b89d28872e6562491af1
anjana-analyst/Programming-Tutorials
/Competitive Programming/DAY-25/password.py
875
4.0625
4
def password(p): sym=['$','#','@','%'] val=True if len(p)<6: print("Length should be atleast 6") if len(p)>20: print("Length is more than 20") if not any(char.isdigit() for char in p): print("It should have atleast one number") val=False if not any(char.isupper() for char in p): print("It should have atleast one Uppercase Letter") val=False if not any(char.islower() for char in p): print("It should have atleast one Lowercase Letter") val=False if not any(char in sym for char in p): print("It should have atleast one Special Symbol") val=False if val is True: return val pa=input("Enter the password") if(password(pa) is True): print("Valid Password") else: print("Invalid Password")
7cc8f356b89182c0e32637864e9c51e03946a04a
shadmanhiya/Python-Projects-
/tuples.py
747
3.984375
4
""" Write a program to read through the mbox-short.txt and figure out the distribution by hour of the day for each of the messages. You can pull the hour out from the 'From ' line by finding the time and then splitting the string a second time using a colon. From stephen.marquard@uct.ac.za Sat Jan 5 09:14:16 2008 Once you have accumulated the counts for each hour, print out the counts, sorted by hour as shown below. """ fname = input("Enter File name: ") fh = open(fname) counts = dict() for line in fh: if line.startswith("From:"): continue elif line.startswith("From"): w = line.split() hour = w[5].split(":") h = hour[0] counts[h] = counts.get(h, 0) + 1 for key, val in sorted(counts.items()): print(key,val)
5be927cbe41c2b02cd2e659620873d41547dd4ab
Gitlittlerubbish/SNS
/exe5_2.py
229
4.15625
4
#! usr/bin/python3 def fact(num): if num == 1 or num == 0: return 1 return fact(num-1) + fact(num-2) def main(): num = 20 print("Factorial of 20 is ", fact(num)) if __name__ == "__main__": main()
2e4058b42f48378529dde75c77a89db7110cf6f4
erinnlebaron3/python
/PipenvManaging/PolymorphBuildHtml.py
2,130
4.28125
4
# going to build out a HTML class so you can think of this as a tool that can render HTML on the page # build multiple subclasses that allow you to render custom versions of that HTML. # going to be a common convention that you see whenever you're using very complex system # going to create what is called a abstract class and then this abstract class has the sole purpose of holding and # storing shared behavior and then only the inherited classes so only the child classes are going to be the ones # that ever called this class. # polymorphism does is it's when you have a child class that inherits these methods from a parent class and then it overrides the behavior. # right here we have access to content we have access to content in all child classes but in this case, # we decided to wrap that content in an H1 tag. Here we decided to wrap it in a div tag and so we have different # behavior with these child classes and because of it we have some pretty powerful behavior in a very short amount of code. # You can see we only have a few different classes here but we were actually able to create our own custom HTML generator # just by doing that and we leverage Object-oriented programming we leveraged inheritance and polymorphism. class Html: def __init__(self, content): self.content = content def render(self): raise NotImplementedError("Subclass must implement render method") class Heading(Html): def render(self): return f'<h1>{self.content}</h1>' class Div(Html): def render(self): return f'<div>{self.content}</div>' tags = [ Div('Some content'), Heading('My Amazing Heading'), Div('Another Div') ] for tag in tags: print(tag.render()) # do not have any reference at all to the HTML parent class we're only calling those child classes # polymorphism it's a very big word that represents something that's actually kind of straightforward which is # and it's all in the name poly means many and morphism comes from the word meaning to change. # Which means it can have many changes or one item can have many forms.
5a3bca5570f26f93134815941c1bfda9833b8d7d
piyavishvkarma09/dictionery
/w3_eg.py
453
3.828125
4
# #Add a new item to the original dictionary # car = { # "brand": "Ford", # "model": "Mustang", # "year": 1964 # } # x = car.keys() # print(x) #before the change # car["color"] = "white" # print(x) #after the change # a=0 # while a<10: # # print(a) # a+=1 # print(a) # # print(a) a=[{"a":1,"data":"happy"},{"b":2,"data":"bday"},{"c":3,"data":"rash"}] for i in range(len(a)): if a[i]==2: del a[i] break print(a)
a34cb02704752606582ca48169365c39c72869a9
renderance/tic-tac-toe-python
/tictactoe.py
5,586
3.53125
4
import os # A little googling yielded this to clear interpereter window: def cls(): os.system('cls' if os.name=='nt' else 'clear') # The game consists of tiles changing values. class tile: def __init__(self): self.state = ' ' def set_state(self,player): if player == 1: self.state = 'X' elif player == 2: self.state = 'O' # Those tiles are collected in a 3x3 board, which I want to visualize. class board: def __init__(self): self.tiles = [[tile(), tile(), tile()], [tile(), tile(), tile()], [tile(), tile(), tile()]] def give_board(self): output_string='' for ii in [0, 1, 2]: for jj in [0, 1, 2]: output_string+=' '+self.tiles[ii][jj].state+' ' if jj<2: output_string+='|' output_string+='\n' if ii<2: output_string+='---+---+---\n' print(output_string) # Each game has a board, a turn, players, and win conditions. # Each game needs to report its game-state, check for win conditions, # and play turns. class game: def __init__(self): self.board = board() self.turn = 1 self.player = 1 self.draw = False self.winner = 0 def give_gamestate(self): cls() print('Press [Ctrl][C] to exit at any time.\n') self.board.give_board() if self.draw == False and self.winner == 0: print('Turn:\t\t',self.turn) print('Player on turn:\t',self.player) elif self.winner != 0: print('Winner is player ',self.winner) elif self.draw == True: print('Game is a draw!') def check_draw(self): if self.turn == 9: return True else: return False def play_turn(self): print('\nTo claim a tile, enter a column number, i.e. 1, 2 or 3.') column = int(input()) print('To claim a tile, enter a row number, i.e. 1, 2 or 3.') row = int(input()) if (column > 0 and column < 4 and row > 0 and row < 4): ii = row-1 jj = column-1 if self.board.tiles[ii][jj].state==' ': self.board.tiles[ii][jj].set_state(self.player) self.winner = self.check_win() self.draw = self.check_draw() if self.player == 1: self.player = 2 elif self.player == 2: self.player = 1 self.turn+=1 return True else: print('That tile is already claimed. Choose another.') return False else: print('That tile does not exist.') return False def check_win(self): win = False # Check rows for row in [0,1,2]: if (self.board.tiles[row][0].state != ' ' and self.board.tiles[row][0].state == self.board.tiles[row][1].state and self.board.tiles[row][0].state == self.board.tiles[row][2].state): win = True # Check columns if win == False: for col in [0,1,2]: if (self.board.tiles[0][col].state != ' ' and self.board.tiles[0][col].state == self.board.tiles[1][col].state and self.board.tiles[0][col].state == self.board.tiles[2][col].state): win = True # Check diagonals if win == False: if (self.board.tiles[1][1].state != ' ' and self.board.tiles[0][0].state == self.board.tiles[1][1].state and self.board.tiles[2][2].state == self.board.tiles[1][1].state): win = True elif (self.board.tiles[1][1].state != ' ' and self.board.tiles[0][2].state == self.board.tiles[1][1].state and self.board.tiles[2][0].state == self.board.tiles[1][1].state): win = True if win == True: return self.player else: return 0 # Now, our user needs to be able to start a game, so dialogue! print("Hello, welcome to Glenn's tic-tac-toe, v1a!") print("Would you like to start a game?") print("Type 'y' and press [Enter] to confirm.") print("or press [Ctrl][C] to exit.") reply = input("Start a game? ") # Start a game: while reply == 'y': current_game=game() # So long as the started game has not been won... while (current_game.draw == False and current_game.winner == 0): # ... we want to see the board ... current_game.give_gamestate() # ... play a turn ... turn_done = False while turn_done == False: turn_done = current_game.play_turn() # ... and we want to see the final board when a winning turn occurs. current_game.give_gamestate() # Re-initialize a game? print("Do you want to play another game?") print("Type 'y' and hit [enter] if you do!") reply=input("Start a new game? ") # Goodbye dialogue print("Goodbye!") print("Press [Ctrl][C] to exit.")
49588239d6e6261abe74b97b3e9646b90845dcf2
melvanliu123/StudentCard.py
/Date.py
608
4.03125
4
class Date(): def __init__(self, month,day,year): self.__month = month self.__day = day self.__year = year def setMonth(self, newMonth): self.__month=newMonth def setDay(self, newDay): self.__day=newDay def setYear(self, newYear): self.__year=newYear def getMonth(self): return self.__month def getDay(self): return self.__day def getYear(self): return self.__year def toString(self): print(self.__month,"\\",self.__day,"\\",self.__year,end=" ")
ccbd3e032b6436918eb220807e453c10359ceb84
cladren123/study
/AlgorithmStudy/백준/6 유니온파인드/1922 네트워크 연결(크루스칼).py
700
3.765625
4
import sys input = sys.stdin.readline def find(x) : if x == parent[x] : return x else : rootx = find(parent[x]) parent[x] = rootx return parent[x] def union(x,y) : rootx = find(x) rooty = find(y) # 이 부분이 중요 if rootx != rooty : parent[rooty] = rootx n = int(input()) m = int(input()) wire = [] for _ in range(m) : wireone = list(map(int, input().split())) wire.append(wireone) parent = [i for i in range(n+1)] wire.sort(key=lambda x : x[2]) cost = 0 for i in wire : start = i[0] end = i[1] if find(start) != find(end) : union(start, end) cost += i[2] print(cost)
1dc7de84d546dd61aeebaf31d2e89dd359154ff2
westlicht/euler
/006/euler.py
278
3.671875
4
#!/usr/bin/python def sumsquares(max): num = 0 for i in range(1,max+1,1): num += i * i return num def squaresum(max): num = 0 for i in range(1,max+1,1): num += i return num * num max = 100 a = sumsquares(max) b = squaresum(max) print "%d - %d = %d" % (b, a, b -a)
ca5e3fee45038cbc63be07f5472a4cced3c2d339
githubeiro/Estudos-Python
/curso-em-video/curso-de-python-3/mundo-1-fundamentos/ex008-conversor-de-medidas.py
284
4.03125
4
# Escreva um programa que leia um valor em metros e o exiba convertido em centímetros e milímetros. medida = float(input('Infome um valor em metros: ')) cm = medida * 100 mm = medida * 1000 print(f'{medida}m equivale a {cm:.0f}cm') print(f'{medida}m equivale a {mm:.0f}mm')
4c9ea53d8bcf0376ccc4258828145c018404fc3a
jxhe/sparse-text-prototype
/scripts/compress_glove.py
1,507
3.75
4
import argparse import numpy as np def parse_embedding(embed_path): """Parse embedding text file into a dictionary of word and embedding tensors. The first line can have vocabulary size and dimension. The following lines should contain word and embedding separated by spaces. Example: 2 5 the -0.0230 -0.0264 0.0287 0.0171 0.1403 at -0.0395 -0.1286 0.0275 0.0254 -0.0932 """ embed_dict = {} with open(embed_path) as f_embed: # next(f_embed) # skip header for line in f_embed: pieces = line.rstrip().split(" ") embed_dict[pieces[0]] = pieces[1:] return embed_dict if __name__ == '__main__': parser = argparse.ArgumentParser(description='simplify glove word embedding') parser.add_argument('--embed-path', type=str, help='the original glove embed path') parser.add_argument('--dict-path', type=str, default='dict path') args = parser.parse_args() embed_dict = parse_embedding(args.embed_path) sample = embed_dict['a'] embed_dim = len(sample) with open(args.dict_path) as fin: vocab_size = len(fin.readlines()) print('{} {}'.format(vocab_size, embed_dim)) with open(args.dict_path) as fin: for line in fin: word = line.split()[0] if word in embed_dict: print('{} {}'.format(word, ' '.join(embed_dict[word]))) else: print('{} {}'.format(word, ' '.join(['0'] * embed_dim)))
1a9c3bbb7b8796e9b4393da8bd06c51437872f7a
ai-kmu/etc
/algorithm/2022/0719_199_Binary_Tree_Right_Side_View/jaeseok.py
1,086
3.71875
4
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def rightSideView(self, root: Optional[TreeNode]) -> List[int]: def sol(node, depth): if node: output[depth] = node.val if node.right is not None or node.left is not None: sol(node.left, depth + 1) # 왼편의 노드에 의해 덮여진 동일한 depth의 노드는 오른편의 노드로 알아서 갱신됨 sol(node.right, depth + 1) else: # 말단 노드에 도착하면 해당 depth의 노드 value 추가 output[depth] = node.val if not root: return [] # 불가능한 값들로 output을 채움 output = [101 for _ in range(100)] sol(root, 0) # 불가능한 값들을 제외한 list를 반환 return list(filter(lambda x: x <= 100, output))
5a2e32b494ab7d029ff790f16076bcba9487ed10
TatyanaV/Finding-Mutations-in-DNA-and-Proteins-Bioinformatics-VI-
/6_Shortest_NonShared_Substring.py
2,761
4.125
4
''' Shortest Non-Shared Substring Problem: Find the shortest substring of one string that does not appear in another string. Input: Strings Text1 and Text2. Output: The shortest substring of Text1 that does not appear in Text2. CODE CHALLENGE: Solve the Shortest Non-Shared Substring Problem. (Multiple solutions may exist, in which case you may return any one.) https://github.com/ngaude/sandbox/blob/f009d5a50260ce26a69cd7b354f6d37b48937ee5/bioinformatics-002/bioinformatics_chapter7.py Sample Input: CCAAGCTGCTAGAGG CATGCTGGGCTGGCT Sample Output: AA ''' """ Shortest Non-Shared Substring Problem Find the shortest substring of one string that does not appear in another string. Given: Strings Text1 and Text2. Return: The shortest substring of Text1 that does not appear in Text2. """ def naive_shortest_non_shared_substring(text1,text2): """ Shortest Non-Shared Substring Problem: Find the shortest substring of one string that does not appear in another string. Input: Strings Text1 and Text2. Output: The shortest substring of Text1 that does not appear in Text2. """ shortests = [text1] for i in range(len(text1)): maxj = min(i+len(shortests[-1]),len(text1)) for j in range(i,maxj): if text1[i:j] not in text2: shortests.append(text1[i:j]) break return shortests[-1] string = naive_shortest_non_shared_substring('AAAATAAACAAAGAATTAATCAATGAACTAACCAACGAAGTAAGCAAGGATATACATAGATTTATTCATTGATCTATCCATCGATGTATGCATGGACACAGACTTACTCACTGACCTACCCACCGACGTACGCACGGAGAGTTAGTCAGTGAGCTAGCCAGCGAGGTAGGCAGGGTTTTCTTTGTTCCTTCGTTGCTTGGTCTCTGTCCCTCCGTCGCTCGGTGTGCCTGCGTGGCTGGGCCCCGCCGGCGCGGGGAAAGATAATTATAGTGCGCCGAGGCATACGGAAACGTTCGATGCCAGGATGGGTATAAAACGATTATCGTGTACACCGGTATCCCAAGGGAGGGCACACAATTGTATCGTGGCTCTTCGTACTTAGGTAAATCTGAACCCATGTCTTTTAACTTAGCATCCACACGAGAGGCGTCGGTACGCGGGGCACGGATCACTACATTGTAAGACAACAAAGCTAGTTATCCTGAGGTTGCATCATCACGGTTACAGGGGTATTGAGAAGTTGCGACTGCTTAGCGCCGAAATAGCCCGTTCTGCCCTTTTGCTTTTCGGAGGATTAGTAGTCTATGACGAAGGGTAATGCTCCAGAAAATCTGGGGCTGGTAAGGGGCAGGGGTCGACTATAAGTAGTTCGAAGACGA','AAAATAAACAAAGAATTAATCAATGAACTAACCAACGAAGTAAGCAAGGATATACATAGATTTATTCATTGATCTATCCATCGATGTATGCATGGACACAGACTTACTCACTGACCTACCCACCGACGTACGCACGGAGAGTTAGTCAGTGAGCTAGCCAGCGAGGTAGGCAGGGTTTTCTTTGTTCCTTCGTTGCTTGGTCTCTGTCCCTCCGTCGCTCGGTGTGCCTGCGTGGCTGGGCCCCGCCGGCGCGGGGAAA') print string ''' with open('6_Shortest_NonShared_Substring.txt') as infile: text1a = infile.read().strip() text2a = infile.read().strip() text1a =str(text1a) text2a= str(text2a) print text1a print text2a answer = naive_shortest_non_shared_substring(text1a,text2a) print answer ''' with open('6_Shortest_NonShared_Substring_Answer.txt','w') as outfile: outfile.write(string)
6794e31ec482e5c1e0193566e9937cfd8a4ac6b1
delfick/timepiece
/timepiece/helpers.py
741
3.65625
4
class memoized_property(object): """Decorator to make a descriptor that memoizes it's value""" def __init__(self, func): self.func = func self.name = func.__name__ self.cache_name = "_{0}".format(self.name) def __get__(self, instance=None, owner=None): if instance is None: return self if not getattr(instance, self.cache_name, None): setattr(instance, self.cache_name, self.func(instance)) return getattr(instance, self.cache_name) def __set__(self, instance, value): setattr(instance, self.cache_name, value) def __delete__(self, instance): if hasattr(instance, self.cache_name): delattr(instance, self.cache_name)
057258f6f8ec245ea98d6ccc1b0c4124494d3376
krunaljain/Data-Mining-top-influencers-in-a-social-network
/adjacencyMatrix.py
1,192
3.671875
4
# Adjacency matrix for the graph def create_adj_matrix(adjacency_list): max_length = 0 for node, neighbors in adjacency_list.items(): if node > max_length: max_length = node temp_max = max(neighbors) if temp_max > max_length: max_length = temp_max # initialize a matrix for the range (0 -> max_length) adjacency_matrix = [[0 for i in range(0, max_length + 1)] for j in range(max_length + 1)] for node, neighbors in adjacency_list.items(): for neighbor in neighbors: adjacency_matrix[node][neighbor] = 1 adjacency_matrix[neighbor][node] = 1 # print(max_length) = 4038 for facebook dataset return adjacency_matrix def print_matrix(matrix): for i in range(0, len(matrix)): print("\n ", matrix[i], ":") for j in range(0, len(matrix)): print(matrix[i][j]) ''' Testing: def test(): g = Graph() g.add_edge(1, 2) g.add_edge(2, 4) g.add_edge(5, 3) g.add_edge(1, 4) g.add_edge(2, 3) g.print_graph() adjacency_list = g.adjlist() adjacency_matrix = create_adj_matrix(adjacency_list) print(adjacency_matrix) test() '''
59f1ef08f8c86e9d443140c547ab007931505300
Jhumbl/A-Multilayer-Network-Understanding-of-Foursquare-Checkins
/network_functions.py
6,725
3.546875
4
''' NETWORK ANALYSIS COURSEWORK 2 FUNCTIONS ======================================== Author: Jack Humble Email: jack.humble@kcl.ac.uk Date: 01/04/2019 This document contains functions creating the networks for the project as well as the functions needed for the recommender system. ''' import pandas as pd import numpy as np import matplotlib.pyplot as plt import networkx as nx from itertools import compress import random def create_interaction_dataframe(csvFile, fileName, networkType = "colocation"): ''' Contains the code for creating an interaction dataframe from the Foursquare kaggle dataset (https://www.kaggle.com/chetanism/foursquare-nyc-and-tokyo-checkin-dataset/). The returned interaction dataframe can be either a network of colocation or taste. The returned dataframe is directly analysable by networkx using: nx.from_pandas_edgelist(interaction_df, source=0, target=1) Parameters ---------- csvFile : pandas.DataFrame (required) pandas dataframe containing the desired rows from the Foursquare checkins dataset fileName : string (required) path to csv file in which csv will be written networkType : string ("colocation" or "taste") (optional) The type of network which will be created Returns ------- interaction_df : pandas.DataFrame DataFrame containing interaction edges of user network source = integer 0 target = integer 1 ''' # network types networkTypes = ["colocation", "taste"] # network type must be colocation of taste if networkType not in networkTypes: raise ValueError("Invalid network type. Expected one of: %s" % networkTypes) # networkType dictionary net_dict = {"colocation" : "venueId", "taste" : "venueCateg"} # Initialise list of list of venues/types each user has been to venuePerUser = [] users = set(csvFile["userId"]) # Create list of list of venues/types each user has been to for user in users: venuePerUser.append(csvFile[net_dict.get(networkType)].loc[csvFile["userId"] == user]) # initialise interaction dataframe for colocation network intdf = [] print("creating interaction dataframe...") # create colocation network for idx, user in enumerate(users): for tidx, targetUser in enumerate(users): # If users share at least one venue, add edge between them if (np.isin(venuePerUser[idx - 1], venuePerUser[tidx - 1]).sum() > 0) and (user != targetUser): intdf.append([user, targetUser]) # primitive loading bar if user % 100 == 0: print("-", end = "") # turn into pandas dataframe intdf2 = pd.DataFrame(intdf) # remove opposite interactions as network is undirected frozen = {frozenset(x) for x in intdf} unique_intdf = [list(x) for x in frozen] # turn into pandas dataframe unique_intdf = pd.DataFrame(unique_intdf) print("") print("writing csv...") unique_intdf.to_csv("interaction_dataframes/" + fileName + ".csv") print("csv file created") return unique_intdf def most_similar_node(specific_user): ''' Contains code using data from the Foursquare kaggle dataset (https://www.kaggle.com/chetanism/foursquare-nyc-and-tokyo-checkin-dataset/). The returned dataframe contains the top most similar users to a specified user. Parameters ---------- specific_user : integer (required) a specific userId to find a list of most similar users Returns ------- interaction_df : pandas.DataFrame DataFrame containing interaction edges of user network user = integer number_overlap = integer percentage_overlap = double ''' # Read in nyc file nyc = pd.read_csv("/Users/jackhumble/Documents/KingsCollege/Network_Analysis/Coursework2/data/dataset_TSMC2014_NYC.csv") #print(nyc.head()) # Obtain all the venues specified each node has been to # Initialise list of list of venues/types each user has been to venuePerUser = [] users = set(nyc["userId"]) #print(users) # Create list of list of venue types each user has been to for user in users: venuePerUser.append(nyc["venueCategoryId"].loc[nyc["userId"] == user]) overlap = [] # for specified node, which node overlaps the most for targetUser in users: overlap.append([targetUser, np.isin(venuePerUser[specific_user - 1], venuePerUser[targetUser - 1]).sum()]) overlap = pd.DataFrame(overlap) overlap = overlap.sort_values([1], ascending = False) # Express overlap as a percentage similarity overlap["percentage_overlap"] = round((overlap[1]/overlap.iloc[0][1]) * 100, 2) overlap.columns = ["user", "number_overlap", "percentage_overlap"] overlap = overlap.reset_index(drop = True) return overlap def venue_recommendation(specific_user, no_of_venues_to_return = 5): ''' This contains code which recommends a list of 5 venue ID's to a specified user based on the users with the most similar taste. Parameters ---------- specific_user : integer (required) a specific user to recommend a list of five venues. no_of_venues_to_return : integer (optional) the number of recommended venues to return Returns ------- venue_recommendation : list list of five venues for a specfied user. ''' # Extract a table of most similar users data = most_similar_node(specific_user) # Extract most similar user most_similar_user = data.iloc[1:2, 0] # Read in nyc file nyc = pd.read_csv("/Users/jackhumble/Documents/KingsCollege/Network_Analysis/Coursework2/data/dataset_TSMC2014_NYC.csv") # Obtain all the venues specified each node has been to # Initialise list of list of venues/types each user has been to venuePerUser = [] users = set(nyc["userId"]) #print(users) # Create list of list of venue types each user has been to for user in users: venuePerUser.append(nyc["venueCategoryId"].loc[nyc["userId"] == user]) # Get venues for each user specific_user_venues = venuePerUser[specific_user] similar_user_venues = venuePerUser[int(most_similar_user)] # find venues in similar_user that are not in specific_user difference = np.isin(similar_user_venues, specific_user, invert=True) # return these venues return list(compress(similar_user_venues, difference))[0:no_of_venues_to_return]
838ed45152864302cd35a611483bfecce3f9dbf4
tuankhaitran/Pythonpractices
/UnitTest/test_circle.py
685
3.859375
4
import unittest from circles import circle_area from math import pi class TestCircleArea(unittest.TestCase): # Test function def test_area(self): #Test when radius > 0 self.assertAlmostEqual(circle_area(1),pi) self.assertAlmostEqual(circle_area(0),0) self.assertAlmostEqual(circle_area(2.1),pi*2.1**2) def test_values(self): #Make sure value errors are raised when necessary self.assertRaises(ValueError,circle_area,-2) def test_types(self): self.assertRaises(TypeError, circle_area,True) self.assertRaises(TypeError, circle_area,"aoc") self.assertRaises(TypeError, circle_area,3+5j)
8318b83447b807eb82a5995a1859443fe98b77fa
chixujohnny/Leetcode
/Leetcode2019/58. 最后一个单词的长度.py
284
3.9375
4
# coding: utf-8 class Solution(object): def lengthOfLastWord(self, s): if len(s.replace(' ','')) == 0: return 0 s = s.strip().split(' ') return len(s[-1]) s = Solution() print s.lengthOfLastWord(' ') print s.lengthOfLastWord('hello world')
59a607099cab1ebce548777a49f0edace6ea11c6
Gummy-stack/Teaching-Python-on-stepik
/metiz_3.4-3.7.py
6,028
3.78125
4
""" 3.4. Список гостей: если бы вы могли пригласить кого угодно (из живых или умерших) на обед, то кого бы вы пригласили? Создайте список, включающий минимум трех людей, которых вам хотелось бы пригласить на обед. Затем используйте этот список для вывода пригласительного сообщения каждому участнику. """ guests = ['number1', 'number2', 'number3', 'number4', 'number5'] message = f'Добро пожаловать на праздник, ' for x in guests: print(message + x.title(), sep='\n') print('___________________________________________________________________________________________________________') """ 3.5. Изменение списка гостей: вы только что узнали, что один из гостей прийти не сможет, поэтому вам придется разослать новые приглашения. Отсутствующего гостя нужно заменить кем-то другим. •Начните с программы из упражнения 3.4. Добавьте в конец программы команду print для вывода имени гостя, который прийти не сможет. •Измените список и замените имя гостя, который прийти не сможет, именем нового приглашенного. •Выведите новый набор сообщений с приглашениями — по одному для каждого участника, входящего в список. """ guests_old = guests.pop().title() message1 = f'К сожалению на праздник не сможет прийти {guests_old}!' print(message1) guests.append('number6') message2 = f'Вместо {guests_old} к нам придет {guests[4].title()}!' print(message2) for x in guests: print(message + x.title(), sep='\n') print('___________________________________________________________________________________________________________') """ 3.6. Больше гостей: вы решили купить обеденный стол большего размера. Дополнительные места позволяют пригласить на обед еще трех гостей. •Начните с программы из упражнения 3.4 или 3.5. Добавьте в конец программы команду print, которая выводит сообщение о расширении списка гостей. •Добавьте вызов insert() для добавления одного гостя в начало списка. •Добавьте вызов insert() для добавления одного гостя в середину списка. •Добавьте вызов append() для добавления одного гостя в конец списка. •Выведите новый набор сообщений с приглашениями — по одному для каждого участника, входящего в список. """ print('Уважаемые гости к нам пришли наши новые друзья!') guests.insert(0, 'number7') guests.insert(4, 'number8') guests.insert(7, 'number9') for x in guests: print(message + x.title(), sep='\n') print(guests) print('___________________________________________________________________________________________________________') """ 3.7. Сокращение списка гостей: только что выяснилось, что новый обеденный стол привезти вовремя не успеют и места хватит только для двух гостей. •Начните с программы из упражнения 3.6. Добавьте команду для вывода сообщения о том, что на обед приглашаются всего два гостя. •Используйте метод pop() для последовательного удаления гостей из списка до тех пор, пока в списке не останутся только два человека. Каждый раз, когда из списка удаляется очередное имя, выведите для этого человека сообщение о том, что вы сожалеете об отмене приглашения. •Выведите сообщение для каждого из двух человек, остающихся в списке. Сообщение должно подтверждать, что более раннее приглашение остается в силе. •Используйте команду del для удаления двух последних имен, чтобы список остался пустым. Выведите список, чтобы убедиться в том, что в конце работы программы список действительно не содержит ни одного элемента. """ print('Новый обеденный стол привезти вовремя не успеют и места хватит только для двух гостей') message3 = f'К сожалению на праздник не сможет прийти ' while len(guests) > 2: print(message3 + guests.pop().title(), sep='\n') print('Осталось 2 гостя') print(guests) message4 = f'Предложение остается в силе для ' for x in guests: print(message4 + x.title(), sep='\n') del guests[0] del guests[0] print(guests) print('___________________________________________________________________________________________________________')
4e5131694561766df044283af92a3dff4adee528
DiegoSantosWS/estudos-python
/estudo-6/tuplas.py
2,221
4.09375
4
print("Tupla com parênteses") linguagens = ("Assembly", "Cobol", "C", "C++") print(linguagens) # para saltar uma linha no resultado, deixando mais fácil sua leitura # posso usar print() ou "\n" (quebra de linha) print("\nTupla sem parênteses") linguagens = "Python", "Java", "Go", "C#" print(linguagens) print("\nAcessando elementos pelo índice") paises = "Brasil", "Paraguai", "Uruguai", "México" pais = paises[0] print(pais) # Brasil print("\nFatiando tupla") fatia = paises[1:3] print(fatia) # ('Paraguai', 'Uruguai') print() print("Percorrendo elementos da tupla com for") paises = "Brasil", "Paraguai", "Uruguai", "México" for pais in paises: print(pais) print("\nConvertendo uma lista em tupla usando tuple") lista_carros = ["Gol", "Corolla", "Ranger", "Kadett", "Fusca", "Clio"] tupla_carros = tuple(lista_carros) print(f"Tupla carros: {tupla_carros}") print("\nConvertendo uma tupla em lista usando list") tupla_carros = "Gol", "Corolla", "Ranger", "Kadett", "Fusca", "Clio" lista_carros = list(tupla_carros) print(f"Lista carros: {lista_carros}") print("\nDesempacotando elementos da tupla") tupla_carros = "Golf", "Corolla", "Civic" carro1, carro2, carro3 = tupla_carros print(f"Carro1: {carro1}") print(f"Carro2: {carro2}") print(f"Carro3: {carro3}") print("\nDesempacotando vários elementos para uma lista. Atribuição múltipla") #Barra invertida indica que a linha continua tupla_carros = "Golf", "Corolla", "Civic", "Opala", \ "Tucson", "Elantra" carro1, *carros = tupla_carros print(f"Carro1: {carro1}") print(f"Carros: {carros}") # Uma lista com os itens restantes print("\nAtribuição múltipla não precisa estar no fim da sequência") tupla_carros = "Golf", "Corolla", "Civic", "Opala", \ "Tucson", "Elantra" *carros, tucson, elantra = tupla_carros print(f"Carros: {carros}") print(f"Tucson: {tucson}") print(f"Elantra: {elantra}") print("\nUma lista como elemento de uma tupla") tupla = ("Python", 10.25, 36, ["Ônibus", "Avião", "Navio", "Carro"]) print(tupla[0]) #Python print(tupla[1]) # 10.25 print(tupla[2]) # 36 print(tupla[3]) # ['Ônibus', 'Avião', 'Navio', 'Carro'] lista = tupla[3] print(lista) #['Ônibus', 'Avião', 'Navio', 'Carro'
00565d6f6597df1fb7cbd6f3f92678bb8753bf87
AlbertoParravicini/nlp-ulb
/assignment-1/code/perplexity.py
3,788
3.578125
4
import pandas as pd import numpy as np import re import timeit import string from language_model import preprocess_string def perplexity(string, language_model, log=True, vocabulary=list(string.ascii_lowercase[:26] + "_")): """ Computes the perplexity of a given string, for the specified language model. Given a sentence composed by character [c_1, c_2, ..., c_n], perplexity is defined as P(c_1, c_2, ..., c_n)^(-1/n). :param string: the input string on which perplexity is computed :param language_model: language model used to compute perplexity. It is a matrix in which entry [i, j, k] is P(k | j, i). :param log: returns perplexity in log-space. :param vocabulary: the vocabulary that is used to evaluate the perplexity. :return: the perplexity of the sentence. """ v_dict = {char: num for num, char in enumerate(vocabulary)} perp = 0 for i in range(len(string) - 2): perp += np.log2(language_model[v_dict[string[i-2]], v_dict[string [i-1]], v_dict[string[i]]]) perp *= -(1/len(string)) return perp if log==True else 2**perp def analyze_results(results, true_cond, perc=True): """ :param results: a list of tuples of the form (real_label, predicted_label) :param true_cond: label that should be considered as true condition :param perc: if true, give the results as % instead than absolute values :return: a dictionary with keys [TP, FN, FP, TN] """ tp = sum([item[0] == true_cond and item[1] == true_cond for item in results]) fn = sum([item[0] == true_cond and item[1] != true_cond for item in results]) fp = sum([item[0] != true_cond and item[1] == true_cond for item in results]) tn = sum([item[0] != true_cond and item[1] != true_cond for item in results]) confusion_matrix = {"TP": tp, "FN": fn, "FP": fp, "TN": tn} return confusion_matrix if not perc else {k: v / len(results) for k, v in confusion_matrix.items()} def accuracy(results): """ :param results: a list of tuples of the form (real_label, predicted_label) :return: accuracy of the results, expressed as the percentage of labels correctly predicted. """ return sum([item[0] == item[1] for item in results]) / len(results) model_names = ["GB", "US", "AU"] language_models = {} for model_name in model_names: language_models[model_name] = np.load("language_model_freq_" + model_name + ".npy") test_filename = "data/test.txt" results = [] with open(test_filename, encoding="utf8") as f: lines = f.readlines() for l in lines: [label, sentence] = l.split("\t", 1) sentence = preprocess_string(sentence) perp_res = {k: perplexity(sentence, language_model) for k, language_model in language_models.items()} results.append((label, min(perp_res.keys(), key=(lambda key: perp_res[key])))) print(sentence[:6], "-- REAL LABEL:", label, "-- PERP:", perp_res) print(results) print("\n======== GB =========\n\n", analyze_results(results, "GB", False)) print("\n======== US =========\n", analyze_results(results, "US", False)) print("\n======== AU =========\n", analyze_results(results, "AU", False)) print("\n===== ACCURACY ======\n", accuracy(results)) #import scipy.io as sio # def save_to_matlab(filename, object_name): # occ_matrix = np.load(filename + ".npy") # occ_matrix -= 1 # sio.savemat(filename + ".mat", {object_name: occ_matrix}) # # occ_matrix_gb = np.load("language_model_occ_GB.npy") # occ_matrix_gb -= 1 # sio.savemat("language_model_occurrencies_GB.mat", {"occ_matrix_gb": occ_matrix_gb}) # # save_to_matlab("language_model_occ_GB_small", "occ_matrix_gb_small") # save_to_matlab("language_model_occ_US_small", "occ_matrix_us_small") # save_to_matlab("language_model_occ_AU_small", "occ_matrix_au_small")
a589d62705ba2f1e9aa51c3fa46c6176ebb273a6
itsolutionscorp/AutoStyle-Clustering
/all_data/exercism_data/python/bob/defc5c0f3d5f4c029a61737f7424d144.py
537
3.921875
4
# Implementation of Bob, a lackadaisical teenager def contains_alpha(str): """check if str contains any alphabet characters""" for x in str: if x.isalpha(): return True return False def hey(str): """Say str to bob. Bob responds (lackadaisically)!""" str = str.strip() if not str: return "Fine. Be that way!" elif str.upper() == str and contains_alpha(str): return "Whoa, chill out!" elif str[-1] == '?': return "Sure." else: return "Whatever."
9d1252ad15b454e333eda7af2dafa89c543ea135
zhangbo1888/timeTransverter
/timeTransverter.py
2,439
3.578125
4
from tkinter import * from time import * ''' 1、这个程序实现时间戳和日期格式的相互转换。 2、使用grid方法按照表格方式对组件位置进行安排 3、通过Button按钮进行转换和刷新操作。 4、通过Entry来获取用户输入。 ''' root = Tk() root.title('时间戳转换') root.resizable(0,0)#禁止拉伸 会变丑 # 对变量进行创建,和数据初始化 Label1 = Label(root, text='时间戳:').grid(row=0, column=0) Label2 = Label(root, text='日期:').grid(row=1, column=0) v1 = StringVar() p1 = StringVar() v1.set(int(time())) Label3 = Label(root, text='日期:').grid(row=3, column=0) Label4 = Label(root, text='时间戳').grid(row=4, column=0) v2 = StringVar() p2 = StringVar() timeArray1 = localtime(int(time())) v2.set(strftime("%Y-%m-%d %H:%M:%S", timeArray1)) p2.set(int(time())) #时间戳转换成日期 def trans1(): e1 = Entry(root, textvariable=v1) # Entry 是 Tkinter 用来接收字符串等输入的控件. e2 = Entry(root, textvariable=p1) e1.grid(row=0, column=1, padx=10, pady=5) # 设置输入框显示的位置,以及长和宽属性 e2.grid(row=1, column=1, padx=10, pady=5) timeArray = localtime(int(e1.get())) p1.set(strftime("%Y-%m-%d %H:%M:%S", timeArray)) #日期转换为时间戳 def trans2(): e3 = Entry(root, textvariable=v2) # Entry 是 Tkinter 用来接收字符串等输入的控件. e4 = Entry(root, textvariable=p2) e3.grid(row=3, column=1, padx=10, pady=5) # 设置输入框显示的位置,以及长和宽属性 e4.grid(row=4, column=1, padx=10, pady=5) p2.set(int(mktime(strptime(e3.get(), "%Y-%m-%d %H:%M:%S")))) #刷新第二个模组 def refresh(): timeArray1 = localtime(int(time())) v2.set(strftime("%Y-%m-%d %H:%M:%S", timeArray1)) p2.set(int(time())) Button(root, text='转换', width=10, command=trans1) \ .grid(row=2, column=0, sticky=W, padx=10, pady=5) Button(root, text='转换', width=10, command=trans2) \ .grid(row=5, column=0, sticky=W, padx=10, pady=5) Button(root, text='刷新', width=10, command=refresh) \ .grid(row=5, column=1, sticky=W, padx=10, pady=5) Button(root, text='退出', width=10, command=root.quit) \ .grid(row=6, column=1, sticky=E, padx=10, pady=5) trans1() trans2() #设置窗口初始显示位置 sw = root.winfo_screenwidth() sh = root.winfo_screenheight() x = (sw) / 2 y = (sh) / 2 root.geometry("+%d+%d" %(x,y)) mainloop()
993b5b868445d3049f15dc875f0b26db0aec85ad
DigiDuncan/AdventOfCode2020
/advent/advent.py
770
3.796875
4
from advent import days from advent.lib.utils import tryInt def main(): day = tryInt(input("Day? ")) part = tryInt(input("Part? ")) if not isinstance(day, int): print(f"{day} is not an integer.") return if not isinstance(part, int): print(f"{part} is not an integer.") return if not getattr(days, f"day{day}", None): print(f"Day {day} has not been coded yet!") return if part not in [1, 2]: print("There is only a part 1 and 2.") return print("-" * 25 + "\n") print(getattr(getattr(days, f"day{day}"), f"part{part}")()) print("wow") # This is needed, or else calling `python -m <name>` will mean that main() is called twice. if __name__ == "__main__": main()
12499347984ced85f73ce2258db7bde81568490e
joe-salih/SelectionMenu
/Selection Menu Design v1.py
20,629
3.671875
4
#Imports import tkinter as tk from tkinter import * from tkinter import ttk from tkinter.ttk import * import tkinter.font as font def Space(): space =tk.Label(bg=bgSetting, text="\n") space.pack() #Global Variables fontSize = "Large" buttonSize = "Small" fontColour = "Black" bgColour = "Grey" errorColour = "OrangeRed3" bgSetting = "" fontSetting = "" titleSize = 0 fontSet = 0 buttonFont = 0 height = 0 width = 0 buttonSetting = "" #Temporary Values check = 0 check2 = 0 check3 = 0 check4 = 0 fontColours=["Black", "White", "Light Blue", "Blue", "Dark Blue", "Red", "Purple", "Yellow", "Light Green", "Dark Green"] bgColours=["Black", "White", "Grey", "Dark Grey", "Light Blue", "Blue", "Dark Blue", "Red", "Purple", "Yellow", "Light Green", "Dark Green", "Neutral"] sizes=["Small", "Medium", "Large"] ########################################################################################################################################################################### """ Colour correspondance Black = Black White = White Grey = Grey94 Dark Grey = Grey40 Light Blue = Cornflower Blue Blue = Medium Blue Dark Blue = Navy Red = FireBrick2 Purple = Dark Orchid Yellow = Yellow Light Green = Lime Green Dark Green = Dark Green Neutral = Burlywood1 """ ########################################################################################################################################################################### def BackgroundSet(): global bgColour global bgSetting global errorColour global buttonSetting if bgColour == "Black": bgSetting = "Black" buttonSetting = "Grey30" errorColour = "Orange Red" elif bgColour == "White": bgSetting = "Snow" buttonSetting = "Grey80" errorColour = errorColour elif bgColour == "Grey": bgSetting = "Grey94" buttonSetting = "DarkGrey" errorColour = errorColour elif bgColour == "Dark Grey": bgSetting = "Grey40" buttonSetting = "Grey80" errorColour = "White" elif bgColour == "Light Blue": bgSetting = "Cornflower Blue" buttonSetting = "Navy" errorColour = errorColour elif bgColour == "Blue": bgSetting = "Medium Blue" buttonSetting = "Navy" errorColour = "Orange Red" elif bgColour == "Dark Blue": bgSetting = "Navy" buttonSetting = "Cornflower Blue" errorColour = errorColour elif bgColour == "Red": bgSetting = "FireBrick2" buttonSetting = "FireBrick4" errorColour = "Black" elif bgColour == "Purple": bgSetting = "Dark Orchid" buttonSetting = "MediumOrchid4" errorColour = "Grey99" elif bgColour == "Yellow": bgSetting = "Yellow" buttonSetting = "Goldenrod3" errorColour = errorColour elif bgColour == "Light Green": bgSetting = "Lime Green" buttonSetting = "Dark Green" errorColour = "OrangeRed4" elif bgColour == "Dark Green": bgSetting = "Dark Green" buttonSetting = "Lime Green" errorColour = "Orange Red" elif bgColour == "Neutral": bgSetting = "Burlywood1" buttonSetting = "Burlywood4" errorColour = "Black" else: bgColour = bgColour def FontSet(): global fontColour global fontSetting if fontColour == "Black": fontSetting = "Black" elif fontColour == "White": fontSetting = "Snow" elif fontColour == "Light Blue": fontSetting = "Cornflower Blue" elif fontColour == "Blue": fontSetting = "Medium Blue" elif fontColour == "Dark Blue": fontSetting = "Navy" elif fontColour == "Red": fontSetting = "FireBrick2" elif fontColour == "Purple": fontSetting = "Dark Orchid" elif fontColour == "Yellow": fontSetting = "Yellow" elif fontColour == "Light Green": fontSetting = "Lawn Green" elif fontColour == "Dark Green": fontSetting = "Dark Green" else: fontColour = fontColour def FontSize(): global fontSize global titleSize global fontSet global buttonFont if fontSize == "Small": titleSize = 24 fontSet = 16 buttonFont = 16 elif fontSize == "Medium": titleSize = 36 fontSet = 18 buttonFont = 24 elif fontSize == "Large": titleSize = 36 fontSet = 26 buttonFont = 36 else: fontSize = fontSize def ButtonSize(): global buttonSize global fontSize global height if buttonSize == "Small": if fontSize == "Small": height = 2 elif fontSize == "Medium": height = 1 else: height = 1 elif buttonSize == "Medium": if fontSize == "Small": height = 3 elif fontSize == "Medium": height = 2 else: height = 1 elif buttonSize == "Large": if fontSize == "Small": height = 3 elif fontSize == "Medium": height = 2 else: height = 1 else: buttonSize = buttonSize def SelectionMenu(): def MainMenu(): global fontSize global buttonSize global fontColour global bgColour global bgSetting global fontSetting global errorColour global titleSize global fontSet global height global width global buttonSetting global buttonFont BackgroundSet() FontSet() FontSize() ButtonSize() #Sorting Button Widths if buttonSize == "Small": width = 20 elif buttonSize == "Medium": width = 25 elif buttonSize == "Large": width = 30 else: buttonSize = buttonSize Menu = tk.Tk() Menu.configure() Menu.attributes("-fullscreen", True) Menu['bg']=bgSetting global screenWidth screenWidth = Menu.winfo_screenwidth() global screenHeight screenHeight = Menu.winfo_screenheight() xPos1 = screenWidth * 0.06 xPos2 = screenWidth * 0.55 yPos1 = screenHeight * 0.2 yPos2 = screenHeight * 0.35 yPos3 = screenHeight * 0.5 yPos4 = screenHeight * 0.65 yPos5 = screenHeight * 0.8 #Sorting Button Positions if fontSize == "Small": buttonY1=yPos1 buttonY2=yPos2 buttonY3=yPos3 buttonY4=yPos4 buttonY5=yPos5 if buttonSize == "Small": buttonY1=buttonY1+60 buttonY2=buttonY2+30 buttonY3=buttonY3 buttonY4=buttonY4-30 buttonY5=buttonY5-60 elif buttonSize == "Medium": buttonY1=buttonY1+20 buttonY2=buttonY2+10 buttonY3=buttonY3 buttonY4=buttonY4-10 buttonY5=buttonY5-20 else: buttonY1=buttonY1-20 buttonY2=buttonY2-15 buttonY3=buttonY3-10 buttonY4=buttonY4-5 buttonY5=buttonY5 elif fontSize == "Medium": buttonY1=yPos1+30 buttonY2=yPos2+30 buttonY3=yPos3+30 buttonY4=yPos4+30 buttonY5=yPos5+30 if buttonSize == "Small": buttonY1=buttonY1+60 buttonY2=buttonY2+30 buttonY3=buttonY3 buttonY4=buttonY4-30 buttonY5=buttonY5-60 elif buttonSize == "Medium": buttonY1=buttonY1 buttonY2=buttonY2 buttonY3=buttonY3 buttonY4=buttonY4 buttonY5=buttonY5 else: buttonY1=buttonY1 buttonY2=buttonY2 buttonY3=buttonY3 buttonY4=buttonY4 buttonY5=buttonY5 elif fontSize == "Large": buttonY1=yPos1+50 buttonY2=yPos2+50 buttonY3=yPos3+50 buttonY4=yPos4+50 buttonY5=yPos5+50 if buttonSize == "Small": buttonY1=buttonY1+20 buttonY2=buttonY2+10 buttonY3=buttonY3 buttonY4=buttonY4-10 buttonY5=buttonY5-20 elif buttonSize == "Medium": buttonY1=buttonY1+20 buttonY2=buttonY2+10 buttonY3=buttonY3 buttonY4=buttonY4-10 buttonY5=buttonY5-20 else: buttonY1=buttonY1+20 buttonY2=buttonY2+10 buttonY3=buttonY3 buttonY4=buttonY4-10 buttonY5=buttonY5-20 else: fontSize = fontSize Space() Title = tk.Label(Menu, text="Projectile Motion and Collision Simulator") Title['font'] = font.Font(family='Fixedsys', size=titleSize, weight='bold') Title['background'] = bgSetting Title['foreground'] = fontSetting Title.pack() Space() Heading = tk.Label(Menu, text="What would you like to do?") Heading['font'] = font.Font(family='Fixedsys', size=fontSet, weight='bold') Heading['background'] = bgSetting Heading['foreground'] = fontSetting Heading.pack() def MenuToVectors(event): Menu.destroy() print("VectorCalculations()") def MenuToProjectileMotion(event): Menu.destroy() print("ProjectileMotion()") def MenuToCollisions(event): Menu.destroy() print("Collisions()") def MenuToSettings(event): Menu.destroy() Settings() def LogOut(event): Menu.destroy() print("LoginSystem()") VectorClick = tk.Button(Menu, text="3-D Vectors", fg=fontSetting, bg=buttonSetting, height=height, width=width) VectorClick['font'] = font.Font(size=buttonFont) vectorWidth = VectorClick.winfo_reqwidth() VectorClick.place(x=((screenWidth/2)-(vectorWidth/2)), y=buttonY1) VectorClick.bind("<Button-1>",MenuToVectors) ProjectileMotionClick = tk.Button(Menu, text="Projectile Motion", fg=fontSetting, bg=buttonSetting, height=height, width=width) ProjectileMotionClick['font'] = font.Font(size=buttonFont) projectileWidth = ProjectileMotionClick.winfo_reqwidth() ProjectileMotionClick.place(x=((screenWidth/2)-(projectileWidth/2)), y=buttonY2) ProjectileMotionClick.bind("<Button-1>",MenuToProjectileMotion) CollisionClick = tk.Button(Menu, text="Collsions", fg=fontSetting, bg=buttonSetting, height=height, width=width) CollisionClick['font'] = font.Font(size=buttonFont) collisionWidth = CollisionClick.winfo_reqwidth() CollisionClick.place(x=((screenWidth/2)-(collisionWidth/2)), y=buttonY3) CollisionClick.bind("<Button-1>",MenuToCollisions) SettingsClick = tk.Button(Menu, text="Settings", fg=fontSetting, bg=buttonSetting, height=height, width=width) SettingsClick['font'] = font.Font(size=buttonFont) settingsWidth = SettingsClick.winfo_reqwidth() SettingsClick.place(x=((screenWidth/2)-(settingsWidth/2)), y=buttonY4) SettingsClick.bind("<Button-1>",MenuToSettings) LogOutClick = tk.Button(Menu, text="Log Out", fg=fontSetting, bg=buttonSetting, height=height, width=width) LogOutClick['font'] = font.Font(size=buttonFont) logoutWidth = LogOutClick.winfo_reqwidth() LogOutClick.place(x=((screenWidth/2)-(logoutWidth/2)), y=buttonY5) LogOutClick.bind("<Button-1>",LogOut) def Settings(): global fontSize global buttonSize global fontColour global bgColour global bgSetting global errorColour global titleSize global fontSet global height global width global buttonSetting global buttonFont global sizes global fontColours global bgColours global check global check2 global check3 global check4 check = 0 check2 = 0 check3 = 0 check4 = 0 if fontSize == "Small": add = 30 boxWidth = 30 elif fontSize == "Medium": add = 50 boxWidth = 40 elif fontSize == "Large": add = 60 boxWidth = 50 else: fontSize = fontSize Setting = tk.Tk() Setting.configure() Setting.attributes("-fullscreen", True) Setting['bg']=bgSetting Space() Title = tk.Label(Setting, text="Settings") Title['font'] = font.Font(family='Fixedsys', size=titleSize, weight='bold') Title['background'] = bgSetting Title['foreground'] = fontSetting Title.pack() Space() global screenWidth global screenHeight xPos1 = screenWidth * 0.17 xPos2 = screenWidth * 0.55 yPos1 = screenHeight * 0.2 yPos2 = screenHeight * 0.35 yPos3 = screenHeight * 0.5 yPos4 = screenHeight * 0.65 yPos5 = screenHeight * 0.8 yPos3_5 = yPos3+((yPos4-yPos3)/2) def BackToMenu(event): Setting.destroy() MainMenu() backArrow = PhotoImage(file = r"E:\Computer Science Programming Project\Images\BackArrow.png") backArrowSized = backArrow.subsample(6,6) BackButton = tk.Button(Setting, bg=buttonSetting, image=backArrowSized, fg=fontSetting) BackButton.image=backArrowSized BackButton.place(x=screenHeight*0.06, y=screenHeight*0.06) BackButton.bind("<Button-1>",BackToMenu) FontSizeLabel = tk.Label(Setting, text="Font Size:", bg=bgSetting, fg=fontSetting) FontSizeLabel['font'] = font.Font(family='Fixedsys', size=fontSet) FontSizeLabel.place(x=xPos1, y=yPos2) w = -1 count = 0 for i in sizes: i = str(i) i = i.strip("('") i = i.strip("',)") if i == fontSize: w = count count = count + 1 else: count = count + 1 InitialFont = tk.StringVar(Setting) InitialFont.set(sizes[w]) FontSize = ttk.Combobox(Setting, justify="center", width=boxWidth, textvariable=InitialFont, state="readonly") FontSize['values']=sizes FontSize.configure(foreground="Gray") FontSize.place(x=xPos1, y=yPos2+add, height=40) def ConfigFont(event): global check if check == 0: FontSize.config(foreground="black") check = 1 else: check = check FontSize.bind("<Button-1>",ConfigFont) FontSize.bind("<FocusIn>",ConfigFont) ButtonSizeLabel = tk.Label(Setting, text="Button Size:", bg=bgSetting, fg=fontSetting) ButtonSizeLabel['font'] = font.Font(family='Fixedsys', size=fontSet) ButtonSizeLabel.place(x=xPos2, y=yPos2) x = -1 count2 = 0 for i in sizes: i = str(i) i = i.strip("('") i = i.strip("',)") if i == buttonSize: x = count2 count2 = count2 + 1 else: count2 = count2 + 1 InitialButton = tk.StringVar(Setting) InitialButton.set(sizes[x]) ButtonSize = ttk.Combobox(Setting, justify="center", width=boxWidth, textvariable=InitialButton, state="readonly") ButtonSize['values']=sizes ButtonSize.configure(foreground="Gray") ButtonSize.place(x=xPos2, y=yPos2+add, height=40) def ConfigButton(event): global check2 if check2 == 0: ButtonSize.config(foreground="black") check2 = 1 else: check2 = check2 ButtonSize.bind("<Button-1>",ConfigButton) ButtonSize.bind("<FocusIn>",ConfigButton) FontColourLabel = tk.Label(Setting, text="Font Colour:", bg=bgSetting, fg=fontSetting) FontColourLabel['font'] = font.Font(family='Fixedsys', size=fontSet) FontColourLabel.place(x=xPos1, y=yPos3_5) y = -1 count3 = 0 for i in fontColours: i = str(i) i = i.strip("('") i = i.strip("',)") if i == fontColour: y = count3 count3 = count3 + 1 else: count3 = count3 + 1 InitialColour = tk.StringVar(Setting) InitialColour.set(fontColours[y]) FontColour = ttk.Combobox(Setting, justify="center", width=boxWidth, textvariable=InitialColour, state="readonly") FontColour['values']=fontColours FontColour.configure(foreground="Gray") FontColour.place(x=xPos1, y=yPos3_5+add, height=40) def ConfigColour(event): global check3 if check3 == 0: FontColour.config(foreground="black") check3 = 1 else: check3 = check3 FontColour.bind("<Button-1>",ConfigColour) FontColour.bind("<FocusIn>",ConfigColour) BGColourLabel = tk.Label(Setting, text="Background Colour:", bg=bgSetting, fg=fontSetting) BGColourLabel['font'] = font.Font(family='Fixedsys', size=fontSet) BGColourLabel.place(x=xPos2, y=yPos3_5) z = -1 count4 = 0 for i in bgColours: i = str(i) i = i.strip("('") i = i.strip("',)") if i == bgColour: z = count4 count4 = count4 + 1 else: count4 = count4 + 1 InitialBG = tk.StringVar(Setting) InitialBG.set(bgColours[z]) BGColour = ttk.Combobox(Setting, justify="center", width=boxWidth, textvariable=InitialBG, state="readonly") BGColour['values']=bgColours BGColour.configure(foreground="Gray") BGColour.place(x=xPos2, y=yPos3_5+add, height=40) def ConfigBG(event): global check4 if check4 == 0: BGColour.config(foreground="black") check4 = 1 else: check4 = check4 BGColour.bind("<Button-1>",ConfigBG) BGColour.bind("<FocusIn>",ConfigBG) def SaveAndExit(event): global fontSize global buttonSize global fontColour global bgColour newFontSize = FontSize.get() newButtonSize = ButtonSize.get() newFontColour = FontColour.get() newBGColour = BGColour.get() fontSize = newFontSize buttonSize = newButtonSize fontColour = newFontColour bgColour = newBGColour Setting.destroy() MainMenu() SaveButton = tk.Button(Setting, text="Save and Exit", height=height, bg=buttonSetting, fg=fontSetting) SaveButton['font'] = font.Font(size=buttonFont) saveWidth = SaveButton.winfo_reqwidth() SaveButton.place(x=((screenWidth/2)-(saveWidth/2)), y=yPos5) SaveButton.bind("<Button-1>",SaveAndExit) Error.pack() MainMenu() SelectionMenu()
519753c34a57c9a96e65b429b28cce6f77a103c0
Dython-sky/AID1908
/study/1905/month01/code/Stage1/day08/exercise08.py
205
3.609375
4
""" 统计一个函数的执行次数 """ count = 0 def fun01(): global count count += 1 fun01() fun01() fun01() fun01() fun01() fun01() fun01() print("函数调用了{}次".format(count))
87aff466ed1f153d59c64f66725ef11e5c86d93d
shrddr/hyperskill
/Tic-Tac-Toe with AI/tictactoe.py
8,160
3.53125
4
import random def negate(char): return 'X' if char == 'O' else 'O' class Board: size = 3 def __init__(self, text=None, data=None): if text: self.data = [] if len(text) != self.size * self.size: raise ValueError for c in text: if c in ['_', 'O', 'X']: self.data.append(c) else: raise ValueError self.data = [self.data[self.size * i:self.size * (i + 1)] for i in range(self.size)] else: if data: self.data = [row[:] for row in data] else: self.data = [['_'] * self.size for _ in range(self.size)] def is_x_move(self): xs = 0 for y in range(self.size): xs += self.data[y].count('X') os = 0 for y in range(self.size): os += self.data[y].count('O') return xs == os def is_empty(self, x, y): return self.data[y][x] == '_' def make_move(self, x, y): if self.is_x_move(): self.data[y][x] = 'X' else: self.data[y][x] = 'O' def state(self): for x in range(self.size): if all([self.data[y][x] == 'X' for y in range(self.size)]): return "X wins" if all([self.data[y][x] == 'O' for y in range(self.size)]): return "O wins" for y in range(self.size): if all([self.data[y][x] == 'X' for x in range(self.size)]): return "X wins" if all([self.data[y][x] == 'O' for x in range(self.size)]): return "O wins" if all([self.data[x][x] == 'X' for x in range(self.size)]): return "X wins" if all([self.data[x][self.size - 1 - x] == 'X' for x in range(self.size)]): return "X wins" if all([self.data[x][x] == 'O' for x in range(self.size)]): return "O wins" if all([self.data[x][self.size - 1 - x] == 'O' for x in range(self.size)]): return "O wins" for x in range(self.size): if any([self.data[y][x] == '_' for y in range(self.size)]): return "Game not finished" return "Draw" def __str__(self): s = "---------\n" for y in range(self.size): s += "| " for x in range(self.size): c = self.data[y][x] if c == '_': c = ' ' s += c + " " s += "|\n" s += "---------" return s def human_move(self): while True: print("Enter the coordinates:") text = input() values = text.split(" ") try: y = int(values[0]) x = int(values[1]) if 1 > x or x > 3 or 1 > y or y > 3: print("Coordinates should be from 1 to 3!") continue x = x - 1 y = y - 1 if not self.is_empty(x, y): print("This cell is occupied! Choose another one!") continue self.make_move(x, y) return self.state() except ValueError: print("You should enter numbers!") continue def ai_move_easy(self): print('Making move level "easy"') while True: y = random.choice([0, 1, 2]) x = random.choice([0, 1, 2]) if self.is_empty(x, y): self.make_move(x, y) return self.state() def ai_find_2row(self, c): for x in range(self.size): if [self.data[y][x] == c for y in range(self.size)].count(True) == 2: for y in range(self.size): if self.data[y][x] == '_': return x, y for y in range(self.size): if [self.data[y][x] == c for x in range(self.size)].count(True) == 2: for x in range(self.size): if self.data[y][x] == '_': return x, y if [self.data[x][x] == c for x in range(self.size)].count(True) == 2: for x in range(self.size): if self.data[x][x] == '_': return x, x if [self.data[x][self.size - 1 - x] == c for x in range(self.size)].count(True) == 2: for x in range(self.size): if self.data[x][self.size - 1 - x] == '_': return self.size - 1 - x, x return None def ai_move_medium(self): print('Making move level "medium"') my_char = 'X' if self.is_x_move() else 'O' ret = self.ai_find_2row(my_char) if ret: self.make_move(*ret) return self.state() op_char = 'O' if my_char == 'X' else 'X' ret = self.ai_find_2row(op_char) if ret: self.make_move(*ret) return self.state() while True: y = random.choice([0, 1, 2]) x = random.choice([0, 1, 2]) if self.is_empty(x, y): self.make_move(x, y) return self.state() def ai_estimate(self, master, turn): state = self.state() for c in ['X', 'O']: if state == f"{c} wins": if master == c and turn != c: return 1, None if master == c and turn == c: return -1, None if master != c and turn != c: return -1, None if master != c and turn == c: return 1, None if state == "Draw": return 0, None best_v = -2 if master != turn: best_v = 2 best_xy = (None, None) for y in range(self.size): for x in range(self.size): newstate = Board(data=self.data) # print('copy', newstate) if newstate.is_empty(x, y): newstate.make_move(x, y) t = negate(turn) v, _ = newstate.ai_estimate(master, t) if (master == turn and v > best_v) or (master != turn and v < best_v): best_v = v best_xy = x, y if (master == turn and best_v == 1) or (master != turn and best_v == -1): return best_v, best_xy # print('returning') # print(self.state()) return best_v, best_xy def ai_move_hard(self): print('Making move level "hard"') my_char = 'X' if self.is_x_move() else 'O' _, (x, y) = self.ai_estimate(my_char, my_char) if x is None: print('x is None') print(self) _, (x, y) = self.ai_estimate(my_char, my_char) self.make_move(x, y) return self.state() def play(player_x, player_o): b = Board() fx = b.human_move if player_x == 'easy': fx = b.ai_move_easy if player_x == 'medium': fx = b.ai_move_medium if player_x == 'hard': fx = b.ai_move_hard fo = b.human_move if player_o == 'easy': fo = b.ai_move_easy if player_o == 'medium': fo = b.ai_move_medium if player_o == 'hard': fo = b.ai_move_hard while True: if b.is_x_move(): state = fx() else: state = fo() print(b) if state != "Game not finished": print(state) break AI_MODES = ['easy', 'medium', 'hard'] MODES = ['user'] + AI_MODES if __name__ == "__main__": while True: print("Input command:") text = input() # text = 'start hard medium' if text == 'exit': break try: cmd, px, po = text.split() except ValueError: print('Bad parameters!') continue if cmd == "start" and px in MODES and po in MODES: play(px, po) continue print('Bad parameters!')
cc9abcc56f86e00e0d6747a90cd93ecedd556a9e
roshankprasad/PythonScratchs
/scratch_27.py
1,127
3.96875
4
#hackerrank seating Arrangment question testcases = int(input()) for _ in range(0,testcases): seatNum = int(input()) divby3 = int(seatNum / 3) modby3 = (seatNum % 3) seatBerth = '' if modby3 > 0: compartment = divby3 + 1 else: compartment = divby3; oppositeCompartment = 0 if compartment % 4 == 1: oppositeCompartment = compartment + 3 elif compartment % 4 == 2: oppositeCompartment = compartment + 1 elif compartment % 4 == 3: oppositeCompartment = compartment - 1 elif compartment % 4 == 0: oppositeCompartment = compartment - 3 num = (compartment - 1) * 3 oppositeSeat = oppositeCompartment * 3 - (seatNum - num) + 1 if oppositeSeat % 2 == 0: if modby3 == 1: seatBerth = 'AS' elif modby3 == 2: seatBerth = 'MS' elif modby3 == 0: seatBerth = 'WS' else: if modby3 == 1: seatBerth = 'WS' elif modby3 == 2: seatBerth = 'MS' elif modby3 == 0: seatBerth = 'AS' print(oppositeSeat, seatBerth)
549d583f5e7959c381efaca191eafb7f7e11b3a2
KoderDojo/hackerrank
/python/challenges/algorithms/algo-reducestring.py
1,221
4.09375
4
""" Steve has a string, , consisting of lowercase English alphabetic letters. In one operation, he can delete any pair of adjacent letters with same value. For example, string "aabcc" would become either "aab" or "bcc" after operation. Steve wants to reduce as much as possible. To do this, he will repeat the above operation as many times as it can be performed. Help Steve out by finding and printing 's non-reducible form! Note: If the final string is empty, print Empty String. Sample Input: aaabccddd Sample Output: abd """ def reduce_string(s): """ >>> assert(reduce_string(None) == 'Empty String') >>> assert(reduce_string('') == 'Empty String') >>> assert(reduce_string('abc') == 'abc') >>> assert(reduce_string('aabbc') == 'c') >>> assert(reduce_string('abcc') == 'ab') >>> assert(reduce_string('aabbcc') == 'Empty String') """ if s is None or len(s) == 0: return 'Empty String' stack = [] for char in s: if len(stack) == 0: stack.append(char) continue if char == stack[-1]: stack.pop() else: stack.append(char) return 'Empty String' if len(stack) == 0 else ''.join(stack)
1fe84444ac10a6a11944304adfaa4b498b3460f5
gresendiz/Python
/cubo.py
166
3.84375
4
#Funciones #Escibir el cubo de un numero def cubo(x): y= x * x * x return y a = int(input("Ingresa el valor: ")) b = cubo(a) print("el cubo es: ", b)
268a0ca3c7b728254fb027309d5dba3f7b396e29
ebsud89/leetcode_python
/python/list/Remove Duplicates from Sorted Array.py
356
3.5625
4
from typing import List class Solution: def removeDuplicates(self, nums: List[int]) -> int: idx = 1 for i in range(0, len(nums)): if i != 0 and nums[i - 1] != nums[i]: nums[idx] = nums[i] idx += 1 return idx s = Solution() nums = [1,1,2] print(s.removeDuplicates(nums)) print(nums)
5e7b663cb61a3a1616ebc5dd78682204d13cb8a9
jjspetz/digitalcrafts
/py-exercises1/CtoF.py
179
4.46875
4
''' Python3 program that converts user inputed value in Celsius to Fahrenheit ''' temp = input("Temperature in C? ") temp = float(temp) * 9 / 5 + 32 print("{} F".format(temp))
193741fc10c6c6e36c662471a7985f23984a7851
pranay0124/cspp1
/cspp1-practice/M3/sum_1_end1.py
91
3.90625
4
n = int(input("Enter the value ")) sum = 0 for i in range(1,n+1,1): sum = sum+i print(sum)
bd076f0c97ce42e0c4c09a4ff32c7135de4ca313
Graham84/LearningPython
/Chapter 3 - Iterating and Making Decisions/simplefor1.py
323
4.3125
4
for number in [0, 1, 2, 3, 4]: print(number) for number in range(5): print(number) print list(range(10)) # one value: from 0 to value (excluded) print list(range(3, 8)) # two values: from start to stop (excluded) print list(range(-10, 10, 4)) # three values: steps is added(4)
1e68e86f0b2b35377ab6173a9eb140dfa48e80d3
DamonReyes/Python_Classes-
/Python_Class/PRACTICE_PY/practice_D_S.py
2,646
3.6875
4
def practice_1(): nomb = input('cual es tu nombre?: ') nume = int(input('escribe el numero de reps: ')) print(f' {nomb} tiene {len(nomb)} letras') math1 = 2+3/2.5**2 print(math1) def practice_7(): horas = int(input('numero de horas trabajadas?: ')) coste = horas * 1000 paga = print(f'su paga es {coste} por {horas} horas') ent = int(input('entero: ')) suma = ent + 1 **2 print(suma) def practice_9(): peso = int(input('cual es tu peso? en kg: ')) estatura = float(input('cual es tu estatura? en mts:')) imc = peso / estatura **2 print(f'Tu indice de masa corporal es {round(imc, 3)}') def practice_10(): num1 = int(input('digita un numero: ')) num2 = int(input('digita otro numero: ')) cociente = num1 // num2 resto = num1 % num2 print(f'{num1} entre {num2} da un cociente de {cociente} y un resto de {resto}') def practice_11(): cantidad = int(input('digita la cantidad a invertir: ')) interes = int(input('digita el interes anual: ')) anos = int(input('digite la cantidad de anos: ')) oper = cantidad * interes / 100 oper2 = oper * anos print(f'el capital de la inversion es {oper} y por {anos} anos seria {oper2}') def practice_12(): pes_clown = 112 pes_doll = 75 clown = int(input('cuantos payasos vendieron?: ')) doll = int(input('cuantas munecas vendieron?: ')) print(clown * pes_clown) print(doll * pes_doll) peso = (pes_clown + pes_doll) * (clown + doll) print(f'el peso total de la venta es {peso}') def practice_13(): ano1 = int(input('')) ano2 = int(input('')) ano3 = int(input('')) suma = ano1 + ano2 + ano3 interes = 4.20 operacion = suma * interes print(f'la cantidad de ahorro en estos 3 anos es {operacion}') def practice_14(): pan = 600 panan = pan / 0.6 barrasan = int(input('cuantas barras anejas quieres?: ')) total = pan * barrasan print(f'el total es {total}') print(f'se hixo un descuento de {panan}') if __name__ == '__main__': hi = print('hola mundo!') menu = int(input('cual ejercicio desea realizae?: ')) if menu == 1: practice_1() elif menu == 7: practice_7() elif menu == 9: practice_9() elif menu == 10: practice_10() elif menu == 11: practice_11() elif menu == 12: practice_12() elif menu == 13: practice_13() elif menu == 14: practice_14() else: print('jaja gracias pues c:')
fac39f56d8519489e825715a070e1c6890e10993
twy3009/sparta
/python/datetime_test.py
796
3.5625
4
import datetime def GetWeekNumberLastDate(year, weekNumber): yearFirstDate = datetime.datetime(year, 1, 1) currentDate = yearFirstDate + datetime.timedelta(weeks=weekNumber - 1) targetDate = currentDate - datetime.timedelta(days=currentDate.isoweekday() % 7 - 7) results = targetDate.strftime('%Y%m%d') return results def GetWeekNumberFirstDate(year, weekNumber): yearFirstDate = datetime.datetime(year, 1, 1) currentDate = yearFirstDate + datetime.timedelta(weeks=weekNumber - 1) targetDate = currentDate - datetime.timedelta(days=currentDate.isoweekday() % 7 - 1) results = targetDate.strftime('%Y%m%d') return results print(GetWeekNumberFirstDate(2019, 1)) # 2018-12-31 00:00:00 print(GetWeekNumberLastDate(2019, 1)) # 2019-01-07 00:00:00
50a9db4cdd0d9bc05ece204e273f77d158e53b5d
tpt5cu/python-tutorial
/language/python_27/operators_/asteriks.py
601
4.28125
4
#https://treyhunner.com/2018/10/asterisks-in-python-what-they-are-and-how-to-use-them/ """Also see the functions/parameters/kwargs_py notes""" def copy_dictionary(): """The ** operator can be used inside of a dict() construction to copy one dict into the new dict""" animals = { # Using this ** operator to copy/merge dictionaries is only possible in Python 3 #**my_dict, "cat": "Ralph", "dog": "Persimmon", "fish": "Joe", } copy = dict(**animals) print(copy) print(copy is animals) if __name__ == "__main__": copy_dictionary()
3d106b73baeb06e3bdeeb4ca1e3bc8a71d7b54e4
MichalGk94/Python
/MG5/rekurencja.py
462
3.9375
4
def factorial(n): wynik = 1 if n == 0 or n == 1: return wynik else: for i in range(1, n+1): wynik *= i return wynik def fibonacci(n): wynik = 0 liczba = 0 if n <= 2: return 1 elif n == 3: return 2 else: f1 = 1 f2 = 2 wynik = 0; for i in range(2, n-1): wynik = f1 + f2 f1 = f2 f2 = wynik return wynik
a8e566888e8897be8544d1ae7fecf58be54e57ad
selbovi/python_exercises
/week3/vkladComplex.py
252
3.59375
4
a = int(input()) b = int(input()) c = int(input()) d = int(input()) total = b while d > 0: total = (b * 100 + c) + (a / 100) * (b * 100 + c) b = int(total // 100) c = int(total % 100) d -= 1 print(int(total // 100), int(total % 100))
08b4a7f3f12677e15afddd2d4cad952ecb3c88d0
daedalus/math
/fermat_factor.py
574
4.1875
4
#!/usr/bin/env python # Author Dario Clavijo 2020 # Example taken from https://en.wikipedia.org/wiki/Fermat%27s_factorization_method # GPLv3 import gmpy2 def fermat(n): a = gmpy2.isqrt(n) if a ** 2 == n: return a, a b2 = (a ** 2) - n step = 0 while not gmpy2.is_square(b2): a += 1 b2 = (a ** 2) - n # step += 1 # print(n,step,a,b2) ib2 = gmpy2.isqrt(b2) return a - ib2, a + ib2 def test(): n = 5959 print("-" * 40) a, b = fermat(n) print("-" * 40) print(n, a, b, n == a * b) test()
f13082bd64d29c89fd481228db0b84cdc003591c
rasmusnuko/4sem
/ML/exercise/exercise_6/exercise6-3.py
1,028
3.984375
4
circles = [(1,3), (1,8), (1,9), (4,6), (5,7), (6,8), (7,6)] squares = [(5,4), (6,1), (6,3), (7,2), (7,4), (8,2), (8,3)] ks = [4,7,10] triangle = (6,6) def dist(p,q): # Manhattan dist return abs(p[0]-q[0])+abs(p[1]-q[1]) # Different k's for k-nearest neighbour for k in ks: list = [None] * k # Find distance to all circles and squares distCircles = sorted([dist(circle, triangle) for circle in circles]) distSquares = sorted([dist(square, triangle) for square in squares]) # if a circle is closest neighbour: distances[0]++ distances = [0,0] for x in range(k): if(distCircles[0] < distSquares[0]): distances[0] += 1 distCircles = distCircles[1:] else: distances[1] += 1 distSquares = distSquares[1:] # Found out if most closest neighbours are circles or squares if distances[0] > distances[1]: print("When k =",k, "The triangle is a circle") else: print("When k =",k, "The triangle is a square")
d550bc52e83b8c8d3c36e6cc7ab9fdd56434db65
AayushRajput98/PythonML
/Practice/Tut1/Program4.py
187
4.3125
4
x=int(input("Enter the number")) while not x%2==0: print("Enter a number that is divisible by 2") x=int(input("Enter again")) print("You have finally entered the correct number")
7fbea669880a538a8c0c12c0a9119ebca3b2e6e3
amccarthy9904/foobar
/LeetCode/Medium/FindPeakElement.py
1,134
3.796875
4
# https://leetcode.com/problems/find-peak-element/ # 162. Find Peak Element # Medium # A peak element is an element that is strictly greater than its neighbors. # Given an integer array nums, find a peak element, and return its index. # If the array contains multiple peaks, return the index to any of the peaks. # You must write an algorithm that runs in O(log n) time. # Sollution 1 # Runtime: 44 ms, faster than 73.70% of Python3 submissions # Memory Usage: 14.4 MB, less than 70.46% of Python3 submissions class Solution: def findPeakElement(self, nums: List[int]) -> int: if len(nums) == 1: return 0 mid = len(nums) // 2 if mid <= len(nums) - 2 and nums[mid + 1] > nums[mid]: return mid + self.findPeakElement(nums[mid:len(nums)]) if mid > 0 and nums[mid - 1] > nums[mid]: return self.findPeakElement(nums[0:mid]) return mid # Slicing the array is non optimal # The same can be done with a front and back pointer # Average them to get mid # Set one equal to mid +- 1 # repeat while front <= back
29fdf7b3afa5bbae446008ec948e367952367703
OSP123/Python_exercises
/Assignment_2.py
1,009
4.15625
4
''' Printing a modular letter: Program has two variables, a letter string and a list with tuples inside. The print statements print the letterString. The strings within the tuples in the list replace the %s parts of the letterString. ''' letterString = 'Dear %s,\n\nI would like you to vote for %s\nbecause I think he is best for this state.\n\nSincerely,\n%s\n' listOfTuples = [('Hildegard', 'Barbara Boxer', 'Brunhilda'), ('Cheech', 'Jerry Brown', 'Chong'), ('Kaneda', 'Akira', 'Tetsuo')] print ( letterString % listOfTuples[0]) print ( letterString % listOfTuples[1]) print ( letterString % listOfTuples[2]) '''---------------Output------------------ Dear Hildegard, I would like you to vote for Barbara Boxer because I think he is best for this state. Sincerely, Brunhilda Dear Cheech, I would like you to vote for Jerry Brown because I think he is best for this state. Sincerely, Chong Dear Kaneda, I would like you to vote for Akira because I think he is best for this state. Sincerely, Tetsuo '''
b583922c366c6e6b39567c1d0f7046bc446b3d07
adityaveldi/simplepythonprograms
/venv/functions.py
269
4.03125
4
# Now let us see how to use functions in python #we have to use def keyword for defining functions def add(x,y): a=x b=y c=a+b print('the sum is',c) x=int(input('enter first value for addition')) y=int(input('enter second value for addition')) add(x,y)
c2d30c76377cf3f3eabe69acf73425686e47070c
anniasebold/prog1-ufms
/if else/lanche.py
268
3.5
4
cod, qtd = input().split() cod = int(cod) qtd = int(qtd) if cod == 1: total = qtd * 4.00 elif cod == 2: total = qtd * 4.50 elif cod == 3: total = qtd * 5.00 elif cod == 4: total = qtd * 2.00 elif cod == 5: total = qtd * 1.50 print(f"Total: R$ {total:.2f}")
1e4a671bfd2b73a01e77db96b193dcabfac8c453
RubenPants/RobotSimulator2D
/population_inspection.py
1,007
3.5
4
""" inspect.py Inspect a population of choice. """ import argparse from collections import Counter from population.population import Population def count_genome_sizes(population): c = Counter() for g in population.population.values(): c[g.size()] += 1 return c if __name__ == '__main__': parser = argparse.ArgumentParser(description='') parser.add_argument('--pop', type=str, default='test') parser.add_argument('--count_size', type=bool, default=True) args = parser.parse_args() pop = Population( name=args.pop, # version=1, ) # mut_idx = 2 # print(list(pop.population.values())[mut_idx].size()) # for _ in range(10): # list(pop.population.values())[mut_idx].mutate(pop.config.genome_config) # print(list(pop.population.values())[mut_idx].size()) if args.count_size: counter = count_genome_sizes(pop) for k, v in counter.items(): print(f"Number of {k} shapes: {v}")
f5d1efa3aa9f480d7ff820ad04190935b66a0b14
Zylophone/Programming-for-Sport
/firecode.io/03-number_of_leaves.py
2,734
3.6875
4
class BinaryTree: def __init__(self, data, left_child=None, right_child=None): self.data= data self.left_child= left_child self.right_child= right_child def number_of_leaves(self,root): count_soFar = 0 node_stack = [] node_stack.append(root) while node_stack: curr_node = node_stack.pop() if not curr_node: continue if self.is_leaf(curr_node): count_soFar += 1 node_stack.append(curr_node.left_child) node_stack.append(curr_node.right_child) return count_soFar # O(n) time where n is the number of nodes in self # O(depth) extra space (due to recursive call which must be saved in the call stack) # where depth is the depth of self # depth is O(log(n)) if self is balanced # depth is O(n) if self is so unbalanced that it resembles a list def number_of_leaves_recursive(self): tree= self if tree is None: return 0 if tree.isLeave(): return 1 left, right = tree.left_child, tree.right_child return ( left.number_of_leaves() if left else 0) + \ (right.number_of_leaves() if right else 0) def isLeave(self): tree= self if tree is None: return False return ( tree.left_child is None ) and ( tree.right_child is None ) # 1 # / \ # 2 3 # / \ \ # 4 5 6 # / # 7 # \ # 8 bn= [None]*(8+1) # d left right bn[8]= BinaryTree(8) bn[7]= BinaryTree(7, None, bn[8]) bn[6]= BinaryTree(6) bn[5]= BinaryTree(5, bn[7]) bn[4]= BinaryTree(4) bn[3]= BinaryTree(3, None, bn[6]) bn[2]= BinaryTree(2, bn[4], bn[5]) bn[1]= BinaryTree(1, bn[2], bn[3]) for i in xrange(1, 8+1): print ("bn%d.isLeave() equals:" % i), bn[i].isLeave() # print out # bn1.isLeave() equals: False # bn2.isLeave() equals: False # bn3.isLeave() equals: False # bn4.isLeave() equals: True # bn5.isLeave() equals: False # bn6.isLeave() equals: True # bn7.isLeave() equals: False # bn8.isLeave() equals: True for i in xrange(1, 8+1): print ("bn%d.number_of_leaves() equals:" % i), bn[i].number_of_leaves() # print out # bn1.number_of_leaves() equals: 3 # bn2.number_of_leaves() equals: 2 # bn3.number_of_leaves() equals: 1 # bn4.number_of_leaves() equals: 1 # bn5.number_of_leaves() equals: 1 # bn6.number_of_leaves() equals: 1 # bn7.number_of_leaves() equals: 1 # bn8.number_of_leaves() equals: 1
0a4894f687a22fdc186de0cc0031b409e734c55d
Demitroy/Euler_Python
/euler_9.py
287
3.515625
4
# Find pythagorean triple where a + b + c = 1000 import time t1 = time.time() for a in range(1,500): for b in range(a,1000): if((a**2 + b**2)**(1/2))%1 == 0 and a+b+(a**2 + b**2)**(1/2) == 1000: print(a*b*(a**2+b**2)**(1/2)) print(time.time() - t1)
8636e96cc7c98ba30f884ba335480db9b71a0097
vyshuks/june-leetcoding-challenge
/search_in_binary_tree.py
725
3.90625
4
""" Given the root node of a binary search tree (BST) and a value. You need to find the node in the BST that the node's value equals the given value. Return the subtree rooted with that node. If such node doesn't exist, you should return NULL. For example, Given the tree: 4 / \ 2 7 / \ 1 3 And the value to search: 2 You should return this subtree: 2 / \ 1 3 """ class Solution: def searchBST(self, root: TreeNode, val: int) -> TreeNode: if root is None: return None if root.val == val: return root if root.val > val: return self.searchBST(root.left, val) return self.searchBST(root.right, val)
ee43a379c19dbed25d6fb60c29243bd4c0857c02
cristiancmello/python-learning
/5-data-structures/5.3-tuples-sequences/script-1.py
682
4.28125
4
# Tuples and Sequences # TIPOS DE DADOS SEQUENCIAIS => list, tuple, range # Há um outro tipo sequencial => TUPLA tupla = 2, 5, 'hello' # ou (2, 5, 'hello') print(tupla) # (2, 5, 'hello') # Suportam Nested Tuples tupla = 1, 2, ('hello', 'world') print(tupla) # (1, 2, ('hello', 'world')) # IMPORTANTE! # TUPLAS SÃO IMUTÁVEIS, ASSIM COMO STRINGS. # NO ENTANTO, PODEM CONTER OBJETOS MUTÁVEIS. # tupla[0] = 'a' # Erro... v = ([1, 2, 3], [3, 2, 1]) print(v) # ([1, 2, 3], [3, 2, 1]) # É possível essa construção... empty = () singleton = 'hello', print(len(empty), '=>', empty) # 0 => () print(len(singleton), '=>', singleton) # 1 => ('hello',)
0402db8f23be68c3f26cf65ea4317fbf2fe231ad
msaei/coding
/LeetCode/Top Interview Questions/Math/Roman to Integer.py
659
3.75
4
#Roman to Integer #https://leetcode.com/explore/interview/card/top-interview-questions-easy/102/math/878/ class Solution: def romanToInt(self, s: str) -> int: vals = { "I":1, "V":5, "X":10, "L":50, "C":100, "D":500, "M":1000 \ , "IV":4, "IX":9, "XL":40, "XC":90, "CD":400, "CM":900 } i = 0 l = len(s) res = 0 while i < l: if i+1 < l and s[i:i+2] in vals.keys(): symb = s[i:i+2] res += vals[symb] i += 2 else: symb = s[i] res += vals[symb] i += 1 return res
582fe920cc4dd459ec3f9b102f3f91dc5fd3960f
xpansong/learn-python
/列表/列表元素的排序.py
750
4.25
4
print('--------使用列表对象sort()进行排序,不生成新的列表,原列表直接运算,不需要重新赋值----------') lst=[10,90,398,34,21,77,68] print(lst,id(lst)) #调用列表对象sort(),对列表进行升序排序 lst.sort() print(lst,id(lst)) #通过指定关键字参数,对列表进行降序排序 lst.sort(reverse=True) print(lst,id(lst)) print('-------使用内置函数sorted()进行排序,生成新的列表,因此新列表需要重新赋值----------') lst=[10,90,398,34,21,77,68] new_list=sorted(lst) #生成新的列表,new_list是新的列表,ID跟原列表不一样 print(new_list) #通过指定关键字参数,对列表进行降序排序 list2=sorted(lst,reverse=True) print(list2)
668d41c7030aacefd33ba83887146a75bf0361f7
27Saidou/cours_python
/EntityTp.py
338
3.875
4
def guest(): invites = ["Ramatoulaye ", "Ismatou", "Kadiatou", "Musk","Agier"] nom=input("Votre nom") if nom.capitalize() in invites: print("Bonjour Monsieur/Madame",nom) print("Bienvenue") else: print("Désole Monsieur/Madame{},Vous ne faites pas parti de la listes.".format(nom)) guest()
9f7ee87ddc71893b4ff2307cf4944cc278c2d865
luo-simon/British-Informatics-Olympiad-Solutions
/Python/2018/2a.py
733
3.90625
4
n, word = input('> ').split() n = int(n) alphabet = [letter for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'] def create_cipher(): cipher = [] index = 0 while len(alphabet) > 0: index += n-1 index = index % len(alphabet) # equivalent to i %= len(alphabet) cipher.append(alphabet[index]) alphabet.pop(index) return cipher def encrypt(word, cipher): encrypted = '' alphabet = [letter for letter in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'] for c in word: index = alphabet.index(c) encrypted += cipher[index] cipher.extend(cipher[:1]) cipher = cipher[1:] return encrypted cipher = create_cipher() print("".join(cipher[:6])) print(encrypt(word, cipher))
86c9c0021aabf848f6163aab7786e53ddb8f4c2a
czs108/LeetCode-Solutions
/Medium/43. Multiply Strings/solution (1).py
2,139
3.875
4
# 43. Multiply Strings # Runtime: 248 ms, faster than 11.81% of Python3 online submissions for Multiply Strings. # Memory Usage: 14.5 MB, less than 8.02% of Python3 online submissions for Multiply Strings. from itertools import zip_longest class Solution: def multiply(self, num1: str, num2: str) -> str: if num1 == "0" or num2 == "0": return "0" # Reverse both numbers. first_num = num1[::-1] second_num = num2[::-1] # To store the multiplication result of each digit. ans = [0] * (len(first_num) + len(second_num)) # Multiply each digit in the second number by the first number and add each result to answer. for idx, digit in enumerate(second_num): ans = self._add_strings(self._multiply_one_digit(first_num, digit, idx), ans) if ans[-1] == 0: ans.pop() ans.reverse() return "".join(str(digit) for digit in ans) def _multiply_one_digit(self, first_num: str, digit2: str, num_zeros: int): # Insert 0s at the beginning based on the current digit's place. curr_ans = [0] * num_zeros carry = 0 # Multiply the first number with the current digit of the second number. for digit1 in first_num: multiplication = int(digit1) * int(digit2) + carry # Set carry equal to the tens place digit of multiplication. carry = multiplication // 10 # Append the ones place digit of multiplication to the current result. curr_ans.append(multiplication % 10) if carry != 0: curr_ans.append(carry) return curr_ans def _add_strings(self, result: list, answer: list) -> list: carry = 0 i = 0 new_ans = [] for digit1, digit2 in zip_longest(result, answer, fillvalue=0): # Add current digits of both numbers. curr_sum = digit1 + digit2 + carry carry = curr_sum // 10 # Append last digit of the current sum to the answer. new_ans.append(curr_sum % 10) i += 1 return new_ans
e5e75a1c2cb0c7f4ce2975a6dfbb5c95c838618d
ahmadraad97/py
/numpy4.py
2,654
3.796875
4
from numpy import * # ممكن حساب الارقام التي ليست صفر a=random.randint(0,10,(3,3)) b=count_nonzero(a) print(a) # [[2 4 2] # [6 3 7] # [3 2 2]] print(b) # 9 # او تحديد عدد الارقام اكبر او اصغر من كذا a=random.randint(0,10,(3,3)) b=count_nonzero(a>5) c=count_nonzero(a<5) print(a) # [[0 4 1] # [4 9 4] # [5 0 9]] print(b) # 2 print(c) # 6 # وممكن حساب الارقام يكون بالصف اوالعمود كله a=random.randint(0,10,(3,3)) b=count_nonzero(a>5,axis=0) c=count_nonzero(a<5,axis=1) print(a) # [[4 9 7] # [0 0 4] # [1 8 9]] print(b) # [0 2 2] print(c) # [1 3 1] # لمعرفة هل فيه رقم اكبر او اصغر a=random.randint(0,10,(3,3)) b=any(a>7) print(a) # [[8 6 4] # [5 8 9] # [6 6 6]] print(b) # True # ويمكن عملها في كل عمود a=random.randint(0,10,(3,3)) b=any(a>7,axis=0) print(a) # [[3 2 5] # [9 9 0] # [4 0 5]] print(b) # [ True True False] # او صف a=random.randint(0,10,(3,3)) b=any(a>7,axis=1) print(a) # [[7 2 9] # [3 4 2] # [6 6 9]] print(b) # [ True False True] # ويمكن معرفة هل كل العناصر شرط معين a=random.randint(0,10,(3,3)) b=all(a>7,axis=1) print(a) # [[0 3 4] # [9 0 4] # [3 7 5]] print(b) # [False False False] # ويمكن معرفة هل العناصر اكبر من او اصغر من رقم معين a=random.randint(0,10,size=6).reshape(2,3) b=a>5 c=a<5 print(a) # [[4 5 0] # [8 8 1]] print(b) # [[False False False] # [ True True False]] print(c) # [[ True False True] # [False False True]] a=arange(6).reshape(2,3) b=arange(6).reshape(2,3) c=a**2 d=isclose(a,b,rtol=0.2) e=isclose(a,c,rtol=0.2) print(a) # [[0 1 2] # [3 4 5]] print('------------------') print(b) # [[0 1 2] # [3 4 5]] print('------------------') print(c) # [[ 0 1 4] # [ 9 16 25]] print('------------------') print(d) # [[ True True True] # [ True True True]] print('------------------') print(e) # [[ True True False] # [False False False]] # يمكن ضرب قيم المصفوفة في بعضها a=arange(3) print(a) # [0 1 2] print(multiply(a,10)) # [ 0 10 20] # لرفع كل العناصر للأس الرابع a=arange(3) print(a) # [0 1 2] print(power(a,4)) # [ 0 1 16]
170bb1b92f4fc47d6b4c26bd3730a26a6df17e1b
Subtracting/mp3player
/mp3db.py
1,123
3.546875
4
import sqlite3 def create_connection(db_file): conn = None conn = sqlite3.connect(db_file) return conn def insert_row(conn, timestamp, location, table): sql = f'INSERT INTO {table} (timestamp, location) values (?,?)' params = (timestamp, location) cur = conn.cursor() cur.execute(sql, params) conn.commit() def insert_song(conn, location, length, table): sql = f'INSERT INTO {table} (song_location, song_length) values (?,?)' params = (location, length) cur = conn.cursor() cur.execute(sql, params) conn.commit() def clear_table(conn, table): sql = f'DELETE FROM {table}' cur = conn.cursor() cur.execute(sql) conn.commit() def read_rows(conn, table): sql = f"SELECT * FROM {table}" cur = conn.cursor() cur.execute(sql) rows = cur.fetchall() conn.commit() return rows[0] def create_table(): conn = create_connection('mp3_db.sqlite') sql = f'CREATE TABLE songs (song_id INTEGER PRIMARY KEY, song_location TEXT, song_length TEXT);' cur = conn.cursor() cur.execute(sql) conn.commit() # create_table()
05ea4a76df73255cf316f6234b22084879070f6f
Nikunj-Gupta/Python
/practice/Level2/printdigit.py
114
3.5625
4
n = input("Enter a number: ") a = [] while(n>0): a.append(n%10) n = n/10 a.reverse() for i in a: print i
c8c90435d586999c357d3c77fcef016b934691eb
CaoZhens/ML_Learning
/study/4_PythonFoundation/distrubutionGenerate/DistributionWithRandom.py
2,362
4.09375
4
# coding:utf-8 ''' Created on Sep 30, 2017 @author: CaoZhen @desc: Distribution Generation 1. Uniform Distribution 2. Standard Normal Distribution 3. Gaussian Distribution @reference: 4.1.intro.py Section 6 ''' import numpy as np import matplotlib matplotlib.use('TkAgg') import matplotlib.pyplot as plt ''' 1. Uniform Distribution 均匀分布 rand - uniform distribution over [0, 1) ''' x = np.random.rand(10000) fig = plt.figure(figsize=(14,6)) plt.title('Uniform Distribution') ax1 = fig.add_subplot(121) ax1.hist(x, 20, color='b', alpha=0.5) # ax1.axis([0.0, 1.0, 0, 500]) # 两个子图如何处理坐标轴的显示 ax1.grid(True) ax2 = fig.add_subplot(122) ax2.plot(np.arange(len(x)), x) # ax2.axis([0, 10000, 0.0, 1.0]) ax2.grid(True) plt.show() ''' 2. Standard Normal Distribution 标准正态分布 randn - univariate “normal” (Gaussian) distribution of mean 0 and variance 1 ''' x = np.random.randn(10000) label = u'$\mu$=%d, $\sigma^2$=%d' % (np.mean(x), np.var(x)) fig = plt.figure(figsize=(14,6)) plt.title('Standard Normal Distribution') ax1 = fig.add_subplot(121) ax1.hist(x, 20, color='b', alpha=0.5, label=label) ax1.legend(loc='best') # ax1.axis([0.0, 1.0, 0, 500]) # 两个子图如何处理坐标轴的显示 ax1.grid(True) ax2 = fig.add_subplot(122) ax2.plot(np.arange(len(x)), x, label=label) ax2.legend(loc='best') # ax2.axis([0, 10000, 0.0, 1.0]) ax2.grid(True) plt.show() ''' 3. Gaussian Distribution 高斯分布 For random samples from N(\mu, \sigma^2), use: sigma * np.random.randn(...) + mu ''' x = np.sqrt(2) * np.random.randn(10000) + 3 label = u'$\mu$=%.f, $\sigma^2$=%.f' % (np.mean(x), np.var(x)) fig = plt.figure(figsize=(14,6)) plt.title(u'Gaussian Distribution') ax1 = fig.add_subplot(121) ax1.hist(x, 20, color='b', alpha=0.5, label=label) ax1.legend(loc='best') # ax1.axis([0.0, 1.0, 0, 500]) # 两个子图如何处理坐标轴的显示 ax1.grid(True) ax2 = fig.add_subplot(122) ax2.plot(np.arange(len(x)), x, label=label) ax2.legend(loc='best') # ax2.axis([0, 10000, 0.0, 1.0]) ax2.grid(True) plt.show() ''' 4. Poisson ''' # 注意normed的用法 x = np.random.poisson(lam=5, size=10000) # a = plt.hist(x, bins=15, normed=True, range=[0, 15], color='g', alpha=0.5) a = plt.hist(x, bins=15, range=[0, 15], color='g', alpha=0.5) plt.grid() plt.show() # print a # print a[0].sum()
76648a0a63eccae1453622d4deb523aa4adfba86
sakshigarg22/python-projects
/error.py
309
3.78125
4
##rule 1 ##try: ## pass ##except: ## pass try: int('ddsd') except: print('error handled') while 1: try: i = int(input()) print(i) break except ValueError : print('not valid integer...try again') except EOF: print('please enter something')
6dc9ec45a1fef9a2465f1edcc1423248fae92fa3
wunnox/python_grundlagen
/U4_7_Menge.py
517
3.859375
4
#!/usr/bin/python3 ################################################################### # # Uebung: # Erstellen Sie folgendes Tupel: # a=('Petra','Hans','Fred','Hans','Ursula','Robert','Petra','Ursula','Hans') # Geben Sie die obigen Namen auf dem Bildschirm so aus, dass jeder # Name nur einmal erscheint. # ################################################################### #### Lösung: #### a = ('Petra', 'Hans', 'Fred', 'Hans', 'Ursula', 'Robert', 'Petra', 'Ursula', 'Hans') s = set(a) for n in s: print(n)
519bed5582a275737e55c43ed81fe27652e1c533
abinashnayak1996/Function
/function9.py
148
3.609375
4
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] square = list(map(lambda x: x ** 2, nums)) print(square) cube = list(map(lambda x: x ** 3, nums)) print(cube)
4ff60f782c7d8f43f4a52ef187b7603bcd1ce5ea
edumaximo2007/python_remembe
/DESAFIO063.py
551
3.65625
4
import emoji print('=-=' * 10) print('''\033[7m DESAFIO 063 \033[m''') print('=-=' * 10) print(emoji.emojize(''':bulb: \033[1mEscreva um programa que leia um\033[m\033[1;35m número\033[m\033[1;32m n \033[m \033[1minteiro qualquer e mostre na tela os\033[m\033[1;32m n \033[m\033[1mprimeiros elementos de uma\033[m \033[1;32mSequência de Fibonacci\033[m\033[1m.\033[m \033[1;37mEx:\033[m \033[1;32m0:arrow_right:1:arrow_right:1:arrow_right:2:arrow_right:3:arrow_right:5:arrow_right:8\033[m''', use_aliases=True)) print('') print('')
4e650257693dc3c2d683ea638a09e6c81fad9f18
juliecoleman/word-count
/wordcount.py
359
3.875
4
def count_words_in_file(filename): lines = open(filename) word_counts = {} for line in lines: words = line.split(" ") print(words) for word in words: word_counts[word] = word_counts.get(word, 0) + 1 return word_counts print(count_words_in_file("test.txt")) print(count_words_in_file("twain.txt"))
43817943b0f55ae1c5ee5ea1a8ca454c749e3fde
brusetse/chaos
/py/hello.py
81
3.5
4
msg = "Hello world" print(msg) # 输入 # name = input() # print("I am " + name)
84b9605b9859f64085e738573f66569ba62f1cfe
michaelmcnees/server_side_languages
/lectures/helloworld/python.py
180
3.796875
4
import sys name = raw_input("What is your name?") f = open("myfile.txt", "w") # f.write("here is my text"+name) # f.close() # f.open("myfile.txt", "r") print(f.read()) f.close()
8a95f9363d8cfce24cc5be4fbae6af5467416a7f
SigmaQuan/BOOK-CODE-Learning.Python.The.Hard.Way
/lesson_49.py
8,423
4.375
4
""" Exercise 49: Making Sentences What we should be able to get from our little game lexicon scanner is a list that looks like this: # >>> from ex48 import lexicon # >>> lexicon.scan("go north") # [('verb', 'go'), ('direction', 'north')] # >>> lexicon.scan("kill the princess") # [('verb', 'kill'), ('stop', 'the'), ('noun', 'princess')] # >>> lexicon.scan("eat the bear") # [('verb', 'eat'), ('stop', 'the'), ('noun', 'bear')] # >>> lexicon.scan("open the door and smack the bear in the nose") # [('error', 'open'), ('stop', 'the'), ('error', 'door'), ('error', 'and'), ('error', 'smack'), ('stop', 'the'), ('noun', 'bear'), ('stop', 'in'), ('stop', 'the'), ('error', 'nose')] Now let us turn this into something the game can work with, which would be some kind of Sentence class. If you remember grade school, a sentence can be a simple structure like: Subject Verb Object Obviously it gets more complex than that, and you probably did many days of annoying sentence graphs for English class. What we want is to turn the above lists of tuples into a nice Sentence object that has subject, verb, and object. Match and Peek To do this we need four tools: 1. A way to loop through the list of scanned words. That's easy. 2. A way to "match" different types of tuples that we expect in our Subject Verb Object setup. 3. A way to "peek" at a potential tuple so we can make some decisions. 4. A way to "skip" things we do not care about, like stop words. 5. A Sentence object to put the results in. The Sentence Grammar Before you can write the code you need to understand how a basic English sentence grammar works. In our parser we want to produce a Sentence object that has three attributes: Sentence.subject This is the subject of any sentence, but could default to "player" most of the time since a sentence of, "run north" is implying "player run north". This will be a noun. Sentence.verb This is the action of the sentence. In "run north" it would be "run". This will be a verb. Sentence.object This is another noun that refers to what the verb is done on. In our game we separate out directions which would also be objects. In "run north" the word "north" would be the object. In "hit bear" the word "bear" would be the object. Our parser then has to use the functions we described and given a scanned sentence, convert it into List of Sentence objects to match the input. A Word On Exceptions You briefly learned about exceptions but not how to raise them. This code demonstrates how to do that with the ParserError at the top. Notice that it uses classes to give it the type of Exception. Also notice the use of the raise keyword to raise the exception. In your tests, you will want to work with these exceptions, which I'll show you how to do. The Parser Code If you want an extra challenge, stop right now and try to write this based on just my description. If you get stuck you can come back and see how I dit it, but trying to implement the parser yourself is good practice. I will now walk through the code so you can enter it into your ex48/parser.py. We start the parser with the exception we need for a parsing error: # class ParserError(Exception): # pass This is how you make your own ParserError exception class you can throw. Next we need the Sentence object we'll create: # class Sentence(object): # def __init__(self, subject, verb, obj): # # remember we take ('non', 'princess') tuples and convert them # self.subject = subject[1] # self.verb = verb # self.obj = obj There's nothing special about this code so far. You're just making simple classes. In our description of the problem we need a function that can peek at a list of words and return what type of word it is: # def peek(word_list): # if word_list: # word = word_list[0] # return word[0] # else: # return None We need this function because we'll have to make decisions about what kind of sentence we're dealing with based on what the next word is, and then we can call another function to consume that word and carry on. To consume a word we use a the match function, which confirms that the expected word is the right type, takes it off the list, and returns the word. # def match(word_list, expecting): # if word_list: # word = word_list.pop[0] # # if word[0] == expecting: # return word # else: # return None # else: # return None # Again, fairly simple but make sure you understand this code but also why I'm doing it this way. I need to peek at words in the list to decide what kind of sentence I'm dealing with, and then I need to match those words to create my Sentence. The last thing I need is a way to skip words that aren't useful to the Sentence. These are the words labeled "stop words" (type 'stop') that are words like "the", "and", and "a". # # def skip(word_list, word_type): # while peek(word_list) == word_type: # match(word_list, word_type) # Remember that skip doesn't skip one word, it skips as many words of that type as it finds. This makes it so if someone types, "scream at the bear" you get "scream" and "bear". That's our basic set of parsing functions, and with that we can actually parse just about any text we want. Our parser is very simple though, so the remaining functions are short. First we can handle parsing a verb: # # def parse_verb(word_list): # skip(word_list, 'stop') # # if peek(word_list) == 'verb': # return match(word_list, 'verb') # else: # raise ParserError("Excepted a verb next.") We skip any stop words, then peek ahead to make sure the next word is a "verb" type. If it's not then raise the ParserError to say why. If it is a "verb" then match it, which takes it off the list. A similar function handles sentence objects: # # def parse_object(word_list): # skip(word_list, 'stop') # next_word = peek(word_list) # # if next_word == 'noun': # return match(word_list, 'noun') # elif next_word == 'direction': # return match(word_list, 'direction') # else: # raise ParserError("Expected a noun or direction") Again, skip the stop words, peek ahead, and decide if the sentence is correct based on what's there. In the parse_object function thought we need to handle both "noun" and "direction" words as possible objects. Subject are then similar again, but since we want to handle the implied "player" noun, we have to use peek: # def parse_subject(word_list): # skip(word_list, 'stop') # next_word = peek(word_list) # # if next_word == 'noun': # return match(word_list, 'noun') # elif next_word == 'verb': # return ('noun', 'player') # else: # raise ParserError("Expected a verb next.") With that all out of the way and ready, our final parse_sentence function is very simple: # # def parse_sentence(word_list): # subj = parse_subject(word_list) # verb = parse_verb(word_list) # obj = parse_object(word_list) # # return Sentence(subj, verb, obj) What You Should Test For exercise, write a complete test that confirms everything in this code is working. Put the test in tests/parser_tests.py similar to the test file from the last exercise. That includes making exceptions happen by giving the parser bad sentences. Check for an exception by using the function assert_raises from the nose documentation. Learn how to use this so you can write a test that is expected to fail, which is very important in testing. Learn about this function (and others) by reading the nose documentation. When you are done, you should know how this bit of code works and how to write a test for other people's code even if they do not want you to. Trust me, it's a very handy skill to have. Study Drills 1. Change the parse_ methods and try to put them into a class rather than be just methods. Which design do you like better? 2. Make the parser more error-resistant so that you can avoid annoying your users if they type words your lexicon doesn't understand. 3. Improve the grammar by handling more things like numbers. 4. Think about how you might use this Sentences class in your game to do more fun things with a user's input. """
4a5ab04f21bbf2ec2bcc5869a4490ecdbdd82c24
sun9121/CodeUp
/Python_basic100/59.py
719
3.78125
4
# 입력 된 정수를 비트단위로 참/거짓을 바꾼 후 정수로 출력해보자. # 비트단위(bitwise)연산자 ~ 를 붙이면 된다.(~ : tilde, 틸드라고 읽는다.) # ** 비트단위(bitwise) 연산자는, # ~(bitwise not), &(bitwise and), |(bitwise or), ^(bitwise xor), # <<(bitwise left shift), >>(bitwise right shift) # 가 있다. # 예를 들어 1이 입력되었을 때 저장되는 1을 32비트 2진수로 표현하면 # 00000000 00000000 00000000 00000001 이고, # ~1은 11111111 11111111 11111111 11111110 가 되는데 이는 -2를 의미한다. # 예시 # a = 1 # print(~a) #-2가 출력된다. a = int(input()) print(~a) # bitwise 연산에서 not은 앞에 ~를 붙인다.
bcffc88f3cee0f80b84daedb5799477bed2b2f0b
sk-vojik/Intro-Python-I
/src/hello.py
410
3.796875
4
# Print "Hello, world!" to your terminal print("hello world") # class Animal: # # define attributes, assign initial values # def __init__(self, sound, leg_count=4): # self.leg_count = leg_count # self.sound = sound # def set_let_count(self, leg_count): # self.leg_count = leg_count # def make_sound(self): # print(self.sound) # Brooklyn = Animal("bark", 4) # Brooklyn.make_sound()
2fa2f965f2ebb9c9a5ceef55c855cac6b18a2542
dhimanmonika/PythonCode
/Lambda,Map,Filter,Reduce/reduce.py
449
3.8125
4
""" The function reduce(func, seq) continually applies the function func() to the sequence seq. It returns a single value. """ from functools import reduce l=[1,2,6,3,4,9,7,23,66] print("original list ",l) # find the maximum number from the list max=reduce(lambda x,y:x if (x>y) else y,l) print("the max value from the list ",max) #find sum of elements of the list sum=reduce(lambda x,y:x+y,l) print("the sum of all the elements of list ",sum)
cc33a3c72ebe849cec7d049de3e6d5526c8c1eff
DibPuelma/mlnd_capstone
/data_cleaner.py
3,827
3.5625
4
import requests as req import pandas as pd # https://twitter.com/RodrigoWagnerB/status/410907897019629568 API_HOST = 'https://api.rutify.cl/rut/' # get the address, commune and sex for each RUT in the database def get_data(rut): r = req.get(API_HOST + str(rut)) data = r.json() if 'servel' in data: return [data['servel']['domicilio electoral'], data['servel']['comuna'], data['sexo']] else: return ['','',''] # add a verification number or check number to each RUT # in Chile, the mod11 algorithm is used def get_verify_number(rut): rut = str(rut) multiplier = 0 sum = 0 for item in rut[::-1]: sum += int(item) * ((multiplier % 6) + 2) multiplier += 1 result = (11 - sum%11) if result == 11: digit = '0' elif result == 10: digit = 'K' else: digit = str(result) return rut + digit # clean the wholesale customers from the database, # these are considered to buy 3 or more items in only one purchase. # it receives the whole dataframe def clean_majorists(df): count = 0 last_row = df.iloc[0] indexes = [0] to_delete = [] for index, row in df.iterrows(): if index > 0: if last_row['KOEN'] == row['KOEN']: indexes.append(index - 1) count += 1 else: count = 0 indexes = [] if count >= 3: to_delete += indexes + [index] last_row = row df = df.drop(to_delete) df = df[df['KOEN'] != '96521550'] df = df[df['TIDO'] == 'BLV'] df = df[df['CANTIDAD'] > 0] df = df[df['CANTIDAD'] < 5] df = add_verify(df) return df # get the age of the customer from the RUT using a regression found in # https://twitter.com/rodrigowagnerb/status/410907897019629568?lang=es def get_age(rut): result = 2018 - (int(rut)/1000000*3.46 + 1930) if result > 12: return result else: return 0 # add the verification number to the dataframe def add_verify(df): verifies = [] for index, row in df.iterrows(): verifies.append(get_verify_number(row['KOEN'])) verify_serie = pd.Series(verifies) df['rut_v'] = verify_serie.values return df # add the age to the dataframe def add_age(df): df['age'] = df['rut'].apply(get_age) return df # add the address to the dataframe def add_address(df): data_dict = {'address': [], 'commune': [], 'sex': []} rows = df.shape[0] for index, row in df.iterrows(): if index % 25 == 0: print('{}/{}'.format(index, rows)) rut_data = get_data(row['rut_v']) data_dict['address'].append(rut_data[0]) data_dict['commune'].append(rut_data[1]) data_dict['sex'].append(rut_data[2]) address_serie = pd.Series(data_dict['address']) df['address'] = address_serie.values commune_serie = pd.Series(data_dict['commune']) df['commune'] = commune_serie.values sex_serie = pd.Series(data_dict['sex']) df['sex'] = sex_serie.values return df # rename some columns for readability and delete two columns # that have duplicated information def clean_columns(df): df = df.rename(columns={ 'FECHA': 'date', 'MES': 'month', 'AÑO': 'year', 'NOKOSU': 'store', 'KOEN': 'rut', 'NOKOEN': 'name', 'EMAIL': 'email', 'TIDO': 'purchase_type', 'FMPR': 'category', 'CANTIDAD': 'quantity', 'NETO': 'total_value'}) df = df.drop(columns=['CAPRCO1', 'VANELI']) return df df = pd.read_csv('capstone_processed_data.csv') df = add_address(df) df.to_csv('capstone_processed_data.csv')
b55ff227de82e263b26d2fd838ce7cb2421560f0
tcandzq/LeetCode
/Math/IntegerBreak.py
1,753
3.5
4
# -*- coding: utf-8 -*- # @File : IntegerBreak.py # @Date : 2020-02-09 # @Author : tc """ 题号 343 整数拆分 给定一个正整数 n,将其拆分为至少两个正整数的和,并使这些整数的乘积最大化。 返回你可以获得的最大乘积。 示例 1: 输入: 2 输出: 1 解释: 2 = 1 + 1, 1 × 1 = 1。 示例 2: 输入: 10 输出: 36 解释: 10 = 3 + 3 + 4, 3 × 3 × 4 = 36。 说明: 你可以假设 n 不小于 2 且不大于 58。 解法1:参考:https://leetcode-cn.com/problems/integer-break/solution/343-zheng-shu-chai-fen-tan-xin-by-jyd/ 解法2:参考:https://leetcode-cn.com/problems/integer-break/solution/tan-xin-xuan-ze-xing-zhi-de-jian-dan-zheng-ming-py/ 完全是一道数学题。。。 """ class Solution: def integerBreak(self, n: int) -> int: if n <= 3: return n - 1 a, b = n // 3, n % 3 if b == 0: return pow(3, a) if b == 1: return pow(3, a - 1) * 4 return pow(3, a) * 2 def integerBreak2(self, n: int) -> int: dp = [0 for _ in range(n + 1)] dp[2] = 1 for i in range(3,n+1): for j in range(i): dp[i] = max(dp[i],max((i - j) * j,j*dp[i -j])) return dp[n] def integerBreak3(self, n: int) -> int: dp = [1 for _ in range(n + 1)] dp[0] = 0 dp[1] = 1 dp[2] = 1 for i in range(3, n + 1): dp[i] = max(max(dp[i - 1], i - 1), 2 * max(dp[i - 2], i - 2), 3 * max(dp[i - 3], i - 3)) return dp[n] if __name__ == '__main__': n = 10 solution = Solution() print(solution.integerBreak(n)) print(solution.integerBreak2(n)) print(solution.integerBreak3(n))
f57dff4d02a96ac4d4e28e7c6daee2329366fe07
stasvorosh/pythonintask
/INBa/2014/MorenkoAA/MorenkoAA_5_14.py
1,931
4.34375
4
# Задача 5, Вариант 14 # Напишите программу, которая бы при запуске случайным образом отображала название одной из двадцати башен Московского кремля. # Моренко А.А. # 16.03.2016 import random print('Программа случайным образом отображает название одной из двадцати названий башен Кремля') feat = random.randint(1,20) print('Одна из башен называется:', end=" ") if feat == 1 : print("Беклемишевская башня") elif feat == 2 : print("Беклемишевская башня") elif feat == 3 : print("Набатная башня") elif feat == 4 : print("Царская башня") elif feat == 5 : print("Спасская башня") elif feat == 6 : print("Сенатская башня") elif feat == 7 : print("Никольская башня") elif feat == 8 : print("Угловая Арсенальная башня") elif feat == 9 : print("Средняя Арсенальная башня") elif feat == 10 : print("Троицкая башня") elif feat == 11 : print("Кутафья башня") elif feat == 12 : print("Комендантская башня") elif feat == 13 : print("Оружейная башня") elif feat == 14 : print("Боровицкая башня") elif feat == 15 : print("Водовзводная башня") elif feat == 16 : print("Благовещенская башня") elif feat == 17 : print("Тайницкая башня") elif feat == 18 : print("Первая Безымянная башня") elif feat == 19 : print("Вторая Безымянная башня") else: print("Петровская башня") input ('Нажмите Enter для выхода')
155c9422a450d5fd2e7de8e113244513c49b375f
olaruandreea/KattisProblems
/aah.py
233
3.734375
4
s1 = raw_input() s2 = raw_input() count_a1 = 0 count_a2 = 0 for each in s1: if each == "a": count_a1 += 1 for each in s2: if each == "a": count_a2 += 1 if count_a1 < count_a2: print "no" elif count_a1 >= count_a2: print "go"
1b95ba5d4e07b4298ff4a16202e0882031dd9465
erinrep/aoc
/2022/12/puzzle.py
1,954
3.828125
4
print("Day 12: Hill Climbing Algorithm") def valid_neighbor(elevations, curr, i, j): if i >= len(elevations) or i < 0: return False if j >= len(elevations[0]) or j < 0: return False next = elevations[i][j] if next == "E": next = "z" if next <= curr or ord(curr) + 1 == ord(next): return True def bfs(graph, start, goal): explored = [] queue = [[start]] while queue: path = queue.pop(0) node = path[-1] if node not in explored: neighbors = graph[node] for neighbor in neighbors: new_path = list(path) new_path.append(neighbor) queue.append(new_path) if neighbor == goal: return new_path explored.append(node) return [] with open('input.txt', encoding="utf-8") as f: elevations = [list(x.replace('\n', '')) for x in list(f)] start = "" end = "" starting_pts = [] for i in range(len(elevations)): for j in range(len(elevations[i])): pt = elevations[i][j] coords = f"{i},{j}" if pt == "S": start = coords starting_pts.append(coords) elevations[i][j] = "a" elif pt == "a": starting_pts.append(coords) elif pt == "E": end = coords graph = {} for i in range(len(elevations)): for j in range(len(elevations[i])): coords = f"{i},{j}" curr = elevations[i][j] neighbors = [] if valid_neighbor(elevations, curr, i+1, j): neighbors.append(f"{i+1},{j}") if valid_neighbor(elevations, curr, i-1, j): neighbors.append(f"{i-1},{j}") if valid_neighbor(elevations, curr, i, j+1): neighbors.append(f"{i},{j+1}") if valid_neighbor(elevations, curr, i, j-1): neighbors.append(f"{i},{j-1}") graph[coords] = neighbors path = bfs(graph, start, end) print("Part One:", len(path)-1) print("slooooow...") paths = [] for pt in starting_pts: l = len(bfs(graph, pt, end))-1 if l != -1: paths.append(l) print("Part Two:", min(paths))
ba0cc4720686e2bd6d864db7eafd817437881987
sunanqi/algorithms
/quick_sort_random_pivot.py
1,612
4.125
4
""" - Problem: sort an array - Algorithm: 1. Select a pivot. If random_pivot == True, a random number is selected as pivot, otherwise the first number is pivot 2. swap numbers in the array until left part is all <= pivot and right part is all > pivot 3. recurse to sort the left part and right part - time complexity: For random pivot, O(n logn) on average, where average is over the random choices. Worst case can be O(n^2) - input: list[int] - output: list[int] """ import random def quicksort(nums, random_pivot=True): def helper(st, ed): # print(st,ed) if st+1 >= ed: return # work on nums[st:ed] (not including ed) if random_pivot: pivot = random.randint(st,ed-1) nums[st], nums[pivot] = nums[pivot], nums[st] pivot = nums[st] p1, p2 = st+1, ed-1 while True: while p1<ed and nums[p1] <= pivot: p1 += 1 while nums[p2] > pivot: p2 -= 1 ''' pivot st+1 ... ed-1 ed 3 1 2 3 4 5 after here, st=4, ed=3 pivot st+1 ... ed-1 ed 3 1 2 4 2 5 after here, st=4, ed=2 ''' if p1>p2: break nums[p1], nums[p2] = nums[p2], nums[p1] nums[st], nums[p2] = nums[p2], nums[st] helper(st, p2) helper(p1, ed) helper(0, len(nums)) return nums if __name__ == '__main__': nums = [-2, 1, -3, 4, -1, 2, 1, -5, 4] print(quicksort(nums, random_pivot=True))
483e06bbb710bfb7a6c3495eb55c98f3ad4b08b6
tsutsuku/leetcode
/Trie/Word_Search_II.py
1,904
3.71875
4
#Question No.212 Word Search II class Solution: def findWords(self, board, words): """ :type board: List[List[str]] :type words: List[str] :rtype: List[str] """ root = Trie() for i in range(len(board)): for j in range(len(board[i])) class Trie: def __init__(self): """ Initialize your data structure here. """ self.root = TrieNode() def insert(self, word): """ Inserts a word into the trie. :type word: str :rtype: void """ node = self.root for ch in word: if not node.contiansKey(ch): node.put(ch, TrieNode()) node = node.get(ch) node.setEnd() def search(self, word): """ Returns if the word is in the trie. :type word: str :rtype: bool """ node = self.searchPrefix(word) return node != None and node.isEnd() def startsWith(self, prefix): """ Returns if there is any word in the trie that starts with the given prefix. :type prefix: str :rtype: bool """ node = self.searchPrefix(prefix) return node != None def searchPrefix(self, word): node = self.root for ch in word: if node.contiansKey(ch): node = node.get(ch) else: return None return node class TrieNode: def __init__(self): self.links = [None] * 26 self.is_end = False def contiansKey(self, ch): return self.links[ord(ch) - ord('a')] != None def get(self, ch): return self.links[ord(ch) - ord('a')] def put(self, ch, node): self.links[ord(ch) - ord('a')] = node def setEnd(self): self.is_end = True def isEnd(self): return self.is_end
3ad621858e6219a7f9d16bc89ce77ba6baee90b2
Ambitioner-c/Flower
/python/branch.py
961
3.984375
4
import turtle as t def draw_tree1(branch): # 条件满足先画右边 if branch > 10: # 绘制最开始的树干 t.fd(branch) # 然后右转30,第一个右分支 t.right(30) # 继续画右边的,走不动了往左边转60和下面一样用到了递归 draw_tree1(branch / 1.5) # 然后左转60 进入向左绘制 t.left(60) # 继续画左边的,走不动了右转30回到最后一步的之前那个节点 draw_tree1(branch / 1.5) t.right(30) # 给最后二个树枝画上雪白的叶子 # 这个条件可以根据实际设置 if branch / 1.5 <= 10: t.pencolor("snow") else: # 褐色 t.pencolor("Tan") # 当递归条件不满足的时候,后退一个节点 t.backward(branch) if __name__ == '__main__': # 枝条总数 my_branch = 60 draw_tree1(my_branch)
b192adb8ab518f80293805134841f8cdc2b2e187
an-lam/python-class
/oo-examples/car1maincopy.py
1,033
3.84375
4
# car1main.py from car1 import Car toyota = Car("Toyota", 2005) print(toyota.make) print(toyota.year) print(toyota) toyota.year = 2017 honda = Car("Honda", 2010) print("Cars: {}: {}, {}: {}".format(toyota.make, toyota.year, honda.make, honda.year)) print("Cars: {0.make}: {0.year}, {1.make}, {1.year}".format(toyota, honda)) print(toyota.start) toyota.start_engine() # same as #Car.start_engine(toyota) # There is a bug in start_engine print(toyota) print(Car.power_source) print(toyota.power_source) print(honda.power_source) toyota.horse_power = 220 # define new attribute print("Toyota.horse_power: {} HP".format(toyota.horse_power)) #print(honda.horse_power) # Error, why? print("Switch all car power to gas:") Car.power_source = "gas" print(Car.power_source) print(toyota.power_source) print(honda.power_source) print("Switch Toyota to hybrid") toyota.power_source = "hybrid" print(toyota) print(honda) print(Car.__dict__) print(toyota.__dict__) print(honda.__dict__)
8120ecd337b137ee0c7a6f4d0a8c194ae6fcd0c0
maleficus1234/School
/COMP452TME3/Game2/Tiles/Tile.py
1,641
3.515625
4
import pygame # Map for storage of tile sprites tileTextures = {} # Base class for tiles class Tile(object): # Create a tile using the given texture, with the given pathfinding cost. # -1 cost indicates inaccessibility def __init__(self, textureFile, cost): # Load the sprite if it hasn't already been. if not tileTextures.has_key(textureFile): tileTextures[textureFile] = pygame.image.load(textureFile) self.texture = tileTextures[textureFile] self.cost = cost self.x = 0 self.y = 0 # Set default values for the user info # Whether this tile was visited at any point during pathfinding self.visited = False # Whether this node was considered as part of a path self.processed = False # At which step in the pathfinding this node was considered. self.step = -1 # Render the tile. If debug is true, the tile will be rendered with pathfinding data. def draw(self, screen, font, debug = False): rect = self.texture.get_rect() rect = rect.move(self.x, self.y) screen.blit(self.texture, rect) if debug == True: if self.processed: label = font.render("p", 1, (0,0,0)) screen.blit(label, (self.x+2, self.y)) else: if self.visited: label = font.render("v", 1, (0,0,0)) screen.blit(label, (self.x+2, self.y)) if self.step != -1: label = font.render(str(self.step), 1, (0,0,0)) screen.blit(label, (self.x+16, self.y))
ca9111c91a3af84b2f7b6ef3541bfd2a29b98368
kaloyandenev/Python-learning
/Odd Occurrences.py
329
3.515625
4
data_list = input().split() data_dict = {} data_list = [element.lower() for element in data_list] for element in data_list: if element in data_dict: data_dict[element] += 1 else: data_dict[element] = 1 for element in data_dict.items(): if element[1] % 2 != 0: print(f"{element[0]}", end=" ")
271dd4f431070c14320b04b1794dbd8f88272ae9
cernst122/dev
/PythonReview/script.py
1,815
4.03125
4
# sales_tax=.095 # item_list={"water": 1.00, "milk": 1.50, "apple": .75} # def calc_tax(price): # return price*sales_tax # # def calculate_final_price(item_value): # return calc_tax(item_value)+item_value # # def calculate_final_price_by_name(item_name): # return calculate_final_price(item_list[item_name]) # # print ("Please insert item name") # user_input=raw_input()#will return what the user has typed # # if (user_input in item_list)==False: # print "Not in dictionary" # else: # print calculate_final_price_by_name(user_input) class Ninja(object): def __init__(self, name, level): self.name = name self.level = level def fight(self, other): if self.level>other.level: print "I win" elif self.level==other.level: print "draw" else: print "I lose" ninja1 = Ninja("Tyson", 1) #ninja1.fight(ninja1) # # class Sensei(Ninja): class Monster(object): #3 properties and two methods; ne method include a way to interact, then have a monster an a ninja interact. #have some properties in ninja and monsters? def __init__(self, name, color, size): self.color = color self.size = size self.name = name def scare(self): print "I'M BEING SCARY" def roarAt(self, other): print "I'M ROARING AT "+ other.name.upper() def describeSelf(self): print "My name is " + self.name + ". I am " + self.color.lower() + " and I am " + self.size.lower() + ". " Mike=Monster("Mike", "Green", "Small") Sully=Monster("Sully", "Blue and Purple", "Huge") Sully.roarAt(Mike) Sully.roarAt(ninja1) Mike.describeSelf() Sully.scare def collatz(n): while n>1: yield n; n=(n/2 if n%2==0 else 3*n+1) print max(sum(1 for _ in collatz(n)) for n in xrange(1, 1000001))
1b3ad1f75c681cfd3781d7a3d20b587bc1545272
dquan101/MLE2020
/tarea_14_01_2020/menu.py
166
3.625
4
def menu(options): print("Bienvenido al menu!") print("\n".join(list(options.keys()))) return list(options.values())[int(input("Elija su opcion:")) - 1]
0ebba6345fbea934d42dca93b933d831bc0755fc
neilpa/euler
/Python/040.py
713
3.84375
4
#!/usr/bin/env python """ Problem 40 28 March 2003 An irrational decimal fraction is created by concatenating the positive integers: 0.123456789101112131415161718192021... It can be seen that the 12th digit of the fractional part is 1. If d_n represents the nth digit of the fractional part, find the value of the following expression. d_1 * d_10 * d_100 * d_1000 * d_10000 * d_100000 * d_1000000 Answer: ????? """ def solve(): # Brute-force solution s = "".join(str(n) for n in xrange(1,1000000)) return int(s[0]) * int(s[9]) * int(s[99]) * int(s[999]) * \ int(s[9999]) * int(s[99999]) * int(s[999999]) if __name__ == '__main__': print "Answer: %s" % solve()
fe29b3faa1353a37fa37f6a7eae041085d11c7d6
Aasthaengg/IBMdataset
/Python_codes/p02261/s555222998.py
1,096
3.5625
4
from copy import deepcopy def bubble_sort(lst): size=len(lst) for i in xrange(size): for j in reversed(range(i+1,size)): if lst[j].num<lst[j-1].num: tmp=lst[j] lst[j]=lst[j-1] lst[j-1]=tmp def selection_sort(lst): size=len(lst) for i in xrange(size): mn=i for j in xrange(i+1,size): if lst[mn].num>lst[j].num: mn=j tmp=lst[i] lst[i]=lst[mn] lst[mn]=tmp class pock: def __init__(self,val): self.val=val self.num=int(val[1:]) def __gt__(self,other): return self.num>other.num num=raw_input().strip() inp=raw_input().strip().split() arr=[] for ii in inp: arr.append(pock(ii)) bubb=deepcopy(arr) bubble_sort(bubb) insec=deepcopy(arr) selection_sort(insec) print " ".join(pp.val for pp in bubb) print "Stable" print " ".join(pp.val for pp in insec) ok=1 ln=len(arr) for i in xrange(ln): if(bubb[i].val!=insec[i].val): ok=0 break if ok==1: print "Stable" else: print "Not stable"