blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
cb79d395415f75fdd0ab1fb39ebc4098e6d11db5
iAmMrinal0/grokking_algos
/chapter1/binary_search.py
798
3.703125
4
def binary_search(arr, num): low = 0 high = len(arr) - 1 while low <= high: mid = (low + high) // 2 guess = arr[mid] if guess == num: return mid if guess < num: low = mid + 1 else: high = mid - 1 return None def rec_search(arr, num, low, high): if low > high: return None mid = (low + high) // 2 if arr[mid] == num: return mid if arr[mid] > num: return rec_search(arr, num, low, mid - 1) if arr[mid] < num: return rec_search(arr, num, mid + 1, high) return None a = [10, 12, 23, 34, 55, 76, 87, 98, 109, 110] print(binary_search(a, 2)) print(rec_search(a, 2, 0, len(a) - 1)) print(binary_search(a, 109)) print(rec_search(a, 109, 0, len(a) - 1))
68f70f58eb30f59d582d752b22cb1921e6bebe0b
ElectronicGomez/Python
/Py/TKINTER/SpinBox_opcion_lista.py
912
3.671875
4
# -*- coding: utf-8 -*- """ Created on Fri May 15 13:54:18 2020 @author: ASUS """ from tkinter import * from tkinter import messagebox def obtener(): messagebox.showinfo("Mensaje","tu seleccionaste" + valor.get()) messagebox.showwarning("Advertencia", "Peligro") ventana = Tk() valor = StringVar() ventana.title("Uso de SpinBox con tkinter") ventana.geometry("400x300") # Colocando valores etiqueta = Label(ventana, text = "Ejemplo de SpinBox").place(x = 20, y = 20) combo = Spinbox(ventana, values = ("UNO","DOS","TRES","CUATRO","CINCO")).place(x = 20, y = 50 ) #Haciendo un rango etiqueta2 = Label(ventana, text = "Ejemplo 2 de SpinBox").place(x = 20, y = 80) combo2 = Spinbox(ventana,from_= 1, to = 10, textvariable = valor).place(x = 20, y = 110) boton = Button(ventana, text = "Obtener valor SpinBox", command = obtener).place(x = 80, y = 140) ventana.mainloop()
7bd98e5bebd6fbd4cb77ec1bcc779148b79397ea
suacalis/VeriBilimiPython
/Ornek11_7.py
467
3.96875
4
''' Örnek 11.7: Sayıları harf karşılıkları ile eşleştiren bir sözlük yapısı oluşturalım. Sonra da klavyeden girilen rakamın harf karşılığını ekrana yazdıran programı kodlayalım ''' rakam = int(input("1-9 arası bir sayı gir.:")) Sozluk = {1:"Bir", 2:"İki", 3:"Üç", 4:"Dört", 5:"Beş", 6: "Altı", 7:"Yedi", 8:"Sekiz", 9:"Dokuz"} #Rakam karşılığı sözlükte yoksa uyarı mesajı verelim print(Sozluk.get(rakam, "Sözlükte yoktur!"))
8070ee1da99ebbf927adbb9bb4117ccc18f596da
fagan2888/Coding-Interview
/Python/Data Structure/Sliding Window/Contains Duplicate.py
418
3.640625
4
class Solution: def containsDuplicate(self, nums: 'List[int]') -> 'bool': # we can use set very easily, or do sort or dictionary dict = {} for num in nums: if num in dict: return True else: dict[num] = 1 return False """ def containsDuplicate(self, nums: List[int]) -> bool: return len(nums) != len(set(nums)) """
084c04c3cf2fe77b13f36645e561ed08cc31c118
lorenzocogolo/repo1
/social science project/step1.py
3,069
3.609375
4
#!/usr/bin/env python # coding: utf-8 # In[5]: from datetime import * from dataread import cheaters,kills,dic_kills # In[2]: def cheaters_accounts(): '''This function takes the cheaters list as input and estrapolates the cheaters' accounts for each match in the dictionary It returns a list made of sublists that contain the active cheaters present in each game''' match_cheaters = [] for key in dic_kills: lst = [] for value in dic_kills[key]: for i in range(len(cheaters)): if cheaters[i][0] == value[0] and cheaters[i][1] < value[2] < cheaters[i][2]: lst.append(value[0]) unique = sorted(set(lst)) match_cheaters.append(unique) return match_cheaters match_cheaters = cheaters_accounts() # In[4]: def suspects(dic): '''This function iterates over each game played and firstly: compares each killer to the cheaters list and appends the killed player to the suspect list if they are killed by a cheater. Secondly, if this number of kills by a cheater in a game reaches 3, it adds the following killed players to the suspect list. It returns the suspect list.''' susp_list = [] loc = 0 for key in dic: lst1 = [] if len(match_cheaters[loc]) > 0: for cheater in cheaters: count = 0 for v in dic[key]: if cheater[0] == v[0] and cheater[1] < v[2] < cheater[2]: count += 1 lst = [] lst.extend([v[1],v[2]]) susp_list.append(lst) # for each vlaue[1], if count is >= 3, checks if the account is already in the susp_list # to avoid duplicates. If this is not the case, add killed player encountered to the suspect list elif count >= 3 and not any(v[1] in sl for sl in susp_list): lst1 = [] lst1.extend([v[1],v[2]]) susp_list.append(lst1) loc += 1 return susp_list susp_list = suspects(dic_kills) def start_cheating(s_list): '''This function iterates over the suspect list and compares each player to the cheaters' accounts. If one player is matched to a cheater's account and the cheating start date is less than 5 days from the time when the player was added to the suspect list, the count for the number of players that started cheating is increased. The function returns the number of players that started cheating.''' count = 0 for i in s_list: for j in cheaters: delta = j[1] - i[1] # compare each suspect to the cheaters list and thier suspect date with the cheating period if i[0] == j[0] and delta.days < 5 and delta.days >= 0: count += 1 return count new_cheaters = start_cheating(susp_list)
15b3b2c659548009094fb590ff4afd0d3f828fbf
osnaldy/Python-StartingOut
/chapter8/charge_acount_validation.py
556
4.09375
4
def main(): #Here we open the file and read the lines file_name = open("charge_account.txt", 'r') charges = file_name.readlines() file_name.close() #Here we create an empty array, loop through it and append the values to a list arr = [] for i in charges: name = int(i) arr.append(name) #Here we verify if the value searched in the list exists search = int(raw_input("Enter the number to be searched: ")) if search in arr: print "Valid number" else: print "Invalid number" main()
ee0a576cddca0543df503bc6f2884f6a3b6a319a
geshem14/my_study
/Coursera_2019/Python/week4/week4task9.py
1,319
3.890625
4
# week 4 task 9 """ текст задания тут 79 символ=>! Дано натуральное число n>1. Выведите его наименьший делитель, отличный от 1. Решение оформите в виде функции MinDivisor(n). Алгоритм должен иметь сложность порядка корня квадратного из n. Указание. Если у числа n нет делителя не превосходящего корня из n, то число n — простое и ответом будет само число n. А у всех составных чисел обязательно есть делители, отличные от единицы и не превосходящие корня из n. """ from math import sqrt n = int(input()) # целочисленная переменная для ввода def MinDivisor(d_n): """ функция возвращает наименьший делитель числа """ i = 2 # индекс для оператора while while i <= d_n: if d_n % i == 0: return i elif i >= sqrt(d_n): return d_n else: i = i + 1 print(MinDivisor(n))
cb9a30d3530cbcad2e75617f8484b3bbfdaa6793
sailengsi/sls-python-study
/001-test/study_cli.py
390
4.0625
4
''' 初步体验交互式Python编程 ''' print('欢迎来此新世界') username = input('请输入您的用户名:') password = input('请输入您的密码:') if username and password: print('登录成功,您的账号->username,密码是password') else: if not username: print('用户名不能为空') if not password: print('密码不能为空')
6d9a8ef988cb3d88685d06caeddc6dbf1b0eb408
ololo123321/euler
/problems/p071.py
1,052
3.8125
4
""" https://math.stackexchange.com/questions/39582/how-to-compute-next-previous-representable-rational-number https://en.wikipedia.org/wiki/Modular_multiplicative_inverse """ from problems.utils import modinv, log @log def main(): """ Consider the fraction, n/d, where n and d are positive integers. If n<d and HCF(n,d)=1, it is called a reduced proper fraction. If we list the set of reduced proper fractions for d ≤ 8 in ascending order of size, we get: 1/8, 1/7, 1/6, 1/5, 1/4, 2/7, 1/3, 3/8, 2/5, 3/7, 1/2, 4/7, 3/5, 5/8, 2/3, 5/7, 3/4, 4/5, 5/6, 6/7, 7/8 It can be seen that 2/5 is the fraction immediately to the left of 3/7. By listing the set of reduced proper fractions for d ≤ 1,000,000 in ascending order of size, find the numerator of the fraction immediately to the left of 3/7. """ p, q = 3, 7 n = 1000000 r = modinv(p, q) b = n while b % q != r: b -= 1 return (b * p + 1) // q # if p1/q1 < p2/p2, then q1*p2 - q2*p1 = 1 if __name__ == '__main__': main()
5ff11f101a8471a67afd2ccfe6b8d8277e831ed9
bingwin/python
/python/习题/mianshi7.py
627
3.734375
4
# -*- coding: utf-8 -*- # Python中默认的编码格式是 ASCII 格式,在没修改编码格式时无法正确打印汉字,所以在读取中文时会报错。 # 输入两个正整数计算最大公约数和最小公倍数 x = int(input('x = ')) y = int(input('y = ')) if x > y: x, y = y, x for factor in range(x, 0, -1): if x % factor == 0 and y % factor == 0: print('%d和%d的最大公约数是%d' % (x, y, factor)) print('%d和%d的最小公倍数是%d' % (x, y, x * y // factor)) break # s = 10 * 10 // 2 # //取整除 - 返回商的整数部分(向下取整) # print(s)
28f3026db240559cca1c87c70aca4ce9b5316a9f
a01375832/Actividad-04
/calculopago.py
687
3.859375
4
#Encoding:UTF-8 #Autor:Manuel Zavala Gómez #Calculo de pago de un trabajador def main(): normal=int(input("Horas normales trabajadas")) extra=int(input("Horas extra trabajadas")) pago=int(input("Pago por hora normal")) print("Horas normales:",normal) print("Horas extras:",extra) print("Pago por hora:$%.2f"% pago) calcularNormal(normal,pago) calcularExtra(normal,extra,pago) def calcularNormal(normal,pago): a=normal*pago print("Pago semanal normal:$%.2f"% a) def calcularExtra(normal,extra,pago): b=(pago/2)+ pago c= b*extra d= (normal*pago)+c print("Pago semanal extra:$%.3f" % c) print("Pago semanal total:$%.2f"%d) main()
d104d38a59a5866d2cb4c30de4a4cab203c9c49c
SvetlanaTsim/python_basics_ai
/lesson_3_ht/task_3_4.py
1,153
3.8125
4
""" 4. Программа принимает действительное положительное число x и целое отрицательное число y. Необходимо выполнить возведение числа x в степень y. Задание необходимо реализовать в виде функции my_func(x, y). При решении задания необходимо обойтись без встроенной функции возведения числа в степень. Подсказка: попробуйте решить задачу двумя способами. Первый — возведение в степень с помощью оператора **. Второй — более сложная реализация без оператора **, предусматривающая использование цикла. """ #Вариант 1 def my_func(x, y): return round(x ** y, 4) #Вариант 2 def my_func_2(x, y): result = 1 for _ in range(abs(y)): result *= 1 / x return round(result, 4) print(my_func(3.4, -2)) print(my_func_2(3.4, -2))
5814ec32e1c0804f4ad0abeb749483c6a68316df
lkapinova/Pyladies
/05/dp_04.py
2,021
3.90625
4
# Napiš funkci tah_hrace, která dostane řetězec s herním polem, # zeptá se hráče, na kterou pozici chce hrát, # a vrátí herní pole se zaznamenaným tahem hráče. # Funkce by měla odmítnout záporná nebo příliš velká čísla a tahy na obsazená políčka. # Pokud uživatel zadá špatný vstup, funkce mu vynadá a zeptá se znova. def tah(pole, cislo_policka, symbol): "Vrátí herní pole s daným symbolem umístěným na danou pozici" herni_pole = pole[:cislo_policka] + symbol + pole[(cislo_policka+1):] return herni_pole # def tah_hrace(herni_pole): # "Funkce zaznamenava tah hrace do herniho pole a kontroluje vstupni data hrace." # while True: # tvuj_tah = input("Kam chces umistit svuj symbol? ") # if tvuj_tah.isdigit(): # tvuj_tah = int(tvuj_tah) # if tvuj_tah >= 0 and tvuj_tah <= 19: # if herni_pole[tvuj_tah] == '-': # herni_pole = tah(herni_pole, tvuj_tah, 'x') # break #asi tu neni potreba # else: # print("Smula, policko uz je zabrane.") # else: # print("Bohuzel, netrefil ses do herniho pole.") # else: # print("Co delas?! Hrajeme piskovorky! Zkus to znovu.") # return herni_pole def tah_hrace(herni_pole): "Funkce zaznamenava tah hrace do herniho pole a kontroluje vstupni data hrace." while True: tvuj_tah = input("Kam chces umistit svuj symbol? ") if not tvuj_tah.isdigit(): print("Nezadal jsi cislo.") continue tvuj_tah = int(tvuj_tah) if not (0 <= tvuj_tah < len(herni_pole)): print("Bohuzel, netrefil ses do herniho pole.") elif herni_pole[tvuj_tah] != '-': print("Smula, policko uz je zabrane.") else: herni_pole = tah(herni_pole, tvuj_tah, 'x') break return herni_pole print(tah_hrace('-'*20)) print(tah_hrace("----xx----"))
81b3092b3543fb97dc63f006991432044709ed6e
jmontara/become
/Data Structures/Hash Table/hashtable_start.py
621
4.4375
4
# demonstrate hashtable usage # create a hashtable all at once items1 = dict({"key1": 1, "key2" : 2, "key3" : "three"}) print(items1) # create a hashtable progressively items2 = {} items2["key1"] = 1 items2["key2"] = 2 items2["key3"] = 3 print(items2) # access a nonexistant key #print items1["key6"] # replace an items items2["key2"] = "two" print items2 # iterate the keys and values in the dictionary for key in items2.keys(): print "key:", key, "value:", items2[key] # iterate the keys and values in the dictionary, sorted by key for key in sorted(items2.keys()): print "key:", key, "value:", items2[key]
bccdd38a7c6e3acf79ee2e88bdb215d784decbab
AldanaVallejos/Guia-5
/Guia5.Ejercicio6.py
1,111
3.609375
4
#*********************************************************** # Guia de ejercitación nº5 # Fecha: 06/10/21 # Autor: Aldana Vallejos #*********************************************************** # EJERCICIO 6: Desarrollar un procedimiento que imprima una fecha en # formato DD/MM/AA. El dato que recibe es un longint con una fecha en formato aaaammdd. #*********************************************************** # D I S E Ñ O #*********************************************************** # Declaración de variables f=0 def fechas(f): #Defino la función import datetime f=datetime.datetime.strptime(f, '%Y%m%d').date() tiempo=datetime.datetime.strftime(f,'%d/%m/%y') #Cambio el formato de la fecha print("La fecha ingresada en formato DD/MM/AA es: {0}".format(tiempo)) # Salida por pantalla try:# Validación f=int(input("Ingrese una fecha en formato (aaaammdd): ")) #Ingreso de dato except ValueError: print("Error. Ingrese un numero tipo longint") f=int(input("Ingrese una fecha en formato (aaaammdd): ")) f=str(f) fechas(f)
7666e0fd76be260230ac59df4bcb49a056161b0b
spidernik84/udemypybootcamp
/milestone_proj1.py
3,893
4.28125
4
''' Simple TicTacToe implementation ''' import random def display_board(board): print(' | |') print(' ' + board[7] + ' | ' + board[8] + ' | ' + board[9]) print(' | |') print('-----------') print(' | |') print(' ' + board[4] + ' | ' + board[5] + ' | ' + board[6]) print(' | |') print('-----------') print(' | |') print(' ' + board[1] + ' | ' + board[2] + ' | ' + board[3]) print(' | |') test_board = ['#','X','O','X','O','X','O','X','O','X'] # display_board(test_board) def player_input(): marker = '' while not (marker == 'O' or marker == 'X'): marker = input('Please pick X or O: ').upper() if marker == 'X': return ('X', 'O') else: return ('O', 'X') # player_input() def place_marker(board,marker,position): board[position] = marker # place_marker(test_board,'$',8 ) # display_board(test_board) def win_check(board,mark): return ((board[7] == mark and board[8] == mark and board[9] == mark) or # across the top (board[4] == mark and board[5] == mark and board[6] == mark) or # across the middle (board[1] == mark and board[2] == mark and board[3] == mark) or # across the bottom (board[7] == mark and board[4] == mark and board[1] == mark) or # down the middle (board[8] == mark and board[5] == mark and board[2] == mark) or # down the middle (board[9] == mark and board[6] == mark and board[3] == mark) or # down the right side (board[7] == mark and board[5] == mark and board[3] == mark) or # diagonal (board[9] == mark and board[5] == mark and board[1] == mark)) # diagonal print(win_check(test_board,'O')) def choose_first(): if random.randint(0,1) == 0: return 'Player 2' else: return 'Player 1' def check_available(board,position): return board[position] == ' ' def check_board_full(board): for cell in range(0,len(board)): if check_available(board,cell): return False else: return True def player_choice(board): position = 0 while position not in range(1,10) or not check_available(board,position): position = int(input('Choose your next position: (1-9) ')) return position def replay(): return input("Play again? (y/n): ") == "y".lower() # ------------------------- # MAIN # ------------------------- greeting = 'Welcome to TicTacToe' while True: print(greeting) print('-' * len(greeting)) TheBoard = [' '] * 10 game_on = True player1_marker, player2_marker = player_input() turn = choose_first() print(turn + " plays first. Go!") while game_on: if turn == "Player 1": # Player 1 display_board(TheBoard) position = player_choice(TheBoard) place_marker(TheBoard,player1_marker,position) if win_check(TheBoard,player1_marker): display_board(TheBoard) print('You won!') game_on = False else: if check_board_full(TheBoard): display_board(TheBoard) print('The game is a draw...') break else: turn = 'Player 2' else: # Player 2 display_board(TheBoard) position = player_choice(TheBoard) place_marker(TheBoard,player2_marker,position) if win_check(TheBoard,player2_marker): display_board(TheBoard) print('You won!') game_on = False else: if check_board_full(TheBoard): display_board(TheBoard) print('The game is a draw...') break else: turn = 'Player 1' if not replay(): break
bd049ab3ea3b8cb1313ba169c659d1859b4b5fa2
Bertram-Liu/Note
/NOTE/02_PythonBase/day01/code/variable.py
249
3.90625
4
# 练习: # 已知有矩形的长边长为6cm, 短边长为4cm, 求周长和面积 a = 6 # a变量代表长边的长度 b = 4 # b变量代表短边的长度 print("周长是", 2 * (a + b), "厘米") print("面积是:", a * b, "平方厘米")
0bacef1b8a51592327bf9e50e12707bb3b959496
amile/sql
/venicles1.py
297
3.75
4
import sqlite3 conn = sqlite3.connect("cars.db") cursor = conn.cursor() cursor.execute("update inventory set quantity = 2") conn.commit() cursor.execute("select * from inventory where make = 'Ford'") fords = cursor.fetchall() for ford in fords: print ford[0], ford[1], ford[2] conn.close()
6571e1e29c274d206d0edbb6e48da701c7c45a14
tww-software/py_ais_nmea
/pyaisnmea/export.py
6,180
3.953125
4
""" code for the export of data into various file formats """ import csv import json import logging import os import re AISLOGGER = logging.getLogger(__name__) INVALIDDIRCHARSREGEX = re.compile(r'[/\*><:|?"]') def write_json_file(jsonstations, outpath): """ write jsonstations to a json file Args: jsonstations(dict): data to be written to json file outpath(str): full path to write to """ with open(outpath, 'w') as jsonfile: json.dump(jsonstations, jsonfile, indent=2) def write_json_lines(datalist, outpath): """ take a list of dictionaries and write them out to a JSON lines file Note: JSON lines is a text file where each new line is a separate JSON string Args: datalist(list): a list of dictionaries to write out outpath(str): the full filepath to write to """ with open(outpath, 'w') as jsonlines: for jdict in datalist: jsonlines.write(json.dumps(jdict) + '\n') def write_csv_file(lines, outpath, dialect='excel'): """ write out the details to a csv file Note: default dialect is 'excel' to create a CSV file we change this to 'excel-tab' for TSV output Args: lines(list): list of lines to write out to the csv, each line is a list outpath(str): full path to write the csv file to dialect(str): type of seperated values file we are creating """ with open(outpath, 'w') as outfile: csvwriter = csv.writer(outfile, dialect=dialect) csvwriter.writerows(lines) def create_summary_text(summary): """ format a dictionary so it can be printed to screen or written to a plain text file Args: summary(dict): the data to format Returns: textsummary(str): the summary dict formatted as a string """ summaryjson = json.dumps(summary, indent=3) textsummary = re.sub('[{},"]', '', summaryjson) return textsummary def export_overview( aistracker, nmeatracker, aismsglog, outputdir, printsummary=False, orderby='Types', region='A'): """ export the most popular file formats KMZ - map JSON & CSV - vessel details JSONLINES and CSV - AIS message debug - ALL AIS MESSAGES Args: aistracker(ais.AISTracker): object tracking all AIS stations nmeatracker(nmea.NMEAtracker): object to process NMEA sentences aismsglog(allmessages.AISMessageLog): object to log all AIS messages outputdir(str): directory path to export files to printsummary(bool): whether to print a summary to the terminal orderby(str): order the stations by 'Types', 'Flags' or 'Class' default is 'Types' region(str): IALA region 'A' or 'B', default is 'A' """ stnstats = aistracker.tracker_stats() sentencestats = nmeatracker.nmea_stats() summary = create_summary_text({'AIS Stats': stnstats, 'NMEA Stats': sentencestats}) with open(os.path.join(outputdir, 'summary.txt'), 'w') as textsummary: textsummary.write(summary) if printsummary: print(summary) joutdict = {} joutdict['NMEA Stats'] = sentencestats joutdict['AIS Stats'] = stnstats joutdict['AIS Stations'] = aistracker.all_station_info( verbose=False) write_json_file( joutdict, os.path.join(outputdir, 'vessel-data.json')) outputdata = aistracker.create_table_data() write_csv_file( outputdata, os.path.join(outputdir, 'vessel-data.csv')) aistracker.create_kml_map( os.path.join(outputdir, 'map.kmz'), kmzoutput=True, orderby=orderby, region=region) jsonlineslist, messagecsvlist = aismsglog.debug_output() write_json_lines( jsonlineslist, os.path.join(outputdir, 'ais-messages.jsonl')) write_csv_file( messagecsvlist, os.path.join(outputdir, 'ais-messages.csv')) def export_everything( aistracker, aismsglog, outputdir, orderby='Types', region='A'): """ export everything we have on each AIS Station Args: aistracker(ais.AISTracker): object tracking all AIS stations aismsglog(allmessages.AISMessageLog): object to log all AIS messages outputdir(str): directory path to export files to orderby(str): order the stations by 'Types', 'Flags' or 'Class' default is 'Types' region(str): IALA region 'A' or 'B', default is 'A' """ AISLOGGER.info('outputting data for all AIS stations') mmsicatagories = aistracker.sort_mmsi_by_catagory() aisstndir = os.path.join(outputdir, 'AIS Stations') try: os.mkdir(aisstndir) except FileExistsError: pass for catagory in mmsicatagories[orderby]: AISLOGGER.info('processing %s', catagory) try: os.mkdir(os.path.join(aisstndir, catagory)) except FileExistsError: pass for mmsi in mmsicatagories[orderby][catagory]: stnobj = aistracker.stations[mmsi] if stnobj.name != '': foldername = '{} - {}'.format( mmsi, INVALIDDIRCHARSREGEX.sub('', stnobj.name)) else: foldername = mmsi AISLOGGER.info(' processing %s', foldername) mmsipath = os.path.join(aisstndir, catagory, foldername) try: os.mkdir(mmsipath) except FileExistsError: pass stnobj.create_kml_map( os.path.join(mmsipath, 'map.kmz'), kmzoutput=True, region=region) stninfo = stnobj.get_station_info(verbose=True, messagetally=True) write_json_file( stninfo, os.path.join(mmsipath, 'vessel-data.json')) stnobj.create_positions_csv( os.path.join(mmsipath, 'vessel-positions.csv')) msgsjsonlines, msgscsv = aismsglog.debug_output(mmsi=mmsi) write_json_lines(msgsjsonlines, os.path.join(mmsipath, 'ais-messages.jsonl')) write_csv_file(msgscsv, os.path.join(mmsipath, 'ais-messages.csv'))
2f050182c0320cfad901675cfb7e44c005d904f5
daniel-reich/turbo-robot
/AgGWvdPi56x5nriQW_12.py
1,146
4.15625
4
""" Create a function that takes a list of pyramid numbers and returns the maximum sum of consecutive numbers from the top to the bottom of the pyramid. /3/ \7\ 4 2 \4\ 6 8 5 \9\ 3 # Longest slide down sum is 3 + 7 + 4 + 9 = 23 ### Examples longest_slide([[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]) ➞ 23 longest_slide([[1], [2, 3], [4, 5, 6], [7, 8, 9, 10]]) ➞ 20 longest_slide([[2], [9, 4], [1, 8, 7], [6, 4, 7, 2]]) ➞ 26 ### Notes N/A """ def merge(a, b): int_len = max(len(a), len(b)) arr_res = [] for idx, item in enumerate(b): idx_upper_1 = idx-1 if idx -1 >= 0 else idx idx_upper_2 = idx if idx <= len(a)-1 else idx-1 arr_res.append(max(item + a[idx_upper_1], item + a[idx_upper_2])) return arr_res ​ def longest_slide(pyramid): if len(pyramid) == 1: return pyramid[0][0] temp = merge(pyramid[0], pyramid[1]) for i in range(2,len(pyramid)): temp = merge(temp, pyramid[i]) return max(temp)
b776e18de7a0c45485411a03534292da780c9f83
jasonjiexin/Python_Basic
/magedu/jiexishi/List_comprehension.py
4,740
4.28125
4
#!/usr/bin/env python # coding: utf-8 # jason # ## 解析式 # 作用:解析式和生成器都是python特有的两个特性,他们能够帮助优化程序,大大减少代码的数量. # ### 1.生成一个列表,列表0~9,对每一个元素自增1后求平方返回新的列表 # In[31]: # 一般的写法 lst1 = list(range(10)) lst2 = [] for i in range(10): lst1[i] += 1 square_num = lst1[i]**2 lst2.append(square_num) print(lst2) print(lst1) # In[32]: # 根据规律简化代码 lst1 = list(range(10)) lst2 = [] for i in lst1: lst2.append((i+1)**2) print(lst2) # In[33]: # 解析式写法 lst1 =list(range(10)) lst2 = [(i+1)**2 for i in lst1] print(lst1) print(lst2) # **注:能用列表解析式就用列表解释式,这种写法更加python** # **注:[ 返回值 for 元素 in 可迭代对象 [if条件] ]** # # ### 2.获取10 以内的偶数,比较执行效率 # In[34]: # 普通写法 even = [] for x in range(10): if x % 2 == 0: even.append(x) print(even) # 列表解析式写法 even = [] even = [x for x in range(10) if x % 2 == 0] print(even) # print 没有返回值 even = [] even = [print(x) for x in range(10) if x % 2 == 0] # print((x) 是没有返回值的 print(even) # print 没有返回值 # ### 3. 获取20以内的偶数,并且打印3的倍数. 获取20以内的偶数,并且打印不是3的倍数. # In[35]: even = [i for i in range(20) if i % 2 == 0 or i % 3==0] print(even) even = [i for i in range(20) if i % 2 == 0 or not i % 3==0] print(even) # ### 4.获取20以内能被2整除也能被3整除的数字 # # 注:语法2 # [ expr for item in iterable if cond1 if cond2 ] # 等价于 # ret = [] # for item in iterable: # if cond1: # if cond2: # ret.append(expr) # In[36]: # 一下两种表达方式表达的逻辑是一致的,and等于两个if even = [i for i in range(20) if i % 2 == 0 and i %3 == 0] print(even) even = [i for i in range(20) if i % 2 == 0 if i %3 == 0] print(even) # [expr for i in iterable1 for j in iterable2] # 等价于 # ret = [] # for i in iterable1: # for j in iterable2: # ret.append(expr) # In[37]: # tuple 嵌套在列表中 [(x,y) for x in 'abcde' for y in range(3)] # 字典嵌套在列表中 [{x,y} for x in 'abcde' for y in range(3)] # 列表嵌套在列表中 [[x,y] for x in 'abcde' for y in range(3)] # In[38]: # 以下三种方法表达的意义结果一致 # 每个 for 都做好 if 判断 [(i,j) for i in range(7) if i>4 for j in range(20,25) if j >23] # 先写for,之后再做判断 [(i,j) for i in range(7) for j in range(20,25) if i>4 if j > 23] # 先写for,之后再判断,if cond1 and cond2 等同于 if cond1 if cond2 [(i,j) for i in range(7) for j in range(20,25) if i>4 and j>23] # ### 5.返回1-10平方的列表 # In[39]: [i**2 for i in range(10)] # ### 6.有一个列表lst=[1,4,9,16,2,5,10,15],生成一个新列表,要求新列表元素是lst相邻2项的和 # In[40]: lst = [1,4,9,16,2,5,10,15] lst_length = len(lst) [lst[i]+lst[i+1] for i in range(lst_length-1)] # ### 7.打印九九乘法表 # In[41]: ["{}*{}={}".format(i,j,i*j) for i in range(1,10) for j in range(1,10) if i<=j] # In[3]: # 'String1'.join('String2'),九九乘法表的横向构造 # 列表套列表的方式实现 print('\n'.join([' '.join(['%s*%s=%-3s' %(x,y,y*x) for x in range(1,y+1)]) for y in range(1,10)])) # In[1]: # ()'\n' if i==j else ' '),三目运算符的写法 [print('{}*{}={:<3}{}'.format(j,i,j*i,'\n' if i==j else ' '),end="") for i in range(1,10) for j in range(1,10)] # ### 8.生成如下格式的ID号,“0001.abadicddws” # In[18]: import random #代码拆解 bytes(range(97,123)).decode() # 获取 26个英文字母 [random.choice(bytes(range(97,123)).decode())] # 在26个英文字母中随机获取一个字符 # 在26个英文字母中随机获取一个字符 ,取10次,但是获取后的格式不是需要的 ['b', 't', 'q', 'z', 'i', 'd', 'o', 'k', 'o', 'g'] [random.choice(bytes(range(97,123)).decode()) for _ in range(10)] # 用 join() 函数格式化字符串 (''.join([random.choice(bytes(range(97,123)).decode()) for _ in range(10)])) # 这种写法只是关注次数,但是每一次的值并不关心 # for _ in range(10) # {:04} 四位有效数字,不够用0填充,系统默认就是右对齐 ['{:04}.{}'.format(n,''.join([random.choice(bytes(range(97,123)).decode()) for _ in range(10)])) for n in range(1,101)] # In[24]: import random # 生成随机数random函数有很多的方法 chr(random.randint(97,122)) ['{:04}.{}'.format(i,"".join([chr(random.randint(97,122)) for _ in range(10)]))for i in range(1,101)]
500e5edfe531d04caad8d222a50aaf2e7ab05ee5
FedorAglyamov/Chemical-Equation-Balance
/ChemicalEquationBalance.py
7,306
4.0625
4
# Simple program for balancing chemical equations # v0.9 # Imports import numpy as np from scipy import linalg from fractions import Fraction import re import sys # Declare constants SEPERATOR = "=" TUTORIAL_MSG = "Please seperate left/right side of equation with '=' char, " \ "and expand components like (OH)3 to O3H3." BARS = "\n-------------------------------------------------------------------" ATTEMPT_BAL_MSG = "\n*** Attempted Balance with {}***" # Main function running program def main(): print(TUTORIAL_MSG) while True: print(BARS) # Find balanced equation reaction = get_reaction() coeff_matrix = build_coeff_matrix(reaction) print(coeff_matrix) frac_coeffs, coeffs = solve_coeff(coeff_matrix) print(ATTEMPT_BAL_MSG.format("Fraction Coefficients")) print_eq(reaction, frac_coeffs) print(ATTEMPT_BAL_MSG.format("Whole Coefficients")) print_eq(reaction, coeffs) # Confirm whether user would like to balance more equations if (not more_eq()): break # Get user's input for chem equation and do some basic error checking def get_reaction(): # Initialize vars user_input = direction = "" reaction = [] sides = [] cur_side = [] cur_elems = [] side_elems = [] elems = [] # While user equation does not have two sides while True: user_input = input("\nPlease input reaction: ") # If user passes an equation if (user_input.count(SEPERATOR) == 1): # Get reaction and sides reaction = list(filter(None, re.split(r"\s|\+|(" + SEPERATOR + ")", user_input))) direction = re.findall(r"" + SEPERATOR, user_input) sides = list(filter(None, re.split(r"" + SEPERATOR, user_input))) # Find elems present on left and right side of reaction for i in range(2): cur_side = sides[i] cur_elems = re.findall(r"[A-Z][a-z]?", cur_side) # If this is left side, record order of elems if i == 0: elems = list(dict.fromkeys((filter(None, cur_elems)))) cur_elems = set(elems) else: cur_elems = set(filter(None, cur_elems)) side_elems.append(cur_elems) sides[i] = list(filter(None, re.split(r"\s|\+", cur_side))) # If left and right side of reaction have matching elems if side_elems[0] == side_elems[1]: reaction = Reaction(reaction, direction, sides[0], sides[1], elems) break; error_msg("Invalid input") return reaction # Build coefficient matrix for user chem equation def build_coeff_matrix(reaction): # Initialize vars elems = reaction.get_elems() num_elems = len(elems) num_left_compounds = len(reaction.get_left()) num_compounds = len(reaction.get_reaction()) - 1 coeff_matrix = np.zeros((num_elems, num_compounds)) compound_count = 0; cur_elems = [] elem = "" elem_info = [] sub_coeff = 0; row = 0; # Iterate through compounds in reaction for compound in reaction.get_reaction(): # If current compound is an actual compound if (compound != SEPERATOR): cur_elems = re.findall(r"[A-Z][a-z]?[\d]*", compound) # Iterate through elems in current compound for elem in cur_elems: elem_info = list(filter(None, re.split(r"(\d+)", elem))) # Find corresponding coeff if len(elem_info) == 1: sub_coeff = 1; else: sub_coeff = int(elem_info[1]) # If elem on right side, multiply coeff by -1 if compound_count >= num_left_compounds: sub_coeff *= -1 # Update coeff in coeff matrix row = elems.index(elem_info[0]) coeff_matrix[row, compound_count] += sub_coeff compound_count += 1 # Iterate first half of equation return coeff_matrix # Solve coeff matrix for coeffs, return fraction and whole number lists def solve_coeff(coeff_matrix): # Initialize vars coeff = 0 cur_frac = 0 base_coeffs_frac = [] temp_coeffs = [] coeffs = [] try: # Find null space of coeff matrix, basis serves as basic coeffs base_coeffs = linalg.null_space(coeff_matrix) print(base_coeffs) # Convert float coeffs to fractions for coeff in base_coeffs: cur_frac = Fraction(float(coeff)).limit_denominator() base_coeffs_frac.append(cur_frac) # Attempt to remove fractions from coeff matrix min_val = base_coeffs.min() temp_coeffs = ((1 / min_val) * base_coeffs) for coeff in temp_coeffs: coeffs.append(coeff[0]) except: error_msg("Equation could not be balanced") input(">>> Press <Enter> to exit program ") sys.exit() return (base_coeffs_frac, coeffs) # Print resultant chem equation with proper coefficients def print_eq(reaction, coeffs): # Initialize vars reaction_sections = reaction.get_reaction() coeff_indx = 0 # Iterate through compounds in reaction for compound in reaction_sections: # If current compound is an acutal compound if compound != SEPERATOR: print(str("({})".format(coeffs[coeff_indx])), end ="") coeff_indx += 1 print(compound, end = " ") print() # Return whether user would like to balance more equations def more_eq(): response = input("\nWould you like to balance another " \ "equation? (y / n): ").lower() result = True if response == "y" else False return result # Print simple invalid input error def error_msg(msg): print(">>> Error: {}".format(msg)) # Equation class storing info on reaction class Reaction: # Equation constructor def __init__(self, reaction, direction, left, right, elems): self.direction = direction self.reaction = reaction self.left = left self.right = right self.elems = elems # Return raw reaction data def get_reaction(self): return self.reaction # Return direction of reaction def get_direction(self): return self.direction # Return left side of reaction def get_left(self): return self.left # Return right side of reaction def get_right(self): return self.right # Return elems involved in reaction def get_elems(self): return self.elems # String representation of reaction def __str__(self): format_str = "Reaction: {}\nDirection: {}\nLeft: {}\nRight: {}\nElems: {}" return format_str.format(self.reaction, self.direction, self.left, self.right, self.elems) # Run main function main()
22e1f3adb516f559cde7862cf775cf356b59f3b4
ashokmoorthi/Personal_Python_Learning
/Ram_Scenarios/R1_To_Match_String.py
741
4.09375
4
''' Ram scenario One: 1) Get input from user (String alone) 2) Check the characters in the string and see if you can form the word "idirect" 3) If yes print iDirect 4) Else print Not a valid Input 5) Later update it to get both inputs from user 6) Print the reuslts''' import sys input_text_string = input('Please Enter the String: ') print('Your input String:', input_text_string) Tobecomaprestring = input('Please Enter the sub string to check part of the String: ') for character in Tobecomaprestring: if Tobecomaprestring.count(character) > input_text_string.count(character): print ("Is Not a Valid String") sys.exit() print (Tobecomaprestring + " is sub string of the first string provided: " +input_text_string)
c69618f688f5a39895c5becb913500426dd16390
stevenluk/Advanced-Data-Storage-and-Retrieval
/app.py
4,350
3.578125
4
import numpy as np import sqlalchemy import datetime as dt from sqlalchemy.ext.automap import automap_base from sqlalchemy.orm import Session from sqlalchemy import create_engine, func from flask import Flask, jsonify # Database Setup engine = create_engine("sqlite:///hawaii.sqlite") # reflect an existing database into a new model Base = automap_base() # reflect the tables Base.prepare(engine, reflect=True) # Save reference to the table measurement= Base.classes.measurement station=Base.classes.station # Create our session (link) from Python to the DB session=Session(engine) # Flask Setup app = Flask(__name__) # Define what to do when a user hits the index route @app.route("/") def welcome(): return ( # print out all available routes and information about each route f"Available Routes:<br/>" f"<br>" f"/api/v1.0/precipitation<br/>" f"- List of precipitation information from previous year of all stations<br/>" f"<br>" f"/api/v1.0/stations<br/>" f"- List of Information of all stations<br/>" f"<br>" f"/api/v1.0/tobs<br/>" f"- List of temperature information from previous year of the most active station<br/>" f"<br>" f"/api/v1.0/start<br/>" f"- Temperature information from start date of all stations <br/>" f"- Enter date information as Y-M-D<br/>" f"<br>" f"/api/v1.0/start/end<br/>" f"- Temperature information from start date to end date of all stations<br/>" f"- Enter date information as Y-M-D<br/>" ) # Define what to do when a user hits the /api/v1.0/precipitation route @app.route("/api/v1.0/precipitation") def precipitation(): #calculate of date one year before the last day lastyear=dt.date(2017,8,23)-dt.timedelta(days=365) #query the date and precipitation information in the previous year scores=session.query(measurement.date,measurement.prcp).filter(measurement.date>=lastyear).all() #store information in a list rain=[] for score in scores: rain_dict = {} rain_dict["Date"] = score[0] rain_dict["Prcp"] = score[1] rain.append(rain_dict) return jsonify(rain) # Define what to do when a user hits the /api/v1.0/stations route @app.route("/api/v1.0/stations") def Station(): #get station information stations=session.query(measurement.station,station.name,station.latitude,station.longitude,station.elevation).\ filter(measurement.station==station.station).group_by(measurement.station).all() return jsonify(stations) # Define what to do when a user hits the /api/v1.0/tobs route @app.route("/api/v1.0/tobs") def tobs(): #calculate of date one year before the last day lastyear=dt.date(2017,8,23)-dt.timedelta(days=365) #find the most active station station_active=session.query(measurement.station,func.count(measurement.tobs)).group_by(measurement.station).order_by(func.count(measurement.tobs).desc()).all() #get temperature information from previous year temp=session.query(measurement.date,measurement.tobs).filter(measurement.station==station_active[0][0]).filter(measurement.date>=lastyear).all() #store information in a list tep=[] for t in temp: row2 = {} row2["Date"] = t[0] row2["Temp"] = t[1] tep.append(row2) return jsonify(tep) # Define what to do when a user hits the /api/v1.0/<start> route @app.route("/api/v1.0/<start>") def date(start): #find information of min, avg and max temp after the start date temp_data = session.query(func.min(measurement.tobs), func.avg(measurement.tobs), func.max(measurement.tobs)).\ filter(measurement.date >= start).all() return jsonify(temp_data) # Define what to do when a user hits the /api/v1.0/<start>/<end> route @app.route("/api/v1.0/<start>/<end>") def date2(start,end): #find information of min, avg and max temp within the start and end date temp_data2 = session.query(func.min(measurement.tobs), func.avg(measurement.tobs), func.max(measurement.tobs)).\ filter(measurement.date >= start).filter(measurement.date<=end).all() return jsonify(temp_data2) #run the app if __name__ == "__main__": app.run(debug=True)
ac2eecea1e53f97284eb08069c6e24b6975d7b14
Yaciukdh/RandomPythonCode
/tutorialPy/lesson2.py
2,013
4.28125
4
# Lesson two: libraries and functions import time def func1(): print("This function prints some lines") print("Functions are reusable pieces of code") print("Sometimes they make code more readable") def sumasafunction(begin, end, timeStep): sum = 0 for x in range(begin, end, timeStep): sum = sum+x return sum def weirdprint(printable): print("You are in weird print! A weird print you can pass stuff to!") if type(printable) is int: print("You entered a integer!") print("printable is equal to: " + str(printable)) elif type(printable) is str: print("You entered a string!") print("printable is equal to: " + printable) else: print("what are ya doin? Passing a non int or string? what am I, a mind reader? ") print("") if __name__ == "__main__": print("") time.sleep(1) print("import statements brings libraries into the program that you can use") time.sleep(1) print("time.wait() lets the program wait for a specified amount of time") print("") time.sleep(1) print("the program waited 1 second to print!") print("") time.sleep(1) print("Now we get to functions.") # FUNCTIONS time.sleep(1) func1() print("You don't need input for a function.") cool = sumasafunction(0, 5, 1) print("You can return a result!") print(cool) print("You can reuse code as necessary!") cool = sumasafunction(0, 7, 2) print(cool) print("You can do crazier things too.") print("") weirdprint("Bagel.") weirdprint(sumasafunction(0, 5, 1)) weirdprint(1.1) time.sleep(1) #IF, ELSE IF. ELSE print("type() is for type checking, you can run functions inside functions so you're not storing anything in a var,") print("and elif means else if. The chain is if, then elif until else which handles weird cases.") print("") time.sleep(2) print("Stuff is dope. Wait until classes.") time.sleep(3)
6cd54f904b2b2f5fbb2e6742ad20861c28eaf437
a2aniket/Python-3
/DataSience Project/Predict_customer_Will_Leave_the-Bank/Predict_customer_Will_Leave_the-Bank-master/Bank_customerPredict.py
1,954
3.953125
4
# Importing the libraries import numpy as np import matplotlib.pyplot as plt import pandas as pd # Importing the dataset dataset = pd.read_csv('BankCustomers.csv') X = dataset.iloc[:, 3:13].values y = dataset.iloc[:, 13].values # convert categorical feature into dummy variables states=pd.get_dummies(X['Geography'],drop_first=True) gender=pd.get_dummies(X['Gender'],drop_first=True) #concatenate the remaining dummies columns X=pd.concat([X,states,gender],axis=1) #drop the columns as it is no longer required X=X.drop(['Geography','Gender'],axis=1) # Splitting the dataset into the Training set and Test set from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0) # Feature Scaling from sklearn.preprocessing import StandardScaler sc = StandardScaler() X_train = sc.fit_transform(X_train) X_test = sc.transform(X_test) # Importing the Keras libraries and packages import keras from keras.models import Sequential from keras.layers import Dense # Initialising the ANN classifier = Sequential() # Adding the input layer and the first hidden layer classifier.add(Dense(activation="relu", input_dim=11, units=6, kernel_initializer="uniform")) # Adding the second hidden layer classifier.add(Dense(activation="relu", units=6, kernel_initializer="uniform")) # Adding the output layer classifier.add(Dense(activation="sigmoid", units=1, kernel_initializer="uniform")) # Compiling the ANN classifier.compile(optimizer = 'adam', loss = 'binary_crossentropy', metrics = ['accuracy']) # Fitting the ANN to the Training set classifier.fit(X_train, y_train, batch_size = 10, nb_epoch = 100) # Predicting the Test set results y_pred = classifier.predict(X_test) y_pred = (y_pred > 0.5) # Making the Confusion Matrix from sklearn.metrics import confusion_matrix,accuracy_score cm = confusion_matrix(y_test, y_pred) accuracy=accuracy_score(y_test,y_pred)
71987b0a1c367ddc7bc5e63a166fcf253461cd86
swapnil-sat/webwing-code
/ManthanBore/Collections/str_strip.py
135
3.546875
4
# str=" Rohit " # print("before=",str) # print("after=",str.strip()) # print("after=",str.rstrip()) # print("after=",str.lstrip())
8670f4319e7e2037f9c69314009143487e43dd5a
barshan23/snakeGame
/snake.py
2,947
3.578125
4
import pygame,random pygame.init() # WHITE = (255,255,255) BLACK = (0,0,0) RED = (255,0,0) display_height = 600 display_width = 800 FPS = 20 blockSize = 10 gameDisplay = pygame.display.set_mode((display_width,display_height)) pygame.display.set_caption("Snake") pygame.display.update() clock = pygame.time.Clock() font = pygame.font.SysFont(None, 25) def showMessage(msg,color): w,h = font.size(msg) textScreen = font.render(msg, True, color) gameDisplay.blit(textScreen, [(display_width/2)-(w/2), (display_height/2)-(h/2)]) def snake(blockSize, snakeList): for x,y in snakeList: pygame.draw.rect(gameDisplay, BLACK, [x,y,blockSize,blockSize]) def gameLoop(): gameExit = False gameOver = False lead_x, lead_y = display_width/2,display_height/2 lead_x_change = 0 lead_y_change = 0 score = 0 snakeList = [] snakeLength = 1 randAppleX = round(random.randrange(0, display_width-blockSize)/10.0)*10.0 randAppleY = round(random.randrange(0, display_height-blockSize)/10.0)*10.0 while not gameExit: while gameOver == True: gameDisplay.fill(WHITE) showMessage("Score is "+str(score)+" Game Over! Press C to play again, Q to quit game",RED) pygame.display.update() for event in pygame.event.get(): if event.type == pygame.QUIT: gameOver = False gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_q: gameExit = True gameOver = False if event.key == pygame.K_c: gameOver = False gameLoop() for event in pygame.event.get(): if event.type == pygame.QUIT: gameExit = True if event.type == pygame.KEYDOWN: if event.key == pygame.K_LEFT and lead_x_change == 0: lead_x_change = -blockSize lead_y_change = 0 if event.key == pygame.K_RIGHT and lead_x_change == 0: lead_x_change = blockSize lead_y_change = 0 if event.key == pygame.K_UP and lead_y_change == 0: lead_y_change = -blockSize lead_x_change = 0 if event.key == pygame.K_DOWN and lead_y_change == 0: lead_y_change = blockSize lead_x_change = 0 if lead_x >= display_width or lead_x < 0 or lead_y >= display_height or lead_y < 0 : gameOver = True lead_x += lead_x_change lead_y += lead_y_change gameDisplay.fill(WHITE) pygame.draw.rect(gameDisplay, RED, [randAppleX, randAppleY, blockSize, blockSize]) snakHead = [] snakHead.append(lead_x) snakHead.append(lead_y) snakeList.append(snakHead) if len(snakeList) > snakeLength: del snakeList[0] for eachSegment in snakeList[:-1]: if eachSegment == snakHead: gameOver = True snake(blockSize, snakeList) pygame.display.update() if lead_x == randAppleX and lead_y == randAppleY: randAppleX = round(random.randrange(0, display_width-blockSize)/10.0)*10.0 randAppleY = round(random.randrange(0, display_height-blockSize)/10.0)*10.0 snakeLength +=1 score +=1 clock.tick(FPS) pygame.quit() quit() gameLoop()
c1539856fc613119684c63097432783ad7110772
zranguai/python-learning
/day23/08 作业.py
3,803
4.09375
4
# 8点之前 统计作业完成度,难点 # 作业笔记 # 写每一个题的用时 # 遇到的问题 # 解决思路 #第一大题 : 读程序,标出程序的执行过程,画出内存图解,说明答案和为什么 # 请不要想当然,执行之后检查结果然后再确认和自己的猜想是不是一致 # (1) # class A: # Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的 # def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的 # self.name = name # self.age = age # def func1(self): # print(self) # # a = A('alex',83,'印度') # b = A('wusir',74,'泰国') # A.Country = '英国' # a.Country = '日本' # print(a.Country) # 日本 # print(b.Country) # 英国 # print(A.Country) # 英国 # (2) # class A: # Country = ['中国'] # 静态变量/静态属性 存储在类的命名空间里的 # def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的 # self.name = name # self.age = age # def func1(self): # print(self) # # a = A('alex',83,'印度') # b = A('wusir',74,'泰国') # a.Country[0] = '日本' # print(a.Country) # ['日本'] # print(b.Country) # ['中国'](看错题) # print(A.Country) # ['中国'](看错题) # (3) # class A: # Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的 # def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的 # self.name = name # self.age = age # self.Country = country # def func1(self): # print(self) # # a = A('alex',83,'印度') # b = A('wusir',74,'泰国') # A.Country = '英国' # a.Country = '日本' # print(a.Country) # 日本 # print(b.Country) # 泰国 # print(A.Country) # 英国 # (4) 有点疑问 # class A: # Country = '中国' # 静态变量/静态属性 存储在类的命名空间里的 # def __init__(self,name,age,country): # 绑定方法 存储在类的命名空间里的 # self.name = name # self.age = age # def Country(self): # return self.Country # # a = A('alex',83,'印度') # b = A('wusir',74,'泰国') # print(a.Country) # 中国(0x000002D59353D388) # print(a.Country()) # 中国 (0x000002D59353D388) # 第二大题:基于圆形类实现一个圆环类,要求接收参数 外圆半径和内圆半径 # 完成方法 :计算环形面积和环形周长(公式自己上网查) # 要求,借助组合,要求组合圆形类的对象完成需求 # from math import pi # class Circle: # def __init__(self, r): # self.r = r # def area(self): # return pi * self.r**2 # def perimeter(self): # return 2 * pi * self.r # # class Ring: # def __init__(self, outer_r, inner_r, circle): # self.outer_r = outer_r # self.inner_r = inner_r # self.circle = circle # def area1(self): # return self.circle(self.outer_r).area() - self.circle(self.inner_r).area() # # circle1 = Circle(5) # circle = Circle(3) # ring = Ring(5, 3, circle) # print(ring.area1()) # 重做 from math import pi class Circle: def __init__(self, r): self.r = r def area(self): return pi * self.r**2 def perimeter(self): return 2 * pi * self.r class Ring: def __init__(self, inner_r, outer_r): self.inner_r = Circle(inner_r) self.outer_r = Circle(outer_r) def area(self): return self.outer_r.area() - self.inner_r.area() def perimeter(self): return self.outer_r.perimeter() + self.inner_r.perimeter() ring = Ring(3, 5) print(ring.area()) print(ring.perimeter()) # 第三大题:继续完成计算器和优化工作 # 为什么要用组合
b9dbd8e5bb1cd3d9b258432a02e2cd4e62bfeb15
kaoru-kitajima/titanic
/pythonlearning.py
2,327
3.828125
4
words = ["start", "middle", "end"] #slice print(words[0:2]) #0~1までのlistを返す # for for wd in words: print(wd) else: # forが終わったあとに呼ばれる。 print("finished") for i, wd in enumerate(words): if i >= 2: print("too much!") break # for文から抜けてelseに飛ぶ if wd == "start": print("this is start") continue # for文の次のループに飛ぶ print(wd) else: print("finished") #for文のiterableをfor文の中で編集するようなプログラムを書く際には # コピーを撮っておかないと困ることがある。そんなとき for i, wd in enumerate(words[:]):#sliceの[:]ですべてを含むコピーを生成する words.insert(2, words.pop(2)) #popで抜き出したものをinsertで挿入する print(words) # print関数などが返す値はNone print(print()) # 関数の引数 def ask_ok( prompt: str, retries: int = 4, reminder: str = "Please Try Again!" ) -> bool: # 型ヒントはこう書く """Simple console ask yes or no. Raises: ValueError -- raise when run out of retries Returns: bool -- user response """ while True: ok = input(prompt) if ok in ("y", "ye", "yes"): return True if ok in ("n", "no", "nop", "nope"): return False retries = retries - 1 if retries < 0: raise ValueError("Invalid user respose") print(reminder) #呼び出し。オプション引数は名前を指定して代入できる。 #オプションでない変数は順番を入れ替えられないので気をつける ask_ok("Are You Human?", reminder="input again!") #*args: tupleとして任意の数の引数を受け取る。 #**kwargs: dictionaryとして任意の数の引数を受け取る def printstr(arg, *args, **kwargs): print(arg) (print(a) for a in args) #printの返り値Noneのgenerator型が生成される事になってしまう map(print, args) #printの返り値Noneのgenerator型が生成される事になってしまう for a in args: print(a) #これで出力される。 for x in kwargs:#dict型。 print("{0}:{1}".format(x, kwargs[x])) printstr("example", "a", "b", "c", x = "cost", y = "sint")
f8d3b508efb0f1bfacc0169566a19b82d62432d2
S1AG0N/python_codes
/Play_Rock_Paper_Scissors_With_Computer.py
1,464
4.21875
4
import random # use randint to make the computer make a choice ran_num = random.randint(0, 2) # Human Choice human = input("Please Enter your choice against the computer! ::").lower() # Validate Human Input if human not in ("rock", "paper", "scissors"): print("Please input either 'rock' 'paper' or 'scissors' ") # human = input("Please Enter your choice against the computer! ::").lower() # Game Logic elif ran_num == 0: computer_option = "rock" # human = input("Please Enter your choice against the computer! ::").lower() print("Computer choice is: " + computer_option) if human == "rock": print("Its a tie") elif human == "scissors": print("Computer Wins") elif human == "paper": print("Human Wins!!") elif ran_num == 1: computer_option = "paper" # human=input("Please Enter your choice against the computer! ::").lower() print("Computer choice is: " + computer_option) if human == "rock": print("Computer Wins") elif human == "scissors": print("Human Wins") elif human == "paper": print("Its a Tie!!") else: computer_option = "scissors" # human = input("Please Enter your choice against the computer! ::").lower() print("Computer choice is: " + computer_option) if human == "rock": print("Human Wins") elif human == "scissors": print("Its a Tie!!") elif human == "paper": print("Computer Wins!!")
6995963f0407e57fb3d46009c0ea3f62f37abea7
waredeepak/python_basic_beginners_programs
/in.python.basic/AverageCalculator.py
402
3.96875
4
print("Enter marks obtained in 5 subjects: "); m1 = input(); m2 = input(); m3 = input(); m4 = input(); m5 = input(); mark1 = int(m1); mark2 = int(m2); mark3 = int(m3); mark4 = int(m4); mark5 = int(m5); sum = mark1 + mark2 + mark3 + mark4 + mark5; average = sum/5; percentage = (sum/500)*100; print("out of 500 ",sum); print("Average Marks = ", average); print("Percentage Marks = ", percentage,"%");
5fdf526131ad0456fe24d7ee5566c6d0eccd61cd
rosrez/python-lang
/06-iteration/for-enumerate.pl
262
4.15625
4
#!/usr/bin/env python list = [2, 4, 6, 8, 10]; print "Iteration using enumerate to get index" for i,n in enumerate(list): # enumerate(s), where s is a sequence, returns a tuple (index, item) print "squares[%d] = %d**2 = %d" % (i, n, 2**n)
b7532900c8444144cdb24fa2e8e2053f4189f619
StewartCB/math
/arrayInfo.py
1,146
3.625
4
arr = [] l = input("Input number of items: ") for i in range(0, l): arr.append(1.0 * input("Item " + str(i) + " = ")) i = i + 1 print " " arr.sort() sum = 0.0 #Average / Mean for o in range(0, len(arr)): sum = sum + arr[o] print ("Sum = " + str(sum)) print ("Average = " + str(sum/(len(arr) ))) #Median if len(arr) % 2 == 0: print ("Median = " + str((arr[len(arr)/2] + arr[len(arr)/2 - 1])/2)) else: print ("Median = " + str(arr[len(arr)/2])) #mode most = 0 numMode = 0 poses = [] for x in range (0, len(arr)): count = 0 check = 0 for y in range(len(arr)): if arr[y] == arr[x]: count = count + 1 if count > most: most = count pos = x numMode = 1 poses.append(pos) elif count == most: for b in range(0, len(poses)): if arr[poses[b]] == arr[x]: check = check + 1 if check == 0: poses.append(x) numMode = numMode + 1 if most == 1: print ("No mode") elif numMode == 1: print ("Mode = " + str(arr[pos])) else: finText = "Mode = " for p in range(0, len(poses)): if p == len(poses) - 1: finText = finText + str(arr[poses[p]]) else: finText = finText + str(arr[poses[p]]) + " & " print finText
2bfde1b4f424d9d874a792d6abbdb96a61c54500
eds8531/Leitner_Notes
/Leitner-Notes-Dict.py
6,574
3.890625
4
import random import shelve import datetime from datetime import timedelta, datetime, date # is a function for developers only and will not be in the finished program. It resets the shelf file where words are saved to a blank list. # Creates an empty list and sends it to 'fcdata' def init(): sure = input("Are you sure you want to recreate the shelf file (y/n)? ") if sure.lower()[0] == 'y': shelfFile = shelve.open('fcdata') output = [] shelfFile['output'] = output shelfFile.close() main() else: main() # Another developer function that I use to run various tasks. Not part of the final program. def six(): shelfFile = shelve.open('fcdata') output = shelfFile['output'] for card in output: card[2] = card[2] + timedelta(days = -1) print(card[2]) shelfFile['output'] = output shelfFile.close() main() # A method that adds words and definitions from 'Notes1.txt' to the shelfFile output list # Takes list of dictionaries from 'fcdata' # Takes data from .txt file # Produces list with new dictionaries added. def update(): notes_source = input('Enter notes file name: ') filename = '/Users/ericschlosser/Desktop/Notes/' + notes_source + '.txt' l = 0 shelfFile = shelve.open('fcdata') output = shelfFile['output'] with open(filename) as file_object: lines = file_object.readlines() # Creates list of values within each card. # list[0] = item # List[1] = definition # list[2] = datetime date // This is the date the card will next be used. # list[3] = Number of consecutive right answers # list[4] = binary state that shows if the card has been used today for line in lines: if line[0] == '@': subject = line[1:] if line[0] == '!': l += 1 card = line.split('--') card[0] = card[0][1:] card = card[:2] print(card[0] + ' - ' + card[1]) #Add code to deal with duplcates term_dict = {} term_dict['term'] = card[0] term_dict['subject'] = subject term_dict['definition'] = card[1] term_dict['date'] = date.today() term_dict['consecutive right'] = 0 term_dict['card used'] = 0 output.append(term_dict) shelfFile['output'] = output shelfFile.close() print('\n\nUpdate Sucessful.\n\n') print(str(l) + ' new cards added.') main() # Prints a list of today's words and definitions. #Change to accomodate different subjects. def print_list(): shelfFile = shelve.open('fcdata') print("\n\n\nLIST OF TODAY'S WORDS\n\n\n") row = "{:15}: {:60}" word_list_today = shelfFile['output'] #print(type(word_list_today)) #print(word_list_today) for card in shelfFile['output']: if card['date'] <= date.today(): print(row.format(card['term'], card['definition'])) shelfFile.close() main() # Quizes user with that day's flashcards. def fc(): word_list_today = [] word_list_future = [] shelfFile = shelve.open('fcdata') word_list = shelfFile['output'] #print(word_list) for card in word_list: card['card used'] = 0 #for key in card: #print(key) #card[key]['card used'] = 0 #card.get('card used') = 0 for card in word_list: if card['date'] <= date.today(): word_list_today.append(card) else: word_list_future.append(card) print("There are " + str(len(word_list_today)) + " words in today's word list.") while len(word_list_today) > 0: #print(word_list_today[0]) print('Subject: ' + word_list_today[0]['subject']) print(word_list_today[0]['term'] + '\n\n') answer = input('Enter definition: ') print('\n\n' + word_list_today[0]['definition'] + '\n\n') card = word_list_today.pop(0) correct = input(' Did you get the question right or wrong or have you mastered the concept (type r, w, m or q)? ') if correct[0].lower() == 'r': if card['card used'] == 0: card['card used'] += 1 card['consecutive right'] += 1 card['date'] = date.today() + timedelta(days = card['consecutive right'] * 2) word_list_today.append(card) if correct[0].lower() == 'm': if card['card used'] == 0: card['card used'] +=1 card['consecutive right'] +=1 card['date'] = date.today() + timedelta(days = card['consecutive right'] * 2) word_list_future.append(card) #Flip function: removed, but I may readd. # if correct[0].lower() == 'f': # card[0], card[1] = card[1], card[0] # word_list_today.append(card) if correct[0].lower() == 'w': if card['card used'] == 0: card['card used'] += 1 card['consecutive right'] = 1 card['date'] = date.today() + timedelta(days = 1) word_list_today.append(card) if correct[0].lower() == 'q': break #The following is for wrong answers. I used an 'else' statement as a filler to handle exceptions. for i in word_list_today: word_list_future.append(i) tomorrows_words = 0 for card in word_list_future: if card['date'] <= date.today() +timedelta(days = 1): tomorrows_words += 1 print("There are " + str(tomorrows_words) + " words in tomorrow's word list.") shelfFile['output'] = word_list_future shelfFile.close() cont = input('\n\nList Completed: Type "y" to return to the main menu.') if cont == 'y': main() else: pass # A menu function. Option 4 has not been added yet. def main(): print("\n\n\nFlashcards: Main Menu\n\n") print("Print list of today's flashcards: Press['1']\n") print("Run today's flashcards: Press['2']\n") print("Scan notes for flashcards: Press['3']\n") print("Manually enter flashcards: Press['4']\n") print("Quit: Press['5']\n") menu_choice = input("> ") if menu_choice == '1': print_list() elif menu_choice == '2': fc() elif menu_choice == '3': update() elif menu_choice == '4': manual() elif menu_choice == '5': pass elif menu_choice == '6': six() elif menu_choice == '0': init() main()
72f019884e5b5efc5f07e17d2b7556ade1cdc884
newbabyknow/python_practice
/longest_substring.py
454
3.78125
4
# 滑动窗口方法,计算字符串的最长不重复子字符串 def window(s): begin_index = 0 max_long = 0 for i in range(1, len(s)): if s[i] in s[begin_index:i]: max_long = max(max_long, len(s[begin_index:i])) begin_index += s[begin_index:i].index(s[i]) + 1 if max_long == 0: max_long = len(s) return max_long if __name__ == '__main__': a = window('abcaaaabcdfcdc') print(a)
0251c6a7dbe635da68165d24c0dd57afc51f7a49
dsintsov/python
/labs/lab3/class.py
2,737
3.78125
4
""" Вариант 1 Создать класс – Треугольник, заданного тремя точками. Функции-члены изменяют точки, обеспечивают вывод на экран координат, рассчитывают длины сторон и периметр треугольника. Создать список объектов. a) подсчитать количество треугольников разного типа (равносторонний, равнобедренный, прямоугольный, произвольный). b) определить для каждой группы наибольший и наименьший по периметру объект. """ import math class Triangle: def __init__(self, x1, y1, x2, y2, x3, y3): self.x1, self.y1, self.x2, self.y2, self.x3, self.y3 = x1, y1, x2, y2, x3, y3 self.ab = self.ac = self.bc = -1 self.isEquilateral = self.isIsosceles = self.isRectangular = False self.Perimeter = -1 self.GetEdges() self.GetPerimeter() self.GetType() def GetCoordinats(self): return [self.x1, self.y1, self.x2, self.y2, self.x3, self.y3] def GetEdges(self): self.ab = math.sqrt((self.x2 - self.x1) ** 2 + (self.y2 - self.y1) ** 2) self.ac = math.sqrt((self.x3 - self.x1) ** 2 + (self.y3 - self.y1) ** 2) self.bc = math.sqrt((self.x3 - self.x2) ** 2 + (self.y3 - self.y2) ** 2) def GetPerimeter(self): self.Perimeter = self.ab + self.ac + self.bc def GetType(self): if self.ab == self.ac and self.ab == self.bc: self.isEquilateral = True if self.ab == self.ac or self.ab == self.bc or self.ac == self.bc: self.isIsosceles = True if self.ab ** 2 == self.ac ** 2 + self.bc ** 2 or self.ac ** 2 == self.ab ** 2 + self.bc or self.bc ** 2 == self.ac ** 2 + self.ab ** 2: self.isRectangular = True TR = [] TR.append(Triangle(5, 4, 3, -1, 4, 5)) TR.append(Triangle(1, 3, -2, 0, -1, 4)) TR.append(Triangle(4, 1, -2, 3, -1, 4)) TR.append(Triangle(8, 13, 4, 0, 2, 11)) Equilateral = isIsosceles = isRectangular = 0 maxPerimeter=minPerimeter=TR[0].Perimeter for T in TR: print("Coord =", T.GetCoordinats()) print("Edges =", T.ab, T.ac, T.bc) print("Perimeter =", T.Perimeter) if T.isEquilateral: Equilateral+=1 if T.isIsosceles: Isoscelesl += 1 if T.isRectangular: Rectangular += 1 if T.Perimeter > maxPerimeter: maxPerimeter= T.Perimeter if T.Perimeter < minPerimeter: minPerimeter= T.Perimeter print("maxPerimeter=" + str(maxPerimeter), "minPerimeter=" + str(minPerimeter))
7b85c1bfd3a8ec347ddd742de2ae2703df5acd3f
benryan03/Python-Practice
/basic-part1-exercise049-list_directory.py
178
3.84375
4
#https://www.w3resource.com/python-exercises/python-basic-exercises.php #49. Write a Python program to list all files in a directory in Python. import os print(os.listdir())
99f975f464800047c30f9d596c8e10c4a0f6b346
nabin-info/hackerrank.com
/text-alignment.py
658
3.515625
4
#!/usr/bin/python import sys def input_arg(tr=str): return tr(raw_input().strip()) def input_args(tr=str): return map(tr, list(input_arg().split(' '))) def input_arglines(n,tr=str): return [input_arg(tr) for x in range(n)] def print_logo(t,c='H'): for i in range(t): print (c*i).rjust(t-1)+c+(c*i).ljust(t-1) for i in range(t+1): print (c*t).center(t*2)+(c*t).center(t*6) for i in range((t+1)/2): print (c*t*5).center(t*6) for i in range(t+1): print (c*t).center(t*2)+(c*t).center(t*6) for i in range(t): print ((c*(t-i-1)).rjust(t)+c+(c*(t-i-1)).ljust(t)).rjust(t*6) T = input_arg(int) print_logo(T)
0d97917da23b63c4036fb2b579add0e46ddc85dd
emmanuel-mfum/Pomodoro
/main.py
3,961
3.609375
4
from tkinter import * import math # ---------------------------- CONSTANTS ------------------------------- # PINK = "#e2979c" RED = "#e7305b" GREEN = "#9bdeac" YELLOW = "#f7f5dd" FONT_NAME = "Courier" WORK_MIN = 25 SHORT_BREAK_MIN = 5 LONG_BREAK_MIN = 20 reps = 0 timer = None # ---------------------------- TIMER RESET ------------------------------- # def reset_timer(): global reps start_button.config(state="normal") window.after_cancel(timer) # cancel the after() method call in the timer variable canvas.itemconfig(timer_text, text="00:00") # reset the time displayed title.config(text="Timer") # reset the title displayed check_marks.config(text="") # rest the checks marks reps = 0 # reset the number of reps # ---------------------------- TIMER MECHANISM ------------------------------- # def start_timer(): # function be called upon start global reps start_button.config(state="disabled") reset_button.config(state="normal") reps += 1 work_sec = WORK_MIN * 60 short_break_sec = SHORT_BREAK_MIN * 60 long_break_sec = LONG_BREAK_MIN * 60 if reps % 8 == 0: title.config(text="Break", fg=RED) # set the title to be displayed count_down(long_break_sec) elif reps % 2 == 0: title.config(text="Break", fg=PINK) # set the title to be displayed count_down(short_break_sec) else: title.config(text="Work", fg=GREEN) # set the title to be displayed count_down(work_sec) # ---------------------------- COUNTDOWN MECHANISM ------------------------------- # def count_down(count): # we put the after method into a function in order to have a loop-like call to the function count_minutes = math.floor(count / 60) # calculates the number of minutes count_seconds = count % 60 # calculated the number of seconds if count_seconds == 0: count_seconds = "00" # thanks to Python dynamic typing elif count_seconds < 10: count_seconds = f"0{count_seconds}" # thanks to Python dynamic typing canvas.itemconfig(timer_text, text=f"{count_minutes}:{count_seconds}") # change the text on the canvas if count > 0: global timer timer = window.after(1000, count_down, count - 1) # waits 1000 ms, then call the function and passes an arg else: window.attributes('-topmost', 1) # brings the window at the top of the desktop window.attributes('-topmost', 0) # brings the window at the top of the desktop start_timer() marks = "" work_sessions = math.floor(reps/2) # calculate the amount of work sessions (1 out of 2 reps) for _ in range(work_sessions): marks += "✔" # add a check mark check_marks.config(text=marks) # displays the check marks # ---------------------------- UI SETUP ------------------------------- # window = Tk() window.title("Pomodoro") window.config(padx=100, pady=50, bg=YELLOW) # adds padding to the window canvas = Canvas(width=200, height=224, bg=YELLOW, highlightthickness=0) # width and height are in pixels tomato_img = PhotoImage(file="tomato.png") # reads the image and makes it a PhotoImage file canvas.create_image(100, 112, image=tomato_img) # the two first arguments are the x and y coordinate of image on canvas timer_text = canvas.create_text(100, 130, text="00:00", fill="white", font=(FONT_NAME, 35, "bold")) canvas.grid(column=1, row=1) # loads the canvas on the window # Labels title = Label(fg=GREEN, text="Timer", font=(FONT_NAME, 35, "bold"), bg=YELLOW) # fg is used to color text and labels title.grid(column=1, row=0) check_marks = Label(fg=GREEN, bg=YELLOW) check_marks.grid(column=1, row=3) # Buttons start_button = Button(text="Start", command=start_timer, state="normal") start_button.grid(column=0, row=2) reset_button = Button(text="Reset", command=reset_timer, state="disabled") reset_button.grid(column=2, row=2) window.mainloop()
1ff6bc17e6eea80fe4e3e9c8a3e57fd1189a6825
alieu93/Comp-Simulation-Assignments
/Assignment 1/Assign1_Part2B.py
3,056
3.703125
4
#Name: Adam Lieu #Student ID: 100451790 #Description: #Part 2B of Assignment 1, simulate the spread of an infectious disease # Constant Spread Rate: 0.15 # Fatality rate: 0.025 # Recovery rate: 0.15 import itertools as it import numpy as np import scipy as sp import pylab as pl import matplotlib.pyplot as plt import random def simulateNDays(days, numContacts, numInfected, numPeople): #For each susceptible person (not infected, dead, or recovered) #infectionRate = spreadProb * numContacts * numInfected / numPeople #For each infected person: #deathProb should be something between 1 and 0 #Return: # - Number of fatalities # - Number of infected people # - Number of Recovered people # - Number of Susceptible people #numContacts - Times a typical person come into contact with people #numPeople - total population # Set up lists listDeaths = [] listInfected= [] listRecovered = [] listSusceptible = [] spreadProb = 0.15 deathProb = 0.025 recoverProb = 0.15 numRecovered = 0 numDeath = 0 #Simulate if the susceptible person becomes infected infectionRate = (spreadProb * numContacts * numInfected) / numPeople #print infectionRate #Number of susceptible people numOfSusPeople = numPeople - numInfected # initial values for lists listDeaths.append(0) listInfected.append(numInfected) listRecovered.append(0) listSusceptible.append(numOfSusPeople) #Simulate if suspectible person gets infected or not # loop for however many days for i in range(days): for j in range(numOfSusPeople): rand = random.random() if rand < infectionRate: numInfected += 1 numOfSusPeople -= 1 #Simulate if infected person recovers or dies for j in range(numInfected): rand = random.random() if rand < deathProb: # patient dies numPeople -= 1 numInfected -= 1 numDeath += 1 else: if rand < recoverProb: # patient recovers numInfected -= 1 numRecovered += 1 # store results for each day listDeaths.append(numDeath) listInfected.append(numInfected) listRecovered.append(numRecovered) listSusceptible.append(numOfSusPeople) return listDeaths, listInfected, listRecovered, listSusceptible day = range(0, 51) # initial number of infected people = 100 # With initial total number of people = 100 # simulate for 50 days D, I, R, S = simulateNDays(50, 5, 100, 100) plt.plot(day, D, "rs") plt.plot(day, I, "y^") plt.plot(day, R, "go") plt.plot(day, S, "+") plt.xlabel('Day') plt.ylabel('Count') plt.title('Spread of Infection') plt.legend(['Fatalities', 'Infected', 'Recovered', 'Susceptible'], loc='upper right') plt.show()
3d524bfbc085da7c0efde07504414bf8f9cd9d12
xaneon/PythonProgrammingBasics
/python_example_scripts/documentation_in_python.py
608
3.609375
4
""" Beschreibung des Moduls. """ def addiere(arg1, arg2): """*Addiert* ``arg1`` und ``arg2``.""" return arg1 + arg2 # Kommentar eines Entwicklers def multipliziere(arg1, arg2): """ >>> multipliziere(3, 5) 15 """ return arg1 * arg2 def potenziere(basis, exponent): """ **Zusammenfassung** der Funktion. Parameters ----------- basis: float Die Beschreibung zu ``basis``. exponent: int Die Beschreibung zu ``exponent``. Returns -------- int Das Ergebnis des Pontenzierens. """ return basis ** exponent
94d2f25a28aa77cb71b87f563aaa4f498436e9fa
DTA-XCIV/Python
/ex30.py
1,298
4.25
4
# enkele variabelen met integers als waarde people = 30 cars = 40 trucks = 15 # deze blok vergelijkt in totaal 2 variabelen: cars en people # de if-functie komt als eerste en kijkt of er meer auto's zijn dan mensen # de waarde is True, dus print de script de lijn die onder de if staat # mocht het zijn dat de waarde not true was, dan zou Python de elif testen # en zien of er minder cars zijn dan mensen, als DIE waarde true zou zijn # dan print Python de lijn die daar onderstaan # mochten beide waardes False geven, in deze situatie enkel mogelijk wanneer # het aantal auto's gelijk is aan het aantal mensen # dan gaat Python naar de else-functie, die standaard werkt wanneer de if en # elif allebei False zijn if cars > people: print("We should take the cars.") elif cars < people: print("We should not take the cars.") else: print("We can't decide.") # de principes van deze blok zijn hetzelfde als die van erboven if trucks > cars: print("That's too many trucks.") elif trucks < cars: print("Maybe we could take the trucks") else: print("We still can't decide.") # deze blok heeft geen elif, dus test het enkel de if, en anders is het de # else if people > trucks: print("Alright, let's just take the trucks.") else: print("Fine, let's just stay home then.")
4493accafe7054910c37c82e96b7421fc98b0f00
daniel-reich/ubiquitous-fiesta
/FPNLQWdiShE7HsFki_6.py
830
3.578125
4
def spider_vs_fly(spider, fly): label = "ABCDEFGH" d = 4 - abs(4 - abs(label.index(spider[0]) - label.index(fly[0]))) path = [spider] ​ if abs(int(spider[1]) - int(fly[1]) > 0): while spider[1] != fly[1]: spider = spider[0] + str(int(spider[1]) - 1) path.append("A0" if spider[1] == "0" else spider) ​ if d > 2: while spider[1] != "0": spider = spider[0] + str(int(spider[1]) - 1) path.append("A0" if spider[1] == "0" else spider) ​ while spider != fly: spider = fly[0] + str(int(spider[1]) + 1) path.append(spider) else: a = label.index(spider[0]) clockwise = label[(a + d) % 8] == fly[0] ​ while spider != fly: a = (a + (1 if clockwise else -1)) % 8 spider = label[a] + spider[1] path.append(spider) ​ return "-".join(path)
a363b843b1070b4f244505dd15d85e7c3f20f700
babint/AoC-2015
/02/part2.py
1,377
3.953125
4
#!/usr/bin/env python3 import sys paper_needed = 0 ribbon_needed = 0 # Usage if len(sys.argv) != 2: print("usage: part2.py input.txt") exit(1) # Read File with open(sys.argv[1]) as f: lines = f.read().splitlines() for line in lines: dimensions = line.split('x') shortest = sys.maxsize short_a = short_b = 0 paper = 0 ribbon = 0 # Get dimensions l = int(dimensions[0]) w = int(dimensions[1]) h = int(dimensions[2]) # Figure out shortest sides if (shortest > l*w): short_a = l short_b = w shortest = short_a * short_b if (shortest > w*h): short_a = w short_b = h shortest = short_a * short_b if (shortest > h*l): short_a = h short_b = l shortest = short_a * short_b # Calcuate paper and ribbon needed to wrap presents paper = (2*l*w) + (2*w*h) + (2*h*l) + (shortest) ribbon = (short_a + short_a + short_b + short_b) + () # Track total needed paper_needed = paper_needed + paper ribbon_needed = ribbon_needed + ribbon #print(f"Dimensions: {line}, paper: {paper}, ribbon: {ribbon}, short_a: {short_a}, short_b: {short_b}, shortest: {shortest}") # Print Results print(f"\npaper_needed: {paper_needed} square feet of paper"); print(f"ribbon_needed: {ribbon_needed} feet of ribbon"); print("\ndone."); # ---- 2+2+3+3 = 10 feet of ribbon # ---- 2*3*4 = 24 feet for ribbon for bow
9e492897afa9b8d19f3055f3e19cd7d53f1bff5b
burnasheva/scripts
/generate_files.py
316
3.53125
4
for value in range(10): # construct the filename; prefix or suffix optional filename = 'prefix-' + str(value) + '.txt' # open the file to be written fo = open(filename, 'w') # write the content in the file including the value being passed to each; %s indicates a string fo.write('%s' % value) fo.close()
ea3fd457c39c08c91b22d3e4200f1fe83aadcf38
simonmonk/prog_pi_ed3
/03_04_double_dice_while.py
276
3.84375
4
#03_04_double_dice_while import random throw_1 = random.randint(1, 6) throw_2 = random.randint(1, 6) while not (throw_1 == 6 and throw_2 == 6): total = throw_1 + throw_2 print(total) throw_1 = random.randint(1, 6) throw_2 = random.randint(1, 6) print('Double Six thrown!')
fcf36b2fd1228fe0d65951269002e48af858f638
tyraeltong/py-algorithms
/sorting/selection_sort.py
960
3.875
4
from sorting.utils import print_tests class SelectionSort: """ Time complexity: - Worst case: O(nˆ2) - Best case: O(nˆ2) - Average case: O(nˆ2) Space complexity: - O(1) """ @staticmethod def sort(data): if data is None: raise TypeError("data should not be None.") if len(data) < 2: return data for i in range(len(data) - 1): min_idx = SelectionSort._find_min_idx(data[i:]) data[i], data[min_idx+i] = data[min_idx+i], data[i] return data @staticmethod def _find_min_idx(items): if len(items) < 1: return None min_item = items[0] min_idx = 0 for idx in range(1, len(items)): if items[idx] < min_item: min_item = items[idx] min_idx = idx return min_idx if __name__ == '__main__': print_tests(SelectionSort)
e9817120246d9b29d18c1615be19bcbe0d8bbf7f
girishalwani/Training
/python/python fundamentals/functions_modules_packages/prog_1.py
359
3.96875
4
""" Write a function to return the sum of all numbers in a list. """ def sumAll(list): sum=0 for i in list: sum+=int(i) return sum number = input("enter list elements separated by space -> ") lis=number.split() lis2=[] for i in lis: lis2.append(int(i)) print('list items -> ',lis2) print('sum of all elements -> ',sumAll(lis))
98efaf16c4b6c3fc9b0dc061c7f7a47e453fd203
newwby/EnaiRimDocumentationParser
/output_handlers.py
1,098
3.890625
4
######################### """ Accepts input in the form of a list containing dict entries for every item. (Basically objects but with built-in python types) """ ######################### def parser_printer(given_list: list, file_output_string: str, write_raw_to_file: bool = True, erase_file: bool = True): if write_raw_to_file: if erase_file: given_file = open(file_output_string, "w") else: given_file = open(file_output_string, "a") for i in given_list: # i is the dict for n in i: # n is the key:value pairs in dict if not write_raw_to_file: print_line(n, i) else: given_file.write(i[n] + "\t") #print(i[n], end='\t') if not write_raw_to_file: print() # at end print a blank line to separate perk blocks else: given_file.write("\n") if not write_raw_to_file: print("\nFinished printing to console. \n") else: print("\nPrinted output to: " + file_output_string + "\n") # simplifies printing dict def print_line(given_string, given_dict): print(given_string + ": " + given_dict[given_string])
e90c44641308f87815fe8e370799fc73e2a139aa
medifle/python_6.00.1x
/defMul.py
118
3.78125
4
# multiplication def iterMul(a, b): result = 0 for i in range(b): result += a return result
605632faca8f7f57558fa1bba084d643f4b8fa96
tchapeaux/project-euler
/004.py
1,030
3.828125
4
import math def is_palindrom(word): l = len(word) for i in range(math.floor(l / 2)): if word[i] != word[l-1-i]: return False return True assert(is_palindrom("")) assert(is_palindrom("1")) assert(is_palindrom("zz")) assert(is_palindrom("bob")) assert(is_palindrom("baobabbaboab")) assert(is_palindrom("9229")) assert(is_palindrom("KAYAKKAYAKKAYAKKAYAK")) assert(is_palindrom("12321")) assert(not is_palindrom("12345")) assert(not is_palindrom("AZERTYXTREZA")) assert(not is_palindrom("1234221")) assert(not is_palindrom("aA")) n1 = 999 n2 = 999 currentMax = 0 while n1 > 0: while n2 > 0: product = n1 * n2 if product > currentMax: if is_palindrom(str(product)): currentMax = product print("new max", product, "=", n1, "x", n2) else: # we can skip all remaining n2 values as their product with n1 # will always be smaller than currentMax. break n2 -= 1 n1 -= 1 n2 = n1
beff943471560d3cb65d7eb999d55eec826672b7
DucarrougeR/COMP30670_Final-Project-DublinBikes
/bikes.py
2,376
3.6875
4
import requests import pandas as pd import sqlite3 import traceback import time # Setting up NAME = "Dublin" STATIONS = "https://api.jcdecaux.com/vls/v1/stations" APIKEY = "1c8d24323042b11c89877648adfe3c180f15fa3c" conn = sqlite3.connect("dublinBikes.db") # Connect to database (creates if it does not exist) cursor = conn.cursor() # Create a new table in the current database # Specify column names and data types cursor.execute("CREATE TABLE IF NOT EXISTS dublinBikes (address text, available_bike_stands integer, available_bikes integer, banking integer, bike_stands integer, bonus integer, contract_name text, last_update integer, name text, number integer, position_lat real, position_lng real, status text)") conn.commit() # Save the changes def add_to_database(dataframe): """ Function to add information to the database """ # df.shape returns the number of columns and rows in a dataframe # So using the first value returned, we can cycle through each row in the dataframe (where each row has information on a specific station) for i in range(0, (dataframe.shape[0]-1)): data = dataframe.iloc[i] # df.iloc[] just allows us to access elements via normal indexing of a pandas dataframe # Store all the information from the dataframe in a list elements = [data.get("address"), int(data.get("available_bike_stands")), int(data.get("available_bikes")), int(data.get("banking")), int(data.get("bike_stands")), int(data.get("bonus")), data.get("contract_name"), float(data.get("last_update")), data.get("name"), int(data.get("number")), data.get("position").get("lat"), data.get("position").get("lng"), data.get("status")] # Add each of these elements to the table in our database cursor.execute("INSERT INTO dublinBikes VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)", elements) conn.commit() # Always run while True: try: # Access info on JCDecaux website using API key # Convert the JSON information into a pandas dataframe format df = pd.read_json("https://api.jcdecaux.com/vls/v1/stations?contract=" + NAME + "&apiKey=" + APIKEY) # Add the information to the database add_to_database(df) # Sleep for 5 minutes time.sleep(15) except: # Print traceback if there is an error print(traceback.format_exc())
a5062dcbfff7f5a60bbc3c78c6d7b9a174e7e178
gaoxinge/bible
/python/pysheeet/4/test.py
395
3.65625
4
def decorator(func): def wrapper(*args, **kwargs): print("I am decorator") ret = func(*args, **kwargs) return ret return wrapper @decorator def hello(str): print("Hello {0}".format(str)) @decorator def add(a, b): print("add %d + %d = %d" % (a, b, a + b)) return a + b print hello("KerKer") print add(1, 2)
4bf612c9c3847ae6a6347afb4f98d632e0694faf
SinghGauravKumar/Project-Euler-Python-Solutions
/euler_problem_052.py
229
3.53125
4
import itertools def compute(): for i in itertools.count(1): digits = sorted(str(i)) if all(sorted(str(i * j)) == digits for j in range(2, 7)): return str(i) if __name__ == "__main__": print(compute())
1aa20111e6db5a61efd9af07110331258cbab7ce
sharanya-code/Telephone-Directory-Program
/Telephone Dictonary Program.py
5,591
4
4
import pickle ######################################## To Create the Binary File phone.dat def Append(): print("\n") Name=input("Enter name of the Person: ") RollNo=int(input("Enter Phone Number of the Person: ")) Data=[Name,RollNo] while True: try: inFile=open("phone.dat","rb") List=pickle.load(inFile) inFile.close() break except: List=[] break List.append(Data) outFile=open("phone.dat","wb") pickle.dump(List,outFile) outFile.close() ####################### To Read and Display the Entire Binary File phone.dat def Display(): print("\n") inFile=open("phone.dat","rb") List=pickle.load(inFile) inFile.close() print(List) ################### To Read and Search an Entry in the Binary File phone.dat def Search(): Found=0 print("\n\n<< SEARCH MENU >>\n\n") print("1. Search by Name.\n") print("2. Search by Phone Number.\n") Ch=int(input("Enter your choice: ")) if(Ch==1): Name=input("Enter Name of the Person to be searched : ") else: RollNo=int(input("Enter Phone Number of the Person to be searched: ")) while True: try: inFile=open("phone.dat","rb") List=pickle.load(inFile) inFile.close() break except: List=[] break print("\nSearched Result:") for L in List: if (Ch==1 and Name==L[0]): print(L) Found=1 elif(Ch==2 and RollNo==L[1]): print(L) Found=1 if(Found==0): print("No Match Found!") ################# To Search and Modify an Entry in the Binary File phone.dat def Modify(): FoundIndex=-1 print("\n\n<< MODIFY MENU >>\n\n") print("1. Modify by Name.\n") print("2. Modify by Phone Number.\n") Ch=int(input("Enter your choice: ")) if(Ch==1): Name=input("Enter Name of the Person to be modified: ") else: RollNo=int(input("Enter Phone Number of the Person to be modified: ")) while True: try: inFile=open("phone.dat","rb") List=pickle.load(inFile) inFile.close() break except: List=[] break for i in range(len(List)): L=List[i] if (Ch==1 and Name==L[0]): FoundIndex=i RollNo=List[i][1] newRollNo=int(input("Enter the Modified Phone Number of the Person: ")) List[i][1]=newRollNo print(RollNo," has been modified as ",newRollNo) break elif(Ch==2 and RollNo==L[1]): FoundIndex=i Name=List[i][0] newName=input("Enter the Modified Name of the Person: ") List[i][0]=newName print(Name," has been modified as ",newName) break if(FoundIndex==-1): print("No Match Found!") else: outFile=open("phone.dat","wb") pickle.dump(List,outFile) outFile.close() ################# To Search and Delete an Entry in the Binary File phone.dat def Delete(): FoundIndex=-1 print("\n\n<< DELETE MENU >>\n\n") print("1. Delete by Name.\n") print("2. Delete by Phone Number.\n") Ch=int(input("Enter your choice: ")) if(Ch==1): Name=input("Enter Name of the Person to be deleted: ") else: RollNo=int(input("Enter Phone Number of the Person to be deleted: ")) while True: try: inFile=open("phone.dat","rb") List=pickle.load(inFile) inFile.close() break except: List=[] break for i in range(len(List)): L=List[i] if (Ch==1 and Name==L[0]): FoundIndex=i break elif(Ch==2 and RollNo==L[1]): FoundIndex=i break if(FoundIndex==-1): print("No Match Found!") else: Data=List.pop(FoundIndex) print(Data," has been deleted!") outFile=open("phone.dat","wb") pickle.dump(List,outFile) outFile.close() ################################################### Main Menu with Choices def Menu(): Choice=0 while(Choice!=6): print("\n\n\n") print("<<<<<<< BINARY FILE >>>>>>>\n") print("<< TELEPHONE DIRECTORY >>\n") print("<<<<<<< MAIN MENU >>>>>>>\n\n") print("1. Append a Fresh Entry.\n") print("2. Display Entire File.\n") print("3. Search an Entry.\n") print("4. Modify an Entry.\n") print("5. Delete an Entry.\n") print("6. Quit Program.\n\n") Choice=int(input("Enter your choice: ")) if (Choice==1): Append() elif (Choice==2): Display() elif (Choice==3): Search() elif (Choice==4): Modify() elif (Choice==5): Delete() elif (Choice==6): print("\n\n\nThank you for using this software!\n\n\n") else: print("Invalid Input! Try AGain!") ############################################################# Main Program Menu() a=input()
782780d34b340f5e001a57cbb30768b2d70270e1
lapricope/personal_search
/searcher/searcher.py
726
3.609375
4
import os class Searcher(object): def __init__(self): self.__results = [] pass def search(self, start_path='D:\\', pattern=None): """ Function will search files/images which match the provided pattern Will place results in self.results list :param start_path: Path from where to start recursive search :param pattern: :return: number of results """ path_content = os.listdir(start_path) self.__results = path_content return len(path_content) def results(self): return self.__results if __name__ == '__main__': searcher = Searcher() no_of_matches = searcher.search() print(searcher.results())
f22d7d41d7744ce3f7be065873ec5cfdd6244fe7
jxseff/python-exercise
/chapter 4/animals.py
132
3.953125
4
animals = ['cat', 'dog', 'duck'] for animal in animals: print(f"A {animal} would make a great pet.") print('They are all loud.')
4922f808738c9f98ab50b9a74f16a87163a5e86b
StaroverovAleksey/GeekBrains
/lesson_4/lesson_4_task_6.1.py
232
3.671875
4
from itertools import count start = int(input('Введите начальное число: ')) stop = int(input('Введите конечное число: ')) for i in count(start): print(i) if i == stop: break
bf9c250b6b5fc2d38bec248a0d9b6b027b56c1c9
akbagai/MITx-6.00.1x-Introduction-to-Computer-Science-and-Programming-Using-Python
/week2/lecture4/fib.py
1,811
3.84375
4
# -*- coding: utf-8 -*- """ Add caching """ import timeit from timeit import Timer from functools import lru_cache def fibi(n): """ Iterative Fibonacci :param n: nth number to calculate the Fibonacci value :return: Fibonacci value """ a, b = 0, 1 for i in range(n): a, b = b, a + b return a @lru_cache(maxsize=10000) def fib(x): """assumes x an int >= 0 returns Fibonacci of x""" if x == 0 or x == 1: return 1 else: return fib(x - 1) + fib(x - 2) fib_cache = {} def fibm(x): # Check cache if x in fib_cache: return fib_cache[x] # Compute if x == 0 or x == 1: return 1 else: value = fibm(x - 1) + fibm(x - 2) fib_cache[x] = value return value def wrapper(func, *args, **kwargs): def wrapped(): return func(*args, **kwargs) return wrapped wrapped = wrapper(fibm, 1000) # for n in range(1, 10001): # print(n, ":", fib(n)) # create timer object # t1 = timeit.Timer("fibm(30)") # n = 5 # secs = t1.timeit(number=n) # print(secs) # print(timeit.timeit('1+3', number=100)) # print(timeit.timeit("fibm(30)", number=100)) # n = 40 # time = timeit.timeit('fib(1000)', setup='from __main__ import fib, n, fib_cache', number=n) # time = timeit.timeit('fib(1000)', setup='from __main__ import fib, n, fib_cache', number=n) ##print(timeit.timeit(wrapped, number=5)) #t1 = Timer("fib(10)", "from __main__ import fib") for i in range(1, 10000): s = "fibm(" + str(i) + ")" t1 = Timer(s, "from __main__ import fibm") time1 = t1.timeit(3) s = "fib(" + str(i) + ")" t2 = Timer(s, "from __main__ import fib") time2 = t2.timeit(3) print("n=%2d, fib: %8.6f, fibi: %7.6f, percent: %10.2f" % (i, time1, time2, time1 / time2))
edbeeca71e09940ae1f35a25df855b44071ce80a
lemnissa/1sem
/lab2/2.13.py
643
3.9375
4
import turtle as t def my_fill(col, R, tri=360): t.begin_fill() t.color(col) t.circle(R, tri) t.end_fill() t.color('black') t.circle(R, tri) t.shape("turtle") t.up() t.goto(0, -200) t.down() my_fill('yellow', 200) # t.up() # t.goto(-90, 60) t.down() my_fill('blue', 30) t.up() # t.goto(90, 60) t.down() my_fill('blue', 30) t.up() # t.goto(0, 20) t.down() t.right(90) t.width(12) t.forward(50) t.up() # t.goto(-60, -100) t.down() t.color('red') t.circle(60, 180) t.ht()
3de834acde82a669511370ab541848d98f03b060
mollinaca/ac
/code/practice/abc/abc099/a.py
109
3.6875
4
#!/usr/bin/env python3 # -*- coding: utf-8 -*- n = int(input()) print ('ABC') if n <= 999 else print ('ABD')
991978eaaacb557f9a7143e9fe3968ea2b99c440
stevechuckklein/tstp-chapter-challenges
/chapter-seven-challenges.py
1,420
4.125
4
#1. Print each item in the following list: ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"]. chal1 = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"] for i in chal1: print(i) #2. Print all the numbers from 25 to 50. for i in range(25,51): print(i) #3. Print each item in the list from the first challenge and their indexes. i=0 for entry in chal1: print(entry, i) i += 1 shows = ["The Walking Dead", "Entourage", "The Sopranos", "The Vampire Diaries"] for index, show in enumerate(shows): print(index) print(show) #4. Write a program with an inifinite loop (with the option to type q to quit) and a list of numbers. Each time through the loop ask the user to guess a number on the list and tell them whether or not they guessed correctly. # lister = [4,5,7,9] # while True: # print("Type q to quit") # ans = input("Guess a number in the list.") # if ans == "q": # break # elif ans in lister: # print("Good guess, you got it.") # else: # print("Wrong, try again") #5. Multiply all the numbers in the list [8, 19, 148, 4] with all the numbers in the list [9, 1, 33, 83], and append each result to a third list. list1 = [8, 19, 148, 4] list2 = [9, 1, 33, 83] result = [] for num1 in list1: for num2 in list2: result.append(num1 * num2) print(result) #Solutions: http://tinyurl.com/z2m2ll5
c992962cd8498ee4a42313d4dff8f6217937b7bf
peacej/random
/algo_exercises/sqrt_multiple_implementations.py
1,151
3.921875
4
def sqrt_halving(x, epsilon=0.0001): if x > 0: res = (x + 1) / 2 else: raise ValueError("invalid input") i = 0 if res * res < x: while res * res < x: prev_delta = res res = 2 * res i +=1 else: while res * res > x: prev_delta = res res = res / 2 i +=1 while abs(res * res - x) > epsilon: if res * res > x: res = res - prev_delta / 2 else: res = res + prev_delta / 2 prev_delta = prev_delta / 2 i += 1 print(f"Took {i} iterations to find solution.") return res def sqrt_newton(x, epsilon=0.0001): if x > 0: res = (x + 1) / 2 else: raise ValueError("invalid input") i = 0 while abs(res * res - x) > epsilon: res = (x + res*res) / (2 * res) # manually did algebra using newton's method i += 1 print(f"Took {i} iterations to find solution.") return res for value in [0.05, 1.5, 53, 4450455]: print(f"Calculating square root for {value}...") print(sqrt_halving(value)) print(sqrt_newton(value))
961d4060c73db8f9f2361f1ea82219e02f173c4b
iteong/comp9021-principles-of-programming
/labs_finals/Lab7_Recursion_Strings.py
2,543
4.3125
4
strings = [] ordinals = ('first','second','third') for i in ordinals: strings.append(input('Please input the {:} string: '.format(i))) print('\nInputs in Strings List: {:}'.format(strings)) # Sorting strings: assign index values to variables to check particular string's index in list strings using length, # so that these variables can be used in merge function to input strings where string3 is always # the longest string last = 0 if len(strings[1]) > len(strings[0]): last = 1 if len(strings[2]) > len(strings[last]): last = 2 if last == 0: first, second = 1, 2 elif last == 1: first, second = 0, 2 else: # last = 2 first, second = 0, 1 print('\nFirst ordinal string "{:}" is index {:} in Strings list.'.format(strings[first], first)) print('Second ordinal string "{:}" is index {:} in Strings list.'.format(strings[second], second)) print('Last ordinal string "{:}" is index {:} in Strings list.'.format(strings[last], last)) def merge(string1, string2, string3): ## base cases # first base case: if string1 empty AND string2 = string3, merge = True! if not string1 and string2 == string3: return True # second base case: if string2 empty AND string1 = string3, merge = True! if not string2 and string1 == string3: return True ## if string1 and string2 empty (nothing to merge to give resulting string if not string1 and not string2: return False # if string1 has same first letter as string3 (i.e. ab, cd, abcd) , and # merge(string1's letters without 1st, string2, string3's letters without first) is True # (ab, cd, abcd) => (_b, cd, _bcd) => (_, cd, _cd) => hits first base case if string1[0] == string3[0] and merge(string1[1:], string2, string3[1:]): return True # (cd, ab, abcd) => (cd, _b, _bcd) => (cd, _, _cd) => hits second base case if string2[0] == string3[0] and merge(string1, string2[1:], string3[1:]): return True return False # otherwise if conditions not met, merge is False # 2 substrings cannot be added up in length to give same length as longest string if len(strings[last]) != len(strings[first]) + len(strings[second]): print('\nNo solution.') # sorted strings in list cannot be merged if not merge(strings[first], strings[second], strings[last]): print('\nNo solution.') else: # 2 substrings can be added up in length to give resulting string and sorted strings can be merged print('\nThe {:} string can be obtained by merging the other two.'.format(ordinals[last]))
93b2361806ab82b49f0f3283b65ff08247b07140
yatengLG/leetcode-python
/question_bank/keys-and-rooms/keys-and-rooms.py
674
3.578125
4
# -*- coding: utf-8 -*- # @Author : LG """ 执行用时:80 ms, 在所有 Python3 提交中击败了87.03% 的用户 内存消耗:14.6 MB, 在所有 Python3 提交中击败了10.98% 的用户 解题思路: 深度优先遍历,递归 """ class Solution: def canVisitAllRooms(self, rooms: List[List[int]]) -> bool: record = set() def visit_room(key): record.add(key) now_keys = rooms[key] for key in now_keys: if key not in record: visit_room(key) visit_room(0) if len(record) == len(rooms): return True else: return False
128bb19c16cfc39e199647ed5364259517bccc50
olabarka5/python-selenium-automation
/hw_algoritms_1/Max_of_three.py
277
4.125
4
a = int(input ("input first value ")) b = int(input ("input second value ")) c = int(input ("input third value ")) if a < b: if b < c: print (" c-max") else: print ("b-max") else: if a > c: print ("a-max") else: print ("c-max")
24ea20577f4c937e94c67233b6dcc1e19f0ec28b
Muntaser/PythonExploration
/lab_9/test_pokerodds.py
8,343
4.09375
4
''' Lab 9-4 Module: test_pokerodds.py: Muntaser Khan ''' import random SUITS = ["Clubs", "Diamonds", "Hearts", "Spades"] RANKS = ["", "Ace", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Jack", "Queen", "King"] class Card(): """ Represents a single playing card, whose rank internally is int _rank: 1..13 => "Ace".."King" and whose suit internally is int _suit 0..3 => "Clubs".."Spades" """ def __init__(self, rank=1, suit=3): ''' Initialize card with given int suit and int rank :param rank: :param suit: :return: ''' self._rank = rank self._suit = suit def __str__(self): ''' Return the string name of this card: "Ace of Spades": translates int fields to strings :return: ''' # "Ace of Spades" is string for self._rank==1, self._suit==3 toreturn = RANKS[self._rank] + " of " + SUITS[self._suit] return toreturn class Deck(): """ Represents a deck of 52 standard playing cards, as a list of Card refs """ def __init__(self): ''' Initialize deck: field _cards is list containing 52 Card refs, initially :return: nothing ''' self._cards = [] for rank in range(1, 14): for suit in range(4): c = Card(rank, suit) self._cards.append(c) def __str__(self): ''' "Stringified" deck: string of Card named, with \n for easier reading :return: ''' toreturn = '' # for index in range(len(self._cards)): # self._cards[index] for c in self._cards: temp = str(c) # temp is the stringified card toreturn = toreturn + temp + "\n" # note \n at end return toreturn def shuffle(self): random.shuffle(self._cards) # note random function to do this def dealCard(self): toreturn = self._cards.pop(0) # get and remove top card from deck return toreturn def buildDict(hand): dict = {} for card in hand: dict[card._rank] = dict.get(card._rank, 0) + 1 # Complete this return dict def hasOnePair(dict): # Check for EXACTLY one pair in dict and no three-of-a-kinds # Note there might be 2 pairs; hence the counting of pairs # and there might be three-of-a-kind plus a single pair: # full house twocount = 0 threecount = 0 for v in dict.values(): if v == 2: twocount += 1 elif v == 3: threecount += 1 if(twocount == 1 and threecount == 0): return True return False def hasTwoPairs(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' twocount = 0 for v in dict.values(): if v == 2: twocount += 1 if twocount == 2: return True return False def hasThreeOfAKind(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' threecount = 0 for v in dict.values(): if v == 3: threecount += 1 if threecount == 1: return True return False def hasFullHouse(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' twocount = 0 threecount = 0 for v in dict.values(): if v == 2: twocount += 1 elif v == 3: threecount += 1 if(twocount == 1 and threecount == 1): return True return False def hasFourOfAKind(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' fourcount = 0 for v in dict.values(): if v == 4: fourcount += 1 if fourcount == 1: return True return False def hasStraight(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' # five cards of sequential rank return False def hasFlush(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' return False def hasStraightFlush(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' return False def hasRoyalFlush(dict): ''' Complete this! :param dict: dictionary with card ranks to check ''' return False def main(): # finish this... TRIALS = 10000 # int(input ("Input number of hands to test: ")) hand = [] # list of Card in hand # accumulators for different counts onepairCount = 0 twopairCount = 0 threeCount = 0 fourCount = 0 fullHouseCount = 0 # more if you wish... for num in range(TRIALS): d = Deck() d.shuffle() hand = [] for count in range(5): hand.append(d.dealCard()) dict = buildDict(hand) if hasOnePair(dict): onepairCount += 1 elif hasTwoPairs(dict): twopairCount += 1 elif hasThreeOfAKind(dict): threeCount += 1 elif hasFourOfAKind(dict): fourCount += 1 ## elif hasFullHouse(dict): ## fourCount += 1 # add more if you wish... # print out results... print("Number of one pair hands is: ", onepairCount) print("% of hands: ", 100.0 * onepairCount / TRIALS) print("Number of two pair hands is: ", twopairCount) print("% of hands: ", 100.0 * twopairCount / TRIALS) print("Number of three of a kind hands is: ", threeCount) print("% of hands: ", 100.0 * threeCount / TRIALS) print("Number of four of a kind hands is: ", fourCount) print("% of hands: ", 100.0 * fourCount / TRIALS) # Number of one pair hands is: 4225 # % of hands: 42.25 , theoritical propbability is the same # Number of two pair hands is: 432 # % of hands: 4.32, theoritical propbability is 4.75% # Number of three of a kind hands is: 229 # % of hands: 2.29, theoritical propbability is 2.11% # Number of four of a kind hands is: 2 # % of hands: 0.02, theoritical propbability is 0.024% #The results match theoritical propbabilities def card_example_1(): card1 = Card() # Card(1,3) card2 = Card(12, 2) card1._newfield = 47 print(card1.__str__()) # long-winded form print(str(card2)) print(card1._newfield) print(card1._rank) print(card1._suit) def deck_example_1(): ''' Test Deck: create, print then shuffle, print again Then deal first two cards and print, along with bottom card ''' deck = Deck() print(str(deck)) print("Now we shuffle:\n") deck.shuffle() print(str(deck)) c = deck.dealCard() c2 = deck.dealCard() print("The first card dealt is", str(c), "and the second is", str(c2)) print("Bottom of deck is", deck._cards[-1]) # can't hide the implementation! if __name__ == "__main__": # testCard() # uncomment to test creating & calling Card methods deck_example_1() # uncomment to test Deck: create, print, shuffle, print # test() # uncomment to test hand (list of 5 Card obj) for one pair main() # uncomment to run general poker odds calculations # #------------------------------------------------------------------------- # def test_one_pair(): testhand = [Card(2, 3), Card(1, 2), Card(3, 1), Card(13, 2), Card(2, 0)] dict = buildDict(testhand) assert hasOnePair(dict) def test_two_pair(): testhand = [Card(2, 3), Card(1, 2), Card(2, 1), Card(1, 3), Card(13, 0)] dict = buildDict(testhand) assert hasTwoPairs(dict) def test_three_of_a_kind(): testhand = [Card(2, 3), Card(1, 2), Card(2, 1), Card(2, 3), Card(13, 0)] dict = buildDict(testhand) assert hasThreeOfAKind(dict) def test_four_of_a_kind(): testhand = [Card(2, 3), Card(2, 2), Card(2, 1), Card(2, 3), Card(13, 0)] dict = buildDict(testhand) assert hasFourOfAKind(dict) def test_full_house(): testhand = [Card(2, 3), Card(2, 2), Card(2, 1), Card(13, 3), Card(13, 0)] dict = buildDict(testhand) assert hasFullHouse(dict)
a9bd5d5fe221f9a29c943a95e12b4dcc2d9ef3be
yashika51/Hacktoberfest
/Python/dictionary-comp.py
208
3.78125
4
# this is one of my favorite code snippets because it allows me to easily create an arbitrary size dictionary keys = ['key1','key2','key3','key4','keyn'] dictionary = {k : [] for k in keys} print(dictionary)
85ab204d40e2e61ae4074206cc005eeceb6c9595
TPIOS/LeetCode-cn-solutions
/First Hundred/0048.py
413
3.53125
4
class Solution: def rotate(self, matrix): n = len(matrix) if n == 0 or n == 1: return for i in range(0, (n+1)//2): for j in range(0, n//2): tmp = matrix[i][j] matrix[i][j] = matrix[n-1-j][i] matrix[n-1-j][i] = matrix[n-1-i][n-1-j] matrix[n-1-i][n-1-j] = matrix[j][n-1-i] matrix[j][n-1-i] = tmp
2fcb3271e2616d658d6ff80e04c092615d9a1b5c
venkyvijayb/codingground
/New Project-20170703/main.py
538
4.09375
4
# Hello World program in Python print "hello "+\ "world"; print "keep going" integer = 101; print integer+10; name = age = 'venkat' print name+" is a good boy " + age print name+str(integer) print eval(name) a,b,c=10,20,30 print a+1,b+2,c+3 print name print name[0] print name[2:4] print name[1:] print name*3 name = ['b','c'] print name[0],name[1] #dictionary print "Dictionary" dic = {} dic['name']='venkat' dic['age']=20 print dic print dic['name'] dic['name']+='esh bylla' print dic['name'] print dic.keys() print dic.values()
5be8d605b7347bcdb2fe33f6debf65a5fc3687b3
Kush1101/Standard-Data-Structures-and-Algorithms-Applications
/Printing Duplicates in array/002.py
425
4
4
# in any unknown range. # Here we will use the unordered map to maintain a frequency count of all elements and return the ones with frequency>1 def find_duplicates(arr): freq = {} # use a dictionary to store frequency values for i in range(len(arr)): try: freq[arr[i]]+=1 except: freq[arr[i]] = 1 duplicates = [item for item in freq if freq[item]>1] return duplicates
98aa352616163788996edb9a9364cd592aa33f48
JoshMez/Python_Intro
/While_Input/Intro_While.py
1,293
4.59375
5
#Aim: Asking the user to enter an input. #Using the input fucntion. #How to keep program running as long as users want them to. #So they can enter as much information as they need to. ####### ####### #Use Pythons while loop to keep programs running as long as certain conditions remain true. #### ### ########## ######## ####################### How does the Input function work ############# #Pauses your program. Wait for the user to enter some text. #Once typed, the input written in assigned to a variable. #### #Example of using the input function. message = input("Type a message and i will repeat back to you :D: ") # print(message) ##Keep in mind, alway write clear prompts that tell the user what they have to do. Just always add a semi:colon. # #Look at how we use to one variable to create a prompt and one to create the user input. #the Plus input. Uses the += sign, just think about it as being a an add on the prompt. #We can use a variable to create a prompt to the user to get info from the user. prompt = "Please can you tell us you name so that we can personalise your name tag" prompt += "\nWhat is you first name: " #Interesting. name = input(prompt) # print(f"Hi {name.title().strip()}, thank you for taking the time to get to know and understand the concept at hand. ")
9ba155316e8934ce4720d0172e88958c2b509c8a
borjamoll/programacion
/Python/Act_05/09.py
409
3.890625
4
h=int(input('Un lado, un lado !!! ')) l=int(input('Dame la altura, compañero. ')) if l==h: print("Mira jefe, te voy a ser sincero, lo que me has puesto es un cuadrado pero te lo calculo igual, por pena o por burla, como quieras tomártelo.") halt=h*"*" halt2=(h-2)*(' ') halt3=("*"+str(halt2)+("*")) a=l for i in range(l): if a==l or l==1: print(halt) else: print(halt3) l=l-1
05ac083ac4426487b01f830fb214d63781652f94
mjmingd/study_algorithm
/08.Math/CountFactors.py
1,007
3.890625
4
''' Codility - CountFactors A positive integer D is a factor of a positive integer N if there exists an integer M such that N = D * M. For example, 6 is a factor of 24, because M = 4 satisfies the above condition (24 = 6 * 4). Write a function: def solution(N) that, given a positive integer N, returns the number of its factors. For example, given N = 24, the function should return 8, because 24 has 8 factors, namely 1, 2, 3, 4, 6, 8, 12, 24. There are no other factors of 24. Write an efficient algorithm for the following assumptions: N is an integer within the range [1..2,147,483,647]. Copyright 2009–2019 by Codility Limited. All Rights Reserved. Unauthorized copying, publication or disclosure prohibited. ''' from math import sqrt def solution(N): ''' time complexity : O(sqrt(N)) space complexity : O(1) ''' rt, cnt = int(sqrt(N)), 0 for n in range(1, rt+1) : if N % n == 0 : cnt += 1 return cnt * 2 - 1 if rt * rt == N else cnt * 2
fb4398eca315ba86d27d3486c0ba8d61b9578024
creepjavaer/algorithm
/enunzip.py
882
3.78125
4
#enunzip.py def enhancezip(str): stack=[] result="" number="" end=-1 p="" temp="" for ch in str: if ch !="]": stack.append(ch) print(stack) elif ch=="]": p=stack.pop() if stack: while p!="[": temp+=p print("hahh") p=stack.pop() print(p) result=temp p="" temp="" print(stack) temp=stack.pop() print(temp) if stack: while temp.isdigit(): number+=temp if stack: temp=stack.pop() if not number: number=temp else: stack.append(temp) print(temp) print(stack) temp="" print(number) print("$$") print(number) new=number[::-1] print(new) number="" count=int(new) result=result[::-1]*count stack.append(result) result="" #else: #stack.append(ch) for strs in stack: result+=strs return result print(enhancezip("1[a]2[b3[c]]"))
0bc7907c35eaee8703d941e66427a1e182ad236b
tommyvtran97/SnakeAI
/neural_network.py
1,594
3.6875
4
""" This script contains the feed forward neural network that is implemented to the algorithm to train the snake AI agent. """ import numpy as np from settings import * class Neural_Network(object): def __init__(self, weights=None, bias=None): self.layer = layer self.weights_size = weights_size self.bias_size = bias_size self.weights = [] self.bias = [] if weights is None: for k in range(num_individuals): weights_temp = [] for i in range(len(layer)-1): weights_temp.append(np.random.choice(np.arange(-1, 1, step=0.01), size=(layer[i], layer[i+1]))) self.weights.append(weights_temp) else: self.weights = weights if bias is None: for _ in range(num_individuals): bias_temp = [] for i in range(1, len(layer)): bias_temp.append(np.random.choice(np.arange(-1, 1, step=0.01), size=(1, layer[i]))) self.bias.append(bias_temp) else: self.bias = bias def feed_forward(self, X): output_layer1 = self.relu(np.dot(X, self.weights[0]) + self.bias[0]) current_layer = output_layer1 if len(self.weights) > 2: for i in range(1, len(self.weights)-1): print(np.dot(current_layer, self.weights[i]) + self.bias[i]) output_hidden = self.relu(np.dot(current_layer, self.weights[i]) + self.bias[i]) current_layer = output_hidden output = self.sigmoid(np.dot(current_layer, self.weights[-1]) + self.bias[-1]) return (np.argmax(output)) def relu(self, matrix): relu = np.maximum(0, matrix) return (relu) def sigmoid(self, matrix): sigmoid = 1 / (1 + np.exp(-matrix)) return (sigmoid)
673bf6f30551e600810a1ce468234ddc9763328d
kesia-barros/exercicios-python
/ex001 a ex114/ex060.py
682
4.03125
4
'''from math import factorial n = int(input("Digite um número: ")) f = factorial(n) print("Calculando o fatorial de {}! = {}".format(n, f)) # outra forma de fazer: n = int(input("Digite um número: ")) c = n f = 1 print("Calculando {}! = ".format(n), end="") while c > 0: print("{} ".format(c), end="") print("X " if c > 1 else " = ", end="") f = f * c c = c - 1 print("{}".format(f))''' # outra forma de fazer: n = int(input("Digite um número: ")) c = n f = 1 print("Calculando {}! = ".format(n), end="") for i in range(n, 1, -1): print("{} ".format(c), end="") print("X " if c > 1 else " = ", end="") f = f * c c = c - 1 print("{}".format(f))
035a149c36827230993cf1edc60171ac4d8c0181
sevda-ebadi/django-asvs
/app/xss.py
322
3.515625
4
invalid_chars = { ' ': '&nbsp', "\"": '&quot', '>': '&gt', '<': '&lt', "'": '&apos' } def xss(string): out = str() for character in string: token = invalid_chars.get(character, None) if token: out += token else: out += character return out
a32588c3b36950cc5ad0f4955a9bd2e29e60951e
ATLAS-P/Introduction
/Workshop 1/Concepts/For Loops.py
621
4.65625
5
#Every time the code is run, the for loop sets one variable. for i in range(5): print(i) print("Done!") ''' The output of the above code is: 0 1 2 3 4 Done! For now, we're only using for loops in combination with range(). This gives the following options: ''' for i in range(7): # loops i from 0 (included) to 7 (excluded): # 0, 1, 2, 3, 4, 5, 6 for i in range(5, 9): # loops i from 5 (included) to 9 (excluded): # 5, 6, 7, 8 for i in range(10, 2, -2): # loops i from 10 (included) to 2 (excluded) with steps of -2: # 10, 8, 6, 4 #Note. The loop stops before it reaches the end number.
cf583385a8d299f6d1719e3062c90ef587a44dd5
JakubKazimierski/PythonPortfolio
/Coderbyte_algorithms/Medium/PairSearching/PairSearching.py
2,695
4.46875
4
''' Pair Searching from Coderbyte December 2020 Jakub Kazimierski ''' def PairSearching(num): ''' Have the function PairSearching(num) take the num parameter being passed and perform the following steps. First take all the single digits of the input number (which will always be a positive integer greater than 1) and add each of them into a list. Then take the input number and multiply it by any one of its own integers, then take this new number and append each of the digits onto the original list. Continue this process until an adjacent pair of the same number appears in the list. Your program should return the least number of multiplications it took to find an adjacent pair of duplicate numbers. For example: if num is 134 then first append each of the integers into a list: [1, 3, 4]. Now if we take 134 and multiply it by 3 (which is one of its own integers), we get 402. Now if we append each of these new integers to the list, we get: [1, 3, 4, 4, 0, 2]. We found an adjacent pair of duplicate numbers, namely 4 and 4. So for this input your program should return 1 because it only took 1 multiplication to find this pair. Another example: if num is 46 then we append these integers onto a list: [4, 6]. If we multiply 46 by 6, we get 276, and appending these integers onto the list we now have: [4, 6, 2, 7, 6]. Then if we take this new number, 276, and multiply it by 2 we get 552. Appending these integers onto the list we get: [4, 6, 2, 7, 6, 5, 5, 2]. Your program should therefore return 2 because it took 2 multiplications to find a pair of adjacent duplicate numbers (5 and 5 in this case). ''' steps, nums, num_lists = 0, [num], [list(str(num))] while True: # below checks for pair for digit in '0123456789': if any(2*digit in ''.join(num_list) for num_list in num_lists): return steps steps += 1 new_nums, new_num_lists = [], [] # below for each digit from num, creates new num_list with added product of multiplication # also creates new numbers which are products of multiplication, and previous, checked for pair # are overwritten for num, num_list in zip(nums, num_lists): for digit in str(num): new_nums.append(num*int(digit)) new_num_lists.append(num_list + list(str(num*int(digit)))) # old list are reassigned, in order not to get repeatition in algorithm nums, num_lists = new_nums, new_num_lists
1fed4c344bfe5bb8f87bd2af479c45d5956e09ab
NTN-code/Bank-System
/with refactoring/class_BinaryTree.py
890
3.5625
4
from random import randint class Node: def __init__(self, node,number): self.node = node self.left = None self.right = None self.number = number def add(self, value,number): if value < self.node: if self.left is None: self.left = Node(value,number) else: self.left.add(value,number) elif value > self.node: if self.right is None: self.right = Node(value,number) else: self.right.add(value,number) def printTree(tree, level=0,rec=1): try: if tree.node is not None: printTree(tree.left, level + 1,rec+1) print(' ' * 4 * level + str(rec) + "№:" + str(tree.number) + ' ->' + str(tree.node)) printTree(tree.right, level + 1,rec+1) except AttributeError: pass
685b7af6b8f12a4e39c01cb046b47ebf2ba78497
MrHamdulay/csc3-capstone
/examples/data/Assignment_3/shrdan007/question1.py
210
4.09375
4
# Assignment 3, Question 1 # Danielle Sher i = height = eval(input("Enter the height of the rectangle:\n")) d = width = eval(input("Enter the width of the rectangle:\n")) for i in range(i): print (width*"*")
478418471db2d1cba5b58e5543b9526e84af50bb
luizhmfonseca/Estudos-Python
/EXERCÍCIOS - meus códigos/EX13.py
301
3.546875
4
#Faça um algoritmo que leia o salário de um funcionário e mostre seu novo salário com 15% de aumento. sal1 = float (input('Digite o valor do seu salário atual: ')) acresc = sal1 / 100*15 reaj = sal1 + acresc print(f'O seu salário teve um reajuste de 15% totalizando o valor de {reaj:.2f} reais')
c9ebac8c60f0c75076206f1c6f4b486896b3d7ac
taruntej14/PYTHON-PROGRAMS
/sortbyvalue.py
152
3.71875
4
dic1={'n':'tarun','t':'likhith','s':'santosh'} for i in sorted(dic1.values()): for j in dic1.keys(): if dic1[j]==i: print(j,i)
912ced747225e9d0ca4ee4dff51b5de3d618dc72
EldanGS/Engineering
/Python/aiohttp-intro/install_peps_asyncly.py
1,510
3.78125
4
import aiohttp import time import asyncio """ The code is looking more complex than when we’re doing it synchronously, using requests. But you got this. Now that you know how to download an online resource using aiohttp, now you can download multiple pages asynchronously. Let’s take the next 10-15 minutes to write the script for downloading PEPs 8010 - 8016 using aiohttp. """ async def download_content(pep_number: int) -> bytes: url = f"https://www.python.org/dev/peps/pep-{pep_number}/" print(f"Begin downloading {url}") async with aiohttp.ClientSession() as session: async with session.get(url) as response: content = await response.read() print(f"Finished downloading {url}") return content async def write_to_file(pep_number: int, content: bytes) -> None: filename = f"async_{pep_number}.html" with open(filename, "wb") as pep_file: print(f"Begin writing {filename}") pep_file.write(content) print(f"Finished writing {filename}") async def web_scrap_task(pep_number: int) -> None: content = await download_content(pep_number) await write_to_file(pep_number, content) async def main(): tasks = [web_scrap_task(number) for number in range(8010, 8017)] await asyncio.wait(tasks) if __name__ == '__main__': s = time.perf_counter() asyncio.run(main()) elapsed = time.perf_counter() - s print(f"Execution time {elapsed:0.2f} seconds.") # Execution time 0.33 seconds.
0d084a2ebddcc9d395ecfd9b3d66419d2f63b578
rohithkumar282/LeetCode
/LeetCode1455.py
481
3.578125
4
''' Author: Rohith Kumar Punithavel Email: rohithkumar@asu.edu Problem Statement: https://leetcode.com/problems/check-if-a-word-occurs-as-a-prefix-of-any-word-in-a-sentence/ ''' class Solution: def isPrefixOfWord(self, sentence: str, searchWord: str) -> int: import re key=-1 list_compare=sentence.split(" ") for ele in list_compare: if re.match(searchWord,ele): key = list_compare.index(ele)+1 break return key
f0ca68b93317a099b1dcf59650c681a876e720a6
Holladaze804/Python-Problems
/Grade_Average_Calculator_Assignment 20.py
810
4.03125
4
test1 = int(input("What grade did you receive on test 1? ")) test2 = int(input("What grade did you receive on test 2? ")) test3 = int(input("What grade did you receive on test 3? ")) test4 = int(input("What grade did you receive on test 4? ")) testaverage = ((test1 + test2 + test3 + test4) / 4) if testaverage >=90: print ("Your grade is A. Excellent job! ") print ("Your final average is",testaverage) elif testaverage >=80: print("Your grade is B. Good work. ") print("Your final average is",testaverage) elif testaverage >=70: print("Your grade is C. You passed the course. ") print("Your final average is",testaverage) elif testaverage <70: print("Your grade is F. You failed the course. ") print("Your final average is",testaverage)
61a55fa10f431566b8b774eb31464da128667ad9
h4hany/leetcode
/python_solutions/891.sum-of-subsequence-widths.py
1,702
3.625
4
# # @lc app=leetcode id=891 lang=python # # [891] Sum of Subsequence Widths # # https://leetcode.com/problems/sum-of-subsequence-widths/description/ # # algorithms # Hard (26.58%) # Total Accepted: 3.4K # Total Submissions: 12.9K # Testcase Example: '[2,1,3]' # # Given an array of integers A, consider all non-empty subsequences of A. # # For any sequence S, let the width of S be the difference between the maximum # and minimum element of S. # # Return the sum of the widths of all subsequences of A.  # # As the answer may be very large, return the answer modulo 10^9 + 7. # # # # # Example 1: # # # Input: [2,1,3] # Output: 6 # Explanation: # Subsequences are [1], [2], [3], [2,1], [2,3], [1,3], [2,1,3]. # The corresponding widths are 0, 0, 0, 1, 1, 2, 2. # The sum of these widths is 6. # # # # # Note: # # # 1 <= A.length <= 20000 # 1 <= A[i] <= 20000 # # # # class Solution(object): def sumSubseqWidths2(self, a): """ my own solution :type A: List[int] :rtype: int """ a.sort() maxn = minn = 0 mod = 10 ** 9 + 7 co = 1 for n in a: maxn = (maxn + co * n) % mod co = (co * 2) % mod maxn = maxn % mod co = 1 for n in a[::-1]: minn = (minn + co * n) % mod co = (co * 2) % mod return (mod + maxn - minn) % mod def sumSubseqWidths(self, a): # someone else's solution, quite smart a.sort() res = 0 for i, n in enumerate(a): res <<= 1 res += a[~i] - n res %= 10 ** 9 + 7 return res % (10**9 + 7) a = [2, 1, 3] print(Solution().sumSubseqWidths(a))
a0bb435a8d3b6fde39a7f472433895d31934d992
ravi4all/Python_Aug_4-30
/CorePython/01-BasicPython/StonePaperScissor.py
750
3.953125
4
import random import time cpu_choice = ['stone', 'paper', 'scissor'] cpu_ch = random.choice(cpu_choice) user_choice = input("Enter your choice : ") print("Cpu choice is",cpu_ch) time.sleep(2) if user_choice == cpu_ch: print("Match Tie") elif user_choice == 'scissor' and cpu_ch == 'paper': print("You win") elif user_choice == 'stone' and cpu_ch == 'scissor': print("You win") elif user_choice == 'paper' and cpu_ch == 'stone': print("You win") elif user_choice == 'scissor' and cpu_ch == 'stone': print("CPU win") elif user_choice == 'stone' and cpu_ch == 'paper': print("CPU win") elif user_choice == 'paper' and cpu_ch == 'scissor': print("CPU win") else: print("Wrong Choice")
e28d149336752ffa3036695657485e8f1bb61a65
chunweiliu/leetcode2
/kth_largest_element_in_an_array.py
1,419
3.671875
4
"""K largest numbers in an array << [3, 1, 2, 5, 4, 9, 4, 2], k = 3 => 9, 5, 4 - Heap Time: O(n + klogn) Space: O(k) - Quick Select Time: O(n + n) in average Space: O(1) """ import random class Solution(object): def findKthLargest(self, nums, k): """ :type nums: List[int] :type k: int :rtype: int """ def partition(nums, first, last): pivot = nums[random.randrange(first, last + 1)] bottom, middle, upper = first, first, last while middle <= upper: if nums[middle] > pivot: nums[bottom], nums[middle] = nums[middle], nums[bottom] bottom += 1 middle += 1 elif nums[middle] == pivot: middle += 1 else: nums[middle], nums[upper] = nums[upper], nums[middle] upper -= 1 return bottom first, last = 0, len(nums) - 1 while first + 1 < last: pivot_index = partition(nums, first, last) if pivot_index < k: first = pivot_index + 1 else: last = pivot_index - 1 if nums[first] < nums[last]: nums[first], nums[last] = nums[last], nums[first] return nums[k - 1] nums = [1, 2, 3, 4, 5] k = 2 print Solution().findKthLargest(nums, k)
2f23249f4a1273abea55701f099747290b53ae6b
SensehacK/playgrounds
/python/PF/Intro/Day8/Exercise41.py
796
3.546875
4
#PF-Exer-41 #This verification is based on string match. def sum_all(function, data): total_sum = 0 normal_sum = 0 for d in data : if function(d) : normal_sum = normal_sum + d #total_sum = total_sum + normal_sum return normal_sum #list_of_nos=[1,3,4,5,6,7,8,9,10,15,20,30,110] list_of_nos = [100,200,300,500,1040] #list_of_nos = [25,26,27,28,29,30,147,187] greater = lambda x : x > 10 divide = lambda x : (x % 10 == 0) and (x <= 100) range_of_values = lambda x : (x >= 25) and (x <= 50) #Use the below given print statements to display the output # Also, do not modify them for verification to work print(sum_all(greater,list_of_nos)) print(sum_all(divide,list_of_nos)) print(sum_all(range_of_values,list_of_nos))
1a91d8877583316ae1e0df1a28c9160a83664d33
pedrohcf3141/CursoEmVideoPython
/CursoEmVideoExercicios/Desafio027.py
152
4.0625
4
# Desafio 27 nome = input('Digite seu nome ').strip().split() print('Primeiro nome {}'.format(nome[0])) print('Primeiro nome {}'.format(nome[-1]))
925bbd3f1fc80058cd94f48a93a396b88bbb8cf8
chenglinguang/python-class
/classnew.py
3,702
4.125
4
''' Created on Apr 12, 2016 @author: echglig ''' class Student(object): def __init__(self,name,score): self.name=name self.score=score def print_score(self): print('%s: %s' % (self.name,self.score)) def get_grade(self): if self.score>=90: return 'A' elif self.score>=60: return 'B' else: return 'C' bart=Student('Bart Simpson',90) lisa=Student('Lisa Simpson',70) bart.print_score() lisa.print_score() print(bart.get_grade()) print(lisa.get_grade()) bart.age=9 print(bart.age) #print(lisa.age) #Private variables: class New_Student(object): def __init__(self,name,score): self.__name=name self.__score=score def print_score(self): print('%s: %s' % (self.__name,self.__score)) def get_name(self): return self.__name def get_score(self): return self.__score def set_score(self,score): if 0<=score<=100: self.__score=score else: raise ValueError('bad score') new_bart=New_Student('Bart Anderson',98) new_lisa=New_Student('Lisa Anderson',60) new_bart.print_score() new_lisa.print_score() print(new_bart.get_name()) print(new_bart.get_score()) class Animal(): def run(self): print('Animal is running....') class Dog(Animal): def run(self): print('Dog is running......') def eat(self): print('Cat is eating.......') class Cat(Animal): def run(self): print('Cat is running......') dog=Dog() cat=Cat() dog.run() cat.run() a=list() b=Animal() c=Dog() #usage of isinstance print(isinstance(a,list)) print(isinstance(b,Animal)) print(isinstance(c,Dog)) print(isinstance(c,Animal)) print(isinstance(b,Dog)) def run_twice(animal): animal.run() animal.run() run_twice(Animal()) run_twice(Dog()) #对于一个变量,我们只需要知道它是Animal类型,无需确切地知道它的子类型, #就可以放心地调用run()方法,而具体调用的run()方法是作用在Animal、Dog、Cat还是Tortoise对象上, #由运行时该对象的确切类型决定,这就是多态真正的威力:调用方只管调用,不管细节,而当我们新增一种Animal的子类时, #只要确保run()方法编写正确,不用管原来的代码是如何调用的。这就是著名的“开闭”原则: ###use type to get the object style print(type(123)) print(type('str')) print(type(abs)) print(type(123)==int) print(type('abc')==str) #types import types def fn(): pass print(type(fn)==types.FunctionType) print(type(abs)==types.BuiltinFunctionType) print(type(lambda x: x)==types.LambdaType) print(type((x for x in range(10)))==types.GeneratorType) #isinstance print(isinstance('a', str)) print(isinstance(123,int)) print(isinstance(c,Animal)) print(isinstance(c,Animal) and isinstance(c,Dog)) print(isinstance([1, 2, 3], (list, tuple))) print(isinstance((1,2,3),(list,tuple))) #get the attr dir('ABC') print(dir('ABC')) print(len('ABC')) print('ABC'.__len__()) print('ABC'.lower()) class MyObject(object): def __init__(self): self.x=9 def power(self): return self.x*self.x obj=MyObject() print(hasattr(obj,'x')) print(hasattr(obj,'y')) print(setattr(obj,'y',9)) print(hasattr(obj,'y')) print(getattr(obj,'y')) print(obj.y) ####attr class AStudent(object): def __int__(self,name): self.name=name #s=AStudent('Bob') #s.score=50 #class attribute class BStudent(object): name='Student' sb=BStudent() print(sb.name) sb.name='Michael' print(sb.name) del sb.name print(sb.name)
4d9e0dbef8ce61e27cf5648ce35459ff4730a7d0
givaldodecidra/controle-combustivel
/consumo.py
1,076
3.859375
4
#!/usr/bin/env python # -*- coding: utf-8 -*- from __future__ import print_function ## pega o valor da kilometragem inicial do carro km_inicial = float(raw_input("Digite a kilometragem inicial: ")) ## pega o valor da kilometragem final do carro km_final = float(raw_input("Digite a kilometragem Final: ")) ## pega o valor do combustível valor = float(raw_input("Digite o valor do combustível: ")) ## pega a quantidade em litros de combustível litros = float(raw_input("Digite a quantidade de litros: ")) # calcula a kilometragem rodada km_rodados = km_final - km_inicial # valor pago pelo combustível valor_pago = valor * litros #calcula o consumo do carro consumo = km_rodados / litros print("Informações:") print("Quilometragem inicial: {0} km\nQuilometragem final: {1} km".format(km_inicial, km_final)) print("Valor do combustível: R$ {0}\nLitros de combustível: {1} l".format(valor, litros)) print("Resultados:") print('Valor do Combustível: R$', valor_pago) print('O carro rodou: ', km_rodados, 'km') print('O carro está fazendo: ', consumo, 'Km/lt')
1a6af15e5d5ce5e04e11ff5b5fd9129c4e19a44b
314H/Data-Structures-and-Algorithms-with-Python
/Graphs/Prim's Algorithm Problem.py
3,088
3.953125
4
""" ----------------------- Prim's Algorithm Problem ----------------------------- Given an undirected, connected and weighted graph G(V, E) with V number of vertices (which are numbered from 0 to V-1) and E number of edges. Find and print the Minimum Spanning Tree (MST) using Prim's algorithm. For printing MST follow the steps - 1. In one line, print an edge which is part of MST in the format - v1 v2 w where, v1 and v2 are the vertices of the edge which is included in MST and whose weight is w. And v1 <= v2 i.e. print the smaller vertex first while printing an edge. 2. Print V-1 edges in above format in different lines. Note : Order of different edges doesn't matter. Input Format : Line 1: Two Integers V and E (separated by space) Next E lines : Three integers ei, ej and wi, denoting that there exists an edge between vertex ei and vertex ej with weight wi (separated by space) Output Format : MST Constraints : 2 <= V, E <= 10^5 Sample Input 1 : 4 4 0 1 3 0 3 5 1 2 1 2 3 8 Sample Output 1 : 0 1 3 1 2 1 0 3 5 """ import sys class Graph: def __init__(self,nVertices): self.nVertices=nVertices self.adjMatrix=[[0 for i in range(nVertices)] for j in range(nVertices)] def addEdge(self,v1,v2,wt): self.adjMatrix[v1][v2]=wt self.adjMatrix[v2][v1]=wt def removeEdge(self,v1,v2): if self.containsEdge(v1,v2) is False: return self.adjMatrix[v1][v2]=0 self.adjMatrix[v2][v1]=0 def containsEdge(self,v1,v2): return True if self.adjMatrix[v1][v2]>0 else False def __str__(self): return str(self.adjMatrix) def __getMinVertex(self,visited,weight): min_vertex=-1 for i in range(self.nVertices): if visited[i] is False and (min_vertex==-1 or weight[min_vertex]>weight[i]): min_vertex=i return min_vertex def prims(self): visited=[False for i in range(self.nVertices)] parent=[-1 for i in range(self.nVertices)] weight=[sys.maxsize for i in range(self.nVertices)] weight[0]=0 for i in range(self.nVertices-1): min_vertex=self.__getMinVertex(visited,weight) visited[min_vertex]=True for j in range(self.nVertices): if self.adjMatrix[min_vertex][j]>0 and visited[j] is False: if weight[j]>self.adjMatrix[min_vertex][j]: weight[j]=self.adjMatrix[min_vertex][j] parent[j]=min_vertex for i in range(1,self.nVertices): if i<parent[i]: print(str(i)+" "+str(parent[i])+" "+str(weight[i])) else: print(str(parent[i])+" "+str(i)+" "+str(weight[i])) li=[int(ele) for ele in input().split()] n=li[0] E=li[1] g=Graph(n) for i in range(E): curr_input=[int(ele) for ele in input().split()] g.addEdge(curr_input[0],curr_input[1],curr_input[2]) g.prims()
d93ed82879e70534a7ec1259fba89ba341c39c79
Tezameru/scripts
/python/pythontut/0011_tuples.py
231
3.78125
4
coordinates = (4, 5) # coordinates[1] = 10 does not work, because tuples are immutable, they cannot be changed print(coordinates[0]) # you can make a list of tuples coords = [(9, 4), (4, 6), (3, 7)] print(coords) print(coords[2])
b154e06fa331038bcb860fa3d3def67ce9834397
nickest14/Leetcode-python
/python/medium/Solution_79.py
2,680
3.65625
4
# 79. Word Search from typing import List class Solution: def exist(self, board: List[List[str]], word: str) -> bool: rows, cols = len(board), len(board[0]) path = set() def dfs(r, c, i): if i == len(word): return True if (min(r, c) < 0 or r >= rows or c >= cols or word[i] != board[r][c] or (r, c) in path): return False path.add((r, c)) ans = (dfs(r + 1, c, i + 1) or dfs(r - 1, c, i + 1) or dfs(r, c + 1, i + 1) or dfs(r, c - 1, i + 1)) path.remove((r, c)) return ans for r in range(rows): for c in range(cols): if dfs(r, c, 0): return True return False class Solution2: def exist(self, board, word: str) -> bool: if not word: return False self.board = board self.x_axis = len(board) self.y_axis = len(board[0]) for x in range(self.x_axis): for y in range(self.y_axis): if board[x][y] == word[0]: used = set() used.add((x, y)) if self.checkword(x, y, word[1:], used): return True return False def checkword(self, x, y, word, used): if len(word) == 0: return True # check up if x-1 >= 0 and (x-1, y) not in used and self.board[x-1][y] == word[0]: used.add((x-1, y)) if self.checkword(x-1, y, word[1:], used): return True else: used.remove((x-1, y)) # check right if y+1 < self.y_axis and (x, y+1) not in used and self.board[x][y+1] == word[0]: used.add((x, y+1)) if self.checkword(x, y+1, word[1:], used): return True else: used.remove((x, y+1)) # check down if x+1 < self.x_axis and (x+1, y) not in used and self.board[x+1][y] == word[0]: used.add((x+1, y)) if self.checkword(x+1, y, word[1:], used): return True else: used.remove((x+1, y)) # check left if y-1 >= 0 and (x, y-1) not in used and self.board[x][y-1] == word[0]: used.add((x, y-1)) if self.checkword(x, y-1, word[1:], used): return True else: used.remove((x, y-1)) return False board = [ ['A', 'B', 'C', 'E'], ['S', 'F', 'C', 'S'], ['A', 'D', 'E', 'E'] ] word = 'ASD' ans = Solution().exist(board, word) print(ans)
05d63521e7703c4301cf72a984e73915eff1f1b1
isaacburke/GradeCalculator
/142_grade.py
1,136
3.84375
4
#weight LAB=.1 HW=.1 PROJ=.1 EX1=.17 EX2=.23 FIN=.3 def main(): #lab lab_g=100 lab_t=90 g_lab=score(lab_g,lab_t,LAB) #hw hw_g=10+10+12+15+18+20 hw_t=10+14+15+15+20+20 g_hw=score(hw_g,hw_t,HW) #proj proj_g=40 proj_t=40 g_proj=score(hw_g,hw_t,PROJ) #ex1 ex1_g=61 ex1_t=60 g_ex1=score(ex1_g,ex1_t,EX1) #ex2 ex2_g=62.5 ex2_t=64 g_ex2=score(ex2_g,ex2_t,EX2) #fin fin_g=73 fin_t=75 g_fin=score(fin_g,fin_t,FIN) percent=g_lab+g_hw+g_proj+g_ex1+g_ex2+g_fin print("Your percentage is ",format(percent*100,".2f"),"%",sep="") print("Your letter grade is ",grade(percent)) print("Your GPA is",gpa(percent)) def gpa(percent): p=percent*100 if p>95: g=4.0 elif percent>=62: g=(0.1)*percent-(5.5) else: g=0.0 return g def score(grade,total,weight): return (grade/total)*weight def grade(percent): s=percent*100 if s>=90: g="A" elif s>=80: g="B" elif s>=70: g="C" elif s>=60: g="D" else: g="F" return g main()
14f952e81e76418707cfe91aaee7a6787ada8527
ishanoon/advance_python
/not_function.py
205
3.96875
4
def is_even(num): if num % 2 == 0: return True else: return False numbers = [1,56,234,87,4,76,24,69,90,135] print([n for n in numbers if not(is_even(n))])