blob_id
stringlengths 40
40
| repo_name
stringlengths 6
108
| path
stringlengths 3
244
| length_bytes
int64 36
870k
| score
float64 3.5
5.16
| int_score
int64 4
5
| text
stringlengths 36
870k
|
---|---|---|---|---|---|---|
97e3b6c670ca0ce6ddd02db55c7fcb4e16aa156c | Orig5826/Basics | /Lang/Python/py_base/15_map2.py | 1,107 | 3.671875 | 4 |
import re
def calc_add_custon():
while True:
print('>> ', end='')
content = input()
if not isinstance(content, str):
break
if content == 'q':
break
# 对于:数字和运算符号的判断,暂没有想到合适的办法
# 取消开头和结尾的空格
content = content.strip()
# re.split 和 str.split的区别在于
# str.split仅能通过一个字符分割
# re.split可以多个字符,且可以通过()来将分割用的字符也列举出来。功能更加强大
formula = re.split(r'[\W+]+', content) # 分隔符:空格,+
# print(formula)
result = sum(map(int, formula))
print(result)
def calc_eval():
while True:
print('>> ', end='')
content = input()
if not isinstance(content, str):
break
if not content:
continue
if content == 'q':
break
# 嘿嘿... 这种方式有点不要脸哈
result = eval(content)
print(result)
calc_eval()
|
c1d781121ddabf28a30f37676dee2770153fc93d | claxman/Clustering_Models | /hierarchical_clustering.py | 1,294 | 3.625 | 4 | # Author: Chaitanay Laxman
# Importing the libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
# Importing the dataset
dataset = pd.read_csv('Mall_Customers.csv')
X = dataset.iloc[:, [3, 4]].values
# Using the dendrogram to find the optimal number of clusters
import scipy.cluster.hierarchy as sch
dendrogram = sch.dendrogram(sch.linkage(X, method = 'ward'))
plt.title('Dendrogram')
plt.xlabel('Observations')
plt.ylabel('Euclidean distances')
plt.show()
# Training the Hierarchical Clustering model on the dataset
from sklearn.cluster import AgglomerativeClustering
ac = AgglomerativeClustering(n_clusters = 5, affinity = 'euclidean', linkage = 'ward')
y_pred = ac.fit_predict(X)
# Visualising the clusters
plt.scatter(X[y_pred == 0,0], X[y_pred == 0,1], s = 40, c = "green", label = "cluster1")
plt.scatter(X[y_pred == 1,0], X[y_pred == 1,1], s = 40, c = "blue", label = "cluster2")
plt.scatter(X[y_pred == 2,0], X[y_pred == 2,1], s = 40, c = "grey", label = "cluster3")
plt.scatter(X[y_pred == 3,0], X[y_pred == 3,1], s = 40, c = "purple", label = "cluster4")
plt.scatter(X[y_pred == 4,0], X[y_pred == 4,1], s = 40, c = "black", label = "cluster5")
plt.title("Cluster of customers")
plt.xlabel("Annual Income($)")
plt.ylabel("Spending Score")
plt.legend()
plt.show() |
f89dac9b2145ebdf5f674b4820df668b3f1330be | jdrestre/Online_courses | /Udemy/Python_Chirou/test_if.py | 185 | 4 | 4 | #/usr/bin/python3
nota = float(input())
if nota >= 6 and nota <= 10:
print("pasó")
elif nota < 6 and nota >=0:
print("perdió")
else:
print("ingrese valor entre 1 y 10")
|
3a0f95ee5ddec0299dcd31db6f9d9cca3b1f442a | jorgeajimenezl/school-projects | /algebra/bisection.py | 421 | 3.625 | 4 | def bisection(f, a, b):
# Initial condition
assert f(a) * f(b) < 0, "sign(f(a)) != sign(f(b))"
while abs(a - b) > 1E-10:
m = (a + b) * 0.5
if f(a) * f(m) < 0:
b = m
else:
a = m
return a
def main():
x = bisection (
f = lambda x: x**2 + 4*x + 2,
a = -2,
b = 2
)
print(f"x = {x}")
if __name__ == "__main__":
main() |
8060420958a34d3cdaf321c442aac70dba917480 | marinisz/CEV_Python | /036.py | 574 | 3.703125 | 4 | print('\033[34mBem-vindo ao sistema de crédito!\033[m')
print('-=-'*11)
salario = int(input('\033[34mQual o eu salário? \033[m'))
print('-=-'*11)
casa = int(input('\033[34mQual o valor da casa que pretende comprar (meses)? \033[m'))
print('-=-'*11)
tempo = int(input('\033[34mEm quanto tempo você pretende pagar a casa? \033[m'))
presta = casa/tempo
x = presta*0.3
if salario <= x:
print('\033[31mInfelizmente não podemos aprovar o seu crédito!\033[m')
else:
print('\033[36mSeu crédito foi aprovado, favor se dirigir ao próximo guichê\033[m')
|
4cba449580a41a9be35ae1bdead5558510cb914b | hardeep0444/ailab | /percep.py | 1,149 | 3.515625 | 4 | import numpy as np
import math
th = 1
Epochs = 3
class Perceptron:
def __init__(self,no_of_inputs,alpha=0.2):
self.alpha = alpha
self.weights = np.zeros(no_of_inputs+1)
def net_input(self,inputs):
yin = np.dot(inputs,self.weights[1:])+self.weights[0]
return yin
def train(self,training_inputs,t,weights):
for inputs,target in zip(training_inputs,t):
yin = self.net_input(inputs)
if yin > th:
Y = 1
elif yin > -th:
Y = 0
else:
Y = -1
if target!=Y:
self.weights[1:]+=self.alpha*target*inputs
self.weights[0]+=self.alpha*target
print(inputs," ",target,"\t%.2f"%yin,"\t",Y,"\t",self.weights)
training_inputs = []
training_inputs.append(np.array([1,1]))
training_inputs.append(np.array([1,-1]))
training_inputs.append(np.array([-1,1]))
training_inputs.append(np.array([-1,-1]))
t = np.array([1,-1,-1,-1])
percep = Perceptron(2)
for i in range(Epochs):
print("Epochs :",i)
weights = percep.weights
print("Initial weights :",weights)
print("x1 x2 t\t Yin \t Yout B w1 w2")
percep.train(training_inputs,t,weights)
|
7b57783f465c395a61278d2e13a76afe320b6a4f | GENGLEIN/PYTHON | /day1/login.py | 1,074 | 3.625 | 4 | #-*- coding:utf-8 -*-
##################################################
#Filename: login.py #
#Revsion: 1.0 #
#Description login is test #
#Date: 2017/01/13 #
#Auther: genglei #
#Email: [email protected] #
##################################################
# 自己定义的用户名密码
import getpass #导入模块
_user = "genglei"
_passwd = "abc123"
count = 0 #计数器
while count <3: #判断count是否大于3
useradd = input("请输入用户名: ") #提示用户输入用户名名
password = getpass.getpass("请输入密码: ") #提示用户输入密码
if useradd == _user and password == _passwd: #判断用户输入的和自己定义的是否一致
print ("欢迎登陆")
break #跳出循环
else:
print ("请检查用户名密码") #打印信息
count += 1 #count=count+1 |
8ebf27f0739faf2997558c78498fd912fdca923f | rup3sh/python_expr | /designpatterns/structural/singleton | 745 | 3.9375 | 4 | #!/bin/python3
class Singleton():
__single = None
__right_way = False
def __init__(self, name):
print("Comes to init")
if not Singleton.__right_way:
print("Comes to err")
raise RuntimeError("CREATE USING RIGHT WAY")
if not Singleton.__single:
self.x = name
@classmethod
def getInstance(cls, name):
if not cls.__single:
cls.__right_way = True
cls.__single = Singleton(name)
return cls.__single
def __str__(self):
return str(self.x)
def main():
print ("Singleton Demo: Singleton always the returns the same object once object is created.")
i1 = Singleton.getInstance("RightWay")
#i1 = Singleton("WrongWay")
print(i1)
i2 = Singleton.getInstance("RightWay2")
print(i2)
if __name__=="__main__":main()
|
4e165c870bb22e0241e715e5260a83d761a9a329 | AyrtonDev/Curso-de-Python | /aula22b/aula22.py | 237 | 3.875 | 4 |
from uteis.numeros import fatorial, dobro, triplo
num = int(input('Digite um valor: '))
fat = fatorial(num)
print(f'O fatorial de {num} é {fat}.')
print(f'O dobro de {num} é {dobro(num)}')
print(f'O triplo de {num} é {triplo(num)}') |
554562b9af28dc8446e91575183089157963e275 | rjsu26/ScheduleMe | /history_reader.py | 11,562 | 3.59375 | 4 | #! /usr/bin/env python
""" Program to read all history from firefox in the system and use their frequency count for categorization purpose. To be used as cron job set to once every month."""
"""
Format of data in HISTORY_FILE(which only has uncategorised data):
{
"website" : {
"mozilla":{"site":["support.mozilla.com", "www.mozilla.com"], "count":19}
},
"offline":{"totem":7, "code":31}
}
"""
import os,sys
import sqlite3
import tldextract
import subprocess
import glob
import pprint
import json
import time
from datetime import date, timedelta
from config import HISTORY_FILE, CATEGORIZATION_FILE
menu = """
Categories:
1. Academic : Materials related to academics
2. Non-Academic : Anything which is not exactly academic but neither entertainment like news, howto tutorials, blogging, Messaging, etc.
3. Entertainment : Activities like music, videos, adult, etc.
4. Miscellaneous : Activities like youtube, terminal, calculator, file explorer, software and updates, etc which can't be clearly distinguished as academic, non-academic or entertainment.
"""
def main():
""" Main function to gather data from firefox history and system applications and prompt user to categorise them. There are 2 separate cases: one that would run during fresh installation and the other that would run at all other instances. """
try: # to catch keyboard interrupt
categorised_data = {}
categorised_data["website"] = {} # domain to category manpping
categorised_data["offline"] = {}
categorised_data["website"]["youtube"] = 4
categorised_data["website"]["private"] = 3
# scan for all history in firefox
data= {"website":{}, "offline":{}}
do_offline = True # set to "do" for installation time running.
try: # On normal days, when its not installation procedure, simply process the HISTORY_FILE which has been updated everyday by timer.json.
categorised_data = json.load(open(CATEGORIZATION_FILE, "r+"))
data = json.load(open(HISTORY_FILE, "r"))
do_offline = False # do_offline parameter decides if categorization for offline application is to be done or not. Set to "don't do" here since its not installation-run.
except Exception as e: # On first installation, create CATEGORIZATION_FILE and read all of history
# print(e)
data["website"] = firefox_history_scan(categorised_data)
finally:
do_the_categorization(data, categorised_data, do_offline) # Ask the user to categorize and save all the changes into the data and categorised_data dictionary.
except KeyboardInterrupt:
print("Interrupted!! Terminating..")
except Exception as e:
print(e)
finally:
today_date = date.today().strftime("%d-%m-%Y")
data["last_updated"] = today_date
json.dump(data, open(HISTORY_FILE, "w+"))
json.dump(categorised_data, open(CATEGORIZATION_FILE, "w+"))
print("\nAll changes saved successfully!!\n")
def do_the_categorization(data, categorised_data, do_offline):
""" Using the un-classified data and previously categorised data, prompt the user for top most visited unclassified websites and then put them inside categorised data after removing it from the unclassified data.
Add an last_updation_date field before exiting.
"""
print("\n\n[!] Starting categorising new 'Website' data in descending order.\n\n")
time.sleep(1)
# "website" categorisation
for k,v in sorted(data["website"].items(), key = lambda x: x[1]["count"], reverse=True):
os.system("clear")
if categorised_data["websites"].get(k)==None: # if domain not categorised till now
print("Domain : {}".format(k))
print("Sites : ")
for site in v["sites"]:
print(" - ", site)
print("\n\n Frequency use: ", v["count"])
print()
print(menu)
choice = get_choice()
if choice==6:
return
elif choice==5:
continue
else:
categorised_data["websites"][k]=choice
data["website"].pop(k,None) # remove the domain <k> from data dictionary if present, otherwise return None
print("\nGetting list of all system applications ...\n")
applications_dict = find_all_applications()
if do_offline==False: # do_offline will be false when its not the installation-time run.
""" access "offline" activities from data dictionary. """
# print("I was here")
print("\n\n[!][!] Starting offline categorisation..\n\n")
time.sleep(1)
for k,v in sorted(data["offline"].items(), key = lambda x: x[1] , reverse=True):
os.system("clear")
if k not in categorised_data["offline"]:
print("Process: ", )
if k in applications_dict:
print(applications_dict[k])
else:
print(k)
print("\n\n Frequency use: ", v)
print()
print(menu)
choice = get_choice()
if choice==6:
return
elif choice==5:
continue
else:
categorised_data["offline"][k]=choice
data["offline"].pop(k,None)
else:
# "Offline" categorisation
print("\n\n[!] Starting categorising new 'Offline' applications. \n\nJust select all those which you recognise and use frequently. You may do it later, but doing it now would increase the accuracy of the scheduler..\n\n")
# time.sleep(1)
for k,v in applications_dict.items():
os.system("clear")
if categorised_data["offline"].get(k)==None:
print("Application Name: ",v)
print()
print(menu)
choice = get_choice()
if choice==6:
return
elif choice==5:
continue
else:
categorised_data["offline"][k]=choice
return
def get_choice():
""" Ask user to input any number between 1 to 6(both inclusive) and returns the choice when found valid. """
while True:
choice = input("Choose the option out of above 4 possibilities. Enter 5 to skip, 6 to terminate: ")
if choice.strip() =="":
continue
choice = int("0"+choice)
if choice>=1 and choice<=6:
return choice
else:
print("Wrong input. Please re-enter.. ")
def find_all_applications():
""" scan /usr/share/applications folder and return a dictionary of all applications in the system with mapping of system name to display name. E.g: nautilus: File Explorer. """
application_path = "/usr/share/applications/"
files = os.listdir(application_path)
list_of_applications = {}
for file in files:
try:
file_path = os.path.join(application_path ,file)
data = subprocess.Popen(["cat", file_path], stdout=subprocess.PIPE)
grep = subprocess.Popen(
["grep", "Application"], stdin=data.stdout, stdout=subprocess.PIPE
)
out = grep.communicate()[0].decode("utf-8").strip()
if out != "":
data = subprocess.Popen(["cat", file_path], stdout=subprocess.PIPE)
name_pipe = subprocess.Popen(
["grep", "Name="], stdin=data.stdout, stdout=subprocess.PIPE
)
name = (
name_pipe.communicate()[0].decode("utf-8").strip().splitlines()[0]
)
list_of_applications[file[:-8]]=name[5:]
except:
pass
return list_of_applications
def firefox_history_scan(categorised_data):
""" Scan the sqlite file of firefox history in the PC and add all visited URLs along with their visit count to browser_history_log.json. This will be used to request the user for categorize the most visited yet unresolved domains in the browser."""
prev_data = {}
# try:
# prev_data = json.load(open(file_name, "r"))
# except:
# pass
data_path = os.path.expanduser("~") + "/.mozilla/firefox/*.default*/"
all_possible_paths = glob.glob(data_path)
location = "places.sqlite"
history_path = [x + location for x in all_possible_paths]
for i in range(len(history_path)):
if os.path.exists(history_path[i]): # if a db file exists
# make a copy of it to remove lock and prevent any unwanted errors.
os.system('cp {} {}'.format(history_path[i], os.path.join(all_possible_paths[i],"places.backup.sqlite")))
# Save the path to backup file to be used later
path = os.path.join(all_possible_paths[i],'places.backup.sqlite')
if os.path.exists(path): # if the backup file was made successfully....
try:
c = sqlite3.connect(path)
cursor = c.cursor()
select_statement = (
"select moz_places.url, moz_places.visit_count from moz_places;"
)
cursor.execute(select_statement)
results = cursor.fetchall()
for url, count in results:
url_object = tldextract.extract(url)
subdomain = (
url_object.subdomain + "."
if url_object.subdomain.strip() != ""
else ""
)
domain = (
url_object.domain + "." if url_object.domain.strip() != "" else ""
)
suffix = url_object.suffix if url_object.suffix.strip() != "" else ""
main_url = "{}{}{}".format(subdomain, domain, suffix)
domain = url_object.domain
if domain.strip() != "":
domain = domain.lower()
if categorised_data["website"].get(domain)==None: # domain is not yet categorised
prev_data["website"][domain] = prev_data.get(domain, dict())
prev_data["website"][domain]["site"] = prev_data[domain].get("site", list())
if main_url not in prev_data["website"][domain]["site"]:
prev_data["website"][domain]["site"].append(main_url)
prev_data["website"][domain]["count"] = (
prev_data["website"][domain].get("count", 0) + count
)
# Now remove the backup file after the work is complete
try:
os.system('rm {}'.format(path))
except:
pass
except Exception as e:
print("ERROR", e)
print()
pass
return prev_data
if __name__ == "__main__":
main()
# data_dic = firefox_history_scan()
# pprint.pprint(data_dic)
# Sort the data_dic as per count
|
82111550ad58675ae5ddfae99e2d8b7d44368a10 | AcubeK/LeDoMaiHanh-Fundamental-C4E23 | /Season 2/homework_no2/stars/4.c.py | 144 | 3.6875 | 4 | # print out 9 (stars and xs) in total
for i in range(1, 10):
if i%2 == 1:
print("* ", end="")
else:
print("x ", end="") |
8f27a6dc4d7975c6450d12945fc5a18c92ae889a | kamyu104/LeetCode-Solutions | /Python/reach-a-number.py | 662 | 3.515625 | 4 | # Time: O(logn)
# Space: O(1)
import math
class Solution(object):
def reachNumber(self, target):
"""
:type target: int
:rtype: int
"""
target = abs(target)
k = int(math.ceil((-1+math.sqrt(1+8*target))/2))
target -= k*(k+1)/2
return k if target%2 == 0 else k+1+k%2
# Time: O(sqrt(n))
# Space: O(1)
class Solution2(object):
def reachNumber(self, target):
"""
:type target: int
:rtype: int
"""
target = abs(target)
k = 0
while target > 0:
k += 1
target -= k
return k if target%2 == 0 else k+1+k%2
|
df8bb09d9c7fa0182fe8428db806d66ee31abbeb | mattkim8/CSI | /sierpinski.py | 1,360 | 3.671875 | 4 | # Problem Set 7, Part IV
# Name: Kim, Matthew
# Don't change/remove this line please.
from Tkinter import *
# Don't change this function please.
def draw_triangle(p1, p2, p3):
"""Draw a triangle whose corners are given by tuples p1, p2, and p3."""
window.create_polygon(*(p1+p2+p3), fill='red3')
# Don't change this function please.
def sierpinski(n):
p1 = (100, 450)
p2 = (300, 103.6)
p3 = (500, 450)
sierpinski_helper(n, p1, p2, p3)
return None
# Complete the following function defintion. Feel free to define any other
# function that might help you simplify your code.
def sierpinski_helper(n, p1, p2, p3):
# this function has to be recursive.
# the rest of this function.
if n == 1:
return draw_triangle(p1,p2,p3)
p12 = (((p1[0] +p2[0])/2), (p1[1] + p2[1])/2)
p13 = (((p1[0] +p3[0])/2), (p1[1] + p3[1])/2)
p23 = (((p2[0] +p3[0])/2), (p2[1] + p3[1])/2)
return sierpinski_helper((n-1), p1, p12, p13), sierpinski_helper((n-1),p12, p2,p23), sierpinski_helper((n-1),p13,p23,p3)
# Please don't change the following two lines.
window = Canvas(Tk(), width=600, height=600)
window.pack()
# Change the argument in the following function call to try different examples
# (inputs). For example, try sierpinski(4). Try sierpinski(6)
sierpinski(1)
# Please keep the following line at the end of your code.
mainloop()
|
16c90b7e533f9850501bfcdf034f1a815d6b1e84 | Goodleey/PraktikaPython5 | /Praktika5.py | 1,062 | 3.734375 | 4 | import time
# декаратор времени
def time_this(NUM_RUNS=n): # число прогонов функции(n)
def decorator(func): # декаратор, который принимает в значение другую функцию
def func(*args, **kwargs): # нам не известно, сколько и какие будут аргументы у функции
avg = 0
for i in range(NUM_RUNS):
t0 = time.time() # начальное время
func(*args, **kwargs) # тут выполняется наша функция(или полезный код функции)
t1 = time.time() # конечное время
avg += (t1 - t0) # конечное - начальное
avg /= NUM_RUNS
fn = func.__name__
print("среднее время выполнения", fn)
print("Количество запусков ", NUM_RUNS)
print(avg)
return func
return decorator |
66b1c1b83300b70c837f8e6f827e338793675187 | jayounghoyos/My-Scripts | /Bucles.py | 182 | 3.671875 | 4 | #contador = 0
#print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador))
contador = 1
print("2 elevado a la" + str(contador) + " es igual a: " + str(2**contador)) |
889fdc994806d84b8978ea4658fa70a4794d0484 | celticcow/led | /led.py | 725 | 3.578125 | 4 | #!/usr/bin/python3
import time
import RPi.GPIO as GPIO
def turn_led_on(color):
GPIO.setmode(GPIO.BCM)
GPIO.setup(color, GPIO.OUT)
GPIO.output(color, True)
#end of turn_led_on
def turn_led_off(color):
GPIO.setmode(GPIO.BCM)
GPIO.setup(color, GPIO.OUT)
GPIO.output(color, False)
#end of turn_led_off
def main():
green_led_pin = 18
#GPIO.setmode(GPIO.BCM)
#GPIO.setup(green_led_pin, GPIO.OUT)
#GPIO.output(green_led_pin, True)
turn_led_on(green_led_pin)
for i in range(10):
print("-")
time.sleep(1)
#time.sleep(20)
turn_led_off(green_led_pin)
GPIO.cleanup()
#end of main
if __name__ == "__main__":
main()
#end of program |
a0f735a6d0f71332d287da2a901be7ad3cda9350 | JackMGrundy/coding-challenges | /common-problems-leetcode/medium/longest-turbulent-subarray.py | 3,417 | 3.546875 | 4 | """
A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:
For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is
odd.
That is, the subarray is turbulent if the comparison sign flips between each
adjacent pair of elements in the subarray.
Return the length of a maximum size turbulent subarray of A.
Example 1:
Input: [9,4,2,10,7,8,8,1,9]
Output: 5
Explanation: (A[1] > A[2] < A[3] > A[4] < A[5])
Example 2:
Input: [4,8,12,16]
Output: 2
Example 3:
Input: [100]
Output: 1
Note:
1 <= A.length <= 40000
0 <= A[i] <= 10^9
"""
# 520ms. 97 percentile.
class Solution:
def maxTurbulenceSize(self, A: List[int]) -> int:
up, down = [1]*len(A), [1]*len(A)
for i in range(1, len(A)):
if A[i-1] < A[i]:
up[i] = down[i-1] + 1
elif A[i-1] > A[i]:
down[i] = up[i-1] + 1
return max(max(up), max(down))
# 620ms.
# 20 percentile.
# cmp
class Solution:
def maxTurbulenceSize(self, A: List[int]) -> int:
ans, anchor = 1, 0
for i in range(1, len(A)):
leftVsMid = (A[i-1] > A[i])-( A[i-1] < A[i])
midVsRight = 0 if i == len(A)-1 else (A[i] > A[i+1])-( A[i] < A[i+1])
if leftVsMid == 0:
anchor = i
elif leftVsMid*midVsRight != -1:
ans = max(ans, i - anchor + 1)
anchor = i
return ans
"""
Notes:
We can think of convertin A to a series of cmp operations comparing i and i-1
so that:
[9,4,2,10,7,8,8,1,9]
looks like:
[-1, -1, 1, -1, 1, 0, -1, 1]
Then our goal is to find the longest sequence of alternating +1 -1.
The cmp approach does this explicitly. Python3 got rid of the cmp operation so instead we can
use (a > b)-(a < b).
A more efficient approach is to maintain two arrays "up" and "down that records the
longest streaks such that the last comparison was an increase or decrease respectively.
We can note that for an "up" streak to be valid, there must have been a down on the previous
comparison. As a result, at an index i, if there is an up, then up[i] will be equal to
1 + down[i-1]
""" |
9168818ddf257975a7d1fdb7b8d67f12055f88b9 | infern018/ML-Coursera-in-Python | /EX-1/ex1.1.py | 1,775 | 3.734375 | 4 | import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
data = pd.read_csv('ex1data1.txt', header = None, sep=",")
X = data.iloc[:,0]
y = data.iloc[:,1]
m = len(y)
X = X[:, np.newaxis]
y = y[:, np.newaxis]
theta = np.zeros([2,1])
iterations = 10000
alpha = 0.01
ones = np.ones([m,1])
X = np.hstack((ones,X))
def computeCost(X, y, theta):
temp = np.dot(X, theta) - y
return np.sum(np.power(temp,2))/(2*m)
def gradientDescent(X, y, theta, alpha, iterations):
for i in range(iterations):
temp = np.dot(X, theta) - y
temp = np.dot(X.T, temp)
theta = theta - ((alpha/m)*temp)
return theta
theta = gradientDescent(X, y, theta, alpha, iterations)
print(theta)
J = computeCost(X, y, theta)
print(J)
plt.scatter(X[:,1], y, marker = "x", color= "red")
plt.xlabel('Population of City in 10,000s')
plt.ylabel('Profit in $10,000s')
plt.plot(X[:,1], np.dot(X, theta), color = "blue")
#plt.savefig('graph_1.png')
ppl = int(input("Enter the population in 10,000s: "))
ppl_arr = [1,ppl]
profit = np.dot(ppl_arr, theta)
print("Expected profit: ")
print(profit)
plt.show()
# FROMN INBUILT PYTHON LIBRARY
# data = pd.read_csv('ex1data1.txt', delimiter=',') # load data set
# X = data.iloc[:, 0].values.reshape(-1, 1) # values converts it into a numpy array
# Y = data.iloc[:, 1].values.reshape(-1, 1) # -1 means that calculate the dimension of rows, but have 1 column
# linear_regressor = LinearRegression() # create object for the class
# linear_regressor.fit(X, Y) # perform linear regression
# Y_pred = linear_regressor.predict(X) # make predictions
# plt.xlabel('Population of City in 10,000s')
# plt.ylabel('Profit in $10,000s')
# print()
# plt.scatter(X, Y, marker="x")
# plt.plot(X, Y_pred, color='red')
# plt.show() |
0ae8281b9c222e174432948d5d8433af17fafcee | tbindi/hackerrank | /chocolate_feast.py | 741 | 3.578125 | 4 | '''
Little Bob loves chocolates, and goes to a store with $N in his pocket. The price of each chocolate is $C. The store offers a discount: for every M wrappers he gives to the store, he gets one chocolate for free. How many chocolates does Bob get to eat?
I/P:
3
10 2 5
12 4 4
6 2 2
O/P:
6
3
5
'''
def chocolate_feast(inp):
for i in inp:
N = i[0]
C = i[1]
M = i[2]
ate = wrap = int(N/C)
while wrap >= M:
ate += int(wrap/M)
wrap = int(wrap%M) + int(wrap/M)
print ate
if __name__ == "__main__":
T = int(raw_input())
inp = []
while T != 0:
inp.append(map(int,raw_input().split(' ')))
T -= 1
chocolate_feast(inp) |
ececae10b18697efab08481fcd862f4b8219919f | tayjade/learning-python | /completed_lessons/word reverse script.py | 181 | 4.03125 | 4 |
reverse = input("Type in a word")
index = len(reverse) - 1
output = ""
while index >= 0:
output = output + reverse[index]
index = index - 1
print(output)
|
40709ba151d336b2c474c220f21794e30ba1cbfc | manish4005/my_code | /chessQueenpy | 943 | 3.796875 | 4 | #!/usr/bin/python
import sys
# Problem Statement : Find the place of N queen in NxN chess box
# such they do not kill them selves
to_update = 10
queen_pos = [-25,-25,-25,-25]
def isvalid(raw,col):
global queen_pos
#print "checking validation for {0}, {1} and current queen {2}".format(raw,col,queen_pos)
for i in range(raw):
#print "inside for"
#print i,queen_pos[i],col
if queen_pos[i] ==col or (abs(i-raw) == abs(queen_pos[i]-col)):
return False
return True
def printQueen(raw, col):
global queen_pos
for i in range(col):
#print "raw n col {0},{1} nd last: {2} before check".format(raw,i,col)
if isvalid(raw,i):
#print "raw n col {0},{1}".format(raw,i)
queen_pos.pop(raw)
queen_pos.insert(raw,i)
if raw == col-1:
print "placed queen {0}".format(queen_pos)
return
else:
printQueen(raw+1,col)
printQueen(0,4)
'''queen_pos = [0,-25,-25,-25]
if isvalid(1,0):
print "yes"
else:
print "no" '''
|
cd23d7402f8f212dd8a57b9cbf0a85553426eab2 | thepros847/python_programiing | /assingment/string_istitle_method.py | 304 | 3.765625 | 4 | txt = "Hello, And Welcome To My World!"
x = txt.istitle()
print(x)
a = "HELLO, AND WELCOME TO MY WORLD"
b = "Hello"
c = "22 Names"
d = "This Is %'!?"
e = "theophilus"
f = "prosperia"
print(a.istitle())
print(b.istitle())
print(c.istitle())
print(d.istitle())
print(e.istitle())
print(f.istitle())
|
8d5217dc93c27b806aa6db88ccb60af09b03dbd7 | reynardasis/code-sample | /ex16.py | 646 | 4.125 | 4 | from sys import argv
script, filename = argv
print "we're going to erase %r" %filename
print "press ctrl+c if you dont want"
print "Press enter if you want to proceed"
raw_input("?")
print "Opening file.."
target = open(filename, 'w' , 'r')
print "Erasing data in file..."
target.truncate()
print "Now im going to ask you three lines.."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "Im going to write this in file"
target.write(line1)
target.write("\n")
target.write(line2)
target.write("\n")
target.write(line3)
target.write("\n")
print "and finnally we open it"
print target.read()
|
452003fadc1b4ee159c716acf70aea09ef286b85 | dlee533/comp1510-programming-methods | /Assignments/A4/question_3.py | 787 | 3.515625 | 4 | import doctest
def dijkstra(colour_list: list) -> None:
"""sort the list
:param colour_list: a list
:precondition: cololur_list must be a list with any number of 'red', 'white', and 'blue'
:postcondition: sort the list with value returned from second_character function
:return: None
"""
colour_list.sort(key=second_character)
def second_character(word: str) -> str:
"""Return the second character
:param word: a string
:precondition: word must be a string
:return: the second character/index one of the string
>>> second_character('white')
'h'
>>> second_character('red')
'e'
>>> second_character('blue')
'l'
"""
return word[1]
def main():
doctest.testmod()
if __name__ == "__main__":
main()
|
d279a67256599d2b7f9201e83b0d2ea365f9ad81 | oaao/smsos | /smsos/classifiers/input.py | 1,649 | 3.734375 | 4 | import os
import pandas
class CsvDataInput:
"""
Ingests a classified CSV dataset as a pandas dataframe
and distributes items into training and test data
according to a given item count or decimal proportion.
"""
def __init__(self, filepath, training_cases=None, encoding='utf-8'):
self.data = self._load_csv(filepath, encoding)
self.split_index = self._get_data_split(training_cases)
self.train, self.test = self.split_data()
def split_data(self):
return (self.data[:self.split_index], self.data[self.split_index:])
def _load_csv(self, path, encoding):
realpath = os.path.join(os.path.abspath(os.path.dirname(__file__)), path)
data = pandas.read_csv(realpath, encoding=encoding)
try:
if data.count == 0:
raise ValueError('Dataframe is empty')
else:
return data
except AttributeError:
raise AttributeError('Data coult not be loaded as a dataframe')
def _get_data_split(self, n):
rows, cols = self.data.shape
if isinstance(n, int):
if n <= rows:
return n
else:
raise ValueError('Training case count cannot exceed total data length')
elif isinstance(n, float):
if n <= 1.0:
# casting float to int is a floor operation
return int(n * rows)
else:
raise ValueError('Training case proportion cannot exceed 100%')
else:
raise ValueError('Unsupported value; please use count integer or float proportion')
|
cce715b6938e2f5c16d6ee158ebfa7e15b4e0645 | samsolariusleo/cpy5python | /practical02/q11_find_gcd.py | 725 | 4.28125 | 4 | # Filename: q11_find_gcd.py
# Author: Gan Jing Ying
# Created: 20130207
# Modified: 20130207
# Description: Program to find the greatest common divisor of two integers.
# main
# prompt user for the two integers
integer_one = int(input("Enter first integer: "))
integer_two = int(input("Enter second integer: "))
# find out which is the smaller of integer_one and integer_two
if integer_one > integer_two:
d = integer_two
elif integer_one < integer_two:
d = integer_one
else:
print("The greatest common divisor is " + str(integer_one) + ".")
exit()
# find greatest divisor
while integer_one % d != 0 or integer_two % d != 0:
d = d - 1
# return results
print("The greatest common divisor is " + str(d) + ".")
|
24586b9f007be49feaced2d7daf64cd59e35f9be | morozov1982/python-checkio | /oop/the_warriors.py | 6,696 | 4 | 4 | """
***** The Warriors *** (Simple) *****
***(EN)***
I'm sure that many of you have some experience with computer games.
But have you ever wanted to change the game so that the characters or a game world
would be more consistent with your idea of the perfect game? Probably, yes.
In this mission (and in several subsequent ones, related to it) you’ll have a chance "to sit in the developer's chair"
and create the logic of a simple game about battles.
Let's start with the simple task - one-on-one duel.
You need to create the class Warrior, the instances of which will have 2 parameters - health (equal to 50 points)
and attack (equal to 5 points), and 1 property - is_alive,
which can be True (if warrior's health is > 0) or False (in the other case).
In addition you have to create the second unit type - Knight,
which should be the subclass of the Warrior but have the increased attack - 7.
Also you have to create a function fight(),
which will initiate the duel between 2 warriors and define the strongest of them.
The duel occurs according to the following principle:
* Every turn, the first warrior will hit the second and this second will lose his health
in the same value as the attack of the first warrior.
After that, if he is still alive, the second warrior will do the same to the first one.
* The fight ends with the death of one of them.
If the first warrior is still alive (and thus the other one is not anymore),
the function should return True, False otherwise.
Round 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Warrior 50 50 43 43 36 36 29 29 22 22 15 15 8 8 1 1 -6
Knight 50 45 45 40 40 35 35 30 30 25 25 20 20 15 15 10 10
Example:
1. chuck = Warrior()
2. bruce = Warrior()
3. carl = Knight()
4. dave = Warrior()
5.
6. fight(chuck, bruce) == True
7. fight(dave, carl) == False
8. chuck.is_alive == True
9. bruce.is_alive == False
10. carl.is_alive == True
11. dave.is_alive == False
Input: The warriors.
Output: The result of the duel (True or False).
How it is used: For computer games development.
Precondition:
* 2 types of units
* All given fights have an end (for all missions).
***(RU)***
Наверняка многие из вас имеют опыт прохождения компьютерных игр.
Возникало ли у вас в процессе игры желание изменить что-нибудь и сделать так,
чтобы персонажи или игровой мир больше соответствовали вашему представлению о хорошей игре? Скорее всего да.
В этой миссии (и в нескольких последующих, связанных с ней)
вам предоставится возможность «посидеть в кресле разработчика» и создать логику простой игры о сражениях.
Давайте начнем с малого — сражения 1×1.
В этой миссии вам необходимо будет создать класс Warrior,
у экземпляров которого будет 2 параметра — здоровье (равное 50) и атака (равная 5),
а также свойство is_alive, которое может быть True (если здоровье воина > 0) или False (в ином случае).
Кроме этого вам необходимо создать класс для второго типа солдат — Knight, который будет наследником Warrior,
но с увеличенной атакой — 7. Также вам необходимо будет создать функцию fight(),
которая будет проводить дуэли между 2 воинами и определять сильнейшего из них.
Бои происходят по следующему принципу:
• каждый ход первый воин наносит второму урон в размере своей атаки,
вследствие чего здоровье второго воина уменьшается
• аналогично и второй воин, если он еще жив, поступает по отношению к первому.
Битва заканчивается смертью одного из них. Если первый воин все еще жив (а второй, соответственно, уже нет),
функция возвращает True, или в ином случае False.
Round 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Warrior 50 50 43 43 36 36 29 29 22 22 15 15 8 8 1 1 -6
Knight 50 45 45 40 40 35 35 30 30 25 25 20 20 15 15 10 10
Пример:
1. chuck = Warrior()
2. bruce = Warrior()
3. carl = Knight()
4. dave = Warrior()
5.
6. fight(chuck, bruce) == True
7. fight(dave, carl) == False
8. chuck.is_alive == True
9. bruce.is_alive == False
10. carl.is_alive == True
11. dave.is_alive == False
Входные данные: воины.
Выходные данные: результат поединка (True или False).
Как это используется: Для разработки компьютерных игр.
Предусловие: 2 типа солдат
"""
class Warrior:
def __init__(self):
self.health = 50
self.attack = 5
@property
def is_alive(self):
return self.health > 0
class Knight(Warrior):
def __init__(self):
super().__init__()
self.attack = 7
def fight(unit_1, unit_2):
attacker, attacked = unit_1, unit_2
while True:
attacked.health -= attacker.attack
if attacked.is_alive:
attacker, attacked = attacked, attacker
continue
break
return unit_1.is_alive
if __name__ == '__main__':
# These "asserts" using only for self-checking and not necessary for auto-testing
chuck = Warrior()
bruce = Warrior()
carl = Knight()
dave = Warrior()
mark = Warrior()
print(chuck.health)
print(chuck.attack)
print(chuck.is_alive)
print(carl.health)
print(carl.attack)
print(carl.is_alive)
assert fight(chuck, bruce) == True
assert fight(dave, carl) == False
assert chuck.is_alive == True
assert bruce.is_alive == False
assert carl.is_alive == True
assert dave.is_alive == False
assert fight(carl, mark) == False
assert carl.is_alive == False
print("Coding complete? Let's try tests!")
|
c5e6ebcfb91bc63b4e520e6a63b8ffcb7ccb58cc | jkane002/tomas_python | /homework/unit_03/hw05.py | 266 | 3.59375 | 4 |
import requests
from bs4 import BeautifulSoup
url = input("Enter a website to extract the URL's from: ")
response = requests.get(url)
page = response.content
soup = BeautifulSoup(page, 'html.parser')
for link in soup.find_all('a'):
print(link.get('href'))
|
9edecbf7bd5f5afb31eafdef193a0ca04ec5a85e | benchng/python_onsite | /week_01/05_lists/Exercise_01.py | 283 | 4.09375 | 4 | '''
Take in 10 numbers from the user. Place the numbers in a list.
Using the loop of your choice, calculate the sum of all of the
numbers in the list as well as the average.
Print the results.
'''
numbers = [1, 2, 3, 4, 5]
sum = 0
for i in numbers:
sum = i + sum
print(sum)
|
576b007fdfa7c8cc983f6f9241118b85757b3be7 | Alex-GCX/algorithm | /08.binary_search.py | 2,233 | 3.765625 | 4 | def binary_search(items, item):
"""二分法查找, 切片递归"""
# 最优时间复杂度: O(1), 刚好要找的数就在中间
# 最坏时间复杂度: O(logn), 一直对半拆分, 直到拆到最后一层才找到元素, 共拆分了logn次
# 说明: 只能针对有序列表进行二分法查找
# 算法: 将有序列表对半拆分, 比较中间的元素和要找的元素, 若相等, 则找到了, 若比中间元素大, 则将右边列表切片出来递归调用, 继续寻找
# 使用切片只能判断元素是否在列表中, 而不能返回元素在列表中的下标位置
# 获取长度
length = len(items)
# 若长度为0, 则说明不存在该列表中
if length < 1:
return False
# 对半分找到中间元素
mid = length // 2
# 比较中间元素和所找元素
if item == items[mid]:
return True
elif item > items[mid]:
return binary_search(items[mid + 1:], item)
else:
return binary_search(items[:mid], item)
def binary_search_2(items, item, start=0, end=None):
"""二分法查找, 原列表递归"""
# 最优时间复杂度: O(1), 刚好要找的数就在中间
# 最坏时间复杂度: O(logn), 一直对半拆分, 直到拆到最后一层才找到元素, 共拆分了logn次
# 说明: 只能针对有序列表进行二分法查找
# 算法: 将有序列表对半拆分, 比较中间的元素和要找的元素, 若相等, 则找到了, 若比中间元素大, 则将右边列表部分进行递归调用, 继续寻找
# 获取长度
length = len(items)
# 初始化end
if end is None:
end = length
# 若起始位置和结束位置相同, 则说明没有找到
if start == end:
return False
# 获取中间位置
mid = (start+end) // 2
# 比较中间元素和所找元素
if item == items[mid]:
return mid
elif item > items[mid]:
return binary_search_2(items, item, mid+1, end)
else:
return binary_search_2(items, item, start, mid)
if __name__ == '__main__':
items = [3, 4, 7, 20, 20, 29, 39, 56, 90]
item = 56
print(binary_search(items, item))
print(binary_search_2(items, item))
|
64c22bf8255a55cbed23b2a39b9f61d1626d87d1 | burakbayramli/books | /Python_Scripting_for_Computational_Science_Third_Edition/py/regex/latex_subst.py | 2,830 | 4.125 | 4 | #!/usr/bin/env python
"""
This program investigates match and replacement involving
words starting with a backslash. Such words are highly relevant
when working with text in LaTeX format.
The program identifies problematic characters that need a
double backslash in the replacement string. For a right
substitution, all commands that start with a backslash need
an extra backslash, as two things may go wrong: \b will
indicate a word boundary and give a wrong match, while \c
will simply escape the c, and hence match the c and then
leave an extra undesired backslash in the substituted string.
"""
import string, re
letters = string.ascii_letters
print '\nInvestigating matching with re.search and re.sub\n'
escape4match = []
for letter in letters:
pattern = r'(\%sword)' % letter
text = r'Text with \%sword in it' % letter
repl = 'xxxx'
try:
m = re.search(pattern, text)
if not m:
print 'could not match', pattern, 'in', text
escape4match.append(letter)
else:
# correct match?
if m.group(1) != r'\%sword' % letter:
print m.group(1), 'is wrong match of', pattern
# what about substitutions?
new = re.sub(pattern, repl, text)
if not ' xxxx ' in new:
print 'wrong %s substitution:' % pattern, new
except Exception, e:
print 'problem with %s: ' % pattern, e
escape4match.append(letter)
# add double backslash:
pattern = r'\\%sword' % letter
try:
m = re.search(pattern, text)
if m:
print 'could match', pattern, 'in', text
new = re.sub(pattern, repl, text)
if ' xxxx ' in new:
print 'correct %s substitution:' % pattern, new
except Exception, e:
print 'problem with %s: ' % pattern,
print e
print '\nInvestigating replacement string in re.sub\n'
escape4replacement = []
for letter in letters:
pattern = 'xxxx'
replacement = r'\%s' % letter
text = r'Text with xxxx in it'
try:
new, n = re.subn(pattern, replacement, text)
for i in new:
if ord(i) == 32 or 65 <= ord(i) <= 90 or \
ord(i) == 92 or 97 <= ord(i) <= 122:
pass # fine
else:
print '\nunsuccessful replacement by %s' % replacement
print 'output repr:', repr(new)
print 'output str :', str(new)
escape4replacement.append(letter)
except Exception, e:
print 'problem with letter %s: ' % letter,
print e
escape4replacement.append(letter)
print 'Always need an extra backslash for match'
print 'If char is any of %s, \\char has special meaning' % ''.join(escape4match)
print 'Need to escape %s for replacement pattern' % ''.join(escape4replacement)
|
fb761f82946b04906b0afb4f62130a7cd0f498e7 | NiceToMeeetU/ToGetReady | /Code/leetcode_everyday/0330.py | 3,605 | 3.75 | 4 | # coding : utf-8
# @Time : 21/03/30 10:39
# @Author : Wang Yu
# @Project : ToGetReady
# @File : 0330.py
# @Software: PyCharm
# Definition for singly-linked list.
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
"""
25. K 个一组翻转链表
给你一个链表,每k个节点一组进行翻转,请你返回翻转后的链表。
k是一个正整数,它的值小于或等于链表的长度。
如果节点总数不是k的整数倍,那么请将最后剩余的节点保持原有顺序。
进阶:
你可以设计一个只使用常数额外空间的算法来解决此问题吗?
你不能只是单纯的改变节点内部的值,而是需要实际进行节点交换。
:param head:
:param k:
:return:
base case 不太好处理
"""
if not head or not head.next:
return head
n1, n2 = head, head
for _ in range(k):
if not n2:
return head
n2 = n2.next
# n1 起, n2 止
res = None
while n1 != n2:
n1.next, tmp, n1 = tmp, n1, n1.next
head.next = self.reverseKGroup(n2, k)
return res
def reorderList(self, head: ListNode) -> None:
"""
132. 重排链表
前后交叉重排
:param head:
:return:
先把后半段反转,然后遍历合并?
"""
# slow, fast = head, head
# while fast and fast.next:
# slow = slow.next
# fast = fast.next.next
# tmp = None
# while slow:
# slow.next, tmp, slow = tmp, slow, slow.next
#
# p1, p2 = head, tmp
# while p1 and p2:
# # 合并两个链表
# p1.next = p2
# tmp = p2.next
# p2.next = p1.next
# p1 = p1.next
# p2 = tmp
# return head
def findMiddle(head_: ListNode):
"""
找到链表的中点
"""
slow, fast = head_, head_
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def reverse(head_: ListNode):
"""
反转链表
"""
p1, p2 = head_, None
while p1:
p1.next, p2, p1 = p2, p1, p1.next
return p2
def merge(n1: ListNode, n2: ListNode):
"""
交替合并两个链表
"""
# 递归的写法不太友好
if not n1:
return n2
if not n2:
return n1
tmp1 = n1.next
tmp2 = n2.next
n1.next = n2
n2.next = merge(tmp1, tmp2)
return n1
# 重写个迭代的
while not n1 and not n2:
tmp1 = n1.next
tmp2 = n2.next
n1.next = n2
n1 = tmp1
n2.next = n1
n2 = tmp2
# 放大招
n1,n2,n1.next,n2.next = n1.next, n2.next, n2, n1
mid = findMiddle(head)
l1 = head
l2 = mid.next
mid.next = None
l2 = reverse(l2)
merge(l1, l2)
|
436974bf6f9725aa66ca63c3754c9d1e6d2e8c0b | yizhiyan1992/LeetCode_problems | /496_Next_Greater_Element_I.py | 1,007 | 3.65625 | 4 | #monostack problem
#Keep the stack with decreasing order, when an element gonna be added in the stack, examine weather it is smaller than the peak element of the stack.
# If yes, then put the element in the stack. If no, then pop the peak element and put the answer in array[stack[peak]]. Then, repeat this process until the last element is tested.
# Note: the length of the asnwer array is max(nums1), instead of len(nums1)
#Time complexity: O(n)
class Solution:
def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:
if not nums1: return []
Max=max(nums2)
store=[-1 for _ in range(Max+1)]
monostack=[float('inf')]
i=0
while i<=len(nums2)-1:
if nums2[i]<monostack[-1]:
monostack.append(nums2[i])
i+=1
else:
value=monostack.pop()
store[value]=nums2[i]
ans=[]
for i in nums1:
ans.append(store[i])
return ans
|
96c64fdfd4a2831871a61784c82675caad64a3de | vii-sem/vii-a-web-programs-DeepakPurohit_ENG17CS0062 | /python program 4/program 4_thread.py | 673 | 3.75 | 4 | #Create Virtual Environment in Python2
'''
virtualenv -p `which python2` env
source env/bin/activate
'''
#copy the program in thread.py
import _thread
import time
# Define a function for the thread
def print_time(threadName, delay):
count=0
while count <5:
time.sleep(delay)
count+=1
print("%s: %s" %(threadName,time.ctime(time.time())))
# Create two threads as follows
try:
_thread.start_new_thread(print_time,("Thread-1",2,))
_thread.start_new_thread(print_time,("Thread-2",4,))
except:
print("Error: unable to start thread")
while 1:
pass
'''
#Run the program
python thread.py
'''
|
eb58cf6d44f6c90444b3729b780a47284d5340eb | odys-z/hello | /challenge/leet/medium/q047.py | 1,607 | 3.640625 | 4 | from unittest import TestCase
from typing import List
from itertools import permutations
class Solution2:
'''
can't work in python 3.5?
'''
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
return list( dict.fromkeys( permutations(nums) ).keys() )
class Solution:
def permuteUnique(self, nums: List[int]) -> List[List[int]]:
def key(permu):
k = 0
for x in permu:
k = (k*100) + (x + 10) # -10 <= nums[i] <= 10
return k
l = len(nums)
if l <= 1: return [nums[:]]
else:
res = []
pdict = {}
for _ in range(l):
c = nums.pop(0)
subs = self.permuteUnique(nums)
for p in subs:
p.append(c)
for s in subs:
k = key(s)
if k not in pdict:
res.append(s)
pdict.update({k: None})
nums.append(c)
return res
if __name__ == "__main__":
t = TestCase()
s, s2 = Solution(), Solution2()
t.assertCountEqual([[1,2], [2, 1]], s.permuteUnique( [1,2] ))
t.assertCountEqual([[1,2,2],[2,1,2],[2,2,1]],
s.permuteUnique( [1,2,2] ))
print( s2.permuteUnique( [0, -1, 1] ) )
print( s.permuteUnique( [0, -1, 1] ) )
t.assertCountEqual([[1, -1, 0], [-1, 1, 0], [0, 1, -1], [1, 0, -1], [-1, 0, 1], [0, -1, 1]],
s.permuteUnique( [0, -1, 1] ))
print('OK!') |
b25f4cdad748309ec1ae967bccf6ffade51044ba | sainad2222/my_cp_codes | /codeforces/382/A.py | 346 | 3.828125 | 4 | string = input().split("|")
s = [len(x) for x in string]
t = input()
if (s[0] + s[1] + len(t)) % 2:
print("Impossible")
exit()
mid = (s[0] + s[1] + len(t)) // 2
if not (s[0] <= mid and s[1] <= mid):
print("Impossible")
exit()
string[0] += t[:mid - s[0]]
string[1] += t[mid - s[0]:]
print(string[0] + "|" + string[1])
|
b8041d9d964f868323b5a5d00fce79eee4e203e2 | caleb0/ProjectEuler | /Questions 1-50/007.py | 250 | 3.640625 | 4 | # Problem 7
# 5th September 2016
# Python 2
def isPrime(n):
for i in range(2, int(n**0.5)+1):
if (n % i ) == 0:
return False
return True
index = 1
num = 1
while index != 10001:
if isPrime(num):
index += 1
num += 2
print(num)
|
27ce45eb840660db8a1d7f8eedf9bd13fed94b2e | Yoodahun/Practice-RESTAPITest-on-Python | /CSV/CSVDemo.py | 696 | 3.546875 | 4 | import csv
# Open the file and read
with open('/Users/yoodahun/Documents/Github/Python/RestAPI-Testing-on-Python/utilities/practiceCSV.csv') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=",")
# print(csv_reader)
# print(dict(csv_reader))
name = []
status = []
for row in list(csv_reader):
name.append(row[0])
status.append(row[1])
print(name)
print(status)
name_sam_index = name.index('sam')
print(status[name_sam_index])
# Open the file write
with open('/Users/yoodahun/Documents/Github/Python/RestAPI-Testing-on-Python/utilities/practiceCSV.csv', 'a') as csv_file:
write = csv.writer(csv_file)
write.writerow(["Bob", "rejected"]) |
7d3abe8e4c22670fd6e72b28e1bdc178c2773865 | Tymekkos/python-files | /RzutKostka/Proc4.py | 1,534 | 4.0625 | 4 |
import random
print("----------------------------")
print("------ Dice Throwing -------")
print("----------------------------")
print("1 - Drawing ")
print("2 - Quit")
continuation = True
operation = input("What will you choose ? - ")
while continuation:
res = random.randrange(1, 7)
if operation == "1":
if res == 1:
print(" X X X")
print("1 - X O X")
print(" X X X")
elif res == 2:
print(" X X X")
print("2 - O X O")
print(" X X X")
elif res == 3:
print(" X X O")
print("3 - X O X")
print(" O X X")
elif res == 4:
print(" O X O")
print("4 - X X X")
print(" O X O")
elif res == 5:
print(" O X O")
print("5 - X O X")
print(" O X O")
elif res == 6:
print(" O X O")
print("6 - O X O")
print(" O X O")
elif operation == "2":
continuation = False
else:
print(" You choosed wrong number or letter !")
operation2 = input("Would You like to continue this program? [yes - \"press enter\" / no] ")
if operation2 == "no":
continuation = False
elif operation2 == "":
continuation = True
|
7b511da832b6d985eada6c3691bf574f212acd19 | sw30637/assignment8 | /hh818/mergeByYear.py | 401 | 3.703125 | 4 | '''
Created on Apr 14, 2015
@author: ds-ga-1007
'''
import pandas as p
def merge_by_year(income, countries, year):
'''merge two data sets by country names, and have three columns: Country, Region, and Income'''
tempDf = p.DataFrame({'Country':income.ix['gdp pc test'], "Income":income.ix[year]})
mergedDf = p.merge(countries, tempDf, on = 'Country', how='inner')
return mergedDf |
468f09264e8b203f911845312f7db9d27592eb64 | ZhouningMan/LeetCodePython | /dynamicprogramming/CoinsInALineII.py | 1,529 | 3.6875 | 4 | class Solution:
"""
@param values: a vector of integers
@return: a boolean which equals to true if the first player will win
"""
def firstWillWin(self, values):
if not values:
return False
n = len(values)
if n < 3:
return True
dp = [0] * 3
dp[(n-1) % 3] = values[n-1]
dp[(n-2) % 3] = values[n-1] + values[n-2]
for i in reversed(range(n-2)):
# dp[i] stores the maximum differences starting from position i
dp[i % 3] = max(values[i] - dp[(i + 1) % 3], values[i] + values[i+1] - dp[(i + 2) %3])
return dp[0] > 0
def firstWillWinPrefix(self, values):
if not values:
return False
n = len(values)
if n < 3:
return True
suffix_sum = self.suffix_sum(values)
dp = [0] * n
dp[-1] = values[-1]
dp[-2] = values[-1] + values[-2]
for i in reversed(range(n-2)):
# the maximum value at i for an actor is the maximum value of choosing either i or (i and i+1)
# elements,
dp[i] = max(values[i] + suffix_sum[i+1] - dp[i+1], # dp[i+1] is the maximum value of opponent
values[i] + values[i+1] + suffix_sum[i+2]-dp[i+2])
return dp[0] > suffix_sum[0] / 2
def suffix_sum(self, values):
ss = [0] * len(values)
ss[-1] = values[-1]
for i in reversed(range(len(values) - 1)):
ss[i] = ss[i+1] + values[i]
return ss |
b1bae4b3c95226ba85208fe2f54aa9530e9ba585 | knpatil/learning-python | /src/car.py | 1,524 | 4.25 | 4 | class Car:
# constructor
def __init__(self, make, model, year):
self.make = make
self.model = model
self.year = year
# odometer
self.odometer_reading = 0
self.color = "red"
# to string method -- means string representation of object
def __str__(self):
return f"CAR: model={self.model},make={self.make},year={self.year}"
def get_description(self):
print("My car details: ")
print(f"\t Make: {self.make}")
print(f"\t Model: {self.model}")
print(f"\t Year: {self.year}")
print(f"\t Color: {self.color}")
def read_odometer(self):
print(f"This car has {self.odometer_reading} kilometers on it.")
def drive_car(self, kms):
print(f"Driving this car by {kms} kilometers")
self.odometer_reading += kms
def paint_car(self, color):
print(f"Painting the car with color {color}")
self.color = color
def fill_gas_tank(self):
print(f"Filling gas tank in this model {self.model}")
my_new_car = Car("Audi", 'A4', 2020)
x = 10
name = "xyz"
print(x)
print(name)
print(my_new_car) # __str__ tostring
car2 = Car("BMW", 'Series 5', 2023)
print(car2)
# my_new_car.get_description()
# my_new_car.read_odometer()
#
# my_new_car.drive_car(10)
# my_new_car.read_odometer()
#
# my_new_car.drive_car(400)
# my_new_car.read_odometer()
#
# my_new_car.drive_car(200)
# my_new_car.read_odometer()
#
# my_new_car.paint_car("Blue")
# my_new_car.get_description()
|
a73f7a8016b7a8275e5a4e9c60b8b1bcf27f42b2 | archenRen/learnpy | /leetcode/binary_search/code-69.py | 308 | 3.53125 | 4 | def mySqrt(x: int) -> int:
def guess(mid):
return mid * mid <= x
lo = 0
hi = x + 1
ans = 0
while lo < hi:
mid = (lo + hi) // 2
if guess(mid):
ans = mid
lo = mid + 1
else:
hi = mid
return ans
print(mySqrt(231234))
|
b67926a1569c2e248232184d39f3e5d6a670d276 | tomi77/python-t77-date | /t77_date/time.py | 983 | 3.75 | 4 | """A set of datetime.time related functions"""
from __future__ import absolute_import
from datetime import datetime, time
def diff_time(t1, t2):
"""
Calculates datetime.timedelta between two datetime.time values.
:param t1: First time
:type t1: datetime.time
:param t2: Second time
:type t2: datetime.time
:return: Differences between t1 and t2 or None when t1 or t2 is None
:rtype: datetime.timedelta/None
:raise: ValueError when t1 or t2 is not datetime.time or None
"""
if t1 is None or t2 is None:
return None
if not isinstance(t1, time):
raise ValueError('"t1" must be a datetime.time')
if not isinstance(t2, time):
raise ValueError('"t2" must be a datetime.time')
dt1 = datetime(1, 1, 1,
t1.hour, t1.minute, t1.second, t1.microsecond, t1.tzinfo)
dt2 = datetime(1, 1, 1,
t2.hour, t2.minute, t2.second, t2.microsecond, t2.tzinfo)
return dt1 - dt2
|
9b6049bf0bfa4303e4144fdcd2729dc5f269a7cf | aeronqu/projecteuler | /problem14.py | 396 | 3.875 | 4 |
def collatzSeq(n):
yield n
while 1:
if n == 1:
break
elif n % 2 == 0:
n = n/2
yield n
else:
n = n*3 + 1
yield n
def colatz():
for i in range(1,1000000):
yield sum(1 for value in collatzSeq(i))
number = 0
for value in colatz():
if number < value:
number = value
print number
|
ecba36c433819051003b329b4368ec0709c2c08d | khemadeepthi/python | /loops.py | 820 | 4.03125 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Dec 1 21:47:08 2018
@author: hema
"""
input_number = int(input("enter a number: "))
type(input_number)
if(input_number < 10):
print("input number is < 10")
elif(input_number == 10):
print("number is 10")
else:
print("input number is > 10")
# while loop
i=0
while(i <= 10):
print(i)
i+=2
for i in range(0,11):
if(i%2 == 0):
print(i)
else:
pass
for i in range(0,11):
if(i%2 == 0):
print(i)
tuple1 = ('mon','tue','wed')
for i in tuple1:
print(i)
tuple2 = ('jan','feb','mar')
for i in tuple2:
print(i,end=',')
a = 10
for i in a:
print(i)
alphabets = 'abcde'
for i in alphabets:
print(i.upper() ,end=',')
|
153aa9b3713cdf137d847860e43b861325f2a24c | amark02/ICS4U-Classwork | /Quiz2/test_evaluation.py | 1,322 | 3.515625 | 4 | import evaluation
def test_average():
assert evaluation.average(1, 1, 1) == 1.0
assert evaluation.average(1, 2, 3) == 2.0
assert evaluation.average(3, 0, 0) == 1.0
def test_pieces_of_wood():
assert evaluation.count_length_of_wood([10, 12, 13, 10, 15], 10) == 2
assert evaluation.count_length_of_wood([5, 3, 10, 2], 4) == 0
assert evaluation.count_length_of_wood([2, 2, 2, 2], 2) == 4
def test_occurance_of_board_length():
initial_list = []
expected = {}
result = evaluation.occurance_of_board_length(initial_list)
assert result == expected
intial_list = [10, 10, 3]
expected = {10: 2, 3: 1}
result = evaluation.occurance_of_board_length(intial_list)
assert result == expected
intial_list = [5, 5, 5, 5, 5]
expected = {5: 5}
result = evaluation.occurance_of_board_length(intial_list)
assert result == expected
def test_get_board_length():
intial_dict = {10: 2, 5: 1}
expected = 2
result = evaluation.get_board_length(intial_dict, 10)
assert result == expected
intial_dict = {15: 5, 3: 1, 0: 2}
expected = 5
result = evaluation.get_board_length(intial_dict, 15)
assert result == expected
intial_dict = {}
expected = 0
result = evaluation.get_board_length(intial_dict, 5)
assert result == expected |
a38504fb9031d8aa7e4f804c147fdf7fc1f9100b | lucasbflopes/codewars-solutions | /7-kyu/map-function-issue/python/solution.py | 309 | 3.875 | 4 | def func(n):
return int(n) % 2 == 0
def map(arr, somefunction):
if not callable(somefunction):
return 'given argument is not a function'
elif any(str(n).isalpha() for n in arr):
return 'array should contain only numbers'
else:
return [somefunction(n) for n in arr] |
5359bdc2312603e6950b89c10eefb92ee16fa204 | jddelia/think-python | /Section10/anagram.py | 270 | 4.34375 | 4 | # This program checks whether two words
# are anagrams.
def is_anagram(word1, word2):
for i in word1:
if i not in word2:
break
if i in word2 and i == word2[-1]:
print(word1 + ' is an anagram of ' + word2 + '.')
is_anagram()
|
bcabc538471d0925536463efca00cb6bf0e9edd5 | AlexRuadev/python-bootcamp | /10 - Errors and Exceptions Handling/try_except_finally.py | 1,004 | 4.28125 | 4 | try:
# introducing an error with "r" instead of "w"
f = open('testfile', 'w')
f.write('Write a test line')
except TypeError:
# if we have a type error, print the following
print('There was a type error')
except:
print('There is another exception error')
# Finally will always run the code, no matter what
finally:
print('I always run')
def ask_for_int():
# Creating a loop to repeat our function until an int is provided and there's no more errors
while True:
try:
result = int(input("Please provide number: "))
except:
print("Whoops! That is not a number")
continue
else:
print("Yes thank you")
# break the loop if we have a "Yes thank you"
break
finally:
print("End of try/except/finally")
print("I'm always running at the end")
# run this and write a string for an error, or an integer for it to print our finally
ask_for_int()
|
5ed76ac888a1d0917832b9ed482aea6eb112b3f1 | Favii4/Pruebas_de_conocimiento | /archivoParesImpares.py | 750 | 3.671875 | 4 | def num_pares(n=20):
pares=[]
contador = 0
numero = 0
while contador < n:
if numero % 2 == 0:
pares.append(numero)
contador += 1
numero += 1
return pares
def num_impares(n=20):
impares=[]
contador = 0
numero = 0
while contador < n:
if numero % 2 != 0:
impares.append(numero)
contador += 1
numero += 1
return impares
n = int(input('Escriba un numero '))
pares = num_pares(n)
impares = num_impares(n)
print('Estos son los primeros' , (n) , 'numeros pares: ' , (pares))
print('Estos son los primeros' , (n) , 'numeros impares: ' , (impares)) |
a81c746208f502cbac9a4a4f591be5f131ad02cd | kanhaichun/ICS4U | /Shutupandbounce/Emma/FruitStand.py | 7,000 | 4.09375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Mon Apr 16 16:27:32 2018
Porject name: Fruit Stand
Purpose: to design a set of classes for a "Fruit Stand" application.
Variables:name, quantity, price
@author: fy
"""
class fruit:
'''
This class organizes infomation for each fruit available at the stand.
'''
#Pass 3 arguments for each fruit(type: string, integer, and integer)
def __init__(self, name, quantity, price):
self.name = name
self.quantity = int(quantity)
self.price = float(price)
def getName(self):
#Prints the name of the fruit.
return self.name
def getPrice(self):
#Prints the price of the fruit.
return self.price
def getQuantity(self):
#Prints the number of fruit.
return self.quantity
class fruitstand:
'''
This class contains a collection of fruit instances
and allows the shopper to buy fruit,
adjusting quantities of fruit accordingly.
'''
#This function creates a list of 5 instances of the fruit class complete with names, quantities,
#and prices to initialize the stand with those instances.
def __init__(self):
'''
#The fruit stand has 10 apples, $2/each.
#The fruit stand has 20 bananas, $0.5/each.
#The fruit stand has 7 pears, $1.5/each.
#The fruit stand has 6 avocados, $3/each.
#The fruit stand has 14 durians, $8/each.
'''
self.fruitstand_inventory = [fruit("Apple",10,2),fruit("Banana",20,0.5),
fruit("Pear",7,1.5),fruit("Avocado",6,3),
fruit("Durian",14,8)]
#This function adjusts the number of fruit available in its fruit class
#according to the number of fruit actually purchased.
#Takes the name of the shopper, the shopper's available cash,
#the name of the fruit, and the quantity of fruit as arguments
#(type:string,integer,string, integer).
def purchase(self, shoppername, shoppercash, choice_of_fruit, choice_of_quantity):
for i in self.fruitstand_inventory:
if choice_of_fruit == i.getName():
#If the shopper can afford the fruit,
if shoppercash >= choice_of_quantity * float(i.getPrice()):
#and if the fruit stand can support the fruit,
if i.quantity >= choice_of_quantity:
#the shopper succeeds in buying this fruit.
i.quantity -= choice_of_quantity
shoppercash -= choice_of_quantity * float(i.getPrice())
else:
i.quantity = choice_of_quantity
#If the shopper cannot afford the quantity that has to be paid:
else:
choice_of_quantity = shoppercash/choice_of_fruit.getPrice()
self.quantity -= choice_of_quantity
#Returns the name and quantity of that fruit to indicate
#that the customer has successfully purchased the fruit
#(up to the number of available fruit)
return [i.getName(), choice_of_quantity]
#This function lists the names and quantities of fruit available at the
#fruitstand by iterating through the list and accessing the names of the fruit...
def display(self):
print("Available inventory of the fruit stand:","\n",
"Name Quantity")
for i in self.fruitstand_inventory:
print("{0} {1}".format(i.getName(), i.getQuantity()))
class shopper:
'''
This class represents a customer. The customer has money and is shopping
for fruit at the fruitstand.
'''
#This function passes 2 arguments for each shopper(type:string,integer).
def __init__(self, shoppername, shoppercash):
self.shoppername = shoppername
self.shoppercash = shoppercash
shoppercash = 100
self.F = fruitstand()#An instance of the fruitstand class.
#I - a personal inventory of fruit in the form of a list of fruit instances.
self.I = [fruit("Apple",0,2),fruit("Banana",0,0.5),
fruit("Pear",0,1.5),fruit("Avocado",0,3),
fruit("Durian",0,8)]
def update(self, choice_of_fruit, choice_of_quantity):
#new_shopper_inventory = self.F.purchase(self.shoppername, self.shoppercash,
# self.choice_of_fruit, self.choice_of_quantity)
gain = self.F.purchase(self.shoppername, self.shoppercash, choice_of_fruit, choice_of_quantity)
for e in self.I:
if e.getName() == gain[0]:
e.quantity += gain[1]
self.shoppercash -= choice_of_quantity * float(e.getPrice())
def display(self):
#lists the shopper's name, the amount of money the shopper has,
#the names and quantities of fruit the shopper has,
#and available fruit st the fruit stand.
while True:
print("Shopper's name:",self.shoppername,"\n"
"Money the shopper has($):", self.shoppercash,"\n"
"Fruits owned by the shopper(qty,price):")
for i in self.I:
print("{0} {1}".format(i.getName(), i.getQuantity()))
print(self.F.display())
choice_of_fruit = input("Hi, welcome! Which fruit would you like to have?(Apple/Banana/Pear/Avocado/Durian)")
for i in self.F.fruitstand_inventory:
if choice_of_fruit != i.getName():
continue
else:
choice_of_quantity = int(input("How many would you like?"))
if choice_of_quantity <= 0:
continue
else:
print("Shopper's name:",self.shoppername,"\n"
"Money the shopper has($):", self.shoppercash,"\n"
"Fruits owned by the shopper(qty,price):")
for i in self.I:
print("{0} {1}".format(i.getName(), i.getQuantity()))
print(self.F.display())
answer = input("Would you like to finish?(y/n)")
if answer != "n":
print("Shopper's name:",self.shoppername,"\n"
"Money the shopper has($):", self.shoppercash,"\n"
"Fruits owned by the shopper(qty,price):")
for i in self.I:
print("{0} {1}".format(i.getName(), i.getQuantity()))
print(self.F.display())
print("Thanks for shopping! Bye~")
return False
return False
#Start the program.
a = shopper("Neal",100)
a.display()
|
bd79ed2f912fc5ff8b306ff49429e49e0f734c94 | ccmiller214/python_api_class | /exchange.py | 1,127 | 3.546875 | 4 | #!/usr/bin/python3
import requests
import json
import argparse
key = "LDLCS9364HNRRJEU"
url = 'https://www.alphavantage.co/query?function=CURRENCY_EXCHANGE_RATE&from_currency={}&to_currency={}&apikey={}'
def main():
try:
if args.curto: toCurr = args.curto
else: toCurr = input("Enter currency to change to > ")
if args.curfr: fromCurr = args.curfr
else: fromCurr = input("Enter currency to change from > ")
rate = requests.get(url.format(fromCurr,toCurr,key))
rate_json = rate.json()["Realtime Currency Exchange Rate"]
fromName = rate_json["2. From_Currency Name"]
toName = rate_json["4. To_Currency Name"]
exRate = rate_json["5. Exchange Rate"]
print(f"\n{fromName} equals {float(exRate):.4f} {toName}\n")
except:
print("\nSomething went wrong! Please recheck currency abrreviations.\n")
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument('--curfr', help="Currency to exchange from")
parser.add_argument('--curto',help="Currency to exchange to")
args = parser.parse_args()
main()
|
a3df4192584053b70855386b49501f85ae197c42 | AKP101/Practice-Excercises-Python | /WritingToFiles.py | 255 | 3.640625 | 4 | # writing and appending to a file are different. writing poverwrites and appending adds
text = "Sample Text to save\nA new Line!"
saveFile = open("exampleFile.txt", "w") # open a new file to overwrite to it.
saveFile.write(text)
saveFile.close()
|
662f5f48447b93561747eb935777022b94b7be50 | jborycz/Self-Taught-Programmer | /ch9-challenge/n2.py | 87 | 3.515625 | 4 | x = input("Write to a file: ")
with open("writetofile","w+") as f:
f.write(x)
|
a914d3e764f8d6a4081ca31b27b515a6c7731a8a | ericwu0930/leetcode | /Container With Most Water.py | 352 | 3.609375 | 4 | height=[1,8,6,2,5,4,8,3,7]
left=0
right=len(height)-1
maxarea=(right-left)*min(height[left],height[right])
while left+1<right:
if height[left]<=height[right]:
left+=1
else:right-=1
newarea=(right-left)*height[left] if height[left]<=height[right] else (right-left)*height[right]
if maxarea<newarea:maxarea=newarea
print(maxarea)
|
43fcd133cdb64467d96d3b01b055e848b435f428 | trentmbx/GitHub | /LoginSys.py | 5,122 | 3.890625 | 4 |
# coding: utf-8
# In[2]:
get_ipython().run_line_magic('pylab', 'inline')
from time import *
# In[3]:
usernames = []
passwords = []
emails = []
# In[ ]:
#-Boolean creation-#
usrn_check1 = False
pswrd_check1 = False
usrn_check2 = False
pswrd_check2 = False
fpass = False
taken1 = False
taken2 = False
#-Ask user if they are new-#
new = input("Are you a new user? (y/n) ")
#----------------------------------------------------------------------------------------------------------------#
#-If the user is new-#
if (new == "y"):
#-Account Creation-#
print("\nRegister:")
newuser = input("Enter your username: ")
while (new == "y"): #Password length requirement loop
newpass = input("Enter your password: ")
if (len(newpass) < 8): #"len" function credit to Stack Overflow - checks length of input
print ('\033[93m' + "Password must be at least 8 characters.")
else:
break
newemail = input("Enter your email address: ")
#-Check if username and email are taken-#
for l in usernames:
if l == newuser:
taken1 = True
break
else:
taken1 = False
break
for m in emails:
if m == newemail:
taken2 = True
break
else:
taken2 = False
break
if (taken1 and taken2):
print ('\033[93m' + "Sorry, the username and email you entered is already taken.")
elif (taken1):
print ('\033[93m' + "Sorry, the username you entered is already taken.")
elif (taken2):
print ('\033[93m' + "Sorry, the email you entered is already taken.")
else:
usernames.append(newuser)
passwords.append(newpass)
emails.append(newemail)
sleep(1)
print("\nUser account created.")
#-Login Segment-#
sleep(1)
print("\nLogin:")
user= input("What is your username: ")
pw= input("What is your password: ")
#-Search arrays for username and password-#
for i in usernames:
if i == user:
for j in passwords:
if j == pw:
usrn_check1 = True
pswrd_check1 = True
break
#-Correct Login/Incorrect Login-#
if (pswrd_check1 is True and usrn_check1 is True):
print("Welcome. \n-Coded by Trent Bissette")
else:
print('\033[93m' + "Sorry that login is incorrect.")
pwinc = input('\033[93m' + "Forgot your login info? (y/n) ")
if (pwinc == "y"):
fpass = True
else:
fpass = False
print('\033[93m' + "Please try again. \n-Code by Trent Bissette")
#-If user forgot their login info-#
if (fpass):
nEmail = input("Enter your email address to recover your login info: ")
sleep(1)
for k in emails:
if k == nEmail:
print("An email has been sent to recover your login info. \n-Code by Trent Bissette")
break
else:
print('\033[93m' + "Please enter a valid email address. \n-Code by Trent Bissette")
break
#-----------------------------------------------------------------------------------------------------------------#
#-If user isn't new (Does same thing as above without account creation)-#
elif (new == "n"):
#-Let user login-#
print("\nLogin:")
user= input("What is your username: ")
pw= input("What is your password: ")
#-Search arrays for username and password-#
for i in usernames:
if i == user:
for j in passwords:
if j == pw:
usrn_check2 = True
pswrd_check2 = True
break
#-Correct Login/Incorrect Login-#
if (pswrd_check2 is True and usrn_check2 is True):
print("Welcome. \n-Code by Trent Bissette")
else:
print('\033[93m' + "Sorry that login is incorrect.")
pwinc = input('\033[93m' + "Forgot your login info? (y/n) ")
if (pwinc == "y"):
fpass = True
else:
fpass = False
print('\033[93m' + "Please try again.")
#-If the user forgot their login info-#
if (fpass):
nEmail = input("Enter your email address to recover your login info: ")
sleep(1)
for k in emails:
if k == nEmail:
print("An email has been sent to recover your login info. \n-Code by TERN")
break
else:
print('\033[93m' + "Please enter a valid email address. \n-Code by TERN")
break
#---------------------------------------------------------------------------------------------------------------#
#-Print out all arrays for troubleshooting-#
elif (new == "arrays"):
print(usernames)
print(passwords)
print(emails)
#-If user does not say they are new or not-#
else:
print ('\033[93m' + "Please enter y/n.")
#--#
|
a23201b014fa9f2dc743feac342aa94d09eee6b0 | MarcelArthur/leetcode_collection | /628_Maximum_Product_of_Three_Numbers.py | 1,244 | 4.09375 | 4 | # python3
'''
description: 维护一个最大堆和最小堆,遍历一遍数组,持续更新最大堆和最小堆的值,从而得到一个2个元素的最小堆和3个元素的最大堆.
时间复杂度O(n), 空间复杂度O(1)
Given an integer array, find three numbers whose product is maximum and output the maximum product.
Example 1:
Input: [1,2,3]
Output: 6
Example 2:
Input: [1,2,3,4]
Output: 24
Note:
The length of the given array will be in range [3,104] and all elements are in the range [-1000, 1000].
Multiplication of any three numbers in the input won't exceed the range of 32-bit signed integer.
'''
import sys
class Soluction:
def maximumProduct(self, nums):
min1, min2 = sys.maxsize, sys.maxsize
max1, max2, max3 = -sys.maxsize, -sys.maxsize, -sys.maxsize
for i in nums:
if i < min1:
min2 = min1
min1 = i
elif i < min2:
min1 = i
if i > max1:
max3 = max2
max2 = max1
max1 = i
elif i > max2:
max3 = max2
max2 = i
elif i > max3:
max3 = i
return max(min1*min2* max1, max1*max2*max3) |
80bc592b47ed3db15ed164b1e17508c099978dcf | codingple/PyNavi | /trajectory_clustering/z_clusering.py | 3,150 | 3.71875 | 4 | from itertools import combinations
from driver import index, lat, lon, clustering_criterion, time
import distance_calculator
"""
In clustering, every distance among GPS points are supposed to be calculated,
and GPS clusters based on close interval are produced between two trajectories of each pair,
which are comprised of route number and GPS index.
( route_number1, route_number2, list[ tuple( set(GPS indexes of route1), set(GPS indexes of route2) ) ] ),
in which the tuple means GPS cluster and the list means list of the clusters between route1 and route2.
"""
def clustering(mapinfo):
# Combination
comb = combinations(mapinfo, 2)
correlation_list = []
# Each pair (route1, route2)
for pair in comb:
route1 = pair[0]
route2 = pair[1]
route1_num = route1[index]
route2_num = route2[index]
del route1[index]
del route2[index]
index_cluster = ()
cluster_list = []
# Each GPS point
for point1 in route1:
index1 = point1[index]
lat1 = point1[lat]
lon1 = point1[lon]
points = set()
for point2 in route2:
lat2 = point2[lat]
lon2 = point2[lon]
# Making a correlated set of point2_number with point1 : set(indexes of point2)
if distance_calculator.haversine(lat1, lon1, lat2, lon2) < clustering_criterion:
points.add(point2[index])
# If the correlation has been made : tuple( index of point1, set(indexes of point2) )
if points:
current_cluster = ({index1}, points)
# Check index_cluster
if index_cluster:
# If current_cluster needs to be integrated
# : tuple( set(indexes of point1), set(indexes of point2) )
if index_cluster[1] & current_cluster[1]:
index_cluster = (index_cluster[0] | current_cluster[0], index_cluster[1] | current_cluster[1])
# Or new cluster created
else:
cluster_list.append(index_cluster)
index_cluster = current_cluster
else:
index_cluster = current_cluster
# Last cluster added
if index_cluster:
cluster_list.append(index_cluster)
# Filtering bad clusters
if cluster_list:
cluster_list = filter(sequential_check, cluster_list)
# Correlation completed
if cluster_list:
correlation_list.append( (route1_num, route2_num, cluster_list) )
for test in cluster_list:
one = list(test[0])
two = list(test[1])
one.sort()
two.sort()
for x in one:
print route1[x][time]
print ".........."
for y in two:
print route2[y][time]
print '\n'
break
def sequential_check(tupl):
c_list = list(tupl[1])
c_list.sort()
return c_list[-1] - c_list[0] + 1 == len(c_list) |
fc44764db5edf03211e637d0fd02a9eaf2bc80e7 | martincastro1575/python | /3.- Introducing Lists/try_your_self/3-6 more_guests.py | 832 | 3.8125 | 4 | guests = ['margaret', 'simon', 'juana']
print('\t\nGuest list to dinner:',f"\n\tGuest number one: {guests[0].title()}",
f"\n\tGuest number two: {guests[1].title()}",
f"\n\tGuest number three: {guests[2].title()}")
print("I've got had news for you, my dears!!!",
"I've found a big table for dinner. So",
"I've invated three special people more.")
guests.insert(0, 'maria')
guests.insert(2,'pedro')
guests.append('patricia')
print('\nUpdate Guest list to dinner:',f"\n\tGuest number one: {guests[0].title()}",
f"\n\tGuest number two: {guests[1].title()}",
f"\n\tGuest number three: {guests[2].title()}",
f"\n\tGuest number four: {guests[3].title()}",
f"\n\tGuest number five: {guests[4].title()}",
f"\n\tGuest number six: {guests[5].title()}")
|
ab26ce1f3a122d1c30b032d52d5548ab41200a2a | AJsenpai/codewars | /order.py | 1,174 | 3.921875 | 4 | """
Your task is to sort a given string. Each word in the string will contain a single number. This number is the position the word should
have in the result.
Note: Numbers can be from 1 to 9. So 1 will be the first word (not 0).
If the input string is empty, return an empty string. The words in the input String will only contain valid consecutive numbers.
Examples
"is2 Thi1s T4est 3a" --> "Thi1s is2 3a T4est"
"4of Fo1r pe6ople g3ood th5e the2" --> "Fo1r the2 g3ood 4of th5e pe6ople"
"" --> ""
"""
# my solution
def order(sentence):
return " ".join(sorted(sentence.split(), key=lambda w: sorted(w)))
print(order("is2 Thi1s T4est 3a"))
# codewar solution 1
# def extract_number(word):
# for l in word:
# if l.isdigit():
# return int(l)
# return None
# def order(sentence):
# return " ".join(sorted(sentence.split(), key=extract_number))
# codewar solution 2
# def order(sentence):
# for i in range(1, 10):
# for item in sentence.split():
# if str(i) in item:
# result.append(item)
# # adds them in numerical order since it cycles through i first
# return " ".join(result)
|
bbe7fb7d8f5bc7b1bc1bde3db889008c30e07a01 | CaseyMcGuire/leetcode_old | /InvertBinaryTree/python/solution.py | 487 | 3.546875 | 4 | from collections import deque
from TreeNode import *
class Solution:
# @param {TreeNode} root
# @return {TreeNode}
def invertTree(self,root):
if root is None:
return
self._invert_tree(root)
return root
def _invert_tree(self, node):
if node is None:
return
temp = node.right
node.right = node.left
node.left = temp
self._invert_tree(node.right)
self._invert_tree(node.left)
|
5e352b95e7eca27b124c6dbd2abb08ec5f3bd837 | suacalis/VeriBilimiPython | /Ornek13_7.py | 632 | 3.765625 | 4 | '''
Örnek 13.7: Soyut sınıf ve metot kavramını bir önceki örnek uygulama
üzerinden açıklayalım.
'''
from abc import *
class Pizza(ABC): #üst soyut sınıf
icerik = ['Peynir', 'Zeytin']
@classmethod #sınıf metodu
@abstractmethod #soyut metot
def getMalzeme(cls):
return cls.icerik
#DiyetPizza sınıfı Pizza sınıfının metotlarına sahip olmalıdır
class DiyetPizza(Pizza): #alt sınıf
@classmethod #sınıf metodu
def getMalzeme(cls):
return ['Mantar'] + cls.icerik
#Ana program da
#Örnek oluşturmadan sınıf metoduna erişebiliriz
print(DiyetPizza.getMalzeme()) |
32cf275e8646e74570ebaf3b1168ec1f54007f44 | albiurs/edu_codecademy_learn_python_3 | /src/01_syntax/08_calculations.py | 1,065 | 3.875 | 4 | """
08_calculations
@author created by Urs Albisser, on 2020-10-10
@version 0.1
"""
# Calculations
#
# Computers absolutely excel at performing calculations. The “compute” in their name comes from their historical association with providing answers to mathematical questions. Python performs addition, subtraction, multiplication, and division with +, -, *, and /.
# Prints "500"
print(573 - 74 + 1)
# Prints "50"
print(25 * 2)
# Prints "2.0"
print(10 / 5)
# Notice that when we perform division, the result has a decimal place. This is because Python converts all ints to floats before performing division. In older versions of Python (2.7 and earlier) this conversion did not happen, and integer division would always round down to the nearest integer.
#
# Division can throw its own special error:
# ZeroDivisionError
# . Python will raise this error when attempting to divide by 0.
#
# Mathematical operations in Python follow the standard mathematical order of operations:
# https://en.wikipedia.org/wiki/Order_of_operations
print(25 * 68 + 13 / 28)
|
b213e7068eb35cfcfff83e91a0a6497f66848cdb | keithxm23/CTCI | /Ch1_Arrays_and_Strings/q1_3.py | 942 | 4.28125 | 4 | #Check if one string is permutation of the other
import sys
if len(sys.argv) != 3:
raise Exception("Please provide input string. Run 'python q1_3.py <string-here> <string-here>'")
else:
str1 = sys.argv[1]
str2 = sys.argv[2]
"""
#method1 by sorting both
if sorted(str1) == sorted(str2):
print "Strings are anagrams of each other"
else:
print "strings are not anagrams of each other"
"""
#method2: by counting occurences of each char in both
count = {}
str1 = list(str1)
str2 = list(str2)
if len(str1) != len(str2):
print "Strings are not anagrams of each other"
sys.exit()
else:
for i in xrange(0,len(str1)):
if str1[i] in count:
count[str1[i]] +=1
else:
count[str1[i]] = 1
if str2[i] in count:
count[str2[i]] -= 1
else:
count[str2[i]] = -1
for key, value in count.items():
if value != 0:
print "Strings are not anagrams of each other"
sys.exit()
print "Strings are anagrams of each other"
|
5c7f875bbe4f07cb1978255d1131ee8676a24eb4 | xHammercillox/Kata1 | /Kata1/1#if2.py | 801 | 4 | 4 | """
Escribir un programa para una empresa que tiene salas de juegos para todas las
edades y quiere calcular de forma automática el precio que debe cobrar a sus
clientes por entrar. El programa debe preguntar al usuario la edad del cliente
y mostrar el precio de la entrada. Si el lciente es menor de 4 años puede
entrar gratis, si tiene entre 4 y 18 años debe pagar 5€ y si es mayor de 18
años, 10€.
"""
edad = input("Introduce tu edad: ")
edad = int(edad)
if edad < 4:
print("El precio de la entrada es 0€.")
elif edad >= 4 and edad <= 18:
print("El precio de la entrada es 5€.")
else:
print("El precio de la entrada es 10€.")
"""
Esto es lo mismo que el elif anterior:
elif 4 <= edad <= 18:
print("El precio de la entrada es 5€.")
""" |
733d6127e88ebf391f58f4a3685b9ce735c2cd15 | pavanq/Practice | /q23.py | 556 | 3.953125 | 4 | #n=input("No. of values:")
#lst=[]
#for i in range(0,n):
#print i
#lst[i]=input("Enter value:")
#print lst
lst=[1,2,3,4,5,6,7,8,9,10]
value=input("Enter value to be searched:")
def binary(data,key,start,end):
mid=(start+end)/2
if data[mid]==key:
return mid
if data[mid]>key:
return binary(data,key,start,mid)
else:
return binary(data,key,mid+1,end)
if (lst[len(lst)-1]<value or lst[0]>value):
print ("Value not found")
else :
index=binary(lst,value,0,len(lst)-1)
print index
|
dd91e8cb0fd32b0b5e45195a084e1c806f2a38e8 | sainihimanshu1999/Dynamic-Programming | /MinimumSubarrayMinProduct.py | 549 | 3.6875 | 4 | '''
In this question we use monotonic stack, monotonic stack is a useful data structure which helps in knowing
the boundary of things, used in many questions like maximum area in histogram etc
'''
def minProd(self,nums):
stack = [(-1,0)]
running_sum = 0
max_sum = 0
nums.append(0)
for v in nums:
while stack[-1][0] >= v:
min_val,i = stack.pop()
max_sum = max(max_sum, min_val*(running_sum-stack[-1][1]))
running_sum += v
stack.append((v,running_sum))
return max_sum |
a61df0bcce436d1eb14369d4a9a4e24f94374cfe | paulyun/python | /Schoolwork/Python/In Class Projects/3.10.2016/Notes.py | 230 | 4.09375 | 4 | print (format(y,'.2f')) # this code tells you to print only 2 decimal points.
#the .2f means 2 decimal points. if it was .5f it would be 5 decimal points.
2**5 = 2 to the power of 5 or print ("using function pow() ..",pow(3, 5)) |
67343cc61852c0c78df55e439f2adda09e17745a | MarcoGorelli/rsmtool | /rsmtool/container.py | 10,080 | 3.921875 | 4 | """
Classes for storing any kind of data contained
in a pd.DataFrame object.
:author: Jeremy Biggs ([email protected])
:author: Anastassia Loukina ([email protected])
:author: Nitin Madnani ([email protected])
:organization: ETS
"""
import warnings
from copy import copy, deepcopy
class DataContainer:
"""
A class to encapsulate datasets.
"""
def __init__(self,
datasets=None):
"""
Initialize ``DataContainer`` object.
Parameters
----------
datasets : list of dicts, optional
A list of dataset dicts. Each dict should have the following keys:
``name`` containing the name of the dataset, ``frame`` containing
the dataframe object that contains the dataset, and ``path`` containing
the file from which the dataset was read.
"""
self._names = []
self._dataframes = {}
self._data_paths = {}
if datasets is not None:
for dataset_dict in datasets:
self.add_dataset(dataset_dict,
update=False)
def __contains__(self, key):
"""
Check if DataContainer object
contains a given key.
Parameters
----------
key : str
A key to check in the DataContainer object
Returns
-------
key_check : bool
True if key in DataContainer object, else False
"""
return key in self._names
def __getitem__(self, key):
"""
Get frame, given key.
Parameters
----------
key : str
Name for the data.
Returns
-------
frame : pd.DataFrame
The DataFrame.
Raises
------
KeyError
If the key does not exist.
"""
return self.get_frame(key)
def __len__(self):
"""
Return the length of the
DataContainer names.
Returns
-------
length : int
The length of the container (i.e. number of frames)
"""
return len(self._names)
def __str__(self):
"""
String representation of the object.
Returns
-------
container_names : str
A comma-separated list of names from the container.
"""
return ', '.join(self._names)
def __add__(self, other):
"""
Add two DataContainer objects together and return a new
DataContainer object with DataFrames common to both
DataContainers
Raises
------
ValueError
If the object being added is not a DataContainer
KeyError
If there are duplicate keys in the two DataContainers.
"""
if not isinstance(other, DataContainer):
raise ValueError('Object must be `DataContainer`, '
'not {}.'.format(type(other)))
# Make sure there are no duplicate keys
common_keys = set(other._names).intersection(self._names)
if common_keys:
raise KeyError('The key(s) `{}` already exist in the '
'DataContainer.'.format(', '.join(common_keys)))
dicts = DataContainer.to_datasets(self)
dicts.extend(DataContainer.to_datasets(other))
return DataContainer(dicts)
def __iter__(self):
"""
Iterate through configuration object keys.
Yields
------
key
A key in the container dictionary
"""
for key in self.keys():
yield key
@staticmethod
def to_datasets(data_container):
"""
Convert a DataContainer object to a list of dataset dictionaries
with keys {`name`, `path`, `frame`}.
Parameters
----------
data_container : DataContainer
A DataContainer object.
Returns
-------
datasets_dict : list of dicts
A list of dataset dictionaries.
"""
dataset_dicts = []
for name in data_container.keys():
dataset_dict = {'name': name,
'path': data_container.get_path(name),
'frame': data_container.get_frame(name)}
dataset_dicts.append(dataset_dict)
return dataset_dicts
def add_dataset(self, dataset_dict, update=False):
"""
Update or add a new DataFrame to the instance.
Parameters
----------
dataset_dict : pd.DataFrame
The dataset dictionary to add.
update : bool, optional
Update an existing DataFrame, if True.
Defaults to False.
"""
name = dataset_dict['name']
data_frame = dataset_dict['frame']
path = dataset_dict.get('path')
if not update:
if name in self._names:
raise KeyError('The name {} already exists in the '
'DataContainer dictionary.'.format(name))
if name not in self._names:
self._names.append(name)
self._dataframes[name] = data_frame
self._data_paths[name] = path
self.__setattr__(name, data_frame)
def get_path(self, key, default=None):
"""
Get path, given key.
Parameters
----------
key : str
Name for the data.
Returns
-------
path : str
Path to the data.
"""
if key not in self._names:
return default
return self._data_paths[key]
def get_frame(self, key, default=None):
"""
Get frame, given key.
Parameters
----------
key : str
Name for the data.
default
The default argument, if the frame does not exist
Returns
-------
frame : pd.DataFrame
The DataFrame.
"""
if key not in self._names:
return default
return self._dataframes[key]
def get_frames(self, prefix=None, suffix=None):
"""
Get all data frames in the container that have
a specified prefix and/or suffix. Note that
the selection by prefix or suffix will be
case-insensitive.
Parameters
----------
prefix : str or None, optional
Only return frames with the given prefix.
If None, then do not exclude any frames based
on their prefix.
Defaults to None.
suffix : str or None, optional
Only return frames with the given suffix.
If None, then do not exclude any frames based
on their suffix.
Defaults to None.
Returns
-------
frames : dict
A dictionary with all of the data frames
that contain the specified prefix and suffix.
The keys are the names of the data frames.
"""
if prefix is None:
prefix = ''
if suffix is None:
suffix = ''
names = [name for name in self._names if
name.lower().startswith(prefix) and
name.lower().endswith(suffix)]
frames = {}
for name in names:
frames[name] = self._dataframes[name]
return frames
def keys(self):
"""
Return keys as a list.
Returns
-------
keys : list
A list of keys in the Configuration object.
"""
return self._names
def values(self):
"""
Return values as a list.
Returns
-------
values : list
A list of values in the Configuration object.
"""
return [self._dataframes[name] for name in self._names]
def items(self):
"""
Return items as a list of tuples.
Returns
-------
items : list of tuples
A list of (key, value) tuples in the Configuration object.
"""
return [(name, self._dataframe[name]) for name in self._names]
def drop(self, name):
"""
Drop a given data frame from the
container.
Parameters
----------
name : str
The name of the data frame to drop from the
container object.
Returns
-------
self
"""
if name not in self:
warnings.warn('The name `{}` is not in the '
'container. No data frames will '
'be dropped.'.format(name))
else:
self._names.remove(name)
self._dataframes.pop(name)
self._data_paths.pop(name)
return self
def rename(self, name, new_name):
"""
Rename a given data frame in the
container.
Parameters
----------
name : str
The name of the current data frame
in the container object.
new_name : str
The the new name for the data frame
in the container object.
Returns
-------
self
"""
if name not in self:
warnings.warn('The name `{}` is not in the '
'container and cannot '
'be renamed.'.format(name))
else:
frame = self._dataframes[name]
path = self._data_paths[name]
self.add_dataset({'name': new_name,
'frame': frame,
'path': path},
update=True)
self.drop(name)
return self
def copy(self, deep=True):
"""
Create a copy of the DataContainer object.
Parameters
----------
deep : bool, optional
If True, create a deep copy of the
underlying data frames.
Defaults to True.
"""
if deep:
return deepcopy(self)
return copy(self)
|
d1aa5868314e78d4acc951a7ac2996eb4c69d105 | isi-frischmann/python | /multiples.py | 534 | 4.40625 | 4 | # Part I - Write code that prints all the odd numbers from 1 to 1000. Use the for loop and don't use a list to do this exercise.
for i in range (1, 1000):
if i % 2 == 0:
print i
# Part II - Create another program that prints all the multiples of 5 from 5 to 1,000,000.
for i in range (5, 1000000):
if i % 5 == 0:
print i
#creat a programm which prints the sum of the list
a = [1, 2, 5, 10, 255, 3]
print sum(i for i in a)
#print average list
b = [1, 2, 5, 10, 255, 3]
avg = sum(b)/len(b)
print avg |
d15ce695b88491568046dce38def69a8c535cf4b | iamsamitdev/BasicAdvancePythonPRD | /pythongui/gui07.py | 4,690 | 3.703125 | 4 | from tkinter import *
from tkinter import ttk
mainfrm = Tk()
mainfrm.title("โปรแกรมเครื่องคิดเลข") # แสดงข้อความที่ title bar
# สร้างฟังก์ชัน calculate() กำหนดรูปแบบการคำนวณ
def calculate():
result = 0 # ก่อนการคำนวณควรเซ็ตค่าผลลัพธ์เป็น 0 ทุกครั้ง
entResult.delete(0, END) # เคลียร์ช่องผลลัพธ์ให้เป็นค่าว่างก่อนทุกครั้ง
num1 = entNum1.get()
num2 = entNum2.get()
# ตรวจสอบเงื่อนไขแล้วว่าค่าสตริง v ของ Radio button เป็น 1 2 3 หรือ 4 (บรรทัด 78)
# ให้เข้าเงื่อนไข บวก ลบ คูณ หรือหาร นั้นๆ แล้วคำนวณค่าเก็บใน result พร้อมแสดงผล
if str(v.get()) == "1":
result = int(num1) + int(num2)
entResult.insert("", str(result))
elif str(v.get()) == "2":
result = int(num1) - int(num2)
entResult.insert("", str(result))
elif str(v.get()) == "3":
result = int(num1) * int(num2)
entResult.insert("", str(result))
elif str(v.get()) == "4":
result = int(num1) / int(num2)
entResult.insert("", str(result))
# สร้างฟังก์ชัน clearEntry() สำหรับลบข้อมูลแต่ละ Entry widget
def clearEntry():
entNum1.delete(0, END)
entNum2.delete(0, END)
entResult.delete(0, END)
# สร้าง LabelFrame เอาไว้ใช้สำหรับจัดกลุ่ม Label และ Entry widget
lblFrm1 = ttk.LabelFrame(mainfrm, text="โปรแกรมคำนวณ", labelanchor="n")
lblFrm1.pack(padx=10, pady=10, side="left")
# สร้าง Label widget กำหนดให้แสดงข้อความ
lblNum1 = ttk.Label(lblFrm1,
text="ป้อนตัวเลขที่ 1 :").grid(column=0, row=0,
padx=5, sticky="e")
lblNum2 = ttk.Label(lblFrm1,
text="ป้อนตัวเลขที่ 2 :").grid(column=0, row=1,
padx=5, sticky="e")
lblResult = ttk.Label(lblFrm1,
text="ผลลัพธ์ :").grid(column=0, row=2,
padx=5, sticky="e")
# สร้าง Entry widget ขึ้นมา 3 ตัว สำหรับป้อนข้อมูล
entNum1 = ttk.Entry(lblFrm1)
entNum2 = ttk.Entry(lblFrm1)
entResult = ttk.Entry(lblFrm1)
# จัดวาง Entry widget ด้วยเมธอด grid()
entNum1.grid(column=1, row=0, padx=5)
entNum2.grid(column=1, row=1, padx=5)
entResult.grid(column=1, row=2, padx=5)
# สร้างปุ่มกด Button widget เรียกใช้งานฟังก์ชัน calculate() และฟังก์ชัน clearEntry()
btnEnter = ttk.Button(lblFrm1, text="Enter",
command=calculate).grid(column=0, row=3,
padx=5, pady=5)
btnClear = ttk.Button(lblFrm1, text="Clear",
command=clearEntry).grid(column=1, row=3,
padx=5, )
# สร้าง LabelFrame widget สำหรับจัดกลุ่ม Radio button widget
lblFrm2 = ttk.LabelFrame(mainfrm, text="เลือกการคำนวณ", labelanchor="n")
lblFrm2.pack(padx=10, pady=10)
# สร้าง Radio button widget 4 ตัว ใช้ตรวจสอบการเลือกการ + - * /
# กำหนดค่าเริ่มต้นของ Radio button ที่ 1 (การบวก)
v = StringVar(lblFrm2, "1")
# สร้างดิกชันนารี key และ value เป็นชนิดข้อมูลสตริงเก็บค่าเครื่องหมาย
operations = {"การบวก": "1",
"การลบ": "2",
"การคูณ": "3",
"การหาร": "4"
}
# สร้าง Radio button โดยใช้การวน loop กำหนดค่าต่าง ๆ
for (text, operations) in operations.items():
Radiobutton(lblFrm2, text=text, variable=v,
value=operations).pack(side=TOP, ipady=4)
mainfrm.mainloop() |
1486e84c7e1dab4d52043a775a7d0d82c9cb20e6 | speed785/Python-Projects | /main.py | 1,502 | 4.0625 | 4 | import Employee
p1 = Employee.Employee()
p2 = Employee.Employee()
p3 = Employee.Employee()
p1_Name = str(input("Please enter the Name for First employee: "))
p1_id = int(input("Please enter the Id Number for First Employee: "))
p1_Department = str(input("Please enter the Departmet of First Employee: "))
p1_Position = str(input("Please enter the Position for First employee: "))
p2_Name = str(input("Please enter the Name for Second employee: "))
p2_id = int(input("Please enter the Id Number for Second Employee: "))
p2_Department = str(input("Please enter the Departmet of Second Employee: "))
p2_Position = str(input("Please enter the Position for Second employee: "))
p3_Name = str(input("Please enter the Name for third employee: "))
p3_id = int(input("Please enter the Id Number for third Employee: "))
p3_Department = str(input("Please enter the Departmet of third Employee: "))
p3_Position = str(input("Please enter the Position for third employee: "))
def main():
print("{0:15} {1:15} {2:15} {3:15}".format("Name","ID Number","Accounting","Position"))
print(p1.set_Employee_info("{0:15} {1:15} {2:15} {3:15}".format(p1_Name,p1_id,p1_Department,p1_Position)))
print(p2.set_Employee_info("{0:15} {1:15} {2:15} {3:15}".format(p2_Name,p2_id,p2_Department,p2_Position)))
print(p3.set_Employee_info("{0:15} {1:15} {2:15} {3:15}".format(p3_Name,p3_id,p3_Department,p3_Position)))
p1.get_Employee_info()
p2.get_Employee_info()
p3.get_Employee_info()
main()
|
7d79ce9fe82653773c0a169c1e5bd436052b583e | rozeachus/Python.py | /takingAVacation.py | 1,130 | 4.4375 | 4 | """
This code is taken from the Python excercise 'Taking a Vacation' on CodeAcademy.
It will calculate how much a trip will cost, taking into account the hotel, car hire, flights and spending money.
"""
# First we define the cost of the hotel, which is $140 per night
def hotel_cost(nights):
return 140 * nights
# Then we define the plane ride cost, which is dependent on the city you travel to
def plane_ride_cost(city):
if city == "Charlotte":
return 183
elif city == "Tampa":
return 220
elif city == "Pittsburgh":
return 222
elif city == "Los Angeles":
return 475
# Then we define the rental car cost. Note - the price changes dependent on hiring days
def rental_car_cost(days):
cost = days * 40
if days >= 7:
cost -= 50
elif days >= 3:
cost -= 20
return cost
# We sum the three functions together
def trip_cost(city, days, spending_money):
return rental_car_cost(days) + hotel_cost(days - 1) + plane_ride_cost(city) + spending_money
# Lastly, we print where we're staying, how many days for and how much spending money we have
print trip_cost("Los Angeles", 5, 600)
|
0aff84adce41e42e273eed7c239eed58209312b6 | EmilyOng/cp2019 | /y5_practical3/q2_display_pattern.py | 421 | 4.0625 | 4 | #2 (Displaying patterns) q2_display_pattern.py
#Write a function display_pattern(n) to display a pattern as follows:
# 1
# 2 1
# 3 2 1
#...
#n n-1 ... 3 2 1
def display_pattern(n):
for i in range(n):
for j in range(0,n-i-1):
print(" ",end="")
for k in range(n-i-1,n):
print("*",end="")
print()
display_pattern(5)
|
17cbff8b56d99a94ba6d808d2372bc0071a501e8 | TalhaYa/My_Python_Project | /MehmetAbiAperatif.py | 1,996 | 3.75 | 4 | tum_siparis = {"Siparisleriniz": [], "Hesabınız": []}
aperatif = {"Kasarlı Tost": 6, "Kıymalı Tost": 8,
"Sucuklu Yumurta": 10,"Karışık Tost": 10,
"Sucuklu Tost": 7,"Soguk Sandvic":7}
print("*****Aperatif ÇEŞİTLERİMİZ*****")
print(aperatif)
def siparis(yemek):
siparis_listesi = []
adet = int(input("Kaç porsiyon sipariş edeceksiniz?"))
def hesap(adisyon):
adi_list = []
if yemek == 'Kasarlı Tost':
adisyon += 6 * adet
adi_list.append(adisyon)
tum_siparis["Hesabınız"].append(adisyon)
elif yemek == 'Kıymalı Tost':
adisyon += 8 * adet
adi_list.append(adisyon)
tum_siparis["Hesabınız"].append(adisyon)
elif yemek == 'Sucuklu Yumurta':
adisyon += 10 * adet
adi_list.append(adisyon)
tum_siparis["Hesabınız"].append(adisyon)
elif yemek == 'Karışık Tost':
adisyon += 10 * adet
adi_list.append(adisyon)
tum_siparis["Hesabınız"].append(adisyon)
elif yemek == 'Sucuklu Tost':
adisyon += 7 * adet
adi_list.append(adisyon)
tum_siparis["Hesabınız"].append(adisyon)
elif yemek == 'Soguk Sandvic':
adisyon += 7 * adet
adi_list.append(adisyon)
tum_siparis["Hesabınız"].append(adisyon)
return adi_list
for i in range(0, adet):
siparis_listesi.append(yemek)
print(hesap(adisyon=0))
return siparis_listesi
while True:
yemek = input("İstediğiniz Aperatif Çeşiti nedir?")
print(siparis(yemek))
tum_siparis["Siparisleriniz"].append(yemek)
print(tum_siparis)
exit=int(input("Sipariş sizin için yeterli mi?(Evet=1 Hayır =2)"))
if exit == 1:
print("Bizi Tercih Ettiğiniz İçin Teşekkür Ederiz.")
break
elif exit ==2 :
continue
|
43423637f8bb846103623332dc6b3d8a6d1e9aec | tulioac/ExerciciosTST | /unidade05/abaixo_da_media/p.py | 304 | 3.671875 | 4 | lista = []
media = 0
valor = ''
while(valor != 'fim'):
valor = raw_input()
if valor != 'fim':
lista.append(float(valor))
media += float(valor)
media /= len(lista)
print "%.2f" % media
for i in range(len(lista)):
if lista[i] < media:
print "%d %d" % (i+1, lista[i]) |
db3bbc96c2dc844c9ccd0df553e7cf7d881e4eb1 | QiliWu/leetcode-and-Project-Euler | /leetcode/10-Regular Expression Matching.py | 830 | 3.546875 | 4 | class Solution(object):
def isMatch(self, s, p):
"""
:type s: str
:type p: str
:rtype: bool
"""
if not p: # p = ''
return not s # True if s = '', and False if not
#bool(s): return False if s = ''
# p[0] should = t[0] or '.', otherwise False
first_match = bool(s) and p[0] in [s[0],'.']
#if p[1] = '*'.
#CASE ONE: '*' means repeat zero times, so p[:2] = ''. Check isMatch(t, p[2:])
#CASE TWO: '*' means one or more times. first check first_match, second: check t[1:] vs p
if len(p)>=2 and p[1] == '*':
return self.isMatch(s, p[2:]) or first_match and self.isMatch(s[1:], p)
# Finally, check first_match and t[1:] vs p[1:]
return first_match and self.isMatch(s[1:], p[1:])
|
68cceac8266799ce3bb1eaac29aed22a9b374c36 | albusdunble1/Leetcode | /leet_code/easy/leet_robot.py | 1,052 | 3.671875 | 4 | class Solution(object):
def judgeCircle(self, moves):
"""
:type moves: str
:rtype: bool
"""
# vertical = 0
# horizontal = 0
# for move in moves:
# if move == 'U':
# vertical += 1
# elif move == 'D':
# vertical -= 1
# elif move == 'L':
# horizontal -= 1
# elif move == 'R':
# horizontal += 1
# if not(vertical or horizontal):
# return True
# return False
flag = False
if 'U' in moves or 'D' in moves:
if moves.count('U') == moves.count('D'):
flag = True
else:
return False
if 'L' in moves or 'R' in moves:
if moves.count('L') == moves.count('R'):
flag = True
else:
return False
return flag
#https://leetcode.com/problems/robot-return-to-origin/ |
d3eea85ab79961773f24f52b3b35dd8f5dd5d83b | srikanthpragada/PYTHON_07_SEP_2018_DEMO | /oop/mi.py | 420 | 3.765625 | 4 | class A:
def print(self):
print("print() of A")
def add(self):
print("add() of A")
class B(A):
def print(self):
print("print() of B")
def sub(self):
print("sub() of B")
class C(B,A):
def print(self):
print("print() of C")
def fun(v):
pass
fun(10)
fun("Abc")
obj = C()
print( issubclass(C,B))
print( issubclass(A,B))
print( isinstance(obj,A))
|
37aedc746a3ac3bd0edfd58591442275c4837628 | monkop/Data-Structure-in-Python | /Stack/stackArray.py | 722 | 3.75 | 4 | class StackArray:
def __init__(self):
self._data = []
def __len__(self):
return len(self._data)
def isempty(self):
return len(self._data) == 0
def push(self,e):
self._data.append(e)
def pop(self) :
if self.isempty():
print('stack is empty')
return
return self._data.pop()
def top(self):
if self.isempty():
print('Stack is empty')
return
return self._data[-1]
s = StackArray()
s.push(5)
s.push(3)
print(s._data)
print('Length : ',len(s ))
print(s.pop())
print(s.isempty)
print(s.pop())
print(s.isempty())
s.push(7)
s.push(9)
s.push(4)
print(s._data)
print(s.top())
print(s._data) |
a535d1ce0fac7c3030509efbc6f15e814f453bfe | ceneri/CSBasics | /Queue.py | 2,913 | 4.0625 | 4 | #!/usr/bin/env python3
"""
File: Queue.py
Author: Cesar Neri <[email protected]>
Date: 05/07/2019
Custom implementation of Queue using my custom LinkedList.
Queue makes use only of LinkedList methods that would guarante
an O(1) runtime for all of the Queue basic methods.
"""
from LinkedList import LinkedList
class Queue(object):
def __init__(self):
self.__Llist = LinkedList()
def __len__(self):
return self.__Llist.__len__()
def __str__(self):
"""
Returns a STRING that contains every element in the Queue.
Top of the Queue indicated by "->" character.
"""
return "-> " + self.__Llist.__str__()
def isEmpty(self):
"""
True if current Queue is empty, False otherwise.
"""
return self.__Llist.isEmpty()
def add(self, data):
"""
Inserts a new element DATA at the end of the Queue.
Runtime: O(1)
"""
self.__Llist.addLast(data)
def peek(self):
"""
Returns the element at the top of the Queue withouth
removing it.
Runtime: O(1)
"""
dataPeeked = None
try:
dataPeeked = self.__Llist.getFirst()
except IndexError: #as e:
print("Cannot peek on an empty Queue")
return dataPeeked
def poll(self):
"""
Removes and returns the element at the top of the Queue.
Runtime: O(1)
"""
dataPopped = None
try:
dataPopped = self.__Llist.removeFirst()
except IndexError: #as e:
print("Cannot pop from an empty Queue")
return dataPopped
def main():
#Dummy main that test basic functionality
q1 = Queue()
print("Queue created")
print("Size of queue:", len(q1), "\n")
print("Add 3")
q1.add(3)
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
print("Add 2")
q1.add(2)
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
print("Add 1")
q1.add(1)
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
print("Peek:", q1.peek())
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
print("Poll:", q1.poll())
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
print("Poll:", q1.poll())
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
print("Poll:", q1.poll())
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
#Test empty list exceptions handling
print("Peek:", q1.peek())
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
print("Poll:", q1.poll())
print("Queue:", q1)
print("Size of queue:", len(q1), "\n")
if __name__ == "__main__":
main()
|
b67122683f2509b193b3d5d6dea09687c06e04b3 | hanjingfeng1971/appelpy | /appelpy/eda.py | 2,886 | 3.96875 | 4 | """Methods for general exploratory data analysis.
These are for analysis on datasets, rather than analysis on models.
"""
import pandas as pd
import numpy as np
import scipy as sp
import matplotlib.pyplot as plt
import seaborn as sns
def statistical_moments(df, *, kurtosis_fisher=True):
"""Produce a dataframe with the four main statistical moments calculated
for each continuous variable specified in a given dataframe.
The dataframe has the moments stored in columns and each continuous
variable stored in the index.
The columns for each probability distribution:
- 'mean': the first moment
- 'var': the second central moment
- 'skew': the third standardized moment
- 'kurtosis': Defaults to 'fisher'. The fourth standardized moment.
Fisher's kurtosis (kurtosis excess) is used by default, otherwise
Pearson's kurtosis is used.
Args:
df (pd.DataFrame): dataframe with numerical columns
Returns:
pd.DataFrame: shape (# numerical regressors, 4)
"""
df_numeric = df.select_dtypes(include=np.number)
df_stats = pd.DataFrame(columns=['mean', 'var', 'skew', 'kurtosis'],
index=df_numeric.columns)
for col in df_numeric.columns:
df_stats.loc[col, 'mean'] = np.mean(df_numeric[col].dropna())
df_stats.loc[col, 'var'] = np.var(df_numeric[col].dropna(), ddof=1)
df_stats.loc[col, 'skew'] = sp.stats.skew(df_numeric[col].dropna())
if kurtosis_fisher:
df_stats.loc[col, 'kurtosis'] = sp.stats.kurtosis(
df_numeric[col].dropna(), fisher=True)
else:
df_stats.loc[col, 'kurtosis'] = sp.stats.kurtosis(
df_numeric[col].dropna(), fisher=False)
return df_stats
def correlation_heatmap(df, *, font_size=12, ax=None):
"""Produce annotated heatmap for lower triangle of correlation matrix,
given a specified dataframe.
Args:
df (pd.DataFrame): dataframe with numerical columns
font_size (int, optional): Defaults to 12. The font size of the
correlation values displayed in the heatmap cells
ax (Axes object): Matplotlib Axes object (optional)
Returns:
Figure object
"""
if ax is None:
plt.gca()
# Correlation matrix via Pandas (numeric data only)
corr_matrix = df.corr()
# Generate a mask for the upper triangle
mask = np.zeros_like(corr_matrix, dtype=np.bool)
mask[np.triu_indices_from(mask)] = True
# Store heatmap from mask
heat_plot = sns.heatmap(corr_matrix, mask=mask,
cmap='RdBu_r', cbar_kws={"shrink": .6},
annot=True, annot_kws={"size": font_size},
vmax=1, vmin=-1, linewidths=.5,
square=True, ax=ax)
fig = heat_plot.figure
return fig
|
5f596f8bb8ce82aeb203b80efd6ca6938a32467e | GenosseBlaackberry/MIPT_B02-113 | /lab 2 (Turtle 1)/Exercise 9.py | 701 | 3.828125 | 4 | import turtle
turtle.shape('turtle')
import math
turtle.speed(10)
def polygon(n, r, alpha, spin=1, par=True, T=True):
pos =[]
if par:
a=r
else:
a=r*(2*math.sin(math.pi/n))
if T:
turtle.penup()
turtle.forward(a/(2*math.sin(math.pi/n)))
turtle.left(spin*180-90*(n-2)/n)
turtle.pendown()
for i in range(alpha):
turtle.forward(a)
turtle.left(spin*360/n)
pos.append(turtle.position())
if T:
turtle.penup()
turtle.goto(0, 0)
turtle.pendown()
turtle.right(spin*180-90*(n-2)/n)
return pos
def ex9():
for i in range(3, 13):
polygon(i, 10*i, i)
ex9()
|
a2b1918de9aed6e5dad6ecc0aab03bdbada59d2c | mveselov/CodeWars | /katas/kyu_6/help_the_bookseller.py | 370 | 3.53125 | 4 | from collections import defaultdict
OUTPUT = '({} : {})'.format
def stock_list(books, categories):
if not books or not categories:
return ''
book_quantity = defaultdict(int)
for book in books:
code, num = book.split()
book_quantity[code[0]] += int(num)
return ' - '.join(OUTPUT(a, book_quantity.get(a, 0)) for a in categories)
|
911e5dcb4612d47cf090accd862d035888c35611 | jgarciaodowd/Boletin1 | /main.py | 5,541 | 3.96875 | 4 | # Ej. 1:
print("---EJERCICIO 1:")
numero = int(input("Escribe un número entero: "))
print("La tabla de multiplicar es: ")
for i in range(1, 11):
print(f'{i} * {numero} = {i * numero}')
# Ej. 2:
print("---EJERCICIO 2:")
def bucle():
for j in range(10, 20):
print(j)
bucle()
# Ej. 3:
print("---EJERCICIO 3:")
def ConvertirFaC(x):
res = ((9 / 5) * x + 32)
return res
def TablaF():
for i in range(0, 130, 10):
print(str(i) + " ºC = " + str(ConvertirFaC(i)) + " F")
TablaF()
# Ej. 4:
print("---EJERCICIO 4:")
def añoBisiesto(x):
if x % 4 == 0 and (x % 400 == 0 or x % 100 != 0):
return True
return False
print(añoBisiesto(2020)) # Año Bisiesto. True
print(añoBisiesto(2019)) # Año común. False
print(añoBisiesto(1700)) # 1700 es divisible entre 4 pero no es divisible por 400. False
print(añoBisiesto(4000)) # 4000 es divisible entre 4 y 400. True
# Ej. 5:
print("---EJERCICIO 5:")
def diaDelMes(x):
dias = {
1: 31,
2: 28,
3: 31,
4: 30,
5: 31,
6: 30,
7: 31,
8: 31,
9: 30,
10: 31,
11: 30,
12: 31
}
if 1 <= x <= 12:
return dias.get(x)
return -1
print(diaDelMes(1))
print(diaDelMes(6))
print(diaDelMes(12))
# Ej. 6:
print("---EJERCICIO 6:")
def fechaValida(d, m, año):
valido = False
if diaDelMes(m) > 0:
if 1 <= d <= diaDelMes(m):
valido = True
else:
valido = False
if m == 2 and añoBisiesto(año):
if 1 <= d <= (diaDelMes(m) + 1):
valido = True
return valido
print(fechaValida(29, 2, 2020))
print(fechaValida(32, 6, 2020))
print(fechaValida(5, 4, 2020))
# Ej. 7:
print("---EJERCICIO 7:")
cadena = input("Escribe la cadena: ")
def primeraLetra(cadena):
palabras = cadena.split()
nueva_cadena = ""
for palabra in palabras:
nueva_cadena = nueva_cadena + str(palabra[0])
print(nueva_cadena)
primeraLetra(cadena)
# Ej. 8:
print("---EJERCICIO 8:")
cadena = input("Escribe una palabra: ")
def devolverConso(cadena):
nueva_cadena = ""
list = ("a", "e", "i", "o", "u")
cadena.lower()
for letra in list:
cadena = cadena.replace(letra, "")
print(cadena)
devolverConso(cadena)
# Ej. 9:
print("---EJERCICIO 9:")
cadena1 = input("Introduce una palabra: ")
cadena2 = input("Introduce otra palabra: ")
def comprobarOrden():
cadenas = [cadena1, cadena2]
print("La cadena mas pequeña es: " + min(cadenas))
comprobarOrden()
# Ej. 10:
print("---EJERCICIO 10:")
tuplaNumeros = (1, 2, 3, 5, 6, 9, 10)
def ordenados(tuple1):
tuple2 = tuple(sorted(tuple1))
print(tuple1)
print(tuple2)
if tuple1 == tuple2:
print("La tupla está ordenada. ")
else:
print("La tupla no está ordenada. ")
ordenados(tuplaNumeros)
# Ej. 11:
print("---EJERCICIO 11:")
tupla = (3, 4)
tupla1 = (5, 4)
if tupla[0] == tupla1[0] or tupla[0] == tupla1[1] or tupla[1] == tupla1[0] or tupla[1] == tupla1[0]:
print("Las fichas no encajan. ")
else:
print("Las fichas encajan. ")
# Ej. 12:
print("---EJERCICIO 12:")
listaNumeros = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def factorial(num):
factorial = 1
if num == 0:
return 1
else:
for j in range(1, num + 1):
factorial = factorial * j
return factorial
for i in listaNumeros:
print("El factorial de " + str(listaNumeros[i]) + " es: " + str(factorial(listaNumeros[i])))
# Ej. 13:
print("---EJERCICIO 13:")
listaDeNumeros = [12, 34, 55, 7, 10, 2, 21, 77, 0]
k = int(input("Introduce el valor de k: "))
def listas(lista, k):
listaMayores = []
listaMenores = []
listaIguales = []
for i in range(0, len(lista)):
if lista[i] < k:
listaMenores.append(lista[i])
if lista[i] > k:
listaMayores.append(lista[i])
if lista[i] == k:
listaIguales.append(lista[i])
print("Lista de números menores: " + str(listaMenores))
print("Lista de números mayores: " + str(listaMayores))
print("Lista de números iguales: " + str(listaIguales))
listas(listaDeNumeros, k)
# Ej. 14:
print("---EJERCICIO 14:")
cadena = str(input("Escribe una cadena: "))
cadena = cadena.lower()
def cuentaPalabras(frase):
diccionario = {}
listapalbras = frase.split()
for i in range(0, len(listapalbras)):
if listapalbras[i] in diccionario:
diccionario[listapalbras[i]] = diccionario[listapalbras[i]] + 1
else:
diccionario[listapalbras[i]] = 1
print(str(diccionario))
cuentaPalabras(cadena)
# Ej. 15:
import random
print("---EJERCICIO 15:")
dado1 = []
dado2 = []
def hacerTirada(lista):
lista.append(random.randrange(1, 7))
hacerTirada(dado1)
hacerTirada(dado2)
hacerTirada(dado1)
hacerTirada(dado2)
hacerTirada(dado1)
hacerTirada(dado2)
hacerTirada(dado1)
hacerTirada(dado2)
print("Tiradas del dado 1: " + str(dado1))
print("Tiradas del dado 2: " + str(dado2))
def cantidad(dado1, dado2):
suma = []
for i in range(0, len(dado1)):
suma = dado1[i] + dado2[i]
print(str(suma))
cantidad(dado1, dado2)
|
084f4ed722201763c9a1b9a4e70b26ed2dc94956 | Zylophone/Programming-for-Sport | /pramp.com/as josvi/01-BST_successor_searh_scratch-work.py | 1,218 | 3.75 | 4 | Jose
# 100
# / \
# 50 200
# / \ / \
# 10 70 150 300
# for a node n, if it has a right subtree then return the smallest in the right subtree, which is the left most node in the right subtree
# if n does not have a right subtree,
# look at the parent
# if the successor was placed in the BST before node
# then
# suc
# /
# a
# \
# b
# \
# n<<
# anc: b < n
# : a < n
# : suc > n
# PRECONDITION: all nodes of the BST are unique
def findSuccessorOf(node):
if node is None:
return None
if node.right:
return findSmallestIn(node.right)
# node doesn't have a right subtree
ancestor = node.parent
while ancestor and ancestor.val < node.val:
ancestor = ancestor.parent
if ancestor is None:
# node does not have a successor
return None
# {ancestor is not None}
return ancestor
# 100
# / \
# 50 200
# / \ / \
# 10 70 150 300
def findSmallestIn(node):
if node is None:
# an empty tree has no smallest node
return None
while node.left:
node = node.left
return node |
d52fd774013246e530351ab32c89aa3d64a14fc5 | artsiom-kotau/coursera-alg-spec | /alg-toolbox/week4_divide_and_conquer/1_binary_search/binary_search.py | 874 | 3.828125 | 4 | # Uses python3
import sys
import math
def do_search(left, right, a, x):
mid = math.ceil((right + left) / 2)
length = right - left
if length == 0:
return -1
if length == 1:
return -1 if a[left] != x else left
if a[mid] == x:
return mid
elif a[mid] < x:
return do_search(mid + 1, right, a, x)
else:
return do_search(left, mid, a, x)
def binary_search(a, x):
return do_search(0, len(a), a, x)
def linear_search(a, x):
for i in range(len(a)):
if a[i] == x:
return i
return -1
if __name__ == '__main__':
input = sys.stdin.read()
data = list(map(int, input.split()))
n = data[0]
m = data[n + 1]
a = data[1 : n + 1]
for x in data[n + 2:]:
# replace with the call to binary_search when implemented
print(binary_search(a, x), end = ' ')
|
d2c49855562d61ccd7a26e08b12a511b21a254b0 | popuguy/ga-testing | /ga1.py | 1,531 | 3.703125 | 4 | import random
POPULATION_SIZE = 100
CHROMOSOME_SIZE = 40
MAGIC_NUMBER = 42
RECOMBINATION_RATE = 0.7
MUTATION_RATE = 0.001
def split_every(s, n):
split = []
while len(s) >= n:
split.append(s[:n])
s = s[n:]
return split
def fitness(chrom):
value = parse_chromosome(chrom)
if value == MAGIC_NUMBER:
return 2 #maximum fitness
return 1.0 / (MAGIC_NUMBER - value)
def make_chromosome():
return "".join([random.choice(['0', '1']) for _ in range(CHROMOSOME_SIZE)])
def parse_chromosome(chrom):
last = None
total = 0
takes_num = True
chromosome = [int(i, 2) for i in split_every(chrom, 4)]
print chromosome
for gene in chromosome:
if (last == None and gene > 9) or gene > 13:
pass
elif last == None:
print 'START',
last = gene
total = gene
takes_num = False
print gene,
elif takes_num and last > 9 and gene <= 9:
if last == 10: #+
print '+',
total += gene
elif last == 11: #-
print '-',
total -= gene
elif last == 12: #*
print '*',
total *= gene
elif last == 13: #/
print '/',
total /= gene
else:
print 'PROGRAMERROR',
print gene,
last = gene
takes_num = False
elif not takes_num and gene > 9:
takes_num = True
last = gene
elif not takes_num:
pass
print 'END',
return total
if __name__ == "__main__":
chromosomes = [make_chromosome() for _ in range(POPULATION_SIZE)]
chromosomes = alg_iter(chromosomes)
i = 0
while 2 not chromosomes:
chromosomes = alg_iter(chromosomes)
i += 1
print "{0} iterations.".format(i) |
cd0112fdc5011381b456da5d110749630682f00c | rokigeorg/CloudVision_AssableLine | /01_Camera/ImgStoredInDB/retrieveImgDB.py | 429 | 3.625 | 4 | import sqlite3
# create or connect to database
conn = sqlite3.connect('testDB.db')
# get the curser to do stuff in the db
cur = conn.cursor()
cur.execute("""SELECT name,bdata FROM pictures WHERE name == 'pic_4.png' """)
data = cur.fetchone()
# send all commands from the cursor to the db
conn.commit()
# close the db conncetion savely
conn.close()
print data
file = open("new.jpg",'wb')
file.write(data[1])
file.close()
|
8e0a46f1d34c23f56b5694805327221d41f2f560 | prachuryanath/DSA-Problems | /Easy/83. Remove Duplicates from Sorted List/ans.py | 1,356 | 3.75 | 4 | class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
def deleteDuplicates(self, head: ListNode) -> ListNode:
# if input head is NULL, return it
# if input is single node, return it since there are no repetitions
if not head or not head.next:
return head
# we know we have atleast two nodes
# we use two pointers, we are testing if the candidate pointer (curr) is a duplicate
prev=head
curr=prev.next
# we will loop until there are no more candidate pointers to evaluate
while curr:
if curr.val==prev.val:
prev.next = curr.next # skip the curr node and therefore remove it from linked list
else:
prev = curr # increment the prev node
curr = curr.next # increment the candidate node
return head
# We considered every node excatly one, so we have O(N) time complexity
# We used two pointers, so we have O(1) space complexity
# Submission results:
# Runtime: 32 ms, faster than 98.69% of Python3 online submissions for Remove Duplicates from Sorted List.
# Memory Usage: 14.4 MB, less than 27.40% of Python3 online submissions for Remove Duplicates from Sorted List.
|
5776e97f3d274d06dbe48b445370dfa290afd3e5 | cairoas99/Projetos | /PythonGuanabara/exers/listaEx/Mundo2/ex067.py | 262 | 3.84375 | 4 | num = ctg = 0
while True:
num = int(input('Insira um numero para fazer a tabuada ( negativo para parar): '))
print('='*62)
if num < 0 :
break
for c in range(0, 11, 1):
print(f'{num:^4} X {c:^4} = {num*c :^5}')
print('=' * 62) |
a2c55fbdc35ef473b4db76d7cd600cc8ec46e9ab | Domen1234/Programerski-Krozek | /srecanje2/Elif.py | 183 | 3.703125 | 4 | n = 10
if n % 2 == 0:
print("Deljiv je z 2")
elif n % 3 == 0:
print("Deljiv je z 3")
elif n % 4 == 0:
print("Deljiv je z 4")
else:
print("Ni deljiv z niš od tega.")
|
c771da6a9f5d2fdcf575a1193101920d807bf120 | Jason003/Interview_Code_Python | /stripe/vo/toy database.py | 2,905 | 3.578125 | 4 | import functools
class Comparator:
def __init__(self, key, direction):
self.key = key
self.signal = 1 if direction == 'asc' else -1
def compare(self, left, right):
left.setdefault(self.key, 0)
right.setdefault(self.key, 0)
if left[self.key] < right[self.key]:
return -self.signal
elif left[self.key] > right[self.key]:
return self.signal
else:
return 0
def min_by_key(key, records):
# minRecord = {}
# minKey = float('inf')
# for record in records:
# if key not in record:
# if minKey > 0:
# minRecord = record
# minKey = 0
# else:
# if minKey > record[key]:
# minRecord = record
# minKey = record[key]
# return minRecord
return sorted(records, key = lambda x : x.get(key, 0))[0]
def first_by_key(key, direction, records):
# if direction == 'asc':
# return min_by_key(key, records)
# maxRecord = {}
# maxKey = -float('inf')
# for record in records:
# if key not in record:
# if maxKey < 0:
# maxRecord = record
# maxKey = 0
# else:
# if maxKey < record[key]:
# maxRecord = record
# maxKey = record[key]
# return maxRecord
return sorted(records, key = lambda x: (1 if direction == 'asc' else -1) * x.get(key, 0))[0]
def first_by_sort_order(sortOrder, records):
def compare(a, b):
for order in sortOrder:
cmp = Comparator(*order)
result = cmp.compare(a, b)
if result != 0:
return cmp.compare(a, b)
return 0
return sorted(records, key = functools.cmp_to_key(compare))[0]
assert first_by_key("a", "asc", [{"a": 1}]) == {"a": 1}
assert first_by_key("a", "asc", [{"b": 1}, {"b": -2}, {"a": 10}]) in [{"b": 1}, {"b": -2}]
assert first_by_key("a", "desc", [{"b": 1}, {"b": -2}, {"a": 10}]) == {"a": 10}
assert first_by_key("b", "asc", [{"b": 1}, {"b": -2}, {"a": 10}]) == {"b": -2}
assert first_by_key("b", "desc", [{"b": 1}, {"b": -2}, {"a": 10}]) == {"b": 1}
assert first_by_key("a", "desc", [{}, {"a": 10, "b": -10}, {}, {"a": 3, "c": 3}]) == {"a": 10, "b": -10}
cmp = Comparator("a", "asc")
assert cmp.compare({"a": 1}, {"a": 2}) == -1
assert cmp.compare({"a": 2}, {"a": 1}) == 1
assert cmp.compare({"a": 1}, {"a": 1}) == 0
assert (
first_by_sort_order(
[("a", "desc")],
[{"a": 5.0}, {"a": 6.0}],
) == {"a": 6.0}
)
assert (
first_by_sort_order(
[("b", "asc"), ("a", "asc")],
[{"a": -5, "b": 10}, {"a": -4, "b": 9}],
) == {"a": -4, "b": 9}
)
assert (
first_by_sort_order(
[("b", "asc"), ("a", "asc")],
[{"a": -5, "b": 10}, {"a": -4, "b": 10}],
) == {"a": -5, "b": 10}
) |
d94878215ecf281b803076c1058b92f7c5ba1b64 | JejeDurden/TSP-Solver | /parser.py | 434 | 3.5625 | 4 | import argparse
def parse_args(argv):
parser = argparse.ArgumentParser()
parser.add_argument("<salesmen>", type=check_positive, help="number of salesmen as a positive number (e.g: \"1\" or \"42\")")
args = parser.parse_args()
return args
def check_positive(value):
ivalue = int(value)
if ivalue <= 0:
raise argparse.ArgumentTypeError("%s is an invalid positive int value" % value)
return ivalue
|
acafccc6c42a80814675b04367b9e55a3d850913 | vinicius-gadanha/python-courses-cev | /MUNDO 3/ex088.py | 655 | 3.671875 | 4 | from random import randint
from time import sleep
print('=' * 60)
print('{:^60}'.format('GERADOR DE JOGOS'))
print('{:^60}'.format('PARA MEGASENA'))
print('=' * 60)
njogos = int(input('Digite a quantidade de jogos que você quer gerar: '))
print('=' * 60)
print('{:^60}'.format(f'GERANDO {njogos} JOGOS...'))
print('=' * 60)
num = []
x = 0
while not njogos == x:
x += 1
while len(num) != 6:
nr = randint(1, 60)
if num.count(nr) < 2:
num.append(nr)
print(f'Jogo {x:^2}: {num}')
num.clear()
sleep(0.4)
print('=' * 60)
print('{:^60}'.format('BOA SORTE!!!'))
print('=' * 60)
|
11af499b75e3b70c1f0d8550212110bfb8c064bb | reddevil1996/Python-DS | /CheckInsertion.py | 272 | 4.25 | 4 | import InsertionSort as Is
lst = []
size = eval(input('Enter the size of the list: '))
for i in range(size):
n = int(input('Enter the number: '))
lst.append(n)
print('Before sorting list is: ', lst)
Is.Inssort(lst)
print('After sorting list is: ', lst)
|
5c4dc54ea91230809df0b25196e8a53663fce28f | jamiezeminzhang/Leetcode_Python | /math/268_Missing_Number.py | 875 | 3.9375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Feb 21 13:43:21 2016
268. Missing Number
Total Accepted: 39162 Total Submissions: 100071 Difficulty: Medium
Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing
from the array.
For example,
Given nums = [0, 1, 3] return 2.
Note:
Your algorithm should run in linear runtime complexity. Could you implement it using only constant
extra space complexity?
Another great solution using XOR
class Solution(object):
def missingNumber(self, nums):
a = reduce(operator.xor, nums)
b = reduce(operator.xor, range(len(nums) + 1))
return a ^ b
It is because if a^b = c, then c^a = b, c^b = a, which are easy to be verified.
@author: Jamie
"""
class Solution(object):
def missingNumber(self, nums):
return (1+len(nums))*len(nums)/2 - sum(nums) |
3ac1258bf21afaea944f502abbcfd4ea13a729da | SaiAnvitha-k/Bestenlist | /day2.py | 1,123 | 4.28125 | 4 | #How to print a value:
print("30 days 30 hour challenge")
print('30 days 30 hour challenge')
#Assigning String to Variable:
Hours = "thirty"
print(Hours)
#Indexing using String:
Days = "Thirty days"
print(Days[0])
#How to print the particular character from certain text:
Challenge = "I will win"
print(Challenge[7:10])
#Print the length of Character:
Challenge = "I will win"
print(len(Challenge))
#Convert String into lower character:
Challenge = "I will win"
print(Challenge.lower())
#String Concatenation – Joining two strings:
a = "30 Days"
b = "30 hours"
c = a + b
print(c)
#Adding space during concatenation:
a = "30 Days"
b = "30 hours"
c = a + " " + b
print(c)
#casefold() - Usage
text = "Thirty days and Thirty hours"
x = text.casefold()
print(x)
#capitalize() - Usage
text = "Thirty days and Thirty hours"
x = text.capitalize()
print(x)
#find() - Usage
text = "Thirty days and Thirty hours"
x = text.find("o")
print(x)
#isalpha() - Usage
text = "Thirty days and Thirty hours"
x = text.isalpha()
print(x)
#isalnum() - Usage
text = "Thirty days and Thirty hours"
x = text.isalnum()
print(x)
|
f401499c50c5f5aec76be903116c672a6dfe3833 | pogrebnyak/PythonBasic | /class/oop_car/cars.py | 804 | 4.1875 | 4 | class Car(object):
"""
self.price - чистая цена. Может быть изменена методом "Акция"
self.skidka - по-умолчанию отсутсвует. Создаётся методом "Акция"
"""
def __init__(self, name, color, price):
self.name = name
if not isinstance(color, str):
raise ValueError('color incorrect type')
self.color = color
if not isinstance(price, int):
raise ValueError('price incorrect type')
self.price = price
def __str__(self):
return f"{self.name} цвета {self.color} по цене {self.price}"
def __repr__(self):
return f"Car({repr(self.name)}, {repr(self.color)}, {repr(self.price)})"
class SportCar(Car):
pass
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.