blob_id string | repo_name string | path string | length_bytes int64 | score float64 | int_score int64 | text string |
|---|---|---|---|---|---|---|
6c31abcce8c523fd07f4b1fb7e6be1a395b6f72c | bradysalz/Laverna-Viewer | /parser/notebooktree.py | 3,852 | 3.5 | 4 | from parser.notebook import Notebook
class NotebookTree():
"""A NotebookTree represents our Laverna notebook structure.
Each node in tree is a Notebook. We initialize it as a strucutre
containing a root node with a blank Notebook and a no parentId."""
def __init__(self, notebook_list=None):
self._root = Notebook()
self._root.id = '0'
if notebook_list is not None:
for notebook in notebook_list:
self.add_notebook(notebook)
def add_child_notebook(self, new_notebook):
"""Adds a notebook to the tree.
Recurses through the tree to find parent. Returns -1 if parent
not found OR if notebook is marked as 'trashed'."""
if new_notebook.trash != 0:
return
parent = self._find_parent_nb(self._root, new_notebook.parentId)
if parent is not None:
parent.add_child(new_notebook)
else:
return -1
def add_note(self, new_note):
"""Recursively searches the tree to find the notebook to add the
note to. Returns -1 if no parent notebook is found or note
is marked as 'trashed'."""
if new_note.trash != 0:
return
par_id = new_note.notebookId
parent_notebook = self._find_parent_nb(self._root, par_id)
if parent_notebook is not None:
parent_notebook.notes.append(new_note)
else:
return -1
def get_note(self, nb_id, note_id):
par_nb = self._find_parent_nb(self.get_root_nb(), nb_id)
for note in par_nb.notes:
if note.id == note_id:
return note
return None
def print_tree(self):
return self._build_tree_string(self._root, 0)
def get_all_notes(self):
return self._get_all_notes_helper(self.get_root_nb())
def _get_all_notes_helper(self, root_nb):
if len(root_nb.get_children()) == 0:
return root_nb.get_notes()
arr = []
for nb in root_nb.get_children():
arr += self._get_all_notes_helper(nb)
return arr
def order_by_create(self):
"""Orders all notebooks and notes by create date"""
self._order_all_by_created(self._root)
def _order_all_by_created(self, nb):
"""Recursive helper to order all notebooks by create date"""
if nb.notes:
nb.notes = sorted(nb.notes, key=lambda x: x.created, reverse=True)
if nb.children:
nb.children = sorted(nb.children, key=lambda x: x.created)
for child in nb.children:
self._order_all_by_created(child)
def _build_tree_string(self, curr_nb, depth):
"""Prints out the NotebokTree.
Recurses over all notebooks (NB:) and notes. Should only be used for
debugging."""
spacing = depth * ' '
print(spacing + '|-- ' + curr_nb.name)
for nt in curr_nb.notes:
spacing = (depth + 1) * ' '
print(spacing + '> ' + nt.title)
if curr_nb.children == []:
pass
else:
for nb in curr_nb.children:
self._build_tree_string(nb, depth + 1)
def get_root_nb(self):
return self._root
def _find_parent_nb(self, curr_notebook, new_nb_par_id):
"""Recurses through the NotebookTree to find the parent
notebook, else returns None."""
if curr_notebook.id == new_nb_par_id:
return curr_notebook
elif curr_notebook.children == []:
return None
else:
for child in curr_notebook.children:
recurse = self._find_parent_nb(child, new_nb_par_id)
if recurse is not None:
return recurse
def __repr__(self):
return "<NotebookTree: {0}>".format(self._root)
|
9c935745876373f99296f9b703b2691c2bda5d8c | penguinsss/Project | /面向对象/面向对象基本语法.py | 3,473 | 4.21875 | 4 | class Fruits: # 类名大驼峰
def __init__(self, color, name): # 使用场景:初始化
self.color = color
self.name = name
def zd(self): # self对应的实参是 调用该方法的对象(由解释器自动设置); 使用场景:想在方法中使用对象自己的属性
print('我长大啦')
print("我是:%s" % self.name)
def __str__(self):
return '颜色:%s,名字:%s' % (self.color, self.name)
apple = Fruits('红红', '苹果')
apple.taste = '香甜可口' # 属性:首次赋值会定义,再次赋值修改; 这种定义属性方式叫动态绑定
print("%s的%s" % (apple.color, apple.name))
print(apple.zd())
banana = Fruits('黄色', '香蕉')
print(banana.zd())
print(apple)
# _xxx_(self):这类方法会在特定情况下自动调用,人称 '魔法方法'
# ● __init__(self):对象一创建完自动调用,用于初始化处理
# ● __str__(self):自定义对象的打印;
# 必须有返回值,返回的内容会代替默认的对象打印(默认打印对象内存地址)
# ● __del__(self):对象销毁前执行;
# 1> 回收资源; 关闭文件、数据库连接等;
# 2> 用户观察对象的删除情况(进行分析);
# ★对象 局部变量 方法结束时销毁 ,执行_del_方法;
# 全局变量 文件执行结束时 ,执行_del_方法;
# ● __dict__(self):python编译器内部会将私有属性变量转为 '_类名和私有属性名'的字符串拼接,然后进行操作,所以在外部直接进行修改是改不了的
# ● 查看继承链(方法查询顺序) 多继承:
# 1> 属性: 类对象._mro_
# 2> 方法: 类对象.mro()
# ● __all__: 该变量可以控制 from 模块 import * 导入的内容
# 如果不把功能放到__all__变量列表中,那么通过 ' from 模块 import * '导入时,是不会被导入的
# ● __name__: ❀ 无论采用哪种导入方式,都会将模块中的代码全部执行一遍
# 当主动执行模块文件时,__name__变量为__name__
# 当模块被其他文件按导入时,__name__变量为 模块名
# if __name__ == '__main__':
# 测试代码
class Dog:
def __init__(self):
self.file = open('123.txt', 'w')
print(self.file)
def __del__(self):
print('对象销毁前回收')
self.file.close() # 对象删除前将文件关闭,避免内存泄漏
# python中 数字(int、float)、字符串(str)、列表(list)、函数(function) 都是对象
tuple1 = (1,)
list1 = list(tuple1) # 强转 / 对象调用
print(type(list1))
# 私有属性: __xx
# 只能在类内部使用
# 在类外部使用会报错
# 即使强制在类外部赋值,私有属性值也不会修改
class Dog:
def __init__(self):
self.file = open('123.txt', 'w')
self.__count = 1
def __del__(self):
print('对象销毁前回收')
self.file.close() # 对象删除前将文件关闭,避免内存泄漏(不及时释放从而造成内存空间的浪费)
d = Dog()
d._Dog__count = 4
print(Dog.mro())
# 私有方法:仅在类内部使用
|
0f970945158abfa4462cef8a21ff8ad80fbb30b4 | bwotten/starsandswag | /db2.py | 934 | 3.515625 | 4 | #Simple script to get the idea for connecting to the db
import psycopg2
import getpass
# Run this command to start ssh tunneling
# ssh -L 63333:localhost:5432 zpfallon@db.cs.wm.edu
password = getpass.getpass('Password: ')
params = {
'database': 'group3_stars',
'user': 'zpfallon',
'password': password,
'host': 'localhost',
'port': 63333
}
#Open the connection
conn = psycopg2.connect(**params)
#Open the cursor
cur = conn.cursor()
#latitude taken from input in the real program
latitude = 40
co_lat = 90 - latitude
#Simple select statement and then fetch to get results
SQL = "select x,y,y from stars where (%s+dec) > 0 and mag < 5.5;"
cur.execute(SQL,(co_lat,))
for x in cur.fetchall():
print ("x= "+str(float(x[0]))+", y= "+str(float(x[1]))+", z= "+str(float(x[2])))
cur.execute("select * from const_names;")
for x in cur.fetchall():
print (str(x[0])+","+str(x[1])+"\n")
#Close everything out
cur.close()
conn.close()
|
16be585bcd3d0499413a5ab8007448486376a270 | samadhan563/Python-Programs | /Logical Program/CheckInputTypes.py | 458 | 4.28125 | 4 | # Program for ASCII Value pattern
'''
Author : Samadhan Gaikwad.
Software Developer
Location: Pune.
'''
char=(input("Enter char : charactor"))
# char2=(input("Enter char1 : "))
if char>='A' and char <='Z':
print(char, "is a upper case charactor.")
elif char>='a' and char <='z':
print(char, "is a lower case charactor.")
elif char>='0' and char <='9':
print(char, "is a digit charactor.")
else:
print(char, "is a special charactor.")
|
1118c7cd44d7d9e6314479424f6ddce5b84f7814 | yugant6/100-days-of-code | /day-12/strings.py | 356 | 3.9375 | 4 | a = "Hello, World!"
print(a[0])
print(a[1])
print(a[2:5]) # from second character to 4th character
b = " Hello, World! "
print(b.strip())
print(len(a))
print(len(b))
print(a.lower())
print(a.upper())
print(a.replace("H", "J"))
print(a.split(","))
print("Enter your name:")
x = input()
print("Hello, " + x)
y = input("Enter your name \n")
print(y)
|
81cb52843367b21e7c713f5e6d5bbc71217cdaa9 | danoliveiradev/PythonExercicios | /ex039.py | 570 | 3.703125 | 4 | from datetime import date
anoNasc = int(input('Digite seu ano de nascimento com 4 digitos: '))
idade = date.today().year - anoNasc
if idade < 18:
print('\033[32mVocê não completou 18 anos! Vai poder se alistar daqui a {} anos.'.format(18 - idade))
elif idade == 18:
print('\033[33mVocê completou 18 anos! Procure um junta militar para se alistar.')
elif idade > 18:
print('\033[31mVocê tem mais de 18 anos e passou do período de alistamento a {} anos.'.format(idade - 18))
print('CASO NÃO TENHA SE ALISTADO, PROCURE A JUNTA MILITAR MAIS PRÓXIMA!') |
31cc5a2e481301104bbde979f720284b5b625440 | juanarmond/HackerRankCode | /Count Triplets.py | 2,331 | 3.9375 | 4 | # You are given an array and you need to find number of tripets of indices such that the elements at those indices are in geometric progression for a given common ratio and .
# For example, . If , we have and at indices and .
# Function Description
# Complete the countTriplets function in the editor below. It should return the number of triplets forming a geometric progression for a given as an integer.
# countTriplets has the following parameter(s):
# arr: an array of integers
# r: an integer, the common ratio
# Input Format
# The first line contains two space-separated integers and , the size of and the common ratio.
# The next line contains space-seperated integers .
# Constraints
# Output Format
# Return the count of triplets that form a geometric progression.
# Sample Input 0
# 4 2
# 1 2 2 4
# Sample Output 0
# 2
# Explanation 0
# There are triplets in satisfying our criteria, whose indices are and
# Sample Input 1
# 6 3
# 1 3 9 9 27 81
# Sample Output 1
# 6
# Explanation 1
# The triplets satisfying are index , , , , and .
# Sample Input 2
# 5 5
# 1 5 5 25 125
# Sample Output 2
# 4
# Explanation 2
# The triplets satisfying are index , , , .
#!/bin/python3
import math
import os
import random
import re
import sys
from itertools import combinations
from collections import defaultdict
# Complete the countTriplets function below.
def countTriplets(arr, r):
# print(arr, r)
common_ratio=r
ans_list=[]
for subset in list(combinations(arr, 3)):
list_set=list(subset)
if (list_set[0]*common_ratio) == list_set[1] and (list_set[1]*common_ratio) == list_set[2]:
ans_list.append(list_set)
# print(ans_list)
return len(ans_list)
# Very Fast
# def countTriplets(arr, r):
# second = defaultdict(int)
# third = defaultdict(int)
# c = 0 #count
# for num in arr:
# c += third[num]
# third[num*r] += second[num]
# second[num*r] += 1
# # print(num, c, third[num], second[num])
# return c
if __name__ == '__main__':
fptr = open(os.environ['OUTPUT_PATH'], 'w')
nr = input().rstrip().split()
n = int(nr[0])
r = int(nr[1])
arr = list(map(int, input().rstrip().split()))
ans = countTriplets(arr, r)
fptr.write(str(ans) + '\n')
fptr.close()
|
d465964ca43fbfe940ccce4fe5807167fd9e7aa6 | yunaranyancat/personal_projects | /project_7/caesarCipher.py | 2,385 | 4.21875 | 4 | import argparse
def caesar_cipher(filename_to_read,filename_to_append,mode):
with open(filename_to_read, "r+") as thefile:
lines = thefile.readlines()
if (mode=="encrypt"):
with open(filename_to_append, 'w+') as theEncryptedFile:
for each_line in lines:
encrypted_text = encrypt_text(each_line)
theEncryptedFile.write(encrypted_text)
elif (mode=="decrypt"):
with open(filename_to_append, 'w+') as theDecryptedFile:
for each_line in lines:
decrypted_text = decrypt_text(each_line)
theDecryptedFile.write(decrypted_text)
def encrypt_text(text):
words = ''
for each_line in text:
if (32 < ord(each_line) < 123):
words += chr(ord(each_line)+3)
else:
words += each_line
return words
def decrypt_text(text):
words = ''
for each_line in text:
if (32 < (ord(each_line)-3) < 123):
words += chr(ord(each_line)-3)
else:
words += each_line
return words
def main():
parser = argparse.ArgumentParser()
parser.add_argument("filename", help="The file you would like to encrypt/decrypt.", type=str)
group = parser.add_mutually_exclusive_group()
group.add_argument("-d", "--decrypt", action="store_true")
group.add_argument("-e", "--encrypt", action="store_true")
parser.add_argument("-r", "--result", help="Specify filename for the encryption/decryption",type=str)
args = parser.parse_args()
#initialization
getFileName = args.filename
getResultFile = args.filename
mode = "NOMODE"
if args.result:
getResultFile = args.result
if not(args.decrypt or args.encrypt):
parser.error("Please select one of the options, -e for encryption, -d for decryption")
else:
if args.decrypt:
mode = "decrypt"
print("Decrypting file..")
caesar_cipher(getFileName,getResultFile,mode)
anyKey = input("Decryption finished.. Press any key to exit.")
elif args.encrypt:
mode = "encrypt"
print("Encrypting file...")
caesar_cipher(getFileName,getResultFile,mode)
anyKey = input("Encryption finished.. Press any key to exit.")
if __name__ == '__main__':
main()
|
93ad9c33f5797f7c585ed94ba199ac13c9198216 | Jean-Bi/100DaysOfCodePython | /Day 13/day-13-3-exercise/main.py | 578 | 4.4375 | 4 | for number in range(1, 101):
#if number % 3 == 0 or number % 5 == 0: -> "FizzBuzz" has to be displayed when both the conditions are true, not only one of them
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
#if number % 3 == 0: -> elif has to be used as only one condition should be fulfilled at max
elif number % 3 == 0:
print("Fizz")
#if number % 5 == 0: -> elif has to be used as only one condition should be fulfilled at max
elif number % 5 == 0:
print("Buzz")
else:
#print([number]) -> [] don't have to be displayed
print(number) |
9b8b117f3a8fd5ccc76ff499dbf7af9f082a93d7 | smiroshnikov/telegramBotforMiningControl | /linxacad/basics/bmi.py | 1,481 | 4.25 | 4 | #!bin/python
def validate_input(input):
for e in input:
if not e.isdigit():
print("only digit input allowed :")
return False
else:
return True
def get_user_data():
height = input("Whats your height :? (inches or meters) ")
while not validate_input(height):
print("Please use a numeric value...")
height = input("Whats your height :? (inches or meters) ")
validate_input(height)
weight = input("Whats your weight :? (pounds or kilograms) ")
unit = input("Are your measurements in metric or imperial units ? ").lower().strip()
return weight, height, unit, stop_flag
def calculate_bmi(weight, height, unit="metric"):
if unit == "metric":
bmi = (float(weight / (height) ** 2))
else:
bmi = 703 * (float(weight / (height ** 2)))
return bmi
stop_flag = False
while not stop_flag:
height, weight, unit, stop_flag = get_user_data()
if stop_flag:
break
if (unit.lower().startswith("q") or
weight.lower().startswith("q") or
height.lower().startswith("q")):
print("Quiting ....")
break
elif unit.startswith("i"):
print(f"Your BMI is {calculate_bmi(height=height, weight=weight, unit='imperial')}")
elif unit.startswith("m"):
print(f"Your BMI is {calculate_bmi(height=height, weight=weight, unit='metric')}")
else:
print(f"Unsupported format {unit}, FU!")
|
b51be2cfcae5c1fd31e2e2cd945b119ab87b4e4a | Rup-Royofficial/Codeforces_solutions | /codeforces_AIsitrated_contest.py | 100 | 4.125 | 4 |
for i in range(3):
n = str(input())
if n=="Is it rated?":
print("NO")
|
4ab7b5da9ffc099c7b89a4eabe7fb112d066af68 | astrid23/cmp2035-homework | /04/pythonworkshop.py | 658 | 3.765625 | 4 | A = 100
B = 300
C = STRING
print type class (object):
"""docstring for """
def __init__(self, arg):
super(, self).__init__()
self.arg = arg
print C + ""
print str(A)
# data structures
# list
listofwww = [" different type of variables"]
print listofwww[1]
print listofwww [0:2]
print len(listofwww)
for album in listofwww
print "" + albumn
albumscores ={
"a" :0
}
print albumscores["]"]
def keyword(nameofbbb):
score = []
for album in albumnames
albumscore
socres.append()
return socres
print albumscore([albumnames])
#datacamp intro to python of data science
numpy
import numpy as numpy
import matplotlib
x = np.linspace(0, 2*np, 100)
plt. |
4fd18ba2ade552e1a5708d36e582248280969270 | sid-verma/Coding-Interview-Questions | /DP-Recursion-Bktracking/ClimbStairs.py | 629 | 4 | 4 | # You are climbing a stair case. It takes n steps to reach to the top.
# Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?
# Note: Given n will be a positive integer.
# Key step: Write out the patterns for n = 1,2,3... and you will see it is a Fibonacci Series.
# Thus you have to simply iterate upto n, and add the previous digit to the current one.
# TC: O(n)
# SC: O(1)
class Solution(object):
def climbStairs(self, n):
"""
:type n: int
:rtype: int
"""
a = b = 1
for _ in xrange(n):
a, b = b, a+b
return a |
311bb4f3e2f7a7f488b46df96df158f22e914131 | alissabaigent/Election-Analysis-Alissa-Baigent | /Python_practice.py | 1,960 | 4.28125 | 4 | counties = ["Arapahoe", "Denver", "Jefferson"]
if counties[1] == 'Denver':
print(counties[1])
if counties[2] != 'Jefferson':
print(counties[2])
if "El Paso" in counties:
print("El Paso is in the list of counties")
else:
print( "El Paso is not in the list of counties")
if "Arapahoe" or "El Paso" in counties:
print("Arapahoe or El Paso are in the list of counties")
else:
print("Arapahoe and El Paso are not in the list of counties")
for county in counties:
print(county)
numbers = [0, 1, 2, 3, 4]
for num in range(5):
print(num)
for i in range(len(counties)):
print(counties[i])
counties_dict = {"Arapahoe": 422829, "Denver": 463353, "Jefferson": 432438}
for county in counties_dict:
print(county)
for county in counties_dict:
print(counties_dict.get(county))
voting_data = [{"county":"Arapahoe", "registered_voters": 422829},
{"county":"Denver", "registered_voters": 463353},
{"county":"Jefferson", "registered_voters": 432438}]
for county_dict in voting_data:
for value in county_dict.values():
print(value)
my_votes = int(input("How many votes did you get in the election? "))
total_votes = int(input("What is the total votes in the election? "))
print(f"I received {my_votes / total_votes * 100}% of the total votes.")
counties_dict = {"Arapahoe": 369237, "Denver":413229, "Jefferson": 390222}
for county, voters in counties_dict.items():
print(county + " county has " + str(voters) + " registered voters.")
candidate_votes = int(input("How many votes did the candidate get in the election? "))
total_votes = int(input("What is the total number of votes in the election? "))
message_to_candidate = (
f"You received {candidate_votes} number of votes. "
f"The total number of votes in the election was {total_votes}. "
f"You received {candidate_votes / total_votes * 100}% of the total votes.")
print(message_to_candidate)
import csv
dir(csv)
|
85b781baf80568e981973ca5cd7902c82ba092bb | lucasdmazon/CursoVideo_Python | /pacote-download/Exercicios/Desafio02.py | 698 | 3.78125 | 4 | var = input("{}Digite algo: {}".format('\033[1;31m', '\033[m'))
print('{}O tipo primitivo desse valor é: {}'.format('\033[1;35m', type(var)))
print('Somente Espaços: {}'.format(var.isspace()))
print('Numerico: {}'.format(var.isnumeric()))
print('Alfabetico: {}'.format(var.isalpha()))
print('Alfanumerico: {}'.format(var.isalnum()))
print('Maiusculas: {}'.format(var.isupper()))
print('Minusculas: {}'.format(var.islower()))
print('Capitalizada: {}'.format(var.istitle()))
print('Decimal: {}'.format(var.isdecimal()))
print('Ascii: {}'.format(var.isascii()))
print('Digito: {}'.format(var.isdigit()))
print('Dentifier: {}'.format(var.isidentifier()))
print('Table {}'.format(var.isprintable()))
|
e3c486c81f16a40e954ad036aaf4ccab6ba720f6 | seweissman/advent_of_code_2020 | /day21/day21.py | 5,656 | 3.578125 | 4 | """
You reach the train's last stop and the closest you can get to your vacation island without getting wet. There aren't even any boats here, but nothing can stop you now: you build a raft. You just need a few days' worth of food for your journey.
You don't speak the local language, so you can't read any ingredients lists. However, sometimes, allergens are listed in a language you do understand. You should be able to use this information to determine which ingredient contains which allergen and work out which foods are safe to take with you on your trip.
You start by compiling a list of foods (your puzzle input), one food per line. Each line includes that food's ingredients list followed by some or all of the allergens the food contains.
Each allergen is found in exactly one ingredient. Each ingredient contains zero or one allergen. Allergens aren't always marked; when they're listed (as in (contains nuts, shellfish) after an ingredients list), the ingredient that contains each listed allergen will be somewhere in the corresponding ingredients list. However, even if an allergen isn't listed, the ingredient that contains that allergen could still be present: maybe they forgot to label it, or maybe it was labeled in a language you don't know.
For example, consider the following list of foods:
mxmxvkd kfcds sqjhc nhms (contains dairy, fish)
trh fvjkl sbzzf mxmxvkd (contains dairy)
sqjhc fvjkl (contains soy)
sqjhc mxmxvkd sbzzf (contains fish)
could be fish = sqjcc mxmxvkd
could be dairy = mxmxvkd
could be soy = sqjhc fvjkl
mxmxvkd kfcds sqjhc nhms (contains dairy, fish)
trh fvjkl sbzzf mxmxvkd (contains dairy)
sqjhc fvjkl (contains soy)
sqjhc mxmxvkd sbzzf (contains fish)
The first food in the list has four ingredients (written in a language you don't understand): mxmxvkd, kfcds, sqjhc, and nhms. While the food might contain other allergens, a few allergens the food definitely contains are listed afterward: dairy and fish.
The first step is to determine which ingredients can't possibly contain any of the allergens in any food in your list. In the above example, none of the ingredients kfcds, nhms, sbzzf, or trh can contain an allergen. Counting the number of times any of these ingredients appear in any ingredients list produces 5: they all appear once each except sbzzf, which appears twice.
Determine which ingredients cannot possibly contain any of the allergens in your list. How many times do any of those ingredients appear?
--- Part Two ---
Now that you've isolated the inert ingredients, you should have enough information to figure out which ingredient contains which allergen.
In the above example:
mxmxvkd contains dairy.
sqjhc contains fish.
fvjkl contains soy.
Arrange the ingredients alphabetically by their allergen and separate them by commas to produce your canonical dangerous ingredient list. (There should not be any spaces in your canonical dangerous ingredient list.) In the above example, this would be mxmxvkd,sqjhc,fvjkl.
Time to stock your raft with supplies. What is your canonical dangerous ingredient list?
"""
from collections import defaultdict
if __name__ == "__main__":
with open("input.txt") as input:
lines = input.readlines()
lines = [line.strip() for line in lines]
all_ingredients = set()
all_allergens = set()
food_ingredients = []
food_allergens = []
# Parse input
for line in lines:
ing_str, all_str = line.split(" (contains ")
all_str = all_str[:-1]
ingredients = set(ing_str.split(" "))
allergens = set(all_str.split(", "))
all_ingredients.update(ingredients)
food_ingredients.append(ingredients)
food_allergens.append(allergens)
all_allergens.update(allergens)
could_have_allergen = defaultdict(lambda: all_ingredients)
# Since only one ingredient can have each allergen the only ingredients that could have an allergen
# are in the intersection of the ingredients lists that list that allergen
for i, ingredients_set in enumerate(food_ingredients):
for allergen in food_allergens[i]:
could_have_allergen[allergen] = could_have_allergen[allergen].intersection(ingredients_set)
# Find all ingredients that aren't in an allergen set
remaining_ingredents = all_ingredients
for allergen, ingredient_set in could_have_allergen.items():
remaining_ingredents -= ingredient_set
# Find number of appearances for ingredients without allergens
appearance_ct = 0
for ingredient in remaining_ingredents:
for ingredient_set in food_ingredients:
if ingredient in ingredient_set:
appearance_ct += 1
print("Answer1:", appearance_ct)
# Part 2
# Find ingredient - allergen assignments
# If only one ingredient could have a given allergen we remove that ingredient from all other sets
# Repeat until we (hopefully) have one ingredient in each allergen set
assigned = set()
while assigned != all_allergens:
for allergen in could_have_allergen:
ingredient_set = could_have_allergen[allergen]
if len(ingredient_set) == 1:
ingredient = list(ingredient_set)[0]
assigned.add(allergen)
for other_allergen in could_have_allergen:
if allergen != other_allergen:
could_have_allergen[other_allergen] -= {ingredient}
# Sort ingredients by allergen alphabetically
ingredients = [list(could_have_allergen[allergen])[0] for allergen in sorted(could_have_allergen)]
print("Answer2:", ",".join(ingredients)) |
89adf53e265f6d0e5804ee013ec38dee60628ca0 | PdxCodeGuild/class_redmage | /code/cory/Python/lab20_credit_card_validation/credit_card_validation.py | 1,033 | 3.984375 | 4 | # Setup main function
def credit_checker(card_number):
card_list = list(card_number) # convert string to list of ints
last_digit = card_list.pop(-1) # slice off and save digit
card_list.reverse() # reverse card list
for i in range(len(card_list)):
card_list[i] = int(card_list[i]) # change string to int
for i in range(0,(len(card_list)),2): # double every other element
card_list[i] *= 2
for i in range(len(card_list)): # subtract nine from numbers over nine
if card_list[i] > 9:
card_list[i] -= 9
sum_variable = sum(card_list) # sum of numbers in a list
sum_variable = list(str(sum_variable)) # converting sum variable into string list
if sum_variable[-1] == last_digit: # checking to see if second digit of sum
return True
return False
input_string = "4556737586899855"
print(credit_checker(input_string))
# Take the second digit of that sum.
#If that matches the check digit, the whole card number is valid. |
7630757e5125133c66aac47d0ec50741cc243670 | gschen/sctu-ds-2020 | /1906101105-石涛/day0225/test03/02.py | 416 | 3.828125 | 4 | # coding=utf-8
# if嵌套
num=int(input('请输入一个数字:'))
if num % 2==0:
if num % 3==0:
print('这个数字既能被2整除,也可以被3整除')
else:
print('这个数字能被2整除,但不能被3整除')
else:
if num % 3==0:
print('这个数字能被3整除,不能被2整除')
else:
print('这个数字既不能被2整除,也不能被3整除')
|
1a8ef6f571133782744603b9925cf810d775d811 | dcryptOG/pytutorial | /2/2.py | 5,840 | 4.40625 | 4 | # 2. Using the Python Interpreter
# 2.1. Invoking the Interpreter
# The Python interpreter is usually installed as /usr/local/bin/python3.7 on those machines where it is available; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:
# python3.7
# to the shell. 1 Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)
# On Windows machines where you have installed from the Microsoft Store, the python3.7 command will be available. If you have the py.exe launcher installed, you can use the py command. See Excursus: Setting environment variables for other ways to launch Python.
# Typing an end-of-file character (Control-D on Unix, Control-Z on Windows) at the primary prompt causes the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command: quit().
# The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that support readline. Perhaps the quickest check to see whether command line editing is supported is typing Control-P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive Input Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.
# The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
# A second way of starting the interpreter is python -c command [arg] ..., which executes the statement(s) in command, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quote command in its entirety with single quotes.
# Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] ..., which executes the source file for module as if you had spelled out its full name on the command line.
# When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script.
# All command line options are described in Command line and environment.
# 2.1.1. Argument Passing
# When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the argv variable in the sys module. You can access this list by executing import sys. The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as '-' (meaning standard input), sys.argv[0] is set to '-'. When -c command is used, sys.argv[0] is set to '-c'. When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.
# 2.1.2. Interactive Mode
# When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs (>>>); for continuation lines it prompts with the secondary prompt, by default three dots (...). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt:
# $ python3.7
# Python 3.7 (default, Sep 16 2015, 09:25:04)
# [GCC 4.8.2] on linux
# Type "help", "copyright", "credits" or "license" for more information.
# >>>
# Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
# >>>
# >>> the_world_is_flat = True
# >>> if the_world_is_flat:
# ... print("Be careful not to fall off!")
# ...
# Be careful not to fall off!
# For more on interactive mode, see Interactive Mode.
# 2.2. The Interpreter and Its Environment
# 2.2.1. Source Code Encoding
# By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of most languages in the world can be used simultaneously in string literals, identifiers and comments — although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
# To declare an encoding other than the default one, a special comment line should be added as the first line of the file. The syntax is as follows:
# # -*- coding: encoding -*-
# where encoding is one of the valid codecs supported by Python.
# For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file should be:
# # -*- coding: cp1252 -*-
# One exception to the first line rule is when the source code starts with a UNIX “shebang” line. In this case, the encoding declaration should be added as the second line of the file. For example:
# #!/usr/bin/env python3
# # -*- coding: cp1252 -*-
# Footnotes
# 1
# On Unix, the Python 3.x interpreter is by default not installed with the executable named python, so that it does not conflict with a simultaneously installed Python 2.x executable.
|
8119dfc230ff8cdb1751ebb6f77af30adcc076a4 | invalidsyntax1/randomize_mafia_telegram | /randomize.py | 1,054 | 3.609375 | 4 | #распределение на 2 команды
from random import randint
def sort_for_two_commands(players: list) -> list:
first_len_players_command = len(players) / 2
first_command = []
while len(players) != first_len_players_command:
index_random_player = randint(0, len(players)-1)
random_player = players[index_random_player]
first_command.append(random_player)
del players[index_random_player]
second_command = players
return first_command, second_command
def mafia_or_no(players_in_command, roles = ["мирный житель","мирный житель","мирный житель","мафия"]):
player_and_role = dict()
for player in players_in_command:
random_index_role = randint(0, len(roles)-1)
player_and_role[player] = roles[random_index_role]
del roles[random_index_role]
return player_and_role
#tests
if __name__ == "__main__":
print(sort_for_two_commands([1,2,3,4,5,6,7,8]))
print(mafia_or_no([856567, 634534, 454534, 354634])) |
dea602c5ef90516037808f65421b2a39712a81c3 | AdamZhouSE/pythonHomework | /Code/CodeRecords/2482/60769/262153.py | 731 | 3.5 | 4 | num = int(input())
for j in range(num):
dividend = list(input())
divisor = int(input())
last = 0
res = ""
for i in dividend:
temp = last * 10 + int(i)
res += str(temp // divisor)
last = temp % divisor
# 处理整数部分结束
if last == 0:
print(eval(res))
continue
# 如果有待处理的小数部分
small = ""
record = [] # 记录出现过的余数
while last != 0 and last not in record:
record.append(last)
last = last * 10
small += str(last // divisor)
last = last % divisor
if last != 0:
small = small[:record.index(last)]+"("+small[record.index(last):]+")"
print(str(eval(res))+"."+small) |
7d11d86bfbdf0210ed19ce8f844dfd653e816795 | MCVitzz/AED | /Fraction.py | 1,977 | 3.640625 | 4 | import math
class Fraction:
def __init__(self, num, den):
if not (type(num) is int and type(den) is int):
raise ValueError()
gcd = math.gcd(num, den)
self.den = int(den // gcd)
self.num = int(num // gcd)
def getNum(self):
return self.num
def getDen(self):
return self.den
def __add__(self, other):
gcd = math.gcd(self.den, other.den)
num1 = (gcd // self.den) * self.num
num2 = (gcd // other.den) * other.num
return Fraction(num1 + num2, gcd)
def __sub__(self, other):
gcd = math.gcd(self.den, other.den)
num1 = (gcd // self.den) * self.num
num2 = (gcd // other.den) * other.num
return Fraction(num1 - num2, gcd)
def __mul__(self, other):
den = self.den * other.den
num = self.num * other.num
return Fraction(num, den)
def __truediv__(self, other):
den = self.den * other.num
num = self.num * other.den
return Fraction(num, den)
def get_real(self):
return self.num / self.den
def __gt__(self, other):
return self.get_real() > other.get_real()
def __ge__(self, other):
return self.get_real() >= other.get_real()
def __lt__(self, other):
return self.get_real() < other.get_real()
def __le__(self, other):
return self.get_real() <= other.get_real()
def __ne__(self, other):
return self.get_real() != other.get_real()
def __str__(self):
return str(self.num) + '/' + str(self.den)
def __iadd__(self, other):
frac = self + other
return frac
def __radd__(self, other):
if type(other) is int:
frac = Fraction(other, 1)
return frac + self
raise NotImplementedError()
def __repr__(self):
return 'Numerator: ' + str(self.num) + '\nDenominator: ' + str(self.den)
a = Fraction(1, 2) + 3
print(a) |
a6d386eee5ce79fe241d04aa40321fc84b534abf | Abhishek-IOT/Data_Structures | /DATA_STRUCTURES/DSA Questions/Searching and sorting/Pairdiff.py | 845 | 4.0625 | 4 | """
Find Pair Given Difference
Easy Accuracy: 47.62% Submissions: 16791 Points: 2
Given an unsorted array Arr[] and a number N. You need to write a program to
find if there exists a pair of elements in the array whose difference is N.
Logic=Have two counter and check that the difference is equal or not ,if not then check if greater then
increase j counter else increase i counter.
"""
def pair(arr,size,n):
i,j=0,1
while i<size and j<size:
if i!=j and arr[j]-arr[i]==n:
print("The pair found",arr[i],arr[j])
return True
elif arr[j]-arr[i]<n:
j=j+1
else:
i=i+1
return False
if __name__ == '__main__':
arr=[1, 8, 30, 40, 100]
n=60
m=pair(arr,len(arr),n)
if m==True:
print("Yes")
else:
print("no") |
2477ba014fadb55d1f1a5651c8d62098dccddd08 | Vasilic-Maxim/LeetCode-Problems | /problems/409. Longest Palindrome/1 - Counter.py | 414 | 3.5625 | 4 | from collections import Counter
class Solution:
"""
Time: O(n)
Space: O(1) because there would be 52 or less keys
(lower and upper case chars of English alphabet)
"""
def longestPalindrome(self, string: str) -> int:
div, mod = 0, 0
for count in Counter(string).values():
div = count // 2 * 2
mod = count % 2
return div + 1 if mod else div
|
725c7b6124151f82b5cc3d02033be1d36c7372f1 | withoutwaxaryan/programming-basics | /Python/inheritance.py | 664 | 4.0625 | 4 | # University has some stuff which can be used by both Teachers and Student. THerefore we can use inheritance to reuse code
class University:
def __init__(self, fname, lname):
self.fname = fname
self.lname = lname
def fullname(self):
print(self.fname + ' ' + self.lname)
class Student(University):
pass
class Teacher(University):
def __init__(self, fname, lname, salary):
super().__init__(fname, lname)
self.salary = salary
student_1 = Student('Aryan', 'Gupta')
teacher_1 = Teacher('Shobha', 'Bagai', '1cr')
print(student_1.fname)
print(student_1.lname)
print(teacher_1.lname)
print(teacher_1.salary)
|
9ea3aa699485622c17b8f54c882f3dfddbd895b7 | luizffdemoraes/Python_1Semestre | /AC/Área de um hexágono regular.py | 909 | 4.34375 | 4 | """
Escreva um programa em Python3 que peça o valor do lado de um hexágono regular, calcule e imprima sua área e seu perímetro.
Sabemos que um hexágono regular é o polígono de 6 lados iguais e com todos os ângulos internos iguais entre si.
Sabemos ainda que um hexágono regular de lado L é formado por 6 triângulos equiláteros de lado L,
e que a área de 1 triângulo equilátero de lado L é dada por:
A entrada poderá ser qualquer número real positivo.
Sendo valor 1, 2 e 3 respectivamente os valores do lado, da área e do perímetro do hexágono.
Dica: Usem um print() para cada linha da resposta, não usem o '\n'.
"""
import math
valor1 = float(input())
valor2 = round(6 * valor1 ** 2 * math.pow(3, 1/2) / 4, 20)
valor3 = valor1 * 6
print(f'Lado do hexagono: {valor1} metros,')
print(f'Area: {valor2} metros quadrados,')
print(f'Perimetro: {valor3} metros.') |
009356adfad3179a5ef369df70ec6a284e6faeaa | wallge/interviewTestProblems | /python/fibonacci.py | 6,672 | 4.4375 | 4 | # -*- coding: utf-8 -*-
"""
Created on Sun Nov 1 11:59:44 2015
@author: Geoffrey Wall
usage: python fibonacci.py -n <number of fibonacci numbers to generate>
usage: python fibonacci.py -t <number of fibonacci numbers to generate and test against reference implementation>
"""
#!/usr/bin/python
import sys, math
import numpy as np
# generate the fibonacci sequence the traditional recursive way
def genFibRecursive(n):
if n == 0:
return 0
elif n == 1:
return 1
else:
return genFibRecursive(n-1) + genFibRecursive(n-2)
# generate the fibonacci sequence recursively, but this time using a
# dictionary to store already computed fibonacci numbers
def genFibMemoized(n, memo):
if n == 0:
return 0
elif n == 1:
return 1
else:
##check to see if we have already computed this fibonacci number and stored it in
##our dictionary
if n in memo:
return memo[n]
else:
n_1 = 0
if n-1 in memo:
n_1 = memo[n-1]
else:
n_1 = genFibMemoized(n-1, memo)
n_2 = 0
if n-2 in memo:
n_2 = memo[n-2]
else:
n_2 = genFibMemoized(n-2, memo)
fib = n_1 + n_2
memo[n] = fib
return fib
#generate the fibbonacci sequence looping over fibbonacci's 2 thru n and summing previous values
#this is less expensive in compute time as well as memory consumed compared to the naive recursive formulation
def genFibMemConstrained(n):
if n == 0:
return 0
elif n == 1:
return 1
Fn = 0
FnMinusOne = 1
FnMinusTwo = 0
for i in range(2, n+1):
Fn = FnMinusOne + FnMinusTwo
FnMinusTwo = FnMinusOne
FnMinusOne = Fn
return Fn
#generate the fibbonacci sequence using the linear algebra formulation by exponentiating
#the fibonacci matrix [1, 1; 1, 0] to the n-1th power and returning the 0,0th element of the resultant matrix
#this comes from the difference equation formulation from here:
#https://en.wikipedia.org/wiki/Fibonacci_number#Matrix_form
#note::this runs into precision issues once we get to n = 94
def genFibLinAlg(n):
if n <= 0:
return 0
if n == 1:
return 1
M = np.matrix('1, 1; 1, 0')
M = M.astype(np.uint64)
#exponentiate the matrix to the n-1'th power
F = M**(n-1)
return F[0, 0]
#this method uses the recurrence relation from here:
# https://en.wikipedia.org/wiki/Fibonacci_number#Closed-form_expression
def genFibFast(n):
def _inner(n):
if n == 0:
return (0, 1)
else:
a, b = _inner(n // 2)
c = a * (b * 2 - a)
d = a * a + b * b
if n % 2 == 0:
return (c, d)
else:
return (d, c + d)
return _inner(n)[0]
def genFibGoldenRatio(n):
golden = np.double(1.61803398875)
Fn = (math.pow(golden, n) - math.pow(1 - golden, n)) / math.sqrt(5.0)
return (round(Fn))
#loop over all natural numbers in range [2, n-1] and see if they will divide into n without a remainder
#this is the dumb (obvious) way to do this
def isPrimeNaive(n):
if n < 2:
return False
for i in range(2, n):
if n % i == 0:
return False
return True
def isPrime(n):
#primes are defined as being greater than 1
if n <= 1:
return False
# two and three are prime, return true
elif n <= 3:
return True
#test if divisible by two or three, return false
elif n % 2 == 0 or n % 3 == 0:
return False
#five is the next divisor to check
i = 5
while i * i <= n:
if n % i == 0 or n % (i + 2) == 0:
return False
i = i + 6
#if we pass the above tests, then this is a prime
return True
#this function implements the faster, less naive version of what the
#interview problem is asking for
def generateInterviewProblemResult(n):
myList = []
for i in range(0, n+1):
fib = genFibFast(i)
#method below runs into precision issues
#genFibLinAlg(i)
if fib % 3 == 0:
myList.append('Buzz')
elif fib % 5 == 0:
myList.append('Fizz')
elif isPrime(i):
myList.append('BuzzFizz')
else:
myList.append(fib)
return myList
#this function implements the dumb but simpler reference implementation
#of what the interview problem is asking for
def generateReferenceResult(n):
myList = []
for i in range(0, n+1):
#fib = genFibMemConstrained(i)
fib = genFibMemoized(i, dict())
if fib % 3 == 0:
myList.append('Buzz')
elif fib % 5 == 0:
myList.append('Fizz')
elif isPrimeNaive(i):
myList.append('BuzzFizz')
else:
myList.append(fib)
return myList
def main(argv):
if len(argv) < 2:
print 'usage: python fibonacci.py -n <number of fibonacci numbers to generate>'
print 'usage: python fibonacci.py -t <number of fibonacci numbers to generate and test against reference implementation>'
sys.exit(2)
else:
if argv[0] == '-n':
print generateInterviewProblemResult(int(argv[1]))
elif argv[0] == '-t':
myResult = generateInterviewProblemResult(int(argv[1]))
referenceResult = generateReferenceResult(int(argv[1]))
print myResult
caughtError = False
for i in range(0, len(myResult)):
if myResult[i] != referenceResult[i]:
print "Reference Implementation does not match my implementation for n = " + str(i)
print "Reference value = " + str(referenceResult[i])
print "Generated value = " + str(myResult[i])
caughtError = True
if caughtError == False:
print 'Reference implementation matched my implementation for all ' + str(i) + ' Fibonacci numbers!'
else:
print 'usage: python fibonacci.py -n <number of fibonacci numbers to generate>'
print 'usage: python fibonacci.py -t <number of fibonacci numbers to generate and test against reference implementation>'
if __name__ == "__main__":
main(sys.argv[1:]) |
151c2ac39fa9ce8778a277bec391984c24d063f6 | Poluru-Venkata-Koushik/SIMPLE_PROJECTS | /temp.py | 1,839 | 3.59375 | 4 | from tkinter import messagebox
import xlrd
import random
import tkinter as tk
from PyDictionary import PyDictionary
loc = (r"C:\Users\Hp\Downloads\allword.xls") #change this as per requirement
dict = PyDictionary()
wb = xlrd.open_workbook(loc)
sheet = wb.sheet_by_index(0)
sheet.cell_value(0, 0)
def create_word():
a=sheet.cell_value(random.randint(0,sheet.nrows), 0)
if dict.meaning(a)==NotADirectoryError:
create_word()
else:
return a
a=create_word()
meaning = dict.meaning(a)
print("Word :{}, length :{}".format(a,len(a)-1))
main_e=tk.Tk()
main_e.geometry('400x200')
main_e.resizable(False,False)
main_e.title("WORD GAME BY PVK")
main_head=tk.Label(text='Welcome to PVK WORD GAME')
main_head.place(x=100,y=10)
def on_hint():
if meaning==None:
messagebox.showinfo("Hint", "Load error . Reload")
elif "Noun" in meaning.keys():
messagebox.showinfo("Hint",meaning['Noun'])
elif "Verb" in meaning.keys():
messagebox.showinfo("Hint",meaning['Verb'])
elif "Adjective" in meaning.keys():
messagebox.showinfo("Hint",meaning['Adjective'])
else:
messagebox.showinfo("Hint", "Load error . Reload")
def on_submit():
global a
word=a
print(word)
if word == answer.get():
messagebox.showinfo('PVK',"Hurray ! YOu guessed it")
else:
messagebox.showinfo('PVK',"Try again")
print(answer.get())
lab_1=tk.Label(main_e,text="Answer:")
lab_1.place(x=100,y=50)
lab_2=tk.Label(main_e,text="Clue : Length of word is {}".format(len(a)-1))
lab_2.place(x=100,y=75)
answer=tk.Entry()
answer.place(x=150,y=50)
hint_bx=tk.Button(text='Hint',command=on_hint)
hint_bx.place(x=150,y=100)
sub_bx=tk.Button(text='Submit',command=on_submit)
sub_bx.place(x=200,y=100)
main_e.mainloop() |
fedf8995642dc771864e444787e82bd9376784cf | Omkar02/FAANG | /UnboundedKnapsack.py | 1,936 | 3.84375 | 4 | import __main__ as main
from Helper.TimerLogger import CodeTimeLogging
fileName = main.__file__
fileName = fileName.split('\\')[-1]
CodeTimeLogging(Flag='F', filename=fileName, Tag='Dynamic-Programing', Difficult='Hard')
'''Given a knapsack weight W and a set of n items with certain value
vali and weight wti, we need to calculate minimum amount that could
make up this quantity exactly. This is different from classical Knapsack problem,
here we are allowed to use
---------->unlimited number of instances of an item<---------------.
Examples:
Input : W = 100
val[] = {1, 30}
wt[] = {1, 50}
Output : 100
There are many ways to fill knapsack.
1) 2 instances of 50 unit weight item.
2) 100 instances of 1 unit weight item.
3) 1 instance of 50 unit weight item and 50
instances of 1 unit weight items.
We get maximum value with option 2.
Input : W = 8
val[] = {10, 40, 50, 70}
wt[] = {1, 3, 4, 5}
Output : 110
We get maximum value with one unit of
weight 5 and one unit of weight 3.'''
totalWeight = 100
values = [10, 30, 20]
weight = [5, 10, 15]
def unboundedKnapsack(totalWeight, value, weight):
knapSackValues = [0 for i in range(totalWeight + 1)]
for i in range(totalWeight + 1):
for j in range(len(value)):
if weight[j] <= i:
knapSackValues[i] = max(knapSackValues[i],
knapSackValues[i - weight[j]] + value[j])
print(knapSackValues)
print(knapSackValues[-1])
unboundedKnapsack(totalWeight, values, weight)
# def unboundedKnapsack(W, n, val, wt):
# # dp[i] is going to store maximum
# # value with knapsack capacity i.
# dp= [0 for i in range(W + 1)]
# ans= 0
# # Fill dp[] using above recursive formula
# for i in range(W + 1):
# for j in range(n):
# if (wt[j] <= i):
# dp[i]= max(dp[i], dp[i - wt[j]] + val[j])
# return dp[W]
|
5c1623a75da7d69c1966ca3a2675895627a25600 | ChuixinZeng/PythonStudyCode | /PythonCode-OldBoy/Day1/随堂练习/5_Interaction.py | 1,751 | 4.28125 | 4 | # -*- coding:utf-8 -*-
# Author:Chuixin Zeng
# raw_input 2.x input 3.x
#input 2.x 里输出的结果必须是定义好的变量,不建议用,很多余的语法,忘记他,不要用它
#要求格式化输出为下面的格式
name = input("name:")
age = int(input("age:")) #强制数据类型转换,默认age是string,这里强制转换成int
#打印当前数据类型
print(type(age),type(str(age))) #把int再转换成string
job = input("job:")
salary = input("salary:")
#字符串拼接,+号拼接的方式效率比较低下
#info = '''
#-------- info of ''' + name + ''' -----
#Name:'''+ age +'''
#Age:'''+ job+'''
#Job:''' + job +'''
#Salary:''' + salary
#print(info)
#更简单的字符串拼接方法,使用%s占位符,是string的简写
#下面括号有两个name,第一个name代表info of 后面的%s
#info = '''
#------------- info of %s ---------
#Name:%s
#Age:%s
#Job:%s
#Salary:%s
#''' %(name,name,age,job,salary)
#print(info)
#上面的输出可以定义数据类型,d代表只能接受数据
info1 = '''
------------- info of %s ---------
Name:%s
Age:%d
Job:%s
Salary:%s
''' %(name,name,age,job,salary)
print(info1)
#官方建议用下面这个
info2 = '''
------------- info of {_name} ---------
Name:{_name}
Age:{_age}
Job:{_job}
Salary:{_salary}
''' .format(_name=name,
_age=age,
_job=job,
_salary=salary)
print(info2)
#下面的也可以,但是参数显得不够清晰
#format只有上面和下面这两种格式
info3 = '''
------------- info of {0} ---------
Name:{0}
Age:{1}
Job:{2}
Salary:{3}
''' .format(name,age,job,salary)
print(info3)
# 万恶的+号每出现一次就会在内从中重新开辟一块空间
# PS: 字符串是 %s;整数 %d;浮点数%f
|
5fd5f9bc78d9eb8848f5925603b497a6b561a5f6 | byj9511/Hello-world | /判断列表数字累加和.py | 268 | 3.671875 | 4 | def sum2(list1):
number = len(list1)
list2 = [list1[i] for i in range(number)if type(list1[i])== float or type(list1[i])== int]
#列表中的数为小数或者整数式,进行累加
return sum(list2)
a = [1, 2, 3, 4, 2.41, "a", "b"]
print(sum2(a))
|
7d3c2541393ef9f935939989a4ee61f532535592 | abdullahmehboob20s/Python-learning | /chapter-11-inheritance/5-super.py | 1,087 | 3.90625 | 4 | import os
os.system("cls")
# multiLevel-inheritance
# Parent
class Person:
country = "Pakistan"
city = "Karachi"
gender = "male"
def __init__(self):
print("Intializing Person...\n")
def takeBreath(self):
print("I am breathing...")
# Child
class Employee(Person):
company = "Youtube"
salary = 1000000
def __init__(self):
super().__init__()
print("Intializing Employee...\n")
def getSalary(self):
print(f"Salry is {self.salary}")
def takeBreath(self):
super().takeBreath()
print("I am an employee so, I am breathing also")
# Grand-Child
class Programmer(Employee):
company = "Fiver"
def __init__(self):
super().__init__()
print("Intializing Programmer...\n")
@staticmethod
def getSalary():
print("No salary to programmers")
def takeBreath(self):
super().takeBreath()
print("I am Programmer so, I don't breath")
# p = Person()
# p.takeBreath()
# e = Employee()
# e.takeBreath()
pr = Programmer()
# pr.takeBreath()
|
7e34de6796d430af09f0c47c7be281b8a3878f53 | lavanya-shirur/Computer-Vision | /KMeans.py | 4,252 | 4.21875 | 4 | class KmeansSegmentation:
def segmentation_grey(self, image, k = 2):
"""Performs segmentation of an grey level input image using KMeans algorithm, using the intensity of the pixels as features
takes as input:
image: a grey scale image
return an segemented image
-----------------------------------------------------
Sample implementation for K-means
1. Initialize cluster centers
2. Assign pixels to cluster based on (intensity) proximity to cluster centers
3. While new cluster centers have moved:
1. compute new cluster centers based on the pixels
2. Assign pixels to cluster based on the proximity to new cluster centers
"""
return image
def segmentation_rgb(self, image, k=2):
"""Performs segmentation of a color input image using KMeans algorithm, using the intensity of the pixels (R, G, B)
as features
takes as input:
image: a color image
return an segemented image"""
iterations = 5
print(image.shape)
imageW = image.shape[0]
imageH = image.shape[1]
dataVector = np.ndarray(shape=(imageW * imageH, 5), dtype=float)
pixelClusterAppartenance = np.ndarray(shape=(imageW * imageH), dtype=int)
for y in range(0, imageH):
for x in range(0, imageW):
xy = (x, y)
rgb=image[x,y]
print(rgb)
#rgb = image.getpixel(xy)
dataVector[x + y * imageW, 0] = rgb[0]
dataVector[x + y * imageW, 1] = rgb[1]
dataVector[x + y * imageW, 2] = rgb[2]
dataVector[x + y * imageW, 3] = x
dataVector[x + y * imageW, 4] = y
print("data vector")
print(dataVector)
dataVector_scaled = preprocessing.normalize(dataVector)
minValue = np.amin(dataVector_scaled)
maxValue = np.amax(dataVector_scaled)
centers = np.ndarray(shape=(k,5))
for index, center in enumerate(centers):
centers[index] = np.random.uniform(minValue, maxValue, 5)
print("center")
print(centers[index])
for iteration in range(iterations):
for idx, data in enumerate(dataVector_scaled):
distanceToCenters = np.ndarray(shape=(k))
for index, center in enumerate(centers):
distanceToCenters[index] = euclidean_distances(data.reshape(1, -1), center.reshape(1, -1))
pixelClusterAppartenance[idx] = np.argmin(distanceToCenters)
clusterToCheck = np.arange(k)
clustersEmpty = np.in1d(clusterToCheck, pixelClusterAppartenance)
for index, item in enumerate(clustersEmpty):
if item == False:
pixelClusterAppartenance[np.random.randint(len(pixelClusterAppartenance))] = index
for i in range(k):
dataInCenter = []
for index, item in enumerate(pixelClusterAppartenance):
if item == i:
dataInCenter.append(dataVector_scaled[index])
dataInCenter = np.array(dataInCenter)
centers[i] = np.mean(dataInCenter, axis=0)
print("Centers Iteration num", iteration, ": \n", centers)
for index, item in enumerate(pixelClusterAppartenance):
dataVector[index][0] = int(round(centers[item][0] * 255))
dataVector[index][1] = int(round(centers[item][1] * 255))
dataVector[index][2] = int(round(centers[item][2] * 255))
image = Image.new("RGB", (imageW, imageH))
for y in range(imageH):
for x in range(imageW):
image.putpixel((x, y), (int(dataVector[y * imageW + x][0]),
int(dataVector[y * imageW + x][1]),
int(dataVector[y * imageW + x][2])))
print(type(image))
image = cv2.cvtColor(np.asarray(image), cv2.COLOR_BGR2GRAY)
print(type(image))
return image
|
052e3ed9101f06e9525c169502ee963485674e98 | PullBack993/Python-Fundamentals | /07. Dictionaries - Exercise/08. Company Users.py | 597 | 3.734375 | 4 | command = input()
company_users = {}
while not command == 'End':
company, id = command.split(" -> ")
if company not in company_users:
company_users[company] = [id]
else:
if id in company_users:
command = input()
company_users[company].append(id)
command = input()
sorted_list = []
sorted_company = sorted(company_users.items(), key=lambda x: x[0])
for key, value in sorted_company:
print(f"{key}")
for v in value:
if v not in sorted_list:
sorted_list.append(v)
print(f"-- {v}")
sorted_list.clear()
|
0b34a7942bc398a6c45228f3c7116ecfcce8ce4d | jorien-witjas/python-labs | /python_fundamentals-master/03_more_datatypes/2_lists/03_08_reorder.py | 914 | 3.84375 | 4 | '''
Read in 10 numbers from the user. Place all 10 numbers into an list in the order they were received.
Print out the second number received, followed by the 4th, then the 6th, then the 8th, then the 10th.
Then print out the 9th, 7th, 5th, 3rd, and 1st.
Example input: 1,2,3,4,5,6,7,8,9,10
Example output: 2,4,6,8,10,9,7,5,3,1
first try:
count = 0
x = [10, 21, 3, 43, 15, 87, 7, 811, 9, 10]
for i in x:
if count % 2 == 1:
print(i)
count += 1
count = 10
for i in x:
if count % 2 == 0:
print(i)
count -= 1
'''
# x = [10, 21, 3, 43, 15, 87, 7, 811, 9, 10]
# count = 0
# for i in x:
# if count % 2 == 1:
# print(i, end=" ")
# count += 1
# x.reverse()
# count = 0
# for i in x:
# if count % 2 == 1:
# print(i, end=" ")
# count +=1
#try after some Gilad-input :)
x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
updated_x = x[1::2] + x[-2::-2]
print(updated_x) |
a79bf9fb6882143be4de92fdeb703746134788cd | yaHaart/hometasks | /Module15/03_cells/main.py | 387 | 3.578125 | 4 | cell_list = [3, 0, 6, 2, 12, 3, 2, 6, 9, 7, 6, 55, 14, 16, 1]
bad_cells = []
print('Кол-во клеток: ', len(cell_list))
for i in range(len(cell_list)):
print(f'Эффективность {i + 1} клетки: {cell_list[i]}')
if i > cell_list[i]:
bad_cells.append(cell_list[i])
print('Неподходящие значения: ', bad_cells)
# зачёт! 🚀
|
8926f73f9d11355c06f028b6f276d2bd0ff958bf | Draeriel/Advent-of-Code | /Day2/Part Two.py | 886 | 3.625 | 4 | from itertools import permutations
def preparador(casostest, lista):
fichero = open(casostest, 'r')
fila = []
for linea in fichero:
numeros = []
for j in linea:
try:
j = int(j)
numeros.append(str(j))
except ValueError:
if not j.isdigit():
numeros = "".join(numeros)
fila.append(numeros)
numeros = []
if len(numeros) > 0:
numeros = "".join(numeros)
fila.append(numeros)
lista.append(fila)
fila = []
return lista
def checksum(matrix):
contador = []
for row in matrix:
for posible in permutations(row, 2):
recolector = []
for numeros in posible:
recolector.append(int(numeros))
if recolector[0] % recolector[1] == 0:
print(recolector)
contador.append(int(posible[0])/int(posible[1]))
return sum(contador)
rutaDeAcceso = "casosTest.txt"
lista = []
preparador(rutaDeAcceso, lista)
print(checksum(lista))
|
274ca9658832c197a8f91fccd7b659490f314f97 | thai321/data-structures-alogrithms | /Stacks Queues and Deques/queue.py | 353 | 3.84375 | 4 | class Queue(object):
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def enqueue(self, item):
self.items.insert(0,item)
def dequeue(self):
return self.items.pop()
def size(self):
return len(self.items)
q = Queue()
q.isEmpty()# True
q.enqueue(1)
q.enqueue(2)
q.size()# 2
q.dequeue()# 1
|
79d19230275c01c26ba96f99263b3558973102d0 | andrewonyango/bioinformatics | /1-finding-hidden-messages-in-dna/week1/reverse_complement.py | 317 | 4.3125 | 4 | def reverse_complement(string):
"""
returns the reverse complement of a dna string
string: the original dna string
"""
dna_dict = {"A": "T", "G": "C", "T": "A", "C": "G"}
complement = []
for char in string:
complement.append(dna_dict[char])
return "".join(complement[::-1])
|
8639c01c07a320a2e76d08b2d7e6d2c879a3bb15 | Dragonway/LeetCode | /py/remove_linked_list_elements.py | 762 | 4.09375 | 4 | # Remove all elements from a linked list of integers that have value val.
#
# Example:
#
# Input: 1->2->6->3->4->5->6, val = 6
# Output: 1->2->3->4->5
from typing import Optional
from py.collections.list import ListNode
class Solution:
def remove_elements(self, head: Optional[ListNode], val: int) -> Optional[ListNode]:
new_head = node = None
while head:
_next = head.next
if head.val != val:
if not node:
node = head
node.next = None
new_head = node
else:
node.next = head
node = node.next
node.next = None
head = _next
return new_head
|
5e383a596f1bf14f671a77e0756b259b1efc200f | gaurav-dalvi/codeninja | /python-junk/balance_array.py | 683 | 3.734375 | 4 | def merge(intervals):
intervals = sorted(intervals, key = lambda x: x[0])
print intervals
stack = []
stack.append(intervals[0])
for item in xrange(1, len(intervals)):
stack_elem = stack.pop()
if stack_elem[1] >= intervals[item][0]:
low = min(stack_elem[0], intervals[item][0])
high = max(stack_elem[1], intervals[item][1])
stack.append((low, high))
else:
stack.append(stack_elem)
stack.append(intervals[item])
ans = []
for item in stack:
ans.append(item)
return ans
if __name__ == '__main__':
intervals = [(1,4), (4,5)]
print merge(intervals) |
dfbe6bf9e06278aa4ea0cad505443058ba7a55b9 | fengbaoheng/leetcode | /python/876.middle-of-the-linked-list.py | 913 | 3.71875 | 4 | #
# @lc app=leetcode.cn id=876 lang=python3
#
# [876] 链表的中间结点
#
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
# 快慢指针
def middleNode(self, head: ListNode) -> ListNode:
try:
if head is None:
return None
# 仅有一个节点
if head.next is None:
return head
# 两个节点及以上
low = head
fast = head.next
# 不考虑环形链表,因为环形没有中间节点
while True:
low = low.next
if fast.next is not None and fast.next.next is not None:
fast = fast.next.next
else:
# 快指针到达终点
break
return low
except:
return None
|
3f8f5527a36b2c9fac380b594ff9a8aee804afc6 | ghoshorn/leetcode | /leet01_2.py | 1,349 | 3.6875 | 4 | # encoding: utf8
'''
Two Sum
Given an array of integers, find two numbers such that they add up to a specific target number.
The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.
You may assume that each input would have exactly one solution.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
思路:先排序;再从两头向中间找 O(nlogn)
'''
class Solution:
# @return a tuple, (index1, index2)
def twoSum(self, num, target):
d={}
for i in xrange(len(num)):
if target-num[i] in d:
return(d[target-num[i]]+1,i+1)
d[num[i]]=i
# d={}
# d2={}
# for i in xrange(len(num)):
# if num[i] not in d:
# d[num[i]]=i
# else:
# d2[num[i]]=i
# print d,d2
# for x in num:
# if target-x in d:
# if target-x in d2:
# return(d[x]+1,d2[target-x]+1)
# elif x!=target-x:
# return(d[x]+1,d[target-x]+1)
a=Solution()
print a.twoSum([2,7,11,15],9)
print a.twoSum([3,2,4],6)
print a.twoSum([0,4,3,0],0)
print a.twoSum([3,2,4], 6)
|
30e04f6509927677aabd850a3164cdca1ba3f808 | rroberts1990/Exercism | /python/pangram/pangram.py | 212 | 3.734375 | 4 | import string
def is_pangram(sentence):
alphabet = set(string.ascii_lowercase)
letter_list = set([char.lower() for char in sentence if char.lower() in alphabet])
return len(letter_list) == len(alphabet)
|
f59cb5ab086ff40ce4002f9da69efff2589b3b0b | SupakornNetsuwan/Prepro64 | /test131.py | 435 | 3.734375 | 4 | """Func"""
def func():
"""#2"""
numbers = list(map(float, input().split(" ")))
lookfor = float(input())
findnum = [i for i, x in enumerate(numbers) if x == lookfor]
if findnum:
print("Index: %d" %findnum[-1])
else:
findnum2 = [abs(lookfor - i) for i in numbers]
print("Index:", findnum2.index(min(findnum2)))
print("Number: %.2f" %numbers[findnum2.index(min(findnum2))])
func()
|
61957581321a62fca45c2d3ea6ca8fc1d1942863 | JulianoA28/TrabalhoPratico_TeoricaDaComputacao | /Máquina de Turing/maquina.py | 4,333 | 3.921875 | 4 | '''
TRABALHO PRATICO
GCC108 - Teoria da Computacao
Nome: Juliano Expedito de Andrade Godinho
Turma: 14A
Matricula: 201811302
'''
# Funcao para checar se a fita esta correta!
def checarFita(fita, alfabeto):
for f in fita:
# Se nao pertencer ao alfabeto, retorna False e a letra do alfabeto
if f not in alfabeto:
return False, f
# Caso o alfabeto esteja correto, retorna True e uma string vazia
return True, ''
# Utilizando o sys para abertura do arquivo
import sys
# Uma lista com os estados
# Cada posicao representa um estado que contem um dicionario com as transicoes
# [{}, {}, {}]
estados = []
# Alfabeto de entrada
alfabeto_entrada = []
# Alfabeto da fita
alfabeto_fita = []
# Abrindo o arquivo
f = open(sys.argv[1])
# Leitura do inicio
f.read(3)
# Lendo os estados
while f.read(1) != ',':
# Lendo cada estado e uma virgula
f3 = f.read(3)
# Adicionando um dicionario vazio a lista de estados
estados.append({})
# Leitura apos os estados
f.read(2)
# Lendo o alfabeto de entrada
while f.read(1) != ',':
f2 = f.read(2)
alfabeto_entrada.append(f2[0])
# Leitura apos alfabeto de entrada
f.read(2)
# Lendo o alfabeto da fita
while f.read(1) != '}':
# Lendo uma letra do alfabeto
f1 = f.read(1)
# Adicionando ao alfabeto
alfabeto_fita.append(f1)
# Cria uma chave que corresponde a letra do alfabeto em cada estado na lista de estados
for estado in estados:
estado[f1] = {}
# Leitura apos o alfabeto da fita
f.read(4)
# Escrevendo as transicoes no dicionario de cada estado
while f.read(3)[1] != '}':
# Lendo a linha da transicao
# Exemplo(22 caracteres): (q0, B) -> (q1, B, R),
transicao = f.read(22)
# Pegando o estado da lista estados
estado = estados[eval(transicao[2])]
'''
Exemplo do formato:
Estado q0 -> portanto pega-se a posicao 0 da lista de estados
No dicionario desta posicao, entao se adiciona uma chave que corresponde a leitura
E seu valor e uma tupla que corresponde (qj, y, D)
Sendo qj o destino da transicao
y a escrita
e D a direcao
Exemplo:
(q0, B) -> (q1, B, R),
Posicao 0 na lista estados
{'B' : (q1, B, R)}
Portanto, o estado q0 ao ler B, ira para q1, escrevera B na fita e ira para direita
'''
estado[transicao[5]]= (transicao[13], transicao[16], transicao[19])
# Guardando o estado inicial
estado_inicial = f.read(8)[3]
# Lendo a fita (Restante do arquivo)
fita = f.readlines()[0]
# Fechando o arquivo
f.close()
# Criando o estado atual
estado_atual = estado_inicial
# Posicao da fita
pos = 0
# Realizando a checagem da fita
checagem = checarFita(fita, alfabeto_fita)
# Caso a checagem esteja correta (True), entra no while para percorrer a fita
if checagem[0]:
# Criando o arquivo para saida - Cria-se apenas se nao houver erro na fita
f = open(sys.argv[2], 'w')
# Loop
while True:
# Escrevendo a fita no arquivo
f.write(fita[:pos] + '{{q{}}}'.format(estado_atual) + fita[pos:] + '\n')
# Recebendo o estado
estado = estados[eval(estado_atual)]
# Leitura da posicao atual da fita
leitura = fita[pos]
# Tupla -> (Destino, Escrita, Movimento)
tupla = estado[leitura]
# Condicao de Parada
# Caso o estado atual nao consiga transitar com a posicao atual da fita, programa para!
if tupla == {}:
break
# Organizando e escrevendo na fita
fita = fita[:pos] + tupla[1] + fita[pos+1:]
# Movimentando
if tupla[2] == 'R':
pos += 1
else: pos -= 1
# Alterando o estado atual
estado_atual = tupla[0]
# Caso a fita esteja incorreta, emite uma mensagem, indicando o erro na fita
else:
print('Fita incorreta - Arquivo nao foi criado! {} nao pertence ao alfabeto da fita!'.format(checagem[1]))
|
71553365dd09d1202bd814a49fe1fdc14b8a547a | zickalate/CP3-Phatcha-Kambor | /assignments/Lecture50_Phatcha_K.py | 230 | 3.84375 | 4 | def plusNumber(x,y):
print(x+y)
def minusNumber(x,y):
print(x-y)
def multiplyNumber(x,y):
print(x*y)
def divideNumber(x,y):
print(x/y)
plusNumber(20,10)
minusNumber(20,10)
multiplyNumber(20,10)
divideNumber(20,10) |
94e6c62de029b35883066ead225c7aed8ff658d7 | Darrian5120/CIS2348 | /HW2/woodard_6_17.py | 403 | 3.671875 | 4 | #Darrian Woodard
#1593984
word = input()
password = ''
for i in range(0, len(word)):
if word[i] == 'i':
password += '!'
elif word[i] == 'a':
password += '@'
elif word[i] == 'm':
password += 'M'
elif word[i] == 'B':
password += '8'
elif word[i] == 'o':
password += '.'
else:
password += word[i]
password = password + "q*s"
print(password) |
417d251240aaf565c206b7c366a6952dd4c1f5fc | bernardombraga/Solucoes-exercicios-cursos-gratuitos | /Curso-em-video-Python3-mundo1/ex025.py | 147 | 3.59375 | 4 | lido = str(input('Qual é seu nome completo? '))
nome = lido.strip().lower()
silva = 'silva' in nome
print('Seu nome tem Silva? {}'.format(silva))
|
250944e7eacbfc433ca960298509c4d791c763f7 | danielrazavi/Garner-Assessment | /shipment_stats.py | 8,369 | 3.5 | 4 | """
Created on Tue Feb 19 17:16:19 2019
.Done
@author: Dan
"""
import sys
import re
import datetime as dt
from dateutil import tz
# Check to see if ther right amount of parameters are given.
if len(sys.argv)!=2:
print("Need to give the right number of parameters (one).\nFor example:\n\t python shipment_stats.py test_data.txt")
exit()
# A class object created to treat each line of data as its own entity.
class line_info():
def __init__(self, time, given_status, category):
self.time = time
self.status = given_status
self.info_type = category
self.country = None
self.location = None
self.duration = dt.timedelta(0)
# A method that translates the given time to a standard time so that durations can be calculated correctly.
def translate_time(self):
try:
from_tz = tz.gettz(location_bank[(self.country, self.location)][1])
to_zone = tz.gettz('UTC')
self.time = self.time.replace(tzinfo=from_tz)
self.time = self.time.astimezone(to_zone)
except KeyError:
if (self.country == None) or (self.location == None):
lazy_error_msg("Data does not specify where the shipment was picked up from.")
else:
lazy_error_msg("Location," + str((self.location, self.country)) + " doesn't exist in location_bank.")
# The data that is assumed that will be given in the real world.
location_bank = {('china','shanghai'):['Asia', 'PRC'],
('hong kong','hong kong'):['Asia','Hongkong'],
('usa','cincinnati hub,oh'):['North America','US/Eastern'],
('canada','ontario service area'): ['North America', 'Canada/Eastern'],
('canada','toronto'):['North America','Canada/Eastern']}
# Setting up the variables that will contain all the scraped data.
time_continent = {}
time_country = {}
the_data = []
max_obj = line_info(0,0,0)
# A function that gives custom error message so that it can exactly pinpoint the error of the data by line number and
# to finally exit out of the program so that the code cannot continue on.
def lazy_error_msg(string):
line_number = open(sys.argv[1]).readlines().index(line) + 1
error_message = "In '" + str(sys.argv[1]) + "', line number " + str(line_number) + ": " + string
print(error_message)
exit()
# A mini duration calculator which recieves a duration object and returns two integers that signify the duration time
# in hours and minutes.
def give_hm(given_duration):
hours = (given_duration.days * 24) + (given_duration.seconds // 3600)
minutes = (given_duration.seconds-((given_duration.seconds//3600)*3600))//60
if ((given_duration.seconds - (given_duration.seconds // 60) * 60) > 0): minutes += 1
return hours,minutes
# A function that acts like a book keeper and keeps track of the amount of time spent in a certain country or location
# and also keeps track of the Longest shipment step in the data.
def time_tracker(given_time):
global max_obj
the_data[-1].duration = given_time - the_data[-1].time
if max_obj.duration < the_data[-1].duration:
max_obj = the_data[-1]
this_country = the_data[-1].country
this_continent = location_bank[(the_data[-1].country,the_data[-1].location)][0]
if this_country in time_country:
time_country[this_country] += the_data[-1].duration
else:
time_country[this_country] = the_data[-1].duration
if this_continent in time_continent:
time_continent[this_continent] += the_data[-1].duration
else:
time_continent[this_continent] = the_data[-1].duration
try:
# Processing all lines.
for line in reversed(open(sys.argv[1]).readlines()):
if re.match(r'(Date, Time, Status|[\r\n\s]+)', line, re.M | re.I): continue
match_str = re.match(r'(\d{4}-\d{2}-\d{2},\s\d{2}:\d{2}:\d{2}),\s(.*)', line, re.M | re.I)
time_object = dt.datetime.strptime(match_str.group(1), "%Y-%m-%d, %H:%M:%S")
match_str2 = re.match(r'(\w+).*', match_str.group(2), re.M | re.I)
category = match_str2.group(1)
line_obj = line_info(time_object, match_str.group(2), category)
if category in ["Shipment", "Arrived", "Delivered"]:
match_str3 = re.match(r'(Arrived at Sort Facility|Shipment picked up at|Delivered - Signed for by receiver in)(.*)[,-]([\w\s]*)\.?$', match_str.group(2), re.M | re.I)
if (category == "Delivered") and not (the_data[-1].country == match_str3.group(3).strip().lower()):
lazy_error_msg("Logistic Error in status, location wasn't `" + match_str3.group(2).strip().lower() + "` before.")
line_obj.location = match_str3.group(2).strip().lower()
line_obj.country = match_str3.group(3).strip().lower()
line_obj.translate_time()
if category != "Shipment":
time_tracker(line_obj.time)
elif category in ["Processed","Departed","Clearance"]:
match_str3 = re.match(r'(Processed at|Departed Facility in|Clearance processing complete at)(.*)-(.*)$', match_str.group(2), re.M | re.I)
a = (the_data[-1].location == match_str3.group(2).strip().lower())
b = (the_data[-1].country == match_str3.group(3).strip().lower())
if not(a):
lazy_error_msg("Logistic Error in status, location wasn't `"+ match_str3.group(2).strip().lower() + "` before.")
elif not(b):
lazy_error_msg("Logistic Error in status, country wasn't `"+ match_str3.group(3).strip().lower() + "` before.")
line_obj.location = match_str3.group(2).strip().lower()
line_obj.country = match_str3.group(3).strip().lower()
line_obj.translate_time()
time_tracker(line_obj.time)
elif category in ["Customs", "With", "Delivery"]:
its_not_okay = not(re.match(r'^Customs status updated$', match_str.group(2), re.M | re.I)) and\
not(re.match(r'^With delivery courier$', match_str.group(2), re.M | re.I)) and\
not(re.match(r'^Delivery attempted; recipient not home$', match_str.group(2), re.M | re.I))
if its_not_okay:
lazy_error_msg("Data given is not recognized - e3")
line_obj.location = the_data[-1].location
line_obj.country = the_data[-1].country
line_obj.translate_time()
time_tracker(line_obj.time)
else: lazy_error_msg("Data given is not recognized - e1")
if the_data:
if the_data[-1].time > line_obj.time:
lazy_error_msg("Logistic Error in status, Data travels back in time")
the_data.append(line_obj)
# Making sure the shipment was shipped.
if the_data[0].info_type != "Shipment":
lazy_error_msg("Shipment was never officially shipped.")
# Making sure the shipment was delivered.
elif the_data[-1].info_type != "Delivered":
lazy_error_msg("Shipment was never delivered.")
# Total Time Calculations
th, tm = give_hm(the_data[-1].time - the_data[0].time)
# Time Spent in Asia Calculations
if not('Asia' in time_continent):
ah,am = 0
else:
ah, am = give_hm(time_continent['Asia'])
#Time Spent in USA Calculations
if not('usa' in time_country):
uh, um = 0, 0
else:
uh, um = give_hm(time_country['usa'])
except ValueError:
lazy_error_msg("Time data '"+ match_str.group(1) +"' doesn't make sense.")
except AttributeError:
lazy_error_msg("Data given is not recognized - e2")
except IndexError:
print("File contains not enough/no data")
exit()
except NameError:
print("File contains not enough/no data.")
exit()
except FileNotFoundError:
print("Need to pass in a proper file.\nFor example:\n\t python shipment_stats.py test_data.txt")
exit()
print("Total shipment time: {0}:{1}".format(th, tm))
print("Total time in Asia: {0}:{1}".format(ah, am))
print("Total time in USA: {0}:{1}".format(uh, um))
print("Longest shipment step: from \"{0}\" to \"{1}\"".format(max_obj.status,the_data[the_data.index(max_obj)+1].status))
# Resseting the data variables since they are no longer needed
time_continent = None
time_country = None
the_data = None
max_obj = None |
11f44f9c0f466a8343463fac09d2e24c96f911f4 | rnaster/python-study | /order.py | 2,265 | 3.8125 | 4 | """
first-class function design pattern practice
"""
from collections import namedtuple
Customer = namedtuple('Customer', 'name fidelity')
promos = []
def promotion(promo_func):
promos.append(promo_func)
return promo_func
@promotion
def fidelity_promo(order):
"""
apply discount 5% of total price to customers who have fidelity 1,000 points
"""
return order.total() * 0.05 if order.customer.fidelity >= 1_000 else 0
@promotion
def bulk_item_promo(order):
"""
apply discount 10% of total price to customers who order 20 same products
"""
discount = 0
for item in order.cart:
if item.quantity >= 20:
discount += item.total() * 0.1
return discount
@promotion
def large_order_promo(order):
"""
apply discount 7% of total price to customers who order 10 or more different kinds of products
"""
distinct_items = {item.product for item in order.cart}
if len(distinct_items) >= 10:
return order.total() * 0.07
return 0
def best_promo(order):
"""
return max discount
"""
return max(promo(order) for promo in promos)
class LineItem:
def __init__(self, product, quantity, price):
self.product = product
self.quantity = quantity
self.price = price
def total(self):
return self.price * self.quantity
class Order:
def __init__(self, customer, cart, promotion=None):
self.customer = customer
self.cart = cart
self.promotion = promotion
self.__total = -1
def total(self):
self.__total = sum(item.total() for item in self.cart)
return self.__total
def due(self):
discount = 0
if self.promotion is not None:
discount = self.promotion(self)
return self.total() - discount
def __repr__(self):
fmt = '<Order total: {:.2f} due: {:.2f}>'
return fmt.format(self.total(), self.due())
if __name__ == '__main__':
yun = Customer('yun lee', 0)
seop = Customer('seop park', 1100)
cart = [LineItem('banana', 4, 0.5),
LineItem('apple', 10, 1.5),
LineItem('watermelon', 5, 5.0)]
print(Order(yun, cart, fidelity_promo))
print(Order(seop, cart, fidelity_promo))
|
6dc79dd6ca1390e37938db236fded066e6ec8f4f | bespontoff/checkio | /solutions/Storage/braille_translator.py | 4,097 | 3.984375 | 4 | #!/home/bespontoff/PycharmProjects/checkio/venv/bin/checkio --domain=py run braille-translator
# Brailleis a tactile writing system used by the blind and the visually impaired. It is traditionally written with embossed paper. Braille characters are small rectangular blocks, called cells, which contain tiny palpable bumps called raised dots. The number and arrangement of these dots distinguish one character from another.
#
# We will use a 6-dots Braille alphabet. Each letter can be represented as a 3x2 matrix where 1 is a raised dot and 0 is an empty space.
#
#
#
# (Letter W is not original)
#
# Letters should be separated by an empty column. Whitespaces are two empty columns (plus a separator empty column if it is between letters). Various formatting marks indicate the values of the letters that follow them. They have no direct equivalent in print. The most important indicators in English Braille are: "capital" and "number". These marks work as "shift" - only for a follow letter.
#
#
#
# We will use several basic punctuation symbols:
#
#
#
# You are given a page of text and you should convert it into Braille. The page contains one or several lines represented as a matrix. Each line contains no more than 10 symbols (including non-printed). Lines are separated by one empty row. Symbols are separated by empty columns but there are no separators in beginnings and ends of lines. If text can be placed in one line, then the page width is proportional to the length of the text. If the page has more than one line, then the width is equal to the longer line and the final line is appended by whitespaces.
#
# For example, this is the text "hello 1st World!".
#
#
#
# Input:A text as a string.
#
# Output:The page as a list of lists or tuple of tuples with integers (1/0).
#
# Precondition:
# 0 < len(text)
# all(ch in string.ascii_letters + " .,!?-_0123456789" for ch in text)
#
#
# END_DESC
def convert(code):
bin_code = bin(code)[2:].zfill(6)[::-1]
return [[int(bin_code[j + i * 3]) for i in range(2)] for j in range(3)]
LETTERS_NUMBERS = list(map(convert,
[1, 3, 9, 25, 17, 11, 27, 19, 10, 26,
5, 7, 13, 29, 21, 15, 31, 23, 14, 30,
37, 39, 62, 45, 61, 53, 47, 63, 55, 46, 26]))
CAPITAL_FORMAT = convert(32)
NUMBER_FORMAT = convert(60)
PUNCTUATION = {",": convert(2), "-": convert(18), "?": convert(38),
"!": convert(22), ".": convert(50), "_": convert(36)}
WHITESPACE = convert(0)
def braille_page(text: str):
return [[0, 0], [0, 0], [0, 0]]
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
def checker(func, text, answer):
result = func(text)
return answer == tuple(tuple(row) for row in result)
assert checker(braille_page, "hello 1st World!", (
(1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1),
(1, 1, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 1, 1),
(0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 1, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0, 0),
(0, 0, 0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0))
), "Example"
assert checker(braille_page, "42", (
(0, 1, 0, 1, 1, 0, 0, 1, 0, 1, 0),
(0, 1, 0, 0, 1, 0, 0, 1, 0, 1, 0),
(1, 1, 0, 0, 0, 0, 1, 1, 0, 0, 0))), "42"
assert checker(braille_page, "CODE", (
(0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 0),
(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1),
(0, 1, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0))
), "CODE" |
795afad9a9710cd6cb2d9ccd7aa013a1d9c260ae | safwanc/python-sandbox | /recursion/fibonacci.py | 155 | 3.9375 | 4 | def fibonacci_recursive(n):
if n in [0, 1]: return 1
return fibonacci_recursive(n - 1) + fibonacci_recursive(n - 2)
print(fibonacci_recursive(10)) |
d89be24a6349cce2dbd0470f61b86907a2860285 | danui/project-euler | /solutions/python/problem-7.py | 890 | 4.09375 | 4 | """
By listing the first six prime numbers: 2, 3, 5, 7, 11, and 13, we can
see that the 6th prime is 13.
What is the 10001st prime number?
"""
# This uses a growable sieve
def kth_prime(k):
P = [2] # list of primes
A = [1, 1, 1] # seen.
x = 3 # current value
while len(P) < k:
# If the sieve is too small double its size
if len(A) < x+1:
n = len(A)
A = A + [0]*n
for y in P:
j = n//y * y
while j < len(A):
A[j] = 1
j += y
if A[x] == 0:
j = x
while j < len(A):
A[j] = 1
j += x
P.append(x)
x += 2
return P[k-1]
for k in [6, 100, 10001]:
print "The %d'th prime is %d" % (k, kth_prime(k))
|
f6f7c32b7b803142a3d4a0b8e3f962e06f2bde77 | phuycke/Project-Euler | /Code/problem_40.py | 1,543 | 4.15625 | 4 | #!/usr/bin/env python3
# Problem setting
"""
An irrational decimal fraction is created by concatenating the positive integers:
0.123456789101112131415161718192021...
It can be seen that the 12th digit of the fractional part is 1.
If dn represents the nth digit of the fractional part, find the value of the following expression.
d1 × d10 × d100 × d1000 × d10000 × d100000 × d1000000
"""
def createChampernowne(length):
decimals = list(range(1, 10))
for index in range(len(decimals)):
decimals[index] = str(decimals[index])
number = 10
unchecked = True
while len(decimals) < length + 1 and unchecked:
listed = list(str(number))
for i in range(len(listed)):
checking = len(decimals)
if checking > length:
unchecked = False
break
else:
decimals.append(listed[i])
number += 1
return decimals
def findValues(inputlist, listed):
if len(listed) == 0:
raise IndexError("The list you provided is empty...")
else:
values = []
for j in range(len(listed)):
index = listed[j]
values.append(int(inputlist[index - 1]))
return values
needed = createChampernowne(1000000)
result = findValues(needed, [1, 10, 100, 1000, 10000, 100000, 1000000])
product = result[0]
for i in range(1, len(result)):
product = product * result[i]
print("The numbers we selected are:")
print(result)
print("The product of these numbers is", product)
|
ed3935c3f18bc462e58a1b84c771c0d12ea99f95 | hackingmaterials/duramat_dashboard | /degradation/degradation_functions.py | 4,775 | 3.515625 | 4 | """
These are 'toy' smoothing/degradation functions. These will eventually be replaced by those in
existing analytics software (RdTools) or refactored to be more robust/easier to read.
"""
import pandas as pd
import numpy as np
from sklearn import linear_model
import statsmodels.api as sm
def trendline(df, column='Power(W) norm'):
"""Perform linear least squares on data set.
Parameters
----------
df: pd.DataFrame
column: str
Name of column to perform OLS on.
Returns
-------
df: pd.DataFrame
Input df with new '<column> + trend_ols' column.
yearly_coef: float
Yearly degradation rate.
"""
try:
df = df[df['mask']]
except KeyError:
pass
# tmp = df[df['mask']][column]
# df = pd.DataFrame(df.values, columns=['orig'], index=df.index)
df.name = 'orig'
df = pd.DataFrame(df)
print(df)
tmp = df
# tmp = df[column]
tmp = tmp.dropna()
# print(tmp.index)
day_vec = tmp.index - tmp.index[0]
day_vec = day_vec.days.values
x = day_vec.reshape(-1, 1)
y = tmp.values.reshape(-1, 1)
lr = linear_model.LinearRegression()
lr.fit(x, y)
full_day_vec = df.index - df.index[0]
full_day_vec = full_day_vec.days.values
df['trend ols'] = lr.predict(full_day_vec.reshape(-1, 1))
daily_coef = lr.coef_[0][0]
daily_intercept = lr.intercept_[0]
yearly_coef = daily_coef * 365
return df['trend ols'], yearly_coef
# `return df, yearly_coef
def csd(df, column='Power(W) norm'):
"""Perform classical seasonal decomposition on time series data.
Parameters
----------
df: pd.DataFrame
column: str
Column name on which to perform.
Returns
-------
df: pd.DataFrame
Input df with addtional columns for trend, seasonality, and residuals.
"""
# try:
# df = df[df['mask']]
# except KeyError:
# pass
# df[column] = df[column].fillna(method='bfill')
# df[column] = df[column].fillna(method='ffill')
# ser = df[df.index.isin(pd.date_range(df[column].first_valid_index(), df[column].last_valid_index()))][column]
# ser = ser.interpolate()
# res = sm.tsa.seasonal_decompose(ser, two_sided=True, freq=365)
# # res = sm.tsa.seasonal_decompose(df[column], two_sided=True, freq=365)
# df[column + ' trend csd'] = res.trend
# df[column + ' seasonality csd'] = res.seasonal
# df[column + ' residuals csd'] = res.resid
# return df
df = df.fillna(method='bfill')
df = df.fillna(method='ffill')
df = df[df.index.isin(pd.date_range(df.first_valid_index(), df.last_valid_index()))]
df = df.interpolate()
res = sm.tsa.seasonal_decompose(df, two_sided=True, freq=365)
df = res.trend
tmp = pd.DataFrame(df, columns=['orig'])
print(tmp)
# res = sm.tsa.seasonal_decompose(df[column], two_sided=True, freq=365)
tmp['trend csd'] = res.trend
tmp['seasonality csd'] = res.seasonal
tmp['residuals csd'] = res.resid
return tmp['seasonality csd']
def yoy(df, column='Power(W) norm'):
"""Perform year-on-year degradation analysis.
Parameters
----------
df: pd.DataFrame
column: str
Column name for yoy calculation.
Returns
-------
diffs: array
Shifted differences
rate: float
Yearly degradation.
"""
try:
df = df[df['mask']]
except KeyError:
pass
# df = df[df['mask']]
diffs = (df[column].shift(365, freq='D') - df[column]).dropna()
rate = np.median(diffs)
return diffs, rate
def rolling_mean(df, column='Power(W) norm'):
"""Perform rolling mean smoothing.
Parameters
----------
df: pd.DataFrame
column: str
Returns
-------
df: pd.DataFrame
"""
# try:
# df = df[df['mask']]
# except KeyError:
# pass
# df = df[df['mask']]
# if column + ' trend rolling mean' in df.keys():
# return df
# df[column + ' trend rolling mean'] = df[column].rolling('90D').mean()
return df.rolling('90D').mean()
def lowess(df, column='Power(W) norm'):
"""Perform LOWESS smoothing.
Parameters
----------
df: pd.DataFrame
column: str
Returns
-------
df: pd.DataFrame
"""
try:
df = df[df['mask']]
except KeyError:
pass
# df = df[df['mask']]
if column + ' trend lowess' in df.keys():
return df
tmp = pd.DataFrame(df, columns=['orig'])
print(tmp)
# tmp = sm.nonparametric.lowess(df[column].values, np.arange(len(df)))[:, 1]
# df[column + ' trend lowess'] = tmp
tmp = sm.nonparametric.lowess(tmp['orig'].values, np.arange(len(tmp)))[:, 1]
df['trend lowess'] = tmp
return df['trend lowess']
# return df
|
9f80119bfcdf9fa7321c2fcd814e34858c22f4be | Aakancha/Python-Workshop | /Jan19/Assignment/Dictionary/Q12.py | 548 | 4.21875 | 4 | dict1 = {
'mother': 53,
'father': 62,
'sister': 35,
'brother': 26,
'me': 20,
'uncle': 43
}
'''
maxval = max(dict1.keys(), key=lambda x: dict1[x])
minval = min(dict1.keys(), key=lambda x: dict1[x])
print(f"Minimum value: {dict1[minval]}")
print(f"Maximum value: {dict1[maxval]}")
'''
minval = list(dict1.values())[0]
maxval = 0
print(dict1)
for each in dict1.values():
if each > maxval:
maxval = each
if each < minval:
minval = each
print(f"Minimum value: {minval}")
print(f"Maximum value: {maxval}")
|
ef2093898cab746a11d3372d7cffe00f143b295d | SThomas1234/EscapeTheGhost | /ghost.py | 16,280 | 4.0625 | 4 | import sys, random
def check_options(options, inp):
# This function checks to see if the user's input can be found in the list of potential options per situation
# The list of options is represented by the options variable found before each while True loop.
# If the input is found in the list, the function returns True and False otherwise.
val = True
if inp not in options:
val = False
else:
val = True
return val
def is_str(inp):
# This function checks an input's validity by checking to see if it's a string or not
# If the input is not a string, the function returns True and False otherwise.
val = True
inp.strip()
if inp.isdigit():
val = False
else:
val = True
return val
def repeated_inputs(option_number):
# This function checks to see if the user has entered an option multiple times
# The global variables represent the amount of times each input has been entered
# Every time the user enters an input, this function is called to increment the respective count variable.
global option1_frequency, option2_frequency, option3_frequency, option4_frequency
if option_number == 1:
option1_frequency += 1
return option1_frequency # Represents frequency of the first option
elif option_number == 2:
option2_frequency+=1
return option2_frequency # Represents frequency of the second option
elif option_number == 3:
option3_frequency +=1
return option3_frequency # Represents frequency of the third option
elif option_number == 4:
option4_frequency+=1
return option4_frequency # Represents frequency of the fourth option
def get_user_response(): # Written with assistance from Professor Boady
# The purpose of this function is to ensure that the input the user provided is valid in all respects (in the options list, a string, not repeated)
# If these conditions are met, the function keeps executing, and if not it jumps to the last else statement.
# The function first asks the user for input, and uses the check_options and is_str functions to check for initial validity (in the list of potential options, a string)
# Then the function uses the for loop to find the value of i (represents the option_number described in the repeated_inputs() function)
# The function then passes the value of i into the repeated_inputs to check if has already been used. If so, it tells the user the input was repeated. If not, it returns the option number.
while True:
response = input()
if check_options(options,response) and is_str(response):
for i in range(len(options)):
if options[i] == response:
option_num=i+1
val = repeated_inputs(option_num)
if val==1:
return option_num
else:
print("You already selected this option. Please choose another.")
else:
print("Invalid Input. Please try again.")
def random_event(outcomes):
# This function creates the possibility of additional lose conditions in addition to the one presented in the game's second situation.
# It chooses a random element from the passed in list, outcomes, which list potential lose scenarios
# If the value of "val," determined by the random.randint() function is <=5, the original outcome for the response will still occur
# If val >5, however, the new condition will exectute and the player will lose the game.
val = random.randint(0,10)
element = random.choice(outcomes) # Chooses a random element from the outcomes list.
if val <= 5:
pass
else:
print(element)
print("GAME OVER")
sys.exit()
print("""You wake up and realize that you have been captured by the infamous Ghost Killer, a serial killer that has
evaded capture for years. He has left you in a room in an abandoned house. You have a short amount of time to escape
before he returns to kill you. In the room, there are two doors, a radiator, and a window.
What will you do?
a.) Check out the window
b.) Check out the first door
c.) Check out the second door
""")
counter = 0
options = ["Check out the window", "Check out the first door", "Check out the second door"] # Establishes options for scenario 1
option1_frequency, option2_frequency, option3_frequency, option4_frequency = 0, 0, 0, 0
response = get_user_response() # Gets user response and checks for its validity
while counter < 3:
# This while loop is responsible for dealing with user responses to the first scenario: exploring the room they are trapped in
# The point of this while True loop is for the user to explore all given possibilities before advancing to the next scenario.
# To break out of the loop, the while loop operates off a counter variable which is incremented after every unique option choice.
if response == 1: # Conditional checks if the user selected the first option in the "options" list
print("The window is sealed")
elif response == 2 or response == 3: # Conditional checks if the user selected the second or third options in the "options" list
print("The door is sealed")
counter +=1 # Increments count after each valid user response
if counter ==3: # Exits the while True loop
break
print("What will you do?")
response = get_user_response() # Gets user response and checks for its validity
print("""
You notice something shine in the corner of the room. Upon closer inspection, you find out that it's a toolbox. What
will you do?
a.) Use the screwdriver to try and dismantle the first door
b.) Use the screwdriver to try and dismantle the second door
c.) Use the screwdriver and hammer to try and unseal the window
""")
options = ["Use the screwdriver to try and dismantle the first door",
"Use the screwdriver to try and dismantle the second door",
"Use the screwdriver and hammer to try and unseal the window"] # Updates Options for scenario 2
option1_frequency, option2_frequency, option3_frequency, option4_frequency = 0, 0, 0, 0 # Resets count variables for the new responses
response = get_user_response() # Gets user response and checks for its validity
outcomes = ["You took too long trying to unscrew the door. The Ghost Killer has found and killed you.",
"You made too much noise trying to unscrew the door. The Ghost Killer has found and killed you."] # Updates lose scenarios for scenario 2
while True:
# This while True loop is responsible for handling the user responses to the second scenario in the game: the player's intial escape attempt.
# The point of the loop is to introduce a lose condition and demonstrate to the user that they are sealed in (supposedly).
# To break out of the loop, the player must select the third option: using tools to try and unseal the window.
if response == 1: # Conditional checks if the user selected the first option in the "options" list
random_event(outcomes) # Checks to see if the normal outcome or the lose condition executes.
print("The screwdriver head does not match the screws found on this door")
print("What will you do?")
elif response == 2: # Conditional checks if the user selected the second option in the "options" list
print("""The screwdriver head is a match, but, in your weakened state, it is taking awhile to undo the door’s hinges.
When you finally get to the last screw, the Ghost Killer reappears and stabs you in the heart. Soon after,
you bleed to death.""")
print("GAME OVER") # Player has lost the game
sys.exit() # Exits the program
elif response == 3: # Conditional checks if the user selected the third option in the "options" list
break # Breaks out of the while True loop, progresses onto the next scenario
response = get_user_response() # Gets user responses and checks for its validity
print("""You successfully manage to squeeze the screwdriver between the window’s gap and begin to use the hammer to
try and pry open the window. However, a few hits in, the screwdriver breaks off. You quickly grab a piece of the
screwdriver and use it to keep the window open. However, you don’t have much time because the window is extremely
heavy. What will you do now?
a.) Try to push the window up
b.) Run and get an item from the toolbox to keep the window open
c.) Try to smash the window with the hammer """)
options = ["Try to push the window up", "Try to smash the window with the hammer", # Updates options for scenario 3
"Run and get an item from the toolbox to keep the window open"]
outcomes = ["You took too long. The Ghost Killer has found and killed you.",
"You made too much noise. The Ghost Killer has found and killed you."] # Updates extra lose scenarios for scenario 3
option1_frequency, option2_frequency, option3_frequency, option4_frequency = 0, 0, 0, 0 # Resets count variables for the new responses
response = get_user_response() # Gets user response and checks for its validity.
while True:
# This while True loop is responsible for handling the game's third scenario: trying to get the window to budge
# The loop breaks when the user enters the third option: getting an item from the toolbox to get the window open.
if response == 1: # Conditional checks if the user selected the first option in the "options" list
random_event(outcomes) # Checks to see if the normal outcome or the lose condition executes.
print("You try to lift up the window, but you don’t have the strength to. What will you do?")
elif response == 2: # Conditional checks if the user selected the second option in the "options" list
random_event(outcomes) # Checks to see if the normal outcome or the lose condition executes.
print("The window does not budge to your attacks. What will you do?")
elif response == 3: # Conditional checks if the user selected the third option in the "options" list
break
response = get_user_response() # Gets user response and checks for its validity.
print("""Which item will you pick?
a.) Nails
b.) Flashlight
c.) Metal Wedge
d.) Rope""")
options = ["Nails", "Flashlight", "Metal Wedge", "Rope"] # Updates options for fourth scenario
option1_frequency, option2_frequency, option3_frequency, option4_frequency = 0, 0, 0, 0 # Resets count variables for new responses
response = get_user_response() # Gets user response and checks for its validity.
while True:
# This while True loop handles the user's responses to the game's fourth scenario: deciding what tool to use to keep the window open
# The loop breaks when the user enters the third option: choosing the metal wedge to keep the window open.
if response == 1 or response == 4: # Conditional checks if the user selected the first or fourth option in the "options" list
print("That seems ineffective. Select another item.")
elif response == 2: # Conditional checks if the user selected the second option in the "options" list
print("That doesn't seem sturdy enough to support the weight of the window. Select another item.")
elif response == 3: # Conditional checks if the user selected the third option in the "options" list
print("Good choice. This item is sturdy enough to keep the window open.")
break
response = get_user_response() # Gets user response and checks for its validity.
print("""After placing the wedge under the window, you manage to keep the window open. From there, you hammer away at
the wedge, causing the window to slowly lift up. Eventually, you manage to lift up the window to a point where you can
narrowly squeeze through. To secure this point, vertically place the hammer between the window and the wedge.
Now, how will you get out of the window?
a.) Jump out
b.) Use the rope to descend down""")
options = ["Jump out", "Use the rope to descend down"] # Resets options for the fifth scenario
option1_frequency, option2_frequency, option3_frequency, option4_frequency = 0, 0, 0, 0 # Resets count variables for new response
response = get_user_response() # Gets user response and checks for its validity.
while True:
# This while True loop is responsible for hanlding user responses to the game's fifth scenario: Deciding how the player will get out of the window
# The loop breaks when the user enters the second option: Deciding to use the rope to descend down.
if response == 1: # Conditional checks if the user selected the first option in the "options" list
print("The window is too high from the ground for you to successfully land without injuring yourself. What will you do?")
elif response == 2: # Conditional checks if the user selected the second option in the "options" list
break
response = get_user_response() # Gets user response and checks for its validity.
print("""The rope is long enough to reach the ground, but where will you tie it to?
a.) First Door’s Door Knob
b.) Second Door’s Door Knob
c.) Radiator""")
options = ["First Door's Door Knob", "Second Door's Door Knob", "Radiator"] # Resets options for game's final scenario.
option1_frequency, option2_frequency, option3_frequency, option4_frequency = 0, 0, 0, 0 # Resets count variables for game's final scenario.
response = get_user_response() # Gets user response and checks for its validity.
outcomes = ["You took too long to find an anchor for the rope. The Ghost Killer has found and killed you.",
"You made too much while dragging the rope. The Ghost Killer has found and killed you."] # Reset outcomes for game's final scenarios.
while True:
# This while True loop manages user responses to the game's final scenario: where the player will anchor the rope to escape out the window
# To break out of the loop, the user must pick the third option: tying the rope to the radiator next to the window.
if response == 1: # Conditional checks if the user selected the first option in the "options" list
random_event(outcomes) # Checks to see if the normal outcome or the lose condition executes.
print("The rope is not long enough to extend all the way from the first door (which is in the far corner of the"
" room) to the ground outside. Pick another point to tie the rope from.")
elif response == 2: # Conditional checks if the user selected the second option in the "options" list
random_event(outcomes) # Checks to see if the normal outcome or the lose condition executes.
print("The second door is close enough to the window to attach the rope, but the doorknob itself is rusting. "
"It is likely that it would break due to the pressure of your weight hanging on the rope. "
"Pick another point to tie the rope from.")
elif response == 3: # Conditional checks if the user selected the third option in the "options" list
break
response = get_user_response() # Gets user response and checks for its validity.
print("""Good choice. The radiator is right below the window, constructed out of metal, and is firmly attached to the floor.
It can definitely support your weight hanging on the rope.\n""")
print("""You hear footsteps approaching. The Ghost Killer is coming, so you don’t have a lot of time. You quickly tie the
rope around the radiator and descend downwards to the grass below. The footsteps get louder and louder, but you rejoice
as you get closer and closer to the ground below. As soon as your feet touch the ground, you run for it, as the Ghost Killer
screams in anger that you escaped his clutches.\n""") # Final Message
print("YOU WON") # Player has completed and won the game.
|
468c432e5d49a90c7aed95ef4e721dbd5ab5ca62 | walkerone/pythonalex | /day1113/login_homework.py | 1,515 | 3.953125 | 4 | # -*- coding:utf-8 -*-
"""
while 循环最多输入三次账号名称和密码,
先判断输入的name是否在lockfile,若是被锁定直接退出,with可以同时打开多个文件
若是不在loclfile,再判断name是否在loginfile,若是则输入密码尝试登录三次,若是正确,则提示欢迎语:
若是输入三次密码且一直未正确,则直接写入lockfile
"""
count = 0
while count < 3:
flag = False
account_input = input("input your account:")
password_input = input("input the account\'s password")
with open("login_name", "r") as accounts_file, open("lock_account", "r+") as lock_account:
lock_account_name = lock_account.read()
for account_input1 in lock_account_name.split():
print(lock_account_name.split())
if account_input1.strip() == account_input:
flag = True
break
accounts = accounts_file.readlines()
for account in accounts:
name, password = account.split()
name = name.strip()
password = password.strip()
if name == account_input and password == password_input:
print("welcome to my family")
flag = True
break
else:
print("valid account or wrong password")
break
if flag:
break
count += 1
else:
with open("lock_account", "a+") as lock_account:
lock_account.write("\n" + account_input)
|
e49798fb7679be5f54487930672eb3bfb924b3bc | joehammer934/python-program | /斐波那契数列.py | 312 | 3.625 | 4 | # -*- coding: utf-8 -*-
"""
Created on Wed Oct 5 15:43:47 2016
@author: li
"""
class Fib(object):
def __getitem__(self, n):
a, b = 1, 1
for x in range(n):
a, b = b, a + b
return a
#for n in Fib():
#if n<1000:
#print(n)
f=Fib()
print(f[20]) |
aaecd87baa6e5c5c9a29d8ff5649d7eeff8767a7 | mikeflowerdew/DMSTA_calibration | /CombineCLs.py | 43,184 | 3.53125 | 4 | #!/usr/bin/env python
import pickle,math
class CLs:
"""Small data class"""
def __init__(self, value):
try:
# Maybe "value" is actually a CLs object
self.value = value.value
self.valid = value.valid
self.ratio = value.ratio
except AttributeError:
# Or maybe "value" is really just a value
# If "value" is negative, then it must be the log of a CLs value
if value > 0:
self.value = value
else:
self.value = math.pow(10,value)
self.valid = True
self.ratio = 1. # ratio to minimum CLs value
def __float__(self):
return float(self.value)
def __cmp__(self, other):
if self.value < float(other):
return -1
elif self.value > float(other):
return 1
else:
return 0
def __mul__(self, other):
# A bit tricky to define, but let's go
result = CLs(self.value*other.value)
result.valid = self.valid and other.valid
result.ratio = min([self.ratio,other.ratio])
# Explanation: the ratio is used to determine if the
# result was extrapolated. Therefore we want to
# record the worst case, ie the smallest.
return result
def __str__(self):
valuestr = '%.3f'%(self.value) if self.value > 0.01 else '%.2e'%(self.value)
if self.valid:
return valuestr
else:
return 'INVALID CLs value of %s'%valuestr
def __repr__(self):
return self.__str__()
class DoNotProcessError(Exception):
"""Signals that there is something really wrong with the model,
and it should not be processed by the STAs.
"""
pass
# def __init__(self, value):
# self.value = value
# def __str__(self):
# return repr(self.value)
class Combiner:
def __init__(self, yieldfilename, calibfilename):
"""Inputs are the ROOT files with the truth-level ntuple
and the CL/yield calibration."""
self.__yieldfilename = yieldfilename
self.ReadCalibrations(calibfilename)
# Some other configurable options
self.strategy = 'smallest'
self.truncate = False
self.useexpected = False
@classmethod
def __FixXrange(cls, graph):
"""Fixes the x-axis range for a calibration graph.
The range is [0,1] for a linear scale, and [-6,0] for a log scale.
In the case of a log scale, the original minimum is stored under graph.xmin
"""
# Retrieve the x-axis minimum, extend the range back down to zero
graph.xmin = graph.GetXmin()
# Test for linear or log x-axis scale
if graph.xmin >= 0:
# Linear
graph.SetRange(0,graph.GetXmax())
else:
# Logarithmic
graph.SetRange(-6,0)
graph.xmin = math.pow(10,graph.xmin) # Convert back to linear scale
# Nothing more to do
return
@classmethod
def __HepDataSRname(cls, SR):
"""Reinterpret the in-code SR name with a theorist-friendly one for HepData.
"""
splitname = SR.split('_')
if splitname[0] == 'EwkTwoLepton':
if 'mT' in splitname[-1]:
threshold = 90 if 'a' in splitname[-1] else (120 if 'b' in splitname[-1] else 150)
return '2L_SR_mT2_%i'%(threshold)
else: # Zjets or WWx
return '2L_SR_%s'%(splitname[-1])
elif splitname[0] == 'EwkThreeLepton':
if 'SR0a' in splitname[-2]:
return '3L_SR_0tau_a_bin_%s'%(splitname[-1])
elif splitname[-1] == 'SR0b':
return '3L_SR_0tau_b'
elif splitname[-1] == 'SR1SS':
return '3L_SR_1tau'
elif splitname[0] == 'EwkFourLepton':
return '4L_%s'%(splitname[-1])
elif splitname[0] == 'EwkTwoTau':
if splitname[2].startswith('C1'):
return '2tau_SR_%s'%(splitname[2])
else:
return '2tau_SR_DS_lowMass' if 'low' in splitname[-1] else '2tau_SR_DS_highMass'
# If we get here, something went wrong
return SR #'ERROR'
def ReadCalibrations(self, calibfilename):
"""Reads all TF1 objects and stores them in self.CalibCurves.
This is a dictionary, with entries either like {SRname: CL_graph}.
Another dictionary, self.CalibCurvesExp, stores the expected fit results,
if they are found in the file.
"""
self.CalibCurves = {}
self.CalibCurvesExp = {}
calibfile = ROOT.TFile.Open(calibfilename)
for keyname in calibfile.GetListOfKeys():
# Let's just make this easier
keyname = keyname.GetName()
thing = calibfile.Get(keyname)
if not thing.InheritsFrom('TF1'):
continue
# This is a graph we want!
# Fix its x-axis range
self.__FixXrange(thing)
# The graph names come with the CL type
# separated from the analysis/SR by an underscore
analysisSR = '_'.join(keyname.split('_')[:-1])
# Work out if this is an expected or an observed result
if 'Exp' in keyname:
self.CalibCurvesExp[analysisSR] = thing
else:
self.CalibCurves[analysisSR] = thing
calibfile.Close()
return
def __AnalyseModel(self, entry):
"""Analyse a single entry in the ntuple.
This can raise a DoNotProcessError if the truth yields are not present."""
results = {}
resultsExp = {}
negativeYieldList = []
def GetCLs(graph, truthyield):
"""Small helper function to extract a valid CLs from a TGraph.
If the number is out of the valid range, then None is returned.
"""
result = CLs(graph.GetX(truthyield))
# If on a linear scale, check if the CLs value is within the valid range
if graph.GetXmin() >= 0 and result.value >= 0.999*graph.GetXmax():
# Too high
return None
# Similar range check for a log scale
if graph.GetXmin() < 0 and math.log10(result.value) >= graph.GetXmax():
return None
# Compare the CLs to our self-imposed minimum
if result.value < graph.xmin:
# This message prints out A LOT
# print 'WARNING in CombineCLs: %s has CLs = %f below the min of %s'%(analysisSR,CLs,graph.xmin)
result.valid = False
result.ratio = result.value/graph.xmin
return result
# Start the event loop
for analysisSR,graph in self.CalibCurves.items():
# slow, slow, slow, but I guess OK for now
truthyield = getattr(entry, graph.branchname)
# trutherror = getattr(entry, '_'.join(['EW_ExpectedError',analysisSR]))
if truthyield < 0:
negativeYieldList.append(analysisSR)
continue
# Get the main result
number = GetCLs(graph, truthyield)
if number is None:
continue
if self.useexpected:
# See if we have the corresponding expected result
try:
graphExp = self.CalibCurvesExp[analysisSR]
except KeyError:
# Only write the results out if we have the expected results
continue
numberExp = GetCLs(graphExp, truthyield)
if numberExp is None:
continue
# We have both expected+observed results, so this is looking OK
results[analysisSR] = number
resultsExp[analysisSR] = numberExp
else:
# self.useexpected == False
results[analysisSR] = number
# print '%40s: %.3f events, CLs = %s, log(CLs) = %.2f'%(analysisSR,truthyield,number,math.log10(number.value))
# if number.value < 1e-3:
# print number.value,graph.xmin,number.ratio
if negativeYieldList:
# Oh dear, we may have a problem, where a model with generated events
# has no recorded yield for one or more SRs
if len(negativeYieldList) == len(self.CalibCurves):
# Perfectly straightforward, no evgen yields were found, the model is completely broken
raise DoNotProcessError
else:
# There is a known issue with some 2tau yields
# If this is the only issue, the result I get should still be OK
# I also found one model with missing 3L results
onlyTau = True
only3L = True
for analysisSR in negativeYieldList:
if 'TwoTau' not in analysisSR:
onlyTau = False
if 'ThreeLepton' not in analysisSR:
only3L = False
if only3L:
# We can't really drop the strongest search, so let's drop the model
raise DoNotProcessError
if not onlyTau:
# A bit clumsy, but I had this code already and it does the job
try:
assert len(negativeYieldList) == len(self.CalibCurves)
except AssertionError:
print '================ Oh dear, some SRs have yields and others don\'t!'
print len(negativeYieldList),len(self.CalibCurves)
for analysisSR,graph in self.CalibCurves.items():
truthyield = getattr(entry, graph.branchname)
print '%30s: %6.2f'%(analysisSR,truthyield)
raise
# If only 2tau results were affected, carry on!
pass
if results:
# Find the best SR
if self.useexpected:
resultkey = min(resultsExp, key=resultsExp.get)
else:
resultkey = min(results, key=results.get)
# FIXME: Use results[resultkey] to find if CLs < 0.05
# What we do next depends on the CLs combination strategy
if self.strategy == 'smallest':
# Take only the best result
# This is a copy constructor, as result might be truncated later
result = CLs(results[resultkey])
elif self.strategy == 'twosmallest':
# Now we need to sort the whole list
if self.useexpected:
sortedkeys = sorted(resultsExp, key=resultsExp.get)[:2]
else:
sortedkeys = sorted(results, key=results.get)[:2]
# Find the observed CLs from the two best results
mylist = [results[k] for k in sortedkeys]
result = reduce(lambda x,y: x*y, mylist, CLs(1.))
# However we got the result, truncate it now if necessary
if self.truncate and result.value < 1e-6:
result.value = 1e-6
if not result.valid:
print 'Invalid result: %s has CLs = %6e below the min of %6e'%(resultkey,result.value,self.CalibCurves[resultkey].xmin)
else:
# Absolutely no sensitive SR
resultkey = None
result = CLs(1.)
result.valid = False
return result,resultkey,results,resultsExp
def ReadNtuple(self, outdirname, Nmodels=None, eventlist=None):
"""Read all truth yields, record the estimated CLs values.
Use Nmodels to reduce the number of analysed models, for testing."""
import os
if not os.path.exists(outdirname):
os.makedirs(outdirname)
# An extra subdirectory for detailed per-SR information
perSRdirname = '/'.join([outdirname,'perSRresults'])
if not os.path.exists(perSRdirname):
os.makedirs(perSRdirname)
yieldfile = ROOT.TFile.Open(self.__yieldfilename)
tree = yieldfile.Get('susy')
if eventlist:
tree.SetEventList(eventlist)
tree.SetBranchStatus('*', 0)
tree.SetBranchStatus('modelName', 1)
tree.SetBranchStatus('*ExpectedEvents*', 1)
for analysisSR,graph in self.CalibCurves.items():
graph.branchname = '_'.join(['EW_ExpectedEvents',analysisSR])
graph.yieldbranch = tree.GetBranch(graph.branchname)
graph.yieldvalue = getattr(tree, graph.branchname)
# I can't find out how to actually use this :(
# Some stuff for record-keeping
# SR:count - the key SR was the best SR in count models
# And also some other useful information
SRcount = {'total': 0, # Total number of models with at least 1 sensitive SR
'CLs1' : 0, # Total number of models with _no_ sensitive SR
'rounded': 0, # Models with a sensitive SR, but CLs=1.00 is given to STAs due to rounding
'STA': 0, # Number of results actually given to the STAs (should be "total"+"CLs1")
}
# Same thing, but only if CLs < 5% (best SR not required)
ExclusionCount = {'total': 0, # Total number of models excluded by the STA procedure
'total_any': 0, # Total number of models excluded by any SR (cross-check to compare to best expected SR)
}
# Now the count for where each SR is the best *and* CLs < 0.05
BestExclusionCount = {'total': 0, # Total number of models excluded by the STA procedure
}
# Plots of the CLs values for all models
CLsTemplate = ROOT.TH1I('CLsTemplate',';CL_{s};Number of models',100,0,1)
LogCLsTemplate = ROOT.TH1I('LogCLsTemplate',';log(CL_{s});Number of models',120,-6,0)
class CLsPlots:
"""Convenient holder of all CLs plots."""
def __init__(self, xaxisprefix='', CLstype='CLs', namesuffix=''):
if namesuffix and not namesuffix.startswith('_'):
namesuffix = '_'+namesuffix
# Plots of the observed CLs and its logarithm
self.CLs = self.__makeHistogram( CLstype+namesuffix, xaxisprefix)
self.LogCLs = self.__makeHistogram('Log'+CLstype+namesuffix, xaxisprefix)
# Plots of the CLs values for "valid" models (ie within the calibration function range)
self.CLs_valid = self.__makeHistogram( CLstype+namesuffix+'_valid', xaxisprefix)
self.LogCLs_valid = self.__makeHistogram('Log'+CLstype+namesuffix+'_valid', xaxisprefix)
@classmethod
def __makeHistogram(cls, newname, xaxisprefix=''):
result = LogCLsTemplate.Clone(newname) if newname.startswith('Log') else CLsTemplate.Clone(newname)
result.SetDirectory(0)
if xaxisprefix:
result.GetXaxis().SetTitle( ' '.join([xaxisprefix,result.GetXaxis().GetTitle()]) )
return result
def fill(self, CLresult):
self.CLs.Fill(CLresult.value)
self.LogCLs.Fill(math.log10(CLresult.value))
if CLresult.valid:
self.CLs_valid.Fill(CLresult.value)
self.LogCLs_valid.Fill(math.log10(CLresult.value))
def write(self):
self.CLs.Write()
self.LogCLs.Write()
self.CLs_valid.Write()
self.LogCLs_valid.Write()
# Plots of the observed CLs
ObsCLsPlots = CLsPlots('Observed', 'CLsObs')
ObsCLsSRPlots = {} # One plot per best SR
if self.useexpected:
# Plots of the expected CLs
ExpCLsPlots = CLsPlots('Expected', 'CLsExp')
ExpCLsSRPlots = {} # One plot per best SR
# How many SRs were used? Absolute maximum of 42 :D
NSRplot = ROOT.TH1I('NSRplot',';Number of active SRs;Number of models',43,-0.5,42.5)
NSRplot.SetDirectory(0)
# More refined information, in 20 bins of CLs
NSRplots = [NSRplot.Clone('NSRplot_%i'%(i)) for i in range(20)]
for p in NSRplots:
p.SetDirectory(0)
# A correlation plot
NSRs = len(self.CalibCurves)
SRcorr_numerator = ROOT.TH2D('SRcorrelation_numerator','',NSRs,-0.5,NSRs-0.5,NSRs,-0.5,NSRs-0.5) # Initially fill iff both SRs exclude
SRcorr_numerator.Sumw2()
SRcorr_numerator.SetDirectory(0)
for ibin,analysisSR in enumerate(sorted(self.CalibCurves.keys())):
SRcorr_numerator.GetXaxis().SetBinLabel(ibin+1, analysisSR)
SRcorr_numerator.GetYaxis().SetBinLabel(ibin+1, analysisSR)
SRcorr_denominator = SRcorr_numerator.Clone('SRcorrelation_denominator') # Fill if x-axis SR excludes
SRcorr_denominator.SetDirectory(0)
# Output text file for the STAs
stafile = open('/'.join([outdirname,'STAresults.csv']), 'w')
badmodelfile = open('/'.join([outdirname,'DoNotProcess.txt']), 'w')
# Output text file for HepData
hepdatafile = open('/'.join([outdirname,'HepData.csv']), 'w')
# More detailed info for each SR
perSRfiles = {} # For each SR, the excluded models where that SR is the best
def addPerSRresult(key, value):
try:
perSRfiles[key].write(value+'\n')
except KeyError:
perSRfiles[key] = open('/'.join([perSRdirname,key+'.txt']), 'w')
perSRfiles[key].write(value+'\n')
pass
perSRCLsfiles = {} # A full record of model ID vs CLs value
def addPerSRCLsresult(key, model, CLsObs, CLsExp):
# Only write these if we're in "subset" mode,
# in which case we have an event list
if not EL:
return
line = ','.join([str(model),str(CLsObs),str(CLsExp)]) + '\n'
try:
perSRCLsfiles[key].write(line)
except KeyError:
perSRCLsfiles[key] = open('/'.join([perSRdirname,key+'.dat']), 'w')
perSRCLsfiles[key].write(line)
pass
# Prepare for the loop over models
if eventlist:
print '%i models found in event list'%(eventlist.GetN())
else:
print '%i models found in tree'%(tree.GetEntries())
imodel = 0 # Counter
for ientry,entry in enumerate(tree):
if eventlist and not eventlist.Contains(ientry):
continue
modelName = entry.modelName
if modelName % 1000 == 0:
print 'On model %6i'%(modelName)
if Nmodels is not None:
if imodel >= Nmodels: break
imodel += 1
if Nmodels is not None:
# Debug mode, essentially
print '============== Model',modelName
try:
CLresult,bestSR,CLresults,CLresultsExp = self.__AnalyseModel(entry)
except DoNotProcessError:
badmodelfile.write('%i\n'%(modelName))
continue
# This could definitely be done in a more clever way, but let's just get it done
nonBestSRs = []
excludedSRs_CLsExp = {} # A dict of {SRname: CLsExp}, to allow sorting by best expected CLs
excludedSRs_CLsObs = {} # A dict of {SRname: CLsObs}, for debugging
for k,v in CLresults.items():
# if v.value < 0.05:
if self.useexpected:
excludedSRs_CLsExp[self.__HepDataSRname(k)] = CLresultsExp[k]
excludedSRs_CLsObs[self.__HepDataSRname(k)] = CLresults[k]
if v.value < 0.05 and k != bestSR:
nonBestSRs.append(k)
stafile.write('%i,%6e,%s,%s\n'%(modelName,CLresult.value,bestSR,','.join(nonBestSRs)))
SRcount['STA'] += 1
# Sort the SRs, the same way as in self.__AnalyseModel
if self.useexpected:
sortedSRs = sorted(excludedSRs_CLsExp, key=excludedSRs_CLsExp.get)
else:
sortedSRs = sorted(excludedSRs_CLsObs, key=excludedSRs_CLsObs.get)
# Construct two lists of SRs. First the best SR(s)
bestSRlist = []
# Only fill this if it makes any sense at all
if CLresult.value < 0.99:
for SRname in sortedSRs:
# If the CL is too high, break out
# Add a sanity check that the CL is also not too low
if self.useexpected:
if excludedSRs_CLsExp[SRname].value - CLresultsExp[bestSR].value > 1e-2*CLresultsExp[bestSR].value:
break
elif excludedSRs_CLsExp[SRname].value - CLresultsExp[bestSR].value < -1e-2*CLresultsExp[bestSR].value:
print '================================== ERROR ERROR ERROR RESULTS DO NOT AGREE'
else:
if excludedSRs_CLsObs[SRname].value - CLresults[bestSR].value > 1e-2*CLresults[bestSR].value:
break
elif excludedSRs_CLsObs[SRname].value - CLresults[bestSR].value < -1e-2*CLresults[bestSR].value:
print '================================== ERROR ERROR ERROR RESULTS DO NOT AGREE'
# If we get to here, it's a "best" SR
bestSRlist.append(SRname)
try:
if bestSRlist:
assert(self.__HepDataSRname(bestSR) in bestSRlist)
except AssertionError:
print '=============== best SR not in the list?'
from pprint import pprint
pprint(excludedSRs_CLsExp)
print bestSR
raise
bestSRstring = ';'.join(bestSRlist)
# Now make a string of the excluding SRs, in order of best observed CLs
sortedSRs = sorted(excludedSRs_CLsObs, key=excludedSRs_CLsObs.get)
excludingSRlist = []
for SRname in sortedSRs:
if excludedSRs_CLsObs[SRname] >= 0.05:
break
excludingSRlist.append(SRname)
excludingSRstring = ';'.join(excludingSRlist)
if len(bestSRlist) > 1 and CLresult.value < 0.05:
# Should generally mean we have no problems excluding
try:
for SRname in bestSRlist:
assert(SRname in excludingSRlist)
except AssertionError:
print '====================== Multiple best SRs do not all exclude?? Model',modelName
from pprint import pprint
print CLresult
print bestSR
pprint(CLresults)
pprint(CLresultsExp)
pprint(bestSRlist)
pprint(excludingSRlist)
# if modelName != 245974 and modelName != 43893: raise
hepdatafile.write('%i,%s,%s\n'%(modelName,bestSRstring,excludingSRstring))
# # Construct a string listing the excluding SRs, ordered by CLsExp
# # Sort in _exactly_ the same way as in self.__AnalyseModel.
# if self.useexpected:
# hepdatastring = ';'.join(sorted(excludedSRs_CLsExp, key=excludedSRs_CLsExp.get))
# else:
# hepdatastring = ';'.join(sorted(excludedSRs_CLsObs, key=excludedSRs_CLsObs.get))
# hepdatafile.write('%i,%s\n'%(modelName,hepdatastring))
# try:
# bestSR_HepData = hepdatastring.split(';')[0]
# if bestSR and CLresult.value < 0.05:
# # FIXME: If both CLsExp results are equal to 1e-6, then the order is arbitrary
# if CLresultsExp[bestSR].value > 1e-6 or excludedSRs_CLsExp[bestSR_HepData].value > 1e-6:
# # Check that the two SRs have the same name
# assert(bestSR_HepData == self.__HepDataSRname(bestSR))
# elif hepdatastring:
# # In principle an error
# assert(excludedSRs_CLsObs[bestSR_HepData].value < 0.05) # FIXME: Report exclusion where we use none in the paper
# except AssertionError:
# from pprint import pprint
# print '================= ERROR on event',ientry,', model',modelName
# print CLresult
# print bestSR
# pprint(CLresults)
# pprint(CLresultsExp)
# print hepdatastring
# raise
ObsCLsPlots.fill(CLresult)
if bestSR:
try:
ObsCLsSRPlots[bestSR].fill(CLresult)
except KeyError:
ObsCLsSRPlots[bestSR] = CLsPlots('Observed', 'CLsObs', bestSR)
ObsCLsSRPlots[bestSR].fill(CLresult)
NSRplot.Fill(len(CLresults))
if CLresult.value < 1.: # This would be zero by default
NSRplots[int(CLresult.value/0.05)].Fill(len(CLresults))
if self.useexpected and bestSR:
CLsExp = CLresultsExp[bestSR]
ExpCLsPlots.fill(CLsExp)
if bestSR:
try:
ExpCLsSRPlots[bestSR].fill(CLsExp)
except KeyError:
ExpCLsSRPlots[bestSR] = CLsPlots('Expected', 'CLsExp', bestSR)
ExpCLsSRPlots[bestSR].fill(CLsExp)
bestSRkey = bestSR if bestSR else ''
if bestSRkey:
SRcount['total'] += 1
if '+' in '%6e'%(CLresult.value):
SRcount['rounded'] += 1
else:
SRcount['CLs1'] += 1
try:
SRcount[bestSRkey] += 1
except KeyError:
SRcount[bestSRkey] = 1
# Test if model is excluded, record this for posterity if it is
if CLresult.value < 0.05:
ExclusionCount['total'] += 1
BestExclusionCount['total'] += 1
try:
BestExclusionCount[bestSRkey] += 1
except KeyError:
BestExclusionCount[bestSRkey] = 1
addPerSRresult(bestSR, str(int(modelName)))
# Also record all CLs values, regardless of other considerations
for k,v in CLresults.items():
if self.useexpected:
addPerSRCLsresult(k, int(modelName), v.value, CLresultsExp[k].value)
else:
addPerSRCLsresult(k, int(modelName), v.value, '---')
exclusionSRs = []
for k,v in CLresults.items():
if v.value < 0.05:
exclusionSRs.append(k)
try:
ExclusionCount[k] += 1
except KeyError:
ExclusionCount[k] = 1
if exclusionSRs:
ExclusionCount['total_any'] += 1
for exclSR in exclusionSRs:
# Denominator: fill the entire column:
for ibiny in range(1,SRcorr_denominator.GetNbinsY()+1):
SRcorr_denominator.Fill(exclSR, ibiny, 1)
# Numerator: Loop over other SRs
for exclSR2 in exclusionSRs:
# Order does not matter, as every combo comes up eventually
SRcorr_numerator.Fill(exclSR, exclSR2, 1)
stafile.close()
badmodelfile.close()
hepdatafile.close()
yieldfile.Close()
SRcorr_exclusion = SRcorr_numerator.Clone('SRcorr_exclusion')
SRcorr_exclusion.Divide(SRcorr_numerator, SRcorr_denominator, 1, 1, 'B')
# Save the results
outfile = ROOT.TFile.Open('/'.join([outdirname,'CLresults.root']),'RECREATE')
ObsCLsPlots.write()
if self.useexpected:
ExpCLsPlots.write()
for p in ObsCLsSRPlots.values():
p.write()
if self.useexpected:
for p in ExpCLsSRPlots.values():
p.write()
NSRplot.Write()
for p in NSRplots:
p.Write()
SRcorr_exclusion.Write()
SRcorr_numerator.Write()
SRcorr_denominator.Write()
outfile.Close()
from pprint import pprint
print '================== Printing the SRcount results'
pprint(SRcount)
print '================== Printing the ExclusionCount results'
pprint(ExclusionCount)
print '================== Printing the BestExclusionCount results'
pprint(BestExclusionCount)
# Pickle the SR count results, to make a nice table later
SRcountFile = open('/'.join([outdirname,'SRcount.pickle']), 'w')
pickle.dump(SRcount,SRcountFile)
SRcountFile.close()
# And again for the exclusion counts
ExclusionCountFile = open('/'.join([outdirname,'ExclusionCount.pickle']), 'w')
pickle.dump(ExclusionCount,ExclusionCountFile)
ExclusionCountFile.close()
# And again for the best SR exclusion counts
BestExclusionCountFile = open('/'.join([outdirname,'BestExclusionCount.pickle']), 'w')
pickle.dump(BestExclusionCount,BestExclusionCountFile)
BestExclusionCountFile.close()
def PlotSummary(self, dirname):
"""Makes some pdf plots.
Separated from the event loop, as that's so slow."""
canvas = ROOT.TCanvas('can','can',800,600)
infile = ROOT.TFile.Open('/'.join([dirname,'CLresults.root']))
def CLsPlot_withInvalid(basename, logY=False, pdfname=None):
CLsPlot = infile.Get(basename)
CLsPlot_valid = infile.Get(basename+'_valid')
CLsPlot_valid.SetFillColor(ROOT.kBlue)
CLsPlot_valid.SetLineWidth(0)
CLsPlot_valid.Draw()
CLsPlot.Draw('same')
ROOT.ATLASLabel(0.3,0.85,"Internal")
ROOT.myBoxText(0.3,0.8,0.02,ROOT.kWhite,'All models')
ROOT.myBoxText(0.3,0.75,0.02,CLsPlot_valid.GetFillColor(),'Non-extrapolated models')
# HACKHACKHACK
if 'Ewk' in basename:
# This is for an individual SR
ROOT.myText(0.2, 0.95, ROOT.kBlack, basename)
canvas.SetLogy(logY)
if pdfname is None:
canvas.Print('/'.join([dirname,basename+'Plot.pdf']))
else:
canvas.Print('/'.join([dirname,pdfname+'Plot.pdf']))
canvas.SetLogy(0) # Always revert to a linear scale
def CLsPlot_withExpected(basename, logY=False, pdfname=None):
CLsPlot = infile.Get(basename)
CLsExpPlot = infile.Get(basename.replace('Obs','Exp'))
CLsExpPlot.SetLineColor(ROOT.kBlue)
CLsExpPlot.Draw()
CLsPlot.Draw('same')
ROOT.ATLASLabel(0.3,0.85,"Internal")
ROOT.myBoxText(0.3,0.8,0.02,CLsPlot.GetLineColor(),'Observed')
ROOT.myBoxText(0.3,0.75,0.02,CLsExpPlot.GetLineColor(),'Expected')
# HACKHACKHACK
if 'Ewk' in basename:
# This is for an individual SR
ROOT.myText(0.2, 0.95, ROOT.kBlack, basename)
canvas.SetLogy(logY)
if pdfname is None:
canvas.Print('/'.join([dirname,basename+'ExpPlot.pdf']))
else:
canvas.Print('/'.join([dirname,pdfname+'ExpPlot.pdf']))
canvas.SetLogy(0) # Always revert to a linear scale
CLsPlot_withInvalid('CLsObs')
CLsPlot_withInvalid('LogCLsObs', True)
if self.useexpected:
CLsPlot_withExpected('CLsObs')
CLsPlot_withExpected('LogCLsObs', True)
# Try some per-SR plots
pdfname = 'PerSRCLs'
pdfnameLog = 'PerSRLogCLs'
canvas.Print('/'.join([dirname,pdfname+'Plot.pdf[']))
canvas.Print('/'.join([dirname,pdfnameLog+'Plot.pdf[']))
if self.useexpected:
canvas.Print('/'.join([dirname,pdfname+'ExpPlot.pdf[']))
canvas.Print('/'.join([dirname,pdfnameLog+'ExpPlot.pdf[']))
for key in sorted(infile.GetListOfKeys()):
keyname = key.GetName()
if keyname.endswith('_valid'): continue
if keyname.startswith('CLsObs'):
CLsPlot_withInvalid(keyname, pdfname=pdfname)
if self.useexpected:
CLsPlot_withExpected(keyname, pdfname=pdfname)
elif keyname.startswith('LogCLsObs'):
CLsPlot_withInvalid(keyname, True, pdfname=pdfnameLog)
if self.useexpected:
CLsPlot_withExpected(keyname, True, pdfname=pdfnameLog)
canvas.Print('/'.join([dirname,pdfname+'Plot.pdf]']))
canvas.Print('/'.join([dirname,pdfnameLog+'Plot.pdf]']))
if self.useexpected:
canvas.Print('/'.join([dirname,pdfname+'ExpPlot.pdf]']))
canvas.Print('/'.join([dirname,pdfnameLog+'ExpPlot.pdf]']))
NSRname = '/'.join([dirname,'NSRplot.pdf'])
NSRplot = infile.Get('NSRplot')
NSRplot.Draw()
canvas.Print(NSRname+'(')
for ibin in range(20):
NSRplot = infile.Get('NSRplot_%i'%(ibin))
NSRplot.Draw()
ROOT.myText(0.2,0.95,ROOT.kBlack,'Bin %i: %i%% < CLs < %i%%'%(ibin,5*ibin,5*(ibin+1)))
canvas.Print(NSRname)
canvas.Print(NSRname+']')
# Add some useful printout too
CLsObsPlot = infile.Get('CLsObs')
CLsObsPlot_valid = infile.Get('CLsObs_valid')
Ninvalid = CLsObsPlot.Integral() - CLsObsPlot_valid.Integral()
print 'Number of invalid models :',Ninvalid
Nexcluded = CLsObsPlot.Integral(0,CLsObsPlot.GetXaxis().FindBin(0.049))
print 'Number of excluded models:',Nexcluded
def LatexSummary(self, dirname):
"""Makes some LaTeX tables to put directly into the support note (maybe also the paper)."""
# First grab the SR count information
SRcountFile = open('/'.join([dirname,'SRcount.pickle']))
SRcount = pickle.load(SRcountFile)
SRcountFile.close()
blah = []
for SR in SRcount.keys():
if 'SR' in SR:
blah.append(SR)
# And the same for the exclusion counts
ExclusionCountFile = open('/'.join([dirname,'ExclusionCount.pickle']))
ExclusionCount = pickle.load(ExclusionCountFile)
ExclusionCountFile.close()
# And the same for the best SR exclusion counts
BestExclusionCountFile = open('/'.join([dirname,'BestExclusionCount.pickle']))
BestExclusionCount = pickle.load(BestExclusionCountFile)
BestExclusionCountFile.close()
# A combined table of all results
latexfile = open('/'.join([dirname,'SRcountTable.tex']), 'w')
latexfile.write('\\begin{tabular}{lrrr}\n')
latexfile.write('\\toprule\n')
latexfile.write('Signal region & Number of models & Excluded models & Excluded and best SR \\\\ \n')
latexfile.write('\\midrule\n')
def writeLine(latexname,SR):
"""Little helper function for writing one line of the table."""
latexfile.write('%s & \\num{%i}'%(latexname,SRcount[SR]))
if ExclusionCount.has_key(SR):
latexfile.write(' & \\num{%i}'%ExclusionCount[SR])
else:
latexfile.write(' & 0')
if BestExclusionCount.has_key(SR):
latexfile.write(' & \\num{%i} '%BestExclusionCount[SR])
else:
latexfile.write(' & 0 ')
latexfile.write('\\\\ \n')
# Now add in the SR results
# Start with the 2L SRWW results
mySRs = [SR for SR in SRcount.keys() if 'SR_WW' in SR]
for SR in sorted(mySRs):
# It's either SR_WWa, b, or c
whichone = SR.split('_')[2][-1]
writeLine('2$\\ell$ SR-\\Wboson{}\\Wboson{}'+whichone, SR)
# Now on to the 2L Zjets SR
mySRs = [SR for SR in SRcount.keys() if 'Zjets' in SR]
for SR in sorted(mySRs):
# There should be only one...
writeLine('2$\\ell$ SR-\\Zboson{}jets', SR)
# Next, the 2L mT2 SRs
mySRs = [SR for SR in SRcount.keys() if 'SR_mT2' in SR]
for SR in sorted(mySRs):
# It's either SR_mT2a, b, or c
whichone = SR.split('_')[2][-1]
# But we don't call them a,b,c in the note...
whichone = {'a':90, 'b':120, 'c':150}[whichone]
writeLine('2$\\ell$ SR-$\\mttwo^{%i}$'%(whichone), SR)
# Have a break
latexfile.write('\\midrule\n')
# Next, 3L SR0a
mySRs = [SR for SR in SRcount.keys() if 'SR0a' in SR]
for ibin in range(1,21):
# See if we have a result for this bin
theSRs = [SR for SR in mySRs if SR.endswith('_%i'%(ibin))]
if len(theSRs) > 1:
print 'WARNING in WriteLatex: found %i SRs for SR0a bin %i'%(len(theSRs),ibin)
print theSRs
if theSRs:
SR = theSRs[0]
writeLine('3$\\ell$ SR0$\\tau$a bin %i'%(ibin), SR)
# Now the other 3L regions, if we have them
mySRs = [SR for SR in SRcount.keys() if 'SR0b' in SR]
for SR in sorted(mySRs):
# There should be only one...
writeLine('3$\\ell$ SR0$\\tau$b', SR)
mySRs = [SR for SR in SRcount.keys() if 'SR1SS' in SR]
for SR in sorted(mySRs):
# There should be only one...
writeLine('3$\\ell$ SR1$\\tau$', SR)
# Have a break
latexfile.write('\\midrule\n')
# Now the 4L regions
mySRs = [SR for SR in SRcount.keys() if 'FourLepton' in SR]
for SR in sorted(mySRs):
whichone = SR.split('_')[1]
writeLine('4$\\ell$ '+whichone, SR)
# Now the 2tau regions
mySRs = [SR for SR in SRcount.keys() if 'TwoTau' in SR]
# Have a break, _if_ we have any 2tau SRs
if mySRs:
latexfile.write('\\midrule\n')
for SR in sorted(mySRs):
# Let's just hard-code this
if 'C1C1' in SR:
latexSR = 'SR-C1C1'
elif 'C1N2' in SR:
latexSR = 'SR-C1N2'
elif 'highMT2' in SR:
latexSR = 'SR-DS-highMass'
elif 'lowMT2' in SR:
latexSR = 'SR-DS-lowMass'
writeLine('2$\\tau$ '+latexSR, SR)
latexfile.write('\\midrule\n')
writeLine('All SRs', 'total')
# Finish the file off
latexfile.write('\\bottomrule\n')
latexfile.write('\\end{tabular}\n')
latexfile.close()
if __name__ == '__main__':
# Add some command line options
import argparse
parser = argparse.ArgumentParser(
description="""
Reads truth yields and uses the CLs calibration functions to produce the ATLAS likelihood.""",
)
parser.add_argument(
"-a", "--all",
action = "store_true",
dest = "all",
help = "Process the full event loop")
parser.add_argument(
"-s", "--strategy",
dest = "strategy",
choices = ['smallest','twosmallest'],
default = 'smallest',
help = "How to combine multiple CLs values")
parser.add_argument(
"-t", "--truncate",
action = 'store_true',
dest = "truncate",
help = "Truncate CLs values below 1e-6")
parser.add_argument(
"-e", "--useexpected",
action = 'store_true',
dest = "useexpected",
help = "Use expected CLs to determine the best results")
parser.add_argument(
"-n", "--nmodels",
type = int,
dest = "nmodels",
help = "Only analyse N models (for testing)")
parser.add_argument(
"--truthlevel",
action = "store_true",
dest = "truthlevel",
help = "Get yields from evgen rather than official MC")
parser.add_argument(
"--systematic",
dest = "systematic",
choices = [None, "Lin", "Quad", "2L", "LinAll", "QuadAll"],
help = "Try a systematic variation of the CLs calibration")
parser.add_argument(
"--subset",
action = "store_true",
dest = "subset",
help = "Perform the analysis using D3PDs_testsubset.txt")
cmdlinearguments = parser.parse_args()
import ROOT
ROOT.gROOT.SetBatch(True)
ROOT.gROOT.LoadMacro("AtlasStyle.C")
ROOT.SetAtlasStyle()
ROOT.gROOT.LoadMacro("AtlasUtils.C")
ROOT.gROOT.LoadMacro("AtlasLabels.C")
# Let's create subdirectories so different runs don't overwrite each other
subdirname = cmdlinearguments.strategy
if cmdlinearguments.truncate:
subdirname += 'Truncate'
if cmdlinearguments.truthlevel:
subdirname += '_privateMC'
else:
subdirname += '_officialMC'
if cmdlinearguments.useexpected:
subdirname += '_bestExpected'
else:
subdirname += '_bestObserved'
if cmdlinearguments.systematic:
subdirname += '_sys'+cmdlinearguments.systematic
if cmdlinearguments.subset:
subdirname += '_subset'
outdirname = '/'.join(['results',subdirname])
if cmdlinearguments.nmodels:
outdirname += '_test'
CLsdir = 'plots_privateMC' if cmdlinearguments.truthlevel else 'plots_officialMC'
if cmdlinearguments.systematic:
CLsdir += '_sys'+cmdlinearguments.systematic
if cmdlinearguments.subset:
CLsdir += '_subset'
if cmdlinearguments.subset:
# Special kind of run: just a subset of the "sim" samples
# We need an event list in this case
ELfile = ROOT.TFile.Open('Data_Yields/EventLists_sim.root')
EL = ELfile.Get('elist_TestSample')
EL.SetDirectory(0)
ELfile.Close()
infile = 'Data_Yields/SummaryNtuple_STA_sim.root'
else:
EL = None
infile = 'Data_Yields/SummaryNtuple_STA_evgen.root'
obj = Combiner(infile, '/'.join([CLsdir,'calibration.root']))
if cmdlinearguments.all:
obj.strategy = cmdlinearguments.strategy
obj.truncate = cmdlinearguments.truncate
obj.useexpected = cmdlinearguments.useexpected
obj.ReadNtuple(outdirname, cmdlinearguments.nmodels, EL)
obj.PlotSummary(outdirname)
obj.LatexSummary(outdirname)
|
ad12922f69612f9cf7525b4795c3e1abb5e00233 | Mr-Rakib/Python | /FileIO/main.py | 624 | 3.890625 | 4 | """
r - read mode - default
w - write mode
x - create file if not exist
a - append to the file
t - text mode - default
b - binary mode
+ - read and update
file.read() -> read the hole file as a text
file.readLine() -> read by line
file.readLines()
file.open()
file.close()
"""
file = open("student.json")
file2 = open("rakib.txt")
# content = file.read(100) read the 100 character
# content = file.read()
for index in file:
print(index)
file.close()
file2.close()
file = open("student.json")
file2 = open("rakib.txt")
print(file2.readline())
print(file.readlines())
|
f8e1592a3803f01017496bf6f67411712b8fac3d | ranrolls/pythonExFiles | /4-ELHCLT00046625/basic_dataStructure.py | 1,563 | 3.96875 | 4 | Python 3.6.0a4 (v3.6.0a4:017cf260936b, Aug 16 2016, 00:45:10) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print('hey')
hey
>>> aL = []
>>> for n in range(1,4):
aL += [n]
>>> aL
[1, 2, 3]
>>> for n in range(5,9):
aL.append(n)
>>> aL
[1, 2, 3, 5, 6, 7, 8]
>>> aL[3]
5
>>> aL[2] = 100
>>> aL
[1, 2, 100, 5, 6, 7, 8]
>>> # tuples now =>
>>> t1 = 1,2,3,4,5
>>> t1
(1, 2, 3, 4, 5)
>>> t1[3]
4
>>> # tuple items cannot be re assigned
>>> t1[3]= 2
Traceback (most recent call last):
File "<pyshell#18>", line 1, in <module>
t1[3]= 2
TypeError: 'tuple' object does not support item assignment
>>> t1
(1, 2, 3, 4, 5)
>>> # unpack items for string, list, tuple
>>> aS = "abc"
>>> aL = [1,2,3]
>>> aT = "a","A",3
>>> a,b,c = aS
>>> print(a,b,c)
a b c
>>> a,b,c = aL
>>> print(a,b,c)
1 2 3
>>> a,b,c = aT
>>> print(a,b,c)
a A 3
>>> aD = {}
>>> aD = {'a':0,'b':1,'c':2,'d':3}
>>> aD
{'c': 2, 'd': 3, 'a': 0, 'b': 1}
>>> aD['c']
2
>>> aD['e'] = 4
>>> aD
{'c': 2, 'd': 3, 'e': 4, 'a': 0, 'b': 1}
>>> aD['e'] = 5
>>> aD
{'c': 2, 'd': 3, 'e': 5, 'a': 0, 'b': 1}
>>> del aD['e']
>>> aD
{'c': 2, 'd': 3, 'a': 0, 'b': 1}
>>> # we have different methods available for list and dictionaries
>>> aL.sort()
>>> aL
[1, 2, 3]
>>> bL = range(0,99,3)
>>> bL
range(0, 99, 3)
>>> aL = range(0,88,3)
>>> aL
range(0, 88, 3)
>>> aL = [1,2,4,5,65,6,6]
>>> sK = int(input('enter search index key'))
enter search index key2
>>> aL.index(sK)
1
>>> aL
[1, 2, 4, 5, 65, 6, 6]
>>> # INDEX is used to index for given value
>>>
|
e86b773f209395a03aa64681e360a367de349136 | alexander-travov/algo | /InterviewBit/GraphAlgorithms/CommutableIslands.py | 2,672 | 4.0625 | 4 | # -*- coding: utf8 -*-
"""
Commutable Islands
==================
There are A islands and there are M bridges connecting them. Each bridge has some cost attached to it.
We need to find bridges with minimal cost such that all islands are connected.
It is guaranteed that input data will contain at least one possible scenario in which all islands are connected with each other.
Input Format:
The first argument contains an integer, A, representing the number of islands.
The second argument contains an 2-d integer matrix, B, of size M x 3:
=> Island B[i][0] and B[i][1] are connected using a bridge of cost B[i][2].
Output Format:
Return an integer representing the minimal cost required.
Constraints:
1 <= A, M <= 6e4
1 <= B[i][0], B[i][1] <= A
1 <= B[i][2] <= 1e3
Examples:
Input 1:
A = 4
B = [ [1, 2, 1]
[2, 3, 4]
[1, 4, 3]
[4, 3, 2]
[1, 3, 10] ]
Output 1:
6
Explanation 1:
We can choose bridges (1, 2, 1), (1, 4, 3) and (4, 3, 2), where the total cost incurred will be (1 + 3 + 2) = 6.
Input 2:
A = 4
B = [ [1, 2, 1]
[2, 3, 2]
[3, 4, 4]
[1, 4, 3] ]
Output 2:
6
Explanation 2:
We can choose bridges (1, 2, 1), (2, 3, 2) and (1, 4, 3), where the total cost incurred will be (1 + 2 + 3) = 6.
"""
from __future__ import print_function
from collections import namedtuple
from operator import attrgetter
Edge = namedtuple("Edge", "start stop weight")
class DSU:
class Node:
def __init__(self):
self.root = None
self.rank = 0
def get_root(self):
if self.root is None:
return self
self.root = self.root.get_root()
return self.root
def __init__(self, n):
self.nodes = [DSU.Node() for _ in range(n)]
def equivalent(self, x, y):
return self.nodes[x-1].get_root() == self.nodes[y-1].get_root()
def unite(self, x, y):
xr = self.nodes[x-1].get_root()
yr = self.nodes[y-1].get_root()
small, big = (xr, yr) if xr.rank < yr.rank else (yr, xr)
small.root = big
if small.rank == big.rank:
big.rank += 1
def kruskal(n, edges):
dsu = DSU(n)
edges.sort(key=attrgetter('weight'))
mst = []
for e in edges:
if not dsu.equivalent(e.start, e.stop):
dsu.unite(e.start, e.stop)
mst.append(e)
if len(mst) == n-1:
break
return mst
mst = kruskal(n=4, edges=[Edge(*e) for e in [
[1, 2, 1],
[2, 3, 4],
[1, 4, 3],
[4, 3, 2],
[1, 3, 10]
]])
print('Cost:', sum(e.weight for e in mst))
|
db67594fddca76f2bed9632a2a48a1cdadb3d4dc | rafaelperazzo/programacao-web | /moodledata/vpl_data/59/usersdata/195/61943/submittedfiles/testes.py | 684 | 3.765625 | 4 | # -*- coding: utf-8 -*-
def interseção(a,b):
cont=0
indice=0
if len(a)<len(b):
while indice<len(a):
for j in range(0,len(b),1):
if listaindice==b[j]:
con=cont+1
indice=indice+1
else:
while indice<len(b):
for j in range(0,len(a),1):
if listaindice==a[j]:
cont=cont+1
indice=indice+1
return(cont)
n=int(input('digite n:'))
m=int(input('digite m:'))
d=[]
f=[]
for i in range(n):
d=float(input('digite d:'))
d=d+[a]
for i in range(m):
f=float(input('digite f:'))
f=f+[a]
c=interseção(d,f)
print(c)
|
06c5a955b925276dcd46be316f0f917727a2ee7c | vanshaw2017/leetcode_vanshaw | /349_intersection/349_solution.py | 447 | 3.78125 | 4 | class Solution:
def intersection(self, nums1, nums2):
"""
:type nums1: List[int]
:type nums2: List[int]
:rtype: List[int]
"""
intersection=[]
for i in nums1:
for j in nums2:
if (i==j ):
if(i in intersection):
pass
else:
intersection.append(i)
return intersection |
47ccdd71212ca7c53eb5854b9bdf6a97cc4b9b7e | vegetdove/learngit | /homework1/YearJudge.py | 175 | 3.828125 | 4 | print("请输入一个年份",end=" ")
year = int(input())
if(year % 4 == 0 and year % 400 != 0) :
print(year,"年是闰年")
else :
print(year,"年不是闰年") |
f5db747c8f42a3cb02d14169733f8e015571d462 | dguelde/python | /Algorithms/hw2/Guelde_Donovan_HW2.py | 3,763 | 4.09375 | 4 | # Author: Donovan Guelde
# CSCI-3104 FAll 2015
# HW 2: write a python program implementing RSA encryption to encrypt and decrypt a simple message
# Automatically executes RSA algorithm with 8,16, and 24 bit-length keys, and displays relevant info
# On my honor, as a University of Colorado at Boulder student,
# I have neither given nor received unauthorized assistance.
from random import randint
from math import floor
import time
# takes a potentially prime number as input and runs Fermat's Little Theorem test
# to check for primality. Returns a boolean.
def isPrime(possiblePrime):
for k in range(0,10): #100 iterations of Fermat's Little Theorem (pretty sure it's gonna be accurate...)
a = long(randint(2,possiblePrime-1)) #random a between 2 and N-1
if (modExp(a,possiblePrime-1,possiblePrime)!=1): # a^(N-1) mod N !=1 then not prime
return False
return True #passed all tests so true
def numberGenerator(upperLimit): #generates a potentially prime number up to the bit limit specified by user
possiblePrimeFound = False #flag
while (possiblePrimeFound == False): #while not found
possiblePrime = long(randint(2,upperLimit)) #generates a number between 2 and 2^(bitlimit) - 1
if (possiblePrime%10 == 1 or possiblePrime%10==3 or possiblePrime%10==7 or possiblePrime%10 ==9):
#use only if ends in 1,3,7,9
possiblePrimeFound = True #set flag
return possiblePrime
def generatePrime(y,x): #generates a prime number between lower and an upper limit
primeFound = False
while (primeFound==False):
possiblePrime = long(numberGenerator(x)) #generate posssibly prime number
if (isPrime(possiblePrime)==True and possiblePrime>y): #check primality
return possiblePrime
def gcd(a,b): #finds gcd(a,b) recursively
if (b==0):
return a
return gcd(b, a%b)
def modExp(x,y,n): #returns (x^y) mod n
if (y==0):
return 1
else:
z = modExp(x,(y//2),n)
if (y%2==0):
return ((z*z)%n)
else:
return ((x*z**2)%n)
def extendedEuclidean(a,b): #finds gcd(a,b) and returns x,y,d s.t. xa + by = d
if (b == 0):
return 1,0,a
else:
xprime,yprime,d = extendedEuclidean(b,a % b)
return (yprime, xprime-(a//b)*yprime, d) #returns x,y,d where xa yN= 1 (mod N)
def generateD(e,N): #generates private key d via extended Euchlid algorithm
xPrime, yPrime, g = extendedEuclidean(e,N) # xprime*a = 1 mod N (other values discarded)
if (xPrime<0): #ensure d>0
xPrime+=N
return int(xPrime)
def runRSA(bitLength):
start = start1 = start2 = 0 #reset timer variables
message = 2015
upperLimit = 2**(bitLength-1)-1
lowerLimit = 2**(bitLength-2) #ensures that the key is 'bitlength' bits (not led by a bunch of zeros)
start = time.time()
p = generatePrime(lowerLimit,upperLimit) # p and q are primes in the range (2^bitLimit)-1 and (2^(limit-1))
q = generatePrime(lowerLimit,upperLimit) #avoids 0000000000000001, etc...
N = p*q
phi = (p-1)*(q-1)
eFound = False
e = 17
while (eFound == False):
gcdEPhi = gcd(e,phi)
if gcdEPhi==1:
eFound = True
else:
e+=1
d = generateD(e,phi)
print "time to generate keys (including p, q, N, phi, d,and e",time.time() - start
encryptedMessage=modExp(message,e,N) #encrypt (message^e)mod N
decryptedMessage=modExp(encryptedMessage,d,N) #decrypt (encryptedMessage^d)mod N
#print relevant info
print "key length:",bitLength,"bits"
print "p =",p
print "q =",q
print "N = ",N
print "phi =",phi
print "message =",message
start2 = time.time()
print "encryptedMessage =",encryptedMessage
print "time to encrypt message",time.time() - start2
start3 = time.time()
print "decryptedMessage =",decryptedMessage
print "time to decrypt message",time.time() - start3
print "\n"
return
def main():
x = input("how many bits")
runRSA(x)
#runRSA(16)
#runRSA(24)
main() |
070a4f1449ee54ffcd1cc4e0d89b8464bdd71daf | niladri18/coding_problems_python | /chap5.py | 1,113 | 3.84375 | 4 | import sys
'''
Problem 5.1
You are given two 32-bit numbers, N and M, and two bit positions, i and j.
Write a method to set all bits between i and j in N equal to M
(e.g., M becomes a substring of N located at i and starting at j).
'''
x = int('101011',2)
y = int('1000111100000',2)
j = 2
i = 7
#All 1's
max_i = ~0
#All 1's from left to i
left = max_i -((1 << i)-1)
#All 1's to the right of j
right = (1<<j) - 1
mask = left|right
movex = x << j
print(bin(movex))
print(bin((mask&y)|movex))
'''
Given a (decimal - e.g. 3.72) number that is passed in as a string,
print the binary representation. If the number can not be represented
accurately in binary, print “ERROR”
'''
x = '3.72'
x = '0.25'
x = x.split('.')
print(x)
n = int(x[0])
intpart = ''
while n > 0:
bit = int(n%2)
#print(str(bit))
n = n//2
intpart += str(bit)
d = float('.'+x[1])
#print(d)
decpart = ''
while d > 0:
if len(x[1]) > 32:
print('ERROR:')
break
if d==1:
decpart += str(d)
break
r = d*2
if r >= 1:
decpart += str(1)
d = r-1
else:
decpart += str(0)
d = r
print(intpart+'.'+decpart)
|
2be0b04a612847ea0417bf0095a2329a06e6a846 | mrarmyant/python_oop | /car.py | 599 | 3.5625 | 4 | class Car:
def __init__(self,price,speed,fuel,mileage):
self.price=price
self.speed=speed
self.fuel=fuel
self.mileage=mileage
self.salesTax=15 if price>10000 else 12
def display_all(self):
return ("price:" + str(self.price), "speed:" + str(self.speed), "fuel:" + str(self.fuel), "mileage:" + str(self.mileage), "tax:" + str(self.salesTax))
Porsche=Car(80020,181,13,5)
Audi=Car(180000,202,15,80)
Acura=Car(220000,198,10,12)
Chevrolet=Car(90000,200,13,5)
Volvo=Car(1000,80,20,500000)
Delorean=Car(80000,181,13,5)
print (Porsche.display_all())
|
bc6668fa0dfee7eb0cf2c585fede81a9724a8706 | human02/solved-questions | /349. Intersection of Two Arrays.py | 1,739 | 3.984375 | 4 | """
Given two integer arrays nums1 and nums2, return an array of their intersection. Each element in the result must be unique and you may return the result in any order.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]
Explanation: [4,9] is also accepted.
Constraints:
1 <= nums1.length, nums2.length <= 1000
0 <= nums1[i], nums2[i] <= 1000
"""
# Using Python Set type methods
class Solution:
def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
nums1=set(nums1)
nums2=set(nums2)
return(list(nums1.intersection(nums2)))
"""
This is a Facebook interview question.
They ask for the intersection, which has a trivial solution using a hash or a set.
Then they ask you to solve it under these constraints:
O(n) time and O(1) space (the resulting array of intersections is not taken into consideration).
You are told the lists are sorted.
Cases to take into consideration include:
duplicates, negative values, single value lists, 0's, and empty list arguments.
Other considerations might include
sparse arrays.
function intersections(l1, l2) {
l1.sort((a, b) => a - b) // assume sorted
l2.sort((a, b) => a - b) // assume sorted
const intersections = []
let l = 0, r = 0;
while ((l2[l] && l1[r]) !== undefined) {
const left = l1[r], right = l2[l];
if (right === left) {
intersections.push(right)
while (left === l1[r]) r++;
while (right === l2[l]) l++;
continue;
}
if (right > left) while (left === l1[r]) r++;
else while (right === l2[l]) l++;
}
return intersections;
}
""" |
2cb01bbf4052151df651fec433eaa20c9eb63541 | SandraCoburn/cs-module-project-hash-tables | /applications/word_count/word_count.py | 651 | 3.984375 | 4 | import re #regular expressions
def word_count(s):
d = {}
#ignored = ['"', ':', ';', ',', '.', '-','+','=','\\','|','[',']','{', '}', '(', ')','*', '^', '&', '/']
words = s.lower().split()
for w in words:
w = re.sub(r'[^\w\']+', '', w)
if w == "":
continue
if w not in d:
d[w] = 0
d[w] += 1
return d
if __name__ == "__main__":
print(word_count(""))
print(word_count("Hello"))
print(word_count('Hello, my cat. And my cat doesn\'t say "hello" back.'))
print(word_count('This is a test of the emergency broadcast network. This is only a test.')) |
f151670e1f909e20e59fa0f3bd398e993546a173 | nsapundzhiev/HackBG | /week2/ 2-File-System-Problems/cat.py | 236 | 3.59375 | 4 | import sys
def cat():
if len(sys.argv) > 1:
filename = sys.argv[1]
file = open (filename, "r")
content = file.read()
return content
file.close()
else:
return "Please enter a file"
if __name__ == '__cat__':
print(cat())
|
b533ba3978f6e642e4853da1e631c37da785e73b | celetrik/bug-free-umbrella | /my_info.py | 1,146 | 3.96875 | 4 | # get the user name when the file is run
# from sys import argv
# filename, name = argv
# prompt = ">>"
# print(f"Hi {name}")
# print(f"I'm going to ask you a series of questions")
# print(f"How many keys are there on a computer keyboard?", end = '')
# keys = int(input(prompt))
# #conditions
# #if the answer 296 they are correct
# #if the answer is less than 296 they are wrong
# #if the answer is more than 296 they are wrong
# if keys > 296:
# print('incorrect answer')
# elif keys < 296:
# print('incorrect answer ')
# else:
# print('correct answer')
# num = 4
# for i in range(10, 20, 2): #loop through the variable in a range of 7
# print (num) #print the value of num
# num = num + 1 #update the value of num by adding 1
password = "mynameishill"
# while True:
# print("type your name")
# name = input()
# print("type your password")
# pw = input()
# if (pw != password):
# print("incorrect password, Access Denied")
# else:
# print("Access granted")
# break
# print(f"Thanks, {name}")
num =20
while num < 30:
print(num)
num = num + 1
|
e6c5ab088004f2540ca6a4d25bc041e5a287e86c | quangineer/soccerdatawithpandas | /SQLdatasoccer.py | 1,962 | 4.21875 | 4 | import pandas as pd
filedata = 'data.csv'
#Read File :
data = pd.read_csv(filedata)
#Make an object out of an object:
data_Age = data["Age"]
#Make a list from object of data["Age"] from object of data:
# data_Age = data["Age"].tolist()
#Use python to find out how many players' age equal and over 30:
# A = []
# for i in range(len(data_Age)):
# if data_Age[i] >= 30:
# A.append(data_Age[i])
# print (len(A))
#Shorter verion of the operation above:
# B = 0
# for i in range(len(data_Age)):
# if data_Age[i] >= 30:
# B += 1
# print (B)
#print how many columns and how many row in each column (does not count cell without any values)
# print (data.count())
#print how many row in columns Age
# print (data_Age.count())
#given the condition of Age >= 30, find out how many players in data file using SQL:
#This SQL count include every columns counts
# print ((data[data.Age >= 30]).count())
#Using SQL to count: First select only column Age (of table data) where Age >= 30, then start counting
#For this SQL count, have to decide which column , which condition first to narrow the result, then using index of
#data file to start counting.
# print ((data[data.Age >= 30])["Age"].count())
########################
#which player under 30 get paid the most?
#Remember: to strip an object, we use .item()
#SELECT Name
#From data
#Where Age < 30
#Order by Salary DESC,
#Limit 1
# print (data[data.Age < 30].sort_values('Value',ascending = False)["Name"][0:1].item())
#########################
#which player has the most potential but get paid the least?
#SELECT Name
#From data
#Order by Potential DESC, Wage
#Limit 1
# print (data.sort_values((["Wage"],descending=False))(["Potential"], ascending=False))
# sorted = data.sort_values(by=['Potential', 'Wage'], ascending=[False, True])[0:1]["ID"].item()
# print(sorted)
sorted2 = data.sort_values(by=['Potential', 'Wage'], ascending=[False, True])[0:2]["Name"]
print(sorted2)
|
1f654d5893c3cc754458592e7d53160d792210ad | EpsilonHF/Leetcode | /Python/1041.py | 1,097 | 4.25 | 4 | """
On an infinite plane, a robot initially stands at (0, 0) and
faces north. The robot can receive one of three instructions:
"G": go straight 1 unit;
"L": turn 90 degrees to the left;
"R": turn 90 degress to the right.
The robot performs the instructions given in order, and repeats
them forever.
Return true if and only if there exists a circle in the plane
such that the robot never leaves the circle.
Example 1:
Input: "GGLLGG"
Output: true
Explanation:
The robot moves from (0,0) to (0,2), turns 180 degrees, and then
returns to (0,0).
When repeating these instructions, the robot remains in the circle
of radius 2 centered at the origin.
"""
class Solution:
def isRobotBounded(self, instructions: str) -> bool:
direct = [(0, 1), (1, 0), (0, -1), (-1, 0)]
i = 0
x, y = 0, 0
for move in 4 * instructions:
if move == 'L':
i = (i - 1) % 4
elif move == 'R':
i = (i + 1) % 4
else:
x += direct[i][0]
y += direct[i][1]
return not x and not y
|
21e49d1ad698cd59df0c262c7ee21287a9759072 | ShellCode33/CompressionAlgorithms | /compress/algorithms/huffman.py | 9,856 | 3.6875 | 4 | # coding: utf-8
from compress.utils.binary_tree import *
class HuffmanNode(Node):
"""Unlike the classic Node, the HuffmanNode is sorted by frequency and not value.
Attributes
----------
frequency : int
Holds the frequency of the byte(s).
"""
def __init__(self, frequency=0, value=None):
super().__init__(value)
self.frequency = frequency
def __lt__(self, other):
return self.frequency < other.frequency
def __str__(self):
if self.is_leaf():
return "[{}]".format(self.value)
return "<{}> ( {} {} )".format(self.frequency, self.left, self.right)
class Huffman(BinaryTree):
""" This class is an implementation of the Huffman compression algorithm.
Attributes
----------
bytes_occurrences : dict
Association between a byte and its number occurrences.
huffman_code : dict
Association between a byte and its new code.
encoded_tree : str
Contains the tree in a minimalist representation. This is a binary string that will be converted
Notes
-----
The method we have chosen to use here is semi-adaptive because it will build a tree based on actual frequencies
instead of using static symbols weights.
(but it will not dynamically change the tree like the real adaptive algorithm
https://en.wikipedia.org/wiki/Adaptive_Huffman_coding ).
The problem with this method is that we have to transmit the tree with the encoded content in order to decompress.
The tree can't be bigger than 256 leaves, which means this method will be good to compress big chunks of data but
it will be inefficient to compress small ones.
"""
def __init__(self, verbose=False):
super().__init__()
self.verbose = verbose
self.bytes_occurrences = {}
self.huffman_code = {}
self.encoded_tree = None
def create_node(self, left=None, right=None):
""" Redefine parent's behavior.
Notes
-----
Our algorithm only cares about tree leaves but we need the tree to be built depending on bytes occurrences,
that why newly created node's value will be an addition of children sort_on values (which are in this algorithm
byte occurrences).
"""
new_node = HuffmanNode(0 if left is None or right is None else left.frequency + right.frequency)
new_node.left = left
new_node.right = right
return new_node
def traversal_action(self, node):
"""Overwrites BinaryTree's default action.
In huffman, the traversal enables the creation of a binary minimalist representation of the tree in order
to store the tree space-efficiently.
Parameters
----------
node : Node
The node to process.
"""
if node.is_leaf():
self.encoded_tree += "1" + format(node.value, "08b")
else:
self.encoded_tree += "0"
def __find_bytes_occurrences(self, bytes_list):
self.bytes_occurrences.clear()
# Count bytes
for byte in bytes_list:
try:
self.bytes_occurrences[byte] += 1
except KeyError:
self.bytes_occurrences[byte] = 1
def __create_huffman_code(self, node, code=""):
if node.is_leaf():
self.huffman_code[node.value] = code
else:
self.__create_huffman_code(node.left, code + "0")
self.__create_huffman_code(node.right, code + "1")
def build_tree_from(self, binary_string):
""" Recreates the tree when minimized by the traversal_actions and stored to a file.
Attributes
----------
binary_string : str
Contains the bits from the whole file.
"""
self.root_node = self.create_node()
self.root_node.value = 0
return self.__build_tree_from(binary_string, self.root_node)
def __build_tree_from(self, binary_string, current_node, current_index=0):
current_node.left = self.create_node()
current_node.right = self.create_node()
bit = binary_string[current_index]
if bit == "1":
# We grab the 8 bits following the 1
current_node.left.value = int(binary_string[current_index + 1:current_index + 1 + 8], 2)
current_index += 9 # Skip the 1 and the 8 following bits
else:
current_node.left.value = 0
current_index = self.__build_tree_from(binary_string, current_node.left, current_index+1)
bit = binary_string[current_index]
if bit == "1":
# We grab the 8 bits following the 1
current_node.right.value = int(binary_string[current_index + 1:current_index + 1 + 8], 2)
current_index += 9 # Skip the 1 and the 8 following bits
else:
current_node.right.value = 0
current_index = self.__build_tree_from(binary_string, current_node.right, current_index+1)
return current_index
def __compress(self, bytes_list):
self.__find_bytes_occurrences(bytes_list)
if self.verbose:
print("Occurrences: " + str(self.bytes_occurrences))
print("Number of different bytes : {}".format(len(self.bytes_occurrences)))
self.build_tree([HuffmanNode(self.bytes_occurrences[byte], byte) for byte in self.bytes_occurrences])
if self.verbose:
print("Tree: " + str(self.root_node))
self.__create_huffman_code(self.root_node)
if self.verbose:
print("Code: " + str(self.huffman_code))
encoded_string = "1" # Padding needed to convert to bytes, otherwise we will lose information (the first zeros)
for byte in bytes_list:
encoded_string += self.huffman_code[byte]
# Convert to bytes array
return int(encoded_string, 2).to_bytes((len(encoded_string) + 7) // 8, byteorder='big')
def compress_file(self, input_filename, output_filename):
if self.verbose:
print("Reading {}...".format(input_filename))
with open(input_filename, "rb") as input_file:
bytes_list = input_file.read() # All the file will be in memory, can be a problem with huge files.
if not bytes_list:
raise IOError("File is empty !")
if self.verbose:
print("Input size : ", len(bytes_list))
compressed = self.__compress(bytes_list)
if self.verbose:
print("Compressed size : ", len(compressed))
# There is a maximum of 256 leaves in the tree (because there are 256 different bytes), so the number of leaves
# in the tree will be encoded on 1 byte. A byte can be any value between 0 and 255. And the maximum number of
# leaves is 256. So we will store size-1. It's not a problem because the tree can't contain 0 leaf.
self.encoded_tree = "" # Reset encoded tree
self.preorder_traversal()
# Pad with a 1 to keep zeros
self.encoded_tree = "1" + self.encoded_tree[1:] # Remove the 0 of the root node which is useless, 1 bit gain :)
tree_big_int_format = int(self.encoded_tree, 2)
final_encoded_tree = tree_big_int_format.to_bytes((tree_big_int_format.bit_length() + 7) // 8, 'big')
if self.verbose:
print("final_encoded_tree = ", final_encoded_tree)
total_file_size = len(final_encoded_tree) + len(compressed)
if self.verbose:
print("Total size output : {} bytes".format(total_file_size))
if len(bytes_list) <= total_file_size:
raise Exception("Aborted. No gain, you shouldn't compress that file. (+{} bytes)".format(
total_file_size - len(bytes_list)))
compression_rate = 100 - total_file_size * 100 / len(bytes_list)
# Print anyway, even when not in verbose mode
print("Compression gain : {0:.2f}%".format(compression_rate))
with open(output_filename, "wb") as output_file:
output_file.write(final_encoded_tree)
output_file.write(compressed)
return compression_rate
def __decompress(self, compressed_data_bits):
decompressed = []
current_node = self.root_node
for i in compressed_data_bits:
if current_node.is_leaf():
decompressed.append(current_node.value)
current_node = self.root_node
if i == "0":
current_node = current_node.left
elif i == "1":
current_node = current_node.right
return bytes(decompressed)
def decompress_file(self, input_filename, output_filename):
with open(input_filename, "rb") as input_file:
bytes_list = input_file.read() # All the file will be in memory, can be a problem with huge files.
if not bytes_list:
raise IOError("File is empty !")
binary_string = ""
for byte in bytes_list:
binary_string += format(byte, "08b")
padding_index = 0
while binary_string[padding_index] == "0":
padding_index += 1
binary_string = binary_string[padding_index+1:] # Remove first zeros and the 1 padding
tree_end_index = self.build_tree_from(binary_string)
binary_string = binary_string[tree_end_index:]
if self.verbose:
print("Rebuilt tree: ", self.root_node)
padding_index = 0
while binary_string[padding_index] == "0":
padding_index += 1
binary_string = binary_string[padding_index + 1:] # Remove first zeros and the 1 padding
decompressed = self.__decompress(binary_string)
with open(output_filename, "wb") as output_file:
output_file.write(decompressed)
|
51d054fa29a5c65a12b0f5556bea69e7c4f0ed57 | DasisCore/python_challenges-master | /pyChallenge_058.py | 399 | 3.78125 | 4 | import random
score = 0
for i in range(1, 6):
r_num1 = random.randint(1, 50)
r_num2 = random.randint(1, 50)
answer = r_num1 + r_num2
print(r_num1, '+', r_num2, '= ?')
reply = int(input('Your answer? : '))
if reply == answer:
print('"Well done!"\n')
score = score + 1
else:
print('"Wrong answer."\n')
print('There are ', score, 'correct answers.')
|
2aa16eaad49faac5b6cd268e1923bd2a9f26a51b | Sauluslo/holbertonschool-higher_level_programming | /0x04-python-more_data_structures/4-only_diff_elements.py | 211 | 3.578125 | 4 | #!/usr/bin/python3
""" A Function that returns a set of
all elements present in only one set.
"""
def only_diff_elements(set_1, set_2):
set_list = set_1.symmetric_difference(set_2)
return set_list
|
32d93e5c2a76460809f71b66c4d95929a19294e4 | chuckinator0/Projects | /scripts/mergesort.py | 1,966 | 4.4375 | 4 | '''
Mergesort!
'''
def merge(left, right):
"""
This function merges two sorted subarrays into one sorted array.
"""
result = []
left_index = 0
right_index = 0
# We check each subarray from left to right, appending the lower value
# to a result array. The left_index is updated when a value from the left
# subarray is appended, and vice versa with the right_index.
while left_index < len(left) and right_index < len(right):
if left[left_index] < right[right_index]:
result.append(left[left_index])
left_index += 1
else:
result.append(right[right_index])
right_index += 1
# One of the arrays might be longer than the other. In which case, we just append the rest of whichever
# array is longer
try:
result.extend(left[left_index:])
except IndexError:
pass
try:
result.extend(right[right_index:])
except IndexError:
pass
return result
left = [1,2,3,4]
right = [3,4,5,6]
print(merge(left,right)) # should give [1,2,3,3,4,4,5,6]
def mergeSort(array):
"""
Divide, conquer, and combine to sort an array.
We break the array into parts [leftpoint, ..., midpoint,..., endpoint] -> [leftpoint,...,midpoint] and [midpoint+1,...,endpoint]
We recursively sort the subarrays and merge the sorted subarrays together. The base case is a singleton array.
"""
length = len(array)
# The base case. A singleton array is very easy to sort because it's already sorted.
if length == 1:
return array
# this is the midpoint of the array (rounded down)
midpoint = length // 2
# create sorted subarrays. The left subarray goes from the beginning to the midpoint.
left = mergeSort( array[ : midpoint] )
# The right subarray goes from the midpoint to the end.
right = mergeSort( array[ midpoint : ] )
# merge the sorted subarrays and return the sorted list!
return merge(left,right)
array = [1,4,3,6,2,5,7,8,2,4,8,4,9,9,5,1,2]
print(mergeSort(array)) # should give [1, 1, 2, 2, 2, 3, 4, 4, 4, 5, 5, 6, 7, 8, 8, 9, 9]
|
c90954c0d3273c5a3ee4d3c99f9925f6371f519b | wang264/JiuZhangLintcode | /DP/L6/29_interleaving-string.py | 3,230 | 3.953125 | 4 | # 29. Interleaving String
# 中文English
# Given three strings: s1, s2, s3, determine whether s3 is formed by the interleaving of s1 and s2.
#
# 样例
# Example 1:
#
# Input:
# "aabcc"
# "dbbca"
# "aadbbcbcac"
# Output:
# true
#
# Example 2:
# Input:
# ""
# ""
# "1"
# Output:
# false
#
# Example 3:
# Input:
# "aabcc"
# "dbbca"
# "aadbbbaccc"
# Output:
# false
#
# 挑战
# O(n2) time or better
class Solution:
"""
@param s1: A string
@param s2: A string
@param s3: A string
@return: Determine whether s3 is formed by interleaving of s1 and s2
"""
# A=s1, B=s2, X=s3
# f[i][j] = X的前i+j个字符是否为A的前i个字符和B的前j个字符交替组成。
# A的长度为m, B的长度为n,X的长度是m+n
# 我们看最后一步,假设X是由A和B交错形成的,那么X的最后一个字符X[m+n-1]有两种情况。
# 情况一:X的最后一个字符X[m + n - 1] 是由A的最后一个字符A[m-1]组成的,那么
# X[0.....m+n-2] 则由A[0...m-2] 和 B[0...n-1]交错形成的
# 情况二:X的最后一个字符X[m + n - 1] 是由的最后一个字符B[n-1]组成的,那么
# X[0.....m+n-2] 则由A[0...m-1] 和 B[0...n-2]交错形成的
def isInterleave(self, s1, s2, s3):
# write your code here
m = len(s1)
n = len(s2)
A = s1
B = s2
X = s3
if m + n != len(X):
return False
f = [[None] * (n + 1) for _ in range(m + 1)]
for i in range(0, m + 1):
for j in range(0, n + 1):
# print(f'i:{i} j:{j}')
if i == 0 and j == 0:
f[0][0] = True
continue
f[i][j] = False
# 情况一
if i > 0 and X[i + j - 1] == A[i - 1] and f[i - 1][j]:
f[i][j] = True
# 情况二
if j > 0 and X[i + j - 1] == B[j - 1] and f[i][j - 1]:
f[i][j] = True
return f[m][n]
sol = Solution()
s1 = "abc"
s2 = "a"
s3 = "b"
sol.isInterleave(s1, s2, s3)
sol = Solution()
s1 = "aabcc"
s2 = "dbbca"
s3 = "aadbbcbcac"
sol.isInterleave(s1, s2, s3)
class Solution2:
"""
@param s1: A string
@param s2: A string
@param s3: A string
@return: Determine whether s3 is formed by interleaving of s1 and s2
"""
def isInterleave(self, s1, s2, s3):
# write your code here
l_1 = len(s1)
l_2 = len(s2)
if l_1 + l_2 != len(s3):
return False
dp = [[False] * (l_2 + 1) for _ in range(l_1 + 1)]
for i in range(0, l_1 + 1):
for j in range(0, l_2 + 1):
if i == 0 and j == 0:
dp[i][j] = True
continue
if i == 0:
dp[0][j] = s2[0:j] == s3[0:j]
continue
if j == 0:
dp[i][0] = s1[0:i] == s3[0:i]
continue
if s3[i + j - 1] == s1[i - 1]:
dp[i][j] = dp[i][j] or dp[i - 1][j]
if s3[i + j - 1] == s2[j - 1]:
dp[i][j] = dp[i][j] or dp[i][j - 1]
return dp[l_1][l_2]
|
71948ab032a1959e2ff30fa9b83d79c606fd537f | GGbb2046/ST018 | /Assignments/Assignment03/Turtlegraphics.py | 160 | 3.765625 | 4 | import turtle
gal= turtle.Turtle()
C = (input("Please enter the color of the circle "))
gal.color(C)
gal.circle(100)
window = turtle.Screen()
window.mainloop()
|
a08be912d3fe75de2f3751f88ad191ea21dd5d45 | tanxvyang/Python- | /src/day06/coach2.py | 2,186 | 3.71875 | 4 | def sanitize(time_string):
if '-' in time_string:
splitize = '-'
(mins, secs)=time_string.split(splitize)
elif ':' in time_string:
splitize = ':'
(mins, secs)=time_string.split(splitize)
else:
return(time_string)
return(mins+'.'+secs)
'''
#1,2
def get_coach_data(filename):
try:
with open (filename) as f:
data = f.readline()
return(data.strip().split(','))
except IOError as err:
print('file error :'+str(err))
return(None)
'''
def get_coach_data(filename):
try:
with open (filename) as f:
data = f.readline()
'''#
student= data.strip().split(',')
data = {}
data['Name'] = student.pop(0)
data['DOB'] = student.pop(0)
data['Times']= student
print(data['Name']+'s fastest times are: '+
str(sorted(set(sanitize(t) for t in data['Times']))[0:3]))
return(data)
'''
student = data.strip().split(',')
return({'name':student.pop(0),'DOB':student.pop(0),'times':str(sorted(set(sanitize(t) for t in student))[0:3])})
except IOError as err:
print('file error :'+str(err))
return(None)
sarah = get_coach_data('sarah2.txt')
#print(data)
print(sarah['name']+"'s fastest times are : "+sarah['times' ])
james = get_coach_data('james2.txt')
print(james['name']+"'s fastest times are : "+james['times' ])
julie = get_coach_data('julie2.txt')
print(julie['name']+"'s fastest times are : "+julie['times' ])
mikey = get_coach_data('mikey2.txt')
print(mikey['name']+"'s fastest times are : "+mikey['times' ])
'''
#1.处理多类型数据
(sarah_name,sarah_dob) = sarah.pop(0),sarah.pop(0)
print(sarah_name+'s fastest times are: '+
str(sorted(set(sanitize(t) for t in sarah))[0:3]))
'''
'''
#2.使用字典处理数据
sarah_data = {}
sarah_data['Name'] = sarah.pop(0)
sarah_data['DOB'] = sarah.pop(0)
sarah_data['Times']= sarah
print(sarah_data['Name']+'s fastest times are: '+
str(sorted(set(sanitize(t) for t in sarah_data['Times']))[0:3]))
'''
|
6d184c91577ff8f0c3b8ecaab2efaec7b0874c34 | daniel-reich/ubiquitous-fiesta | /r9y4yrSAGRaqTT7nM_4.py | 346 | 3.578125 | 4 |
def find_missing(lst):
if lst == None:
return False
for i in range(len(lst)-1):
if lst[i] == []:
return False
lst = sorted(lst, key=len)
for i in range(len(lst)-1):
increment = 1
if len(lst[i]) + increment != len(lst[i+1]):
return len(lst[i+1])-increment
return False
|
d48bb6afed7e891b4e82e5eb4b6c20f9466ceb00 | BillMaZengou/nature_of_code | /0_Introduction/04_custom_distribution/custom_random_number_with_MonteCarlo.py | 615 | 3.59375 | 4 | import numpy as np
import matplotlib.pyplot as plt
def monteCarlo():
selection = True
while selection:
r1 = np.random.rand()
r2 = np.random.rand()
probability = r1 * r1 # Custom function (only polynominal, for logrithmic r1 and r2 need modification)
if r2 < probability:
selection = False
return r1
def main():
random_count = np.zeros(100)
for i in range(10000):
r = int(monteCarlo() * 100)
random_count[r] += 1
plt.bar(range(len(random_count)), random_count, width=1.0)
plt.show()
if __name__ == '__main__':
main()
|
208b31101fa7b95f2f61e33388da8f1c0a4ef85e | woofan/leetcode | /530-get-minimum-difference.py | 836 | 3.578125 | 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 getMinimumDifference(self, root: TreeNode) -> int:
if not root:
return 0
tree_ele = []
def myhelp(root):
if not root:
return
tree_ele.append(root.val)
if root.left:
myhelp(root.left)
if root.right:
myhelp(root.right)
myhelp(root)
res = float('inf')
tree_ele = sorted(tree_ele)
for i in range(len(tree_ele)-1):
temp = abs(tree_ele[i+1] - tree_ele[i])
if temp == 0:
return 0
if temp < res:
res = temp
return res |
afc7190d651de40cff29bce59147d5db13211bbf | noahlwest/leetcode | /python/medium/74_Search_a_2D_Matrix.py | 458 | 3.625 | 4 | class Solution:
def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
#search down, then right
row = 0
for i in range(0, len(matrix)):
if matrix[i][0] <= target:
row = i
for j in range(0, len(matrix[row])):
if matrix[row][j] == target:
return True
return False
#runtime: O(n + m)
#memory: O(1) |
6d758f9949483fd7387820fd5d6d5245ca5a086e | suddencode/pythontutor_2018 | /7.3.py | 108 | 3.515625 | 4 | a = input().split()
for i in range(1, len(a)):
if int(a[i]) > int(a[i-1]):
print(int(a[i]), end=' ')
|
28717e9f466d1e98c66a1a5152564c8fe861ef5c | 4dv3ntur3/bit_seoul | /keras/keras18_simpleRNN2_scale.py | 2,029 | 3.546875 | 4 | #2020-11-12 (4일차)
#RNN(Recurrent Neural Network): LSTM, SimpleRNN, GRU
# LSTM -> SimpleRNN (용법 같다)
import numpy as np
#1. 데이터
x = np.array([[1, 2, 3], [2, 3, 4], [3, 4, 5], [4, 5, 6],
[5, 6, 7], [6, 7, 8], [7, 8, 9], [8, 9, 10],
[9, 10, 11], [10, 11 ,12],
[20, 30, 40], [30, 40, 50], [40, 50, 60]])
y = np.array([4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 50, 60, 70])
x_input = np.array([50, 60, 70])
# print(x.shape)
#shape 맞추기
x = x.reshape(13, 3, 1)
#2. 모델
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense, SimpleRNN
#실습: LSTM 완성
#예측값: 80
model = Sequential()
# model.add(LSTM(200, input_shape=(3, 1)))
# model.add(Dense(100))
# model.add(Dense(50))
# model.add(Dense(30))
# model.add(Dense(10))
# model.add(Dense(1))
#과제: 80.00809
model.add(SimpleRNN(30, activation='relu', input_shape=(3, 1)))
model.add(Dense(70))
model.add(Dense(100))
model.add(Dense(50))
model.add(Dense(30))
model.add(Dense(10))
model.add(Dense(1))
#3. 컴파일, 훈련
model.compile(loss='mse', optimizer='adam', metrics='mse')
model.fit(x, y, epochs=200, batch_size=1)
#4. 평가, 예측
loss, acc = model.evaluate(x, y, batch_size=1)
print("\nloss: ", loss)
#x_input reshape
x_input = x_input.reshape(1, 3, 1)
y_predict = model.predict(x_input)
print(y_predict)
model.summary()
# 동일한 모델로 돌렸을 경우
#------------------------------------------------------------------------------
# LSTM | simpleRNN
#--------------------------------------------------------------------------------
# predict() | 80.300995 | 79.99036
#-------------------------------------------------------------------------------
# loss | 0.8289151787757874 | 1.1793473277066369e-05
#-------------------------------------------------------------------------------
# param | LSTM:3840, total:20011 | simpleRNN:960, total:17131 |
b45737a281d71ee6c336e72e8e109452eae4287d | wenjunz/leetcode | /swap_nodes_in_pairs.py | 667 | 3.75 | 4 | # Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
dummy = ListNode(0);
dummy.next = head;
prev, curr = dummy, head;
while curr:
if curr.next:
n1 = curr.next;
n2 = curr.next.next;
prev.next = n1;
n1.next = curr;
curr.next = n2;
prev = curr;
curr = curr.next
return dummy.next
|
0266201f9a5b1c1656a80ab1f40f9558ddaf7361 | ErikLeemet/python-test | /8.py | 466 | 3.921875 | 4 | year = int(input("Sissesta aasta: "))
if year % 4 == 0 and year % 100 != 0 or year % 400 == 0:
print("on liigaasta")
else:
print("pole liigaasta")
if (year % 4) == 0:
if (year % 100) == 0:
if (year % 400) == 0:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
else:
print("{0} is a leap year".format(year))
else:
print("{0} is not a leap year".format(year))
|
c243083a97b553340c0ab8461f1a8c361c730dd9 | MasterCoookie/python_advanced | /Templates/cart.py | 911 | 4.34375 | 4 | '''
Templates are used to build a number of strings using, you guessed it,
templates. Variables in templates are preceded with a $ sign.
May be useful for ex. while writing a programme that renames pictures
The placeholder can be specified using {} ex ("The ${place}yard")
'''
from string import Template
class MyTemplate(Template):
'''The $ can be changed to any character by editing the delimiter property'''
delimiter = '#'
def main():
'''The name speaks for itself.'''
cart = []
cart.append(dict(item="Coke", price=8, qty=2))
cart.append(dict(item="Cake", price=12, qty=1))
cart.append(dict(item="Fish", price=32, qty=4))
template = MyTemplate("#qty x #item = #price$")
total = 0
print("Cart: ")
for data in cart:
print(template.substitute(data))
total += data["price"]
print("Total: ", total, '$')
if __name__ == '__main__':
main()
|
783456d0f344db493b3c4ddab81127f714cb0be0 | Nockternal/Burger | /intro to programming/Completed Tasks/Task 10/example.py | 4,638 | 4.4375 | 4 | #************* HELP *****************
#REMEMBER THAT IF YOU NEED SUPPORT ON ANY ASPECT OF YOUR COURSE SIMPLY LOG IN TO www.hyperiondev.com/support TO:
#START A CHAT WITH YOUR MENTOR, SCHEDULE A CALL OR GET SUPPORT OVER EMAIL.
#************************************
# PLEASE ENSURE YOU OPEN THIS FILE IN IDLE otherwise you will not be able to read it.
# *** NOTE ON COMMENTS ***
# This is a comment in Python.
# Comments can be placed anywhere in Python code and the computer ignores them - they are intended to be read by humans.
# Any line with a # in front of it is a comment.
# Please read all the comments in this example file and all others.
# ========= elif Statements ===========
# elif is short for else if.
# It allows you to specify a new condition to test, if the first condition is False.
# Unlike the else statement, you can have multiple elif statements in an if-elif-else statement.
# If the condition of the if statement is False, the condition of the next elif statement is checked.
# If the elif statement condition is False the condition of the next elif statement is checked, etc.
# If all the elif conditions are False, the else statement and its indented block of statements are executed.
# In Python, if-elif-else statements have the following syntax:
# if condition1 :
# indented Statements
# elif condition2 :
# indented Statements
# elif condition3 :
# indented Statements
# elif condition4 :
# indented Statements
# else:
# indented Statements
# ************ Example 1 ************
print ("Example 1: ")
grade = 66
if grade >= 80:
print ("Congratulations! You have an A")
elif grade >= 70:
print ("Good job! You have a B")
elif grade >= 60:
print ("Keep it up! You have a C")
elif grade >= 50:
print ("Try a little harder next time! You have a D")
else:
print ("Oh No! You have an F")
# Run this program to see what prints out, then try changing the value of the grade variable and running it again.
# ========= Some Important Points to Note on the Syntax of if-elif-else Statements ===========
# Make sure that the if/elif/else statements end with a colon (the : symbol).
# Ensure that your indentation is done correctly (i.e. statements that are part of a certain control structure's 'code block' need the same indentation).
# To have an elif you must have an if above it.
# To have an else you must have an if or elif above it.
# You can't have an else without an if - think about it!
# You can have as many elif under an if, but only one else right at the bottom. It's like the fail-safe statement that executes if the other if/elif statements fail!
# ************ Example 2 ************
print ("Example 2: ")
if len("Hello World") > 6:
print("This sentence is long!")
elif len("Hello World") > 3:
print("Slightly more manageable!")
else:
print("Easy stuff")
# ****************** END OF EXAMPLE CODE ********************* #
# == Make sure you have read and understood all of the code in this Python file.
# == Please complete the compulsory task below to proceed to the next task ===
# == Ensure you complete your work in this folder so that one of our tutors can easily locate and mark it ===
# ================= Compulsory Task ==================
# Create a Python file called “Control.py” in this folder.
# This is going to expand on the first control structure task we created.
# Write code to take in a user’s age using nput and store their age in an integer variable called age.
# Then check if the user’s age is over 18. If the user is over 18, print out the message “You are old enough!”
# else if they are over 16 print “Almost there”,
# otherwise print “You’re just too young!” You should use one if, one elif and one else statement to do this.
# ================= BONUS Optional Task ==================
# Create a new Python file in this folder called “Optional_task.py”
# Create a program that calculates a person's BMI
# Ask the user to enter their weight in kg and their height in m
# Use the formula below to calculate the user's BMI:
# BMI = (weight in kg) / ((height in m)*(height in m))
# If the users BMI is 30 or greater the user is obese
# else if the users BMI is 25 or greater the user is overweight
# else if the users BMI is 18.5 or greater the user is normal
# If the users BMI is less than 18.5 the user is underweight
# Display the users BMI and whether they are obese, overweight, normal or underweight
|
08b0a3056f070aba2d74c466a213f2324f5f9ba7 | a8578062/store | /day02/demo10.py | 251 | 3.84375 | 4 | username = 'jason'
password = 'admin'
username1 = input("请输入用户名:")
password1 = input("请输入密码:")
if username1 == username and password == password1:
print("登录成功")
else:
print("用户名密码错误!")
|
e2b281a48696cd6cd16626b99f55af5e0d77497f | yuriscripnic/kmeans | /kmeans_question.py | 1,838 | 3.765625 | 4 | """
KMean Question:
Given a set of two dimensional points P (e.g. [(1.1, 2.5), (3.4,1.9)...]; the size of set can be
100s), write a function that calculates simple K-means. The expected returned value from the
function is 1) a set of cluster id that each point belongs to, and 2) coordinates of centroids at the
end of iteration.
Although you can write this in any language, we would recommend for you to use python.
Please feel free to research and look up any information you need, but please note plagiarism
will not be tolerated
This app calculate K-means using simple random values to initialize the centroids
Because this, the algorithm is not sure to find a global minimum and could diverge
Consecutive tries can result in a correct response
"""
from clustering import KMeans
import logging
import random
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = (16, 9)
plt.style.use('ggplot')
logging.getLogger("clustering.KMeans").setLevel(logging.DEBUG)
def main():
k = 3
X = [[random.randint(0,20),random.randint(0,20)] for i in range(30)] \
+ [[random.randint(40,60), random.randint(40,60)] for i in range(30)] \
+ [[random.randint(80, 100), random.randint(80, 100)] for i in range(30)]
print(f"Cluster points:{X}")
kmeans = KMeans(n_cluster=k, tol=3e-4)
centroids = kmeans.fit(X)
prediction = kmeans.predict([[0.0,0.0],[50.0,40.0],[100.0,100.0]])
print(f"KMeans centroids: {centroids}")
print(f"KMeans predict for [0,0],[50,40],[100,100]]: {prediction}")
colors = ['r', 'g', 'b']
for i in range(k):
plt.scatter([x[0] for x in X], [x[1] for x in X], s=7, c=colors[i])
plt.scatter([x[0] for x in centroids], [x[1] for x in centroids], marker='*', s=200, c='black')
plt.show()
if __name__ == "__main__":
main()
|
de869f9b795105e4eacafd21a930a27906276df8 | CLCdawn/Hello-world | /PycharmProjects/dataScience/lowerAndUpper.py | 196 | 3.96875 | 4 | s = input()
result = ""
for c in s:
if 'A' <= c <= 'Z':
result += c.lower()
elif 'a' <= c <= 'z':
result += c.upper()
elif c == ',':
result += ','
print(result) |
a0788563b6405befb47b3adc68952c92a1b5b1a7 | DennisSoemers/MultiMAuS | /authenticators/abstract_authenticator.py | 596 | 3.875 | 4 | from abc import ABCMeta, abstractmethod
class AbstractAuthenticator(metaclass=ABCMeta):
def __init__(self):
"""
Every authenticator has to have a name
:param name:
"""
super().__init__()
@abstractmethod
def authorise_transaction(self, customer):
"""
Decide whether to authorise transaction.
Note that all relevant information can be obtained from the customer.
:param customer: the customer making a transaction
:return: boolean, whether or not to authorise the transaction
"""
|
efeb734cb5de30824245bdd5fad0dcbc589d29ab | czar3985/mini-projects | /03_Secret_Message/rename_files.py | 954 | 3.96875 | 4 | # TITLE: Secret Message Decoder
# DESCRIPTION: A secret message is in folder decodeThis.
# Running this program will rename the files to remove the numbers
# from the file names. When the files are sorted, a secret message
# will appear.
# NOTE: The translate method is different in Python 3.x.
# This was run using Python 2.7.5
import os
def rename_files():
# get file names from a folder
file_list = os.listdir(".\\decodeThis")
print(file_list)
# save the current working directory
orig_path = os.getcwd()
# change the current working directory
os.chdir(".\\decodeThis")
# for each file, rename filename
for file_name in file_list:
new_file_name = file_name.translate(None,"0123456789")
os.rename(file_name, new_file_name)
print("Old name: " + file_name + ", New name: " + new_file_name)
# revert back to the original working directory
os.chdir(orig_path)
rename_files()
|
057fe131d6d1718c861bf70cea95a3816f42d588 | 233-wang-233/python | /day15/15day_2.py | 361 | 3.78125 | 4 | """
动态规划 - 适用于有重叠子问题和最优子结构性质的问题
使用动态规划方法所耗时间往往远少于朴素解法(用空间换取时间)
"""
def fib(num,temp={}):
if num in (1,2):
return 1
try:
return temp[num]
except KeyError:
temp[num]=fib(num-1)+fib(num-2)
return temp[num] |
9a793efb0bdbba6573c82ad1fc6b41025fd3dd36 | nsiicm0/project_euler | /15/impl2.py | 721 | 3.515625 | 4 | '''
Starting in the top left corner of a 2×2 grid, and only being able to move to the right and down, there are exactly 6 routes to the bottom right corner.
- RRDD
- RDRD
- RDDR
- DRRD
- DRDR
- DDRR
How many such routes are there through a 20×20 grid?
'''
from math import factorial
# for lattice path, the number of possible paths are represented by the binomial coefficient
# Catalan numbers give you half of the square
def catalan_numbers(n):
ans = 1
for k in range(2,n+1):
ans = ans * (n+k) // k
return ans
def binomial(x, y):
try:
binom = factorial(x) // factorial(y) // factorial(x - y)
except ValueError:
binom = 0
return binom
n = 20
print(binomial(2*n,n)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.