blob_id
string | repo_name
string | path
string | length_bytes
int64 | score
float64 | int_score
int64 | text
string |
---|---|---|---|---|---|---|
5b8eb9ff576b910d7bcc5c71e53ca4298d0cc5ac | seobie/algorithms | /가운데글자가져오기.py | 551 | 3.640625 | 4 | """
문제 설명
단어 s의 가운데 글자를 반환하는 함수, solution을 만들어 보세요. 단어의 길이가 짝수라면 가운데 두글자를 반환하면 됩니다.
재한사항
s는 길이가 1 이상, 100이하인 스트링입니다.
"""
def solution(s):
answer = ''
div = int(len(s)/2)
if len(s) % 2 == 0:
answer = s[div-1:div+1]
else:
answer = s[div:div+1]
return answer
# return str[(len(str)-1)//2:len(str)//2+1] # possibly "better" way?
# test
print(solution('powe')) # 'ow'###
|
85efd4a3868608274797daca22b567dc5f63e81d | gittyy1310/guvi-code-kata | /biggest.py | 112 | 3.75 | 4 | n1,n2,n3=input().split()
if(n1>=n2)and(n1>=n3):
print(n1)
elif(n2>=n1)and(n2>=n3):
print(n2)
else:
print(n3)
|
de9a98069631642476e45930c1a493f86e629798 | izzymgm/HODP_Art_Museum | /HAM_API_data_access.py | 1,859 | 3.671875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Nov 2 10:06:57 2020
@author: isabellagm
"""
import requests
import json
def pagination(url):
r = requests.get(url)
# Convert data to jSON format
data = r.json()
# Extract the info and records
info = data['info']
records = data['records']
# For each record of objects, print the title and classification
for item in records:
# Get any people info associated with artwork
peopleArray = item.get('people')
# Create empty array to append information to
peopleInfo = []
# If there are people associated with object,
if peopleArray:
# Go through each person (if several),
for person in peopleArray:
# And append gender and role to a list
gender = person.get('gender')
role = person.get('role')
peopleInfo.append([gender, ';', role])
# Convert created list to string for printing
peopleInfoString = ';'.join(map(str, peopleInfo))
print(str(item['objectid']) + ';' + item['dated'] + ';' + peopleInfoString )
try:
# If there is a next page, repeat pagination function
if (info['next']):
pagination(info['next'])
# If next page doesn't work, end function
except:
pass
# Query to find all objects that have cat in the title
url = "https://api.harvardartmuseums.org/object?q=accessionyear:[2008%20TO%202020]%20AND%20accessionmethod:Purchase&apikey=7c2d8233-3970-4f32-b1d3-f405159bd403&size=100"
# Perform Pagination function defined above on the query
pagination(url)
#+ item['classification'] + ';' + item['dated']
#str(item['objectid']) + ';' +
#';' + str(item['accessionyear']) + ';' + (item['classification']) + ';'
|
354784d0dc003e64371f25e52084589fb30089e3 | berindererikjanos/Gyakorlo-feladatok-2018-2 | /Anagramma.py | 436 | 3.671875 | 4 | #Kérjen két szót, és írja ki, hogy anagrammák-e.
#Két szó anagramma, ha ugyanazokból a betűkből áll.
def anagramma_e(s1,s2):
s1_rendezve = sorted(s1) #ABC sorrendbe rendezi a betűket, és az eredményt egy új stringbe menti
s2_rendezve = sorted(s2)
if s1_rendezve == s2_rendezve:
return True
else:
return False
s1 = input()
s2 = input()
print(anagramma_e(s1,s2))
#anagramma gyakorló
|
badbad2540eb1fba5c9de66f81fa7674db90d836 | v-shieh/restaurant_rating | /ratings.py | 408 | 3.59375 | 4 | """Restaurant rating lister."""
def get_ratings(filename):
"""Function which opens a .txt file and prints restaurant and corresponding
rating.
"""
ratings = open(filename)
for line in ratings:
rating_list = line.rstrip().split(":")
# print rating_list
restaurant, rating = rating_list
print restaurant + " is rated " + rating
get_ratings("scores.txt")
|
0ece865580f259664636f14bfcbabe6ea918fe18 | Johnz86/testbedmonitor | /server/scripts/python/hosts.py | 505 | 3.578125 | 4 | import re
def getEtcHosts():
"""Read the hosts file at the given location and parse the contents"""
with open('/etc/hosts', 'r') as hosts_file:
for line in hosts_file.read().split('\n'):
if len(re.sub('\s*', '', line)) and not line.startswith('#'):
parts = re.split('\s+', line)
ip_address = parts[0]
for host_name in parts[1:]:
hosts[host_name] = ip_address
return hosts
print getEtcHosts() |
b5ad564f17680e98d3ed7806a9440837f2db34a3 | topliceanu/learn | /python/algo/src/shunting_yard.py | 1,761 | 3.5 | 4 | # -*- coding:utf-8 -*-
from collections import deque
op_prec = {
'+': 2,
'-': 2,
'*': 3,
'/': 3,
'^': 4,
}
def prec(op):
if op in op_prec:
return op_prec[op]
return -1
def assoc(op):
if op == '^':
return 'right'
return 'left'
def shunting_yard(tokens):
output_queue = deque([])
operator_stack = []
for token in tokens:
if str.isdigit(token):
output_queue.appendleft(token)
elif token == '(':
operator_stack.append(token)
elif token == ')':
while operator_stack[-1] != '(':
output_queue.appendleft(operator_stack.pop())
operator_stack.pop() # ditch the '('
elif token in ['+', '-', '*', '/', '^']:
while len(operator_stack) > 0 and \
operator_stack[-1] != '(' and \
(prec(operator_stack[-1]) > prec(token) or \
(prec(operator_stack[-1]) == prec(token) and assoc(token) == 'left')):
output_queue.appendleft(operator_stack.pop())
operator_stack.append(token)
else: # is function
operator_stack.append(token)
while len(operator_stack) > 0:
output_queue.appendleft(operator_stack.pop())
return list(output_queue)
class ASTNode(object):
def __init__(self, token, left=None, right=None):
self.token = token
self.left = left
self.right = right
def parse(tokens):
stack = []
rpn = shunting_yard(tokens)
for token in reversed(rpn):
if str.isdigit(token):
stack.append(ASTNode(token))
else:
op = ASTNode(token, stack.pop(), stack.pop())
stack.append(op)
return stack.pop()
|
75e2cf0de4c676882a883e8906c7c017205fb364 | Rachanahande/python1 | /LAB_QUESTIONS/interogative.py | 210 | 3.890625 | 4 | while True:
inp = input("enter the string")
if inp == 'done':
break
else:
if inp.endswith('?'):
print("interogative statements")
else:
print("assert") |
9c61957967ca3d8cbd978a02a07c2bc83c3524ec | StaticNoiseLog/python | /ffhs/limes.py | 282 | 3.515625 | 4 | import math
epsilon = 0.0000000001
previous = -1
current = 0
n = 1
#while current - previous > epsilon:
while n < 1009:
previous = current
current = 1/n**3 + math.log10(n)/3628800
# current = math.sqrt(9 + (-1**n/n))
print("n: ", n, " - ", current)
n += 1 |
23f964d6f63804489db206a6b59432bb2e2e9bed | devpaz94/All-Projects | /triangles.py | 1,796 | 3.984375 | 4 | #Take a triangle and select some coordinate inside that triangle and plot a single point. Then randomly pick one of the three
#corners of the triange and plot a new point exactly half way between the point and the corner. From this new point, repeat
#the process picking a corner at random and plotting a point exaclty half way between you and that new randomly selected corner. If this
#process is repeated many many times, it plots a nice unexpected pattern which is quite cool. Thats what this code does
# shown in this numberphile video https://www.youtube.com/watch?v=kbKtFN71Lfs
import matplotlib.pyplot as plt
import random
x_points = [1]
y_points = [1]
yi = 1
xi = 1
points = [[1, 1],[2, 3],[3, 1]] # three corners of the tiangle
def yfinder(yi):
#takes the y-coordinate for the current position inside the triange
#and returns the new y-coordinate half way between the one and the randomly selected point
if point[1] <= yi:
yi = point[1] + (abs(float(yi - point[1])/2))
else:
yi = point[1] - (abs(float(yi - point[1])/2))
return yi
for i in range(100000):
point = (random.choice(points)) # select a random corner of the triangle
#theses lines take the x-coordinate for the current position inside the triange
#and returns the new x-coordinate half way between the one and the randomly selected point
if point[0] <= xi:
xi = point[0] + (abs(float(xi - point[0])/2))
yi = yfinder(yi)
else:
xi = point[0] - (abs(float(xi - point[0])/2))
yi = yfinder(yi)
x_points.append(xi)
y_points.append(yi)
plt.plot(x_points, y_points, 'bs', ms=0.5) #plot all the points
plt.show()
|
eaab4be803bee8f45472e112ced8336d48146596 | marija2102ua/Homework | /HW7/hw7.1.py | 886 | 4.3125 | 4 | from modules.square_math import rectangle,triangle,circle
def main():
while True:
num = input("""What do you want to calculate?
1.calculates the square of a rectangle
2.calculates the square of triangle
3.calculates the square of circle
Your choice: """)
if num == "1":
sideA = float(input("Enter A: "))
sideB = float(input("Enter B: "))
print(f'Square: {rectangle(sideA, sideB)}')
elif num == "2":
sideA = float(input("Enter A: "))
sideB = float(input("Enter B: "))
sideC = float(input("Enter C: "))
print(f'Square: {triangle(sideA, sideB, sideC)}')
elif num == "3":
radius = float(input("Enter radius: "))
print(f'Square: {circle(radius)}')
else:
print("Please make a choice")
if __name__ == '__main__':
main()
|
9ac402585c0b139b7a3500e93a5465f7b89cbb97 | dsweed12/My-Projects | /Project II - Python MITx/Midter.py | 1,624 | 3.546875 | 4 | def closest_power(base, num):
guess=0
exp=1
while abs(base**guess - num) != 0:
if num > base**guess:
if abs(base**guess - num) <= abs(base**exp - num):
exp = guess
if base**guess > num:
if abs(base**guess - num) < abs(base**exp - num):
exp = guess
if abs(base**guess - num) > abs(base**exp - num):
break
guess += 1
return exp
def dict_invert(dic):
d = {}
for v in dic.values():
d[v] = []
for k, v in dic.items():
d[v].append(k)
d[v].sort()
return d
def max_val(t):
""" t, tuple or list
Each element of t is either an int, a tuple, or a list
No tuple or list is empty
Returns the maximum int in t or (recursively) in an element of t """
# Your code here
def openItem(term):
newList = []
for item in term:
if type(item) == int:
newList.append(item)
else:
newList += openItem(item)
return newList
sortingList = openItem(t)
maximum = sortingList[0]
for item in sortingList:
if maximum < item:
maximum = item
return maximum
def general_poly (L):
"""
L: a list of numbers (n0, n1, n2, ... nk)
Returns: a function, which when applied to a value x, returns the value
n0 * x^k + n1 * x^(k-1) + ... nk * x^0
"""
def func(x):
value = 0
k = len(L) - 1
for num in L:
value = value + num * (x ** k)
k -= 1
return value
return func |
d375793c3358c3260ed9616d2349660fe6b766b4 | EmilyWasher/SomethingAwesome | /python_version/ciphers/rail_fence.py | 2,940 | 4.0625 | 4 | import re
'''
print("Welcome to the rail fence cipher")
# Read in the input, ensuring to sanitise the choice and key
while True:
choice = int(input("Do you want to encrypt (1) or decrypt (2): "))
if choice == 1 or choice == 2:
break
else:
print("Invalid option. PLease select a different option.")
message = input("Enter message: ")
while True:
try:
key = int(input("Enter the number of rails ( > 0): "))
if key < 0:
raise ValueError
except ValueError:
print("Invalid number of rails. Please enter a new number.")
continue
else:
break
'''
# Major credit to https://www.geeksforgeeks.org/rail-fence-cipher-encryption-decryption/
class Rail_fence:
def __init__(self, message, rails):
self._message = message
self._rails = rails
# Function to encrypt the plain text to cipher text
def encrypt(self):
new_message = re.sub("\W", '', self._message)
rails = [""] * self._rails
direc = False # direction we are traverse the array, false is down, true is up
i = 0
for ch in new_message:
rails[i] += ch
if i == self._rails - 1:
direc = True
elif i == 0:
direc = False
if direc == True:
i -= 1
else:
i += 1
return ''.join(rails)
def create_matrix(self, message):
matrix = [['' for i in range(len(message))] for j in range(self._rails)]
direc = False # direction we are traverse the array, false is down, true is up
row = 0
for col in range(len(message)):
matrix[row][col] = True
if row == self._rails - 1:
direc = True
elif row == 0:
direc = False
if direc == True:
row -= 1
else:
row += 1
return matrix
# Function to decrypt provided ciphertext given a key
def decrypt(self):
new_message = re.sub("\W", '', self._message)
matrix = self.create_matrix(new_message)
plaintext = ''
ch_index = 0
for row in range(self._rails):
for col in range(len(new_message)):
if (matrix[row][col] == True) and (ch_index < len(new_message)):
matrix[row][col] = new_message[ch_index]
ch_index += 1
row = 0
for col in range(len(new_message)):
plaintext += matrix[row][col]
if row == self._rails - 1:
direc = True
elif row == 0:
direc = False
if direc == True:
row -= 1
else:
row += 1
return plaintext
'''
# Main body of the program
if choice == 1:
encrypt(message, key)
elif choice == 2:
decrypt(message, key)
'''
|
e16c68ae805ae865fe06ff7cde48e04dd938d889 | rbshadow/Python_URI | /Beginner/URI_1006.py | 288 | 3.546875 | 4 | def math():
a = float(input())
b = float(input())
c = float(input())
update_a = a * 2
update_b = b * 3
update_c = c * 5
result = ((update_a + update_b + update_c) / 10.0).__format__('.1f')
print('MEDIA =', result)
if __name__ == '__main__':
math()
|
15df052ba0344d7ec50beb514711542342b35d4e | RonanAlmeida/income-classifer | /Income Classifer/extractData.py | 3,605 | 3.953125 | 4 | """
This module is used for reading the data and creating the test and training
data sets.
"""
import urllib.request
def readData(url):
"""
This function reads all the data contained in the given url. It creates a dictionary for each line and adds this dictionary to a list.
Parameters:
url: name of the url containing the data records
Returns: a list of dictionaries
"""
# This function is done - Do not modify.
dataSet = []
# Open the web page containing the data
response = urllib.request.urlopen(url)
# Read first line and remove new line indicator
html = response.readline().rstrip()
# Read in file
while len(html) != 0:
# data will contain a list with each element a different attribute
lineList = html.decode('utf-8').split(",")
# Create a dictionary for the line
# assigns each attribute of the record (each item in the linelist)
# to an element of the dictionary, using the constant keys
record = {}
record["age"] = float(lineList[0])
record["workclass"] = lineList[1]
record["educationnum"] = float(lineList[4])
record["marital"] = lineList[5]
record["occupation"] = lineList[6]
record["relationship"] = lineList[7]
record["race"] = lineList[8]
record["sex"] = lineList[9]
record["capitalgain"] = float(lineList[10])
record["capitalloss"] = float(lineList[11])
record["hours"] = float(lineList[12])
record["class"] = lineList[14]
# Add the dictionary to a list
dataSet.append(record)
# Read next line
html = response.readline().rstrip()
return dataSet
def makeTrainingSet(data):
""""
Makes a new list of dictionaries containing the first half of the records
from the full data set (the parameter "data")
Parameters:
data - a list of dictionaries read from the url
Returns:
trainingData - a list of dictionaries (1/2 of data)
"""
trainingData = data[:len(data) // 2] # Double // used for integer division
return trainingData # Return the data only containing the first half of the records
def makeTestSet(data):
"""
Create a test set of data from the second half of the data (ie. the
second half of the data set (indicated by the parameter data).
Add to each dictionary in this set a key called "predicted"
and set it to "unknown".
Paramters:
data - a list of dictionaries (complete data read from url)
Returns:
testData - a list of dictionaries (second half of data file)
"""
testData = data[len(data) // 2:] # Double // used for integer division
return testData # Return the data only containing the second half of the records
# testing goes here. For each module you should show tests for each function.
if __name__ == "__main__":
data = readData("http://research.cs.queensu.ca/home/cords2/annualIncome.txt")
# trying to print all the data will probably make your program crash.
# so, print the first and last values to check them.
print(data[0])
print(data[len(data) - 1])
print(len(data), "records have been read")
x = data[0].get("class")
# show more tests for the functions that you write.
print("\nThe first person makes:", x, "\n")
print("Length of the test set: ", len(makeTestSet(data)))
print("Length of the training set:", len((makeTrainingSet(data))))
|
c1d3205669c264ba7069ca810c2b3bcf45194918 | jancyranij/python | /pg64.py | 143 | 3.734375 | 4 | def sumodd():
a=int(input())
b=int(input())
u=a+b
if u%2==0:
print('even')
else :
print('odd')
try:
sodd()
except:
print('invalid')
|
798028dfc516535c06bcfea95bb337a6eac7d27f | shuiyue-xiaoxiao/xiaomawang_L1 | /小码王-Python-常规课-L1-教学案例-第35课-小码银行3-V3.0-20190920/小码银行(窗口版).py | 5,235 | 3.953125 | 4 | import tkinter # 导入tkinter模块
import tkinter.messagebox # 导入tkinter.messagebox模块
# 账户类
class Account():
def __init__(self, name, password, balance, operation):
self.name = name
self.password = password
self.balance = balance
self.operation = operation
print(self.name, "账户" + self.operation + "成功")
# 查询余额
def check(self):
tkinter.messagebox.showinfo("余额", "您的账户余额为:" + str(self.balance))
# 存钱
def save(self, money):
self.balance += money
self.operation = "存入" + str(money)
tkinter.messagebox.showinfo("提示", "存入成功")
# 取钱
def withdraw(self, money):
if money <= self.balance:
self.balance -= money
self.operation = "取出" + str(money)
tkinter.messagebox.showinfo("提示", "取出成功")
else:
tkinter.messagebox.showwarning("警告", "没钱还想来得瑟")
# 记录
def record(self):
f = open(self.name + ".txt", "a")
text = self.name + "," + self.password + "," + str(self.balance) + "," + self.operation + "\n"
f.write(text)
f.close()
window = tkinter.Tk() # 创建窗口
window.geometry("400x500") # 设置窗口大小
window.title("注册/登录") # 设置窗口标题
# 创建文字标签
label1 = tkinter.Label(window, text="小码银行", font=("微软雅黑", 20))
# 粘贴文字
label1.pack(pady=50)
label2 = tkinter.Label(window, text="账户名", font=("微软雅黑", 20))
label2.pack(pady=0)
# 创建“账户名”输入框
entry1 = tkinter.Entry(window, font=("微软雅黑", 20))
entry1.pack()
# “密码”文字标签
label3 = tkinter.Label(window, text="密码", font=("微软雅黑", 20))
label3.pack(pady=0)
# “密码”输入框
entry2 = tkinter.Entry(window, font=("微软雅黑", 20))
entry2.pack()
# 注册函数
def signin():
name = entry1.get() # 获取账户名
pw = entry2.get() # 获取密码
try:
open(name + ".txt", "r")
except:
# 创建账户和生成txt文件
user = Account(name, pw, 0, "创建账户")
user.record()
tkinter.messagebox.showinfo("提示", "注册成功")
else:
# 提示账户已存在,请重新输入
tkinter.messagebox.showwarning("警告", "账户已存在,请重新输入")
# 登录函数
def login():
name = entry1.get() # 获取账户名
pw = entry2.get() # 获取密码
try:
f1 = open(name + ".txt", "r")
except:
tkinter.messagebox.showinfo("提示", "账户不存在,请先注册")
else:
# 读取密码
lines = f1.readlines()
line = lines[len(lines) - 1]
lineList = line.split(",")
password1 = lineList[1]
# 密码正确
if pw == password1:
balance1 = int(lineList[2])
user = Account(name, pw, balance1, "登录账户")
user.record()
tkinter.messagebox.showinfo("提示", "登录成功")
# 销毁 注册/登录窗口
window.destroy()
# 功能页窗口
homepage = tkinter.Tk()
homepage.geometry("400x500")
homepage.title("功能页")
label11 = tkinter.Label(homepage, text="小码银行", font=("微软雅黑", 20))
label11.pack(pady=50)
# 输入框
label22 = tkinter.Label(homepage, text="请输入存取金额", font=("微软雅黑", 20))
label22.pack()
entry11 = tkinter.Entry(homepage, font=("微软雅黑", 20))
entry11.pack(pady=10)
# 查询余额
def checkMoney():
user.check()
# 存钱
def saveMoney():
money = int(entry11.get())
user.save(money)
user.record()
# 取钱
def withdrawMoney():
money = int(entry11.get())
user.withdraw(money)
user.record()
# 查询余额按钮
btn11 = tkinter.Button(homepage, text="查询余额", font=("微软雅黑", 20), width=20, command=checkMoney)
btn11.pack(pady=10)
# 存钱按钮
btn22 = tkinter.Button(homepage, text="存钱", font=("微软雅黑", 20), width=20, command=saveMoney)
btn22.pack(pady=10)
# 取钱按钮
btn33 = tkinter.Button(homepage, text="取钱", font=("微软雅黑", 20), width=20, command=withdrawMoney)
btn33.pack(pady=10)
# 密码错误
else:
tkinter.messagebox.showerror("错误", "密码错误")
# “登录”按钮
btn1 = tkinter.Button(window, text="登录", font=("微软雅黑", 20), width=20, command=login)
btn1.pack(pady=20)
# “注册”按钮
btn2 = tkinter.Button(window, text="注册", font=("微软雅黑", 20), width=20, command=signin)
btn2.pack()
|
97d01ccf479a6e33c4ade4d770066a97a24f8724 | daksh105/CipherSchool | /Assignment4/GenerateValidIp.py | 909 | 3.65625 | 4 | def GenerateValidIp(s):
n = len(s)
if n == 0 or n > 12:
print("NO Valid Ip")
return
total_Ips = []
IpValidChecker(s, total_Ips)
if total_Ips:
for i in total_Ips:
print(i, end = " ")
else:
print("No Valid Ip")
def IpValidChecker(s, total_Ips, current_Ips = [""] * 4, cur = 0, Ip_cur = 0):
if Ip_cur == 4 and cur == len(s):
total_Ips.append(f"{current_Ips[0]}.{current_Ips[1]}.{current_Ips[2]}.{current_Ips[3]}")
return
elif Ip_cur == 4 or cur == len(s):
return
for i in range(1, 4):
substring = s[cur: cur + i]
if substring[0] == '0' or Ip_cur >=2 and int(substring) > 255:
break
current_Ips[Ip_cur] = substring
IpValidChecker(s, total_Ips, current_Ips, cur + i, Ip_cur + 1)
current_Ips[Ip_cur] = -1
s = input()
GenerateValidIp(s)
|
f7dedd0f022e0728bcb2a6020785869e3c456adc | snangunuri/python-examples | /readfile.py | 379 | 3.96875 | 4 | #!/usr/bin/python
import sys
input_file= sys.argv[1]
gene= sys.argv[2]
print 'argument is', gene
sequence=""
with open (input_file, 'r') as myfile:
for line in myfile:
if gene in line:
for line in myfile:
if line.startswith('>'):
break
else:
sequence = sequence + line.strip()
print("The sequence for %s is %s" % (gene, sequence))
|
4caa864aab4251b5eecbc744da63b5f21d2c110f | MichaelShoemaker/AdventOfCode-2020 | /Day10/Incomplete-Day10-Part2.py | 2,057 | 3.5625 | 4 | #import time
import typing
from itertools import combinations_with_replacement
#Create ordered list of ints, add zero to the beginning
#and a value three larger than the highest value
def make_data(file) -> list:
data = open(file,'r').read().splitlines()
intdata = [int(i) for i in data if len(i) > 0]
intdata.sort()
intdata.insert(0,0)
adapter = max(intdata)+3
intdata.append(adapter)
return intdata
def find_jumps(file) -> int:
jumps = make_data(file)
ones = 0
threes = 0
for r, i in enumerate(jumps):
if r+1 > len(jumps)-1:
break
elif jumps[r+1] -1 == i:
#print(f"Jump from {i} to {jumps[r+1]} is 1")
#time.sleep(.5)
ones+=1
elif jumps[r+1] - 3 == i:
#print(f"Jump from {i} to {jumps[r+1]} is 3")
#time.sleep(.5)
threes +=1
else:
2
return ones * threes
def make_viable_combos(data: list) -> int:
parts = []
winners = []
end = len(data) -1
for num1, e1 in enumerate(data):
for num2, e2 in enumerate(data):
temp= data[num1:num2]
if len(temp)==0:
pass
else:# (max(temp)-min(temp))/3>=len(temp):
if temp[0]!=0 and max(data)-3 in temp:
parts.append([0]+temp+[22])
elif max(data)-3 in temp and temp not in parts:
parts.append(temp+[22])
else:
pass
for t, l in enumerate(parts):
for n, r in enumerate(l):
if n == len(data) -1:
winners.append(l)
elif l[n+1]-r > 3:
print(temp)
break
for i in parts:
print(i)
if __name__=='__main__':
assert find_jumps('test.txt') == 220
assert find_jumps('small.txt') == 35
print(make_viable_combos(make_data('small.txt')))
#print(f"The answer to Part1 is {find_jumps('input.txt')}")
|
e3a691a9e5cc437da91cd3904aea3eb1ad25448e | jhn--/sample-python-scripts | /python3/thinkcs-python3/5.14.1.py | 1,483 | 4.3125 | 4 | '''
Assume the days of the week are numbered 0,1,2,3,4,5,6 from Sunday to Saturday. Write a function which is given the day number, and it returns the day name (a string).
'''
#! /usr/bin/env python
def numtoday(num, listofdays):
# print(num)
if num >= 0 and num < 7:
if num == 0:
print(listofdays[0])
elif num == 1:
print(listofdays[1])
elif num == 2:
print(listofdays[2])
elif num == 3:
print(listofdays[3])
elif num == 4:
print(listofdays[4])
elif num == 5:
print(listofdays[5])
else:
print(listofdays[6])
else:
print("Number", num, "is out of range.")
return
def another_numtoday(num, listofdays):
# num = int(num)
# print(num)
if num >= 0 and num < 7:
for i, j in enumerate(listofdays):
if i == num:
print("its ", j)
else:
print("Number", num, "is out of range.")
return
def checkingforint():
num = input(
'''
Enter an integer between 0 to 6.
(Decimals are okay, I'll convert it into integer.)
: ''')
listofdays = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday']
try:
int_num = int(float(num))
numtoday(int_num, listofdays)
another_numtoday(int_num, listofdays)
except:
print("Error, you did not enter a number.")
checkingforint() |
96dc19a4cdb52380bcb61ad2db12d949b7a2da59 | UpendraDange/JALATechnologiesAssignment | /pythonLoops/program_11.py | 279 | 4.21875 | 4 | """
Program to check whether a number is EVEN or ODD using switch
"""
def demo(arg):
switcher = {
0: "EVEN",
1: "ODD",
}
return switcher.get(arg)
if __name__ == "__main__" :
num = int(input("Enter a number:"))
print("Number is:",demo(num%2)) |
1383f7e4555d702fa1bd0cd6d892f1d980403918 | markleeb/stock_strategies | /trending_value.py | 8,484 | 3.765625 | 4 | import pandas as pd
import numpy as np
import sys
from argparse import ArgumentParser, RawTextHelpFormatter
def read_data(filename, key_file):
"""Reads in filename and assigns column names based on
values in key_file, replacing spaces with '-' in column names.
Returns dataframe.
:filename: data file (ie TRENDING_VALUE.TXT)
:key_file: file that tells us the column names (ie
TRENDING_VALUE_Key.TXT
:returns: dataframe with data from filename and columns from key_file
"""
df = pd.read_csv(filename, header=None)
colnames = pd.read_csv(key_file, header=None)
#change column names to be more dot operator friendly:
#spaces replaced with underscores
#slashes replaced with '_to_' (ie Price/CFPS becomes Price_to_CFPS)
cols = colnames[1].tolist()
col_underscore = [name.replace(' ', '_') for name in cols]
col_slash = [name.replace('/', '_to_') for name in col_underscore]
df.columns = col_slash
return df
def insert_nulls(df, fill_val=-99999999.99):
"""replaces fill_val with null in all columns of df.
:df: Dataframe
:fill_val: fill value to be replaced with nulls.
default=-99999999.99
:returns: Dataframe with fill_val replaced with nulls
"""
for col in df.columns.tolist():
df.ix[df[col] == fill_val, col] = None
return df
def market_cap(df, min_cap=200):
"""filters out stocks that don't meet the min_cap minimum capitalization
criteria.
:df: dataframe
:min_cap: minimum market_cap number (*1 million) for stocks to include in
stock universe (default = 200)
:returns: Dataframe with stocks that have market capitalization>min_cap
"""
df_allstocks = df[df.Market_Cap_Q1>200]
return df_allstocks
def ranks(df, col, asc):
"""Adds columns that rank each column from 0-99 based on rank.
:df: Dataframe
:col: column to rank. Added column will be called 'score_<col>'
:asc: boolean value to pass the ascending parameter in pd.rank() function
:returns: df with added 0-99 ranking columns
"""
try:
df_rank = df[col].rank(pct=True, ascending=asc)
return pd.qcut(df_rank, 100, labels=False).fillna(49)
except ValueError:
try:
df_rank = df[col].rank(pct=True, ascending=asc, method='first')
return pd.qcut(df_rank, 100, labels=False).fillna(49)
except ValueError:
raise(e)
print('{} has non-unique bin edges and will not be included in ranking'.format(col))
def add_rank_cols(df):
"""loops through columns in df and adds ranking columns based on James O'Shaughnessy's
value factor methods. Each of the following is ranked:
Shareholder_Yield
Price to Book
Price to Earnings
Price to Sales
Price to Cash Flow
Enterprise value to EBITDA
The stocks are ranked on a scale of 0-99, with the lowest one percent of Price to Earnings values
recieving a 99 and the highest one percent of price to earnings values recieving a 0. The other
factors are ranked in the same way except for Shareholder Yield, which is assigned a 0 for the
lowest one percent of values and a 99 for the highest one percent. Null values recieve a score
of 49. This is consistent with James O'Shaughnessy's method exept it uses python's 0-based indexing,
which should not have an effect on the overall scoring (O'Shaughnessy uses a 1-100 range of scoring)
"""
for col in df.columns.tolist():
colstring = 'score_{}'.format(col)
if df[col].dtype in ('float64', 'int64'):
if col in ('Shareholder_Yield'):
print('assigning rank to {}'.format(col))
df[colstring] = pd.DataFrame(ranks(df, col, True))
continue
elif col in ('Price_to_Book', 'PE', 'Price_to_Sales', 'Enterprise_Value_to_EBITDA',
'Price_to_CFPS'):
print('assigning rank to {}'.format(col))
df[colstring] = pd.DataFrame(ranks(df, col, False))
continue
else:
print('{} will not be ranked due to datatype'.format(col))
def trending_value(df, num_stocks):
"""Appends column to df with decile rankings based on James O'Shaughnessy's value factor two
method. Decile 9 contains the stocks with the highest scores from the following 6 factors:
Shareholder_Yield
Price to Book
Price to Earnings
Price to Sales
Price to Cash Flow
Enterprise value to EBITDA
See add_rank_cols docstring for details on how each column is scored
Also appends a boolean column with True for stocks in the trending value 25 or 50 stock portfolio
:df: Dataframe with ranked value columns (ranked 0-99)
:num_stocks: number of value factor 2 stocks to return that have the highest 26 week price change
(Typically either 25 or 50; default=25)
:returns: Dataframe with the above described two columns appended as well as a sum of scores column
***HIGHEST SCORE STOCKS ARE IN DECILE 9***
A second dataframe with only the num_stocks trending value stocks
"""
#add a sum of scores column
score_cols = ['score_Price_to_Book',
'score_PE',
'score_Price_to_Sales',
'score_Enterprise_Value_to_EBITDA',
'score_Price_to_CFPS',
'score_Shareholder_Yield']
df['sum_scores'] = df[score_cols].sum(axis=1)
#calculate deciles of sum_scores and create value_factor_two colum (boolean) of highest decile
df['decile_value_factor_two'] = pd.qcut(df['sum_scores'], 10, labels=False)
df['value_factor_two'] = df['decile_value_factor_two']==9
#find the num_stocks value factor two stocks that have the highest 6 month price change
trending_value = df[df['value_factor_two']==True].sort('Price_Change_26_week', ascending=False)[:num_stocks]
tickers = [ticker for ticker in trending_value['Ticker']]
df['trending_value'] = df['Ticker'].isin(tickers)
return trending_value
def initialize_parser():
"""Initialize argparser
"""
p=ArgumentParser(
description='This program is designed to mirror '
'James O\'Shaughnessy\'s trending value portfolio '
'strategy and return the following: \n\t'
'--Take in a filename and key_file, and optional \n\t'
'num_stocks and raw_data args.\n\t'
'--A csv file containing data from the trending \n\t'
'value stocks will be saved in the current dir.\n\t'
'--A csv with raw data from the all_stocks universe \n\t'
'will be saved if --raw_data is passed.',
formatter_class=RawTextHelpFormatter
)
p.add_argument('filename', type=str, help='filename for data ie '
'TRENDINGVALUE.TXT')
p.add_argument('key_file', type=str, help='column name file for '
'data ie TRENDINGVALUE_Key.TXT')
#optional args
p.add_argument('--num_stocks', type=int, help='number of stocks to '
'include in trending value portfolio. Typically 25 or '
'50. Default = 25')
p.add_argument('--raw_data', help='call flag if you want to save the '
'raw data as a csv', action="store_true")
return p
def main():
"""program logic"""
#initialize arg_parser and parse arguments
p=initialize_parser()
args = p.parse_args()
#positional args
filename = args.filename
key_file = args.key_file
#optional args
num_stocks = args.num_stocks if args.num_stocks else 25
raw_data = args.raw_data
print(raw_data)
#get data
df = read_data(filename, key_file)
#replace fill_val with null vals
df = insert_nulls(df)
#filter out low market cap stocks
df = market_cap(df)
#add decile ranking columns
add_rank_cols(df)
#add value factor 2 and trending value columns and return dataframe of trending value portfolio stocks
trending_value_df = trending_value(df, num_stocks)
#reset indices
trending_value_df.reset_index()
df.reset_index()
#save trending value portfolio stocks as csv
trending_value_df.to_csv('trending_value_{}_stocks.csv'.format(str(num_stocks)), index=False)
#save raw data if flagged
if raw_data:
df.to_csv('allstocks_composite_factor.csv', index=False)
#run program logic:
if __name__=='__main__':
main()
|
b198372f3fb4d338a5771d23748c099261fa89a5 | Bartlomiej9867463/Wizualizacja-danych | /47.py | 1,552 | 3.703125 | 4 | class robot:
# definicja konstruktora
def __init__(self, x, y, krok, xa,ya):
if xa>x or ya>y or xa<1 or ya<1:
print("robocik spadl z planszy :(")
del self
else:
self.x=x
self.xa = xa
self.y = y
self.ya = ya
self.krok = krok
def pokaz_gdzie_jestes(self):
return self.xa, self.ya
def idz_w_gore(self,ile_krokow):
if self.ya+ile_krokow>self.y:
print("robocik spadl z planszy :(")
del self
else:
self.ya+=ile_krokow
def idz_w_dol(self, ile_krokow):
if self.ya - ile_krokow < 1:
print("robocik spadl z planszy :(")
del self
else:
self.ya -= ile_krokow
def idz_w_prawo(self,ile_krokow):
if self.xa+ile_krokow>self.x:
print("robocik spadl z planszy :(")
del self
else:
self.xa+=ile_krokow
def idz_w_lewo(self,ile_krokow):
if self.xa-ile_krokow<1:
print("robocik spadl z planszy :(")
del self
else:
self.xa-=ile_krokow
def __del__(self):
print("koniec programu")
sledz = robot(10,10,1,2,1)
print(sledz.pokaz_gdzie_jestes())
sledz.idz_w_gore(4)
print(sledz.pokaz_gdzie_jestes())
sledz.idz_w_prawo(4)
print(sledz.pokaz_gdzie_jestes())
sledz.idz_w_dol(2)
print(sledz.pokaz_gdzie_jestes())
sledz.idz_w_lewo(4)
print(sledz.pokaz_gdzie_jestes())
|
402bd83fe350343fffc89cb25cb3e58928395bfe | miroslavgasparek/python_intro | /pandas_intro.py | 2,697 | 4.25 | 4 | # 03 March 2018 Miroslav Gasparek
# Python bootcamp, lesson 30: Introduction to Pandas
# Import modules
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
rc={'lines.linewidth': 2, 'axes.labelsize': 18, 'axes.titlesize': 18}
sns.set(rc=rc)
# Read in data files with pandas
df_high = pd.read_csv('data/xa_high_food.csv', comment='#')
df_low = pd.read_csv('data/xa_low_food.csv', comment='#')
# Read in data files with pandas with no orw headings.
df_high = pd.read_csv('data/xa_high_food.csv', comment='#', header=None)
df_low = pd.read_csv('data/xa_low_food.csv', comment='#', header=None)
# A Pandas Series is basically a one-dimensional DataFrame
# Pandas Series can be thought of as generalized NumPy array.
# Dictionary of top men's World Cup scorers and how many goals they scored
wc_dict = { 'Klose': 16,
'Ronaldo': 15,
'Muller': 14,
'Fontaine': 13,
'Pele': 12,
'Kocsis': 11,
'Klinsmann': 11}
# Create a Series from the Dictionary
s_goals = pd.Series(wc_dict)
# Make another Dictionary
nation_dict = { 'Klose': 'Germany',
'Ronaldo': 'Brazil',
'Muller': 'Germany',
'Fontaine': 'France',
'Pele': 'Brazil',
'Kocsis': 'Hungary',
'Klinsmann': 'Germany'}
# Series with nations
s_nation = pd.Series(nation_dict)
# Combine Series into a DataFrame, whose keys are the column headers
# and values are the series we are building into a DataFrame.
# Combine into a DataFrame
df_wc = pd.DataFrame({'nation': s_nation, 'goals': s_goals})
# We can index by columns
print(df_wc['goals'])
# We can access data of a single particular person, like slice indexing
print(df_wc.loc['Fontaine', :])
# Look only at German players, for instance, using similar Boolean indexing
german_nat = df_wc.loc[df_wc['nation']=='Germany', :]
# Combine the cross-sectional area data into a DataFrame
# These series are not Series, so we use pd.concat()
# Change column headings
df_low.columns = ['low']
df_high.columns = ['high']
# Concatenate DataFrames
df = pd.concat((df_low, df_high), axis=1)
# Outputting a new CSV file
# kwarg index='False' to avoid explicit writing of the indices to the file
# Write out DataFrame
df.to_csv('xa_combined.csv', index=False)
# Load DataFrame
df_reloaded = pd.read_csv('xa_combined.csv')
## Tidy DataFrames follow these rules:
# 1. Each variable is a column.
# 2. Each observation is a row.
# 3. Each type of observation has its own separate DataFrame.
# Tidy up the DataFrame
df = pd.melt(df, var_name='food density', value_name='cross-sectional area (sq micron)').dropna()
|
610c4b71682e1b62efdc236f19455fd3ec1d37da | xmu-ggx/coding-in-offer | /2-二叉树/2-1.py | 628 | 3.625 | 4 |
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# 返回对应节点TreeNode
def KthNode(self, pRoot, k):
if pRoot is None or k <= 0:
return None
stack = [pRoot]
count = 0
while stack:
while pRoot:
stack.append(pRoot)
pRoot = pRoot.left
temp = stack.pop()
count += 1
if count == k:
return temp
if temp.right is not None:
pRoot = temp.right
return None
|
004b005d61815271a08b2c7d87cd76563f6cc4f0 | candekn/PythonDia1 | /EjercicioSeis.py | 650 | 3.796875 | 4 | #Tipos de colecciones: Listas, Tuplas y Dicionarios
lista = [10,40,50,100]
i = 0
suma = 0
while i < 4:
print(lista[i])
i = i+1
lista.append(1000) #Agrega un nuevo obj al final de la lista
lista.insert(2,33) #Inserta un nuevo obj en el indice elegido
#lista.insert(posicion, valor)
del(lista[0]) #elimina el elemento que se encuentra en esa posicion
lista[-1] #trae el ultimo elemento de la lista
#-2 ante ultimo
#-3 ante penultimo y asi sucesivamente...
len(lista) #permite saber la cantidad de elementos de la lista
j = 0
while j < len(lista)-1:
suma = suma + lista[j]
j = j+1
print(suma) |
7c44987d226a5f0aeba1bffa85ad1de10ff66990 | crazykuma/leetcode | /python3/0104.py | 915 | 3.640625 | 4 | # Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def maxDepth1(self, root: TreeNode) -> int:
# 递归,其实是后序遍历,求出左节点的值与右节点的值比较取大值+1作为树根节点的值
if not root:
return 0
ans = max(self.maxDepth1(root.left)+1, self.maxDepth1(root.right)+1)
return ans
def maxDepth2(self, root: TreeNode) -> int:
# 前序遍历,先计算中间节点的值,再计算左右节点的值
def travel(root, depth):
if not root:
return depth
depth += 1
l = travel(root.left, depth) if root.left else depth
r = travel(root.right, depth) if root.right else depth
return max(l, r)
return travel(root, 0)
|
d392d3e8469e257a30eb4634b4313227870e4425 | BearachB/Hello_World | /Assignment_1/test_1.py | 2,474 | 4.1875 | 4 |
#Get word function goes here to generate the list of words.
def get_word_list():
""" Return a list of words from a word_list.txt file. """
data_file = open("word_list.txt", "r")
word_list = [] # start with an empty word list
for word in data_file: # for every word (line) in the file
# strip off end−of−line characters and make each word lowercase
# then append the word to the word list
word_list.append(word.strip().lower())
return word_list
# Definition of the new function 'puzzle'. This function takes 1 argument (words).
# The word_list will take the list of 45,425 words provided for this assignment and return a list.
def puzzle(words):
# Imports the time module so that the function can be timed to assess efficiency
import time
# Sets the start time
start_time = time.process_time()
# The characters we are looking for
search = "lmnopqrstuv"
# The matching words will be appended to this list once they have been found
results = []
# The first for loop that iterates through the list of 45,000 words
for word in words:
# The count used to check how many matching characters a word has
count = 0
# The second for loop that is used to check the contents of individual letters within the words
for letter in search:
# The if statement uses the rfind function to check if the letter contains a letter from the list.
# If result is not equal to 0 (i.e. it has found a
if word.rfind(letter) != -1:
# Adds 1 to the count variable to keep track of how many words from our list have been used
count +=1
print(count)
# If statement checks whether search characters are in the given word
if (results.count(word) < 1 and count == 9):
# Append given word to results list
results.append(word)
# Calculates how long the function took to run, rounded to 2 decimal places
total_time = round(time.process_time() - start_time,2)
# Prints the time taken to run the function
print("This function took",total_time, "seconds to run.")
# Prints a statement saying how many words match the criteria
print("There are", len(results), "words matching this criteria:")
# Returns the results list
return results
# Driver code to call the function and print the results
print(puzzle(get_word_list()))
|
49761afbefd00bf47c7ac8e816ebb06478a7dd5a | spillay/AHRM | /EmoService/WebSrv/utilities/utilmath.py | 800 | 3.53125 | 4 | import sys
python_version = sys.version_info[0]
if python_version != 2 and python_version != 3:
print('Error Python version {0}, quit'.format(python_version))
exit(0)
def get_3d_centroid(data_list_3d):
xx = []
yy = []
zz = []
for x,y,z in data_list_3d:
xx.append(x)
yy.append(y)
zz.append(z)
length = len(data_list_3d)
cx = sum(xx) / float(length)
cy = sum(yy) / float(length)
cz = sum(zz) / float(length)
return (cx,cy,cz)
def get_3d_distance(pfrom, pto):
if len(pfrom) < 3:
return None
if len(pto) < 3:
return None
x1 = pfrom[0]
y1 = pfrom[1]
z1 = pfrom[2]
x2 = pto[0]
y2 = pto[1]
z2 = pto[2]
d = (x1-x2)**2 + (y1-y2)**2 + (z1-z2)**2
d = math.sqrt(d)
return d
|
3629084157204285c8f6b07f94254bb7c20b43b3 | Ydeh22/QuantumComputing | /SuperdenseCoding.py | 2,952 | 3.6875 | 4 | '''
File: SuperdenseCoding.py
Author: Collin Farquhar
Description: An an example of superdense coding where two entangled qubits
are entangled and then given separately to two parties (Alice and Bob).
Alice wants to send a two (classical) bit message to Bob and can do so by applying quantum
operation to her qubit and sending it to Bob.
Bob then measures the state of the two qubits to reveal the two
classical bit message.
There is no way to convey two bits of information with one classial
bit.
'''
from pyquil import Program
from pyquil import get_qc
from pyquil.gates import *
def entangle_qubits():
"""
Paramaters:
None
Returns:
p: ('pyquil.quil.Program') a pyquil Program to entangle qubits to
the |+> Bell state
"""
p = Program()
p += H(0)
p += CNOT(0,1)
return p
def Alice_Encode(p, cbits):
"""
Paramaters:
p: (pyquil.quil.Program) a pyquil Program that entangles qubits
cbits: (string) the two classical bits that Alice wants to send to Bob
Returns:
p: (pyquil.quil.Program) a pyquil Program with Alice's operation on
the entangled qubits
"""
# Alice's quantum operation
if cbits == '00':
p += I(0)
elif cbits == '01':
p += X(0)
elif cbits == '10':
p += Z(0)
elif cbits == '11':
p += Z(0)
p += X(0)
else:
exit("Invalid cbit string")
return p
def Bob_measurement(p):
"""
Paramaters:
p: (pyquil.quil.Program) The program representing the operations done on the qubits
after Alice's encodes the the information and sends her qubit to Bob
Returns:
p: (pyquil.quil.Program) The full superdense coding Program
result: (np.ndarray) The result of Bob's measurement on the 2 qubits
"""
p += CNOT(0,1)
p += H(0)
qc = get_qc("2q-qvm")
#result = qc.run_and_measure(p, trials=10)
ro = p.declare('ro', 'BIT', 2)
p += MEASURE(0, ro[0])
p += MEASURE(1, ro[1])
executable = qc.compile(p)
result = qc.run(executable)
return p, result
def main():
print("First, we entangle two qubits and give one to Alice and one to Bob.")
p = entangle_qubits()
print("\nEnter the two classical bits Alice would like to send to Bob:")
cbit_string = input(" Possiblities are {00, 01, 10, 11}: ")
Alice_p = Alice_Encode(p, cbit_string)
print("\nTo send those bits, alice applies the following quantum operations to her qubit:")
print(Alice_p[2:])
print("\nAlice sends her qubit to Bob.")
p, result = Bob_measurement(Alice_p)
print("\nBob applies the following quantum operations:")
print(p[-5:-3])
print("\nResult of Bob's measurement:")
print(result)
if __name__ == '__main__':
main()
|
7f367924f8f6216c6cfae4c02c3db6f5db944648 | pooyamb/py-moneyed | /moneyed/money.py | 8,073 | 3.6875 | 4 | # -*- coding: utf-8 -*-
from __future__ import division
from __future__ import unicode_literals
from decimal import Decimal
import sys
import warnings
PYTHON2 = sys.version_info[0] == 2
# Default, non-existent, currency
DEFAULT_CURRENCY_CODE = 'XYZ'
def force_decimal(amount):
"""Given an amount of unknown type, type cast it to be a Decimal."""
if not isinstance(amount, Decimal):
return Decimal(str(amount))
return amount
class Currency(object):
"""
A Currency represents a form of money issued by governments, and
used in one or more states/countries. A Currency instance
encapsulates the related data of: the ISO currency/numeric code, a
canonical name, and countries the currency is used in.
"""
def __init__(self, code='', numeric='999', name='', countries=None):
if countries is None:
countries = []
self.code = code
self.countries = countries
self.name = name
self.numeric = numeric
def __hash__(self):
return hash(self.code)
def __eq__(self, other):
return type(self) is type(other) and self.code == other.code
def __ne__(self, other):
return not self.__eq__(other)
def __repr__(self):
return self.code
class MoneyComparisonError(TypeError):
# This exception was needed often enough to merit its own
# Exception class.
def __init__(self, other):
assert not isinstance(other, Money)
self.other = other
def __str__(self):
# Note: at least w/ Python 2.x, use __str__, not __unicode__.
return (
"Cannot compare instances of Money and %s" % self.other.__class__.__name__
)
class CurrencyDoesNotExist(Exception):
def __init__(self, code):
super(CurrencyDoesNotExist, self).__init__(
"No currency with code %s is defined." % code
)
class Money(object):
"""
A Money instance is a combination of data - an amount and a
currency - along with operators that handle the semantics of money
operations in a better way than just dealing with raw Decimal or
($DEITY forbid) floats.
"""
def __init__(self, amount=Decimal('0.0'), currency=DEFAULT_CURRENCY_CODE):
if not isinstance(amount, Decimal):
amount = Decimal(str(amount))
self.amount = amount
if not isinstance(currency, Currency):
currency = get_currency(str(currency).upper())
self.currency = currency
def __repr__(self):
return "<Money: %s %s>" % (self.amount, self.currency)
def __unicode__(self):
from moneyed.localization import format_money
return format_money(self)
def __str__(self):
from moneyed.localization import format_money
if PYTHON2:
return '%s%s' % (
self.currency.code,
format_money(self, include_symbol=False),
)
else:
return format_money(self)
def __hash__(self):
return hash((self.amount, self.currency))
def __pos__(self):
return self.__class__(amount=self.amount, currency=self.currency)
def __neg__(self):
return self.__class__(amount=-self.amount, currency=self.currency)
def __add__(self, other):
if other == 0:
# This allows things like 'sum' to work on list of Money instances,
# just like list of Decimal.
return self
if not isinstance(other, Money):
raise TypeError(
'Cannot add or subtract a ' + 'Money and non-Money instance.'
)
if self.currency == other.currency:
return self.__class__(
amount=self.amount + other.amount, currency=self.currency
)
raise TypeError(
'Cannot add or subtract two Money ' + 'instances with different currencies.'
)
def __sub__(self, other):
return self.__add__(-other)
def __mul__(self, other):
if isinstance(other, Money):
raise TypeError('Cannot multiply two Money instances.')
else:
if isinstance(other, float):
warnings.warn(
"Multiplying Money instances with floats is deprecated",
DeprecationWarning,
)
return self.__class__(
amount=(self.amount * force_decimal(other)), currency=self.currency
)
def __truediv__(self, other):
if isinstance(other, Money):
if self.currency != other.currency:
raise TypeError('Cannot divide two different currencies.')
return self.amount / other.amount
else:
if isinstance(other, float):
warnings.warn(
"Dividing Money instances by floats is deprecated",
DeprecationWarning,
)
return self.__class__(
amount=(self.amount / force_decimal(other)), currency=self.currency
)
def round(self, ndigits=0):
"""
Rounds the amount using the current ``Decimal`` rounding algorithm.
"""
if ndigits is None:
ndigits = 0
return self.__class__(
amount=self.amount.quantize(Decimal('1e' + str(-ndigits))),
currency=self.currency,
)
def __abs__(self):
return self.__class__(amount=abs(self.amount), currency=self.currency)
def __bool__(self):
return bool(self.amount)
if PYTHON2:
__nonzero__ = __bool__
def __rmod__(self, other):
"""
Calculate percentage of an amount. The left-hand side of the
operator must be a numeric value.
Example:
>>> money = Money(200, 'USD')
>>> 5 % money
USD 10.00
"""
if isinstance(other, Money):
raise TypeError('Invalid __rmod__ operation')
else:
if isinstance(other, float):
warnings.warn(
"Calculating percentages of Money instances using floats is deprecated",
DeprecationWarning,
)
return self.__class__(
amount=(Decimal(str(other)) * self.amount / 100), currency=self.currency
)
__radd__ = __add__
__rsub__ = __sub__
__rmul__ = __mul__
__rtruediv__ = __truediv__
# _______________________________________
# Override comparison operators
def __eq__(self, other):
return (
isinstance(other, Money)
and (self.amount == other.amount)
and (self.currency == other.currency)
)
def __ne__(self, other):
result = self.__eq__(other)
return not result
def __lt__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
if self.currency == other.currency:
return self.amount < other.amount
else:
raise TypeError('Cannot compare Money with different currencies.')
def __gt__(self, other):
if not isinstance(other, Money):
raise MoneyComparisonError(other)
if self.currency == other.currency:
return self.amount > other.amount
else:
raise TypeError('Cannot compare Money with different currencies.')
def __le__(self, other):
return self < other or self == other
def __ge__(self, other):
return self > other or self == other
CURRENCIES = {}
CURRENCIES_BY_ISO = {}
def add_currency(code, numeric, name, countries):
global CURRENCIES
CURRENCIES[code] = Currency(
code=code, numeric=numeric, name=name, countries=countries
)
CURRENCIES_BY_ISO[numeric] = CURRENCIES[code]
return CURRENCIES[code]
def get_currency(code=None, iso=None):
try:
if iso:
return CURRENCIES_BY_ISO[str(iso)]
return CURRENCIES[code]
except KeyError:
raise CurrencyDoesNotExist(code)
|
8a84cd28897a551935e13257e313ac813d07a762 | ShiJingChao/Python- | /PythonStart/一阶段查漏补缺/Day1.py | 1,839 | 3.625 | 4 | # 小数在运算涉及到二进制问题
# a = 0.1+0.2
# print(a)
# if (round(0.1) + round(0.2)) == round(0.3):
# print(True)
# else:
# print(False) # True
"""
高级版
4位验证码:
要求不能重复,且必须含有字母
"""
# import random
# str = ""
# s_str = set()
# letter = [chr(i) for i in range(65,91)]
# letter1 = [chr(i) for i in range(97,123)]
# letter.extend(letter1)
# f = False
# while True:
# for i in letter:
# if i in s_str:
# f = True
# if len(s_str) == 4 and f == True:
# break
# else:
# a = random.choice([chr(random.randint(48, 57)),chr(random.randint(65,90)),chr(random.randint(97,122))])
# s_str.add(a)
# for i in s_str:
# str += i
#
# print(str)
# code = input("请输入验证码:")
# if code == str:
# print("验证成功")
# else:
# print("验证失败")
# 格式 {:填充的字符 填充的方式 填充的宽度}
# a = "Python等级考试"
# b = "="
# c = ">"
# # {0:"=">25}
# print("{0:{1}{3}{2}}".format(a,b,25,c)) # 0 是a 0是后面索引值 {1}是b ,{3}是c {2}是25
#
# # [练习] 字符串'i love python' 将python填充长度为10, 右对齐, 填充字符为p
# s5 = 'i love {:p>10}'.format('python')
# print(s5) # i love pppppython
# print(oct(8))
import os
import random
strs = "abcdefghijklmnopqrstuvwxyzABCDEFGHIGKLMNOPQRSTUVWXYZ1234567890!@#$%^&*?"
str1 = set()
str11 = ""
file = open(r"D:/a.txt","a")
while True:
if len(str1) == 10:
break
else:
s = random.sample(strs,10) # 从strs中取出10个,用s接收列表
for i in s: # 遍历列表
str11 += i # 将列表中的字符拼接
str1.add(str11[0]) # 将每个字符串的首字母存在集合中
file.write(str11 + "\n")
str11 = ""
continue
file.close()
|
43dbcb31f9c0d34cbc33fe8e646bd9daedf770f8 | Shahzaib1999/Python | /calc.py | 633 | 3.6875 | 4 | from tkinter import *
top=Tk()
top.geometry("400x250")
n1=IntVar()
n1.set("")
n2=IntVar()
n2.set("")
n3=IntVar()
n3.set("")
def add(n1,n2):
add=n1+n2
n3.set(add)
number1=Label(top,text="number 1")
number1.grid()
number2=Label(top,text="number 2")
number2.grid(row=1)
result=Label(top,text="Result")
result.grid(row=2)
e1=Entry(top,textvariable=n1)
e1.grid(row=0,column=1)
e2=Entry(top,textvariable=n2)
e2.grid(row=1,column=1)
e3=Entry(top,text=n3)
e3.grid(row=2,column=1)
submit=Button(top,text="Add",command=lambda:add(n1.get(),n2.get()))
submit.grid(row=3)
top.mainloop()
|
3be346cfa3394f7714383a42d7218f4675c5faee | Riceair/Python_homework | /week_9/Part2_41to60_43.py | 162 | 3.5625 | 4 | a_list = ['apple',('Danny','Rob'),'ball']
print("a_list =",a_list)
var1, var2, var3 = a_list
print("var1 =",var1)
print("var2 =",var2)
print("var3 =",var3)
|
38b6ea977f21e35243fa66b48af67f33a6c41f26 | jeanjoubert10/Simple-Pong-in-python-3-and-Turtle-with-start-and-game-over-screen | /bounce.py | 1,932 | 3.9375 | 4 | # Very simple ball paddle game J Joubert 4 Nov 2019
# Writtten on mac osx - may need minor changes for windows as shown
# This code can be copied, changed, updated and if improved - please let me know how!!
import turtle
#import time # and time.sleep(0.017) windows?
win = turtle.Screen()
win.title('Paddle Game')
win.setup(500,600)
win.tracer(0) # Stops all animation until win.update() - try without this!!
win.listen() # Listen for key presses (right and left)
ball = turtle.Turtle()
ball.shape('circle')
ball.color('red')
ball.up() # lift pen up - you do not want to draw
# Chosen ball speed in x and y axis
ball.dx = 5 # May need change in windows eg 0.05
ball.dy = 5
paddle = turtle.Turtle()
paddle.shape('square')
paddle.shapesize(1,5) # 5x on y axis (turtle still looking right)
paddle.color('blue')
paddle.up()
paddle.goto(0,-260)
def paddle_right(): # Move paddle 50 pixels right only if still in screen
if paddle.xcor()<180:
paddle.goto(paddle.xcor()+50, paddle.ycor())
def paddle_left():
if paddle.xcor()>= -150:
paddle.goto(paddle.xcor()-50, paddle.ycor())
win.onkey(paddle_right, 'Right')
win.onkey(paddle_left, 'Left')
def move_ball():
ball.goto(ball.xcor()+ball.dx, ball.ycor()+ball.dy)
# Change dx if ball gets to either side
if ball.xcor() >=230 or ball.xcor()<= -240:
ball.dx *= -1
# Change dy if ball gets to top
if ball.ycor() >= 290:
ball.dy *= -1
# Reset ball to middle if out on the bottom
if ball.ycor() <= -280:
ball.goto(0,0)
ball.dy *= -1
def ball_bounce(): # Bounce on paddle
# If ball moving down and at level of paddle and between the left and right side, dy * -1
if ball.dy<0 and ball.ycor()<=-245 and (paddle.xcor()-60 <= ball.xcor() <= paddle.xcor()+60):
ball.dy *= -1
while True:
win.update()
move_ball()
ball_bounce()
#time.sleep(0.017) # windows?
|
5d56167607f7c35940b177daadea7e0cdb7c8d38 | xichengxml/python-tutorial | /src/geektime/01/T007_If.py | 87 | 3.75 | 4 | x = 'abc'
if x == 'abc':
print('x和abc相等')
else:
print('x和abc不相等') |
cc41dd5a7f3a1f5d46f1e5384ec9b2447fe309d3 | lies98/Programmation-Concurrente | /tp3_amarouche_lies.txt | 3,079 | 3.59375 | 4 | import time
def count_mot(phrase):
cpt = 0
phrase = phrase.strip()
for index in range(len(phrase)):
if phrase[index] == ' ' and phrase[index - 1] != ' ':
cpt += 1
return cpt + 1
def count_mot2(phrase):
mots = [item for item in phrase.split() if item != " "]
return len(mots)
def replace_multiple(s1, s2, n):
s3 = list(s1)
for index in range(n, len(s1), n):
if len(s2) != 0:
s3[index] = s2[0]
s2 = s2.replace(s2[0], '', 1)
return ''.join(s3) + s2
def termeU(n):
if n == 0:
return 1
else:
return termeU(n - 1) * 2 ** n + n
def series(n):
res = 0;
for i in range(0, n + 1):
res += termeU(i)
return res
def series_v2(n):
res = [1]
for i in range(1, n + 1):
res.append(res[i - 1] * 2 ** i + i)
return sum(res)
#pour le tableau pour n = 5
#res=[1]
#i:1 res=[1,3]
#i:2 res=[1,3,14]
#i:3 res=[1,3,14,115]
#i:4 res=[1,3,14,115,1844]
#i:5 res=[1,3,14,115,1844,59013]
def facto(n):
res = 1
for i in range(1, n + 1):
res *= i
return res
if __name__ == '__main__':
print("count_mot( hi hello in the woods ) ", count_mot(" hi hello in the woods "))
print("count_mot2( hi hello in the woods ) ", count_mot2(" hi hello in the woods "))
print("replace_multiple(hirondelles, nid, 3) ", replace_multiple("hirondelles", "nid", 3))
print("replace_multiple(abacus, oiseau, 2) ", replace_multiple("abacus", "oiseau", 2))
print("replace_multiple( , , 2) ", replace_multiple("", "", 2))
print("termeU(0) = ", termeU(0))
print("termeU(1) = ", termeU(1))
print("termeU(5) = ", termeU(5))
print("termeU(10) = ", termeU(10))
print("series(0) = ", series(0))
print("series(1) = ", series(1))
print("series(5) = ", series(5))
print("series_v2(0) = ",series_v2(0))
print("series_v2(1) = ",series_v2(1))
print("series_v2(5) = ",series_v2(5))
depart = time.clock()
series(100)
arrive = time.clock()
print("series(100) met ", arrive - depart)
depart = time.clock()
series_v2(100)
arrive = time.clock()
print("series_v2(100) met ", arrive - depart)
depart = time.clock()
series(300)
arrive = time.clock()
print("series(300) met ", arrive - depart)
depart = time.clock()
series_v2(300)
arrive = time.clock()
print("series_v2(300) met ", arrive - depart)
depart = time.clock()
series(400)
arrive = time.clock()
print("series(400) met ", arrive - depart)
depart = time.clock()
series_v2(400)
arrive = time.clock()
print("series_v2(400) met ", arrive - depart)
depart = time.clock()
series_v2(1000)
arrive = time.clock()
print("series_v2(1000) met ", arrive - depart)
print("on remarque que seriesV2 est bien plus puissant que series")
print("facrtorielle(1) = ", facto(1))
print("facrtorielle(2) = ", facto(2))
print("facrtorielle(3) = ", facto(3))
print("facrtorielle(4) = ", facto(4))
|
f839611b8d9f1752c1da179920b5f87de9e20285 | AnkusManish/Machine-Learning | /Week2/Sets/Program_3.py | 227 | 4.21875 | 4 | #!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Wed Jul 31 22:49:49 2019
@author: ankusmanish
"""
a = set([1,2,3,4,5])
#add() method adds the element to the set
a.add(6)
print('Updated list is : {}'.format(a)) |
02ba62b13fb59a5c8576d2b7d07670b05c5c6e78 | CriSarC/PythonExercises | /3.Condicionales/3.1OperadoresRelacionales.py | 205 | 3.875 | 4 | # -*- coding: utf-8 -*-
Num1 = 50
Num2 = 10
Num3 = 100
Num4 = 100
print(Num1 < Num2)
print(Num1 > Num2)
print(Num1 <= Num2)
print(Num1 >= Num2)
print(Num3 >= Num4)
print(Num1 != Num2)
print(Num3 != Num4) |
d37ef098f66adce79d910c1b6ceb34603740dfcb | kawmaiparis/Comsci_AS | /Pre Release - Book/Task 2.py | 1,024 | 3.875 | 4 | while True:
print("1. display the file contents")
print("2. search the array for a particular book")
print("3. end the program")
choice = input("") #DECLARE choice : string
if choice == "1":
myfile = open('BOOK-FILE.txt','r') #DECLARE myfile : file
top = [line.replace("\n","") for line in myfile] #DECLARE top : string
print(top)
myfile.close()
elif choice == "2":
filebook = open('BOOK-FILE.txt','r') #DECLARE filebook : file
title = [line.replace("\n","") for line in filebook] #DECLARE title : string
print("Enter book")
thisbook = input("") #DECLARE thisbook : string
n = 0 #DECLARE n = integer
isfound = False #DECLARE isfound : boolean
for i in range(len(title)):
if thisbook == title[n]:
print("BOOK FOUND!")
isfound = True
n += 1
if isfound == False:
print("BOOK NOT FOUND!")
elif choice == "3":
break
|
0b9935ccc90e7698e62ea3d19b2a7532a9d03ca1 | ashish-dalal-bitspilani/python_recipes | /python_cookbook/edition_one/Chapter_One/recipe_four.py | 1,750 | 4.4375 | 4 | # Chapter 1
# Section 1.4
# Getting a value from a dictionary
# Problem context : We want to obtain a value from a dictionary,
# without having to handle an exception if the key for which the value is
# being sought is not in the dictionary
# Approach 1
print()
colors = dict(red = 1, green = 2, blue = 3)
print('colors : ', colors)
print('APPROACH 1:\n')
def get_value_from_dict(dictionary, key):
print('checking for key membership in dict using has_key()\n')
try:
if dictionary.has_key(key):
print(dictionary[key])
else:
print(key, 'not found\n')
except Exception as e:
print('\nException type : {}\n'.format(type(e).__name__))
print('\nException message : {}\n'.format(e))
print('checking for key membership in dict using IN clause\n')
try:
if key in dictionary:
print('Value of {} in dictionary : '.format(key), dictionary[key])
else:
print(key, 'not found\n')
except Exception as e:
print('\nException type : {}\n'.format(type(e).__name__))
print('\nException message : {}\n'.format(e))
get_value_from_dict(colors, 'purple')
get_value_from_dict(colors, 'red')
print('*****************************************************\n')
# Approach 2
print()
print('APPROACH 2:\n')
print('using get method dict.get()')
print('dict.get() IS EXTREMELY USEFUL IN ITERATING THROUGH DATA STRUCTURES\n')
def get_value_from_d(dictionary, key):
return (dictionary.get(key, '{} not found'.format(key)))
print('red value : ', get_value_from_d(colors, 'red'), '\n')
print('purple value : ', get_value_from_d(colors, 'purple'), '\n')
print('*****************************************************\n') |
c810cbebae3077e83cf151ee08233bd781339787 | fcdmoraes/aulas_FitPart | /aula4_string.py | 412 | 4.0625 | 4 | x = "isso é um string"
print(x)
##print(x[0])
##for letra in x:
## print(letra)
##x[0]='o'
##print(x.upper())
##print(x)
##x = x.upper()
##print(x)
##print(x.lower())
##print(x.title())
##print(x.capitalize())
##lista = list(x)
##print(lista)
##lista[0] = 'o'
##print(lista)
##
##print("/".join(lista))
##lista = x.split(' ')
##print(lista)
nx = x.replace('i','o')
print(nx)
|
fe146ee7fd16aa8c09a647885a1371198f3c6144 | Finn969/Homework | /returnPosition.py | 218 | 3.8125 | 4 | def returnPosition(string, char):
if char in string:
newstring = string.replace(' ','')
return newstring.index(char) + 1
else:
return -1
print(returnPosition("This is a Sentence","s")) |
dae2c1ce94f5b95a79cae0fb6618bfa57888d467 | Emirates2008/Tarun_2008 | /rectangle.py | 232 | 3.625 | 4 | import turtle
screen = turtle.Screen()
#screen.bgcolor("purple")
line = turtle.Turtle()
line.color("green")
line.fillcolor("orange")
for i in range(2):
line.forward(90)
line.right(90)
line.forward(70)
line.right(90)
|
b82a96690d548302850e9dc453fd54a0fade8443 | Md-Saif-Ryen/roc-pythonista | /Basic Programs/Infinite_monkey_theorem.py | 1,539 | 4.28125 | 4 | """
1, import random
2, user input
3, function to generate a random string of same length as user input.
4, function to compare the randomly generated string to the user's string and giving it a score each time it generates and compare.
"""
import random
def random_str(user_str):
"""This function will produce a random string of same lenght as the user Enter"""
#generated string
gen_str = ''
#all alpha char with white space
char = ' abcdefghijklmnopqrstuvwxyz'
for i in range(len(user_str)):
#picking a random character from alpha char
cha = char[random.randrange(27)]
#adding character to generated string
gen_str += cha
return gen_str
def check_str(user_str, gen_str):
"""This function will make sure if the generated string is equal to user string or not"""
if user_str.lower() == gen_str:
return True
return False
def main(user_str):
"""This function runs the above two funcitons and return the number of times
that monkey hit the keyboard to randomly get the user string"""
#score of monkey
scr = 0
while True:
#getting a random generated string
gen_str = random_str(user_str)
# print(f'{gen_str} ---->> Monkey hitting key-board >>> {scr} times')
if check_str(user_str, gen_str):
scr += 1
break
else:
scr += 1
continue
return f'Monkey hit the key-board {scr} times to enter your input.'
inp = input('Enter here --->>> ')
print(main(inp))
|
45461ac07c8b4e98177638eeda44f00799ff66e9 | ian-garrett/CIS_122 | /Assignments/Week 4/Lab4-2.py | 1,106 | 4.09375 | 4 | # Ian Garrett
# Lab4-2
def get_int(prompt_message):
"""(str) -> int
displays prompt message,
gets input from user
converts input string to number,
returns number to caller
"""
prompt = prompt_message + ' '
temp = input(prompt) # get input from user
return int(temp)
limit = 10
do_again = 'y'
while do_again == 'y':
x = get_int("Enter x as a number from -10 to 20")
# is limit <x?
if limit < x:
print("Yes!", limit, "less than", x)
else:
print("No..", limit, "not less than", x)
# is limit <=x?
if limit <= x:
print ("Yes!", limit,"less than or equal to", x)
else: print("No..", limit,"not less than or equal to", x)
# is limit == x?
if limit == x:
print ("Yes!", limit,"equal to", x)
else:
print ("No..", limit,"not equal to", x)
# is is limit != x?
if limit != x:
print ("Yes!", limit,"not equal to", x)
else:
print ("No..", limit,"equal to", x)
# loop will end when you type in an n
do_again = input("try another? (y or n)")
# end while
|
5832aee986392d800f03c7dbe3a25be4fc4af173 | PJHalvors/Learning_Python | /ZedEx1to4.py | 3,415 | 4.25 | 4 | #!/bin/env/python
#This program contains exercises Num1 to Num4 from Zed's Book
#Excercise 1: Printing strings
#In this exercise using the print command, print seven strings
#The text in a few of the strings may have slightly been changed, only to test, break, and re-build code
#You can use a pair of single or double quotes for each string.
#I prefer double quotes, personally.
#Several of these single lines with a number sign are comments.
#They appear in code, but not on your terminal.
print "Hello World!"
print "Hello Again"
print "I like typing this."
print "This is much too fun."
print 'Woot! iPrint.'
#You can also place a pair of single quotes in a double quote string, like so:
print "I'd much rather you 'not'."
print 'I "said" do not touch this.'
#FYI even though i'm on Excercise 25 now, this is stil super helpful for me.
#Don't forget your basics!!!
#FYI to add space in between each exercise I'm inserting [print ""] to make four lines worth of space. Helps me see things a bit better.
print ""
print ""
print ""
print ""
#Exercise #2:Commenting. On. Everything. Is. IMPORTANT!
#Two sample comments, like this one and the one above, are listed below:
# A comment, this is so you can read your program later.
# Anything after the # is ignored by python.
#You can add a comment within each string, which helps esp. if string is short
print "I could have code like this." # and the comment after is ignored
'''FYI # is a commenting symbol that helps you explain your code. you can insert at the beginning of any string to disable that string or piece of code.'''
#print "This won't run"
print "This will run."
print ""
print ""
print ""
print ""
#Exercise 3: Math in Python
#Display sentence in a string
print "I will count my chickens."
#In line list string followed by equation. I use more spaces that I probably should, but I like it that way.
print "Hens", 25 + 30 / 6
print "Roosters", 100 - 25 * 3 % 4
print "Now I will count the eggs:"
print 3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6
print "Is it true that 3 + 2 < 5 - 7?"
print 3 + 2 < 5 - 7 #This should show up FALSE. 5 is not less than -2
print "What is 3 + 2?", 3 + 2
print "What is 5 - 7?", 5 - 7
print "Oh, that's why it's False."
print "How about some more."
print " Is it greater?", 5 > -2 #This should show up TRUE
print " Is it greater or equal?", 5 >= -2 #This should show up TRUE
print " Is it less or equal?", 5 <= -2 #This should show up FALSE
#So in Exercise#3, Python can be a calculator, the percent sign is a modulus and shows remainders from division, and python follows PEMDAS
print ""
print ""
print ""
print ""
#Exercise 4: Variables and Naming things
#Note: I changed the numbers to test/break and re-build the code.
#Set variables to numbers or equations with those variables
cars = 125
space_in_a_car = 5.0
drivers = 25
passengers = 75
cars_not_driven = cars - drivers
cars_driven = drivers
carpool_capacity = cars_driven * space_in_a_car
average_passengers_per_car = passengers / cars_driven
#Write six strings that include one of the above variables in each string
print "There are", cars, "cars available."
print "There are only", drivers, "drivers available."
print "There will be", cars_not_driven, "empty cars today."
print "We can transport", carpool_capacity, "people today."
print "We have", passengers, "to carpool today."
print "We need to put about", average_passengers_per_car, "in each car."
|
ec9477c9b3ffefaf0758ae0b0947941db48650a4 | rng-atb/rng-hackathon | /tools/generate_data.py | 1,525 | 3.5 | 4 | import argparse
import random
def generate_data(num_accounts, labels, num_lines, output=None):
print("""
num accounts: {0}
labels: {1}
num_lines: {2}
""".format(num_accounts, labels, num_lines))
labels = labels.split(",")
data = []
for a in range(num_accounts):
for l in range(num_lines):
r = random.randint(0, len(labels)-1)
v = random.randint(1, 99)
entry = "Account{0},{1},{2}".format(a, labels[r], v)
data.append(entry)
if output is not None:
with open(output, 'w') as outfile:
outfile.write("source,target,value"+'\n')
for line in data:
outfile.write(line+'\n')
else:
for line in data:
print(line)
return
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Process args to generate d3 open banking data')
parser.add_argument('--num_accounts', '-a', type=int,
help='number of accounts to generate data for')
parser.add_argument('--labels', '-l',
help='comma separate list of labels')
parser.add_argument('--num_lines', '-c', type=int,
help='average number of lines connecting accounts to labels')
parser.add_argument('--outputfile', '-o',
help='output file to write to ')
args = parser.parse_args()
generate_data(args.num_accounts, args.labels, args.num_lines, args.outputfile) |
1cf8b3e011bcb391c3ae40f70da3afeee4c63a2d | christopher-beckham/bio-algorithms | /algo-heights/ins.py | 365 | 3.953125 | 4 | import sys
def swap(arr, i ,j):
temp = arr[i]
arr[i] = arr[j]
arr[j] = temp
def insertion_sort(arr):
swaps = 0
for i in range(1, len(arr)):
k = i
while k > 0 and arr[k] < arr[k-1]:
swap(arr, k-1, k)
swaps += 1
k = k -1
return swaps
sys.stdin.readline()
arr = [int(x) for x in sys.stdin.readline().rstrip().split()]
print insertion_sort(arr) |
73b81a1f8040b47cf35ea3f500d19f4ec6d2aeaf | HidoCan/Programlama_dilleri_yaz_okulu | /2019/2019_TYT_TemelKavramlar_Soru5.py | 690 | 3.8125 | 4 | from math import *
a = input("Kenar sayısı")
b = input("İçerdiği sayı")
c = input ("Küçük kenar sayısı")
d = input("Büyük kenar sayısı")
a = int(a)
b = int(b)
c = int(c)
d = int(d)
x = a/b
x = floor(x)
f = x * c
e = x * d
while e/c > x+1:
e = e+1
break
while f/d < x:
f = f+1
break
if e==f:
toplam = 0
for rakam in e:
toplam += int(rakam)
print("sayının rakamları toplamı:", toplam)
else:
print("e ve f dahil arasındaki bütün sayıları al"
"herbirinin basamaklarını ayrı ayrı topla"
"topladğıgın basamakların sonuçlarından birbirinden farklı olanları yazdır") |
ade8f3f7ec772f17e6aaafa614511ec33ed9ce85 | addriango/curso-python | /sintaxis-basica/15.continue.py | 393 | 4.03125 | 4 | ## la palabra clave "continue" ignora todo lo que esta debajo
## de el en la iteracion donde se cumple la condicion
for letra in "python":
if letra =="h":
continue
print(f"viendo la letra {letra}")
nombre = "Adrian David Gomez Rivera"
print(len(nombre))
contador_caracteres = 0
for i in nombre:
if i == " ":
continue
contador_caracteres+=1
print(contador_caracteres)
|
32165ba5122c7ce7d1d3e2a9fb0620356a9c30ab | yorchd3/JNoriega_GW_HW3 | /Part-1/HW_Task3_Email/employee_email_jorge.py | 1,333 | 4 | 4 | # -*- coding: UTF-8 -*-
"""Employee Email Script.
This module allows us to create an email address using employee data from
a csv file.
Example:
$ python employee_email.py
"""
import os
import csv
filepath = os.path.join("employees.csv")
new_employee_data = []
# Read data into dictionary and create a new email field
with open(filepath) as csvfile:
reader = csv.DictReader(csvfile)
for row in reader:
# YOUR CODE HERE
first_name = row['first_name']
last_name = row['last_name']
ssn = row['ssn']
email = first_name + "." + last_name + "@email.com"
#Create a new dictionary with the data
my_dict = {"first_name":first_name, "last_name":last_name,"SSN":ssn,"Email":email}
#Save/append dictionary information per row into the new_employee_data
new_employee_data.append(my_dict)
#print(new_employee_data)
# Grab the filename from the original path
output_file = os.path.join("jorge.csv")
# Write updated data to csv file
csvpath = os.path.join(output_file)
with open(csvpath, "w") as csvfile:
# YOUR CODE HERE
fieldnames = ['first_name', 'last_name', 'SSN', 'Email']
writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
writer.writeheader()
writer.writerows(new_employee_data)
|
64084796ea507d0b56189fa6838465f15dc4e4d2 | siddharth778/toc | /count_0_and_1.py | 341 | 3.71875 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Sep 22 23:17:59 2019
@author: SiddharthPorwal
"""
n=input()
count0=0
count1=0
for i in n:
if i=='0':
count0=count0+1
for x in n:
if x=='1':
count1=count1+1
print("no of 0's in a string are :"+ str(count0))
print("no of 1's in a string are :"+ str(count1)) |
6f753d2c0aa21a00b72f481d56aa5b074427a3ba | FarzanRashid/CodingBat-Solutions | /List-1/max_end3/solution.py | 134 | 3.609375 | 4 | def max_end3(nums):
if nums[0] > nums[-1]:
return [nums[0], nums[0], nums[0]]
else:
return [nums[-1], nums[-1], nums[-1]]
|
5729e2f8bd9cbcbf081da97db8bf89913fe6d3ea | alangberg/AED3-TP1 | /Ejercicio 2/convert.py | 890 | 3.5625 | 4 | import sys
def toBase3(n):
if n < 3:
res = []
res.append(n)
return res
else:
res = toBase3(int(n/3))
res.append(n%3)
return res
ls = toBase3(int(sys.argv[1]))
ls.reverse()
res = [0] * (len(ls) + 1) #arreglo de 0s
i = 0
for d in ls:
if d == 2:
# si tiene un 2 lo puedo reemplazar sumando la potencia que sigue y restando la potencia acutal
# ej: (6)_10 == (20)_3 <==> 2*3^1 + 0*3^0 <==> 1*3^2 - 1*3^1 + 0*3^0
res[i] = res[i] - 1
res[i+1] = res[i+1] + 1
elif d == 1:
if res[i] == 1:
# entonces tendria un 2, tengo que dejar -1
res[i] = -1
res[i+1] = res[i+1] + 1
else:
res[i] = 1
i = i + 1
# res.reverse()
# print res
i = 0
left = []
right = []
for d in res:
if d == 1:
left.append(3**i)
elif d == -1:
right.append(3**i)
i = i + 1
left.reverse()
right.reverse()
print str(len(left)) + " " + str(len(right))
print left
print right
|
2062698cc5a1bead9ca10a70cb2c81acc5da8466 | chriskopacz/ProjectEuler_python | /problem7.py | 598 | 3.875 | 4 | #Chris Kopacz
#Project Euler
#Problem 7 - 10001st prime
"""
By listing the first six prime numbers: 2, 3, 5, 7, 11, 13
we can see that the 6th prime is 13.
What is the 10001st prime number?
"""
import math
def isPrime(val):
stop = math.ceil(math.sqrt(val))
for iter in range(2,stop+1):
if val % iter == 0:
return False
return True
n = 3
counter = 2
while counter <= 10001:
if isPrime(n) == True:
print(str(counter) + " " + str(n))
counter += 1
n += 2
else:
n += 2
#end of page space holder
|
ab506552bd1072db8c7bb8836f9cca9edb5b37a9 | L1nwatch/leetcode-python | /19.删除链表的倒数第N个节点/solve.py | 2,113 | 3.859375 | 4 | #!/bin/env python3
# -*- coding: utf-8 -*-
# version: Python3.X
"""
"""
import re
from typing import List
__author__ = '__L1n__w@tch'
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
node_map, i = {1: head}, 1
cur_node = head
while cur_node.next != None:
i += 1
node_map[i] = cur_node.next
cur_node = cur_node.next
# 删除第一个节点
if i == n:
head = node_map[2] if i >= 2 else None
# 删除最后一个节点
elif n == 1:
node_map[i - n].next = None
# 删除中间一个节点
else:
node_map[i - n].next = node_map[i - n + 2]
return head
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
length = 0
current_node = head
while current_node:
current_node = current_node.next
length += 1
if length == 1:
return None
if length == n:
head = head.next
return head
target = length - n
current_node = head
for i in range(target-1):
current_node = current_node.next
else:
current_node.next = current_node.next.next
return head
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def removeNthFromEnd(self, head: ListNode, n: int) -> ListNode:
answer = ListNode(0, head)
slow, fast = answer, head
while n > 0:
fast = fast.next
n -= 1
while fast:
slow = slow.next
fast = fast.next
slow.next = slow.next.next
return answer.next |
4252944096740632857a8b620208001820a5ffe9 | CatFootPrint/rl_channel_allocation | /environment.py | 6,143 | 3.8125 | 4 | """
This is the environment which is essentially similar to the bin packing problem.
"""
import numpy as np
class Environment:
"""
This environment info:
state combines the 'channel' and the buffers
action is the placement of the buffer at some position in the 'channel'
On an action being taken, a reward is calculated and the block is placed
in the 'channel' if possible and then the channel is shifted downwards
"""
def __init__(self, cap, time):
"""
Executed on initialisation of Environment
"""
self.cap=cap #the capacity of the channel
self.time=time #the max time avaliable for allocation
self.create_env() #initialise channel
self.action_initiate() #initialises actions
self.buffer_initiate() #creates buffers
def create_env(self):
"""
Randomly initiate the channel.
"""
self.env=np.random.randint(0,2,size=(self.cap+self.time)).reshape(self.cap,self.time)
return self.env
def add_block(self,c,t,x,y):
"""
Firstly checks if the action of size capacity (c), time (t) can fit at position x,y where
that is the bottom left of the block placed.
if it is possible it is placed.
Returns new env and if the move was possible
"""
x_poss=True
y_poss=True
block_pres=False
poss=True
if (x+c)>self.cap:
x_poss=False
if (t+y)>self.time:
y_poss=False
for j in range(x,x+c):
for i in range(y,y+t):
if self.env[i,j]!=0:
block_pres=True
else:
self.env[i,j]=1
if not x_poss or not y_poss or block_pres:
poss=False
return self.env,poss
def buffer_initiate(self):
"""
Jobs in should be a list of the dimensions, priority, and wait time
will be in a numpy array. Where column 1=c,2=t,3=time4=time elap
"""
self.buffer=np.array([np.append(np.random.randint(1,3,size=2),np.array([1,1])),np.append(np.random.randint(1,3,size=2),np.array([1,1]))])
def action_initiate(self):
"""
takes argument which is the index of the action
for a 2x2 there are 9 possible actions.
action space is a little messed up, coords in y,x order for some reason. I forget TODO:fix this.
"""
self.actions_poss={0:np.array([2,2,0,0]),1:np.array([1,1,0,0]),2:np.array([1,1,0,1]),3:np.array([1,1,1,0]),4:np.array([1,1,1,1]),5:np.array([2,1,0,0]),6:np.array([1,2,0,0]),7:np.array([2,1,0,1]),8:np.array([1,2,1,0]),9:np.array([0,0,0,0])}
return self.actions_poss
def perform_action(self,index):
"""
agent selected action (index) which relates to the key in dictionary self.actions_poss, is executed. Which involves checking if it's in the buffer
then calling add_block (above) and finding out if the selected move is possible
"""
c,d=self.buffer.shape
done=False
valid_q=True
for i in range(c):
if (np.array_equal(self.actions_poss[index][0:2],self.buffer[i,0:2])) and not done:#check if selected action is present in buffer
state,valid_q=self.add_block(self.actions_poss[index][0],self.actions_poss[index][1],self.actions_poss[index][2],self.actions_poss[index][3])
if valid_q==True:#if it is succesfully executed, the buffered rep can be removed from the buffer
self.buffer=np.delete(self.buffer,i,0)
done=True
break
elif index==9:#9 means do nothing, which is always valid
valid_q=True
break
else:#if action was not buffered, its not valid
valid_q=False
return self.incr_time(valid_q,index)
def incr_time(self,valid,action):
"""
on this happening, the env gets shifted down once. A reward gets calculated and the buffer gets refilled.
"""
reward=self.calc_reward(valid,action)#calculate reward
temp=np.zeros([self.cap,self.time])
temp[1:,:]=self.env[0:-1,:]
self.env=temp
self.buffer[:,2]=1#To allow for incremement of time later
self.buffer_length_maintain()
return reward
def calc_reward(self,valid,action):
"""
The reward is dependent on the buffered pieces and the capacity used
"""
reward=(np.average(self.env[1])*1.4)+(np.average(self.env[0])*0.6)#r(capacity)
if valid and action!=9:#if it's valid and not do nothing reward is plus 1
reward+=1
elif valid and action==9:#if it's valid and do nothing penalise a little
reward+=-1
elif not valid:#not valid could lead to problems so massively penalised
reward=-50
return reward
def convert_to_state(self):
"""
converts the state to a decimal representation
where first 4 bits represent the state and the final 4 represented the 2 buffers.
Related arrays are flatten and concatenated and then converted to decimal giving a
unique repr for every possible state.
"""
binaryrep=self.env.flatten()
temp=self.buffer[:,0:2].flatten()
temp[temp==1]=0
temp[temp==2]=1
state=np.append(binaryrep,temp)
state=np.array_str(state)
for i in ['[',']','.',' ']:
state=state.replace(i,'')
return int(state,2)
def convert_from_state(self,state):
"""
For troubleshooting
"""
state=np.fromstring(bin(state)[2:].zfill(8).replace('',' ')[1:-1],dtype=int,sep=' ')
return state[0:4].reshape(2,2),state[4:6],state[6:]
def buffer_length_maintain(self):
"""
ensures the buffer always stays at a length of 2
"""
c,d=self.buffer.shape
while c<2:
self.buffer=np.vstack([self.buffer,[np.append(np.random.randint(1,3,size=2),np.array([1,1]))]])
c,d=self.buffer.shape
return 0
|
b9f8e9ba9b29ddfbdf44bd2dd3ca00f7a6e453b4 | zi-yuan-ch/python | /exercise_010.py | 347 | 3.78125 | 4 | # 实例010:给人看的时间
# 题目 暂停一秒输出,并格式化当前时间。
if __name__ == '__main__':
# method1
import time
print("当前时间为:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
time.sleep(1)
print("暂停1秒后时间为:", time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
|
d4387996de68a55e50ee0c29d38b7e188e0cf52a | kinowaki/python-poker | /card.py | 588 | 3.828125 | 4 | #-*-coding:utf-8-*-
import random
class Card:
amount = 52
def __init__(self):
self.card_nums = [2, 3, 4, 5, 6, 7, 8, 9, "T", "J", "Q","K","A"]
self.card_kinds = ["s", "c", "d", "h"]
self.deck = []
for num in self.card_nums:
for kind in self.card_kinds:
self.deck.append(str(num)+kind)
def shuffle(self):
random.shuffle(self.deck)
def push(self):
#number + kind :2d, As
return self.deck.pop()
'''
if __name__=="__main__":
card = Card()
print card.deck, len(card.deck)
card.shuffle()
print card.deck, len(card.deck)
print card.push(), len(card.deck)
'''
|
54c8070acf415fe7410dde5c719464758b25a713 | AxelGarsal/Python-Retos | /3-5_Suma.py | 387 | 3.921875 | 4 | print('Encuentra la suma de todos los múltiplos de 3 o 5 por debajo de 1000.')
'''la funcion range debe tener dos parametros
poner bien los bloques identadores
'''
suma = 0
for i in range(1, 1000):
if i % 3 == 0 or i % 5 == 0:
suma += i
print(i,suma)
print(suma)
mult = 0
for i in range(1, 1001):
if i % 2 == 0 or i % 3 == 0:
mult = mult +1
print(mult)
|
2b5f1fb67f4566e5fdb69ea7015b342f46e5f4b0 | maheshd20/NbaPlayerDetails | /project1.py | 449 | 3.796875 | 4 | import json
myplayer=json.load(open("nbaplayer.json"))
def PlayerSearch(name):
i=1
search=0
for k in range(0,len(myplayer)):
if( (myplayer[k]['firstName'].lower()+' '+myplayer[k]['lastName'].lower())==name.lower()):
print(myplayer[k])
search=1
if(search==0):
print("invalid entery...PLease try again")
playsearch=input("enter player name")
print(PlayerSearch(playsearch))
|
c713e2cd97e3d4a9209072281f68b82f1a50a530 | rootid23/fft-py | /bits/hamming-distance.py | 1,345 | 4.375 | 4 | #The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
#Given two integers x and y, calculate the Hamming distance.
#Note:
#0 ≤ x, y < 231.
#Example:
#Input: x = 1, y = 4
#Output: 2
#Explanation:
#1 (0 0 0 1)
#4 (0 1 0 0)
# ↑ ↑
#The above arrows point to positions where the corresponding bits are different.
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
return bin(x^y).count("1")
#How numbers represented in python?
#How to handle -ve numbers?
def hamming_distance(x, y):
xor = x ^ y
d = 0
while xor > 0:
d += xor & 1
xor >>= 1
return d
#Can't handle negative numbers
#negative number throws the computer into an infinite loop
def hamming_distance(x, y):
diff = x ^ y
cnt = 0
while(diff) :
diff &= diff - 1 #clear the least significant bit set
cnt += 1
return cnt
#To overcome the limitation of negative numbers
def hamming_distance(x, y):
diff = x ^ y
cnt = 0
for _ in range(32) :
if(diff == 0) : break
diff &= diff - 1 #clear the least significant bit set
cnt += 1
return cnt
return bin(x^y).count('1') # bin operation
|
7b37fe0d2e21e82330ceb119c38bfde32193c51a | vaibhavverma9999/Movie-genre-prediction | /model.py | 5,266 | 3.625 | 4 | #in this model we will predict movie genres using movie plots
#to predict we are using bernoulli naive bayes algorithm
#in this section we import all the required libraries
import pandas as pd
import numpy as np
from sklearn.naive_bayes import BernoulliNB
from sklearn.preprocessing import LabelEncoder
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.model_selection import train_test_split
#we import movie database
n1 = LabelEncoder()
df = pd.read_csv('movies_metadata.csv')
#here is the list of all the movie genres considered in this model
genre_types = ['Drama', 'Comedy', 'Adventure', 'History', 'War', 'Thriller', 'Crime', 'Fantasy', 'Horror', 'Family', 'Documentary', 'Mystery', 'Romance', 'Science Fiction', 'Action']
#now we will count the number of movies in each genre
genre_count = {'Drama':0, 'Comedy':0, 'Adventure':0, 'History':0, 'War':0, 'Thriller':0, 'Crime':0, 'Fantasy':0, 'Horror':0, 'Family':0, 'Documentary':0, 'Mystery':0, 'Romance':0, 'Science Fiction':0, 'Action':0}
for i in df['genres']:
t = i.split(', {')
for j in range(len(t)):
q = t[j].split("'name':")
if(len(q)<=1):
continue
q = q[1]
q = q.split("'")
q = q[1]
if q in genre_types:
genre_count[q] = genre_count[q] + 1
print(genre_count)
all_data = []
all_out = []
for genre in genre_types:
data = []
limit = min(5000, genre_count[genre])
out = []
pos_count = 0
neg_count = 0
for i in range(len(df)):
t = df['genres'][i].split(', {')
if(t[0]=='[]'):
continue
k = 0
for j in range(len(t)):
if(k==0):
q = t[j].split("'name':")
if(len(q)<=1):
continue
q = q[1]
q = q.split("'")
q = q[1]
if q == genre and pos_count<limit:
data.append(df['overview'][i])
out.append(1)
k = 1
pos_count += 1
break
if(k==0 and neg_count<=limit*(2)):
data.append(df['overview'][i])
out.append(0)
neg_count += 1
all_data.append(data)
all_out.append(out)
import re
for i in range(len(all_data)):
all_data[i] = np.array(all_data[i])
t = []
for j in range(np.size(all_data[i])):
q = re.sub("[^a-zA-Z0-9 ]", "", all_data[i][j])
q = q.lower()
t.append(q)
t = np.array(t)
all_data[i] = np.array(t)
all_out[i] = np.array(all_out[i])
#saving the tfidf and model for each genre
from sklearn.externals import joblib
import pickle
for i in range(len(genre_types)):
model = BernoulliNB()
data = all_data[i]
out = all_out[i]
tfidf = TfidfVectorizer(lowercase=True, analyzer='word', stop_words='english', ngram_range=(1,1), use_idf=True)
data = tfidf.fit_transform(data)
tfidfname = genre_types[i]+'-tfidf.pkl'
joblib.dump(tfidf, tfidfname)
model.fit(data, out)
modelname = genre_types[i]+'-model.picket'
save_classifier = open(modelname, "wb")
pickle.dump(model, save_classifier)
save_classifier.close()
#calculating the accuracy
from sklearn.externals import joblib
import pickle
from sklearn import metrics
avg = 0
for i in range(len(genre_types)):
model = BernoulliNB()
data = all_data[i]
out = all_out[i]
tfidf = TfidfVectorizer(lowercase=True, analyzer='word', stop_words='english', ngram_range=(1,1), use_idf=True)
data = tfidf.fit_transform(data)
tfidfname = genre_types[i]+'-tfidf.pkl'
joblib.dump(tfidf, tfidfname)
X_train, X_test, Y_train, Y_test = train_test_split(data, out, test_size=0.1, random_state=1)
model.fit(X_train, Y_train)
Y_predict = model.predict(X_test)
acc = metrics.accuracy_score(Y_test, Y_predict)*100
avg = avg + acc
print(genre_types[i], round(acc, 2))
print("Overall Accuracy: ", round(avg/15, 2))
#predict the genre using the plot of a movie
import pickle
import numpy as np
from sklearn.externals import joblib
import re
plot = "In the years after the Civil War, Jo March (Saoirse Ronan) lives in New York City and makes her living as a writer, while her sister Amy March (Florence Pugh) studies painting in Paris. Amy has a chance encounter with Theodore Laurie Laurence (Timothée Chalamet), a childhood crush who proposed to Jo, but was ultimately rejected. Their oldest sibling, Meg March (Emma Watson), is married to a schoolteacher, while shy sister Beth (Eliza Scanlen) develops a devastating illness that brings the family back together."
plot = re.sub("[^a-zA-Z0-9 ]", "", plot)
plot = plot.lower()
plot = np.array(plot).reshape(-1,1)
genres = []
genre_types = ['Drama', 'Comedy', 'Adventure', 'History', 'War', 'Thriller', 'Crime', 'Fantasy', 'Horror', 'Family', 'Documentary', 'Mystery', 'Romance', 'Science Fiction', 'Action']
for i in range(len(genre_types)):
tfidfname = genre_types[i]+'-tfidf.pkl'
tfidf = joblib.load(tfidfname)
temp = tfidf.transform(plot[0])
modelname = genre_types[i]+'-model.picket'
classifier_f = open(modelname, "rb")
model = pickle.load(classifier_f)
classifier_f.close()
if (model.predict(temp)[0]==1):
genres.append(genre_types[i])
print(genres)
|
20c1964462ff6f46dba9a156d736daa3df2178d9 | Macrichie/python | /general/re/match.start match.end match.re.pattern match.string.py | 594 | 3.515625 | 4 |
In [14]: pattern = "find me"
In [15]: text = "i am in between find me end"
In [16]: match = re.search(pattern, text)
In [17]: match.start()
Out[17]: 16
In [18]: match.end()
Out[18]: 23
In [19]: match.re
Out[19]: re.compile(r'find me', re.UNICODE)
In [20]: match.re.pattern
Out[20]: 'find me'
In [22]: match.string
Out[22]: 'i am in between find me end'
In [23]: print("found %s in %s from %d to %d match is %s" % (match.re.pattern, match.string, match.start(), match.end(), text[match.start():match.end()]))
found find me in i am in between find me end from 16 to 23 match is find me
|
ea5ba396a4d6d6f698009e654846745708b9e4e8 | johnehunt/python-covid-data-analysis | /scikitlearn_data_prediction/merge_data_files.py | 2,387 | 3.59375 | 4 | import pandas as pd
# UK Gov Covid data downloaded on 20th Oct 2021
COVID_DATA = 'covid_data_overview_2021-10-20.csv'
# Data from the 19th Oct 2021 - only covers 2020 - so want to predict 2021 behaviour
MOBILITY_CHANGE = '2020_GB_Region_Mobility_Report_2021-10-19.csv'
# Load the UK Covid overview data
print(f'Loading - {COVID_DATA}')
df1 = pd.read_csv(COVID_DATA)
# Drop columns that don't provide any additional data
df1.drop(['areaCode',
'areaName',
'areaType',
'newPeopleVaccinatedFirstDoseByPublishDate',
'newPeopleVaccinatedSecondDoseByPublishDate'],
axis='columns',
inplace=True)
# Set the date column to be a datetime column
df1['date'] = pd.to_datetime(df1['date'])
# Sort the rows into ascending date order
df1.sort_values(by=["date"], ignore_index=True, inplace=True)
# Extract 2021 data for use in testing classifiers and save to file
date_mask_2021 = (df1['date'] >= '2021-01-01') & (df1['date'] <= '2021-12-31')
df_2021 = df1.loc[date_mask_2021]
df_2021.to_csv('covid_data_2021_only.csv', index=False)
# Want to select 2020-02-15 to the 2020-12-31 in terms of dates
# Set up a mask to indicate the date selection for 2020 and 2021
date_mask = (df1['date'] >= '2020-02-15') & (df1['date'] <= '2020-12-31')
# Select all the rows that meet the mask search criteria
df1 = df1.loc[date_mask]
# Replace missing values with zeros for hospitalCases
df1['hospitalCases'] = df1['hospitalCases'].fillna(0)
df1['newAdmissions'] = df1['newAdmissions'].fillna(0)
print(f'Loading - {MOBILITY_CHANGE}')
# Load the google Mobility data for the UK
df2 = pd.read_csv(MOBILITY_CHANGE, low_memory=False)
# Drop columns that don't provide any additional data
df2.drop(['country_region_code',
'country_region',
'sub_region_1',
'sub_region_2',
'metro_area',
'iso_3166_2_code',
'census_fips_code',
'place_id'],
axis='columns',
inplace=True)
df2['date'] = pd.to_datetime(df2['date'])
df2.rename(columns={'retail_and_recreation_percent_change_from_baseline': 'retail_and_recreation_change'}, inplace=True)
# Pick up the first 322 rows
df2 = df2.head(321)
# Can now concatenate them together into a single dateset
df3 = pd.merge(df1, df2, on='date')
print('Writing merged_covid_data.csv file')
df3.to_csv("merged_covid_data.csv", index=False)
|
b763c1f00360f50874b7c0565f4f64de8f386e5f | BaoCaiH/Daily_Coding_Problem | /Python/2019_05_02_Problem_107_Print_Binary_Tree_Level_Wise.py | 1,627 | 4.0625 | 4 | #!/usr/bin/env python
# coding: utf-8
"""2019 May 2nd - Daily_Coding_Problem #107."""
# <markdown>
# ## 2019 May 2nd - Daily_Coding_Problem #107
#
# Problem: Print the nodes in a binary tree level-wise.
# For example, the following should print 1, 2, 3, 4, 5.
#
# ` 1
# / \
# 2 3
# / \
# 4 5`
# %%
class Node:
"""Node class for a binary tree."""
def __init__(self, value, left=None, right=None):
"""Initialize the node."""
self.value = value
self.left = left
self.right = right
def deconstruct(self, level='@'):
"""Deconstruct the binary tree into a string."""
sub = []
if self.left:
sub = sub + self.left.deconstruct(level + '@')
if self.right:
sub = sub + self.right.deconstruct(level + '@')
return [level] + [self.value] + sub
def printLevelWise(self):
"""Print the binary tree level-wise."""
treeInString = self.deconstruct()
layers = {}
for e in treeInString:
try:
if '@' in e:
count = e.count('@')
else:
if count not in layers:
layers[count] = []
layers[count].append(e)
except TypeError:
if count not in layers:
layers[count] = []
layers[count].append(e)
printing = []
for value in layers.values():
printing = printing + value
return printing
# %%
node1 = Node(1, Node('2'), Node(3, Node(4), Node(5)))
# %%
node1.printLevelWise()
|
b9978f1676fd697c353ff3b16677509c05120f9d | priyankakumbha/python | /day3/test14.py | 270 | 3.75 | 4 | # a = input("enter some thing")
# print(a)
un = input("enter username:")
pw = input("enter password:")
if un != 'lara':
print('username is incorrect')
if pw != '123':
print('password is incorrect')
if un == 'lara' and pw == '123':
print('login success')
|
714765685fd79f538e55308d32eb0caa5b5b05d5 | jekhokie/scriptbox | /python--learnings/coding-practice/integer_float_division.py | 265 | 3.96875 | 4 | #!/usr/bin/env python
#
# Print integer and floating point division results.
#
if __name__ == '__main__':
a = int(input())
b = int(input())
int_divide = a // b
float_divide = float(a) / float(b)
print(int_divide)
print("%f" % float_divide)
|
4f94f71319218cf04b3ea22fe7d205192611afb1 | hzrg/songqin_course | /python_code/字符串格式化/C_跨行字符串格式化.py | 207 | 3.546875 | 4 | # -*- coding:utf-8 -*-
vs = [('Jack',8756),('Patrick',10000)]
# 跨行字符串,用3个引号
fs = '''
%s salary: %d $
%s salary: %d $
'''
print(fs % (vs[0][0], vs[0][1], vs[1][0], vs[1][1]))
|
603ce91dbde68ecfbf970eb87f21d944fa92814d | ankeoderij/vbtl-dodona | /sequentie 11.py | 298 | 3.515625 | 4 | lengte = float(input("Geef de lengte van de muur (in m): "))
hoogte = float(input("Geef de hoogte van de muur (in m): "))
aantal_breedtes = (lengte + 0.519) // 0.52
aantal_rollen = (aantal_breedtes * hoogte + 9.999) // 10
print("Minimumaantal te kopen rollen:", aantal_rollen)
|
6ea44e5d0d0bc8774ea93423586088372177c6e8 | raghavsaboo/data-structures | /linked_lists/doubly_linked_list.py | 804 | 3.8125 | 4 | class Node:
def __init__(self, val):
self.data = val
self.next_element = None
self.previous_element = None
class DoublyLinkedList:
def __init__(self):
self.head_node = None
self.tail_node = None
def detect_loop(self):
"""
O(n) Time Complexity
O(1) Space Complexity
"""
current = self.head_node
skip_node = current.next_element
if skip_node == None:
return False
else:
skip_node = skip_node.next_element
while current and skip_node and skip_node.next_element:
if current == skip_node:
return True
current = current.next_element
skip_node = skip_node.next_element.next_element
return False |
14bbdecb6b3278d02abd4f40d790a363376b2e82 | zwakenberg/basictrack_2021_2a | /sessions/week_3/teenage_mutant.py | 384 | 4.03125 | 4 | import turtle
ninja = turtle.Turtle()
screen = turtle.Screen()
screen.title("Teenage Mutant Ninja Turtles")
screen.bgcolor("papayawhip")
for step in range(15):
ninja.forward(50)
ninja.left(120)
# after a complete triangle
print(step, step % 3)
if step % 3 == 2:
ninja.penup()
ninja.forward(100)
ninja.pendown()
screen.exitonclick()
|
e54831ec857c733ca51b6f6adb1c3dcd9f1746ca | vinceparis95/garage | /machineLearning/frameworks/python/elements/objects/list.py | 254 | 4.15625 | 4 |
# create a list
List = []
print(List)
# create a populated list
List = [1, 5, 9]
print(List)
# print elements 0 and 2
# (first and third item)
print(List[0], List[2])
# add elements to the list
List.append(95)
print(List)
List.append(361)
print(List) |
d34c22597b7fac89572b250c2c52f8df7b2dfd5b | acgis-sun00163/gis4107--day02 | /VikySAndBenS/ex6.py | 594 | 3.84375 | 4 | #-------------------------------------------------------------------------------
# Name: Exercise 6
# Purpose: numbers of bears
#
# Author: chengjiaqi sun
#
# Created: 10/09/2019
# Copyright: (c) cheng 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
BDens = 4
squareM = 10000000
squareKM = squareM/ 1000000
BearN = float (BDens * squareKM)
print "When bear density is " + str(BDens) + " bears / sq. km and the area is " + str(squareM) + " sq. m, the probably number of bears is " + str (BearN) |
31e10134d6c2f2e9ab9afd69b7bdcbb914ffcfdb | emurph1/unit5 | /matrixDemo.py | 424 | 4.28125 | 4 | #Emily Murphy
#2017-11-17
#matrixDemo.py - how to create and use matrix (list inside of list)
board = [['a','b','c'],['d','e','f'],['g','h','i']]
def printBoard():
for row in range(0,3):
for col in range(0,3):
print(board[row][col], end = ' ')
print()
printBoard()
row = int(input('Enter row number: '))
col = int(input('Enter column number: '))
board[row-1][col-1] = 'x'
printBoard() |
c34c69c17e43d0c072f2a6c281f64d373b10c0aa | samuelcarvalho1/JogoNIM.py | /NIM.py | 4,284 | 4.125 | 4 | #CAMPEONATO
def campeonato():
rodadas = 1
rodadas_faltantes = 2
while rodadas <= 3:
print()
print(" **** Rodada", rodadas,"de 3", "falta(m) mais", rodadas_faltantes, "****")
print()
partida()
rodadas += 1
rodadas_faltantes -= 1
print()
print('Placar: Você 0 X 3 Computador')
#USUÁRIO ESCOLHE JOGADA
def usuario_escolhe_jogada(n, m):
jogada_valida = False
while not jogada_valida:
usuario_remove = int(input("Quantas peças você gostaria de tirar? "))
if usuario_remove > m or usuario_remove < 1:
print()
print("Oops! Jogada inválida! Tente novamente")
print()
else:
jogada_valida = True
return usuario_remove
#COMPUTADOR ESCOLHE JOGADA
def computador_escolhe_jogada(n, m):
computador_remove = 1
while computador_remove != m:
if (n - computador_remove) % (m+1) == 0:
return computador_remove
else:
computador_remove += 1
return computador_remove
#DEFINIÇÃO DA PARTIDA
def partida():
n=1
m=2
computador_comeca = False
while m >= n:
n = int(input("Quantas peças teremos no jogo? "))
m = int(input("Qual o limite de peças retiradas por jogada?"))
if m >= n:
print()
print("o número de peças por jogada deve ser menor do que o número total de peças")
print()
return(n, m)
#ESTRATÉGIA VENCEDORA
if (n % (m+1)) == 0:
print()
print("Por favor, começe!")
print("Lembre-se: ganha quem tirar a última peça do jogo")
print()
else:
print()
print("O computador... ou melhor: EUUU vou começar!!!")
print("Lembre-se: ganha quem tirar a última peça do jogo")
print()
computador_comeca = True
while n > 0:
if computador_comeca:
computador_remove = computador_escolhe_jogada(n, m)
n -= computador_remove
print()
if computador_remove == 1:
print("O computador tirou uma peça")
if n > 0:
print("Agora restarm", n, "peças")
print()
else:
print("Agora restarm Zero peças e você perdeu, porque não há mais peças para tirar")
else:
print("O computador tirou", computador_remove, "peças")
if n > 0:
print("Agora restarm", n, "peças")
print()
else:
print("Agora restarm Zero peças e você perdeu porque não há mais peças para tirar")
computador_comeca = False
else:
usuario_remove = usuario_escolhe_jogada(n, m)
n -= usuario_remove
print()
if usuario_remove == 1:
print("Você tirou uma peça")
print("Agora restarm", n, "peças")
else:
print("Você tirou", usuario_remove, "peças")
if n > 0:
print("Agora restarm", n, "peças")
else:
print("Agora restarm Zero peças e você ganhou")
computador_comeca = True
#BOAS VINDAS E INÍCIO
print("Bem vindo ao jogo do NIM!")
print()
print("GANHA QUEM TIRAR A ÚLTIMA PEÇA DO JOGO")
print()
print("ESCOLHA:")
print("1 - para jogar uma partida isolada")
print("2 - para jogar um campeonato")
print()
tipodejogo = int(input("Você escolhe 1 ou 2? "))
while tipodejogo != 1 and tipodejogo !=2:
print()
tipodejogo = int(input("Você escolhe 1 ou 2? "))
if tipodejogo == 1:
print()
print("Você escolheu jogar uma partida isolada!")
print()
partida()
else:
print()
print("Você escolheu um campeonato!")
print()
campeonato()
|
ed169fdb9762326ca5c8334409805ef951b8cbf1 | DeekshaNarang/python | /class obj implementation.py | 290 | 3.703125 | 4 | class Student:
def __init__(self):
self.name=" "
self.rollno="0"
def __init__(self,name,rollno):
self.name=name
self.rollno=rollno
def printValues(self):
print(self.name)
print(self.rollno)
S1=Student("abc","123")
S1.printValues() |
6cdabadccce9924c981fdced4c2ad13f6527a449 | upc-projects/tsp-genetic-algorithm | /server/city.py | 1,083 | 4.15625 | 4 | import numpy as np
# This is the class that represents a city with a name and (x,y) coordinates.
class City:
"""
Represents a city to visit for the traveler salesman into the map
Attributes
----------
name: str
The name of the city
x: int
The horizontal coordinate into the map for the city
x: int
The vertical coordinate into the map for the city
"""
def __init__(self, name: str, x: float, y: float):
self.name = name
self.x = x
self.y = y
def calculateDistance(self, endCity):
'''
Method used to calculate the euclidean distance between this and another city
Parameters
----------
endCity : City
The end city
'''
xDistance = abs(self.x - endCity.x)
yDistance = abs(self.y - endCity.y)
distance = np.sqrt((xDistance ** 2) + (yDistance ** 2))
return distance
def __repr__(self):
# Mapper for the City object
return self.name + " (" + str(self.x) + "," + str(self.y) + ")"
|
866706f2ab2766861704df5df02a3f2846f0e353 | fadedge13/prg-105 | /12.1.py | 368 | 4.09375 | 4 | def main():
number(int(input('How many monkeys are jumping on the bed?')))
def number(times):
count = 0
while count < times:
print(times, ' times the monkeys fell of the bed')
print(times, ' time the mother called the doctor')
times -= 1
print(times, 'number of monkeys still jumping on the bed? \n\n')
main()
|
0e21106c733bd9b2cbc8ea817d997aa49e109840 | umerdar/Python | /house_of_trees/basics/functions.py | 309 | 3.578125 | 4 | def hows_the_parrot():
print("WAT")
# hows_the_parrot()
def lumberjack(name):
if name.lower() == 'umer':
print("Umer's a lumberjack and he's the man.")
else:
print("{} sleeps all night and works all day!".format(name))
lumberjack("sleepy")
def counter(count):
print("Hi " * count)
counter(3)
|
a71a9b891fbae1600bf02e4b92489ebe63f43acf | JoniNoct/python-laboratory | /Lab3/func.py | 1,956 | 3.609375 | 4 | import re
def is_one_symbol(start_str):
return bool(re.match(r"^\S$", start_str))
def is_integer(start_str):
return bool(re.match(r"^[+-]?\d+$", start_str))
def is_negative_integer(start_str):
return bool(re.match(r"^[-]?\d+$", start_str))
def is_positive_integer(start_str):
return bool(re.match(r"^[+]?\d+$", start_str))
def is_float(start_str):
return bool(re.match(r"^[+-]?\d+\.?\d*$", start_str))
def int_Validator(prop_str="", type_of=""):
temp_int = input(prop_str)
if type_of == "+":
while not is_positive_integer(temp_int):
temp_int = input("Введіть ціле додатнє число: ")
elif type_of == "-":
while not is_negative_integer(temp_int):
temp_int = input("Введіть ціле від'ємне число: ")
else:
while not is_integer(temp_int):
temp_int = input("Введіть ціле число: ")
return int(temp_int)
def one_symbol(prop_str=""):
temp_symbol = input(prop_str)
while not is_one_symbol(temp_symbol):
temp_symbol = input("Введіть один символ: ")
return temp_symbol
def float_Validator(prop_str=""):
temp_float = input(prop_str)
while not is_float(temp_float):
temp_float = input(prop_str)
return float(temp_float)
def setChoice():
print("Ви би хотіли розпочати знову?\n1) так\n2) ні")
i = 1
j = 1
while i == 1:
c = int_Validator()
if c == 1:
print("Починаэмо спочатку")
i += 1
elif c == 2:
print("До побачення")
i += 1
j += 1
else:
print("У вас є можливість обрати лише з 2 пунктів")
return j
def welcome(a):
print("Лабораторна робота №%d Майструк Ілля №6\nДоброго дня" %(a))
|
7fe5d9cc487317d3ff1429e57b09e52bd9bbf3b6 | aman-singh7/training.computerscience.algorithms-datastructures | /01-algorithm-design-and-techniques/2_algorithmic_warmup/fibonacci_sum_last_digit.py | 1,029 | 3.875 | 4 | #Last Digit of the Sum of Fibonacci Numbers:
#Problem Introduction:
#The goal in this problem is to find the last digit of a sum of the first n Fibonacci numbers.
import sys
from fibonacci_huge import get_fibonacci_huge
def fibonacci_sum_naive(n):
if n <= 1:
return n
previous = 0
current = 1
sum = 1
for _ in range(n - 1):
previous, current = current, previous + current
sum += current
return sum % 10
# O(n)?
# Sum(F(n)) = F(n+2) - 1 for n > 3
# I proved it by induction:
# n = 4: Sum(F(4)) = 7 = 8 - 1 = F(6) - 1
# Let's assume Sum(F(n)) = F(n + 2) - 1 and let's prove that Sum(F(n + 1)) = F(n + 3) - 1
# Sum(F(n + 1)) = Sum(F(n)) + F(n + 1) = F(n + 2) - 1 + F(n + 1) = F(n + 3) - 1
def fibonacci_sum(n, m):
return((get_fibonacci_huge(n + 2, m) + m - 1) % m)
if __name__ == '__main__':
input = sys.stdin.read()
n = int(input)
print(fibonacci_sum(n, 10))
for i in range(n):
assert(fibonacci_sum_naive(i) == fibonacci_sum(i, 10)) |
945138709d1e187471d3b34b161a6acd3610ecd5 | Leandro1391/learn-python | /leccion02/personAge.py | 395 | 3.9375 | 4 | age = int(input(f'Input your age: '))
if (age >= 20 and age < 30) or (age >= 30 and age < 40):
print(f'Dentro de rango (20\'s) o (30\'s)')
# if (age >= 20 and age < 30):
# print('Dentro de los 20\'s')
# elif (age >= 30 and age < 40):
# print('Dentro de los 30\'s')
# else:
# print('Out of range')
else:
print('No está dentro de los 20\'s ni 30\'s') |
a46367163f4f40bd0def22719ada088a1c019f9e | jalexvig/algos_datastructures | /string_search/aho_corasick.py | 2,398 | 3.859375 | 4 | """
Search for patterns in text.
Summary:
1. Construct a [trie](https://en.wikipedia.org/wiki/Trie) of the patterns.
2. Recursively determine fail states by looking at parent's fail state.
3. Use trie to create DFA with non-matches following to fail states.
Characteristics:
* `m` = length of all patterns -- O(m) incurred when building the trie
* `n` = length of search text
* `z` = number matches
Worst Time: O(m + n + z)
Other:
* This is KMP extended to multiple patterns.
"""
from collections import deque
class Node:
def __init__(self):
self.paths = {}
self.out = []
self.fail = None
def __contains__(self, item):
return item in self.paths
def __getitem__(self, item):
return self.paths[item]
def construct_trie(*patterns: list):
root = Node()
for pattern in patterns:
node = root
for c in pattern:
node = node.paths.setdefault(c, Node())
node.out.append(pattern)
return root
def update_failed_states(root: Node):
"""Mark fail states for all nodes in graph."""
q = deque()
for node_level_1 in root.paths.values():
node_level_1.fail = root
q.append(node_level_1)
while q:
node_parent = q.popleft()
for char, node_child in node_parent.paths.items():
node_fail = node_parent.fail
# fail node is node of maximal suffix for node_child
while node_fail and char not in node_fail:
node_fail = node_fail.fail
node_child.fail = node_fail[char] if node_fail else root
# this maximal suffix may be word
node_child.out += node_child.fail.out
q.append(node_child)
def find(root: Node, text: str):
"""Find instances of patterns defined by root in a string."""
res = []
node = root
for c in text:
while node and c not in node:
node = node.fail
# No suffix exists... skip this character
if not node:
node = root
continue
node = node[c]
if node.out:
res += node.out
return res
if __name__ == '__main__':
patterns = ['a', 'abc', 'bcd', 'abcdef', 'cdefg']
text = 'eaabcdabcdefg'
root = construct_trie(*patterns)
update_failed_states(root)
print(*find(root, text))
|
2676849b33f9426c2683c995a96502662ea2e7bc | iamrishap/PythonBits | /InterviewBits/hashing/copy-list.py | 1,978 | 4.125 | 4 | """
A linked list is given such that each node contains an additional random pointer which could point to any node in
the list or NULL.
Return a deep copy of the list.
Example
Given list
1 -> 2 -> 3
with random pointers going from
1 -> 3
2 -> 1
3 -> 1
You should return a deep copy of the list. The returned answer should not contain the same node as the original list,
but a copy of them. The pointers in the returned list should not link to any node in the original input list.
"""
# There are 2 approaches to solving this problem.
# Approach 1 : Using hashmap.
# Use a hashmap to store the mapping from oldListNode to the newListNode.
# Whenever you encounter a new node in the oldListNode (either via random pointer or through the next pointer ),
# create the newListNode, store the mapping. and update the next and random pointers of the newListNode
# using the mapping from the hashmap.
# Approach 2 : Using 2 traversals of the list.
# Step 1: create a new node for each existing node and join them together eg: A->B->C will be A->A’->B->B’->C->C’
# Step2: copy the random links: for each new node n’, n’.random = n.random.next
# Step3: detach the list: basically n.next = n.next.next; n’.next = n’.next.next
# Definition for singly-linked list with a random pointer.
class RandomListNode:
def __init__(self, x):
self.label = x
self.next = None
self.random = None
class Solution:
# @param head, a RandomListNode
# @return a RandomListNode
def copyRandomList(self, head):
if head == None:
return None
done = {}
cur = head
while cur is not None:
done[cur] = RandomListNode(cur.label)
cur = cur.next
for (k, v) in done.iteritems():
new_node = v
new_node.next = done[k.next] if k.next in done else None
new_node.random = done[k.random] if k.random in done else None
return done[head]
|
296a7bfe4936869d43f8e2720e3f01ce98c4611e | CodingHaHa/PythonBase | /02Python基本语法/11编码/01编码.py | 325 | 3.734375 | 4 | #在win上不能以r模式打开,但是在Linux上就可以
# f = open("txt.txt","r")
#解决中文乱码,添加,encoding="utf8")
# f = open("txt.txt","r",encoding="utf8")
# print(f.read())
# print("中国馆")
# print(["中国馆"])
s = "中国"
print(type(s))
print(len(s))
s = u"中国"
print(type(s))
print(len(s)) |
8960a1747859414cd4e7bc80cc1c0a8531531163 | christ134/mean-stack-dev | /ICTA_CALICUT/python/largest.py | 577 | 4.21875 | 4 | # num1=int(input("Enter first number "))
# num2=int(input("Enter second number "))
# num3=int(input("Enter third number "))
# if(num1<num2):
# l=num2
# else:
# l=num1
# if(num3<l):
# l=l
# else:
# l=num3
# print("largest is: ",l)
def largest(x,y,z):
if(num1<num2):
l=num2
else:
l=num1
if(num3<l):
l=l
else:
l=num3
return l
num1=int(input("Enter first number "))
num2=int(input("Enter second number "))
num3=int(input("Enter third number "))
lr=largest(num1,num2,num3)
print("Largest is: ",lr)
|
845c6495347c77893b67f2fd675667a1ba17d2e7 | cfw123/pylearn | /basePython/08_objectOriented/hm_05_initMeth.py | 209 | 3.59375 | 4 | class Cat:
def __init__(self):
print("This is init Method")
self.name = "tom"
def eat(self):
print("%s like eat finsh" % self.name)
tom = Cat()
print(tom)
print(tom.name)
|
640d288868b7bf5e64084103c63fd10ed7a5a6df | shankardengi/DataStructure | /firsthighst_secondhigst_other_approch.py | 1,602 | 4 | 4 | class node:
def __init__(self,data):
self.data = data
self.next = None
@staticmethod
def creat_list(n):
first = None
cur = first
for i in range(n):
data = int(input("Enter Data to list:"))
nodes = node(data)
if first == None:
first = nodes
cur = first
else:
cur.next = nodes
cur = nodes
return first
@staticmethod
def display(first):
cur = first
if first == None:
print("List is empty")
else :
while cur != None:
print(f"list data is {cur.data}")
cur = cur.next
@staticmethod
def first_second_hig_method(first):
if first == None:
print("list is empty")
else:
cur = first
if first.data>first.next.data:
fh = first
sh = first.next
else:
fh = first.next
sh = first
cur = first.next.next
while cur != None:
if cur.data > fh.data:
sh = fh
fh = cur
elif cur.data > sh.data:
sh = cur
cur = cur.next
return (fh,sh)
if __name__ == "__main__":
n = int(input("Enter size of list:"))
first = node.creat_list(n)
node.display(first)
fh,sh = node.first_second_hig_method(first)
print(f"first highst data is {fh.data} \n second highst data is {sh.data} \n")
|
e693d1ec61872e689fd55f85ae2605a73894e043 | Apm96/Ejercicios_Secuenciales_Condicionales | /ejercicios_condicionales.py | 8,836 | 4.0625 | 4 | # 1 Hacer un algoritmo que calcule el total a pagar por la compra de
# camisas. Si se compran tres camisas o mas se aplica un descuento
# del 30% sobre el total de la compra y si son menos de tres camisas
# un descuento del 10%.
valorCamisas = int(input("Digite el valor de las camisetas a comprar "))
numCamisas = int(input("Digite numero de camisetas a comprar "))
montototal = 0
if (numCamisas >= 3):
montototal = (valorCamisas * numCamisas) * 0.7
else:
montototal = (valorCamisas * numCamisas) * 0.9
print(f"El total a pagar por la compra de las camisas es ${montototal:,}")
# 2 En un supermercado se hace una promoción, mediante la cual el
# cliente obtiene un descuento dependiendo de un número que se
# escoge al azar. Si el número escogido es menor que 74 el descuento
# es del 15% sobre el total de la compra, si es mayor o igual a 74 el
# descuento es del 20%. Obtener cuanto dinero se le descuenta
numero = int(input("Digite el numero escogido al azar "))
valorCompra = int(input("Digite el valor de la compra "))
montototal = 0
descuento = 0
if (numero < 74):
montototal = valorCompra * 0.85
descuento = valorCompra * 0.15
else:
montototal = valorCompra * 0.8
descuento = valorCompra * 0.2
print(f"El total a pagar por la compra es ${montototal:,} \n" +
f"El valor descontado es ${descuento:,}")
# 3 Una compañía de seguros está abriendo un departamento de
# finanzas y estableció un programa para captar clientes, que conssite
# en lo siguiente: Si el monto por el que se efectúa la fianza es menor
# que $50.000 la cuota a pagar será por el 3% del monto, y si el monto
# es mayor que $50.000 la cuota a pagar será el 2% del monto. La
# afianzadora desea determinar cual será la cuota que debe pagar al
# cliente.
finanza = int(input("Digite el monto de la finanza "))
cuota = 0
if (finanza < 50000):
cuota = finanza * 0.03
else:
cuota = finanza * 0.02
print(f"El total valor de la cuota que debe pagar el cliente es ${cuota:,}")
# 4 Una fábrica ha sido sometida a un programa de control de
# contaminación para lo cual se efectúa una revisión de los puntos de
# contaminación generados por la fábrica. El programa de control de
# contaminación consiste en medir los puntos que emite la fábrica en
# cinco días de una semana y si el promedio es superior a los 170
# puntos entonces tendrá la sanción de parar su producción por una
# semana y una multa del 50% de las ganancias diarias cuando no se
# detiene la producción. Si el promedio obtenido de puntos es de 170 o
# menos entonces no tendrá ni sanción ni multa. El dueño de la fábrica
# desea saber cuanto dinero perderá después de ser sometido a la
# revisión
p1 = int(input("Digite los puntos del dia 1 "))
p2 = int(input("Digite los puntos del dia 2 "))
p3 = int(input("Digite los puntos del dia 3 "))
p4 = int(input("Digite los puntos del dia 4 "))
p5 = int(input("Digite los puntos del dia 5 "))
valorTotalSemana = int(input("Digite el valor de las ganancias de la semana "))
promedio = (p1 + p2 + p3 + p4 + p5) / 5
perdida = 0
if (promedio > 170):
perdida = valorTotalSemana * 0.5
print(f"El valor que descontara tras la revision es ${perdida:,}")
# 5 Una persona se encuentra con un problema de comprar un automóvil
# o un terreno, los cuales cuestan exactamente lo mismo. Sabe que
# mientras el automóvil se devalúa, con el terreno sucede lo contrario.
# Esta persona comprará el automóvil si al cabo de tres años la
# devaluación de este no es mayor que la mitad del incremento del
# valor del terreno. Ayúdale a esta pesona a determinar si debe o no
# comprar el automóvil.
valor = int(input("Digite el valor del terreno y el auto "))
PorceAuto = float(input("Digite el porcentaje de devaluacion del auto "))
PorceTerreno = float(input("Digite el porcentaje de valorizacion del terreno "))
ValorAutoDevaluado = (valor * (PorceAuto / 100) * 3)
ValorTerrenoAvaluado = (valor * (PorceTerreno / 100) * 3)
if (ValorAutoDevaluado <= (ValorTerrenoAvaluado / 2)):
print(f"Si comprara el auto porque el valor de la devaluacion del auto: ${ValorAutoDevaluado:,} \n" +
f"es menor que la mitad del incremento del terreno: ${(ValorTerrenoAvaluado / 2):,}")
else:
print(f"No comprara el auto porque el valor de la devaluacion del auto: ${ValorAutoDevaluado:,} \n" +
f"es mayor que la mitad del incremento del terreno: ${(ValorTerrenoAvaluado / 2):,}")
# 6 En una fábrica de computadoras se planea ofrecer a los clientes un
# descuento que dependerá del número de computadoreas que
# compre. Si las computadoras son menos de cinco se les dará un 10%
# de descuento sobre el total de la compra; si el número de
# computadoras es mayor o igual a cinco pero menos de diez se le
# otorga un 20% de descuento; y si son 10 o más se les da un 40%. El
# precio de cada computadora es de $11.000.
numcomputadora = int(input("Digite el numero de computadoras a comprar "))
descuento = 0
if (numcomputadora < 5):
descuento = numcomputadora * 11000 * 0.1
print(f"El valor del descuento es ${descuento:,}")
elif (numcomputadora >= 5 and numcomputadora < 10):
descuento = numcomputadora * 11000 * 0.2
print(f"El valor del descuento es ${descuento:,}")
else:
descuento = numcomputadora * 11000 * 0.4
print(f"El valor del descuento es ${descuento:,}")
# 7 Un proveedor de estéreos ofrece un descuento del 10% sobre el
# precio sin IVA, de algún aparato si este cuesta $2000 o más. Además,
# independientemente de esto, ofrece un 5% de descuento si la marca
# es NOSY. Determinar cuanto pagará, con IVA incluido, un cliente
# cualquiera por la compra de su aparato. IVA es del 16%
valorAparato = float(input("Digite el valor del aparato "))
marca = input("Digite el nombre de la marca (NOSY, SONY, LG, OTRA) ")
descuento = 0
total = 0
if (valorAparato >= 2000):
descuento = valorAparato * 0.1
if (marca == "NOSY"):
total = ((valorAparato - descuento) * 0.95) + (valorAparato * 0.16)
else:
total = (valorAparato - descuento) + (valorAparato * 0.16)
print(f"El valor total a pagar por el cliente es ${total:,}")
# 8 Una empresa quiere hacer una compra de varias piezas de la misma
# clase a una fábrica de refacciones. La empresa, dependiendo del
# monto total de la compra, decidirá que hacer para pagar al fabricante.
# Si el monto total de la compra excede de $500.000 la empresa tendrá
# la capacidad de invertir de su propio dinero un 55% del monto de la
# compra, pedir prestado al banco un 30% y el resto lo pagará
# solicitando un crédito al fabricante. Si el monto total de la compra no
# excede de $500.00 la empresa tendrá capacidad de invertir de su
# propio dinero un 70% y el restante 30% lo pagará solicitando crédito
# al fabricante. El fabricante cobra por concepto de interes un 20%
# sobre la cantidad que se le pague a crédito. Obtener la cantidad a
# inverir, valor del préstamo, valor del crédito y los intereses.
valorCompra = float(input("Digite el valor de la compra "))
cantidadInvertir = 0
prestamo = 0
credito = 0
intereses = 0
if (valorCompra > 500000):
cantidadInvertir = (valorCompra * 0.55)
prestamo = (valorCompra * 0.3)
credito = (valorCompra * 0.15)
intereses = (credito * 0.2) + credito
else:
cantidadInvertir = (valorCompra * 0.7)
credito = (valorCompra * 0.3)
intereses = (credito * 0.2) + credito
print(f"La cantidad a invertir es ${cantidadInvertir:,} \n" +
f"El valor del prestamo es ${prestamo:,}\n"
f"El valor del credito es ${credito:,}\n"
f"El valor de los intereses es ${intereses:,}")
# 9 Leer 2 números; si son iguales que lo multiplique, si el primero es
# mayor que el segundo que los reste y sino que los sume.
num1 = float(input("Digite el 1 numero "))
num2 = float(input("Digite el 2 numero "))
resultado = 0
if (num1 == num2):
resultado = num1 * num2
elif (num1 > num2):
resultado = num1 - num2
else:
resultado = num1 + num2
print(f"El resultado de la operacion es {resultado:,}")
# 10 Leer tres números diferentes e imprimir el número mayor de los
# tres
num1 = float(input("Digite el 1 numero "))
num2 = float(input("Digite el 2 numero "))
num3 = float(input("Digite el 3 numero "))
if ((num1 == num2 or num1 == num3) or (num2 == num3 or num2 == num1)):
print("Los numeros deben ser diferentes")
elif (num1 > num2 and num1 > num3):
print(f"El numero {num1:,} es el mayor")
elif (num2 > num1 and num2 > num3):
print(f"El numero {num2:,} es el mayor")
elif (num3 > num2 and num3 > num1):
print(f"El numero {num3:,} es el mayor")
|
fbc6259a223a30ccfbd67be4ec0501a9c9689fa8 | david3de/CruzHacks-x-SWE-Pre-Hackathon-Python-Workshop | /numbers.py | 208 | 3.890625 | 4 | # Basic int and float arithmetic
x, y = 27, 13
sum = x + y
diff = x - y
prod = x * y
quot = x / y
mod = x % y
print('Sum: %d, Difference: %d, Product: %d, Quotient: %d'
% (sum, diff, prod, quot))
|
53d57ef73b508e589bc0e27022ab9e06eb1febca | Mkurtz424/n00bc0d3r | /Projects/CodingBat/List-2/List-2 count_evens Mike.py | 188 | 3.828125 | 4 | def count_evens(nums):
evencount = 0
x = 0
while x < len(nums):
if nums[x] % 2 == 0:
evencount = evencount + 1
x = x + 1
else:
x = x + 1
return evencount
|
0c007e12530793ac89e4b93e660be15feb9a2a12 | nadaAlqahtani/Images-Processing | /Pillow.py | 1,406 | 3.75 | 4 | from PIL import Image
img = Image.open(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\1.jpg")
print(img.format)
print(img.mode)
print(img.size)
#resize image
small_img = img.resize((200,300))
small_img.save(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\resize_img_small.jpg")
img.thumbnail((200,300))
img.save(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\resize_img_small_thumbnail.jpg")
print(img.size)
#make image larger
'''
you can't use thumbnail to resize image to larger than original image.
'''
large_img = img.resize((1500,900))
large_img.save(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\resize_img_large.jpg")
print(large_img.size)
#crop image
cropped_img = img.crop((0, 0, 300, 300))
cropped_img.save(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\crop_img.jpg")
print(cropped_img.size)
#copy part from one image to another
img1 = Image.open(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\1.jpg")
img2 = Image.open(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\2.png")
print(img1.size)
print(img2.size)
img2.thumbnail((150,200))
img1_copy = img1.copy()
img1_copy.paste(img2, (100, 100))
img1_copy.save(r"C:\Users\nadaa\Python Project\Courses\Image Processing Spyder\copy_img.jpg")
|
602c47513c32317e3480ca64e76f49026542ae63 | MychalCampos/Udacity_CS101_Lesson4 | /add_page_to_index.py | 938 | 3.515625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Jul 01 22:14:46 2015
# Define a procedure, add_page_to_index,
# that takes three inputs:
# - index
# - url (String)
# - content (String)
# It should update the index to include
# all of the word occurences found in the
# page content by adding the url to the
# word's associated url list.
@author: Mychal
"""
index = []
def add_to_index(index, keyword, url):
for entry in index:
if entry[0] == keyword:
entry[1].append(url)
return
index.append([keyword, [url]])
def add_page_to_index(index, url, content):
words = content.split()
for i in words:
add_to_index(index, i, url)
add_page_to_index(index, 'fake.text', "This is a test")
print index
# >>> [['This', ['fake.text']], ['is', ['fake.text']], ['a', ['fake.text']],
# >>> ['test',['fake.text']]]
add_page_to_index(index, 'real.test', "This is not a test")
print index |
16b905142b1e0f6eaf7e0685f18bdcd7365c9d96 | WeiChienHsu/Coursera_DS_Algorithm_HW | /Algorithmic_ToolBox/Week 3/covering_segments/covering_segments.py | 722 | 3.6875 | 4 | # Uses python3
import sys
from collections import namedtuple
Segment = namedtuple('Segment', 'start end')
def optimal_points(segments):
seg_text = segments
points = []
inx = segments[0][1]
a = 0
for i, j in segments:
if inx < i:
points.append(inx)
inx = j
if inx > i and inx > j:
inx = j
# print(i, j, inx)
points.append(inx)
return(points)
if __name__ == '__main__':
k = sys.stdin.read()
n, *data = map(int, k.split())
segments = sorted(list(map(lambda x: Segment(x[0], x[1]), zip(data[::2], data[1::2]))))
points = optimal_points(segments)
print(len(points))
for p in points:
print(p, end=' ')
|
2be1c4381a7080c3177292f991d3829864f76843 | raunakshakya/PythonPractice | /Classes & Objects/08_multiple_inheritance.py | 864 | 4.4375 | 4 | # https://www.javatpoint.com/multiple-inheritance-in-python
"""
Multiple Inheritance allows us to inherit multiple parent classes. We can derive a child class from more than one base
(parent) classes. The multi-derived class inherits the properties of all the base classes.
"""
class First(object):
def __init__(self):
super(First, self).__init__()
print("first")
class Second(object):
def __init__(self):
super(Second, self).__init__()
print("second")
class Third(Second, First):
def __init__(self):
"""
The super() method is most commonly used with __init__ function in base class. This is usually the only place
where we need to do some things in a child then complete the initialization in the parent.
"""
super(Third, self).__init__()
print("third")
Third()
|
0c88e664f178607a97d6791cc3968941400f2b6c | jacobpad/cs-hash-tables | /applications/01_lookup_table/lookup_table.py | 1,125 | 3.65625 | 4 | # Add required imports
import random
import math
# Add non-required imports
import time
def slowfun_too_slow(x, y):
v = math.pow(x, y)
v = math.factorial(v)
v //= x + y
v %= 982451653
return v
# Gotta have webster
webster = {}
def slowfun(x, y):
"""
Rewrite slowfun_too_slow() in here so that the program produces the same
output, but completes quickly instead of taking ages to run.
"""
if (x, y) not in webster:
webster[x, y] = slowfun_too_slow(x, y)
return webster[x, y]
##############################################################################
# Do not modify below this line!
# I'm ignoring that instruction above ^^
start = time.time()
# I'll leave this alone
for i in range(50000):
x = random.randrange(2, 14)
y = random.randrange(3, 6)
print(f"{i}: {x},{y}: {slowfun(x, y)}")
# Again, I'm adding code in the forbidden area
end = time.time()
total = end - start
print(f"Time it took to run (seconds): {total:.2f}")
#######################################
# Time it took to run (seconds): 3.07 #
#######################################
|
3054900cd89e800d30bc76910a2b427dd8fdeee5 | chandanadasarii/CrackingTheCodingInterview | /CrackingTheCodingInterview/Stacks/minium.py | 711 | 3.6875 | 4 | class minStack:
__values = list()
__minval = list()
def push(self, data):
self.__values.append(data)
minval = self.getmin()
if minval and data < minval:
self.__push_min(data)
def __push_min(self, data):
self.__minval.append(data)
def peek(self):
return self.__values[-1]
def __pop_min(self):
return self.__minval.pop()
def pop(self):
val = self.__values.pop()
if val == self.getmin():
self.__pop_min()
def getmin(self):
if len(self.__minval) == 0:
return None
return self.__minval[-1]
ms = minStack()
ms.push(10)
ms.push(20)
ms.push(30)
ms.push(5) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.