blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
df968beb2a09a5a573488c88082cfeb157a9b741
thosamanitha/python
/python/python.py
1,256
4.03125
4
# radius=4 # pi=3.14 # perimeter=2*pi*radius # print(perimeter) # area=pi*(radius**2) # print(area) # age=float(input()) # if 12<age<18: # g_s="teen" # print("g_s: " +g_s) # elif 18<=age<21: # print("Growth Stage:Young Adult") # elif 18>=21: # print("Growth Stage:Adult") # elif age<=12: # print("Growth Stage:child") # print(str(age) + " Years old") # n=int(input()) # i=1 # while i<n: # print(end=" " + str(i)) # i=i+1 # n,i=int(input()),1 # output="1" # while i<n: # i+=1 # if i%5==0: # continue # output+= " " + str(i) # print (output) # def add(a,b): # return a+b # print(add(b="anu",a="chinni")) #keyword arguments # print(add("anu","chinni")) #positional arguments # def add(a,b): # return a+b # print(add(a=2,b=3)) # def add(a,b): # return a+b # def multiply(a,b): # return a*b # def operate(a,b,operation=add): # return operation(a,b) # print (operate(2,4)) # print (operate(2,4,operation=multiply)) # def get_operator(operator): # if operator=="ADD": # return add # elif operator=="MULTIPLY": # return multiply # op=get_operator("ADD") # op(2,4) # op=get_operator("MULTIPLY") # op(2,4) add=lambda x,y:x+y print(add(1,2))
18d7eda436980e39885c58a19883ccee9225e794
ButchBet/Game-in-python
/rectangle.py
1,109
3.53125
4
import sys import pygame pygame.init() width = 400 height = 500 surface = pygame.display.set_mode((width, height)) #surface pygame.display.set_caption('Rectangle') ## Working with the colors ## Using a class .Color red = pygame.Color(255, 0, 0) green = pygame.Color(0, 255, 0) blue = pygame.Color(0, 0, 255) white = pygame.Color(255, 255, 255) black = pygame.Color(0, 0, 0) # Using a tuple my_color = (200, 90, 130) # Represent a rectangle # Using class .Rect rect = pygame.Rect(100, 150, 120, 60) # (x, y, width, height) rect.center = (width // 2, height // 2) # (x//2, y//2) Using double / cause # need that return be integer number # Using a tuple (We can't use atributes of the .Rect class) rect2 = (100, 100, 80, 40) # integers elements (x, y, width, height) print(rect.y) print(rect.x) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() surface.fill(white) pygame.draw.rect(surface, red, rect) #(surface, color, rectangle-perse) pygame.draw.rect(surface, green, rect2) pygame.display.update()
d660acb905c6b098f6ea27256606fbcb5a7fc2cb
v1nnyb0y/Coursera.BasePython
/Coursera/Week.5/Task.30.py
282
3.65625
4
''' Количество различных элементов ''' def countNum(a): count = 0 last = float('-inf') for i in a: if (i != last): last = i count += 1 return count a = list(map(int, input().split())) print(countNum(a))
cf7ae57d863e390eb9f4170c0d27cb26c87d38de
saurabhkawli/PythonHackerRankCodes
/TestSmartNumber.py
612
3.921875
4
import math num = 1 val = int(math.sqrt(num)) print("num: ",num," Val: ",val) print("Num/val",num/val) print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") num = 2 val = int(math.sqrt(num)) print("num: ",num," Val: ",val) print("Num/val",num/val) print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") num = 7 val = int(math.sqrt(num)) print("num: ",num," Val: ",val) print("Num/val",num/val) print("GGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGGG") num = 169 val = int(math.sqrt(num)) print("num: ",num," Val: ",val) print("Num/val",num/val)
797fc1ea37ea865d2873d0877dad7194ded9c682
MischaGithub/Python-project
/main_file.py
1,274
3.859375
4
import time #Import from the lottery file all that will be needed for display purposes #And to be able to write for the text file from lottery import legal_age, lottery_random, player_numbers, prize_catogery #Importing the date from datetime module to get the output of the date from datetime import date #Creating the variables for the functions to be displayed on screen and to be able to write #in a text file player_age = legal_age() now = date.today() lottery_numbers = lottery_random() player_numbers = player_numbers() category_details = prize_catogery(player_numbers, lottery_numbers) #Printing the results per function with its output print("The results of the lottery for today", str(now)) print("Lottery Numbers: ", str(lottery_numbers)) print("User Numbers: ", str(player_numbers)) print("You have won: ", category_details['category']) time.sleep(5) #Creating a text file to write the results #And putting each results on a new line with open('output-file.txt', 'w+') as file: file.write("The results of the lottery for today " + str(now) + "\n") file.write("Lottery Numbers: " + str(lottery_numbers) + "\n") file.write("User Numbers: " + str(player_numbers) + "\n") file.write("You have won: " + category_details['category'] + "\n")
81dc4a9c43e6499205735a14c93505e3bf31e50c
voodoopeople42/Vproject
/1/testc.py
1,067
4.125
4
import math what = input ( "what u want? (+, -, /, *, cos, sin, log, sqrt): " ) if what == "+": a = float (input("first number: ")) b = float (input("second number: ")) c = a + b print ("result: " + str(c)) elif what == "-": a = float (input("first number: ")) b = float (input("second number: ")) c = a - b print("result: " + str(c)) elif what == "/": a = float (input("first number: ")) b = float (input("second number: ")) c = a / b print("result: " + str(c)) elif what == "*": a = float (input("first number: ")) b = float (input("second number: ")) c = a * b print("result: " + str(c)) elif what == "cos": a = float (input("Input a number: ")) a = math.cos (a) print ("result: " + str(a)) elif what == "sin": a = float (input("Input a number: ")) a = math.sin (a) print ("result: " + str(a)) elif what == "log": a = float (input("Input a number: ")) a = math.log (a) print("result: " + str(a)) elif what == "sqrt": a = float (input("Input a number: ")) c = math.sqrt (a) print("result: " + str(a)) print("Thx for using myCalc" )
76bc7dedaecc1e88c3bae528125b2fa2860f3ce5
wail1994/pruches
/venv/Data.py
1,169
3.9375
4
import sqlite3 from tkinter import ttk import tkinter as tk conn = sqlite3.connect('Purchases.db') conn.execute('''CREATE TABLE IF NOT EXISTS Purchases (ID INT PRIMARY KEY NOT NULL, NAME TEXT NOT NULL, AGE TEXT NOT NULL, ADDRESS TEXT, SALARY TEXT);''') conn.execute("INSERT INTO Purchases (NAME,AGE,ADDRESS,SALARY) \ VALUES ( 'Paul', '32', 'California', '20000.00' )"); conn.commit() conn.close() def View(): conn = sqlite3.connect("Purchases.db") cur = conn.cursor() cur.execute("SELECT * FROM Purchases") rows = cur.fetchall() for row in rows: print(row) # it print all records in the database tree.insert("", tk.END, values=row) conn.close() root = tk.Tk() root.geometry("400x400") tree= ttk.Treeview(root, column=("column1", "column2", "column3", "column4"), show='headings') tree.heading("#1", text="NUMBER") tree.heading("#2", text="FIRST NAME") tree.heading("#3", text="NUMBER") tree.heading("#4", text="FIRST NAME") tree.pack() View() #b2 = tk.Button(text="view data", command=Insert) b2.pack() root.mainloop()
13ce35d609fe73c581fcadd5e175b3b4aa94eab7
ky2009888/learn_python_from_begin
/01-Python核心编程/代码/07-面向对象/03-面向对象其他/hm_04_类方法.py
316
3.59375
4
# 1. 定义类:私有类属性,类方法获取这个私有类属性 class Dog(object): __tooth = 10 # 定义类方法 @classmethod def get_tooth(cls): return cls.__tooth # 2. 创建对象,调用类方法 wangcai = Dog() result = wangcai.get_tooth() print(result)
fefaa9eb049a32fbf518d18f4bff6ff561e3ad74
maxx1256/scripts
/rate/mortgage.py
1,901
3.71875
4
class MortgageCalc(object): def __init__(self): self._balance = 211000.0 self._rate = 0.0375 self._periodsPerYear = 12 self._payPerPeriod = 2000.66 self._ratePaidTotal = 0.0 self._primePaidTotal = 0.0 self._ratePaidYear = 0.0 self._primePaidYear = 0.0 def _RunPeriod(self, year, month): ratePaid = self._balance * self._rate / self._periodsPerYear primePaid = self._payPerPeriod - ratePaid if (primePaid > self._balance): primePaid = self._balance ratePaid = 0 print("{}/{:02d} {:11.2f} {:11.2f} {:9.2f} {:9.2f}" .format(year, month, self._balance, self._balance - primePaid, primePaid, ratePaid)) self._balance = self._balance - primePaid self._ratePaidTotal = self._ratePaidTotal + ratePaid self._primePaidTotal = self._primePaidTotal + primePaid self._ratePaidYear = self._ratePaidYear + ratePaid self._primePaidYear = self._primePaidYear + primePaid def _RunYear(self, year): print("Month BalanceStart BalanceEnd PrincipalPaid InterestPaid") self._ratePaidYear = 0.0 self._primePaidYear = 0.0 i = 0 while i < self._periodsPerYear: i += 1 self._RunPeriod(year, i) print("{} total -- -- {:9.2f} {:9.2f}".format(year, self._primePaidYear, self._ratePaidYear)) print("Grand Total -- -- {:9.2f} {:9.2f}".format(self._primePaidTotal, self._ratePaidTotal)) print("Deficit {:11.2f}".format(self._ratePaidTotal + self._balance)) print() def Run(self): year = 2020 while year < 2028: self._RunYear(year) year += 1 mort = MortgageCalc() mort.Run()
f087f12bd1fa4e7b0bf884a58676e49dd99f5a27
nikhilNathwani/project_euler
/euler26.py
772
3.828125
4
import time import math primes=[2] start= time.time() def isPrime(num): sqrt= math.sqrt(num) for elem in primes: if num%elem==0: return False if elem>sqrt: return True return True def primesUnder(n): global primes curr= 3 while curr<n: #print curr, len(primes) if isPrime(curr): primes += [curr] curr += 2 def repeatedNineMultiple(num): nineMult= 9 count= 0 while nineMult%num != 0: count += 1 nineMult += 9*(10**count) return nineMult, count+1 primesUnder(1000) maxRepeat= 0; maxRepeatNum= 0 primes.remove(2); primes.remove(5) #can't have divisors of 10 for p in primes: n,reps= repeatedNineMultiple(p) if reps>maxRepeat: maxRepeat= reps maxRepeatNum= p print "Answer:", maxRepeatNum print "Time taken:", time.time()-start
07a2e20be31df85c638ddb9a4e6af874e29a8130
wernicka/learn_python
/original_code/experiments/transit_expenses_calculator_v4.py
3,526
3.703125
4
# I do not understand how I fucked this up so much. Something about floats vs. strings? #error messages not_number = "Error message: not a number" too_small = "Error message: number too small" too_large = "Error message: number too large" #empty clean variables clean_weeks_vacation = "" # none of the options seem to work clean_days_public_transit = [] clean_one_way = 0 #commenting out the feedback to see if that eliminates the issues #weeks_feedback = "Ok, you were off work about {} weeks, so you worked about {} weeks." .format(clean_weeks_vacation, 52 - float(clean_weeks_vacation)) #days_feedback = "Ok, you typically take public transit {} days each week." .format(clean_days_public_transit) #fare_feedback = "Gotcha, your one way fare is $ {}." .format(clean_one_way) #set variables for lists of questions, max numbers, variables for validated data to be set to, #and user feedback message for each of the three data points I need to analyze weeks = ["How many weeks were you on vacation or leave this year? ", 52, clean_weeks_vacation] #weeks_feedback as forth item in list days = ["""Think about how many days per week you work from home, carpool, bike, or rideshare. So how many days per week do you typically take public transit? """, 7, clean_days_public_transit] #days_feedback as forth item in list fare = ["""Go to wmata.com and calculate your one way fare. Make sure it's the rush hour fare if you commute during rush hour. Enter that value here: """, 100, clean_one_way] #fare_feedback as forth item in list #list of lists allData = [weeks, days, fare] #function to test if input is a float def NumberTest(i): try: val = float(i) return True except ValueError: return False #function to test for bad inputs, provide user error messages, require new input, # set valid input to pre-specified variable, and print user feedback def validate(x): q = x[0] m = x[1] c = x[2] #f = x[3] while True: print(q) k = input() if NumberTest(k) is True: if float(k) > 0: if float(k) <= m: break else: print(too_large) else: print(too_small) else: print(not_number) c = k #WTF my new values are not being saved to the variable after I set the c = 0 in the original variables. #After I put in return c, it also stopped doing any of these print statements #return c didn't do anything to fix, nor did c += float(k) print(c) print(k) #print(f) print (" ") # Intro print("Welcome to Amanda's D.C. Public Transit Annual Expense Calculator") print("First, I need some information.") for i in allData: validate(i) total = clean_one_way * (float(clean_days_public_transit) * 2) * (52 - float(clean_weeks_vacation)) # cost of public transit commutes per year print ("Your approximate total public transit cost this year was $", int(total), ".") print(" ") print("Don't forget to use your employer's commuter benefit so you don't have to pay taxes on this $" , int(total), ".") print("By using commuter benefits, you save roughly $",int(total * 0.33),".") print(" ") print("Thanks for using Amanda's D.C. Public Transit Annual Expense Calculator!") #ideas for more complexities/modifications #what if the user takes the bus some days and the metro others? Those have different costs #what the user commutes differently seasonally? e.g. I bike for 6 months and metro the rest
423532a1100a2802712fae5921d603f916ff1ab5
python-yc/pycharm_script
/spider/basicuse_lxml_26_etree_and_soup.py
622
3.5
4
# -*- coding: utf-8 -*- from lxml import etree from bs4 import BeautifulSoup # 使用beautifulsoup4读取时,需要先使用read将文件读取出来,然后再进行使用 with open("./test.xml") as f: html = f.read() soup = BeautifulSoup(html, 'lxml') print(soup.find("book")) print('-'*10) print(soup.find(name="book")) print('=========================='*10) html = etree.parse("./test.xml") print(type(html)) rst = html.xpath('//book[@category="sport"]') rst = rst[0] print(type(rst)) print(rst, "===") print(rst.tag) print("===================================") rst = html.xpath('//book') print(rst)
a53e8435feed1ccc3985d8cd9b85109ea484b069
ShahriarXD/Junks
/04_input_function.py
118
3.921875
4
a = input("Enter a number: ") a = int(a) # Convert a to an Integer(if possible) a += 55 print(type(a)) print (a)
0e34598f139b35f6776d39b43d2c32a227d4a2a7
jiangkuan2018/algorithm
/prime.py
878
3.734375
4
# coding=utf-8 import math def sieve_of_eratosthenes(n):#埃拉托色尼筛选法,返回少于n的素数 primes = [True] * (n+1)#范围0到n的列表 p = 2#这是最小的素数 while p * p <= n:#一直筛到sqrt(n)就行了 if primes[p]:#如果没被筛,一定是素数 for i in range(p * 2, n + 1, p):#筛掉它的倍数即可 primes[i] = False p += 1 primes = [element for element in range(2, n) if primes[element]]#得到所有少于n的素数 return primes def isPrime(n): if n % 5 != 0 and n % 7 != 0: # 判断一个属于是否能被5或7整除 return True # 真,则为质数 else: return False HRNUM = 707829217 daixuan = [] print(sieve_of_eratosthenes(100)) def findPrime(arr): for num in arr: if isPrime(HRNUM / num): daixuan.append(num) print(daixuan) findPrime(sieve_of_eratosthenes(100))
435a340c7f2bf6bca328abed4ee791c03ce2805c
CamiloBzt/proyecto_palabras_encadenadas
/temas/mostrar_temas.py
2,343
3.703125
4
import json def traer_temas(ruta: str) -> dict: """ Función que retorna un diccionario con los temas y palabras. :param ruta: ruta del archivo de temas. :return: diccionario de temas. """ archivo = open(ruta, 'r') dic_temas = json.loads(archivo.read()) archivo.close() return dic_temas def save_temas(ruta: str, temas: list, palabra: str) -> None: """ Función que guarda las palabras que se validen durante una partida. :param ruta: ruta del archivo de temas. :param temas: temas escogidos en la partida. :param palabra: palabra digitada por el jugador. """ temas_dic = traer_temas(ruta) if len(temas) == 1: palabras = temas_dic.get(temas[0]) palabras.append(palabra) temas_dic[temas[0]] = palabras temas_dic = json.dumps(temas_dic, indent=3) archivo = open(ruta, "w") archivo.write(temas_dic) archivo.close() else: print(''.center(40, '-')) print(' Digite a que tema pertenece '.center(40, '-')) print(' la palabra {} '.center(40).format(palabra)) print(''.center(40, '-')) topic = None while not topic: for tema in temas: if not topic: print(' Digite 1 si es del tema'.center(40, '-')) print(' enter de lo contrario '.center(40, '-')) print(''.center(40, '-')) print(tema.center(40)) print(''.center(40, '-')) selec = input() while selec != '1' and selec != '': print('-'.center(40, '-')) print(' Digite una opción valida '.center(40, '-')) print('-'.center(40, '-')) selec = input() if selec == '1' and selec != '': topic = tema palabras = temas_dic.get(topic) palabras.append(palabra) temas_dic[topic] = palabras temas_dic = json.dumps(temas_dic, indent=3) archivo = open(ruta, "w") archivo.write(temas_dic) archivo.close() print(''.center(40, '-')) print(' Gracias '.center(40, '-')) print(' Volvamos al juego '.center(40, '-')) print(''.center(40, '-'))
3f2c363094349e5a56faa83c3231b3c53ef4fcc1
gpreviatti/exercicios-python
/MUNDO_02/Aula_14/Ex62.py
520
4.09375
4
#melhore o desafio 061, perguntando para o usuário se ele quer mostrar mais #alguns termos. O programa encerra quando disse que quer mostrar 0 termos n = int(input('Digite um número: ')) r = int(input('Digite a razão: ')) termo = n cont = 1 total = 0 mais = 10 while mais != 0: total += mais while cont<= total: print(termo) termo += r cont += 1 print('PAUSA') mais = int(input('Deseja ver mais quantos termos? ')) print(f'Foram mostrados {total} termos')
f385b19544051242da85344b7ba5b0406378fc43
igorgabrig/AprendizadoPython---curso-em-video
/Mundo03/desafios/Desafios Modulos e Pacotes/ex107/main.py
489
3.84375
4
# Crie um módulo chamado moeda.py que tenha as funções incorporadas # aumentar(), diminuir(), dobro() e metade(). # Faça também um programa que importe esse módulo e use algumas dessas funções. import moeda valor = float(input('Digite um valor: ')) print(f'A metade de {valor} é {moeda.metade(valor)}') print(f'O dobro de {valor} é {moeda.dobro(valor)}') print(f'Aumentando em 10%, temos {moeda.aumentar(valor)}') print(f'Diminuindo em 10%, temos {moeda.diminuir(valor)}')
a467122e901e2ba7732798dae74c81d17d50d241
goswamiprashant/Machine-Learning
/matplotlib_4.py
298
4.0625
4
# to draw a bar graph import matplotlib.pyplot as plt x=[1,2,3,4,5,6] y=[12,34,22,10,45,21] tick_label=['one','two','three','four','five','six'] plt.bar(x,y,tick_label=tick_label,color=['green','blue'],width=.7) plt.xlabel("x-axis") plt.ylabel("y-axis") plt.title('bar-graph') plt.show()
b9aa84330526ef1a8a5ca9066490d6af052bff36
Nikolas2001-13/Universidad
/Nikolas_ECI_181/PIMB/Arena 2/arithmetic.py
209
3.578125
4
from sys import stdin def arithmetic(): a=int(stdin.readline().strip()) b=int(stdin.readline().strip()) x=a+b y=a-b z=a*b print(x) print(y) print(z) arithmetic()
2d18f1e7878a535d8938ec1d63eb303acdcd2c4d
yashwanth-ds/human-actions
/mlp/alcohal.py
1,404
3.5625
4
import numpy as np import pandas as pd import matplotlib.pyplot as plt from sklearn.datasets import load_wine wine = load_wine() X= pd.DataFrame(wine.data, columns=wine.feature_names) data1=pd.DataFrame(X['alcohol'])#load the values in alcohol column to data1 data2=pd.DataFrame(X['malic_acid'])#load the values in malic_acid column to data2 data=pd.concat([data1,data2],axis=1) data.head(5) plt.scatter(data1,data2,color='green') #plt.show() data1_std = np.array(data1) feature1 = (data1_std - data1_std.mean())/data1_std.std() data2_std = np.array(data2) feature2 = (data2_std - data2_std.mean())/data2_std.std() print(f"Mean after standardization:\nAlcohol={feature1.mean()}, Malic acid={feature2.mean()}") print(f"standard deviation after standardization:\nAlcohol={feature1.std()}, Malic acid={feature2.std()}") plt.scatter(feature1,feature2,c='r') from sklearn import preprocessing std_scale = preprocessing.StandardScaler().fit([data1,data2]) df_standardize = std_scale.transform([data1,data2]) data1_norm = np.array(data1) ft1 = (data1_norm - data1_norm.mean()) / (max(data1_norm)-min(data1_norm)) data2_norm = np.array(data2) ft2 = (data2_norm - data2_norm.mean()) / (max(data2_norm)-min(data2_norm)) print(f"Mean after standardization:\\nAlcohol={ft1.mean()}, Malic acid={ft2.mean()}") print(f"Standard deviation after standardization:\\nAlcohol={ft1.std()}, Malic acid={ft2.std()}")
bd8a2a0907d434376ba2b7d2dd8e891f88e7e5d4
PritKalariya/Python-practice-problems-and-exercises
/The Basics - Functions and Conditionals/Hot, Warm or Cold.py
434
4.1875
4
# Write a function that: # 1. Takes a temperature as parameter # 2. Returns 'Hot' if the temp is greater than 25 # 3. Returns 'Warm' if the temp is between 15 and 25, including 15 and 25 # 4. Return 'Cold' if temp is less than 15 def meter(temp): if temp > 25: return "Hot" elif temp >=15 and temp <=25: return "Warm" else: return "Cold" print(meter(10)) print(meter(20)) print(meter(30))
1157431041aad5849df9c0f5c26bd73594791aa5
lyricjixh/pychallenge
/challenge07.py
1,105
3.625
4
#!/usr/bin/env python # challenge level 6 from PIL import Image import urllib,string,StringIO url = "http://www.pythonchallenge.com/pc/def/oxygen.png" img = urllib.urlopen(url).read() data = Image.open(StringIO.StringIO(img)) y = 0 while True: col = data.getpixel((0, y)) # print "col: ", col if(col[0] == col[1] == col[2]): break y += 1 print "the hight of grey bar is: ", y #how far across? x = 0 while True: col = data.getpixel((x, y)) # print "col: ", col if not(col[0] == col[1] == col[2]): break x += 1 print "the width of grey bar is: ", x print "the grey bar is: ",x, "x",y, "px" #span of the grey block? z = 0 span=list() rgb_new = data.getpixel((0,y)) for z in xrange(x): print rgb_new rgb_old = rgb_new rgb_new = data.getpixel((z, y)) if not (rgb_new == rgb_old): print 'new grey block at: %s * %s' %(z,y) span.append(z) print span out = [] for i in range(0,x,7): col = data.getpixel((i,y)) out.append(chr(col[0])) print "out: ", out print "".join(out) hint = [105, 110, 116, 101, 103, 114, 105, 116, 121] print ''.join([chr(i) for i in hint])
2ab93852d6be16e2bcf1614de5aaf7846572908b
superpigBB/Happy-Coding
/Algorithm/K Closet In Sorted Array - Lai.py
5,865
3.5625
4
""" K Closest In Sorted list Medium Given a target integer T, a non-negative integer K and an integer list A sorted in ascending order, find the K closest numbers to T in A. If there is a tie, the smaller elements are always preferred. Assumptions A is not null K is guranteed to be >= 0 and K is guranteed to be <= A.length Return A size K integer list containing the K closest numbers(not indices) in A, sorted in ascending order by the difference between the number and T. Examples A = {1, 2, 3}, T = 2, K = 3, return {2, 1, 3} or {2, 3, 1} A = {1, 4, 6, 8}, T = 3, K = 3, return {4, 1, 6} """ class Solution(object): """ 解题思路:有target value, and list is a sorted list => binary search基本直接能判定 实际这题有点像find closest element的进阶,相当于先用binary search找到那个closest element in list; 然后再在那个数的list的位置附近找K个数 Time:O(logn + k) => O(logn) Space: O(k) """ """2nd 参考其他optimized解法写的: binary search part是基本一样的,就是加了个helper function; 然后就是在在two pointer search k的时候有改善 =>空间和时间复杂度一样 ref: laicode https://docs.google.com/document/d/1h2VPHYKFPE9v1_LJIfRQn8a9-kJX22j-QDCANGyGRgY/edit 九章 https://www.jiuzhang.com/solution/find-k-closest-elements/ """ def kClosest(self, list, target, k): """ input: int[] list, int target, int k return: int[] """ # write your solution here """ 这一段binary search和kclosest2 一样, 在closest_index这里改动了下: """ """Corner Cases: better ask interviewer to confirm return value for corner cases""" if list is None or len(list) == 0 or k == 0: return [] """find closest element from target first in list: 利用helper function call binary search first to get closest index make that closet element a centered value and set two pointers i & j to get the k closest """ i = self.findLowerClosest(list, target) j = i + 1 return_list = list() # return list to store sorted elemets according to |e.value - target| """这一段找k个element的入list的过程是enhanced的,只是喜欢这个的func design思想,别的没区别""" for index in range(k): # if left i is closer if j > len(list) - 1 or (i >= 0 and abs(list[i] - target) <= abs(list[j] - target)): return_list.append(list[i]) i -= 1 else: # if right j is closer return_list.append(list[j]) j += 1 return return_list """helper function for binary search""" def findLowerClosest(self, list, target): start, end = 0, len(list) - 1 """Removed closest_index 先定义,因为可以把找到的当成end,然后继续找最小的""" while start < end - 1: mid = (start + end) // 2 if list[mid] == target: end = mid elif list[mid] > target: end = mid else: start = mid return start if abs(list[start] - target) <= abs(list[end] - target) else end """1st 自己第一次写的""" def kClosest2(self, list, target, k): """ input: int[] list, int target, int k return: int[] """ # write your solution here """Corner Cases: better ask interviewer to confirm return value for corner cases""" if list is None or len(list) == 0 or k == 0: return [] """find closest element from target first in list""" start, end = 0, len(list) - 1 while start < end - 1: mid = (start + end) // 2 if list[mid] == target: end = mid # 因为就算相等,也可能有多个index和Target value一样,要找最小的Index elif list[mid] > target: end = mid else: start = mid # locate closest index closest_index = start if abs(list[start] - target) <= abs(list[end] - target) else end """make that closet element a centered value and set two pointers i & j to get the k closest""" i, j = closest_index - 1, closest_index + 1 return_list = [list[closest_index]] # return list to store sorted elemets according to |e.value - target| if len(return_list) == k: # if k == 1 return return_list while i >= 0 and j <= len(list) - 1: if abs(list[i] - target) <= abs(list[j] - target): return_list.append(list[i]) i -= 1 else: return_list.append(list[j]) j += 1 if len(return_list) == k: return return_list if i < 0: return_list.extend(list[j:(j + k - len(return_list))]) return return_list if j > len(list) - 1: if i - (k - len(return_list)) < 0: return_list.extend(list[i::-1]) else: return_list.extend(list[i : i - (k - len(return_list)): -1]) return return_list print(Solution().kClosest([1, 2, 3], target=2, k=1)) # [2] print(Solution().kClosest([1, 2, 3], target=2, k=3)) # [2, 1, 3] or [2, 3, 1] print(Solution().kClosest([1, 4, 6, 8], target=3, k=3)) # [4, 1, 6] print(Solution().kClosest([1, 2, 4, 6, 7, 8, 9], target=7.5, k=5)) # [7, 8, 6, 9, 4] print(Solution().kClosest([1, 2, 4, 6, 7, 8, 9], target=0, k=3)) # [1, 2, 4] print(Solution().kClosest([1, 2, 4, 6, 7, 8, 9], target=9, k=1)) # [9] print(Solution().kClosest([1, 3, 5], target=10, k=3)) # [5, 3,1] print(Solution().kClosest([1], target=0, k=0)) # []
9f93d21a44525f98ac43c68841a9120ceb88319a
brandoneng000/LeetCode
/medium/893.py
580
3.71875
4
from typing import List import collections class Solution: def numSpecialEquivGroups(self, words: List[str]) -> int: res = set() for word in words: even = "".join(sorted(word[::2])) odd = "".join(sorted(word[1::2])) res.add((even, odd)) return len(res) def main(): sol = Solution() print(sol.numSpecialEquivGroups(words = ["abcd","cdab","cbad","xyzz","zzxy","zzyx"])) print(sol.numSpecialEquivGroups(words = ["abc","acb","bac","bca","cab","cba"])) if __name__ == '__main__': main()
184a8033d5eaee11db5ce81fff40d62db29437fa
Hrkrabbe/Python
/Øving 7/Sortering.py
1,164
3.71875
4
__author__ = 'Anders' import timeit import random def main(): listelengde = 200 liste = [random.randint(0,listelengde) for i in range(listelengde)] liste1 = bubbleSort(liste[:]) liste2 = selectionSort(liste[:]) print("Usortert liste: ") print(liste) print() print("Liste sortert med bubblesort:") print(liste1) t = timeit.Timer(lambda: bubbleSort(liste[:])) print("Tid:",t.timeit(number=1)) print() print("Liste sortert med selectionsort:") print(liste2) t = timeit.Timer(lambda: selectionSort(liste[:])) print("Tid:",t.timeit(number=1)) def bubbleSort(liste): sorted = False while(not sorted): sorted = True for i in range(len(liste)-1): if (liste[i] > liste[i+1]): liste[i], liste[i+1] = liste[i+1], liste[i] sorted = False return liste def selectionSort(liste): for j in range(len(liste)): iMin = j for i in range(j, len(liste)): if(liste[i] < liste[iMin]): iMin = i if(iMin != j): liste[j], liste[iMin] = liste[iMin], liste[j] return liste main()
edf03be03bb19ef848d5f6f7517b83b8175eb996
alvinzhu33/6.006
/6/tests.py
3,770
3.515625
4
import unittest from solve_puzzle import solve_puzzle def solved(n, m): return tuple(tuple(n * (m - j) - i - 1 for i in range(n)) for j in range(m)) def move(mv, config): n, m = len(config[0]), len(config) for i in range(n): for j in range(m): if config[j][i] == 0: k, l = i, j if mv == 'U' and j != m - 1: l = j + 1 elif mv == 'D' and j != 0: l = j - 1 elif mv == 'L' and i != n - 1: k = i + 1 elif mv == 'R' and i != 0: k = i - 1 else: return None return tuple(tuple( config[j][i] if el == config[l][k] else ( config[l][k] if el == config[j][i] else el) for el in row) for row in config) raise TypeError('No zero to move configuration') def check_moves(config, moves): if moves is None: return True # this case not checked here (would solve your problem set) sol = solved(len(config[0]), len(config)) for mv in moves: config = move(mv, config) if config == sol: return True return False test = ( ((3, 2), (1, 0)), ((1, 0), (2, 3)), ((0, 1, 4), (5, 2, 3)), ((3, 0, 1), (4, 5, 2)), ((0, 4), (5, 3), (1, 2)), ((2, 1), (3, 5), (0, 4)), ((8, 7, 6), (2, 5, 4), (1, 0, 3)), ((8, 4, 0), (5, 3, 7), (2, 6, 1)), ((15, 14, 0, 12), (11, 10, 13, 8), (7, 6, 9, 4), (3, 2, 5, 1)), ((15, 14, 13, 12), (11, 10, 9, 8), (7, 0, 2, 5), (3, 1, 6, 4)), ) test_solutions = ( # one solving sequence for each (many are possible) (), ('U', 'R', 'D', 'L', 'U'), ('U', 'L', 'D', 'L', 'U'), ('R', 'U', 'L', 'L', 'D', 'R', 'R', 'U', 'L', 'L'), ('U', 'L', 'U'), ('D', 'D', 'L', 'U', 'U', 'R', 'D', 'D', 'L', 'U', 'U', 'R', 'D', 'L', 'U'), ('R', 'D', 'L', 'L', 'U'), ('U', 'R', 'U', 'L', 'D', 'R', 'D', 'L', 'U', 'U'), ('U', 'U', 'U', 'L'), ('L', 'U', 'R', 'D', 'L', 'L', 'U'), ) class TestDecodeMessage(unittest.TestCase): def test_01(self): self.assertTrue(check_moves(test[0], solve_puzzle(test[0]))) # self.assertTrue(check_moves(test[0], test_solutions[0])) def test_02(self): self.assertTrue(check_moves(test[1], solve_puzzle(test[1]))) # self.assertTrue(check_moves(test[1], test_solutions[1])) def test_03(self): self.assertTrue(check_moves(test[2], solve_puzzle(test[2]))) # self.assertTrue(check_moves(test[2], test_solutions[2])) def test_04(self): self.assertTrue(check_moves(test[3], solve_puzzle(test[3]))) # self.assertTrue(check_moves(test[3], test_solutions[3])) def test_05(self): self.assertTrue(check_moves(test[4], solve_puzzle(test[4]))) # self.assertTrue(check_moves(test[4], test_solutions[4])) def test_06(self): self.assertTrue(check_moves(test[5], solve_puzzle(test[5]))) # self.assertTrue(check_moves(test[5], test_solutions[5])) def test_07(self): self.assertTrue(check_moves(test[6], solve_puzzle(test[6]))) # self.assertTrue(check_moves(test[6], test_solutions[6])) def test_08(self): self.assertTrue(check_moves(test[7], solve_puzzle(test[7]))) # self.assertTrue(check_moves(test[7], test_solutions[7])) def test_09(self): self.assertTrue(check_moves(test[8], solve_puzzle(test[8]))) # self.assertTrue(check_moves(test[8], test_solutions[8])) def test_10(self): self.assertTrue(check_moves(test[9], solve_puzzle(test[9]))) # self.assertTrue(check_moves(test[9], test_solutions[9])) if __name__ == '__main__': res = unittest.main(verbosity = 3, exit = False)
4f221cbe290f3e5c9b2fc5b2fa37ba9fd15c7b64
rimesta21/ZombieGame
/Zombies/Turn.py
1,570
3.625
4
# -*- coding: utf-8 -*- """ Created on Mon Jan 25 16:34:28 2021 @author: rimes """ import random from Zombies.Dice.greenDie import greenDie from Zombies.Dice.redDie import redDie from Zombies.Dice.yellowDie import yellowDie class Turn: def __init__(self): self.cup = {"red" : 3, "yellow" : 3, "green" : 3} self.onHand = [] def checkCup(self): inCup = sum(list(self.cup.values())) if inCup + len(self.onHand) < 3: self.cup = {"red" : 3, "yellow" : 3, "green" : 3} for i in self.onHand: self.cup[i] -= 1 def getDice(self): self.checkCup() while len(self.onHand) < 3: color = list(self.cup.keys())[random.randint(0,2)] if(self.cup[color] != 0): self.cup[color] -= 1 self.onHand.append(color) def rollDice(self, zombie): result = [] temp = list(self.onHand) for i in temp: if i == "red": die = redDie() elif i == "yellow": die = yellowDie() else: die = greenDie() face = die.getFace() print(zombie + " got a " + i + " die and rolled " + face + ".") if face != "footstep": self.onHand.remove(i) result.append(face) return result def reset(self): self.cup = {"red" : 3, "yellow" : 3, "green" : 3} self.onHand = []
606af434d714d6c7b924f996c7662ba6e30050a1
kcyoon689/Algorithm
/ETC/trump.py
675
3.59375
4
#2 # Trump Card list1 = ["Spade", "Heart", "Diamond", "Clover"] list2 = ["A", 2, 3, 4, 5, 6, 7, 8, 9, 10, "J", "Q", "K"] count = 1 for i in list1: for j in list2: print(count, i, j) count += 1 #################################################################################################### # 2-1 list1 = ["Spade", "Heart", "Diamond", "Clover"] list2_1 = ["A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K"] trump = { } # 딕셔너리 선언 count = 1 for i in list1: for j in list2_1: trump[count] = [i + " " + j] # 딕셔너리에 저장 count += 1 print(trump) # 딕셔너리 출력
53ea49ca1b2924a8e8f2f11fcf438302f81fee35
helenpark/PIP
/Algorithm and Data Structure Impl/Generator.py
341
4.09375
4
# Generator example def square(nums): for i in nums: yield (i * i) my_nums = square([1,4,2,5]) # OR: using comprehension # comprehension nums_comprehended = [x*x for x in [1,2,3,4]] # becomes: generator nums_generator = (x*x for x in [1,2,3,4]) print my_nums print nums_comprehended print nums_generator print list(nums_generator)
0dddcecae59283f218e4ce8efc83d4e15bb4a43b
PTLamTOP/A-Level
/29/check_age_new.py
3,549
3.703125
4
""" 1) класс, который принимает дату рождения в текстовый формат (01-05-1991). 2) написать property, которая возвращает возраст 3) вынести в статик метод метод перевода строки в дату 4) написать свойство которое говорить сколько человек прожил високосных год. )Узнать какие годы были высокосные и потом посчитать количество) """ # импортируем модуль datetime для работы с датой и временем import datetime # создаем свой класс ошибки для обработки неправильного форматат даты class InvalidDate(Exception): pass # создаем класс Man class Man: # сегодняшняя дата today = datetime.date.today() # принимаем имя и дату рождения при нициализации def __init__(self, name: str, date: str, *args, **kwargs): self.name = name self._date = self._validate_date(date=date) # МЕТОДЫ ДЛЯ РАБОТЫ С ДАТОЙ # создаем staticmethod для перевода строки в нужный формат даты ДД-ММ-ГГГГ @staticmethod def _date_formatting(date): return datetime.datetime.strptime(date, '%d-%m-%Y') # метод для проверки валидации даты def _validate_date(self, date): # форматированная дата из строки formatted_date = self._date_formatting(date).date() # проверяем date не пустая строка, если тип данных в строке # и проверяем если формат даты в строки является таким ДД-ММ-ГГГГ # проверяем если дата рождения не больше сегодняшней даты if date and isinstance(date, str) and formatted_date and self.today >= formatted_date: return formatted_date # вызываем кастомную ошибку, если формат не сходится raise InvalidDate('Invalid Date!') # создаем свойства через property для подсчета и вывода возраста @property def get_age(self): # сравниваем если текущий день и месяць, с днем и месяцям рождения. Если меньше, то возращает 0(false), в противном случае 1(true) age = self.today.year - self._date.year - ((self.today.month, self.today.day) < (self._date.month, self._date.day)) return f'{self.name} is {age} years old' # создаем свойство для получения даты рождения @property def get_birthday_date(self): return self._date # создаем свойство для подсчета високосных лет @property def get_leap_year(self): leap_year = 0 for year in range(self._date.year, self.today.year): if (year % 100 == 0) and (year % 400 == 0) or (year % 4 == 0): leap_year += 1 return f'{self.name}\'ve lived for {leap_year} leap years.' # Тест man_1 = Man('Akira', '02-12-2000') print(man_1.get_leap_year)
3aa582c3a80e8040a3a436fca17c7b4de4e5c6d5
Deepa-chinnu/python-lab
/Lab/Lab 3/football.py
3,647
4.3125
4
""" Title: Football Description: Define a class called “Ball” which defines the position of the ball by using x,y positions [x-coordinate, y-coordinate] and delta-x, delta-y which gives the amount change in x-direction and y-direction respectively. Define another class called “MyFavGame” which inherits the “Ball” class has dimensions of ground, goal posts and has methods to move the ball in the ground, into the posts and maintains score. You get a point if you move the ball into the goal posts and lose a point if your ball moves out of the ground. Also give yourself a minimum of 5 moves and print the score you get after that. Author: akashroshan135 Date: 25-Feb-2021 """ class ball(): # sets ball to center of the ground def newBall(self, x, y): self.x_pos = x self.y_pos = y # moves the ball's position def ball_move(self, x, y): self.x_pos += x self.y_pos += y # prints the ball's current position def give_ball_pos(self): print('Ball\'s X position =', self.x_pos) print('Ball\'s Y position =', self.y_pos) class MyFavGame(ball): # coordinates for the ground, can be altered ground_x = 100 ground_y = 80 score = 0 # sets the goal positons def __init__(self): x = int(self.ground_x / 2) y = int(self.ground_y / 2) self.newBall(x, y) self.Goal_y1 = self.ground_y * 0.4 self.Goal_y2 = self.ground_y * 0.6 # resets the ball's position after goal or out of bounds def resetBall(self): x = int(self.ground_x / 2) y = int(self.ground_y / 2) self.newBall(x, y) self.show_score() # changes the ball's position and checks for goal or out of bounds def kick(self, x, y): self.ball_move(x, y) # checks for goal if self.x_pos >= self.ground_x and self.y_pos >= self.Goal_y1 and self.y_pos <= self.Goal_y2: print('Goal!!!') self.score += 1 self.resetBall() # checks for opponent's goal elif self.x_pos <= 0 and self.y_pos >= self.Goal_y1 and self.y_pos <= self.Goal_y2: print('You hit the opponent\'s goal!') self.score -= 1 self.resetBall() # checks for out of bounds elif self.x_pos >= self.ground_x or self.y_pos >= self.ground_y or self.x_pos < 0 or self.y_pos <0: print('Ball is out of bounds!') self.score -= 1 self.resetBall() # prints the current score def show_score(self): print('Score is', self.score) # prints the grounds coordinates def show_ground(self): print('Ground X coordinates are from 0 to', self.ground_x) print('Ground Y coordinates are from 0 to', self.ground_y) # prints the goal coordinates def show_goals(self): print('Your goal coordinates are >', self.ground_x, ',', self.Goal_y1, ',', self.Goal_y2) print('Your opponent\'s goal coordinates are < 0', ',', self.Goal_y1, ',', self.Goal_y2) print('\tWelcome to Football Game\n') play = True while play == True: loop = 0 game = MyFavGame() game.show_ground() game.give_ball_pos() game.show_goals() while loop < 5: print('\nyou have', 5 - loop, 'move(s) left') choice = int(input('1. Kick the ball\n2. Check ball\'s position\n3. Check Score\n4. Check Ground coordinates \n5. Check Goal Posts\n6. Exit\n')) if choice == 1: x = int(input('Give delta x = ')) y = int(input('Give delta y = ')) game.kick(x, y) game.give_ball_pos() loop += 1 elif choice == 2: game.give_ball_pos() elif choice == 3: game.show_score() elif choice == 4: game.show_ground() elif choice == 5: game.show_goals() else: loop = 5 print('\nGame Over\nYou have scored', game.score, 'points') choice = input('Do you want to continue playing (y/n) : ') if choice != 'y': play = False print('Thank you for playing')
7ab72b4899e6c4202236a5dddf4cbaa3325463d7
bri4nle/ai-text-completion-project
/file_io.py
426
3.765625
4
class FileIO: """ This class provides file IO """ def __init__(self, file_name): self.content = '' self.__file_name = file_name def read(self): """ This function read the file input file and return its content :return: """ with open(self.__file_name, encoding='utf8', mode="r") as f: self.content += f.read() return self.content
d9b2abada9bc6968e5f6e51a2a0de7fdf756510b
Ataago/Data-Structures-Algorithms
/src/recursions/007_recursion_sum_of_subset.py
564
4.0625
4
# !/usr/bin/env python3 # encoding: utf-8 """ Given a list a list of Integers, find any subset which adds up to a Target. @author: Mohammed Ataaur Rahaman """ def sum_of_subset0(integers, target, subset): if sum(subset) == target: print(subset) exit(0) if len(integers) == 0: return sum_of_subset0(integers[1:], target, subset + [integers[0]]) sum_of_subset0(integers[1:], target, subset) if __name__ == '__main__': integers = [1, -10, 9, 4, 3, 2, 50, 12, 13, -5] target = 20 sum_of_subset0(integers, target, [])
38ab475dee8ec4b68f53f3a5b18b5c611b9bb56b
katarzynawozna/metody-numeryczne-1
/Lista2/zadanie3.py
275
3.703125
4
def first_method(x): return (((x ** 2) + 1) ** (1 / 2)) - 1 def second_method(x): return (x ** 2) / ((((x ** 2) + 1) ** (1 / 2)) + 1) for x in range(25): print(f"For {x} first method gives: {first_method(2 ** x)} \n second method gives {second_method(2 ** x)}")
1a1a1ee0f841a67ee9fe38c78ef962be99a0da2d
yaroslav2703/CodeWars
/task18.py
345
3.671875
4
def sum_of_intervals(intervals): a = () for j in intervals: a = a + tuple(range(j[0], j[1])) a = sorted(list(set(a))) return len(a) print(sum_of_intervals([(1, 4), (7, 10), (3, 5)])) print(sum_of_intervals([(1, 5), (6, 10)])) print(sum_of_intervals([(1, 5), (1, 5)])) print(sum_of_intervals([(1, 4), (7, 10), (3, 5)]))
43faf4fbc765556c1a1dee1717c1fa11c47bec5b
abay-90/NISprogramming
/Module 2/Class Lecture & Practise programming/CalculateAreaOfShape.py
1,075
4.3125
4
import math def calculate_area_of_shape(shape, length=0, height=0, width=0, radius=0): if shape == "square": return length * length if shape == "rectangle": return length * width if shape == "cube": return length * length * 6 if shape == "circle": # You could import Math and use math.Pi instead of 3.14 return 3.14 * radius * radius # return math.pi * radius * radius if shape == "cylinder": # You could import Math and use math.Pi instead of 3.14 return 2 * 3.14 * radius * height + 2 * 3.14 * radius * radius # return 2 * math.pi * radius * height + 2 * math.pi * radius * radius if __name__ == "__main__": print("Square: ", calculate_area_of_shape("square", length=10)) print("Rectangle: ", calculate_area_of_shape("rectangle", length=12, width=5)) print("Cube: ", calculate_area_of_shape("cube", length=10)) print("Circle: ", calculate_area_of_shape("circle", radius=8)) print("Cylinder: ", calculate_area_of_shape("cylinder", radius=9, height=15))
d7d03a886938cbb9eef4cdcd0ee8f93af0fc33a0
daDaiMa/Algorithm
/leetcode精选TOP面试题/🌟TOP84.Largest Rectangle In Histogram/code.py
2,106
3.59375
4
# # 写的太臭了…… python的代码和c的一样长 # # class Solution: def largestRectangleArea(self, heights: List[int]) -> int: tree = SegmentTree.buildTree(0, len(heights)-1, heights) return self.getAns(tree, 0, len(heights)-1, heights) def getAns(self, root, start: int, end: int, heights: List[int]): if start > end: return 0 if start == end: return heights[start] min_index = root.query(start, end, heights) # print(min_index) if min_index == -1: print('error:index out of range') return return max(heights[min_index]*(end-start+1), self.getAns(root, start, min_index-1, heights), self.getAns(root, min_index+1, end, heights)) class SegmentTree: def __init__(self, start: int, end: int): self.left = None self.right = None self.start = start self.end = end self.min = 0 @staticmethod def buildTree(start: int, end: int, heights: List[int]): if start > end: return None root = SegmentTree(start, end) if end == start: root.min = start # 保存的最小值是下标而不是值 else: mid = (start+end)//2 root.left = SegmentTree.buildTree(start, mid, heights) root.right = SegmentTree.buildTree(mid+1, end, heights) root.min = root.left.min if heights[root.left.min] < heights[root.right.min] else root.right.min return root def query(self, start: int, end: int, heights: List[int]) -> int: if end < self.start or start > self.end: return -1 # 没找到返回-1 因为index不可能是负数 if end >= self.end and start <= self.start: return self.min left_min = self.left.query(start, end, heights) right_min = self.right.query(start, end, heights) if left_min < 0: return right_min if right_min < 0: return left_min return left_min if heights[left_min] < heights[right_min] else right_min
36740e07bb487517982c60f24063e09d599d002e
laxmanlax/Programming-Practice
/CodeEval/hard/string_searching.py
3,357
4.375
4
#!/usr/bin/env python # Challenge description: # You are given two strings. Determine if the second string is a substring of the # first (Do NOT use any substr type library function). The second string may # contain an asterisk(*) which should be treated as a regular expression i.e. # matches zero or more characters. The asterisk can be escaped by a \ char in # which case it should be interpreted as a regular '*' character. To summarize: # the strings can contain alphabets, numbers, * and \ characters. import sys import fileinput substring = True escaped_ast = True def is_substring(superstr, substr, super_index): global substring, escaped_ast curr = super_index sub_curr = 0 escaped_ast = False length = len(superstr) - curr for sub_index, char in enumerate(substr): # Didn't find it. if curr >= len(superstr): substring = False break if char == "\\": escaped_ast = True # Not followed by asterisk. if sub_index == len(substr)-1: substring = False break if substr[sub_index+1] != "*": substring = False break # Skip. curr -= 1 elif char == "*": if escaped_ast: if superstr[curr] != "*": substring = False escaped_ast = False break else: # Asterisk last char. if sub_index == len(substr)-1: substring = True break try: index = curr + 1 + superstr[curr+1:].index(substr[sub_index+1]) except ValueError: substring = False break except IndexError: substring = False break is_substring(superstr, substr[sub_index+1:], index) break else: if superstr[curr] != char: substring = False break curr += 1 sub_curr += 1 if sub_curr == len(substr)-1: substring = True for line in fileinput.input(): global substring, escaped_ast substring = True superstr = line.split(",")[0] substr = line[:-1].split(",")[1] curr_char = substr[0] if curr_char == "*": if len(substr) == 1: print("true") continue else: curr_char = substr[1] substr = substr[1:] elif curr_char == "\\": if len(substr) <= 1: print("false") continue else: curr_char = substr[1] substr = substr[1] escaped_ast = True try: index = superstr.index(curr_char) except ValueError: print("false") continue is_substring(superstr, substr, index) # Do it for each instance of curr_char in super. for i in range(superstr.count(curr_char)-1): if substring: break try: index = superstr.index(curr_char, index+1) is_substring(superstr, substr, index) except ValueError: substring = False break if substring: print("true") else: print("false")
3f533f155808199a0daee84dcbadcb7acf37b0ad
FedorovMisha/PUL_LAB_1
/pz1_task2.py
1,335
3.546875
4
# Рассчитать объём и полную поверхность по заданным параметрам (вводятся с клавиатуры): # 2. Параллелепипеда (по трем сторонам) # Получить обьём паралеппипеда по трем сторонам def get_parallelepiped_volume(sideA, sideB, sideC): return sideA * sideB * sideC # Получить площадь полной поверхности параллепипеда def get_full_parallelepiped_surface(sideA, sideB, sideC): return 2 * (sideA * sideB + sideA * sideC + sideB * sideC) parallelepipedSideA, parallelepipedSideB, parallelepipedSideC = float(input("Введите сторону A: ")), \ float(input("Введите сторону B: ")), \ float(input("Введите сторону C: ")) print(" Обьем параллепипеда = ", get_parallelepiped_volume(parallelepipedSideA, parallelepipedSideB, parallelepipedSideC)) print(" Площадь полной поверхности параллепипеда = ", get_full_parallelepiped_surface(parallelepipedSideA, parallelepipedSideB, parallelepipedSideC))
edf3cbd549f2d8e6026efa2c26a9619a37e0a347
sruj01/Coursera-Python-Data-Structures
/ass10.2.py
475
3.578125
4
fn=input('Enter file name: ') if len(fn)<1: fn='mbox-short.txt' fh=open(fn) else: fh=open(fn) di=dict() li=list() li1=list() for l in fh: if l.startswith('From '): pos=l.find(':') li.append(l[pos-2:pos]) for item in li: di[item]=di.get(item,0)+1 for k,v in di.items(): newtup=(k,v) li1.append(newtup) li1=sorted(li1) #put li1=sorted(li1,reverse=True) to get descending order for k,v in li1: print(k,v)
93ed6663b5f6fd877195a7d4cbb5efb7284e0921
JanaMojdlova/pyladies-7
/soubory/procvicovani/BONUS_4_pythagoras.py
546
3.578125
4
# -*- coding: UTF-8 -*- # Napis funkci, ktera ti pro dve zadane delky odvesen pravouhleho # trojuhelnika vypocita delku prepony. # (TIP budes potrebovat Pythagorovu vetu) # BONUS: Pridej funkce i pro vypocet strany, # pokud zname jednu odvesnu a preponu # Pythagorova věta: a**2 + b**2 = c**2 from math import sqrt def vypocti_delku_prepony(odvesna_a, odvesna_b): prepona = sqrt(odvesna_a**2 + odvesna_b**2) return prepona def vypocti_delku_strany(odvesna, prepona): strana = sqrt(prepona**2 - odvesna**2) return strana
d5cec1594863e09e28d92b3c1fc531e35c2c682d
mtndcl/HACETTEPE
/HACETTEPE/2019-2020/BBM103_Introduction to Programming I/Quiz-5/quiz5-1.py
621
3.765625
4
import sys def draw(began_point, end_point, mid_point): if end_point>began_point : if mid_point>began_point: if end_point==began_point: print(' '*(mid_point-began_point)+'*'*((began_point<<1)+1),end='') else: print(' '*(mid_point-began_point)+'*'*((began_point<<1)+1)) else: if end_point==began_point: print(' '*(began_point-mid_point)+'*'*((end_point-began_point<<1)-1),end='') else: print(' '*(began_point-mid_point)+'*'*((end_point-began_point<<1)-1)) draw(began_point + 1, end_point, mid_point) if __name__ == '__main__': size=(int(sys.argv[1])*2)-1 draw(0,size,size >> 1)
fb620b5cafd8a78f476340c9dd49a667cf6637d3
nkoomson/CSS225Homework
/Week_10/Adventure_Game_Section_1.py
2,862
4.1875
4
#Section_1.py #Nelson Koomson #3/17/2021 #First Section of my Adventure Game from main_character import player def start(): #This is what the player should have on his way. #player.money = 10 #wounded = False #weapon = ["pepper_spray", "knife"] #Introduction print("This is a journey to a friends party!") print("I have set out of my house, ready to start the journey!") #Player chooses to turn right, left, or walk straight. #print("Which direction do you want to go?") #choice = input("A: Right B: Left C: Far Right").upper() #This function asks the player the direction he wants to go. def Direction(): print("Where do you want to go?") choice = input("A: Right B: Left C: Far Right") return(choice) # Modified Direction() that removes option A def Direction2(): print("Where do you want to go?") choice = input("B: Left C: Far Right") return(choice) #Modified Direction() that removes option B def Direction3(): print("Where do you want to go?") choice = input("A:Right C: Far Right") return choice choice = Direction() #If the player chooses A he turns right. print(choice) while choice != "C": if choice == "A": print("Chef chooses to turn right") print("Chef encountered with wild animals.") print("Chef needs to turn to another direction") choice = Direction2() #Option A is removed # Runs if the player tries to pick A again. if choice == "A": choice = input("You cannot go Right again. Pick B or C.") #If the player chooses B he turns left. elif choice == "B": print("Chef turns left") print("Chef come across a lake") print("Chef needs to turn") choice = Direction3() #Option B is removed #If the player chooses any other letter, this will print invalid else: print("Invalid input") #If the player chooses C he turns left. if choice == "C": print("Chef chooses to turn far right") print("Chef have come in contact with armed robbers") print("Chef needs to use a weapon") print("Which weapon do you want to use? ", player.weapon) choice = input() print(choice) if choice == "knife": print("Player is defeated") exit() elif choice == "pepper_spray": print("player defeats the armed robbers and can continue the game") print("Is Chef wounded? ", player.wounded) choice = input() if choice == "Yes": player.wounded Wounded = True return
8b98e49fc36f8fe1bdca32d832e27ef3802b0dd1
bmoretz/Python-Playground
/src/DoingMathInPython/ch_06/growing_circle.py
634
3.921875
4
''' A Growing Circle ''' from matplotlib import pyplot as plt from matplotlib import animation def create_circle(): circle = plt.Circle( ( 0, 0 ), 0.05 ) return circle def update_radius( i, circle ): circle.radius = i * 0.5; return circle def create_animation(): fig = plt.gcf() ax = plt.axes( xlim = ( -10, 10 ), ylim = ( -10, 10 ) ) ax.set_aspect( 'equal' ) circle = create_circle() ax.add_patch( circle ) anim = animation.FuncAnimation( fig, update_radius, fargs = ( circle, ), frames = 30, interval = 50 ) plt.title( 'Simple Circle Animation' ) plt.show() if __name__ == '__main__': create_animation();
3419cd9515ad20ba28de8ccc28c7160457adc630
ava6969/CS101
/Student.py
323
3.671875
4
class Student: def __init__(self, name, age, height): self.name = name self.age = age self.height = height def study(self): print(self.name, 'is studying') class HighSchoolStudent(Student): def __init__(self, name, age, height): super().__init__(name, age, height)
afe68280d5aff3021ab0030e22d6713a99a09ac7
disciuser/homework_koshulko
/hw3_koshulko.py
4,229
3.96875
4
"""Homework 3""" """Для запуска програмы нужно указать правильное размещение текстового файла в функции print_all в строках 90 и 95""" #task 1 def counting_letters(string,list_leters = ['a','e','i','o','u']):#функция посчета определенных букв counted_leters = 0 for check in range(0,len(str(string))): if string[check] in list_leters: counted_leters += 1 return counted_leters def count_text(file_name,list_leters = ['a','e','i','o','u']):#функция посчета определенных букв в тексте и максимальное каличество этих букв в слове second_out_text = text_line = list_text = "" max_leters = 0 prev_max_leters = 1 with open(file_name) as file: for line in file: list_text = line.split() for string in range(0,len(list_text)): max_leters = counting_letters(list_text[string]) second_out_text += list_text[string] + "(" + str(max_leters) + ") " if max_leters > prev_max_leters: prev_max_leters = max_leters text_line = list_text[string] second_out_text += '\n' + 'Max leters in string: ' + str(text_line) + '= ' + str(prev_max_leters) + '.' return second_out_text #print("task 1:") #print(count_text("D:/py/text.txt")) #task 2 def the_long_word(first_string): for line in first_string: string = first_string.split() max_word = len(string[0]) new_list_equal = [] for line in range(0,len(string)): string[line] = string[line].replace(".","") if max_word < len(string[line]): max_word = len(string[line]) for line in range(0,len(string)): if max_word == len(string[line]): new_list_equal.append(string[line]) return max_word,new_list_equal #print("task 2:") #print(the_long_word("""Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non #nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada.""")) #task 3 import random def open_files(file_name):#фукция для открытия файла with open(file_name) as file: list_text = file.read() return str(list_text) def get_string(list_li):#функция для преобразования из списка в строку new_string = "" for text in list_li:#уровень предложений for string in text:#уровень строк for literal in string:#уровень букв new_string += str(literal) if string != []: new_string += " " new_string = new_string[0:-1]#удаление лишнего пробела в конце предложении что бы точка ишла сразу после буквы if text != []: new_string += ". " return new_string def revers_literals(list_literals):#функция для рандомного размещения букв в слове return random.sample(list(list_literals),len(list(list_literals))) def revers_string(string_list):#функция для рандомного размещения слов в одном предложении new_list = [] string = [] for line in string_list: string = string_list.split(' ') for line in range(0,len(string)): new_list.append(revers_literals(string[line])) return random.sample(new_list,len(new_list)) def revers_text(file_name):#функция для рандомного размещения предложений в тексте new_list = [] first_string = open_files(file_name) for line in first_string: string = first_string.split('. ') for line in range(0,len(string)): new_list.append(revers_string(string[line])) new_list = random.sample(new_list,len(new_list)) new_string = get_string(new_list) return new_string #print("task 3:") #print(revers_text("D:/py/text.txt")) def print_all(): print("task 1:") print(count_text("D:/py/text.txt")) print("task 2:") print(the_long_word("""Proin eget tortor risus. Cras ultricies ligula sed magna dictum porta. Proin eget tortor risus. Curabitur non nulla sit amet nisl tempus convallis quis ac lectus. Donec rutrum congue leo eget malesuada.""")) print("task 3:") print(revers_text("D:/py/text.txt")) print_all()
b3ad2471d168c8d6d1b4f47b6cad5ad7709c8412
nagask/Interview-Questions-in-Python
/Bitwise_Operations/Equality_NoComparisonOperators.py
259
3.84375
4
''' Created on Sep 20, 2015 @author: gaurav ''' def checkEquality(a,b): print(a,b) return not(a^b) if __name__ == '__main__': print(checkEquality(2,3)) print(checkEquality(2,2)) print(checkEquality(2,-1)) print(checkEquality(-1,-1))
3e5fd6f75d7729b1ffe1f4a52843a1e693f82769
TrCaM/Letter-Classifiers
/src/LogisticRegression.py
3,349
3.75
4
""" Assignment1.LogisticRegression ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Logistic Regression implementation """ import numpy as np import matplotlib.pyplot as plt def sigmoid(x): return 1 / (1 + np.exp(-x)) def least_squares(X, y): return np.linalg.inv(X.T @ X) @ X.T @ y def cost_function(w, X, y): # Computes the cost function for all the training samples m = X.shape[0] probability = sigmoid(X @ w) total_cost = -(1 / m) * np.sum(y * np.log(probability) + (1 - y) * np.log(1 - probability)) return total_cost class LogisticRegression: """ The implementation of logistic regression """ NAME = "Logistic Regression" def __init__( self, name="", learn_rate=0.01, tolerance=1e-2, max_iter=int(1e5), trans_func=None, ): self.weights = None self.name = name or self.NAME self.learn_rate = learn_rate self.tolerance = tolerance self.max_iter = max_iter self.feature_transform_func = trans_func def gradient_descent(self, X, y, learn_rate, tolerance, max_iter): """ Gradient descent implementation @param X: the training matrix of examples @param y: the label vector @param learn_rate: the learning rate of GD @param tolerance: stopping tolerance condition (epsilon) @param max_iter: maximum iterations @return w: The trained weight vector """ w = np.zeros(X.shape[1]) step_norm = 0.000001 self.cost = [cost_function(w, X, y)] for _ in range(max_iter): gradient = X.T @ (sigmoid(X @ w) - y) / y.size step = learn_rate * gradient w -= step cur_norm = np.linalg.norm(step, 2) step_norm = cur_norm self.cost.append(cost_function(w, X, y)) if step_norm < tolerance: break return w def fit(self, train_data, labels): train_data = self.add_x_0(train_data) self.weights = self.gradient_descent( train_data, labels, self.learn_rate, self.tolerance, self.max_iter ) # Uncomment to see the plot of cost function decrease by iterations # x = list(range(len(self.cost))) # y = self.cost # plt.plot(x, y) # plt.show() def add_x_0(self, X): """ Add the base feature x_0 with all having value of 1 """ X_new = np.ones((X.shape[0], X.shape[1] + 1)) X_new[:, 1:] = X return X_new def predict(self, x_test): """ Predict the test data """ x_test = self.add_x_0(x_test) y_predict = sigmoid(x_test @ self.weights) >= 0.5 return y_predict.astype(int) @staticmethod def Acu_eval(predicted_labels, true_labels): """ Evaluate accuracy """ return 1 - np.count_nonzero(predicted_labels ^ true_labels) / len(true_labels) def fit_and_predict(self, X_train, y_train, X_test, y_test): """ Aggregate function with the full train and test workflow """ if self.feature_transform_func: X_train, X_test = self.feature_transform_func(X_train, X_test) self.fit(X_train, y_train) y_predict = self.predict(X_test) return self.Acu_eval(y_predict, y_test)
1088d0ec4864e0d15fe53418add5a8e8a9c1c03b
ElinorThorne/QA_Work
/Encryption4.py
559
3.78125
4
def ASCII(a): f = open(a, "r") msg = f.read() numbers=[] for chr in msg: x = ord(chr) numbers.append(x) return numbers def Key(a): ch = ord(a[0:1]) return ch def Encrypt(a, b): multiplied = [] for i in a: x = i+b multiplied.append(x) print(multiplied) #get inputs fileName = input("Document name: ") password = input("Password: ") #turn file to ASCII Code tempFile = (ASCII(fileName)) #get 1st char of password key = Key(password) #multiply ASCII file with Key multip = Encrypt(a = tempFile, b = key)
d1e882041caa42473d59758a5e816f73a7924de5
CodyBankz/SisonkeRising
/sisonkelength.py
927
3.90625
4
""" Program By: Koketso Maphothoma.. """ myList1 = [1,5,8,11,12,15] myList2 = [1,100,25] def Sisonke_length(list): length = 0 for index in list: length = length + 1 return length #Returning the length listLength = Sisonke_length(myList1) print("List 1 length :") print(listLength) length2 = Sisonke_length(myList2) print("Second list : ") print(length2) print(" ") #getting the value at def get_value_at(index,list): value = list[index] return value myValue = 3 print("Your value is : ",get_value_at(myValue,myList1)) #getting the index of value def get_index_of_value(value,list): list_length = Sisonke_length(list) counter = 0 while(counter < list_length): for index in range(0,list_length): if(list[index] == value): return index counter =+ 1 return "Did not match" print("Your Index Is : ",get_index_of_value(15,myList1))
86f48fc479c372b0b5a989adc0a7ea53c6aa0a73
dhermes/project-euler
/python/complete/no095.py
1,856
3.65625
4
#!/usr/bin/env python # We use a sieve type method to calculate # the sum of all proper divisors up to n # by looping through all possible factors # and adding to the sum for each number # that the factor divides into from python.decorators import euler_timer def proper_divisor_sums(n): result = [0] * (n + 1) # loop over all possible divisors for divisor in xrange(1, n + 1): # loop over all numbers that # i divides properly (we want # the sum of proper divisors) for parent in xrange(2 * divisor, n + 1, divisor): result[parent] += divisor return result def amicable_cycle(n, cycle_hash, divisors, break_point): if n in cycle_hash: return cycle_hash[n][1] cycle = [n] next = divisors[n] while (next not in cycle_hash and next not in cycle and next <= break_point): cycle.append(next) next = divisors[next] if next > break_point: set_val = [None] elif next in cycle_hash: set_val = cycle_hash[next][1] elif next in cycle: start = cycle.index(next) set_val = cycle[start:] else: raise Exception("Cycle should've occurred, check algorithm") for val in cycle: cycle_hash[val] = (divisors[val], set_val[:]) return cycle_hash[n][1] def main(verbose=False): MAX_n = 10 ** 6 divisors = proper_divisor_sums(MAX_n) chains = {1: (0, [0]), 2: (1, [0]), 3: (1, [0])} best_length = 1 longest_chain = [0] for i in range(4, MAX_n + 1): chain = amicable_cycle(i, chains, divisors, MAX_n) if len(chain) > best_length: best_length = len(chain) longest_chain = chain[:] return min(longest_chain) if __name__ == '__main__': print euler_timer(95)(main)(verbose=True)
d1fb1700f0dbbe6639c2a4af9019c3abdaa7fcb6
jsourabh1/Striver-s_sheet_Solution
/Day-10_Backtracking/question6_word_break.py
552
3.859375
4
#User function Template for python3 def wordBreak(line, dictionary): # Complete this funct def solve(line,dictt,string2,start): if start==len(line): return True word="" for i in range(start,len(line)): word+=line[i] # print(word) if word in dictt : if solve(line,dictt,string2+" "+word,i+1): return True return solve(line,dictionary,"",0)
dc44121b7845aee45ad2da2e0866e485efbc4aab
Aasthaengg/IBMdataset
/Python_codes/p03307/s600961107.py
86
3.765625
4
N=int(input()) if N==1: print(2) elif N%2==0 and N>1: print(N) else: print(2*N)
42b7db75956cc2cceab687d8fe933a3a81caf5ae
anuteresa/Employee_Details
/employee_contact_details.py
2,001
3.53125
4
from tkinter import* import employee_backend window= Tk() def add(): employee_backend.insert(first_name.get(),last_name.get(),employee_id.get(),phone_no.get(),department_name.get()) list1.delete(0,END) list1.insert(END,(first_name.get(),last_name.get(),employee_id.get(),phone_no.get(),department_name.get())) def view_all(): list1.delete(0,END) for row in employee_backend.view(): list1.insert(END,row) # Label formation a1=Label(window,text="Contact List") a1.grid(row=0, column=0,columnspan=2) a2=Label(window,text= "New Contact") a2.grid(row=0,column=4) b1=Label(window,text="First Name:") b1.grid(row=1,column=3) b2=Label(window,text="Last Name:") b2.grid(row=2,column=3) b3=Label(window,text="Employee ID:") b3.grid(row=3,column=3) b4=Label(window,text="phone #") b4.grid(row=4,column=3) b5=Label(window,text="Department:") b5.grid(row=5,column=3) b6=Label(window,text="Last Name:") b6.grid(row=10,column=0) #Entry label formation first_name=StringVar() e1=Entry(window,textvariable=first_name) e1.grid(row=1,column=4) last_name=StringVar() e2=Entry(window,textvariable=last_name) e2.grid(row=2,column=4) employee_id=StringVar() e3=Entry(window,textvariable=employee_id) e3.grid(row=3,column=4) phone_no=StringVar() e4=Entry(window,textvariable=phone_no) e4.grid(row=4,column=4) department_name=StringVar() e5=Entry(window,textvariable=department_name) e5.grid(row=5,column=4) search_value=StringVar() e6=Entry(window,textvariable=search_value) e6.grid(row=10,column=1) # listbox formation list1=Listbox(window,height=6,width=20) list1.grid(row=1, column=0,rowspan=4,columnspan=2) #Button formation d1=Button(window,text="Add Contact",width=10,command=add) d1.grid(row=6,column=4) d2=Button(window,text="Search ",width=10,command=view_all) d2.grid(row=12,column=1) d3=Button(window,text="Display",width=10) d3.grid(row=4, column=0,rowspan=4,columnspan=2) window.mainloop()
10c04155cfe1694964306ecbf669ecc241fabcc3
l8g/graph
/Graph/Bfs/BipartitionDetection.py
1,466
3.53125
4
# -*- coding: utf-8 -*- import sys sys.path.insert(0, "../Expression") from Graph import Graph from collections import deque class BipartitionDetection(): def __init__(self, g): self._g = g self._visited = [False] * g.v() self._colors = [0] * g.v() self._isBipartite = True for v in range(g.v()): if not self._visited[v]: if not self._bfs(v, 0): self._isBipartite = False break def _bfs(self, v, color): self._visited[v] = True self._colors[v] = color queue = deque() queue.append(v) while len(queue) > 0: curr = queue.popleft() for w in self._g.adj(curr): if not self._visited[w]: self._visited[w] = True self._colors[w] = 1 - self._colors[curr] queue.append(w) elif self._colors[curr] == self._colors[w]: return False return True def isBipartite(self): return self._isBipartite if __name__ == "__main__": g = Graph('g.txt') bd = BipartitionDetection(g) print(bd.isBipartite()) g2 = Graph("g2.txt") bd2 = BipartitionDetection(g2) print(bd2.isBipartite()) g3 = Graph("g3.txt") bd3 = BipartitionDetection(g3) print(bd3.isBipartite())
6dbd90ba9625817e1e54203220b26e96766faf82
Chansazm/Project_31_Dynamic_Programming
/allconstruct.py
615
3.5625
4
def allconstruct(target,wordbank): if target == '': return [] result = [] for word in wordbank: if target[0] == word[0]: suffix = target[len(word):] suffixwaysways = allconstruct(suffix,wordbank) #targetways = suffixwaysways.map(way => [word,...way]) targetways = map(lambda x: x + x, word,suffixwaysways) result.append(targetways) #Driver function #m = targetsum #Time complexity:: Brute force n^m * m^2, memoised n * m #Space complexity:: height of the tree m, memoised m*m print(allconstruct("abcdef",["ab","abc","ce","def","abcd"]))
36148ff85fab3c3bf610ab9db0eb9e12832f14ca
junior333/lista-python
/ex11.py
189
3.953125
4
###Receba o raio de uma circunferência. Calcule e mostre o comprimento da # circunferência. raio=float(input('digite o raio de um circulo: ')) print(f'a circunferencia é {2*3.14*raio}')
a08f032eb8467531268d21d2884ee72bcbb8aaab
PiciAkk/factorial.py
/fact2.py
135
3.96875
4
def factorial(num): fact = 1 for i in range(1, num+1): fact = fact * i return fact print(factorial(int(input())))
89696db4ddb5bff68fe51ff6d767397b1292d877
maihan040/Python_Random_Scripts
/plusOne.py
1,413
4.1875
4
#!/usr/bin/python3 ''' plus_one.py Given a non-empty array where each element represents a digit of a non-negative integer, add one to the integer. The most significant digit is at the front of the array and each element in the array contains only one digit. Furthermore, the integer does not have leading zeros, except in the case of the number '0'. Example: Input: [2,3,4] Output: [2,3,5] created: 08/30/2020 version: 1.0 ''' ################################## Function Definitions ############################### def plus_one(numbers): #local variables n = len(numbers) carry = 0 #validate the input list if n == 0: return [1] #assuming an empty list is equivalent to [0] #add one to the last digit in the list numbers[n - 1] += 1 #check each digit from the last index to the first for i in range(n - 1, -1, -1): #add the current carry to the current sum numbers[i] += carry #check if overflow occured if numbers[i] < 10: carry = 0 break else: carry = number[i] // 10 numbers[i] %= 10 #check if overflow occured on the first element in the list if carry: numbers = [1] + numbers #return the completed list return numbers ################################## Main Function ######################################### number = [] print("Original number is : " + str(number)) number = plus_one(number) print("New number is : " + str(number))
a08212d4e139b83297451fd14c05063a977cda16
CHIAHSUNCHIANG/c_to_f
/c_to_f.py
100
3.75
4
temp = input("Please type in 'C: ") temp = float(temp) F_temp = temp*9/5+32 print(" 'F : ", F_temp)
553a6cbff21c2dce8b762b7808d1369bdbd4da3e
shivani1611/python
/ListCompare/main.py
505
3.84375
4
#!/usr/bin/env python3 import sys def main( ): # two lists to compare list1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] list2 = ['b', 'd', 'f'] # remove all the elements that are in list2 from list1 for a in range( len( list2 ) - 1, -1, -1 ): for b in range( len( list1 ) - ( 1 ), -1, -1 ): if( list1[b] == list2[a] ): del( list1[b] ) # display the results for a in range( 0, len( list1 ), 1 ): print( list1[a] ) if( __name__ == ( "__main__" ) ): sys.exit( main( ) )
b1881b8950b482e17c7cd17d453c5f6bca60ad10
BobbyHemming/maze-game
/CollisionFinder.py
2,233
3.640625
4
import pygame from Vector import Vector def collision_detection(player, walls): pos = player.pos vel = player.vel size = player.size collision_list = [] for wall in walls: wall_top = wall.rect.y wall_bottom = wall.rect.y + wall.rect.height wall_right = wall.rect.x + wall.rect.width wall_left = wall.rect.x if wall_top <= pos.y <= wall_bottom or wall_top <= pos.y + size <= wall_bottom: # or pos.y <= wall_bottom <= pos.y + size: if vel.x > 0 and pos.x+size/2 < wall_left: if pos.x + size >= wall_left: collision_list.append(wall) if vel.x < 0 and pos.x+size/2 > wall_right: if pos.x <= wall_right: collision_list.append(wall) if wall_left <= pos.x <= wall_right or wall_left <= pos.x + size <= wall_right: # or pos.x <= wall_left <= pos.x + size: if vel.y > 0 and pos.y+size/2 < wall_top: if pos.y + size >= wall_top: collision_list.append(wall) if vel.y < 0 and pos.y+size/2 > wall_bottom: if pos.y <= wall_bottom: collision_list.append(wall) # Edge pieces, special collisions: if pos.x <= wall_left <= pos.x + size: if vel.y > 0 and pos.y < wall_top: # Moving down and above wall if pos.y + size >= wall_top + 2: collision_list.append(wall) if vel.y < 0 and pos.y + size > wall_bottom: # Moving up and below wall if pos.y <= wall_bottom - 2: collision_list.append(wall) if pos.y <= wall_bottom <= pos.y + size: if vel.x > 0 and pos.x < wall_left: # Moving down and above wall if pos.x + size >= wall_left + 2: collision_list.append(wall) if vel.x < 0 and pos.x + size > wall_right: if pos.x <= wall_right - 2: collision_list.append(wall) collision = False if len(collision_list) != 0: collision = True print(f'Collision ...! x{len(collision_list)} at {pos.x, wall.rect.x}') return collision_list, collision
1009198ad21ce38799dea1f46463444fce6db103
hnaseem1/webmaps
/map1.py
1,245
3.578125
4
import folium import pandas #reading data from external txt file using pandas because it can make sense out of the structure data = pandas.read_csv("Volcanoes.txt") #storing the required columns in variables lat = list(data["LAT"]) lon = list(data["LON"]) elev = list(data["ELEV"]) #function to call later for volcano active level def color_producer(elevation): if elevation < 1000: return 'green' elif 1000 <= elevation < 3000: return 'orange' else: return 'red' #coordinates 30.58, -99.09 are starting potions map = folium.Map(location=[30.58, -99.09], zoom_start=6, tiles="Mapbox Bright") #this value is stored to make code cleaner fg = folium.FeatureGroup(name="My Map") # 3 iterations using 3 lists for lt, ln, el in zip(lat, lon, elev): fg.add_child(folium.CircleMarker(location=[lt, ln], radius = 6, popup=str(el)+" m", fill=True, fill_color= color_producer(el), color='grey', fill_opacity=0.7)) #loading json file to add a polygon layer fg.add_child(folium.GeoJson(data=(open('world.json', 'r', encoding='utf-8-sig').read()))) #adding points on to the map map.add_child(fg) #saving the html file for viewing map.save("map1.html")
a4db44c52f996b4711725bb1cf38bee562e0ee0f
waltlrutherfordgmailcom/CTI110
/P4HW3_SumNumbers_WalterRutherford.py
1,084
4.3125
4
# This program asks the user to enter a series of positive numbers for a sum. # 3/6/2019 # CTI-110 P4HW3 - Sum of Numbers # Walter Rutherford # Define function. # Define variables. # Display introduction. # Create while loop. # Get the Integer. # Display Total. # Beginning of function. def Sum_function (): # Defined variables for max, Total, Number, and variable for while loop (Start_over = 'y'). Total= 0 Number = 0 # Displayed introduction. print('\nThis program calculates the sum of all positive numbers.If a negative number is entered, the series will end, and the program will exit.') # Nested while loop. while Number > -1: # Equation for total. Total += Number # Input number type. Number = int (input('\nEnter a number:')) # printed total print('\nThe total is',Total) # End of function. Sum_function()
a912e4d36338d8cefbf3781a36b335478117f99a
ivanmopa/sumalista
/otrasumalista.py
516
4.09375
4
#!/usr/bin/env python #-*- coding: utf-8 -*- #Hacer una función que reciba una lista de números, sume solamente #los positivos y devuelva el resultado de la cuenta. li = [] def suma(li): resultado = 0 for numero in li: if numero > 0: resultado = resultado + numero else: resultado = resultado return resultado print suma([10, 10, 10, -10]) #Debería dar 30 print suma([-3, -4, -5, 6]) #Debería dar 6 print suma([4, -1, 8, -5, 9, -4]) #Debería dar 21 print suma([3, 4, -5, 4, 3]) #Debería dar 14
d0d448a2e27c332c9a8d22fc4722600956d712f4
RenukaSenthil/tutorials
/prime.py
181
3.5
4
n=int(input()) for i in range(n): if i>1: for j in range(2,i): if (i%j) == 0: break else: print(i,end=" ") else: print("0")
4382dbb546b398130032c398b3ed96904b36338c
Rude-Crow/python
/Regex expressions.py
1,472
3.71875
4
import re def PasswordChecker(): #defines function called PasswordChecker passwd = input("Enter a password to check: ") #Gets user input passwd_check = re.match(r'^[a-zA-Z0-9@#$%^&+=]{1,8}$', passwd) #creates an expression to check against if passwd_check: print('Valid') else: print('Invalid') def LicenseChecker(): #defines function called LicenseChecker license = input("Enter a license plate to check: ") #Gets user input validLicense = re.match(r'^[A-Z]{2}[0-9]{2}\s?[A-Z]{3}$', license) #creates an expression to check against if validLicense: print('Valid') else: print('Invalid') def WebAddressChecker(): #defines function called WebAddressChecker WebAddress = input("Enter a web address to check: ") #Gets user input WebAddressCheck = re.match(r'^(www.)?[a-zA-Z0-9]+.[a-zA-Z.]{1,5}$', WebAddress) #creates an expression to check against if WebAddressChecker: print('Valid') else: print('Invalid') def PrivIPCheck(): #defines function called PrivIPCheck IP = input("Enter a private IP address to check: ") #Gets user input IPCheck = re.match(r'(^127\.)|(^10\.)|(^172\.1[6-9]\.)|(^172\.2[0-9]\.)|(^172\.3[0-1]\.)|(^192\.168\.)', IP) #creates an expression to check against if IPCheck: print('Valid') else: print('Invalid') #PasswordChecker() #LicenseChecker() #WebAddressChecker() PrivIPCheck()
7f7a6be39e3cff47a39358aa13c96431398b82de
conrad1451/calendar-populator
/gtdHelperCode.py
17,306
4.03125
4
from datetime import datetime # ---------------------- MY STANDARD HELPER FUNCTIONS -------------------- # # returns true if 'theChar' is found in 'theStr' def foundInText(theStr, theChar): # returns true if 'theChar' is found in 'str' return theStr.find(theChar) != -1; # returns true if 'substr' is found in 'theStr' def foundInText(theStr, substr): # returns true if 'substr' is found in 'str' return theStr.find(substr) != -1; # note that all string methods return new values # source: https://www.w3schools.com/python/python_ref_string.asp # things that are standard in python library (but not C++) # "==" to compare two strings to determine if their characters are equal # casefold() to convert a string to lower case # lower() to convert a string to lower case # islower() to determine if all the characters in a stirng are lowercase # isnumeric() is a method to a string to determine if all the characters in a string are numeric # ----------------------------------------------------------------------- # class CalEvent(object): name = "" age = 0 major = "" theName = "" theDayOfWeek = "" theStartTime = 0 theEndTime = 0 theRepeat = False # The class "constructor" - It's actually an initializer def __init__(self, theName, theDayOfWeek, theStartTime, theEndTime, theRepeat): self.theName = theName self.theDayOfWeek = theDayOfWeek self.theStartTime = theStartTime self.theEndTime = theEndTime self.theRepeat = theRepeat def make_calEvent(theName, theDayOfWeek, theStartTime, theEndTime, theRepeat): calEvent = CalEvent(theName, theDayOfWeek, theStartTime, theEndTime, theRepeat) return calEvent def stringifyCalEvent(aCalEvent): line1 = "name: " + aCalEvent.theName + "\n" line2 = "day of week: " + aCalEvent.theDayOfWeek + "\n" line3 = "start time: " + str(aCalEvent.theStartTime) + "\n" line4 = "end time: " + str(aCalEvent.theEndTime) + "\n" line5 = "repeating event?: " + str(aCalEvent.theRepeat) + "\n" return line1 + line2 + line3 + line4 + line5 def findMin(val1, val2): if (val1 < val2): return val1 else: return val2 def findMax(val1, val2): if (val1 > val2): return val1 else: return val2 theDaysOfWeek = ["sun", "mon", "tue", "wed", "thu", "fri", "sat"] def elapsedTimeBetweenTwoDates(firstTime, secondTime): fTime = datetime.strptime(firstTime, '%m/%d/%Y') sTime = datetime.strptime(secondTime, '%m/%d/%Y') print("\n") print("the first time is: ", fTime) print("and the second time is: ", sTime) def splitIntoStringList(theStr, charSplitter): # takes in a string called "theStr" and character called "theChar" and returns a list of strings theList = [] startPos = 0 endPos = 0 while (foundInText(theStr, charSplitter) and endPos != -1): endPos = theStr.find(charSplitter, startPos) if (endPos != -1): theList.append(theStr[startPos : endPos+1]) startPos = endPos + 1 # end of while loop, last step is to return from function # TODO #print("shown following for testing purposes", theList[2], "\n\n") return theList; def grabDay(dateToSplit): firstTimeSplitPos = dateToSplit.find("2021") theDay = dateToSplit[0 : firstTimeSplitPos + 4] timeFormattedDate = datetime.strptime(theDay, '%m/%d/%Y') stringFormattedDate = timeFormattedDate.strftime('%a, %m/%d/%Y %H:%M:%S') # TODO - test done # print("Date in dd/mm/yyy format: ", stringFormattedDate) commaPos = stringFormattedDate.find(",") return stringFormattedDate[commaPos-3 : commaPos] def isEndOfDay(curTime, passedFirstHr, isAM): return (curTime == 1200) and (passedFirstHr) and (not isAM) def timeAdjust(time, AM, eod): theTime = 0 if(AM and time > 1200): theTime = time - 1200 elif( (not AM and time < 1200) or eod ): theTime = time + 1200 return theTime def switchToPM(curTime, prevTime): returnVal = False # if(not prevTime.isnumeric()), do nothing """if(prevTime.isnumeric()): cur12 = (1200 <= curTime and curTime <= 1259) cur11Under = (100 <= curTime and curTime <= 1159) prev12 = (1200 <= prevTime and prevTime <= 1259) prev11Under = (100 <= prevTime and prevTime <= 1159) opt1 = prev11Under and cur12 opt2 = False if(not(prev12 and cur11Under)): opt2 = prevTime > curTime returnVal = opt1 or opt2""" cur12 = (1200 <= curTime and curTime <= 1259) cur11Under = (100 <= curTime and curTime <= 1159) prev12 = (1200 <= prevTime and prevTime <= 1259) prev11Under = (100 <= prevTime and prevTime <= 1159) opt1 = prev11Under and cur12 opt2 = False if(not(prev12 and cur11Under)): opt2 = prevTime > curTime returnVal = opt1 or opt2 return returnVal def grabTime(dateToSplit, prevTime): passedFirstHr = False endOfDay = True timeSplitPos = dateToSplit.find("2021") stringifiedTime = dateToSplit[timeSplitPos + 5: -1] # no longer needed because input file is in miltary time # timeOfDayIdentifier = dateToSplit[timeSplitPos + 10: -1] # TODO - test done """print("dateToSplit is ", dateToSplit) print("stringifiedTime is ", stringifiedTime) print("\n")""" if(len(stringifiedTime) < 3): theHr = "0" else: theHr = stringifiedTime[0 : -3] theMin = stringifiedTime[-2 :] timeAsNum = int(theHr)*100 + int(theMin) #nowAtAM = timeOfDayIdentifier == "AM" if(timeAsNum <= 1159): passedFirstHr = True """ this following line determining isEndOfDay is part of why timeAdjust is failing and producing 3x the data (the extra data erronesouly) """ #if (isEndOfDay(timeAsNum, passedFirstHr, nowAtAM)): # endOfDay = True # print("why have we reached end of day?") #if (switchToPM(timeAsNum, prevTime)): # nowAtAM = False #correctedTime = timeAdjust(timeAsNum, nowAtAM, endOfDay) return timeAsNum #return correctedTime def modeNameAlteration(curEvent, curMode, theStart, theEnd): chosenName = "" if (curMode == 1): chosenName = curEvent.theName elif (curMode == 2): timesToAdd = " start: " + str(theStart) + " end: " + str(theEnd) chosenName = "\n" + "[" + curEvent.theName + timesToAdd + "]" return chosenName def fakeBreakPoint(): response = input("Press space to leave breakpoint: ") while (response != " "): response = input("I said presss space if you want to leave breakpoint") def splitIntoDayListEntries(theDayList, inputEvent, theDayIndex, theMode, theCounter): """ It seems that passing in theDayList is done by reference, because the edits I make to theDayList inside of this function are reflected outside of the function. Because of this, passing in theDayList as a parameter and then editing it works the same as editing a global variable (we avoid global variables as much as possible). Also notice how inputEvent is a parameter. if we did not want to edit theDayList in this function, we would have to have a helper function to return each 15 min interval, which are then pushed to theDayList from the function that called the helper function. This helper function would then, when a new event is reached, push the spaces to theDayList. It is much easier to implement as I have done. """ #curStartTime = 0 #curEndTime = 0 # TODO - is this following line even necessary? startVal = findMax(0, inputEvent.theStartTime) endVal = findMin(startVal + 15, inputEvent.theEndTime) #endVal = 0 # the following commented chunk of code results in a missingEvent fail """ hitShortEvent = False if(abs(inputEvent.theEndTime - inputEvent.theStartTime) < 15): #((inputEvent.theEndTime - startVal) < 15): # Following line never reached - all events happen to end at 15, 30, 45, or 00 of the hour curEndTime = inputEvent.theEndTime # TODO - testing hitShortEvent = True print("\n") print("starttime: ", inputEvent.theStartTime, "endtime: ", inputEvent.theEndTime) print("short event hit: ", inputEvent.theName, ": ", inputEvent.theStartTime, " - ", inputEvent.theEndTime) fakeBreakPoint() print("\n\n\n") else: curEndTime = startVal + 15 print("\n\nstarttime: ", inputEvent.theStartTime, "endtime: ", inputEvent.theEndTime) print("curEndTime is ", curEndTime, " and inputEvent.theEndTime is ", inputEvent.theEndTime) """ """ if(theCounter <= 13): print("first event catch?: ", inputEvent.theName) """ # endVal should never be greater than theEndTime, so a less than sign is used in while loop while (endVal < inputEvent.theEndTime): # endVal should be corrected to represent 60-minute hours before any incrementation or use if((endVal % 100) == 60): endVal = endVal + 40 result = modeNameAlteration(inputEvent, theMode, startVal, endVal) theDayList[theDayIndex].append(result) # may need to edit later to fit multiple events that overlap startVal = endVal # How close endVal is to the end time determines how much to increment endVal if((inputEvent.theEndTime - endVal) <= 15): # Following line never reached - all events happen to end at 15, 30, 45, or 00 of the hour endVal = inputEvent.theEndTime else: endVal = endVal + 15 """ if(theCounter <= 13): print("second event catch?: ", inputEvent.theName, "\n\n") """ result = modeNameAlteration(inputEvent, theMode, startVal, endVal) theDayList[theDayIndex].append(result) # provides spacing after the printout of each day to the log file theDayList[theDayIndex].append("\n\n\n") def automaticEventCreation(inputStr): # takes in a string called "inputStr" and returns a CalEvent # lets make following assumptions # every event is contained within a single day (as opposed to spanning days) stringList = splitIntoStringList(inputStr, ',') firstTimeSplitPos = 0 secondTimeSplitPos = 0 # FIXME dayOfWeek = "" stringifiedBeginTime = "" stringifiedEndTime = "" beginTime = 0 endTime = 0 dayOfWeek = "" name = stringList[0] name = name[:-1] # TODO - test complete # print("name is", name) firstDateToSplit = stringList[1] secondDateToSplit = stringList[2] # TODO - will this make a bug? prevTime = 0 # TODO - test done # print("shown following for testing purposes", inputStr, "\n\n") if(len(stringList) > 0): if (foundInText(firstDateToSplit, "2021")): beginTime = grabTime(firstDateToSplit, prevTime) prevTime = beginTime dayOfWeek = grabDay(firstDateToSplit) # TODO - test done # print("Day of week: ", dayOfWeek) # TODO - test done # print("begin time: ", beginTime) #else: # I’m not processing dates before Jan 1 2021. Too hard. if (foundInText(secondDateToSplit, "2021")): secondTimeSplitPos = secondDateToSplit.find("2021") endTime = grabTime(secondDateToSplit, prevTime) prevTime = endTime # TODO - test done # print("end time: ", endTime, "\n\n") #else # I’m not processing dates before Jan 1 2021. Too hard. testCalEvent = CalEvent(name, dayOfWeek.lower(), beginTime, endTime, False) return testCalEvent; def loadFileContent(inputFilename): # open input file to read content infile = open(inputFilename, 'r') fileContent = infile.readlines() listOfLines = [] for line in fileContent: if(line[-1] == '\n'): listOfLines.append(line[:-1]) else: listOfLines.append(line) infile.close() return listOfLines def handleLogOutput(aDayList, theMode): # TODO: this test shows that aDayList, for some reason, is not properly storing testEvent3 and # 4 right after testEvent1 and 2. The reason the printout is incorrect is because the data # stored in aDayList is incorrect, somehow. print(aDayList) myFilename = input("Give your log file a name (should end in \'.txt\'): ") while (not foundInText(myFilename, ".txt")): myFilename = input("text file must end in \'.txt\': ") outFile = open(myFilename, 'w') dayNum = 0 for eachDay in aDayList: outFile.write("Now printing day: " + theDaysOfWeek[dayNum] + "\n") tmpStr = "" for eachLog in eachDay: tmpStr = tmpStr + eachLog """ if (theMode == 2): print(eachLog) """ outFile.write(tmpStr) # TODO - test complete # outFile.write("\n\nNew day up\n\n") dayNum = dayNum + 1 outFile.close() def setMode(): inputNum = input("Select a mode in which to write log file (1 or 2): ") # Implementing "until loop" in python for this application checksPassed = False while(not checksPassed): if(inputNum.isnumeric()): theNum = int(inputNum) if(theNum == 1 or theNum == 2): checksPassed = True if(not checksPassed): inputNum = input("Input should be either \'1\' or \'2\': ") return int(inputNum) def loadDayList(theListOfEventBlocks, theMode): theDayList = [ [], [], [], [], [], [], [] ] # TODO - test done # counter = 0 dayIndex = -1 curDay = "sun" # An event block is a single event with a name, start and end time. # It may be an isolated event or part of a series of events for eventBlock in theListOfEventBlocks: if(foundInText(eventBlock, ',') and not foundInText(eventBlock.lower(), "summary")): anEvent = automaticEventCreation(eventBlock) # update day to ensure each day of week gets their respective events if(anEvent.theDayOfWeek != curDay): dayIndex = dayIndex + 1 curDay = anEvent.theDayOfWeek # split current event into theDayList entries to load into theDayList at respective dayIndex """ if(counter <= 13): print("all event catch: ", anEvent.theName) """ if (dayIndex < 7): splitIntoDayListEntries(theDayList, anEvent, dayIndex, theMode, counter) # TODO - test verifying that every event in original csv file is converted into an event """ print("Event #", str(counter), ": \n", stringifyCalEvent(anEvent), "\n\n")""" counter = counter + 1 # FIXME: may not be necessary - I might remove # autoAddedCalEvents.append(anEvent) return theDayList def modifiedDayList(aDayList): return 0 def autoConverter(): # will return autoAddedCalEvents mode = setMode() autoAddedCalEvents = [] fin = input("Enter name of the input text file (should end in \'.csv\'): ") while (not foundInText(fin, ".csv")): fin = input("text file must end in \'.csv\': ") print("\n") fin = "inputFiles/" + fin listOfEventBlocks = loadFileContent(fin) dayList = loadDayList(listOfEventBlocks, mode) #TODO - testing now #newDayList = modifiedDayList(dayList) handleLogOutput(dayList, mode) return autoAddedCalEvents def main(): allCalEvents = [] anInput = input("Select 1 for the manual event scanning or 2 for the automatic event scanning): ") while(anInput != "1" and anInput != "2"): anInput = input("Select a valid input! (1 for the manual event scanning or 2 for the automatic event scanning): ") if(anInput == "1"): theCondition = True while (theCondition): # FIXME: Add manualEventCreation as a function #allCalEvents.append(manualEventCreation()) myStr = input("\nwant to add new event (Y|N): ") print("\n\n") theCondition = (len(myStr) == 1) and ( (myStr.lower())[0] == 'y' ) elif (anInput == "2"): listOfEvents = autoConverter() main()
04659bf85c6f9c2c36b96499c0ce3cbc62752fe7
ArnoutSchepens/Python_3
/Oefeningen/standalone/dictionary_4.py
1,032
4.3125
4
# Every character has an ASCII code (basically, a number that represents it). # Python has a function called chr() that will return a string if you provide the corresponding integer ASCII code. # For example: # chr(65) will return 'A' # chr(66) will return 'B' # All the way up to: # chr(90) will return 'Z' # Your task is to create dictionary that maps ASCII keys to their corresponding letters. Use a dictionary comprehension and chr(). # Save the result to the answer variable. You only need to care about capital letters(65-90). # The end result will look like this: # { # 65: 'A', # 66: 'B', # 67: 'C', # 68: 'D', # 69: 'E', # 70: 'F', # 71: 'G', # 72: 'H', # 73: 'I', # 74: 'J', # 75: 'K', # 76: 'L', # 77: 'M', # 78: 'N', # 79: 'O', # 80: 'P', # 81: 'Q', # 82: 'R', # 83: 'S', # 84: 'T', # 85: 'U', # 86: 'V', # 87: 'W', # 88: 'X', # 89: 'Y', # 90: 'Z' # } answer = {value: chr(value) for value in range(65, 91)}
3b1bcce9eb77a9a2729258805beda987dbe941e4
jeysusmeister/calculadora
/main.py
2,861
3.5625
4
from modulos.Aritmetica import Aritmetica sigue = "y" while sigue=="y": try: operacion = int(input("\nIngrese la operación que desea realizar:\n\t1.-Suma.\n\t2.-Resta.\n\t3.-Producto.\n\t4.-División.\n\t5.-Salir.\n\t\t")) switcher = { 1:"Suma", 2:"Resta", 3:"Producto", 4:"División", 5:"Salir" } seleccion = switcher.get(operacion,"Valor invalido") if seleccion==5: print("\nUd. prefirio salir de la operación", seleccion) else: print("\nUd. selecciono operación", seleccion) aritmetica = Aritmetica() if seleccion=="Suma": valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") while valor_1.isalpha() or valor_2.isalpha(): valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") aritmetica.setSuma(valor_1, valor_2) print("\n\tEl resultado de la suma es: ", aritmetica.getSuma()) elif seleccion=="Resta": valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") while valor_1.isalpha() or valor_2.isalpha(): valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") aritmetica.setResta(valor_1, valor_2) print("\n\tEl resultado de la Resta es: ", aritmetica.getResta()) elif seleccion=="División": valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") while valor_1.isalpha() or valor_2.isalpha(): valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") aritmetica.setDivi(valor_1, valor_2) print("\n\tEl resultado de la División es: ", aritmetica.getDivi()) elif seleccion=="Producto": valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") while valor_1.isalpha() or valor_2.isalpha(): valor_1 = input("\n\tIngresa el primer valor: ") valor_2 = input("\n\tIngresa el segundo valor: ") aritmetica.setMulti(valor_1, valor_2) print("\n\tEl resultado de la Multiplicar es: ", aritmetica.getMulti()) else: print("Adios") break except ValueError as identifier: print("\n\tDebe ingresar valores númericos.") sigue = input("\n\tDesea realizar otra operación presione \"y\" para continuar o \"n\" para salir\n")
94056f4970ae5ee028d5746b5a833f14bf54faf0
theturbokhemist/Optimization-Algorithms-for-Traveling-Salesman-Problem
/opt_TSP.py
29,290
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Project Team #2 Authors: Daniel Gordin & Kyle Mikami """ #Import packages import numpy as np import pandas as pd import matplotlib.pyplot as plt import math import random as rnd import statistics import itertools from scipy.spatial import ConvexHull class CityData: """ CityData class generates, cointains, and visualizes the coordinates data for the "cities" in the Traveling Salesman Problem. Cities are all contained on a unit circle centered at the origin. """ def __init__(self, num_cities = 10): """ Initializes numpy 2D-array of city coordinates Param num_cities: Number of cities in the array """ #Generate the matrix of coordinates self.num_cities = num_cities x = np.random.rand(num_cities) #formula for unit circle center at (0,0) y = np.sqrt(1 - x*x) x = x*(2*np.random.randint(0,2,size=(num_cities))-1) y = y*(2*np.random.randint(0,2,size=(num_cities))-1) cities_mat = np.vstack((x,y)).T self.cities_mat = cities_mat self.optimal_solution = self.calc_optimal_solution() self.optimal_solution_dist = self.total_dist(self.optimal_solution) self.cities_df = pd.DataFrame(cities_mat, columns= ['X', "Y"]) def plot_cities(self, path): """ Plots and connects the city coordinates for a given permutation Param path: A permutation of the city IDs """ #rearranges cities mat so that it is in the order of the given permutation mat = self.cities_mat[path, :] #appends the coordinates of the first city to the end so route is complete mat = np.vstack((mat, mat[0,])) df = pd.DataFrame(mat, columns= ['X', "Y"]) plt.scatter('X', 'Y', data = df, color = "red") plt.plot('X', 'Y', data = df) plt.title('City Coordinates') plt.xlabel('X') plt.ylabel('Y') def calc_distance(self, city1, city2): """ Calculates the distance between 2 cities Param city1: Coordinates of 1 city Param city2: Coordinates of another city Returns a numeric value which represents the distance between two cities. """ #distance formula x = self.cities_mat[city2, ][0] - self.cities_mat[city1, ][0] y = self.cities_mat[city2, ][1] - self.cities_mat[city1, ][1] d = math.sqrt(x*x + y*y) return d def total_dist(self, path): """ Calculates the distance it takes to travel to each city. The order is determined by the given permutation. Param path: A permutation of the city IDs Returns a numeric value which represents the distance it takes to travel to each city. """ perm_array = np.append(path, path[0]) current_sum = 0 for i in range(len(perm_array) - 1): current_sum = current_sum + self.calc_distance(city1 = perm_array[i], city2 = perm_array[i + 1]) return current_sum def calc_optimal_solution(self): """ Calculates the "optinal solution" which is the permutation of cities which yields the lowest total distance. Returns a list of city IDs """ #Convex Hull algorithm hull = ConvexHull(self.cities_mat) return hull.vertices #GA Class class GA: """ GA class contains the methods and attributes that employ a genetic algorithm to optimize the Traveling Salesman Problem """ def __init__(self, num_generations = 10, pop_size = 20, num_cities = 10, elitism_frac = 0.25, selection_method = "Roulette", mating_method = "Random", mutation_rate = 1): """ Creates an instance of a CityData object well as all combinations of ranges for a list of length num_cities Param num_cities: Number of cities to optimize for TSP Param num_generations: Number of generations to create Param pop_size: Number of individuals in a generation Param elitism_frac: The percent of individuals with the best fitness scores that will be included in the mating pool and subsequent generation Param selection_method: The way the individuals are selected for each mating pool. If "Roulette", the individuals are selected randomly with a probability determined by their fitness scores. If "Fittest Half", the top half of fittest individuals are chosen. Param mating_method: The way the individuals are selected to mate. If "Random", individuals are chosen to mate at random. If "Fittest Paired", the fittest individuals are paired up to mate. Param mutation_rate: The amount of random times two cities swap places for all children produced from a mating """ self.num_generations = num_generations self.pop_size = pop_size self.elitism_frac = elitism_frac self.selection_method = selection_method self.mating_method = mating_method self.CityData = CityData(num_cities = num_cities) self.range_combos = list(itertools.combinations(range(0,self.CityData.num_cities), 2)) + [(self.CityData.num_cities - 1, self.CityData.num_cities)] self.mutation_rate = mutation_rate self.mean_distances = [] self.min_score = [] def run_GA(self): """ Runs the Genetic Algorithm """ initial_pop = self.initialize_population() self.current_generation = initial_pop for i in range(0, self.num_generations): self.next_generation(current_generation = self.current_generation) self.ranked_final_population = self.rank_population(population = self.current_generation) self.best_path = self.ranked_final_population.Path[0] self.error = round(self.CityData.total_dist(path = self.best_path), 5) - round(self.CityData.optimal_solution_dist,5) def initialize_population(self): """ Creates the 1st generation of individuals. Each individual is randomly generated. """ population = [] for i in range(self.pop_size): population.append(np.array(rnd.sample(range(self.CityData.num_cities), self.CityData.num_cities))) return population def rank_population(self, population): """ Ranks each individual of a population based on their fitness score (the total distance of their permutation) Param population: A list of each individual in the population/generation. Each individual is a permutation list. Returns a sorted pandas dataframe that includes the individual IDs, their fitness scores, their inverse scores, the fraction each individuals inverse score is of the sum of all the fitness scores (probability), and their permutations. """ fitness_scores = [] for i in range(self.pop_size): fitness_scores.append(self.CityData.total_dist(population[i])) self.mean_distances.append(statistics.mean(fitness_scores)) df = pd.DataFrame({'Ind':np.argsort(fitness_scores), 'Score':[fitness_scores[i] for i in np.argsort(fitness_scores)]}) df['Inv_Score'] = 1/df['Score'] df['Percent'] = df.Inv_Score/df.Inv_Score.sum() pop_ordered = [] for i in range(0, len(df)): pop_ordered.append(population[df.Ind[i]]) df['Path'] = pop_ordered self.min_score.append(df.Score[0]) return df def mating_pool(self, ranked_population): """ Determines which individuals will be available for mating to create the next generation Param ranked_population: A sorted pandas dataframe that includes the ID's and probabilities of being selected for each individual in a population/generation. Returns a list of individual IDs """ mating_pool = [] num_elites = math.ceil(self.elitism_frac*len(ranked_population)) for i in range(0, num_elites): mating_pool.append(ranked_population.Ind[i]) if self.selection_method == "Roulette": mating_pool = mating_pool + rnd.choices(population = ranked_population.Ind, weights = ranked_population.Percent, k = (len(ranked_population) - num_elites)) elif self.selection_method == "Fittest Half": for i in range(0, math.ceil(len(ranked_population)/2)): mating_pool.append(ranked_population.Ind[i]) return mating_pool def mate(self, parent1, parent2): """ Performs ordered crossover on the permutations of two "parent" individuals to create two "children" permutations Param parent1: A permutation of city IDs Param parent2: A permutation of city IDs Returns a list of two permutation arrays """ #ordered crossover start, end = self.range_combos[rnd.randrange(0, len(self.range_combos))] c1 = [None]*self.CityData.num_cities c2 = [None]*self.CityData.num_cities temp1 = [] temp2 = [] for i in range(start, end): c1[i] = parent1[i] temp1.append(parent1[i]) c2[i] = parent2[i] temp2.append(parent2[i]) counter1 = 0 counter2 = 0 for i in range(0, len(c1)): if c1[i] == None: for j in range(i + counter1, len(parent2)): if parent2[j] in temp1: counter1 += 1 else: c1[i] = parent2[j] break for j in range(i + counter2, len(parent1)): if parent1[j] in temp2: counter2 += 1 else: c2[i] = parent1[j] break else: counter1 = counter1 - 1 counter2 = counter2 - 1 return self.mutate(c1) + self.mutate(c2) def mutate(self, individual): """ Swaps the positions of two cities in a list of city IDs Param individual: A permutation of city IDs Returns a permutation of city IDs """ if self.mutation_rate > 0: for i in range(0, self.mutation_rate): start, end = self.range_combos[rnd.randrange(0, len(self.range_combos)-1)] individual[start], individual[end] = individual[end], individual[start] return [np.array(individual)] else: return [np.array(individual)] def next_generation(self, current_generation): """ Pairs up individuals from the current generation to create the next generation of individuals Param current_generation: A list of each individual in the generation. Each individual is a permutation array. Returns a list of individuals where each individual is a permutation array. """ ranked_pop = self.rank_population(current_generation) new_generation = [] num_elites = math.ceil(self.elitism_frac*len(ranked_pop)) for i in range(0, num_elites): new_generation.append(current_generation[ranked_pop.Ind[i]]) mating_pool = self.mating_pool(ranked_pop) if self.mating_method == "Random": pool = [] for i in range(0, len(mating_pool)): pool.append(current_generation[mating_pool[i]]) while len(new_generation) < self.pop_size: p1 = np.random.choice(range(0,len(pool)), 1, replace=False)[0] p2 = np.random.choice(range(0,len(pool)), 1, replace=False)[0] new_generation = new_generation + self.mate(parent1 = pool[p1], parent2 = pool[p2]) elif self.mating_method == "Fittest Paired": mating_pool = list(set(mating_pool)) order = list(ranked_pop.Ind) mating_pool = 2*sorted(mating_pool, key=lambda mating_pool: order.index(mating_pool)) pool = [] for i in range(0, len(mating_pool)): pool.append(current_generation[mating_pool[i]]) k = 0 while len(new_generation) < self.pop_size: p1 = k p2 = k + 1 new_generation = new_generation + self.mate(parent1 = pool[p1], parent2 = pool[p2]) k = k + 2 self.current_generation = new_generation return new_generation[0:self.pop_size] def plot_results(self): """ Creates two subplots of the results of the genetic algorithm. One subplot shows the mean total distance per generation. Another shows the total_distance of the fittest individual per generation. """ x = list(range(1, self.num_generations + 2)) fig, (ax1, ax2) = plt.subplots(1, 2, sharey = 'row') fig.suptitle('Optimization Results') ax1.plot(x, self.mean_distances) ax1.set_title("Mean Path Length") ax1.set(xlabel = "Generation", ylabel = "Path Length") ax1.axhline(y= self.CityData.optimal_solution_dist, color='r', linestyle='-') ax2.plot(x, self.min_score) ax2.set_title("Minimum Path Length") ax2.set(xlabel = "Generation") fig.subplots_adjust(hspace=0.05) ax2.axhline(y= self.CityData.optimal_solution_dist, color='r', linestyle='-') def plot_error(self, num_simulations, print_progress = True): """ Simulates the optimization algorithm multiple times and plots the error per simulation as well as the average error. """ self.num_simulations = num_simulations error_list = [] for i in range(num_simulations): self.run_GA() error_list.append(self.error) if print_progress: print(i) avg = sum(error_list)/len(error_list) self.mean_error = avg mat = np.vstack((list(range(1, num_simulations + 1)),error_list)).T df = pd.DataFrame(mat, columns= ['X', "Y"]) plt.scatter('X', 'Y', data = df, color = "green") plt.plot('X', 'Y', data = df) plt.title('Error per Simulation') plt.xlabel('Iteration') plt.ylabel('Error') plt.axhline(y = avg, color='r', linestyle='-') def plot_best_path(self): """ Plots the path of the best solution found """ self.CityData.plot_cities(self.best_path) #PSO# #Particle Class class Particle: """Initializes particle (permutation)""" def __init__(self, permutation): """ Initializes particle (permutation) Param permutation: Possible route of cities """ self.current = permutation # current particle permutation self.pbest= permutation # best individual particle permutation class PSO: def __init__(self, num_iterations = 100, num_cities = 10, num_particles = 100, current_weight = 0.3, pbest_weight = 0.5, gbest_weight = 0.9): """ Creates the swarm Params: Num_iterations, how many times you want to run algorithm Num_cities, number of cities in TSP Num_particles, number of permutations of routes Current_weight, how much to weigh current permutation Pbest_weight, how much to weigh particle's best permutation Gbest_weight, how much to weigh the global best permutation """ self.num_cities = num_cities self.num_particles = num_particles self.num_iterations = num_iterations self.CityData = CityData(num_cities = num_cities) self.current_weight = current_weight self.pbest_weight = pbest_weight self.gbest_weight = gbest_weight self.current_mean = [] self.gbest_list = [] def initialize_swarm(self): """Initializes the swarm""" swarm = [] dist = [] #Iterates through each permutation and appends each permutation and total distance to swarm and dist lists for i in range(self.num_particles): swarm.append(Particle(permutation = np.array(rnd.sample(range(self.CityData.num_cities), self.CityData.num_cities)))) temp_dist = self.CityData.total_dist(path = swarm[i].current) dist.append(temp_dist) swarm[i].current_dist = temp_dist swarm[i].pbest_dist = temp_dist self.swarm = swarm # self.dist = dist #Sets gbest_distance and gbest permutation self.gbest_dist = dist[np.argmin(dist)] self.gbest = swarm[np.argmin(dist)].current #Appends mean distance to current and gbest lists self.current_mean.append(statistics.mean(dist)) self.gbest_list.append(self.gbest_dist) def crossover(self, particle): """ Crossover algithm Param particle: permutation """ new_perm = [] #Sets weights for the current permutation, pbest, and gbest w_current = self.current_weight w_pbest = self.pbest_weight w_gbest = self.gbest_weight #Sets length and start and end of current permutation you want to select l_current = math.ceil((w_current*self.num_cities)) l_current = l_current - int(rnd.random()*(l_current-1)) start = rnd.sample(range(self.num_cities - l_current), 1)[0] end = start + l_current part_current = particle.current[start:end] new_perm = new_perm + list(part_current) #Repeats process for pbest l_pbest = math.ceil((w_pbest*self.num_cities)) l_pbest = l_pbest - int(rnd.random()*(l_pbest-1)) start = rnd.sample(range(self.num_cities - l_pbest), 1)[0] end = start + l_pbest part_pbest = particle.pbest[start:end] #Checks if cities selected from pbest overlap with what was already selected from current for i in range(len(part_pbest)): if part_pbest[i] in new_perm: continue else: new_perm.append(part_pbest[i]) #Repeats process for gbest l_gbest = math.ceil((w_gbest*self.num_cities)) l_gbest = l_gbest - int(rnd.random()*(l_gbest-1)) start = rnd.sample(range(self.num_cities - l_gbest), 1)[0] end = start + l_gbest part_gbest = self.gbest[start:end] #Checks if cities selected from gbest overlap with what was already selected from current and pbest for i in range(len(part_gbest)): if part_gbest[i] in new_perm: continue else: new_perm.append(part_gbest[i]) #Finally, adds any missing cities if len(new_perm) == self.num_cities: pass else: for i in range(self.num_cities): if i in new_perm: continue else: new_perm.append(i) particle.current = np.array(new_perm) particle.current_dist = self.CityData.total_dist(particle.current) if particle.current_dist < particle.pbest_dist: particle.pbest_dist = particle.current_dist particle.pbest = particle.current def update_swarm(self): """Updates the swarm by comparing permutations to global best""" dist = [] #Iterate through particles in swarm and evaluate fitness for i in range(self.num_particles): self.crossover(self.swarm[i]) dist.append(self.swarm[i].current_dist) #Checks if current particle is the best globally if self.swarm[i].current_dist < self.gbest_dist: self.gbest = self.swarm[i].current #updates gbest self.gbest_dist = self.swarm[i].current_dist #updates gbest_dist self.current_mean.append(statistics.mean(dist)) self.gbest_list.append(self.gbest_dist) def run_PSO(self): """Runs the algorithm""" #Initializes the swarm self.initialize_swarm() #Updates swarm for each iteration for i in range(self.num_iterations): self.update_swarm() #Calculates error self.error = self.gbest_dist - self.CityData.optimal_solution_dist def plot_results(self): """Plots mean path length and global best length in relation to optimal distance""" x = list(range(1, self.num_iterations + 2)) fig, (ax1, ax2) = plt.subplots(1, 2, sharey = 'row') fig.suptitle('Optimization Results') ax1.plot(x, self.current_mean) ax1.set_title("Mean Path Length") ax1.set(xlabel = "Iteration", ylabel = "Path Length") ax1.axhline(y= self.CityData.optimal_solution_dist, color='r', linestyle='-') ax2.plot(x, self.gbest_list) ax2.set_title("Global Best Path Length") ax2.set(xlabel = "Iteration", ylabel = "Path Length") fig.subplots_adjust(hspace=0.05) ax2.axhline(y= self.CityData.optimal_solution_dist, color='r', linestyle='-') def plot_error(self, num_simulations, print_progress = True): self.num_simulations = num_simulations error_list = [] for i in range(num_simulations): self.run_PSO() error_list.append(self.error) if print_progress: print(i) avg = sum(error_list)/len(error_list) self.mean_error = avg mat = np.vstack((list(range(1, num_simulations + 1)),error_list)).T df = pd.DataFrame(mat, columns= ['X', "Y"]) plt.scatter('X', 'Y', data = df, color = "green") plt.plot('X', 'Y', data = df) plt.title('Error per Simulation') plt.xlabel('Iteration') plt.ylabel('Error') plt.axhline(y = avg, color='r', linestyle='-') def plot_best_path(self): self.CityData.plot_cities(self.gbest) """ #Nelder-Mead Algorithm #Did not use class Location: #Location class initalizes an x,y coordinate grid and allows for mathematical operations on the locations #May not need this depending on data setup def __init__(self, x, y): # Initializes an x,y coordinate like loc = Location(1,1) self.x = x self.y = y def __add__(self, new): #Addition method x = self.x + new.x y = self.y + new.y return Location(x, y) def __sub__(self, new): #Subtraction method x = self.x - new.x y = self.y - new.y return Location(x, y) def __rmul__(self, new): #Multiplication method x = self.x * new y = self.y * new return Location(x, y) def __truediv__(self, new): #Division method x = self.x / new y = self.y / new return Location(x, y) def getcoordinates(self): #Returns coordinates in x,y return (self.x, self.y) def __str__(self): #Returns a printable string representation of coordinates return str((self.x, self.y)) """ """ Nelder-Mead uses reflection, expansion, and contraction methods 1.) Reflection: xr = centroid + alpha(centroid - worst) 2.) Expansion: xe = centroid + gamma(xr - centroid) 3.) Contraction: xc = centroid + rho(worst - centroid) 4.) Did not use shrink as it is not necessary with contraction """ """ # Function you want to find optimal solution for (circle) def func (coordinates): x, y = coordinates return (x-5)**2 + (y-5)**2 #circle with center at (5,5) def nelder_mead (alpha=1, gamma=2, rho=0.5, num_iter=100): """ """ Params: alpha is the reflection paramater/coefficient, usually 1 gamma is the expansion paramater/coefficient, usually 2 rho is the contraction paramater/coefficient, usually equal to 0.5 num_iter is the number of iterations you want to run through the algorithm, default is 100 """ """ # Initialize the simplex using 3 random points v1 = Location(0, 0) v2 = Location(10, 0) v3 = Location(-15, 10) for i in range(num_iter): #runs through loop for number of iterations #Puts results into dictionary with each location and values from the test function results = {v1: func(v1.getcoordinates()), v2: func(v2.getcoordinates()), v3: func(v3.getcoordinates())} #Sorts results based on the lowest function value sorted_results = sorted(results.items(), key = lambda coordinates: coordinates[1]) #Creates best, second best, and worst points best = sorted_results[0][0] #best point = coordinates of first value second_best = sorted_results[1][0] #second best point = coordinates of second value worst = sorted_results[2][0] #worst point = coordinates of third value centroid = (second_best + best)/2 #centroid is geometric center of points besides worst #1. Reflection #checks if value of xr is better than the second best value but not better than the best xr = centroid + alpha * (centroid - worst) #formula for reflected point if func(xr.getcoordinates()) < func(second_best.getcoordinates()) and func(best.getcoordinates()) <= func(xr.getcoordinates()): worst = xr #replace the worst point with the reflected point #2. Expansion if func(xr.getcoordinates()) < func(best.getcoordinates()): #if reflected point is best so far xe = centroid + gamma * (xr - centroid) #formula for expanded point if func(xe.getcoordinates()) < func(xr.getcoordinates()): #if expanded point is better than the reflected point worst = xe #replace worst point with expanded point else: worst = xr #else replace worst point with reflected point #3. Contraction if func(xr.getcoordinates()) > func(second_best.getcoordinates()): #checks if reflected point is better than second best point xc = centroid + rho * (worst - centroid) #formula for contracted point if func(xc.getcoordinates()) < func(worst.getcoordinates()): #if contracted point is better than the worst point worst = xc #replace worst point with contracted point #Update points based on loop v1 = best v2 = second_best v3 = worst #print("v1: ", v1, " v2: ", v2, " v3: ", v3) return v1 #returns best point x = nelder_mead() print(x) x.getcoordinates() """
8d232e675310da91e5385a1b94f8f45db12660f6
Kdoger/LeetCode
/leetcode_1.py
910
3.703125
4
''' 问题描述: 给定一个整数数组 nums和一个整数目标值 target,请你在该数组中找出 和为目标值 target 的那两个整数,并返回它们的数组下标。 你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。 你可以按任意顺序返回答案 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/two-sum 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 ''' class Solution: def twoSum(self, nums, target): for i in range(len(nums)): for j in range(i+1, len(nums)): if nums[i] + nums[j] == target: return [i,j] nums = [2,7,11,15] # [2,7,11,15] [3,2,4] [3,3] [2,7,11,15] target = 9 # 9 6 6 9 solution = Solution() print(solution.twoSum(nums, target))
49556b7afe7501383f6f848c66a3bbf8e4cda0d1
skiry/University
/Fundamentals of Programming/Assignment01/B.06.py
1,103
3.953125
4
year=int(input("I am gonna compute your age in number of days. Your year : ")) month=int(input("And your month : ")) day=int(input("Day : ")) age=0 import datetime actual=datetime.datetime.now() months=[] def assigndays(): months.append(31) months.append(28) months.append(31) months.append(30) months.append(31) months.append(30) months.append(31) months.append(31) months.append(30) months.append(31) months.append(30) months.append(31) def testleap(x): if x%4==0 and x%100!=0: return True elif x%400==0: return True return False def computeage(): assigndays() if testleap(year)==True: months[1]=29 age=months[month-1]-day for i in range(month+1,12): age+=months[i] for i in range(year+1,2017): if testleap(i)==True: age+=366 else: age+=365 for i in range(0,actual.month): age+=months[i] age+=actual.day return age old=computeage() print("You are " , old , " days old!")
f345c78a8dc07f78c6b215a5275b7b6904e02529
Karngupt/pdsnd_github
/Bikeshare_Project_v2.py
8,050
3.859375
4
#!/usr/bin/env python # coding: utf-8 # In[ ]: import datetime as dt import pandas as pd import numpy as np import calendar # In[ ]: #Reading in raw data to enable user to view it chicago_orig=pd.read_csv("chicago.csv") newyork_orig=pd.read_csv("new_york_city.csv") washington_orig=pd.read_csv("washington.csv") # In[ ]: #Making some basic edits to the raw dataframes chicago = pd.read_csv("chicago.csv") chicago = chicago.dropna(how='any') chicago['city']="chicago" newyork = pd.read_csv("new_york_city.csv") newyork = newyork.dropna(how='any') newyork['city']="newyork" washington = pd.read_csv("washington.csv") washington = washington.dropna(how='any') washington['city']="washington" def get_filters(): print("Hello! Lets explore some US bikeshare data!") check = False while check == False: city = input("Which city do you want to explore? (chicago, newyork, washington)") month = input("Which month do you want to explore(all, 1(jan), 2(feb), 3(mar), 4(apr), 5(may), 6(jun), 7(jul), 8(aug), 9(sep), 10(oct), 11(nov), 12(dec)") day = input("Which day do you want to explore(all, 0(mon), 1(tue), 2(wed), 3(thu), 4(fri), 5(sat), 6(sun)") if city == "chicago" or city == "newyork" or city == "washington": if month == "all" or month == "1" or month == "2" or month == "3" or month == "4" or month == "5" or month == "6" or month == "7" or month == "8" or month == "9" or month == "10" or month == "11" or month == "12": if day == "all" or day == "0" or day == "1" or day == "2" or day == "3" or day == "4" or day == "5" or day == "6": check = True else: print("Please enter from the options in brackets") check = False print('_'*100) return city, month, day # In[ ]: chicago.head() # In[ ]: newyork.head() # In[ ]: washington.head() # In[ ]: chicago['Start Time'] = pd.to_datetime(chicago['Start Time']) chicago["year"] = chicago["Start Time"].dt.year chicago["month"] = chicago["Start Time"].dt.strftime("%B") chicago["day"] = chicago["Start Time"].dt.strftime("%A") chicago["hour"] = chicago["Start Time"].dt.strftime("%H") chicago["combination"] = chicago["Start Station"] + " to " + chicago["End Station"] chicago.head() # In[ ]: newyork['Start Time'] = pd.to_datetime(newyork['Start Time']) newyork["year"] = newyork["Start Time"].dt.year newyork["month"] = newyork["Start Time"].dt.strftime("%B") newyork["day"] = newyork["Start Time"].dt.strftime("%A") newyork["hour"] = newyork["Start Time"].dt.strftime("%H") newyork["combination"] = newyork["Start Station"] + " to " + newyork["End Station"] newyork.head() # In[ ]: washington['Start Time'] = pd.to_datetime(washington['Start Time']) washington["year"] = washington["Start Time"].dt.year washington["month"] = washington["Start Time"].dt.strftime("%H") washington["day"] = washington["Start Time"].dt.strftime("%H") washington["hour"] = washington["Start Time"].dt.strftime("%H") washington["combination"] = washington["Start Station"] + " to " + washington["End Station"] washington.head() # In[ ]: chicago.count() chicago["Birth Year"] = chicago["Birth Year"].astype(int) chicago.head() # In[ ]: newyork.count() # In[ ]: washington.count() # In[ ]: def load_data(city, month, day): """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ if city == "chicago": df = chicago elif city == "newyork": df = newyork else: df = washington if month == "all": df = df else: df = df[(df["month"] == int(month))] if day == "all": df = df else: df = df[(df["day"] == int(day))] return df # In[ ]: def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') # display the most common month common_month = df['month'].mode()[0] print("The most common month of travel is "+str(common_month)) # display the most common day of week common_day = df['day'].mode()[0] print("The most common day of travel is "+str(common_day)) # display the most common start hour common_hour = df['hour'].mode()[0] print("The most common hour of travel is "+str(common_hour)) print('_'*100) # In[ ]: def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') # display most commonly used start station common_startstation = df['Start Station'].mode()[0] print("The most common start station is "+str(common_startstation)) # display most commonly used end station common_endstation = df['End Station'].mode()[0] print("The most common end station is "+str(common_endstation)) # display most frequent combination of start station and end station trip combination_endstation = df['combination'].mode()[0] print("The most common combination of start and end station is "+str(combination_endstation)) print('_'*100) # In[ ]: def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') # display total travel time Total = df['Trip Duration'].sum() print ("Total time travelled is ", str(Total)) # display mean travel time average = df['Trip Duration'].mean() average = round(average,2) print ("Average time travelled is ", str(average)) print('_'*100) # In[ ]: def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') # Display counts of user types user_counts = df['User Type'].value_counts() print ("The counts of user types:") print(user_counts) # Display counts of gender if df.city.unique()==['chicago'] or df.city.unique()==['newyork']: gender_counts = df['Gender'].value_counts() print("\nThe counts of gender types:") print(gender_counts) else: print ("Gender not available for chosen city") # Display earliest, most recent, and most common year of birth if df.city.unique()==['chicago'] or df.city.unique()==['newyork']: common_birth=df['Birth Year'].mode()[0] birth_max = df['Birth Year'].max() birth_min = df['Birth Year'].min() print ("\nThe most recent year of birth is "+str(birth_max)) print ("The earliest year of birth is "+str(birth_min)) print ("The most common year of birth is "+str(common_birth)) else: print ("Birth Year not available for chosen city") print('_'*100) # In[ ]: def raw_data(df): check = False index = 0 while check == False: viewdata = input("Do you want to view five lines of raw data? Enter yes or no.") index += 5 if viewdata == "yes": if df.city.unique()==['chicago']: print(chicago_orig.head(index)) elif df.city.unique()==['newyork']: print(newyork_orig.head(index)) else: print(washington_orig.head(index)) else: check = True print('_'*100) # In[ ]: def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) raw_data(df) restart = input('\nWould you like to restart? Enter yes or no.\n') if restart.lower() != 'yes': break # In[ ]: if __name__ == "__main__": main()
dec3f2ba1ce0644df31f326fc27cb37c26fda669
matthenschke/30-Days-of-Code-HackerRank
/day6.py
186
3.53125
4
# Enter your code here. Read input from STDIN. Print output to STDOUT test_cases = int(input()) for _ in range(test_cases): s = input() print("{0} {1}".format(s[::2], s[1::2]))
6e7583931facafefcc54a652884f5d19193d4b3b
BeiNNOnAir/grokking_algorithms
/ch4.py
1,058
3.65625
4
# 4.1 sum function def sum_(lst): if len(lst)==1: return lst[-1] else: return lst.pop()+sum_(lst) # test = sum_([3,4,5]) # print(test) # 4.2 count function def count_(lst): if len(lst)==1: return 1 else: return 1+ count_(lst[1:]) # test = count_([3,4,5]) # print(test) # 4.3 max function def max_(lst): if len(lst) == 0: return None elif len(lst) == 1: return lst[0] elif len(lst) ==2: if lst[0] >lst[1]: return lst[0] else: return lst[1] else: return max_([lst[0], max_(lst[1:])]) # test = max_([8,3,4,5]) # print(test) def quicksort(lst): less = [] greater = [] if len(lst)<2: return lst else: pivot = lst[0] for i in lst[1:]: # here remember [1:], otherwise it is a dead loop if i <=pivot: less.append(i) else: greater.append(i) return quicksort(less)+[pivot]+quicksort(greater) print(quicksort([4,6,3,5,2]))
b398fe50cfb5ed87228184cf64c8f2637731afbd
pfkevinma/stanCode_Projects
/stanCode_Projects/my_photoshop/shrink.py
1,541
4.15625
4
""" File: shrink.py Name: Pei-Feng (Kevin) Ma ------------------------------- Create a new "out" image half the width and height of the original. Set pixels at x=0 1 2 3 in out , from x=0 2 4 6 in original, and likewise in the y direction. """ from simpleimage import SimpleImage def shrink(filename): """ :param filename: str, :return img: SimpleImage using the concept of the checker board. select pixels we need and reorganize into a new image """ img = SimpleImage(filename) after_shrink = SimpleImage.blank(img.width // 2, img.height // 2) for y in range(img.height): for x in range(img.width): p_org = img.get_pixel(x, y) if (x+y) % 2 == 0: if x % 2 == 0: p_shrink = after_shrink.get_pixel(x//2, y//2) p_shrink.red = p_org.red p_shrink.green = p_org.green p_shrink.blue = p_org.blue else: p_shrink = after_shrink.get_pixel((x-1) // 2, (y-1) // 2) p_shrink.red = p_org.red p_shrink.green = p_org.green p_shrink.blue = p_org.blue return after_shrink def main(): """ This program will shrink the image into 1/2 original sizw. """ original = SimpleImage("images/poppy.png") original.show() after_shrink = shrink("images/poppy.png") after_shrink.show() if __name__ == '__main__': main()
e8e072f565b74063cbdceb5d833b3ffd8c7171d7
AndrewAct/DataCamp_Python
/Image Processing with Keras in Python/2 Using Convolutions/02_Image_Convolutions.py
1,208
4.28125
4
# # 8/16/2020 # The convolution of an image with a kernel summarizes a part of the image as the sum of the multiplication of that part of the image with the kernel. In this exercise, you will write the code that executes a convolution of an image with a kernel using Numpy. Given a black and white image that is stored in the variable im, write the operations inside the loop that would execute the convolution with the provided kernel. kernel = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]]) result = np.zeros(im.shape) # Output array for ii in range(im.shape[0] - 3): for jj in range(im.shape[1] - 3): result[ii, jj] = (im[ii:ii+3, jj:jj+3] * kernel).sum() # Print result print(result) # <script.py> output: # [[2.68104586 2.95947725 2.84313735 ... 0. 0. 0. ] # [3.01830077 3.07058835 3.05098051 ... 0. 0. 0. ] # [2.95163405 3.09934652 3.20261449 ... 0. 0. 0. ] # ... # [0. 0. 0. ... 0. 0. 0. ] # [0. 0. 0. ... 0. 0. 0. ] # [0. 0. 0. ... 0. 0. 0. ]]
bd1426414c3dacb561ffc5f5da752531d9bb6a58
mwhooker/gallery_tool
/gallery.py
1,013
3.8125
4
""" gallery.py helps you calculate where to place your hanger All units in inches """ from fractions import Fraction # we hang frames at 57" on center CENTER = Fraction(57) def parse_input(s): """ >>> parse_input("5") Fraction(5, 1) >>> parse_input("5 7/8") Fraction(47, 8) """ parts = s.split(' ') if len(parts) == 1: return Fraction(parts[0]) elif len(parts) == 2: return Fraction(parts[0]) + Fraction(parts[1]) else: raise ValueError("Can't parse %s" % s) def repr_fraction(f): """ >>> x = "5 7/8" >>> repr_fraction(parse_input(x)) == x True """ whole = int(f) part = f - whole return "%s %s/%s" % (whole, part.numerator, part.denominator) def main(): height = parse_input(raw_input("Frame height:\n\t")) hang_pt = parse_input(raw_input("Distance from top to mount point:\n\t")) print "Install hook at %s" % repr_fraction(CENTER + (height / 2) - hang_pt) if __name__ == '__main__': main()
5f9576f1a3f3084c859f12fa72baa03044901232
sergiovasquez122/Common-sense-data-structures
/chapter11/exercise1.py
395
4.1875
4
''' Use recursion to write a function that accepts an array of strings and returns the total number of characters across all the strings. For example, if the input array is ["ab", "c", "def", "ghij"] , the output should be 10 since there are 10 characters in total. ''' def total_characters(l, idx=0): if idx >= len(l): return 0 return len(l[idx]) + total_characters(l, idx + 1)
457762be3ea60a8f986177821bb4cf59b1993236
adibl/project1
/csv_cla.py
2,361
3.859375
4
""" writer: adi bleyer date: 11/11/2017 ths file contain the student class. the class have init, str methode. the clas handel amat students """ class Student: SCIENCE = [('physics', "5"), ('chemistry', "5"), ('arabic', "5"), ('biology', "5")] MATH = [("math", "5")] COMPUTER = [('computer science', "5"), ("computer science", "10")] def __init__(self, line): self.subject = [] self.subject.append((line[-2], line[-1])) self.properties = [] self.properties = line[:-2] def get_properties(self): return self.properties def is_same(self, student): """ check if the student line and this student are the same :var:student: student line :return: true if the student properties are the same and false otherwise """ if student.get_properties() == self.properties: return True else: return False def add_subject(self, line): """ add a subject to the student :var:line: a list of the subject,level :retern: the subjects list """ self.subject.append((line[0], line[1])) return self.subject def is_amat(self): """ check if the student is amat student :return: true if he is amat student and false if not """ is_scientific = False is_computer = False is_math = False for sub in self.subject: if sub in Student.SCIENCE: is_scientific = True if sub in Student.MATH: is_math = True if sub in Student.COMPUTER: is_computer = True return is_math and is_scientific and is_computer def scientific_subjects(self): """ cange student subjects to amat subjects only, delete all others. """ subjects = [] for sub in self.subject: if ((sub in Student.COMPUTER) or (sub in Student.SCIENCE) or (sub in Student.MATH)): subjects.append(sub) self.subject = subjects def __str__(self): line = "" for prop in self.properties: line += str(prop) + "," for s in self.subject: line += str(s[0]) + "," + str(s[1]) + "," return line[:-1]
49cdc3fd3963d6681a122e5142731c2f0e2c960f
AP-MI-2021/lab-3-ClaudiuDC21
/main.py
6,314
3.953125
4
from typing import List def show_menu(): print('1. Citire Date. ') print('2. Determinare cea mai lunga secventa cu proprietatea ca numerele sunt palindrome. ') print('3. Determinare cea mai lunga secventa cu proprietatea ca numerele sunt formate din cifre prime ') print('4. Determinare cea mai lunga secventa cu proprietatea ca numerele sunt pare. ') print('5. Iesire. ') def read_list(): lista = [] lista_str = input('Dati numerele separate prin spatiu: ') lista_str_split = lista_str.split(' ') for num_str in lista_str_split: lista.append(int(num_str)) return lista def is_palindrome(lst: List[int]) -> bool: ''' Determina daca un o lista data are toate elementele palindrom. :param lst: o lista data :return: True daca lista data are toate elementele palindrom, False in caz contrar. ''' for n in lst: invers = 0 copie_n = n while copie_n != 0: invers = invers * 10 + copie_n % 10 copie_n = copie_n // 10 while n != 0: if n % 10 != invers % 10: return False n = n // 10 invers = invers // 10 return True def test_is_palindrome(): assert is_palindrome([5, 11, 44]) == True assert is_palindrome([5, 55, 555, 5555]) == True assert is_palindrome([1, 2, 12]) == False assert is_palindrome([1, 2, 3, 4, 5, 6, 7, 8, 9]) == True assert is_palindrome([11, 33, 44, 55, 66, 78]) == False def get_longest_all_palindromes(lst: List[int]) -> List[int]: ''' Determina cea mai lunga subsecventa cu elemente palindrom. :param lst:O lista data. :return: Cea mai lunga subsecventa cu elemente palindrom. ''' lungime = len(lst) result = [] for st in range(lungime): for dr in range(st, lungime): if is_palindrome(lst[st:dr + 1]) and len(lst[st:dr + 1]) > len(result): result = lst[st:dr + 1] return result def test_get_longest_all_palindromes(): assert get_longest_all_palindromes([5, 6, 7, 12, 11, 11, 44, 55, 45, 55, 33, 343]) == [11, 11, 44, 55] assert get_longest_all_palindromes([11, 12, 13, 1, 2, 3, 42, 24, 1, 2, 3, 4]) == [1, 2, 3, 4] assert get_longest_all_palindromes([111, 121, 131, 212, 234, 333, 444, 545, 13]) == [111, 121, 131, 212] def is_prime(n: int) -> bool: ''' Determina daca un numar dat n este prim. :param n: numar intreg dat. :return: Treu daca n este prime, False in caz contrar. ''' if n < 2: return False for d in range(2, int(n ** 0.5) + 1): if n % d == 0: return False return True def test_is_prime(): assert is_prime(1) == False assert is_prime(2) == True assert is_prime(4) == False assert is_prime(11) == True assert is_prime(18) == False def all_numbers_prime(lst: List[int]) -> bool: ''' Determina daca fiecare cifra a elementelor unei liste sunt prime. :param lst: O lista data. :return: True daca fiecare cifra a elemntelor listei sunt prime, False in caz contrar. ''' for n in lst: while n != 0: if is_prime(n % 10) == False: return False n = n // 10 return True def test_all_numbers_prime(): assert all_numbers_prime([25, 55, 77]) == True assert all_numbers_prime([12, 13, 14, 15]) == False assert all_numbers_prime([35, 37, 52]) == True assert all_numbers_prime([123, 124, 125, 126]) == False def get_longest_prime_digits(lst: List[int]) -> List[int]: ''' Determina cea mai lunga subsecventa a carei elemente are toate cifrele prime. :param lst: Lista data. :return:Cea mai lunga subsecventa a carei elemente are toate cifrele prime ''' lungime = len(lst) result = [] for st in range(lungime): for dr in range(st, lungime): if all_numbers_prime(lst[st:dr + 1]) == True and len(lst[st:dr + 1]) > len(result): result = lst[st:dr + 1] return result def sorted_even(lst: List[int]) -> bool: ''' Determina daca elementele dintr-o lista sunt pare. :param lst: Lista data. :return: True daca elementele listei sunt ordonate crescator, False in caz contrar. ''' for n in lst: if n % 2 == 1: return False return True def test_sorted_even(): assert sorted_even([2, 4, 6, 8]) == True assert sorted_even([24, 24, 24, 24]) == True assert sorted_even([12, 14, 16, 17]) == False assert sorted_even([3, 5, 7, 9]) == False def get_longest_all_even(lst: List[int]) -> List[int]: ''' Determina cea mai lunga subsecventa de numere pare dintr-o lista data. :param lst: Lista data. :return: Cea mai lunga subsecventa de numere pare. ''' result = [] lungime = len(lst) for st in range(lungime): for dr in range(st, lungime): if sorted_even(lst[st:dr + 1]) == True and len(lst[st:dr + 1]) > len(result): result = lst[st:dr + 1] return result def test_get_longest_all_even(): assert get_longest_all_even([1, 2, 2, 4, 1, 2, 4, 1, 45, 236]) == [2, 2, 4] assert get_longest_all_even([24, 48, 3, 23, 24, 25, 26, 26, 26, 5, 24, 64, 646]) == [ 26, 26, 26] assert get_longest_all_even([962, 424, 323, 244, 566, 656, 15, 16, 18, 22, 26, 28]) == [16, 18, 22, 26, 28] def main(): lista = [] while True: show_menu() print() optiunea = input('Alegeti optiunea: ') print() if optiunea == '1': lista = read_list() elif optiunea == '2': print('Lista cu cele mai multe numere palindrom este: ', get_longest_all_palindromes(lista)) elif optiunea == '3': print('Lista cu cele mai multe numere ale caror cifre sunt numere prime: ', get_longest_prime_digits(lista)) elif optiunea == '4': print('Lista cu cele mai multe numere pare este:', get_longest_all_even(lista)) elif optiunea == '5': break else: print('Optiune invalida! Incercati alta optiune! ') if __name__ == '__main__': test_is_palindrome() test_get_longest_all_palindromes() test_is_prime() test_all_numbers_prime() test_sorted_even() test_get_longest_all_even() main()
b95d84c0ec196e15a2142a6bd8932b5677e4aa9b
yhx0105/leetcode
/04_chazhaohepaixu/15_岛屿数量.py
1,168
3.8125
4
""" 给定一个由 '1'(陆地)和 '0'(水)组成的的二维网格, 计算岛屿的数量。一个岛被水包围, 并且它是通过水平方向或垂直方向上相邻的陆地连接而成的。 你可以假设网格的四个边均被水包围。 输入: 11110 11010 11000 00000 输出: 1 输入: 11000 11000 00100 00011 输出: 3 """ class Solution: def numIslands(self, grid): w=len(grid) l=len(grid[0]) res=0 for r in range(w): for c in range(l): if grid[r][c]=='1': res+=1 self.__iterater(r,c,grid,w,l) return res def __iterater(self,r,c,grid,w,l): if r<0 or c<0 or r>=w or c>=l: return if grid[r][c]=='0': return grid[r][c]='0' self.__iterater(r-1,c,grid,w,l) self.__iterater(r+1,c,grid,w,l) self.__iterater(r,c-1,grid,w,l) self.__iterater(r,c+1,grid,w,l) if __name__ == '__main__': grid=[["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"]] s=Solution() print(s.numIslands(grid))
15f9fab2b877165bc8b797f5af81037319579cce
sankethsunkad/sllab
/sl lab/5/5a.py
1,081
4.0625
4
conversions=set([]) amendd=[] def c_f(temp): final=(temp*1.8)+32 return final def f_c(temp): final=(temp-32)*(5/9) return final while('true'): print("1.Celsius to fahrenheit") print("2.fahrenheit to celsius") print("3.to print the convrsions value") print("press 0 to terminate") op = int(input("Enter the option")) if(op==1): tem=int(input("enter the temprature in celsius scale")) f_tem=c_f(tem) a=["celsius",tem,"to","fahrenheit",f_tem] amendd=list(conversions) amendd.append(a) conversions=tuple(amendd) print("Temperature in fahrenheit scale is",f_tem) elif(op==2): tem = int(input("enter the temprature in fahrenheit scale")) f_tem = f_c(tem) a = ["fahrenheit", tem, "to", "celsius", f_tem] amendd = list(conversions) amendd.append(a) conversions = tuple(amendd) print("Temperature in celsius scale is", f_tem) elif(op==3): print(conversions) elif(op==0): exit()
d2244e2b701d415c28343bd4926a85e75a91c634
jxnu-liguobin/cs-summary-reflection
/python-leetcode/laozhang/tree/leetcode_105_.py
1,281
3.546875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # coding=utf-8 """ 105. 从前序与中序遍历序列构造二叉树 """ from typing import List from laozhang import TreeNode class Solution: ##待优化 def buildTree_(self, preorder: List[int], inorder: List[int]) -> TreeNode: if not preorder: return None val = preorder[0] k = inorder.index(val) root = TreeNode(val) root.left = self.buildTree(preorder[1:k + 1], inorder[:k]) root.right = self.buildTree(preorder[k + 1:], inorder[k + 1:]) return root ##优化版 def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode: def helper(preorder: List[int], inorder: List[int], preleft: int, preright: int, inleft: int, inright: int): if inleft > inright: return None val = preorder[preleft] mid = inorder.index(val) root = TreeNode(val) root.left = helper(preorder, inorder, preleft + 1, mid - inleft + preleft, inleft, mid - 1) root.right = helper(preorder, inorder, mid - inleft + preleft + 1, preright, mid + 1, inright) return root return helper(preorder, inorder, 0, len(preorder) - 1, 0, len(inorder) - 1)
95efdb9847e0d4362d38737b38f78a93af1db3ed
karthikh07/Python-core
/Basics/arithmatic.py
185
3.5
4
a=5 b=10 c = a+b d=a-b e=a*b f=a/b g=a**b #square h=a//b #div without float answer i=a%b print (c) print (d) print (e) print (f) print (g) print (h) print (i)
c7a823eee922684b22ece5bc3c9f08ab80f348c9
GalvanizeDataScience/building-spark-applications-live-lessons
/code/person.py
278
3.859375
4
# print print "hello world" # classes class Person(object): def __init__(self, name, company): self.name = name self.company = company def say_hello(self): return "Hello, my name is {0} and I work at {1}".format(self.name, self.company)
218592a365ff30b76b7636c5b1b48af46552d2b5
helas/takehome
/client_data/query_api.py
3,212
3.546875
4
import requests from datetime import datetime from datetime import timedelta class TakeHomeApiClient: # Calculate result of task 4a def highest_average_temperature_since_2000(self): # first, using the params bellow, we ask our API for the highest temperatures per city since 2000 now = datetime.now() params = {'start_date': '2000-01-01', 'end_date': now.strftime('%Y-%m-%d'), 'aggregation': 'max', 'n_results': '1'} response = requests.get('http://web-service:8000/land_temperatures/', params=params) # then, if the request worked, we filter out the highest temperature. max_record = {} if response.status_code == 200: results = response.json() for result in results: avg_temp = result.get('avg_temp', None) if max_record == {} or (avg_temp is not None and avg_temp > max_record['avg_temp']): max_record = result # at this point, either we have a max_record, either the response was empty. if max_record: print(f'Max temp of {max_record["avg_temp"]} in city {max_record["city_name"]}') else: print(f'No records are available in that period') return max_record return None # Calculate result of task 4b def create_new_entry_for_record_city(self, max_record): # first we findout which month was last month and compose the data that we want to create now = datetime.now() last_month = now - timedelta(days=30) max_record['date'] = f'{last_month.year}-{last_month.month}-01' max_record['avg_temp'] += 0.1 # we issue the request and return the new record response = requests.post('http://web-service:8000/land_temperatures/', data=max_record) if response.status_code == 201: print(f'Created new record with max temp {max_record["avg_temp"]} in month {max_record["date"]}') return response.json() elif response.status_code == 400: print('The request is not well formed. Cannot continue.') return None # Calculate result of task 4c def create_update_entry_for_record_city(self, wrong_record): params = {'city_name': wrong_record['city_name'], 'date': wrong_record['date']} data = {'avg_temp': wrong_record['avg_temp'] - 2.5} response = requests.put(f'http://web-service:8000/land_temperature/{params["city_name"]}/{params["date"]}', data=data) if response.status_code == 200: print(f'Successfully updated the record. The new avg_temp is {data["avg_temp"]}') else: print(f'There was an issue: {response.status_code}') def run_exercises(self): max_avg_record = self.highest_average_temperature_since_2000() if max_avg_record: wrong_record = self.create_new_entry_for_record_city(max_avg_record) if wrong_record: self.create_update_entry_for_record_city(wrong_record) if __name__ == '__main__': client = TakeHomeApiClient() client.run_exercises()
1f086346e820da605a418b435f2ddfc0d8721a6d
Diegokernel/holbertonschool-machine_learning
/supervised_learning/0x03-optimization/4-moving_average.py
395
3.90625
4
#!/usr/bin/env python3 """calculates the weighted moving average of a data set:""" import numpy as np def moving_average(data, beta): """calculates the weighted moving average of a data set:""" a = 0 bias_corrected = [] for i in range(len(data)): a = (beta * a + (1 - beta) * data[i]) bias_corrected.append(a / (1 - beta ** (i + 1))) return bias_corrected
43a26e199791f63f3c7d8ce73ea816fe0d24fd28
DeshErBojhaa/sports_programming
/leetcode/Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree.py
936
4.03125
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 # Check If a String Is a Valid Sequence from Root to Leaves Path in a Binary Tree class Solution: def isValidSequence(self, root: TreeNode, arr: List[int]) -> bool: ans = False def trav(cur, ind): nonlocal ans if ans: return if not cur: return if not cur.left and not cur.right and ind == len(arr) - 1 and cur.val == arr[-1]: ans = True return if ind >= len(arr): return if cur.val != arr[ind]: return trav(cur.left, ind+1) trav(cur.right, ind+1) trav(root, 0) return ans
42ed21f6afec015ace7c9e6e608510caa253468a
mkiterian/oop
/computer.py
2,254
3.546875
4
class Computer(): def __init__(self, brand, memory_size, storage_size, os_type): self.brand = brand self.memory_size = memory_size self.storage_size = storage_size self.os_type = os_type #use name mangling to make it private self.__warranty = 12 def power_up(self): return 'The Computer is booting' def shutdown(self): return 'The computer is shutting down' def show_spec(self): print('Brand: {} Memory: {} GB Storage Size: {} GB'.format( self.brand, self.memory_size, self.storage_size)) def set_warranty(self, months): self.__warranty = months def get_warranty(self, elapsed_months=0): self.__warranty -= elapsed_months return self.__warranty class Laptop(Computer): def __init__(self, brand, memory_size, storage_size, os_type, battery_life): super().__init__(brand, memory_size, storage_size, os_type) self.battery_life = battery_life def show_battery_life(self): return 'The battery lasts up to {} Hours'.format(self.battery_life) def can_run_windows_ten(self): if self.memory_size > 1 and self.storage_size > 100: if self.os_type != 'Windows 10': return True else: return False return False def power_up(self): return 'The Laptop is booting' def shutdown(self): return 'The Laptop is shutting down' def install_drivers(self): return 'Drivers are being installed' class CellPhone(): def __init__(self, brand, model, sim_type): self.brand = brand self.model = model self.sim_type = sim_type self.contacts = {} def add_contact(self, name, number): self.name = name self.number = number self.contacts[self.name] = self.number def call(self, name): if name in self.contacts.keys(): return 'Calling {}'.format(name) class SmartPhone(Computer, CellPhone): def __init__(self, brand, memory_size, storage_size, os_type, model, sim_type): Computer.__init__(self, brand, memory_size, storage_size, os_type) CellPhone.__init__(self, brand, model, sim_type)
44f7855ed323edc5237bd66bc25a25a9bf1d77f5
amitjain17/FSDP2019
/DAY5/simpsons.py
533
3.828125
4
# -*- coding: utf-8 -*- """ Created on Sat May 11 21:38:32 2019 @author: NITS """ import re #import regular expression list3 =[] #intialize the list with open("simpsons_phone_book.txt",'rt') as simp: #open the text file list1 = simp.read() list2 = list1.split("\n") for item in list2: #search for the name in the file if re.search(r'^[j|J]{1}[Neu]',item): list3.append(item) for i in list3: print(i)
ee1fab47670ab02048c0a3c94ebab55b11a101b1
dogeplusplus/DailyProgrammer
/247SecretSanta.py
1,448
3.8125
4
import random def secret_santa(participants): pairings = [] # Final pairings at the end participant_list = [x.split(' ') for x in participants.splitlines()] # Split participants into list of families # Random member from largest family remaining largest_family = max(participant_list,key=len) family_id = [i for i, item in enumerate(participant_list) if item == largest_family][0] random.shuffle(participant_list[family_id]) x = participant_list[family_id].pop() # While there are still givers unassigned while not all(len(family) == 0 for family in participant_list): ''' Get the sizes of the two largest families to account for ties and uneven family sizes ''' largest_families = sorted(map(len, participant_list),reverse = True)[:1] # Get indicies of the largest/second largest families, take the first one family_id = [i for i, item in enumerate(participant_list) if i != family_id and len(item) in largest_families][0] random.shuffle(participant_list[family_id]) # Take random person in the family y = participant_list[family_id].pop() pairings.append((x,y)) # Recipiant is now the giver x = y print(pairings) test_participants = '''Sean Winnie Brian Amy Samir Joe Bethany Bruno Anna Matthew Lucas Gabriel Martha Philip Andre Danielle Leo Cinthia Paula Mary Jane Anderson Priscilla Regis Julianna Arthur Mark Marina Alex Andrea ''' secret_santa(test_participants)
31be2f297b789c0414c69e40ab8647f41b60c3ca
Sushmitha999/python
/13.py
333
3.625
4
#modified encoding from itertools import groupby def encode_modified(alist): def aux(lg): if len(lg)>1: return [len(lg), lg[0]] else: return lg[0] return [aux(list(group)) for key, group in groupby(alist)] print(encode_modified("aaaabbbbccccdddddd"))
a89e6a7f9b214058f5c68a492d5622980c226d7d
apang-ai/InterView
/InterView/DataStructures/6.LeetCode.py
976
3.984375
4
''' 给定一个仅包含大小写字母和空格 ' ' 的字符串 s,返回其最后一个单词的长度。如果字符串从左向右滚动显示,那么最后一个单词就是最后出现的单词。 如果不存在最后一个单词,请返回 0 。 说明:一个单词是指仅由字母组成、不包含任何空格字符的 最大子字符串。   示例: 输入: "Hello World" 输出: 5 题解: def lengthOfLastWord(s): # 判断如果不存在这个字符串就返回空 if not s: return 0 # rstrip 默认删除末尾的空字符,如果末尾是空字符,先删除 s = s.rstrip() # 倒叙遍历字符串,判断如果里面有空字符串,就返回空字符串之后的长度 for i in range(len(s)-1, -1, -1): if s[i] == ' ': return len(s)-1-i # 如果末尾是空字符串,且中间也没有空字符串列如 s = "a ",就返回去掉末尾空字符串的长度 return len(s) '''
7cf036633f5d19256af8888d279a992c34d2a61a
cristinarivera/python
/untitled-24.py
181
3.671875
4
def find_last(s,t): n = s.find(t) while n > 0: return n n = n + 1 else: return n print find_last('baaa','a') #>>> 3
fe902ff7847005527c70d93c52716be9917e58ee
Jhon-Chen/Code_Practice
/C_miniWeb_server/01_miniWeb服务器_动态网页.py
1,595
3.6875
4
# 导入模块 import socket from application import app class WebServer(): # 定义初始化方法 def __init__(self): # 创建套接字 tcp_server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 设置套接字属性 tcp_server_socket.setsocketopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, True) # 绑定端口 tcp_server_socket.bind("", 8080) # 开启监听 设置套接字从主动变为被动 tcp_server_socket.listen(128) self.tcp_server_socket = tcp_server_socket # 定义启动服务器方法 def start(self): while True: # 接受客户端连接并拆包 new_client_socket, ip_port = self.tcp_server_socket.accept() # 调用request_handler()处理请求 self.requset_handler(new_client_socket, ip_port) # 定义响应服务器的方法 def requset_handler(self, new_client_socket, ip_port): # 接受客户端请求报文 requset_data = new_client_socket.recv(1024) # 判断客户端是否已经下线 if not requset_data: print('客户端[%s]已断开连接' % str(ip_port)) new_client_socket.close() return # 调用app模块的application方法处理请求 response_data = app.application # 发送请求报文 new_client_socket.send(response_data) # 关闭连接 new_client_socket.close() def main(): # 主函数入口 ws = WebServer() ws.start if __name__ == '__main__': main()
c3fbcdf75a468fe81dc58c7a29b70b2b92a65d5c
tanyayez/map_lab2_Tetyana_Yezerska
/buid_map.py
4,401
3.5
4
from geopy.geocoders import Nominatim import folium def read_file(path): '''(str) -> (list) This program reads data from file. Returns list of lists that consist of filminfo(name year etc) and location ''' with open(path, encoding="utf-8", errors='ignore') as f: info = f.read() info = info.split("\n") res = [] for line in info[14:-2]: first = line.split("\t") if "(" in first[-1]: location = first[-2] else: location = first[-1] res.append([first[0], location]) return res def loc_dict(data, year): '''(lst, int) -> (dict) This function returns dictionary with locations as keys and lists of movies as value ''' res = dict() years = '(' + str(year) for line in data: if years in line[0]: film = line[0].split(years) location = line[-1] name_movie = film[0].replace("'", '"') if location in res: res[location] += [name_movie] else: res[location] = [name_movie] return res def country_dict(data): '''(lst) -> (dict) This function returns dictionary with countries as keys and number of movies created for all time in the country as value ''' res = dict() for line in data: loc = line[-1].replace(". ", ",") country = loc[loc.rfind(',')+1:].lstrip() if 'USA' in country: country = 'United States' elif 'UK' in country: country = 'United Kingdom' if country in res: res[country] += 1 else: res[country] = 1 return res def check_num(country, data): '''(str, dict) -> (int) This function returns the number of movies created in the given country ''' if country in data: return data[country] else: return 0 def get_coord(name): '''(str) -> (int, int) Returns a tuple of coordinates of given address. If the coordinates are not found it looks for approximate coordinate In case of error prints messege and returns None ''' try: geolocator = Nominatim(timeout=20) location = geolocator.geocode(name) res = [location.latitude, location.longitude] except: new_name = name[name.find(",")+1:] if name != new_name: return get_coord(new_name) else: print("Location not found ", new_name) return None return res def build_map(locations, count): '''(dict, dict) -> None This function creates a map with two layears: first colors depending on overall number of movie created, second: markers of locations where movies where created in specific year ''' my_map = folium.Map(location=[48.314775, 25.082925], zoom_start=2) layer1 = folium.FeatureGroup(name='Movies(red> 20000,\ 3000 <orange <20000, green < 3000)') layer1.add_child(folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function=lambda x: {'fillColor': 'green' if check_num(x['properties']["NAME"], count) < 3000 else 'orange' if 3000 <= check_num(x['properties']["NAME"], count) <= 20000 else 'red'})) my_map.add_child(layer1) my_map.save("Res_Map.html") layer2 = folium.FeatureGroup(name='Locations of movies in given year') for loc in locations: tag_film = '' for k in locations[loc]: tag_film += k + ", " locat = get_coord(loc) if locat is not None: layer2.add_child(folium.Marker(location=locat, popup=tag_film, icon=folium.Icon())) my_map.add_child(layer2) my_map.add_child(folium.LayerControl()) my_map.save("Res_Map.html") def main(): ''' None -> None This is the main function ''' year = input("Enter a year: ") try: year = int(year) except: print("Year should be an integer!") all_data = read_file("locations.list") year_data = loc_dict(all_data, year) country = country_dict(all_data) build_map(year_data, country) main()
73340d763c3695ad266296a4261b1bad9d78e575
taylorcreekbaum/lpthw
/ex21/ex21-2.py
835
3.984375
4
def add(a, b): print(f"ADDING {a} + {b}") return a + b def subtract(a, b): print(f"SUBTRACTING {a} - {b}") return a - b def multiply(a, b): print(f"MULTIPLYING {a} * {b}") return a * b def divide(a, b): print(f"DIVIDING {a} / {b}") return a / b print("Let's do some math with just functions!") age = add(30,5) height = subtract(78,4) weight = multiply(90,2) iq = divide(100,2) print(f"Age: {age}, Height: {height}, Weight: {weight}, IQ: {iq}") # A puzzle for the extra credit, type it in anyway. print("Here is a puzzle.") # (30 + 5) + ((78 - 4) - ((90 * 2) * ((100 / 2) / 2))) # 35 + (74 - (180 * (50 / 2))) # 35 + (74 - (180 * 25)) # 35 + (74 - 4500) # 35 - 4426 # -4391 what = add(age, subtract(height, multiply(weight,divide(iq,2)))) print("That becomes: ", what, "Can you do it by hand?")
747a3d0d648ccd8e6e116e6a7fe3022963ce7a45
kenziebottoms/py-testing-calc
/calculator.py
968
4.09375
4
class Calculator(): """Performs the four basic mathematical operations Methods: add(number, number) subtract(number, number) multiply(number, number) divide(number,number) """ def add(self, x, y): """Adds two numbers together Arguments: x - Any number y - Any number """ return x + y def subtract(self, x, y): """Subtracts the second number from the first Arguments: x - Any number y - Any number """ return x - y def multiply(self, x, y): """Multiplies the two numbers together Arguments: x - Any number y - Any number """ return x * y def divide(self, x, y): """Multiplies the first number by the second Arguments: x - Any number y - Any number """ return x / y