blob_id
string
repo_name
string
path
string
length_bytes
int64
score
float64
int_score
int64
text
string
7f84a02124f4b669371f0350c6230e5d2edcf990
vtsartas/ejpython
/ejpy/ejElenaPY/22_hoja-V-7_tres_cifras_reves.py
1,376
4.25
4
# Ejercicio 22 (hoja V, 7) - Pedir un número de tres cifras y si lo es invertir el orden de estas # Pedimos por pantalla el número a verificar num = int(input("Introduce un número de tres cifras (100 a 999): ")) # Si el número está entre 100 y 999 tendrá 3 cifras y lo pondremos al revés if num>99 and num<1000: # las unidades serán el resto de dividir el número entre 10 unidades=int(num%10) texto="Unidades={}" print(texto.format(unidades)) # las decenas serán el resto de dividir el número menos las unidades entre 100 entre 10 decenas=int(((num-unidades)%100)/10) texto="Decenas={}" print(texto.format(decenas)) # las centenas serán el resto de dividir el número menos las unidades y las decenas entre 100 entre 100 centenas=int((((num-unidades)-(decenas*10))%1000)/100) texto="Centenas={}" print(texto.format(centenas)) # el número al revés se obtendra convirtiendo las unidades en centenas, las decenas tal cual y las centenas se dejan como unidades numfinal=int((unidades*100)+(decenas*10)+centenas) texto="El numero original ({}) al revés es {}." print(texto.format(num,numfinal)) else: # si el número no tiene 3 cifras lo indicamos print("Número incorrecto: tiene más o menos de tres cifras")
561840249f9c3f68014899343e950f371eb3a974
YOGESH-TECH/python-basic-problems
/monday.py
399
3.796875
4
year=int(input("enter the year here: ")) ref_year=1900 diff=year-ref_year lyear=diff//4 nyear=diff-lyear td=((nyear*365)+(lyear*366)) day=td%7 if day==0: print("monday") elif day==1: print("tuesday") elif day==2: print("wednessday") elif day==3: print("thrusday") elif day==4: print("friday") elif day==5: print("sat.") elif day==6: print("sunday") else: print("error")
f4497baa33da90534488a1ecc26a0cc6f3bd4972
TorpidCoder/Python
/W3School/List/10.py
160
4
4
list = ['sail','nikki','vimal','manju','rajkumar','killer'] n = int(input("Enter the number : ")) for vals in list: if(len(vals)>n): print(vals)
bb0a90d66dac3ee34710779782512ac4ac3f6fc7
Billshimmer/blogs
/algorithm_problem/spiral_matrix_ii.py
890
3.515625
4
#!/usr/bin/python # -*- coding: latin-1 -*- # leetcode 59 class Solution(object): def spiralMatrix(self, n): if n == 0: return [] if n == 1: return [[1]] self.Array = [ [ 0 for __ in range(n)] for __ in range(n) ] self.Array[0][0] = 1 self.runInMatrix(0, -1, n-1, 1) return self.Array def runInMatrix(self, i, j, le, step): self.Array[i][j+step] = self.Array[i][j] + 1 x, y = 0, 0 if le == 0: return while x < le+1: x += 1 j += step self.Array[i][j] = self.Array[i][j-step] + 1 while y < le: y += 1 i += step self.Array[i][j] = self.Array[i-step][j] + 1 self.runInMatrix(i, j, le-1, step*-1) if __name__ == "__main__": print(Solution().spiralMatrix(4))
5d49162b0935047a90c7c84fc29949ecb5631e1b
arthurDz/algorithm-studies
/leetcode/number_of_connected_components_in_an_undirected_graph.py
1,126
3.96875
4
# Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph. # Example 1: # Input: n = 5 and edges = [[0, 1], [1, 2], [3, 4]] # 0 3 # | | # 1 --- 2 4 # Output: 2 # Example 2: # Input: n = 5 and edges = [[0, 1], [1, 2], [2, 3], [3, 4]] # 0 4 # | | # 1 --- 2 --- 3 # Output: 1 # Note: # You can assume that no duplicate edges will appear in edges. Since all edges are undirected, [0, 1] is the same as [1, 0] and thus will not appear together in edges. def countComponents(self, n, edges): d = collections.defaultdict(list) for x, y in edges: d[x].append(y) d[y].append(x) to_visit = set(range(n)) def dfs(node): to_visit.remove(node) for i in d[node]: if i in to_visit: dfs(i) count = 0 while to_visit: node = next(iter(to_visit)) dfs(node) count += 1 return count + len(to_visit)
7bf05a23763155cf74e1b6e521bd602fd7400cf2
ericdegan/Curso-em-Video
/ex044.py
759
3.84375
4
valor = float(input('Qual o valor a pagar R$:')) pag = input('Você pode pagar em [1] Dinheiro ou [2] Cartão qual você prefere? ').upper() if pag == ('1'): print('Em dinheiro você ganha 10% de desconto vai ficar R$:{:.2f}'.format(valor - (valor/100) * 10)) elif pag == ('2'): cart = input('Voce quer pagar á [1] vista, em [2] 2x ou [3] 3x no cartão? ') if cart == '2': print('Em duas vezes o vai ficar R$:{:.2f} por mês'.format(valor/2)) elif cart == '3': juros = (valor/100) * 20 print('Em três vezes vai ficar R${:.2f} por mês'.format(valor/3 + juros)) else: desc = (valor/100) * 5 print('A vista no cartão temos 5% de desconto, vai ficar R$:{:.2f}'.format(valor - desc))
5ed0c019d962c97d5684afded731c0775f56765a
ChrisXi/Hadoop-Learning
/Streaming version/mapper.py
1,674
3.609375
4
#!/usr/bin/env python import sys # input comes from STDIN (standard input) for line in sys.stdin: # remove leading and trailing whitespace line = line.strip() # split the line into words words = line.split() # increase counters #print len(words) i0 = 0 for i1 in range(i0+1,len(words)-1): for i2 in range(i1+1,len(words)): # write the results to STDOUT (standard output); # what we output here will be the input for the # Reduce step, i.e. the input for reducer.py # # tab-delimited; the trivial word count is 1 #get possible triangle t0 = int(words[i0]) t1 = int(words[i1]) t2 = int(words[i2]) #sort for key n1 = 0;n1 = 0;n2 = 0 if t0<t1: if t0<t2: n0 = t0 if t1<t2: n1 = t1;n2 = t2 else: n1 = t2;n2 = t1 else: n0 = t2;n1 = t0;n2 = t1 else: if t1<t2: n0 = t1 if t0<t2: n1 = t0;n2 = t2 else: n1 = t2;n2 = t0 else: n0 = t2;n1 = t1;n2 = t0 #maper output, value as triangle if t1<t2: tri = words[i0]+','+words[i1]+','+words[i2] print '%s%s%s\t%s' % (n0, n1, n2, tri) else: tri = words[i0]+','+words[i2]+','+words[i1] print '%s%s%s\t%s' % (n0, n1, n2, tri)
05cfc0d2d57b3e4e5fe16a281eec7faf33970abf
gopalkrishna12/json2xml
/src/cli.py
620
3.515625
4
import sys import argparse from src.json2xml import Json2xml def main(argv=None): parser = argparse.ArgumentParser(description='Utility to convert json to valid xml.') parser.add_argument('--url', dest='url', action='store') parser.add_argument('--file', dest='file', action='store') args = parser.parse_args() if args.url: url = args.url data = Json2xml.fromurl(url) print(Json2xml.json2xml(data)) if args.file: file = args.file data = Json2xml.fromjsonfile(file) print(Json2xml.json2xml(data)) if __name__ == "__main__": main(sys.argv)
8d5f817d8cbc9b7849713b74ee4ed343df2a39ad
Janepoor/Python-Practice-
/first non-repeat char.py
303
3.625
4
### first non-repeat char def firstchar(inputstring): hash={} for i in inputstring: if i not in hash: hash[i]=1 else: hash[i]+=1 for i in inputstring: if hash[i]==1: return i return ('##') print (firstchar("hhelloworld"))
cc32e2ce1a8dc494bc420357f674f48c04bfa2d8
green-fox-academy/FulmenMinis
/week-02/day-01/seconds_in_a_day.py
387
4.125
4
current_hours = 14 current_minutes = 34 current_seconds = 42 # Write a program that prints the remaining seconds (as an integer) from a # day if the current time is represented bt the variables remaining_hours = 24-current_hours remaining_minutes = 60-current_minutes remaining_seconds = 60-current_seconds print(remaining_seconds + (remaining_minutes * 60) + (remaining_hours * 3600))
5c294a50fecad04d67394d388be16fd588585012
TheSmurfs/pypractice
/week4/员工信息表程序/main.py
6,730
3.84375
4
#!/usr/bin/env python #-*- coding:utf-8 -*- # author:FCQ # datetime:2018/7/11 19:24 # software: PyCharm #!/usr/bin/env python # -*- coding:utf-8 -*- # Author: Colin Yao """python 员工信息表操作""" import sys import os def select1(): ''' 查看文件函数 :return: ''' with open('peopledb', 'r', encoding='utf-8') as f: line = f.readlines() for i in line: print(i) def select(): ''' 查询函数 :return: ''' msg = ''' 请输入或复制查询命令例如:    1. select name,age from staff_table where age > 22    2. select * from staff_table where dept = "IT" 3. select * from staff_table where enroll_date like "2013" ''' print(msg) user_choice_input = input(">>>:") user_choice_input1 = user_choice_input.split(' ') if user_choice_input == 'select name,age from staff_table where age > %s' % (user_choice_input1[7]): with open('peopledb', 'r+', encoding='utf-8') as f: list1 = [] count = 0 for line in f: i = line.strip().split(',') if i[2] > user_choice_input1[7]: list1.append(i) for s in list1: count = count + 1 for j in list1: print(j) print('满足条件的个数为>>:%s' % (count)) elif user_choice_input == ('select * from staff_table where dept = %s' % (user_choice_input1[7])): with open('peopledb', 'r+', encoding='utf-8') as f: list2 = [] count = 0 for line in f: i1 = line.strip().split(',') if i1[4] == eval(user_choice_input1[7]): list2.append(i1) for s1 in list2: count = count + 1 # print(list1) for j1 in list2: print(j1) print('满足条件的个数为>>:%s' % (count)) elif user_choice_input == ('select * from staff_table where enroll_date like %s' % (user_choice_input1[7])): with open('peopledb', 'r+', encoding='utf-8') as f: list3 = [] list4 = [] count = 0 for line in f: i = line.strip().split(',') list3.append(i) for j in list3: m = j[5].split('-') if m[0] == eval(user_choice_input1[7]): list4.append(j) for s in list4: count = count + 1 if count < 1: print("没有找到类似的条目:") pass else: pass for j in list4: print(j) print('满足条件的条数为>>:%s' % (count)) return () def alter(): ''' 添加函数 :return: ''' msg = ''' 1)添加命令如下:Jack Wang,30,13304320533,HR,2015-05-03 ''' print(msg) user_choice_input = input("请输入命令>>>:") user_choice_input1 = user_choice_input.split(',') with open('peopledb', 'r+', encoding='utf-8') as f: list = [] for line in f: s2 = line.strip().split(',') m = s2[3] list.append(m) if user_choice_input1[2] in list: print('这条记录已经存在') main() else: my_index = str(len(list) + 1) user_choice_input1.insert(0, my_index) user_choice_input1 = ','.join(user_choice_input1) f.write('\n') f.write(user_choice_input1) f.close() print("记录添加完成", '\n') select1() return () def delect(): ''' 删除函数 :return: ''' print("请输入删除命令例如: 输入用户ID 既可以从staff_table里删除") msg = ''' 1)按1 删除、直接删除ID即可 2)按2或者q退出 3)按任意返回上一层 ''' print(msg) user_choice_input = input("请输入命令>>>: ") if user_choice_input == '1': print("现有的用户为:") select1() print('\n') user_choice_input1 = input("请输入需要删除的用户ID:") user_choice_input2 = user_choice_input1[0] f = open('peopledb', 'r+', encoding='utf-8') f1 = open('new_peopledb', 'w+', encoding='utf-8') for line in f: i = line.strip().split(',') i1 = i[0] if user_choice_input2 != i1: i = ','.join(i) f1.write(i) f1.write('\n') else: continue f.close() f1.close() os.remove('peopledb') os.rename('new_peopledb', 'peopledb') print('\n') select1() elif user_choice_input == '2' or 'q': sys.exit() return () def update(): ''' 更新函数 :return: ''' msg = ''' 1)这里第一个等号按照没有空格的格式划分 2)命令范例:UPDATE staff_table SET dept="INS" where dept = "HR" ''' print(msg) user_choice_input = input("请输入命令>>>:") user_choice_input1 = user_choice_input.split(' ') dept = user_choice_input1[3].split('=') dept_new = dept[1] dept_old = user_choice_input1[7] if user_choice_input == ('UPDATE staff_table SET dept=%s where dept = %s' % (dept_new, dept_old)): dept_new1 = eval(dept_new) dept_old1 = eval(dept_old) f = open('peopledb', 'r+', encoding='utf-8') f1 = open('new_peopledb', 'w+', encoding='utf-8') for line in f: i = line.strip().split(',') dept_change = i[4] if dept_change == dept_old1: i[4] = eval(dept_new) i = ','.join(i) f1.write(i) f1.write('\n') f.close() f1.close() os.remove('peopledb') os.rename('new_peopledb', 'peopledb') print('\n') select1() pass return () def main(): ''' 交互程序 :return: ''' print("员工信息表操作作业练习") msg = ''' 1)查询 2)添加 3)删除 4)更新 5) 退出 ''' exit_flag = False while not exit_flag: print(msg) user_choice = input("请选择>>:") if user_choice == '1': select() elif user_choice == '2': alter() elif user_choice == '3': delect() elif user_choice == '4': update() elif user_choice == '5' or 'q': sys.exit() else: print("您的选择有误、请重新输入") main()
7c6bbe6c69ec15bf7bd2a9efbed8753d4e030a70
kazukazu7/p-semi
/question3.py
871
3.59375
4
import random from collections import Counter import statistics as st sum = 0 list = [] for i in range(1000): i = random.randint(1, 6) sum = sum + i list.append(i) list.sort() # N=1000 N = len(list) print("合計は" + str(sum)) def average(): # 平均値を求める ave = sum / N print("平均は" + str(ave)) def median(): # 中央値を求める median1 = N / 2 median2 = N / 2 + 1 median1 = int(median1) - 1 median2 = int(median2) - 1 med = (list[median1] + list[median2]) / 2 print("中央値は" + str(med)) def mode(): # 最頻値を求める c = Counter(list) mod = c.most_common(1) print("最頻値は" + str(mod[0][0]) + "で" + str(mod[0][1]) + "個ありました") def sd(): # 標準偏差を求める print("標準偏差は" + str(st.stdev(list))) average() median() mode() sd()
00f58c5501e33b39ec61c8436ea2effeb1d88168
IANHUANGGG/Gomoku-AI
/Five-In-a-Row/src/board.py
1,754
3.71875
4
from src.piece import Piece import src.util import src.constant as cons import copy class Board: def __init__(self): self.board = [[Piece.EMPTY for col in range(cons.NORMAL_B_HEIGHT)] for row in range(cons.NORMAL_B_WIDTH)] self.height = cons.NORMAL_B_HEIGHT self.width = cons.NORMAL_B_WIDTH def resetBoard(self): """ Reset the Board to empty """ self.board = [[Piece.EMPTY for col in range(15)] for row in range(15)] def getBoard(self): """ return a copy of the board """ return copy.deepcopy(self.board) def place_piece(self, piece, row, col): """ return true if placed a piece on the board successfully Arguments: piece {Piece} -- either EMPTY, WHITE, or BLACK """ return self.board[row][col] def piece_type(self, row, col): return self.board[row][col] def verify_pos(self, row, col): """ verify if the given position is on the board, and return True if on the board Arguments: row {int} -- the row col {int} -- the column Returns: bool - if the given position is valid in the chess board """ return (row >= 0 and col >= 0 and row < self.height and col < self.width) def if_on_boundary(self, row, col, dir, func): """ check if a piece can be placed at the posotion where is one slot further in the direction of the given position. Returns: [bool] -- True if the position is already on the boundary """ pos = tuple(map(func, (row, col), dir.value)) return not self.verify_pos(pos[0], pos[1])
efcd6c2fd9d302466f1353cce80d55c718e5c5ba
lj1064201288/Python-Notebook
/飞机蛇的练习题/Restaurant.py
892
3.640625
4
class Restaurant(): def __init__(self, name, cuisine): self.restaurant_name = name self.cuisine_type = cuisine self.number_serced = 0 def describe_restaurant(self): print("这个餐馆的名字是:", self.restaurant_name) print("这个餐馆是一个" + self.cuisine_type + "餐馆.") def open_restaurant(self): print("该餐馆正在营业!") def set_number_served(self, num): self.num = num print(id(self.num)) print("这个餐馆最多能容纳" + str(self.num) + "人!") def increment_number_serced(self, value): self.value = value self.number_serced += self.value if restaurant.num <= restaurant.number_serced: print("餐馆已满!请明天再来!") else: print("有" + str(restaurant.number_serced) + "人来过这家餐厅!")
73666546940d16f5977cd377088779ce92141134
superhman/DSC510Spring2020
/Gunasekaran_DS510/Gunasekaran_DS510_Final_Project.py
11,905
4.09375
4
# File : Gunasekaran_DS510_FinalProject.py # Name : Ragunath Gunasekaran # Date : 05/30/2020 # Course : DSC-510 - Introduction to Programming # Assignment : # Created a header for this Program. # Created new API - # api_key = "09d020dd8193c479bf9e062588c60cfa" # Created a Python Application which asks the user for their zip code or city. # Used the zip code or city name in order to obtain weather forecast data from OpenWeatherMap. # Displayed the weather forecast in a readable format to the user. # Commented within the application where appropriate in order to document what the program is doing. # Used functions including a main function. # Allowed the user to run the program multiple times to allow them to look up weather conditions # for multiple locations. # Validated whether the user entered valid data. # If valid data isn’t presented notify the user. # Used the Requests library in order to request data from the webservice. # Used Try blocks to ensure that your request was successful. # If the connection was not successful display a message to the user. # Used try blocks when establishing connections to the webservice. # Printed a message to the user indicating whether or not the connection was successful import requests import datetime import configparser from requests.exceptions import HTTPError # Class to represent config values ( apikey, units, country, language, base URl ) class Config: def __init__(self, apikey, units, country, language, baseurl): self.apikey = apikey self.units = units self.country = country self.language = language self.baseurl = baseurl # function to retrive configuration values from config file def get_configvalues(): config = configparser.ConfigParser() config.read('config.ini') return Config(config['openweathermap']['api'], config['openweathermap']['units'], config['openweathermap']['country'], config['openweathermap']['language'], config['openweathermap']['baseurl']) # function to request for weather data def get_weatherdata(query,config): # try-except block try: api_key = config.apikey base_url = config.baseurl # base_url = "http://api.openweathermap.org/data/2.5/" complete_url = base_url + query + "&appid=" + api_key # "&cnt=3" # +"&units=metric" # get the API value into response print('Web Serivce requesting...') response = requests.get(complete_url) # returns an HTTPError object if an error has occurred during the process response.raise_for_status() # if status code 200 is succefully received the data from API if response.status_code == 200: print('sucessfull received data from Web Serivce') # convert response details into jsonresponse as JSON format return response.json() # Exception Handling except HTTPError as http_err: print(f'HTTP error occurred: {http_err}') except Exception as err: print(f'Other than HTTP error occurred: {err}') # function to display results from Json def display_results(weathers, weatherData): # try-except block try: print("Here is the Weather details of the given City or Zip Code") print("---------------------------------------------------------") print("{:<20} {:<15} {:<15} {:<15} {:<15} {:<15}{:<15} {:<15}{:<15}{:<15}".format('Date', 'Temp', 'Temp Min', 'Temp Max', 'Pressure', 'Humidity', 'description', 'Pressure', 'Wind_Speed', 'Wind Deg')) print( "--------------------------------------------------------------------------------------------------------------------------------------------------------") # Looping the weathers list of JSON objects to print the weather details for the selected Range if (weatherData == "2"): print("Name of the Place : " + (weathers['city']['name'])) for i in weathers['list']: print( "{:<20} {:<15} {:<15} {:<15} {:<15} {:<15}{:<15} {:<15}{:<15}{:<15}".format(i["dt_txt"], i["main"]["temp"], i["main"]["temp_min"] , i["main"]["temp_max"], i['main']['pressure'], i['main']['humidity'] , i['weather'][0][ 'description'], i['main']['pressure'] , i['wind']['speed'], i['wind']['deg'] )) # Current Weather details elif (weatherData == "1"): print("Name of the Place : " + (weathers['name'])) print( "{:<20} {:<15} {:<15} {:<15} {:<15} {:<15}{:<15} {:<15}{:<15}{:<15}".format("now", weathers['main']['temp'], weathers["main"]["temp_min"] , weathers["main"][ "temp_max"], weathers['main'][ 'pressure'], weathers['main']['humidity'] , weathers['weather'][0][ 'description'], weathers['main']['pressure'] , weathers['wind']['speed'], weathers['wind']['deg'] )) else: print("Invalid Entry") print( "--------------------------------------------------------------------------------------------------------------------------------------------------------") except: print("Unable to get weather information for the given City. Please try again") # main function def main(): # try-except block try: now = datetime.datetime.now() # Fetching Default Parameter Country as US and Units - Imperial from configuration file config = get_configvalues() unitsparameter = config.units countryparameter = config.country Languageparameter = config.language weatherdataoption = "weather" countparameter = 1 print("Welcome to the API : Weather Forecast Data") print('Date : ' + now.strftime("%Y-%m-%d %H:%M:%S")) # printing date & time # Driving Variable to allow User to enter multiple times iscontinue = True while (iscontinue): print("************MAIN MENU**************") inputselection = input("Select your choice : \n" "1. Temperature Unit Selection - Default " + unitsparameter + " \n" + "2. Country Selection - Default " + countryparameter + " \n" + "3. Language Selection - Default " + Languageparameter + " \n" + "4. Search City or Zip \n" + "5. Exit \n") # If User wants to change to metric C if inputselection == "1": inputunitsparameters = input("Please Enter Units : 1. metric (celcius) or 2. imperial (fahrenheit)\n") if inputunitsparameters == "1": unitsparameter = "metric" elif inputunitsparameters == "2": unitsparameter = "imperial" else: " Please enter 1 or 2 to update Units" # If User wants to change the Country from US to different Country elif inputselection == "2": countryparameter = input("Please Enter the 2 digit Country ISO Code\n") # If User wants to change the Country from US to different Country elif inputselection == "3": Languageparameter = input("Please Enter Language to view\n") # If Users choose to search by City or Zip code elif inputselection == "4": city = input('Enter zip code or City name: \n') inputweatherDataoption = input( 'Enter Your Choice of Weather Data : 1. Current Weather Data 2. 3 hour forecast data \n') if inputweatherDataoption == "1": weatherdataoptionparameter = "weather" elif inputweatherDataoption == "2": countparameter = input("Please enter Number of Forecasting (only Integer days) \n") weatherdataoptionparameter = "forecast" else: print("Invalid Input. Please select the option 1 or 2") continue if city.isdigit(): query = weatherdataoptionparameter + '?zip=' + city + "," + countryparameter + "&" + "units=" + unitsparameter + "&" + "lang=" + Languageparameter + "&cnt=" + str( countparameter) else: query = weatherdataoptionparameter + '?q=' + city + "," + countryparameter + "&" + "units=" + unitsparameter + "&" + "lang=" + Languageparameter + "&cnt=" + str( countparameter) # Calling get_weatherdata function to get the API response details as JSON w_data = get_weatherdata(query, config); # Calling display_results function to display all the details display_results(w_data, str(inputweatherDataoption)) # Exit Option elif inputselection == "5": SystemExit iscontinue = False # Invalid Option else: print("Invalid Input : Please enter 1,2,3,4,5 Only") except Exception as err: print(f'Other than HTTP error occurred: {err}') if __name__ == '__main__': main()
64afa25a0ab78e0a536883dccd63398da8206f27
ANKerD/competitive-programming-constests
/uri/upsolving/2175/code.py
194
3.734375
4
a,b,c = map(float, raw_input().split()) if a == b or b == c or a == c: print 'Empate' elif a == min(a,b,c): print 'Otavio' elif b == min(a,b,c): print 'Bruno' else: print 'Ian'
85d07d593a26735e39441af937d47294d9026f3d
nuekodory/AtCoder
/Other/SoundHound2018/F.py
162
3.71875
4
input_line = input().split() a = int(input_line[0]) b = int(input_line[1]) if a + b == 15: print("+") elif a * b == 15: print("*") else: print("x")
8207e1092bab6cae13ed8d63d8c437d11c1af78a
theravikumar/dataStructure
/queue_List.py
618
3.9375
4
class queue: def __init__(self): self.List = [] def enqueue(self,value): self.List.append(value) def dequeue(self): del self.List[0] def peek(self): print(self.List[0]) def isEmpty(self): if len(self.List)==0: print("the queue is empty") else: print("the queue is not empty") def printQueue(self): print(self.List) Queue = queue() Queue.enqueue(5) Queue.printQueue() Queue.dequeue() Queue.isEmpty() for i in range(10): Queue.enqueue(i) Queue.isEmpty() Queue.peek() Queue.printQueue()
f1cdfe661a81438835dd02ef9ab2485e4f61be20
Viditagarwal7479/Assignments-2021
/Week1/run.py
679
4.03125
4
## This is the most simplest assignment where in you are asked to solve ## the folowing problems, you may use the internet ''' Problem - 0 Print the odd values in the given array ''' arr = [5,99,36,54,88] ## Code Here i=0 count=0 while(i<5) if(arr[0]%2!=0) count+=1 i+=1 print(count) ''' Problem - 1 Print all the prime numbers from 0-100 ''' i=1 while(i=<100) i+=1; w=2; if(i==2) print(2); else a=true while(w<i) if(i%w==0) a=false break w+=1 if(a) print(i) ## Code Here ''' Problem - 2 Print the reverse of a string ''' string = 'Reverse Me!' ## Code Here, i=10 while(i>=0) print(string[i]) i-=1
8b631e49768fc802011b27d5e1cd610ac1c065ef
jonnytrade/Learning_Python
/Other task/String.py
67
3.78125
4
word = "Hello World" print(word) print(word[::-1]) a=10 b=5 print(a>b)
aadaf9fbd54b68f249c2a96d2e3ac2793299f9e5
kiminh/implementation_of_papers
/CF_recommender_system/BPR/accuracy.py
306
3.578125
4
# accuracy.py import numpy as np # dataset that will be given to accuracy calculating functions must have [ [~~~~~, real_value, predicted_value] * number_of_data ] form def RMSE(dataset): return np.sqrt(np.mean([float((true_value - prediction)**2) for (_, _, true_value, prediction) in dataset]))
3d78f8ba2acdf2e2f479a5ca1b1544c04e5eb784
katonamac/CSES-7960
/day1.py
1,275
4.28125
4
# Day 1 of Python course num = 7 num_float = 7.0 l = [2,3,4,5,6] item = 3 print(item == 3) #note that when you aren't in the console you have to use the #print function to get an output myStr = "This is my string!" print(myStr) print(myStr[0],myStr[9],myStr[-1]) myStr = myStr + "biatch" #An equivalent way to do this is myStr += "biatch" print(myStr.startswith('this')) print(myStr.startswith('This')) myList = [1, 'Jim', 17.3, [1,2,3,]] myList.append('Jack') #to instantiate tuples use () instead of [] myTuple = ('Emergency','Mad Kat','System') #unlike lists, tuples are immutable #dictionaries, also known as libraries, associate key:value pairs charstats = {'Moose':[16,14,17], 'Cassandra':[10,16,13]} print(charstats['Cassandra']) charstats['Alex'] = [12,18,16] print(charstats) #print the keys of a dictionary print(charstats.keys()) character = "Lana" if character == "Archer": print("Danger Zone!") elif character == "Lana": print("Noooooope!") else: print("Inapropes.") numList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for YIPE in numList: print(YIPE) if YIPE == 9: print(YIPE) secList = [10,20,30,40,50] for num in numList: for secNum in secList: print num, secList
ad628fa230030458d2c3d6bb75b8290949350a62
VishalGupta2597/batch89
/notepadwithobj.py
1,328
3.609375
4
from tkinter import * from tkinter import filedialog class text_editor: def open_file(self): f = filedialog.askopenfile(initialdir="c://", title="Select file", filetypes=(("text file", "*.txt"), ("all files", "*.*"))) def save_file(self): pass def save_as_file(self): pass def __init__(self,master): self.master=master master.title("MyNotePAd") self.text_area=Text() self.text_area.pack(fill=BOTH,expand=1) self.main_menu=Menu() self.master.config(menu=self.main_menu) #creating file menu self.file_menu=Menu(self.main_menu,tearoff=False) self.main_menu.add_cascade(label="File",menu=self.file_menu) #to add open in file menu self.file_menu.add_command(label="Open",command=self.open_file) self.file_menu.add_command(label="Save", command=self.save_file) self.file_menu.add_command(label="SaveAs", command=self.save_as_file) #seprator self.file_menu.add_separator() self.file_menu.add_command(label="Exit", command=master.quit) # creating Edit menu self.edit_menu = Menu(self.main_menu) self.main_menu.add_cascade(label="Edit", menu=self.file_menu) bob = Tk() te =text_editor(bob) bob.mainloop()
683dd7dba56426f22cfaca860c2f2c83fb6bce90
Kylar42/wvup
/Project Euler/euler20.py
229
3.9375
4
def factorial(n): if n == 0: return 1 else: recurse = factorial(n-1) result = n * recurse return result bignum = factorial(100) cursum=0 while(bignum > 0): cursum += bignum%10 bignum /= 10 print cursum
4d3bd7ea4e348e49585af33e6b2be8761af364db
mrinmoybasak/PythonTutorial
/tut9.py
349
3.6875
4
# grocery = ["harpic" , "loliop" , "shop","egg", "rice"] # print(grocery[4]) # numbers = [2,7,9,11,5,3] # numbers.remove(9) # numbers.pop() numbers.sort() # print(numbers) # numbers.reverse() # print(numbers) # print (numbers[1:5:2]) # numbers = [] # numbers.append(7) # numbers.append(71) # numbers.append(79) # numbers.insert(1,67) print(numbers)
3483ad49dedbcf7aec805141967ac529a9c8adf9
niranjan-nagaraju/Development
/python/leetcode/binary_tree_max_width/binary_tree_max_width_efficient.py
4,806
4.125
4
''' https://leetcode.com/problems/maximum-width-of-binary-tree/ Given a binary tree, write a function to get the maximum width of the given tree. The width of a tree is the maximum width among all levels. The binary tree has the same structure as a full binary tree, but some nodes are null. The width of one level is defined as the length between the end-nodes (the leftmost and right most non-null nodes in the level, where the null nodes between the end-nodes are also counted into the length calculation. Example 1: Input: 1 / \ 3 2 / \ \ 5 3 9 Output: 4 Explanation: The maximum width existing in the third level with the length 4 (5,3,null,9). Example 2: Input: 1 / 3 / \ 5 3 Output: 2 Explanation: The maximum width existing in the third level with the length 2 (5,3). Example 3: Input: 1 / \ 3 2 / 5 Output: 2 Explanation: The maximum width existing in the second level with the length 2 (3,2). Example 4: Input: 1 / \ 3 2 / \ 5 9 / \ 6 7 Output: 8 Explanation:The maximum width existing in the fourth level with the length 8 (6,null,null,null,null,null,null,7). Example 5: Input: 1 / \ 3 2 \ 9 \ 7 Output: 2 Explanation:The maximum width existing in the second level with the length 2 (3,2) Note: Answer will in the range of 32-bit signed integer. ''' ''' Solution outline: 0. Do a BFS 1. Use heap-like array positions (if root=i, left:2i+1, right 2i+2) along with each node Keep a track of the left-most position where a non-empty node exists, Keep updating of right-most position where a non-empty node end in the level width at end of any level = (right - left + 1) 3. Return max of width at any level ''' class Node(object): def __init__(self, value): self.value = value self.left = None self.right = None def __str__(self): return str(self.value) def __repr__(self): return str(self.value) class Solution(object): def widthOfBinaryTree(self, root): """ :type root: TreeNode :rtype: int """ if not root: return 0 curr_level = 0 max_width = 0 left_position = 0 right_position = 0 pos = 0 q = [(0,0,root)] while q: (pos,level,node) = q.pop(0) q.append((pos*2+1, level+1, node.left)) if node.left else None q.append((pos*2+2, level+1, node.right)) if node.right else None # We have moved to the next level # Check if previous level's width is higher than all widths seen so far if curr_level != level: curr_level = level # Current level's width > max curr_width = right_position - left_position + 1 if curr_width > max_width: max_width = curr_width # capture left-most position in this level left_position = pos # Update right-most position in this level # as we hit more nodes to the right in current level right_position = pos # Check last level's width curr_width = right_position - left_position + 1 if curr_width > max_width: max_width = curr_width return max_width if __name__ == '__main__': s = Solution() ''' 1 \ 2 ''' root = Node(1) root.right = Node(2) assert s.widthOfBinaryTree(root) == 1 ''' 1 / \ 3 2 / \ \ 5 3 9 ''' root = Node(1) root.left = Node(3) root.right = Node(2) root.left.left = Node(5) root.left.right = Node(3) root.right.right = Node(9) assert s.widthOfBinaryTree(root) == 4 ''' 1 / 3 / \ 5 3 ''' root2 = Node(1) root2.left = Node(3) root2.left.left = Node(5) root2.left.right = Node(3) assert s.widthOfBinaryTree(root2) == 2 ''' 1 / \ 3 2 / 5 ''' root3 = Node(1) root3.left = Node(3) root3.right = Node(2) root3.left.left = Node(5) assert s.widthOfBinaryTree(root3) == 2 ''' 1 / \ 3 2 / \ 5 9 / \ 6 7 ''' root4 = Node(1) root4.right = Node(2) root4.left = Node(3) root4.left.left = Node(5) root4.right.right = Node(9) root4.left.left.left = Node(6) root4.right.right.right = Node(7) assert s.widthOfBinaryTree(root4) == 8 ''' 1 / \ 3 2 \ 9 \ 7 ''' root5 = Node(1) root5.right = Node(2) root5.left = Node(3) root5.right.right = Node(9) root5.right.right.right = Node(7) assert s.widthOfBinaryTree(root5) == 2
cb47206e2f407ad15549c3b1ddbfba07d13a3f82
jing1988a/python_fb
/好咧,最后还是要搞google/hard/MinimumCosttoHireKWorkers857.py
4,809
3.640625
4
# There are N workers. The i-th worker has a quality[i] and a minimum wage expectation wage[i]. # # Now we want to hire exactly K workers to form a paid group. When hiring a group of K workers, we must pay them according to the following rules: # # Every worker in the paid group should be paid in the ratio of their quality compared to other workers in the paid group. # Every worker in the paid group must be paid at least their minimum wage expectation. # Return the least amount of money needed to form a paid group satisfying the above conditions. # # # # Example 1: # # Input: quality = [10,20,5], wage = [70,50,30], K = 2 # Output: 105.00000 # Explanation: We pay 70 to 0-th worker and 35 to 2-th worker. # Example 2: # # w per q , as low as possible WperQ [7 , 2.5 , 6] # Input: quality = [3,1,10,10,1], wage = [4,8,2,2,7], K = 3 # Output: 30.66667 # Explanation: We pay 4 to 0-th worker, 13.33333 to 2-th and 3-th workers seperately. # # # Note: # # 1 <= K <= N <= 10000, where N = quality.length = wage.length # 1 <= quality[i] <= 10000 # 1 <= wage[i] <= 10000 # Answers within 10^-5 of the correct answer will be considered correct. # Accepted # 11,831 # Submissions # 25,367 # Approach 2: Heap # Intuition # # As in Approach #1, at least one worker is paid their minimum wage expectation. # # Additionally, every worker has some minimum ratio of dollars to quality that they demand. For example, if wage[0] = 100 and quality[0] = 20, then the ratio for worker 0 is 5.0. # # The key insight is to iterate over the ratio. Let's say we hire workers with a ratio R or lower. Then, we would want to know the K workers with the lowest quality, and the sum of that quality. We can use a heap to maintain these variables. # # Algorithm # # Maintain a max heap of quality. (We're using a minheap, with negative values.) We'll also maintain sumq, the sum of this heap. # # For each worker in order of ratio, we know all currently considered workers have lower ratio. (This worker will be the 'captain', as described in Approach #1.) We calculate the candidate answer as this ratio times the sum of the smallest K workers in quality. # import heapq # class Solution(object): # def mincostToHireWorkers(self, quality, wage, K): # from fractions import Fraction # workers = sorted((Fraction(w, q), q, w) # for q, w in zip(quality, wage)) # # ans = float('inf') # pool = [] # sumq = 0 # for ratio, q, w in workers: # heapq.heappush(pool, -q) # sumq += q # # if len(pool) > K: # sumq += heapq.heappop(pool) # # if len(pool) == K: # ans = min(ans, ratio * sumq) # # return float(ans) # # import sys # class Solution: # def mincostToHireWorkers(self, quality, wage, K): # """ # :type quality: List[int] # :type wage: List[int] # :type K: int # :rtype: float # """ # # #brute force choose a worker, then choose min quality based on his wage per quality ratio. loop all possiblity # # n=len(quality) # nw=len(wage) # if n!=nw: # return -1 # if n<K: # return -1 # if K==1: # return min(wage) # ans=sys.maxsize # QandW=list(zip(quality , wage)) # QandW.sort() # print(QandW) # for i in range(n): # q=QandW[i][0] # w=QandW[i][1] # WperQ=w/q # count=1 # total=w # for j in range(n): # if j==i: # continue # candidateW=WperQ*QandW[j][0] # if candidateW<QandW[j][1]: # continue # total+=candidateW # count+=1 # if count==K: # ans = min(ans, total) # break # # # # return ans if ans!=sys.maxsize else -1 import heapq import sys class Solution(object): def mincostToHireWorkers(self, quality, wage, K): pool = [] queue = [(w / q, q, w) for q, w in zip(quality, wage)] queue.sort() sumQ = 0 ans = sys.maxsize # print(queue) for ratio, q, w in queue: sumQ += q heapq.heappush(pool, -q) if len(pool) > K: sumQ += heapq.heappop(pool) if len(pool) == K: ans = min(ans, sumQ * ratio) # print(ans) # print(pool) # print(' ') return ans # [10,20,5] # [70,50,30] # 2 # stdout # [(5, 30), (10, 70), (20, 50)] # Output # null # Expected # 105.0 test = Solution() print(test.mincostToHireWorkers([10, 20, 5], [70, 50, 30], 2))
af06056b6ddf07de7ab9146fa5b25e8fff6feecd
landron/Project-Euler
/Python/easy/problem_66_continued_fraction.py
4,231
3.984375
4
""" Square roots as continued fractions https://projecteuler.net/problem=64 Detect cycles is not possible: 2 = 1; 2 41 = 6; 2, 2, 12 55 = 7; 2, 2, 2, 14 "All irrational square roots of integers have a special form for the period; a symmetrical string, like the empty string (for √2) or 1,2,1 (for √14), followed by the double of the leading integer." """ import math def representation(number): """ continued fraction representation cycle detection does not work: 2 = 1; 2 41 = 6; 2, 2, 12 55 = 7; 2, 2, 2, 14 "Period of continued fraction for square root of n (or 0 if n is a square)." """ integer = math.floor(math.sqrt(number)) if integer**2 == number: return [integer] def get_next(number, subtrahend, denominator): # get integer out of reciprocal of (root-subtrahend)/denominator ''' 1/(a-b) = (a+b)/(a^2-b^2) (root+subtrahend)/new_denominator ''' # print(subtrahend, denominator) new_denominator = number - subtrahend * subtrahend assert new_denominator % denominator == 0 assert denominator, "only for square numbers" new_denominator = new_denominator // denominator integer = (math.floor(math.sqrt(number)) + subtrahend) // new_denominator return (integer, -(subtrahend - integer * new_denominator), new_denominator) subtrahend = integer denominator = 1 rep = [] # for i in range(20): while True: next_val, subtrahend, denominator = get_next( number, subtrahend, denominator) assert next_val > 0, "0 is impossible ?" rep.append(next_val) if next_val == 2 * integer: break # print(number, rep) return [integer] + rep def problem(limit): """ solve PE problem """ odd_period = 0 for i in range(2, limit + 1): rep = representation(i) # representation includes the square root besides the period if len(rep) % 2 == 0: odd_period += 1 return odd_period def problem_hackerrank(): """ https://www.hackerrank.com/contests/projecteuler/challenges/euler064/problem """ limit = int(input().strip()) print(problem(limit)) def test_period_series(): """ Reference "Period of continued fraction for square root of n (or 0 if n is a square)." https://oeis.org/A003285 https://planetmath.org/tableofcontinuedfractionsofsqrtnfor1n102 """ series = [ 0, 1, 2, 0, 1, 2, 4, 2, 0, 1, 2, 2, 5, 4, 2, 0, 1, 2, 6, 2, 6, 6, 4, 2, 0, 1, 2, 4, 5, 2, 8, 4, 4, 4, 2, 0, 1, 2, 2, 2, 3, 2, 10, 8, 6, 12, 4, 2, 0, 1, 2, 6, 5, 6, 4, 2, 6, 7, 6, 4, 11, 4, 2, 0, 1, 2, 10, 2, 8, 6, 8, 2, 7, 5, 4, 12, 6, 4, 4, 2, 0, 1, 2, 2, 5, 10, 2, 6, 5, 2, 8, 8, 10, 16, 4, 4, 11, 4, 2, 0, 1, 2, 12] for i, val_ref in enumerate(series): val = representation(i+1) assert len(val) > 0 # if len(val) - 1 != val_ref: # print(i+1, val_ref) # print(val) assert len(val) - 1 == val_ref def debug_validations(): """unit tests""" assert representation(2) == [1, 2] assert representation(3) == [1, 1, 2] assert representation(5) == [2, 4] assert representation(6) == [2, 2, 4] assert representation(7) == [2, 1, 1, 1, 4] assert representation(8) == [2, 1, 4] assert representation(10) == [3, 6] assert representation(11) == [3, 3, 6] assert representation(12) == [3, 2, 6] assert representation(13) == [3, 1, 1, 1, 1, 6] assert representation(14) == [3, 1, 2, 1, 6] assert representation(23) == [4, 1, 3, 1, 8] # problems assert representation(29) == [5, 2, 1, 1, 2, 10] assert representation(41) == [6, 2, 2, 12] assert representation(55) == [7, 2, 2, 2, 14] assert problem(13) == 4 test_period_series() if __name__ == "__main__": debug_validations() # print(representation(55)) # print(problem(100)) # problem_hackerrank()
83aa24e98b7587d4206fa4d983c18cecd1872d58
compilepeace/DS_AND_ALGORITHMS
/DS_with_python/trees/04_traversal.py
1,209
3.890625
4
class BTNode: def __init__(self, data): self.data = data self.left = None self.right = None def BTInput(): n = int(input()) if n == -1: return None new_node = BTNode(n) new_node.left = BTInput() new_node.right = BTInput() return new_node def BTPrint(root): if root == None: return print(f"{root.data}", end = ': ') if root.left != None: print(f"{root.left.data}", end = ', ') if root.right != None: print(f"{root.right.data}", end = ' ') print() BTPrint(root.left) BTPrint(root.right) # preorder traversal - Root, left, right def BTPreorder(root): if root == None: return print(f"{root.data}", end = ' ') BTPreorder(root.left) BTPreorder(root.right) # postorder traversal def BTPostorder(root): if root == None: return BTPostorder(root.left) BTPostorder(root.right) print(f"{root.data}", end = ' ') # inorder traversal def BTInorder(root): if root == None: return BTInorder(root.left) print(f"{root.data}", end = ' ') BTInorder(root.right) root = BTInput() BTPrint(root) print("Preorder ", end = ': ') BTPreorder(root) print() print("Inorder ", end = ': ') BTInorder(root) print() print("Postorder", end = ': ') BTPostorder(root) print()
80603d73c5a815e2cb1a02acdeeaeece897bd9d3
bauassr/Session19_assignment2
/Session19.2.py
2,140
3.671875
4
import numpy as np import pandas as pd Group1=np.array([51, 45, 33, 45, 67]) Group2= np.array([23, 43, 23, 43, 45]) Group3=np.array([ 56, 76, 74, 87, 56]) print("Group of mean",Group1.mean()) print("Group2 mean",Group2.mean()) print("Group3 mean",Group3.mean()) def getdf(value): Group = pd.DataFrame(value, columns={"Data"}) Group['Mean']= Group['Data'].mean() st = Group['Data'] - Group['Mean'] Group['Deviation']=st Group['Sq Dev']=st*st return Group Group1 = getdf(Group1) print(Group1.head()) Group2 = getdf(Group2) print(Group2.head()) Group3 = getdf(Group3) print(Group3.head()) var1 = Group1['Sq Dev'].sum()/(Group1.shape[0]-1) print('Variance of Sq. Dev for group 1:',var1) var2 = Group2['Sq Dev'].sum()/(Group2.shape[0]-1) print('Variance Sq. Dev for group 2:',var2) var3 = Group3['Sq Dev'].sum()/(Group3.shape[0]-1) print('Variance Sq. Dev for group 3:',var3) MS = (var1 + var2+var3)/3 print('MS error for groups:% 6.f' % MS) print(' Note: this is just the average within-group variance; it is not sensitive to group mean differences!') Dferror=(15 - 3) SSerror=MS*Dferror print('Intermediate steps in calculating the variance of the sample means:') GrandMean = (Group1['Data'].mean() + Group2['Data'].mean() + Group3['Data'].mean()) /3 GMean = np.array([Group1['Data'].mean() , Group2['Data'].mean() , Group3['Data'].mean()]) Grand= getdf(GMean) print(Grand) print("Sum of squares (SSmeans)=",Grand['Sq Dev'].sum()) var = Grand['Sq Dev'].sum()/(Grand.shape[0]-1) print("\nVar means=",var) MSG = (var)/5 print('\nMS error for groups:% 6.f' % MS) print('\nNote: this is just the average within-group variance; it is not sensitive to group mean differences!') DferrorG=(3 - 1) print("\nDF error for groups:" ,DferrorG) SSerrorG=MSG*DferrorG print("SS group",SSerrorG) print('\nTest statistic and critical value:') F = MSG/MS print("F =",F) print("Fcritical(2,12)=3.89\n") print("Decision: reject H0\n") print("Effect size\n") η2=3022.9/4883.7 print("APA writeup") print("F(2, 12)=9.75, p <0.05, η2=0.62.")
1c7c9e9a66c782512ada137f492a507c1d22955f
onikun94/algo_python
/src/abc049_c.py
412
3.671875
4
s = input() data = ["erase", "eraser","dream", "dreamer"] count = 0 count1 = 0 while 1: for frag in data: count += 1 print("count =",count) if s.endswith(frag): count1 += 1 s = s[:-len(frag)] print(s) print("count1 =",count1) break else: print("NO") break if not s: print("YES") break
aaf600f5de07756d75e519a6ea6d92f8d8d74c46
Andru-filit/andina
/Clase #5/15.py
74
3.734375
4
x= int (input (3)) y= int (input (2)) x= x % y x= x % y y= y % x print(y)
408c2e3ee9a830a29a3cc3bf7113e38cbd22c171
brigitteunger/katas
/test_min_insertions.py
2,416
3.953125
4
import unittest from typing import List class Solution: def minInsertions(self, s: str) -> int: if s == "" or s is None: return 0 nums = 0 expected = 0 index = -1 max_index_s = len(s) - 1 while index < max_index_s: index += 1 if s[index] == '(': expected += 1 elif index < max_index_s and s[index+1] == ')': index += 1 if expected == 0: nums += 1 else: expected -= 1 else: # letter == ) if expected == 0: nums += 2 else: expected -= 1 nums += 1 return nums + (2*expected) def minInsertions_long(self, s: str) -> int: if s == "" or s is None: return 0 s = list(s) for i in range(len(s)-2, -1, -1): if s[i] == ")" and s[i+1] == ")": s[i] = "2" del s[i+1] print(s) nums = 0 expected = 0 for letter in s: if letter == '(': expected += 1 elif letter == '2': if expected == 0: nums += 1 else: expected -= 1 else: # letter == ) if expected == 0: nums += 2 else: expected -= 1 nums += 1 return nums + (2*expected) class TestMinInsertions(unittest.TestCase): def setUp(self): self.sol = Solution() def test_canConvertString_1(self): s = "(()))" self.assertEqual(self.sol.minInsertions(s), 1) def test_canConvertString_2(self): s = "())" self.assertEqual(self.sol.minInsertions(s), 0) def test_canConvertString_3(self): s = "))())(" self.assertEqual(self.sol.minInsertions(s), 3) def test_canConvertString_4(self): s = "((((((" self.assertEqual(self.sol.minInsertions(s), 12) def test_canConvertString_5(self): s = ")))))))" self.assertEqual(self.sol.minInsertions(s), 5) def test_canConvertString_6(self): s = "()()()()()(" self.assertEqual(self.sol.minInsertions(s), 7) if __name__ == "__main__": unittest.main()
288cbc3622d1979e5708693709997faa4291392d
unclebae/Python3-tutorial
/07.string/isalphaTest.py
135
3.921875
4
str = "this"; # No space & digit in this string print (str.isalpha()) str = "this is string example....wow!!!" print (str.isalpha())
02886f4c99ac5332d13896773de1d3094a08e2cf
cardstdani/arrays-python
/QuickSort.py
371
3.921875
4
a = [41, 14, 6, 23, 19, 2, 11, 8, 30] def quickSort(n): if len(n) < 2: return n pivot = n.pop() rightList = [] leftList = [] for item in n: if item > pivot: rightList.append(item) else: leftList.append(item) return quickSort(leftList) + [pivot] + quickSort(rightList) a = quickSort(a) print(a)
48a64cfccf5470b12c6fe7693077fa3a1d783963
HourGu/python-ex
/iteration.py
847
3.953125
4
# -*- coding: cp936 -*- #����iteration ## for```in``` >>> d={'a':1,'b':2,'c':3} ## >>> for key in d: print key a c b ## >>> for value in d.itervalues(): print value 1 3 2 ## >>> for value in d: print value a c b ## >>> for key,value in d.iteritems(): print key,value a 1 c 3 b 2 >>> ## >>> for ch in 'ABC': print ch A B C #ֻҪ�ǿɵ��������ݶ�����for����isinstance���ж϶������͵����ú�������iterable���������͵�һ�֣��ж��Ƿ���ѭ�� from collections import Iterable >>> isinstance([1,2,3],Iterable) True >>> isinstance(123,Iterable) False >>> #��enumerate������ѭ��������� for i,value in enumerate(['a','b','c']): print i,value 0 a 1 b 2 c
f5abafce6c509dad03963192228120aca6b53a94
Sanford137/Python-Tetris
/tetris_9_classes.py
1,798
4.125
4
# Tetris Classes '''This program contains the classes for Tetris.''' import pygame import random # Colors BLACK = (0, 0, 0) GREY = (125, 125, 125) WHITE = (255, 255, 255) GREEN = (0, 255, 0) YELLOW = (0, 150, 150) RED = (255, 0, 0) ORANGE = (255, 100, 100) LIGHT_BLUE = (0, 0, 150) BLUE = (0, 0, 255) PURPLE = (200, 0, 200) class Block(pygame.sprite.Sprite): '''This class represents the blocks that make up the shapes.''' def __init__(self, x_cordinate, y_cordinate, y_speed, color): ''' This is the constructor function.''' super().__init__() self.image = pygame.Surface([30, 30]) self.image.fill(color) self.rect = self.image.get_rect() self.rect.x = x_cordinate self.rect.y = y_cordinate self.speed_x = 0 self.speed_y = y_speed def move_horizontal(self): '''This function finds the block's new horizontal position each time through the main program loop.''' self.rect.x += self.speed_x def move_vertical(self): '''This function finds the block's new vertical position each time through the main program loop.''' self.rect.y += self.speed_y class Box(pygame.sprite.Sprite): '''This class represents the (invisible) horizontal lines of boxes programmed so that, when a row of 10 of them is fully covered, the shapes that are helping to cover the row are destroyed.''' def __init__(self, x_cordinate, y_cordinate): '''This is the constructor function.''' super().__init__() self.image = pygame.Surface([10, 10]) self.image.fill(BLACK) self.image.set_colorkey(BLACK) self.rect = self.image.get_rect() self.rect.x = x_cordinate self.rect.y = y_cordinate
a3936646d5f48dab0d8ba5adb3485d1e30c4575d
anubeig/python-material
/MyTraining_latest/MyTraining/Pandas/ImpFunctions.py
1,209
3.53125
4
import pandas as pn dict1 = {'Names':['Nazeer','Malika','Anu','Parru','Arshiya','Seema','Amir','Asma','Mateen','Ashiq'], 'Age':[55,48,30,29,25,22,7,3,1,1], 'food':['Chicken','Fish','Chicken','Mutton','Ice','Ice','Fish','Mutton','ceralac','cerelac'], 'weight':[70,55,71,45,44,43,15,9,7,4]} df = pn.DataFrame(dict1); "sorting" print(df.sort_values('Names')) print(df.sort_values('Names',ascending=False)) print(df.sort_values(['Names','Age'],ascending=[False,True])) ipl_data = {'Team': ['Riders', 'Riders', 'Devils', 'Devils', 'Kings', 'kings', 'Kings', 'Kings', 'Riders', 'Royals', 'Royals', 'Riders'], 'Rank': [1, 2, 2, 3, 3,4 ,1 ,1,2 , 4,1,2], 'Year': [2014,2015,2014,2015,2014,2015,2016,2017,2016,2014,2015,2017], 'Points':[876,789,863,673,741,812,756,788,694,701,804,690]} df = pn.DataFrame(ipl_data) "groupby" print(df.groupby('Team').groups) "Multiple columns" print(df.groupby((['Team','Year'])).groups) print("get_group method") print(df.groupby('Year').get_group(2014)) "Iterating throup groupby object" for group,name in df.groupby('Team'): print(group) print(name) import numpy as np "Aggregate function" print(df.groupby('Year').agg(np.mean))
c5f6adce6c12cc8c17865f8956cc31ad976f75d4
anila-a/CEN-206-Data-Structures
/lab03/ex14.py
799
4.125
4
''' Program: ex14.py Author: Anila Hoxha Last date modified: 03/13/2020 Write a short Python program that takes two arrays a and b of length n storing int values, and returns the dot product of a and b. That is, it returns an array c of length n such that c[i] = a[i] · b[i], for i = 0, . . . ,n−1. ''' def dot_product(a, b, n): c = [] for i in range(0, n, 1): c.append(a[i] * b[i]) # Add product to c return c a = [] b = [] n = int(input("Enter the value of n: ")) print("Enter the first array: ") for i in range(n): a.append(int(input())) # Add elements in the array print("Enter the second array: ") for i in range(n): b.append(int(input())) # Add elements in the array print(dot_product(a, b, n)) # Call the function to print the dot product
3939624cb13024d6b430cfffcdda79b6d3188352
ucsb-cs8-f18/cs8-f18-lecture-code
/lec13/termination_trace.py
233
3.5
4
n = 3 while n > 0: if n % 5 == 0: n = -99 print n n = n + 1 ----- n = 3 3 > 0? yes print 3 n = 4 4 > 0? yes print 4 n = 5 5 > 0? yes n remainder 5 is 0! n = -99 print -99 n = -98 -98 > 0? no
b1fbffa3718f22ffb73b60333caaf54fddd8666b
NARENSTAR/python
/day14/sub function.py
140
3.890625
4
def sub(a,b): c=a-b; print("subtraction",c) return a=int(input("enter the number1:")) b=int(input("enter the number 2:")) sub(a,b)
584b7f3ee70d92b9d529bcbe46bfe29f396972e1
ShaoxiongYuan/PycharmProjects
/1. Python语言核心编程/1. Python核心/Day04/exercise05.py
256
3.859375
4
str_input = input("请输入一个字符串:") for i in str_input: print(ord(i)) while True: str_input = input("请输入编码值:") if str_input == "": break else: message = chr(int(str_input)) print(message)
d41e1b0b4b55b36ec18c9dd8da68a094eb7da4cc
AnkitaYadav1999/Python-Programs
/Arithmatic Operations.py
576
4
4
Python 3.9.2 (tags/v3.9.2:1a79785, Feb 19 2021, 13:44:55) [MSC v.1928 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> print("Arithmatic Operations") Arithmatic Operations >>> print("Addition") Addition >>> a = 10 >>> b = 20 >>> c = a + b >>> print(c) 30 >>> print("Subtraction") Subtraction >>> a = 10 >>> b = 5 >>> c = a - b >>> print(c) 5 >>> print("Multiplication") Multiplication >>> a = 10 >>> b = 2 >>> c = a*b >>> print(c) 20 >>> print("Dividation") Dividation >>> a = 50 >>> b = 5 >>> c = a % b >>> print(c) 0 >>>
1201238b1dc00b2cf65cac64434a5fa9e28451a9
inlee12/Python
/quiz4_part4.py
135
3.75
4
def non_even(x): tot =0 for k in x: if k%2 != 0: tot += k return tot x=[2,4,6,7,9] print(non_even(x))
ac155f66844f153f9533fc6564ff772561e32795
Tr4shL0rd/mathScripts
/funktioner/findFunktionsVærdien_X_Plus.py
382
3.8125
4
#https://www.matematikfessor.dk/lessons/funktionsvaerdi-for-lineaert-udtryk-2-1198?id=21391446 try: def main(): while True: print("f(x) = a*x+b") x = int(input("x = ")) a = int(input("a = ")) b = int(input("b = ")) print(a*x+b) print() main() except KeyboardInterrupt: print("CTRL-C\r\tGood-Bye") except ValueError: print("something went wrong!?\n") main()
54dae5293a39d78856ef91e37b70ddd19600a68b
c344081/learning_algorithm
/02/99.py
1,345
3.734375
4
''' Recover Binary Search Tree Two elements of a binary search tree (BST) are swapped by mistake. Recover the tree without changing its structure. Note: A solution using O(n) space is pretty straight forward. Could you devise a constant space solution? ''' # Definition for a binary tree node. class TreeNode(object): def __init__(self, x): self.val = x self.left = None self.right = None class Solution(object): def recoverTree(self, root): """ :type root: TreeNode :rtype: void Do not return anything, modify root in-place instead. """ if not root: return stack = [] x = y = prev = None while root or len(stack): while root: stack.append(root) root = root.left root = stack.pop() if prev and prev.val >= root.val: if not x: x = prev if x: y = root prev = root root = root.right x.val, y.val = y.val, x.val root = TreeNode(0) root.left = TreeNode(1) s = Solution() s.recoverTree(root) stack = [] while root or len(stack): while root: stack.append(root) root = root.left root = stack.pop() print(root.val) root = root.right
03e8b7d1821f055f9f3a68f7cdb0a2e985507f01
Flerken101/Python-Crash-Course
/Chapter 9/restaurant.py
1,343
3.921875
4
class Restaruant(): """一次模拟餐馆的简单尝试""" def __init__(self, restaurant_name, cuisine_type): """初始化描述餐馆的属性""" self.restaurant_name = restaurant_name self.cuisine_type = cuisine_type self.number_served = 0 def describe_restaurant(self): """简单描述餐馆的名字及主营菜品""" print("The " + self.restaurant_name.title() + " is mainly engaged in " + self.cuisine_type + ".") def open_restaurant(self): """打印一条消息指出餐馆正在营业""" print("The restaurant is open now.") def guests_number(self): """打印一条关于接待客人人数的消息""" print('This restaurant has received ' + str(self.number_served) + " guests.") def set_number_served(self, a): """将接待过的客人人数设置为特定的值""" if a >= self.number_served: self.number_served += a else: print("Please try again.") def increment_number_served(self, b): """将餐馆接待过的人数增加特定的值""" print("I think " + restaruant.restaurant_name.title() + " can accommodate " + str(b) + " guests today.") self.number_served += b
604a626652c1f6f94a2b3156d56f84efa06bac0a
sbhusal123/Python-Data-Structures
/Data Structures/Tuples/immutable_property.py
241
3.84375
4
x = (1,2,3) # del(x[0]) # TypeError: 'tuple' object doesn't support item deletion # x[1] = 8 # TypeError: 'tuple' object does not support item assignment # y = ([1,2,3],4,5) # del(y[0][1]) # print(y) a = (1,2,3) b = (4,5,6) print(a+b)
5ead77bf50795522e4f862c40fae3d897fb1efad
PiotrusWatson/evogame
/species.py
413
3.5
4
"""A class for each species in the game which contains the base population, speed, size, and power and possible mutations""" from mutants import Mutants from biome import Biome class Species: def __init__(self, name): self.name = name self.population = 100 self.mutants = [] self.biomes = [] def toString(self): return """Your name is {}. Population is {}""".format(self.name, self.population)
5b56868c3ef6062d012d17ba2674960cdd4a56cc
EveryDayIsAPractice/Leetcode-python3
/242_Valid_Anagram-0.py
859
3.53125
4
class Solution: def isAnagram(self, s, t): """ :type s: str :type t: str :rtype: bool """ if s is None: if t is None: return True else: return False elif t is None: return False memory=dict() memory2=dict() for i in s: if i in memory: memory[i]+=1 else: memory[i]=1 for i in t: if i in memory2: memory2[i]+=1 else: memory2[i]=1 if len(memory)!=len(memory2): return False for i in memory: if i in memory2: if memory[i]!=memory2[i]: return False else: return False return True
90741111dca4f139ebf5be3f55af61df8b488a03
akhilmn18/CollegeStuff
/AI/Python/DFS_Example.py
506
3.90625
4
GRAPH = { 'S': ['A', 'B', 'C'], 'A': ['D'], 'B': ['E'], 'C': ['F'], 'D': ['G'], 'E': [], 'F': [], 'G': [] } # Recursive DFS def dfs(node): if node not in VISITED: # Check for Visited Node print(node) VISITED.add(node) # Add node if Visited for adjacent in GRAPH[node]: # apply dfs dfs(adjacent) VISITED = set() print('Recursive Depth First Search') dfs('S')
af61ee159105da4298dde129c2520c31e0f9c248
Jetpuffed/CS-1.1-Intro-to-Programming
/spaceman/spaceman.py
4,366
4.375
4
import random def load_word(): ''' A function that reads a text file of words and randomly selects one to use as the secret word from the list. Returns: string: The secret word to be used in the spaceman guessing game ''' f = open('words.txt', 'r') words_list = f.readlines() f.close() words_list = words_list[0].split(' ') #comment this line out if you use a words.txt file with each word on a new line secret_word = random.choice(words_list) return secret_word def is_word_guessed(secret_word, letters_guessed): ''' A function that checks if all the letters of the secret word have been guessed. Args: secret_word (string): the random word the user is trying to guess. letters_guessed (list of strings): list of letters that have been guessed so far. Returns: bool: True only if all the letters of secret_word are in letters_guessed, False otherwise ''' # TODO: Loop through the letters in the secret_word and check if a letter is not in lettersGuessed correct_guesses = 0 for i in secret_word: if i in letters_guessed: correct_guesses += 1 if correct_guesses == len(secret_word): return True else: return False def get_guessed_word(secret_word, letters_guessed): ''' A function that is used to get a string showing the letters guessed so far in the secret word and underscores for letters that have not been guessed yet. Args: secret_word (string): the random word the user is trying to guess. letters_guessed (list of strings): list of letters that have been guessed so far. Returns: string: letters and underscores. For letters in the word that the user has guessed correctly, the string should contain the letter at the correct position. For letters in the word that the user has not yet guessed, shown an _ (underscore) instead. ''' #TODO: Loop through the letters in secret word and build a string that shows the letters that have been guessed correctly so far that are saved in letters_guessed and underscores for the letters that have not been guessed yet blank = "" for i in secret_word: if i in letters_guessed: blank += i else: blank += " _ " return blank def is_guess_in_word(guess, secret_word): ''' A function to check if the guessed letter is in the secret word Args: guess (string): The letter the player guessed this round secret_word (string): The secret word Returns: bool: True if the guess is in the secret_word, False otherwise ''' #TODO: check if the letter guess is in the secret word return guess in secret_word def spaceman(secret_word): ''' A function that controls the game of spaceman. Will start spaceman in the command line. Args: secret_word (string): the secret word to guess. ''' lives = 7 letter_count = len(secret_word) letters_guessed = [] #TODO: show the player information about the game according to the project spec print("Welcome to Spaceman, a clone of Hangman written in Python.") print("The word you have to guess is",letter_count,"letters long.") print("You will have 7 attempts to guess the word. Good luck!") #TODO: Ask the player to guess one letter per round and check that it is only one letter while lives > 0 and is_word_guessed(secret_word, letters_guessed) == False: guess = input("Enter a letter: ") print("You have",lives,"left.") letters_guessed.append(guess) #TODO: Check if the guessed letter is in the secret or not and give the player feedback correct_letter = is_guess_in_word(guess, secret_word) if correct_letter: print("Correct!") else: print("Incorrect!") lives -= 1 #TODO: show the guessed word so far print(get_guessed_word(secret_word, letters_guessed)) #TODO: check if the game has been won or lost is_word_guessed(letters_guessed, secret_word) if lives == 0: print("You lost! The word was:",secret_word) if lives > 0: print("You won! You correctly guessed:",secret_word) #These function calls that will start the game secret_word = load_word() spaceman(secret_word)
8afc5f1cba8232870d20d12c09b3455d9362c611
mengqhui/mnist_LeNet
/tensorflow_model.py
9,253
3.515625
4
import tensorflow as tf from tensorflow.examples.tutorials.mnist import input_data import utility def weight_variable(shape): initial = tf.truncated_normal(shape, stddev=0.1) return tf.Variable(initial) def bias_variable(shape,init_value=0.1): initial = tf.constant(init_value , shape=shape) return tf.Variable(initial) def conv2d(x, W): return tf.nn.conv2d(x, W, strides=[1, 1, 1, 1], padding='SAME') def max_pool_2x2(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 2, 2, 1], padding='SAME') def max_pool_1x1(x): return tf.nn.max_pool(x, ksize=[1, 2, 2, 1], strides=[1, 1, 1, 1], padding='SAME') def variable_summaries(var): """ Attach a lot of summaries to a Tensor (for TensorBoard visualization). """ with tf.name_scope('summaries'): mean = tf.reduce_mean(var) tf.summary.scalar('mean', mean) with tf.name_scope('stddev'): stddev = tf.sqrt(tf.reduce_mean(tf.square(var - mean))) tf.summary.scalar('stddev', stddev) tf.summary.scalar('max', tf.reduce_max(var)) tf.summary.scalar('min', tf.reduce_min(var)) tf.summary.histogram('histogram', var) def nn_layer(input_tensor, input_dim, output_dim, layer_name, act=tf.nn.relu): """ Reusable code for making a simple neural net layer. It does a matrix multiply, bias add, and then uses relu to nonlinearize. It also sets up name scoping so that the resultant graph is easy to read, and adds a number of summary ops. """ # Adding a name scope ensures logical grouping of the layers in the graph. with tf.name_scope(layer_name): # This Variable will hold the state of the weights for the layer with tf.name_scope('weights'): weights = weight_variable([input_dim, output_dim]) variable_summaries(weights) with tf.name_scope('biases'): biases = bias_variable([output_dim]) variable_summaries(biases) with tf.name_scope('Wx_plus_b'): preactivate = tf.matmul(input_tensor, weights) + biases tf.summary.histogram('pre_activations', preactivate) activations = act(preactivate, name='activation') tf.summary.histogram('activations', activations) return activations def tf_LeNet(x,y_): # input 28*28=784 # reshape for conv with tf.name_scope('input_reshape_image'): x_image = tf.reshape(x, [-1,28,28,1]) # image_shaped_input = tf.reshape(x, [-1, 28, 28, 1]) tf.summary.image('input', x_image, 10) # first layer:conv W_conv1 = weight_variable([5, 5, 1, 32]) b_conv1 = bias_variable([32]) h_conv1 = tf.nn.relu(conv2d(x_image, W_conv1) + b_conv1) h_pool1 = max_pool_2x2(h_conv1) # second layer:conv W_conv2 = weight_variable([5, 5, 32, 64]) b_conv2 = bias_variable([64]) h_conv2 = tf.nn.relu(conv2d(h_pool1, W_conv2) + b_conv2) h_pool2 = max_pool_2x2(h_conv2) # third layer:fully-connected W_fc1 = weight_variable([7 * 7 * 64, 1024]) b_fc1 = bias_variable([1024]) h_pool2_flat = tf.reshape(h_pool2, [-1, 7*7*64]) h_fc1 = tf.nn.relu(tf.matmul(h_pool2_flat, W_fc1) + b_fc1) # visible layer:output W_fc2 = weight_variable([1024, 10]) b_fc2 = bias_variable([10]) # output y_output = tf.matmul(h_fc1, W_fc2) + b_fc2 return y_output def loss(y_predition,y_label): """ Calculates the loss from the logits and the labels. Args: y_predition: Logits tensor, float - [batch_size, NUM_CLASSES]. y_labels: Labels tensor, int32 - [batch_size]. Returns: loss: Loss tensor of type float. """ with tf.name_scope('cross_entropy'): diff = tf.nn.softmax_cross_entropy_with_logits(labels=y_label, logits=y_predition) with tf.name_scope('total'): loss = tf.reduce_mean(diff) return loss class TF_Model(): def __init__(self,FLAGS): self.data_set = input_data.read_data_sets(FLAGS.data_dir, one_hot=True) self.path=FLAGS.path+"_tf_sess.ckpt" self.log_dir=FLAGS.log_path self.FLAGS=FLAGS if(FLAGS.load!=False): # load a existing model # self.inference() self.load_model() self.simple_log=utility.load_json(self.log_dir+"simple_log.json") self.current_i=self.simple_log["current_i"] else: # which means build a new model print("build a new model") self.x,self.y=self.build_graph_input() self.current_i=0 self.simple_log=dict() self.inference(self.x,self.y) self.current_i=0 self.sess = tf.InteractiveSession() tf.global_variables_initializer().run() self.saver = tf.train.Saver() utility.check_dir(self.log_dir) self.train_writer = tf.summary.FileWriter(self.log_dir + '/train', self.sess.graph) self.test_writer = tf.summary.FileWriter(self.log_dir + '/test') def load_model(self): self.sess = tf.InteractiveSession() tf.global_variables_initializer().run() self.saver= tf.train.import_meta_graph(self.path+".meta") print("loading existing model from ",self.path) self.saver.restore(self.sess,self.path) self.merged = tf.summary.merge_all() print("loading success") self.train_writer = tf.summary.FileWriter(self.log_dir + '/train', self.sess.graph) self.test_writer = tf.summary.FileWriter(self.log_dir + '/test') return def save_model(self): path=self.saver.save(self.sess,self.path) try: with open(self.log_dir+"simple_log.json","r") as f: d=json.load(f) except: d=dict() d["current_i"]=self.current_i utility.save_json(d,self.log_dir+"simple_log.json") print("model saved in path ",path) return def build_graph_input(self): with tf.name_scope('input'): # Create the model self.x = tf.placeholder(tf.float32, [None, 784], name='x-input') # Define loss and optimizer self.y_ = tf.placeholder(tf.float32, [None, 10], name='y-input') return self.x,self.y_ def inference(self,x,y_): ''' build the inference graph ''' self.y_output=tf_LeNet(x,y_) self.objective_function=loss(self.y_output,self.y_) tf.summary.scalar('cross_entropy', self.objective_function) with tf.name_scope('train'): self.train_step = tf.train.AdamOptimizer(1e-4).minimize(self.objective_function) with tf.name_scope('accuracy'): with tf.name_scope('correct_prediction'): self.correct_prediction = tf.equal(tf.argmax(self.y_output, 1), tf.argmax(self.y_, 1)) with tf.name_scope('accuracy'): # self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) self.accuracy = tf.reduce_mean(tf.cast(self.correct_prediction, tf.float32)) tf.summary.scalar('accuracy', self.accuracy) self.merged = tf.summary.merge_all() return def train(self,epoch_num=100): # Train print("training: epoch number",epoch_num) for i in utility.logged_range(epoch_num,log_info="training!"): batch_xs, batch_ys = self.data_set.train.next_batch(100) # self.sess.run(self.train_step, feed_dict={self.x: batch_xs, self.y_: batch_ys,self.keep_prob:0.1}) if i % 10 == 0: # Record summaries and test-set accuracy summary, acc = self.sess.run([self.merged, self.accuracy], feed_dict={self.x: batch_xs, self.y_: batch_ys}) self.test_writer.add_summary(summary, i+self.current_i) else: # Record train set summaries, and train if i % 100 == 99: # Record execution stats summary, _ = self.sess.run([self.merged, self.train_step], feed_dict={self.x: batch_xs, self.y_: batch_ys}) self.train_writer.add_summary(summary, i+self.current_i) else: # Record a summary summary, _ = self.sess.run([self.merged, self.train_step], feed_dict={self.x: batch_xs, self.y_: batch_ys}) self.train_writer.add_summary(summary, i+self.current_i) self.current_i+=epoch_num self.train_writer.close() self.test_writer.close() self.save_model() self.test() def test(self): # Test trained model print("now start evaluating the trained model") acc=self.sess.run(self.accuracy, feed_dict={self.x: self.data_set.test.images, self.y_: self.data_set.test.labels}) print("accuracy is ",acc) try: self.simple_log=utility.load_json(self.log_dir+"simple_log.json") except: print("simple log does not exist, create a new one") self.simple_log=dict() self.simple_log["current_i"]=self.current_i self.simple_log["acc at "+str(self.current_i)]=float(acc) utility.save_json(self.simple_log,self.log_dir+"simple_log.json")
d7a81689fa56e29cabbb21da07c471ff7e615a70
ericosur/ericosur-snippet
/python3/omc/ser1357.py
318
3.59375
4
#!/usr/bin/python3 # coding: utf-8 ''' 1+3+5+7... ''' def main(): ''' main ''' limit = 400 t = 0 k = 1 repeat = 1000 for i in range(repeat): #print(k) t += k k += 2 print(i, t) if t >= limit: break if __name__ == '__main__': main()
ddd9d480a859f453e2e2dd52a4dbb8c0fc61cb21
cuban1edziela/pisscord
/Flask_Backend_API/api/db.py
1,138
3.796875
4
import sqlite3 class Database: def __init__(self, db): self.conn = sqlite3.connect(db) self.cur = self.conn.cursor() self.cur.execute("CREATE TABLE IF NOT EXISTS contacts (id INTEGER PRIMARY KEY, name text, surname text, n text, e text)") self.conn.commit() def fetch(self): self.cur.execute("SELECT * FROM contacts") rows = self.cur.fetchall() return rows def insert(self, name, surname, n, e ): self.cur.execute("INSERT INTO contacts VALUES (NULL, ?, ?, ?, ?)", (name, surname, n, e)) self.conn.commit() def remove(self, id): self.cur.execute("DELETE FROM contacts WHERE id=?", (id,)) self.conn.commit() def update(self, id, name, surname, n, e): self.cur.execute("UPDATE contacts SET name = ?, surname = ?, n = ?, e = ? WHERE id = ?", (name, surname, n, e, id)) self.conn.commit() def __del__(self): self.conn.close() # # db = Database("contacts.db") # db.insert("Conor", "Sheridan", "711247", "84101") # db.insert("Kuba", "Niedziela", "720553", "415")
650bdece75a5d5a90a951c42948b91a1363dc06c
robertompfm/morais-parking-python
/MoraisParkingPython/model/area_estacionamento.py
1,417
3.875
4
class AreaEstacionamento(): # CONSTRUCTOR def __init__(self, nome, tipo, capacidade, especial=True, ocupacao=0): self.nome = nome self.capacidade = capacidade if capacidade > 0 else 1 self.tipo = tipo self.especial = especial self.ocupacao = ocupacao # GETTERS AND SETTERS def get_nome(self): return self.nome def set_nome(self, nome): self.nome = nome def get_capacidade(self): return self.capacidade def set_capacidade(self, capacidade): self.capacidade = capacidade def get_tipo(self): return self.tipo def set_tipo(self, tipo): self.tipo = tipo def is_especial(self): return self.especial def set_especial(self): return self.especial def get_ocupacao(self): return self.ocupacao def set_ocupacao(self, ocupacao): self.ocupacao = ocupacao # HASH def __hash__(self): return hash(self.nome) # EQUALS def __eq__(self, other): return isinstance(other, AreaEstacionamento) and self.nome == other.nome # NOT EQUAL def __ne__(self, other): return not self.__eq__(other) # STR (toString) def __str__(self): return "Area: {0}; ocupacao: {1} / {2} ({3:.2f}%)".format( self.nome, self.ocupacao, self.capacidade, (self.ocupacao / self.capacidade * 100) )
159db7ca66fb6267fec7680d3562e9e4b9b70c0e
here0009/LeetCode
/Python/294_FlipGameII.py
1,244
3.765625
4
""" You are playing the following Flip Game with your friend: Given a string that contains only these two characters: + and -, you and your friend take turns to flip two consecutive "++" into "--". The game ends when a person can no longer make a move and therefore the other person will be the winner. Write a function to determine if the starting player can guarantee a win. Example: Input: s = "++++" Output: true Explanation: The starting player can guarantee a win by flipping the middle "++" to become "+--+". Follow up: Derive your algorithm's runtime complexity. 来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/flip-game-ii 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。 """ from functools import lru_cache class Solution: def canWin(self, s: str) -> bool: @lru_cache(None) def dp(string): # print(string) for i in range(1, length): if string[i-1:i+1] == '++': if not dp(string[:i-1] + '--' + string[i+1:]): return True return False length = len(s) return dp(s) S = Solution() s = "++++" print(S.canWin(s))
328e67619c06ffea93a93a323e4ebf963caeba92
rafaelperazzo/programacao-web
/moodledata/vpl_data/303/usersdata/287/77772/submittedfiles/testes.py
401
3.796875
4
# -*- coding: utf-8 -*- #COMECE AQUI salarioh=float(input('quanto vc ganha por hora?: ')) salariob=salarioh*30 ir=salariob-(salariob*0.11) inss=salariob-(salariob*0.08) sindicato=salariob-(salariob*0.05) salariol=salariob-ir-inss-sindicato print(salariob) print('-ir(11%):(ir)R$') print('-inss(8%):'+inss+'R$') print('-sindicato(5%):(sindicato)R$') print('=salario liquido: (salariol)R$')
7a158ab33100ad8ab78bf04b8d38388935892737
Imafikus/orbital-paradox
/check_types.py
2,098
4.28125
4
import datetime def check_positive_int(value): """ Checks if provided value is positive integer. Returns True or False """ check = True try: int(value) except ValueError: check = False return check if int(value) < 0: check = False return check return check def check_positive_float(value): """ Checks if provided value is positive float. Returns True or False """ check = True try: float(value) except ValueError: check = False return check if float(value) < 0: check = False return check return check def check_datetime(value): """ Checks if provided value is a valid date in DD-MM-YYYY format. Returns True or False """ check = True #check if all three values were given try: day, month, year = value.split('-') except ValueError: check = False return check #try if they are valid values for DD-MM-YYYY format try : #datetime.datetime.strptime(value, "%d-%m-%Y") datetime.datetime.strptime(value, "%Y-%m-%d") except ValueError: check = False return check return check def check_for_letters(name): """ Checks if provided name has at least 1 letter. Returns True or False """ check = True if not isinstance(name, str) or name.isdigit() or name == "": check = False return check def check_email(email): """ Checks if provided value is a valid email. Returns True or False """ check = True if "@" not in email: check = False return check before_at, after_at = email.split("@") if "." not in after_at: check = False return check if len(before_at) == 0 or len(after_at) == 0: check = False return check before_dot, after_dot = after_at.split(".") if len(before_dot) == 0 or len(after_dot) == 0: check = False return check return check
4c54aeead1be8f44715fb19166b44115c2665197
antweer/learningcode
/intro2python/multiplication_table.py
118
3.90625
4
for num in range(1,11): for num1 in range(1,11): num2 = num*num1 print("{} x {} = {}".format(num, num1, num2))
296d7b690884a0569ea666f4fc4ced1ef37a05da
khryss/PLP
/exercises/e7_tree_iterator.py
317
3.625
4
'''Tree iterator in pre-order''' def tree_iter(tree): # tree format: ('a', ('b', None, None), None) if tree: name, child_left, child_right = tree yield name for left in tree_iter(child_left): yield left for right in tree_iter(child_right): yield right
9139b798084f54b81567e8e9ddd850fb0dcf3072
jarkynashyrova/pythoProject
/lists.py
5,905
4.53125
5
# lists (Array) a list a collection of items in a particular order. you can make # list that includes the letters, digits from 0-9 or names # the pop() method removes the element #append() add items to the list #operations: create, access, add element, remove element, copy #num = lists()# create an empty list #evens = [] # create an empty list num = 11 odds = [1, 3, 5, 7, 9,457] # 5 elements, size of 'odds list is 5 [element] # index: 0, 2, 3, 4 .... # n ind: -6 -5 -4 -3 -2 -1 # from back , there is no 0 # what is the element on index 2? it is 5, becouse indexing starts with 0 friends = ['jackson', 'said', 'linur', 'tyson'] # it is better to have same data type print(friends) # Access first_friends = friends [0] print(f"friends:{friends[0]}") print(f"friends:{friends[2]}") print(f"friends:{friends[3]}") print(f"friends:{friends[-1]}") print(f"friends:{friends[-3]}") # adding alemnts: Adding to the list # list.append(new_element) - this new_element to end of the list # list.insert(index, new_elemnts) this adds new_elemnts # add tp a friend list friends.append('obama') # append is better to use than insert to add value print(f"new friends lists:{friends}") friends.insert(0, 'messi') friends.insert(0, 'Ronaldo') print(f"new friends list after insert:{friends}") #restetting the existing element, only existing index should be used friends[2] = 'mark' # replaces Tyson with mark print(f"new friends list after reset:{friends}") #friends[7] = 'mark' # replaces Tyson with mark #print(f"new friends list after reset:{friends}") # to comment do >>ctrl + / #remove the elements by value , by index friends.remove('mark') # by value print(f"new friends list after removing 'mark': {friends}") #remove_one1 = friends.remove('mark') - this is not valid statment, since remove() does not return anything # print(remove_one1) removed_friends =[] remove_one = friends.pop(4) friends.pop(4) # pop function returns(informs) what is it is removing print(f"new friends list after popping index 4: {friends}") del friends[-1] print(f"new friends list after del index -1: {friends}") friends = [] print(f"new friends list after redefining:{friends}") names = ['Irma', 'Daria','Elizabeth','OLga'] print(names [0]) print(names [1]) print(names [2]) print(names [3]) # 3-2 names = ['Irma', 'Daria','Elizabeth','Olga'] removed_guests=[] print('***************************see removed guest') removed_guests.append(names.pop()) print(removed_guests[-1] + ",I am sorry I can't invite you for dinner.") print(removed_guests) removed_guests.append(names.pop(0)) print(removed_guests[-1] + ",I am sorry I can't invite you for dinner.") print(removed_guests) print(names) message = "I am sorry that I can't invite you for my dinner party " + names [0] + "." print(message) print(names.pop(-1) + ", I am sorry that I can't invite you for my dinner party. ") #3-3 cars = ['Jeep', 'Tesla', 'Range' 'bmw'] print(cars) message = "I would like to own a " + cars [0].title() + "." print(message) #3-4 print("*******************guest list************************") Family = ['Father', 'Grand Father', 'taine', 'Taita'] print(Family) print(f"Hi {Family [0].title()}, I would like to invite you to Family dinner.") print(f"Hi {Family [1].title()}, I would like to invite you to Family dinner.") print(f"Hi {Family [2].title()}, I would like to invite you to Family dinner.") print(f"Hi {Family [3].title()}, I would like to invite you to Family dinner.") #3-5 print(f"Hi {Family [0].title()}, my Grand father cant make for family dinner tonight.") Family [1] = 'Sultan Ata' print(f"New dinner guest list after reset:{Family}") print(f"Hi {Family [1].title()}, I would like to invite you to Family dinner.") #3-6 Family.insert(0,'Tyigun') print(f"New Family dinner list after insert:{Family}") Family.insert(3,'chon apa') print(f"New Family dinner list after insert:{Family}") Family.append('taike') print(f"New Family dinner list after append:{Family}") print(f"Hi {Family [0].title()}, I would like to invite you to Family dinner.") #3-7 Family.pop(4) print(f"new Family list after popping index 4: {Family}") print("first pop") Family.pop(-2) print(f"new Family list after popping index -2: {Family}") Family.pop(2) print(f"new Family list after popping index 2: {Family}") print(f"Hi {Family [0].title()}, you are still invited to Family dinner.") print(f"Hi {Family [1].title()}, you are still invited to Family dinner.") del Family [0] print(f" Family list after del last two after index 0: {Family}") del Family [-1] print(f" Family list after del last two after index -1: {Family}") print("****************** 03/07/2021 # orgonizing the list ****************") # sorting the list permanently names = ['Irma', 'Daria','Elizabeth','OLga'] print(names) names.sort() # changing the list in desending order for original list names.sort(reverse=True) # changing the list sorting in descending order print(names) #sorting the list temperarily and returning the copy of sorted list cars = ['Audi', 'Tesla', 'Range', 'BMW'] sorted_cars_asc = sorted(cars) sorted_cars_desc = sorted(cars,reverse = True) print(f"cars: {cars}") print(f"sorted_cars_asc: {sorted_cars_asc}") print(f"sorted_cars_desc: {sorted_cars_desc}") # reverese is used otherway around, oposite cars.reverse() # reverses the list print(f"cars: {cars}") sorted_cars_asc2 = sorted(cars) print(sorted_cars_asc2) sorted_cars_asc2.reverse() print(sorted_cars_asc2) # abstruct thinking is tested on solving some coding problems #list, sum() list_size = len(cars) print(f"list_size: {list_size}") #3-8 locations=['London', 'Australia', 'Germany', 'Crotia'] print(locations) print(sorted (locations)) print(locations) #locations.reverse() print(sorted(locations, reverse = True)) print(locations) # none: null in sql # object: evrything is an abject in the python (charcater, file, string, variable, list, fucntions,etc) # iterable: something that
bd19efc46d7d3bed2a822ed4a543313f4df43918
Md-ASIFUR-RAHMAN/Data-preprocessing
/pandas02.py
17,721
3.515625
4
#!/usr/bin/env python # coding: utf-8 # In[24]: import pandas as pd df = pd.read_csv('annual-buisness-csv.csv') df.head(50) df['year'] # In[10]: get_ipython().run_line_magic('matplotlib', 'inline') df.plot.scatter(x='hp',y='mpg') # In[11]: get_ipython().run_line_magic('matplotlib', 'inline') df.plot.scatter(x='hp',y='mpg') # In[5]: import pandas as pd df = pd.read_csv('annual-buisness-csv.csv') df.head(50) x = df[['year']] print(x) # In[ ]: # In[24]: import pandas as pd df = pd.read_csv('annual-buisness-csv.csv') df.head() #df.loc[4,'Variable_name'] # In[21]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan'],'Age':[21,17,23]}) df.head() #df.loc[2,'Age'] # data collect from data frame # In[27]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan'],'Age':[21,17,23]}) #df.head() df.loc[2,'Age'] # data collect from data frame # In[26]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan'],'Age':[21,17,23]}) df.iloc[1,2] # In[31]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan'],'Age':[21,17,23]}) df.head() df.iloc[1,0] # In[39]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan'],'Age':[21,17,23]}) df.head() df.loc[0:2,'Name':'Age'] # In[5]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan','Halima','Punnota','Rakib','Nayeem','Sayed'],'Age':[21,17,23,31,35,15,45,26]}) df.head() df.iloc[0:3,0:2] get_ipython().run_line_magic('matplotlib', 'inline') df.plot.scatter(x='Name',y='Age') # In[9]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan','Halima','Punnota','Rakib','Nayeem','Sayed'],'Age':[21,17,23,31,35,15,45,26]}) df.head() df.iloc[0:9,0:2] # In[10]: get_ipython().run_line_magic('matplotlib', 'inline') df.plot.scatter(x='Name',y='Age') # In[12]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan','Halima','Punnota','Rakib','Nayeem','Sayed'],'Age':[21,17,23,35,35,15,45,45]}) df.head() df['Age'].unique()# just unique number nibe # In[33]: import pandas as pd df=pd.DataFrame({'Name':['ayon','omee','rehan','Halima','Punnota','Rakib','Nayeem','Sayed'],'Age':[21,17,23,35,35,15,45,45]}) df.head() df1 = df[df['Age']>=23] df1 # In[25]: df1.to_csv('New-data.csv') # In[32]: import pandas as pd df = pd.read_csv('New-data.csv') df.head() df.loc[3,'Age'] # In[34]: import pandas as pd df = pd.read_csv('New-data.csv') df.head() df.loc[3,'Name'] # In[37]: import pandas as pd df = pd.read_csv('New-data.csv') df.head() df.iloc[3,1] # In[38]: import pandas as pd df = pd.read_csv('New-data.csv') df['Age']==35 # In[39]: import pandas as pd df = pd.read_csv('New-data.csv') df2 = df[df['Age']==35] df2 # In[40]: df2.to_excel('New-data2.xlsx') # In[11]: import pandas as pd df = pd.DataFrame({'Temp(c)':[25,27,35,45,10],'Sell($)':[20,25,30,35,5]}) df.head() # In[ ]: # In[15]: import pandas as pd df = pd.DataFrame({'Temp(c)':[25,27,35,45,10],'Sell($)':[20,25,30,35,5]}) df.head() get_ipython().run_line_magic('matplotlib', 'inline') df.plot.scatter(x='Temp(c)',y='Sell($)') # In[16]: import pandas as pd df = pd.DataFrame({'Temp(c)':[25,27,35,45,10],'Sell($)':[20,25,30,35,5]}) df.head() # In[17]: get_ipython().run_line_magic('matplotlib', 'inline') df.plot.scatter(x='Temp(c)',y= 'Sell($)') # In[23]: import pandas as pd calories = {'DAY1':300,'DAY2':500,'DAY3':100,'DAY4':200,'DAY5':600} c = pd.Series(calories) c.index['DAY2'] print(c) # In[24]: import pandas as pd calories = {'DAY1':300,'DAY2':500,'DAY3':100,'DAY4':200,'DAY5':600} c = pd.Series(calories) c(calories,index=['DAY2']) print(c) # In[26]: import pandas as pd calories = {'DAY1':300,'DAY2':500,'DAY3':100,'DAY4':200,'DAY5':600} c = pd.Series(calories) print(c) # In[29]: df = pd.Series(calories,index=['DAY2']) print(df) # In[37]: import pandas as pd df = pd.read_csv('New-data.csv') print(df.to_string())# full data frame show kore # In[38]: import pandas as pd df = pd.read_csv('New-data.csv') df.head()# First 5 ta show kore # In[40]: import pandas as pd df = pd.read_csv('annual-buisness-csv.csv') print(df)# FiRST 5 ta & last 5 ta show kore # In[46]: import pandas as pd data = { "Duration":{ "0":60, "1":60, "2":60, "3":45, "4":45, "5":60, "6":60, "7":45, "8":30, "9":60, "10":60, "11":60, "12":60, "13":60, "14":60, "15":60, "16":60, "17":45, "18":60, "19":45, "20":60, "21":45, "22":60, "23":45, "24":60, "25":60, "26":60, "27":60, "28":60, "29":60, "30":60, "31":45, "32":60, "33":60, "34":60, "35":60, "36":60, "37":60, "38":60, "39":45, "40":45, "41":60, "42":60, "43":60, "44":60, "45":60, "46":60, "47":45, "48":45, "49":60, "50":60, "51":80, "52":60, "53":60, "54":30, "55":60, "56":60, "57":45, "58":20, "59":45, "60":210, "61":160, "62":160, "63":45, "64":20, "65":180, "66":150, "67":150, "68":20, "69":300, "70":150, "71":60, "72":90, "73":150, "74":45, "75":90, "76":45, "77":45, "78":120, "79":270, "80":30, "81":45, "82":30, "83":120, "84":45, "85":30, "86":45, "87":120, "88":45, "89":20, "90":180, "91":45, "92":30, "93":15, "94":20, "95":20, "96":30, "97":25, "98":30, "99":90, "100":20, "101":90, "102":90, "103":90, "104":30, "105":30, "106":180, "107":30, "108":90, "109":210, "110":60, "111":45, "112":15, "113":45, "114":60, "115":60, "116":60, "117":60, "118":60, "119":60, "120":30, "121":45, "122":60, "123":60, "124":60, "125":60, "126":60, "127":60, "128":90, "129":60, "130":60, "131":60, "132":60, "133":60, "134":60, "135":20, "136":45, "137":45, "138":45, "139":20, "140":60, "141":60, "142":45, "143":45, "144":60, "145":45, "146":60, "147":60, "148":30, "149":60, "150":60, "151":60, "152":60, "153":30, "154":60, "155":60, "156":60, "157":60, "158":60, "159":30, "160":30, "161":45, "162":45, "163":45, "164":60, "165":60, "166":60, "167":75, "168":75 }, "Pulse":{ "0":110, "1":117, "2":103, "3":109, "4":117, "5":102, "6":110, "7":104, "8":109, "9":98, "10":103, "11":100, "12":106, "13":104, "14":98, "15":98, "16":100, "17":90, "18":103, "19":97, "20":108, "21":100, "22":130, "23":105, "24":102, "25":100, "26":92, "27":103, "28":100, "29":102, "30":92, "31":90, "32":101, "33":93, "34":107, "35":114, "36":102, "37":100, "38":100, "39":104, "40":90, "41":98, "42":100, "43":111, "44":111, "45":99, "46":109, "47":111, "48":108, "49":111, "50":107, "51":123, "52":106, "53":118, "54":136, "55":121, "56":118, "57":115, "58":153, "59":123, "60":108, "61":110, "62":109, "63":118, "64":110, "65":90, "66":105, "67":107, "68":106, "69":108, "70":97, "71":109, "72":100, "73":97, "74":114, "75":98, "76":105, "77":110, "78":100, "79":100, "80":159, "81":149, "82":103, "83":100, "84":100, "85":151, "86":102, "87":100, "88":129, "89":83, "90":101, "91":107, "92":90, "93":80, "94":150, "95":151, "96":95, "97":152, "98":109, "99":93, "100":95, "101":90, "102":90, "103":90, "104":92, "105":93, "106":90, "107":90, "108":90, "109":137, "110":102, "111":107, "112":124, "113":100, "114":108, "115":108, "116":116, "117":97, "118":105, "119":103, "120":112, "121":100, "122":119, "123":107, "124":111, "125":98, "126":97, "127":109, "128":99, "129":114, "130":104, "131":107, "132":103, "133":106, "134":103, "135":136, "136":117, "137":115, "138":113, "139":141, "140":108, "141":97, "142":100, "143":122, "144":136, "145":106, "146":107, "147":112, "148":103, "149":110, "150":106, "151":109, "152":109, "153":150, "154":105, "155":111, "156":97, "157":100, "158":114, "159":80, "160":85, "161":90, "162":95, "163":100, "164":105, "165":110, "166":115, "167":120, "168":125 }, "Maxpulse":{ "0":130, "1":145, "2":135, "3":175, "4":148, "5":127, "6":136, "7":134, "8":133, "9":124, "10":147, "11":120, "12":128, "13":132, "14":123, "15":120, "16":120, "17":112, "18":123, "19":125, "20":131, "21":119, "22":101, "23":132, "24":126, "25":120, "26":118, "27":132, "28":132, "29":129, "30":115, "31":112, "32":124, "33":113, "34":136, "35":140, "36":127, "37":120, "38":120, "39":129, "40":112, "41":126, "42":122, "43":138, "44":131, "45":119, "46":153, "47":136, "48":129, "49":139, "50":136, "51":146, "52":130, "53":151, "54":175, "55":146, "56":121, "57":144, "58":172, "59":152, "60":160, "61":137, "62":135, "63":141, "64":130, "65":130, "66":135, "67":130, "68":136, "69":143, "70":129, "71":153, "72":127, "73":127, "74":146, "75":125, "76":134, "77":141, "78":130, "79":131, "80":182, "81":169, "82":139, "83":130, "84":120, "85":170, "86":136, "87":157, "88":103, "89":107, "90":127, "91":137, "92":107, "93":100, "94":171, "95":168, "96":128, "97":168, "98":131, "99":124, "100":112, "101":110, "102":100, "103":100, "104":108, "105":128, "106":120, "107":120, "108":120, "109":184, "110":124, "111":124, "112":139, "113":120, "114":131, "115":151, "116":141, "117":122, "118":125, "119":124, "120":137, "121":120, "122":169, "123":127, "124":151, "125":122, "126":124, "127":127, "128":125, "129":151, "130":134, "131":138, "132":133, "133":132, "134":136, "135":156, "136":143, "137":137, "138":138, "139":162, "140":135, "141":127, "142":120, "143":149, "144":170, "145":126, "146":136, "147":146, "148":127, "149":150, "150":134, "151":129, "152":138, "153":167, "154":128, "155":151, "156":131, "157":120, "158":150, "159":120, "160":120, "161":130, "162":130, "163":140, "164":140, "165":145, "166":145, "167":150, "168":150 }, "Calories":{ "0":409.1, "1":479.0, "2":340.0, "3":282.4, "4":406.0, "5":300.5, "6":374.0, "7":253.3, "8":195.1, "9":269.0, "10":329.3, "11":250.7, "12":345.3, "13":379.3, "14":275.0, "15":215.2, "16":300.0, "18":323.0, "19":243.0, "20":364.2, "21":282.0, "22":300.0, "23":246.0, "24":334.5, "25":250.0, "26":241.0, "28":280.0, "29":380.3, "30":243.0, "31":180.1, "32":299.0, "33":223.0, "34":361.0, "35":415.0, "36":300.5, "37":300.1, "38":300.0, "39":266.0, "40":180.1, "41":286.0, "42":329.4, "43":400.0, "44":397.0, "45":273.0, "46":387.6, "47":300.0, "48":298.0, "49":397.6, "50":380.2, "51":643.1, "52":263.0, "53":486.0, "54":238.0, "55":450.7, "56":413.0, "57":305.0, "58":226.4, "59":321.0, "60":1376.0, "61":1034.4, "62":853.0, "63":341.0, "64":131.4, "65":800.4, "66":873.4, "67":816.0, "68":110.4, "69":1500.2, "70":1115.0, "71":387.6, "72":700.0, "73":953.2, "74":304.0, "75":563.2, "76":251.0, "77":300.0, "78":500.4, "79":1729.0, "80":319.2, "81":344.0, "82":151.1, "83":500.0, "84":225.3, "85":300.1, "86":234.0, "87":1000.1, "88":242.0, "89":50.3, "90":600.1, "91":201, "92":105.3, "93":50.5, "94":127.4, "95":229.4, "96":128.2, "97":244.2, "98":188.2, "99":604.1, "100":77.7, "101":500.0, "102":500.0, "103":500.4, "104":92.7, "105":124.0, "106":800.3, "107":86.2, "108":500.3, "109":1860.4, "110":325.2, "111":275.0, "112":124.2, "113":225.3, "114":367.6, "115":351.7, "116":443.0, "117":277.4, "119":332.7, "120":193.9, "121":100.7, "122":336.7, "123":344.9, "124":368.5, "125":271.0, "126":275.3, "127":382.0, "128":466.4, "129":384.0, "130":342.5, "131":357.5, "132":335.0, "133":327.5, "134":339.0, "135":189.0, "136":317.7, "137":318.0, "138":308.0, "139":222.4, "140":390.0, "142":250.4, "143":335.4, "144":470.2, "145":270.8, "146":400.0, "147":361.9, "148":185.0, "149":409.4, "150":343.0, "151":353.2, "152":374.0, "153":275.8, "154":328.0, "155":368.5, "156":270.4, "157":270.4, "158":382.8, "159":240.9, "160":250.4, "161":260.4, "162":270.0, "163":280.9, "164":290.8, "165":300.4, "166":310.2, "167":320.4, "168":330.4 } } df = pd.DataFrame(data) print(df.info()) # In[47]: print(df.head())#if the number of rows is not specified, the head() method will return the top 5 rows. # In[51]: print(df.tail())#if the number of rows is not specified, the tail() method will return the last 5 rows.From the bottom. # In[49]: print(df) # In[56]: print(df.to_string()) # In[57]: df.corr() # In[60]: df["Duration"].plot(kind = 'hist') # In[ ]: # In[69]: import pandas as pd import matplotlib.pyplot as plt df = pd.read_csv('New-data.csv') df.plot.hist() # In[70]: print(df.to_string()) # In[35]: import pandas as pd df = pd.read_csv('dirtydata (1).csv') print(df.to_string()) # Return full Data Frame with empty/null cells # In[37]: import pandas as pd df = pd.read_csv('dirtydata (1).csv') new_df = df.dropna() # Return a new Data Frame with no empty cells....By default the dropna() method returns a new DataFrame, and will not change the original. print(new_df) # In[24]: import pandas as pd df = pd.read_csv('dirtydata (1).csv') df.dropna(inplace=True) print(df.to_string())# Now the dropna(inplace = True) will NOT return a new DataFrame, but it will remove all rows containg NULL values from the original DataFrame. df.to_csv('new_csv_without_null.csv') # In[38]: import pandas as pd df = pd.read_csv('dirtydata (1).csv') df.fillna(130,inplace= True) # Replace NULL values with the number 130 print(df.to_string()) # In[33]: #The example above replaces all empty cells in the whole Data Frame. #To only replace empty values for one column, specify the column name for the DataFrame. import pandas as pd df = pd.read_csv('dirtydata (1).csv') df['Date'].fillna('2020/12/22',inplace= True)# Replace NULL values for Date column. df['Calories'].fillna(350.5,inplace= True)#Replace NULL values for Calories column. print(df.to_string()) # In[39]: import pandas as pd df = pd.read_csv('dirtydata (1).csv') x = df['Calories'].mean() # same median(). df['Calories'].fillna(x,inplace=True) y = df['Date'].mode()[0] df['Date'].fillna(y,inplace=True) print(df.to_string()) # In[45]: import pandas as pd df = pd.read_csv('dirtydata (1).csv') df['Date']= pd.to_datetime(df['Date']) print(df.to_string()) # In[4]: get_ipython().run_line_magic('matplotlib', 'inline') import numpy as np from sklearn.linear_model import LinearRegression import pandas as pd import matplotlib.pyplot as plt import matplotlib.style plt.style.use('classic') import seaborn as sns mpg_df = pd.read_csv("car-mpg.csv") mpg_df.head(50) # In[10]: mpg_df = mpg_df.drop('car_name',axis=1) # In[9]: mpg_df # In[11]: mpg_df['origin'] = mpg_df['origin'].replace({1:'america',2:'europe',3:'asia'}) # In[12]: mpg_df # In[13]: mpg_df = pd.get_dummies(mpg_df, columns=['origin']) # In[14]: mpg_df # In[15]: mpg_df.describe() # In[16]: mpg_df.describe().transpose() # In[17]: temp = pd.DataFrame(mpg_df.hp.str.isdigit()) temp[temp['hp'] == False ] # In[18]: mpg_df = mpg_df.replace('?',np.nan) # In[20]: mpg_df[mpg_df.isnull().any(axis=1)] # In[ ]: # In[ ]: # In[9]: import numpy as np print(np.cos(np.pi)) print(np.sqrt(4)) print(np.log(2)) print(np.log(np.exp(5))) # In[15]: a = np.array([1,5,9]) print(a) mat= np.array([[1,5,9],[5,9,7],[10,23,5]]) print(mat) print(mat.T) # In[26]: b = np.arange(1,10+1) print(b) print(b.reshape(5,2)) # In[28]: v = np.random.randn(15) print(v) print(v[-1]) # In[29]: print(v[np.arange(0,3)]) # In[34]: sub_mat2=v[0:2,0:3].copy() print(sub_mat2) print(v) # In[ ]:
5afd5f2c7d902962f9898981a8a640ea04d016bf
zyb8023/py_study
/zip_f/zip_demo.py
1,318
3.734375
4
import os; import zipfile; def create_zip(path): """创建一个压缩文件""" # 创建一个zip文件对象 print(os.path.basename(path)) zip_file = zipfile.ZipFile(os.path.basename(path) + ".zip", "w") # 将文件写入zip文件中,即将文件压缩 # os.walk 遍历目标文件夹,获取每一个文件和文件夹 print('开始压缩文件……') for root, dirs, files in os.walk(path, topdown=False): for name in dirs: print("正在压缩文件夹:" + os.path.join(root, name)) zip_file.write(os.path.join(root, name)) for name in files: print("正在压缩文件:" + os.path.join(root, name)) zip_file.write(os.path.join(root, name)) # 关闭zip文件对象 zip_file.close() def uncommoner(path): '''解压缩''' zFile = zipfile.ZipFile(path, 'r'); zFile.extractall(); # 程序主入口 if __name__ == "__main__": # 打包(解压缩)的文件路径(文件名) path_info = 'test' print(os.path.isdir(path_info)) if os.path.isdir(path_info): # 打包 create_zip(path_info) print('压缩完成!') elif os.path.isfile(path_info): uncommoner(path_info); print('解压缩'); else: print('文件格式不正确!')
8acd4a653443970dd861207c6fccc196579b4a05
bisoisk/An-Introduction-to-Interactive-Programming-in-Python-Part_1
/Practical Exercises/Ex1_LogicAndConditionals1.py
6,643
4.375
4
# Ex1 for logic and conditionals ################################################### # 1. Write a Python function is_even that takes as input the parameter number (an integer) and returns True if number is even # and False if number is odd. Hint: Apply the remainder operator to n (i.e., number % 2) and compare to zero. # Compute whether an integer is even. ################################################### # Is even formula # Student should enter function on the next lines. def is_even(number): if number%2==0: return True elif number%2==1: return False # Solution: def is_even(number): """Returns whether the number is even.""" return (number % 2) == 0 ################################################### # Tests # Student should not change this code. def test(number): """Tests the is_even function.""" if is_even(number): print number, "is even." else: print number, "is odd." test(8) test(3) test(12) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #8 is even. #3 is odd. #12 is even. ################################################### # 2. Write a Python function is_cool that takes as input the string name and returns True if name is either "Joe", "John" or # "Stephen" and returns False otherwise. (Let's see if Scott manages to catch this?) # Compute whether a person is cool. ################################################### # Is cool formula # Student should enter function on the next lines. def is_cool(name): return (name=="Joe") or (name=="John") or (name=="Stephen") ################################################### # Tests # Student should not change this code. def test(name): """Tests the is_even function.""" if is_cool(name): print name, "is cool." else: print name, "is not cool." test("Joe") test("John") test("Stephen") test("Scott") ################################################### # Expected output # Student should look at the following comments and compare to printed output. #Joe is cool. #John is cool. #Stephen is cool. #Scott is not cool. ################################################### # 3. Write a Python function is_lunchtime that takes as input the parameters hour (an integer in the range [1,12]) and is_am # (a Boolean “flag” that represents whether the hour is before noon). The function returns True when the input corresponds # to 11am or 12pm (noon) and False otherwise. # Compute whether the given time is lunchtime. ################################################### # Is lunchtime formula # Student should enter function on the next lines. def is_lunchtime(hour, is_am): return (hour==11 and is_am) or (hour==12 and is_am) ################################################### # Tests # Student should not change this code. def test(hour, is_am): """Tests the is_lunchtime function.""" print hour, if is_am: print "AM", else: print "PM", if is_lunchtime(hour, is_am): print "is lunchtime." else: print "is not lunchtime." test(11, True) test(12, True) test(11, False) test(12, False) test(10, False) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #11 AM is lunchtime. #12 AM is not lunchtime. #11 PM is not lunchtime. #12 PM is lunchtime. #10 PM is not lunchtime. ################################################### # 4. Write a Python function is_leap_year that take as input the parameter year and returns True if year (an integer) is a # leap year according to the Gregorian calendar and False otherwise. # Compute whether the given year is a leap year. # #if (year is not divisible by 4) then (it is a common year) #else #if (year is not divisible by 100) then (it is a leap year) #else #if (year is not divisible by 400) then (it is a common year) #else (it is a leap year) # ################################################### # Is leapyear formula # Student should enter function on the next lines. def is_leap_year(year): if (year%4 != 0): return False else: if (year%100 != 0): return True else: if (year%400 != 0): return False else: return True # Solution: def is_leap_year(year): """ Returns whether the given Gregorian year is a leap year. """ return ((year % 4) == 0 and ((year % 100) != 0 or (year % 400) == 0)) ################################################### # Tests # Student should not change this code. def test(year): """Tests the is_leapyear function.""" if is_leap_year(year): print year, "is a leap year." else: print year, "is not a leap year." test(2000) test(1996) test(1800) test(2013) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #2000 is a leap year. #1996 is a leap year. #1800 is not a leap year. #2013 is not a leap year. ################################################### # 5. Write a Python function interval_intersect that takes parameters a, b, c, and d and returns True if the intervals [a,b] # and [c,d] intersect and False otherwise. While this test may seem tricky, the solution is actually very simple. # Compute whether two intervals intersect. ################################################### # Interval intersection formula # Student should enter function on the next lines. # Solution: def interval_intersect(a, b, c, d): """Returns whether the intervals [a,b] and [c,d] intersect.""" return (c <= b) and (a <= d) ################################################### # Tests # Student should not change this code. def test(a, b, c, d): """Tests the interval_intersect function.""" print "Intervals [" + str(a) + ", " + str(b) + "] and [" + str(c) + ", " + str(d) + "]", if interval_intersect(a, b, c, d): print "intersect." else: print "do not intersect." test(0, 1, 1, 5) test(1, 2, 0, 1) test(0, 1, 2, 3) test(2, 3, -8, 1) test(0, 3, 1, 2) ################################################### # Expected output # Student should look at the following comments and compare to printed output. #Intervals [0, 1] and [1, 5] intersect. #Intervals [1, 2] and [0, 1] intersect. #Intervals [0, 1] and [2, 3] do not intersect. #Intervals [2, 3] and [-8, 1] do not intersect. #Intervals [0, 3] and [1, 2] intersect.
974b7ff3e203cb6725351ecf117e2832075b30e0
dingyaguang117/ProjectEuler
/util/Prime.py
1,675
3.6875
4
import math def PrimeList(N = None,limit = None): ''' return first N primes or primes <= limit ''' if N ==None and limit ==None: raise Exception('need either N or limit') ans = [2,3] i = 5 dt = 2 while True: if N != None and len(ans) >= N : break if limit != None and ans[-1] >= limit: break f = True for j in ans: if i%j == 0: f = False break if f: ans.append(i) i += dt dt = 6 - dt return ans def PrimeListFill(limit): ''' return primes <= limit ''' A = [True] * (limit + 1) plist = PrimeList(limit=int(math.sqrt(limit))) for p in plist: n = 2 * p while n <= limit: A[n] = False n += p ans = [] for i in xrange(2,len(A)): if A[i]: ans.append(i) return ans,A def GetIntegerFactorization(N): ''' N is the max Integer supposed to Fac ''' plist = PrimeListFill(limit=int(math.sqrt(N))) def IntegerFactorization(N): n = N ans = [] while n > 1: f = False for p in plist: if n % p == 0: ans.append(p) n /= p f = True break if not f: ans.append(n) break return ans return IntegerFactorization def GetIntegerMapFactorization(N): ''' N is the max Integer supposed to Fac ''' plist = PrimeListFill(limit=int(math.sqrt(N))) def IntegerFactorization(N): n = N ans = {} while n > 1: f = False for p in plist: if n % p == 0: if p not in ans: ans[p] = 1 else: ans[p] += 1 n /= p f = True break if not f: ans[n] =1 break return ans return IntegerFactorization #print PrimeListFill(100000) #print GetIntegerFactorization(100000)(1009) #print GetIntegerMapFactorization(100000)(1007)
7d7c3d808a9736e8a724d4e28aac1e9717cb25ad
Ranjith8796/Python-programs
/Task-1 (sum_of_the _employees).py
1,141
3.828125
4
import pandas as pd # function for returning the sum of the Employees of all Department where the Country is India def sum_of_emp(): object_2=['India'] r_df2 = df2.loc[df2['COUNTRY'].isin(object_2)] object_1=r_df2['CODE'].tolist() r_df1 = df1.loc[df1['COMPANY_CODE'].isin(object_1)] allemp=r_df1['TOTAL_EMPLOYEES'].tolist() return allemp Department={'ID':[1,2,3,4,5,], 'NAME':['Engineering & Technology','Sales, Service & Support','Marketing & Communications','Business Strategy','Marketing & Communications'], 'COMPANY_CODE':['A101','B102','C103','D104','E105'], 'TOTAL_EMPLOYEES':[100,110,120,130,140]} Company={'CODE':['A101','B102','C103','D104','E105'], 'NAME':['GOOGLE','MICROSOFT','GOOGLE','MICROSOFT','KPMG'], 'COUNTRY':['India','Australia','India','Australia','Netherlands'], 'TOTAL_EMPLOYEES':[500,1000,250,600,100]} df1=pd.DataFrame(Department) df2=pd.DataFrame(Company) soe=sum_of_emp() for i in range(0,len(soe)): soe[i]=int(soe[i]) sum_of_the_employees=sum(soe) print('The sum of the employees of all department where the country (India) is {}'.format(sum_of_the_employees))
5c2e566a0a4b1a9905b9a3d099a94d557750281b
RickWazowski98/csv_viewer
/src/tools.py
282
3.546875
4
import csv import pandas as pd def read_csv_header(path): pass def read_csv_data(path): with open(path, "r") as file: df = pd.read_csv(file, usecols=[0,1,2,3,4,5,6], delimiter=",") list_of_rows = [list(row) for row in df.values] return list_of_rows
adbbe1127e59c28fbf25ff628d7cf12c2424d286
sarae17/2019-T-111-PROG
/exams/stoduprof/sales.py
1,297
4.09375
4
def open_file(): ''' Prompts the user for a file name. Returns the corresponding file stream or None if file not found ''' try: file_name = input("Enter file name: ") file_stream = open(file_name) return file_stream except FileNotFoundError: return None def read_sales_data(file_stream): ''' Reads sales data from the given file stream. Returns a list of lists, in which each inner list contains the sales found in the corresponding line/department ''' all_sales_data = [] for line in file_stream: line_sales = line.split() line_sales_ints = [int(i) for i in line_sales] all_sales_data.append(line_sales_ints) return all_sales_data def print_averages_sales(sales_data): ''' Prints the averages sales for each department ''' print("Average sales:") for index, data in enumerate(sales_data): sum_sales = sum(data) count_sales = len(data) print("Department no. {}: {:.1f}".format(index+1, sum_sales/count_sales)) def main(): file_stream = open_file() if file_stream: sales_data = read_sales_data(file_stream) file_stream.close() print_averages_sales(sales_data) else: print("File not found!") main()
f03e7476418f393bd23a9526d1bce54b4827d735
lingzhengZHANG/Junior-Year
/Introduction to Machine Learning/Logistic Regression.py
4,512
3.53125
4
from numpy import * ''' filename='hw3_train.dat' #文件目录 def loadDataSet(): #读取数据(这里只有两个特征) dataMat = [] labelMat = [] fr = open(filename) for line in fr.readlines(): lineArr = line.strip().split() dataMat.append([1.0, float(lineArr[0]), float(lineArr[1])]) #前面的1,表示方程的常量。比如两个特征X1,X2,共需要三个参数,W1+W2*X1+W3*X2 labelMat.append(int(lineArr[2])) return dataMat,labelMat ''' def loadDataSet(): x_train= load('data/train_data.npy') y_train = load('data/train_target.npy') #print(x_train) #print(y_train) return x_train,y_train def sigmoid(inX): # sigmoid函数 return 1.0 / (1 + exp(-inX)) def gradAscent(x_train, y_train): m, n = shape(x_train) alpha = 0.001 maxCycles = 500 weights = ones((n, 1)) for k in range(maxCycles): h = sigmoid(dot(x_train,weights)) error = (y_train.reshape(len(y_train),1) - h) weights = weights + alpha * dot(x_train.transpose(),error) return weights def stocGradAscent(x_train, y_train): #dataMatrix = mat(dataMat) #classLabels = labelMat m, n = shape(x_train) alpha = 0.01 maxCycles = 100 #weights = ones((n, 1)) weights = ones((n,1)) for k in range(maxCycles): for i in range(m): # 遍历计算每一行 h = sigmoid(sum(dot(x_train[i].reshape(1,len(x_train[0])) ,weights))) error = y_train[i] - h weights = weights + alpha * error * x_train[i].reshape(len(x_train[i]),1) #print(weights.shape) #weights = weights + alpha * dot(x_train[i].transpose(),error) return weights def stocGradAscent1(dataMat, labelMat): # 改进版随机梯度上升,在每次迭代中随机选择样本来更新权重,并且随迭代次数增加,权重变化越小。 dataMatrix = mat(dataMat) classLabels = labelMat m, n = shape(dataMatrix) weights = ones((n, 1)) maxCycles = 500 for j in range(maxCycles): # 迭代 dataIndex = [i for i in range(m)] for i in range(m): # 随机遍历每一行 alpha = 4 / (1 + j + i) + 0.0001 # 随迭代次数增加,权重变化越小。 randIndex = int(random.uniform(0, len(dataIndex))) # 随机抽样 h = sigmoid(sum(dataMatrix[randIndex] * weights)) error = classLabels[randIndex] - h weights = weights + alpha * error * dataMatrix[randIndex].transpose() del (dataIndex[randIndex]) # 去除已经抽取的样本 return weights def loadDataSet1(): x_test = load('data/test_data.npy') y_test = load('data/test_target.npy') print(x_test) print(y_test) return x_test,y_test def plotBestFit(weights): # 画出最终分类的图 import matplotlib.pyplot as plt dataMat, labelMat = loadDataSet() dataArr = array(dataMat) n = shape(dataArr)[0] xcord1 = [] ycord1 = [] xcord2 = [] ycord2 = [] for i in range(n): if int(labelMat[i]) == 1: xcord1.append(dataArr[i, 1]) ycord1.append(dataArr[i, 2]) else: xcord2.append(dataArr[i, 1]) ycord2.append(dataArr[i, 2]) fig = plt.figure() ax = fig.add_subplot(111) ax.scatter(xcord1, ycord1, s=30, c='red', marker='s') ax.scatter(xcord2, ycord2, s=30, c='green') x = arange(-3.0, 3.0, 0.1) y = (-weights[0] - weights[1] * x) / weights[2] ax.plot(x, y) plt.xlabel('X1') plt.ylabel('X2') plt.show() def calculateac(weights): x_test,y_test = loadDataSet() y_predict = sigmoid(dot(x_test,weights)) #print(y_test) #print(y_test.shape) #all_len = len(y_predict) accuracy = 0 #y_predict = y_predict.reshape((len(y_predict,))) for i in range(len(y_predict)): if y_predict[i]>=0.5: y_predict[i] = 1 else: if y_predict[i] <0.5: y_predict[i] = 0 if y_predict[i]==y_test[i]: accuracy+=1 print('testset_accuracy=',accuracy/len(y_predict)) def main(): #filepath = 'C:/Users/13501/Documents/Tencent Files/1350163822/FileRecv/data/LR' dataMat, labelMat = loadDataSet() #print(dataMat.shape) #print(labelMat.shape) #weights = gradAscent(dataMat, labelMat) weights = stocGradAscent(dataMat,labelMat) #print(weights.shape) plotBestFit(weights) calculateac(weights) if __name__ == '__main__': main()
92c514d2639d25de402bfa65ad6c8e02068ef3e1
Thamarai-Selvam/Exthand-test
/Test_app.py
1,938
3.578125
4
from tkinter import * from PIL import Image,ImageTk import time #root window welcomewin = Tk() welcomewin.title("Welcome to Exthand") welcomewin.configure(background='#3C3C3C') logo = Image.open("D:\Exthand\Title.png") logocard = ImageTk.PhotoImage(logo) logolabel = Label(image=logocard) logolabel.image = logocard logolabel.place(x=3, y=20) welcome = Label(welcomewin,text='Welcome to \n\tExtHand',font="Helvetica 10 bold italic") f1bg = '#ab47bc' frame1 = LabelFrame(welcomewin,text="Begin Now.....\n\n",background=f1bg,borderwidth=0,highlightthickness=0,) frame1.grid(column=0,row=6,padx=20,pady=30) header = Label(welcomewin,background='#3C3C3C',image=PhotoImage('Title.png')) #Holders for frame1 name=StringVar() mail=StringVar() phone = StringVar() #frame1 widgets namelbl = Label(frame1,background=f1bg,foreground='#FAFAFA',text="Please Enter Your Name :") namelbl.grid(row=1,sticky=W,padx=0) nameentry = Entry(frame1,width=20,textvariable=name) nameentry.grid(row=1,column=2,sticky=W,padx=0) emaillbl = Label(frame1,background=f1bg,foreground='#FAFAFA',text="E-Mail :") emaillbl.grid(row=2,sticky=W,padx=10) mailentry = Entry(frame1,width=20,textvariable=mail) mailentry.grid(row=2,column=2,sticky=W,padx=10) phonelbl = Label(frame1,background=f1bg,foreground='#FAFAFA',text="Phone Number :") phonelbl.grid(row=3,sticky=W,padx=20) phoneentry = Entry(frame1,width=20,textvariable=phone) phoneentry.grid(column=2,row=3,sticky=W,padx=20) #frame1 button functions def pwgotp(): submit.configure(text="Please Wait...",foreground='#FAFAFA',background='lightgreen') check() def enter(): submit.configure(text="Getting OTP",foreground='#FAFAFA',background='lightgreen',command=pwgotp) #get OTP (frame1) submit = Button(frame1,text="Get OTP",foreground='#FAFAFA',background="lightgreen",command=enter) submit.grid(row=5,sticky=W) welcomewin.mainloop()
86c2c2a8756cbf616714fa23289f626292438a37
dssk2001/Rock-Paper-Scissors
/RPS.py
1,740
3.75
4
import random import tkinter as tk window = tk.Tk() window.geometry("300x300") window.title("Rock Scissor Paper") ui="" ci="" usc = 0 csc = 0 def rcc(): return random.choice(['Rock','Paper','Scissor']) def choice_to_number(choice): rps={'Scissor':0,'Paper':1,'Rock':2} return rps[choice] def result(hc,cc): global usc global csc user = choice_to_number(hc) comp = choice_to_number(cc) if (user == comp): print("Tie") elif ((user - comp) % 3 == 2): print("You win") usc += 1 else: print("Comp wins") csc += 1 # Text text_area = tk.Text(master=window, height=12, width=30) text_area.grid(column=60, row=4) answer = "Your Choice: {uc} \nComputer's Choice : {cc} \n Your Score : {u} \n Computer Score : {c}".format( uc=ui, cc=ci, u=usc, c=csc, font=('arial', 24, 'bold')) text_area.insert(tk.END, answer) def rock(): global ui global ci ui = 'Rock' ci = rcc() result(ui,ci) def paper(): global ui global ci ui = 'Paper' ci = rcc() result(ui,ci) def scissor(): global ui global ci ui = 'Scissor' ci = rcc() result(ui,ci) button1=tk.Button(text=" Scissor ",bg="blue",command=scissor, height=1,width=8,font=('calibri',15,'bold')) button1.grid(column=60,row=1) button2=tk.Button(text=" Paper ",bg="pink",command=paper, height=1,width=8,font=('calibri',15,'bold')) button2.grid(column=60,row=2) button3=tk.Button(text=" Rock ",bg="yellow",command=rock, height=1,width=8,font=('calibri',15,'bold')) button3.grid(column=60,row=3) window.mainloop()
24f9f681421781ac884004d35e8c4f815b0b533a
mkseth4774/ine-guide-to-network-programmability-python-course-files
/TSHOOT/TSHOOT#2/good.higher.py
247
4.15625
4
## ## number1 = int(input("Please enter your first number: ")) number2 = int(input("Please enter your first number: ")) if number1 > number2: HIGHEST = number1 else: HIGHEST = number2 print("The higher of the two numbers was ", HIGHEST)
c347c6cdb59c5b3f395bc0dc902d31866c1b4ff5
DavidWrightOS/Intro-Python-II
/src/adv.py
4,059
3.5
4
from room import Room from player import Player from item import Item # Declare all the rooms room = { 'outside': Room("Outside Cave Entrance", "North of you, the cave mount beckons."), 'foyer': Room("Foyer", """Dim light filters in from the south. Dusty passages run north and east."""), 'overlook': Room("Grand Overlook", """A steep cliff appears before you, falling into the darkness. Ahead to the north, a light flickers in the distance, but there is no way across the chasm."""), 'narrow': Room("Narrow Passage", """The narrow passage bends here from west to north. The smell of gold permeates the air."""), 'treasure': Room("Treasure Chamber", """You've found the long-lost treasure chamber! Sadly, it has already been completely emptied by earlier adventurers. The only exit is to the south."""), } # Declare all the items item = { 'sword': Item("sword", """a close range weapon used to defeat enemies, cut tall grass, and break open clay pots."""), 'rupee': Item("rupee", """this is the primary local unit of currency and can be used to purchase items from the local shops."""), 'key': Item("key", """this key looks like it would fit into a lock on a treasure chest."""), 'potion': Item("potion", """drink this potion to replenish your health if you are running low."""), 'hookshot': Item("hookshot", """a spring-loaded, trigger-pulled hooks attached to lengthy chains. It can can attack enemies at a distance, retrieve remote items, and attach onto certain surfaces (like wood) to pull you across large distances."""), } # Link rooms together room['outside'].n_to = room['foyer'] room['foyer'].s_to = room['outside'] room['foyer'].n_to = room['overlook'] room['foyer'].e_to = room['narrow'] room['overlook'].s_to = room['foyer'] room['narrow'].w_to = room['foyer'] room['narrow'].n_to = room['treasure'] room['treasure'].s_to = room['narrow'] # Add items to room room['outside'].items = [item['sword']] room['foyer'].items = [item['rupee'], item['potion']] room['overlook'].items = [item['hookshot']] room['treasure'].items = [item['key']] # Main # # Make a new player object that is currently in the 'outside' room. # Write a loop that: # # * Prints the current room name # * Prints the current description (the textwrap module might be useful here). # * Waits for user input and decides what to do. # # If the user enters a cardinal direction, attempt to move to the room there. # Print an error message if the movement isn't allowed. # # If the user enters "q", quit the game. def print_valid_commands(): print("""Valid commands: \'n\', \'s\', \'e\', or \'w\' move North, South, East, or West \'take <item>\' pickup an item, where <item> is the item name \'drop <item>\' drop an item, where <item> is the item name \'i\' or \'inventory\' view the items currently in your inventory \'q\' quit\n""") # Program Start possible_directions = ['n', 's', 'e', 'w'] player = Player("David", room["outside"]) player.print_location_status() print_valid_commands() # REPL Start while True: cmd = input("What would you like to do? ").strip().lower().split() num_words = len(cmd) if num_words == 1: cmd = cmd[0] if cmd == 'q': print("\nThanks for playing! Goodbye.\n") break if cmd in possible_directions: player.try_direction(cmd) continue elif cmd == 'i' or cmd == 'inventory': player.print_inventory() continue elif num_words == 2: verb = cmd[0] item_name = cmd[1] if verb == 'get' or verb == 'take': player.try_add_item_to_inventory(item_name) continue elif verb == 'drop': player.try_drop_item_from_inventory(item_name) continue print("Invalid input, please try again.\n") print_valid_commands()
0ba23f7e46e494909fcda0dd9767250703dcf91f
eltnas/ExerciciosPythonBrasil
/04 - ExerciciosListas/04.py
342
3.578125
4
vetor = [] vogal = ['A','E','I','O','U'] contVogal = 0 contConsoante = 0 for i in range(10): palavra = str(input("Escreva: ").upper()) vetor.append(palavra) if palavra in vogal: contVogal = contVogal + 1 else: contConsoante = contConsoante + 1 print("São {} consoantes!".format(contConsoante))
367a2db5539d2304773d484d9219a887ed49eb61
yeazin/python-test-tutorial-folder
/list manipulation.py
335
3.875
4
#list manipulation x=[5,544,54543,5421,85,32,424,4] #x.append(55555) #x.insert(2,555) #remove element ##x.remove(85) #remove element for specify ##x.remove(x[2]) #for count a data from the list type ##print(x.count(85)) #for finding of place of a value type #print(x.index(anything)) ## for sort of the list type x.sort() print(x)
306fdc4dde5e8f0aa01567f0ad7df135cb96d6be
AmenehForouz/leetcode-1
/python/problem-1290.py
1,653
3.765625
4
""" Problem 1290 - Convert Binary Number in a Linked List to Integer Given head which is a reference node to a singly-linked list. The value of each node in the linked list is either 0 or 1. The linked list holds the binary representation of a number. Return the decimal value of the number in the linked list. """ from typing import List class ListNode: def __init__(self, x): self.val = x self.next = None class Solution: def getDecimalValue(self, head: ListNode) -> int: number = str(head.val) currNode = head while currNode.next != None: currNode = currNode.next number = number + str(currNode.val) power = len(number) - 1 decNumber = 0 for i in number: decNumber += int(i) * (2 ** power) power -= 1 return decNumber def list_to_linkedlist(vals: List[int]) -> ListNode: head = ListNode(vals[0]) temp_node = head for i in range(1, len(vals)): temp_node.next = ListNode(vals[i]) temp_node = temp_node.next return head if __name__ == "__main__": l1 = list_to_linkedlist([1, 0, 1]) print(Solution().getDecimalValue(l1)) # Should return 5 l2 = list_to_linkedlist([0]) print(Solution().getDecimalValue(l2)) # Should return 0 l3 = list_to_linkedlist([1]) print(Solution().getDecimalValue(l3)) # Should return 1 l4 = list_to_linkedlist([1, 0, 0, 1, 0, 0, 1, 1, 1, 0, 0, 0, 0, 0, 0]) print(Solution().getDecimalValue(l4)) # Should return 18800 l5 = list_to_linkedlist([0, 0]) print(Solution().getDecimalValue(l5)) # Should return 0
cc0b4aaa92b7a22892b4f2711ee355a8b0e1109a
astamminger/zotero-bibtize
/tests/bibkey_formatter/test_formatters/test_author_formatters.py
7,679
3.53125
4
""" Test suite for BibKey formatting sequences. Tests the generation of key contents based on the author entry """ from zotero_bibtize.bibkey_formatter import KeyFormatter # # Test lower author formatting # def test_no_author_lower(): key_formatter = KeyFormatter({}) key_format = '[author:lower]' assert key_formatter.generate_key(key_format) == 'noname' def test_single_author_lower(): authors = 'Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:lower]' assert key_formatter.generate_key(key_format) == 'surname' def test_prefixed_author_lower(): authors = 'Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:lower]' assert key_formatter.generate_key(key_format) == 'prefixsurname' def test_multi_author_lower(): authors = 'Surname, Firstname and Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) # default only first author key_format = '[author:lower]' assert key_formatter.generate_key(key_format) == 'surname' # use only one author (i.e. the first author) key_format = '[author:1:lower]' assert key_formatter.generate_key(key_format) == 'surname' # use two authors from the list key_format = '[author:2:lower]' assert key_formatter.generate_key(key_format) == 'surnameprefixsurname' # use maximal three authors key_format = '[author:3:lower]' assert key_formatter.generate_key(key_format) == 'surnameprefixsurname' # # Test upper author formatting # def test_no_author_upper(): key_formatter = KeyFormatter({}) key_format = '[author:upper]' assert key_formatter.generate_key(key_format) == 'NONAME' def test_single_author_upper(): authors = 'Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:upper]' assert key_formatter.generate_key(key_format) == 'SURNAME' def test_prefixed_author_upper(): authors = 'Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:upper]' assert key_formatter.generate_key(key_format) == 'PREFIXSURNAME' def test_multi_author_upper(): authors = 'Surname, Firstname and Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) # default only first author key_format = '[author:upper]' assert key_formatter.generate_key(key_format) == 'SURNAME' # use only one author (i.e. the first author) key_format = '[author:1:upper]' assert key_formatter.generate_key(key_format) == 'SURNAME' # use two authors from the list key_format = '[author:2:upper]' assert key_formatter.generate_key(key_format) == 'SURNAMEPREFIXSURNAME' # use maximal three authors key_format = '[author:3:upper]' assert key_formatter.generate_key(key_format) == 'SURNAMEPREFIXSURNAME' # # Test capitalized author formatting # def test_no_author_capitalize(): key_formatter = KeyFormatter({}) key_format = '[author:capitalize]' assert key_formatter.generate_key(key_format) == 'NoName' def test_single_author_capitalize(): authors = 'Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:capitalize]' assert key_formatter.generate_key(key_format) == 'Surname' def test_prefixed_author_upper(): authors = 'Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:capitalize]' assert key_formatter.generate_key(key_format) == 'PrefixSurname' def test_multi_author_upper(): authors = 'Surname, Firstname and Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) # default only first author key_format = '[author:capitalize]' assert key_formatter.generate_key(key_format) == 'Surname' # use only one author (i.e. the first author) key_format = '[author:1:upper]' key_format = '[author:1:capitalize]' assert key_formatter.generate_key(key_format) == 'Surname' # use two authors from the list key_format = '[author:2:capitalize]' assert key_formatter.generate_key(key_format) == 'SurnamePrefixSurname' # use maximal three authors key_format = '[author:3:capitalize]' assert key_formatter.generate_key(key_format) == 'SurnamePrefixSurname' # # Test abbreviated author formatting # def test_no_author_abbreviate(): key_formatter = KeyFormatter({}) key_format = '[author:abbreviate]' assert key_formatter.generate_key(key_format) == 'NN' key_formatter = KeyFormatter({}) key_format = '[author:abbr]' assert key_formatter.generate_key(key_format) == 'NN' def test_single_author_abbreviate(): authors = 'Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:abbreviate]' assert key_formatter.generate_key(key_format) == 'S' key_format = '[author:abbr]' assert key_formatter.generate_key(key_format) == 'S' def test_prefixed_author_abbreviate(): authors = 'Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) key_format = '[author:abbreviate]' assert key_formatter.generate_key(key_format) == 'PS' key_format = '[author:abbr]' assert key_formatter.generate_key(key_format) == 'PS' def test_multi_author_abbreviate(): authors = 'Surname, Firstname and Prefix Surname, Firstname' key_formatter = KeyFormatter({'author': authors}) # default only first author key_format = '[author:abbreviate]' assert key_formatter.generate_key(key_format) == 'S' key_format = '[author:abbr]' assert key_formatter.generate_key(key_format) == 'S' # use only one author (i.e. the first author) key_format = '[author:1:abbreviate]' assert key_formatter.generate_key(key_format) == 'S' key_format = '[author:1:abbr]' assert key_formatter.generate_key(key_format) == 'S' # use two authors from the list key_format = '[author:2:abbreviate]' assert key_formatter.generate_key(key_format) == 'SPS' key_format = '[author:2:abbr]' assert key_formatter.generate_key(key_format) == 'SPS' # use maximal three authors key_format = '[author:3:abbreviate]' assert key_formatter.generate_key(key_format) == 'SPS' key_format = '[author:3:abbr]' assert key_formatter.generate_key(key_format) == 'SPS' def test_missing_author(): """Test editor is used if author is missing""" key_format = '[author]' # check that editor is used if author not present editors = 'Surname, Firstname and Prefix Surname, Firstname' authors = '' key_formatter = KeyFormatter({'author': authors, 'editor': editors}) assert key_formatter.generate_key(key_format) == 'Surname' # check authors take precedence over editors editors = 'Editor, Firstname and Prefix Author, Firstname' authors = 'Author, Firstname and Prefix Author, Firstname' key_formatter = KeyFormatter({'author': authors, 'editor': editors}) assert key_formatter.generate_key(key_format) == 'Author' # check No Name author is used if none is present editors = '' authors = '' key_formatter = KeyFormatter({'author': authors, 'editor': editors}) assert key_formatter.generate_key(key_format) == 'NoName' def test_author_list_split_for_name_containing_and(): """Test that author lists are only split at and that is not part of a name""" key_format = '[author]' authors = 'Ackland, G. J. and Bacon, D. J. and Calder, A. F.' key_formatter = KeyFormatter({'author': authors}) assert key_formatter.generate_key(key_format) == 'Ackland'
5056723c07701b29b5ba8f4555be10a52bb7b640
krstoilo/SoftUni-Fundamentals
/Python-Fundamentals/Exams/shopping_list.py
842
4
4
shopping_list = input().split("!") command = input() while command != "Go Shopping!": if "Urgent" in command: command = command.split() if command[1] not in shopping_list: shopping_list.insert(0, command[1]) elif "Unnecessary" in command: command = command.split() if command[1] in shopping_list: shopping_list.remove(command[1]) elif "Correct" in command: command = command.split() if command[1] in shopping_list: shopping_list = [command[2] if x == command[1] else x for x in shopping_list] elif "Rearrange" in command: command = command.split() if command[1] in shopping_list: shopping_list.remove(command[1]) shopping_list.append(command[1]) command = input() print(", ".join(shopping_list))
737044d300685f6c1d111fc3a17acb15ba82d2ee
contactsohail07/Huffman-Coding
/huff.py
1,279
3.875
4
inp_string=raw_input("enter the string ") def frequency(): global inp_string freq={} for char in inp_string: freq[char]=freq.get(char,0)+1 return freq inp_freq=frequency() def sort(dict): inp_list=[] for char in dict: inp_list.append((dict[char],char)) inp_list.sort() return inp_list lis_tup=sort(inp_freq) def least_add(lis): while len(lis)>1: least_two=(lis[0:2]) add=lis[0][0]+lis[1][0] bal=lis[2:] lis=bal + [(add,least_two)] lis.sort() return lis[0] res_leaf=least_add(lis_tup) def resultant_leaves(tup): ch=tup[1] if type(ch)==type(""): return ch else: return (resultant_leaves(ch[0]),resultant_leaves(ch[1])) result_leaves=resultant_leaves(res_leaf) codes={} def assign_codes(tupl,s=''): global codes if type(tupl)==type(""): codes[tupl]=s else: assign_codes(tupl[0],s+"0") assign_codes(tupl[1],s+"1") return codes assigned_codes=assign_codes(result_leaves) print(assigned_codes) def encode(dic): enc_string="" global inp_string for char in inp_string: enc_string+=dic[char] return enc_string res_string=encode(assigned_codes) print(res_string)
449f78675dd6e62d724c708546de2627f9b0b5a3
sheetal101/loop
/average.py
227
3.8125
4
i=1 count=0 sum=0 while i<=4: A=int(input("enter a weight: ")) sum=sum+A count=count+1 i=i+1 print(sum) print(sum/count) average=sum/count if average%5==0: print("divisible") else: print("not divisible")
97296de5e01d888f2acb09cc888d53a7ea188ba4
qmnguyenw/python_py4e
/geeksforgeeks/python/python_all/147_1.py
4,304
4.46875
4
Python program for word guessing game Python is a powerful multi-purpose programming language used by multiple giant companies. It has simple and easy to use syntax making it perfect language for someone trying to learn computer programming for first time. It is a high- level programming language, and its core design philosophy is all about code readability and a syntax which allows programmers to express concepts in a few lines of code. In this article, we will use random module to make a word guessing game. This game is for beginners learning to code in python and to give them a little brief about using strings, loops and conditional(If, else) statements. > **random module** : > Sometimes we want the computer to pick a random number in a given range, > pick a random element from a list, pick a random card from a deck, flip a > coin, etc. The random module provides access to functions that support these > types of operations. One such operation is random.choice() method (returns a > random item from a list, tuple, or string.) that we are going to use in > order to select one random word from a list of words that we’ve created. In this game, there is a list of words present, out of which our interpreter will choose 1 random word. The user first has to input their names and then, will be asked to guess any alphabet. If the random word contains that alphabet, it will be shown as the output(with correct placement) else the program will ask you to guess another alphabet. User will be given 12 turns(can be changed accordingly) to guess the complete word. Below is the Python implementation: ## Python3 __ __ __ __ __ __ __ import random # library that we use in order to choose # on random words from a list of words name = input("What is your name? ") # Here the user is asked to enter the name first print("Good Luck ! ", name) words = ['rainbow', 'computer', 'science', 'programming', 'python', 'mathematics', 'player', 'condition', 'reverse', 'water', 'board', 'geeks'] # Function will choose one random # word from this list of words word = random.choice(words) print("Guess the characters") guesses = '' # any number of turns can be used here turns = 12 while turns > 0: # counts the number of times a user fails failed = 0 # all characters from the input # word taking one at a time. for char in word: # comparing that character with # the character in guesses if char in guesses: print(char) else: print("_") # for every failure 1 will be # incremented in failure failed += 1 if failed == 0: # user will win the game if failure is 0 # and 'You Win' will be given as output print("You Win") # this print the correct word print("The word is: ", word) break # if user has input the wrong alphabet then # it will ask user to enter another alphabet guess = input("guess a character:") # every input character will be stored in guesses guesses += guess # check input with the character in word if guess not in word: turns -= 1 # if the character doesn’t match the word # then “Wrong” will be given as output print("Wrong") # this will print the number of # turns left for the user print("You have", + turns, 'more guesses') if turns == 0: print("You Loose") --- __ __ **Output:** What is your name? Gautam Good Luck! Gautam Guess the characters _ _ _ _ _ guess a character:g g _ _ _ _ guess a character:e g e e _ _ guess a character:k g e e k _ guess a character:s g e e k s You Win The word is: geeks Attention geek! Strengthen your foundations with the **Python Programming Foundation** Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the **Python DS** Course. My Personal Notes _arrow_drop_up_ Save
0b8578558ca24d1999db75c3ded6adc42eff4cbe
981377660LMT/algorithm-study
/11_动态规划/dp分类/区间dp/dfs/回文/1278. 分割回文串 III-枚举分割点.py
1,353
3.625
4
from functools import lru_cache # 首先,你可以将 s 中的部分字符修改为其他的小写英文字母。 # 接着,你需要把 s 分割成 k 个非空且不相交的子串,并且每个子串都是回文串。 # 请返回以这种方式分割字符串所需修改的最少字符数。 # 1 <= k <= s.length <= 100 # 总结: # 枚举分割点+记忆化dfs class Solution: def palindromePartition(self, s: str, k: int) -> int: @lru_cache(None) def cal(left: int, right: int) -> int: """计算[left,right]修改多少个字符能变成回文""" if left >= right: return 0 return cal(left + 1, right - 1) + int(s[left] != s[right]) @lru_cache(None) def dfs(index: int, remain: int) -> int: if index >= n: return int(1e20) if remain == 1: return cal(index, n - 1) res = n for mid in range(index, n): res = min(res, cal(index, mid) + dfs(mid + 1, remain - 1)) return res n = len(s) return dfs(0, k) print(Solution().palindromePartition(s="abc", k=2)) # 输出:1 # 解释:你可以把字符串分割成 "ab" 和 "c",并修改 "ab" 中的 1 个字符,将它变成回文串。
bb381455e2bcf75bd8679ed5413a17c6a70247f4
fgardete/pdsnd_github
/Bikeshare_GiadaSartori_3.py
7,557
4.375
4
import time import pandas as pd import numpy as np CITY_DATA = { 'chicago': 'chicago.csv', 'new york city': 'new_york_city.csv', 'washington': 'washington.csv' } def get_filters(): """ Asks user to specify a city, month, and day to analyze. Returns: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day - name of the day of week to filter by, or "all" to apply no day filter """ print('Hello! Let\'s explore some US bikeshare data together!') # get user input for city (chicago, new york city, washington). HINT: Use a while loop to handle invalid inputs city = input("Choose a city between chicago, new york city or washington: ").lower() while city not in CITY_DATA: print('Sorry, the city you entered is not correct. Try again.') city = input("Choose a city between chicago, new york city or washington: ").lower() # get user input for month (all, january, february, ... , june) month = input("Choose a month from january to june or all: ").lower() while month not in ['january', 'february', 'march', 'april', 'may', 'june', 'all']: print('Sorry, the month you entered is not correct. Try again.') month = input("Choose a month from january to june or all: ").lower() # get user input for day of week (all, monday, tuesday, ... sunday) day = input("Choose a day from monday to sunday or all: ").lower() while day not in ['all', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday', 'sunday']: print('Sorry, the day of week you entered is not correct. Try again.') day = input("Choose a day from monday to sunday or all: ").lower() print('-'*40) return city, month, day MONTH_DATA = {'january': 1, 'february': 2, 'march': 3, 'april': 4, 'may': 5, 'june': 6 } DAY_DATA = {'monday': 0, 'tuesday': 1, 'wednesday': 2, 'thursday': 3, 'friday': 4, 'saturday': 5, 'sunday': 6 } def load_data(city, month, day): df = pd.read_csv(CITY_DATA[city]) # we access the value of the dictionary through the key print("The city you entered is: ", city) print ("The month you enteres is: ", month) print ("The day you entered is: ", day) print('Hello! Let\'s explore some US bikeshare data together!') """ Loads data for the specified city and filters by month and day if applicable. Args: (str) city - name of the city to analyze (str) month - name of the month to filter by, or "all" to apply no month filter (str) day -ye name of the day of week to filter by, or "all" to apply no day filter Returns: df - Pandas DataFrame containing city data filtered by month and day """ df['Start Time'] = pd.to_datetime(df['Start Time']) df['weekday'] = df['Start Time'].dt.dayofweek df['month'] = df['Start Time'].dt.month if month != 'all': # filter the city file by month from Jan to Jun to create the new dataframe df = df[df['month'] == MONTH_DATA[month]] if day != 'all': # filter by day of week to create the new dataframe df = df[df['weekday'] == DAY_DATA[day]] return df def time_stats(df): """Displays statistics on the most frequent times of travel.""" print('\nCalculating The Most Frequent Times of Travel...\n') start_time = time.time() # display the most common month print('Most common month: ') print(df['month'].mode()[0]) # display the most common day of week print('Most common day of week: ') print(df['weekday'].mode()[0]) # display the most common start hour df["hour"] = df['Start Time'].dt.hour print('Most common start hour: ') print(df['hour'].mode()[0]) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def station_stats(df): """Displays statistics on the most popular stations and trip.""" print('\nCalculating The Most Popular Stations and Trip...\n') start_time = time.time() # display most commonly used start station print('Most common start station: ') print(df['Start Station'].mode()[0]) # display most commonly used end station print('Most common end station: ') print(df['End Station'].mode()[0]) # display most frequent combination of start station and end station trip print('Most common trip journey: ') df ['start_end'] = df['Start Station'] + '' + df['End Station'] print(df['start_end'].mode()[0]) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def trip_duration_stats(df): """Displays statistics on the total and average trip duration.""" print('\nCalculating Trip Duration...\n') start_time = time.time() # display total travel time print ('Total travel time: ') print(df['Trip Duration'].sum()) # display mean travel time print ('Average travel time: ') print(df['Trip Duration'].mean()) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def user_stats(df): """Displays statistics on bikeshare users.""" print('\nCalculating User Stats...\n') start_time = time.time() # display counts of user types print ('Counts of user types: ') print(df['User Type'].value_counts()[0]) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def gender_stats(df): """Displays statistics on gender of bikeshare users.""" print('\nCalculating Gender Stats...\n') start_time = time.time() # display counts of gender types if 'Gender' in df.columns: print('Count male: ') print(df['Gender'].value_counts()['Male']) print('Count female: ') print(df['Gender'].value_counts()['Female']) print('Count gender: ') print(df['Gender'].value_counts()[0]) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def birth_year_stats(df): """Displays statistics on the birth years of bikeshare users.""" print('\nCalculating Birth Year Stats...\n') start_time = time.time() # display earliest, most recent, and most common year of birth if 'Birth Year' in df.columns: print('Earliest year of birth: ') print(int(df['Birth Year'].min())) print('Most recent year of birth: ') print(int(df['Birth Year'].max())) print('Most common year of birth: ') print(int(df['Birth Year'].mode()[0])) print("\nThis took %s seconds." % (time.time() - start_time)) print('-'*40) def main(): while True: city, month, day = get_filters() df = load_data(city, month, day) time_stats(df) station_stats(df) trip_duration_stats(df) user_stats(df) gender_stats (df) birth_year_stats (df) restart = input('\nWould you like to restart? Enter yes or no.\n') while restart.lower() not in ("yes", "no"): restart = input('\nSorry, the answer you entered is not correct. If you would like to start again, choose between yes or no.\n') if restart.lower() != 'yes': break else: print if __name__ == "__main__": main()
2b12f948d52ff866884b143da3d682c3d1286135
bfaure/Encryption
/algo/shift.py
2,421
3.78125
4
import sys # 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 letters_upper = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"] letters_lower = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"] # Ensure that the input is above zero def input_validator(shift): if shift < 0: return False return True def shifter(plaintext, shift, function="encrypt"): if input_validator(shift) == False: return False print "Encrypting with shift = "+str(shift) if function=="encrypt" else "Decrypting with shift = "+str(shift) ciphertext = "" for letter in plaintext: if letter == '\n': ciphertext += '\n' elif letter == " ": # If the letter is just a space ciphertext += " " # Add space to ciphertext else: # If the letter is not a space is_letter = True if letter in letters_lower: # If the letter is lowercase letter_set = letters_lower elif letter in letters_upper: # If the letter is uppercase letter_set = letters_upper else: # The current is not a letter is_letter = False if is_letter: x = letter_set.index(letter) fx = x+shift if function=="encrypt" else x-shift fx = fx % 26 ciphertext += letter_set[fx] else: ciphertext += letter return ciphertext def main(): if len(sys.argv) == 4: # The four arguments (after affine.py) should be [filename] [function] [alpha] [beta] print "Note: Argument order is as follows -> [filename] [-e or -d] [shift]" filename = sys.argv[1] function = sys.argv[2] shift = int(sys.argv[3]) # Reading the entire file into string 'data' with open(filename, 'r') as source: data = source.read() if function == "-e" or function == "-E": new_data = shifter(data, shift) elif function == "-d" or function == "-D": new_data = shifter(data, shift, "decrypt") else: print "ERROR: The second argument should be either -e (encrypt) or -d (decrypt)." return if new_data == False: # Something went wrong with translation print "ERROR: Ensure that shift >= 0." return new_file = open(filename, 'w') new_file.write(new_data) print "Process complete." return else: print "ERROR: Argument order is as follows -> [filename] [-e or -d] [shift]" if __name__ == '__main__': main()
44f27dbb637a603c0bd93a78a8b4ee2398d70d2b
greenfox-velox/timikurucz
/week-03/day-4/cw02.py
654
3.875
4
# Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contains any char. def XO(s): num_o = 0 num_x = 0 o_letters = ('o', 'O') x_letters = ('x', 'X') for char in s: if char in o_letters: num_o += 1 elif char in x_letters: num_x += 1 if num_o == num_x: return True else: return False print(XO("ooxx")) # => true print(XO("xooxx")) # => false print(XO("ooxXm")) # => true print(XO("zpzpzpp")) # => true // when no 'x' and 'o' is present should return true print(XO("zzoo")) # => false
af47b5effb408dc49f78bde3ee4f0226342d8506
daniel-reich/ubiquitous-fiesta
/sDvjdcBrbHoXKvDsZ_19.py
343
3.59375
4
def anagram(name, words): l = [] for i in range(len(name)): if name[i] != ' ': l.append(name[i].lower()) for i in range(len(words)): for j in range(len(words[i])): if words[i][j].lower() in l: l.remove(words[i][j]) else: return False if len(l) == 0: return True else: return False
88213522cfb133b24a460b44ed6f6010898e0057
christinapanto/project
/New folder/dmelt/python/packages/npfinder/classes.py
4,792
3.859375
4
class Point: """ Point object class Attributes: point_number = number of given point x -> point x coordinate y -> point y coordinate x_err_low -> low error in x x_err_high -> high error in x y_err_low -> low error in y y_err_high -> high error in y in_peak -> True if point is in a peak; False if point is not in a peak alpha1 -> angle between this point and previous neighboring point, assigned with SetAlpha1 alpha2 -> angle between this point and next neighboring point, assigned with SetAlpha2 All attributes are accessible via their respective 'Get _____' method. See below. All attributes can be set via their respective 'Set ____' method. See below. """ def __init__(self, point_number, x_pos, y_pos): """Initialization function for Point class""" self.point_number = point_number self.x = x_pos self.y = y_pos def GetPointNumber(self): point_number = self.point_number return point_number def GetX(self): x = self.x return x def GetY(self): y = self.y return y def GetXErrLow(self): x_err_low = self.x_err_low return x_err_low def GetXErrHigh(self): x_err_high = self.x_err_high return x_err_high def GetYErrLow(self): y_err_low = self.y_err_low return y_err_low def GetYErrHigh(self): y_err_high = self.y_err_high return y_err_high def GetAlpha1(self): alpha1 = self.alpha1 return alpha1 def GetAlpha2(self): alpha2 = self.alpha2 return alpha2 def SetX(self, new_x): """Set new x value for point""" self.x = new_x def SetY(self, new_y): """Set new y value for point""" self.y = new_y def SetXErrLow(self, new_x_err_low): """Set new x_err_low for point""" self.x_err_low = new_x_err_low def SetXErrHigh(self, new_x_err_high): """Set new x_err_high for point""" self.x_err_high = new_x_err_high def SetYErrLow(self, new_y_err_low): """Set new y_err_low value for point""" self.y_err_low = new_y_err_low def SetYErrHigh(self, new_y_err_high): """Set new y_err_high for point""" self.y_err_high = new_y_err_high def SetAlpha1(self, alpha1): self.alpha1 = alpha1 def SetAlpha2(self, alpha2): self.alpha2 = alpha2 class Peak: """ Peak object class Peak attributes: -> peak_number - number of the peak -> points - list of points in the peak -> linreg_points - list of linearly regressed background points for the peal -> residuals - list of residuals for each point in the peak compared to respective background point -> stat_sig - statistical significance of the peak All attributes (and a few more properties of the peak) can be accessed by their respective 'Get ____' method. See below. Some attributes may be set using their 'Add ___' or 'Set ____' methods. See below. """ def __init__(self, peak_number): self.peak_number = peak_number self.points = [] self.linreg_points = [] self.residuals = [] self.stat_sig = 0 def AddLinRegPoint(self, point): self.linreg_points.append(point) def AddPoint(self, point): self.points.append(point) def AddResidual(self, value): self.residuals.append(value) def GetLinRegPoints(self): linreg_points = self.linreg_points return linreg_points def GetNumberOfPoints(self): num_points = len(self.points) return num_points def GetPeakEnd(self): peak_end = self.points[len(self.points) - 1] return peak_end def GetPeakNumber(self): peak_number = self.peak_number return peak_number def GetPeakStart(self): peak_start = self.points[0] return peak_start def GetPoints(self): points = self.points return points def GetResiduals(self): residuals = self.residuals return residuals def GetStatSig(self): stat_sig = self.stat_sig return stat_sig def SetStatSig(self, stat_sig): self.stat_sig = stat_sig def toString(self): return 'Peak:'+str(self.peak_number)+' Start:'+str(self.points[0].x)+' End:'+str(self.points[len(self.points) - 1].x)+' Sign:'+str(self.stat_sig)
f23e4bd10c978746b9a0ffdac838c88ab4489478
Cyberghost999/Basic-Python-Programmes
/extractNumbersFromList.py
121
3.59375
4
str = "Hello 12345 World" l =[] for i in str: if i.isdigit(): l.append(i) else: continue print(l)
aa3b63cde85b7be7fc44906fffe567e0d8367446
weichuntsai0217/work-note
/programming-interviews/epi-in-python/ch05/06_6_BUYANDSELLASTOCKONCE.py
652
3.921875
4
from __future__ import print_function def get_max_profit(x): """ Time complexity is O(n) where n is the length of x """ max_profit = 0 min_price = float('inf') for p in x: max_profit = max(max_profit, p - min_price) min_price = min(min_price, p) return max_profit def get_input(case=0): if case == 0: return [310,315,275,295,260,270,290,230,255,250], 30 elif case == 1: return [12,11,13,9,12,8,14,13,15], 7 def main(): for arg in xrange(2): x, ans = get_input(arg) res = get_max_profit(x) print(res) print('Test success' if res == ans else 'Test failure') if __name__ == '__main__': main()
0f23fd0ec2fa18e21f5183498e6b72c6cc60b8c7
manuelmj/Dise-o_Microelectronico_Digitial
/taller/ejercicio6.py
897
4.125
4
def media(Numeros:list)->float: sumaNumeros=sum(Numeros) cantidadNumeros=len(Numeros) return(sumaNumeros/cantidadNumeros) def desviacionEstadar(Numeros:list)->float: cantidadNumeros=len(Numeros) sumatoria=0 x=media(Numeros) for numero in Numeros: sumatoria+=((numero-x)**2) resultadoDE=(sumatoria/(cantidadNumeros-1))**(1/2) return(resultadoDE) def main()->None: numeros=[] comprobar=1 while(comprobar): comprobar=float(input("ingrese un numero, para salir ingrese el cero: ")) numeros.append(comprobar) numeros.pop(); print("\r\nel resultado de la media de los numeros es: {md}\r\n".format(md=(media(numeros)))) print("la desviacion estandar de los datos es: {dvc}\r\n".format(dvc=desviacionEstadar(numeros))) pass if __name__ == "__main__": main()
56f77016d3ecbb8eae86168037e2a74999d963a5
nghiemphan93/machineLearning
/2019-03-14_Genetic Algorithm/Population.py
4,206
3.515625
4
import random from DNA import DNA from typing import List class Population: def __init__(self, target: str, mutationRate: float, populationSize: int): self.DNAList = [] self.matingPool = [] self.target = target self.generations = 0 self.mutationRate = mutationRate self.isFinished = False self.perfectScore = 1 for i in range(populationSize): newDNA = DNA(target) self.DNAList.append(newDNA) self.calcFitnessAllMembers() def calcFitnessAllMembers(self) -> None: for i in range(len(self.DNAList)): self.DNAList[i].calcFitness(self.target) def naturalSelect(self) -> None: #print("len mating pool: ", len(self.matingPool)) #self.matingPool.clear() self.matingPool = [] maxFitness = 0 minFitness = 1 for i in range(len(self.DNAList)): if self.DNAList[i].fitness > maxFitness: maxFitness = self.DNAList[i].fitness if self.DNAList[i].fitness < minFitness: minFitness = self.DNAList[i].fitness #print("min fitness: ", minFitness) #print("max fitness: ", maxFitness) ''' for i in range(len(self.DNAList)): #scaledFitness = map(self.DNAList[i].fitness, 0, maxFitness, 0, 1) scaledFitness = self.normalize(self.DNAList[i].fitness, maxFitness, minFitness) timesAdded = int(scaledFitness * 100) if scaledFitness == 0.0: self.matingPool.append(self.DNAList[i]) x = 0 else: for i in range(timesAdded): self.matingPool.append(self.DNAList[i]) ''' for i in range(len(self.DNAList)): timesAdded = int(self.DNAList[i].fitness * 100) for j in range(timesAdded): self.matingPool.append(self.DNAList[i]) #print(len(self.matingPool)) ''' totalFitness = self.calcSumFitness() if totalFitness == 0: for i in range(len(self.DNAList)): self.matingPool.append(self.DNAList[i]) else: for i in range(len(self.DNAList)): scaledFittness = self.DNAList[i].fitness / totalFitness timesAdded = int(scaledFittness*100) if timesAdded == 0: self.matingPool.append(self.DNAList[i]) else: for i in range(timesAdded): self.matingPool.append(self.DNAList[i]) ''' def normalize(self, number, max, min) -> float: if (max - min) == 0: return 0.0 else: return (number - min) / (max - min) def newGeneration(self) -> None: for i in range(len(self.DNAList)): indexA = int(random.randint(0, len(self.matingPool) - 1)) indexB = int(random.randint(0, len(self.matingPool) - 1)) #print("index A: ", indexA) #print("len(matingPool): ", len(self.matingPool)) partnerA: DNA = self.matingPool[indexA] partnerB: DNA = self.matingPool[indexB] child = partnerA.crossover(partnerB) child.mutate(self.mutationRate) self.DNAList[i] = child self.generations += 1 def getBestDNA(self) -> DNA: bestFitness = 0.0 bestIndex = 0 for i in range(len(self.DNAList)): if self.DNAList[i].fitness > bestFitness: bestIndex = i bestFitness = self.DNAList[i].fitness if bestFitness == self.perfectScore: self.isFinished = True return self.DNAList[bestIndex] def isFinished(self) -> bool: return self.isFinished def getGeneration(self) -> int: return self.generations def calcAverageFitness(self) -> float: return self.calcSumFitness() / len(self.DNAList) def calcSumFitness(self) -> float: totalFitness = 0.0 for i in range(len(self.DNAList)): totalFitness += self.DNAList[i].fitness return totalFitness def getAllPhrases(self) -> str: allPhrases = "" displayLimit = min(len(self.DNAList), 10) for i in range(displayLimit): #allPhrases.join(self.DNAList[i].getPhrase() + "\n") allPhrases += "{}\n".format(self.DNAList[i].getPhrase()) return allPhrases
0783d25b0675030de78e18229e5719a821951a6a
ShinW0330/ps_study
/05_Graph_Search/Level3/5567.py
1,014
3.640625
4
# 결혼식 # https://www.acmicpc.net/problem/5567 # 힌트 # 1. BFS를 이용하여 깊이 2까지의 모든 노드의 개수를 파악한다. import sys from collections import deque def bfs(s): q = deque() q.append(s) check[s] = True depth = 0 ans = 0 while len(q) != 0: q_size = len(q) if depth == 2: return ans for i in range(q_size): current = q.popleft() for j in range(1, N + 1): if not check[j] and table[current][j]: check[j] = True q.append(j) ans += 1 depth += 1 return 0 if __name__ == "__main__": N = int(sys.stdin.readline()) M = int(sys.stdin.readline()) table = [[False] * (N + 1) for _ in range(N+1)] for i in range(M): x, y = map(int, sys.stdin.readline().split()) table[x][y] = True table[y][x] = True check = [False] * (N + 1) answer = bfs(1) print(answer)
394dcfa3fb98be7ead1a337a3eb2f732eaca920f
bpapillon/adventofcode2020
/02/01.py
691
4
4
import re def parse_line(line): pattern = r'([0-9]+)\-([0-9]+) ([a-z])\: ([a-z]+)$' match = re.match(pattern, line) min_occurrences = int(match.group(1)) max_occurrences = int(match.group(2)) char = match.group(3) password = match.group(4) return (password, char, min_occurrences, max_occurrences) def valid_password(line): password, char, min_occurrences, max_occurrences = parse_line(line) occurrences = password.count(char) return occurrences >= min_occurrences and occurrences <= max_occurrences lines = open('input.txt', 'rb').read().strip().split("\n") valid_lines = [line for line in lines if valid_password(line)] print len(valid_lines)
b3712dcaab606d5cf6b974e4d1803fd865173ced
alexsks65536/Python-base
/lesson01/lesson1-3.py
573
3.890625
4
def procent_write(procent): s = procent[-1] if s == '1' and procent != '11': text = 'процент' return text elif procent == '11' or procent == '12' or procent == '13' or procent == '14': text = 'процентов' return text elif s == '2' or s == '3' or s == '4': text = 'процента' return text else: text = 'процентов' return text procent = input('Введите число процентов: ') print("Вы ввели: ", procent, "%", procent_write(procent))
cbfff23b392e048b2f9d085405903790c752911e
Hanchen-Yao/opencv-test
/python/roi_demo.py
1,510
3.5
4
# ROI与泛洪填充:换掉图片区域的某个部分 # 作者:hanchen # 时间:2020年5月10日 import cv2 as cv import numpy as np import matplotlib.pyplot as plt def fill_color_demo(image): copyImg = image.copy() h, w = image.shape[:2] mask = np.zeros([h + 2, w + 2], np.uint8) # 参数:原图,mask图,起始点,起始点值减去该值作为最低值,起始点值加上该值作为最高值,彩色图模式 cv.floodFill(copyImg, mask, (30, 30), (0, 255, 255), (100, 100, 100), (50, 50, 50), cv.FLOODFILL_FIXED_RANGE) cv.imshow("fill_color_demo", copyImg) def fill_binary(image): image = np.zeros([400, 400, 3], np.uint8) image[100:300, 100:300, :] = 255 cv.imshow("fill_binary", image) mask = np.ones([402, 402, 1], np.uint8) mask[101:301, 101:301] = 0 cv.floodFill(image, mask, (200, 200), (100, 2, 255), cv.FLOODFILL_MASK_ONLY) cv.imshow("filled binary", image) if __name__ == '__main__': print("----------Hello World!----------") src = cv.imread("D:/opencv_exercises-master/images/a_zhu.jpg") cv.namedWindow("input image", cv.WINDOW_AUTOSIZE) #cv.imshow("input image", src) """ fill_color_demo(src) face = src[50:250, 100:300] gray = cv.cvtColor(face,cv.COLOR_RGB2GRAY) blackface = cv.cvtColor(gray, cv.COLOR_GRAY2BGR) src[50:250, 100:300] = blackface #cv.imshow("gray", gray) cv.imshow("blackface", src) """ cv.waitKey(0) cv.destroyAllWindows()
feb184b75e3c57ac1433881c6bc74e797e89f52b
thatsokay/advent-of-code
/2018/05/part2.py
316
3.59375
4
from string import ascii_lowercase from part1 import react if __name__ == '__main__': with open('input.txt') as f: polymer = f.read().strip() results = ( len(react(polymer.replace(letter, '').replace(letter.upper(), ''))) for letter in ascii_lowercase ) print(min(results))
6fd43374f0bc36dffb2839f570bbd73c9bc5a808
endy-see/AlgorithmPython
/ZuoShen/0-MinArrSum.py
600
3.5
4
""" 计算数组的小和 题目:数组的小和定义如下: 例如,数组s=[1,3,5,2,4,6],在s[0]的左边小于或等于s[0]的数的和为0,在s[1]的左边小于或等于s[1]的数的和为1, 在s[2]的左边小于或等于s[2]的数的和为1+3=4,在s[3]的左边小于等于s[3]的数的和为1,在s[4]的左边小于或等于s[4] 的和为1+3+2=6,在s[5]的左边小于或等于s[5]的数的和为1+3+5+2+4=15,所以s的小和为0+1+4+1+6+15=27. 给定一个数组s,实现函数返回s的小和 思路:归并排序,在归并的时候对右边的每个数,如果 """
08fa36e86ec240d83526c43a5b90fc89475fe9b6
thanikaReddy/fbNewsAnalysis
/regression/multivariate.py
9,635
3.703125
4
""" Fits a multivariate linear regression model to all features, to predict mins_to_100_comment Fits a multivariate linear regression model multiple times - the number of times is defined by NUMITER. Each iteration, * One feature is added to the model at a time and the change in R2 and RMSE is noted for each feature. * The order in which features are added changes randomly. * P-values and coefficients are displayed. Over all iterations, Keeps track of the addition of which six features leads to the largest increase in the R2 score. Reads from /data/postsWithReciRoot.csv """ import pandas as pd import numpy as np import operator import random import plotly.express as px import plotly.graph_objects as go import matplotlib.pyplot as plt import statsmodels.api as sm from sklearn import datasets, linear_model from sklearn.metrics import mean_squared_error, r2_score from sklearn.model_selection import cross_val_predict from yellowbrick.regressor import ResidualsPlot from statistics import mean from math import log posts = pd.read_csv("../data/postsWithReciRoot.csv") image_path = "figures/multivariate_{:d}.png" image_num = 1 """ Number of iterations of linear regression to run. """ NUMITER = 1 """ Create labels for each feature """ features = ["log_angry_per_sec", "log_sad_per_sec", "log_love_per_sec", "log_wow_per_sec", "log_haha_per_sec", "log_like_per_sec", "reciroot_mins_to_first_comment", "reciroot_shares_per_sec", "reciroot_reactions_per_sec", "vader_sentiment", "vader_pos", "vader_neg", "vader_neu"] featureLabels = ["Angry reactions per second", "Sad reactions per second", "Love reactions per second", "Wow reactions per second", "Haha reactions per second", "Likes per second", "Minutes until first comment", "Shares per second", "Reactions per second", "Post Sentiment", "Post Positivity", "Post Negativity", "Post Neutrality"] featureToLabel = dict(zip(features, featureLabels)) """ Plots residuals for a given pair of arrays of predicted and actual values. """ def plotResiduals(y_test, predicted): global image_num residuals = y_test - predicted plt.subplot(1, 2, 1) plt.axhline(y=0, color='k', linestyle='-.') plt.scatter(predicted, residuals, color='b') plt.xlabel('Predicted values') plt.ylabel('Residuals') plt.subplot(1, 2, 2) plt.hist(residuals, normed=True, bins=40) plt.savefig("../paper_images/multireg_residuals.png") plt.show() plt.savefig(image_path.format(image_num), bbox_inches='tight') image_num += 1 """ Fits a multivariate linear regression model for all predictors in xLabels. The feature yLabel is the outcome. Prints P-values and plots coefficients. Returns the R2 score and RMSE for the model. """ def multiRegression(p, xLabels, yLabel): global image_num # Randomly shuffle rows p = p.sample(frac=1).reset_index(drop=True) # Split train and test twentyPercent = -1*round(p.shape[0]*0.2) n = len(xLabels) xCol = p[xLabels].values.reshape(-1,n) X_train = xCol[:twentyPercent] X_test = xCol[twentyPercent:] y_train = p[yLabel][:twentyPercent].values.reshape(-1,1) y_test = p[yLabel][twentyPercent:].values.reshape(-1,1) # Fit linear regression model lr = linear_model.LinearRegression() lr.fit(X_train, y_train) # Make predictions predicted = lr.predict(X_test) r2 = r2_score(y_test, predicted) mse = mean_squared_error(y_test, predicted) if len(xLabels) == 13: # P-values and coefficients X2_train = sm.add_constant(X_train) est = sm.OLS(y_train, X2_train) est2 = est.fit() print(est2.summary()) print("p-values") print(est2.pvalues) l = xLabels l.insert(0, "Const") params = [abs(number) for number in est2.params] sorted_coeffs = [list(t) for t in sorted(zip(est2.params, l), reverse=True)] print("Coefficients") print(sorted_coeffs) sorted_abs_coeffs = [list(t) for t in sorted(zip(params, l), reverse=True)] print("Absolute values of coefficients") print(sorted_abs_coeffs) coeff = [] feature = [] for j in range(1,len(sorted_abs_coeffs)): coeff.append(abs(sorted_abs_coeffs[j][0])) feature.append(featureToLabel[sorted_abs_coeffs[j][1]]) x = list(range(0,len(feature))) # Plot coefficients plt.clf() plt.figure(figsize=(10,15)) plt.xticks(x,feature, rotation='vertical') plt.bar(x, coeff, align='center', alpha=0.5) plt.yscale('log') plt.xlabel('Features') plt.ylabel('Log of absolute value of coefficient') plt.tight_layout() plt.show() plt.savefig(image_path.format(image_num), bbox_inches='tight') image_num += 1 coeff = [] feature = [] for j in range(0,len(sorted_coeffs)-1): coeff.append(sorted_coeffs[j][0]) feature.append(featureToLabel[sorted_coeffs[j][1]]) plt.clf() plt.figure(figsize=(10,15)) plt.xticks(x,feature, rotation='vertical') plt.bar(x, coeff, align='center', alpha=0.5) plt.yscale('log') plt.xlabel('Features') plt.ylabel('Log of coefficient') plt.tight_layout() plt.show() plt.savefig(image_path.format(image_num), bbox_inches='tight') image_num += 1 return r2, mse """ Shuffles a list of predictors and calls multiRegression adding one predictor at a time. Returns a list of R2 scores and RMSEs. """ def stepwiseMultiRegression(): global image_num features = ["log_angry_per_sec","log_sad_per_sec","log_love_per_sec","log_wow_per_sec","log_haha_per_sec","log_like_per_sec","reciroot_mins_to_first_comment","reciroot_shares_per_sec","reciroot_reactions_per_sec","vader_sentiment","vader_pos","vader_neg","vader_neu"] random.shuffle(features) r2_stepwise = [] mse_stepwise = [] for i in range(len(features)): r,m = multiRegression(posts, features[0:i+1], "reciroot_mins_to_100_comment") r2_stepwise.append(r) mse_stepwise.append(m) return r2_stepwise, mse_stepwise, features """ Performs stepwiseMultiRegression multiple times and keeps track of top 6 features for each iteration. Plots the change in R2 score and RMSE for each iteration. Returns a dictionary that maps each feature to the number of iterations in which it was part of the top 6 features""" def runStepwiseFor(numIter): global image_num # Dictionary that stores feature:count (in the top 6 features, across all stepwise iterations) numOcc = {} featureNames = [] for j in range(numIter): r2, mse, f= stepwiseMultiRegression() for g in range(len(f)): featureNames.append(featureToLabel[f[g]]) x = list(range(0,len(f))) plt.clf() plt.xticks(x,featureNames, rotation='vertical') plt.plot(x, r2) plt.xlabel('Features') plt.ylabel('R2') plt.tight_layout() plt.show() plt.savefig(image_path.format(image_num), bbox_inches='tight') image_num += 1 plt.clf() plt.xticks(x, featureNames, rotation='vertical') plt.plot(x, mse) plt.xlabel('Features') plt.ylabel('RMSE') plt.tight_layout() plt.show() plt.savefig(image_path.format(image_num), bbox_inches='tight') image_num += 1 # Calculate % increase in r2 and decrease in rmse that each feature leads to r2_delta = [] rmse_delta = [] for i in range(1,len(r2)): val = (r2[i]-r2[i-1]) r2_delta.append(val) val = (mse[i]-mse[i-1]) rmse_delta.append(val) delta_df = pd.DataFrame(list(zip(featureNames[1:],r2_delta, rmse_delta)), columns =['Feature added', 'Change in R2', 'Change in RMSE']) print(delta_df.sort_values(by=['Change in R2'], ascending=False)) x = list(range(0,len(f)-1)) plt.clf() plt.xticks(x,featureNames[1:], rotation='vertical') plt.bar(x, r2_delta, align='center', alpha=0.5) plt.xlabel('Features') plt.ylabel('Change in R2') plt.tight_layout() plt.show() plt.savefig(image_path.format(image_num), bbox_inches='tight') image_num += 1 plt.clf() plt.xticks(x, featureNames[1:], rotation='vertical') plt.bar(x, rmse_delta, align='center', alpha=0.5) plt.xlabel('Features') plt.ylabel('Change in RMSE') plt.tight_layout() plt.show() plt.savefig(image_path.format(image_num), bbox_inches='tight') image_num += 1 for e in delta_df.sort_values(by=['Change in R2'], ascending=False)[0:6]["Feature added"]: if e in numOcc: numOcc[e] += 1 else: numOcc[e] = 1 return numOcc numOcc = runStepwiseFor(NUMITER) # Sort by the number of times each feature occured in the top 6 list in each itertion of stepwise linear regression sorted_numOcc = sorted(numOcc.items(), key=operator.itemgetter(1), reverse = True) print(sorted_numOcc) print("\nTop 6 features and frequency of occurance: ") for s in sorted_numOcc: print(s)
798aad37b7e6d7d6c3cdb0eeeb042a274b6c8924
jorgezafra94/Python_to_the_top
/Python_intro/lists_tup_set_dic.py
5,456
4.5625
5
# lists tuples sets dictionaries print('****************************** LIST *************************************') print('---------------- slicing ---------------------') a = [1,2,3,4,5,6,7,8] print(a) print(a[:]) print(a[1: 4]) print(a[3:]) print(a[:5]) print(a[-2]) print(a[-5: 5]) print('--------------------ADD----------------------------') a = [1,2,3,4] b = ['a', 'b', 'c'] #********* add ************** # we can add elements to a list in 4 different ways # 1. append, this method will add an element at the end of the list print(a) a.append(5) # 2. insert, this method will add an element in a specified position insert(position, value) # if the position is bigger than the length of the list, it will automatically add it at the end of the list print(b) b.insert(2, 'z') print(b) b.insert(99999, 'x') print(b) # 3. extend, this method allow us to join lists, be careful with the order c = [1, 'z'] print(c) c.extend([9, 8, 7, 'f', 'e']) print(c) # 4. using + operator e = [1,2,3] print(e) e = e + [5,6,7] print(e) print('------------------REMOVE------------------------------') # ****** remove elements ****** # we can do this in two ways # 1. remove, this method will let us to remove an element specifying it a = [1, 'a', 9, 'b', 199] print(a) a.remove('b') print(a) # 2. pop, this is the most used method to delete elements because we can use the position to this purpose # remeber if you dont specify a position by default it will take the last element pop() a = [1, 'a', 9, 'b', 199] print(a) a.pop(3) print(a) print('---------------------COPY---------------------------') # to create a copy we should use copy method z = a.copy() print(a) print(z) print('---------------------REVERSE---------------------------') # to reverse a list we should use the reverse method print(z) z.reverse() print(z) print('---------------------SORT---------------------------') z = [1, 2, 6, 90, 87, -5, 8] print(z) z.sort() print(z) print('---------------------INDEX---------------------------') # the index method will allow us to get the index of an element # if there are more than one same element in the same list # it will return the position of the first match z = [2, 3, 4, 5, 6, 7, 5, 9] print(z, 'this time we are going to get the index of the 5') res = z.index(5) print('this was the result, the position of the first match', res) print('---------------------CLEAR---------------------------') # with this method we will going to delete all the elements of a list # and we will have an empty list after apply the method z = [1,2,3,4,5,1,1,2,3] print(z) z.clear() print(z) print('---------------------COUNT---------------------------') # this method will count how many times an element is on the list z = [1,2,3,4,5,1,1,2,3] print(z, 'lets count how many 1, and how many 2 are in the list') print(z.count(1), 'this is the amount of 1') print(z.count(2), 'this is the amount of 2') print('if you wanna know more methods of the list please do dir([1])') print('****************************** TUPLE *************************************') # tuples dont have many methods a = (1,2,3) print(a) # we can select the element using the position print(a[0]) # the only way to add elements to a tuple is using + operator b = a + (4, 5) print(b) # we can use slicing to get part of the tuple c = b[0::2] print(c) print('***************************** SET ***********************************') # NOTEs: the set are not iterables so that is why we cant play with positions print('---------- ADD ----------') # with the add method we can add a new element in the set a = {2,3,4} print(a) a.add(5) print(a) print('---------- REMOVE ----------') # with this method we can remove an specified element, as they are unique # we are going to erase the correct one print(a) a.remove(3) print(a) print('------ POP --------') # with this element we will be able to erase the last element of the set # the problem here is that we CANT SPECIFY the position to erase print(a) a.pop() print(a) print('-------- INTERSECTION ---------') # with the sets we can treat them as conjuntos # so we can get the intersection using & or method .intersection a = {1,2,3,4,5,6} b = {4,5,6,7,8,9} print(a, b) print('using & for intersection', a & b) print('--------- UNION -----------') # using | operator to create the union of sets or .union a = {1,2,3,4,5,6} b = {4,5,6,7,8,9} print(a, b) print('using | for union', a | b) print('----------- DIFFERENCES ----------') # using - t get difference or .difference a = {1,2,3,4,5,6} b = {4,5,6,7,8,9} print(a, b) print('using - for differences', a - b) print('------ SYMMETRIC DIFFERENCE ---------') a = {1,2,3,4,5,6} b = {4,5,6,7,8,9} print(a, b) print(a.symmetric_difference(b)) print('************************** DICTIONARY *********************************') a = {'a': 23, 4: 'felipe'} print(a) print(a['a'], a[4]) print('******** KEYS ************') keys = a.keys() print(keys) print('***** VALUES **********') val = a.values() print(val) print('****** ITEMS **********') items = a.items() print(items) print('******* update **********') b = {'a': 19, 'b': 90} print(a) print(b) a.update(b) # here we are going to see how the dictionary change the value in the key a # and also we are going to see how a new key 'b' is gonna to be created in a dict print(a) # how to create a dictionary from a list of tuples list_tuple = [('jorge', 26), ('juan', 28), ('ivan', 38)] my_dicty = dict(list_tuple) print(list_tuple) print(my_dicty)